use cranpose_core::{
LaunchedEffect, State, collectAsState, rememberEventStream, rememberMutableStateOf,
};
use super::{
lease::start_device_motion,
sample::{MotionConfig, MotionSample},
sensor::latest_device_motion,
status::{DeviceMotionStatus, device_motion_status, observe_device_motion_status},
};
#[derive(Clone, Copy)]
pub struct DeviceMotion {
status: State<DeviceMotionStatus>,
}
impl DeviceMotion {
pub fn status(&self) -> State<DeviceMotionStatus> {
self.status
}
pub fn latest(&self) -> Option<MotionSample> {
latest_device_motion()
}
}
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[track_caller]
pub fn rememberDeviceMotion(config: MotionConfig) -> DeviceMotion {
let updates = rememberEventStream(config, move |sender| {
let lease = start_device_motion(config);
let observer = observe_device_motion_status(move |status| sender.send(status));
(lease, observer)
});
DeviceMotion {
status: collectAsState(updates, (), device_motion_status()),
}
}
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[track_caller]
pub fn rememberDeviceMotionSample(motion: DeviceMotion) -> State<Option<MotionSample>> {
let sample = rememberMutableStateOf(|| None::<MotionSample>);
let live = motion.status().get() == DeviceMotionStatus::Live;
LaunchedEffect(live, async move |scope| {
if !live {
if sample.get_non_reactive().is_some() {
sample.set(None);
}
return;
}
let clock = scope.runtime().frame_clock();
loop {
clock.next_frame().await;
let latest = latest_device_motion();
if latest.map(|s| s.index) != sample.get_non_reactive().map(|s| s.index) {
sample.set(latest);
}
}
});
sample.as_state()
}