Skip to main content

platform

Package platform provides platform channel communication between Go and native code. It enables Go code to call native APIs (clipboard, haptics, etc.) and receive events from the native platform (lifecycle changes, sensor data, etc.).

Variables

Standard errors for platform channel operations.

var (
ErrChannelNotFound = errors.New("platform channel not found")
ErrMethodNotFound = errors.New("method not implemented")
ErrInvalidArguments = errors.New("invalid arguments")
ErrPlatformUnavailable = errors.New("platform feature unavailable")
ErrTimeout = errors.New("operation timed out")
ErrViewTypeNotFound = errors.New("platform view type not registered")
)

Accessibility is the global accessibility channel instance.

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

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

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

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

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}

func BackgroundTaskEvents

func BackgroundTaskEvents() <-chan BackgroundEvent

BackgroundTaskEvents returns a channel that receives task events.

func CameraResults

func CameraResults() <-chan CameraResult

CameraResults returns a channel that receives camera operation results.

func CancelAllBackgroundTasks

func CancelAllBackgroundTasks() error

CancelAllBackgroundTasks cancels all scheduled background tasks.

func CancelAllLocalNotifications

func CancelAllLocalNotifications() error

CancelAllLocalNotifications cancels all scheduled local notifications.

func CancelBackgroundTask

func CancelBackgroundTask(id string) error

CancelBackgroundTask cancels a scheduled background task.

func CancelBackgroundTasksByTag

func CancelBackgroundTasksByTag(tag string) error

CancelBackgroundTasksByTag cancels all tasks with the given tag.

func CancelLocalNotification

func CancelLocalNotification(id string) error

CancelLocalNotification cancels a scheduled local notification by ID.

func CapturePhoto

func CapturePhoto(opts CapturePhotoOptions) error

CapturePhoto captures a photo using the device camera. Results are delivered asynchronously via CameraResults().

func CaptureVideo

func CaptureVideo(opts CaptureVideoOptions) error

CaptureVideo captures a video using the device camera. Results are delivered asynchronously via CameraResults().

func CompleteBackgroundTask

func CompleteBackgroundTask(id string, success bool) error

CompleteBackgroundTask signals completion of a background task.

func DeepLinks() <-chan DeepLink

DeepLinks streams deep link events while the app is running.

func DeleteFile

func DeleteFile(pathOrURI string) error

DeleteFile deletes a file.

func DeletePushToken

func DeletePushToken() error

DeletePushToken deletes the current push token.

func DeviceTokens

func DeviceTokens() <-chan DeviceToken

DeviceTokens streams device push token updates.

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 GetAppDirectory

func GetAppDirectory(dir AppDirectory) (string, error)

GetAppDirectory returns the path to a standard app directory.

func GetFocusedTarget

func GetFocusedTarget() any

GetFocusedTarget returns the render object that currently has keyboard focus.

func GetPushToken

func GetPushToken() (string, error)

GetPushToken returns the current push token if available.

func HandleEvent

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

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

func HandleEventDone

func HandleEventDone(channel string) error

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

func HandleEventError

func HandleEventError(channel string, code, message string) error

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

func HandleMethodCall

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

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

func HasFocus

func HasFocus() bool

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

func InitializeAccessibility

func InitializeAccessibility()

InitializeAccessibility sets up the accessibility system with the semantics binding.

func IsBackgroundRefreshAvailable

func IsBackgroundRefreshAvailable() (bool, error)

IsBackgroundRefreshAvailable checks if background refresh is available.

func IsLocationEnabled

func IsLocationEnabled() (bool, error)

IsLocationEnabled checks if location services are enabled on the device.

func LocationUpdates

func LocationUpdates() <-chan LocationUpdate

LocationUpdates returns a channel that receives location updates.

func NotificationErrors

func NotificationErrors() <-chan NotificationError

NotificationErrors streams notification errors.

func NotificationOpens

