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.

Constants

Canonical media error codes shared by audio and video playback. Native implementations (ExoPlayer on Android, AVPlayer on iOS) map platform-specific errors to these codes so that Go callbacks receive consistent values across platforms.

const (
// ErrCodeSourceError indicates the media source could not be loaded.
// Covers network failures, invalid URLs, unsupported formats, and
// container parsing errors.
ErrCodeSourceError = "source_error"

// ErrCodeDecoderError indicates the media could not be decoded or
// rendered. Covers codec failures, audio track initialization errors,
// and DRM-related errors.
ErrCodeDecoderError = "decoder_error"

// ErrCodePlaybackFailed indicates a general playback failure that
// does not fit a more specific category.
ErrCodePlaybackFailed = "playback_failed"
)

Error codes for secure storage operations.

const (
SecureStorageErrorItemNotFound = "item_not_found"
SecureStorageErrorAuthFailed = "auth_failed"
SecureStorageErrorAuthCancelled = "auth_cancelled"
SecureStorageErrorBiometricNotAvailable = "biometric_not_available"
SecureStorageErrorBiometricNotEnrolled = "biometric_not_enrolled"
SecureStorageErrorAuthPending = "auth_pending"
SecureStorageErrorPlatformNotSupported = "platform_not_supported"
)

Canonical webview error codes shared by Android and iOS. Native implementations map platform-specific errors to these codes so that Go callbacks receive consistent values across platforms.

const (
// ErrCodeNetworkError indicates a network-level failure such as
// DNS resolution, connectivity, or timeout errors.
ErrCodeNetworkError = "network_error"

// ErrCodeSSLError indicates a TLS/certificate failure such as
// untrusted certificates or expired certificates.
ErrCodeSSLError = "ssl_error"

// ErrCodeLoadFailed indicates a general page load failure that
// does not fit a more specific category.
ErrCodeLoadFailed = "load_failed"
)

DefaultPermissionTimeout is the default timeout for permission requests.

const DefaultPermissionTimeout = 30 * time.Second

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")
)

Sentinel errors for platform operations.

var (
// ErrClosed is returned when operating on a closed channel or stream.
ErrClosed = errors.New("platform: channel closed")

// ErrNotConnected is returned when the platform bridge is not connected.
ErrNotConnected = errors.New("platform: not connected")

// 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")
)

Accessibility is the global accessibility channel instance.

var Accessibility = &accessibilityChannel{
method: NewMethodChannel("drift/accessibility"),
stateEvents: NewEventChannel("drift/accessibility/state"),
actionEvents: NewEventChannel("drift/accessibility/actions"),
}

Calendar is the singleton calendar service.

var Calendar = &CalendarService{
Permission: &basicPermission{inner: newPermission("calendar")},
}

ClipboardService provides access to the system clipboard.

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

Contacts is the singleton contacts service.

var Contacts = &ContactsService{
Permission: &basicPermission{inner: newPermission("contacts")},
}

ErrAuthPending is returned when an operation requires biometric authentication and the result will be delivered asynchronously via the event channel. Callers should listen on SecureStorage.Listen() to receive the result.

var ErrAuthPending = &SecureStorageError{
Code: SecureStorageErrorAuthPending,
Message: "Biometric authentication pending - listen for result on event channel",
}

ErrCameraBusy is returned when a camera operation is already in progress. Native camera handlers only support one operation at a time.

var ErrCameraBusy = errors.New("camera operation already in progress")

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

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

ErrPickerCancelled is returned when the user cancels the picker.

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

ErrPlatformNotSupported is returned when secure storage is not available on the platform. On Android, this occurs on API < 23 (pre-Marshmallow).

var ErrPlatformNotSupported = &SecureStorageError{
Code: SecureStorageErrorPlatformNotSupported,
Message: "Secure storage requires Android 6.0 (API 23) or higher",
}

ErrStorageBusy is returned when a storage picker operation is already in progress.

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),
}

Microphone is the singleton microphone service.

var Microphone = &MicrophoneService{
Permission: &basicPermission{inner: newPermission("microphone")},
}

Photos is the singleton photos service.

var Photos = &PhotosService{
Permission: &basicPermission{inner: newPermission("photos")},
}

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{},
}

SecureStorage provides secure key-value storage using platform-native encryption. On iOS, this uses the Keychain with optional LocalAuthentication. On Android, this uses EncryptedSharedPreferences with optional BiometricPrompt.

Security notes:

  • All data is encrypted at rest using platform-native encryption (Keychain/EncryptedSharedPreferences)
  • On Android API < 23, secure storage is not available and operations return ErrPlatformNotSupported
  • Biometric protection (RequireBiometric option) provides app-level authentication:
  • On iOS: Hardware-backed via Keychain SecAccessControl with .biometryCurrentSet
  • On Android: App-level UI gate only (BiometricPrompt without CryptoObject). The data is still encrypted, but the biometric check is enforced by the app, not cryptographically tied to key unlocking. This is a common pattern but provides weaker security guarantees than iOS Keychain biometric protection.
var SecureStorage = &SecureStorageService{
channel: NewMethodChannel("drift/secure_storage"),
events: NewEventChannel("drift/secure_storage/events"),
}

ShareService provides access to the system share sheet.

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

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, code, message string) error

HandleEventError is called from the bridge when an event stream errors.

func HandleMethodCall

