Quantity belongs to shared state and has one range rule: 1–20. The reducers call that rule, rather than only hiding an invalid action in the view. Copy freezes the quantity whilst the request is pending, so its acknowledgement cannot be mistaken for a later edited plan.
The memory provider appears only inside a Rust test. The runnable native and Web apps use their real default clipboard hosts.
{"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, Default, PartialEq, Eq)]
pub enum CopyStatus {
#[default]
Idle,
Pending,
Copied,
Unsupported,
Failed,
}
impl CopyStatus {
pub fn key(self) -> &'static str {
match self {
Self::Idle => "lunch.ready",
Self::Pending => "lunch.copying",
Self::Copied => "lunch.copied",
Self::Unsupported => "lunch.unsupported",
Self::Failed => "lunch.failed",
}
}
}
#[derive(Debug)]
pub struct LunchPlanState {
pub quantity: u16,
pub copy_status: CopyStatus,
}
impl Default for LunchPlanState {
fn default() -> Self { Self { quantity: 1, copy_status: CopyStatus::Idle } }
}
impl GlobalState for LunchPlanState {}
impl LunchPlanState {
pub fn increase(&mut self) {
if self.copy_status == CopyStatus::Pending { return; }
self.quantity = self.quantity.saturating_add(1).min(20);
self.copy_status = CopyStatus::Idle;
}
pub fn decrease(&mut self) {
if self.copy_status == CopyStatus::Pending { return; }
self.quantity = self.quantity.saturating_sub(1).max(1);
self.copy_status = CopyStatus::Idle;
}
}
pub fn copy_quantity(state: &mut LunchPlanState, ctx: &mut ReducerContext<LunchPlanState>) {
if state.copy_status == CopyStatus::Pending { return; }
state.copy_status = CopyStatus::Pending;
let ok = ctx.effects.bind(QuantityCopied, reduce_with!(quantity_copied));
let err = ctx.effects.bind(CopyFailed, reduce_with!(copy_failed));
ctx.effects.clipboard().write_text(ClipboardWriteTextRequest {
text: state.quantity.to_string(),
}).on_ok(ok).on_err(err);
}
#[fission_reducer(QuantityCopied)]
fn quantity_copied(state: &mut LunchPlanState, ctx: &mut ReducerContext<LunchPlanState>) {
if state.copy_status != CopyStatus::Pending { return; }
state.copy_status = if ctx.input.capability_ok(WRITE_CLIPBOARD_TEXT).is_some() {
CopyStatus::Copied
} else {
CopyStatus::Failed
};
}
#[fission_reducer(CopyFailed)]
fn copy_failed(state: &mut LunchPlanState, ctx: &mut ReducerContext<LunchPlanState>) {
if state.copy_status != CopyStatus::Pending { return; }
state.copy_status = match ctx.input.capability_error(WRITE_CLIPBOARD_TEXT) {
Some(error) if error.code == "unsupported" => CopyStatus::Unsupported,
_ => CopyStatus::Failed,
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quantity_stays_bounded_and_cannot_change_during_copy() {
let mut state = LunchPlanState::default();
state.decrease();
assert_eq!(state.quantity, 1);
for _ in 0..30 { state.increase(); }
assert_eq!(state.quantity, 20);
state.copy_status = CopyStatus::Pending;
state.decrease();
assert_eq!(state.quantity, 20);
}
#[test]
fn memory_provider_round_trip_is_only_a_provider_contract_check() {
let host = MemoryClipboardHost::default();
assert_eq!(host.read_text().unwrap().text, None);
host.write_text(ClipboardWriteTextRequest { text: "2".into() }).unwrap();
assert_eq!(host.read_text().unwrap().text.as_deref(), Some("2"));
}
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, CopyStatus, LunchPlanState};
fission_component! {
pub LunchPlan<LunchPlanState> {}
view(_plan, state, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
SafeArea(child: Scroll(child: Container(
child: Column(gap: tokens.spacing.m, children: [
Text(cx.tr("lunch.title")).size(tokens.typography.heading2_size),
Text(cx.tr("lunch.context")),
SemanticsRegion(
identifier: Some("lunch.quantity".to_string()),
label: Some(cx.tr("lunch.quantity_label")),
value: Some(state.quantity.to_string()),
child: Text(state.quantity.to_string()).size(tokens.typography.heading1_size),
),
Wrap(spacing: tokens.spacing.s, children: [
Button(
child: Text(cx.tr("lunch.decrease")),
key: "decrease-lunch",
disabled: state.quantity == 1 || state.copy_status == CopyStatus::Pending,
on_press: reduce { state.decrease(); },
).semantics_identifier("lunch.decrease"),
Button(
child: Text(cx.tr("lunch.increase")),
key: "increase-lunch",
disabled: state.quantity == 20 || state.copy_status == CopyStatus::Pending,
on_press: reduce { state.increase(); },
).semantics_identifier("lunch.increase"),
]),
Button(
child: Text(cx.tr("lunch.copy")),
key: "copy-lunch-quantity",
disabled: state.copy_status == CopyStatus::Pending,
on_press: reduce { state::copy_quantity(state, cx); },
).semantics_identifier("lunch.copy"),
if state.copy_status == CopyStatus::Pending {
Spinner(
motion: Some(SpinnerMotion::Default),
label: cx.tr("lunch.copying"),
)
} else {
Text(cx.tr(state.copy_status.key()))
},
]),
).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"}
lunch.title: "Plan lunchbox quantities"
lunch.context: "Choose 1–20 lunchboxes, then copy the number into your own order. This app does not place an order or save the plan."
lunch.quantity_label: "Lunchbox quantity"
lunch.increase: "Add one lunchbox"
lunch.decrease: "Remove one lunchbox"
lunch.copy: "Copy quantity"
lunch.ready: "The clipboard has not been changed for this quantity."
lunch.copying: "Copying the quantity…"
lunch.copied: "Quantity copied."
lunch.unsupported: "This host cannot write to the clipboard. Use the displayed quantity."
lunch.failed: "The quantity could not be copied. The plan is still available."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
lunch.title: "Planificar las cantidades de almuerzos"
lunch.context: "Elige entre 1 y 20 almuerzos y copia la cantidad en tu propio pedido. Esta aplicación no hace el pedido ni guarda el plan."
lunch.quantity_label: "Cantidad de almuerzos"
lunch.increase: "Añadir un almuerzo"
lunch.decrease: "Quitar un almuerzo"
lunch.copy: "Copiar la cantidad"
lunch.ready: "No se ha cambiado el portapapeles para esta cantidad."
lunch.copying: "Copiando la cantidad…"
lunch.copied: "Cantidad copiada."
lunch.unsupported: "Este host no puede escribir en el portapapeles. Usa la cantidad mostrada."
lunch.failed: "No se pudo copiar la cantidad. El plan sigue disponible."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;
use app::LunchPlan;
use state::LunchPlanState;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<LunchPlanState, _>::new(LunchPlan)
.with_env(translations::create_env())
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<LunchPlanState, LunchPlan> {
let app = MobileApp::<LunchPlanState, _>::new(LunchPlan)
.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::<LunchPlanState, _>::new(LunchPlan)
.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::LunchPlanState, _>::new(app::LunchPlan)
.with_env(translations::create_env())
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}