func NotificationOpens() <-chan NotificationOpen

NotificationOpens streams notification open events.

func NotificationPermissionUpdates

func NotificationPermissionUpdates() <-chan PermissionStatus

NotificationPermissionUpdates streams permission updates after a request.

func Notifications

func Notifications() <-chan NotificationEvent

Notifications streams notification deliveries.

func OpenAppSettings

func OpenAppSettings() error

OpenAppSettings opens the app settings page where users can manage permissions.

func PermissionChanges

func PermissionChanges() <-chan PermissionChange

PermissionChanges returns a channel that receives permission status changes.

func PickDirectory

func PickDirectory() error

PickDirectory opens a directory picker dialog. Results are delivered asynchronously via StorageResults().

func PickFile

func PickFile(opts PickFileOptions) error

PickFile opens a file picker dialog. Results are delivered asynchronously via StorageResults().

func PickFromGallery

func PickFromGallery(opts PickFromGalleryOptions) error

PickFromGallery opens the device gallery to pick media. Results are delivered asynchronously via CameraResults().

func PushErrors

func PushErrors() <-chan PushError

PushErrors returns a channel that receives push-related errors.

func PushTokenUpdates

func PushTokenUpdates() <-chan PushToken

PushTokenUpdates returns a channel that receives token updates.

func ReadFile

func ReadFile(pathOrURI string) ([]byte, error)

ReadFile reads the contents of a file.

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 RegisterForPush

func RegisterForPush() error

RegisterForPush registers the device for push notifications.

func RequestPermissions

func RequestPermissions(permissions []Permission) (map[Permission]PermissionResult, error)

RequestPermissions requests multiple runtime permissions.

func SaveFile

func SaveFile(data []byte, opts SaveFileOptions) error

SaveFile saves data to a file chosen by the user. Results are delivered asynchronously via StorageResults().

func ScheduleBackgroundTask

func ScheduleBackgroundTask(request TaskRequest) error

ScheduleBackgroundTask schedules a background task.

func ScheduleLocalNotification

func ScheduleLocalNotification(request NotificationRequest) error

ScheduleLocalNotification schedules a local notification.

func SetActiveConnection

func SetActiveConnection(id int64)

SetActiveConnection marks a connection as the currently active one.

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 SetNotificationBadge

func SetNotificationBadge(count int) error

SetNotificationBadge sets the app badge count.

func SetSystemUI

func SetSystemUI(style SystemUIStyle) error

SetSystemUI updates the system UI appearance.

func ShouldShowPermissionRationale

func ShouldShowPermissionRationale(permission Permission) bool

ShouldShowPermissionRationale returns whether the app should show a rationale for requesting a permission. This is Android-specific and always returns false on iOS.

func StartLocationUpdates

func StartLocationUpdates(opts LocationOptions) error

StartLocationUpdates starts receiving continuous location updates.

func StopLocationUpdates

func StopLocationUpdates() error

StopLocationUpdates stops receiving location updates.

func StorageResults

func StorageResults() <-chan StorageResult

StorageResults returns a channel that receives storage operation results.

func SubscribeToTopic

func SubscribeToTopic(topic string) error

SubscribeToTopic subscribes to a push notification topic.

func UnfocusAll

func UnfocusAll()

UnfocusAll hides the keyboard and unfocuses all text input connections.

func UnsubscribeFromTopic

func UnsubscribeFromTopic(topic string) error

UnsubscribeFromTopic unsubscribes from a push notification topic.

func WriteFile

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

WriteFile writes data to a file.

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 BackgroundEvent

BackgroundEvent represents a background task event.

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

type CameraResult

CameraResult represents a result from camera/gallery operations.

type CameraResult struct {
Type string // "capture" or "gallery"
Media *CapturedMedia // For capture results
MediaList []CapturedMedia // For gallery results
Cancelled bool
}

type CapturePhotoOptions

CapturePhotoOptions configures photo capture behavior.

