The initial value is unknown. Do not display zero or a made-up percentage whilst waiting for the device. The reducer marks the operation pending, requests GET_VOLUME_LEVEL, and its callback reads the typed response from the reducer context.
Both read and adjust helpers are defined here so the result and error handling have one authority. This first screen exposes only the read operation.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"},{"index":2,"label":"src/translations.rs","value":"src-translations-rs"},{"index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":5,"label":"src/lib.rs","value":"src-lib-rs"},{"index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pending { Read, Adjust }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VolumeIssue { Unsupported, Denied, Failed }
impl VolumeIssue {
pub fn key(self) -> &'static str {
match self {
Self::Unsupported => "volume.unsupported",
Self::Denied => "volume.denied",
Self::Failed => "volume.failed",
}
}
}
#[derive(Debug, Default)]
pub struct VolumeState {
pub confirmed: Option<VolumeLevel>,
pub pending: Option<Pending>,
pub issue: Option<VolumeIssue>,
}
impl GlobalState for VolumeState {}
pub fn read_level(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
if state.pending.is_some() { return; }
state.pending = Some(Pending::Read);
state.issue = None;
let ok = ctx.effects.bind(VolumeRead, reduce_with!(volume_read));
let err = ctx.effects.bind(VolumeFailed, reduce_with!(volume_failed));
ctx.effects.volume().get_level(VolumeStream::Media).on_ok(ok).on_err(err);
}
pub fn adjust_level(
state: &mut VolumeState,
ctx: &mut ReducerContext<VolumeState>,
direction: VolumeAdjustDirection,
) {
if state.pending.is_some() || state.confirmed.is_none() { return; }
state.pending = Some(Pending::Adjust);
state.issue = None;
let ok = ctx.effects.bind(VolumeAdjusted, reduce_with!(volume_adjusted));
let err = ctx.effects.bind(VolumeFailed, reduce_with!(volume_failed));
ctx.effects.volume().adjust_level(VolumeAdjustRequest {
stream: VolumeStream::Media,
direction,
step: 5,
}).on_ok(ok).on_err(err);
}
fn accept_level(state: &mut VolumeState, response: Option<VolumeLevel>) {
match response {
Some(level) if level.stream == VolumeStream::Media && level.level <= 100 => {
state.confirmed = Some(level);
state.issue = None;
}
_ => state.issue = Some(VolumeIssue::Failed),
}
}
#[fission_reducer(VolumeRead)]
fn volume_read(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
if state.pending != Some(Pending::Read) { return; }
state.pending = None;
accept_level(state, ctx.input.capability_ok(GET_VOLUME_LEVEL));
}
#[fission_reducer(VolumeAdjusted)]
fn volume_adjusted(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
if state.pending != Some(Pending::Adjust) { return; }
state.pending = None;
accept_level(state, ctx.input.capability_ok(ADJUST_VOLUME_LEVEL));
}
#[fission_reducer(VolumeFailed)]
fn volume_failed(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
let code = match state.pending.take() {
Some(Pending::Read) => ctx.input.capability_error(GET_VOLUME_LEVEL).map(|error| error.code),
Some(Pending::Adjust) => ctx.input.capability_error(ADJUST_VOLUME_LEVEL).map(|error| error.code),
None => return,
};
state.issue = Some(match code.as_deref() {
Some("unsupported") => VolumeIssue::Unsupported,
Some("permission_denied") => VolumeIssue::Denied,
_ => VolumeIssue::Failed,
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_response_does_not_replace_the_last_confirmed_media_level() {
let mut state = VolumeState::default();
accept_level(&mut state, Some(VolumeLevel {
stream: VolumeStream::Media, level: 40, muted: false,
}));
accept_level(&mut state, Some(VolumeLevel {
stream: VolumeStream::Alarm, level: 80, muted: false,
}));
assert_eq!(state.confirmed.as_ref().unwrap().level, 40);
assert_eq!(state.issue, Some(VolumeIssue::Failed));
accept_level(&mut state, None);
assert_eq!(state.confirmed.as_ref().unwrap().level, 40);
}
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, VolumeState};
fission_component! {
pub VolumeScreen<VolumeState> {}
view(_screen, state, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
SafeArea(
child: Scroll(
child: Container(
child: Column(gap: tokens.spacing.m, children: [
Text(cx.tr("volume.title")).size(tokens.typography.heading2_size),
Text(cx.tr("volume.context")),
Button(
child: Text(cx.tr("volume.read")),
key: "read-media-volume",
disabled: state.pending.is_some(),
on_press: reduce { state::read_level(state, cx); },
).semantics_identifier("volume.read"),
if let Some(level) = &state.confirmed {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr("volume.last_confirmed").replace("{level}", &level.level.to_string())),
Text(cx.tr(if level.muted { "volume.muted" } else { "volume.not_muted" })),
Text(cx.tr("volume.snapshot_help")),
])
} else {
Text(cx.tr("volume.not_read"))
},
if let Some(pending) = state.pending {
Spinner(
motion: Some(SpinnerMotion::Default),
label: cx.tr(match pending {
state::Pending::Read => "volume.reading",
state::Pending::Adjust => "volume.adjusting",
}),
)
},
if let Some(issue) = state.issue {
Text(cx.tr(issue.key())).color(tokens.colors.error)
},
]),
).padding_all(tokens.spacing.l),
),
)
}
{"id":"fission-tabs-1","index":2,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::prelude::*;
pub fn create_env() -> Env {
let mut env = Env::default();
env.locale = Locale::from("en-US");
for (locale, source) in [
("en-US", include_str!("../i18n/en-US.yaml")),
("es-ES", include_str!("../i18n/es-ES.yaml")),
] {
let messages: HashMap<String, String> =
serde_yaml::from_str(source).expect("valid checked-in translations");
env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
}
env
}
{"id":"fission-tabs-1","index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
volume.title: "Media volume"
volume.context: "Read the device's media volume before choosing whether to change it. This screen does not play audio."
volume.read: "Read current media volume"
volume.not_read: "No device volume has been read."
volume.last_confirmed: "Last confirmed media volume: {level}%"
volume.muted: "The last response reported this stream muted."
volume.not_muted: "The last response reported this stream not muted."
volume.snapshot_help: "Other apps and the hardware buttons can change volume. Read it again to refresh this snapshot."
volume.change_warning: "These actions change the device's shared media volume, not just this app's playback."
volume.lower: "Lower media volume"
volume.raise: "Raise media volume"
volume.reading: "Reading media volume…"
volume.adjusting: "Changing media volume…"
volume.unsupported: "This host does not support system volume control. Use the device's own volume controls."
volume.denied: "The system did not allow the operation. Use the device's own controls or check its policy."
volume.failed: "The operation failed. Any displayed level is the last confirmed value; read it again before relying on it."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
volume.title: "Volumen multimedia"
volume.context: "Lee el volumen multimedia del dispositivo antes de decidir si lo cambias. Esta pantalla no reproduce audio."
volume.read: "Leer el volumen multimedia actual"
volume.not_read: "Todavía no se ha leído el volumen del dispositivo."
volume.last_confirmed: "Último volumen multimedia confirmado: {level}%"
volume.muted: "La última respuesta indicó que este canal estaba silenciado."
volume.not_muted: "La última respuesta indicó que este canal no estaba silenciado."
volume.snapshot_help: "Otras aplicaciones y los botones físicos pueden cambiar el volumen. Léelo otra vez para actualizar este valor."
volume.change_warning: "Estas acciones cambian el volumen multimedia compartido del dispositivo, no solo el de esta aplicación."
volume.lower: "Bajar el volumen multimedia"
volume.raise: "Subir el volumen multimedia"
volume.reading: "Leyendo el volumen multimedia…"
volume.adjusting: "Cambiando el volumen multimedia…"
volume.unsupported: "Este host no admite el control del volumen del sistema. Usa los controles del dispositivo."
volume.denied: "El sistema no permitió la operación. Usa los controles del dispositivo o revisa su política."
volume.failed: "La operación falló. El nivel mostrado es el último confirmado; vuelve a leerlo antes de confiar en él."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;
use app::VolumeScreen;
use state::VolumeState;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<VolumeState, _>::new(VolumeScreen)
.with_env(translations::create_env())
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<VolumeState, VolumeScreen> {
let app = MobileApp::<VolumeState, _>::new(VolumeScreen)
.with_env(translations::create_env());
#[cfg(all(target_os = "android", debug_assertions))]
let app = app.with_test_control_port(48761);
app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
WebApp::<VolumeState, _>::new(VolumeScreen)
.with_env(translations::create_env())
.run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod state;
mod translations;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::VolumeState, _>::new(app::VolumeScreen)
.with_env(translations::create_env())
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}