The draft is application data. Its revision changes whenever the text changes. pending_revision records the revision at the start of the one permitted clipboard request; it is not the current value of the text and must not change as someone types.
The starting reducer binds both completion actions before borrowing the effect builder. Each callback reads the actual result from cx.input. An authored action payload would carry the value supplied when the action was bound, not the value returned by the host.
The button disables additional paste requests while one is pending, but the text field remains editable. A spinner represents pending work. Empty and failed reads preserve the draft and allow another attempt.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/reducers.rs","value":"src-reducers-rs"},{"index":2,"label":"src/app.rs","value":"src-app-rs"},{"index":3,"label":"src/lib.rs","value":"src-lib-rs"},{"index":4,"label":"src/translations.rs","value":"src-translations-rs"},{"index":5,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NoteState {
pub draft: String,
pub revision: u64,
pub pending_revision: Option<u64>,
pub status: &'static str,
pub error: Option<String>,
}
impl GlobalState for NoteState {}
impl NoteState {
pub fn edit(&mut self, text: String) {
self.draft = text;
self.revision += 1;
self.status = "paste.status.editing";
self.error = None;
}
pub fn begin_paste(&mut self) -> bool {
if self.pending_revision.is_some() {
return false;
}
self.pending_revision = Some(self.revision);
self.status = "paste.status.pending";
self.error = None;
true
}
pub fn complete_paste(&mut self, result: Result<Option<String>, String>) {
let Some(request_revision) = self.pending_revision.take() else { return };
if request_revision != self.revision {
self.status = "paste.status.ignored";
return;
}
match result {
Ok(Some(text)) if !text.trim().is_empty() => {
if text.chars().count() > 2000 {
self.status = "paste.status.too_long";
return;
}
self.edit(text);
self.status = "paste.status.pasted";
}
Ok(_) => self.status = "paste.status.empty",
Err(error) => {
self.status = "paste.status.failed";
self.error = Some(error);
}
}
}
}
{"id":"fission-tabs-1","index":1,"label":"src/reducers.rs","value":"src-reducers-rs"}
use fission::prelude::*;
use crate::state::NoteState;
pub fn request_paste(state: &mut NoteState, cx: &mut ReducerContext<NoteState>) {
if !state.begin_paste() { return; }
let ok = cx.effects.bind(PasteCompleted, reduce_with!(paste_completed));
let err = cx.effects.bind(PasteFailed, reduce_with!(paste_failed));
cx.effects.clipboard().read_text().on_ok(ok).on_err(err);
}
#[fission_reducer(PasteCompleted)]
fn paste_completed(state: &mut NoteState, cx: &mut ReducerContext<NoteState>) {
let result = cx.input.capability_ok(READ_CLIPBOARD_TEXT)
.map(|value| value.text)
.ok_or_else(|| "Clipboard completion had no text result".to_owned());
state.complete_paste(result);
}
#[fission_reducer(PasteFailed)]
fn paste_failed(state: &mut NoteState, cx: &mut ReducerContext<NoteState>) {
let error = cx.input.capability_error(READ_CLIPBOARD_TEXT)
.map(|error| error.message)
.or_else(|| cx.input.capability_error_message(READ_CLIPBOARD_TEXT).map(str::to_owned))
.unwrap_or_else(|| "Clipboard read failed".to_owned());
state.complete_paste(Err(error));
}
{"id":"fission-tabs-1","index":2,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::{reducers::request_paste, state::NoteState};
fission_component! {
pub DeliveryNote<NoteState> {}
view(_note, state, cx) {
let tokens = &cx.view.env().theme.tokens;
let status = if state.status.is_empty() { "paste.status.ready" } else { state.status };
} =>
Container(SafeArea(child: Scroll(child: Container(
Column(gap: tokens.spacing.m, children: [
Text(cx.tr("paste.title")).size(tokens.typography.heading2_size),
Text(cx.tr("paste.summary")).color(tokens.colors.text_secondary),
TextInput(
label: Some(cx.tr("paste.note.label").into()),
value: state.draft.clone(),
multiline: true,
min_lines: Some(4),
max_lines: Some(8),
max_length: Some(2000),
semantics_identifier: Some("delivery-note.draft".into()),
on_input: reduce {
if let Some(change) = cx.input.text_change() {
state.edit(change.new_text.clone());
}
},
),
Button(
child: Text(cx.tr("paste.action")),
key: "paste-note",
disabled: state.pending_revision.is_some(),
on_press: reduce { request_paste(state, cx); },
).semantics_identifier("delivery-note.paste"),
if state.pending_revision.is_some() { Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("paste.status.pending"))) },
Text(cx.tr(status)),
if let Some(error) = &state.error {
Code(text: error.clone())
},
Text(cx.tr("paste.scope")).color(tokens.colors.text_secondary),
])
).padding_all(tokens.spacing.l)
.width_length(Length::percent(100.0))
.max_width(720.0))))
.height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1","index":3,"label":"src/lib.rs","value":"src-lib-rs"}
mod state;
mod reducers;
mod app;
mod translations;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<state::NoteState, _>::new(app::DeliveryNote)
.with_env(translations::create_env())
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<state::NoteState, app::DeliveryNote> {
let app = MobileApp::<state::NoteState, _>::new(app::DeliveryNote)
.with_env(translations::create_env())
.with_title("Delivery note");
#[cfg(target_os = "android")]
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::<state::NoteState, _>::new(app::DeliveryNote)
.with_env(translations::create_env())
.with_title("Delivery note")
.run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":4,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::i18n::{Locale, TranslationBundle};
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("checked-in setup translations");
env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
}
env
}
{"id":"fission-tabs-1","index":5,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod state;
mod reducers;
mod app;
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::NoteState, _>::new(app::DeliveryNote)
.with_env(translations::create_env())
.with_title("Delivery note")
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
paste.title: "Delivery instructions"
paste.summary: "Paste instructions you have copied, or type a new note. A late clipboard result must not replace a newer edit."
paste.note.label: "Instructions for this delivery"
paste.action: "Paste from clipboard"
paste.status.ready: "No clipboard request has been made."
paste.status.editing: "Draft changed; nothing has been submitted."
paste.status.pending: "Reading the clipboard…"
paste.status.ignored: "Your newer edit was kept. The earlier paste result was ignored."
paste.status.too_long: "The copied text exceeds the 2,000-character limit. Your draft was kept."
paste.status.pasted: "Copied text inserted; review it before using it."
paste.status.empty: "The clipboard contains no plain text. Your draft was kept."
paste.status.failed: "The clipboard could not be read. Keep typing or try again."
paste.scope: "This draft stays in app memory. It is not saved or sent to a delivery service. Clipboard access occurs only after pressing Paste."
{"id":"fission-tabs-1","index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
paste.title: "Instrucciones de entrega"
paste.summary: "Pega instrucciones que hayas copiado o escribe una nota. Un resultado tardío no debe sustituir una edición más reciente."
paste.note.label: "Instrucciones para esta entrega"
paste.action: "Pegar del portapapeles"
paste.status.ready: "No se ha solicitado acceso al portapapeles."
paste.status.editing: "Borrador modificado; no se ha enviado nada."
paste.status.pending: "Leyendo el portapapeles…"
paste.status.ignored: "Se ha conservado tu edición más reciente y se ha ignorado el resultado anterior."
paste.status.too_long: "El texto copiado supera el límite de 2000 caracteres. Se conserva el borrador."
paste.status.pasted: "Texto copiado insertado; revísalo antes de usarlo."
paste.status.empty: "El portapapeles no contiene texto. Se conserva el borrador."
paste.status.failed: "No se ha podido leer el portapapeles. Sigue escribiendo o inténtalo de nuevo."
paste.scope: "El borrador permanece en la memoria de la app. No se guarda ni se envía a un servicio. Solo se accede al portapapeles al pulsar Pegar."
{"id":"fission-tabs-1"}