type CapturePhotoOptions struct {
Quality int
MaxWidth int
MaxHeight int
UseFrontCamera bool
SaveToGallery bool
}

type CaptureVideoOptions

CaptureVideoOptions configures video capture behavior.

type CaptureVideoOptions struct {
Quality int
MaxDuration time.Duration
UseFrontCamera bool
SaveToGallery bool
}

type CapturedMedia

CapturedMedia represents a captured photo or video.

type CapturedMedia struct {
Path string
MimeType string
Width int
Height int
Size int64
Duration time.Duration
}

type ChannelError

ChannelError represents an error returned from native code.

type ChannelError struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
}

func NewChannelError

func NewChannelError(code, message string) *ChannelError

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

func NewChannelErrorWithDetails

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

NewChannelErrorWithDetails creates a new ChannelError with additional details.

func (*ChannelError) Error

func (e *ChannelError) Error() string

type ClipboardData

ClipboardData represents data on the clipboard.

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

type ClipboardService

ClipboardService manages clipboard operations.

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

func (*ClipboardService) Clear

func (c *ClipboardService) Clear() error

Clear removes all data from the clipboard.

func (*ClipboardService) GetText

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

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

func (*ClipboardService) HasText

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

HasText returns true if the clipboard contains text.

func (*ClipboardService) SetText

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

SetText copies text to the clipboard.

DeepLink describes an incoming deep link.

type DeepLink struct {
URL string
Source string
Timestamp time.Time
}
func GetInitialDeepLink() (*DeepLink, error)

GetInitialDeepLink returns the launch deep link, if available.

type DeviceToken

DeviceToken represents a device push token update.

type DeviceToken struct {
Platform string
Token string
Timestamp time.Time
IsRefresh bool
}

type EdgeInsets

EdgeInsets represents the safe area insets from system UI elements.

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

type EndOfStream

EndOfStream is sent when an event stream terminates normally.

type EndOfStream struct{}

type Event

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

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

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

type EventChannel

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

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

func NewEventChannel

func NewEventChannel(name string) *EventChannel

NewEventChannel creates a new event channel with the given name.

func (*EventChannel) Listen

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

Listen subscribes to events on this channel. Any error from starting the native event stream is reported via the error handler but does not prevent the subscription from being created.

func (*EventChannel) Name

func (c *EventChannel) Name() string

Name returns the channel name.

type EventError

EventError represents an error that occurred in an event stream.

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

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

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

type EventHandler

EventHandler receives events from an EventChannel.

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

type FileInfo

FileInfo contains metadata about a file.

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

func GetFileInfo

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

GetFileInfo returns metadata about a file.

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

func (l *LifecycleService) State() LifecycleState

State returns the current lifecycle state.

type LifecycleState

LifecycleState represents the current app lifecycle state.

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

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

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

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

type LocationOptions

LocationOptions configures location update behavior.

type LocationOptions struct {
HighAccuracy bool
DistanceFilter float64
IntervalMs int64
FastestIntervalMs int64
}

type LocationUpdate

LocationUpdate represents a location update from the device.

type LocationUpdate struct {
Latitude float64
Longitude float64
Altitude float64
Accuracy float64
Heading float64
Speed float64
Timestamp time.Time
IsMocked bool
}

func GetCurrentLocation

func GetCurrentLocation(opts LocationOptions) (*LocationUpdate, error)

GetCurrentLocation gets the device's current location.

func GetLastKnownLocation

func GetLastKnownLocation() (*LocationUpdate, error)

GetLastKnownLocation returns the last known location without triggering a new request.

type MediaType

MediaType specifies the type of media to pick.

type MediaType string
const (
MediaTypeImage MediaType = "image"
MediaTypeVideo MediaType = "video"
MediaTypeAll MediaType = "all"
)

type MessageCodec

MessageCodec encodes and decodes messages for platform channel communication.

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

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