func HandleMethodCall(channel, method string, argsData []byte) ([]byte, error)

HandleMethodCall is called from the bridge when native invokes a Go method.

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(ctx context.Context) 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. The ctx parameter is currently unused and reserved for future cancellation support.

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.

After setting the bridge, SetNativeBridge starts event streams for any event channels that acquired subscriptions before the bridge was available (e.g., during package init). This ensures that init-time Listen calls for Lifecycle, SafeArea, Accessibility, etc. are not silently lost. Startup errors are dispatched to subscribers' error handlers.

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(config DatePickerConfig) (time.Time, error)

ShowDatePicker shows the native date picker modal. Returns the selected date or error if cancelled.

func ShowTimePicker

func ShowTimePicker(config TimePickerConfig) (hour, minute int, err error)

ShowTimePicker shows the native time picker modal. Returns the selected hour and minute or error if cancelled.

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 {
// 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) 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 AudioPlayerController

AudioPlayerController provides audio playback control without a visual component. Audio has no visual surface, so this uses a standalone platform channel rather than the platform view system. Build your own UI around the controller.

Multiple controllers may exist concurrently, each managing its own native player instance. Call AudioPlayerController.Dispose to release resources when a controller is no longer needed.

Set callback fields (OnPlaybackStateChanged, OnPositionChanged, OnError) before calling AudioPlayerController.Load or any other playback method to ensure no events are missed.

All methods are safe for concurrent use. Callback fields should be set on the UI thread (e.g. in InitState). Setting them before calling Load ensures no events are missed.

type AudioPlayerController struct {

// OnPlaybackStateChanged is called when the playback state changes.
// Called on the UI thread.
// Set this before calling [AudioPlayerController.Load] or any other
// playback method to avoid missing events.
OnPlaybackStateChanged func(PlaybackState)

// OnPositionChanged is called when the playback position updates.
// The native platform fires this callback approximately every 250ms
// while media is loaded.
// Called on the UI thread.
// Set this before calling [AudioPlayerController.Load] or any other
// playback method to avoid missing events.
OnPositionChanged func(position, duration, buffered time.Duration)

// OnError is called when a playback error occurs.
// The code parameter is one of [ErrCodeSourceError],
// [ErrCodeDecoderError], or [ErrCodePlaybackFailed].
// Called on the UI thread.
// Set this before calling [AudioPlayerController.Load] or any other
// playback method to avoid missing events.
OnError func(code, message string)
// contains filtered or unexported fields
}

func NewAudioPlayerController

func NewAudioPlayerController() *AudioPlayerController

NewAudioPlayerController creates a new audio player controller. Each controller manages its own native player instance.

func (*AudioPlayerController) Buffered

func (c *AudioPlayerController) Buffered() time.Duration

Buffered returns the buffered position.

func (*AudioPlayerController) Dispose

func (c *AudioPlayerController) Dispose()

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

func (*AudioPlayerController) Duration

func (c *AudioPlayerController) Duration() time.Duration

Duration returns the total media duration.

func (*AudioPlayerController) Load

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

Load prepares the given URL for playback. The native player begins buffering the media source. Call AudioPlayerController.Play to start playback.

func (*AudioPlayerController) Pause

func (c *AudioPlayerController) Pause() error

Pause pauses playback.

func (*AudioPlayerController) Play

func (c *AudioPlayerController) Play() error

Play starts or resumes playback. Call AudioPlayerController.Load first to set the media URL.

func (*AudioPlayerController) Position

func (c *AudioPlayerController) Position() time.Duration

Position returns the current playback position.

func (*AudioPlayerController) SeekTo

func (c *AudioPlayerController) SeekTo(position time.Duration) error

SeekTo seeks to the given position.

func (*AudioPlayerController) SetLooping

func (c *AudioPlayerController) SetLooping(looping bool) error

SetLooping sets whether playback should loop.

func (*AudioPlayerController) SetPlaybackSpeed

func (c *AudioPlayerController) SetPlaybackSpeed(rate float64) error

SetPlaybackSpeed sets the playback speed (1.0 = normal). The rate must be positive. Behavior for zero or negative values is platform-dependent.

func (*AudioPlayerController) SetVolume

func (c *AudioPlayerController) SetVolume(volume float64) error

SetVolume sets the playback volume (0.0 to 1.0). Values outside this range are clamped by the native player.

func (*AudioPlayerController) State

func (c *AudioPlayerController) State() PlaybackState

State returns the current playback state.

func (*AudioPlayerController) Stop

func (c *AudioPlayerController) Stop() error

Stop stops playback and resets the player to the idle state. The loaded media is retained, so calling Play will restart playback from the beginning. To release native resources, use Dispose instead.

type BackgroundEvent

BackgroundEvent represents a background task event.

type BackgroundEvent struct {
TaskID string
EventType string
Data map[string]any
Timestamp time.Time
}

type BackgroundService

BackgroundService provides background task scheduling and event access.

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

Background is the singleton background service.

var Background *BackgroundService

func (*BackgroundService) Cancel

func (b *BackgroundService) Cancel(ctx context.Context, id string) error

Cancel cancels a scheduled background task.

func (*BackgroundService) CancelAll

func (b *BackgroundService) CancelAll(ctx context.Context) error

CancelAll cancels all scheduled background tasks.

func (*BackgroundService) CancelByTag

func (b *BackgroundService) CancelByTag(ctx context.Context, tag string) error

CancelByTag cancels all tasks with the given tag.

func (*BackgroundService) Complete

func (b *BackgroundService) Complete(ctx context.Context, id string, success bool) error

Complete signals completion of a background task.

func (*BackgroundService) Events

func (b *BackgroundService) Events() *Stream[BackgroundEvent]

Events returns a stream of background task events.

func (*BackgroundService) IsRefreshAvailable

func (b *BackgroundService) IsRefreshAvailable(ctx context.Context) (bool, error)

IsRefreshAvailable checks if background refresh is available.

func (*BackgroundService) Schedule

func (b *BackgroundService) Schedule(ctx context.Context, request TaskRequest) error

Schedule schedules a background task.

type BiometricType

BiometricType represents the type of biometric authentication available.

type BiometricType string
const (
// BiometricTypeNone indicates no biometric authentication is available.
BiometricTypeNone BiometricType = "none"

// BiometricTypeTouchID indicates Touch ID is available (iOS).
BiometricTypeTouchID BiometricType = "touch_id"

// BiometricTypeFaceID indicates Face ID is available (iOS).
BiometricTypeFaceID BiometricType = "face_id"

// BiometricTypeFingerprint indicates fingerprint authentication is available (Android).
BiometricTypeFingerprint BiometricType = "fingerprint"

// BiometricTypeFace indicates face authentication is available (Android).
BiometricTypeFace BiometricType = "face"
)

type CalendarService

CalendarService provides calendar access.

type CalendarService struct {
// Permission for calendar access.
Permission Permission
}

type CameraResult

CameraResult represents the result of a camera or gallery operation.

type CameraResult struct {

// Type indicates the operation: "capture" for camera, "gallery" for picker.
Type string

// Media contains the captured/selected media for single-selection operations.
Media *CapturedMedia

// MediaList contains multiple selected media when AllowMultiple is true.
MediaList []CapturedMedia

// Cancelled is true if the user dismissed the camera/picker without selecting.
Cancelled bool

// Error contains the error message if the operation failed.
Error string
// contains filtered or unexported fields
}

type CameraService

CameraService provides camera capture and photo library access.

type CameraService struct {
// Permission for camera access. Request before capturing photos.
Permission Permission
// contains filtered or unexported fields
}

Camera is the singleton camera service.

var Camera *CameraService

func (*CameraService) CapturePhoto

func (c *CameraService) CapturePhoto(ctx context.Context, opts CapturePhotoOptions) (CameraResult, error)

CapturePhoto opens the native camera to capture a photo. Blocks until the user captures a photo, cancels, or the context expires. This method should be called from a goroutine, not the main/render thread.

Returns ErrCameraBusy if another camera operation is already in progress.

Important: Always pass a context with a deadline or timeout. If the native layer fails to send a result and the context has no deadline, this method blocks forever and holds the camera mutex, preventing further operations.

Note: If the context is canceled, the native camera UI remains open. The user must dismiss it manually; there's no programmatic close.

func (*CameraService) PickFromGallery

func (c *CameraService) PickFromGallery(ctx context.Context, opts PickFromGalleryOptions) (CameraResult, error)

PickFromGallery opens the photo picker. Blocks until the user selects images, cancels, or the context expires. This method should be called from a goroutine, not the main/render thread.

Returns ErrCameraBusy if another camera operation is already in progress.

Important: Always pass a context with a deadline or timeout. If the native layer fails to send a result and the context has no deadline, this method blocks forever and holds the camera mutex, preventing further operations.

Note: If the context is canceled, the native picker UI remains open.

type CapturePhotoOptions

CapturePhotoOptions configures photo capture behavior.

type CapturePhotoOptions struct {
// UseFrontCamera opens the front-facing camera when true.
// Note: On Android, this is a hint that not all camera apps honor.
UseFrontCamera bool
}

type CapturedMedia

CapturedMedia represents a captured or selected media file.

type CapturedMedia struct {
// Path is the absolute file path to the media file in the app's temp directory.
Path string

// MimeType is the media type (e.g., "image/jpeg").
MimeType string

// Width is the image width in pixels.
Width int

// Height is the image height in pixels.
Height int

// Size is the file size in bytes.
Size int64
}

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"`
}

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

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 ContactsService

