driver

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 modules, 0 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 driver is the protocol between core and the platform backends: the mount items a commit sends, the events backends report, the TextEngine they implement, and the values both sides share. It also holds what every backend runs the same way on its main thread: the animation graph's Animator, the selection model and text field edits.

Backends import driver, never core; core aliases the values apps use.

Index

Constants

View Source
const (
	// ActionActivate replaces the press a screen reader's double tap or
	// VO-Space makes.
	ActionActivate = "activate"
	// ActionIncrement and ActionDecrement adjust an adjustable element:
	// a swipe up or down on iOS, TalkBack's volume keys, VO-Up and Down.
	ActionIncrement = "increment"
	ActionDecrement = "decrement"
	// ActionLongPress replaces a long press (Android).
	ActionLongPress = "longpress"
	// ActionExpand and ActionCollapse change an expandable element
	// (Android).
	ActionExpand   = "expand"
	ActionCollapse = "collapse"
	// ActionEscape is VoiceOver's two-finger scrub on iOS, AXCancel on
	// macOS and Escape on the web.
	ActionEscape = "escape"
	// ActionMagicTap is VoiceOver's two-finger double tap (iOS).
	ActionMagicTap = "magicTap"
)

Standard accessibility actions.

View Source
const (
	MaxSoundBytes    = 8 << 20
	MaxSoundDuration = 5 * time.Second
	MaxSounds        = 64
	MaxDecodedBytes  = 16 << 20
	MaxSoundVoices   = 32
)

The limits a sound is held to, NSH's: its encoded bytes, which the platform's reader checks before decoding; its decoded length, which the platform decodes no more of; the sounds one engine holds and their decoded bytes, which the core counts; and the playbacks at once, past which the platform stops the oldest.

View Source
const (
	AudioNotAllowed    = "not-allowed"
	AudioNetwork       = "network"
	AudioDecode        = "decode"
	AudioNotSupported  = "not-supported"
	AudioQuotaExceeded = "quota-exceeded"
	AudioUnavailable   = "unavailable"
	AudioFailed        = "failed"
)

The errors a sound or a player fails with, named as NSH's, which follow the web's MediaError.

View Source
const (
	// ModalityKeyboard is a key pressed, not a modifier alone: Tab, an
	// arrow, a shortcut or typing, from a hardware keyboard or a remote.
	ModalityKeyboard uint32 = iota + 1
	// ModalityPointer is a mouse button, a pen or a finger going down.
	ModalityPointer
)

What EventInputModality reports.

View Source
const (
	NoFileOpener   = "this platform opens no files in other apps"
	NoShareSheet   = "this platform has no share sheet"
	NoFileRevealer = "this platform has no file manager"
	NoTrash        = "the volume has no trash"
)

What a platform that cannot open a file or share answers ItemOpenFile or ItemShare with.

View Source
const (
	OverlayDenied = iota
	OverlayGranted
	OverlayUnavailable
)

OverlayPermission is what EventOverlayPermission answers an ItemOverlayPermission with, as core's.

View Source
const (
	OverlayEndDenied = iota + 1
	OverlayEndUnavailable
	OverlayEndRevoked
	OverlayEndRemoved
	OverlayEndFailed
)

Why EventWindowEnded says the platform ended an overlay, as core's OverlayEnd.

View Source
const (
	BiometricNone = iota
	BiometricFace
	BiometricFingerprint
)

Biometric kinds, as reported by an availability request.

View Source
const (
	BiometricSuccess = iota + 1
	BiometricFailure
	BiometricCancelled
	BiometricUnavailable
)

Biometric results, as reported by an authentication request.

View Source
const (
	NotificationsNotAsked = iota
	NotificationsGranted
	NotificationsDenied
	NotificationsUnavailable
)

NotificationPermission is what EventNotification answers an ItemNotificationPermission with, as core's.

View Source
const (
	PermissionAccessibility   = "accessibility"
	PermissionScreenRecording = "screen-recording"
	PermissionInputMonitoring = "input-monitoring"
	PermissionFullDiskAccess  = "full-disk-access"
	PermissionAppManagement   = "app-management"
	PermissionDeveloperTools  = "developer-tools"
	PermissionMicrophone      = "microphone"
	PermissionCamera          = "camera"
	PermissionCalendars       = "calendars"
	PermissionReminders       = "reminders"
	PermissionBluetooth       = "bluetooth"
	PermissionMediaLibrary    = "media-library"
)

The permissions an ItemPermission names (PermissionRequest.Name), as core.Permission's values.

View Source
const (
	PermissionNotAsked = iota
	PermissionGranted
	PermissionDenied
	PermissionUnknown
	PermissionNotGated
	PermissionUnavailable
)

The statuses EventPermission answers with (Index), as core.PermissionStatus.

View Source
const (
	DecelerationNormal float32 = 0.998
	DecelerationFast   float32 = 0.99
)

Deceleration rates, as UIKit's.

View Source
const (
	SoftEdgeBlur  Points  = 10
	SoftEdgeTail  Points  = 24
	HardEdgeBlur  Points  = 6.4
	EdgeTint      float32 = 0.8
	HairlineWidth Points  = 0.5
)

What a platform drawing an edge effect itself draws, alike everywhere: both edges lay the tint at EdgeTint under the bars; a soft edge blurs by SoftEdgeBlur at the side, down to nothing SoftEdgeTail past the bars, where its tint has eased out (SoftTint); a hard edge blurs by HardEdgeBlur under the bars and draws a hairline HairlineWidth wide past them. Blurs are a Gaussian's standard deviation, as CSS's blur() takes.

View Source
const (
	UnblurredSoftTint float32 = 0.85
	UnblurredHardTint float32 = 0.95
)

A platform that cannot blur what is behind a view, Linux, fades the content into the tint alone, more opaque: at UnblurredSoftTint under a soft edge's bars, and at UnblurredHardTint under a hard edge's.

View Source
const (
	SpeechNotAllowed          = "not-allowed"
	SpeechNoSpeech            = "no-speech"
	SpeechAudioCapture        = "audio-capture"
	SpeechNetwork             = "network"
	SpeechLanguageUnsupported = "language-not-supported"
	SpeechUnavailable         = "unavailable"
	SpeechFailed              = "failed"
)

The errors a session ends with, named as the Web Speech API's.

View Source
const AttachmentRune = '\uFFFC'

AttachmentRune stands in a text for an attachment, as the object replacement character does in attributed strings.

View Source
const DefaultPickQuality = 0.9

DefaultPickQuality is the JPEG quality images are encoded at when the request gives none.

View Source
const FontMonospace = "monospace"

FontMonospace is the family name of the platform's fixed-pitch font, for code.

View Source
const FrameInterval = 16667 * time.Microsecond

FrameInterval is a frame at 60 Hz, in whole microseconds as NSH's: what an app assumes where the display's own pace is unknown. Sixty of them reach a second, so a second of frames counts 60.

View Source
const MaxClipboardImage = 48 << 20

MaxClipboardImage is the most bytes of a PNG a clipboard read returns: a larger image is left out, since the app's memory may not hold it.

View Source
const MaxPicked = 100

MaxPicked is the most files one pick answers with.

View Source
const NoDirectoryPicker = "this platform has no folder picker"

NoDirectoryPicker is what a platform without a folder picker answers ItemPickDirectories with.

View Source
const SampleRate = 60

SampleRate is how many samples a second the samplers take: the frames of a 60 Hz display.

View Source
const ShaderBuiltinLanes = 3

ShaderBuiltinLanes is how many lanes a WGSL program's built-ins take before its uniforms: the time, the progress and the overflow.

View Source
const ShareStageAge = time.Hour

ShareStageAge is how long a file Stage made stays before a later stage in the same directory removes it: long enough for the app the user chose to read it.

View Source
const Smoothing = 0.6

Smoothing is how far continuous corners ease into their edges: Figma's corner smoothing at 60%, which matches iOS's.

View Source
const SwitchComponent = "nsgo/switch"

SwitchComponent is the native component macOS and iOS register for core.SystemSwitch: NSSwitch or UISwitch. Its props are "checked", "disabled" and "size" ("small" or "large", which only macOS has); it emits "change" with the value the user chose.

View Source
const TabBarComponent = "nsgo/tab-bar"

TabBarComponent is the native component iOS and Android register for core.TabBar: the system's tab bar. Its props are "items", a list of {"title", "icon"} maps, "selectedIndex" and "tint", the selected tab's Color as a number (0: the system's); it emits "change" with the index the user chose.

Variables

View Source
var (
	// PaintNone paints nothing.
	PaintNone = Paint{/* contains filtered or unexported fields */}
	// PaintCurrentColor paints with the text color, CSS's currentColor.
	PaintCurrentColor = Paint{/* contains filtered or unexported fields */}
)
View Source
var (
	MinContent = Length{/* contains filtered or unexported fields */}
	MaxContent = Length{/* contains filtered or unexported fields */}
	FitContent = Length{/* contains filtered or unexported fields */}
)

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

View Source
var (
	Linear    = Curve{}
	Ease      = Curve{0.25, 0.1, 0.25, 1}
	EaseIn    = Curve{0.42, 0, 1, 1}
	EaseOut   = Curve{0, 0, 0.58, 1}
	EaseInOut = Curve{0.42, 0, 0.58, 1}
)

The standard curves, as CSS names them.

View Source
var Applied func(b *MountBatch, took time.Duration)

Applied, which nsgo dev -devtools sets, hears how long a platform took to apply each batch on its main thread; nil measures nothing.

View Source
var Auto = Points(float32(math.NaN()))

Auto marks a length the layout computes, such as a text engine's unbounded width. Styles use Length instead.

View Source
var AutoMinimum = Length{/* contains filtered or unexported fields */}

AutoMinimum is CSS's automatic minimum, for a minimum size: a flex item keeps its content's size, where an unset minimum is 0, as in Yoga.

View Source
var BlobFile func(url, name string) File

BlobFile, set by the web backend, is the file the page's blob: URL url (without its fragment) stands for, named name: the Blob a drop made it for, with its size, type and time, or else one read by fetching url.

View Source
var CheckCommits bool

CheckCommits has every commit compare the whole tree again after it and panic if that finds changes its marks missed. Tests set it; it doubles what commits cost.

View Source
var DefaultViewStyle = ViewStyle{Opacity: 1}

DefaultViewStyle is the style of a view no style changes: opaque and nothing else. Backends create views in it, and the core sends a new view's style only when it differs, as it sends no empty ViewProps and no empty EventMask.

View Source
var Identity3D = Matrix3D{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}

Identity3D changes nothing.

View Source
var IdentityColorMatrix = ColorMatrix{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0}

IdentityColorMatrix changes nothing.

View Source
var ImageScaleValues = [...]float32{1, 1.5, 2, 3, 4}

ImageScaleValues are the pixel densities an image asset can ship in, as its file name's suffix says ("@1.5x" to "@4x"; the file without one is 1x).

View Source
var KeyboardCurve = Curve{0.38, 0.7, 0.125, 1}

KeyboardCurve is UIKit's keyboard curve, as near as a cubic Bézier comes; Android's runtime uses the IME's interpolator instead.

View Source
var TraceCauses bool

TraceCauses has commits record what they followed from in MountBatch.Causes: nsgo dev -trace and nsgo test -trace set it. While it is unset, a signal's write and a computation's run cost one check of it.

UpdateDownload and UpdateInstall are backend hooks. The core and updater packages use them without importing a platform package.

View Source
var UpdateInstall func(string, func(error))

Functions

func AllowsHost

func AllowsHost(patterns []string, host string) bool

AllowsHost reports whether one of patterns allows host: "*" any, "*.example.com" its subdomains, else the host itself. Hosts compare in lower case.

func AnswerPermission

func AnswerPermission(id uint32, r PermissionRequest, status func(name string) int, dispatch func(Event))

AnswerPermission answers ItemPermission id where nothing asks, opens settings or guides: a check, a request and a guide hear status of the permission at once, opening the settings that none opened, and a stop nothing.

func Apply

func Apply(b *MountBatch, apply func(*MountBatch))

Apply applies b with apply, timing it for Applied while one is set: what each backend calls where it applies a batch.

func AudioType

func AudioType(data []byte) string

AudioType is the media type the first bytes of a sound or a player's Data say they are, for decoders that go by a file's name or type, as NSH names bytes the app gives: audio/wav, audio/aiff, audio/x-caf, audio/flac, audio/ogg, audio/mp4, audio/mpeg or audio/aac, and application/octet-stream for none of these.

func ClipUTF16

func ClipUTF16(s string, max int) string

ClipUTF16 cuts s to at most max UTF-16 units, never inside a character; max 0 or less keeps all of it.

func ConnectLiveUpdates

func ConnectLiveUpdates(send func([]byte))

ConnectLiveUpdates is the Android backend's: send carries package widget's messages to the runtime, those that waited first.

func ConnectRecordings

func ConnectRecordings(send func([]byte))

ConnectRecordings is the recorder's, the Android backend's or nsgotest's fake microphone's: send carries package microphone's messages, those that waited first. A nil send disconnects the recorder, and messages wait for the next.

func CopiedText

func CopiedText(text string, spans []TextSpan, from, to int) string

CopiedText is what a copy of text's bytes from to to takes: its hidden spans left out, and each attachment the copy takes whole replaced by its span's Copy, or left out without one.

func EdgeLine

func EdgeLine(s Side) (x0, y0, x1, y1 float32)

EdgeLine returns the line of a gradient across a band from side s, from the side to the band's other end, in fractions of the band.

func FindKey

func FindKey(keymap []KeyBinding, names []string, focus KeyUse, repeat bool) (key string, consumed bool)

FindKey says what a key press does with keymap: names are the press's normalized names (with "mod" and with the literal modifier), focus the keys the view with the keyboard focus uses itself (FocusKeyUse, KeyUseText alone for a backend that knows only whether a text input or web view has it), and repeat whether it is a held key's auto-repeat. A binding takes no press from a focused text input or web view unless InText, nor from a focused control whose keys it Yields. It returns the binding that fires, or "" and whether the press is consumed anyway: the repeat of a binding that fires once.

func FolderFS

func FolderFS(src FolderSource, root FolderEntry) fs.FS

FolderFS reads the folder root through src. It remembers each listing to find what a name opens, and lists a folder afresh whenever it is read.

func HasSpanCursor

func HasSpanCursor(spans []TextSpan) bool

HasSpanCursor reports whether any span names a cursor, so a backend knows the cursor under a still pointer may change with the text.

func HearLiveUpdates

func HearLiveUpdates(fn func([]byte))

HearLiveUpdates is package widget's: fn hears the runtime's reports, those that waited first.

func HearRecordings

func HearRecordings(fn func([]byte))

HearRecordings is package microphone's: fn hears the recorder's reports, those that waited first. It runs on the goroutine that reports, which it must not hold up.

func HostCovers

func HostCovers(pattern, other string) bool

HostCovers reports whether pattern covers other, a host or a pattern.

func ImageExtension

func ImageExtension(mime string) string

ImageExtension returns the extension of an image of type mime, or "".

func InnerRadii

func InnerRadii(c Corners, widths Edges) [4][2]float64

InnerRadii returns the radii of the padding box inside borders of widths (top, right, bottom, left) around a box with fitted corners: each corner less the widths of the sides it joins, elliptical where they differ, as CSS shrinks them.

func IntersectHosts

func IntersectHosts(a, b []string) []string

IntersectHosts returns the patterns allowing what both a and b allow.

func IsStandardAction

func IsStandardAction(name string) bool

IsStandardAction reports whether name is one of the standard actions, which platforms map to their own gestures rather than list as custom actions.

func JSString

func JSString(s string) string

JSString quotes s as a JavaScript string literal.

func KeyOf

func KeyOf(text string) string

KeyOf is what EventKeyPress reports for an edit inserting text: the text, or "Enter" for a line break.

func LimitEdit

func LimitEdit(text string, replaced int, insert string, maxLength int) (kept string, ok bool)

LimitEdit is what a field with maxLength keeps of an edit replacing replaced units of text with insert: insert cut to the room left, as the platforms' own limits do. ok is false when nothing of a non-empty insert fits.

func MIMEForFile

func MIMEForFile(name string) string

MIMEForFile returns the media type a file name's extension says, application/octet-stream for one it does not know.

func MIMEForName

func MIMEForName(name string) string

MIMEForName returns the image type a file name's extension says, or "".

func NormalizeKey

func NormalizeKey(key string) string

NormalizeKey returns key lowercased with its modifiers in the order mod, ctrl, alt, shift, meta; "cmd" and "command" are meta, "option" is alt, "control" is ctrl and the key "return" is "enter".

func PhonePermission

func PhonePermission(name string) int

PhonePermission is whether a phone's or a watch's system keeps the permission name, PermissionUnknown for one it keeps, for the backends that cannot tell it yet: the six only Macs keep are PermissionUnavailable.

func PickedName

func PickedName(name, mime string) string

PickedName returns name without its directories and with the extension of mime (IMG_0042.HEIC as a JPEG is IMG_0042.jpg); a name without a stem becomes image.

func PlaceWindow

func PlaceWindow(anchor Bounds, size Size, area Bounds, side WindowPlacement) (Point, WindowPlacement)

PlaceWindow returns the top-left corner of a panel of size placed beside anchor in area, a display's visible frame, and the side it took: side, below for WindowPlaceDefault, unless the panel overflows area there and fits on the opposite side. Along the side it is centered on anchor, and either way it is kept inside area, at its top-left corner when it is larger.

func PressesAt

func PressesAt(spans []TextSpan, i int) bool

PressesAt reports whether a pressable text takes a press on byte offset i (-1 off its glyphs): a text with links takes only those on a link, as the core gives it no press of its own then.

func Reach

func Reach(frame Bounds, props *ViewProps, area Bounds, p Point) (self, children bool)

Reach reports what a point p, in the coordinates of a view's parent's content, may reach of a view at frame with props: the view itself, by its bounds and HitSlop, and its children, by its bounds and area, the one ItemOverflow gave it. Platforms that hit-test their own views ask it on the way down.

func RecordingsConnected

func RecordingsConnected() bool

RecordingsConnected says whether a recorder is connected.

func RefusedNavigation

func RefusedNavigation(url string) string

RefusedNavigation is the message of EventError for a navigation Navigable refused.

func ReportLiveUpdate

func ReportLiveUpdate(report []byte)

ReportLiveUpdate is the Android backend's: it hands package widget a report of the runtime.

func ReportRecording

func ReportRecording(report []byte)

ReportRecording is the recorder's: it hands package microphone a report.

func RoleName

func RoleName(r Role) string

RoleName is r's name in selectors such as nsgotest's role:button, "" for none.

func RubberBand

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

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

func SampleDecay

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

SampleDecay returns a decay 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 platforms evaluate it.

func SampleSpring

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

SampleSpring returns a spring from from to to, as the platforms run it, at SampleRate until it rests: the drivers' own code, stepped like frames.

func SendLiveUpdate

func SendLiveUpdate(msg []byte)

SendLiveUpdate sends package widget's msg to the Android runtime, once the backend has connected.

func SendRecording

func SendRecording(msg []byte)

SendRecording sends package microphone's msg to the recorder, once one has connected.

func SetAnimatedProp

func SetAnimatedProp(c NativeComponent, b NativeBinding, num float64, col Color)

SetAnimatedProp hands component c an animated prop's value, as ChangedNatives reports it.

func ShownText

func ShownText(text string, spans []TextSpan, labels []string) string

ShownText is text as screen readers read it: its hidden spans left out, and its attachments, in order, read as labels say, separated from the text around them by a space; one past the labels is left out. A span's Copy is never read: a formula reads as its spoken label, not its TeX.

func SniffImage

func SniffImage(b []byte) string

SniffImage returns the media type an image's bytes start with, or "" for a format it does not know.

func SplitFilters

func SplitFilters(filters []Filter) (m ColorMatrix, ok bool, blur Points, shadows []BoxShadow)

SplitFilters returns what platforms that cannot chain filters draw of filters: their color filters as one matrix (ok false when there are none), the widest blur and the drop shadows.

func TreeFS

func TreeFS(files []TreeFile) fs.FS

TreeFS is the folder holding files, and the folders their paths name.

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 converts a UTF-16 offset in s to a byte offset, clamped to s.

func UTF16Units

func UTF16Units(s string, bytes int) int

UTF16Units converts a byte offset in s to UTF-16 units.

func UprightEmoji

func UprightEmoji(t *AttributedText)

UprightEmoji gives the color emoji of t's italic runs spans of their own that are not italic: emoji fonts have no italic face, and Chrome and Android would slant them where WebKit and CoreText keep them upright, as every platform does here.

func VisibleText

func VisibleText(text string, spans []TextSpan) string

VisibleText is text with its hidden spans left out, its attachments' places kept.

func WebBridge

func WebBridge(post string) string

WebBridge is the script a platform runs at the start of every page before the app's, given post, the JavaScript expression of a function that sends its string argument to the app.

func WebEvaluateAnswer

func WebEvaluateAnswer(answer string) (string, error)

WebEvaluateAnswer decodes what WebEvaluateScript posted after its marker: the result as JSON, or the error the script threw.

func WebEvaluateFailure

func WebEvaluateFailure(marker, message string) string

WebEvaluateFailure is what a page posts when the script after marker threw message, as WebEvaluateAnswer decodes it.

func WebEvaluateMarker

func WebEvaluateMarker(script string) (string, bool)

WebEvaluateMarker returns the marker of a script WebEvaluateScript made, for a backend that has no page to run it in and answers it with WebEvaluateFailure instead.

func WebEvaluateScript

func WebEvaluateScript(script, marker string) string

WebEvaluateScript is the script that runs script in a page as an expression and posts its answer through the bridge, marker first: its result as JSON, a promise's once settled, or what it threw (decoded by WebEvaluateAnswer).

func WebMIME

func WebMIME(path string, body []byte) string

WebMIME returns the media type a web scheme response should use. It first trusts the URL's extension, then applies the small signature set browsers use for responses without one. The fallback is always a valid media type.

func WebMessageScript

func WebMessageScript(data string) string

WebMessageScript is the script WebPostMessage runs in the page.

func WebOrigin

func WebOrigin(rawURL string) string

WebOrigin is the origin of the page at rawURL as browsers write one: scheme://host, with the port when it is not the scheme's own, in lower case, such as "https://example.com" or "app://bundle". A blob: URL has the origin of the URL it holds and every file: URL "file://"; a URL with no host, such as about:blank or a data: URL, or one that does not parse, has an opaque origin, written "null". No URL ("") has no origin ("").

func WriteTrace

func WriteTrace(w io.Writer, label string, b *MountBatch, took time.Duration)

WriteTrace prints batch b, which a commit that took took made, as traces show it: a line with label, the items and the commit's time, then a line per item. nsgo test -trace labels batches by their step, nsgo dev -trace by their commit.

Types

type AccessibilityAction

type AccessibilityAction struct {
	// Name is a standard action (ActionActivate and the others), which
	// the screen reader performs with its own gesture or key, or a custom
	// action's name.
	Name string
	// Label is what a custom action is called in the screen reader's
	// actions menu; Name when empty.
	Label string
}

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

type AccessibilityValue

type AccessibilityValue struct {
	// Min, Max and Now are a range, when Max is above Min: a slider's or
	// a progress bar's.
	Min, Max, Now float32
	// NoNow leaves a range without its current value, as an indeterminate
	// progress bar's.
	NoNow bool
	// Text is read instead of Now, or alone without a range.
	Text string
}

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

func (AccessibilityValue) IsRange

func (v AccessibilityValue) IsRange() bool

IsRange reports whether v is a range.

type Accessible

type Accessible uint8

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

const (
	// AccessibleAuto leaves it to the platform: views with a role, a
	// label or a press handler are elements.
	AccessibleAuto Accessible = iota
	// AccessibleYes makes the view one element: its descendants are not
	// exposed separately, and without a label it reads their text.
	AccessibleYes
	// AccessibleNo makes the view no element; its descendants still are.
	AccessibleNo
)

type Affinity

type Affinity uint8

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.

const (
	// Downstream is with the character after the offset: at the start of
	// the later line.
	Downstream Affinity = iota
	// Upstream is with the character before the offset: at the end of the
	// earlier line.
	Upstream
)

type AlertAction

type AlertAction struct {
	Label string
	Role  AlertRole
}

AlertAction is one button of an alert.

type AlertConfig

type AlertConfig struct {
	Title   string
	Message string
	Actions []AlertAction
	// Sheet presents the actions as an action sheet from the bottom
	// (UIAlertController's; a list dialog on Android) instead of an alert.
	Sheet bool
	// Cancelable lets Escape, back and a press outside close it without
	// an action, answered with -1.
	Cancelable bool
	// ID numbers the alert; the engine sets it.
	ID uint32
}

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

type AlertRole

type AlertRole uint8

AlertRole says what an alert's button does.

const (
	AlertDefault AlertRole = iota
	// AlertCancel is the button Escape and back choose.
	AlertCancel
	// AlertDestructive is drawn as dangerous.
	AlertDestructive
)

type AndroidEventMapper

type AndroidEventMapper interface {
	ViewEvent(name string, args []any)
}

AndroidEventMapper is implemented by an Android component that receives the listener callbacks of its view itself, to emit what it likes; without it each callback is emitted as is.

type AndroidPropMapper

type AndroidPropMapper interface {
	ViewProps(name string, value any) []AndroidViewProp
}

AndroidPropMapper is implemented by an Android component that chooses the setter calls a prop makes, in order; without it each prop calls its own setter with its value.

type AndroidViewProp

type AndroidViewProp struct {
	Name  string
	Value any
}

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

type AnimatedArg

type AnimatedArg interface {
	// AnimatedNodeID is the node's ID in the animation graph; 0 binds
	// nothing.
	AnimatedNodeID() uint32
}

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

type AnimatedProp

type AnimatedProp uint8

AnimatedProp is a view property an animated node drives.

const (
	PropOpacity AnimatedProp = iota
	PropTranslateX
	PropTranslateY
	PropScale
	PropScaleX
	PropScaleY
	PropRotate
	PropBackground
	PropBorderColor
	PropShadowColor
	PropShadowRadius
	// PropShadowOpacity multiplies the shadow color's alpha.
	PropShadowOpacity
	// PropTextColor colors a text's whole content, its spans included.
	PropTextColor
	// PropRotateX and PropRotateY turn the view out of its plane, in
	// degrees.
	PropRotateX
	PropRotateY
	// PropCount is the number of animated props.
	PropCount
)

type AnimatedPropSetter

type AnimatedPropSetter interface {
	SetAnimatedNumber(name string, v float64)
	SetAnimatedColor(name string, c Color)
}

AnimatedPropSetter is implemented by a component that takes its animated props as numbers and colors, on the main thread on the frames they change; without it SetProp receives them, a number as a float64 and a color as a Color.

type AnimatedValues

type AnimatedValues struct {
	// Set holds a bit for each bound AnimatedProp.
	Set                    uint16
	Opacity                float32
	TranslateX, TranslateY Points
	Scale, ScaleX, ScaleY  float32
	Rotate                 float32
	Background             Color
	BorderColor            Color
	ShadowColor            Color
	ShadowRadius           Points
	ShadowOpacity          float32
	// TextColor colors a text's whole content.
	TextColor        Color
	RotateX, RotateY float32
}

AnimatedValues are the bound properties of a view, as the animator last evaluated them.

func (AnimatedValues) Apply

func (v AnimatedValues) Apply(vs ViewStyle) ViewStyle

Apply returns vs with the bound properties in place of its own, for backends that draw from a ViewStyle.

func (AnimatedValues) Has

func (v AnimatedValues) Has(p AnimatedProp) bool

Has reports whether p is bound.

type Animation

type Animation struct {
	Kind AnimationKind
	// Value is the node a Timing, Spring or Decay moves; To where Timing
	// and Spring take it.
	Value  uint32
	To     float64
	Timing TimingConfig
	Spring SpringConfig
	Decay  DecayConfig
	// Steps are a composite's animations.
	Steps []*Animation
	// Delay is Delay's wait and Stagger's interval.
	Delay time.Duration
	// Iterations is Loop's count; 0 repeats forever. NoReset starts each
	// iteration where the last ended, rather than with its values back
	// at their start.
	Iterations int
	NoReset    bool
	// FrameRate caps how many times a second the whole run moves its
	// values, on the animation StartAnimation is given; 0 is every frame
	// the display has.
	FrameRate float64
}

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

type AnimationKind

type AnimationKind uint8

AnimationKind is what an Animation does.

const (
	AnimationTiming AnimationKind = iota + 1
	AnimationSpring
	AnimationDecay
	AnimationSequence
	AnimationParallel
	AnimationStagger
	AnimationDelay
	AnimationLoop
)

type AnimationOp

type AnimationOp struct {
	Kind          AnimationOpKind
	Node          uint32
	Value         float64
	Input         uint32
	Interpolation *Interpolation
	Math          MathOp
	A, B          Operand
	Min, Max      float64
	// Snap makes a diff clamp settle at a bound when its scroll view
	// rests.
	Snap bool
	// ID names a run or a read.
	ID        uint32
	Animation *Animation
	// Endless marks a run its owner starts again whenever it ends, as a
	// shader's clock is, so Ending does not wait for it.
	Endless bool
	View    NodeID
	Prop    AnimatedProp
	X, Y    uint32
}

AnimationOp is one change to the animation graph.

type AnimationOpKind

type AnimationOpKind uint8

AnimationOpKind is a change to the animation graph.

const (
	// AnimCreateValue makes value Node at Value.
	AnimCreateValue AnimationOpKind = iota + 1
	// AnimCreateInterpolate makes Node map Input through Interpolation.
	AnimCreateInterpolate
	// AnimCreateMath makes Node combine A and B with Math.
	AnimCreateMath
	// AnimCreateDiffClamp makes Node follow Input's changes within Min
	// and Max; with Snap it settles at its nearer bound when the scroll
	// view its input follows comes to rest.
	AnimCreateDiffClamp
	// AnimSet, AnimSetOffset, AnimFlattenOffset, AnimExtractOffset and
	// AnimStopValue change value Node.
	AnimSet
	AnimSetOffset
	AnimFlattenOffset
	AnimExtractOffset
	AnimStopValue
	// AnimRead answers ID with value Node's value in an EventAnimation.
	AnimRead
	// AnimStart runs Animation as ID; its end is an EventAnimation.
	AnimStart
	// AnimStop ends run ID early.
	AnimStop
	// AnimBind makes Node drive Prop of View; Node 0 unbinds it.
	AnimBind
	// AnimBindPan has drags on View set values X and Y to their
	// translation, and AnimBindScroll has scroll view View set them to its
	// offset.
	AnimBindPan
	AnimBindScroll
	// AnimRelease drops Node.
	AnimRelease
	// AnimBindPinch has pinches on View scale value Node, and
	// AnimBindRotation has rotations on View turn it, in radians.
	AnimBindPinch
	AnimBindRotation
	// AnimReset ends run ID unfinished, if it runs, and puts the values
	// it moves back where they were when it started.
	AnimReset
	// AnimForgetRun drops what the animator keeps of run ID for a reset.
	AnimForgetRun
	// AnimBindPull has vertical scroll view View set value Node to how
	// far it is pulled past its top: 0 at rest, the room kept above the
	// content while it refreshes.
	AnimBindPull
	// AnimCreateRubberBand makes Node follow Input but resist it past Min
	// and Max, never by more than Value, the size of what moves
	// (RubberBand).
	AnimCreateRubberBand
)

type Animator

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

Animator evaluates the animation graph on a platform's main thread, as NSH's does: backends feed it each ItemAnimation, step it once a frame while it runs, and apply the values it gives each bound view. It is pure Go and touches no view, so every backend shares it.

Drivers are closed-form functions of the time since they started, so the result does not depend on the frame rate or dropped frames. Not safe for concurrent use.

func NewAnimator

func NewAnimator(report func(Event)) *Animator

NewAnimator returns an animator that reports finished runs and reads through report, for the backend to dispatch to the engine.

func (*Animator) Apply

func (a *Animator) Apply(ops []AnimationOp)

Apply applies a batch's changes to the graph.

func (*Animator) BindCanvas

func (a *Animator) BindCanvas(view NodeID, slots []DrawSlot)

BindCanvas has nodes drive the arguments of canvas view's drawing that slots name, replacing what it bound before (Drawing.Slots). ChangedCanvases reports the view next.

func (*Animator) BindNative

func (a *Animator) BindNative(view NodeID, bindings []NativeBinding)

BindNative has animated nodes drive props of native view's component, replacing what it bound before (NativeConfig.Bindings). ChangedNatives hands every bound value over next.

func (*Animator) BindShader

func (a *Animator) BindShader(view NodeID, nodes []ShaderNode)

BindShader has nodes drive lanes of shader view's uniforms, replacing what it bound before (Shader.Nodes). ChangedShaders reports the view next.

func (*Animator) CanvasBound

func (a *Animator) CanvasBound(view NodeID) bool

CanvasBound reports whether view's drawing has bound arguments.

func (*Animator) CanvasOps

func (a *Animator) CanvasOps(view NodeID, d *Drawing) []DrawOp

CanvasOps returns d's ops with the arguments view binds set to their nodes' values, d.Ops itself when it binds none. The slice is reused by the next call for the view.

func (*Animator) Changed

func (a *Animator) Changed(fn func(view NodeID, v AnimatedValues))

Changed calls fn with each bound view whose values may have changed since the last call, and their values.

func (*Animator) ChangedCanvases

func (a *Animator) ChangedCanvases(fn func(view NodeID))

ChangedCanvases calls fn with each canvas view whose bound arguments changed since the last call, for the backend to draw again.

func (*Animator) ChangedNatives

func (a *Animator) ChangedNatives(fn func(view NodeID, b NativeBinding, num float64, col Color))

ChangedNatives calls fn with each bound prop of a native view whose value changed since it last handed it over: a number, or a color when the binding's node outputs one. Backends pass them to SetAnimatedProp.

func (*Animator) ChangedShaders

func (a *Animator) ChangedShaders(fn func(view NodeID))

ChangedShaders calls fn with each shader view whose bound lanes changed since the last call, for the backend to draw again.

func (*Animator) Ending

func (a *Animator) Ending() bool

Ending reports whether something runs that ends on its own: an animation without an endless loop that is not marked Endless, or a settling clamp. Tests wait for it before they look.

func (*Animator) Forget

func (a *Animator) Forget(view NodeID)

Forget drops what is bound to a deleted view.

func (*Animator) FrameRate

func (a *Animator) FrameRate() float64

FrameRate returns the frames a second the running animations need, 0 when one needs every frame the display has, for a backend to slow its frame clock.

func (*Animator) Generation

func (a *Animator) Generation() uint64

Generation changes whenever a value may have changed, for backends that place what values drive, such as sticky cells, when it does.

func (*Animator) Gesture

func (a *Animator) Gesture(ev *Event) bool

Gesture moves the values bound to ev's gesture, a pan, pinch or rotation on ev.ID, before the platform reports it: from where they were as it began, so a gesture grabs a value an animation is moving where it is. A pan's start and end report the bound values in ev.Values. It reports whether a value moved, to draw.

func (*Animator) PanBound

func (a *Animator) PanBound(view NodeID) bool

PanBound reports whether drags on view move values.

func (*Animator) Pull

func (a *Animator) Pull(view NodeID, distance Points) bool

Pull sets the value bound to scroll view view's pull to distance, how far it is pulled past its top.

func (*Animator) Pulls

func (a *Animator) Pulls(view NodeID) bool

Pulls reports whether a value follows view's pull.

func (*Animator) Running

func (a *Animator) Running() bool

Running reports whether an animation runs, or a snapping diff clamp settles, so the backend keeps its frame callback.

func (*Animator) Scroll

func (a *Animator) Scroll(view NodeID, offset Point) bool

Scroll sets the values bound to scroll view view to its offset.

func (*Animator) Settle

func (a *Animator) Settle(view NodeID)

Settle starts the snapping diff clamps that follow scroll view view's values toward their nearer bound, as the view comes to rest: the platform calls it where it reports a scroll's end. Max is the nearer bound only once the clamp's input reached it, so a header near the top of the content shows.

func (*Animator) ShaderLanes

func (a *Animator) ShaderLanes(view NodeID, lanes []float64)

ShaderLanes writes the values of view's bound lanes into lanes, which hold its Shader.Lanes; a lane beyond them is left out.

func (*Animator) Step

func (a *Animator) Step(now time.Duration)

Step advances the running animations to now, a monotonic time. A run with a frame rate moves only when its next frame is due, so a clock faster than the run changes nothing in between.

func (*Animator) StickyShift

func (a *Animator) StickyShift(c StickyCell, offset Points) Points

StickyShift is c.StickyShift with the cell's inset the value its node has, as backends place a cell bound to an animated node. A nil animator keeps the inset c was laid out with.

func (*Animator) Touch

func (a *Animator) Touch(view NodeID)

Touch has Changed report view's values again, as a backend needs after it drew the view's own style over them.

func (*Animator) Value

func (a *Animator) Value(node uint32) (float64, Color, bool)

Value returns node's output now: a number, and a color for a color node; false when there is no such node.

func (*Animator) Values

func (a *Animator) Values(view NodeID) (AnimatedValues, bool)

Values returns view's bound values, and false when it has none.

type Appearance

type Appearance uint8

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

const (
	// AppearanceSystem follows the system's appearance.
	AppearanceSystem Appearance = iota
	AppearanceLight
	AppearanceDark
)

type AttributedText

type AttributedText struct {
	Text  string
	Style TextStyle
	// Spans style byte ranges of Text over Style, in order, without gaps
	// or overlaps where they cover it.
	Spans []TextSpan
	// MaxLines limits the lines shown, cutting the rest as Ellipsize
	// says; 0 shows every line.
	MaxLines  int
	Ellipsize EllipsizeMode
	// Shadow is drawn behind the whole text's glyphs. It is drawing only:
	// it changes no line.
	Shadow TextShadow
	// Attachments are views inside the text, in order: each takes the
	// place of an AttachmentRune of Text, which a span styles.
	Attachments []TextAttachment
	// Origin is, for a text an engine cut from another (Cut, CutToFit,
	// CutRest), the index of each attachment in the text it was cut
	// from, so the engine reports where they went by the app's indices.
	Origin []int
}

AttributedText is styled text for a TextEngine.

func (*AttributedText) Cut

func (t *AttributedText) Cut(head bool, front, back int) AttributedText

Cut returns t with the characters between keep runes from its start and keep from its end replaced by an ellipsis, "Lorem…dolor", or with only the last keep runes after one when head is set, "…sum dolor". The ellipsis takes the style of the first character it replaces, and attachments cut out are dropped. The result is one line, clipped. Engines that cannot ellipsize a line's head or middle themselves search for the most characters that still fit.

func (*AttributedText) CutRest

func (t *AttributedText) CutRest(start int, fits func(*AttributedText) bool) AttributedText

CutRest returns t with its lines before the one starting at byte start as they are, then its rest cut at its head or middle, as Ellipsize says, into the most characters with which fits reports the rest fits on one line: what CoreText does to a several-line text's last line, for engines that ellipsize a head or middle only on one line. A line break joins the two, and the result clips at MaxLines.

func (*AttributedText) CutToFit

func (t *AttributedText) CutToFit(fits func(*AttributedText) bool) AttributedText

CutToFit returns t cut at its head or middle, as its Ellipsize says, keeping the most characters with which fits reports true.

func (*AttributedText) Equal

func (a *AttributedText) Equal(b *AttributedText) bool

Equal reports whether a and b lay out and draw the same.

func (*AttributedText) HasHidden

func (t *AttributedText) HasHidden() bool

HasHidden reports whether a span of t is hidden.

type AudioCommand

type AudioCommand uint8

AudioCommand is what an ItemAudio asks of a sound or a player.

const (
	// AudioLoad has the platform read sound Count's Source, failing with AudioQuotaExceeded past MaxBytes, and decode at most MaxDuration of it into memory, reporting AudioLoaded or AudioFailure.
	AudioLoad AudioCommand = iota
	// AudioPlay starts a playback of sound Count at Volume and Rate over those playing; it reports nothing.
	AudioPlay
	// AudioStop stops every playback of sound Count.
	AudioStop
	// AudioUnload frees sound Count, its playbacks stopped. Nothing is reported of it after this.
	AudioUnload
	// AudioOpen makes player Count for Source, with Volume, Rate, Loop, Session and ProgressInterval, starting at Position. It loads nothing: another command follows it in the same batch.
	AudioOpen
	// AudioPreload has player Count load without playing, reporting AudioOpened once it knows its duration.
	AudioPreload
	// AudioResume plays player Count from where it is, loading it first if it has not or failed, and reports AudioPlaying. After AudioEnded it plays from the start, unless an AudioSeek came since.
	AudioResume
	// AudioPause pauses player Count, reporting AudioPaused.
	AudioPause
	// AudioSeek moves player Count to Position, clamped to its duration, once it can seek, and reports AudioProgress from there.
	AudioSeek
	// AudioSet changes player Count's Volume, Rate and Loop.
	AudioSet
	// AudioClose stops and frees player Count. Nothing is reported of it after this.
	AudioClose
)

func (AudioCommand) String

func (c AudioCommand) String() string

String returns the command's name, as traces print it: load, play, ...

type AudioEvent

type AudioEvent struct {
	Phase              AudioPhase
	Duration, Position time.Duration
	// Bytes is a loaded sound's decoded size, which the core counts against MaxDecodedBytes, and Cut says it was longer than the MaxDuration decoded.
	Bytes int64
	Cut   bool
	// Buffering is AudioBuffer's.
	Buffering bool
	// Seeks counts the AudioSeeks the player applied and Laps the times a looping one started over, so the core drops a report from before the last seek and lets the position go back only with one of them.
	Seeks, Laps uint32
	// Error is one of the Audio errors and Message the platform's words.
	Error, Message string
}

AudioEvent is an EventAudio's report.

type AudioPhase

type AudioPhase uint8

AudioPhase is what an EventAudio reports of a sound or a player.

const (
	// AudioLoaded says a sound decoded: Duration, Bytes and Cut.
	AudioLoaded AudioPhase = iota
	// AudioOpened says a player knows its Duration, 0 for a live stream.
	AudioOpened
	// AudioPlaying says a player plays.
	AudioPlaying
	// AudioPaused says a player paused, the app's Pause or the system's, such as an interruption or the app leaving the foreground.
	AudioPaused
	// AudioProgress says where a playing player is, every ProgressInterval and after a seek: Position, Duration, Seeks and Laps. The core reports the position once more as a player pauses or ends, so a platform need not.
	AudioProgress
	// AudioBuffer says whether a player waits for data (Buffering).
	AudioBuffer
	// AudioEnded says a player played to its end; never while it loops.
	AudioEnded
	// AudioFailure says a sound did not load or a player failed, with Error and Message. A player plays nothing more until a command loads it again.
	AudioFailure
)

type AudioRequest

type AudioRequest struct {
	Command AudioCommand
	// Source is AudioLoad's and AudioOpen's: an "asset:" path in the app's resources, a file path or file: URL, a data: URL, an http(s) URL, or Data. A platform reads it as it reads an image's.
	Source ImageSource
	// MaxBytes and MaxDuration are AudioLoad's limits.
	MaxBytes    int64
	MaxDuration time.Duration
	// Volume runs from 0 to 1 and Rate from 0.5 to 2; AudioPlay's, AudioOpen's and AudioSet's.
	Volume, Rate float32
	// Loop has a player start over at its end, with no AudioEnded.
	Loop bool
	// Session is a player's: what it does to other apps' audio while it plays. Sounds mix with other apps' audio.
	Session AudioSession
	// ProgressInterval is the time between a playing player's AudioProgress reports, at least 16 milliseconds.
	ProgressInterval time.Duration
	// Position is AudioOpen's and AudioSeek's.
	Position time.Duration
}

AudioRequest is an ItemAudio's request. Count numbers the sound or the player, from one counter of the process, so a sound's and a player's are never the same.

type AudioSession

type AudioSession uint8

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

const (
	// AudioSessionDefault leaves the app's audio settings to decide: on
	// iOS the device's silent mode silences it.
	AudioSessionDefault AudioSession = iota
	// AudioSessionPlayback plays in iOS's silent mode as speech, pausing
	// other apps' audio until it pauses, ends or goes; Android holds the
	// audio focus while it plays.
	AudioSessionPlayback
	// AudioSessionMixWithOthers plays in iOS's silent mode as speech, with
	// other apps' audio going on.
	AudioSessionMixWithOthers
)

type AutoCapitalize

type AutoCapitalize uint8

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

const (
	AutoCapitalizeSentences AutoCapitalize = iota
	AutoCapitalizeNone
	AutoCapitalizeWords
	AutoCapitalizeCharacters
)

type AutoComplete

type AutoComplete uint8

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

const (
	// AutoCompleteDefault lets the platform decide.
	AutoCompleteDefault AutoComplete = iota
	AutoCompleteOff
	AutoCompleteUsername
	// AutoCompletePassword is an existing password.
	AutoCompletePassword
	// AutoCompleteNewPassword is a password being chosen.
	AutoCompleteNewPassword
	// AutoCompleteOneTimeCode is a code from a text message or e-mail.
	AutoCompleteOneTimeCode
	AutoCompleteEmail
	AutoCompleteTel
	AutoCompleteName
	AutoCompleteGivenName
	AutoCompleteFamilyName
	AutoCompleteMiddleName
	AutoCompleteNickname
	AutoCompleteOrganization
	// AutoCompleteStreetAddress is every line of a street address.
	AutoCompleteStreetAddress
	AutoCompleteAddressLine1
	AutoCompleteAddressLine2
	AutoCompleteCity
	// AutoCompleteRegion is a state or region.
	AutoCompleteRegion
	AutoCompletePostalCode
	AutoCompleteCountry
	AutoCompleteCreditCardNumber
	AutoCompleteCreditCardExpiration
	AutoCompleteCreditCardSecurityCode
	AutoCompleteCreditCardName
	AutoCompleteURL
	AutoCompleteBirthdate
)

func (AutoComplete) String

func (a AutoComplete) String() string

String returns the HTML autocomplete token, empty for the default.

type BackdropMaterial

type BackdropMaterial uint8

BackdropMaterial is the system material iOS draws a backdrop blur with, from the thinnest.

const (
	BackdropUltraThin BackdropMaterial = iota
	BackdropThin
	BackdropRegular
	BackdropThick
	BackdropChrome
)

type BlendMode

type BlendMode uint8

BlendMode is how a view's pixels mix with what is drawn behind it, as CSS's mix-blend-mode.

const (
	BlendNormal BlendMode = iota
	BlendMultiply
	BlendScreen
	BlendOverlay
	BlendDarken
	BlendLighten
	BlendColorDodge
	BlendColorBurn
	BlendHardLight
	BlendSoftLight
	BlendDifference
	BlendExclusion
	BlendHue
	BlendSaturation
	BlendColor
	BlendLuminosity
	BlendPlusLighter
	// BlendPlusDarker is a linear burn: the sum of the colors less white.
	BlendPlusDarker
)

func (BlendMode) Name

func (b BlendMode) Name() string

Name returns the blend mode's CSS name.

type BlurLevel

type BlurLevel struct {
	Blur, Total Points
	Full, Gone  float32
}

BlurLevel is a step of a soft edge's blur, which grows toward the side: what is under it blurred, shown wholly from the side to Full of the way across the band, and fading out from there to nothing at Gone. Blur adds to the levels drawn before it, whose blurs it reads, as variances add up; Total is the whole blur where it shows wholly, for a platform whose levels each read the content alone.

func SoftEdgeLevels

func SoftEdgeLevels() []BlurLevel

SoftEdgeLevels returns the levels of a soft edge's blur, from the finest, as MyGo's progressive blurs: their blurs double from one level to the next up to SoftEdgeBlur, and between two a pixel shows both mixed, which the eye takes for a blur between them.

type BorderStyle

type BorderStyle uint8

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

const (
	BorderSolid BorderStyle = iota + 1
	// BorderDashed draws dashes three widths long, three apart.
	BorderDashed
	// BorderDotted draws round dots a width across, a width apart.
	BorderDotted
	// BorderNone and BorderHidden draw no border, and layout gives it
	// no width, whatever the widths say.
	BorderNone
	BorderHidden
)

func (BorderStyle) Dashes

func (s BorderStyle) Dashes(width Points) (on, off Points, round, ok bool)

Dashes returns the dash pattern of a line of width drawn in style, on then off, with round caps for dots; ok is false for solid lines.

type Bounds

type Bounds struct {
	Origin Point
	Size   Size
}

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

func BandRect

func BandRect(s Side, size Size, band Points) Bounds

BandRect returns the band of side s of a view of size size, in its own points.

func CanvasDamage

func CanvasDamage(before, after []DrawOp) (Bounds, bool)

CanvasDamage returns the part of a canvas that playing after instead of before changes, in the canvas's points, as NSH's DamageScan: before and after are one drawing's ops with its bound arguments at two moments, so they differ only in those arguments. It replays both for their geometry (the transform and the path, line widths, joins and caps, shadows) and adds up the bounds of the painting ops that changed or paint with state that did (the transform, the path, the alpha, the paint, the line's settings, the shadow), under both. Bounds are conservative: curves by their control points, arcs by their circle, strokes by half their width times the transform's largest scale, times the miter limit at miter joins or √2 at square caps, shadows by twice their blur past their offset, text by 1.5 em per character and 1.5 em above and below its baseline. It reports false where only a full redraw is right: a changed clip, changed painting under a composite operation other than source-over, which changes pixels outside its shape, an image at its natural size, or bounds that are not finite. A platform that redraws the area replays the whole drawing clipped to it, so the pixels are those of a full redraw.

func CaretRect

func CaretRect(l TextLayout, c Caret) (Bounds, bool)

CaretRect returns the caret at c in l; false when l has no lines or does not hit-test.

func HairlineRect

func HairlineRect(s Side, band Size) Bounds

HairlineRect returns where a hard edge's hairline is in its band of size band: along the band's other end, outside it.

func LerpBounds

func LerpBounds(a, b Bounds, p float64) Bounds

LerpBounds interpolates a frame from a to b at progress p, never to a negative size.

func RangeRects

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

RangeRects appends to out the boxes of the UTF-16 range from start to end in l.

func (Bounds) Contains

func (b Bounds) Contains(p Point) bool

Contains reports whether p lies inside b.

type BoxShadow

type BoxShadow struct {
	Offset Point
	Blur   Points
	Spread Points
	Color  Color
	Inset  bool
}

BoxShadow is one shadow of a view's box, as one of CSS's box-shadow layers: its shape is the box's, grown by Spread, moved by Offset and blurred by Blur, CSS's blur radius (twice the Gaussian's standard deviation). An inset shadow falls inside the box, over its background, from the edges inwards.

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.

type CanvasGradient

type CanvasGradient struct {
	// Radial makes a radial gradient from the focal circle (X1, Y1, R1)
	// to the outer circle (X2, Y2, R2), as the web's
	// createRadialGradient. Conic makes one around (X1, Y1), offset 0 at
	// Angle radians from the x axis and the offsets turning clockwise, as
	// createConicGradient. Otherwise offset 0 is at (X1, Y1) and offset 1
	// at (X2, Y2).
	Radial, Conic bool
	X1, Y1, R1    float32
	X2, Y2, R2    float32
	Angle         float32
	// Transform is a, b, c, d, e, f, as SVG's matrix(): it maps (x, y) to
	// (a*x + c*y + e, b*x + d*y + f). All zeros is the identity.
	Transform [6]float32
	Spread    GradientSpread
	// Stops are in increasing offsets from 0 to 1, with unpremultiplied
	// colors; between them colors are interpolated.
	Stops []GradientStop
}

CanvasGradient is a linear, radial or conic color gradient that DrawFillGradient and DrawStrokeGradient paint with. Its points are in gradient space, which Transform maps into the coordinates of the fill or stroke that uses it.

func CanvasConic

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

CanvasConic returns a gradient around (x, y) starting at angle radians.

func CanvasLinear

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

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

func CanvasRadial

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

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

func (*CanvasGradient) At

func (g *CanvasGradient) At(t float64) Color

At returns g's color at offset t, its stops clamped and interpolated in unpremultiplied sRGB, for players that sample gradients themselves.

func (*CanvasGradient) Matrix

func (g *CanvasGradient) Matrix() [6]float32

Matrix returns g's transform, the identity for all zeros.

type CanvasNode

type CanvasNode struct {
	// Bounds is where it is in the canvas, in the canvas's own points,
	// whatever the transform.
	Bounds   Bounds
	Role     Role
	Label    string
	TestID   string
	Selected bool
}

CanvasNode is a named part of a drawing, such as a chart's bar or a grid's cell: assistive technology and tests see it as a child of the canvas, and a press on it presses at its center.

type CanvasSplit

type CanvasSplit struct {
	// At is the first op a slot binds, len(Ops) when none is bound.
	At int
	// Path says the current path the ops before At build is still used
	// from At on: by a clip before At, or by an op from At on before a
	// DrawBeginPath starts anew. A path begun anew just before At is
	// empty there and is not.
	Path bool
}

CanvasSplit is where a drawing's static part ends, as NSH's first_animated and prefix_path_needed: what the ops before At paint is the same whatever its bound arguments hold. A backend may keep those pixels and, when the arguments change, play only the painting from At on over them; the ops before At still set the state.

func SplitCanvas

func SplitCanvas(d *Drawing) CanvasSplit

SplitCanvas returns where d's static part ends.

func (CanvasSplit) Skips

func (s CanvasSplit) Skips(i int, op *DrawOp) bool

Skips reports whether a player drawing over the kept static part leaves out op i: one before At that paints, or that builds a path no op from At on uses.

func (CanvasSplit) Static

func (s CanvasSplit) Static(d *Drawing) bool

Static reports whether d has a static part worth keeping: some ops before At paint, and some from At on do too.

type Caret

type Caret struct {
	Offset   int
	Affinity Affinity
}

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

func HitTest

func HitTest(l TextLayout, p Point) Caret

HitTest returns the caret nearest p in l, the start of the text when l does not hit-test.

type CaretCluster

type CaretCluster struct {
	Start, End  int
	Left, Right Points
	// RTL says they run right to left: they start at Right.
	RTL bool
}

CaretCluster is where characters that take one caret stop at each end (a grapheme cluster, or a ligature) sit on their line: UTF-16 offsets and their left and right edges.

type CaretLayout

type CaretLayout []CaretLine

CaretLayout hit-tests the lines an engine read from its layout, so every engine answers as the others do.

func (CaretLayout) CaretRect

func (cl CaretLayout) CaretRect(c Caret) (Bounds, bool)

CaretRect implements TextHitTester.

func (CaretLayout) HitTest

func (cl CaretLayout) HitTest(p Point) Caret

HitTest implements TextHitTester.

func (CaretLayout) RangeRects

func (cl CaretLayout) RangeRects(start, end int, out []Bounds) []Bounds

RangeRects implements TextHitTester.

type CaretLine

type CaretLine struct {
	// Start and End are the UTF-16 offsets of its first character and
	// past its last, its line break included.
	Start, End int
	// Box is the line box: as high as the line, from its left edge to its
	// right, in the content box.
	Box Bounds
	// RTL says the line runs right to left: it ends at its left.
	RTL bool
	// Clusters are its characters' places in logical order, without its
	// line break.
	Clusters []CaretCluster
}

CaretLine is a laid-out line as CaretLayout hit-tests it.

type Causes

type Causes struct {
	Writes                  []Write
	Memos, Renders, Effects int
	// App is how long the app's code ran before the commit, its handlers, timers and effects, and Layout how long the commit laid the tree out; a trace's took is the commit's whole.
	App, Layout time.Duration
	// Ran are the computations that ran, by kind and the line that made them, the longest first; they are named only while DevTools record sites (devtools.Enabled).
	Ran []Ran
}

Causes are what a commit followed from: the signal writes since the graph's last commit, grouped by the line that made them, and the computations that ran.

type Channel

type Channel uint8

Channel is what a shader lane reads of a node: its number, or its color's red, green, blue or alpha, from 0 to 1.

const (
	ChannelNumber Channel = iota
	ChannelRed
	ChannelGreen
	ChannelBlue
	ChannelAlpha
)

func (Channel) Of

func (c Channel) Of(num float64, color Color) float64

Of is what c reads of a node's number and color.

type ClipboardImage

type ClipboardImage struct {
	// PNG is the image encoded as a PNG, which an ImageSource's Data
	// shows.
	PNG []byte
	// Size is its size in pixels.
	Size Size
	// TooLarge is the bytes of a PNG over MaxClipboardImage, left out of
	// PNG.
	TooLarge int
	// Err says why the image the clipboard holds could not be read.
	Err string
}

ClipboardImage is an image read from the clipboard, or why the one it holds was not.

func ClipboardPNG

func ClipboardPNG(data []byte) *ClipboardImage

ClipboardPNG is ReadClipboardImage of a PNG whose size it reads, which fails for data that is no PNG.

func ReadClipboardImage

func ReadClipboardImage(png []byte, size Size, err error) *ClipboardImage

ReadClipboardImage is a platform's answer to a ClipboardReadImage from what converting the clipboard's image to a PNG gave: nil when there was nothing to convert.

type ClipboardRead

type ClipboardRead uint8

ClipboardRead is what an ItemReadClipboard asks of the clipboard.

const (
	// ClipboardReadText reads its plain text, "" when it has none.
	ClipboardReadText ClipboardRead = iota
	// ClipboardReadHasText reports whether it holds text, without reading it,
	// so iOS shows no paste notice.
	ClipboardReadHasText
	// ClipboardReadImage reads its image as a PNG.
	ClipboardReadImage
	// ClipboardReadHasImage reports whether it holds an image, without
	// reading it.
	ClipboardReadHasImage
	// ClipboardReadFiles reads the file: URLs of the local files it holds,
	// such as files copied in a file manager.
	ClipboardReadFiles
)

type Color

type Color uint32

Color is an sRGB color packed as 0xRRGGBBAA, the wire form of mount items. Its zero value is unset: no background, or text color inherited from the parent.

const CurrentColor Color = 0x00000001

CurrentColor, in a style's colors other than the text color itself, is the text color the view has: its own, else the one it inherits, else black, as CSS's currentColor. It never draws as itself.

func MixColors

func MixColors(a, b Color, t float32, space ColorSpace) Color

MixColors returns the color t of the way from a to b, mixed in space with premultiplied alpha, as CSS's gradients and color-mix() mix.

func ParseColor

func ParseColor(s string) (Color, error)

ParseColor reads a CSS color: hex, rgb(), rgba(), hsl(), hsla(), a color name, transparent or currentColor, which is CurrentColor, as is a color-mix() of it a mark ResolveCurrent reads.

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 ResolveCurrent

func ResolveCurrent(c, color Color) Color

ResolveCurrent returns c with CurrentColor, or the marks of its mixes, replaced by color.

func (Color) Components

func (c Color) Components() (r, g, b, a float64)

Components returns the red, green, blue and alpha channels from 0 to 1.

func (Color) Faded

func (c Color) Faded(f float32) Color

Faded returns c with its alpha multiplied by f, from 0 to 1.

func (Color) Over

func (c Color) Over(under Color) Color

Over returns c drawn over an opaque under.

type ColorMatrix

type ColorMatrix [20]float32

ColorMatrix is a 4×5 color matrix in rows, over unpremultiplied red, green, blue and alpha from 0 to 1 and a constant 1, as SVG's feColorMatrix.

func (ColorMatrix) Then

Then returns the matrix that applies m, then n.

type ColorSpace

type ColorSpace uint8

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

const (
	// ColorSpaceOklab, the zero value, mixes perceptually, without the
	// grey middle sRGB gives complementary colors; Tailwind's gradients
	// mix in it.
	ColorSpaceOklab ColorSpace = iota
	// ColorSpaceSRGB mixes the channels, as CSS's gradients of plain
	// colors do.
	ColorSpaceSRGB
	ColorSpaceLinearSRGB
	// ColorSpaceOklch mixes lightness, chroma and hue, the hue the
	// shorter way round.
	ColorSpaceOklch
)

type ColorStop

type ColorStop struct {
	Color Color
	At    Length
}

ColorStop is a color at a place along a gradient: a percentage of its line (of a turn for a conic gradient) or a length from its start. An auto At, the zero value, spreads the stop evenly between its neighbors.

type CompositeOp

type CompositeOp uint8

CompositeOp is how drawing mixes with what the canvas holds, as the web's globalCompositeOperation: Porter and Duff's operators, then the blend modes.

const (
	CompositeSourceOver CompositeOp = iota
	CompositeSourceIn
	CompositeSourceOut
	CompositeSourceAtop
	CompositeDestinationOver
	CompositeDestinationIn
	CompositeDestinationOut
	CompositeDestinationAtop
	CompositeLighter
	CompositeCopy
	CompositeXor
	CompositeMultiply
	CompositeScreen
	CompositeOverlay
	CompositeDarken
	CompositeLighten
	CompositeColorDodge
	CompositeColorBurn
	CompositeHardLight
	CompositeSoftLight
	CompositeDifference
	CompositeExclusion
	CompositeHue
	CompositeSaturation
	CompositeColor
	CompositeLuminosity
)

func (CompositeOp) Blend

func (c CompositeOp) Blend() (BlendMode, bool)

Blend returns the blend mode of a blend operator, which mixes colors and composites as source-over.

func (CompositeOp) Name

func (c CompositeOp) Name() string

Name returns the operator's name on the web.

func (CompositeOp) Unbounded

func (c CompositeOp) Unbounded() bool

Unbounded reports whether the operator changes the canvas outside what is drawn, clearing it there: source-in, source-out, destination-in, destination-atop and copy. Players that composite only where a shape covers draw it into a layer of the whole canvas first.

type Corners

type Corners struct{ TopLeft, TopRight, BottomRight, BottomLeft Points }

Corners holds a radius per corner of a box. Right to left, the core swaps left and right, as it swaps the other sides.

func AllCorners

func AllCorners(r Points) Corners

AllCorners returns corners of the same radius.

func (Corners) Array

func (c Corners) Array() [4]Points

Array returns the radii clockwise from the top left.

func (Corners) Fit

func (c Corners) Fit(size Size) Corners

Fit scales the radii down, all by one factor, until adjacent ones fit along the sides of a box of size, as CSS does with border-radius, and clamps negative ones to 0.

func (Corners) Inset

func (c Corners) Inset(d Points) Corners

Inset returns the radii of a box d inside this one (d negative grows it): each shrinks by d, never below 0, as CSS shrinks the inner corners of a border and grows a shadow's spread.

func (Corners) Uniform

func (c Corners) Uniform() bool

Uniform reports whether every corner has the same radius.

type Cursor

type Cursor uint8

Cursor is the pointer's look over a view (cursor). Auto leaves the look to the view under it or its nearest ancestor that names one; a pressable view's Auto is a pointer on the web.

const (
	CursorAuto Cursor = iota
	CursorDefault
	CursorPointer
	CursorText
	CursorWait
	CursorProgress
	CursorHelp
	CursorCrosshair
	CursorMove
	CursorGrab
	CursorGrabbing
	CursorNotAllowed
	CursorZoomIn
	CursorZoomOut
	CursorColResize
	CursorRowResize
	CursorNone
	// CursorNwseResize and CursorNeswResize are the diagonal resizes:
	// top left to bottom right, and top right to bottom left.
	CursorNwseResize
	CursorNeswResize
)

func SpanCursor

func SpanCursor(spans []TextSpan, i int) (Cursor, bool)

SpanCursor returns the cursor a span names over byte offset i (-1 off the text's glyphs), and false where none does.

func (Cursor) Name

func (c Cursor) Name() string

Name returns the cursor's CSS name.

type Curve

type Curve struct{ X1, Y1, X2, Y2 float32 }

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

func (Curve) At

func (c Curve) At(x float64) float64

At returns the curve's progress at time fraction x from 0 to 1.

type DecayConfig

type DecayConfig struct {
	Velocity     float64
	Deceleration float64
	Clamp        bool
	Min, Max     float64
	Bounce       float64
}

DecayConfig slows a value from Velocity (units per second; the value's current velocity when 0) by Deceleration per millisecond (0.998 when 0). With Clamp it stays within Min and Max: it stops at a bound, or bounces off it keeping Bounce of its speed.

type DirectoriesRequest

type DirectoriesRequest struct {
	// Limit is the most folders the user picks: 1 for a single pick, at
	// most MaxPicked.
	Limit int
	// Title is the dialog's title or message where the target has one.
	Title string
	// Button is the dialog's accept button label where the target has one.
	Button string
	// Start is the folder the dialog opens in when it exists.
	Start string
}

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

type Directory

type Directory struct {
	// Name is its name as the user saw it.
	Name string
	// Path is where it is on disk, "" on Android and the web, where FS
	// reads it.
	Path string
	// FS reads a folder that has no Path.
	FS fs.FS
}

Directory is a folder the user picked, which reads what it holds as an fs.FS: names are slash-separated inside it, "." for itself.

func FinishDirectories

func FinishDirectories(r DirectoriesRequest, dirs []Directory) []Directory

FinishDirectories returns dirs as the app gets them: at most r.Limit, each with a name.

func (Directory) Open

func (d Directory) Open(name string) (fs.File, error)

Open opens the file or folder at name inside d.

func (Directory) ReadDir

func (d Directory) ReadDir(name string) ([]fs.DirEntry, error)

ReadDir reads the folder at name inside d, sorted by name.

func (Directory) Stat

func (d Directory) Stat(name string) (fs.FileInfo, error)

Stat describes the file or folder at name inside d.

type DisplayInfo

type DisplayInfo struct {
	ID           string
	Frame        Bounds
	VisibleFrame Bounds
	Scale        float32
	Main         bool
}

DisplayInfo is one physical display in the desktop's screen coordinate space. Frame is its whole area; VisibleFrame is the area available to windows. Scale is device pixels per point, and Main marks the primary display.

type DrawArg

type DrawArg uint8

DrawArg is an argument of a DrawOp that a DrawSlot binds.

const (
	ArgX DrawArg = iota
	ArgY
	ArgX1
	ArgY1
	ArgX2
	ArgY2
	ArgW
	ArgH
	ArgR
	ArgA
	ArgA0
	ArgA1
	ArgRY
	// ArgColor takes a color node, such as an interpolation to Colors.
	ArgColor
)

type DrawKind

type DrawKind uint8

DrawKind is a drawing operation.

const (
	DrawSave DrawKind = iota + 1
	DrawRestore
	DrawTranslate // X, Y
	DrawScale     // X, Y
	DrawRotate    // A radians
	DrawBeginPath
	DrawMoveTo    // X, Y
	DrawLineTo    // X, Y
	DrawQuadTo    // X1, Y1 (control), X, Y
	DrawCubicTo   // X1, Y1, X2, Y2 (controls), X, Y
	DrawArc       // X, Y (center), R, A0, A1 (radians), CCW
	DrawRect      // X, Y, W, H
	DrawRoundRect // X, Y, W, H, R
	DrawEllipse   // X, Y (center), RX, RY
	DrawClosePath
	DrawFill        // the current path with the fill paint, by EvenOdd's rule
	DrawStroke      // the current path with the stroke settings
	DrawClip        // to the current path, by EvenOdd's rule
	DrawFillColor   // Color, the fill until the next DrawFillGradient
	DrawStrokeColor // Color, the stroke until the next DrawStrokeGradient
	DrawLineWidth   // W
	DrawLineCap     // Cap
	DrawLineJoin    // Join
	DrawAlpha       // A, the global alpha
	// DrawFillText draws Text in Font with its baseline starting at X+X1,
	// Y+Y1: X, Y is the point the app gave and X1, Y1 how far the
	// recorder moved the text from it for TextAlign and TextBaseline.
	DrawFillText
	DrawClear // X, Y, W, H to transparent

	// DrawFillGradient makes Gradient the fill until the next
	// DrawFillColor. A recording always sets a fill color before it, the
	// gradient's first, so a player that does not paint gradients fills
	// with that color instead.
	DrawFillGradient
	// DrawStrokeGradient makes Gradient the stroke until the next
	// DrawStrokeColor, after a stroke color as DrawFillGradient is.
	DrawStrokeGradient

	// DrawTransform multiplies the transform by the matrix with columns
	// (X1, Y1), (X2, Y2) and (X, Y): the web's transform(a, b, c, d, e,
	// f) with a, b = X1, Y1, c, d = X2, Y2 and e, f = X, Y.
	DrawTransform
	// DrawSetTransform replaces the transform with that matrix, from the
	// canvas's own coordinates.
	DrawSetTransform
	// DrawComposite sets how later drawing mixes with the canvas
	// (Composite).
	DrawComposite
	// DrawLineDash sets the stroke's dashes (Dash; nil or empty is
	// solid) and DrawLineDashOffset where they start (W).
	DrawLineDash
	DrawLineDashOffset
	// DrawMiterLimit sets how far a miter join reaches, in line widths
	// (W).
	DrawMiterLimit
	// DrawShadow sets the shadow of later drawing: Color (transparent is
	// none), offset X, Y and blur R, in the canvas's own coordinates,
	// whatever the transform.
	DrawShadow
	// DrawStrokeText draws Text as DrawFillText does, stroked with the
	// stroke settings.
	DrawStrokeText
	// DrawImage draws Image into the rectangle X, Y, W, H, at its natural
	// size when W and H are 0, from the part X1, Y1, X2 (width), Y2
	// (height) of it in its own points, all of it when X2 and Y2 are 0.
	// The platform loads the image and draws again once it has it.
	DrawImage
	// DrawTextAlign and DrawTextBaseline record the TextAlign and
	// TextBaseline later texts take. The recorder places the texts with
	// them, so players skip these.
	DrawTextAlign
	DrawTextBaseline
)

func (DrawKind) BuildsPath

func (k DrawKind) BuildsPath() bool

BuildsPath reports whether an op of kind k adds to the current path or closes it.

func (DrawKind) Paints

func (k DrawKind) Paints() bool

Paints reports whether an op of kind k changes pixels.

func (DrawKind) UsesPath

func (k DrawKind) UsesPath() bool

UsesPath reports whether an op of kind k builds on the current path or closes, fills, strokes or clips with it.

type DrawOp

type DrawOp struct {
	Kind                   DrawKind
	X, Y, X1, Y1, X2, Y2   float32
	W, H, R, A, A0, A1, RY float32
	CCW                    bool
	Color                  Color
	Cap                    LineCap
	Join                   LineJoin
	Text                   string
	Font                   Font
	// EvenOdd fills or clips by the even-odd rule instead of the nonzero
	// one.
	EvenOdd   bool
	Gradient  *CanvasGradient
	Composite CompositeOp
	Dash      *LineDash
	Image     *ImageSource
	// TextAlign and TextBaseline are what a text op was placed with.
	TextAlign    TextAlign
	TextBaseline TextBaseline
}

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

type DrawSlot

type DrawSlot struct {
	Op   int
	Arg  DrawArg
	Node uint32
}

DrawSlot binds argument Arg of operation Op to animated node Node.

func (DrawSlot) Set

func (s DrawSlot) Set(op DrawOp, num float64, col Color) DrawOp

Set returns op with the slot's argument set to num, or to col for ArgColor.

type Drawing

type Drawing struct {
	Ops []DrawOp
	// Slots bind arguments of Ops to animated nodes: the platform plays
	// the ops with the nodes' values in their place, and plays them again
	// when one changes, with no work on the engine.
	Slots []DrawSlot
	// Nodes are named parts of what it draws, which assistive technology
	// and tests see as the canvas's children.
	Nodes []CanvasNode
	// ViewPaints name the ops whose value is their canvas view's paint
	// (FillFromView and the like), which the core sets before the platform
	// plays the drawing.
	ViewPaints []ViewPaint
	// contains filtered or unexported fields
}

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. Once handed to the platform it never changes.

Methods that need the path or the transform so far (ArcTo, EllipseArc, FillPath, the queries) replay the operations recorded since they last looked, so a drawing that never asks pays nothing for them.

func NewDrawing

func NewDrawing(text TextEngine) *Drawing

NewDrawing returns an empty drawing that measures text with text, as the core records a Canvas's: MeasureText, TextMetrics and the alignment of texts ask it.

func (*Drawing) Arc

func (d *Drawing) Arc(x, y, r, a0, a1 float32, ccw bool) *Drawing

Arc adds an arc of radius r around (x, y) from angle a0 to a1, joined to the path by a line.

func (*Drawing) ArcTo

func (d *Drawing) ArcTo(x1, y1, x2, y2, r float32) *Drawing

ArcTo adds an arc of radius r touching the line from the current point to (x1, y1) and the line from there to (x2, y2), joined to the path by a line, as the web's arcTo.

func (*Drawing) BeginPath

func (d *Drawing) BeginPath() *Drawing

func (*Drawing) Bind

func (d *Drawing) Bind(arg DrawArg, node AnimatedArg) *Drawing

Bind has the platform play the last operation's argument arg with the value of node, every frame it changes, in place of the one recorded. The queries and the text placement read the recorded value.

func (*Drawing) Clear

func (d *Drawing) Clear(x, y, w, h float32) *Drawing

Clear makes a rectangle transparent.

func (*Drawing) Clip

func (d *Drawing) Clip() *Drawing

Clip clips later drawing to the current path, by the nonzero rule.

func (*Drawing) ClipEvenOdd

func (d *Drawing) ClipEvenOdd() *Drawing

ClipEvenOdd clips by the even-odd rule.

func (*Drawing) ClipPath

func (d *Drawing) ClipPath(p *Path, rule FillRule) *Drawing

ClipPath clips later drawing to p by rule, leaving the current path as it is.

func (*Drawing) ClosePath

func (d *Drawing) ClosePath() *Drawing

func (*Drawing) CubicTo

func (d *Drawing) CubicTo(x1, y1, x2, y2, x, y float32) *Drawing

CubicTo adds a cubic curve through control points 1 and 2.

func (*Drawing) DrawImage

func (d *Drawing) DrawImage(img ImageSource, x, y float32) *Drawing

DrawImage draws img at (x, y) at its natural size.

func (*Drawing) DrawImageFrom

func (d *Drawing) DrawImageFrom(img ImageSource, sx, sy, sw, sh, x, y, w, h float32) *Drawing

DrawImageFrom draws the part sx, sy, sw, sh of img, in its own points, stretched into the rectangle x, y, w, h.

func (*Drawing) DrawImageIn

func (d *Drawing) DrawImageIn(img ImageSource, x, y, w, h float32) *Drawing

DrawImageIn draws img stretched into the rectangle x, y, w, h.

func (*Drawing) Ellipse

func (d *Drawing) Ellipse(x, y, rx, ry float32) *Drawing

Ellipse adds the whole ellipse around (x, y) with radii rx and ry, as a subpath of its own.

func (*Drawing) EllipseArc

func (d *Drawing) EllipseArc(x, y, rx, ry, rotation, a0, a1 float32, ccw bool) *Drawing

EllipseArc adds an arc of the ellipse around (x, y) with radii rx and ry turned by rotation, from angle a0 to a1, joined to the path by a line, as the web's ellipse. Its curves are cubic Béziers.

func (*Drawing) Fill

func (d *Drawing) Fill() *Drawing

Fill fills the current path by the nonzero rule.

func (*Drawing) FillBackgroundFromView

func (d *Drawing) FillBackgroundFromView(area Bounds) *Drawing

FillBackgroundFromView fills the current path with the canvas view's background, Background and Gradients, placed over area as over a box of that size, as CSS's clip-path shows a box's background. The view then draws no background of its own, so a canvas that takes it draws it once, inside its shapes; one with nothing to fill yet records this over an empty path, so its view never shows the background as a box.

func (*Drawing) FillEvenOdd

func (d *Drawing) FillEvenOdd() *Drawing

FillEvenOdd fills the current path by the even-odd rule.

func (*Drawing) FillFromView

func (d *Drawing) FillFromView(initial Paint) *Drawing

FillFromView fills with the canvas view's Fill style, inherited as CSS inherits it, or with initial where no view sets one.

func (*Drawing) FillPath

func (d *Drawing) FillPath(p *Path, rule FillRule) *Drawing

FillPath fills p by rule, leaving the current path as it is.

func (*Drawing) FillRect

func (d *Drawing) FillRect(x, y, w, h float32) *Drawing

FillRect fills a rectangle with the fill paint, leaving the current path as it is.

func (*Drawing) FillText

func (d *Drawing) FillText(text string, x, y float32, font Font) *Drawing

FillText draws text at (x, y), placed by the text alignment and baseline: its baseline's start, by default.

func (*Drawing) HasBackground

func (d *Drawing) HasBackground() bool

HasBackground reports whether d fills shapes with its view's background, which the view then does not draw.

func (*Drawing) IsPointInPath

func (d *Drawing) IsPointInPath(x, y float32, rule FillRule) bool

IsPointInPath reports whether the point (x, y), in the canvas's own points, is inside the current path by rule, as the web's isPointInPath. After Draw returns, a kept drawing answers from all it recorded, so press handlers can hit-test its shapes. Bound arguments count as recorded.

func (*Drawing) IsPointInStroke

func (d *Drawing) IsPointInStroke(x, y float32) bool

IsPointInStroke reports whether the point is on the current path's stroke with the line width, caps and transform in effect; joins count as round and dashes as solid.

func (*Drawing) LineDashFromView

func (d *Drawing) LineDashFromView() *Drawing

LineDashFromView dashes lines as the canvas view's StrokeDash style says, solid where no view sets one.

func (*Drawing) LineTo

func (d *Drawing) LineTo(x, y float32) *Drawing

func (*Drawing) LineWidthFromView

func (d *Drawing) LineWidthFromView() *Drawing

LineWidthFromView sets the line width to the canvas view's StrokeWidth style, 1 where no view sets one.

func (*Drawing) MeasureText

func (d *Drawing) MeasureText(text string, font Font) float32

MeasureText returns the advance width of text in font, its trailing white space included, as a browser's measureText counts it.

func (*Drawing) MoveTo

func (d *Drawing) MoveTo(x, y float32) *Drawing

func (*Drawing) Node

func (d *Drawing) Node(n CanvasNode) *Drawing

Node names a part of the drawing for assistive technology and tests.

func (*Drawing) Painted

func (d *Drawing) Painted(p *PaintStyle, current Color) *Drawing

Painted returns d with its view paints set from p, current being the view's text color, or d itself when it takes none.

func (*Drawing) PathContains

func (d *Drawing) PathContains(p *Path, x, y float32, rule FillRule) bool

PathContains reports whether the point is inside p under the current transform, by rule.

func (*Drawing) QuadTo

func (d *Drawing) QuadTo(cx, cy, x, y float32) *Drawing

QuadTo adds a quadratic curve through control point (cx, cy).

func (*Drawing) Rect

func (d *Drawing) Rect(x, y, w, h float32) *Drawing

func (*Drawing) ResetTransform

func (d *Drawing) ResetTransform() *Drawing

ResetTransform goes back to the canvas's own coordinates.

func (*Drawing) Restore

func (d *Drawing) Restore() *Drawing

func (*Drawing) Rotate

func (d *Drawing) Rotate(radians float32) *Drawing

func (*Drawing) RoundRect

func (d *Drawing) RoundRect(x, y, w, h, r float32) *Drawing

RoundRect adds a rectangle with corners of radius r.

func (*Drawing) RoundRectCorners

func (d *Drawing) RoundRectCorners(x, y, w, h, topLeft, topRight, bottomRight, bottomLeft float32) *Drawing

RoundRectCorners adds a rectangle with a radius for each corner, from the top left one clockwise, scaled down together where they overlap, as the web's roundRect.

func (*Drawing) Save

func (d *Drawing) Save() *Drawing

func (*Drawing) Scale

func (d *Drawing) Scale(x, y float32) *Drawing

func (*Drawing) SetAlpha

func (d *Drawing) SetAlpha(alpha float32) *Drawing

SetAlpha multiplies everything drawn after it by alpha.

func (*Drawing) SetComposite

func (d *Drawing) SetComposite(c CompositeOp) *Drawing

SetComposite sets how later drawing mixes with the canvas.

func (*Drawing) SetFillColor

func (d *Drawing) SetFillColor(c Color) *Drawing

func (*Drawing) SetFillGradient

func (d *Drawing) SetFillGradient(g *CanvasGradient) *Drawing

SetFillGradient fills with g until the next SetFillColor.

func (*Drawing) SetLineCap

func (d *Drawing) SetLineCap(c LineCap) *Drawing

func (*Drawing) SetLineDash

func (d *Drawing) SetLineDash(lengths ...float32) *Drawing

SetLineDash dashes strokes with lengths of dash and gap in turn, an odd list repeated to make it even; none is solid.

func (*Drawing) SetLineDashOffset

func (d *Drawing) SetLineDashOffset(offset float32) *Drawing

SetLineDashOffset starts the dashes offset into their pattern.

func (*Drawing) SetLineJoin

func (d *Drawing) SetLineJoin(j LineJoin) *Drawing

func (*Drawing) SetLineWidth

func (d *Drawing) SetLineWidth(w float32) *Drawing

func (*Drawing) SetMiterLimit

func (d *Drawing) SetMiterLimit(limit float32) *Drawing

SetMiterLimit sets how far miter joins reach, in line widths; 10 by default.

func (*Drawing) SetShadow

func (d *Drawing) SetShadow(color Color, dx, dy, blur float32) *Drawing

SetShadow shadows later drawing in color, offset by dx, dy and blurred by blur (twice the Gaussian's deviation), in the canvas's own points whatever the transform. A transparent color draws none.

func (*Drawing) SetStrokeColor

func (d *Drawing) SetStrokeColor(c Color) *Drawing

func (*Drawing) SetStrokeGradient

func (d *Drawing) SetStrokeGradient(g *CanvasGradient) *Drawing

SetStrokeGradient strokes with g until the next SetStrokeColor.

func (*Drawing) SetTextAlign

func (d *Drawing) SetTextAlign(a TextAlign) *Drawing

SetTextAlign sets where later texts sit along the point they are drawn at: start and left put it at their left end, end and right at their right end, center at their middle.

func (*Drawing) SetTextBaseline

func (d *Drawing) SetTextBaseline(b TextBaseline) *Drawing

SetTextBaseline sets which line of later texts the point they are drawn at sits on.

func (*Drawing) SetTransform

func (d *Drawing) SetTransform(a, b, c, dd, e, f float32) *Drawing

SetTransform replaces the transform with that matrix, as the web's setTransform.

func (*Drawing) Stroke

func (d *Drawing) Stroke() *Drawing

func (*Drawing) StrokeContains

func (d *Drawing) StrokeContains(p *Path, x, y float32) bool

StrokeContains reports whether the point is on p's stroke under the current transform and line style.

func (*Drawing) StrokeFromView

func (d *Drawing) StrokeFromView(initial Paint) *Drawing

StrokeFromView strokes with the canvas view's Stroke style, or with initial where no view sets one.

func (*Drawing) StrokePath

func (d *Drawing) StrokePath(p *Path) *Drawing

StrokePath strokes p, leaving the current path as it is.

func (*Drawing) StrokeRect

func (d *Drawing) StrokeRect(x, y, w, h float32) *Drawing

StrokeRect strokes a rectangle, leaving the current path as it is.

func (*Drawing) StrokeText

func (d *Drawing) StrokeText(text string, x, y float32, font Font) *Drawing

StrokeText draws text's outline with the stroke settings, placed as FillText places it.

func (*Drawing) TextMetrics

func (d *Drawing) TextMetrics(text string, font Font) TextMetrics

TextMetrics measures text in font with the platform's text engine, as its first line lays it out; without one it approximates: every character 0.6 of the font size wide, an ascent of 0.8 and a descent of 0.2 of it.

func (*Drawing) Transform

func (d *Drawing) Transform(a, b, c, dd, e, f float32) *Drawing

Transform multiplies the transform by the matrix that maps (x, y) to (a*x + c*y + e, b*x + d*y + f), as the web's transform.

func (*Drawing) Translate

func (d *Drawing) Translate(x, y float32) *Drawing

type EaseMode

type EaseMode uint8

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

const (
	EaseModeIn EaseMode = iota
	EaseModeOut
	EaseModeInOut
)

type Easing

type Easing struct {
	Kind EasingKind
	// Mode turns a curve around; Bézier curves ignore it.
	Mode EaseMode
	// Bezier is EasingBezier's curve.
	Bezier Curve
	// Param is Poly's exponent, Elastic's bounciness and Back's
	// overshoot; 0 takes React Native's default. It is Steps's count.
	Param float64
	// Steps is where EasingSteps jumps, as CSS's steps().
	Steps StepPosition
}

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

func (Easing) At

func (e Easing) At(x float64) float64

At returns the eased progress at time fraction x from 0 to 1.

func (Easing) Reversed

func (e Easing) Reversed() Easing

Reversed returns the easing that runs e backwards in time: its curve mirrored, so x → 1 - e(1 - x).

type EasingKind

type EasingKind uint8

EasingKind is an easing's shape.

const (
	EasingBezier EasingKind = iota
	EasingQuad
	EasingCubic
	EasingPoly
	EasingSin
	EasingCircle
	EasingExp
	EasingElastic
	EasingBack
	EasingBounce
	// EasingSteps jumps through Param equal steps, as CSS's steps().
	EasingSteps
)

type EdgeColors

type EdgeColors struct{ Top, Right, Bottom, Left Color }

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.

func (EdgeColors) Or

func (e EdgeColors) Or(c Color) EdgeColors

Or returns e with its unset sides c.

type EdgeEffect

type EdgeEffect uint8

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

const (
	// EdgeEffectAutomatic is soft under the bars; iOS 26 and later also
	// draw their own under their system bars.
	EdgeEffectAutomatic EdgeEffect = iota
	// EdgeEffectSoft blurs the content under the bars progressively, most
	// at the side, and fades it into the background it scrolls over.
	EdgeEffectSoft
	// EdgeEffectHard frosts the content under the bars evenly, with a
	// hairline along their far edge.
	EdgeEffectHard
	// EdgeEffectHidden draws none, under system bars too.
	EdgeEffectHidden
)

type Edges

type Edges struct{ Top, Right, Bottom, Left Points }

Edges holds a length per side.

func All

func All(p Points) Edges

All returns edges of the same length on every side.

func Symmetric

func Symmetric(vertical, horizontal Points) Edges

Symmetric returns edges with vertical and horizontal lengths.

func (Edges) Horizontal

func (e Edges) Horizontal() Points

Horizontal returns the left and right edges together.

func (Edges) Vertical

func (e Edges) Vertical() Points

Vertical returns the top and bottom edges together.

type Effects

type Effects struct {
	// Shadows are drawn under the box, or inside it over the background
	// when inset; the first on top, as CSS orders them.
	Shadows []BoxShadow
	// Gradients are drawn over the background, under the border, the
	// first on top.
	Gradients []GradientPaint
	// Filters change what the view and its children draw, in order.
	Filters []Filter
	// BackdropFilters change what is behind the view, under its
	// background; platforms draw their blur.
	BackdropFilters []Filter
	// Mask, when set, is drawn as much as its alpha says, backdrop
	// included.
	Mask *GradientPaint
}

Effects are the rarer parts of a view's look. They travel behind a pointer, so ViewStyle stays comparable: the core sends the same pointer while they stay Equal.

func (*Effects) BackdropBlur

func (e *Effects) BackdropBlur() Points

BackdropBlur is the blur radius of the backdrop filters, 0 for none.

func (*Effects) Empty

func (e *Effects) Empty() bool

Empty reports whether e has nothing to draw.

func (*Effects) Equal

func (e *Effects) Equal(o *Effects) bool

Equal reports whether e and o draw the same.

type EllipsizeMode

type EllipsizeMode uint8

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

const (
	// EllipsizeTail ends the last line with an ellipsis: "Lorem ips…".
	// It is the default.
	EllipsizeTail EllipsizeMode = iota + 1
	// EllipsizeHead starts it with one, "…sum dolor", and EllipsizeMiddle
	// puts one in its middle, "Lorem…dolor". Platforms do it on a single
	// line; on several lines some cut only the last one's end.
	EllipsizeHead
	EllipsizeMiddle
	// EllipsizeClip cuts the text without an ellipsis.
	EllipsizeClip
)

type Environment

type Environment struct {
	// Displays are the desktop's displays, in screen coordinates. They are
	// empty on targets without desktop displays.
	Displays []DisplayInfo
	// SafeArea is the part of each edge that system bars, notches and
	// rounded corners cover.
	SafeArea Edges
	// TitleBar is what a hidden desktop title bar still covers: its
	// height on top, its buttons on the left or right.
	TitleBar Edges
	// WindowMaterial is the material behind the window's content; None
	// when the window is opaque.
	WindowMaterial WindowMaterial
	// Maximized is whether the window is maximized or zoomed, so an
	// app-drawn maximize button can show restore.
	Maximized bool
	// FullScreen is whether the window fills its screen in full screen.
	FullScreen bool
	// Minimized is whether the surface's window is minimized, an embedded surface's host window; false without desktop windows and where the compositor reports no minimized state.
	Minimized bool
	// WindowFrame is where the window is and how large, as WindowSetFrame
	// takes them; zero without a window, and a position only where the
	// platform knows one (Move).
	WindowFrame WindowFrame
	// KeyboardHeight is how much of the bottom the software keyboard
	// covers; KeyboardDuration is how long it takes to move.
	KeyboardHeight   Points
	KeyboardDuration time.Duration
	Dark             bool
	// FontScale multiplies text sizes, as the user's text size setting
	// asks; 0 means 1.
	FontScale    float32
	ReduceMotion bool
	ScreenReader bool
	// ScreenColor says ItemPickScreenColor works here.
	ScreenColor bool
	// Speech says ItemSpeech recognizes speech here, Audio that ItemAudio plays sounds and players.
	Speech bool
	Audio  bool
	// Camera says ItemTakePhoto shows a camera here.
	Camera bool
	// CanSendInput says Ref.SendInput can deliver trusted input to web views.
	CanSendInput bool
	// HasWebView says this target provides a web view host.
	HasWebView bool
	// VerticalBarEdge is the edge the system chose for a vertical bar where it may place one, as iOS 27.1 does; Unspecified elsewhere. It is not geometry: Tree.Resize reports that.
	VerticalBarEdge VerticalBarEdge
	// RTL lays the app out right to left.
	RTL bool
	// PixelRatio is device pixels per point; 0 means 1.
	PixelRatio float32
	// Locale is a BCP 47 language tag, such as "en-US".
	Locale string
	// LocaleSettings are how the user reads weeks, times and measures,
	// apart from the language, where the platform says.
	LocaleSettings LocaleSettings
	OS             OS
	// OSVersion is the system's version: major and minor on Apple
	// platforms, Windows and Linux (the kernel's), Android's API level
	// as Major, and zero on the web.
	OSVersion OSVersion
	Idiom     Idiom
	// AppleKeyboard says a browser runs on an Apple platform, where "mod"
	// is Command as on macOS and iOS.
	AppleKeyboard bool
	// HeaderHeight and LargeHeaderHeight are the heights of the system
	// header a platform draws over screens, without the status bar, and
	// with a large title. 0 where screens show their Header instead.
	HeaderHeight, LargeHeaderHeight Points
	// Lifecycle is whether the app is in use: the window's, an embedded
	// surface's the host window's.
	Lifecycle Lifecycle
	// AppClip says the app runs as an iOS App Clip, and OpenedURL is the
	// web link that last opened it: the clip's invocation, or a universal
	// link; "" when none did.
	AppClip   bool
	OpenedURL string
}

Environment is what the platform reports about where the app runs. The surface size is not part of it: Tree.Resize reports that.

func (Environment) Equal

func (e Environment) Equal(other Environment) bool

Equal reports whether two platform environments have the same values. Environment includes a slice of displays, so it cannot use ==.

type Event

type Event struct {
	Kind  EventKind
	ID    NodeID
	Text  string
	Count uint32
	Point Point
	// Page is a pointer's position in the root view, the surface or the
	// modal, and Modifiers the keys held.
	Page      Point
	Modifiers Modifiers
	// Button is the mouse button a mouse event holds down.
	Button MouseButton
	Size   Size
	// Loaded and Total are an image's bytes loaded and expected.
	Loaded, Total int64
	Index         int
	// Phase, Velocity and Value are a gesture's.
	Phase    GesturePhase
	Velocity Point
	Value    float32
	// Navigation is a web view's state.
	Navigation *WebNavigation
	// Origin is the origin of the frame that posted a web view's message, as WebOrigin writes it, URL that frame's URL, and MainFrame whether that frame is the page's top one. A backend that cannot tell a frame's origin delivers the top frame's messages alone.
	Origin    string
	URL       string
	MainFrame bool
	// Time, Duration and Buffering are a video's.
	Time, Duration time.Duration
	Buffering      bool
	// URIs are the file: URLs of dropped files.
	URIs []string
	// Data is what a native component emitted.
	Data any
	// Finished is whether an animation ran to its end, or the platform
	// closed a modal.
	Finished bool
	// Insets are what system UI covers of a modal (EventModalSize).
	Insets Edges
	// Touches are EventTouch's fingers.
	Touches []Touch
	// Values are the values a pan moves as it begins and ends
	// (Animator.Gesture).
	Values Point
	// Delta and Precise are a wheel's (EventWheel).
	Delta   Point
	Precise bool
}

Event is one report from the platform to the engine.

func NoBiometric

func NoBiometric(it *MountItem) Event

NoBiometric is how a platform without biometric authentication answers a biometric request: no kind for availability, unavailable for authentication.

func (Event) Mergeable

func (e Event) Mergeable() bool

Mergeable reports whether a later event of the same kind and view replaces this one before the engine handles it: scrolls, progress and mouse moves and a gesture's moves, never its first or last report.

type EventKind

type EventKind uint8

EventKind is what a platform reports about a view.

const (
	// EventPress is a completed press: tap, click or accessibility action.
	EventPress EventKind = iota + 1
	// EventPressDown and EventPressUp bracket a press as it happens.
	EventPressDown
	EventPressUp
	// EventLongPress is a press held past the platform's delay.
	//
	// The four press events carry the position in the view (Point) and in
	// its root view (Page), the Modifiers held when the press began and
	// the click count (Count), where the platform knows them.
	EventLongPress
	// EventMouseEnter and EventMouseLeave follow a pointer over a view:
	// Point, Page, Modifiers and Button as EventMouseMove's, where the
	// platform knows them.
	EventMouseEnter
	EventMouseLeave
	// EventFocus and EventBlur follow keyboard focus.
	EventFocus
	EventBlur
	// EventChangeText carries a text field's text after a user edit
	// (Text) and the edit's number (Count).
	EventChangeText
	// EventSubmitEditing is Return in a text field (Text).
	EventSubmitEditing
	// EventScroll carries a scroll view's offset (Point), the
	// ItemScrollTo and ItemScrollBy items it applied since it was made
	// (Count) and, when it zooms, its zoom scale (Value).
	EventScroll
	// EventLoadStart, EventProgress (Loaded, Total), EventLoad (Size, the
	// source's pixels), EventError (Text) and EventLoadEnd follow an image
	// view's loading. A web view reports EventLoadStart and EventLoad with
	// its Navigation, and EventError with the URL in Navigation. A video
	// reports EventLoadStart, EventLoad (Duration and Size, in points),
	// EventProgress (Time and Duration) and EventError.
	EventLoadStart
	EventProgress
	EventLoad
	EventError
	EventLoadEnd
	// EventPressOutside is a press starting outside the overlay ID, at
	// Point in surface points.
	EventPressOutside
	// EventBack is Escape, the back button or gesture, or the browser's
	// back; the engine routes it to the topmost overlay, modal or stack.
	// With the ID of a screen it is that screen's header's back button or
	// swipe, which goes to the screen's stack while the screen is on top.
	EventBack
	// EventAlert answers ItemAlert Count with the button at Index, or -1.
	EventAlert
	// EventClipboard answers ItemReadClipboard Count with what it read:
	// the Text, the image in Data (a *ClipboardImage, nil for none), the
	// files' URIs, or whether the clipboard has text or an image
	// (Finished).
	EventClipboard
	// EventContextMenu is a secondary click (right click, control click)
	// on ID at Point in the view's coordinates and Page in its root
	// view's, with the Modifiers held.
	EventContextMenu
	// EventKey is a key press matching a binding of the keymap (Text), Count the keys the view with the keyboard focus used as the platform matched it (KeyUse): the engine runs the newest binding of Text that fires over them (KeyBinding.FiresOver), as FindKey chose.
	EventKey
	// EventPan follows an active pan: its phase (Phase), translation
	// (Point) and velocity (Velocity).
	EventPan
	// EventPinch and EventRotation follow a pinch's scale and a rotation's
	// angle in radians (Value) with their phase (Phase) and velocity
	// (Velocity.X).
	EventPinch
	EventRotation
	// EventMenu is an application menu item chosen (Count, its ID).
	EventMenu
	// EventMessage carries what a web view's page posted (Text), with the Origin and URL of the frame that posted it and whether that frame is the page's top one (MainFrame).
	EventMessage
	// EventNavigationStateChange is a web view's page or history changing
	// (Navigation).
	EventNavigationStateChange
	// EventEnd is a video reaching its end, also when it repeats.
	EventEnd
	// EventBuffer is a video starting or stopping waiting for data
	// (Buffering).
	EventBuffer
	// EventFileDragEnter and EventFileDragLeave follow files dragged over
	// the view that would receive them, and EventFileDrop delivers them
	// (URIs).
	EventFileDragEnter
	EventFileDragLeave
	EventFileDrop
	// EventNative is an event a native view's component emitted: its
	// name (Text) and Data.
	EventNative
	// EventNativeSize is the size a native view's component asks for
	// (Size).
	EventNativeSize
	// EventAnimation reports an animation's end or a value read (Count,
	// the request), with Finished and the value's Value.
	EventAnimation
	// EventScrollDragStart and EventScrollDragEnd bracket the user
	// dragging a scroll view, its content or its scroll bar, and
	// EventMomentumStart and EventMomentumEnd the glide or snap after;
	// each carries the offset (Point), the scrolls applied (Count) and
	// zoom scale (Value) as EventScroll does.
	EventScrollDragStart
	EventScrollDragEnd
	EventMomentumStart
	EventMomentumEnd
	// EventRefresh is the user pulling a refreshable scroll view past
	// its top; the platform shows its spinner until a config says else.
	EventRefresh
	// EventImageInfo answers ItemImageInfo Count with the image's Size in
	// pixels, or the error in Text.
	EventImageInfo
	// EventSelectionChange carries a text field's selection after the
	// user moved it: Index to Count, in UTF-16 units. On a selection area
	// it carries the box of the texts its selection touches, in the area
	// (Point and Size), no Size for no selection.
	EventSelectionChange
	// EventKeyPress is a key typed in a text field (Text: what it enters,
	// "Backspace" or "Enter").
	EventKeyPress
	// EventCompositionChange follows an input method's composition in a
	// text field: the text being composed (Text) as it starts and
	// changes, then its end (Finished), after the EventChangeText of the
	// text it commits.
	EventCompositionChange
	// EventAccessibilityAction is an action assistive technology
	// performed on ID, by name (Text).
	EventAccessibilityAction
	// EventRequestClose asks to close the modal ID for the reason Text
	// ("swipe" for an iOS sheet); Finished says the platform closed it.
	EventRequestClose
	// EventModalSize is the Size and Insets of a modal the platform
	// presents at a size of its own, such as an iOS sheet.
	EventModalSize
	// EventMouseMove is the mouse moving over the view, with or without a
	// button down, or a modifier key changing while it rests there with
	// none down: Point, Page and Modifiers as EventContextMenu's, and
	// Button. Android's runtime numbers it EVENT_HOVER_MOVE.
	EventMouseMove
	// EventDownload reports a download of a web view that asked for them
	// (Data, a *WebDownload).
	EventDownload
	// EventTouch reports the fingers on the surface (Touches, with their
	// PagePosition and Changed) as one goes down (Phase GestureBegan),
	// moves (GestureChanged), lifts (GestureEnded) or the system takes
	// them (GestureCancelled), at Time. Platforms send it while a view's
	// mask has it, with no ID, or with the ID of the view a finger went
	// down on, which then starts its path; a mouse is finger 0.
	EventTouch
	// EventCaretMove is where a focused input's caret is: Point and Size
	// in the input's view.
	EventCaretMove
	// EventPaste is what the user pasted into an input (Data, a
	// *PasteEvent), before the text it inserts is reported.
	EventPaste
	// EventScreenHeader is the height of a screen's system header bar
	// (Value), its large title shown, as the platform measured it; the
	// status bar above it is the core's to add.
	EventScreenHeader
	// EventOpenURL answers ItemOpenURL Count with whether the URL opened
	// (Finished).
	EventOpenURL
	// EventPick answers ItemPickImages or ItemTakePhoto Count with the
	// files picked or the photo taken (Data, a []PickedFile), none when the
	// user cancelled; a photo that failed says why in Text.
	EventPick
	// EventMenuClosed answers ItemPopupMenu Count once its menu closed,
	// after the EventMenu of an item chosen.
	EventMenuClosed
	// EventBackStarted says a back gesture began, before its EventBack or
	// EventBackCancelled: the engine answers with ItemBackPreview and lays
	// the screen it would uncover out under the one it pops.
	EventBackStarted
	// EventBackCancelled says the back gesture EventBackStarted announced
	// was given up.
	EventBackCancelled
	// EventScrollEnd says a scroll view came to rest: a drag that set
	// nothing in motion ended, or a glide, a snap, an animated scroll or
	// the wheel's turns did; with the offset as EventScroll's.
	EventScrollEnd
	// EventWheel is a mouse wheel's turn or a touchpad's scroll over a
	// view at Point, moving the content by Delta, with the Modifiers held.
	// Precise marks a touch surface's, whose gesture reports its Phase;
	// a wheel's turns are GestureChanged. A gesture let go where the
	// platform has no momentum of its own ends with its Velocity.
	EventWheel
	// EventFiles answers ItemPickFiles Count with the files picked (Data,
	// a []File), ItemPickDirectories Count with the folders picked (a
	// []Directory), none when the user cancelled, ItemSaveFile Count
	// with whether the file was saved (Finished) and, on desktops, the
	// path it was saved at (a string), ItemOpenFile Count with
	// whether an app opened the file, ItemShare Count with whether the
	// share sheet showed, ItemInstallPackage Count with whether the
	// installer started, ItemCanInstallPackages Count with whether the
	// app may install packages and ItemInstallSettings Count with whether
	// the setting opened (all Finished); Text is what failed.
	EventFiles
	// EventModalShown and EventModalDismissed report that the platform
	// finished presenting modal ID and taking it away, where it says so.
	EventModalShown
	EventModalDismissed
	// EventScreenInsets reports what covers screen ID's content (Insets):
	// its header and the system's bars, where the platform measures them.
	EventScreenInsets
	// EventWindowClose reports that the user asked to close the surface's
	// window; the core closes it unless the app keeps it.
	EventWindowClose
	// EventWindowHidden reports that the platform hid the surface's
	// window, as a panel hides when it loses the focus.
	EventWindowHidden
	// EventReopen reports that the user opened the app again while it
	// ran: from the Dock, or by launching it a second time.
	EventReopen
	// EventOpenFiles reports files the system asks the app to open (Data,
	// a []string of paths): from the Finder, or named when it launched.
	EventOpenFiles
	// EventTray reports a click on tray icon Count: Index 0 for the
	// primary button, 1 for the secondary.
	EventTray
	// EventHotKey reports the global shortcut whose ID is Count.
	EventHotKey
	// EventLaunchAtLogin answers ItemLaunchAtLogin Count with whether the
	// system starts the app at login (Finished).
	EventLaunchAtLogin
	// EventSpeech reports speech session Count (Data, a *SpeechEvent).
	EventSpeech
	// EventUpdate answers ItemCheckForUpdates Count: Finished when the
	// platform's own updater showed what it found, else Data, an *Update.
	EventUpdate
	// EventInputModality reports what the user gave the surface input
	// with last (Count, ModalityKeyboard or ModalityPointer), before the
	// focus moves it causes: the core shows the focus (focus-visible:) by
	// it.
	EventInputModality
	// EventNotification answers ItemNotificationPermission and
	// ItemShowNotification Count.
	EventNotification
	// EventNotificationPress reports that the user pressed the
	// notification whose ID is Text, the one that started the app
	// included.
	EventNotificationPress
	// EventBiometric answers an ItemBiometricAvailability or
	// ItemBiometricAuthenticate request: Index is a kind or result.
	EventBiometric
	// EventQuitRequest asks the app whether a quit the user asked for may proceed, after the kinds Android's Protocol.java mirrors so that they keep their values. Count identifies the request; the app answers with ItemQuitResponse. It is sent for user-initiated app termination, not Scope.Quit.
	EventQuitRequest
	// EventOverlayPermission answers ItemOverlayPermission Count with the permission as Index.
	EventOverlayPermission
	// EventWindowEnded reports that the platform ended the surface's window itself, for the reason Index (OverlayEndDenied, ...), as Android ends an overlay it refuses or removes: the core closes it, and OnClosing has no say.
	EventWindowEnded
	// EventPermission answers ItemPermission Count, after the kinds Android's Protocol.java mirrors: Index is the permission's status (PermissionNotAsked, ...), and Finished says whether PermissionOpenSettings opened the settings.
	EventPermission
	// EventAudio reports sound or player Count (Data, an *AudioEvent).
	EventAudio
	// EventWindowPlacementFailed reports that a panel could not be placed at the requested screen rectangle. Text explains the platform reason. It is appended so Android's wire event numbers stay compatible.
	EventWindowPlacementFailed
	// EventHotKeyState answers global shortcut Count of the latest ItemHotKeys with its registration state, a HotKeyState, in Index, after the kinds Android's Protocol.java mirrors so that they keep their values.
	EventHotKeyState
)

type EventMask

type EventMask uint64

EventMask is a set of event kinds.

func (EventMask) Has

func (m EventMask) Has(k EventKind) bool

Has reports whether m holds k.

type Extrapolate

type Extrapolate uint8

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

const (
	// ExtrapolateClamp keeps the first or last output.
	ExtrapolateClamp Extrapolate = iota + 1
	// ExtrapolateExtend continues the first or last segment.
	ExtrapolateExtend
	// ExtrapolateIdentity returns the input unchanged.
	ExtrapolateIdentity
)

type Family

type Family struct {
	Kind FamilyKind
	Name string
}

Family is a family of a fontFamily list.

func FontFamilies

func FontFamilies(value string) []Family

FontFamilies reads a fontFamily value, most preferred first, as CSS lists families: names separated by commas, each trimmed and unquoted (`Inter, "Noto Sans SC", sans-serif`). A quoted name runs to its closing quote, commas and all, and is always a family's name. Text is set in the first family a platform has, and a character that family lacks in the next that has it.

type FamilyKind

type FamilyKind uint8

FamilyKind is what a family of a fontFamily list names.

const (
	// FamilyNamed is a family installed or registered by the app.
	FamilyNamed FamilyKind = iota
	// FamilySystem is the system font: system-ui, sans-serif and their
	// kind.
	FamilySystem
	FamilySerif
	FamilyMonospace
	// FamilyRounded is the system's rounded font, where it has one.
	FamilyRounded
)

type File

type File struct {
	// Name is its name as the user saw it.
	Name string
	// MIME is its media type, application/octet-stream when nothing says.
	MIME string
	Size int64
	// Modified is when it last changed, zero when the platform does not
	// say.
	Modified time.Time
	// Path is where it is on disk, "" on the web, where Opener reads it.
	Path string
	// Temporary says Path is a copy the platform made in the app's own
	// storage, as iOS and Android do, which the app deletes once it is
	// done with it; elsewhere Path is the user's file.
	Temporary bool
	// Opener opens a file that has no Path.
	Opener func() (io.ReadCloser, error)
}

File is a file the user picked.

func FinishFiles

func FinishFiles(r FilesRequest, files []File) []File

FinishFiles returns files as the app gets them: at most r.Limit, each with a name, a type and, for one on disk, its size and modification time.

func (File) Open

func (f File) Open() (io.ReadCloser, error)

Open opens the file for reading.

type FilesRequest

type FilesRequest struct {
	// Limit is the most files the user picks: 1 for a single pick, at
	// most MaxPicked.
	Limit int
	// Title is the dialog's title or message where the target has one.
	Title string
	// Button is the dialog's accept button label where the target has one.
	Button string
	// TypesName names Types in the filter menu where the target has one.
	TypesName string
	// Start is the folder the dialog opens in when it exists.
	Start string
	// Types are the files offered: lower-case media types
	// (application/pdf), families (image/*) and extensions (.zip). None
	// offers every file.
	Types []string
}

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

func (FilesRequest) Extensions

func (r FilesRequest) Extensions() (exts []string, any bool)

Extensions returns r's types as extensions without dots, for dialogs that filter only by them: a media type becomes the extensions of its files, and any reports that one has none, so the dialog must offer every file.

func (FilesRequest) MIMETypes

func (r FilesRequest) MIMETypes() (types []string, any bool)

MIMETypes returns r's types as media types, for pickers that filter only by them: an extension becomes its type, and any reports that one has none, so the picker must offer every file.

type FillRule

type FillRule uint8

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

const (
	NonZero FillRule = iota
	EvenOdd
)

type Filter

type Filter struct {
	Kind FilterKind
	// Amount is the function's argument: the blur's radius in points,
	// hue rotation's degrees, opacity's alpha, otherwise a factor, where
	// 1 leaves brightness, contrast and saturation as they are and gives
	// the full effect of grayscale, invert and sepia.
	Amount float32
	// Shadow is a drop shadow's offset, blur and color.
	Shadow BoxShadow
}

Filter is one of CSS's filter functions. Filters apply in order; the constructors in core make them.

func (Filter) Matrix

func (f Filter) Matrix() (ColorMatrix, bool)

Matrix returns the color matrix of a color filter, as CSS's Filter Effects define them, and false for a blur or a drop shadow.

type FilterKind

type FilterKind uint8

FilterKind is which filter function a Filter is.

const (
	FilterBlur FilterKind = iota + 1
	FilterBrightness
	FilterContrast
	FilterGrayscale
	FilterHueRotate
	FilterInvert
	FilterOpacity
	FilterSaturate
	FilterSepia
	// FilterDropShadow draws a shadow of what the view draws, in its
	// shape rather than its box's.
	FilterDropShadow
)

type FolderEntry

type FolderEntry struct {
	Name     string
	Dir      bool
	Size     int64
	Modified time.Time
	// Handle is what the platform reads it by: a document's ID on
	// Android, a handle on the web.
	Handle any
}

FolderEntry is a file or folder a folder holds, as its platform lists it.

type FolderSource

type FolderSource interface {
	// List lists the folder e at name.
	List(name string, e FolderEntry) ([]FolderEntry, error)
	// Open opens the file e at name.
	Open(name string, e FolderEntry) (io.ReadSeekCloser, error)
}

FolderSource is how a platform reads a folder without a path. Names are slash-separated inside the folder, "." for itself.

type Font

type Font struct {
	// Family is a font family name; empty is the system font, and
	// FontMonospace the platform's fixed-pitch font.
	Family string
	Size   Points
	Weight FontWeight
	Italic bool
	// Variant turns on OpenType features: small capitals and the forms
	// and widths of figures.
	Variant FontVariant
}

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

type FontExtent

type FontExtent struct {
	// Ascent and Descent reach above and below the baseline; both are
	// positive.
	Ascent, Descent Points
	XHeight         Points
}

FontExtent is the vertical metrics of the font around an attachment: its placeholder's.

type FontRegistrar

type FontRegistrar interface {
	RegisterFont(data []byte) error
}

FontRegistrar is a TextEngine that registers fonts as the app runs, as a TSX module's imports do: RegisterFont makes the families of the font file data (TrueType, OpenType or a collection) available to the text it prepares from then on. A platform that loads a font later tells the engine (FontsChanged), which prepares its text again.

type FontVariant

type FontVariant uint8

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

const (
	// FontVariantNormal is a variant that turns no feature on: a style
	// sets it to undo an inherited variant. Engines ignore it.
	FontVariantNormal FontVariant = 1 << iota
	// FontSmallCaps draws lowercase letters as small capitals (smcp).
	FontSmallCaps
	// FontOldstyleNums draws figures that rise and fall as lowercase
	// letters do (onum); FontLiningNums draws them at the capitals'
	// height (lnum).
	FontOldstyleNums
	FontLiningNums
	// FontTabularNums gives every figure the same width (tnum), so a
	// changing value keeps its place; FontProportionalNums gives each its
	// own (pnum).
	FontTabularNums
	FontProportionalNums
)

func (FontVariant) Tags

func (v FontVariant) Tags() []string

Tags returns the OpenType tags of the features v turns on.

type FontWeight

type FontWeight uint16

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

const (
	FontWeightLight    FontWeight = 300
	FontWeightNormal   FontWeight = 400
	FontWeightMedium   FontWeight = 500
	FontWeightSemibold FontWeight = 600
	FontWeightBold     FontWeight = 700
)

type Geometry

type Geometry struct {
	// Regions are the usable regions, ordered by frame position: top to bottom, then left to right.
	Regions []Region
	// Obstructions are the folds and hinges on the surface, in the same order.
	Obstructions []Obstruction
}

Geometry is how a surface's display divides it: the regions an app can lay out in and the folds and hinges between them, in surface points, measured at the size it travels with (Engine.Resize, Tree.Resize). The zero value is the one-region form of a surface without a fold, which Divide returns for no obstructions.

func Divide

func Divide(size Size, obstructions []Obstruction) Geometry

Divide returns the geometry of a surface of size that obstructions lie on, in surface points: the obstructions within the surface, clipped to it, and the regions those that separate it and cross it from edge to edge leave on either side of their frames. An obstruction that does not divide the surface, such as one that occludes without separating, reserves its frame in the regions it lies in. Frames outside the surface, and those without length, are left out.

func (Geometry) Clone

func (g Geometry) Clone() Geometry

Clone returns g with lists of its own.

func (Geometry) Equal

func (g Geometry) Equal(o Geometry) bool

Equal reports whether two geometries have the same regions and obstructions, an empty list the same as none.

type GesturePhase

type GesturePhase uint8

GesturePhase is where a gesture is in its course.

const (
	// GestureBegan is the first report, once the platform recognized it.
	GestureBegan GesturePhase = iota + 1
	// GestureChanged follows each move.
	GestureChanged
	// GestureEnded is the last report of a gesture that completed.
	GestureEnded
	// GestureCancelled is the last report of one the system took away,
	// such as by a scroll view or an incoming call.
	GestureCancelled
)

type GlassEffect

type GlassEffect uint8

GlassEffect is Apple's Liquid Glass, drawn in place of the backdrop blur where the system has it (iOS and macOS 26).

const (
	GlassNone GlassEffect = iota
	GlassRegular
	GlassClear
)

type Gradient

type Gradient struct {
	Kind GradientKind
	// Angle points a linear gradient, in degrees clockwise from up, as
	// CSS's angles: 90 runs left to right, 180 top to bottom. ToCorner,
	// when set, points it at a corner instead, along the angle that
	// depends on the box's shape. A conic gradient starts at Angle.
	Angle    float32
	ToCorner GradientCorner
	// Circle makes a radial gradient a circle rather than an ellipse of
	// the box's proportions; Extent is how far it reaches.
	Circle bool
	Extent GradientExtent
	// Center is where radial and conic gradients start; its zero value is
	// the box's center, and its percentages are of the box's size.
	Center ObjectPosition
	// Stops are the colors, at least one, in order.
	Stops []ColorStop
	// Repeating repeats the stops past the last, as repeating-*-gradient().
	Repeating bool
	// Space is where colors mix between stops.
	Space ColorSpace
}

Gradient is a gradient image, as CSS's linear-gradient(), radial-gradient() and conic-gradient() and their repeating forms. A view draws its Gradients over its Background, the first on top.

func (*Gradient) Paint

func (g *Gradient) Paint(size Size) (GradientPaint, bool)

Paint resolves g against a box of size: what platforms draw. It reports false when g has no stops.

type GradientCorner

type GradientCorner uint8

GradientCorner points a linear gradient at a corner: CSS's "to top right".

const (
	ToTopLeft GradientCorner = iota + 1
	ToTopRight
	ToBottomRight
	ToBottomLeft
)

type GradientExtent

type GradientExtent uint8

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

const (
	// ExtentFarthestCorner, the zero value, reaches the farthest corner,
	// as CSS's default.
	ExtentFarthestCorner GradientExtent = iota
	ExtentClosestSide
	ExtentClosestCorner
	ExtentFarthestSide
)

type GradientKind

type GradientKind uint8

GradientKind is a gradient's geometry.

const (
	// GradientLinear runs along a line through the box's center.
	GradientLinear GradientKind = iota
	// GradientRadial spreads out from Center to its Extent.
	GradientRadial
	// GradientConic turns around Center, the stops at fractions of a turn.
	GradientConic
)

type GradientPaint

type GradientPaint struct {
	Kind GradientKind
	// X0, Y0 to X1, Y1 is a linear gradient's line, from its first stop to
	// its last.
	X0, Y0, X1, Y1 float32
	// CX, CY is the center of radial and conic gradients; RX and RY are a
	// radial gradient's radii, where its last stop is.
	CX, CY, RX, RY float32
	// Angle is where a conic gradient's first stop is, in degrees
	// clockwise from up.
	Angle float32
	Stops []GradientStop
}

GradientPaint is a gradient resolved against a box, what platforms draw. Its geometry is in fractions of the box's width and height, so it stretches with the box, and its stops run from 0 to 1, sorted, repeats laid out and mixed so that platforms can blend each pair of stops channel by channel in sRGB, unpremultiplied, and pad past the ends.

func (*GradientPaint) ColorAt

func (p *GradientPaint) ColorAt(t float32) Color

ColorAt returns the gradient's color at fraction t of its line, as platforms blend it: for those that draw a gradient pixel by pixel.

func (*GradientPaint) Equal

func (p *GradientPaint) Equal(o *GradientPaint) bool

Equal reports whether two paints draw the same.

type GradientSpread

type GradientSpread uint8

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

const (
	SpreadPad     GradientSpread = iota // the end colors continue
	SpreadReflect                       // the gradient repeats, mirrored
	SpreadRepeat                        // the gradient repeats
)

type GradientStop

type GradientStop struct {
	Offset float32
	Color  Color
}

GradientStop is a color at an offset of a gradient.

type Granularity

type Granularity uint8

Granularity is what a press, drag or extension selects by.

const (
	// ByCharacter is a press and drag.
	ByCharacter Granularity = iota
	// ByWord is a double click or a long press, then drags by words.
	ByWord
	// ByParagraph is a triple click: a whole text.
	ByParagraph
)

type Haptic

type Haptic = uint32

Haptic is what ItemHaptic plays, as core.Haptic.

const (
	HapticSelection Haptic = iota + 1
	HapticLight
	HapticMedium
	HapticHeavy
	HapticSoft
	HapticRigid
	HapticSuccess
	HapticWarning
	HapticError
)

The haptics, as core's.

type HeaderSystemItem

type HeaderSystemItem uint8

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

const (
	HeaderItemAdd HeaderSystemItem = iota + 1
	HeaderItemDone
	HeaderItemClose
	HeaderItemEdit
	HeaderItemCompose
	HeaderItemSearch
	HeaderItemShare
	HeaderItemTrash
	HeaderItemSave
	HeaderItemCancel
)

type HingeState

type HingeState uint8

HingeState is how far a fold or hinge is open.

const (
	HingeUnknown HingeState = iota
	HingeClosed
	HingeHalfOpen
	// HingeOpen is open as far as the device goes, which Android calls flat.
	HingeOpen
)

type HotKeyState

type HotKeyState uint8

HotKeyState is the platform's answer to a global shortcut registration.

const (
	// HotKeyPending says the platform has not answered the latest registration.
	HotKeyPending HotKeyState = iota
	// HotKeyRegistered says the shortcut is active.
	HotKeyRegistered
	// HotKeyTaken says another registration owns the combination.
	HotKeyTaken
	// HotKeyUnsupported says the key or the current session cannot provide a global shortcut.
	HotKeyUnsupported
)

func (HotKeyState) String

func (s HotKeyState) String() string

type Idiom

type Idiom uint8

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

const (
	IdiomPhone Idiom = iota
	IdiomTablet
	// IdiomDesktop is a desktop window, or a browser with a mouse and a
	// wide page.
	IdiomDesktop
	// IdiomMac is an iPhone or iPad app running on a Mac.
	IdiomMac
	// IdiomTV is a television, such as Android TV.
	IdiomTV
	// IdiomWatch is a watch: Apple Watch.
	IdiomWatch
)

type ImageConfig

type ImageConfig struct {
	Source       ImageSource
	Placeholder  ImageSource
	ResizeMode   ResizeMode
	BlurRadius   Points
	FadeDuration time.Duration
	// Position is the style's ObjectPosition: where the fitted image sits
	// (ResizeMode.Fit). It travels with the image, not the ViewStyle.
	Position ObjectPosition
}

ImageConfig is an image view's source and look.

func (ImageConfig) Same

func (a ImageConfig) Same(b ImageConfig) bool

Same reports whether a and b show the same image the same way.

type ImageScales

type ImageScales uint8

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

func (ImageScales) Pick

func (set ImageScales) Pick(ratio float32) float32

Pick returns the scale to load at ratio, as React Native picks: the smallest at least the ratio, else the largest; 0 for an empty set.

type ImageSource

type ImageSource struct {
	URI  string
	Data []byte
	// Size is the image's size in points, when known up front.
	Size Size
	// Scales are the pixel densities an "asset:" image ships in (a.png,
	// a@2x.png, ...): the core mounts the one for the screen's pixel
	// ratio. Empty for a single file.
	Scales ImageScales
	// Variants, for a source whose variants are not asset: files (a TSX
	// bundle's data: URLs), are the URIs of the scales past 1x by scale.
	Variants map[float32]string
}

ImageSource is where an image comes from: a URI (https, file path, file:, data:) or bytes, such as a file embedded with go:embed.

func (ImageSource) Density

func (s ImageSource) Density() float32

Density returns the pixels a point of the image s names has: the density an "asset:" file's name gives (a@2x.png is 2), else 1.

func (ImageSource) Key

func (s ImageSource) Key() string

Key returns a string naming the image s loads, for caches: its URI, or where its bytes are.

func (ImageSource) Same

func (s ImageSource) Same(o ImageSource) bool

Same reports whether s and o load the same image: inline data must be the same bytes, not equal ones.

type InputConfig

type InputConfig struct {
	Style        TextStyle
	Placeholder  string
	Masked       bool
	Readonly     bool
	Disabled     bool
	KeyboardType KeyboardType
	// Content is where the text goes in the view: inside padding and border.
	Content Bounds
	// Accessory is the InputAccessoryView that rides above the keyboard
	// while the field has focus, or 0; AccessoryID is the ID the field
	// names it by, which tests read.
	Accessory   NodeID
	AccessoryID string
	// Multiline takes several lines in a multi-line control.
	Multiline bool
	// MaxLength caps what the user enters, in UTF-16 units; 0 sets none.
	MaxLength int
	// SubmitBehavior is as set; platforms read Submit.
	SubmitBehavior SubmitBehavior
	ReturnKey      ReturnKeyType
	AutoCapitalize AutoCapitalize
	NoAutoCorrect  bool
	AutoComplete   AutoComplete
	// KeyboardAppearance is iOS's.
	KeyboardAppearance KeyboardAppearance
	// PlaceholderColor is 0 for the platform's: the text color at half
	// strength where the platform styles placeholders itself.
	PlaceholderColor Color
	// SelectionColor colors the selection and CaretColor the caret, which
	// takes SelectionColor without one; 0 is the platform's.
	SelectionColor Color
	CaretColor     Color
	// AccentColor is the accent of the input's theme, for what the
	// platform draws around it, such as an input method's candidates.
	AccentColor Color
	HideCaret   bool
	// PasteBehavior says whether a paste inserts its text.
	PasteBehavior PasteBehavior
}

InputConfig is a text field's look and behavior.

func (*InputConfig) Caret

func (c *InputConfig) Caret() Color

Caret is the color of the caret: CaretColor, or else SelectionColor.

func (*InputConfig) Highlight

func (c *InputConfig) Highlight() Color

Highlight is what selected text shows on: SelectionColor, at 30% when it is opaque, as a translucent one already says its strength; 0 is the platform's.

func (*InputConfig) Submit

func (c *InputConfig) Submit() SubmitBehavior

Submit is what Return does, as SubmitBehavior and Multiline say together, as NSH's InputConfig::submit: never SubmitBehaviorDefault, and SubmitBehaviorNewline only when multiline. Platforms read only this. A multiline field that submits still takes a line break from Shift, Option or Alt with Return on hardware keyboards, and a Return that commits an input method's composition never submits.

type Interpolation

type Interpolation struct {
	// Input is increasing; Output (numbers) or Colors has one entry for
	// each.
	Input  []float64
	Output []float64
	Colors []Color
	// ExtrapolateLeft and ExtrapolateRight say what happens outside
	// Input; Extrapolate sets both.
	Extrapolate, ExtrapolateLeft, ExtrapolateRight Extrapolate
	// Easing curves each segment.
	Easing Easing
}

Interpolation maps a node through piecewise-linear ranges.

func (*Interpolation) At

func (r *Interpolation) At(x float64) (float64, Color)

At maps x through the interpolation: a number, and a color when it has Colors.

type ItemKind

type ItemKind uint8

ItemKind is what a mount item does.

const (
	// ItemCreate makes a detached view of Kind for ID.
	ItemCreate ItemKind = iota + 1
	// ItemInsert inserts or moves ID into Parent, below sibling Before
	// (on top when 0). Siblings rather than indices, so views a platform
	// adds of its own cannot shift positions.
	ItemInsert
	// ItemRemove detaches ID from its parent and keeps it.
	ItemRemove
	// ItemDelete detaches and destroys ID; its ID may be created again
	// later in the same batch.
	ItemDelete
	// ItemFrame moves and sizes ID relative to its parent (Frame).
	ItemFrame
	// ItemViewStyle sets what any view draws (ViewStyle).
	ItemViewStyle
	// ItemText sets a text view's content (Text).
	ItemText
	// ItemInput configures a text field (Input).
	ItemInput
	// ItemInputValue sets a text field's value (Value) unless the user
	// edited it after the edit numbered Count.
	ItemInputValue
	// ItemEvents sets which events the view reports (Events).
	ItemEvents
	// ItemViewProps sets accessibility and identity (ViewProps).
	ItemViewProps
	// ItemScrollConfig configures a scroll view (Scroll).
	ItemScrollConfig
	// ItemScrollContent sets the size of a scroll view's content (Size).
	ItemScrollContent
	// ItemFocus moves keyboard focus to ID.
	ItemFocus
	// ItemBlur takes keyboard focus away from ID.
	ItemBlur
	// ItemImage sets an image view's source and look (Image).
	ItemImage
	// ItemModal configures a modal (Modal).
	ItemModal
	// ItemAlert shows a native alert (Alert); the platform answers with
	// EventAlert.
	ItemAlert
	// ItemDismissKeyboard takes focus away from the focused text field.
	ItemDismissKeyboard
	// ItemScrollTo scrolls ID to Point (its content's offset, UIKit's
	// contentOffset: ContentInset makes it negative at the start),
	// animated when Animated; the platform clamps it and reports
	// EventScroll. Platforms count the ItemScrollTo and ItemScrollBy
	// items they applied to each scroll view and report the count with
	// its offsets.
	ItemScrollTo
	// ItemCanvas replaces a canvas's drawing (Drawing), in the view's
	// coordinates.
	ItemCanvas
	// ItemSetClipboard puts Value on the clipboard.
	ItemSetClipboard
	// ItemReadClipboard asks for what Clipboard names; the platform
	// answers with EventClipboard carrying Count.
	ItemReadClipboard
	// ItemAnnounce has the screen reader say Value.
	ItemAnnounce
	// ItemInputSource selects the keyboard input source named Value, or
	// with none goes back to the one it replaced, where the platform lets
	// an app.
	ItemInputSource
	// ItemKeymap replaces the surface's keyboard shortcuts (Keys); the
	// platform consumes matching key presses and reports EventKey.
	ItemKeymap
	// ItemStatusBar sets the status bar (StatusBar): the layers of
	// settings merged.
	ItemStatusBar
	// ItemTitle sets the window's or page's title (Value).
	ItemTitle
	// ItemBackUnhandled says nothing took the last EventBack: Android
	// leaves the app, as its back button does; others ignore it.
	ItemBackUnhandled
	// ItemWindow asks the desktop window to change (Window); platforms
	// without one ignore it.
	ItemWindow
	// ItemMenu replaces the application menu (Menu; nil restores the
	// platform's); a chosen item is reported with EventMenu.
	ItemMenu
	// ItemWeb configures a web view (Web).
	ItemWeb
	// ItemWebCommand has a web view do WebCommand, with Value for the
	// message or script.
	ItemWebCommand
	// ItemVideo configures a video (Video).
	ItemVideo
	// ItemVideoSeek jumps a video to Time.
	ItemVideoSeek
	// ItemNative names a native view's component and sets its changed
	// props (Native).
	ItemNative
	// ItemNativeCommand has a native view's component run the command
	// Value with Data.
	ItemNativeCommand
	// ItemAnimation changes the native animation graph (Animation), after
	// the batch's views exist.
	ItemAnimation
	// ItemZoomTo zooms a zoomable scroll view (Zoom), animated when
	// Animated; the platform clamps it and reports EventScroll.
	ItemZoomTo
	// ItemImageInfo loads Image's Source, keeping its bytes for the views
	// that show it next; the platform answers with EventImageInfo carrying
	// Count.
	ItemImageInfo
	// ItemSelection selects Selection in text field ID, after the batch's
	// value; the platform clamps it to the text.
	ItemSelection
	// ItemScrollBy moves scroll view ID's offset by Point without
	// clamping it, carrying a drag or glide in flight along, so the
	// visible content stays in place as rows above it change size.
	ItemScrollBy
	// ItemStickyCells replaces the sticky cells of scroll view ID
	// (Sticky): on every scroll the platform moves each along the main
	// axis by clamp(offset - Start, 0, End - Start) from its frame.
	ItemStickyCells
	// ItemAccessibilityLabel changes the label (Value) of a view whose
	// ViewProps were sent before, and nothing else: a label following app
	// state changes alone, so the rest is not sent again.
	ItemAccessibilityLabel
	// ItemAccessibilityFocus moves the screen reader's focus to ID.
	ItemAccessibilityFocus
	// ItemScreen configures a screen's system header (Screen) on the
	// platforms that report header heights, before the screen is
	// inserted and when it changes.
	ItemScreen
	// ItemOverflow gives the area ID's children cover outside its bounds
	// (Frame, in its own coordinates), or zero Bounds when they stay
	// inside, for platforms to look for a touch's target there; see
	// Reach. Sent only when it changes.
	ItemOverflow
	// ItemBlockNative stops the scroll views around ID, the touch
	// responder, from taking the touches until they end, or lets them
	// again with no ID.
	ItemBlockNative
	// ItemShader sets a shader view's program and uniforms (Shader), or a
	// view's effect, transition or screen shader (Shader.Role), nil
	// Shader taking it away.
	ItemShader
	// ItemSetClipboardImage puts the encoded image Data ([]byte) on the
	// clipboard.
	ItemSetClipboardImage
	// ItemOpenURL opens Value outside the app; the platform answers with
	// EventOpenURL carrying Count.
	ItemOpenURL
	// ItemPickImages shows the system's photo picker for Pick; the
	// platform answers with EventPick carrying Count.
	ItemPickImages
	// ItemAppearance shows the app in Appearance whatever the system's,
	// native chrome included.
	ItemAppearance
	// ItemPopupMenu shows Menu as the platform's context menu at Point,
	// in the root's points; desktops report a chosen item with EventMenu
	// and answer with EventMenuClosed carrying Count.
	ItemPopupMenu
	// ItemQuit ends the app: desktops close the window and return from
	// Run, Android finishes its activity; iOS and the web ignore it. On
	// says the app restarts, which nsgo.Run does once Run returns.
	ItemQuit
	// ItemBackPreview answers EventBackStarted with the screen a back now
	// pops (ID), for the platform to move it with the gesture; 0 when back
	// goes elsewhere first or nothing pops.
	ItemBackPreview
	// ItemHistory is how many entries back can go through (Count): the
	// screens above each stack's first and the modals shown. The web
	// keeps that many browser history entries; others ignore it.
	ItemHistory
	// ItemPickFiles shows the system's file picker for Files; the
	// platform answers with EventFiles carrying Count.
	ItemPickFiles
	// ItemSaveFile shows the system's save dialog for Save and saves the
	// file where the user chose; the platform answers with EventFiles
	// carrying Count.
	ItemSaveFile
	// ItemDirection says whether the app lays out right to left (RTL), as
	// the language it shows is written, whatever the system's, and that
	// language (Language), and whether the app forces it (Forced,
	// Scope.SetLocale): on its first commit and when any changes.
	// Platforms whose own motion follows a direction, as iOS's navigation,
	// take it, those that draw menus label them in the language, and Apple
	// platforms keep a forced one for what the system says in later
	// launches.
	ItemDirection
	// ItemPickScreenColor lets the user pick a color on the screen: the
	// system's color sampler or the browser's EyeDropper, answered with
	// EventFiles Count, Finished with the color in Data, a Color. Sent only
	// where the environment says ScreenColor.
	ItemPickScreenColor
	// ItemPickDirectories shows the system's folder picker for
	// Directories; the platform answers with EventFiles carrying Count.
	ItemPickDirectories
	// ItemOpenFile opens the file Open in the app the system associates
	// with it; the platform answers with EventFiles carrying Count.
	ItemOpenFile
	// ItemShare shows the system's share sheet for Share; the platform
	// answers with EventFiles carrying Count once it shows.
	ItemShare
	// ItemInstallPackage hands the APK Open to Android's package
	// installer, which asks the user to confirm; the platform answers
	// with EventFiles carrying Count once the installer starts.
	ItemInstallPackage
	// ItemCanInstallPackages asks whether the user lets the app install
	// packages; Android answers with EventFiles carrying Count.
	ItemCanInstallPackages
	// ItemInstallSettings opens the system's setting that lets the app
	// install packages; Android answers with EventFiles carrying Count.
	ItemInstallSettings
	// ItemOpenSurface opens a window, a panel or a tray icon's view
	// (Surface) for the tree the core numbered Surface.ID, which the
	// platform attaches to the engine (engine.Engine.Attach). Only the
	// app's own surface, the first, is sent it.
	ItemOpenSurface
	// ItemTray adds, changes or removes a tray icon (Tray); the app's own
	// surface is sent it, and EventTray reports its clicks.
	ItemTray
	// ItemTrayMenu shows Menu at the place of tray icon Tray.ID, numbered
	// Count as ItemPopupMenu's menus are.
	ItemTrayMenu
	// ItemHotKeys replaces the app's global shortcuts (Keys, each with its ID), which fire whichever app has the focus with EventHotKey. The platform answers each key with EventHotKeyState once it knows whether the key registered.
	ItemHotKeys
	// ItemDock shows the app in the Dock and the app switcher (On), or
	// leaves it to its tray icon and windows.
	ItemDock
	// ItemSetLaunchAtLogin has the system start the app as the user logs
	// in (On), or no more.
	ItemSetLaunchAtLogin
	// ItemLaunchAtLogin asks whether the system starts the app at login;
	// the platform answers with EventLaunchAtLogin carrying Count.
	ItemLaunchAtLogin
	// ItemShaderTransition starts view ID's shader transition, or a
	// page's or a dialog's (ShaderTransition, ShaderNav): it comes first in
	// its batch, so the platform pictures what the view shows before the
	// batch as the transition's first side.
	ItemShaderTransition
	// ItemShaderInput says what view ID's shader pictures changed in the
	// batch, so the platform pictures it again once the batch is applied:
	// an effect's or a transition's children, a screen shader's surface.
	ItemShaderInput
	// ItemSpeech starts, stops or aborts speech session Count (Speech);
	// the platform reports it with EventSpeech carrying Count.
	ItemSpeech
	// ItemTakePhoto shows the system's camera to take one photo, prepared
	// as Pick says; the platform answers with EventPick carrying Count,
	// Text saying what failed. Sent only where the environment says
	// Camera.
	ItemTakePhoto
	// ItemMatch has view ID, which the batch creates and inserts, move and
	// resize from the frame view Before shows, which the batch deletes,
	// on the batch's LayoutAnimation Update instead of appearing with its
	// Create; Before stops showing at once (View.MatchID). It comes after
	// the round's inserts and before its deletes, so both views are in
	// place, and only in a batch whose LayoutAnimation has an Update.
	ItemMatch
	// ItemCheckForUpdates asks the platform's updater for a newer version
	// of the app, in the background when On; the platform answers with
	// EventUpdate carrying Count.
	ItemCheckForUpdates
	// ItemHaptic plays haptic feedback Count (a Haptic) where the device
	// has it and the user allows it.
	ItemHaptic
	// ItemNotificationPermission asks whether the app may show
	// notifications, with the system's prompt when On; the platform
	// answers with EventNotification carrying Count and the permission as
	// Index (a NotificationPermission).
	ItemNotificationPermission
	// ItemShowNotification shows Notification, replacing one of its ID;
	// the platform answers with EventNotification carrying Count, Finished
	// when the system took it.
	ItemShowNotification
	// ItemCloseNotification removes the notification whose ID is Value, and every notification ShowNotification showed when Value is empty (core.Scope.CloseNotifications).
	ItemCloseNotification
	// ItemBadge shows Count on the app's icon; 0 clears it.
	ItemBadge
	// ItemBiometricAvailability asks whether an enrolled biometric can be
	// used; the platform answers with EventBiometric and its kind in Index.
	ItemBiometricAvailability
	// ItemBiometricAuthenticate asks the user to authenticate with the
	// reason in Value; the platform answers with EventBiometric and its
	// result in Index.
	ItemBiometricAuthenticate
	// ItemQuitResponse answers EventQuitRequest Count, after the kinds Android's Protocol.java mirrors so that they keep their values. On permits the platform's pending termination request; false cancels it.
	ItemQuitResponse
	// ItemOverlayPermission asks whether the app may show windows over other apps, Android's SYSTEM_ALERT_WINDOW, opening the system's setting for the app when On; the platform answers with EventOverlayPermission carrying Count and the permission as Index (an OverlayPermission), after the setting once the app is back in front.
	ItemOverlayPermission
	// ItemPermission, after the kinds Android's Protocol.java mirrors, carries Permission, a request numbered Count about one of the system's permissions; the platform answers each one but PermissionStopGuide with EventPermission carrying Count, the status as Index.
	ItemPermission
	// ItemRevealFile shows Open in the system file manager, selected.
	ItemRevealFile
	// ItemTrashFile moves Open to the system Trash or Recycle Bin.
	ItemTrashFile
	// ItemKeepAwake takes a power assertion described by Awake and identified
	// by Count; ItemReleaseAwake releases the assertion identified by Count.
	ItemKeepAwake
	ItemReleaseAwake
	// ItemTaskProgress, after the kinds Android's Protocol.java mirrors, sets the app's task progress bar to Progress.
	ItemTaskProgress
	// ItemAudio asks of sound or player Count what Audio says; the platform reports it with EventAudio carrying Count. The core sends none where the environment says no Audio.
	ItemAudio
)

type KeepAwake

type KeepAwake struct {
	Reason  string
	Display bool
}

KeepAwake is a platform power assertion requested by ItemKeepAwake.

type KeyBinding

type KeyBinding struct {
	// Key is normalized, as NormalizeKey writes it.
	Key string
	// InText fires it while a text input or a web view has the keyboard
	// focus.
	InText bool
	// Repeat fires it again on the auto-repeats of a held key; else they
	// are consumed and fire nothing.
	Repeat bool
	// Yields are the focused controls it gives its key to, a subset of what KeyUsedBy says for the key: it takes no press while such a control has the keyboard focus, which an older binding of the key or the control then takes.
	Yields KeyUse
	// ID is a global shortcut's (ItemHotKeys), which EventHotKey reports.
	ID uint32
}

KeyBinding is one binding of the keymap the platform matches key presses against, on the main thread.

func (KeyBinding) FiresOver

func (b KeyBinding) FiresOver(focus KeyUse) bool

FiresOver reports whether the binding takes a press while the view with the keyboard focus uses the keys focus says: not from a text input or web view unless InText, nor from a control whose keys it Yields.

type KeyUse

type KeyUse uint8

KeyUse is a set of the keys a focused view uses itself, by the kind of view.

const (
	// KeyUsePress is Return and Space, which press a focused pressable view.
	KeyUsePress KeyUse = 1 << iota
	// KeyUseAdjust is the arrows, Page Up, Page Down, Home and End, which move a focused slider or spin button.
	KeyUseAdjust
	// KeyUseSelect is the arrows, Page Up, Page Down, Home and End, which move the selection or the focus in a focused tab bar, radio group, list, menu or tree.
	KeyUseSelect
	// KeyUseText is the keys a focused text input or web view edits with; InText says whether a binding fires over it.
	KeyUseText
)

func FocusKeyUse

func FocusKeyUse(kind ViewKind, role Role, pressable bool) KeyUse

FocusKeyUse returns the keys a focused view uses itself, by its kind, its role and whether it takes presses: a text input or web view its editing keys, a pressable view Return and Space, a slider or spin button its adjusting keys, and a tab bar, radio group, list, menu or tree and their items their moving keys. Each backend's focused view and nsgotest's are read the same way.

func KeyUsedBy

func KeyUsedBy(key string) KeyUse

KeyUsedBy returns the focused views that use key, a normalized key, themselves: Return and Space a pressable view, the arrows and the paging keys a slider or a selection. Modified keys are none's.

type KeyboardAppearance

type KeyboardAppearance uint8

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

type KeyboardDismissMode

type KeyboardDismissMode uint8

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

type KeyboardTaps

type KeyboardTaps uint8

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

const (
	// KeyboardTapsNever dismisses the keyboard, and the tap reaches
	// nothing else.
	KeyboardTapsNever KeyboardTaps = iota
	// KeyboardTapsAlways never dismisses it.
	KeyboardTapsAlways
	// KeyboardTapsHandled dismisses it unless something handles the tap.
	KeyboardTapsHandled
)

type KeyboardType

type KeyboardType uint8

KeyboardType picks a software keyboard.

const (
	KeyboardDefault KeyboardType = iota
	KeyboardEmail
	KeyboardNumber
	KeyboardDecimal
	KeyboardPhone
	KeyboardURL
)

type Keyframe

type Keyframe struct {
	Offset     float32
	Opacity    float32
	Scale      float32
	Rotate     float32
	TranslateY float32
	Easing     Curve
}

Keyframe is one step of a keyframe animation: at Offset of each cycle the view's opacity is multiplied by Opacity, it is scaled by Scale, turned Rotate degrees and moved down TranslateY times its height, on top of its own transform, and Easing takes it to the next step.

func (Keyframe) Matrix

func (k Keyframe) Matrix(size Size) Matrix3D

Matrix returns the step's transform for a box of size, around its center: translated, turned, then scaled.

type KeyframeAnimation

type KeyframeAnimation struct {
	Keyframes  Keyframes
	Duration   time.Duration
	Delay      time.Duration
	Easing     Curve
	Iterations int
}

KeyframeAnimation runs Keyframes over a view on the platform's frame clock, with no work for the engine per frame. Its zero Duration and Easing are the keyframes' own (Tailwind's); a zero Iterations repeats forever.

func (KeyframeAnimation) At

At returns the step a's view is at t into its run (Delay included), and false once it has finished.

func (KeyframeAnimation) Cycle

func (a KeyframeAnimation) Cycle() (time.Duration, []Keyframe)

Cycle returns a's duration and steps, with their defaults filled in.

type Keyframes

type Keyframes uint8

Keyframes are a keyframe animation's steps: Tailwind's animate-spin, animate-ping, animate-pulse and animate-bounce.

const (
	// KeyframesSpin turns the view once a second, for loading indicators.
	KeyframesSpin Keyframes = iota + 1
	// KeyframesPing scales the view to twice its size as it fades out, as
	// a radar ping or a notification badge's halo.
	KeyframesPing
	// KeyframesPulse fades the view to half and back every two seconds,
	// for skeleton loaders.
	KeyframesPulse
	// KeyframesBounce drops the view a quarter of its height and back.
	KeyframesBounce
)

type LayoutAnimation

type LayoutAnimation struct {
	Create, Update, Delete *LayoutTransition
}

LayoutAnimation animates the frame changes, insertions and removals of one commit on the platform, as React Native's LayoutAnimation does. Create animates the views the commit inserts, Update those whose frame changes, Delete those it removes; a nil phase leaves its changes instant.

type LayoutCurve

type LayoutCurve uint8

LayoutCurve is how a layout change progresses.

const (
	LayoutLinear LayoutCurve = iota
	LayoutEaseIn
	LayoutEaseOut
	LayoutEaseInEaseOut
	// LayoutSpring springs with Damping, settling within the duration.
	LayoutSpring
	// LayoutKeyboard is the software keyboard's own curve, timed from
	// when the keyboard started to move where the platform knows it.
	LayoutKeyboard
	// LayoutBezier follows Bezier, a style transition's easing.
	LayoutBezier
)

type LayoutProperty

type LayoutProperty uint8

LayoutProperty is what appearing and disappearing views animate.

const (
	// LayoutOpacity fades them.
	LayoutOpacity LayoutProperty = iota
	// LayoutScale grows and shrinks them from their center.
	LayoutScale
)

type LayoutTransition

type LayoutTransition struct {
	Curve LayoutCurve
	// Damping is LayoutSpring's damping ratio, from 0 to 1.
	Damping float32
	// Bezier is LayoutBezier's curve.
	Bezier Curve
	// Property is what appearing and disappearing views animate.
	Property LayoutProperty
	Duration time.Duration
	Delay    time.Duration
}

LayoutTransition is how one kind of change animates.

func (*LayoutTransition) At

func (tr *LayoutTransition) At(elapsed time.Duration) (float64, bool)

At returns the transition's progress at elapsed time since the change, and whether it is done. A spring may overshoot 1.

func (*LayoutTransition) End

func (tr *LayoutTransition) End() time.Duration

End is when the transition is done.

type LazyCarets

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

LazyCarets builds a CaretLayout once, when hit testing first asks, and guards the native layout it reads from against its release: an engine embeds it, calls Set with the function that reads the lines while the layout is alive, and Drop as it releases it.

func (*LazyCarets) CaretRect

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

CaretRect implements TextHitTester.

func (*LazyCarets) Drop

func (l *LazyCarets) Drop()

Drop forgets the native layout: lines not read yet stay empty.

func (*LazyCarets) HitTest

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

HitTest implements TextHitTester.

func (*LazyCarets) Lines

func (l *LazyCarets) Lines() CaretLayout

Lines returns the lines, read on first use.

func (*LazyCarets) RangeRects

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

RangeRects implements TextHitTester.

func (*LazyCarets) Set

func (l *LazyCarets) Set(read func() CaretLayout)

Set has l read its lines with read, the first time they are asked for.

type Length

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

Length is a style's length. Its zero value is auto: the layout decides.

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.

func (Length) IsAuto

func (l Length) IsAuto() bool

IsAuto reports whether l is auto.

func (Length) Percent

func (l Length) Percent() (float32, bool)

Percent returns l's value in percent, and whether l is a percentage.

func (Length) Points

func (l Length) Points() (Points, bool)

Points returns l's value in points, and whether l is a length in points.

func (Length) Resolve

func (l Length) Resolve(base Points) Points

Resolve returns l in points against base, or Auto. A percentage of an unknown base is Auto.

type Lifecycle

type Lifecycle uint8

Lifecycle is whether the app is in use, as NSH's lifecycle() reads it.

const (
	// LifecycleActive is an app that shows and has the focus: on desktops
	// one of its windows is the active one.
	LifecycleActive Lifecycle = iota
	// LifecycleInactive is an app that shows without the focus, as behind
	// another app's window, an incoming call or the app switcher.
	LifecycleInactive
	// LifecycleBackground is an app none of which shows: hidden,
	// minimized, covered where the system reports it, or in the
	// background on phones.
	LifecycleBackground
)

func (Lifecycle) String

func (l Lifecycle) String() string

String returns the state's name in TSX: active, inactive or background.

type LineCap

type LineCap uint8

LineCap ends open strokes.

const (
	CapButt LineCap = iota
	CapRound
	CapSquare
)

type LineDash

type LineDash []float32

LineDash is the lengths of a stroke's dashes and gaps in turn, an even number of them.

type LineJoin

type LineJoin uint8

LineJoin joins stroke segments.

const (
	JoinMiter LineJoin = iota
	JoinRound
	JoinBevel
)

type LiveRegion

type LiveRegion uint8

LiveRegion says how screen readers announce changes of a view's label and text (accessibilityLiveRegion). Android and the web announce them natively; macOS and iOS announce a changed label or text themselves.

const (
	LiveRegionNone LiveRegion = iota
	// LiveRegionPolite is announced when the user is idle.
	LiveRegionPolite
	// LiveRegionAssertive interrupts what is being read.
	LiveRegionAssertive
)

type LocaleSettings

type LocaleSettings struct {
	FirstDayOfWeek    int
	HourCycle         string
	MeasurementSystem string
	Region            string
}

LocaleSettings are the regional preferences the user set, in Intl's names: FirstDayOfWeek 1 for Monday to 7 for Sunday (ISO 8601), HourCycle "h11", "h12", "h23" or "h24", MeasurementSystem "metric", "us" or "uk"; zero where the platform does not say, which Region decides, else the locale's region (i18n.Regional). Region is the region whose formats the user chose apart from the language, such as Linux's LC_TIME, an ISO 3166 code.

type MathOp

type MathOp uint8

MathOp is an arithmetic node's operation.

const (
	MathAdd MathOp = iota + 1
	MathSub
	MathMul
	// MathDiv is 0 when b is 0.
	MathDiv
	// MathMod is never negative for a positive b.
	MathMod
)

type Matrix3D

type Matrix3D [16]float64

Matrix3D is a 4×4 transform of column vectors, stored column by column as CSS's matrix3d() lists it and Core Animation's CATransform3D lays it out: a point (x, y, z) maps to (M[0]x + M[4]y + M[8]z + M[12], ...) divided by M[3]x + M[7]y + M[11]z + M[15].

func ChildPerspective

func ChildPerspective(d Points, parent Size, offset Point) Matrix3D

ChildPerspective returns the matrix a parent's perspective of depth d puts before the transform of a child whose top left is at offset from the parent's, seen from the parent's center of size: CSS's perspective with its default origin.

func Perspective3D

func Perspective3D(d float64) Matrix3D

Perspective3D sees the plane z = 0 from d away, as CSS's perspective().

func Translate3D

func Translate3D(x, y, z float64) Matrix3D

Translate3D moves by x, y and z.

func (Matrix3D) Affine

func (m Matrix3D) Affine() (a, b, c, d, e, f float64, ok bool)

Affine reports whether m is a 2D transform, and its a, b, c, d, e, f as SVG's matrix() lists them.

func (Matrix3D) Apply

func (m Matrix3D) Apply(x, y float64) (float64, float64)

Apply maps a point of the plane through m, with perspective.

func (Matrix3D) Invert

func (m Matrix3D) Invert() (Matrix3D, bool)

Invert returns m's inverse, and false when it has none.

func (Matrix3D) Mul

func (m Matrix3D) Mul(n Matrix3D) Matrix3D

Mul returns m · n: n applied first, then m.

type MemoryClipboard

type MemoryClipboard struct {
	Text  string
	Image []byte // PNG
	Files []string
}

MemoryClipboard is a clipboard of a test's own: it takes the clipboard items an app sends and answers its reads, so the machine's clipboard is never touched.

func (*MemoryClipboard) Take

func (c *MemoryClipboard) Take(it *MountItem) (ev Event, answer, taken bool)

Take applies it when it is a clipboard item and reports whether it is: a write changes the clipboard, and a read returns the event that answers it, with answer true.

type MenuBarMode uint8

MenuBarMode says when Windows and Linux show the menu bar the window draws for the application menu. macOS's menu bar is the system's and always shows.

const (
	// MenuBarShown always shows it, above the app.
	MenuBarShown MenuBarMode = iota
	// MenuBarAutoHide shows it once Alt is pressed and released alone,
	// until Alt alone, a press elsewhere or a chosen item hides it again,
	// as Windows and GNOME apps do. F10 and Alt with a menu's mnemonic
	// still open a menu, and the bar shows while it is open.
	MenuBarAutoHide
)
type MenuEntry struct {
	ID        uint32
	Label     string
	Shortcut  string
	Role      MenuRole
	Disabled  bool
	Checkable bool
	Checked   bool
	Separator bool
	Items     []MenuEntry
	// NotInText leaves the shortcut to a text input or a web view with
	// the keyboard focus: the key goes to it rather than choosing the
	// item.
	NotInText bool
}

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. A role item without a shortcut takes its role's, which the platform fills in.

type MenuRole uint8

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. The app is not told when it is chosen.

const (
	MenuRoleNone MenuRole = iota
	// MenuAbout, MenuHide, MenuHideOthers and MenuShowAll are macOS's.
	MenuAbout
	MenuHide
	MenuHideOthers
	MenuShowAll
	MenuQuit
	// The edit roles act on the focused text field.
	MenuUndo
	MenuRedo
	MenuCut
	MenuCopy
	MenuPaste
	MenuSelectAll
	MenuMinimize
	MenuZoom
	MenuToggleFullScreen
	MenuClose
)
func (r MenuRole) EditsText() bool

EditsText reports whether r acts on the focused text field, whose own shortcut it then is.

func (r MenuRole) Label() string

Label returns the label of an item with role r and no label of its own.

func (r MenuRole) Shortcut(mac bool) string

Shortcut returns the shortcut of an item with role r and no shortcut of its own, in OnKey's form, on a Mac (mac) or elsewhere; "" for none.

type ModalAnimation

type ModalAnimation uint8

ModalAnimation is how a modal appears.

const (
	ModalSlide ModalAnimation = iota
	ModalFade
	ModalNone
)

func (ModalAnimation) Duration

func (a ModalAnimation) Duration() time.Duration

Duration is how long a modal takes to appear or go with a, as the platforms present it: what its component waits before it reports the modal shown or gone.

type ModalConfig

type ModalConfig struct {
	Animation ModalAnimation
	// Presentation, NoCloseOnSwipe and Orientations are iOS's. A sheet
	// reports its size with EventModalSize, its swipes with
	// EventRequestClose.
	Presentation   ModalPresentation
	NoCloseOnSwipe bool
	Orientations   Orientation
	// NoCloseOnEscape and NoCloseOnBackdropPress are the app's: the
	// core and base keep the modal on those, and tests read them, as
	// StatusBarTranslucent, Android's, which the core lays the modal out
	// by.
	NoCloseOnEscape, NoCloseOnBackdropPress bool
	StatusBarTranslucent                    bool
}

ModalConfig is how a modal appears and goes.

type ModalPresentation

type ModalPresentation uint8

ModalPresentation is how a modal covers the screen on iOS.

const (
	// ModalFullScreen covers the whole screen with the modal's own look.
	ModalFullScreen ModalPresentation = iota
	// ModalPageSheet is the system's sheet, which leaves the content
	// behind it in sight.
	ModalPageSheet
	// ModalFormSheet is a smaller sheet, centered on large screens.
	ModalFormSheet
)

type Modifiers

type Modifiers struct {
	Control, Alt, Shift bool
	// Platform is Command on Apple platforms, the Windows or Super key
	// elsewhere.
	Platform bool
}

Modifiers are the modifier keys held during an event.

type MountBatch

type MountBatch struct {
	Root  NodeID
	Items []MountItem
	// LayoutAnimation, when set, animates the batch's frame changes,
	// insertions and removals on the platform (Scope.AnimateLayout).
	LayoutAnimation *LayoutAnimation
	// Sent is when the engine handed the batch to the platform, for the
	// performance monitor's latency reading; the zero time when no monitor
	// measures.
	Sent time.Time
	// Causes are what the commit followed from, recorded while TraceCauses is set; nil otherwise.
	Causes *Causes
}

MountBatch is one commit's changes, applied in order on the main thread. Root is the view the platform shows in its surface.

type MountItem

type MountItem struct {
	Kind   ItemKind
	ID     NodeID
	View   ViewKind // ItemCreate
	Parent NodeID   // ItemInsert
	Before NodeID   // ItemInsert
	Frame  Bounds   // ItemFrame
	Size   Size     // ItemScrollContent
	Value  string   // ItemInputValue
	Count  uint32   // ItemInputValue
	// Transition, when set, moves an ItemFrame's view from where it shows
	// to Frame, as a batch's LayoutAnimation Update does, which wins.
	Transition *LayoutTransition
	// Point and Animated are ItemScrollTo's.
	Point    Point
	Animated bool
	// Clipboard is what an ItemReadClipboard reads.
	Clipboard ClipboardRead
	// Appearance is ItemAppearance's, RTL, Language and Forced
	// ItemDirection's.
	Appearance Appearance
	RTL        bool
	Language   string
	Forced     bool
	Events     EventMask

	ViewStyle *ViewStyle
	Text      *TextContent
	Input     *InputConfig
	ViewProps *ViewProps
	Scroll    *ScrollConfig
	Image     *ImageConfig
	Modal     *ModalConfig
	Alert     *AlertConfig
	Drawing   *Drawing
	Shader    *Shader
	// Keys are ItemKeymap's bindings, oldest first; see FindKey.
	Keys   []KeyBinding
	Window *WindowCommand
	Menu   []MenuEntry
	Web    *WebConfig
	// WebCommand is ItemWebCommand's.
	WebCommand WebCommand
	Video      *VideoConfig
	Time       time.Duration // ItemVideoSeek
	Native     *NativeConfig
	// Data is ItemNativeCommand's argument.
	Data      any
	Animation []AnimationOp
	Zoom      *ZoomRequest
	// Selection is ItemSelection's range.
	Selection TextRange
	// Sticky are ItemStickyCells' cells.
	Sticky    []StickyCell
	StatusBar *StatusBarConfig
	Screen    *ScreenConfig
	// Pick is ItemPickImages' and ItemTakePhoto's request.
	Pick *PickRequest
	// Speech is an ItemSpeech's request, Audio an ItemAudio's.
	Speech *SpeechRequest
	Audio  *AudioRequest
	// Notification is what ItemShowNotification shows.
	Notification *Notification
	// Permission is an ItemPermission's request.
	Permission *PermissionRequest
	// Awake is ItemKeepAwake's power assertion.
	Awake *KeepAwake
	// Progress is ItemTaskProgress's state.
	Progress *TaskProgress
	// Files is ItemPickFiles' request, Save ItemSaveFile's,
	// Directories ItemPickDirectories', Open ItemOpenFile's and
	// ItemInstallPackage's and Share ItemShare's.
	Files       *FilesRequest
	Save        *SaveRequest
	Directories *DirectoriesRequest
	Open        *SharedFile
	Share       *ShareRequest
	// Surface is ItemOpenSurface's window, Tray ItemTray's icon, and On
	// ItemDock's and ItemSetLaunchAtLogin's choice and whether
	// ItemCheckForUpdates checks in the background.
	Surface *SurfaceConfig
	Tray    *TrayConfig
	On      bool
}

MountItem is one change to the native views. Kind says which fields are set; the large groups are pointers so items stay small.

func (*MountItem) TraceLine

func (it *MountItem) TraceLine() string

TraceLine is the item as traces print it: its kind, its view and what it carries that a reader looks for.

type MouseButton

type MouseButton uint8

MouseButton is a button of the mouse; the zero value is none.

const (
	MouseButtonNone MouseButton = iota
	MouseButtonLeft
	MouseButtonRight
	MouseButtonMiddle
	MouseButtonBack
	MouseButtonForward
)

type NativeBinding

type NativeBinding struct {
	Name  string
	Node  uint32
	Color bool
}

NativeBinding binds a component's prop Name to animated node Node; Color says the node outputs a color.

type NativeComponent

type NativeComponent interface {
	// View is the view that fills the box: an NSView or UIView pointer as
	// a uintptr on Apple platforms, a child HWND on Windows, a GtkWidget
	// pointer on Linux, a DOM element (syscall/js.Value) on the web, and
	// on Android the name of a View class the runtime builds by
	// reflection.
	View() any
	// SetProp sets a prop; nil removes it.
	SetProp(name string, value any)
	// Command runs a command Ref.Command sent.
	Command(name string, args any)
	// Close releases the component when its element goes.
	Close()
}

NativeComponent is one Native element's platform view. Its methods run on the main thread.

type NativeComponents

type NativeComponents map[string]NativeFactory

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

type NativeConfig

type NativeConfig struct {
	Component string
	Props     map[string]any
	// Bindings, when Bind is set, replace the props animated nodes drive,
	// which the platform's Animator hands the component on the frames
	// they change.
	Bind     bool
	Bindings []NativeBinding
}

NativeConfig is what ItemNative sends: the component's name and the props that changed since the last item, nil for one removed. The first item of a view carries all of them.

type NativeContext

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

NativeContext is how a component talks back to its element. Its methods may be called from any goroutine.

func NewNativeContext

func NewNativeContext(emit func(name string, data any), size func(Size)) *NativeContext

NewNativeContext returns the context a platform hands a factory: emit reports an event, size the size the component asks for.

func (*NativeContext) Emit

func (c *NativeContext) Emit(name string, data any)

Emit sends an event to the element's OnEvent.

func (*NativeContext) SetSize

func (c *NativeContext) SetSize(s Size)

SetSize asks for a size: the element measures to it where its style leaves a dimension open, as an image does to its natural size. A dimension of 0 asks for the other alone.

type NativeFactory

type NativeFactory func(cx *NativeContext) NativeComponent

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

type NodeID

type NodeID uint32

NodeID identifies a view of one tree. IDs start at 1, stay dense and are reused after a Delete.

type Notification

type Notification struct {
	ID, Title, Body string
	Silent          bool
}

Notification is a system notification (ItemShowNotification), as core.Notification.

type OS

type OS string

OS names the operating system the app runs on.

const (
	OSMacOS   OS = "macos"
	OSIOS     OS = "ios"
	OSAndroid OS = "android"
	OSWindows OS = "windows"
	OSLinux   OS = "linux"
	OSWeb     OS = "web"
)

type OSVersion

type OSVersion struct {
	Major, Minor int
}

OSVersion is an operating system's version.

func (OSVersion) AtLeast

func (v OSVersion) AtLeast(major, minor int) bool

AtLeast reports whether v is major.minor or later.

func (OSVersion) String

func (v OSVersion) String() string

String returns v as major.minor.

type ObjectPosition

type ObjectPosition struct {
	X, Y PositionAxis
}

ObjectPosition is where an image sits in its view once its ResizeMode has sized it, as CSS's object-position places it. The parts of a covering image that overflow are cropped. The zero value centers it.

func (ObjectPosition) Place

func (p ObjectPosition) Place(box, content Size) Point

Place returns the top left corner of content of the given size placed in a box of size.

type Obstruction

type Obstruction struct {
	Frame Bounds
	// Horizontal is an obstruction between a region above and one below; else it is vertical, between a region on the left and one on the right.
	Horizontal bool
	// Occluding says the pixels under it are not shown or touched.
	Occluding bool
	// Separating says the regions on either side read as logically apart.
	Separating bool
	State      HingeState
	// Angle is the hinge's angle in radians, where the platform reports one, as HasAngle says.
	Angle    float32
	HasAngle bool
}

Obstruction is a fold or a hinge: its frame, its orientation and three properties that vary apart.

type Operand

type Operand struct {
	Node  uint32
	Const float64
}

Operand is an arithmetic node's operand: another node, or Const when Node is 0.

type Orientation

type Orientation uint8

Orientation is a set of interface orientations.

const (
	OrientationPortrait Orientation = 1 << iota
	OrientationPortraitUpsideDown
	OrientationLandscapeLeft
	OrientationLandscapeRight

	OrientationLandscape = OrientationLandscapeLeft | OrientationLandscapeRight
)

type Outline

type Outline struct {
	Width  Points
	Offset Points
	Color  Color
	// Style is solid when 0; none and hidden draw nothing.
	Style BorderStyle
}

Outline is a line around a view's border box, outside layout, Offset away from it (inside when negative), following its corners.

func (Outline) Visible

func (o Outline) Visible() bool

Visible reports whether the outline draws anything.

type Paint

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

Paint is what SVG's paint properties, 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.

func (Paint) Color

func (p Paint) Color(current Color) Color

Color returns the color p paints with, current being the text color; nothing is transparent.

func (Paint) IsSet

func (p Paint) IsSet() bool

IsSet reports whether p is set.

type PaintStyle

type PaintStyle struct {
	Fill, Stroke Paint
	// StrokeWidth is the line width; 0 is unset, CSS's initial 1.
	StrokeWidth Points
	// StrokeDash is the dashes and gaps in turn, repeated when odd; nil is
	// unset and empty solid, as are lengths adding up to 0.
	StrokeDash []Points
	// Background and Gradients are the view's own background, which
	// FillBackgroundFromView fills with.
	Background Color
	Gradients  []Gradient
}

PaintStyle is the SVG paint properties a canvas view inherits.

type PanActivation

type PanActivation struct {
	ActiveOffsetX, ActiveOffsetY Points
	FailOffsetX, FailOffsetY     Points
}

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. A fail offset passed first leaves the touch to others; an active offset passed activates the pan. With no active offset the pan activates after 10 points either way. Zero fields are unset.

func (PanActivation) Decide

func (a PanActivation) Decide(d Point) int

Decide returns whether a drag translated by d activates the pan (1), fails it (-1) or is undecided (0). Platforms call it on each move until it decides.

type PasteBehavior

type PasteBehavior uint8

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

const (
	// PasteInsert inserts it, as inputs do.
	PasteInsert PasteBehavior = iota
	// PasteReport only reports it with OnPaste, for the app to handle.
	PasteReport
)

type PasteEvent

type PasteEvent struct {
	// HTML is the same content with its formatting, on the backends that
	// read it.
	HTML  string
	Text  string
	Files []PastedFile
	URIs  []string
}

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.

type PastedFile

type PastedFile struct {
	Name string
	MIME string
	Data []byte
}

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

type Path

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

Path is a path to fill, stroke or clip with, as the web's Path2D: it records MoveTo, LineTo and the shapes in its own coordinates, which take the drawing's transform where it is used. Its arcs of ellipses and per-corner rectangles are cubic Béziers.

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 ("M 0 0 L 10 10 Z") into a path. It understands every command of SVG 1.1's path grammar; arcs become cubic curves.

func (*Path) AddPath

func (p *Path) AddPath(q *Path) *Path

AddPath adds q's subpaths to p.

func (*Path) Arc

func (p *Path) Arc(x, y, r, a0, a1 float32, ccw bool) *Path

Arc adds an arc of radius r around (x, y) from angle a0 to a1, joined to the path by a line.

func (*Path) ArcTo

func (p *Path) ArcTo(x1, y1, x2, y2, r float32) *Path

ArcTo adds an arc as Drawing.ArcTo does.

func (*Path) ClosePath

func (p *Path) ClosePath() *Path

func (*Path) CubicTo

func (p *Path) CubicTo(x1, y1, x2, y2, x, y float32) *Path

CubicTo adds a cubic curve through control points 1 and 2.

func (*Path) Ellipse

func (p *Path) Ellipse(x, y, rx, ry float32) *Path

Ellipse adds the whole ellipse around (x, y) with radii rx and ry.

func (*Path) EllipseArc

func (p *Path) EllipseArc(x, y, rx, ry, rotation, a0, a1 float32, ccw bool) *Path

EllipseArc adds an arc of an ellipse as Drawing.EllipseArc does.

func (*Path) LineTo

func (p *Path) LineTo(x, y float32) *Path

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float32) *Path

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float32) *Path

QuadTo adds a quadratic curve through control point (cx, cy).

func (*Path) Rect

func (p *Path) Rect(x, y, w, h float32) *Path

func (*Path) RoundRect

func (p *Path) RoundRect(x, y, w, h, r float32) *Path

RoundRect adds a rectangle with corners of radius r.

func (*Path) RoundRectCorners

func (p *Path) RoundRectCorners(x, y, w, h, topLeft, topRight, bottomRight, bottomLeft float32) *Path

RoundRectCorners adds a rectangle as Drawing.RoundRectCorners does.

type PermissionCommand

type PermissionCommand uint8

PermissionCommand is what an ItemPermission asks.

const (
	// PermissionCheck answers the status without asking the user.
	PermissionCheck PermissionCommand = iota
	// PermissionAsk shows the system's prompt where it has one and has not asked yet, then answers the status.
	PermissionAsk
	// PermissionOpenSettings opens the page of the system's settings that gives the permission; EventPermission's Finished says whether one opened.
	PermissionOpenSettings
	// PermissionGuide opens the settings and guides the user there; it is answered once, as the guide ends, with the status then.
	PermissionGuide
	// PermissionStopGuide ends the guide whose request was Count, which still answers its own request; it is not answered itself.
	PermissionStopGuide
)

type PermissionRequest

type PermissionRequest struct {
	Command PermissionCommand
	// Name is the permission's key, one of the Permission* keys; "" for PermissionStopGuide.
	Name string
	// App is the path of the app PermissionGuide holds out to drag, and AppName what it calls it; "" for the defaults.
	App, AppName string
}

PermissionRequest is an ItemPermission's.

type PickEncoding

type PickEncoding uint8

PickEncoding is what a platform does with one picked image.

const (
	// PickKeep keeps its bytes as they are.
	PickKeep PickEncoding = iota
	// PickPNG decodes it, its orientation applied, scales it to fit
	// MaxDimension and encodes it as a PNG: an image that was a PNG.
	PickPNG
	// PickJPEG does the same and encodes a JPEG at the request's quality.
	PickJPEG
)

type PickFormat

type PickFormat uint8

PickFormat says which formats picked images come in.

const (
	// PickCompatible keeps JPEG, PNG, GIF and WebP as they are and turns
	// any other format, such as HEIC or TIFF, into JPEG.
	PickCompatible PickFormat = iota
	// PickCurrent keeps the format the image is stored in, unless it is
	// encoded again to scale it or for a quality.
	PickCurrent
)

type PickRequest

type PickRequest struct {
	// Limit is the most images the user picks: 1 for a single pick, at
	// most MaxPicked.
	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 JPEG quality images are encoded at, from 0 to 1;
	// 0 means DefaultPickQuality and keeps JPEGs that need no other
	// change as they are.
	Quality float32
	// Format says which formats images come in.
	Format PickFormat
}

PickRequest is a pick as the platform carries it out.

func (PickRequest) DialogExtensions

func (r PickRequest) DialogExtensions() []string

DialogExtensions returns the file extensions a desktop's open dialog offers for r when the backend reads files as they are: only the formats every platform shows unless r keeps the current format.

func (PickRequest) Encoding

func (r PickRequest) Encoding(mime string, size Size) PickEncoding

Encoding returns what to do with an image of type mime whose pixels are size, its orientation applied.

func (PickRequest) JPEGQuality

func (r PickRequest) JPEGQuality() float32

JPEGQuality returns the quality JPEGs are encoded at, from 0 to 1.

func (PickRequest) ScaledSize

func (r PickRequest) ScaledSize(size Size) Size

ScaledSize returns the size an image of size pixels is scaled to: its longer side at most MaxDimension, its aspect ratio kept.

type PickedFile

type PickedFile struct {
	// Name has an extension that matches MIME (IMG_0042.jpg).
	Name string
	// MIME is its media type (image/jpeg).
	MIME string
	Data []byte
	// Size is its size in pixels as it shows, its orientation applied.
	Size Size
	// Modified is when it last changed, zero when the platform does not
	// say.
	Modified time.Time
}

PickedFile is an image the user picked.

func FinishPick

func FinishPick(r PickRequest, files []PickedFile, size func(data []byte) (Size, error)) []PickedFile

FinishPick returns files as the app gets them: at most r.Limit, each with a type, a name matching it and, when size reads it, a size.

type Pictures

type Pictures uint8

Pictures is a set of pictures a WGSL program reads, its textures in this order.

const (
	// PictureContent is the children of an effect, or the surface for a
	// screen shader.
	PictureContent Pictures = 1 << iota
	// PictureBackdrop is what the surface shows behind the view.
	PictureBackdrop
	// PictureFrom and PictureTo are a transition's sides.
	PictureFrom
	PictureTo
)

type Point

type Point struct{ X, Y Points }

Point is a position in points.

type PointerEvents

type PointerEvents uint8

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

const (
	// PointerEventsAuto lets the view and its children take them.
	PointerEventsAuto PointerEvents = iota
	// PointerEventsNone lets neither take them: they reach what is below.
	PointerEventsNone
	// PointerEventsBoxNone lets only the children take them.
	PointerEventsBoxNone
	// PointerEventsBoxOnly lets only the view take them, never its
	// children.
	PointerEventsBoxOnly
	// PointerEventsOn is auto in a style, where 0 is unset: it stops a
	// none the view inherits. The core sends it as PointerEventsAuto.
	PointerEventsOn
)

type Points

type Points float32

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

const (
	RefreshPull  Points = 64
	RefreshSpace Points = 56
)

RefreshPull is how far past its top a released pull refreshes with the platform's spinner, and RefreshSpace the room the spinner keeps above the content while refreshing.

const DefaultFontSize Points = 14

DefaultFontSize is the font size of text no ancestor sizes: 14, as NSH's and MyGo's text defaults.

const DefaultPanSlop Points = 10

DefaultPanSlop is the distance a drag moves before it activates a pan without active offsets.

func Projected

func Projected(offset Points, velocity, rate float32) Points

Projected returns where a glide from offset at velocity (points per millisecond) comes to rest, decelerating by rate per millisecond.

func (Points) IsAuto

func (p Points) IsAuto() bool

IsAuto reports whether p is Auto.

type PositionAxis

type PositionAxis struct {
	Offset  Length
	FromEnd bool
}

PositionAxis is an ObjectPosition along one axis: Offset from the start edge (left, top), or from the end edge (right, bottom) when FromEnd. A percentage is of the free space, the view's size less the image's, so Pct(0) is the start, Pct(50) the center and Pct(100) the end; an auto Offset, the zero value, is the center.

func (PositionAxis) Resolve

func (a PositionAxis) Resolve(free Points) Points

Resolve returns where content starts along the axis, from the start edge, given the free space: the box's size less the content's.

type PreparedText

type PreparedText interface {
	// Measure returns the size of the text wrapped at maxWidth (Auto: no
	// wrapping).
	Measure(maxWidth Points) Size
	// Layout returns the text laid out in size, for the main thread to
	// draw.
	Layout(size Size) TextLayout
	// Release frees what the prepared text holds.
	Release()
}

PreparedText is text a TextEngine shaped.

type Ran

type Ran struct {
	Kind, Site string
	Runs       int
	Took       time.Duration
}

Ran is the runs of the computations of one kind made at one line, and their time.

type Region

type Region struct {
	Frame Bounds
	// SafeArea is the part of each of the region's edges that system bars, notches and rounded corners cover: the surface's safe area where it falls in the region, which core fills in from the environment.
	SafeArea Edges
	// Reserved is the part of the region an obstruction that does not divide it takes, such as a fold whose pixels do not show, which the app must not place content across; empty when there is none.
	Reserved Bounds
}

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

type ResizeMode

type ResizeMode uint8

ResizeMode fits an image or a video into its view. The zero value is the element's default: Cover for an image, Contain for a video, as in NSH. Platforms receive the resolved mode.

const (
	// Cover fills the view, cropping what overflows.
	Cover ResizeMode = iota + 1
	// Contain fits the whole image, leaving space.
	Contain
	// Stretch fills the view, distorting the image.
	Stretch
	// Center keeps the image's natural size, cropped where it is larger
	// than the view (CSS's object-fit: none).
	Center
	// ScaleDown keeps the natural size, shrunk to fit where it is larger
	// than the view (CSS's object-fit: scale-down, React Native's center).
	ScaleDown
)

func (ResizeMode) Fit

func (m ResizeMode) Fit(natural, box Size, pos ObjectPosition) Bounds

Fit returns where an image of natural size, in points, goes in a view of size box: scaled as m scales it (Center keeps the natural size, as CSS's none; ScaleDown shrinks an image larger than the box, as CSS's scale-down), then placed at pos. The rectangle may reach outside the box, which crops it. An image without a size fills the box. Every backend fits images and videos with it, as NSH's ResizeMode::fit.

type ReturnKeyType

type ReturnKeyType uint8

ReturnKeyType labels the software keyboard's return key.

const (
	ReturnKeyDefault ReturnKeyType = iota
	ReturnKeyDone
	ReturnKeyGo
	ReturnKeyNext
	ReturnKeySearch
	ReturnKeySend
)

type Ripple

type Ripple struct {
	// Color is the ripple's; 0 takes the theme's.
	Color Color
	// Borderless spreads it past the view's shape.
	Borderless bool
	// Radius is 0 for the platform's.
	Radius Points
	// Foreground draws it over the view's content, else behind it.
	Foreground bool
}

Ripple is Android's ripple over a view while it is pressed.

type Role

type Role uint8

Role is a view's accessibility role.

const (
	RoleNone Role = iota
	RoleButton
	RoleLink
	RoleHeader
	RoleImage
	RoleCheckbox
	RoleSwitch
	RoleRadio
	RoleTab
	RoleText
	RoleTextField
	RoleRadioGroup
	RoleTabList
	RoleMenu
	RoleMenuItem
	RoleDialog
	RoleAlert
	// RoleAdjustable is a slider: its Value is a range that the
	// increment and decrement actions adjust.
	RoleAdjustable
	// RoleProgressBar shows progress, its Value a range.
	RoleProgressBar
	// RoleTable is a table of the app's rows; RoleGrid one whose cells
	// the user selects and moves between. RoleRowGroup holds a header's,
	// a body's or a footer's rows, RoleRow a row's cells, and
	// RoleColumnHeader and RoleCell are a row's cells.
	RoleTable
	RoleGrid
	RoleRowGroup
	RoleRow
	RoleColumnHeader
	RoleCell
	// RoleListbox holds RoleOptions the user picks from, as a select's
	// popup does.
	RoleListbox
	RoleOption
	// RoleGroup, RoleRegion and RoleNavigation are parts of a page, the
	// last two landmarks.
	RoleGroup
	RoleRegion
	RoleNavigation
	// RoleTree holds RoleTreeItems.
	RoleTree
	RoleTreeItem
	RoleToolbar
	// RoleMenuItemCheckbox and RoleMenuItemRadio are menu items with a
	// checked state.
	RoleMenuItemCheckbox
	RoleMenuItemRadio
	// RoleSpinButton is a field for a number: its Value is what it reads
	// as, between its bounds, and its actions step it.
	RoleSpinButton
	// RoleCombobox picks a value from a list it opens, as a select's
	// trigger.
	RoleCombobox
	// RoleAlertDialog is a dialog that asks for an answer to what it
	// says, as a confirmation, ARIA's alertdialog; RoleDialog is any
	// other.
	RoleAlertDialog
)

type SVG

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

SVG is a parsed SVG document: vector shapes that stay sharp at any size. An Icon draws one in the color it inherits, and the image decoders draw SVG files with it.

ParseSVG reads static drawings, icons, logos and illustrations: path, rect, circle, ellipse, line, polyline and polygon inside svg, g, a, switch and use elements, with fills, strokes, stroke widths, caps and joins, fill and clip rules, opacities, transforms, linear and radial gradients, clip paths and markers. A color may be none, currentColor, a hex color, rgb(), rgba(), hsl(), hsla() or a CSS color name. Groups pass these to their children, and presentation attributes, the style attribute and simple style sheets (type, class and id selectors) set them.

Text, images, patterns, masks, filters, dashes and animations are not read: an SVG is a drawing, not a page. ParseSVG reads only the document, never a file or URL it names.

func ParseSVG

func ParseSVG(data []byte) (*SVG, error)

ParseSVG parses an SVG document.

func (*SVG) Draw

func (s *SVG) Draw(d *Drawing, box Size, color Color)

Draw records the document's shapes into d, fitted and centered in box and painted in color: every currentColor becomes color, and a zero color is black. A non-uniform box keeps the document's aspect ratio.

func (*SVG) Size

func (s *SVG) Size() (w, h Points)

Size returns the document's intrinsic size: its width and height, one of them and the viewBox's aspect ratio, or its viewBox's size.

type SaveRequest

type SaveRequest struct {
	// Name is a file name without directories, never empty.
	Name string
	MIME string
	Path string
	Data []byte
}

SaveRequest is a save as the platform carries it out: the file the dialog suggests and what goes in it, the file at Path or else Data.

func (SaveRequest) Open

func (r SaveRequest) Open() (io.ReadCloser, error)

Open opens what r saves.

func (SaveRequest) SaveTo

func (r SaveRequest) SaveTo(path string) error

SaveTo writes what r saves to path through a temporary file beside it, so a write that fails leaves path as it was.

func (SaveRequest) Stage

func (r SaveRequest) Stage(dir string) (string, error)

Stage returns a file named r.Name, in a new directory under dir, that holds what r saves, for platforms that save only files on disk under the name they show: a link to Path where the system allows one, else a copy. The caller removes the directory once the save ended.

type ScreenAnimation

type ScreenAnimation uint8

ScreenAnimation is how a screen of a stack enters and leaves: a push takes the pushed screen's, a pop the popped one's. ScreenDefault is the platform's, a slide where it animates screens.

const (
	ScreenDefault ScreenAnimation = iota
	ScreenSlide
	ScreenFade
	ScreenNone
)

type ScreenConfig

type ScreenConfig struct {
	Title string
	// HeaderHidden hides the header; HeaderHeight is then 0.
	HeaderHidden      bool
	HeaderTransparent bool
	LargeTitle        bool
	// CanGoBack says a screen is below; BackHidden hides the back button
	// to it, and BackTitle is its label.
	CanGoBack  bool
	BackHidden bool
	BackTitle  string
	// OwnBackTitle is the screen's own HeaderBackTitle: the label of the
	// back button to it on the screen above, which that screen's
	// BackTitle shows.
	OwnBackTitle string
	// NoPopOnSwipe turns the swipe back off, as NoPopOnBack does with the
	// back button's popping: a press still reports EventBack.
	NoPopOnSwipe bool
	NoPopOnBack  bool
	// Background, TitleColor and TintColor are the header's colors; 0
	// keeps the platform's.
	Background, TitleColor, TintColor Color
	// Left, Right and TitleView are the header views, each a layout root
	// at its content's size that no view holds, or 0.
	Left, Right, TitleView NodeID
	// Header is the screen's own header, which a platform without a
	// native one would show; the native header leaves it unused.
	Header NodeID
	// RightSystemItem, with a Right view, is the UIKit button iOS shows
	// in Right's place; a press on it presses Right's first view that
	// takes presses.
	RightSystemItem HeaderSystemItem
	// RightSymbols, with a Right view, are the UIKit buttons iOS shows in
	// its place, a line each of an SF Symbol's name, a tab and its label. A
	// press on one presses that of Right's views that take presses.
	RightSymbols string
	// HeaderHeight is the area the header covers from the screen's top:
	// the bar and the part of the status bar the screen reaches under.
	HeaderHeight Points
	// Animation is how the screen enters and leaves.
	Animation ScreenAnimation
}

ScreenConfig is a screen's system header, which the platform draws over the top of the screen's view, HeaderHeight tall.

type ScrollBehavior

type ScrollBehavior struct {
	// Paging stops at multiples of the viewport.
	Paging bool
	// SnapToInterval stops at multiples of this length; 0 turns it off.
	SnapToInterval Points
	// SnapToOffsets stops at these offsets.
	SnapToOffsets []Points
	// SnapToAlignment is the point of a SnapToInterval item that aligns
	// with the viewport.
	SnapToAlignment SnapAlignment
	// DisableIntervalMomentum moves a fling one snap point at most.
	DisableIntervalMomentum bool
	// DecelerationRate is the velocity a fling keeps per millisecond:
	// DecelerationNormal, DecelerationFast or between; 0 is the
	// platform's.
	DecelerationRate float32
	// NoScroll keeps the user from scrolling it (React Native's
	// scrollEnabled false); the app still can.
	NoScroll bool
	// NoBounces stops drags at the edges instead of rubber banding.
	NoBounces bool
	// ContentInset is room around the content that scrolls with it.
	ContentInset Edges
	// KeyboardDismissMode is whether dragging dismisses the software
	// keyboard.
	KeyboardDismissMode KeyboardDismissMode
	// KeyboardShouldPersistTaps is whether a tap while the software
	// keyboard shows dismisses it.
	KeyboardShouldPersistTaps KeyboardTaps
	// RefreshIndicator is the height of the app's own pull-to-refresh
	// indicator, drawn from a pull value, which replaces the platform's
	// spinner: a pull refreshes once it reaches it, and refreshing keeps
	// it above the content. 0 shows the platform's spinner.
	RefreshIndicator Points
}

ScrollBehavior is how a scroll view scrolls, as NSH's Scrollable props (React Native's ScrollView props) say: Scroll's Behavior. Its zero value scrolls freely, bounces and decelerates as the platform does.

func (*ScrollBehavior) Deceleration

func (b *ScrollBehavior) Deceleration() float32

Deceleration returns the velocity a fling keeps per millisecond: DecelerationRate, else DecelerationFast when it snaps and DecelerationNormal otherwise.

func (*ScrollBehavior) Equal

func (b *ScrollBehavior) Equal(o *ScrollBehavior) bool

Equal reports whether b and o scroll the same.

func (*ScrollBehavior) RefreshInset

func (b *ScrollBehavior) RefreshInset() Points

RefreshInset is the room kept above the content while it refreshes: the app's indicator's height, or the spinner's.

func (*ScrollBehavior) RefreshThreshold

func (b *ScrollBehavior) RefreshThreshold() Points

RefreshThreshold is how far past the top a released pull refreshes: the app's indicator's height, or the spinner's distance.

func (*ScrollBehavior) SnapPoints

func (b *ScrollBehavior) SnapPoints(viewport, content Points) []Points

SnapPoints returns the offsets, in order, a view snapping or paging along a viewport and content of those lengths stops at, or none when it does not snap. Backends without SnapTarget's hook, such as the web's CSS scroll snapping, mark them.

func (*ScrollBehavior) SnapTarget

func (b *ScrollBehavior) SnapTarget(offset, projected Points, velocity float32, viewport, content Points) (Points, bool)

SnapTarget returns the snap point a fling ends at, as React Native's, and false when the view neither snaps nor pages. All values are along the main axis: offset is where the drag ended, projected where the fling would glide to (Projected), velocity its speed in points per millisecond (positive: the offset grows), for a viewport and content of those lengths. Pages, and DisableIntervalMomentum, move one snap point; other snapping rounds the projected offset in the fling's direction. Platforms call it, or Android's port, as the user lets go.

func (*ScrollBehavior) Snaps

func (b *ScrollBehavior) Snaps() bool

Snaps reports whether flings end at snap points: snapping or paging.

type ScrollConfig

type ScrollConfig struct {
	Horizontal bool
	// HideIndicator hides the scroll bar.
	HideIndicator bool
	Behavior      ScrollBehavior
	// HeaderInset is the part of Behavior.ContentInset's top that a
	// transparent or large system header covers, which a large title
	// collapses into as the content scrolls under it.
	HeaderInset Points
	// Refreshable says the app listens for EventRefresh: pulling the
	// content down past its top refreshes. Refreshing shows the spinner;
	// a config after EventRefresh says whether the app keeps it.
	Refreshable bool
	Refreshing  bool
	// MinZoomScale and MaxZoomScale bound pinches (1 and at least
	// MinZoomScale); the content zooms when Zooms. ZoomScale is the app's
	// scale, which the platform zooms to when it changes.
	MinZoomScale, MaxZoomScale float32
	ZoomScale                  float32
	// NoBouncesZoom stops pinches at the limits; NoPinchZoom ignores
	// pinches; CenterContent centers content smaller than the viewport.
	NoBouncesZoom bool
	NoPinchZoom   bool
	CenterContent bool
	// Edges are the effects at its sides, in the order of Edges: top,
	// right, bottom, left.
	Edges [4]ScrollEdge
}

ScrollConfig configures a scroll view.

func (*ScrollConfig) ClampZoom

func (c *ScrollConfig) ClampZoom(z float32) float32

ClampZoom returns z within c's zoom scales.

func (*ScrollConfig) Equal

func (c *ScrollConfig) Equal(o *ScrollConfig) bool

Equal reports whether c and o configure a scroll view the same.

func (*ScrollConfig) Zooms

func (c *ScrollConfig) Zooms() bool

Zooms reports whether the content zooms: MaxZoomScale above MinZoomScale.

type ScrollEdge

type ScrollEdge struct {
	Effect EdgeEffect
	// Extent is how far into the scroll view the bars over this side
	// reach from it, 0 without bars; Bars are their views, which iOS 26
	// shapes its effect under (UIScrollEdgeElementContainerInteraction).
	Extent Points
	Bars   []NodeID
	// Tint is the background the content scrolls over, which the effect
	// fades it into, and Line a hard edge's hairline.
	Tint, Line Color
}

ScrollEdge is a scroll view's effect at one of its sides (ScrollConfig.Edges).

func (*ScrollEdge) Band

func (e *ScrollEdge) Band() Points

Band returns how far from its side the drawn effect reaches: a soft edge's past the bars by SoftEdgeTail, 0 for none.

func (*ScrollEdge) Drawn

func (e *ScrollEdge) Drawn() EdgeEffect

Drawn returns the effect a platform drawing it itself draws: soft for an automatic side with bars, and none without bars.

func (*ScrollEdge) Equal

func (e *ScrollEdge) Equal(o *ScrollEdge) bool

Equal reports whether e and o draw the same.

func (*ScrollEdge) SoftTint

func (e *ScrollEdge) SoftTint(most float32) []GradientStop

SoftTint returns the stops of a soft edge's tint across its band, from its side: most of the background SoftEdgeTail short of the bars' end, easing out from there to nothing at the band's end. Its ends ease as smoothstep's do, so no line shows where the tint begins to fade.

type Segment

type Segment struct {
	Kind SegmentKind
	P    [3][2]float64
}

Segment is one step of an outline, in points.

func EllipticRect

func EllipticRect(out []Segment, x, y, w, h float64, radii [4][2]float64, continuous, reverse bool) []Segment

EllipticRect is RoundedRect with each corner's radius along the horizontal and the vertical edge, clockwise from the top left, already fitted: the inner edge of a border whose sides differ.

func RoundedRect

func RoundedRect(out []Segment, x, y, w, h float64, corners Corners, continuous, reverse bool) []Segment

RoundedRect returns the outline of the rectangle at x, y of size w, h with corners, fitted with Corners.Fit first, appending to out. It runs clockwise on screen (y down) from the top edge, or counterclockwise when reverse, which makes a hole under the non-zero rule. Continuous corners are a circular arc between two cubic transitions spreading the curvature over (1 + Smoothing) times the radius of each edge, as NSH's shape module draws them; where the box is too small they shrink to circular corners, so pills stay pills.

type SegmentKind

type SegmentKind uint8

SegmentKind is what a Segment of an outline does.

const (
	// SegmentMove starts the outline at P[0].
	SegmentMove SegmentKind = iota
	// SegmentLine draws a straight line to P[0].
	SegmentLine
	// SegmentCubic draws a cubic Bézier through the control points P[0]
	// and P[1] to P[2].
	SegmentCubic
	// SegmentClose closes the outline.
	SegmentClose
)

type Selectable

type Selectable uint8

Selectable says whether the user can select a text.

const (
	// SelectableAuto selects the text with its selection area when it is
	// in one. Elsewhere only the web selects it, on desktops, as a page's
	// text.
	SelectableAuto Selectable = iota
	// SelectableOn selects the text, alone when it is in no area.
	SelectableOn
	// SelectableOff keeps the text out of selections, its area's too.
	SelectableOff
)

type SelectionHandle

type SelectionHandle uint8

SelectionHandle is one of the two ends of a selection, for touch handles.

const (
	HandleStart SelectionHandle = iota
	HandleEnd
)

type SelectionModel

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

SelectionModel is the selection of one area: an anchor where it started and a focus where it goes, extended by words or paragraphs after a double or triple click. Its zero value selects nothing. Methods that change it report whether the selection changed, so the backend redraws only then.

func (*SelectionModel) Bounds

func (m *SelectionModel) Bounds() (start, end TextPosition, ok bool)

Bounds returns the selection's start and end in document order, and false without a selection.

func (*SelectionModel) Clear

func (m *SelectionModel) Clear() bool

Clear clears the selection.

func (*SelectionModel) Drag

func (m *SelectionModel) Drag(texts SelectionTexts, p Point) bool

Drag moves the focus to p while the pointer is pressed, by the press's granularity.

func (*SelectionModel) Extent

func (m *SelectionModel) Extent(texts SelectionTexts) Bounds

Extent is the box of the texts the selection touches, for EventSelectionChange; no Size without a selection.

func (*SelectionModel) IsEmpty

func (m *SelectionModel) IsEmpty() bool

IsEmpty reports whether nothing is selected: no selection, or an empty one.

func (*SelectionModel) MoveHandle

func (m *SelectionModel) MoveHandle(texts SelectionTexts, h SelectionHandle, p Point) bool

MoveHandle moves the end h to p and keeps the other; they swap when one passes the other. From then on the selection goes by characters.

func (*SelectionModel) Press

func (m *SelectionModel) Press(texts SelectionTexts, p Point, clicks int, extend bool) bool

Press is a pointer press at p: one click puts the anchor there, with nothing selected until a drag, two select the word, three the whole text. With extend (Shift) it extends the selection from its anchor to p instead, by the current granularity.

func (*SelectionModel) Ranges

func (m *SelectionModel) Ranges(texts SelectionTexts) []SelectionRange

Ranges returns what each text has selected, in order, leaving out empty ranges: what the backend highlights.

func (*SelectionModel) SelectAll

func (m *SelectionModel) SelectAll(texts SelectionTexts) bool

SelectAll selects every text of the area.

func (*SelectionModel) SelectWordAt

func (m *SelectionModel) SelectWordAt(texts SelectionTexts, p Point) bool

SelectWordAt selects the word at p, as a long press on a touch screen does.

func (*SelectionModel) Text

func (m *SelectionModel) Text(texts SelectionTexts) string

Text returns the selected text as a copy gives it (CopiedText): each text's selected part, hidden spans left out and each attachment (U+FFFC) the selection holds whole as its span's Copy, or left out without one, texts on one row (their frames overlap vertically) joined by a tab and the others by a line break.

func (*SelectionModel) TextsChanged

func (m *SelectionModel) TextsChanged(texts SelectionTexts) bool

TextsChanged updates the selection to texts, the new list: each end follows its text by key, offsets are clamped to what is there, and a selection whose text is gone is cleared.

type SelectionRange

type SelectionRange struct {
	Text, Start, End int
}

SelectionRange is what one text has selected: UTF-16 offsets from Start to End.

type SelectionSpans

type SelectionSpans interface {
	Spans(i int) []TextSpan
}

SelectionSpans is what SelectionTexts whose texts have spans also tell: text i's spans, whose hidden ones a copy leaves out and whose Copy it takes in place of the attachment each styles.

type SelectionTexts

type SelectionTexts interface {
	// Len is how many texts take part.
	Len() int
	// Content is text i's content.
	Content(i int) string
	// Frame is text i's content box.
	Frame(i int) Bounds
	// OffsetAt is the UTF-16 offset of text i nearest p, a point inside
	// its frame: where a click there puts the caret.
	OffsetAt(i int, p Point) int
	// Key is a stable identity of text i, such as its NodeID, so a
	// selection follows its texts when others come or go before them.
	Key(i int) uint64
}

SelectionTexts is what a backend knows of the texts of one area, in document order (the area's subtree, depth first). Coordinates are the area's, scroll offsets of the views between applied.

type Shader

type Shader struct {
	Program *ShaderProgram
	// Lanes are the program's own uniforms, after those the platform
	// sets, lane by lane in the order they are declared: a vector's
	// components, a matrix's columns and an array's elements in turn.
	// An int, uint or bool lane takes the value's integer part.
	Lanes []float64
	// Nodes are the lanes animated nodes drive over Lanes, which the
	// platform reads from its Animator each frame they change.
	Nodes []ShaderNode
	// Images are what the program's image0At to image3At read, in order.
	// The platform loads each as an image view does and draws the view
	// again once it has them; one it lacks reads as transparent.
	Images []ImageSource

	// Role is what the shader draws: a shader view's fill, or over a
	// view's children, the surface or a change of pages. A WGSL program
	// reads the pictures Pictures names, which the platform takes of
	// the views the role says.
	Role     ShaderRole
	Pictures Pictures
	// Overflow is how far beyond each side of the view the shader draws,
	// and its pictures reach, in points.
	Overflow float64
	// Running is whether a transition runs: the shader draws over the
	// children from the picture taken as it started (ItemShaderTransition)
	// to what they show, hiding them, until a Shader that is not Running
	// ends it. Backwards takes the first picture as the side the change
	// goes to, sample_to, as a pop or a dismissal does.
	Running, Backwards bool
}

Shader is what a shader view draws (ItemShader): Program with the values of its uniforms.

type ShaderNode

type ShaderNode struct {
	Lane    int
	Node    uint32
	Channel Channel
}

ShaderNode binds lane Lane of a shader's uniforms to animated node Node: its number, or one channel of the color it outputs.

type ShaderProgram

type ShaderProgram struct {
	IR *shaderir.Program
	// WGSL is set for a program written in WGSL (package shader/wgsl):
	// its first lanes are the built-ins (ShaderBuiltinLanes) and its
	// textures the pictures (Pictures), not images.
	WGSL bool
}

ShaderProgram is a fragment shader an app compiled: the program the core checked, so platforms translate it for their GPU without linking the compiler. Each translates it once and keeps the result while the program is in use. Once handed to the platform it never changes, so platforms key what they made from it by its pointer.

type ShaderRole

type ShaderRole uint8

ShaderRole is what a shader draws.

const (
	// ShaderFill fills a shader view's box under its children.
	ShaderFill ShaderRole = iota
	// ShaderEffect draws the view's children through the shader, over
	// them and in their place; they still take input.
	ShaderEffect
	// ShaderTransition draws the view's children as they change, while
	// Running, and shows them as they are between changes.
	ShaderTransition
	// ShaderScreen and ShaderScreenTransition do the same with the whole
	// surface, which a view of no size in it holds.
	ShaderScreen
	ShaderScreenTransition
	// ShaderNav draws a stack's change of pages, or the surface as a
	// dialog comes or goes (on the surface's root view), while Running:
	// sample_from the lower side and sample_to the upper.
	ShaderNav
)

func (ShaderRole) Covers

func (r ShaderRole) Covers() bool

Covers reports whether r draws a whole surface.

func (ShaderRole) Transitions

func (r ShaderRole) Transitions() bool

Transitions reports whether r draws a change while Running.

type ShareRequest

type ShareRequest struct {
	Files []SharedFile
	Text  string
	// From is the area the sheet points at where it shows as a popover,
	// as on macOS and iPads, in the root's points; zero for the root's
	// center.
	From Bounds
}

ShareRequest is a share as the platform carries it out: files, text, or both, for the system's share sheet.

type SharedFile

type SharedFile struct {
	// Path is where it is on disk, absolute once the core resolved it.
	Path string
	// Name is the file name the other app sees, Path's own unless the app
	// gave another; the core fills it in.
	Name string
	// MIME is its media type, which the core fills in from Name.
	MIME string
}

SharedFile is a file the app hands another app: one it opens in the app the system associates with it, or one of a share.

func (SharedFile) Stage

func (f SharedFile) Stage(dir string) (string, error)

Stage returns a path to f under its Name, for platforms that hand files on by path and show a file's own name: Path itself when its name is Name, else a link to it, or a copy where the system allows none, in a new directory under dir. Directories a stage made over ShareStageAge ago go first.

type Side

type Side uint8

Side is a side of a box, in the order of Edges.

const (
	SideTop Side = iota
	SideRight
	SideBottom
	SideLeft
)

type Size

type Size struct{ Width, Height Points }

Size is a width and a height in points.

type SnapAlignment

type SnapAlignment uint8

SnapAlignment is where a snapped item sits in the viewport.

const (
	SnapStart SnapAlignment = iota
	SnapCenter
	SnapEnd
)

type SpeechCommand

type SpeechCommand uint8

SpeechCommand is what an ItemSpeech asks of its session.

const (
	// SpeechStart starts recognizing in Lang, the system's language when
	// empty.
	SpeechStart SpeechCommand = iota
	// SpeechStop has the recognizer finish: a last final result, then
	// the end.
	SpeechStop
	// SpeechAbort ends the session at once, reporting nothing more.
	SpeechAbort
)

type SpeechEvent

type SpeechEvent struct {
	Phase SpeechPhase
	// Text is the whole transcript so far, and Final whether the
	// recognizer will not change it.
	Text  string
	Final bool
	// Error is one of the Speech errors, "" for none.
	Error string
}

SpeechEvent is an EventSpeech's report.

type SpeechPhase

type SpeechPhase uint8

SpeechPhase is what an EventSpeech reports of its session.

const (
	// SpeechStarted says the recognizer listens.
	SpeechStarted SpeechPhase = iota
	// SpeechResult carries the whole transcript so far.
	SpeechResult
	// SpeechEnded ends the session with the last transcript, and Error
	// when it failed. A platform reports it once, last.
	SpeechEnded
)

type SpeechRequest

type SpeechRequest struct {
	Command SpeechCommand
	// Lang is a BCP 47 tag for SpeechStart.
	Lang string
	// Interim reports results before they are final.
	Interim bool
}

SpeechRequest is an ItemSpeech's request.

type SpringConfig

type SpringConfig struct {
	Stiffness, Damping, Mass float64
	Velocity                 float64
}

SpringConfig is a damped spring's: Stiffness 100, Damping 10 and Mass 1 when 0. Velocity, in units per second, replaces the value's current velocity when it is not 0.

type StatusBarConfig

type StatusBarConfig struct {
	// Style is never StatusBarInherit.
	Style    StatusBarStyle
	Hidden   bool
	Animated bool
}

StatusBarConfig is the status bar the platform shows (ItemStatusBar).

type StatusBarStyle

type StatusBarStyle uint8

StatusBarStyle is the color of a phone's status bar content.

const (
	// StatusBarInherit keeps the style of the layers below.
	StatusBarInherit StatusBarStyle = iota
	// StatusBarAuto follows the appearance: dark content on light.
	StatusBarAuto
	StatusBarDark
	StatusBarLight
)

type StepPosition

type StepPosition uint8

StepPosition is where a steps easing jumps, as CSS's step positions.

const (
	// JumpEnd holds each step to its end: steps(n, end), the default.
	JumpEnd StepPosition = iota
	// JumpStart jumps at each step's start.
	JumpStart
	// JumpNone holds the first and the last value a step each.
	JumpNone
	// JumpBoth jumps at the start and the end.
	JumpBoth
)

type StickyCell

type StickyCell struct {
	Cell       NodeID
	Start, End Points
	// Node, when set, is the animated node the cell's inset from the
	// viewport's start follows, in place of Inset, which Start counts.
	Node  uint32
	Inset Points
}

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

func (StickyCell) StickyShift

func (c StickyCell) StickyShift(offset Points) Points

StickyShift is how far a sticky cell moves from its frame along the main axis at offset.

type StorageBackend

type StorageBackend interface {
	// Load returns the entries kept, read once when the app first uses
	// its storage. An error leaves the app with none, logged.
	Load() (map[string]string, error)
	// Write keeps change. It is called in order, on the goroutine of the
	// graph that made the change; a backend that blocks writes elsewhere.
	Write(change StorageChange)
}

StorageBackend is where a platform keeps an app's entries: a file in the app's data directory, the browser's localStorage.

type StorageChange

type StorageChange struct {
	Op         StorageOp
	Key, Value string
}

StorageChange is a change to the entries, for the backend to keep.

type StorageOp

type StorageOp uint8

StorageOp says what a StorageChange does.

const (
	// StorageSet sets Key to Value.
	StorageSet StorageOp = iota
	// StorageRemove removes Key.
	StorageRemove
	// StorageClear removes every entry.
	StorageClear
)

type SubmitBehavior

type SubmitBehavior uint8

SubmitBehavior is what Return does in a text field.

const (
	// SubmitBehaviorDefault inserts a line break in a multiline field,
	// and blurs and submits in a single line.
	SubmitBehaviorDefault SubmitBehavior = iota
	// SubmitBehaviorSubmit reports OnSubmit and keeps the focus.
	SubmitBehaviorSubmit
	// SubmitBehaviorBlurAndSubmit reports OnSubmit and takes the focus
	// away.
	SubmitBehaviorBlurAndSubmit
	// SubmitBehaviorNewline inserts a line break in a multiline field; a
	// single line blurs and submits.
	SubmitBehaviorNewline
)

type SurfaceConfig

type SurfaceConfig struct {
	// ID numbers the surface's tree, which the platform attaches.
	ID   uint32
	Kind SurfaceKind
	// Title is a window's; empty is the app's name.
	Title string
	// Width and Height are the content's size in points; zero is the
	// platform's default.
	Width, Height Points
	// Frame, when it moves, places a window instead of centering it,
	// kept on a screen (WindowFrame.OnScreen).
	Frame WindowFrame
	// Hidden opens it without showing it, as panels open.
	Hidden bool
	// Focusable, Passive and Accessible are a SurfaceOverlay's input modes: it takes the focus as well as touches, lets touches through to the apps below instead, or shows its content to screen readers.
	Focusable, Passive, Accessible bool
	// Material is the material behind the content (WindowSetMaterial).
	Material WindowMaterial
	// Constraints limit a window (WindowSetConstraints).
	Constraints WindowConstraints
	// HideOnBlur hides a panel as it loses the focus, reported with
	// EventWindowHidden.
	HideOnBlur bool
	// NoActivate keeps a panel from ever taking the keyboard or activating the app, shown, focused or clicked.
	NoActivate bool
	// Tray is the tray icon a SurfaceTrayIcon draws.
	Tray uint32
}

SurfaceConfig is a window, a panel or a tray icon's view the app opens (ItemOpenSurface).

type SurfaceKind

type SurfaceKind uint8

SurfaceKind is what an opened surface shows in.

const (
	// SurfaceWindow is a window of the platform's own chrome.
	SurfaceWindow SurfaceKind = iota
	// SurfacePanel is a borderless window that floats over the others, which takes the keyboard without activating the app where the platform can: a tray icon's or a launcher's; or, with NoActivate, never takes it.
	SurfacePanel
	// SurfaceTrayIcon is the view a tray icon draws itself with
	// (TrayConfig.View), in the menu bar on macOS.
	SurfaceTrayIcon
	// SurfaceOverlay is a window over other apps on Android
	// (mobile.OpenOverlay): it takes touches but not the focus unless
	// Focusable, none when Passive, and hides from screen readers unless
	// Accessible. The platform reports the frame it applied in its
	// environment's WindowFrame, and ends it with EventWindowEnded.
	SurfaceOverlay
)

type TaskProgress

type TaskProgress struct {
	State TaskProgressState
	Value float64
	// Call numbers the SetTaskProgress call that sent it, from 1 in the order the app made the calls. A platform that shows one progress for several surfaces, as the Dock tile, a Linux launcher entry and the progress Windows windows show from surfaces without a button, ignores a call older than the one it shows: the surfaces commit in their own order, not in the order of the calls.
	Call uint64
}

TaskProgress is the progress shown on an app icon or taskbar button.

func (TaskProgress) BarFraction

func (p TaskProgress) BarFraction() float64

BarFraction is the fraction a bar drawn for p fills where the platform has no indeterminate or cleared state of its own, as the Dock tile and Unity's LauncherEntry: none for no progress, half for an indeterminate task, which a snapshot cannot animate, and Value otherwise.

type TaskProgressState

type TaskProgressState uint8

TaskProgressState is the state of an app task's platform progress bar.

const (
	TaskProgressNone TaskProgressState = iota
	TaskProgressNormal
	TaskProgressIndeterminate
	TaskProgressPaused
	TaskProgressError
)

type TextAlign

type TextAlign uint8

TextAlign aligns lines of text.

const (
	TextAlignStart TextAlign = iota + 1
	TextAlignCenter
	TextAlignEnd
	// TextAlignJustify stretches every line but a paragraph's last to the
	// box's width, aligned to the start.
	TextAlignJustify
	// TextAlignLeft and TextAlignRight keep their sides right to left,
	// where the others follow the direction. The core sends them as
	// TextAlignStart or TextAlignEnd, by the text's direction.
	TextAlignLeft
	TextAlignRight
)

type TextAttachment

type TextAttachment struct {
	// Offset is the byte offset of its AttachmentRune.
	Offset int
	Size   Size
	Align  VerticalAlign
	// Descent is how far an attachment aligned to the baseline reaches below it: the height of its own baseline above its bottom, as a formula's. 0 puts its bottom on the baseline; other aligns ignore it.
	Descent Points
}

TextAttachment is a view inside a text, sized by layout before the text is prepared. Every engine places it with the same rule: its top Ascent above the baseline, its line reserving Extent, so a line grows where an attachment reaches past the font around it.

func (TextAttachment) Ascent

func (a TextAttachment) Ascent(font FontExtent) Points

Ascent returns how far a's top is above the baseline of a line in font, below it when negative: CSS's vertical-align for a replaced inline box.

func (TextAttachment) Extent

func (a TextAttachment) Extent(font FontExtent) (above, below Points)

Extent returns what a's line reserves for it above and below the baseline, each at least 0. Engines give the placeholder these metrics and draw its top Ascent above the baseline.

type TextBackground

type TextBackground struct {
	Color Color
	// Radius rounds each line's box, at most to half its height.
	Radius Points
}

TextBackground is the background of a span, from its style's Background and CornerRadius. It is drawing only: it changes no line.

type TextBaseline

type TextBaseline uint8

TextBaseline is the line of a text that the point it is drawn at sits on, as the web's textBaseline.

const (
	BaselineAlphabetic TextBaseline = iota
	BaselineTop
	BaselineHanging
	BaselineMiddle
	BaselineIdeographic
	BaselineBottom
)

type TextContent

type TextContent struct {
	// Text is the plain text, for accessibility.
	Text string
	// Layout is the platform's TextLayout, ready to draw. The platform
	// owns it from now on and releases the one it replaces.
	Layout TextLayout
	// Content is where Layout goes in the view: inside padding and border.
	Content Bounds
	// Style, Spans, Shadow, MaxLines and Ellipsize are the text's, as it
	// was prepared, for tests to read; platforms draw Layout and read
	// Spans' links for presses.
	Style     TextStyle
	Spans     []TextSpan
	Shadow    TextShadow
	MaxLines  int
	Ellipsize EllipsizeMode
}

TextContent is a text view's content, laid out by the engine.

type TextDecoration

type TextDecoration uint8

TextDecoration draws lines on text; the values combine.

const (
	TextDecorationNone        TextDecoration = 1 << iota
	TextDecorationUnderline                  // underline
	TextDecorationLineThrough                // strikethrough
)

type TextDecorationStyle

type TextDecorationStyle uint8

TextDecorationStyle is how a text's decoration lines are drawn; the zero value is solid.

const (
	DecorationSolid TextDecorationStyle = iota + 1
	DecorationDouble
	DecorationDotted
	DecorationDashed
	DecorationWavy
)

type TextEngine

type TextEngine interface {
	// Prepare shapes text once; the result measures it at any number of
	// widths and lays it out at its final size.
	Prepare(text *AttributedText) PreparedText
}

TextEngine prepares text for layout. The engine calls it on its own goroutine, so implementations must not touch main-thread-only objects.

type TextHitTester

type TextHitTester interface {
	// HitTest returns the caret nearest p: on the line at p's height (the
	// first line above the text, the last below it), at the character
	// edge nearest p's x. A point past the end of a wrapped line gives the
	// line's end, Upstream, so the caret stays on that line.
	HitTest(p Point) Caret
	// CaretRect returns the caret at c: a box of no width as high as its
	// line, at the edge of the characters c stands between; false when
	// the layout has no lines.
	CaretRect(c Caret) (Bounds, bool)
	// RangeRects appends to out the line-high boxes covering the
	// characters from UTF-16 offset start to end: per line, one box per
	// run of adjacent characters (several where bidirectional text splits
	// the range), and through the line's end where the range goes on past
	// it. out is the caller's, so a selection drawn often reuses it.
	RangeRects(start, end int, out []Bounds) []Bounds
}

TextHitTester is a TextLayout that knows where its characters are. Its methods are safe on the engine goroutine and the main thread, also after the layout was released: what they read before stays, and a layout released unread answers as an empty text.

type TextLayout

type TextLayout interface {
	Release()
}

TextLayout is a platform's laid-out text, drawn on the main thread and released there when replaced or deleted.

type TextLine

type TextLine struct {
	// Text is its characters, from byte Start to byte End of the text.
	Text       string
	Start, End int
	// Bounds is its box in the text's content box: its typographic width
	// and its height.
	Bounds Bounds
	// Ascender and Descender reach above and below its baseline;
	// CapHeight and XHeight are the heights of its font's capitals and
	// lowercase letters.
	Ascender, Descender Points
	CapHeight, XHeight  Points
}

TextLine is a line of laid-out text, as Text.OnTextLayout reports it.

type TextMetrics

type TextMetrics struct {
	Width, Ascent, Descent, LineHeight float32
}

TextMetrics are a text's measurements in a font: its advance width, and how far its font reaches above and below the baseline, as the line it is laid out on reports them.

type TextPosition

type TextPosition struct {
	Text, Offset int
}

TextPosition is a place in the texts of an area: a text, by its index in document order, and a UTF-16 offset in it.

type TextRange

type TextRange struct {
	Start, End int
}

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 TextShadow

type TextShadow struct {
	Color  Color
	Offset Point
	// Radius blurs it, as a view's ShadowRadius does.
	Radius Points
}

TextShadow is a shadow behind a text's glyphs; a zero Color is none.

type TextSpan

type TextSpan struct {
	Start, End int
	Style      TextStyle
	// Cursor is the pointer's look over the span's visible characters, ahead of the text view's own; Auto leaves the view's.
	Cursor Cursor
	// Link marks a span with a press handler: a press on it reports
	// EventPress with Index set to a byte offset inside it.
	Link bool
	// Hidden hides the span in place, as CSS's visibility: hidden on an
	// inline element: its characters lay out as visible ones, but
	// nothing of them is drawn, they take no press, and copies and screen
	// readers leave them out. It changes no line. The core draws it in a
	// transparent color with no background, so an engine that does not
	// skip it draws nothing.
	Hidden bool
	// Background is drawn behind the span's characters: a box per line
	// from the font's ascent to its descent, behind the selection and
	// the glyphs.
	Background TextBackground
	// Copy is what a copy takes in place of the attachment the span styles, as a formula copies as its TeX; empty leaves the attachment out. Screen readers read the attachment's label instead (ShownText).
	Copy string
}

TextSpan styles the bytes from Start to End of an AttributedText.

type TextStyle

type TextStyle struct {
	Font  Font
	Color Color
	// LineHeight is the height of a line; 0 is the font's.
	LineHeight    Points
	LetterSpacing Points
	// Align places lines; TextAlignStart is the left, or the right when
	// RTL.
	Align TextAlign
	// RTL makes the paragraphs' base direction right to left, for the
	// order of mixed-direction runs and where lines start.
	RTL        bool
	Decoration TextDecoration
	// DecorationStyle is how Decoration's lines are drawn, solid when 0;
	// DecorationColor colors them, Color when 0.
	DecorationStyle TextDecorationStyle
	DecorationColor Color
	// DecorationThickness is how thick Decoration's lines are, the
	// font's when 0.
	DecorationThickness Points
	// UnderlineOffset is how far below the baseline an underline's top
	// is; auto is where the font puts it.
	UnderlineOffset Length
	// Transform is the core's TextTransform, which it applied to the
	// text already: platforms draw the text as given, tests read it.
	Transform uint8
}

TextStyle is resolved text style: nothing in it is unset.

type TimingConfig

type TimingConfig struct {
	Duration time.Duration
	Easing   Easing
	Delay    time.Duration
}

TimingConfig is a timing animation's: Duration (500 ms when 0) along Easing, after Delay.

type TitleBarStyle

type TitleBarStyle uint8

TitleBarStyle is whether the system draws the window's title bar.

const (
	// TitleBarDefault is the system's title bar, above the app.
	TitleBarDefault TitleBarStyle = iota
	// TitleBarHidden lets the app fill the window up to its top edge and
	// draw its own title bar. The system's window controls stay, in the
	// area Env.TitleBar reports.
	TitleBarHidden
)

type Touch

type Touch struct {
	// ID tells the finger while it is down.
	ID int
	// Position is in the view hearing the event, PagePosition in the
	// surface.
	Position     Point
	PagePosition Point
	// Changed says the event is about this finger: it went down, moved
	// or lifted.
	Changed bool
}

Touch is one finger of a TouchEvent.

type Transform

type Transform struct {
	TranslateX, TranslateY Points
	// TranslateXPercent and TranslateYPercent move the view by percentages
	// of its own width and height, which the core adds to TranslateX and
	// TranslateY each time the size changes.
	TranslateXPercent, TranslateYPercent float32
	// Scale scales both axes; ScaleX and ScaleY one each. 0 is unset (1).
	Scale, ScaleX, ScaleY float32
	// Rotate is in degrees, clockwise. RotateX and RotateY turn the view
	// out of its plane around the horizontal and vertical axes, which
	// shows depth only with a Perspective, its own or its parent's.
	Rotate, RotateX, RotateY float32
	// RotateZ turns the view in its plane after RotateX and RotateY: the
	// transform property's rotateZ, where Rotate is CSS's rotate property,
	// which goes before them.
	RotateZ float32
	// SkewX and SkewY slant the view along each axis, in degrees.
	SkewX, SkewY float32
	// Perspective is the distance the view is seen from, for its own
	// rotations out of its plane; 0 is none.
	Perspective Points
	// Then is a matrix applied after all of those, for what they cannot
	// say: functions in an order of the app's, as CSS's transform lists.
	// Its zero value is none.
	Then Matrix3D
}

Transform moves, scales, rotates and skews a view without changing its layout, around its transform origin (its center unless the style says), in CSS's order: perspective, translate, rotate, rotateX, rotateY, skew, then scale. The zero value changes nothing.

func (Transform) Flat

func (t Transform) Flat() bool

Flat reports whether t stays in the view's plane, a 2D affine transform.

func (Transform) InPlane

func (t Transform) InPlane() Transform

InPlane returns what t does in the view's plane as one translation, rotation and scale around the view's origin, for platforms that have only those: Then joins the rest, and its depth and shear are lost.

func (Transform) Matrix

func (t Transform) Matrix(origin Point) Matrix3D

Matrix returns t as a matrix acting around origin, a point in the view's own coordinates (its top left at 0, 0).

func (Transform) Scales

func (t Transform) Scales() (x, y float32)

Scales returns the x and y scale factors.

type Transition

type Transition struct {
	Duration time.Duration
	Delay    time.Duration
	Easing   Curve
	// Properties lists what animates; every property but
	// TransitionLayout when 0.
	Properties TransitionProperty
}

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.

func (Transition) Layout

func (t Transition) Layout() *LayoutTransition

Layout returns how t moves a view's frame (TransitionLayout).

type TransitionProperty

type TransitionProperty uint8

TransitionProperty is a set of animatable properties.

const (
	TransitionOpacity TransitionProperty = 1 << iota
	TransitionBackground
	TransitionTransform
	TransitionBorder
	TransitionShadow
	// TransitionLayout moves and resizes the view from where it shows
	// when a change to its own style changes its frame. Its children take
	// their new frames inside it at once.
	TransitionLayout
)

type TrayConfig

type TrayConfig struct {
	ID uint32
	// Icon is the icon as PNG, drawn in the menu bar's colors when
	// Template, on macOS.
	Icon     []byte
	Template bool
	// Title is text beside the icon, on macOS.
	Title   string
	Tooltip string
	// View, when set, is the SurfaceTrayIcon the icon draws itself with.
	View uint32
	// Removed takes the icon away.
	Removed bool
}

TrayConfig is a tray icon (ItemTray).

type TreeFile

type TreeFile struct {
	Path     string
	Size     int64
	Modified time.Time
	Open     func() (io.ReadSeekCloser, error)
}

TreeFile is a file of a folder the platform lists whole, as the web's <input webkitdirectory> does: its path, slash-separated inside the folder, and how it opens.

type Update

type Update struct {
	App, Current                     string
	Version, URL                     string
	Download, Signature, SHA256, Key string
	Size                             int64
	Err                              string
}

Update is what a platform's updater with no windows of its own found (EventUpdate): the app's name and running version, and a newer version with the page and verified download that gets it, Version empty when the running one is the newest, or why it could not check.

type UpdateDownloadProgress

type UpdateDownloadProgress struct{ Loaded, Total int64 }

UpdateDownloadProgress reports bytes received by a platform update downloader.

type VerticalAlign

type VerticalAlign uint8

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. Its line grows to hold it wherever it reaches past that font.

const (
	// VerticalAlignBaseline puts its bottom on the baseline, or its own baseline where it has one (TextAttachment.Descent); it is the default.
	VerticalAlignBaseline VerticalAlign = iota + 1
	// VerticalAlignTextTop puts its top at the font's ascent.
	VerticalAlignTextTop
	// VerticalAlignTextBottom puts its bottom at the font's descent.
	VerticalAlignTextBottom
	// VerticalAlignMiddle puts its middle half the font's x height above
	// the baseline.
	VerticalAlignMiddle
)

type VerticalBarEdge

type VerticalBarEdge uint8

VerticalBarEdge is the edge where the system places a vertical bar.

const (
	// VerticalBarUnspecified is a system without a preferred edge, or one that places no vertical bar.
	VerticalBarUnspecified VerticalBarEdge = iota
	VerticalBarLeading
	VerticalBarTrailing
)

type VideoConfig

type VideoConfig struct {
	Source           string
	Paused           bool
	Muted            bool
	Volume           float32
	Rate             float32
	Repeat           bool
	ResizeMode       ResizeMode
	Controls         bool
	ProgressInterval time.Duration
	AudioSession     AudioSession
}

VideoConfig is everything a video plays with (ItemVideo), with the defaults applied: Volume in 0 to 1, Rate above 0, a ResizeMode and ProgressInterval at least 16 milliseconds.

type ViewKind

type ViewKind uint8

ViewKind is the kind of native view a node mounts.

const (
	// KindView is a container: background, border, corners and presses.
	KindView ViewKind = iota + 1
	// KindText draws a TextLayout the engine prepared.
	KindText
	// KindInput is the platform's text field.
	KindInput
	// KindScroll scrolls its children; ItemScrollContent sizes them.
	KindScroll
	// KindImage shows an image the platform loads (ItemImage).
	KindImage
	// KindModal is a layer covering the root view or an outer modal,
	// presented when inserted and dismissed when removed (ItemModal).
	KindModal
	// KindCanvas plays a Drawing (ItemCanvas).
	KindCanvas
	// KindWeb hosts the platform's web view, filling it (ItemWeb).
	KindWeb
	// KindVideo hosts the platform's video player, filling it (ItemVideo).
	KindVideo
	// KindNative hosts a view of a component the app registered, filling
	// it (ItemNative).
	KindNative
	// KindShader fills itself with a fragment shader on the GPU
	// (ItemShader).
	KindShader
)

func (ViewKind) String

func (k ViewKind) String() string

String names the kind as traces print it.

type ViewPaint

type ViewPaint struct {
	Op   int
	Kind ViewPaintKind
	// Initial is what a fill or stroke paints with where no view sets
	// one.
	Initial Paint
	// Area is the box a background is placed over.
	Area Bounds
}

ViewPaint is an op of a drawing whose value is its view's paint.

type ViewPaintKind

type ViewPaintKind uint8

ViewPaintKind is the paint property a ViewPaint takes.

const (
	ViewFill ViewPaintKind = iota
	ViewStroke
	ViewStrokeWidth
	ViewStrokeDash
	// ViewBackground fills with the view's background: a fill the core
	// expands into one for its color and one for each gradient.
	ViewBackground
)

type ViewProps

type ViewProps struct {
	Role Role
	// Level is a heading's or a tree item's level, from 1; 0 for none.
	Level int
	Label string
	// Description says more about the element, read after its name, as
	// ARIA's aria-description; Hint says what activating it does.
	Description string
	Hint        string
	Disabled    bool
	// Selected, Checked and Indeterminate (mixed) are reported to
	// assistive technology, and Expanded when Expandable.
	Selected      bool
	Checked       bool
	Indeterminate bool
	// Pressed is a toggle that is on and Busy an element still loading;
	// Invalid a field whose content the app rejected (aria-invalid).
	Pressed    bool
	Busy       bool
	Invalid    bool
	Expandable bool
	Expanded   bool
	// Value is a range's or a textual element's value.
	Value AccessibilityValue
	// Accessible makes the view one element, or none.
	Accessible Accessible
	// ElementsHidden hides the view and its subtree from assistive
	// technology.
	ElementsHidden bool
	LiveRegion     LiveRegion
	// Actions are the actions offered to assistive technology, reported
	// with EventAccessibilityAction. The list is shared and never changed,
	// so ViewProps stay comparable; read it with ActionList.
	Actions *[]AccessibilityAction
	TestID  string
	// WindowDrag, PanActivation and selections are decided on the main
	// thread.
	WindowDrag    WindowDrag
	PanActivation PanActivation
	// PanScrollHandoff: the view's pan shares a drag with the scroll view
	// inside it where the drag starts, on iOS (View.PanScrollHandoff).
	PanScrollHandoff bool
	// SelectionArea is a view's, Selectable and SelectionColor a text's.
	SelectionArea  bool
	Selectable     Selectable
	SelectionColor Color
	// NoFocus keeps a pressable view out of the Tab stops, and Focusable
	// makes a Tab stop of a view that takes no presses.
	NoFocus, Focusable bool
	// TabAfter is a shown dialog overlay's place in the Tab order, the
	// view it follows, before that view's children: the native view
	// right before it where the app put it, as WAI-ARIA's non-modal
	// popups follow their trigger. Backends that order Tab themselves
	// take it; the toolkits ordering it by their own trees (AppKit's key
	// view loop, the browser's DOM) leave the overlay where it is.
	TabAfter NodeID
	// Appearance is the one its subtree forces (Scope.SetSubtreeAppearance),
	// for the platform's views in it; AppearanceSystem follows the window.
	Appearance Appearance
	// PointerEvents, HitSlop and DelayLongPress are the view's; a zero
	// DelayLongPress is the platform's 500 ms.
	PointerEvents  PointerEvents
	HitSlop        Edges
	DelayLongPress time.Duration
	// Ripple is Android's press ripple, nil for none. It is shared and
	// never changed, as Actions is.
	Ripple *Ripple
}

ViewProps is a view's accessibility and identity.

func (*ViewProps) ActionList

func (p *ViewProps) ActionList() []AccessibilityAction

ActionList returns p's actions.

func (*ViewProps) HasAction

func (p *ViewProps) HasAction(name string) bool

HasAction reports whether p offers the action named name.

func (*ViewProps) HelpText

func (p *ViewProps) HelpText() string

HelpText is what a platform with one place for what is read after the name reads there: the description, then the hint, each a sentence.

type ViewStyle

type ViewStyle struct {
	Background Color
	// CornerRadius rounds every corner, unless Corners is set: then each
	// corner has its own radius. Platforms fit radii that do not fit
	// with Corners.Fit.
	CornerRadius Points
	Corners      Corners
	// ContinuousCorners eases the corners into the edges (RoundedRect)
	// instead of drawing quarter circles.
	ContinuousCorners bool
	// BorderWidth and BorderColor are the border on every side, unless
	// Borders is set: then each side has its width there and its color
	// in BorderColors.
	BorderWidth  Points
	BorderColor  Color
	Borders      Edges
	BorderColors EdgeColors
	// BorderStyle dashes or dots the border; 0 is solid.
	BorderStyle BorderStyle
	Outline     Outline
	Opacity     float32
	// Clip clips children to the bounds and corners.
	Clip         bool
	ShadowColor  Color
	ShadowOffset Point
	ShadowRadius Points
	// TintColor recolors an image's opaque pixels; 0 keeps its colors.
	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
	// Transform moves, scales and rotates the view around its transform
	// origin without moving its children's frames; hit testing follows
	// it. The core has resolved its percentages.
	Transform Transform
	// Origin is where the transform acts, from the view's center, and
	// OriginZ how far toward the viewer.
	Origin  Point
	OriginZ Points
	// BackfaceHidden hides the view while its rotations turn its back to
	// the viewer.
	BackfaceHidden bool
	// ChildPerspective, when set, is the depth children's rotations out
	// of the plane are seen from, at the view's center (ChildPerspective
	// the function).
	ChildPerspective Points
	BlendMode        BlendMode
	// Material and Glass are how iOS draws a backdrop blur.
	Material BackdropMaterial
	// Elevation is Android's: how high the view floats, which casts the
	// system's shadow under it where the style casts none.
	Elevation Points
	Glass     GlassEffect
	// Effects are shadows, gradients, filters and masks, nil without any.
	Effects *Effects
	// Transition, when it has a duration, animates the change from the
	// previous ViewStyle to this one.
	Transition Transition
	// Animation runs keyframes over the view while it is set; a change
	// starts it again.
	Animation KeyframeAnimation
	// Hidden hides the view and its children (display none, visibility
	// hidden).
	Hidden bool
}

ViewStyle is everything a platform draws for a view itself.

func MixStyles

func MixStyles(from, to ViewStyle, t float64, props TransitionProperty) ViewStyle

MixStyles returns the style shown t of the way from from to to, moving only the properties props lists and taking to's for the rest.

func (*ViewStyle) Matrix

func (vs *ViewStyle) Matrix(size Size) Matrix3D

Matrix returns the view's transform for a box of size, around its origin.

func (*ViewStyle) Radii

func (vs *ViewStyle) Radii(size Size) Corners

Radii returns the radius of each corner, fitted to size.

func (*ViewStyle) Rim

func (vs *ViewStyle) Rim() (rim Color, inset Points, ok bool)

Rim is how a rounded view with a fill and one solid border, either of them opaque, keeps the fill from showing past it. Drawn as CSS says, both reach the box's edge, and an edge pixel a curve covers partly takes the fill's color before the border's. So the fill stops inset under the border, and the border is rim, what it shows over the fill, the outer edge being the border's alone. Inset most of the border's width, a line one pixel wide keeps the two apart too, and the rest closes the seam inside. Browsers do the same for CSS; ok is false where nothing needs it or the border must let what is under it show.

func (*ViewStyle) Rounded

func (vs *ViewStyle) Rounded() bool

Rounded reports whether some corner is rounded.

type WebCommand

type WebCommand uint8

WebCommand is what ItemWebCommand asks a web view to do.

const (
	WebReload WebCommand = iota + 1
	WebGoBack
	WebGoForward
	WebStopLoading
	// WebPostMessage dispatches a MessageEvent carrying Value on the
	// page's window.
	WebPostMessage
	// WebInjectJavaScript runs Value in the page.
	WebInjectJavaScript
	// WebSendInput gives the page Data, a *WebInput, as the user's own
	// input.
	WebSendInput
)

type WebConfig

type WebConfig struct {
	Source                          WebSource
	InjectedJavaScript              string
	InjectedJavaScriptBeforeContent string
	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. Platforms read
	// this when the native view is first made.
	Incognito bool
	// SchemeHandlers are app-owned URL schemes and their response bodies.
	// Platforms read them when the native view is first made.
	SchemeHandlers      map[string]func(string) []byte
	NoScroll            bool
	NoJavaScript        bool
	BackForwardGestures bool
	// DownloadDir is where the view saves what its pages download, a
	// directory of its own for each (<id>/<file name>); "" saves nothing.
	DownloadDir string
	// Restricted has the platform refuse the top-level navigations
	// Navigable refuses, as they start, reporting EventError.
	Restricted bool
	// Hosts are the hosts Navigable allows, space-separated patterns:
	// "*", "*.example.com" or a host.
	Hosts string
	// Media is what the pages may capture through getUserMedia; the
	// platform refuses the rest as the page asks.
	Media WebMedia
}

WebConfig is everything a web view loads and allows (ItemWeb). Platforms load the source again when it or the scripts change.

func (*WebConfig) Navigable

func (c *WebConfig) Navigable(rawURL string) bool

Navigable reports whether a restricted view's page may navigate to rawURL at its top level: a page of its own (about:, data:, blob:), or an http or https one of a host Hosts allows. Other schemes, file: among them, are refused.

type WebDownload

type WebDownload struct {
	State    WebDownloadState
	ID       string
	URL      string
	Filename string
	Path     string
	Bytes    int64
	Message  string
}

WebDownload is a download of a web view: its State, and where it is saved. Bytes is what it wrote once finished, and Message why it failed.

type WebDownloadState

type WebDownloadState uint8

WebDownloadState is how far a WebDownload got.

const (
	WebDownloadStarted WebDownloadState = iota
	WebDownloadFinished
	WebDownloadFailed
)

type WebInput

type WebInput struct {
	Kind WebInputKind
	// Point is a click's, in CSS pixels from the viewport's top left, as
	// getBoundingClientRect reports.
	Point Point
	// Text is what WebInputText types.
	Text string
	// Key is what WebInputKey presses, as KeyboardEvent.key names it:
	// Enter, Tab, Escape or Backspace.
	Key string
}

WebInput is input a web view's page takes as the user's hands give it: its events are trusted (isTrusted), which no script it runs can make.

type WebInputKind

type WebInputKind uint8

WebInputKind is what a WebInput gives.

const (
	// WebInputClick is a primary click at Point.
	WebInputClick WebInputKind = iota
	// WebInputText types Text into what has the page's focus.
	WebInputText
	// WebInputKey presses and releases Key.
	WebInputKey
)

type WebMedia

type WebMedia uint8

WebMedia is a set of the devices a web view's pages may capture.

const (
	WebMicrophone WebMedia = 1 << iota
	WebCamera
)

func (WebMedia) Allows

func (m WebMedia) Allows(want WebMedia) bool

Allows reports whether m holds every device of want, so a page asking for both gets neither unless both are allowed.

type WebNavigation

type WebNavigation struct {
	URL          string
	Title        string
	Loading      bool
	CanGoBack    bool
	CanGoForward bool
}

WebNavigation is a web view's page and history.

type WebSource

type WebSource struct {
	Src     string
	HTML    string
	BaseURL string
}

WebSource is what a web view shows: the page at Src, or HTML, whose relative links resolve against BaseURL, instead when it is set.

func (WebSource) Origin

func (s WebSource) Origin() string

Origin is the origin of the page the source loads, as WebOrigin writes it: Src's, or for HTML, BaseURL's, which is "null" without one. A source with neither has none ("").

func (WebSource) Shows

func (s WebSource) Shows(rawURL string) bool

Shows reports whether rawURL is the page s loads, which tells apart the pages of an opaque origin ("null"), as every one of them has the same: HTML without a base URL is at about:blank (about:srcdoc on the web), other HTML at BaseURL and a Src at itself, fragments aside. A page the view went to, such as a data: URL a frame sent it to, is not.

type WindowAction

type WindowAction uint8

WindowAction is what an ItemWindow asks of the window.

const (
	// WindowSetTitleBar shows or hides the title bar (TitleBar, Height).
	WindowSetTitleBar WindowAction = iota + 1
	WindowMinimize
	// WindowToggleMaximize maximizes the window, or restores it.
	WindowToggleMaximize
	WindowToggleFullScreen
	// WindowClose closes the window as its close button does.
	WindowClose
	// WindowSetFrame moves and sizes the window (Frame).
	WindowSetFrame
	// WindowSetLevel puts the window at Level.
	WindowSetLevel
	// WindowOrderFront brings the window to the front of its level, showing it, and activates the app; a panel without the focus (SurfaceConfig.NoActivate) comes to the front alone.
	WindowOrderFront
	// WindowSetMenuBar says when Windows and Linux show the menu bar
	// (MenuBar).
	WindowSetMenuBar
	// WindowSetControls places or hides the window controls of a hidden
	// title bar (Controls).
	WindowSetControls
	// WindowSetMaterial puts Material behind the window's content.
	WindowSetMaterial
	// WindowSetConstraints limits the window's size and what the user may
	// do to it (Constraints).
	WindowSetConstraints
	// WindowShow shows a hidden window without activating the app; a panel shows beside AnchorBounds when Placement is set, else under tray icon Anchor when that is set, and takes the keyboard unless SurfaceConfig.NoActivate keeps it from it.
	WindowShow
	// WindowHide hides the window, keeping it and its views.
	WindowHide
	// WindowDestroy closes an opened surface's window for good: its tree
	// is gone.
	WindowDestroy
	// WindowSetAnchor places a panel beside AnchorBounds on Placement's side, moving it at once if it shows, and keeps the placement for later shows; it changes neither whether it shows nor the focus.
	WindowSetAnchor
)

type WindowCommand

type WindowCommand struct {
	Action   WindowAction
	TitleBar TitleBarStyle
	// Height is the custom title bar's height, in which the platform
	// centers its window controls; 0 is the platform's.
	Height   Points
	Frame    WindowFrame
	Level    WindowLevel
	MenuBar  MenuBarMode
	Controls WindowControls
	Material WindowMaterial
	// Constraints are what WindowSetConstraints sets.
	Constraints WindowConstraints
	// Anchor is the tray icon WindowShow shows a panel under.
	Anchor uint32
	// AnchorBounds is the rectangle, in the screen coordinates of DisplayInfo, that WindowShow and WindowSetAnchor place a panel beside, on Placement's side; WindowPlaceDefault places none.
	AnchorBounds Bounds
	Placement    WindowPlacement
}

WindowCommand is an ItemWindow's request.

type WindowConstraints

type WindowConstraints struct {
	MinWidth, MinHeight Points
	MaxWidth, MaxHeight Points
	// NoResize keeps the user from resizing the window, and so from
	// maximizing it; WindowSetFrame still sizes it.
	NoResize bool
	// NoMinimize keeps the window from minimizing.
	NoMinimize bool
	// NoMaximize keeps the window from maximizing, and on macOS, where
	// the same button goes full screen, from full screen.
	NoMaximize bool
}

WindowConstraints limit a window's content size, in points, and what the user may do to it; the zero value limits nothing. A size of 0 has no limit, and a maximum under the minimum takes the minimum. Full screen goes past the sizes.

func (WindowConstraints) Clamp

func (c WindowConstraints) Clamp(size Size) Size

Clamp returns size within c's sizes, which c.Normalized returned.

func (WindowConstraints) Normalized

func (c WindowConstraints) Normalized() WindowConstraints

Normalized returns c with its negative sizes 0, its maximums at least its minimums and NoResize implying NoMaximize.

type WindowControls

type WindowControls struct {
	// Hidden takes the controls away for the app to draw its own, which
	// call MinimizeWindow, ToggleMaximize and CloseWindow; Env.TitleBar
	// then reports no width at its ends.
	Hidden bool
	// TrafficLights puts the top left corner of macOS's close button
	// this far from the window's top left corner, in points, the other
	// two after it. A zero X keeps them 16 points in, and a zero Y
	// centers them in the title bar.
	TrafficLights Point
	// Offset moves the traffic lights this far from where TrafficLights
	// puts them, so they follow what moves beside them without the app
	// knowing their size.
	Offset Point
}

WindowControls is how a hidden title bar shows the system's window controls: macOS's traffic lights and the caption buttons NSGo draws on Windows. Linux draws none.

type WindowDrag

type WindowDrag uint8

WindowDrag marks a view as a handle that moves the desktop window, or keeps a view inside such a handle clickable. The nearest view that sets it decides; inputs and views with press or gesture handlers nearer than it stay clickable either way.

const (
	// WindowDragInherit follows the views around it.
	WindowDragInherit WindowDrag = iota
	// WindowDragOn drags the window, and a double click zooms it as the
	// system's title bar does.
	WindowDragOn
	// WindowDragOff keeps presses on the view for the app.
	WindowDragOff
)

type WindowFrame

type WindowFrame struct {
	X, Y          Points
	Move          bool
	Width, Height Points
	// Animated animates the change with macOS's resize animation.
	Animated bool
}

WindowFrame is where a window moves and how large it becomes, in points. X and Y place its top left corner from the main screen's top left, y growing down, on every platform; without Move the corner stays where it is, so a window that changes height keeps its top edge. Width and Height are its outer size, borders and title bar included (the default size GTK keeps on Linux); 0 keeps the current one.

func (WindowFrame) OnScreen

func (f WindowFrame) OnScreen(screens []Bounds) WindowFrame

OnScreen returns f when one of screens, the usable areas of the connected screens in f's coordinates, shows enough of its top edge to drag it, as a screen that went away does not. Else f shrinks to fit the first screen and centers on it.

func (WindowFrame) Within

func (f WindowFrame) Within(area Bounds) WindowFrame

Within returns f kept wholly in area, as an overlay keeps to the screen's usable area: no larger than it, and moved in where it pokes out; one that does not move centers on it.

type WindowLevel

type WindowLevel uint8

WindowLevel is where a window stacks among the others.

const (
	// WindowLevelNormal is the level of ordinary windows.
	WindowLevelNormal WindowLevel = iota
	// WindowLevelFloating stays above normal windows, as a palette does.
	WindowLevelFloating
	// WindowLevelDesktop sits with the desktop's icons on macOS, on every
	// space and out of Mission Control; Windows puts the window at the
	// bottom of the others, where activating it raises it again.
	WindowLevelDesktop
)

type WindowMaterial

type WindowMaterial uint8

WindowMaterial is a translucent material behind a desktop window's content, where the app draws nothing opaque. macOS shows a system vibrancy material; Windows 11 22H2 and later shows Mica, Acrylic or Mica Alt, choosing the closest backdrop for the other names. Other platforms keep the window opaque.

The window starts with nsgo.WindowMaterial's and changes it with WindowSetMaterial; Windows shows one only in a window started with one. Env.WindowMaterial reports the one the window actually shows. What the app draws over the material decides how much shows: a view with an opaque background hides it, and one with no background, or a translucent one, lets it through.

const (
	// WindowMaterialNone keeps the window opaque.
	WindowMaterialNone WindowMaterial = iota
	// The materials of window areas.
	WindowMaterialWindow
	WindowMaterialContent
	WindowMaterialSidebar
	WindowMaterialHeader
	WindowMaterialTitlebar
	WindowMaterialUnderWindow
	WindowMaterialUnderPage
	// The materials of transient surfaces: menus, popovers, HUD windows,
	// sheets, tooltips, selections and full-screen UI.
	WindowMaterialMenu
	WindowMaterialPopover
	WindowMaterialHUD
	WindowMaterialSheet
	WindowMaterialTooltip
	WindowMaterialSelection
	WindowMaterialFullScreenUI
	// Windows 11's system backdrops. Mica and Tabbed use the under-window
	// material on macOS; Acrylic uses the HUD one.
	WindowMaterialMica
	WindowMaterialAcrylic
	WindowMaterialTabbed
)

type WindowPlacement

type WindowPlacement uint8

WindowPlacement is the side of an anchor rectangle a panel goes on (core.Window.ShowAt), kept apart from core.Placement so that the platforms do not depend on core.

const (
	// WindowPlaceDefault places the panel at no rectangle.
	WindowPlaceDefault WindowPlacement = iota
	WindowPlaceBottom
	WindowPlaceTop
	WindowPlaceLeft
	WindowPlaceRight
)

type Write

type Write struct {
	Site  string
	Count int
}

Write is the signal writes one line made: the app's line, as dir/file.go:line, or for writes NSGo made of its own, as an animation's, NSGo's function that made them.

type ZoomRequest

type ZoomRequest struct {
	Scale  float32
	Center *Point
}

ZoomRequest is ItemZoomTo's: the scale to zoom to, and the content point (unzoomed) to show in the middle of the viewport, or nil to keep the middle where it is.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL