Add iOS navigation and preserve unsaved work

Edit a service note through Fission Router, keeping its draft on navigation and asking before discarding changes.
iOS

What you will build

Move between the notes screen and editor without making Back, cancel and deliberate discard mean the same thing.
Route through the native Router and registered route-change handler
Keep the draft and session-saved note in shared state
Confirm discard explicitly and preserve the draft when that confirmation is cancelled
Leaving an editor does not have to mean discarding its work. A simpler rule is to retain the draft until the user explicitly saves or discards it. That makes in-app navigation and host Back safe without trying to infer intent from a route change.
We will build a service-note app with a home route, an editor and a real discard dialog. The note starts empty and comes from the user's input. Saved content and the draft belong to application state because they must outlive either route; whether the dialog is open is local editor state.
Start from a new project (optional)

Create the project and add the target

Complete iOS setup first.
cargo install cargo-fission
fission init ios-add-ios-navigation-and-preserve-unsaved-work
cd ios-add-ios-navigation-and-preserve-unsaved-work
fission add-target ios --project-dir .
cargo add serde_yaml
Keep the generated src/main.rs and replace src/lib.rs. Every shell installs the same route handler and shared app. This is normal Router navigation, not a boolean that selects one of two disconnected mock screens.

Run the finished example

fission run --target ios --project-dir .

1. Build the routes around a retained draft

The Router table contains lazy component values. Only the matched route builds its screen. The route handler mirrors ShellRouteChanged into application state, so host history and the rendered destination use the same route value.
{"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/home.rs","value":"src-app-home-rs"},{"index":3,"label":"src/app/editor.rs","value":"src-app-editor-rs"},{"index":4,"label":"src/app/routes.rs","value":"src-app-routes-rs"},{"index":5,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":6,"label":"src/lib.rs","value":"src-lib-rs"},{"index":7,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":9,"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 editor;
pub mod home;
pub mod routes;
pub mod state;

pub use routes::NotesApp;
pub use state::{route_changed, 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 NotesState {
    pub current_path: String,
    pub saved_note: String,
    pub draft: String,
    pub locale: Locale,
}

impl Default for NotesState {
    fn default() -> Self {
        Self {
            current_path: "/".into(),
            saved_note: String::new(),
            draft: String::new(),
            locale: Locale::from("en-US"),
        }
    }
}

impl GlobalState for NotesState {}

pub fn route_changed(
    state: &mut NotesState,
    action: fission::core::action::ShellRouteChanged,
    _cx: &mut ReducerContext<NotesState>,
) {
    state.current_path = action.location.pathname;
}
{"id":"fission-tabs-1","index":2,"label":"src/app/home.rs","value":"src-app-home-rs"}
use super::state::NotesState;
use fission::prelude::*;

fission_component! {
    pub NotesHome<NotesState> {}
    view(_home, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } => Column(gap: tokens.spacing.m, children: [
        Text(cx.tr("notes.home")).size(tokens.typography.heading2_size),
        if state.saved_note.is_empty() {
            Text(cx.tr("notes.empty"))
        } else {
            Text(state.saved_note.clone())
        },
        if state.draft != state.saved_note {
            Text(cx.tr("notes.has_draft"))
        },
        Button(
            child: Text(cx.tr("notes.edit")),
            key: "edit-note",
            on_press: reduce { cx.effects.navigate("/notes/edit"); },
        ),
        Text(cx.tr("notes.storage_scope")).color(tokens.colors.text_secondary),
    ])
}
{"id":"fission-tabs-1","index":3,"label":"src/app/editor.rs","value":"src-app-editor-rs"}
use super::state::NotesState;
use fission::prelude::*;

fission_component! {
    pub NoteEditor<NotesState> {
        state {
            confirm_discard: bool = false,
        }
    }
    view(editor, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let dirty = state.draft != state.saved_note;
    } => Column(gap: tokens.spacing.m, children: [
        Text(cx.tr("notes.editor")).size(tokens.typography.heading2_size),
        TextInput(
            value: state.draft.clone(),
            bind(on_input): to(state.draft),
            label: Some(TextContent::Key("notes.note_label".into())),
            multiline: true,
            semantics_identifier: Some("notes.draft".into()),
        ),
        Text(cx.tr(if dirty { "notes.unsaved" } else { "notes.no_changes" })),
        Button(
            child: Text(cx.tr("notes.save_session")),
            key: "save-session-note",
            disabled: !dirty,
            on_press: reduce { state.saved_note = state.draft.clone(); },
        ),
        Button(
            child: Text(cx.tr("notes.back")),
            key: "back-to-notes",
            on_press: reduce { cx.effects.replace_route("/"); },
        ),
        Button(
            child: Text(cx.tr("notes.discard")),
            key: "request-discard",
            disabled: !dirty,
            on_press: reduce { editor.confirm_discard = true; },
        ),
        Modal(
            id: WidgetId::explicit("notes.discard-dialog"),
            title: cx.tr("notes.discard_title"),
            is_open: editor.confirm_discard,
            on_dismiss: reduce { editor.confirm_discard = false; },
            content: Column(gap: tokens.spacing.m, children: [
                Text(cx.tr("notes.discard_explanation")),
                Button(
                    child: Text(cx.tr("notes.keep_editing")),
                    key: "keep-editing",
                    on_press: reduce { editor.confirm_discard = false; },
                ),
                Button(
                    child: Text(cx.tr("notes.confirm_discard")),
                    key: "confirm-discard",
                    on_press: reduce {
                        state.draft = state.saved_note.clone();
                        editor.confirm_discard = false;
                    },
                ),
            ]),
        ),
    ])
}
{"id":"fission-tabs-1","index":4,"label":"src/app/routes.rs","value":"src-app-routes-rs"}
use super::editor::NoteEditor;
use super::home::NotesHome;
use super::state::NotesState;
use fission::prelude::*;

fission_component! {
    pub UnknownRoute<NotesState> {}
    view(_unknown, _state, cx) => Column(children: [
        Text(cx.tr("notes.not_found")),
        Button(
            child: Text(cx.tr("notes.home")),
            key: "recover-home",
            on_press: reduce { cx.effects.replace_route("/"); },
        ),
    ])
}

fission_component! {
    pub NotesApp<NotesState> {}
    view(_app, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let router = Router::<NotesState>::new()
            .with_path(state.current_path.clone())
            .route_component("/", NotesHome)
            .route_component("/notes/edit", NoteEditor)
            .not_found(|| UnknownRoute);
    } => SafeArea(
        child: Scroll(
            child: Container(
                Column(gap: tokens.spacing.m, children: [
                    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"); },
                        ),
                    ]),
                    router,
                ]),
            )
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface),
        ),
    )
}
{"id":"fission-tabs-1","index":5,"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 navigation 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();
}
{"id":"fission-tabs-1","index":6,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod i18n;

use app::{NotesApp, 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(NotesApp)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .with_route_handler(app::route_changed)
        .run()
}

#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
    MobileApp::<NotesState, _>::new(NotesApp)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .with_route_handler(app::route_changed)
        .run()
}

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = MobileApp::<NotesState, _>::new(NotesApp)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .with_route_handler(app::route_changed)
        .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(NotesApp)
        .with_navigation(WebNavigationConfig::new(WebRouteStrategy::Hash))
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .with_route_handler(app::route_changed)
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"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();
    let window =
        web_sys::window().ok_or_else(|| JsValue::from_str("browser window unavailable"))?;
    let base_path = window.location().pathname()?;
    WebApp::<app::NotesState, _>::new(app::NotesApp)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .with_route_handler(app::route_changed)
        .with_navigation(WebNavigationConfig::new(WebRouteStrategy::Hash).base_path(base_path))
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
notes.home: "Your service note"
notes.empty: "No note has been saved in this session."
notes.has_draft: "An unsaved draft is waiting in the editor."
notes.edit: "Open note editor"
notes.storage_scope: "Saved and draft notes are kept only in memory here. Reloading clears both."
notes.editor: "Edit service note"
notes.note_label: "Note"
notes.unsaved: "You have unsaved changes."
notes.no_changes: "The draft matches the saved note."
notes.save_session: "Save in this session"
notes.back: "Back to notes, keeping draft"
notes.discard: "Discard changes…"
notes.discard_title: "Discard the draft changes?"
notes.discard_explanation: "The draft will be replaced by the last note saved in this session. Returning to notes does not require discarding it."
notes.keep_editing: "Keep editing"
notes.confirm_discard: "Discard draft changes"
notes.not_found: "This route does not exist. Your note and draft are unchanged."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
notes.home: "Tu nota de servicio"
notes.empty: "No hay ninguna nota guardada en esta sesión."
notes.has_draft: "Hay un borrador sin guardar en el editor."
notes.edit: "Abrir editor de notas"
notes.storage_scope: "Las notas y los borradores se conservan solo en memoria. Al recargar se borran ambos."
notes.editor: "Editar nota de servicio"
notes.note_label: "Nota"
notes.unsaved: "Tienes cambios sin guardar."
notes.no_changes: "El borrador coincide con la nota guardada."
notes.save_session: "Guardar en esta sesión"
notes.back: "Volver a las notas y conservar el borrador"
notes.discard: "Descartar cambios…"
notes.discard_title: "¿Descartar los cambios del borrador?"
notes.discard_explanation: "El borrador se sustituirá por la última nota guardada en esta sesión. Puedes volver a las notas sin descartarlo."
notes.keep_editing: "Seguir editando"
notes.confirm_discard: "Descartar cambios del borrador"
notes.not_found: "Esta ruta no existe. La nota y el borrador no cambian."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}
Open the editor, write a note, then return to notes without saving. Reopen the editor: the draft should still be there. Save it in this session and confirm the home route shows the same text.
Show the app preview
Hide the app preview