ContactsService provides contacts/address book access.

type ContactsService struct {
// Permission for contacts access.
Permission Permission
}

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(ctx context.Context) (*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 DeviceToken

DeviceToken represents a device push token update.

type DeviceToken struct {
// Platform is the push provider platform (e.g., "ios", "android").
Platform string
// Token is the raw device push token.
Token string
// Timestamp is when this token was received.
Timestamp time.Time
// IsRefresh reports whether this is a refreshed token.
IsRefresh bool
}

type EdgeInsets

EdgeInsets represents the safe area insets from system UI elements.

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

type EndOfStream

EndOfStream is sent when an event stream terminates normally.

type EndOfStream struct{}

type Event

Event represents an event sent from native to Go via an EventChannel.

type Event struct {
// Name identifies the event type.
Name string `json:"event"`

// Data contains the event payload.
Data any `json:"data,omitempty"`
}

type EventChannel

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

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 (*EventChannel) Listen

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

Listen subscribes to events on this channel. If the native bridge is not yet available (e.g., during init), the subscription is created but the event stream start is deferred until SetNativeBridge is called. Any error from starting the native event stream is reported via the error handler but does not prevent the subscription from being created.

func (*EventChannel) Name

func (c *EventChannel) Name() string

Name returns the channel name.

type EventError

EventError represents an error that occurred in an event stream.

type EventError struct {
// Code is a machine-readable error code.
Code string `json:"code"`

// Message is a human-readable error description.
Message string `json:"message"`

// Details contains additional error information.
Details any `json:"details,omitempty"`
}

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 KeychainAccessibility

KeychainAccessibility determines when a keychain item is accessible (iOS-specific).

type KeychainAccessibility string
const (
// AccessibleWhenUnlocked makes the item accessible only when the device is unlocked.
AccessibleWhenUnlocked KeychainAccessibility = "when_unlocked"

// AccessibleAfterFirstUnlock makes the item accessible after first unlock until reboot.
AccessibleAfterFirstUnlock KeychainAccessibility = "after_first_unlock"

// AccessibleWhenUnlockedThisDeviceOnly is like WhenUnlocked but not included in backups.
AccessibleWhenUnlockedThisDeviceOnly KeychainAccessibility = "when_unlocked_this_device_only"

// AccessibleAfterFirstUnlockThisDeviceOnly is like AfterFirstUnlock but not included in backups.
AccessibleAfterFirstUnlockThisDeviceOnly KeychainAccessibility = "after_first_unlock_this_device_only"
)

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 LocationOptions

LocationOptions configures location update behavior.

type LocationOptions struct {
// HighAccuracy requests the highest available accuracy (may use more power).
HighAccuracy bool
// DistanceFilter is the minimum distance in meters between updates.
DistanceFilter float64
// IntervalMs is the desired update interval in milliseconds.
IntervalMs int64
// FastestIntervalMs is the fastest acceptable update interval in milliseconds (Android).
FastestIntervalMs int64
}

type LocationService

LocationService provides location and GPS services. Context parameters are currently unused and reserved for future cancellation support.

type LocationService struct {
// Permission provides access to location permission levels.
Permission struct {
// WhenInUse permission for foreground location access.
WhenInUse Permission
// Always permission for background location access.
// On iOS, WhenInUse must be granted before requesting Always.
Always Permission
}
// contains filtered or unexported fields
}

Location is the singleton location service.

var Location *LocationService

func (*LocationService) GetCurrent

func (l *LocationService) GetCurrent(ctx context.Context, opts LocationOptions) (*LocationUpdate, error)

GetCurrent returns the current device location. The ctx parameter is currently unused and reserved for future cancellation support.

func (*LocationService) IsEnabled

func (l *LocationService) IsEnabled(ctx context.Context) (bool, error)

IsEnabled checks if location services are enabled on the device. The ctx parameter is currently unused and reserved for future cancellation support.

func (*LocationService) LastKnown

func (l *LocationService) LastKnown(ctx context.Context) (*LocationUpdate, error)

LastKnown returns the last known location without triggering a new request. The ctx parameter is currently unused and reserved for future cancellation support.

func (*LocationService) StartUpdates

func (l *LocationService) StartUpdates(ctx context.Context, opts LocationOptions) error

StartUpdates begins continuous location updates. The ctx parameter is currently unused and reserved for future cancellation support.

func (*LocationService) StopUpdates

func (l *LocationService) StopUpdates(ctx context.Context) error

StopUpdates stops location updates. The ctx parameter is currently unused and reserved for future cancellation support.

func (*LocationService) Updates

func (l *LocationService) Updates() *Stream[LocationUpdate]

Updates returns a stream of location updates.

type LocationUpdate

LocationUpdate represents a location update from the device.

type LocationUpdate struct {
// Latitude is the latitude in degrees.
Latitude float64
// Longitude is the longitude in degrees.
Longitude float64
// Altitude is the altitude in meters.
Altitude float64
// Accuracy is the estimated horizontal accuracy in meters.
Accuracy float64
// Heading is the direction of travel in degrees.
Heading float64
// Speed is the speed in meters per second.
Speed float64
// Timestamp is when the reading was taken.
Timestamp time.Time
// IsMocked reports whether the reading came from a mock provider (Android).
IsMocked bool
}

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 MethodCall

MethodCall represents a method invocation from Go to native or vice versa.

type MethodCall struct {
// ID is a unique identifier for correlating responses with requests.
ID int64 `json:"id"`

// Method is the name of the method to invoke.
Method string `json:"method"`

// Args contains the method arguments.
Args any `json:"args,omitempty"`
}

type MethodChannel

MethodChannel provides bidirectional method-call communication with native code.

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(method string, args any) (any, error)

Invoke calls a method on the native side and returns the result. This blocks until the native side responds or an error occurs.

func (*MethodChannel) Name

func (c *MethodChannel) Name() string

Name returns the channel name.

func (*MethodChannel) SetHandler

func (c *MethodChannel) SetHandler(handler MethodHandler)

SetHandler sets the handler for incoming method calls from native code.

type MethodHandler

MethodHandler handles incoming method calls on a channel.

type MethodHandler func(method string, args any) (any, error)

type MethodResponse

MethodResponse represents the result of a method call.

type MethodResponse struct {
// ID matches the MethodCall.ID this is responding to.
ID int64 `json:"id"`

// Result contains the successful result (nil if error).
Result any `json:"result,omitempty"`

// Error contains error details if the call failed.
Error *ChannelError `json:"error,omitempty"`
}

func (*MethodResponse) IsError

func (r *MethodResponse) IsError() bool

IsError returns true if this response represents an error.

type MicrophoneService

MicrophoneService provides microphone access.

type MicrophoneService struct {
// Permission for microphone access.
Permission Permission
}

type NativeBridge

NativeBridge defines the interface for calling native platform code.

type NativeBridge interface {
// InvokeMethod calls a method on the native side.
InvokeMethod(channel, method string, args []byte) ([]byte, error)

// StartEventStream tells native to start sending events for a channel.
StartEventStream(channel string) error

// StopEventStream tells native to stop sending events for a channel.
StopEventStream(channel string) error
}

type NotificationError

NotificationError represents a notification-related error.

type NotificationError struct {
// Code is a platform-specific error code.
Code string
// Message is the human-readable error description.
Message string
// Platform is the error source platform (e.g., "ios", "android").
Platform string
}

type NotificationEvent

NotificationEvent represents a received notification.

type NotificationEvent struct {
// ID is the notification identifier.
ID string
// Title is the notification title.
Title string
// Body is the notification body text.
Body string
// Data is the payload delivered with the notification.
Data map[string]any
// Timestamp is when the notification was received.
Timestamp time.Time
// IsForeground reports whether the notification was delivered while the app was in foreground.
IsForeground bool
// Source is "local" or "remote".
Source string
}

type NotificationOpen

NotificationOpen represents a user opening a notification.

type NotificationOpen struct {
// ID is the notification identifier.
ID string
// Data is the payload delivered with the notification.
Data map[string]any
// Action is the action identifier (if supported by the platform).
Action string
// Source is "local" or "remote".
Source string
// Timestamp is when the notification was opened.
Timestamp time.Time
}

type NotificationOptions

NotificationOptions configures which notification capabilities to request (iOS only). On Android, all capabilities are granted together; these options are ignored.

type NotificationOptions struct {
// Alert enables visible notifications (banners, alerts). Default: true.
Alert bool
// Sound enables notification sounds. Default: true.
Sound bool
// Badge enables badge count updates on the app icon. Default: true.
Badge bool
// Provisional requests provisional authorization (iOS 12+). Notifications are
// delivered quietly to Notification Center. The user can later promote or disable.
Provisional bool
}

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.
RequestWithOptions(ctx context.Context, opts NotificationPermissionOptions) (PermissionStatus, 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 NotificationRequest

NotificationRequest describes a local notification schedule request.

type NotificationRequest struct {
// ID is the unique identifier for the notification.
// Use the same ID to update or cancel a scheduled notification.
ID string
// Title is the notification title.
Title string
// Body is the notification body text.
Body string
// Data is an optional key/value payload delivered with the notification.
Data map[string]any
// At schedules the notification for a specific time.
// If zero, the notification is scheduled immediately or based on IntervalSeconds.
At time.Time
// IntervalSeconds sets a repeat interval in seconds.
// If > 0 and Repeats is true, the notification repeats at this interval.
// If > 0 and At is zero, the first delivery is scheduled after IntervalSeconds.
IntervalSeconds int64
// Repeats indicates whether the notification should repeat.
// Repeating is only honored when IntervalSeconds > 0.
Repeats bool
// ChannelID specifies the Android notification channel.
// Ignored on iOS.
ChannelID string
// Sound sets the sound name. Use "default" for the platform default.
// An empty string uses the platform default sound.
Sound string
// Badge sets the app icon badge count (iOS only).
// Nil leaves the badge unchanged.
Badge *int
}

type NotificationSettings

NotificationSettings describes the current notification settings.

type NotificationSettings struct {
// Status is the current notification permission status.
Status PermissionResult
// AlertsEnabled reports whether visible alerts are enabled.
AlertsEnabled bool
// SoundsEnabled reports whether sounds are enabled.
SoundsEnabled bool
// BadgesEnabled reports whether badge updates are enabled.
BadgesEnabled bool
}

type NotificationsService

NotificationsService provides local and push notification management.

type NotificationsService struct {
// Permission for notification access. Implements NotificationPermission
// for iOS-specific options.
Permission NotificationPermission
// contains filtered or unexported fields
}

Notifications is the singleton notifications service.

var Notifications *NotificationsService

func (*NotificationsService) Cancel

func (n *NotificationsService) Cancel(ctx context.Context, id string) error

Cancel cancels a scheduled notification by ID. The ctx parameter is currently unused and reserved for future cancellation support.

func (*NotificationsService) CancelAll

func (n *NotificationsService) CancelAll(ctx context.Context) error

CancelAll cancels all scheduled notifications. The ctx parameter is currently unused and reserved for future cancellation support.

func (*NotificationsService) DeletePushToken

func (n *NotificationsService) DeletePushToken(ctx context.Context) error

DeletePushToken deletes the current push token.

func (*NotificationsService) Deliveries

func (n *NotificationsService) Deliveries() *Stream[NotificationEvent]

Deliveries returns a stream of delivered notifications.

func (*NotificationsService) Errors

func (n *NotificationsService) Errors() *Stream[NotificationError]

Errors returns a stream of notification errors.

func (*NotificationsService) GetPushToken

func (n *NotificationsService) GetPushToken(ctx context.Context) (string, error)

GetPushToken returns the current push token if available.

func (*NotificationsService) Opens

func (n *NotificationsService) Opens() *Stream[NotificationOpen]

Opens returns a stream of notification open events (user tapped notification).

func (*NotificationsService) RegisterForPush

func (n *NotificationsService) RegisterForPush(ctx context.Context) error

RegisterForPush registers the device for push notifications. On iOS, call Permission.Request() first. On Android, this triggers FCM token retrieval.

func (*NotificationsService) Schedule

func (n *NotificationsService) Schedule(ctx context.Context, req NotificationRequest) error

Schedule schedules a local notification. The ctx parameter is currently unused and reserved for future cancellation support.

func (*NotificationsService) SetBadge

func (n *NotificationsService) SetBadge(ctx context.Context, count int) error

SetBadge sets the app badge count. The ctx parameter is currently unused and reserved for future cancellation support.

func (*NotificationsService) Settings

func (n *NotificationsService) Settings(ctx context.Context) (NotificationSettings, error)

Settings returns current notification settings and permission status. The ctx parameter is currently unused and reserved for future cancellation support.

func (*NotificationsService) SubscribeToTopic

func (n *NotificationsService) SubscribeToTopic(ctx context.Context, topic string) error

SubscribeToTopic subscribes to a push notification topic.

func (*NotificationsService) Tokens

func (n *NotificationsService) Tokens() *Stream[DeviceToken]

Tokens returns a stream of device push token updates.

func (*NotificationsService) UnsubscribeFromTopic

func (n *NotificationsService) UnsubscribeFromTopic(ctx context.Context, topic string) error

UnsubscribeFromTopic unsubscribes from a push notification topic.

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.

Context usage: The ctx parameter is used for cancellation and timeout on blocking operations (Request). For non-blocking operations (Status, IsGranted, IsDenied, ShouldShowRationale), ctx is accepted for API consistency but not currently used for cancellation.

type Permission interface {
// Status returns the current permission status.
// Note: ctx is accepted for API consistency but not used for cancellation.
Status(ctx context.Context) (PermissionStatus, error)

// Request prompts the user for permission and blocks until they respond
// or the context is canceled/times out. If already in a terminal state,
// returns immediately without showing a dialog.
Request(ctx context.Context) (PermissionStatus, 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(ctx context.Context) 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(ctx context.Context) bool

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

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

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 PermissionStatus

PermissionStatus represents the current state of a permission. This is an alias for PermissionResult for naming consistency.

type PermissionStatus = PermissionResult

type PhotosService

PhotosService provides photo library access.

type PhotosService struct {
// Permission for photo library access.
Permission Permission
}

type PickFileOptions

PickFileOptions configures file picker behavior.

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

type PickFromGalleryOptions

PickFromGalleryOptions configures gallery picker behavior.

type PickFromGalleryOptions struct {
// AllowMultiple enables selecting multiple images from the gallery.
// When true on Android, results are returned in CameraResult.MediaList.
// Note: iOS does not support multi-select; only a single image is returned.
AllowMultiple bool
}

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()
}

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.

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 PlaybackState

PlaybackState represents the current state of audio or video playback. Errors are delivered through separate error callbacks rather than as a playback state.

type PlaybackState int
const (
// PlaybackStateIdle indicates the player has been created but no media is loaded.
PlaybackStateIdle PlaybackState = iota

// PlaybackStateBuffering indicates the player is buffering media data before playback can continue.
PlaybackStateBuffering

// PlaybackStatePlaying indicates the player is actively playing media.
PlaybackStatePlaying

// PlaybackStateCompleted indicates playback has reached the end of the media.
PlaybackStateCompleted

// PlaybackStatePaused indicates the player is paused and can be resumed.
PlaybackStatePaused
)

func (PlaybackState) String

func (s PlaybackState) String() string

String returns a human-readable label for the playback state.

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 SecureStorageError

SecureStorageError represents errors from secure storage operations.

type SecureStorageError struct {
Code string
Message string
}

func (*SecureStorageError) Error

func (e *SecureStorageError) Error() string

type SecureStorageEvent

SecureStorageEvent represents an async result from a secure storage operation.

type SecureStorageEvent struct {
Type string // "auth_result"
Success bool
Key string
Value string // Only for get operations
Error string // Error code if failed
}

type SecureStorageOptions

SecureStorageOptions configures secure storage operations.

type SecureStorageOptions struct {
// KeychainAccessibility determines when the keychain item is accessible (iOS only).
// Defaults to AccessibleWhenUnlocked.
KeychainAccessibility KeychainAccessibility

// RequireBiometric requires biometric authentication (Face ID/Touch ID/Fingerprint)
// to access the stored value.
RequireBiometric bool

// BiometricPrompt is the message shown to the user during biometric authentication.
BiometricPrompt string

// Service is the namespace for storage. Defaults to the app's bundle identifier.
Service string
}

type SecureStorageService

SecureStorageService manages secure storage operations.

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

func (*SecureStorageService) Contains

func (s *SecureStorageService) Contains(key string, opts *SecureStorageOptions) (bool, error)

Contains checks if a key exists in secure storage.

func (*SecureStorageService) Delete

func (s *SecureStorageService) Delete(key string, opts *SecureStorageOptions) error

Delete removes a securely stored value. On Android, deleting a biometric-protected key may return ErrAuthPending.

func (*SecureStorageService) DeleteAll

func (s *SecureStorageService) DeleteAll(opts *SecureStorageOptions) error

DeleteAll removes all values from secure storage.

func (*SecureStorageService) Get

func (s *SecureStorageService) Get(key string, opts *SecureStorageOptions) (string, error)

Get retrieves a securely stored value. Returns empty string and nil error if the key doesn't exist. If the value is protected by biometrics (on Android), this may return ErrAuthPending indicating that biometric authentication is in progress. Listen on Listen() for the result.

func (*SecureStorageService) GetAllKeys

func (s *SecureStorageService) GetAllKeys(opts *SecureStorageOptions) ([]string, error)

GetAllKeys returns all keys stored in secure storage.

func (*SecureStorageService) GetBiometricType

func (s *SecureStorageService) GetBiometricType() (BiometricType, error)

GetBiometricType returns the type of biometric authentication available on the device.

func (*SecureStorageService) IsBiometricAvailable

func (s *SecureStorageService) IsBiometricAvailable() (bool, error)

IsBiometricAvailable checks if biometric authentication is available on the device.

func (*SecureStorageService) Listen

func (s *SecureStorageService) Listen() <-chan SecureStorageEvent

Listen returns a channel for receiving async authentication results. This is useful when biometric authentication is required and runs asynchronously.

func (*SecureStorageService) Set

func (s *SecureStorageService) Set(key, value string, opts *SecureStorageOptions) error

Set stores a value securely. If RequireBiometric is true, this may return ErrAuthPending indicating that biometric authentication is in progress. Listen on Listen() for the result.

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 indicates the status bar icon color scheme.

type StatusBarStyle string
const (
StatusBarStyleDefault StatusBarStyle = "default"
StatusBarStyleLight StatusBarStyle = "light"
StatusBarStyleDark StatusBarStyle = "dark"
)

type StorageResult

StorageResult represents a result from storage picker operations.

type StorageResult struct {
Type string // "pickFile", "pickDirectory", or "saveFile"
Files []PickedFile // For pickFile results
Path string // For pickDirectory or saveFile results
Cancelled bool
Error string
// contains filtered or unexported fields
}

type StorageService

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

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

Storage is the singleton storage service.

var Storage *StorageService

func (*StorageService) DeleteFile

func (s *StorageService) DeleteFile(pathOrURI string) error

DeleteFile deletes a file.

func (*StorageService) GetAppDirectory

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

GetAppDirectory returns the path to a standard app directory.

func (*StorageService) GetFileInfo

func (s *StorageService) GetFileInfo(pathOrURI string) (*FileInfo, error)

GetFileInfo returns metadata about a file.

func (*StorageService) PickDirectory

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

PickDirectory opens a directory picker dialog and blocks until the user selects a directory or cancels. Returns ErrStorageBusy if another picker operation is already in progress.

func (*StorageService) PickFile

func (s *StorageService) PickFile(ctx context.Context, opts PickFileOptions) (StorageResult, error)

PickFile opens a file picker dialog and blocks until the user selects files or cancels. Returns ErrStorageBusy if another picker operation is already in progress.

func (*StorageService) ReadFile

func (s *StorageService) ReadFile(pathOrURI string) ([]byte, error)

ReadFile reads the contents of a file.

func (*StorageService) SaveFile

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

SaveFile saves data to a file chosen by the user and blocks until complete. Returns ErrStorageBusy if another picker operation is already in progress.

func (*StorageService) WriteFile

func (s *StorageService) WriteFile(pathOrURI string, data []byte) error

WriteFile writes data to a file.

type Stream

Stream provides a multi-subscriber broadcast pattern for platform events. Unlike raw channels, multiple listeners can receive all events independently. Use Listen to subscribe and the returned function to unsubscribe.

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 func(T)) (unsubscribe func())

Listen subscribes to events and returns an unsubscribe function. The handler is called for each event. Parse errors are reported via errors.Report. Call the returned function to stop receiving events.

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 {
// 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) 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 system bar and window styling.

type SystemUIStyle struct {
StatusBarHidden bool
StatusBarStyle StatusBarStyle
TitleBarHidden bool // Android only (no-op on iOS)
BackgroundColor *graphics.Color // Android only (no-op on iOS)
Transparent bool // Android only (no-op on iOS)
}

type TaskConstraints

TaskConstraints defines constraints for when a task should run.

type TaskConstraints struct {
RequiresNetwork bool
RequiresUnmeteredNetwork bool
RequiresCharging bool
RequiresIdle bool
RequiresStorageNotLow bool
RequiresBatteryNotLow bool
}

type TaskRequest

TaskRequest describes a background task to schedule.

type TaskRequest struct {
ID string
TaskType TaskType
Tag string
Constraints TaskConstraints
InitialDelay time.Duration
RepeatInterval time.Duration
Data map[string]any
}

type TaskType

TaskType defines the type of background task.

type TaskType string
const (
TaskTypeOneTime TaskType = "one_time"
TaskTypePeriodic TaskType = "periodic"
TaskTypeFetch TaskType = "fetch"
)

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 {
// 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) 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 TimePickerResult

TimePickerResult contains the selected time.

type TimePickerResult struct {
Hour int
Minute int
}

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 VideoPlayerController

VideoPlayerController provides video playback control with a native visual surface (ExoPlayer on Android, AVPlayer on iOS). The controller creates its platform view eagerly, so methods and callbacks work immediately after construction.

Create with NewVideoPlayerController and manage lifecycle with [core.UseDisposable]:

s.video = platform.NewVideoPlayerController()
core.UseDisposable(&s.StateBase, s.video)
s.video.OnPlaybackStateChanged = func(state platform.PlaybackState) { ... }
s.video.Load(url)

Pass the controller to a [widgets.VideoPlayer] widget to embed the native surface in the widget tree.

Set callback fields (OnPlaybackStateChanged, OnPositionChanged, OnError) before calling VideoPlayerController.Load or any other playback method to ensure no events are missed.

All methods are safe for concurrent use. Callback fields should be set on the UI thread (e.g. in InitState). Setting them before calling Load ensures no events are missed.

type VideoPlayerController struct {

// OnPlaybackStateChanged is called when the playback state changes.
// Called on the UI thread.
// Set this before calling [VideoPlayerController.Load] or any other
// playback method to avoid missing events.
OnPlaybackStateChanged func(PlaybackState)

// OnPositionChanged is called when the playback position updates.
// The native platform fires this callback approximately every 250ms
// while media is loaded.
// Called on the UI thread.
// Set this before calling [VideoPlayerController.Load] or any other
// playback method to avoid missing events.
OnPositionChanged func(position, duration, buffered time.Duration)

// OnError is called when a playback error occurs.
// The code parameter is one of [ErrCodeSourceError],
// [ErrCodeDecoderError], or [ErrCodePlaybackFailed].
// Called on the UI thread.
// Set this before calling [VideoPlayerController.Load] or any other
// playback method to avoid missing events.
OnError func(code, message string)
// contains filtered or unexported fields
}

func NewVideoPlayerController

func NewVideoPlayerController() *VideoPlayerController

NewVideoPlayerController creates a new video player controller. The underlying platform view is created eagerly so methods and callbacks work immediately.

func (*VideoPlayerController) Buffered

func (c *VideoPlayerController) Buffered() time.Duration

Buffered returns the buffered position.

func (*VideoPlayerController) Dispose

func (c *VideoPlayerController) Dispose()

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

func (*VideoPlayerController) Duration

func (c *VideoPlayerController) Duration() time.Duration

Duration returns the total media duration.

func (*VideoPlayerController) Load

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

Load loads a new media URL, replacing the current media item. Call VideoPlayerController.Play to start playback.

func (*VideoPlayerController) Pause

func (c *VideoPlayerController) Pause() error

Pause pauses playback.

func (*VideoPlayerController) Play

func (c *VideoPlayerController) Play() error

Play starts or resumes playback. Call VideoPlayerController.Load first to set the media URL.

func (*VideoPlayerController) Position

func (c *VideoPlayerController) Position() time.Duration

Position returns the current playback position.

func (*VideoPlayerController) SeekTo

func (c *VideoPlayerController) SeekTo(position time.Duration) error

SeekTo seeks to the given position.

func (*VideoPlayerController) SetLooping

func (c *VideoPlayerController) SetLooping(looping bool) error

SetLooping sets whether playback should loop.

func (*VideoPlayerController) SetPlaybackSpeed

func (c *VideoPlayerController) SetPlaybackSpeed(rate float64) error

SetPlaybackSpeed sets the playback speed (1.0 = normal). The rate must be positive. Behavior for zero or negative values is platform-dependent.

func (*VideoPlayerController) SetShowControls

func (c *VideoPlayerController) SetShowControls(show bool) error

SetShowControls shows or hides the native transport controls.

func (*VideoPlayerController) SetVolume

func (c *VideoPlayerController) SetVolume(volume float64) error

SetVolume sets the playback volume (0.0 to 1.0). Values outside this range are clamped by the native player.

func (*VideoPlayerController) State

func (c *VideoPlayerController) State() PlaybackState

State returns the current playback state.

func (*VideoPlayerController) Stop

func (c *VideoPlayerController) Stop() error

Stop stops playback and resets the player to the idle state. The loaded media is retained, so calling Play will restart playback from the beginning. To release native resources, use Dispose instead.

func (*VideoPlayerController) ViewID

func (c *VideoPlayerController) ViewID() int64

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

type WebViewController

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

Create with NewWebViewController and manage lifecycle with [core.UseDisposable]:

s.web = platform.NewWebViewController()
core.UseDisposable(&s.StateBase, s.web)
s.web.OnPageFinished = func(url string) { ... }
s.web.Load("https://example.com")

Pass the controller to a [widgets.NativeWebView] widget to embed the native surface in the widget tree.

Set callback fields before calling WebViewController.Load to ensure no events are missed.

All methods are safe for concurrent use.

type WebViewController struct {

// OnPageStarted is called when a page starts loading.
// Called on the UI thread.
OnPageStarted func(url string)

// OnPageFinished is called when a page finishes loading.
// Called on the UI thread.
OnPageFinished func(url string)

// OnError is called when a loading error occurs.
// The code parameter is one of [ErrCodeNetworkError], [ErrCodeSSLError],
// or [ErrCodeLoadFailed]. Called on the UI thread.
OnError func(code, message string)
// contains filtered or unexported fields
}

func NewWebViewController

func NewWebViewController() *WebViewController

NewWebViewController creates a new web view controller. The underlying platform view is created eagerly so methods and callbacks work immediately.

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) 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) 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