The locale is app-wide presentation state. Reducers change NotesState.locale, then .with_sync_env(...) copies it into the environment used to resolve labels. A component does not need to know which file supplied its translation.
TextContent::Key keeps field labels tied to meaning rather than to the current English text. Ordinary captions use cx.tr(...) because they need a resolved string. The note body is supplied as literal user data; treating it as a key would mix application content with interface messages.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":2,"label":"src/app/note.rs","value":"src-app-note-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"}
mod note;
mod screen;
pub mod state;
pub use screen::NotesScreen;
pub use state::NotesState;
{"id":"fission-tabs-1","index":1,"label":"src/app/state.rs","value":"src-app-state-rs"}
use fission::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Note {
pub id: u64,
pub body: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NotesState {
pub notes: Vec<Note>,
pub next_id: u64,
pub locale: Locale,
}
impl Default for NotesState {
fn default() -> Self {
Self {
notes: Vec::new(),
next_id: 1,
locale: Locale::from("en-US"),
}
}
}
impl GlobalState for NotesState {}
pub fn add_note(state: &mut NotesState, body: &str) -> bool {
let body = body.trim();
if body.is_empty() {
return false;
}
let Some(next_id) = state.next_id.checked_add(1) else {
return false;
};
state.notes.push(Note {
id: state.next_id,
body: body.to_owned(),
});
state.next_id = next_id;
true
}
{"id":"fission-tabs-1","index":2,"label":"src/app/note.rs","value":"src-app-note-rs"}
use super::state::NotesState;
use fission::prelude::*;
fission_component! {
pub NoteRow<NotesState> {
props { note_id: u64 }
}
view(row, state, cx) {
let tokens = &cx.view.env().theme.tokens;
let note = state.notes.iter().find(|note| note.id == row.note_id);
} => if let Some(note) = note {
Container(
Column(gap: tokens.spacing.s, children: [
Text(note.body.clone()),
Button(
child: Text(cx.tr("notes.remove")), key: "remove-note",
on_press: reduce { state.notes.retain(|note| note.id != row.note_id); },
),
]),
)
.padding_all(tokens.spacing.m)
.border(tokens.colors.border, 1.0)
.border_radius(tokens.radii.medium)
} else {
Spacer()
}
}
{"id":"fission-tabs-1","index":3,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::{
note::NoteRow,
state::{add_note, NotesState},
};
use fission::prelude::*;
fission_component! {
pub NotesScreen<NotesState> {
state { draft: String = String::new() }
}
view(screen, state, cx) {
let tokens = &cx.view.env().theme.tokens;
let count = state.notes.len();
let count_key = match count {
0 => "notes.count.zero",
1 => "notes.count.one",
_ => "notes.count.other",
};
} => SafeArea(
child: Scroll(
child: Container(Column(gap: tokens.spacing.m, children: [
Text(cx.tr("notes.heading")).size(tokens.typography.heading2_size),
Text(cx.tr("notes.explanation")),
Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
Button(
child: Text(cx.tr("language.english")), key: "english",
disabled: state.locale == Locale::from("en-US"),
on_press: reduce { state.locale = Locale::from("en-US"); },
),
Button(
child: Text(cx.tr("language.spanish")), key: "spanish",
disabled: state.locale == Locale::from("es-ES"),
on_press: reduce { state.locale = Locale::from("es-ES"); },
),
]),
TextInput(
value: screen.draft.clone(), bind(on_input): to(screen.draft),
label: Some(TextContent::Key("notes.draft".into())),
helper_text: Some(TextContent::Key("notes.draft_help".into())),
multiline: true, keyboard_type: TextInputType::Multiline,
),
Button(
child: Text(cx.tr("notes.add")), key: "add-note",
disabled: screen.draft.trim().is_empty() || state.next_id == u64::MAX,
on_press: reduce {
if add_note(state, &screen.draft) { screen.draft.clear(); }
},
),
Text(cx.tr(count_key).replace("{count}", &count.to_string())),
if state.notes.is_empty() {
Text(cx.tr("notes.empty"))
},
for note in &state.notes {
NoteRow(note.id, key: note.id)
},
Text(cx.tr("notes.session")).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 notes translations");
env.i18n.add_bundle(TranslationBundle {
locale: Locale::from(locale),
messages,
});
}
env
}
pub fn sync_env(state: &crate::app::NotesState, env: &mut Env) {
env.locale = state.locale.clone();
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
#[test]
fn both_languages_define_the_same_nonempty_messages() {
let english: HashMap<String, String> =
serde_yaml::from_str(include_str!("../i18n/en-US.yaml")).unwrap();
let spanish: HashMap<String, String> =
serde_yaml::from_str(include_str!("../i18n/es-ES.yaml")).unwrap();
assert_eq!(
english.keys().collect::<BTreeSet<_>>(),
spanish.keys().collect::<BTreeSet<_>>(),
);
assert!(english
.values()
.chain(spanish.values())
.all(|value| !value.trim().is_empty()));
}
}
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod i18n;
use app::{NotesScreen, NotesState};
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<NotesState, _>::new(NotesScreen)
.with_env(i18n::create_env())
.with_sync_env(i18n::sync_env)
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
MobileApp::<NotesState, _>::new(NotesScreen)
.with_env(i18n::create_env())
.with_sync_env(i18n::sync_env)
.run()
}
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
let _ = MobileApp::<NotesState, _>::new(NotesScreen)
.with_env(i18n::create_env())
.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::<NotesState, _>::new(NotesScreen)
.with_env(i18n::create_env())
.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::NotesState, _>::new(app::NotesScreen)
.with_env(i18n::create_env())
.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"}
notes.heading: "Your session notes"
notes.explanation: "Write notes in your own words. Changing the interface language does not translate or replace what you wrote."
notes.draft: "New note"
notes.draft_help: "Add a reminder you want to keep whilst this app is open. Avoid including private information on a shared device."
notes.add: "Add this note to the session list"
notes.remove: "Remove note"
notes.count.zero: "No notes yet"
notes.count.one: "One note"
notes.count.other: "{count} notes"
notes.empty: "Write a note above to start your list."
notes.session: "These notes stay in memory only. Closing or reloading the app clears them."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":8,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
notes.heading: "Tus notas de esta sesión"
notes.explanation: "Escribe las notas con tus propias palabras. Cambiar el idioma de la interfaz no traduce ni sustituye lo que has escrito."
notes.draft: "Nueva nota"
notes.draft_help: "Añade un recordatorio que quieras conservar mientras la aplicación esté abierta. Evita información privada en un dispositivo compartido."
notes.add: "Añadir esta nota a la lista de la sesión"
notes.remove: "Eliminar nota"
notes.count.zero: "Todavía no hay notas"
notes.count.one: "Una nota"
notes.count.other: "{count} notas"
notes.empty: "Escribe una nota arriba para empezar tu lista."
notes.session: "Estas notas solo están en memoria. Cerrar o recargar la aplicación las borra."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}