2. Confirm destructive intent, not ordinary navigation

Back to notes replaces the current route with home and preserves the draft. Host Back also leaves the draft alone because route changes never clear it. There is no invented universal navigation-guard API here, and no promise to intercept every operating-system gesture.
Discard is different: it opens the built-in Modal. Cancelling or dismissing that dialog changes no note data. Confirming replaces the draft with the saved snapshot. If the note has never been saved, that snapshot is empty; the dialog describes the consequence before applying it.
Saving here updates session state, not a database or server. A durable product would request its normal asynchronous save and update the saved snapshot only after success, keeping the draft and error visible on failure. See persistent iOS state for that separate boundary.
Web uses the supported hash routing mode. The embedded preview sets its deployment base to the current tutorial document, so changing routes stays inside that document rather than replacing it with a nonexistent site page. That preview-only mount configuration is not application routing logic.
Change the note, open Discard and choose Keep editing. The text must remain. Reopen the dialog and confirm: only the draft changes back to the saved snapshot. Try an unknown hash route; the not-found screen must preserve both values and offer a return.
Show the app preview
Hide the app preview

3. Check host history without confusing it with storage

fission doctor ios --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
Use simulator selection and iPhone installation for setup. Repeat the edit/return/save/discard sequence on the actual target and test host Back where the active shell exposes it. An iOS gesture is not qualified by a browser history test.
Inspect the modal's focus and dismissal with VoiceOver, then try long notes and both languages at phone width. A launch smoke test does not drive these decisions or verify unsaved-data handling.
Reloading deliberately clears the in-memory example. Route retention is not persistence across process termination. Never describe a draft as durable merely because it survived a screen change.