cargo install cargo-fission
fission init harbour-reads
cd harbour-reads
cargo add serde --features derive
cargo add serde_yaml
fission add-target web --project-dir .
fission add-capability storage --project-dir .
src/
├── main.rs
├── lib.rs
├── app.rs
├── models.rs
├── state.rs
├── storage.rs
├── writes.rs # added in step two
├── translations.rs
└── widgets/
├── mod.rs
├── book_card.rs
└── add_book.rs
i18n/
platforms/web/sqlite/ # installed by the storage capability
preview/lib.rs # documentation startup, same real SQL path
fission run --target web --project-dir .
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/models.rs","value":"src-models-rs"},{"index":1,"label":"src/state.rs","value":"src-state-rs"},{"index":2,"label":"src/storage.rs","value":"src-storage-rs"},{"index":3,"label":"src/app.rs","value":"src-app-rs"},{"index":4,"label":"src/widgets/mod.rs","value":"src-widgets-mod-rs"},{"index":5,"label":"src/widgets/book_card.rs","value":"src-widgets-book-card-rs"},{"index":6,"label":"src/lib.rs","value":"src-lib-rs"},{"index":7,"label":"src/translations.rs","value":"src-translations-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"},{"index":10,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/models.rs","value":"src-models-rs"}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ReadingBook {
pub id: i64,
pub title: String,
pub author: String,
pub total_pages: u32,
pub pages_read: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReadingStatus { WantToRead, Reading, Finished }
impl ReadingStatus {
pub fn translation_key(self) -> &'static str {
match self {
Self::WantToRead => "reading.status.want_to_read",
Self::Reading => "reading.status.reading",
Self::Finished => "reading.status.finished",
}
}
}
pub fn reading_status(book: &ReadingBook) -> ReadingStatus {
if book.pages_read == 0 { ReadingStatus::WantToRead }
else if book.pages_read == book.total_pages { ReadingStatus::Finished }
else { ReadingStatus::Reading }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReadingFilter { All, Reading, WantToRead, Finished }
pub fn matches_book(book: &ReadingBook, query: &str, filter: ReadingFilter) -> bool {
let query = query.trim().to_lowercase();
let status = reading_status(book);
(query.is_empty() || book.title.to_lowercase().contains(&query) || book.author.to_lowercase().contains(&query))
&& match filter {
ReadingFilter::All => true,
ReadingFilter::Reading => status == ReadingStatus::Reading,
ReadingFilter::WantToRead => status == ReadingStatus::WantToRead,
ReadingFilter::Finished => status == ReadingStatus::Finished,
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BookDraft { pub title: String, pub author: String, pub pages: String }
#[derive(Clone, Debug, PartialEq)]
pub struct BookInput { pub title: String, pub author: String, pub total_pages: u32 }
impl BookDraft {
pub fn validate(&self) -> Result<BookInput, &'static str> {
let title = self.title.trim();
let author = self.author.trim();
if title.is_empty() || author.is_empty()
|| title.chars().count() > 160 || author.chars().count() > 160 {
return Err("reading.error.required_fields");
}
let total_pages = self.pages.trim().parse::<u32>().ok()
.filter(|pages| (1..=100_000).contains(pages)).ok_or("reading.error.invalid_pages")?;
Ok(BookInput { title: title.into(), author: author.into(), total_pages })
}
}
pub fn parse_page(source: &str, total_pages: u32) -> Result<u32, &'static str> {
source.trim().parse::<u32>().ok().filter(|page| *page <= total_pages)
.ok_or("reading.error.progress")
}
{"id":"fission-tabs-1","index":1,"label":"src/state.rs","value":"src-state-rs"}
use crate::models::{BookDraft, ReadingBook};
use fission::prelude::*;
#[derive(Clone, Debug, PartialEq)]
pub enum PendingWrite {
Add(BookDraft),
Progress,
Remove,
}
#[derive(Clone, Debug, PartialEq)]
pub enum DatabasePhase {
Loading,
Ready,
Executing(PendingWrite),
Refreshing(PendingWrite),
Failed,
}
#[derive(Clone, Debug, PartialEq)]
pub enum LibraryNotice { Info(&'static str), Error(&'static str) }
impl LibraryNotice {
pub fn key(&self) -> &'static str { match self { Self::Info(key) | Self::Error(key) => key } }
pub fn is_error(&self) -> bool { matches!(self, Self::Error(_)) }
}
#[derive(Clone, Debug, PartialEq)]
pub struct ReadingListState {
pub books: Vec<ReadingBook>,
pub title_draft: String,
pub author_draft: String,
pub page_count_draft: String,
pub phase: DatabasePhase,
pub notice: Option<LibraryNotice>,
}
impl Default for ReadingListState {
fn default() -> Self {
Self {
books: Vec::new(), title_draft: String::new(), author_draft: String::new(),
page_count_draft: String::new(), phase: DatabasePhase::Loading, notice: None,
}
}
}
impl GlobalState for ReadingListState {}
impl ReadingListState {
pub fn draft(&self) -> BookDraft {
BookDraft { title: self.title_draft.clone(), author: self.author_draft.clone(), pages: self.page_count_draft.clone() }
}
pub fn can_write(&self) -> bool { self.phase == DatabasePhase::Ready }
pub fn is_busy(&self) -> bool {
matches!(self.phase, DatabasePhase::Loading | DatabasePhase::Executing(_) | DatabasePhase::Refreshing(_))
}
pub fn reject(&mut self, key: &'static str) { self.notice = Some(LibraryNotice::Error(key)); }
pub fn fail(&mut self) {
self.phase = DatabasePhase::Failed;
self.reject("reading.error.database");
}
pub fn accept_loaded(&mut self, books: Vec<ReadingBook>) {
let previous = std::mem::replace(&mut self.phase, DatabasePhase::Ready);
let notice = match previous {
DatabasePhase::Refreshing(PendingWrite::Add(submitted)) => {
// A successful old write must not erase text entered while it ran.
if self.draft() == submitted {
self.title_draft.clear(); self.author_draft.clear(); self.page_count_draft.clear();
}
Some("reading.notice.book_added")
}
DatabasePhase::Refreshing(PendingWrite::Progress) => Some("reading.notice.progress_saved"),
DatabasePhase::Refreshing(PendingWrite::Remove) => Some("reading.notice.book_removed"),
_ => None,
};
self.books = books;
self.notice = notice.map(LibraryNotice::Info);
}
}
{"id":"fission-tabs-1","index":2,"label":"src/storage.rs","value":"src-storage-rs"}
use crate::models::{BookInput, ReadingBook};
use crate::state::{DatabasePhase, ReadingListState};
use fission::prelude::*;
pub fn insert_statement(book: &BookInput) -> SqlStatement {
SqlStatement::new("INSERT INTO reading_books (title, author, total_pages) VALUES (?1, ?2, ?3)")
.bind(book.title.clone()).bind(book.author.clone()).bind(i64::from(book.total_pages))
}
pub fn query_books(ctx: &mut ReducerContext<ReadingListState>) {
let ok = ctx.effects.bind(BooksLoaded, reduce_with!(books_loaded));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().query(SqlStatement::new(
"SELECT id, title, author, total_pages, pages_read FROM reading_books ORDER BY id DESC LIMIT 501"
)).on_ok(ok).on_err(err);
}
pub fn decode_books(rows: SqlRows) -> Result<Vec<ReadingBook>, &'static str> {
if rows.rows.len() > 500 { return Err("reading.error.library_limit"); }
rows.rows.into_iter().map(|row| {
let book = ReadingBook {
id: row.get("id").map_err(|_| "reading.error.records")?,
title: row.get("title").map_err(|_| "reading.error.records")?,
author: row.get("author").map_err(|_| "reading.error.records")?,
total_pages: u32::try_from(row.get::<i64>("total_pages").map_err(|_| "reading.error.records")?)
.map_err(|_| "reading.error.records")?,
pages_read: u32::try_from(row.get::<i64>("pages_read").map_err(|_| "reading.error.records")?)
.map_err(|_| "reading.error.records")?,
};
if book.id <= 0 || book.title.trim().is_empty() || book.author.trim().is_empty()
|| book.title.chars().count() > 160 || book.author.chars().count() > 160
|| !(1..=100_000).contains(&book.total_pages) || book.pages_read > book.total_pages {
return Err("reading.error.records");
}
Ok(book)
}).collect()
}
#[fission_reducer(PrepareLibrary)]
pub fn prepare_library(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
if matches!(state.phase, DatabasePhase::Executing(_) | DatabasePhase::Refreshing(_)) { return; }
state.phase = DatabasePhase::Loading;
state.notice = None;
let mut migrations = SqlMigrations::new();
migrations.add(SqlMigration::new(1, "reading library",
"CREATE TABLE reading_books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL CHECK (length(trim(title)) BETWEEN 1 AND 160),
author TEXT NOT NULL CHECK (length(trim(author)) BETWEEN 1 AND 160),
total_pages INTEGER NOT NULL CHECK (total_pages BETWEEN 1 AND 100000),
pages_read INTEGER NOT NULL DEFAULT 0 CHECK (pages_read BETWEEN 0 AND total_pages)
);"
)).expect("one migration with a unique version");
let ok = ctx.effects.bind(LibraryPrepared, reduce_with!(library_prepared));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().migrate(migrations)
.on_ok(ok).on_err(err);
}
#[fission_reducer(LibraryPrepared)]
pub fn library_prepared(_state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
query_books(ctx);
}
#[fission_reducer(BooksLoaded)]
pub fn books_loaded(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
if !matches!(state.phase, DatabasePhase::Loading | DatabasePhase::Refreshing(_)) { return; }
match ctx.input.sql_rows().ok_or("reading.error.records").and_then(decode_books) {
Ok(books) => state.accept_loaded(books),
Err(key) => {
state.phase = DatabasePhase::Failed;
state.reject(key);
}
}
}
#[fission_reducer(DatabaseFailed)]
pub fn database_failed(state: &mut ReadingListState, _ctx: &mut ReducerContext<ReadingListState>) {
state.fail();
}
{"id":"fission-tabs-1","index":3,"label":"src/app.rs","value":"src-app-rs"}
use crate::models::{matches_book, ReadingFilter, ReadingStatus, reading_status};
use crate::state::{DatabasePhase, ReadingListState};
use crate::widgets::book_card::ReadingBookCard;
use crate::storage::{prepare_library, PrepareLibrary};
use fission::prelude::*;
fission_component! {
pub ReadingListDashboard<ReadingListState> {
state { search: String = String::new(), filter: ReadingFilter = ReadingFilter::All }
}
view(dashboard, app, cx) {
let tokens = &cx.view.env().theme.tokens;
// Register before the shell dispatches its one startup action.
let prepare = with_reducer!(cx.build, PrepareLibrary, prepare_library);
let visible = app.books.iter().filter(|book| matches_book(book, &dashboard.search, dashboard.filter)).collect::<Vec<_>>();
let reading = app.books.iter().filter(|book| reading_status(book) == ReadingStatus::Reading).count();
let finished = app.books.iter().filter(|book| reading_status(book) == ReadingStatus::Finished).count();
} =>
Container(
Scroll(
semantic_label: Some(cx.tr("reading.title")),
child: Container(Column(gap: tokens.spacing.l, children: [
Text(cx.tr("reading.title")).size(tokens.typography.heading_size).weight(tokens.typography.font_weight_bold),
Text(cx.tr("reading.description")).color(tokens.colors.text_secondary),
Grid(columns: vec![GridTrack::auto_fit(GridTrack::minmax(GridTrack::Points(140.0), GridTrack::Fr(1.0)))],
rows: vec![GridTrack::Auto], column_gap: tokens.spacing.m, row_gap: tokens.spacing.m,
children: [
Stat(label: cx.tr("reading.metric.library"), value: app.books.len().to_string()),
Stat(label: cx.tr("reading.metric.current"), value: reading.to_string()),
Stat(label: cx.tr("reading.metric.finished"), value: finished.to_string()),
]),
Text(cx.tr("reading.library.read_only")),
if app.is_busy() {
Row(gap: tokens.spacing.s, children: [
Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("reading.loading"))),
Text(cx.tr("reading.loading")),
])
},
if let Some(notice) = &app.notice {
Alert(kind: if notice.is_error() { AlertKind::Error } else { AlertKind::Info },
title: cx.tr(notice.key()))
},
if app.phase == DatabasePhase::Failed {
Button(child: Text(cx.tr("reading.action.reload")), key: "reload-library",
on_press: prepare)
.semantics_identifier("reading.reload-library".to_owned())
},
TextInput(label: Some(cx.tr("reading.search.label").into()),
placeholder: Some(cx.tr("reading.search.hint").into()),
bind: dashboard.search, semantics_identifier: "reading.search".to_owned()),
Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
Button(child: Text(cx.tr("reading.filter.all")), key: "all",
variant: if dashboard.filter == ReadingFilter::All { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::All; }),
Button(child: Text(cx.tr("reading.filter.reading")), key: "reading",
variant: if dashboard.filter == ReadingFilter::Reading { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::Reading; }),
Button(child: Text(cx.tr("reading.filter.want_to_read")), key: "queued",
variant: if dashboard.filter == ReadingFilter::WantToRead { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::WantToRead; }),
Button(child: Text(cx.tr("reading.filter.finished")), key: "finished",
variant: if dashboard.filter == ReadingFilter::Finished { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::Finished; }),
]),
if app.phase == DatabasePhase::Ready && app.books.is_empty() {
EmptyState(title: cx.tr("reading.empty.library"))
} else if app.phase == DatabasePhase::Ready && visible.is_empty() {
Column(gap: tokens.spacing.s, children: [
EmptyState(title: cx.tr("reading.empty.search")),
Button(child: Text(cx.tr("reading.action.show_all")), key: "clear-search",
on_press: reduce { dashboard.search.clear(); dashboard.filter = ReadingFilter::All; }),
])
} else {
for book in visible {
ReadingBookCard(book.clone(), key: book.id)
}
},
])).width_length(Length::percent(100.0)).max_width(960.0)
.padding_all(tokens.spacing.l).bg(tokens.colors.background),
)
).height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1","index":4,"label":"src/widgets/mod.rs","value":"src-widgets-mod-rs"}
pub mod book_card;
{"id":"fission-tabs-1","index":5,"label":"src/widgets/book_card.rs","value":"src-widgets-book-card-rs"}
use crate::models::{reading_status, ReadingBook};
use crate::state::ReadingListState;
use fission::prelude::*;
fission_component! {
pub ReadingBookCard<ReadingListState> { props { book: ReadingBook } }
view(card, _app, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
Container(Column(gap: tokens.spacing.s, children: [
Text(card.book.title.clone()).weight(tokens.typography.font_weight_semibold),
Text(format!("{}: {}", cx.tr("reading.book.author"), card.book.author)),
Text(cx.tr(reading_status(&card.book).translation_key())),
Text(format!("{} / {} {}", card.book.pages_read, card.book.total_pages, cx.tr("reading.pages"))),
])).padding_all(tokens.spacing.m).bg(tokens.colors.surface)
.border(tokens.colors.border, 1.0).border_radius(tokens.radii.medium)
}
{"id":"fission-tabs-1","index":6,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod models;
mod state;
mod storage;
mod translations;
mod widgets;
use fission::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<state::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.run()
}
#[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::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.mount("#fission-web-mount").run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"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("valid reading-list translations");
env.i18n.add_bundle(TranslationBundle {
locale: Locale::from(locale),
messages,
});
}
env
}
{"id":"fission-tabs-1","index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
reading.title: "Harbour Reads"
reading.description: "Keep your next read, current progress and finished books in one place."
reading.book.one: "book"
reading.book.many: "books"
reading.book.author: "By"
reading.metric.library: "In your library"
reading.metric.current: "Currently reading"
reading.metric.queued: "On your list"
reading.metric.finished: "Finished"
reading.section.books: "Your books"
reading.progress: "Progress"
reading.pages: "pages"
reading.complete: "complete"
reading.status.want_to_read: "Want to read"
reading.status.reading: "Reading"
reading.status.finished: "Finished"
reading.action.remove_book: "Remove from list"
reading.notice.ready: "Your reading progress is up to date."
reading.notice.book_added: "Book added to your reading list."
reading.notice.progress_saved: "Reading progress saved."
reading.notice.book_removed: "Book removed from your reading list."
reading.error.invalid_pages: "Enter a whole page count from 1 to 100,000."
reading.error.required_fields: "Enter a title and author, each from 1 to 160 characters."
reading.error.book_missing: "That book is no longer in your library."
reading.error.database: "The operation could not be confirmed or the library could not be refreshed. A write may have reached SQLite. Reload and inspect the list before repeating it; your draft is still here."
reading.form.add: "Add a book"
reading.form.description: "Start at page zero, then record a session as you read."
reading.form.title: "Book title"
reading.form.title_hint: "The name on the cover"
reading.form.author: "Author"
reading.form.author_hint: "Author name"
reading.form.pages: "Total pages"
reading.form.pages_hint: "For example, 320"
reading.action.add: "Add to reading list"
reading.action.saving: "Saving book…"
reading.search.label: "Search your books"
reading.search.hint: "Title or author"
reading.filter.all: "All books"
reading.filter.reading: "Reading"
reading.filter.want_to_read: "Want to read"
reading.filter.finished: "Finished"
reading.count.shown: "books shown"
reading.loading: "Loading your reading list…"
reading.empty.library: "Your library is empty. Add a book above to start your list."
reading.empty.search: "No books match this search and status filter."
reading.action.show_all: "Show all books"
reading.library.read_only: "This first step reads the saved library. The next step adds the entry form and editing controls."
reading.page.label: "Page reached"
reading.page.action: "Save bookmark"
reading.error.progress: "Enter a whole page number from zero to this book's final page."
reading.error.records: "The saved library contains an unexpected record. No partial list was loaded."
reading.error.library_limit: "This workbench supports up to 500 books. No partial library was loaded."
reading.action.reload: "Reload library"
{"id":"fission-tabs-1","index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
reading.title: "Harbour Reads"
reading.description: "Ten en un solo lugar tu próxima lectura, el progreso actual y los libros terminados."
reading.book.one: "libro"
reading.book.many: "libros"
reading.book.author: "Autor"
reading.metric.library: "En tu biblioteca"
reading.metric.current: "Leyendo ahora"
reading.metric.queued: "En tu lista"
reading.metric.finished: "Terminados"
reading.section.books: "Tus libros"
reading.progress: "Progreso"
reading.pages: "páginas"
reading.complete: "completado"
reading.status.want_to_read: "Por leer"
reading.status.reading: "Leyendo"
reading.status.finished: "Terminado"
reading.action.remove_book: "Quitar de la lista"
reading.notice.ready: "Tu progreso de lectura está actualizado."
reading.notice.book_added: "Libro añadido a tu lista de lectura."
reading.notice.progress_saved: "Progreso de lectura guardado."
reading.notice.book_removed: "Libro quitado de tu lista de lectura."
reading.error.invalid_pages: "Introduce un número entero de páginas entre 1 y 100.000."
reading.error.required_fields: "Introduce título y autor, de 1 a 160 caracteres cada uno."
reading.error.book_missing: "Ese libro ya no está en tu biblioteca."
reading.error.database: "No se pudo confirmar la operación o actualizar la lista. Es posible que SQLite haya recibido la escritura. Recarga y revisa la lista antes de repetirla; el borrador sigue aquí."
reading.form.add: "Añadir un libro"
reading.form.description: "Empieza en la página cero y registra cada sesión de lectura."
reading.form.title: "Título del libro"
reading.form.title_hint: "El nombre de la portada"
reading.form.author: "Autor"
reading.form.author_hint: "Nombre del autor"
reading.form.pages: "Páginas totales"
reading.form.pages_hint: "Por ejemplo, 320"
reading.action.add: "Añadir a la lista"
reading.action.saving: "Guardando el libro…"
reading.search.label: "Buscar en tus libros"
reading.search.hint: "Título o autor"
reading.filter.all: "Todos los libros"
reading.filter.reading: "Leyendo"
reading.filter.want_to_read: "Por leer"
reading.filter.finished: "Terminados"
reading.count.shown: "libros mostrados"
reading.loading: "Cargando tu lista de lectura…"
reading.empty.library: "Tu biblioteca está vacía. Añade un libro para empezar la lista."
reading.empty.search: "Ningún libro coincide con la búsqueda y el filtro."
reading.action.show_all: "Mostrar todos los libros"
reading.library.read_only: "Este primer paso lee la biblioteca guardada. El siguiente añade el formulario y los controles."
reading.page.label: "Página alcanzada"
reading.page.action: "Guardar marcador"
reading.error.progress: "Introduce una página entera entre cero y la última página del libro."
reading.error.records: "La biblioteca contiene un registro inesperado. No se ha cargado una lista parcial."
reading.error.library_limit: "El límite es de 500 libros. No se ha cargado una biblioteca parcial."
reading.action.reload: "Volver a cargar la biblioteca"
{"id":"fission-tabs-1","index":10,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod models;
mod state;
mod storage;
mod translations;
mod widgets;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.mount("#fission-web-mount").run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/writes.rs","value":"src-writes-rs"},{"index":2,"label":"src/widgets/add_book.rs","value":"src-widgets-add-book-rs"},{"index":3,"label":"src/widgets/book_card.rs","value":"src-widgets-book-card-rs"},{"index":4,"label":"src/widgets/mod.rs","value":"src-widgets-mod-rs"},{"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/app.rs","value":"src-app-rs"}
use crate::models::{matches_book, ReadingFilter, ReadingStatus, reading_status};
use crate::state::{DatabasePhase, ReadingListState};
use crate::widgets::book_card::ReadingBookCard;
use crate::widgets::add_book::AddBookForm;
use crate::storage::{prepare_library, PrepareLibrary};
use fission::prelude::*;
fission_component! {
pub ReadingListDashboard<ReadingListState> {
state { search: String = String::new(), filter: ReadingFilter = ReadingFilter::All }
}
view(dashboard, app, cx) {
let tokens = &cx.view.env().theme.tokens;
// Register before the shell dispatches its one startup action.
let prepare = with_reducer!(cx.build, PrepareLibrary, prepare_library);
let visible = app.books.iter().filter(|book| matches_book(book, &dashboard.search, dashboard.filter)).collect::<Vec<_>>();
let reading = app.books.iter().filter(|book| reading_status(book) == ReadingStatus::Reading).count();
let finished = app.books.iter().filter(|book| reading_status(book) == ReadingStatus::Finished).count();
} =>
Container(
Scroll(
semantic_label: Some(cx.tr("reading.title")),
child: Container(Column(gap: tokens.spacing.l, children: [
Text(cx.tr("reading.title")).size(tokens.typography.heading_size).weight(tokens.typography.font_weight_bold),
Text(cx.tr("reading.description")).color(tokens.colors.text_secondary),
Grid(columns: vec![GridTrack::auto_fit(GridTrack::minmax(GridTrack::Points(140.0), GridTrack::Fr(1.0)))],
rows: vec![GridTrack::Auto], column_gap: tokens.spacing.m, row_gap: tokens.spacing.m,
children: [
Stat(label: cx.tr("reading.metric.library"), value: app.books.len().to_string()),
Stat(label: cx.tr("reading.metric.current"), value: reading.to_string()),
Stat(label: cx.tr("reading.metric.finished"), value: finished.to_string()),
]),
AddBookForm(),
if app.is_busy() {
Row(gap: tokens.spacing.s, children: [
Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("reading.loading"))),
Text(cx.tr("reading.loading")),
])
},
if let Some(notice) = &app.notice {
Alert(kind: if notice.is_error() { AlertKind::Error } else { AlertKind::Info },
title: cx.tr(notice.key()))
},
if app.phase == DatabasePhase::Failed {
Button(child: Text(cx.tr("reading.action.reload")), key: "reload-library",
on_press: prepare)
.semantics_identifier("reading.reload-library".to_owned())
},
TextInput(label: Some(cx.tr("reading.search.label").into()),
placeholder: Some(cx.tr("reading.search.hint").into()),
bind: dashboard.search, semantics_identifier: "reading.search".to_owned()),
Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
Button(child: Text(cx.tr("reading.filter.all")), key: "all",
variant: if dashboard.filter == ReadingFilter::All { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::All; }),
Button(child: Text(cx.tr("reading.filter.reading")), key: "reading",
variant: if dashboard.filter == ReadingFilter::Reading { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::Reading; }),
Button(child: Text(cx.tr("reading.filter.want_to_read")), key: "queued",
variant: if dashboard.filter == ReadingFilter::WantToRead { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::WantToRead; }),
Button(child: Text(cx.tr("reading.filter.finished")), key: "finished",
variant: if dashboard.filter == ReadingFilter::Finished { ButtonVariant::Primary } else { ButtonVariant::Outline },
on_press: reduce { dashboard.filter = ReadingFilter::Finished; }),
]),
if app.phase == DatabasePhase::Ready && app.books.is_empty() {
EmptyState(title: cx.tr("reading.empty.library"))
} else if app.phase == DatabasePhase::Ready && visible.is_empty() {
Column(gap: tokens.spacing.s, children: [
EmptyState(title: cx.tr("reading.empty.search")),
Button(child: Text(cx.tr("reading.action.show_all")), key: "clear-search",
on_press: reduce { dashboard.search.clear(); dashboard.filter = ReadingFilter::All; }),
])
} else {
for book in visible {
ReadingBookCard(book.clone(), key: book.id)
}
},
])).width_length(Length::percent(100.0)).max_width(960.0)
.padding_all(tokens.spacing.l).bg(tokens.colors.background),
)
).height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1","index":1,"label":"src/writes.rs","value":"src-writes-rs"}
use crate::models::parse_page;
use crate::state::{DatabasePhase, PendingWrite, ReadingListState};
use crate::storage::{insert_statement, query_books, DatabaseFailed, database_failed};
use fission::prelude::*;
pub fn add_book(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
if !state.can_write() { return; }
if state.books.len() >= 500 { state.reject("reading.error.library_limit"); return; }
let submitted = state.draft();
let input = match submitted.validate() { Ok(input) => input, Err(key) => { state.reject(key); return; } };
state.phase = DatabasePhase::Executing(PendingWrite::Add(submitted));
state.notice = None;
let ok = ctx.effects.bind(WriteCompleted, reduce_with!(write_completed));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().execute(insert_statement(&input))
.on_ok(ok).on_err(err);
}
pub fn set_page(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>, id: i64, source: &str) {
if !state.can_write() { return; }
let Some(book) = state.books.iter().find(|book| book.id == id) else {
state.reject("reading.error.book_missing"); return;
};
let page = match parse_page(source, book.total_pages) { Ok(page) => page, Err(key) => { state.reject(key); return; } };
state.phase = DatabasePhase::Executing(PendingWrite::Progress);
state.notice = None;
let ok = ctx.effects.bind(WriteCompleted, reduce_with!(write_completed));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().execute(SqlStatement::new(
"UPDATE reading_books SET pages_read = ?1 WHERE id = ?2 AND total_pages >= ?1"
).bind(i64::from(page)).bind(id))
.on_ok(ok).on_err(err);
}
pub fn remove_book(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>, id: i64) {
if !state.can_write() { return; }
if !state.books.iter().any(|book| book.id == id) { state.reject("reading.error.book_missing"); return; }
state.phase = DatabasePhase::Executing(PendingWrite::Remove);
state.notice = None;
let ok = ctx.effects.bind(WriteCompleted, reduce_with!(write_completed));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().execute(SqlStatement::new("DELETE FROM reading_books WHERE id = ?1").bind(id))
.on_ok(ok).on_err(err);
}
#[fission_reducer(WriteCompleted)]
pub fn write_completed(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
let DatabasePhase::Executing(write) = state.phase.clone() else { return; };
if !ctx.input.sql_execute_result().is_some_and(|result| result.affected_rows == 1) {
// A transport error or missing row is not permission to repeat an insert.
state.fail();
return;
}
state.phase = DatabasePhase::Refreshing(write);
query_books(ctx);
}
{"id":"fission-tabs-1","index":2,"label":"src/widgets/add_book.rs","value":"src-widgets-add-book-rs"}
use crate::state::ReadingListState;
use fission::prelude::*;
fission_component! {
pub AddBookForm<ReadingListState> {}
view(_form, app, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
Container(Column(gap: tokens.spacing.s, children: [
Text(cx.tr("reading.form.add")).weight(tokens.typography.font_weight_semibold),
Text(cx.tr("reading.form.description")).color(tokens.colors.text_secondary),
FormControl(label: Some(cx.tr("reading.form.title")), required: true, child:
TextInput(max_length: Some(160), bind: app.title_draft,
semantics_identifier: "reading.new.title".to_owned())),
FormControl(label: Some(cx.tr("reading.form.author")), required: true, child:
TextInput(max_length: Some(160), bind: app.author_draft,
semantics_identifier: "reading.new.author".to_owned())),
FormControl(label: Some(cx.tr("reading.form.pages")), required: true, child:
TextInput(max_length: Some(6), keyboard_type: TextInputType::Number,
bind: app.page_count_draft, semantics_identifier: "reading.new.pages".to_owned())),
Button(child: Text(cx.tr("reading.action.add")), key: "add-book",
disabled: !app.can_write(),
on_press: reduce { crate::writes::add_book(app, cx); })
.semantics_identifier("reading.add-book".to_owned()),
])).padding_all(tokens.spacing.m).bg(tokens.colors.surface)
.border(tokens.colors.border, 1.0).border_radius(tokens.radii.medium)
}
{"id":"fission-tabs-1","index":3,"label":"src/widgets/book_card.rs","value":"src-widgets-book-card-rs"}
use crate::models::{reading_status, ReadingBook};
use crate::state::ReadingListState;
use fission::prelude::*;
fission_component! {
pub ReadingBookCard<ReadingListState> {
props { book: ReadingBook }
state { page: String = String::new() }
}
view(card, app, cx) {
let tokens = &cx.view.env().theme.tokens;
let percentage = u64::from(card.book.pages_read) * 100 / u64::from(card.book.total_pages);
} =>
Container(Column(gap: tokens.spacing.s, children: [
Text(card.book.title.clone()).weight(tokens.typography.font_weight_semibold),
Text(format!("{}: {}", cx.tr("reading.book.author"), card.book.author)).color(tokens.colors.text_secondary),
Text(cx.tr(reading_status(&card.book).translation_key())),
Text(format!("{}: {}/{} {} · {}%", cx.tr("reading.progress"), card.book.pages_read,
card.book.total_pages, cx.tr("reading.pages"), percentage)),
ProgressBar(value: card.book.pages_read as f32 / card.book.total_pages as f32,
label: format!("{} / {} {}", card.book.pages_read, card.book.total_pages, cx.tr("reading.pages"))),
TextInput(label: Some(cx.tr("reading.page.label").into()), max_length: Some(6),
keyboard_type: TextInputType::Number, bind: card.page,
semantics_identifier: format!("reading.page.{}", card.book.id)),
Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
Button(child: Text(cx.tr("reading.page.action")), key: "set-page", disabled: !app.can_write(),
on_press: reduce { crate::writes::set_page(app, cx, card.book.id, &card.page); })
.semantics_identifier(format!("reading.set-page.{}", card.book.id)),
Button(child: Text(cx.tr("reading.action.remove_book")), key: "remove-book",
variant: ButtonVariant::Outline, disabled: !app.can_write(),
on_press: reduce { crate::writes::remove_book(app, cx, card.book.id); })
.semantics_identifier(format!("reading.remove.{}", card.book.id)),
]),
])).padding_all(tokens.spacing.m).bg(tokens.colors.surface)
.border(tokens.colors.border, 1.0).border_radius(tokens.radii.medium)
}
{"id":"fission-tabs-1","index":4,"label":"src/widgets/mod.rs","value":"src-widgets-mod-rs"}
pub mod book_card;
pub mod add_book;
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod models;
mod state;
mod storage;
mod translations;
mod widgets;
mod writes;
use fission::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<state::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.run()
}
#[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::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.mount("#fission-web-mount").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 models;
mod state;
mod storage;
mod translations;
mod widgets;
mod writes;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::ReadingListState, _>::new(app::ReadingListDashboard::new())
.with_env(translations::create_env()).with_title("Harbour Reads")
.with_startup_action(storage::PrepareLibrary)
.mount("#fission-web-mount").run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/storage.rs","value":"src-storage-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/storage.rs","value":"src-storage-rs"}
use crate::models::{BookInput, ReadingBook};
use crate::state::{DatabasePhase, ReadingListState};
use fission::prelude::*;
pub fn insert_statement(book: &BookInput) -> SqlStatement {
SqlStatement::new("INSERT INTO reading_books (title, author, total_pages) VALUES (?1, ?2, ?3)")
.bind(book.title.clone()).bind(book.author.clone()).bind(i64::from(book.total_pages))
}
pub fn query_books(ctx: &mut ReducerContext<ReadingListState>) {
let ok = ctx.effects.bind(BooksLoaded, reduce_with!(books_loaded));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().query(SqlStatement::new(
"SELECT id, title, author, total_pages, pages_read FROM reading_books ORDER BY id DESC LIMIT 501"
)).on_ok(ok).on_err(err);
}
pub fn decode_books(rows: SqlRows) -> Result<Vec<ReadingBook>, &'static str> {
if rows.rows.len() > 500 { return Err("reading.error.library_limit"); }
rows.rows.into_iter().map(|row| {
let book = ReadingBook {
id: row.get("id").map_err(|_| "reading.error.records")?,
title: row.get("title").map_err(|_| "reading.error.records")?,
author: row.get("author").map_err(|_| "reading.error.records")?,
total_pages: u32::try_from(row.get::<i64>("total_pages").map_err(|_| "reading.error.records")?)
.map_err(|_| "reading.error.records")?,
pages_read: u32::try_from(row.get::<i64>("pages_read").map_err(|_| "reading.error.records")?)
.map_err(|_| "reading.error.records")?,
};
if book.id <= 0 || book.title.trim().is_empty() || book.author.trim().is_empty()
|| book.title.chars().count() > 160 || book.author.chars().count() > 160
|| !(1..=100_000).contains(&book.total_pages) || book.pages_read > book.total_pages {
return Err("reading.error.records");
}
Ok(book)
}).collect()
}
#[fission_reducer(PrepareLibrary)]
pub fn prepare_library(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
if matches!(state.phase, DatabasePhase::Executing(_) | DatabasePhase::Refreshing(_)) { return; }
state.phase = DatabasePhase::Loading;
state.notice = None;
let mut migrations = SqlMigrations::new();
migrations.add(SqlMigration::new(1, "reading library",
"CREATE TABLE reading_books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL CHECK (length(trim(title)) BETWEEN 1 AND 160),
author TEXT NOT NULL CHECK (length(trim(author)) BETWEEN 1 AND 160),
total_pages INTEGER NOT NULL CHECK (total_pages BETWEEN 1 AND 100000),
pages_read INTEGER NOT NULL DEFAULT 0 CHECK (pages_read BETWEEN 0 AND total_pages)
);"
)).expect("one migration with a unique version");
let ok = ctx.effects.bind(LibraryPrepared, reduce_with!(library_prepared));
let err = ctx.effects.bind(DatabaseFailed, reduce_with!(database_failed));
ctx.effects.sql().migrate(migrations)
.on_ok(ok).on_err(err);
}
#[fission_reducer(LibraryPrepared)]
pub fn library_prepared(_state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
query_books(ctx);
}
#[fission_reducer(BooksLoaded)]
pub fn books_loaded(state: &mut ReadingListState, ctx: &mut ReducerContext<ReadingListState>) {
if !matches!(state.phase, DatabasePhase::Loading | DatabasePhase::Refreshing(_)) { return; }
match ctx.input.sql_rows().ok_or("reading.error.records").and_then(decode_books) {
Ok(books) => state.accept_loaded(books),
Err(key) => {
state.phase = DatabasePhase::Failed;
state.reject(key);
}
}
}
#[fission_reducer(DatabaseFailed)]
pub fn database_failed(state: &mut ReadingListState, _ctx: &mut ReducerContext<ReadingListState>) {
state.fail();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{BookDraft, parse_page};
fn draft() -> BookDraft { BookDraft { title: "The Dispossessed".into(), author: "Ursula K. Le Guin".into(), pages: "387".into() } }
#[test]
fn names_and_page_counts_are_validated_before_a_request() {
assert!(BookDraft::default().validate().is_err());
for invalid in ["0", "-1", "1.5", "100001", ""] {
assert!(BookDraft { pages: invalid.into(), ..draft() }.validate().is_err());
}
assert_eq!(draft().validate().unwrap().total_pages, 387);
assert_eq!(parse_page("0", 387), Ok(0));
assert_eq!(parse_page("387", 387), Ok(387));
assert!(parse_page("388", 387).is_err());
}
#[test]
fn punctuation_stays_in_bound_parameters_not_sql() {
use fission::sql::{SqlParameters, SqlValue};
let input = BookDraft { title: "Someone's book'); DROP TABLE reading_books; --".into(), ..draft() }.validate().unwrap();
let statement = insert_statement(&input);
assert!(!statement.sql.contains(&input.title));
assert!(matches!(statement.parameters, SqlParameters::Positional(values)
if values == vec![SqlValue::Text(input.title), SqlValue::Text(input.author), SqlValue::Integer(387)]));
}
#[test]
fn malformed_rows_reject_the_whole_read_instead_of_disappearing() {
let columns = ["id", "title", "author", "total_pages", "pages_read"].map(|name| SqlColumn { name: name.into(), declared_type: None }).to_vec();
let row = |pages| SqlRow::new(columns.clone(), vec![1_i64.into(), "Book".into(), "Author".into(), 100_i64.into(), SqlValue::Integer(pages)]);
assert_eq!(decode_books(SqlRows { columns: columns.clone(), rows: vec![row(20)] }).unwrap()[0].pages_read, 20);
assert!(decode_books(SqlRows { columns: columns.clone(), rows: vec![row(20), row(101)] }).is_err());
}
#[test]
fn successful_old_write_does_not_clear_newer_draft_text() {
use crate::state::{PendingWrite, DatabasePhase};
let submitted = draft();
let mut state = ReadingListState::default();
state.title_draft = submitted.title.clone(); state.author_draft = submitted.author.clone();
state.page_count_draft = submitted.pages.clone();
state.phase = DatabasePhase::Refreshing(PendingWrite::Add(submitted));
state.title_draft = "A different book".into();
state.accept_loaded(Vec::new());
assert_eq!(state.title_draft, "A different book");
assert!(state.can_write());
}
#[test]
fn confirmed_unchanged_draft_is_cleared_but_failed_write_is_not() {
use crate::state::{PendingWrite, DatabasePhase};
let submitted = draft();
let mut state = ReadingListState::default();
state.title_draft = submitted.title.clone(); state.author_draft = submitted.author.clone();
state.page_count_draft = submitted.pages.clone();
state.phase = DatabasePhase::Executing(PendingWrite::Add(submitted.clone()));
state.fail();
assert_eq!(state.draft(), submitted);
assert!(!state.can_write());
state.phase = DatabasePhase::Refreshing(PendingWrite::Add(submitted));
state.accept_loaded(Vec::new());
assert_eq!(state.draft(), BookDraft::default());
}
}
{"id":"fission-tabs-1"}
cargo test --lib
fission doctor --project-dir .
fission run --target web --project-dir .
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp