Skip to main content

platform

Package platform provides global singletons for platform services.

It assumes a single application per process. Platform services are initialized during package init and activated when SetNativeBridge is called by the bridge package.

Global Services​

The package exposes singleton services for platform capabilities: Lifecycle, SafeArea, Accessibility, Haptics, Clipboard, etc. These are safe for concurrent use from any goroutine.

Layer Boundary Types​

This package defines its own EdgeInsets struct as a simple 4-field data carrier from native code. This is intentionally separate from [layout.EdgeInsets], which is the canonical app-facing type with rich helper methods (Horizontal, Vertical, Add, etc.). Conversion between the two occurs at the layer boundary in the widgets package (e.g., the SafeArea widget).

Similarly, the PointerEvent/PointerPhase types in the engine package represent raw device-pixel input from embedders, while the gestures package defines its own processed versions with logical coordinates. These duplications are intentional: collapsing them would couple embedder APIs to framework internals.

Variables​

Standard errors for platform channel operations.

var (
// ErrChannelNotFound indicates the requested platform channel does not exist.
ErrChannelNotFound = errors.New("platform channel not found")

// ErrMethodNotFound indicates the method is not implemented on the native side.
ErrMethodNotFound = errors.New("method not implemented")

// ErrInvalidArguments indicates the arguments passed to the method were invalid.
ErrInvalidArguments = errors.New("invalid arguments")

// ErrPlatformUnavailable indicates the platform feature is not available
// (e.g., hardware not present, OS version too old).
ErrPlatformUnavailable = errors.New("platform feature unavailable")

// ErrTimeout indicates the operation exceeded its deadline. For permission requests,
// this means the user did not respond to the dialog within the timeout period.
ErrTimeout = errors.New("operation timed out")

// ErrCanceled indicates the operation was canceled via context cancellation.
ErrCanceled = errors.New("operation was canceled")

// ErrViewTypeNotFound indicates the platform view type is not registered.
ErrViewTypeNotFound = errors.New("platform view type not registered")

// ErrBlocksUIThread indicates the UI thread called a native method that
// replies asynchronously. The UI thread cannot wait for such a reply
// (the reply may need the UI thread), so native refuses the call before
// running it, every time. Call the method from a goroutine and publish
// its result, for example through a Signal.
ErrBlocksUIThread = errors.New("method replies asynchronously; call it from a goroutine, not the UI thread")

// ErrReplyDropped indicates native discarded a method call's reply
// without answering it, a bug in the native handler.
ErrReplyDropped = errors.New("native handler dropped the call without replying")

// ErrNotEncodable indicates native produced a reply or an event that
// is not JSON-like (a NaN, an Infinity, or a type outside null,
// booleans, numbers, strings, lists and string-keyed maps), a bug in
// the native handler. A method call fails with it; an event stream
// delivers it to OnError in place of the event. The message names the
// call or channel and the offending part of the value.
ErrNotEncodable = errors.New("native value is not JSON-like")

// ErrPermissionNotRegistered indicates no native code registered the
// permission kind: the plugin providing it is missing from drift.yaml,
// or not configured for that kind.
ErrPermissionNotRegistered = errors.New("permission kind not registered")

// ErrPermissionNotDeclared indicates the Android manifest does not
// declare a permission the kind needs, so Android would deny it without
// asking. Add the plugin that declares it to drift.yaml.
ErrPermissionNotDeclared = errors.New("permission not declared in the Android manifest")
)

Web view load failures, the same on Android and iOS. A WebViewController's Errors stream delivers them as errors matching these under errors.Is, with the platform's message.

var (
// ErrWebViewNetwork indicates a network-level failure such as DNS
// resolution, connectivity or a timeout.
ErrWebViewNetwork = errors.New("web page could not be reached")

// ErrWebViewSSL indicates a TLS or certificate failure, such as an
// untrusted or expired certificate.
ErrWebViewSSL = errors.New("web page's secure connection failed")

// ErrWebViewLoadFailed indicates any other page load failure.
ErrWebViewLoadFailed = errors.New("web page failed to load")
)

Accessibility is the global accessibility channel instance.

var Accessibility = &accessibilityChannel{
method: NewMethodChannel(accessibilityMethodChannel),
stateEvents: NewEventChannel(accessibilityStateChannel),
actionEvents: NewEventChannel(accessibilityActionsChannel),
}

ClipboardService provides access to the system clipboard.

var Clipboard = &ClipboardService{
channel: NewMethodChannel("drift/clipboard"),
}

ErrChannelNotRegistered is returned when an event is received for an unregistered channel.

var ErrChannelNotRegistered = fmt.Errorf("event channel not registered")

Sentinel errors for platform operations.

var (
// ErrDisposed is returned when a method is called on a controller that
// has already been disposed, or whose underlying resource failed to
// create. Check for this with [errors.Is] when you need to distinguish
// a no-op from a successful operation.
ErrDisposed = errors.New("platform: controller disposed")
)

ErrPickerCancelled is returned when the user cancels the picker.

var ErrPickerCancelled = errors.New("picker cancelled")

ErrStorageBusy is returned when a storage picker is already open.

var ErrStorageBusy = errors.New("storage picker operation already in progress")

HapticsService provides haptic feedback functionality.

var Haptics = &HapticsService{
channel: NewMethodChannel("drift/haptics"),
}

LifecycleService provides app lifecycle state management.

var Lifecycle = &LifecycleService{
channel: NewMethodChannel("drift/lifecycle"),
events: NewEventChannel("drift/lifecycle/events"),
state: LifecycleStateResumed,
handlers: make([]LifecycleHandler, 0),
}

Notifications is the singleton notifications service.

var Notifications = &NotificationsService{Permission: newNotificationPerm()}

Preferences provides simple, unencrypted key-value storage using platform-native mechanisms (UserDefaults on iOS, SharedPreferences on Android). For sensitive data, use SecureStorage instead.

var Preferences = &PreferencesService{
channel: NewMethodChannel("drift/preferences"),
}

SafeArea provides safe area inset management.

var SafeArea = &SafeAreaService{
events: NewEventChannel("drift/safe_area/events"),
insets: EdgeInsets{},
}

ShareService provides access to the system share sheet.

var Share = &ShareService{
channel: NewMethodChannel("drift/share"),
}

Storage is the singleton storage service.

var Storage = &StorageService{channel: NewMethodChannel("drift/storage").WithErrors(ErrorCodes{
"storage_busy": ErrStorageBusy,
"platform_unavailable": ErrPlatformUnavailable,
})}

TextEditingValueEmpty is the default empty editing value.

var TextEditingValueEmpty = TextEditingValue{
Selection: TextSelectionCollapsed(0),
ComposingRange: TextRangeEmpty,
}

TextRangeEmpty is an invalid/empty text range.

var TextRangeEmpty = TextRange{Start: -1, End: -1}

URLLauncher provides access to the system URL launcher.

var URLLauncher = &URLLauncherService{
channel: NewMethodChannel("drift/url_launcher"),
}

func Dispatch​

func Dispatch(callback func()) bool

Dispatch schedules a callback to run on the UI thread. Returns true if the callback was successfully scheduled, false if no dispatch function is registered or the callback is nil.

func GetFocusedTarget​

func GetFocusedTarget() any

GetFocusedTarget returns the render object that currently has keyboard focus.

func HandleEvent​

func HandleEvent(channel string, eventData []byte) error

HandleEvent is called from the bridge when native sends an event.

func HandleEventDone​

