platform
Package platform provides global singletons for platform services.
It assumes a single application per process. Platform services are initialized during package init and activated when SetNativeBridge is called by the bridge package.
Global Services
The package exposes singleton services for platform capabilities: Lifecycle, SafeArea, Accessibility, Haptics, Clipboard, etc. These are safe for concurrent use from any goroutine.
Layer Boundary Types
This package defines its own EdgeInsets struct as a simple 4-field data carrier from native code. This is intentionally separate from [layout.EdgeInsets], which is the canonical app-facing type with rich helper methods (Horizontal, Vertical, Add, etc.). Conversion between the two occurs at the layer boundary in the widgets package (e.g., the SafeArea widget).
Similarly, the PointerEvent/PointerPhase types in the engine package represent raw device-pixel input from embedders, while the gestures package defines its own processed versions with logical coordinates. These duplications are intentional: collapsing them would couple embedder APIs to framework internals.
Variables
Standard errors for platform channel operations.
var (
// ErrChannelNotFound indicates the requested platform channel does not exist.
ErrChannelNotFound = errors.New("platform channel not found")
// ErrMethodNotFound indicates the method is not implemented on the native side.
ErrMethodNotFound = errors.New("method not implemented")
// ErrInvalidArguments indicates the arguments passed to the method were invalid.
ErrInvalidArguments = errors.New("invalid arguments")
// ErrPlatformUnavailable indicates the platform feature is not available
// (e.g., hardware not present, OS version too old).
ErrPlatformUnavailable = errors.New("platform feature unavailable")
// ErrTimeout indicates the operation exceeded its deadline. For permission requests,
// this means the user did not respond to the dialog within the timeout period.
ErrTimeout = errors.New("operation timed out")
// ErrCanceled indicates the operation was canceled via context cancellation.
ErrCanceled = errors.New("operation was canceled")
// ErrViewTypeNotFound indicates the platform view type is not registered.
ErrViewTypeNotFound = errors.New("platform view type not registered")
// ErrBlocksUIThread indicates the UI thread called a native method that
// replies asynchronously. The UI thread cannot wait for such a reply
// (the reply may need the UI thread), so native refuses the call before
// running it, every time. Call the method from a goroutine and publish
// its result, for example through a Signal.
ErrBlocksUIThread = errors.New("method replies asynchronously; call it from a goroutine, not the UI thread")
// ErrReplyDropped indicates native discarded a method call's reply
// without answering it, a bug in the native handler.
ErrReplyDropped = errors.New("native handler dropped the call without replying")
// ErrNotEncodable indicates native produced a reply or an event that
// is not JSON-like (a NaN, an Infinity, or a type outside null,
// booleans, numbers, strings, lists and string-keyed maps), a bug in
// the native handler. A method call fails with it; an event stream
// delivers it to OnError in place of the event. The message names the
// call or channel and the offending part of the value.
ErrNotEncodable = errors.New("native value is not JSON-like")
// ErrPermissionNotRegistered indicates no native code registered the
// permission kind: the plugin providing it is missing from drift.yaml,
// or not configured for that kind.
ErrPermissionNotRegistered = errors.New("permission kind not registered")
// ErrPermissionNotDeclared indicates the Android manifest does not
// declare a permission the kind needs, so Android would deny it without
// asking. Add the plugin that declares it to drift.yaml.
ErrPermissionNotDeclared = errors.New("permission not declared in the Android manifest")
)
Web view load failures, the same on Android and iOS. A WebViewController's Errors stream delivers them as errors matching these under errors.Is, with the platform's message.
var (
// ErrWebViewNetwork indicates a network-level failure such as DNS
// resolution, connectivity or a timeout.
ErrWebViewNetwork = errors.New("web page could not be reached")
// ErrWebViewSSL indicates a TLS or certificate failure, such as an
// untrusted or expired certificate.
ErrWebViewSSL = errors.New("web page's secure connection failed")
// ErrWebViewLoadFailed indicates any other page load failure.
ErrWebViewLoadFailed = errors.New("web page failed to load")
)
Accessibility is the global accessibility channel instance.
var Accessibility = &accessibilityChannel{
method: NewMethodChannel(accessibilityMethodChannel),
stateEvents: NewEventChannel(accessibilityStateChannel),
actionEvents: NewEventChannel(accessibilityActionsChannel),
}
ClipboardService provides access to the system clipboard.
var Clipboard = &ClipboardService{
channel: NewMethodChannel("drift/clipboard"),
}
ErrChannelNotRegistered is returned when an event is received for an unregistered channel.
var ErrChannelNotRegistered = fmt.Errorf("event channel not registered")
Sentinel errors for platform operations.
var (
// ErrDisposed is returned when a method is called on a controller that
// has already been disposed, or whose underlying resource failed to
// create. Check for this with [errors.Is] when you need to distinguish
// a no-op from a successful operation.
ErrDisposed = errors.New("platform: controller disposed")
)
ErrPickerCancelled is returned when the user cancels the picker.
var ErrPickerCancelled = errors.New("picker cancelled")
ErrStorageBusy is returned when a storage picker is already open.
var ErrStorageBusy = errors.New("storage picker operation already in progress")
HapticsService provides haptic feedback functionality.
var Haptics = &HapticsService{
channel: NewMethodChannel("drift/haptics"),
}
LifecycleService provides app lifecycle state management.
var Lifecycle = &LifecycleService{
channel: NewMethodChannel("drift/lifecycle"),
events: NewEventChannel("drift/lifecycle/events"),
state: LifecycleStateResumed,
handlers: make([]LifecycleHandler, 0),
}
Notifications is the singleton notifications service.
var Notifications = &NotificationsService{Permission: newNotificationPerm()}
Preferences provides simple, unencrypted key-value storage using platform-native mechanisms (UserDefaults on iOS, SharedPreferences on Android). For sensitive data, use SecureStorage instead.
var Preferences = &PreferencesService{
channel: NewMethodChannel("drift/preferences"),
}
SafeArea provides safe area inset management.
var SafeArea = &SafeAreaService{
events: NewEventChannel("drift/safe_area/events"),
insets: EdgeInsets{},
}
ShareService provides access to the system share sheet.
var Share = &ShareService{
channel: NewMethodChannel("drift/share"),
}
Storage is the singleton storage service.
var Storage = &StorageService{channel: NewMethodChannel("drift/storage").WithErrors(ErrorCodes{
"storage_busy": ErrStorageBusy,
"platform_unavailable": ErrPlatformUnavailable,
})}
TextEditingValueEmpty is the default empty editing value.
var TextEditingValueEmpty = TextEditingValue{
Selection: TextSelectionCollapsed(0),
ComposingRange: TextRangeEmpty,
}
TextRangeEmpty is an invalid/empty text range.
var TextRangeEmpty = TextRange{Start: -1, End: -1}
URLLauncher provides access to the system URL launcher.
var URLLauncher = &URLLauncherService{
channel: NewMethodChannel("drift/url_launcher"),
}
func Dispatch
func Dispatch(callback func()) bool
Dispatch schedules a callback to run on the UI thread. Returns true if the callback was successfully scheduled, false if no dispatch function is registered or the callback is nil.
func GetFocusedTarget
func GetFocusedTarget() any
GetFocusedTarget returns the render object that currently has keyboard focus.
func HandleEvent
func HandleEvent(channel string, eventData []byte) error
HandleEvent is called from the bridge when native sends an event.
func HandleEventDone
func HandleEventDone(channel string) error
HandleEventDone is called from the bridge when an event stream ends.
func HandleEventError
func HandleEventError(channel string, err *ChannelError) error
HandleEventError is called from the bridge when an event stream errors, with the error native sent.
func HandleNativeConnected
func HandleNativeConnected()
HandleNativeConnected is called from the bridge once native has registered its method handler. It tells native about every event channel that already has subscribers (from package init, say), whose listen requests failed while native was not connected.
func HasFocus
func HasFocus() bool
HasFocus returns true if there is currently a focused text input.
func InitializeAccessibility
func InitializeAccessibility()
InitializeAccessibility sets up the accessibility system with the semantics binding.
func OpenAppSettings
func OpenAppSettings() error
OpenAppSettings opens the system settings page for this app, where users can manage permissions manually. Use this when a permission is permanently denied and the app cannot request it again.
On iOS, opens the Settings app to the app's settings page. On Android, opens the App Info screen in system settings.
func RegisterActivityIndicatorViewFactory
func RegisterActivityIndicatorViewFactory()
RegisterActivityIndicatorViewFactory registers the activity indicator view factory.
func RegisterDispatch
func RegisterDispatch(fn func(callback func()))
RegisterDispatch sets the dispatch function used to schedule callbacks on the UI thread. This should be called once by the engine during initialization.
func RegisterSwitchViewFactory
func RegisterSwitchViewFactory()
RegisterSwitchViewFactory registers the switch view factory.
func RegisterTextInputViewFactory
func RegisterTextInputViewFactory()
toFloat64 converts various numeric types to float64. RegisterTextInputViewFactory registers the text input view factory.
func ResetForTest
func ResetForTest()
ResetForTest resets all global platform state for test isolation. It clears the native bridge, resets cached state (lifecycle, safe area), removes all event subscriptions, and re-registers the built-in init-time listeners (lifecycle, safe area, accessibility) so that the package behaves as if freshly initialized. This should only be called from tests.
func SetFocusedInput
func SetFocusedInput(viewID int64, focused bool)
SetFocusedInput marks a text input view as focused.
func SetFocusedTarget
func SetFocusedTarget(target any)
SetFocusedTarget sets the render object that currently has keyboard focus.
func SetNativeBridge
func SetNativeBridge(bridge NativeBridge)
SetNativeBridge sets the native bridge implementation. Called by the bridge package during initialization.
func SetSystemUI
func SetSystemUI(style SystemUIStyle) error
SetSystemUI updates the system UI appearance.
func SetupTestBridge
func SetupTestBridge(cleanup func(func()))
SetupTestBridge installs a no-op native bridge and synchronous dispatch function for testing. The cleanup function should be testing.T.Cleanup or equivalent; it registers a teardown that calls ResetForTest.
platform.SetupTestBridge(t.Cleanup)
func ShowDatePicker
func ShowDatePicker(ctx context.Context, config DatePickerConfig) (time.Time, error)
ShowDatePicker shows the native date picker and returns the chosen date, at midnight in time.Local, or ErrPickerCancelled. Dates cross the channel as calendar days (year, month, day in each time's own location), so no time zone shifts them. It waits for the user, so call it from a goroutine: from the UI thread it fails with ErrBlocksUIThread.
func ShowTimePicker
func ShowTimePicker(ctx context.Context, config TimePickerConfig) (hour, minute int, err error)
ShowTimePicker shows the native time picker and returns the chosen hour and minute, or ErrPickerCancelled. It waits for the user, so call it from a goroutine: from the UI thread it fails with ErrBlocksUIThread.
func UnfocusAll
func UnfocusAll()
UnfocusAll dismisses the keyboard and clears focus for all text inputs.
func UseLifecycleObserver
func UseLifecycleObserver(s disposable, handler LifecycleHandler)
UseLifecycleObserver subscribes to app lifecycle changes with automatic cleanup. The handler is dispatched to the UI thread via Dispatch (or called synchronously when no dispatch is registered, e.g. in tests).
Call once in InitState, not in Build.
func (s *myState) InitState() {
platform.UseLifecycleObserver(s, func(state platform.LifecycleState) {
if state == platform.LifecycleStatePaused {
s.saveProgress()
}
})
}
type ActivityIndicatorSize
ActivityIndicatorSize represents the size of the activity indicator.
type ActivityIndicatorSize int
const (
// ActivityIndicatorSizeMedium is a medium spinner.
ActivityIndicatorSizeMedium ActivityIndicatorSize = iota
// ActivityIndicatorSizeSmall is a small spinner.
ActivityIndicatorSizeSmall
// ActivityIndicatorSizeLarge is a large spinner.
ActivityIndicatorSizeLarge
)
type ActivityIndicatorView
ActivityIndicatorView is a platform view for native activity indicator.
type ActivityIndicatorView struct {
PlatformViewBase
// contains filtered or unexported fields
}
func NewActivityIndicatorView
func NewActivityIndicatorView(viewID int64, config ActivityIndicatorViewConfig) *ActivityIndicatorView
NewActivityIndicatorView creates a new activity indicator platform view.
func (*ActivityIndicatorView) Create
func (v *ActivityIndicatorView) Create(params map[string]any) error
Create initializes the native view.
func (*ActivityIndicatorView) Dispose
func (v *ActivityIndicatorView) Dispose()
Dispose cleans up the native view.
func (*ActivityIndicatorView) HandleEvent
func (v *ActivityIndicatorView) HandleEvent(method string, _ map[string]any) error
HandleEvent implements PlatformView; the native indicator sends no events.
func (*ActivityIndicatorView) IsAnimating
func (v *ActivityIndicatorView) IsAnimating() bool
IsAnimating returns whether the indicator is currently animating.
func (*ActivityIndicatorView) SetAnimating
func (v *ActivityIndicatorView) SetAnimating(animating bool)
SetAnimating starts or stops the animation.
func (*ActivityIndicatorView) UpdateConfig
func (v *ActivityIndicatorView) UpdateConfig(config ActivityIndicatorViewConfig)
UpdateConfig updates the view configuration.
type ActivityIndicatorViewConfig
ActivityIndicatorViewConfig defines styling passed to native activity indicator.
type ActivityIndicatorViewConfig struct {
// Animating controls whether the indicator is spinning.
Animating bool
// Size is the indicator size (Small, Medium, Large).
Size ActivityIndicatorSize
// Color is the spinner color (ARGB).
Color uint32
}
type AnnouncePoliteness
AnnouncePoliteness indicates the urgency of an accessibility announcement.
type AnnouncePoliteness int
const (
// AnnouncePolitenessPolite is for non-urgent announcements that don't interrupt.
AnnouncePolitenessPolite AnnouncePoliteness = iota
// AnnouncePolitenessAssertive is for important announcements that should interrupt.
AnnouncePolitenessAssertive
)
type AppDirectory
AppDirectory represents standard app directories.
type AppDirectory string
const (
AppDirectoryDocuments AppDirectory = "documents"
AppDirectoryCache AppDirectory = "cache"
AppDirectoryTemp AppDirectory = "temp"
AppDirectorySupport AppDirectory = "support"
)
type CapturedViewGeometry
CapturedViewGeometry holds the resolved geometry for one platform view, captured during a StepFrame pass for synchronous application on the UI thread.
type CapturedViewGeometry struct {
ViewID int64
Offset graphics.Offset
Size graphics.Size
ClipBounds *graphics.Rect // collapsed single-rect after occlusion subtraction (Android fallback); nil if unclipped
VisibleRect graphics.Rect // view bounds intersected with parent clips; {0,0,0,0} if hidden
OcclusionPaths []*graphics.Path // path-based occlusion masks; [] if none
}
type ChannelError
ChannelError represents an error returned from native code.
type ChannelError struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
// contains filtered or unexported fields
}
func NewChannelError
func NewChannelError(code, message string) *ChannelError
NewChannelError creates a new ChannelError with the given code and message.
func NewChannelErrorWithDetails
func NewChannelErrorWithDetails(code, message string, details any) *ChannelError
NewChannelErrorWithDetails creates a new ChannelError with additional details.
func (*ChannelError) Error
func (e *ChannelError) Error() string
func (*ChannelError) Is
func (e *ChannelError) Is(target error) bool
Is reports whether e carries target's wire code: a transport code, such as "blocks_ui_thread" for ErrBlocksUIThread, or one its channel declared (ErrorCodes).
type ClipboardData
ClipboardData represents data on the clipboard.
type ClipboardData struct {
Text string `json:"text,omitempty"`
}
type ClipboardService
ClipboardService manages clipboard operations.
type ClipboardService struct {
// contains filtered or unexported fields
}
func (*ClipboardService) Clear
func (c *ClipboardService) Clear() error
Clear removes all data from the clipboard.
func (*ClipboardService) GetText
func (c *ClipboardService) GetText() (string, error)
GetText retrieves text from the clipboard. Returns empty string if clipboard is empty or contains non-text data.
func (*ClipboardService) HasText
func (c *ClipboardService) HasText() (bool, error)
HasText returns true if the clipboard contains text.
func (*ClipboardService) SetText
func (c *ClipboardService) SetText(text string) error
SetText copies text to the clipboard.
type DatePickerConfig
DatePickerConfig contains configuration for the date picker modal.
type DatePickerConfig struct {
// InitialDate is the initially selected date.
InitialDate time.Time
// MinDate is the minimum selectable date (optional).
MinDate *time.Time
// MaxDate is the maximum selectable date (optional).
MaxDate *time.Time
}
type DeepLink
DeepLink describes an incoming deep link.
type DeepLink struct {
URL string
Source string
Timestamp time.Time
}
type DeepLinkService
DeepLinkService provides deep link event access.
type DeepLinkService struct {
// contains filtered or unexported fields
}
DeepLinks is the singleton deep link service.
var DeepLinks *DeepLinkService
func (*DeepLinkService) GetInitial
func (d *DeepLinkService) GetInitial() (*DeepLink, error)
GetInitial returns the launch deep link, if available.
func (*DeepLinkService) Links
func (d *DeepLinkService) Links() *Stream[DeepLink]
Links returns a stream of deep link events.
type EdgeInsets
EdgeInsets represents the safe area insets from system UI elements.
type EdgeInsets struct {
Top, Bottom, Left, Right float64
}
type Emitter
Emitter feeds a Stream from Go, for events that do not arrive on an event channel of their own: a plugin's runtime half that receives one view's or one player's events and republishes them, say. Delivery is live: subscribers receive what is emitted after they listen.
type Emitter[T any] struct {
// contains filtered or unexported fields
}
func NewEmitter
func NewEmitter[T any](name string) *Emitter[T]
NewEmitter returns an emitter and its stream. name identifies the stream in error reports.
func (*Emitter[T]) Emit
func (e *Emitter[T]) Emit(value T)
Emit delivers value to the stream's subscribers, on the calling goroutine.
func (*Emitter[T]) Error
func (e *Emitter[T]) Error(err error)
Error delivers err to the stream's subscribers (their OnError), on the calling goroutine.
func (*Emitter[T]) Stream
func (e *Emitter[T]) Stream() *Stream[T]
Stream returns the stream the emitter feeds.
type ErrorCodes
ErrorCodes maps the wire codes a channel's native side answers with to the sentinel errors they match. Declare a channel's codes once, with MethodChannel.WithErrors (and EventChannel.WithErrors for its stream): every error the channel returns or streams is then a \*ChannelError that matches its code's sentinel under errors.Is, with the native message kept.
var ErrDenied = errors.New("acme: permission denied")
var errorCodes = platform.ErrorCodes{"permission_denied": ErrDenied}
var channel = platform.NewMethodChannel("acme/camera").WithErrors(errorCodes)
A code must not repeat a transport code (method_not_found and the like), and each sentinel must be comparable (as errors.New's are).
type ErrorCodes map[string]error
func (ErrorCodes) NewError
func (c ErrorCodes) NewError(code, message string) *ChannelError
NewError returns the error native would send with code and message, for Go code that receives codes some other way (in an event's payload, say).
type EventChannel
EventChannel provides stream-based event communication from native to Go.
How an event dispatched with no subscriber, or before a subscriber joined, reaches later subscribers depends on the constructor:
- NewEventChannel: it does not; events go to current subscribers only.
- NewStickyEventChannel: the most recent event is replayed to every new subscriber, for one-shot signals such as "first frame rendered".
- NewQueuedEventChannel: events dispatched while nobody listens are queued and delivered, in order, when a subscriber joins, for events that must each be handled once, such as a notification tap that launched the app before the app subscribed.
Native is told when the channel gains its first subscriber and loses its last, so a stream it declares (DriftChannel.stream) starts and stops with Go's interest; see [streamsChannel].
type EventChannel struct {
// contains filtered or unexported fields
}
func NewEventChannel
func NewEventChannel(name string) *EventChannel
NewEventChannel creates a new event channel with the given name.
func NewQueuedEventChannel
func NewQueuedEventChannel(name string, capacity int) *EventChannel
NewQueuedEventChannel creates an event channel that keeps events dispatched while it has no subscribers, up to capacity (the oldest is dropped and reported beyond that), and delivers them in order to the next subscriber from [Listen], before any later event. Each queued event is delivered once: subscribers joining after the queue drained see only live events. Errors and Done are never queued.
Panics if capacity is not positive.
func NewStickyEventChannel
func NewStickyEventChannel(name string) *EventChannel
NewStickyEventChannel creates an event channel that remembers the most recently dispatched event payload and replays it to each new subscriber on [Listen]. Use this for one-shot lifecycle signals (e.g. first-frame rendered) where a subscriber registering after the event still needs to observe it.
Sticky storage holds a single slot, overwritten on every subsequent dispatch. Errors and Done do not populate the slot.
func (*EventChannel) IsSticky
func (c *EventChannel) IsSticky() bool
IsSticky reports whether the channel was constructed via NewStickyEventChannel. Sticky channels remember the most recent emission and replay it to subscribers that register after the fact. Callers can use this to assert framework-level expectations (e.g. that a lifecycle channel is sticky in tests).
func (*EventChannel) Listen
func (c *EventChannel) Listen(handler EventHandler) *Subscription
Listen subscribes to events on this channel.
func (*EventChannel) Name
func (c *EventChannel) Name() string
Name returns the channel name.
func (*EventChannel) WithErrors
func (c *EventChannel) WithErrors(codes ErrorCodes) *EventChannel
WithErrors declares the error codes native streams on the channel (see ErrorCodes) and returns the channel, so stream errors match their sentinels under errors.Is. Call it once, where the channel is declared, before any subscription; a second call panics, as does a code repeating a transport code.
type EventHandler
EventHandler receives events from an EventChannel.
type EventHandler struct {
OnEvent func(data any)
OnError func(err error)
OnDone func()
}
type FileInfo
FileInfo contains metadata about a file.
type FileInfo struct {
Name string
Path string
Size int64
MimeType string
IsDirectory bool
LastModified int64
}
type HapticFeedbackType
HapticFeedbackType defines the type of haptic feedback.
type HapticFeedbackType string
const (
// HapticLight is a light impact feedback.
HapticLight HapticFeedbackType = "light"
// HapticMedium is a medium impact feedback.
HapticMedium HapticFeedbackType = "medium"
// HapticHeavy is a heavy impact feedback.
HapticHeavy HapticFeedbackType = "heavy"
// HapticSelection is a selection feedback (subtle tick).
HapticSelection HapticFeedbackType = "selection"
// HapticSuccess indicates a successful action.
HapticSuccess HapticFeedbackType = "success"
// HapticWarning indicates a warning.
HapticWarning HapticFeedbackType = "warning"
// HapticError indicates an error.
HapticError HapticFeedbackType = "error"
)
type HapticsService
HapticsService manages haptic feedback.
type HapticsService struct {
// contains filtered or unexported fields
}
func (*HapticsService) HeavyImpact
func (h *HapticsService) HeavyImpact() error
HeavyImpact triggers a heavy impact feedback.
func (*HapticsService) Impact
func (h *HapticsService) Impact(style HapticFeedbackType) error
Impact triggers an impact haptic feedback.
func (*HapticsService) LightImpact
func (h *HapticsService) LightImpact() error
LightImpact triggers a light impact feedback.
func (*HapticsService) MediumImpact
func (h *HapticsService) MediumImpact() error
MediumImpact triggers a medium impact feedback.
func (*HapticsService) SelectionClick
func (h *HapticsService) SelectionClick() error
SelectionClick triggers a selection tick feedback. Use this for selection changes in pickers, sliders, etc.
func (*HapticsService) Vibrate
func (h *HapticsService) Vibrate(durationMs int) error
Vibrate triggers a vibration for the specified duration in milliseconds.
type JsonCodec
JsonCodec implements MessageCodec using JSON encoding. JSON prioritizes interoperability and minimal native dependencies.
type JsonCodec struct{}
func (JsonCodec) Decode
func (c JsonCodec) Decode(data []byte) (any, error)
Decode deserializes JSON bytes to a Go value.
func (JsonCodec) DecodeInto
func (c JsonCodec) DecodeInto(data []byte, v any) error
DecodeInto deserializes JSON bytes into a specific type.
func (JsonCodec) Encode
func (c JsonCodec) Encode(value any) ([]byte, error)
Encode serializes the value to JSON bytes.
type KeyboardType
KeyboardType specifies the type of keyboard to show.
type KeyboardType int
const (
KeyboardTypeText KeyboardType = iota
KeyboardTypeNumber
KeyboardTypePhone
KeyboardTypeEmail
KeyboardTypeURL
KeyboardTypePassword
KeyboardTypeMultiline
)
type LifecycleHandler
LifecycleHandler is called when lifecycle state changes.
type LifecycleHandler func(state LifecycleState)
type LifecycleService
LifecycleService manages app lifecycle events.
type LifecycleService struct {
// contains filtered or unexported fields
}
func (*LifecycleService) AddHandler
func (l *LifecycleService) AddHandler(handler LifecycleHandler) func()
AddHandler registers a handler to be called on lifecycle changes. Returns a function that can be called to remove the handler.
func (*LifecycleService) IsPaused
func (l *LifecycleService) IsPaused() bool
IsPaused returns true if the app is paused.
func (*LifecycleService) IsResumed
func (l *LifecycleService) IsResumed() bool
IsResumed returns true if the app is in the resumed state.
func (*LifecycleService) SetStateForTest
func (l *LifecycleService) SetStateForTest(state LifecycleState)
SetStateForTest updates the lifecycle state and notifies handlers. Use only in tests.
func (*LifecycleService) State
func (l *LifecycleService) State() LifecycleState
State returns the current lifecycle state.
type LifecycleState
LifecycleState represents the current app lifecycle state.
type LifecycleState string
const (
// LifecycleStateResumed indicates the app is visible and responding to user input.
LifecycleStateResumed LifecycleState = "resumed"
// LifecycleStateInactive indicates the app is transitioning (e.g., receiving a phone call).
// On iOS, this occurs during app switcher or when a system dialog is shown.
LifecycleStateInactive LifecycleState = "inactive"
// LifecycleStatePaused indicates the app is not visible but still running.
LifecycleStatePaused LifecycleState = "paused"
// LifecycleStateDetached indicates the app is still hosted but detached from any view.
LifecycleStateDetached LifecycleState = "detached"
)
type MessageCodec
MessageCodec encodes and decodes messages for platform channel communication.
type MessageCodec interface {
// Encode converts a Go value to bytes for transmission to native code.
Encode(value any) ([]byte, error)
// Decode converts bytes received from native code to a Go value.
Decode(data []byte) (any, error)
}
DefaultCodec is the codec used by platform channels.
var DefaultCodec MessageCodec = JsonCodec{}
type MethodChannel
MethodChannel calls methods native code registers under its name. Native reaches Go through event channels.
type MethodChannel struct {
// contains filtered or unexported fields
}
func NewMethodChannel
func NewMethodChannel(name string) *MethodChannel
NewMethodChannel creates a new method channel with the given name.
func (*MethodChannel) Invoke
func (c *MethodChannel) Invoke(ctx context.Context, method string, args any) (any, error)
Invoke calls a method on the native side and returns the result. Blocks until the native side responds, an error occurs, or ctx is canceled. See [invokeNative] for the ctx cancellation contract. A native error is a \*ChannelError matching the channel's ErrorCodes under errors.Is.
func (*MethodChannel) Name
func (c *MethodChannel) Name() string
Name returns the channel name.
func (*MethodChannel) WithErrors
func (c *MethodChannel) WithErrors(codes ErrorCodes) *MethodChannel
WithErrors declares the channel's own error codes (see ErrorCodes) and returns the channel. Call it once, where the channel is declared, before any call; a second call panics, as does a code repeating a transport code.
type NativeBridge
NativeBridge defines the interface for calling native platform code.
type NativeBridge interface {
// InvokeMethod starts a native method call and delivers its outcome
// through reply exactly once: before returning when native answers in
// place, otherwise later, from any thread.
//
// It must start the call on the calling goroutine. Native decides where
// a handler runs from the thread it is called on: a call from the UI
// thread is answered in place (or refused, for a method that replies
// asynchronously), since the UI thread cannot wait for a reply that may
// need it. Moving the call to another goroutine hides that thread and
// deadlocks the app.
InvokeMethod(channel, method string, args []byte, reply func(result []byte, err error))
}
type NotificationPermission
NotificationPermission extends Permission with notification-specific options.
type NotificationPermission interface {
Permission
// RequestWithOptions prompts for notification permission with iOS-specific options.
// Uses the provided values verbatim - zero values mean that capability is NOT requested.
// For default behavior (Alert, Sound, Badge all enabled), use Request() instead.
// Options are ignored on Android. Like Request, it waits for the user,
// and a call made while a notification prompt is up returns that
// prompt's answer without using its own options.
RequestWithOptions(ctx context.Context, opts NotificationPermissionOptions) (PermissionResult, error)
}
type NotificationPermissionOptions
NotificationPermissionOptions configures notification capabilities (iOS only). Zero values mean the capability is NOT requested. Use Request() for defaults.
type NotificationPermissionOptions struct {
Alert bool // Visible notifications (banners, alerts).
Sound bool // Notification sounds.
Badge bool // Badge count on app icon.
Provisional bool // Quiet delivery to Notification Center (iOS 12+).
}
type NotificationsService
NotificationsService holds the notification permission. Drift provides it because the plugins that show notifications share it: local notifications (plugins/notifications) and push (plugins/firebase). On Android those plugins declare POST_NOTIFICATIONS; with neither in drift.yaml, its calls fail with ErrPermissionNotDeclared.
type NotificationsService struct {
// Permission for showing notifications. Implements
// NotificationPermission for iOS-specific options.
Permission NotificationPermission
}
type Permission
Permission provides access to a runtime permission for a platform feature. Use Status to check current state, Request to prompt the user, and Listen to observe changes. Plugins provide permissions (see NewPermission); Drift provides the notification permission (Notifications).
Every method fails with ErrPermissionNotRegistered when no native code registered the kind, and on Android with ErrPermissionNotDeclared when the manifest lacks a permission the kind needs.
Context: only Request takes ctx because it waits for the user. Status, IsGranted, IsDenied, and ShouldShowRationale reply in place, so the high-level permission API does not expose ctx for them.
type Permission interface {
// Status returns the current permission status.
Status() (PermissionResult, error)
// Request prompts the user for permission if needed and returns the
// resulting status once they respond. When no prompt can change the
// status (granted, permanently denied, restricted), it returns at once
// without showing a dialog.
//
// Request waits for the user, so call it from a goroutine: from the UI
// thread it fails with [ErrBlocksUIThread] before any prompt shows.
// One prompt per kind shows at a time: a Request made while one is up
// returns that prompt's answer.
//
// Cancellation: returns ErrCanceled or ErrTimeout on ctx cancellation;
// the native dialog stays up until the user answers it.
Request(ctx context.Context) (PermissionResult, error)
// IsGranted returns true if permission is granted.
// Best-effort convenience: returns false on any error. Use Status for
// precise error handling when error details matter.
IsGranted() bool
// IsDenied returns true if permission is denied or permanently denied.
// Best-effort convenience: returns false on any error. Use Status for
// precise error handling when error details matter.
IsDenied() bool
// ShouldShowRationale returns whether to show a rationale before requesting.
// Android-specific; always returns (false, nil) on iOS.
ShouldShowRationale() (bool, error)
// Listen subscribes to permission status changes.
// Returns an unsubscribe function. Multiple listeners receive all events.
Listen(handler func(PermissionResult)) (unsubscribe func())
}
func NewPermission
func NewPermission(kind string) Permission
NewPermission returns the permission of the given kind, such as "location". Native code registers each kind: Drift registers "notifications", and plugins register theirs (DriftPluginHost registerPermission on iOS and Android). Plugins call this from their runtime package and expose the result; apps use those values.
Calls on a kind no native code registered fail with ErrPermissionNotRegistered: the plugin providing it is missing from drift.yaml, or not configured for that kind.
type PermissionResult
PermissionResult represents the status of a permission.
type PermissionResult string
const (
// PermissionGranted indicates full access has been granted.
PermissionGranted PermissionResult = "granted"
// PermissionDenied indicates the user denied the permission. The app may request again.
PermissionDenied PermissionResult = "denied"
// PermissionPermanentlyDenied indicates the user denied with "don't ask again" (Android)
// or denied twice (iOS). The app cannot request again; direct user to Settings.
PermissionPermanentlyDenied PermissionResult = "permanently_denied"
// PermissionRestricted indicates a system policy prevents granting (parental controls,
// MDM, enterprise policy). The user cannot change this; no dialog will be shown.
PermissionRestricted PermissionResult = "restricted"
// PermissionLimited indicates partial access (iOS only). For Photos, this means the user
// selected specific photos rather than granting full library access.
PermissionLimited PermissionResult = "limited"
// PermissionNotDetermined indicates the user has not yet been asked. Calling Request
// will show the system permission dialog.
PermissionNotDetermined PermissionResult = "not_determined"
// PermissionProvisional indicates provisional notification permission (iOS only).
// Notifications are delivered quietly to Notification Center without alerting the user.
PermissionProvisional PermissionResult = "provisional"
// PermissionResultUnknown indicates the status could not be determined.
PermissionResultUnknown PermissionResult = "unknown"
)
type PickFileOptions
PickFileOptions configures file picker behavior.
type PickFileOptions struct {
AllowMultiple bool
AllowedTypes []string
InitialDir string
DialogTitle string
}
type PickedFile
PickedFile represents a file selected by the user.
type PickedFile struct {
Name string
Path string
URI string
MimeType string
Size int64
}
type PlatformView
PlatformView represents a native view embedded in Drift UI.
type PlatformView interface {
// ViewID returns the unique identifier for this view.
ViewID() int64
// ViewType returns the type identifier for this view (e.g., "native_webview").
ViewType() string
// Create initializes the native view with given parameters.
Create(params map[string]any) error
// Dispose cleans up the native view.
Dispose()
// HandleEvent receives an event or call the native view sent on
// drift/platform_views (other than creation and disposal), with its
// arguments, viewId included. It returns ErrMethodNotFound for a
// method it does not know, and an error for malformed arguments;
// either is reported through Drift's error handling.
HandleEvent(method string, args map[string]any) error
}
type PlatformViewBase
PlatformViewBase implements a platform view's identity: embed it in a PlatformView (a plugin's too) and set it from the factory's viewID.
type PlatformViewBase struct {
// contains filtered or unexported fields
}
func NewPlatformViewBase
func NewPlatformViewBase(viewID int64, viewType string) PlatformViewBase
NewPlatformViewBase returns the identity of view viewID of viewType.