This is the bounded photo workflow developed in the iOS capture tutorial, applied to a repair inspection rather than a preloaded delivery. Its provider boundary stays target-specific, whilst the app's state transitions and image preparation remain shared. The global draft belongs to the inspection workflow, not one disposable camera widget. A capture snapshots its asset reference; a changed reference cannot silently inherit that photo. The prepared review contains its own note and actual image snapshot, not a boolean which merely suggests that evidence exists.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/jobs.rs","value":"src-app-jobs-rs"},{"index":2,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":3,"label":"src/app/screen.rs","value":"src-app-screen-rs"},{"index":4,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":5,"label":"src/lib.rs","value":"src-lib-rs"},{"index":6,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":7,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":8,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
pub mod jobs;
mod screen;
pub mod state;
pub use screen::RepairScreen;
pub use state::RepairState;
{"id":"fission-tabs-1","index":1,"label":"src/app/jobs.rs","value":"src-app-jobs-rs"}
use fission::core::{CameraCapture, JobCtx, JobRef, JobSpec};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PhotoRequest {
pub reference: String,
pub capture: CameraCapture,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InspectionPhoto {
pub reference: String,
pub bytes: Vec<u8>,
pub content_type: String,
}
pub struct CollectPhoto;
impl JobSpec for CollectPhoto {
type Request = PhotoRequest;
type Ok = InspectionPhoto;
type Err = String;
const NAME: &'static str = "repair.collect-photo";
}
pub const COLLECT_PHOTO: JobRef<CollectPhoto> = JobRef::new(CollectPhoto::NAME);
pub async fn collect_photo(request: PhotoRequest, cx: JobCtx) -> Result<InspectionPhoto, String> {
let mut stream = cx
.open_data_stream(request.capture.stream)
.map_err(|error| error.to_string())?;
// Consume the one-shot handle even when its metadata fails these bounds.
let pixels = u64::from(request.capture.width) * u64::from(request.capture.height);
if pixels == 0 || pixels > 16_000_000 {
return Err("Unsupported image dimensions".into());
}
if !matches!(
request.capture.content_type.as_str(),
"image/jpeg" | "image/png"
) {
return Err("Only JPEG and PNG arrival photos are accepted".into());
}
let mut bytes = Vec::new();
while let Some(chunk) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
let chunk = chunk.map_err(|error| error.to_string())?;
let length = bytes
.len()
.checked_add(chunk.len())
.ok_or("Image is too large")?;
if length > 8 * 1024 * 1024 {
return Err("Image exceeds the eight-MiB limit".into());
}
bytes.extend_from_slice(&chunk);
}
if bytes.is_empty() {
return Err("The camera returned an empty image".into());
}
Ok(InspectionPhoto {
reference: request.reference,
bytes,
content_type: request.capture.content_type,
})
}
{"id":"fission-tabs-1","index":2,"label":"src/app/state.rs","value":"src-app-state-rs"}
use super::jobs::{InspectionPhoto, PhotoRequest, COLLECT_PHOTO};
use fission::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReviewSnapshot {
pub reference: String,
pub note: String,
pub photo: InspectionPhoto,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RepairState {
pub locale: Locale,
pub reference: String,
pub note: String,
pub busy: bool,
pub status_key: String,
pub error: Option<String>,
pub device: Option<CameraDevice>,
pub photo: Option<InspectionPhoto>,
pub capture_reference: Option<String>,
pub torch_on: bool,
pub torch_requested: Option<bool>,
pub review: Option<ReviewSnapshot>,
}
impl Default for RepairState {
fn default() -> Self {
Self {
locale: Locale::from("en-US"),
reference: String::new(),
note: String::new(),
busy: false,
status_key: "repair.ready".into(),
error: None,
device: None,
photo: None,
capture_reference: None,
torch_on: false,
torch_requested: None,
review: None,
}
}
}
impl GlobalState for RepairState {}
fn unexpected(state: &mut RepairState) {
state.busy = false;
state.capture_reference = None;
state.torch_requested = None;
state.status_key = "repair.unexpected".into();
}
pub fn check_camera(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
if state.busy || state.torch_on {
return;
}
state.busy = true;
state.error = None;
state.status_key = "repair.permission_pending".into();
let ok = cx
.effects
.bind(PermissionReturned, reduce_with!(permission_returned));
let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
cx.effects
.camera()
.request_permission(CameraPermissionRequest { reason: None })
.on_ok(ok)
.on_err(err);
}
#[fission_reducer(PermissionReturned)]
fn permission_returned(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
match cx.input.capability_ok(REQUEST_CAMERA_PERMISSION) {
Some(CameraPermission::Granted) => {
state.status_key = "repair.features_pending".into();
let ok = cx
.effects
.bind(FeaturesReturned, reduce_with!(features_returned));
let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
cx.effects.camera().availability().on_ok(ok).on_err(err);
}
Some(CameraPermission::Denied | CameraPermission::Restricted) => {
state.busy = false;
state.device = None;
state.status_key = "repair.denied".into();
}
Some(CameraPermission::Unknown) => {
state.busy = false;
state.device = None;
state.status_key = "repair.unknown".into();
}
None => unexpected(state),
}
}
#[fission_reducer(FeaturesReturned)]
fn features_returned(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
let Some(features) = cx.input.capability_ok(GET_CAMERA_AVAILABILITY) else {
unexpected(state);
return;
};
state.busy = false;
if features.permission != CameraPermission::Granted {
state.device = None;
state.status_key = "repair.denied".into();
return;
}
state.device = features
.devices
.iter()
.find(|device| device.facing == CameraFacing::Back)
.or_else(|| features.devices.first())
.cloned();
state.status_key = if state.device.is_some() {
"repair.camera_ready"
} else {
"repair.unavailable"
}
.into();
}
pub fn capture(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
if state.busy || state.reference.trim().is_empty() {
return;
}
let Some(device) = state.device.clone() else {
return;
};
state.capture_reference = Some(state.reference.trim().to_owned());
state.busy = true;
state.error = None;
state.status_key = "repair.capture_pending".into();
let ok = cx.effects.bind(Captured, reduce_with!(captured));
let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
cx.effects
.camera()
.capture_photo(CameraCaptureRequest {
camera_id: Some(device.id),
facing: device.facing,
resolution: Some(CameraResolution {
width: 1600,
height: 1200,
}),
format: CameraImageFormat::Jpeg,
flash: CameraFlashMode::Off,
quality: Some(88),
})
.on_ok(ok)
.on_err(err);
}
#[fission_reducer(Captured)]
fn captured(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
let Some(capture) = cx.input.capability_ok(CAPTURE_PHOTO) else {
unexpected(state);
return;
};
let Some(reference) = state.capture_reference.take() else {
unexpected(state);
return;
};
state.status_key = "repair.image_pending".into();
let ok = cx
.effects
.bind(PhotoCollected, reduce_with!(photo_collected));
let err = cx.effects.bind(PhotoFailed, reduce_with!(photo_failed));
cx.effects
.app(COLLECT_PHOTO, PhotoRequest { reference, capture })
.on_ok(ok)
.on_err(err);
}
#[fission_reducer(PhotoCollected)]
fn photo_collected(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
state.busy = false;
match cx.input.job_ok(COLLECT_PHOTO) {
Some(photo) => {
state.photo = Some(photo);
state.status_key = "repair.attached".into();
}
None => unexpected(state),
}
}
#[fission_reducer(PhotoFailed)]
fn photo_failed(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
state.busy = false;
state.status_key = "repair.failed".into();
state.error = cx.input.job_err(COLLECT_PHOTO);
if state.error.is_none() {
unexpected(state);
}
}
pub fn toggle_torch(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
if state.busy {
return;
}
let Some(device) = state.device.as_ref().filter(|device| device.has_flashlight) else {
return;
};
let request = CameraFlashlightRequest {
camera_id: Some(device.id.clone()),
enabled: !state.torch_on,
intensity: None,
};
state.torch_requested = Some(request.enabled);
state.busy = true;
state.error = None;
state.status_key = "repair.torch_pending".into();
let ok = cx.effects.bind(TorchChanged, reduce_with!(torch_changed));
let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
cx.effects
.camera()
.set_flashlight(request)
.on_ok(ok)
.on_err(err);
}
#[fission_reducer(TorchChanged)]
fn torch_changed(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
state.busy = false;
match (
cx.input.capability_ok(SET_CAMERA_FLASHLIGHT),
state.torch_requested.take(),
) {
(Some(()), Some(enabled)) => {
state.torch_on = enabled;
state.status_key = "repair.torch_changed".into();
}
_ => unexpected(state),
}
}
#[fission_reducer(CameraFailed)]
fn camera_failed(state: &mut RepairState, cx: &mut ReducerContext<RepairState>) {
state.busy = false;
state.capture_reference = None;
state.torch_requested = None;
let error = cx
.input
.capability_error(REQUEST_CAMERA_PERMISSION)
.or_else(|| cx.input.capability_error(GET_CAMERA_AVAILABILITY))
.or_else(|| cx.input.capability_error(CAPTURE_PHOTO))
.or_else(|| cx.input.capability_error(SET_CAMERA_FLASHLIGHT));
match error {
Some(error) => {
state.status_key = if error.code == "unsupported" {
"repair.unavailable"
} else {
"repair.failed"
}
.into();
state.error = Some(format!("{}: {}", error.code, error.message));
}
None => unexpected(state),
}
}
pub fn prepare_review(state: &mut RepairState) {
if state.busy {
return;
}
let Some(photo) = state.photo.as_ref() else {
return;
};
let reference = state.reference.trim();
if reference.is_empty() || state.note.trim().is_empty() || photo.reference != reference {
return;
}
state.review = Some(ReviewSnapshot {
reference: reference.to_owned(),
note: state.note.trim().to_owned(),
photo: photo.clone(),
});
}
{"id":"fission-tabs-1","index":3,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::state::{capture, check_camera, prepare_review, toggle_torch, RepairState};
use fission::prelude::*;
fission_component! {
pub RepairScreen<RepairState> {}
view(_screen, state, cx) {
let tokens = &cx.view.env().theme.tokens;
let matching_photo = state.photo.as_ref()
.is_some_and(|photo| photo.reference == state.reference.trim());
let can_prepare = !state.busy && !state.reference.trim().is_empty()
&& !state.note.trim().is_empty() && matching_photo;
let image_width = (cx.view.viewport_size().width - 2.0 * tokens.spacing.l).clamp(1.0, 560.0);
} => SafeArea(child: Scroll(child: Container(Column(gap: tokens.spacing.m, children: [
Text(cx.tr("repair.title")).size(tokens.typography.heading2_size),
Text(cx.tr("repair.explanation")),
Row(gap: tokens.spacing.s, children: [
Button(child: Text(cx.tr("language.english")), key: "english",
on_press: reduce { state.locale = Locale::from("en-US"); }),
Button(child: Text(cx.tr("language.spanish")), key: "spanish",
on_press: reduce { state.locale = Locale::from("es-ES"); }),
]),
FormControl(
label: Some(cx.tr("repair.reference")),
required: true,
child: TextInput(
value: state.reference.clone(),
bind(on_input): to(state.reference),
),
),
FormControl(
label: Some(cx.tr("repair.note")),
required: true,
child: TextInput(
value: state.note.clone(),
bind(on_input): to(state.note),
multiline: true,
keyboard_type: TextInputType::Multiline,
),
),
Button(child: Text(cx.tr("repair.check_camera")), key: "camera-access",
disabled: state.busy || state.torch_on,
on_press: reduce { check_camera(state, cx); }),
Button(child: Text(cx.tr("repair.capture")), key: "capture",
disabled: state.busy || state.device.is_none() || state.reference.trim().is_empty(),
on_press: reduce { capture(state, cx); }),
if state.device.as_ref().is_some_and(|device| device.has_flashlight) {
Button(child: Text(cx.tr(if state.torch_on { "repair.torch_off" } else { "repair.torch_on" })),
key: "torch", disabled: state.busy,
on_press: reduce { toggle_torch(state, cx); })
} else { Text(cx.tr("repair.no_torch")) },
if state.busy {
Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr(&state.status_key)))
},
Text(cx.tr(&state.status_key)),
if let Some(error) = &state.error { Code(text: error.clone()) },
if let Some(photo) = &state.photo {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr("repair.photo_for").replace("{reference}", &photo.reference)),
Image::memory(photo.bytes.clone()).size(image_width, image_width * 0.75)
.fit(ir_op::ImageFit::Contain).semantic_label(cx.tr("repair.photo_label")),
])
},
Button(child: Text(cx.tr("repair.prepare")), key: "prepare", disabled: !can_prepare,
on_press: reduce { prepare_review(state); }),
if let Some(review) = &state.review {
Column(gap: tokens.spacing.s, children: [
Text(cx.tr("repair.prepared")).weight(tokens.typography.font_weight_semibold),
Text(review.reference.clone()),
Text(review.note.clone()),
Text(cx.tr("repair.prepared_photo").replace("{bytes}", &review.photo.bytes.len().to_string())),
])
},
Text(cx.tr("repair.scope")).color(tokens.colors.text_secondary),
])).padding_all(tokens.spacing.l)))
}
{"id":"fission-tabs-1","index":4,"label":"src/i18n.rs","value":"src-i18n-rs"}
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;
use std::collections::HashMap;
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 voice note translations");
env.i18n.add_bundle(TranslationBundle {
locale: Locale::from(locale),
messages,
});
}
env
}
pub fn sync_env(state: &crate::app::RepairState, env: &mut Env) {
env.locale = state.locale.clone();
}
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod i18n;
use app::{RepairScreen, RepairState};
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<RepairState, _>::new(RepairScreen)
.with_env(i18n::create_env())
.with_async(|asyncs| {
asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
app::jobs::collect_photo(request, cx).await
});
})
.with_sync_env(i18n::sync_env)
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
MobileApp::<RepairState, _>::new(RepairScreen)
.with_env(i18n::create_env())
.with_async(|asyncs| {
asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
app::jobs::collect_photo(request, cx).await
});
})
.with_sync_env(i18n::sync_env)
.run()
}
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
let _ = MobileApp::<RepairState, _>::new(RepairScreen)
.with_env(i18n::create_env())
.with_async(|asyncs| {
asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
app::jobs::collect_photo(request, cx).await
});
})
.with_sync_env(i18n::sync_env)
.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::<RepairState, _>::new(RepairScreen)
.with_env(i18n::create_env())
.with_async(|asyncs| {
asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
app::jobs::collect_photo(request, cx).await
});
})
.with_sync_env(i18n::sync_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 i18n;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<app::RepairState, _>::new(app::RepairScreen)
.with_env(i18n::create_env())
.with_async(|asyncs| {
asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
app::jobs::collect_photo(request, cx).await
});
})
.with_sync_env(i18n::sync_env)
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
repair.title: "Photograph a repair inspection"
repair.explanation: "Enter the actual asset reference and inspection note, then attach a real camera photo."
repair.reference: "Asset or repair reference"
repair.note: "Condition observed"
repair.check_camera: "Check camera access and features"
repair.capture: "Capture inspection photo"
repair.torch_on: "Turn flashlight on"
repair.torch_off: "Turn flashlight off"
repair.no_torch: "Flashlight control is shown only after this camera reports a torch."
repair.ready: "No camera request has been made."
repair.permission_pending: "Waiting for camera permission…"
repair.features_pending: "Checking camera features…"
repair.denied: "Camera access was denied or restricted. Keep the note and review device policy or Settings."
repair.unknown: "Camera permission remains unknown. The note is unchanged."
repair.camera_ready: "The host reported a camera available. Capture still needs to succeed."
repair.unavailable: "The camera operation is unavailable on this host."
repair.capture_pending: "Capturing a photograph…"
repair.image_pending: "Reading the actual image…"
repair.attached: "The camera image is attached in this session."
repair.failed: "The operation failed. The previous image and draft are unchanged."
repair.unexpected: "The host returned no usable result. The previous image and draft are unchanged."
repair.torch_pending: "Waiting for the flashlight response…"
repair.torch_changed: "The host confirmed the flashlight request."
repair.photo_for: "Camera photo for asset {reference}"
repair.photo_label: "Actual camera photo for the inspected asset"
repair.prepare: "Prepare repair review"
repair.prepared: "Prepared review snapshot — not sent"
repair.prepared_photo: "This snapshot contains the actual {bytes}-byte photograph."
repair.scope: "Everything is session-local. Preparing a review does not save it or send a repair request. Turn the flashlight off when finished."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":8,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
repair.title: "Fotografiar una inspección"
repair.explanation: "Introduce la referencia real del equipo y la observación; después adjunta una foto de la cámara."
repair.reference: "Referencia de equipo o reparación"
repair.note: "Estado observado"
repair.check_camera: "Comprobar acceso y funciones de cámara"
repair.capture: "Capturar foto de inspección"
repair.torch_on: "Encender la linterna"
repair.torch_off: "Apagar la linterna"
repair.no_torch: "El control aparece solo cuando esta cámara indica que tiene linterna."
repair.ready: "No se ha solicitado acceso a la cámara."
repair.permission_pending: "Esperando el permiso de cámara…"
repair.features_pending: "Comprobando las funciones de cámara…"
repair.denied: "El acceso fue denegado o restringido. Conserva la nota y revisa la política del dispositivo o Ajustes."
repair.unknown: "El permiso sigue siendo desconocido. La nota no ha cambiado."
repair.camera_ready: "El host indicó una cámara disponible. La captura aún debe completarse."
repair.unavailable: "La operación de cámara no está disponible en este host."
repair.capture_pending: "Capturando una fotografía…"
repair.image_pending: "Leyendo la imagen real…"
repair.attached: "La foto de cámara está adjunta durante esta sesión."
repair.failed: "La operación falló. La imagen anterior y el borrador no han cambiado."
repair.unexpected: "El host no devolvió un resultado utilizable. La imagen anterior y el borrador no han cambiado."
repair.torch_pending: "Esperando la respuesta de la linterna…"
repair.torch_changed: "El host confirmó la solicitud de linterna."
repair.photo_for: "Foto de cámara del equipo {reference}"
repair.photo_label: "Foto real de cámara del equipo inspeccionado"
repair.prepare: "Preparar revisión de reparación"
repair.prepared: "Resumen preparado — no enviado"
repair.prepared_photo: "Este resumen contiene la fotografía real de {bytes} bytes."
repair.scope: "Todo permanece en esta sesión. Preparar una revisión no la guarda ni envía una solicitud de reparación. Apaga la linterna al terminar."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}