func HandleEventDone(channel string) error

HandleEventDone is called from the bridge when an event stream ends.

func HandleEventError​

func HandleEventError(channel string, err *ChannelError) error

HandleEventError is called from the bridge when an event stream errors, with the error native sent.

func HandleNativeConnected​

func HandleNativeConnected()

HandleNativeConnected is called from the bridge once native has registered its method handler. It tells native about every event channel that already has subscribers (from package init, say), whose listen requests failed while native was not connected.

func HasFocus​

func HasFocus() bool

HasFocus returns true if there is currently a focused text input.

func InitializeAccessibility​

func InitializeAccessibility()

InitializeAccessibility sets up the accessibility system with the semantics binding.

func OpenAppSettings​

func OpenAppSettings() error

OpenAppSettings opens the system settings page for this app, where users can manage permissions manually. Use this when a permission is permanently denied and the app cannot request it again.

On iOS, opens the Settings app to the app's settings page. On Android, opens the App Info screen in system settings.

func RegisterActivityIndicatorViewFactory​

func RegisterActivityIndicatorViewFactory()

RegisterActivityIndicatorViewFactory registers the activity indicator view factory.

func RegisterDispatch​

func RegisterDispatch(fn func(callback func()))

RegisterDispatch sets the dispatch function used to schedule callbacks on the UI thread. This should be called once by the engine during initialization.

func RegisterSwitchViewFactory​

func RegisterSwitchViewFactory()

RegisterSwitchViewFactory registers the switch view factory.

func RegisterTextInputViewFactory​

func RegisterTextInputViewFactory()

toFloat64 converts various numeric types to float64. RegisterTextInputViewFactory registers the text input view factory.

func ResetForTest​

func ResetForTest()

ResetForTest resets all global platform state for test isolation. It clears the native bridge, resets cached state (lifecycle, safe area), removes all event subscriptions, and re-registers the built-in init-time listeners (lifecycle, safe area, accessibility) so that the package behaves as if freshly initialized. This should only be called from tests.

func SetFocusedInput​

func SetFocusedInput(viewID int64, focused bool)

SetFocusedInput marks a text input view as focused.

func SetFocusedTarget​

func SetFocusedTarget(target any)

SetFocusedTarget sets the render object that currently has keyboard focus.

func SetNativeBridge​

func SetNativeBridge(bridge NativeBridge)

SetNativeBridge sets the native bridge implementation. Called by the bridge package during initialization.

func SetSystemUI​

func SetSystemUI(style SystemUIStyle) error

SetSystemUI updates the system UI appearance.

func SetupTestBridge​

func SetupTestBridge(cleanup func(func()))

SetupTestBridge installs a no-op native bridge and synchronous dispatch function for testing. The cleanup function should be testing.T.Cleanup or equivalent; it registers a teardown that calls ResetForTest.

platform.SetupTestBridge(t.Cleanup)

func ShowDatePicker​

func ShowDatePicker(ctx context.Context, config DatePickerConfig) (time.Time, error)

ShowDatePicker shows the native date picker and returns the chosen date, at midnight in time.Local, or ErrPickerCancelled. Dates cross the channel as calendar days (year, month, day in each time's own location), so no time zone shifts them. It waits for the user, so call it from a goroutine: from the UI thread it fails with ErrBlocksUIThread.

func ShowTimePicker​

func ShowTimePicker(ctx context.Context, config TimePickerConfig) (hour, minute int, err error)

ShowTimePicker shows the native time picker and returns the chosen hour and minute, or ErrPickerCancelled. It waits for the user, so call it from a goroutine: from the UI thread it fails with ErrBlocksUIThread.

func UnfocusAll​

func UnfocusAll()

UnfocusAll dismisses the keyboard and clears focus for all text inputs.

func UseLifecycleObserver​

func UseLifecycleObserver(s disposable, handler LifecycleHandler)

UseLifecycleObserver subscribes to app lifecycle changes with automatic cleanup. The handler is dispatched to the UI thread via Dispatch (or called synchronously when no dispatch is registered, e.g. in tests).

Call once in InitState, not in Build.

func (s *myState) InitState() {
platform.UseLifecycleObserver(s, func(state platform.LifecycleState) {
if state == platform.LifecycleStatePaused {
s.saveProgress()
}
})
}

type ActivityIndicatorSize​

ActivityIndicatorSize represents the size of the activity indicator.

type ActivityIndicatorSize int
const (
// ActivityIndicatorSizeMedium is a medium spinner.
ActivityIndicatorSizeMedium ActivityIndicatorSize = iota
// ActivityIndicatorSizeSmall is a small spinner.
ActivityIndicatorSizeSmall
// ActivityIndicatorSizeLarge is a large spinner.
ActivityIndicatorSizeLarge
)

type ActivityIndicatorView​

ActivityIndicatorView is a platform view for native activity indicator.

type ActivityIndicatorView struct {
PlatformViewBase
// contains filtered or unexported fields
}

func NewActivityIndicatorView​

func NewActivityIndicatorView(viewID int64, config ActivityIndicatorViewConfig) *ActivityIndicatorView

NewActivityIndicatorView creates a new activity indicator platform view.

func (*ActivityIndicatorView) Create​

func (v *ActivityIndicatorView) Create(params map[string]any) error

Create initializes the native view.

func (*ActivityIndicatorView) Dispose​

func (v *ActivityIndicatorView) Dispose()

Dispose cleans up the native view.

func (*ActivityIndicatorView) HandleEvent​

func (v *ActivityIndicatorView) HandleEvent(method string, _ map[string]any) error

HandleEvent implements PlatformView; the native indicator sends no events.

func (*ActivityIndicatorView) IsAnimating​

func (v *ActivityIndicatorView) IsAnimating() bool

IsAnimating returns whether the indicator is currently animating.

func (*ActivityIndicatorView) SetAnimating​

func (v *ActivityIndicatorView) SetAnimating(animating bool)

SetAnimating starts or stops the animation.

func (*ActivityIndicatorView) UpdateConfig​

func (v *ActivityIndicatorView) UpdateConfig(config ActivityIndicatorViewConfig)

UpdateConfig updates the view configuration.

type ActivityIndicatorViewConfig​

ActivityIndicatorViewConfig defines styling passed to native activity indicator.

type ActivityIndicatorViewConfig struct {
// Animating controls whether the indicator is spinning.
Animating bool

// Size is the indicator size (Small, Medium, Large).
Size ActivityIndicatorSize

// Color is the spinner color (ARGB).
Color uint32
}

type AnnouncePoliteness​

AnnouncePoliteness indicates the urgency of an accessibility announcement.

type AnnouncePoliteness int
const (
// AnnouncePolitenessPolite is for non-urgent announcements that don't interrupt.
AnnouncePolitenessPolite AnnouncePoliteness = iota

// AnnouncePolitenessAssertive is for important announcements that should interrupt.
AnnouncePolitenessAssertive
)

type AppDirectory​

AppDirectory represents standard app directories.

type AppDirectory string
const (
AppDirectoryDocuments AppDirectory = "documents"
AppDirectoryCache AppDirectory = "cache"
AppDirectoryTemp AppDirectory = "temp"
AppDirectorySupport AppDirectory = "support"
)

type CapturedViewGeometry​

CapturedViewGeometry holds the resolved geometry for one platform view, captured during a StepFrame pass for synchronous application on the UI thread.

type CapturedViewGeometry struct {
ViewID int64
Offset graphics.Offset
Size graphics.Size
ClipBounds *graphics.Rect // collapsed single-rect after occlusion subtraction (Android fallback); nil if unclipped
VisibleRect graphics.Rect // view bounds intersected with parent clips; {0,0,0,0} if hidden
OcclusionPaths []*graphics.Path // path-based occlusion masks; [] if none
}

type ChannelError​

ChannelError represents an error returned from native code.

type ChannelError struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
// contains filtered or unexported fields
}

func NewChannelError​

func NewChannelError(code, message string) *ChannelError

NewChannelError creates a new ChannelError with the given code and message.

func NewChannelErrorWithDetails​

func NewChannelErrorWithDetails(code, message string, details any) *ChannelError

NewChannelErrorWithDetails creates a new ChannelError with additional details.

func (*ChannelError) Error​

func (e *ChannelError) Error() string

func (*ChannelError) Is​

func (e *ChannelError) Is(target error) bool

Is reports whether e carries target's wire code: a transport code, such as "blocks_ui_thread" for ErrBlocksUIThread, or one its channel declared (ErrorCodes).

type ClipboardData​

ClipboardData represents data on the clipboard.

type ClipboardData struct {
Text string `json:"text,omitempty"`
}

type ClipboardService​

ClipboardService manages clipboard operations.

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

func (*ClipboardService) Clear​

func (c *ClipboardService) Clear() error

Clear removes all data from the clipboard.

func (*ClipboardService) GetText​

func (c *ClipboardService) GetText() (string, error)

GetText retrieves text from the clipboard. Returns empty string if clipboard is empty or contains non-text data.

func (*ClipboardService) HasText​

func (c *ClipboardService) HasText() (bool, error)

HasText returns true if the clipboard contains text.

func (*ClipboardService) SetText​

func (c *ClipboardService) SetText(text string) error

SetText copies text to the clipboard.

type DatePickerConfig​

DatePickerConfig contains configuration for the date picker modal.

type DatePickerConfig struct {
// InitialDate is the initially selected date.
InitialDate time.Time

// MinDate is the minimum selectable date (optional).
MinDate *time.Time

// MaxDate is the maximum selectable date (optional).
MaxDate *time.Time
}

DeepLink describes an incoming deep link.

type DeepLink struct {
URL string
Source string
Timestamp time.Time
}

type DeepLinkService​

DeepLinkService provides deep link event access.

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

DeepLinks is the singleton deep link service.

var DeepLinks *DeepLinkService

func (*DeepLinkService) GetInitial​

func (d *DeepLinkService) GetInitial() (*DeepLink, error)

GetInitial returns the launch deep link, if available.

func (d *DeepLinkService) Links() *Stream[DeepLink]

Links returns a stream of deep link events.

type EdgeInsets​

EdgeInsets represents the safe area insets from system UI elements.

type EdgeInsets struct {
Top, Bottom, Left, Right float64
}

type Emitter​

Emitter feeds a Stream from Go, for events that do not arrive on an event channel of their own: a plugin's runtime half that receives one view's or one player's events and republishes them, say. Delivery is live: subscribers receive what is emitted after they listen.

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

func NewEmitter​

func NewEmitter[T any](name string) *Emitter[T]

NewEmitter returns an emitter and its stream. name identifies the stream in error reports.

func (*Emitter[T]) Emit​

func (e *Emitter[T]) Emit(value T)

Emit delivers value to the stream's subscribers, on the calling goroutine.

func (*Emitter[T]) Error​

func (e *Emitter[T]) Error(err error)

Error delivers err to the stream's subscribers (their OnError), on the calling goroutine.

func (*Emitter[T]) Stream​

func (e *Emitter[T]) Stream() *Stream[T]

Stream returns the stream the emitter feeds.

type ErrorCodes​

ErrorCodes maps the wire codes a channel's native side answers with to the sentinel errors they match. Declare a channel's codes once, with MethodChannel.WithErrors (and EventChannel.WithErrors for its stream): every error the channel returns or streams is then a \*ChannelError that matches its code's sentinel under errors.Is, with the native message kept.

var ErrDenied = errors.New("acme: permission denied")

var errorCodes = platform.ErrorCodes{"permission_denied": ErrDenied}

var channel = platform.NewMethodChannel("acme/camera").WithErrors(errorCodes)

A code must not repeat a transport code (method_not_found and the like), and each sentinel must be comparable (as errors.New's are).

type ErrorCodes map[string]error

func (ErrorCodes) NewError​

func (c ErrorCodes) NewError(code, message string) *ChannelError

NewError returns the error native would send with code and message, for Go code that receives codes some other way (in an event's payload, say).

type EventChannel​

EventChannel provides stream-based event communication from native to Go.

How an event dispatched with no subscriber, or before a subscriber joined, reaches later subscribers depends on the constructor:

  • NewEventChannel: it does not; events go to current subscribers only.
  • NewStickyEventChannel: the most recent event is replayed to every new subscriber, for one-shot signals such as "first frame rendered".
  • NewQueuedEventChannel: events dispatched while nobody listens are queued and delivered, in order, when a subscriber joins, for events that must each be handled once, such as a notification tap that launched the app before the app subscribed.

Native is told when the channel gains its first subscriber and loses its last, so a stream it declares (DriftChannel.stream) starts and stops with Go's interest; see [streamsChannel].

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

func NewEventChannel​

func NewEventChannel(name string) *EventChannel

NewEventChannel creates a new event channel with the given name.

func NewQueuedEventChannel​

func NewQueuedEventChannel(name string, capacity int) *EventChannel

NewQueuedEventChannel creates an event channel that keeps events dispatched while it has no subscribers, up to capacity (the oldest is dropped and reported beyond that), and delivers them in order to the next subscriber from [Listen], before any later event. Each queued event is delivered once: subscribers joining after the queue drained see only live events. Errors and Done are never queued.

Panics if capacity is not positive.

func NewStickyEventChannel​

func NewStickyEventChannel(name string) *EventChannel

NewStickyEventChannel creates an event channel that remembers the most recently dispatched event payload and replays it to each new subscriber on [Listen]. Use this for one-shot lifecycle signals (e.g. first-frame rendered) where a subscriber registering after the event still needs to observe it.

Sticky storage holds a single slot, overwritten on every subsequent dispatch. Errors and Done do not populate the slot.

func (*EventChannel) IsSticky​

func (c *EventChannel) IsSticky() bool

IsSticky reports whether the channel was constructed via NewStickyEventChannel. Sticky channels remember the most recent emission and replay it to subscribers that register after the fact. Callers can use this to assert framework-level expectations (e.g. that a lifecycle channel is sticky in tests).

func (*EventChannel) Listen​

func (c *EventChannel) Listen(handler EventHandler) *Subscription

Listen subscribes to events on this channel.

func (*EventChannel) Name​

func (c *EventChannel) Name() string

Name returns the channel name.

func (*EventChannel) WithErrors​

func (c *EventChannel) WithErrors(codes ErrorCodes) *EventChannel

WithErrors declares the error codes native streams on the channel (see ErrorCodes) and returns the channel, so stream errors match their sentinels under errors.Is. Call it once, where the channel is declared, before any subscription; a second call panics, as does a code repeating a transport code.

type EventHandler​

EventHandler receives events from an EventChannel.

type EventHandler struct {
OnEvent func(data any)
OnError func(err error)
OnDone func()
}

type FileInfo​

FileInfo contains metadata about a file.

type FileInfo struct {
Name string
Path string
Size int64
MimeType string
IsDirectory bool
LastModified int64
}

type HapticFeedbackType​

HapticFeedbackType defines the type of haptic feedback.

type HapticFeedbackType string
const (
// HapticLight is a light impact feedback.
HapticLight HapticFeedbackType = "light"

// HapticMedium is a medium impact feedback.
HapticMedium HapticFeedbackType = "medium"

// HapticHeavy is a heavy impact feedback.
HapticHeavy HapticFeedbackType = "heavy"

// HapticSelection is a selection feedback (subtle tick).
HapticSelection HapticFeedbackType = "selection"

// HapticSuccess indicates a successful action.
HapticSuccess HapticFeedbackType = "success"

// HapticWarning indicates a warning.
HapticWarning HapticFeedbackType = "warning"

// HapticError indicates an error.
HapticError HapticFeedbackType = "error"
)

type HapticsService​

HapticsService manages haptic feedback.

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

func (*HapticsService) HeavyImpact​

func (h *HapticsService) HeavyImpact() error

HeavyImpact triggers a heavy impact feedback.

func (*HapticsService) Impact​

func (h *HapticsService) Impact(style HapticFeedbackType) error

Impact triggers an impact haptic feedback.

func (*HapticsService) LightImpact​

func (h *HapticsService) LightImpact() error

LightImpact triggers a light impact feedback.

func (*HapticsService) MediumImpact​

func (h *HapticsService) MediumImpact() error

MediumImpact triggers a medium impact feedback.

func (*HapticsService) SelectionClick​

func (h *HapticsService) SelectionClick() error

SelectionClick triggers a selection tick feedback. Use this for selection changes in pickers, sliders, etc.

func (*HapticsService) Vibrate​

func (h *HapticsService) Vibrate(durationMs int) error

Vibrate triggers a vibration for the specified duration in milliseconds.

type JsonCodec​

JsonCodec implements MessageCodec using JSON encoding. JSON prioritizes interoperability and minimal native dependencies.

type JsonCodec struct{}

func (JsonCodec) Decode​

func (c JsonCodec) Decode(data []byte) (any, error)

Decode deserializes JSON bytes to a Go value.

func (JsonCodec) DecodeInto​

func (c JsonCodec) DecodeInto(data []byte, v any) error

DecodeInto deserializes JSON bytes into a specific type.

func (JsonCodec) Encode​

func (c JsonCodec) Encode(value any) ([]byte, error)

Encode serializes the value to JSON bytes.

type KeyboardType​

KeyboardType specifies the type of keyboard to show.

type KeyboardType int
const (
KeyboardTypeText KeyboardType = iota
KeyboardTypeNumber
KeyboardTypePhone
KeyboardTypeEmail
KeyboardTypeURL
KeyboardTypePassword
KeyboardTypeMultiline
)

type LifecycleHandler​

LifecycleHandler is called when lifecycle state changes.

type LifecycleHandler func(state LifecycleState)

type LifecycleService​

LifecycleService manages app lifecycle events.

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

func (*LifecycleService) AddHandler​

func (l *LifecycleService) AddHandler(handler LifecycleHandler) func()

AddHandler registers a handler to be called on lifecycle changes. Returns a function that can be called to remove the handler.

func (*LifecycleService) IsPaused​

func (l *LifecycleService) IsPaused() bool

IsPaused returns true if the app is paused.

func (*LifecycleService) IsResumed​

func (l *LifecycleService) IsResumed() bool

IsResumed returns true if the app is in the resumed state.

func (*LifecycleService) SetStateForTest​

func (l *LifecycleService) SetStateForTest(state LifecycleState)

SetStateForTest updates the lifecycle state and notifies handlers. Use only in tests.

func (*LifecycleService) State​

func (l *LifecycleService) State() LifecycleState

State returns the current lifecycle state.

type LifecycleState​

LifecycleState represents the current app lifecycle state.

type LifecycleState string
const (
// LifecycleStateResumed indicates the app is visible and responding to user input.
LifecycleStateResumed LifecycleState = "resumed"

// LifecycleStateInactive indicates the app is transitioning (e.g., receiving a phone call).
// On iOS, this occurs during app switcher or when a system dialog is shown.
LifecycleStateInactive LifecycleState = "inactive"

// LifecycleStatePaused indicates the app is not visible but still running.
LifecycleStatePaused LifecycleState = "paused"

// LifecycleStateDetached indicates the app is still hosted but detached from any view.
LifecycleStateDetached LifecycleState = "detached"
)

type MessageCodec​

MessageCodec encodes and decodes messages for platform channel communication.

type MessageCodec interface {
// Encode converts a Go value to bytes for transmission to native code.
Encode(value any) ([]byte, error)

// Decode converts bytes received from native code to a Go value.
Decode(data []byte) (any, error)
}

DefaultCodec is the codec used by platform channels.

var DefaultCodec MessageCodec = JsonCodec{}

type MethodChannel​

MethodChannel calls methods native code registers under its name. Native reaches Go through event channels.

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

func NewMethodChannel​

func NewMethodChannel(name string) *MethodChannel

NewMethodChannel creates a new method channel with the given name.

func (*MethodChannel) Invoke​

func (c *MethodChannel) Invoke(ctx context.Context, method string, args any) (any, error)

Invoke calls a method on the native side and returns the result. Blocks until the native side responds, an error occurs, or ctx is canceled. See [invokeNative] for the ctx cancellation contract. A native error is a \*ChannelError matching the channel's ErrorCodes under errors.Is.

func (*MethodChannel) Name​

func (c *MethodChannel) Name() string

Name returns the channel name.

func (*MethodChannel) WithErrors​

func (c *MethodChannel) WithErrors(codes ErrorCodes) *MethodChannel

WithErrors declares the channel's own error codes (see ErrorCodes) and returns the channel. Call it once, where the channel is declared, before any call; a second call panics, as does a code repeating a transport code.

type NativeBridge​

NativeBridge defines the interface for calling native platform code.

type NativeBridge interface {
// InvokeMethod starts a native method call and delivers its outcome
// through reply exactly once: before returning when native answers in
// place, otherwise later, from any thread.
//
// It must start the call on the calling goroutine. Native decides where
// a handler runs from the thread it is called on: a call from the UI
// thread is answered in place (or refused, for a method that replies
// asynchronously), since the UI thread cannot wait for a reply that may
// need it. Moving the call to another goroutine hides that thread and
// deadlocks the app.
InvokeMethod(channel, method string, args []byte, reply func(result []byte, err error))
}

type NotificationPermission​

NotificationPermission extends Permission with notification-specific options.

type NotificationPermission interface {
Permission

// RequestWithOptions prompts for notification permission with iOS-specific options.
// Uses the provided values verbatim - zero values mean that capability is NOT requested.
// For default behavior (Alert, Sound, Badge all enabled), use Request() instead.
// Options are ignored on Android. Like Request, it waits for the user,
// and a call made while a notification prompt is up returns that
// prompt's answer without using its own options.
RequestWithOptions(ctx context.Context, opts NotificationPermissionOptions) (PermissionResult, error)
}

type NotificationPermissionOptions​

NotificationPermissionOptions configures notification capabilities (iOS only). Zero values mean the capability is NOT requested. Use Request() for defaults.

type NotificationPermissionOptions struct {
Alert bool // Visible notifications (banners, alerts).
Sound bool // Notification sounds.
Badge bool // Badge count on app icon.
Provisional bool // Quiet delivery to Notification Center (iOS 12+).
}

type NotificationsService​

NotificationsService holds the notification permission. Drift provides it because the plugins that show notifications share it: local notifications (plugins/notifications) and push (plugins/firebase). On Android those plugins declare POST_NOTIFICATIONS; with neither in drift.yaml, its calls fail with ErrPermissionNotDeclared.

type NotificationsService struct {
// Permission for showing notifications. Implements
// NotificationPermission for iOS-specific options.
Permission NotificationPermission
}

type Permission​

Permission provides access to a runtime permission for a platform feature. Use Status to check current state, Request to prompt the user, and Listen to observe changes. Plugins provide permissions (see NewPermission); Drift provides the notification permission (Notifications).

Every method fails with ErrPermissionNotRegistered when no native code registered the kind, and on Android with ErrPermissionNotDeclared when the manifest lacks a permission the kind needs.

Context: only Request takes ctx because it waits for the user. Status, IsGranted, IsDenied, and ShouldShowRationale reply in place, so the high-level permission API does not expose ctx for them.

type Permission interface {
// Status returns the current permission status.
Status() (PermissionResult, error)

// Request prompts the user for permission if needed and returns the
// resulting status once they respond. When no prompt can change the
// status (granted, permanently denied, restricted), it returns at once
// without showing a dialog.
//
// Request waits for the user, so call it from a goroutine: from the UI
// thread it fails with [ErrBlocksUIThread] before any prompt shows.
// One prompt per kind shows at a time: a Request made while one is up
// returns that prompt's answer.
//
// Cancellation: returns ErrCanceled or ErrTimeout on ctx cancellation;
// the native dialog stays up until the user answers it.
Request(ctx context.Context) (PermissionResult, error)

// IsGranted returns true if permission is granted.
// Best-effort convenience: returns false on any error. Use Status for
// precise error handling when error details matter.
IsGranted() bool

// IsDenied returns true if permission is denied or permanently denied.
// Best-effort convenience: returns false on any error. Use Status for
// precise error handling when error details matter.
IsDenied() bool

// ShouldShowRationale returns whether to show a rationale before requesting.
// Android-specific; always returns (false, nil) on iOS.
ShouldShowRationale() (bool, error)

// Listen subscribes to permission status changes.
// Returns an unsubscribe function. Multiple listeners receive all events.
Listen(handler func(PermissionResult)) (unsubscribe func())
}

func NewPermission​

func NewPermission(kind string) Permission

NewPermission returns the permission of the given kind, such as "location". Native code registers each kind: Drift registers "notifications", and plugins register theirs (DriftPluginHost registerPermission on iOS and Android). Plugins call this from their runtime package and expose the result; apps use those values.

Calls on a kind no native code registered fail with ErrPermissionNotRegistered: the plugin providing it is missing from drift.yaml, or not configured for that kind.

type PermissionResult​

PermissionResult represents the status of a permission.

type PermissionResult string

Permission status constants.

const (
// PermissionGranted indicates full access has been granted.
PermissionGranted PermissionResult = "granted"

// PermissionDenied indicates the user denied the permission. The app may request again.
PermissionDenied PermissionResult = "denied"

// PermissionPermanentlyDenied indicates the user denied with "don't ask again" (Android)
// or denied twice (iOS). The app cannot request again; direct user to Settings.
PermissionPermanentlyDenied PermissionResult = "permanently_denied"

// PermissionRestricted indicates a system policy prevents granting (parental controls,
// MDM, enterprise policy). The user cannot change this; no dialog will be shown.
PermissionRestricted PermissionResult = "restricted"

// PermissionLimited indicates partial access (iOS only). For Photos, this means the user
// selected specific photos rather than granting full library access.
PermissionLimited PermissionResult = "limited"

// PermissionNotDetermined indicates the user has not yet been asked. Calling Request
// will show the system permission dialog.
PermissionNotDetermined PermissionResult = "not_determined"

// PermissionProvisional indicates provisional notification permission (iOS only).
// Notifications are delivered quietly to Notification Center without alerting the user.
PermissionProvisional PermissionResult = "provisional"

// PermissionResultUnknown indicates the status could not be determined.
PermissionResultUnknown PermissionResult = "unknown"
)

type PickFileOptions​

PickFileOptions configures file picker behavior.

type PickFileOptions struct {
AllowMultiple bool
AllowedTypes []string
InitialDir string
DialogTitle string
}

type PickedFile​

PickedFile represents a file selected by the user.

type PickedFile struct {
Name string
Path string
URI string
MimeType string
Size int64
}

type PlatformView​

PlatformView represents a native view embedded in Drift UI.

type PlatformView interface {
// ViewID returns the unique identifier for this view.
ViewID() int64

// ViewType returns the type identifier for this view (e.g., "native_webview").
ViewType() string

// Create initializes the native view with given parameters.
Create(params map[string]any) error

// Dispose cleans up the native view.
Dispose()

// HandleEvent receives an event or call the native view sent on
// drift/platform_views (other than creation and disposal), with its
// arguments, viewId included. It returns ErrMethodNotFound for a
// method it does not know, and an error for malformed arguments;
// either is reported through Drift's error handling.
HandleEvent(method string, args map[string]any) error
}

type PlatformViewBase​

PlatformViewBase implements a platform view's identity: embed it in a PlatformView (a plugin's too) and set it from the factory's viewID.

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

func NewPlatformViewBase​

func NewPlatformViewBase(viewID int64, viewType string) PlatformViewBase

NewPlatformViewBase returns the identity of view viewID of viewType.

func (*PlatformViewBase) SetEnabled​

func (v *PlatformViewBase) SetEnabled(enabled bool)

SetEnabled enables or disables touch input on the native view.

func (*PlatformViewBase) ViewID​

func (v *PlatformViewBase) ViewID() int64

ViewID returns the view's unique identifier.

func (*PlatformViewBase) ViewType​

func (v *PlatformViewBase) ViewType() string

ViewType returns the view's type identifier.

type PlatformViewFactory​

PlatformViewFactory creates platform views of a specific type.

type PlatformViewFactory interface {
// Create creates a new platform view instance.
Create(viewID int64, params map[string]any) (PlatformView, error)

// ViewType returns the view type this factory creates.
ViewType() string
}

type PlatformViewRegistry​

PlatformViewRegistry manages platform view types and instances.

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

func GetPlatformViewRegistry​

func GetPlatformViewRegistry() *PlatformViewRegistry

GetPlatformViewRegistry returns the global platform view registry.

func (*PlatformViewRegistry) BeginGeometryBatch​

func (r *PlatformViewRegistry) BeginGeometryBatch()

BeginGeometryBatch starts collecting geometry updates for batch processing. Call this at the start of each frame before the geometry compositing pass.

func (*PlatformViewRegistry) ClearGeometryCache​

func (r *PlatformViewRegistry) ClearGeometryCache(viewID int64)

ClearGeometryCache removes cached geometry for a view (call on dispose).

func (*PlatformViewRegistry) Create​

func (r *PlatformViewRegistry) Create(viewType string, params map[string]any) (PlatformView, error)

Create creates a new platform view of the given type, natively too: it returns once the native factory has run (on the main thread: at once from the UI thread, otherwise waiting for it), and fails with the factory's error, a \*ChannelError, when the factory fails.

func (*PlatformViewRegistry) Dispose​

func (r *PlatformViewRegistry) Dispose(viewID int64)

Dispose destroys a platform view.

func (*PlatformViewRegistry) FlushGeometryBatch​

func (r *PlatformViewRegistry) FlushGeometryBatch()

FlushGeometryBatch collects all queued geometry updates (including hide entries for unseen views) into the captured snapshot. The caller retrieves the result via TakeCapturedSnapshot.

func (*PlatformViewRegistry) GetView​

func (r *PlatformViewRegistry) GetView(viewID int64) PlatformView

GetView returns a platform view by ID.

func (*PlatformViewRegistry) InvokeViewMethod​

func (r *PlatformViewRegistry) InvokeViewMethod(viewID int64, method string, args map[string]any) (any, error)

InvokeViewMethod invokes a method on a specific platform view.

func (*PlatformViewRegistry) RegisterFactory​

func (r *PlatformViewRegistry) RegisterFactory(factory PlatformViewFactory)

RegisterFactory registers a factory for a platform view type.

func (*PlatformViewRegistry) SetViewEnabled​

func (r *PlatformViewRegistry) SetViewEnabled(viewID int64, enabled bool) error

SetViewEnabled notifies native to enable or disable a view.

func (*PlatformViewRegistry) SetViewVisible​

func (r *PlatformViewRegistry) SetViewVisible(viewID int64, visible bool) error

SetViewVisible notifies native to show or hide a view.

func (*PlatformViewRegistry) TakeCapturedSnapshot​

func (r *PlatformViewRegistry) TakeCapturedSnapshot() []CapturedViewGeometry

TakeCapturedSnapshot returns the geometry captured during the last frame and resets the capture buffer.

func (*PlatformViewRegistry) UpdateViewGeometry​

func (r *PlatformViewRegistry) UpdateViewGeometry(viewID int64, offset graphics.Offset, size graphics.Size, clipBounds *graphics.Rect, visibleRect graphics.Rect, occlusionPaths []*graphics.Path) error

UpdateViewGeometry queues a geometry update for a platform view. Updates are collected during compositing and flushed via FlushGeometryBatch. Gracefully ignores disposed or unknown viewIDs.

func (*PlatformViewRegistry) ViewCount​

func (r *PlatformViewRegistry) ViewCount() int

ViewCount returns the number of active platform views.

type PreferencesService​

PreferencesService manages simple key-value preference storage.

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

func (*PreferencesService) Contains​

func (p *PreferencesService) Contains(key string) (bool, error)

Contains checks if a key exists in preferences.

func (*PreferencesService) Delete​

func (p *PreferencesService) Delete(key string) error

Delete removes the value for the given key.

func (*PreferencesService) DeleteAll​

func (p *PreferencesService) DeleteAll() error

DeleteAll removes all values from preferences.

func (*PreferencesService) Get​

func (p *PreferencesService) Get(key string) (string, error)

Get retrieves a string value for the given key. Returns empty string and nil error if the key doesn't exist. Use Contains to distinguish a missing key from a key set to "".

func (*PreferencesService) GetAllKeys​

func (p *PreferencesService) GetAllKeys() ([]string, error)

GetAllKeys returns all keys stored in preferences.

func (*PreferencesService) Set​

func (p *PreferencesService) Set(key, value string) error

Set stores a string value for the given key.

type SafeAreaService​

SafeAreaService manages safe area inset events.

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

func (*SafeAreaService) AddHandler​

func (s *SafeAreaService) AddHandler(handler func(EdgeInsets)) func()

AddHandler registers a handler to be called on inset changes. Returns a function that can be called to remove the handler.

func (*SafeAreaService) Insets​

func (s *SafeAreaService) Insets() EdgeInsets

Insets returns the current safe area insets.

type SaveFileOptions​

SaveFileOptions configures save file dialog behavior.

type SaveFileOptions struct {
SuggestedName string
MimeType string
InitialDir string
DialogTitle string
}

type ShareFile​

ShareFile represents a file to share.

type ShareFile struct {
Path string
MimeType string
}

type ShareResult​

ShareResult indicates the result of a share operation.

type ShareResult string
const (
// ShareResultSuccess indicates the content was shared successfully.
ShareResultSuccess ShareResult = "success"

// ShareResultDismissed indicates the user dismissed the share sheet.
ShareResultDismissed ShareResult = "dismissed"

// ShareResultUnavailable indicates sharing is not available.
ShareResultUnavailable ShareResult = "unavailable"
)

type ShareService​

ShareService manages sharing content with other apps.

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

func (*ShareService) ShareFile​

func (s *ShareService) ShareFile(filePath, mimeType string) (ShareResult, error)

ShareFile opens the share sheet with a file at the given path. The mimeType helps the system determine which apps can handle the file.

func (*ShareService) ShareFiles​

func (s *ShareService) ShareFiles(files []ShareFile) (ShareResult, error)

ShareFiles opens the share sheet with multiple files.

func (*ShareService) ShareText​

func (s *ShareService) ShareText(text string) (ShareResult, error)

ShareText opens the share sheet with the given text.

func (*ShareService) ShareTextWithSubject​

func (s *ShareService) ShareTextWithSubject(text, subject string) (ShareResult, error)

ShareTextWithSubject opens the share sheet with text and a subject line. The subject is used by email apps and similar.

func (*ShareService) ShareURL​

func (s *ShareService) ShareURL(url string) (ShareResult, error)

ShareURL opens the share sheet with a URL.

func (*ShareService) ShareURLWithText​

func (s *ShareService) ShareURLWithText(url, text string) (ShareResult, error)

ShareURLWithText opens the share sheet with a URL and accompanying text.

type StatusBarStyle​

StatusBarStyle is the colour of the status bar's icons and text.

type StatusBarStyle string
const (
// StatusBarStyleDefault follows the system theme: dark icons in light
// mode, light icons in dark mode.
StatusBarStyleDefault StatusBarStyle = "default"
// StatusBarStyleLight is light icons, for dark content.
StatusBarStyleLight StatusBarStyle = "light"
// StatusBarStyleDark is dark icons, for light content.
StatusBarStyleDark StatusBarStyle = "dark"
)

type StorageService​

StorageService provides file picking, saving, and file system access.

Every method except GetAppDirectory waits for the platform (a picker, or file I/O off the main thread), so call it from a goroutine: from the UI thread it fails with ErrBlocksUIThread. File contents cross the channel as base64.

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

func (*StorageService) DeleteFile​

func (s *StorageService) DeleteFile(ctx context.Context, pathOrURI string) error

DeleteFile deletes a file path or content URI.

func (*StorageService) GetAppDirectory​

func (s *StorageService) GetAppDirectory(dir AppDirectory) (string, error)

GetAppDirectory returns the path to a standard app directory. It does not wait, so the UI thread may call it.

func (*StorageService) GetFileInfo​

func (s *StorageService) GetFileInfo(ctx context.Context, pathOrURI string) (FileInfo, error)

GetFileInfo returns metadata about a file path or content URI.

func (*StorageService) PickDirectory​

func (s *StorageService) PickDirectory(ctx context.Context) (string, error)

PickDirectory opens the system directory picker and returns the chosen directory's path (a content URI on Android), or "" if the user canceled. Returns ErrStorageBusy if a picker is open.

func (*StorageService) PickFile​

func (s *StorageService) PickFile(ctx context.Context, opts PickFileOptions) ([]PickedFile, error)

PickFile opens the system file picker and returns the chosen files, or none if the user canceled. Returns ErrStorageBusy if a picker is open.

func (*StorageService) ReadFile​

func (s *StorageService) ReadFile(ctx context.Context, pathOrURI string) ([]byte, error)

ReadFile reads the contents of a file path or content URI.

func (*StorageService) SaveFile​

func (s *StorageService) SaveFile(ctx context.Context, data []byte, opts SaveFileOptions) (string, error)

SaveFile asks the user where to save data and writes it there, returning the saved file's path (a content URI on Android), or "" if the user canceled. Returns ErrStorageBusy if a picker is open.

func (*StorageService) WriteFile​

func (s *StorageService) WriteFile(ctx context.Context, pathOrURI string, data []byte) error

WriteFile writes data to a file path or content URI, replacing its contents.

type Stream​

Stream is a typed broadcast of platform events: every subscriber receives every event and error independently. Native events arrive through an EventChannel (NewStream); Go code can feed one too (NewEmitter).

Handlers run on the goroutine that delivers the event, which need not be the UI thread: update widgets inside drift.Dispatch.

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

func NewStream​

func NewStream[T any](name string, channel *EventChannel, parser func(data any) (T, error)) *Stream[T]

NewStream creates a Stream wrapping an EventChannel. The parser converts raw event data to the typed value, returning error on parse failure.

func (*Stream[T]) Listen​

func (s *Stream[T]) Listen(handler StreamHandler[T]) (unsubscribe func())

Listen subscribes handler to the stream and returns the function that unsubscribes it.

An event the parser rejects is malformed native data, a bug on the native side: it is reported through Drift's error handling (KindParsing), never delivered.

type StreamHandler​

StreamHandler receives a Stream's events and errors.

type StreamHandler[T any] struct {
// OnEvent receives each event.
OnEvent func(T)
// OnError receives each error the stream reports, such as a native
// failure mid-stream (a revoked permission); for a native stream it is
// a [*ChannelError] matching the channel's [ErrorCodes]. When nil, the
// error is reported through Drift's error handling instead.
OnError func(error)
}

type Subscription​

Subscription represents an active event subscription.

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

func (*Subscription) Cancel​

func (s *Subscription) Cancel()

Cancel stops receiving events on this subscription.

func (*Subscription) IsCanceled​

func (s *Subscription) IsCanceled() bool

IsCanceled returns true if this subscription has been canceled.

type SwitchView​

SwitchView is a platform view for native switch control.

type SwitchView struct {
PlatformViewBase
// contains filtered or unexported fields
}

func NewSwitchView​

func NewSwitchView(viewID int64, config SwitchViewConfig, client SwitchViewClient) *SwitchView

NewSwitchView creates a new switch platform view.

func (*SwitchView) Create​

func (v *SwitchView) Create(params map[string]any) error

Create initializes the native view.

func (*SwitchView) Dispose​

func (v *SwitchView) Dispose()

Dispose cleans up the native view.

func (*SwitchView) HandleEvent​

func (v *SwitchView) HandleEvent(method string, args map[string]any) error

HandleEvent implements PlatformView: value changes from the native switch.

func (*SwitchView) SetClient​

func (v *SwitchView) SetClient(client SwitchViewClient)

SetClient sets the callback client for this view.

func (*SwitchView) SetValue​

func (v *SwitchView) SetValue(value bool)

SetValue updates the switch value from Go side.

func (*SwitchView) UpdateConfig​

func (v *SwitchView) UpdateConfig(config SwitchViewConfig)

UpdateConfig updates the view configuration.

func (*SwitchView) Value​

func (v *SwitchView) Value() bool

Value returns the current value.

type SwitchViewClient​

SwitchViewClient receives callbacks from native switch view.

type SwitchViewClient interface {
// OnValueChanged is called when the switch value changes.
OnValueChanged(value bool)
}

type SwitchViewConfig​

SwitchViewConfig defines styling passed to native switch view.

type SwitchViewConfig struct {
// OnTintColor is the track color when the switch is on (ARGB).
OnTintColor uint32

// ThumbTintColor is the thumb/knob color (ARGB).
ThumbTintColor uint32
}

type SystemUIStyle​

SystemUIStyle describes the system bars. Drift always draws behind them, on both platforms; inset content with SafeArea.

type SystemUIStyle struct {
StatusBarHidden bool
StatusBarStyle StatusBarStyle
}

type TextAffinity​

TextAffinity describes which side of a position the caret prefers.

type TextAffinity int
const (
// TextAffinityUpstream - the caret is placed at the end of the previous character.
TextAffinityUpstream TextAffinity = iota
// TextAffinityDownstream - the caret is placed at the start of the next character.
TextAffinityDownstream
)

type TextCapitalization​

TextCapitalization specifies text capitalization behavior.

type TextCapitalization int
const (
TextCapitalizationNone TextCapitalization = iota
TextCapitalizationCharacters
TextCapitalizationWords
TextCapitalizationSentences
)

type TextEditingController​

TextEditingController manages text input state.

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

func NewTextEditingController​

func NewTextEditingController(text string) *TextEditingController

NewTextEditingController creates a new text editing controller with the given initial text.

func (*TextEditingController) AddListener​

func (c *TextEditingController) AddListener(fn func()) func()

AddListener adds a callback that is called when the value changes. Returns an unsubscribe function.

func (*TextEditingController) Clear​

func (c *TextEditingController) Clear()

Clear clears the text.

func (*TextEditingController) Selection​

func (c *TextEditingController) Selection() TextSelection

Selection returns the current selection.

func (*TextEditingController) SetSelection​

func (c *TextEditingController) SetSelection(selection TextSelection)

SetSelection sets the selection.

func (*TextEditingController) SetText​

func (c *TextEditingController) SetText(text string)

SetText sets the text content.

func (*TextEditingController) SetValue​

func (c *TextEditingController) SetValue(value TextEditingValue)

SetValue sets the complete editing value.

func (*TextEditingController) Text​

func (c *TextEditingController) Text() string

Text returns the current text content.

func (*TextEditingController) Value​

func (c *TextEditingController) Value() TextEditingValue

Value returns the complete editing value.

type TextEditingValue​

TextEditingValue represents the current text editing state.

type TextEditingValue struct {
// Text is the current text content.
Text string
// Selection is the current selection within the text.
Selection TextSelection
// ComposingRange is the range currently being composed by IME.
ComposingRange TextRange
}

func (TextEditingValue) IsComposing​

func (v TextEditingValue) IsComposing() bool

IsComposing returns true if there is an active IME composition.

type TextInputAction​

TextInputAction specifies the action button on the keyboard.

type TextInputAction int
const (
TextInputActionNone TextInputAction = iota
TextInputActionDone
TextInputActionGo
TextInputActionNext
TextInputActionPrevious
TextInputActionSearch
TextInputActionSend
TextInputActionNewline
)

type TextInputView​

TextInputView is a platform view for text input.

type TextInputView struct {
PlatformViewBase
// contains filtered or unexported fields
}

func NewTextInputView​

func NewTextInputView(viewID int64, config TextInputViewConfig, client TextInputViewClient) *TextInputView

NewTextInputView creates a new text input platform view.

func (*TextInputView) Blur​

func (v *TextInputView) Blur()

Blur dismisses the keyboard.

func (*TextInputView) Create​

func (v *TextInputView) Create(params map[string]any) error

Create initializes the native view.

func (*TextInputView) Dispose​

func (v *TextInputView) Dispose()

Dispose cleans up the native view.

func (*TextInputView) Focus​

func (v *TextInputView) Focus()

Focus requests keyboard focus for the text input.

func (*TextInputView) HandleEvent​

func (v *TextInputView) HandleEvent(method string, args map[string]any) error

HandleEvent implements PlatformView: text, action and focus changes from the native field.

func (*TextInputView) IsFocused​

func (v *TextInputView) IsFocused() bool

IsFocused returns whether the view has focus.

func (*TextInputView) Selection​

func (v *TextInputView) Selection() (base, extent int)

Selection returns the current selection.

func (*TextInputView) SetClient​

func (v *TextInputView) SetClient(client TextInputViewClient)

SetClient sets the callback client for this view.

func (*TextInputView) SetSelection​

func (v *TextInputView) SetSelection(base, extent int)

SetSelection updates the cursor/selection position.

func (*TextInputView) SetText​

func (v *TextInputView) SetText(text string)

SetText updates the text content from Go side.

func (*TextInputView) SetValue​

func (v *TextInputView) SetValue(value TextEditingValue)

SetValue updates both text and selection atomically.

func (*TextInputView) Snapshot​

func (v *TextInputView) Snapshot() (text string, selBase, selExt int)

Snapshot returns the current text and selection under a single lock, ensuring a consistent read when both are needed together.

func (*TextInputView) Text​

func (v *TextInputView) Text() string

Text returns the current text.

func (*TextInputView) UpdateConfig​

func (v *TextInputView) UpdateConfig(config TextInputViewConfig)

UpdateConfig updates the view configuration.

type TextInputViewClient​

TextInputViewClient receives callbacks from native text input view.

type TextInputViewClient interface {
// OnTextChanged is called when text or selection changes.
OnTextChanged(text string, selectionBase, selectionExtent int)

// OnAction is called when keyboard action button is pressed.
OnAction(action TextInputAction)

// OnFocusChanged is called when focus state changes.
OnFocusChanged(focused bool)
}

type TextInputViewConfig​

TextInputViewConfig defines styling passed to native text view.

type TextInputViewConfig struct {
// Text styling (native view handles rendering)
FontFamily string
FontSize float64
FontWeight int // 400=regular, 700=bold
TextColor uint32 // ARGB
PlaceholderColor uint32 // ARGB
TextAlignment int // 0=left, 1=center, 2=right

// Behavior
Multiline bool
MaxLines int
Obscure bool
Autocorrect bool
KeyboardType KeyboardType
InputAction TextInputAction
Capitalization TextCapitalization

// Padding inside native view
PaddingLeft float64
PaddingTop float64
PaddingRight float64
PaddingBottom float64

// Placeholder text
Placeholder string
}

type TextRange​

TextRange represents a range of text.

type TextRange struct {
Start int
End int
}

func (TextRange) IsEmpty​

func (r TextRange) IsEmpty() bool

IsEmpty returns true if the range has zero length.

func (TextRange) IsNormalized​

func (r TextRange) IsNormalized() bool

IsNormalized returns true if start <= end.

func (TextRange) IsValid​

func (r TextRange) IsValid() bool

IsValid returns true if both start and end are non-negative.

type TextSelection​

TextSelection represents the current text selection.

type TextSelection struct {
// BaseOffset is the position where the selection started.
BaseOffset int
// ExtentOffset is the position where the selection ended.
ExtentOffset int
// Affinity indicates which direction the caret prefers.
Affinity TextAffinity
// IsDirectional is true if the selection has a direction.
IsDirectional bool
}

func TextSelectionCollapsed​

func TextSelectionCollapsed(offset int) TextSelection

TextSelectionCollapsed creates a collapsed selection at the given offset.

func (TextSelection) End​

func (s TextSelection) End() int

End returns the larger of BaseOffset and ExtentOffset.

func (TextSelection) IsCollapsed​

func (s TextSelection) IsCollapsed() bool

IsCollapsed returns true if the selection has no length (just a cursor).

func (TextSelection) IsValid​

func (s TextSelection) IsValid() bool

IsValid returns true if both offsets are non-negative.

func (TextSelection) Start​

func (s TextSelection) Start() int

Start returns the smaller of BaseOffset and ExtentOffset.

type TimePickerConfig​

TimePickerConfig contains configuration for the time picker modal.

type TimePickerConfig struct {
// Hour is the initial hour (0-23).
Hour int

// Minute is the initial minute (0-59).
Minute int

// Is24Hour determines whether to use 24-hour format.
// If nil, uses system default.
Is24Hour *bool
}

type URLLauncherService​

URLLauncherService manages opening URLs in the system browser.

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

func (*URLLauncherService) CanOpenURL​

func (u *URLLauncherService) CanOpenURL(rawURL string) (bool, error)

CanOpenURL returns whether the system can open the given URL.

On iOS, only schemes listed in LSApplicationQueriesSchemes (Info.plist) can be queried. On Android API 30+, only schemes declared in the manifest's <queries> block are visible to resolveActivity. Both templates include http, https, mailto, tel, and sms by default; other custom schemes will return false unless the app's manifests are updated.

func (*URLLauncherService) OpenURL​

func (u *URLLauncherService) OpenURL(rawURL string) error

OpenURL opens the given URL in the system browser.

type WebPage​

WebPage is what a web view shows.

type WebPage struct {
// URL is the page's URL, "" before the first load.
URL string
// Loading reports whether the page is still loading.
Loading bool
}

type WebViewController​

WebViewController provides control over a native web browser view. The controller creates its platform view eagerly, so its methods work right after construction.

Create with NewWebViewController and manage its lifetime with [core.UseDisposable]:

s.web, err = platform.NewWebViewController()
...
core.UseDisposable(&s.StateBase, s.web)
core.UseListenable(&s.StateBase, s.web.Page())
s.web.Load("https://example.com")

Pass the controller to a [widgets.NativeWebView] widget to embed the native surface in the widget tree. The controller publishes the page as state, WebViewController.Page, and load failures as the WebViewController.Errors stream; subscribe to Errors before Load so no failure is missed.

All methods are safe for concurrent use.

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

func NewWebViewController​

func NewWebViewController() (*WebViewController, error)

NewWebViewController creates a web view controller and its native web view. It fails if the native view cannot be created.

func (*WebViewController) Dispose​

func (c *WebViewController) Dispose()

Dispose releases the web view and its native resources. After disposal, this controller must not be reused. Dispose is idempotent; calling it more than once is safe.

func (*WebViewController) Errors​

func (c *WebViewController) Errors() *Stream[error]

Errors streams the page's load failures (not its images' or scripts'), each matching ErrWebViewNetwork, ErrWebViewSSL or ErrWebViewLoadFailed under errors.Is. Like any stream, its handlers run off the UI thread: update widgets inside drift.Dispatch.

func (*WebViewController) GoBack​

func (c *WebViewController) GoBack() error

GoBack navigates back in history.

func (*WebViewController) GoForward​

func (c *WebViewController) GoForward() error

GoForward navigates forward in history.

func (*WebViewController) Load​

func (c *WebViewController) Load(url string) error

Load loads the specified URL.

func (*WebViewController) Page​

func (c *WebViewController) Page() *core.Derived[WebPage]

Page is the page the web view shows: its URL, and whether it is still loading. It changes on the UI thread, so a widget can rebuild on it with [core.UseListenable]. Each load sets Loading, then clears it when the page finishes or fails.

func (*WebViewController) Reload​

func (c *WebViewController) Reload() error

Reload reloads the current page.

func (*WebViewController) ViewID​

func (c *WebViewController) ViewID() int64

ViewID returns the platform view ID, or 0 if the view was not created.

Generated by gomarkdoc