Skip to content

Commit

Permalink
use ledgerprovider for cards
Browse files Browse the repository at this point in the history
  • Loading branch information
TBS1996 committed Feb 23, 2025
1 parent f81fd4b commit 5654a45
Show file tree
Hide file tree
Showing 17 changed files with 669 additions and 116 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions omtrent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ license = "GPL-2.0-only"


[dependencies]
serde.workspace = true
4 changes: 3 additions & 1 deletion omtrent/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::{
fmt::{Display, Formatter},
};

use serde::{Deserialize, Serialize};

pub enum Precision {
Millenium,
Century,
Expand All @@ -14,7 +16,7 @@ pub enum Precision {
Minute,
}

#[derive(Default, PartialOrd, Eq, Hash, PartialEq, Debug, Clone)]
#[derive(Default, PartialOrd, Eq, Hash, PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct TimeStamp {
millenium: u32,
century: Option<u32>,
Expand Down
10 changes: 10 additions & 0 deletions speki-core/src/cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use std::collections::{BTreeMap, BTreeSet};

use crate::card::CardId;


pub struct Cache {
dependents: BTreeMap<CardId, BTreeSet<CardId>>,
}


104 changes: 94 additions & 10 deletions speki-core/src/card/basecard.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use omtrent::TimeStamp;
use speki_dto::{LedgerProvider, Record, RunLedger, SpekiProvider};

use super::*;
use crate::{attribute::AttributeId, audio::AudioId, card_provider::CardProvider, index::Bigram, App, Attribute};
use crate::{attribute::AttributeId, audio::AudioId, card_provider::CardProvider, index::Bigram, ledger::CardEvent, App, Attribute};

pub type CardId = Uuid;

/// Represents the card without userdata, the part that can be freely shared among different users.
#[derive(Clone, Serialize, Deserialize, Debug, Hash)]
#[derive(Clone, Serialize, Deserialize, Debug, Hash, PartialEq)]
#[serde(from = "RawCard", into = "RawCard")]
pub struct BaseCard {
pub id: CardId,
Expand Down Expand Up @@ -187,21 +188,21 @@ impl CardTrait for ClassCard {
}

/// An unfinished card
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct UnfinishedCard {
pub front: String,
}

/// Just a normal flashcard
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct NormalCard {
pub front: String,
pub back: BackSide,
}

/// A class, which is something that has specific instances of it, but is not a single thing in itself.
/// A class might also have sub-classes, for example, the class chemical element has a sub-class isotope
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct ClassCard {
pub name: String,
pub back: BackSide,
Expand All @@ -210,7 +211,7 @@ pub struct ClassCard {

/// An attribute describes a specific instance of a class. For example the class Person can have attribute "when was {} born?"
/// this will be applied to all instances of the class and its subclasses
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct AttributeCard {
pub attribute: AttributeId,
pub back: BackSide,
Expand Down Expand Up @@ -240,7 +241,7 @@ impl AttributeCard {
/// A specific instance of a class
/// For example, the instance might be Elvis Presley where the concept would be "Person"
/// the right answer is to know which class the instance belongs to
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct InstanceCard {
pub name: String,
pub back: Option<BackSide>,
Expand All @@ -262,7 +263,7 @@ pub struct InstanceCard {
/// 1. It represents a property of an instance or sub-class.
/// 2. The set of the class it belongs to is large
/// 3. The property in that set is rare, but not unique
#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct StatementCard {
pub front: String,
}
Expand All @@ -274,7 +275,7 @@ impl CardTrait for StatementCard {
}
}

#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct EventCard {
pub front: String,
pub start_time: TimeStamp,
Expand Down Expand Up @@ -338,7 +339,7 @@ pub trait CardTrait: Debug + Clone {
async fn get_dependencies(&self) -> BTreeSet<CardId>;
}

#[derive(PartialEq, Debug, Clone, Hash)]
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
pub enum CardType {
Instance(InstanceCard),
Normal(NormalCard),
Expand Down Expand Up @@ -575,6 +576,86 @@ pub fn normalize_string(str: &str) -> String {
deunicode::deunicode(str).to_lowercase()
}

impl RunLedger<CardEvent> for BaseCard {
fn run_event(selv: Option<Self>, event: CardEvent) -> (Self, Vec<CardEvent>) {
let id = event.id;

match event.action {
CardAction::SetFrontAudio { audio } => {
let mut base = selv.unwrap();
base.front_audio = audio;
(base, vec![])
},
CardAction::SetBackAudio { audio } => {
let mut base = selv.unwrap();
base.back_audio = audio;
(base, vec![])
},
CardAction::UpsertCard { ty } => {
(BaseCard::new_with_id(id, ty), vec![])
},
CardAction::DeleteCard => {
/*
let mut events = vec![];
let mut base = selv.unwrap();
base.set_delete();
for dependent in &base.dependents {
let action = CardAction::RemoveDependency { dependency: id };
let event = CardEvent {
action,
id: *dependent,
};
events.push(event);
}
*/

let mut events = vec![];
let mut base = selv.unwrap();

(base, events)

},
CardAction::AddDependent { dependent } => {
let mut base = selv.unwrap();
//base.dependents.insert(dependent);
(base, vec![])
},
CardAction::RemoveDependent { dependent } => {
let mut base = selv.unwrap();
//base.dependents.remove(&dependent);
(base, vec![])
},
CardAction::AddDependency { dependency } => {
let mut base = selv.unwrap();
base.dependencies.insert(dependency);
let event = CardEvent {
action: CardAction::AddDependent { dependent: id },
id: dependency,
};
(base, vec![event])
},
CardAction::RemoveDependency { dependency } => {
let mut base = selv.unwrap();
base.dependencies.remove(&dependency);
base.ty.remove_dep(dependency);
let event = CardEvent {
action: CardAction::RemoveDependent { dependent: id },
id: dependency,
};
(base, vec![event])
},
CardAction::SetBackRef { reff } => {
let backside = BackSide::Card(reff);
let mut base = selv.unwrap();
base.ty = base.ty.set_backside(backside);
(base, vec![])
},
}
}
}

impl Item for BaseCard {
type PreviousVersion = Self;
type Key = CardId;
Expand Down Expand Up @@ -889,3 +970,6 @@ fn from_any(ty: CardType) -> RawType {

raw
}


use serde::{de::DeserializeOwned, Deserialize, Serialize};
41 changes: 18 additions & 23 deletions speki-core/src/card/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ use tracing::info;
use uuid::Uuid;

use crate::{
audio::{Audio, AudioId},
card_provider::CardProvider,
metadata::{IsSuspended, Metadata},
recall_rate::{History, Recall, Review, SimpleRecall},
RecallCalc, Recaller, TimeGetter,
audio::{Audio, AudioId}, card_provider::CardProvider, ledger::{CardAction, CardEvent, HistoryEvent, MetaEvent}, metadata::{IsSuspended, Metadata}, recall_rate::{History, Recall, Review, SimpleRecall}, RecallCalc, Recaller, TimeGetter
};

pub type RecallRate = f32;
Expand Down Expand Up @@ -122,7 +118,6 @@ impl Card {
self.card_provider.dependents(self.id).await {
let card = self.card_provider.load(card).await.unwrap();
cards.insert(card);

}
cards
}
Expand All @@ -140,8 +135,9 @@ impl Card {
time_spent: Default::default(),
};

self.history.push(review);
self.card_provider.providers.reviews.save_item(self.history.clone()).await;
self.history.push(review.clone());
let event = HistoryEvent::Review { id: self.id, review };
self.card_provider.providers.run_event(event).await;
self.refresh().await;
}

Expand Down Expand Up @@ -234,7 +230,9 @@ impl Card {
pub async fn set_ref(mut self, reff: CardId) -> Card {
let backside = BackSide::Card(reff);
self.base.ty = self.base.ty.set_backside(backside);
self.card_provider.save_basecard(self.base.clone()).await;
let action = CardAction::SetBackRef { reff };
let event = CardEvent::new(self.id, action);
self.card_provider.providers.run_event(event).await;
self.refresh().await;
self
}
Expand All @@ -254,24 +252,17 @@ impl Card {

info!("dep was there: {res}");
self.base.ty.remove_dep(dependency);
self.card_provider.save_basecard(self.base.clone()).await;
let action = CardAction::RemoveDependency {dependency };
let event = CardEvent::new(self.id, action);
self.card_provider.providers.run_event(event).await;
self.refresh().await;
}

pub async fn add_dependency(&mut self, dependency: CardId) {
info!("for card: {} inserting dependency: {}", self.id, dependency);
if self.id() == dependency {
info!("not adding dep cause theyre the same lol");
return;
}

if self.recursive_dependents().await.contains(&dependency) {
tracing::warn!("failed to insert dependency due to cycle!");
return;
}

self.base.dependencies.insert(dependency);
self.card_provider.save_basecard(self.base.clone()).await;
let action = CardAction::AddDependency { dependency };
let event = CardEvent::new(self.id, action);
self.card_provider.providers.run_event(event).await;
self.refresh().await;
}

Expand All @@ -285,7 +276,9 @@ impl Card {

pub async fn into_type(mut self, data: impl Into<CardType>) -> Self {
self.base.ty = data.into();
self.card_provider.save_basecard(self.base.clone()).await;
let action = CardAction::UpsertCard { ty: self.base.ty.clone() };
let event = CardEvent::new(self.id, action);
self.card_provider.providers.run_event(event).await;
self.refresh().await;
self
}
Expand Down Expand Up @@ -419,6 +412,8 @@ impl Card {
}

pub async fn set_suspend(&mut self, suspend: bool) {
let event = MetaEvent::SetSuspend { id: self.id, status: suspend };
self.card_provider.providers.run_event(event).await;
self.metadata.write().await.suspended = IsSuspended::from(suspend);
self.card_provider.invalidate_card(self.id);
self.refresh().await;
Expand Down
25 changes: 4 additions & 21 deletions speki-core/src/card_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{
use dioxus_logger::tracing::{info, trace};

use crate::{
card::{BaseCard, CardId}, metadata::Metadata, recall_rate::History, Card, Provider, Recaller, TimeGetter
card::{BaseCard, CardId}, ledger::{CardAction, CardEvent}, metadata::Metadata, recall_rate::History, Card, Provider, Recaller, TimeGetter
};

#[derive(Clone)]
Expand All @@ -29,18 +29,12 @@ impl Debug for CardProvider {

impl CardProvider {
pub async fn remove_card(&self, card_id: CardId) {
let card = self.providers.cards.load_item(card_id).await.unwrap();
for card in self.load_all().await {
info!("removing dependency for {}", card.id());
let mut card = Arc::unwrap_or_clone(card);
card.rm_dependency(card_id).await;
}

self.providers.cards.delete_item(card).await;
info!("done removing i guess");
let event = CardEvent::new(card_id, CardAction::DeleteCard);
self.providers.run_event(event).await;
}

pub async fn load_all_card_ids(&self) -> Vec<CardId> {
info!("x1");
self.providers.cards.load_ids().await
}

Expand Down Expand Up @@ -71,7 +65,6 @@ impl CardProvider {

self.providers.indices.refresh(self, cards.values()).await;
}

}

pub async fn filtered_load<F, Fut>(&self, filter: F) -> Vec<Arc<Card>>
Expand Down Expand Up @@ -161,16 +154,6 @@ impl CardProvider {
self.cards.write().unwrap().remove(&id)
}

pub async fn save_basecard(&self, new_card: BaseCard) -> Arc<Card> {
let id = new_card.id;
let old_card = self.providers.cards.load_item(id).await;
self.providers.dependents.update(old_card.as_ref(), &new_card).await;
self.providers.indices.update(self, old_card.as_ref(), &new_card).await;
self.providers.cards.save_item(new_card).await;
self.invalidate_card(id);
self.load(id).await.unwrap()
}

pub fn time_provider(&self) -> TimeGetter {
self.time_provider.clone()
}
Expand Down
5 changes: 2 additions & 3 deletions speki-core/src/collection.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::{
cmp::Ordering, collections::{BTreeSet, HashSet}, fmt::Display, ops::{Deref, DerefMut}, sync::{Arc, RwLockReadGuard, RwLockWriteGuard}, time::Duration
cmp::Ordering, collections::{BTreeSet, HashSet}, fmt::Display, sync::Arc, time::Duration
};

use async_recursion::async_recursion;
use serde::{Deserialize, Serialize};
use speki_dto::{Item, ModifiedSource, SpekiProvider};
use speki_dto::{Item, ModifiedSource};
use tracing::{error, info, warn};
use uuid::Uuid;
use std::sync::RwLock;

use crate::{card::CardId, card_provider::CardProvider, Card};

Expand Down
Loading

0 comments on commit 5654a45

Please sign in to comment.