Documentation
¶
Overview ¶
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.
Index ¶
- Constants
- Variables
- func Dispatch(callback func()) bool
- func GetFocusedTarget() any
- func HandleEvent(channel string, eventData []byte) error
- func HandleEventDone(channel string) error
- func HandleEventError(channel string, code, message string) error
- func HandleMethodCall(channel, method string, argsData []byte) ([]byte, error)
- func HasFocus() bool
- func OpenAppSettings(ctx context.Context) error
- func RegisterActivityIndicatorViewFactory()
- func RegisterDispatch(fn func(callback func()))
- func RegisterSwitchViewFactory()
- func RegisterTextInputViewFactory()
- func ResetForTest()
- func SetFocusedInput(viewID int64, focused bool)
- func SetFocusedTarget(target any)
- func SetNativeBridge(bridge NativeBridge)
- func SetSystemUI(style SystemUIStyle) error
- func SetupTestBridge(cleanup func(func()))
- func ShowDatePicker(config DatePickerConfig) (time.Time, error)
- func ShowTimePicker(config TimePickerConfig) (hour, minute int, err error)
- func UnfocusAll()
- func UseLifecycleObserver(s disposable, handler LifecycleHandler)
- type ActivityIndicatorSize
- type ActivityIndicatorView
- func (v *ActivityIndicatorView) Create(params map[string]any) error
- func (v *ActivityIndicatorView) Dispose()
- func (v *ActivityIndicatorView) IsAnimating() bool
- func (v *ActivityIndicatorView) SetAnimating(animating bool)
- func (v *ActivityIndicatorView) SetEnabled(enabled bool)
- func (v *ActivityIndicatorView) UpdateConfig(config ActivityIndicatorViewConfig)
- func (v *ActivityIndicatorView) ViewID() int64
- func (v *ActivityIndicatorView) ViewType() string
- type ActivityIndicatorViewConfig
- type AppDirectory
- type AudioPlayerController
- func (c *AudioPlayerController) Buffered() time.Duration
- func (c *AudioPlayerController) Dispose()
- func (c *AudioPlayerController) Duration() time.Duration
- func (c *AudioPlayerController) Load(url string) error
- func (c *AudioPlayerController) Pause() error
- func (c *AudioPlayerController) Play() error
- func (c *AudioPlayerController) Position() time.Duration
- func (c *AudioPlayerController) SeekTo(position time.Duration) error
- func (c *AudioPlayerController) SetLooping(looping bool) error
- func (c *AudioPlayerController) SetPlaybackSpeed(rate float64) error
- func (c *AudioPlayerController) SetVolume(volume float64) error
- func (c *AudioPlayerController) State() PlaybackState
- func (c *AudioPlayerController) Stop() error
- type BackgroundEvent
- type BackgroundService
- func (b *BackgroundService) Cancel(ctx context.Context, id string) error
- func (b *BackgroundService) CancelAll(ctx context.Context) error
- func (b *BackgroundService) CancelByTag(ctx context.Context, tag string) error
- func (b *BackgroundService) Complete(ctx context.Context, id string, success bool) error
- func (b *BackgroundService) Events() *Stream[BackgroundEvent]
- func (b *BackgroundService) IsRefreshAvailable(ctx context.Context) (bool, error)
- func (b *BackgroundService) Schedule(ctx context.Context, request TaskRequest) error
- type BiometricType
- type CalendarService
- type CameraResult
- type CameraService
- type CapturePhotoOptions
- type CapturedMedia
- type CapturedViewGeometry
- type ChannelError
- type ClipboardData
- type ClipboardService
- type ContactsService
- type DatePickerConfig
- type DeepLink
- type DeepLinkService
- type DeviceToken
- type EdgeInsets
- type EndOfStream
- type Event
- type EventChannel
- type EventError
- type EventHandler
- type FileInfo
- type HapticFeedbackType
- type HapticsService
- func (h *HapticsService) HeavyImpact() error
- func (h *HapticsService) Impact(style HapticFeedbackType) error
- func (h *HapticsService) LightImpact() error
- func (h *HapticsService) MediumImpact() error
- func (h *HapticsService) SelectionClick() error
- func (h *HapticsService) Vibrate(durationMs int) error
- type JsonCodec
- type KeyboardType
- type KeychainAccessibility
- type LifecycleHandler
- type LifecycleService
- type LifecycleState
- type LocationOptions
- type LocationService
- func (l *LocationService) GetCurrent(ctx context.Context, opts LocationOptions) (*LocationUpdate, error)
- func (l *LocationService) IsEnabled(ctx context.Context) (bool, error)
- func (l *LocationService) LastKnown(ctx context.Context) (*LocationUpdate, error)
- func (l *LocationService) StartUpdates(ctx context.Context, opts LocationOptions) error
- func (l *LocationService) StopUpdates(ctx context.Context) error
- func (l *LocationService) Updates() *Stream[LocationUpdate]
- type LocationUpdate
- type MessageCodec
- type MethodCall
- type MethodChannel
- type MethodHandler
- type MethodResponse
- type MicrophoneService
- type NativeBridge
- type NotificationError
- type NotificationEvent
- type NotificationOpen
- type NotificationOptions
- type NotificationPermission
- type NotificationPermissionOptions
- type NotificationRequest
- type NotificationSettings
- type NotificationsService
- func (n *NotificationsService) Cancel(ctx context.Context, id string) error
- func (n *NotificationsService) CancelAll(ctx context.Context) error
- func (n *NotificationsService) DeletePushToken(ctx context.Context) error
- func (n *NotificationsService) Deliveries() *Stream[NotificationEvent]
- func (n *NotificationsService) Errors() *Stream[NotificationError]
- func (n *NotificationsService) GetPushToken(ctx context.Context) (string, error)
- func (n *NotificationsService) Opens() *Stream[NotificationOpen]
- func (n *NotificationsService) RegisterForPush(ctx context.Context) error
- func (n *NotificationsService) Schedule(ctx context.Context, req NotificationRequest) error
- func (n *NotificationsService) SetBadge(ctx context.Context, count int) error
- func (n *NotificationsService) Settings(ctx context.Context) (NotificationSettings, error)
- func (n *NotificationsService) SubscribeToTopic(ctx context.Context, topic string) error
- func (n *NotificationsService) Tokens() *Stream[DeviceToken]
- func (n *NotificationsService) UnsubscribeFromTopic(ctx context.Context, topic string) error
- type Permission
- type PermissionResult
- type PermissionStatus
- type PhotosService
- type PickFileOptions
- type PickFromGalleryOptions
- type PickedFile
- type PlatformView
- type PlatformViewFactory
- type PlatformViewRegistry
- func (r *PlatformViewRegistry) BeginGeometryBatch()
- func (r *PlatformViewRegistry) ClearGeometryCache(viewID int64)
- func (r *PlatformViewRegistry) Create(viewType string, params map[string]any) (PlatformView, error)
- func (r *PlatformViewRegistry) Dispose(viewID int64)
- func (r *PlatformViewRegistry) FlushGeometryBatch()
- func (r *PlatformViewRegistry) GetView(viewID int64) PlatformView
- func (r *PlatformViewRegistry) InvokeViewMethod(viewID int64, method string, args map[string]any) (any, error)
- func (r *PlatformViewRegistry) RegisterFactory(factory PlatformViewFactory)
- func (r *PlatformViewRegistry) SetViewEnabled(viewID int64, enabled bool) error
- func (r *PlatformViewRegistry) SetViewVisible(viewID int64, visible bool) error
- func (r *PlatformViewRegistry) TakeCapturedSnapshot() []CapturedViewGeometry
- func (r *PlatformViewRegistry) UpdateViewGeometry(viewID int64, offset graphics.Offset, size graphics.Size, ...) error
- func (r *PlatformViewRegistry) ViewCount() int
- type PlaybackState
- type PreferencesService
- func (p *PreferencesService) Contains(key string) (bool, error)
- func (p *PreferencesService) Delete(key string) error
- func (p *PreferencesService) DeleteAll() error
- func (p *PreferencesService) Get(key string) (string, error)
- func (p *PreferencesService) GetAllKeys() ([]string, error)
- func (p *PreferencesService) Set(key, value string) error
- type SafeAreaService
- type SaveFileOptions
- type SecureStorageError
- type SecureStorageEvent
- type SecureStorageOptions
- type SecureStorageService
- func (s *SecureStorageService) Contains(key string, opts *SecureStorageOptions) (bool, error)
- func (s *SecureStorageService) Delete(key string, opts *SecureStorageOptions) error
- func (s *SecureStorageService) DeleteAll(opts *SecureStorageOptions) error
- func (s *SecureStorageService) Get(key string, opts *SecureStorageOptions) (string, error)
- func (s *SecureStorageService) GetAllKeys(opts *SecureStorageOptions) ([]string, error)
- func (s *SecureStorageService) GetBiometricType() (BiometricType, error)
- func (s *SecureStorageService) IsBiometricAvailable() (bool, error)
- func (s *SecureStorageService) Listen() <-chan SecureStorageEvent
- func (s *SecureStorageService) Set(key, value string, opts *SecureStorageOptions) error
- type ShareFile
- type ShareResult
- type ShareService
- func (s *ShareService) ShareFile(filePath, mimeType string) (ShareResult, error)
- func (s *ShareService) ShareFiles(files []ShareFile) (ShareResult, error)
- func (s *ShareService) ShareText(text string) (ShareResult, error)
- func (s *ShareService) ShareTextWithSubject(text, subject string) (ShareResult, error)
- func (s *ShareService) ShareURL(url string) (ShareResult, error)
- func (s *ShareService) ShareURLWithText(url, text string) (ShareResult, error)
- type StatusBarStyle
- type StorageResult
- type StorageService
- func (s *StorageService) DeleteFile(pathOrURI string) error
- func (s *StorageService) GetAppDirectory(dir AppDirectory) (string, error)
- func (s *StorageService) GetFileInfo(pathOrURI string) (*FileInfo, error)
- func (s *StorageService) PickDirectory(ctx context.Context) (StorageResult, error)
- func (s *StorageService) PickFile(ctx context.Context, opts PickFileOptions) (StorageResult, error)
- func (s *StorageService) ReadFile(pathOrURI string) ([]byte, error)
- func (s *StorageService) SaveFile(ctx context.Context, data []byte, opts SaveFileOptions) (StorageResult, error)
- func (s *StorageService) WriteFile(pathOrURI string, data []byte) error
- type Stream
- type Subscription
- type SwitchView
- func (v *SwitchView) Create(params map[string]any) error
- func (v *SwitchView) Dispose()
- func (v *SwitchView) SetClient(client SwitchViewClient)
- func (v *SwitchView) SetEnabled(enabled bool)
- func (v *SwitchView) SetValue(value bool)
- func (v *SwitchView) UpdateConfig(config SwitchViewConfig)
- func (v *SwitchView) Value() bool
- func (v *SwitchView) ViewID() int64
- func (v *SwitchView) ViewType() string
- type SwitchViewClient
- type SwitchViewConfig
- type SystemUIStyle
- type TaskConstraints
- type TaskRequest
- type TaskType
- type TextAffinity
- type TextCapitalization
- type TextEditingController
- func (c *TextEditingController) AddListener(fn func()) func()
- func (c *TextEditingController) Clear()
- func (c *TextEditingController) Selection() TextSelection
- func (c *TextEditingController) SetSelection(selection TextSelection)
- func (c *TextEditingController) SetText(text string)
- func (c *TextEditingController) SetValue(value TextEditingValue)
- func (c *TextEditingController) Text() string
- func (c *TextEditingController) Value() TextEditingValue
- type TextEditingValue
- type TextInputAction
- type TextInputView
- func (v *TextInputView) Blur()
- func (v *TextInputView) Create(params map[string]any) error
- func (v *TextInputView) Dispose()
- func (v *TextInputView) Focus()
- func (v *TextInputView) IsFocused() bool
- func (v *TextInputView) Selection() (base, extent int)
- func (v *TextInputView) SetClient(client TextInputViewClient)
- func (v *TextInputView) SetEnabled(enabled bool)
- func (v *TextInputView) SetSelection(base, extent int)
- func (v *TextInputView) SetText(text string)
- func (v *TextInputView) SetValue(value TextEditingValue)
- func (v *TextInputView) Snapshot() (text string, selBase, selExt int)
- func (v *TextInputView) Text() string
- func (v *TextInputView) UpdateConfig(config TextInputViewConfig)
- func (v *TextInputView) ViewID() int64
- func (v *TextInputView) ViewType() string
- type TextInputViewClient
- type TextInputViewConfig
- type TextRange
- type TextSelection
- type TimePickerConfig
- type TimePickerResult
- type URLLauncherService
- type VideoPlayerController
- func (c *VideoPlayerController) Buffered() time.Duration
- func (c *VideoPlayerController) Dispose()
- func (c *VideoPlayerController) Duration() time.Duration
- func (c *VideoPlayerController) Load(url string) error
- func (c *VideoPlayerController) Pause() error
- func (c *VideoPlayerController) Play() error
- func (c *VideoPlayerController) Position() time.Duration
- func (c *VideoPlayerController) SeekTo(position time.Duration) error
- func (c *VideoPlayerController) SetLooping(looping bool) error
- func (c *VideoPlayerController) SetPlaybackSpeed(rate float64) error
- func (c *VideoPlayerController) SetShowControls(show bool) error
- func (c *VideoPlayerController) SetVolume(volume float64) error
- func (c *VideoPlayerController) State() PlaybackState
- func (c *VideoPlayerController) Stop() error
- func (c *VideoPlayerController) ViewID() int64
- type WebViewController
Constants ¶
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" )
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 ( 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" )
Error codes for secure storage operations.
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" )
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 DefaultPermissionTimeout = 30 * time.Second
DefaultPermissionTimeout is the default timeout for permission requests.
Variables ¶
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") // (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") )
Standard errors for platform channel 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") )
Sentinel errors for platform operations.
var Calendar = &CalendarService{
Permission: &basicPermission{inner: newPermission("calendar")},
}
Calendar is the singleton calendar service.
var Clipboard = &ClipboardService{ channel: NewMethodChannel("drift/clipboard"), }
ClipboardService provides access to the system clipboard.
var Contacts = &ContactsService{
Permission: &basicPermission{inner: newPermission("contacts")},
}
Contacts is the singleton contacts service.
var ErrAuthPending = &SecureStorageError{ Code: SecureStorageErrorAuthPending, Message: "Biometric authentication pending - listen for result on event channel", }
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 ErrCameraBusy = errors.New("camera operation already in progress")
ErrCameraBusy is returned when a camera operation is already in progress. Native camera handlers only support one operation at a time.
var ErrChannelNotRegistered = fmt.Errorf("event channel not registered")
ErrChannelNotRegistered is returned when an event is received for an unregistered channel.
var ErrPickerCancelled = errors.New("picker cancelled")
ErrPickerCancelled is returned when the user cancels the picker.
var ErrPlatformNotSupported = &SecureStorageError{ Code: SecureStorageErrorPlatformNotSupported, Message: "Secure storage requires Android 6.0 (API 23) or higher", }
ErrPlatformNotSupported is returned when secure storage is not available on the platform. On Android, this occurs on API < 23 (pre-Marshmallow).
var ErrStorageBusy = errors.New("storage picker operation already in progress")
ErrStorageBusy is returned when a storage picker operation is already in progress.
var Haptics = &HapticsService{ channel: NewMethodChannel("drift/haptics"), }
HapticsService provides haptic feedback functionality.
var Lifecycle = &LifecycleService{ channel: NewMethodChannel("drift/lifecycle"), events: NewEventChannel("drift/lifecycle/events"), state: LifecycleStateResumed, handlers: make([]LifecycleHandler, 0), }
LifecycleService provides app lifecycle state management.
var Microphone = &MicrophoneService{
Permission: &basicPermission{inner: newPermission("microphone")},
}
Microphone is the singleton microphone service.
var Photos = &PhotosService{
Permission: &basicPermission{inner: newPermission("photos")},
}
Photos is the singleton photos service.
var Preferences = &PreferencesService{ channel: NewMethodChannel("drift/preferences"), }
Preferences provides simple, unencrypted key-value storage using platform-native mechanisms (UserDefaults on iOS, SharedPreferences on Android). For sensitive data, use SecureStorage instead.
var SafeArea = &SafeAreaService{ events: NewEventChannel("drift/safe_area/events"), insets: EdgeInsets{}, }
SafeArea provides safe area inset management.
var SecureStorage = &SecureStorageService{ channel: NewMethodChannel("drift/secure_storage"), events: NewEventChannel("drift/secure_storage/events"), }
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.
channel: NewMethodChannel("drift/share"), }
ShareService provides access to the system share sheet.
var TextEditingValueEmpty = TextEditingValue{ Selection: TextSelectionCollapsed(0), ComposingRange: TextRangeEmpty, }
TextEditingValueEmpty is the default empty editing value.
var TextRangeEmpty = TextRange{Start: -1, End: -1}
TextRangeEmpty is an invalid/empty text range.
var URLLauncher = &URLLauncherService{ channel: NewMethodChannel("drift/url_launcher"), }
URLLauncher provides access to the system URL launcher.
Functions ¶
func Dispatch ¶ added in v0.4.0
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 ¶
HandleEvent is called from the bridge when native sends an event.
func HandleEventDone ¶
HandleEventDone is called from the bridge when an event stream ends.
func HandleEventError ¶
HandleEventError is called from the bridge when an event stream errors.
func HandleMethodCall ¶
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 OpenAppSettings ¶
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 ¶ added in v0.6.0
func RegisterActivityIndicatorViewFactory()
RegisterActivityIndicatorViewFactory registers the activity indicator view factory.
func RegisterDispatch ¶ added in v0.4.0
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 ¶ added in v0.6.0
func RegisterSwitchViewFactory()
RegisterSwitchViewFactory registers the switch view factory.
func RegisterTextInputViewFactory ¶ added in v0.6.0
func RegisterTextInputViewFactory()
toFloat64 converts various numeric types to float64. RegisterTextInputViewFactory registers the text input view factory.
func ResetForTest ¶ added in v0.7.0
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 ¶ added in v0.6.0
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 ¶ added in v0.11.0
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 ¶ added in v0.6.0
func ShowDatePicker(config DatePickerConfig) (time.Time, error)
ShowDatePicker shows the native date picker modal. Returns the selected date or error if cancelled.
func ShowTimePicker ¶ added in v0.6.0
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 ¶ added in v0.24.0
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()
}
})
}
Types ¶
type ActivityIndicatorSize ¶ added in v0.6.0
type ActivityIndicatorSize int
ActivityIndicatorSize represents the size of the activity indicator.
const ( // ActivityIndicatorSizeMedium is a medium spinner. ActivityIndicatorSizeMedium ActivityIndicatorSize = iota // ActivityIndicatorSizeSmall is a small spinner. ActivityIndicatorSizeSmall // ActivityIndicatorSizeLarge is a large spinner. ActivityIndicatorSizeLarge )
type ActivityIndicatorView ¶ added in v0.6.0
type ActivityIndicatorView struct {
// contains filtered or unexported fields
}
ActivityIndicatorView is a platform view for native activity indicator.
func NewActivityIndicatorView ¶ added in v0.6.0
func NewActivityIndicatorView(viewID int64, config ActivityIndicatorViewConfig) *ActivityIndicatorView
NewActivityIndicatorView creates a new activity indicator platform view.
func (*ActivityIndicatorView) Create ¶ added in v0.6.0
func (v *ActivityIndicatorView) Create(params map[string]any) error
Create initializes the native view.
func (*ActivityIndicatorView) Dispose ¶ added in v0.6.0
func (v *ActivityIndicatorView) Dispose()
Dispose cleans up the native view.
func (*ActivityIndicatorView) IsAnimating ¶ added in v0.6.0
func (v *ActivityIndicatorView) IsAnimating() bool
IsAnimating returns whether the indicator is currently animating.
func (*ActivityIndicatorView) SetAnimating ¶ added in v0.6.0
func (v *ActivityIndicatorView) SetAnimating(animating bool)
SetAnimating starts or stops the animation.
func (*ActivityIndicatorView) SetEnabled ¶ added in v0.6.0
func (v *ActivityIndicatorView) SetEnabled(enabled bool)
func (*ActivityIndicatorView) UpdateConfig ¶ added in v0.6.0
func (v *ActivityIndicatorView) UpdateConfig(config ActivityIndicatorViewConfig)
UpdateConfig updates the view configuration.
type ActivityIndicatorViewConfig ¶ added in v0.6.0
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
}
ActivityIndicatorViewConfig defines styling passed to native activity indicator.
type AppDirectory ¶
type AppDirectory string
AppDirectory represents standard app directories.
const ( AppDirectoryDocuments AppDirectory = "documents" AppDirectoryCache AppDirectory = "cache" AppDirectoryTemp AppDirectory = "temp" AppDirectorySupport AppDirectory = "support" )
type AudioPlayerController ¶ added in v0.11.0
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
}
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 or a UseController callback). Setting them before calling Load ensures no events are missed.
func NewAudioPlayerController ¶ added in v0.11.0
func NewAudioPlayerController() *AudioPlayerController
NewAudioPlayerController creates a new audio player controller. Each controller manages its own native player instance.
func (*AudioPlayerController) Buffered ¶ added in v0.11.0
func (c *AudioPlayerController) Buffered() time.Duration
Buffered returns the buffered position.
func (*AudioPlayerController) Dispose ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *AudioPlayerController) Duration() time.Duration
Duration returns the total media duration.
func (*AudioPlayerController) Load ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *AudioPlayerController) Pause() error
Pause pauses playback.
func (*AudioPlayerController) Play ¶ added in v0.11.0
func (c *AudioPlayerController) Play() error
Play starts or resumes playback. Call AudioPlayerController.Load first to set the media URL.
func (*AudioPlayerController) Position ¶ added in v0.11.0
func (c *AudioPlayerController) Position() time.Duration
Position returns the current playback position.
func (*AudioPlayerController) SeekTo ¶ added in v0.11.0
func (c *AudioPlayerController) SeekTo(position time.Duration) error
SeekTo seeks to the given position.
func (*AudioPlayerController) SetLooping ¶ added in v0.11.0
func (c *AudioPlayerController) SetLooping(looping bool) error
SetLooping sets whether playback should loop.
func (*AudioPlayerController) SetPlaybackSpeed ¶ added in v0.11.0
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 ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *AudioPlayerController) State() PlaybackState
State returns the current playback state.
func (*AudioPlayerController) Stop ¶ added in v0.11.0
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 ¶
type BackgroundEvent struct {
TaskID string
EventType string
Data map[string]any
Timestamp time.Time
}
BackgroundEvent represents a background task event.
type BackgroundService ¶ added in v0.11.0
type BackgroundService struct {
// contains filtered or unexported fields
}
BackgroundService provides background task scheduling and event access.
var Background *BackgroundService
Background is the singleton background service.
func (*BackgroundService) Cancel ¶ added in v0.11.0
func (b *BackgroundService) Cancel(ctx context.Context, id string) error
Cancel cancels a scheduled background task.
func (*BackgroundService) CancelAll ¶ added in v0.11.0
func (b *BackgroundService) CancelAll(ctx context.Context) error
CancelAll cancels all scheduled background tasks.
func (*BackgroundService) CancelByTag ¶ added in v0.11.0
func (b *BackgroundService) CancelByTag(ctx context.Context, tag string) error
CancelByTag cancels all tasks with the given tag.
func (*BackgroundService) Complete ¶ added in v0.11.0
Complete signals completion of a background task.
func (*BackgroundService) Events ¶ added in v0.11.0
func (b *BackgroundService) Events() *Stream[BackgroundEvent]
Events returns a stream of background task events.
func (*BackgroundService) IsRefreshAvailable ¶ added in v0.11.0
func (b *BackgroundService) IsRefreshAvailable(ctx context.Context) (bool, error)
IsRefreshAvailable checks if background refresh is available.
func (*BackgroundService) Schedule ¶ added in v0.11.0
func (b *BackgroundService) Schedule(ctx context.Context, request TaskRequest) error
Schedule schedules a background task.
type BiometricType ¶ added in v0.5.0
type BiometricType string
BiometricType represents the type of biometric authentication available.
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 ¶ added in v0.7.0
type CalendarService struct {
// Permission for calendar access.
Permission Permission
}
CalendarService provides calendar access.
type CameraResult ¶
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
}
CameraResult represents the result of a camera or gallery operation.
type CameraService ¶ added in v0.7.0
type CameraService struct {
// Permission for camera access. Request before capturing photos.
Permission Permission
// contains filtered or unexported fields
}
CameraService provides camera capture and photo library access.
var Camera *CameraService
Camera is the singleton camera service.
func (*CameraService) CapturePhoto ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶
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
}
CapturePhotoOptions configures photo capture behavior.
type CapturedMedia ¶
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
}
CapturedMedia represents a captured or selected media file.
type CapturedViewGeometry ¶ added in v0.13.0
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
}
CapturedViewGeometry holds the resolved geometry for one platform view, captured during a StepFrame pass for synchronous application on the UI thread.
type ChannelError ¶
type ChannelError struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
}
ChannelError represents an error returned from native code.
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 ¶
type ClipboardData struct {
Text string `json:"text,omitempty"`
}
ClipboardData represents data on the clipboard.
type ClipboardService ¶
type ClipboardService struct {
// contains filtered or unexported fields
}
ClipboardService manages clipboard operations.
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 ¶ added in v0.7.0
type ContactsService struct {
// Permission for contacts access.
Permission Permission
}
ContactsService provides contacts/address book access.
type DatePickerConfig ¶ added in v0.6.0
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
}
DatePickerConfig contains configuration for the date picker modal.
type DeepLinkService ¶ added in v0.11.0
type DeepLinkService struct {
// contains filtered or unexported fields
}
DeepLinkService provides deep link event access.
var DeepLinks *DeepLinkService
DeepLinks is the singleton deep link service.
func (*DeepLinkService) GetInitial ¶ added in v0.11.0
func (d *DeepLinkService) GetInitial(ctx context.Context) (*DeepLink, error)
GetInitial returns the launch deep link, if available.
func (*DeepLinkService) Links ¶ added in v0.11.0
func (d *DeepLinkService) Links() *Stream[DeepLink]
Links returns a stream of deep link events.
type DeviceToken ¶
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
}
DeviceToken represents a device push token update.
type EdgeInsets ¶
type EdgeInsets struct {
Top, Bottom, Left, Right float64
}
EdgeInsets represents the safe area insets from system UI elements.
type EndOfStream ¶
type EndOfStream struct{}
EndOfStream is sent when an event stream terminates normally.
type Event ¶
type Event struct {
// Name identifies the event type.
Name string `json:"event"`
// Data contains the event payload.
Data any `json:"data,omitempty"`
}
Event represents an event sent from native to Go via an EventChannel.
type EventChannel ¶
type EventChannel struct {
// contains filtered or unexported fields
}
EventChannel provides stream-based event communication from native to Go.
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.
type EventError ¶
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"`
}
EventError represents an error that occurred in an event stream.
type EventHandler ¶
EventHandler receives events from an EventChannel.
type FileInfo ¶
type FileInfo struct {
Name string
Path string
Size int64
MimeType string
IsDirectory bool
LastModified int64
}
FileInfo contains metadata about a file.
type HapticFeedbackType ¶
type HapticFeedbackType string
HapticFeedbackType defines the type of haptic feedback.
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 ¶
type HapticsService struct {
// contains filtered or unexported fields
}
HapticsService manages haptic feedback.
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 ¶
type JsonCodec struct{}
JsonCodec implements MessageCodec using JSON encoding. JSON prioritizes interoperability and minimal native dependencies.
func (JsonCodec) DecodeInto ¶
DecodeInto deserializes JSON bytes into a specific type.
type KeyboardType ¶
type KeyboardType int
KeyboardType specifies the type of keyboard to show.
const ( KeyboardTypeText KeyboardType = iota KeyboardTypeNumber KeyboardTypePhone KeyboardTypeEmail KeyboardTypeURL KeyboardTypePassword KeyboardTypeMultiline )
type KeychainAccessibility ¶ added in v0.5.0
type KeychainAccessibility string
KeychainAccessibility determines when a keychain item is accessible (iOS-specific).
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 ¶
type LifecycleHandler func(state LifecycleState)
LifecycleHandler is called when lifecycle state changes.
type LifecycleService ¶
type LifecycleService struct {
// contains filtered or unexported fields
}
LifecycleService manages app lifecycle events.
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 ¶ added in v0.24.0
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 ¶
type LifecycleState string
LifecycleState represents the current app lifecycle state.
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 ¶
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
}
LocationOptions configures location update behavior.
type LocationService ¶ added in v0.7.0
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
}
LocationService provides location and GPS services. Context parameters are currently unused and reserved for future cancellation support.
var Location *LocationService
Location is the singleton location service.
func (*LocationService) GetCurrent ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
func (l *LocationService) Updates() *Stream[LocationUpdate]
Updates returns a stream of location updates.
type LocationUpdate ¶
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
}
LocationUpdate represents a location update from the device.
type MessageCodec ¶
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)
}
MessageCodec encodes and decodes messages for platform channel communication.
var DefaultCodec MessageCodec = JsonCodec{}
DefaultCodec is the codec used by platform channels.
type MethodCall ¶
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"`
}
MethodCall represents a method invocation from Go to native or vice versa.
type MethodChannel ¶
type MethodChannel struct {
// contains filtered or unexported fields
}
MethodChannel provides bidirectional method-call communication with native code.
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) 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 MethodResponse ¶
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"`
}
MethodResponse represents the result of a method call.
func (*MethodResponse) IsError ¶
func (r *MethodResponse) IsError() bool
IsError returns true if this response represents an error.
type MicrophoneService ¶ added in v0.7.0
type MicrophoneService struct {
// Permission for microphone access.
Permission Permission
}
MicrophoneService provides microphone access.
type NativeBridge ¶
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
}
NativeBridge defines the interface for calling native platform code.
type NotificationError ¶
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
}
NotificationError represents a notification-related error.
type NotificationEvent ¶
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
}
NotificationEvent represents a received notification.
type NotificationOpen ¶
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
}
NotificationOpen represents a user opening a notification.
type NotificationOptions ¶ added in v0.5.0
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
}
NotificationOptions configures which notification capabilities to request (iOS only). On Android, all capabilities are granted together; these options are ignored.
type NotificationPermission ¶ added in v0.7.0
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)
}
NotificationPermission extends Permission with notification-specific options.
type NotificationPermissionOptions ¶ added in v0.7.0
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+).
}
NotificationPermissionOptions configures notification capabilities (iOS only). Zero values mean the capability is NOT requested. Use Request() for defaults.
type NotificationRequest ¶
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
}
NotificationRequest describes a local notification schedule request.
type NotificationSettings ¶
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
}
NotificationSettings describes the current notification settings.
type NotificationsService ¶ added in v0.7.0
type NotificationsService struct {
// Permission for notification access. Implements NotificationPermission
// for iOS-specific options.
Permission NotificationPermission
// contains filtered or unexported fields
}
NotificationsService provides local and push notification management.
var Notifications *NotificationsService
Notifications is the singleton notifications service.
func (*NotificationsService) Cancel ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.11.0
func (n *NotificationsService) DeletePushToken(ctx context.Context) error
DeletePushToken deletes the current push token.
func (*NotificationsService) Deliveries ¶ added in v0.7.0
func (n *NotificationsService) Deliveries() *Stream[NotificationEvent]
Deliveries returns a stream of delivered notifications.
func (*NotificationsService) Errors ¶ added in v0.7.0
func (n *NotificationsService) Errors() *Stream[NotificationError]
Errors returns a stream of notification errors.
func (*NotificationsService) GetPushToken ¶ added in v0.11.0
func (n *NotificationsService) GetPushToken(ctx context.Context) (string, error)
GetPushToken returns the current push token if available.
func (*NotificationsService) Opens ¶ added in v0.7.0
func (n *NotificationsService) Opens() *Stream[NotificationOpen]
Opens returns a stream of notification open events (user tapped notification).
func (*NotificationsService) RegisterForPush ¶ added in v0.11.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶ added in v0.11.0
func (n *NotificationsService) SubscribeToTopic(ctx context.Context, topic string) error
SubscribeToTopic subscribes to a push notification topic.
func (*NotificationsService) Tokens ¶ added in v0.7.0
func (n *NotificationsService) Tokens() *Stream[DeviceToken]
Tokens returns a stream of device push token updates.
func (*NotificationsService) UnsubscribeFromTopic ¶ added in v0.11.0
func (n *NotificationsService) UnsubscribeFromTopic(ctx context.Context, topic string) error
UnsubscribeFromTopic unsubscribes from a push notification topic.
type Permission ¶
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())
}
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 PermissionResult ¶
type PermissionResult string
PermissionResult represents the status of a permission.
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" )
Permission status constants.
type PermissionStatus ¶
type PermissionStatus = PermissionResult
PermissionStatus represents the current state of a permission. This is an alias for PermissionResult for naming consistency.
type PhotosService ¶ added in v0.7.0
type PhotosService struct {
// Permission for photo library access.
Permission Permission
}
PhotosService provides photo library access.
type PickFileOptions ¶
type PickFileOptions struct {
AllowMultiple bool
AllowedTypes []string
InitialDir string
DialogTitle string
}
PickFileOptions configures file picker behavior.
type PickFromGalleryOptions ¶
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
}
PickFromGalleryOptions configures gallery picker behavior.
type PickedFile ¶
PickedFile represents a file selected by the user.
type PlatformView ¶
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()
}
PlatformView represents a native view embedded in Drift UI.
type PlatformViewFactory ¶
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
}
PlatformViewFactory creates platform views of a specific type.
type PlatformViewRegistry ¶
type PlatformViewRegistry struct {
// contains filtered or unexported fields
}
PlatformViewRegistry manages platform view types and instances.
func GetPlatformViewRegistry ¶
func GetPlatformViewRegistry() *PlatformViewRegistry
GetPlatformViewRegistry returns the global platform view registry.
func (*PlatformViewRegistry) BeginGeometryBatch ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.13.0
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 ¶ added in v0.10.0
func (r *PlatformViewRegistry) ViewCount() int
ViewCount returns the number of active platform views.
type PlaybackState ¶ added in v0.11.0
type PlaybackState int
PlaybackState represents the current state of audio or video playback. Errors are delivered through separate error callbacks rather than as a playback state.
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 ¶ added in v0.11.0
func (s PlaybackState) String() string
String returns a human-readable label for the playback state.
type PreferencesService ¶ added in v0.12.0
type PreferencesService struct {
// contains filtered or unexported fields
}
PreferencesService manages simple key-value preference storage.
func (*PreferencesService) Contains ¶ added in v0.12.0
func (p *PreferencesService) Contains(key string) (bool, error)
Contains checks if a key exists in preferences.
func (*PreferencesService) Delete ¶ added in v0.12.0
func (p *PreferencesService) Delete(key string) error
Delete removes the value for the given key.
func (*PreferencesService) DeleteAll ¶ added in v0.12.0
func (p *PreferencesService) DeleteAll() error
DeleteAll removes all values from preferences.
func (*PreferencesService) Get ¶ added in v0.12.0
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 ¶ added in v0.12.0
func (p *PreferencesService) GetAllKeys() ([]string, error)
GetAllKeys returns all keys stored in preferences.
func (*PreferencesService) Set ¶ added in v0.12.0
func (p *PreferencesService) Set(key, value string) error
Set stores a string value for the given key.
type SafeAreaService ¶
type SafeAreaService struct {
// contains filtered or unexported fields
}
SafeAreaService manages safe area inset events.
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 ¶
type SaveFileOptions struct {
SuggestedName string
MimeType string
InitialDir string
DialogTitle string
}
SaveFileOptions configures save file dialog behavior.
type SecureStorageError ¶ added in v0.5.0
SecureStorageError represents errors from secure storage operations.
func (*SecureStorageError) Error ¶ added in v0.5.0
func (e *SecureStorageError) Error() string
type SecureStorageEvent ¶ added in v0.5.0
type SecureStorageEvent struct {
Type string // "auth_result"
Success bool
Key string
Value string // Only for get operations
Error string // Error code if failed
}
SecureStorageEvent represents an async result from a secure storage operation.
type SecureStorageOptions ¶ added in v0.5.0
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
}
SecureStorageOptions configures secure storage operations.
type SecureStorageService ¶ added in v0.5.0
type SecureStorageService struct {
// contains filtered or unexported fields
}
SecureStorageService manages secure storage operations.
func (*SecureStorageService) Contains ¶ added in v0.5.0
func (s *SecureStorageService) Contains(key string, opts *SecureStorageOptions) (bool, error)
Contains checks if a key exists in secure storage.
func (*SecureStorageService) Delete ¶ added in v0.5.0
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 ¶ added in v0.5.0
func (s *SecureStorageService) DeleteAll(opts *SecureStorageOptions) error
DeleteAll removes all values from secure storage.
func (*SecureStorageService) Get ¶ added in v0.5.0
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 ¶ added in v0.5.0
func (s *SecureStorageService) GetAllKeys(opts *SecureStorageOptions) ([]string, error)
GetAllKeys returns all keys stored in secure storage.
func (*SecureStorageService) GetBiometricType ¶ added in v0.5.0
func (s *SecureStorageService) GetBiometricType() (BiometricType, error)
GetBiometricType returns the type of biometric authentication available on the device.
func (*SecureStorageService) IsBiometricAvailable ¶ added in v0.5.0
func (s *SecureStorageService) IsBiometricAvailable() (bool, error)
IsBiometricAvailable checks if biometric authentication is available on the device.
func (*SecureStorageService) Listen ¶ added in v0.5.0
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 ¶ added in v0.5.0
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 ShareResult ¶
type ShareResult string
ShareResult indicates the result of a share operation.
const ( ShareResultSuccess ShareResult = "success" ShareResultDismissed ShareResult = "dismissed" ShareResultUnavailable ShareResult = "unavailable" )
type ShareService ¶
type ShareService struct {
// contains filtered or unexported fields
}
ShareService manages sharing content with other apps.
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 ¶
type StatusBarStyle string
StatusBarStyle indicates the status bar icon color scheme.
const ( StatusBarStyleDefault StatusBarStyle = "default" StatusBarStyleLight StatusBarStyle = "light" StatusBarStyleDark StatusBarStyle = "dark" )
type StorageResult ¶
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
}
StorageResult represents a result from storage picker operations.
type StorageService ¶ added in v0.11.0
type StorageService struct {
// contains filtered or unexported fields
}
StorageService provides file picking, saving, and file system access.
var Storage *StorageService
Storage is the singleton storage service.
func (*StorageService) DeleteFile ¶ added in v0.11.0
func (s *StorageService) DeleteFile(pathOrURI string) error
DeleteFile deletes a file.
func (*StorageService) GetAppDirectory ¶ added in v0.11.0
func (s *StorageService) GetAppDirectory(dir AppDirectory) (string, error)
GetAppDirectory returns the path to a standard app directory.
func (*StorageService) GetFileInfo ¶ added in v0.11.0
func (s *StorageService) GetFileInfo(pathOrURI string) (*FileInfo, error)
GetFileInfo returns metadata about a file.
func (*StorageService) PickDirectory ¶ added in v0.11.0
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 ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (s *StorageService) ReadFile(pathOrURI string) ([]byte, error)
ReadFile reads the contents of a file.
func (*StorageService) SaveFile ¶ added in v0.11.0
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.
type Stream ¶ added in v0.7.0
type Stream[T any] struct { // contains filtered or unexported fields }
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.
func NewStream ¶ added in v0.7.0
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 ¶ added in v0.7.0
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 ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription represents an active event subscription.
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 ¶ added in v0.6.0
type SwitchView struct {
// contains filtered or unexported fields
}
SwitchView is a platform view for native switch control.
func NewSwitchView ¶ added in v0.6.0
func NewSwitchView(viewID int64, config SwitchViewConfig, client SwitchViewClient) *SwitchView
NewSwitchView creates a new switch platform view.
func (*SwitchView) Create ¶ added in v0.6.0
func (v *SwitchView) Create(params map[string]any) error
Create initializes the native view.
func (*SwitchView) Dispose ¶ added in v0.6.0
func (v *SwitchView) Dispose()
Dispose cleans up the native view.
func (*SwitchView) SetClient ¶ added in v0.6.0
func (v *SwitchView) SetClient(client SwitchViewClient)
SetClient sets the callback client for this view.
func (*SwitchView) SetEnabled ¶ added in v0.6.0
func (v *SwitchView) SetEnabled(enabled bool)
func (*SwitchView) SetValue ¶ added in v0.6.0
func (v *SwitchView) SetValue(value bool)
SetValue updates the switch value from Go side.
func (*SwitchView) UpdateConfig ¶ added in v0.6.0
func (v *SwitchView) UpdateConfig(config SwitchViewConfig)
UpdateConfig updates the view configuration.
func (*SwitchView) Value ¶ added in v0.6.0
func (v *SwitchView) Value() bool
Value returns the current value.
type SwitchViewClient ¶ added in v0.6.0
type SwitchViewClient interface {
// OnValueChanged is called when the switch value changes.
OnValueChanged(value bool)
}
SwitchViewClient receives callbacks from native switch view.
type SwitchViewConfig ¶ added in v0.6.0
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
}
SwitchViewConfig defines styling passed to native switch view.
type SystemUIStyle ¶
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)
}
SystemUIStyle describes system bar and window styling.
type TaskConstraints ¶
type TaskConstraints struct {
RequiresNetwork bool
RequiresUnmeteredNetwork bool
RequiresCharging bool
RequiresIdle bool
RequiresStorageNotLow bool
RequiresBatteryNotLow bool
}
TaskConstraints defines constraints for when a task should run.
type TaskRequest ¶
type TaskRequest struct {
ID string
TaskType TaskType
Tag string
Constraints TaskConstraints
InitialDelay time.Duration
RepeatInterval time.Duration
Data map[string]any
}
TaskRequest describes a background task to schedule.
type TextAffinity ¶
type TextAffinity int
TextAffinity describes which side of a position the caret prefers.
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 ¶
type TextCapitalization int
TextCapitalization specifies text capitalization behavior.
const ( TextCapitalizationNone TextCapitalization = iota TextCapitalizationCharacters TextCapitalizationWords TextCapitalizationSentences )
type TextEditingController ¶
type TextEditingController struct {
// contains filtered or unexported fields
}
TextEditingController manages text input state.
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 ¶
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
}
TextEditingValue represents the current text editing state.
func (TextEditingValue) IsComposing ¶
func (v TextEditingValue) IsComposing() bool
IsComposing returns true if there is an active IME composition.
type TextInputAction ¶
type TextInputAction int
TextInputAction specifies the action button on the keyboard.
const ( TextInputActionNone TextInputAction = iota TextInputActionDone TextInputActionGo TextInputActionNext TextInputActionPrevious TextInputActionSearch TextInputActionSend TextInputActionNewline )
type TextInputView ¶ added in v0.6.0
type TextInputView struct {
// contains filtered or unexported fields
}
TextInputView is a platform view for text input.
func NewTextInputView ¶ added in v0.6.0
func NewTextInputView(viewID int64, config TextInputViewConfig, client TextInputViewClient) *TextInputView
NewTextInputView creates a new text input platform view.
func (*TextInputView) Blur ¶ added in v0.6.0
func (v *TextInputView) Blur()
Blur dismisses the keyboard.
func (*TextInputView) Create ¶ added in v0.6.0
func (v *TextInputView) Create(params map[string]any) error
Create initializes the native view.
func (*TextInputView) Dispose ¶ added in v0.6.0
func (v *TextInputView) Dispose()
Dispose cleans up the native view.
func (*TextInputView) Focus ¶ added in v0.6.0
func (v *TextInputView) Focus()
Focus requests keyboard focus for the text input.
func (*TextInputView) IsFocused ¶ added in v0.6.0
func (v *TextInputView) IsFocused() bool
IsFocused returns whether the view has focus.
func (*TextInputView) Selection ¶ added in v0.6.0
func (v *TextInputView) Selection() (base, extent int)
Selection returns the current selection.
func (*TextInputView) SetClient ¶ added in v0.6.0
func (v *TextInputView) SetClient(client TextInputViewClient)
SetClient sets the callback client for this view.
func (*TextInputView) SetEnabled ¶ added in v0.6.0
func (v *TextInputView) SetEnabled(enabled bool)
func (*TextInputView) SetSelection ¶ added in v0.6.0
func (v *TextInputView) SetSelection(base, extent int)
SetSelection updates the cursor/selection position.
func (*TextInputView) SetText ¶ added in v0.6.0
func (v *TextInputView) SetText(text string)
SetText updates the text content from Go side.
func (*TextInputView) SetValue ¶ added in v0.6.0
func (v *TextInputView) SetValue(value TextEditingValue)
SetValue updates both text and selection atomically.
func (*TextInputView) Snapshot ¶ added in v0.12.0
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 ¶ added in v0.6.0
func (v *TextInputView) Text() string
Text returns the current text.
func (*TextInputView) UpdateConfig ¶ added in v0.6.0
func (v *TextInputView) UpdateConfig(config TextInputViewConfig)
UpdateConfig updates the view configuration.
type TextInputViewClient ¶ added in v0.6.0
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)
}
TextInputViewClient receives callbacks from native text input view.
type TextInputViewConfig ¶ added in v0.6.0
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
}
TextInputViewConfig defines styling passed to native text view.
type TextRange ¶
TextRange represents a range of text.
func (TextRange) IsNormalized ¶
IsNormalized returns true if start <= end.
type TextSelection ¶
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
}
TextSelection represents the current text selection.
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 ¶ added in v0.6.0
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
}
TimePickerConfig contains configuration for the time picker modal.
type TimePickerResult ¶ added in v0.6.0
TimePickerResult contains the selected time.
type URLLauncherService ¶ added in v0.12.0
type URLLauncherService struct {
// contains filtered or unexported fields
}
URLLauncherService manages opening URLs in the system browser.
func (*URLLauncherService) CanOpenURL ¶ added in v0.12.0
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 ¶ added in v0.12.0
func (u *URLLauncherService) OpenURL(rawURL string) error
OpenURL opens the given URL in the system browser.
type VideoPlayerController ¶ added in v0.11.0
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
}
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.UseController]:
s.video = core.UseController(&s.StateBase, platform.NewVideoPlayerController)
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 or a UseController callback). Setting them before calling Load ensures no events are missed.
func NewVideoPlayerController ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *VideoPlayerController) Buffered() time.Duration
Buffered returns the buffered position.
func (*VideoPlayerController) Dispose ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *VideoPlayerController) Duration() time.Duration
Duration returns the total media duration.
func (*VideoPlayerController) Load ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *VideoPlayerController) Pause() error
Pause pauses playback.
func (*VideoPlayerController) Play ¶ added in v0.11.0
func (c *VideoPlayerController) Play() error
Play starts or resumes playback. Call VideoPlayerController.Load first to set the media URL.
func (*VideoPlayerController) Position ¶ added in v0.11.0
func (c *VideoPlayerController) Position() time.Duration
Position returns the current playback position.
func (*VideoPlayerController) SeekTo ¶ added in v0.11.0
func (c *VideoPlayerController) SeekTo(position time.Duration) error
SeekTo seeks to the given position.
func (*VideoPlayerController) SetLooping ¶ added in v0.11.0
func (c *VideoPlayerController) SetLooping(looping bool) error
SetLooping sets whether playback should loop.
func (*VideoPlayerController) SetPlaybackSpeed ¶ added in v0.11.0
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 ¶ added in v0.13.0
func (c *VideoPlayerController) SetShowControls(show bool) error
SetShowControls shows or hides the native transport controls.
func (*VideoPlayerController) SetVolume ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *VideoPlayerController) State() PlaybackState
State returns the current playback state.
func (*VideoPlayerController) Stop ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *VideoPlayerController) ViewID() int64
ViewID returns the platform view ID, or 0 if the view was not created.
type WebViewController ¶ added in v0.11.0
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
}
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.UseController]:
s.web = core.UseController(&s.StateBase, platform.NewWebViewController)
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.
func NewWebViewController ¶ added in v0.11.0
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 ¶ added in v0.11.0
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 ¶ added in v0.11.0
func (c *WebViewController) GoBack() error
GoBack navigates back in history.
func (*WebViewController) GoForward ¶ added in v0.11.0
func (c *WebViewController) GoForward() error
GoForward navigates forward in history.
func (*WebViewController) Load ¶ added in v0.11.0
func (c *WebViewController) Load(url string) error
Load loads the specified URL.
func (*WebViewController) Reload ¶ added in v0.11.0
func (c *WebViewController) Reload() error
Reload reloads the current page.
func (*WebViewController) ViewID ¶ added in v0.11.0
func (c *WebViewController) ViewID() int64
ViewID returns the platform view ID, or 0 if the view was not created.
Source Files
¶
- activityindicator_view.go
- audio_player.go
- background.go
- calendar.go
- camera.go
- channel.go
- clipboard.go
- codec.go
- contacts.go
- convert.go
- datepicker_channel.go
- deeplinks.go
- dispatch.go
- doc.go
- errors.go
- haptics.go
- lifecycle.go
- location.go
- media_error.go
- message.go
- microphone.go
- notification_permission.go
- notifications.go
- permission_interface.go
- permissions.go
- photos.go
- platform_view.go
- playback_state.go
- preferences.go
- registry.go
- safe_area.go
- secure_storage.go
- share.go
- storage.go
- stream.go
- switch_view.go
- system_ui.go
- testing_helpers.go
- textinput.go
- textinput_view.go
- timepicker_channel.go
- url_launcher.go
- video_player_controller.go
- video_player_view.go
- webview_controller.go
- webview_error.go
- webview_view.go