feat(card_db): Implement basic indexed-db based card storage

This commit is contained in:
Tristan Daniël Maat 2025-03-12 00:39:59 +08:00
parent aca5be2a9e
commit 7e9f0ff128
Signed by: tlater
GPG key ID: 49670FD774E43268
8 changed files with 312 additions and 6 deletions

1
src/components.rs Normal file
View file

@ -0,0 +1 @@
pub mod card;

15
src/components/card.rs Normal file
View file

@ -0,0 +1,15 @@
use leptos::prelude::*;
use crate::utils::card_database::CardDetails;
#[component]
pub fn Card(details: Option<CardDetails>) -> impl IntoView {
match details {
Some(details) => view! {
<p>{details.name}</p>
<span style="white-space: pre-line">{details.description}</span>
}
.into_any(),
None => view! { <p>"Placeholder"</p> }.into_any(),
}
}

View file

@ -1 +1,3 @@
pub mod components;
pub mod draft_list;
pub mod utils;

View file

@ -1,6 +1,32 @@
use draft_manager::{components::card::Card, utils::card_database::CardDatabase};
use leptos::prelude::*;
fn main() {
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(|| view! { <p>"Hello, world!"</p> })
leptos::mount::mount_to_body(|| view! { <App /> });
}
#[component]
fn App() -> impl IntoView {
let card = LocalResource::new(|| async move {
let database = CardDatabase::open().await?;
database.load_data().await?;
database.get_card(1861629).await
});
view! {
<Transition fallback=move || {
view! { <p>"Loading database..."</p> }
}>
{move || {
card.read()
.as_deref()
.and_then(|card| {
view! { <Card details=card.as_ref().unwrap().clone() /> }.into()
})
}}
</Transition>
}
}

1
src/utils.rs Normal file
View file

@ -0,0 +1 @@
pub mod card_database;

145
src/utils/card_database.rs Normal file
View file

@ -0,0 +1,145 @@
use std::{cell::RefCell, rc::Rc};
use idb::{
event::VersionChangeEvent, Database, DatabaseEvent, Factory, KeyPath, ObjectStoreParams, Query,
TransactionMode,
};
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen::Serializer;
use thiserror::Error;
#[derive(Clone, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrameType {
Normal,
Effect,
Ritual,
Fusion,
Synchro,
Xyz,
Link,
NormalPendulum,
EffectPendulum,
RitualPendulum,
FusionPendulum,
SynchroPendulum,
XyzPendulum,
Spell,
Trap,
Token,
}
#[derive(Clone, Deserialize)]
pub struct CardDetails {
pub password: u32,
pub name: String,
pub description: String,
pub frame: FrameType,
pub image: String,
}
pub struct CardDatabase(Database);
const DB_VERSION: u32 = 1;
impl CardDatabase {
pub async fn open() -> Result<Self> {
let factory = Factory::new()?;
let mut open_request = factory.open("cards", Some(DB_VERSION))?;
let err = Rc::new(RefCell::new(Ok(())));
let moved_err = err.clone(); // Will be moved inside closure
open_request.on_upgrade_needed(move |event| {
let res = Self::upgrade_database(event);
if let Err(e) = res {
*std::cell::RefCell::<_>::borrow_mut(&moved_err) = Err(e);
drop(moved_err);
}
});
let database = open_request.await?;
// Get the error if there is one - note that if the Rc has a
// strong count > 1 and therefore Symbols value as variable is void: into_inner returns Symbols value as variable is void: None,
// this means that the callback was not called, and as such
// there cannot have been an error.
let res = Rc::into_inner(err).unwrap_or(Ok(()).into()).into_inner();
res.map(|_| Self(database))
}
pub async fn get_card(&self, key: u32) -> Result<Option<CardDetails>> {
let transaction = self.0.transaction(&["cards"], TransactionMode::ReadOnly)?;
let store = transaction.object_store("cards")?;
let card = store.get(Query::Key(key.into()))?.await?;
Ok(card.map(serde_wasm_bindgen::from_value).transpose()?)
}
pub async fn load_data(&self) -> Result<()> {
let transaction = self.0.transaction(&["cards"], TransactionMode::ReadWrite)?;
let store = transaction.object_store("cards")?;
// Add some test data for now
let decode_talker = serde_json::json!({
"password": 1861629,
"name": "Decode Talker",
"description": "2+ Effect Monsters\r\nGains 500 ATK for each monster it points to. When your opponent activates a card or effect that targets a card(s) you control (Quick Effect): You can Tribute 1 monster this card points to; negate the activation, and if you do, destroy that card.",
"frame": "link",
"image": "https://images.ygoprodeck.com/images/cards/1861629.jpg"
});
store
.put(
&decode_talker.serialize(&Serializer::json_compatible())?,
None,
)?
.await?;
transaction.commit()?.await?;
Ok(())
}
/// Upgrade the database; this is called by the browser whenever
/// we try to open a newer database version.
fn upgrade_database(event: VersionChangeEvent) -> Result<()> {
let database = event.database()?;
let upgrade_from = event.old_version()?;
match upgrade_from {
// This version number signals that the database
// hasn't been created before.
0 => {
let mut store_params = ObjectStoreParams::new();
store_params.key_path(Some(KeyPath::new_single("password")));
let store = database.create_object_store("cards", store_params)?;
store.create_index(
"fulltext",
KeyPath::new_array(vec!["password", "name", "description"]),
None,
)?;
}
other => return Err(CardDatabaseError::UnknownDatabaseVersion(other)),
};
Ok(())
}
}
#[derive(Debug, Error)]
pub enum CardDatabaseError {
#[error(
"unknown card database version `{0}`, please close the tab and re-open the application"
)]
UnknownDatabaseVersion(u32),
#[error("card database operation failed; does the browser support IndexedDB?")]
BrowserError(#[from] idb::Error),
#[error("invalid test data")]
SerdeError(#[from] serde_wasm_bindgen::Error),
}
type Result<T> = std::result::Result<T, CardDatabaseError>;