DefaultCodec is the codec used by platform channels.

var DefaultCodec MessageCodec = JsonCodec{}

type MethodCall

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

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

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

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

type MethodChannel

MethodChannel provides bidirectional method-call communication with native code.

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

func NewMethodChannel

func NewMethodChannel(name string) *MethodChannel

NewMethodChannel creates a new method channel with the given name.

func (*MethodChannel) Invoke

func (c *MethodChannel) Invoke(method string, args any) (any, error)

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

func (*MethodChannel) Name

func (c *MethodChannel) Name() string

Name returns the channel name.

func (*MethodChannel) SetHandler

func (c *MethodChannel) SetHandler(handler MethodHandler)

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

type MethodHandler

MethodHandler handles incoming method calls on a channel.

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

type MethodResponse

MethodResponse represents the result of a method call.

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

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

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

func (*MethodResponse) IsError

func (r *MethodResponse) IsError() bool

IsError returns true if this response represents an error.

type NativeBridge

NativeBridge defines the interface for calling native platform code.

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

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

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

type NotificationError

NotificationError represents a notification-related error.

type NotificationError struct {
Code string
Message string
Platform string
}

type NotificationEvent

NotificationEvent represents a received notification.

type NotificationEvent struct {
ID string
Title string
Body string
Data map[string]any
Timestamp time.Time
IsForeground bool
Source string
}

type NotificationOpen

NotificationOpen represents a user opening a notification.

type NotificationOpen struct {
ID string
Data map[string]any
Action string
Source string
Timestamp time.Time
}

type NotificationRequest

NotificationRequest describes a local notification schedule request.

type NotificationRequest struct {
ID string
Title string
Body string
Data map[string]any
At time.Time
IntervalSeconds int64
Repeats bool
ChannelID string
Sound string
Badge *int
}

type NotificationSettings

NotificationSettings describes the current notification settings.

type NotificationSettings struct {
Status PermissionStatus
AlertsEnabled bool
SoundsEnabled bool
BadgesEnabled bool
}

func GetNotificationSettings

func GetNotificationSettings() (NotificationSettings, error)

GetNotificationSettings returns the current notification settings.

type Permission

Permission types for runtime permission requests.

type Permission string
const (
PermissionCamera Permission = "camera"
PermissionMicrophone Permission = "microphone"
PermissionPhotos Permission = "photos"
PermissionLocation Permission = "location"
PermissionLocationAlways Permission = "location_always"
PermissionStorage Permission = "storage"
PermissionContacts Permission = "contacts"
PermissionCalendar Permission = "calendar"
PermissionNotifications Permission = "notifications"
)

type PermissionChange

PermissionChange represents a permission status change event.

type PermissionChange struct {
Permission Permission
Result PermissionResult
}

type PermissionOptions

PermissionOptions defines the permission capabilities to request.

type PermissionOptions struct {
Alert bool
Sound bool
Badge bool
Provisional bool
}

type PermissionResult

PermissionResult represents the result of a permission request.

type PermissionResult string
const (
PermissionGranted PermissionResult = "granted"
PermissionDenied PermissionResult = "denied"
PermissionPermanentlyDenied PermissionResult = "permanently_denied"
PermissionRestricted PermissionResult = "restricted"
PermissionLimited PermissionResult = "limited"
PermissionNotDetermined PermissionResult = "not_determined"
PermissionProvisional PermissionResult = "provisional"
PermissionResultUnknown PermissionResult = "unknown"
)

func CheckPermission

func CheckPermission(permission Permission) (PermissionResult, error)

CheckPermission checks the current status of a permission.

func RequestPermission

func RequestPermission(permission Permission) (PermissionResult, error)

RequestPermission requests a single runtime permission.

type PermissionStatus

PermissionStatus represents notification permission state.

type PermissionStatus string
const (
PermissionStatusGranted PermissionStatus = "granted"
PermissionStatusDenied PermissionStatus = "denied"
PermissionStatusProvisional PermissionStatus = "provisional"
PermissionStatusNotDetermined PermissionStatus = "not_determined"
PermissionStatusUnknown PermissionStatus = "unknown"
)

func RequestNotificationPermissions

func RequestNotificationPermissions(options PermissionOptions) (PermissionStatus, error)

RequestNotificationPermissions requests notification permissions.

type PickFileOptions

PickFileOptions configures file picker behavior.

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

type PickFromGalleryOptions

PickFromGalleryOptions configures gallery picker behavior.

type PickFromGalleryOptions struct {
AllowMultiple bool
MediaType MediaType
MaxSelection int
}

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_text_field").
ViewType() string

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

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

// SetSize updates the view size in logical pixels.
SetSize(size rendering.Size)

// SetOffset updates the view position in logical pixels.
SetOffset(offset rendering.Offset)

// SetVisible shows or hides the native view.
SetVisible(visible bool)
}

type PlatformViewFactory

PlatformViewFactory creates platform views of a specific type.

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

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

type PlatformViewRegistry

PlatformViewRegistry manages platform view types and instances.

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

func GetPlatformViewRegistry

func GetPlatformViewRegistry() *PlatformViewRegistry

GetPlatformViewRegistry returns the global platform view registry.

func (*PlatformViewRegistry) 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) 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) SetViewVisible

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

SetViewVisible notifies native to show or hide a view.

func (*PlatformViewRegistry) UpdateViewGeometry

func (r *PlatformViewRegistry) UpdateViewGeometry(viewID int64, offset rendering.Offset, size rendering.Size) error

UpdateViewGeometry notifies native of a view's position and size change.

type PushError

PushError represents a push notification error.

type PushError struct {
Code string
Message string
}

type PushToken

PushToken represents a device push notification token.

type PushToken struct {
Platform string
Token string
Timestamp time.Time
}

type SafeAreaService

SafeAreaService manages safe area inset events.

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

func (*SafeAreaService) AddHandler

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

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

func (*SafeAreaService) Insets

func (s *SafeAreaService) Insets() EdgeInsets

Insets returns the current safe area insets.

type SaveFileOptions

SaveFileOptions configures save file dialog behavior.

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

type ShareFile

ShareFile represents a file to share.

type ShareFile struct {
Path string
MimeType string
}

type ShareResult

ShareResult indicates the result of a share operation.

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

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

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

type ShareService

ShareService manages sharing content with other apps.

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

func (*ShareService) ShareFile

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

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

func (*ShareService) ShareFiles

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

ShareFiles opens the share sheet with multiple files.

func (*ShareService) ShareText

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

ShareText opens the share sheet with the given text.

func (*ShareService) ShareTextWithSubject

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

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

func (*ShareService) ShareURL

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

ShareURL opens the share sheet with a URL.

func (*ShareService) ShareURLWithText

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

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

type StatusBarStyle

StatusBarStyle indicates the status bar icon color scheme.

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

type StorageResult

StorageResult represents a result from storage picker operations.

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

type Subscription

Subscription represents an active event subscription.

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

func (*Subscription) Cancel

func (s *Subscription) Cancel()

Cancel stops receiving events on this subscription.

func (*Subscription) IsCanceled

func (s *Subscription) IsCanceled() bool

IsCanceled returns true if this subscription has been canceled.

type SystemUIStyle

SystemUIStyle describes system bar and window styling.

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

type TaskConstraints

TaskConstraints defines constraints for when a task should run.

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

type TaskRequest

TaskRequest describes a background task to schedule.

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

type TaskType

TaskType defines the type of background task.

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

type TextAffinity

TextAffinity describes which side of a position the caret prefers.

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

type TextCapitalization

TextCapitalization specifies text capitalization behavior.

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

type TextEditingController

TextEditingController manages text input state.

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

func NewTextEditingController

func NewTextEditingController(text string) *TextEditingController

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

func (*TextEditingController) AddListener

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

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

func (*TextEditingController) Clear

func (c *TextEditingController) Clear()

Clear clears the text.

func (*TextEditingController) Selection

func (c *TextEditingController) Selection() TextSelection

Selection returns the current selection.

func (*TextEditingController) SetSelection

func (c *TextEditingController) SetSelection(selection TextSelection)

SetSelection sets the selection.

func (*TextEditingController) SetText

func (c *TextEditingController) SetText(text string)

SetText sets the text content.

func (*TextEditingController) SetValue

func (c *TextEditingController) SetValue(value TextEditingValue)

SetValue sets the complete editing value.

func (*TextEditingController) Text

func (c *TextEditingController) Text() string

Text returns the current text content.

func (*TextEditingController) Value

func (c *TextEditingController) Value() TextEditingValue

Value returns the complete editing value.

type TextEditingValue

TextEditingValue represents the current text editing state.

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

func (TextEditingValue) IsComposing

func (v TextEditingValue) IsComposing() bool

IsComposing returns true if there is an active IME composition.

type TextInputAction

TextInputAction specifies the action button on the keyboard.

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

type TextInputClient

TextInputClient receives text input events from the platform.

type TextInputClient interface {
// UpdateEditingValue is called when the editing value changes.
UpdateEditingValue(value TextEditingValue)

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

// ConnectionClosed is called when the input connection is closed.
ConnectionClosed()
}

type TextInputConfiguration

TextInputConfiguration configures a text input connection.

type TextInputConfiguration struct {
KeyboardType KeyboardType
InputAction TextInputAction
Capitalization TextCapitalization
Autocorrect bool
EnableSuggestions bool
Obscure bool
ActionLabel string
}

func DefaultTextInputConfiguration

func DefaultTextInputConfiguration() TextInputConfiguration

DefaultTextInputConfiguration returns a default text input configuration.

type TextInputConnection

TextInputConnection manages the connection to the native IME.

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

func NewTextInputConnection

func NewTextInputConnection(client TextInputClient, config TextInputConfiguration) *TextInputConnection

NewTextInputConnection creates a new text input connection.

func (*TextInputConnection) Close

func (c *TextInputConnection) Close()

Close closes this text input connection.

func (*TextInputConnection) Hide

func (c *TextInputConnection) Hide()

Hide hides the soft keyboard.

func (*TextInputConnection) ID

func (c *TextInputConnection) ID() int64

ID returns the connection identifier.

func (*TextInputConnection) SetEditingState

func (c *TextInputConnection) SetEditingState(value TextEditingValue)

SetEditingState updates the native text state.

func (*TextInputConnection) Show

func (c *TextInputConnection) Show()

Show shows the soft keyboard.

type TextRange

TextRange represents a range of text.

type TextRange struct {
Start int
End int
}

func (TextRange) IsEmpty

func (r TextRange) IsEmpty() bool

IsEmpty returns true if the range has zero length.

func (TextRange) IsNormalized

func (r TextRange) IsNormalized() bool

IsNormalized returns true if start <= end.

func (TextRange) IsValid

func (r TextRange) IsValid() bool

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

type TextSelection

TextSelection represents the current text selection.

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

func TextSelectionCollapsed

func TextSelectionCollapsed(offset int) TextSelection

TextSelectionCollapsed creates a collapsed selection at the given offset.

func (TextSelection) End

func (s TextSelection) End() int

End returns the larger of BaseOffset and ExtentOffset.

func (TextSelection) IsCollapsed

func (s TextSelection) IsCollapsed() bool

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

func (TextSelection) IsValid

func (s TextSelection) IsValid() bool

IsValid returns true if both offsets are non-negative.

func (TextSelection) Start

func (s TextSelection) Start() int

Start returns the smaller of BaseOffset and ExtentOffset.

Generated by gomarkdoc