Files
jap_learn/src/repetitions.rs
T

511 lines
18 KiB
Rust
Raw Normal View History

2026-08-18 12:14:35 +03:00
use std::ops::Deref;
2026-04-13 22:25:58 +03:00
use crate::data_provider::card_sets::{delete_set, update_card_set};
2026-08-15 21:32:24 +03:00
use crate::data_provider::card_stats::{add_stat_list, load_stats_of_set};
2026-08-01 17:16:58 +03:00
use crate::history::HistoryState;
2026-08-18 12:14:35 +03:00
use crate::lang::{AppendMode, DeckSettings, CardStatistics, OrderMode};
2026-08-04 16:53:09 +03:00
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
2026-08-01 17:16:58 +03:00
use crate::navigation::{NavigatedPage, Page};
2026-04-13 22:25:58 +03:00
use crate::repetition::RepetitionState;
2026-08-06 11:31:11 +03:00
use crate::repetition_settings::RepetitionSettingsState;
use crate::repetitions::RepetitionsMessage::*;
2026-08-01 17:16:58 +03:00
use crate::styling::*;
2026-08-01 13:04:18 +03:00
use crate::{AppState, RootMessage};
2026-08-15 21:32:24 +03:00
use chrono::{Days, Local, Utc};
use hashbrown::{HashMap, HashSet};
2026-04-13 22:25:58 +03:00
pub use iced::widget::button::{Catalog, Style};
2026-08-18 12:14:35 +03:00
use iced::widget::button::{Status, danger};
2026-08-06 19:12:23 +03:00
use iced::widget::tooltip::Position::Top;
2026-08-15 21:32:24 +03:00
use iced::widget::{
2026-08-18 12:14:35 +03:00
Column, Row, button, column, container, lazy, radio, row, scrollable, space, svg, text,
text_input, tooltip,
2026-08-15 21:32:24 +03:00
};
2026-08-01 19:36:43 +03:00
use iced::{Background, Border, Center, Color, Element, Fill, Length, Shadow, Task, Theme};
2026-08-18 12:14:35 +03:00
use iced_core::Padding;
2026-08-06 19:12:23 +03:00
use iced_core::border::Radius;
2026-08-04 16:53:09 +03:00
use iced_core::svg::Handle;
2026-04-09 22:45:31 +03:00
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct RepetitionsState {
correct_filters: Vec<bool>,
2026-08-15 21:32:24 +03:00
current_sets_cards_cache: HashMap<usize, (Vec<usize>, Vec<usize>)>,
2026-08-16 14:23:00 +03:00
word_id_index_map: HashMap<u32, usize>,
2026-08-18 12:14:35 +03:00
local_settings: HashMap<u32, DeckLocalSetting>,
view_data: Option<SetViewData>,
2026-08-18 12:47:06 +03:00
state: Arc<Mutex<AppState>>,
2026-04-09 22:45:31 +03:00
}
impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
2026-08-18 12:14:35 +03:00
fn navigate(&mut self, message: &RepetitionsMessage) -> Option<Page> {
2026-08-04 16:53:09 +03:00
if let Back = message {
2026-04-09 22:45:31 +03:00
Some(PreviousPage)
2026-08-04 16:53:09 +03:00
} else if let GoToHistory = message {
2026-07-29 12:57:46 +03:00
let card_set;
{
2026-08-18 12:14:35 +03:00
card_set = self.state.lock().unwrap().card_sets[self.selected_set_index.unwrap()].id;
2026-07-29 12:57:46 +03:00
}
Some(History(HistoryState::new(card_set, self.state.clone())))
2026-08-04 16:53:09 +03:00
} else if let GoToRepetition = message {
2026-04-13 22:25:58 +03:00
let clone = self.state.clone();
2026-04-14 15:19:46 +03:00
let card_set;
{
2026-08-18 12:14:35 +03:00
card_set = self.state.lock().unwrap().card_sets[self.selected_set_index.unwrap()].clone();
2026-04-14 15:19:46 +03:00
}
2026-08-15 21:32:24 +03:00
2026-08-18 12:14:35 +03:00
if self.local_settings[&card_set.id].append_mode == AppendMode::Full {
2026-08-15 21:32:24 +03:00
self.append_all_words(&card_set);
2026-08-18 12:14:35 +03:00
} else {
let cache = self
.current_sets_cards_cache
.get(&self.selected_set_index.unwrap())
.unwrap();
if cache.1.is_empty() || cache.0.is_empty() {
let local_settings = self.local_settings.get_mut(&card_set.id).unwrap();
local_settings.append_warning = true;
}
2026-08-15 21:32:24 +03:00
}
2026-05-25 12:23:32 +03:00
Some(Repetition(RepetitionState::new(card_set, clone)))
2026-08-06 11:31:11 +03:00
} else if let GoToSettings = message {
Some(RepetitionSettings(RepetitionSettingsState::new(
2026-08-18 12:14:35 +03:00
self.selected_set_index.unwrap(),
2026-08-06 11:31:11 +03:00
self.state.clone(),
)))
} else {
2026-04-09 22:45:31 +03:00
None
}
}
2026-08-06 23:20:14 +03:00
fn navigated(&mut self) {
2026-08-18 12:14:35 +03:00
self.clear_selection();
2026-08-15 21:32:24 +03:00
self.current_sets_cards_cache.clear();
2026-08-06 23:20:14 +03:00
}
2026-08-13 22:03:47 +03:00
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
2026-04-09 22:45:31 +03:00
match message {
2026-08-04 16:53:09 +03:00
Next => {}
Back => {}
GoToRepetition => {}
GoToHistory => {}
GoToSettings => {}
2026-04-13 22:25:58 +03:00
2026-08-18 12:47:06 +03:00
CreateSet => {
}
2026-08-18 12:14:35 +03:00
DeleteSet => {}
SetName(_) => {}
SelectSet(_) => {}
Save => {}
SetForward(_) => {}
SetBackward(_) => {}
SetFilter(_) => {}
TryFilter => {}
SetOpenMode(_) => {}
SetAppendMode(_) => {}
AppendWords(_) => {}
2026-04-09 22:45:31 +03:00
}
Task::none()
}
2026-08-13 22:03:47 +03:00
fn view(&self) -> Element<'_, RepetitionsMessage> {
2026-08-01 19:43:07 +03:00
back_overlay(
row![
column![
scrollable(self.sets_list()).height(Fill),
button("Добавить")
.style(jl_button)
.width(Fill)
2026-08-04 16:53:09 +03:00
.on_press(CreateSet),
2026-04-09 22:45:31 +03:00
]
2026-08-01 19:43:07 +03:00
.spacing(DEFAULT_SPACING)
.width(Length::FillPortion(1)),
self.selected_set_view(),
]
2026-08-15 21:32:24 +03:00
.align_y(Center)
.spacing(DEFAULT_SPACING)
.width(Fill)
.height(Fill)
.into(),
2026-08-04 16:53:09 +03:00
Back,
2026-08-01 19:43:07 +03:00
)
2026-04-09 22:45:31 +03:00
}
2026-08-13 22:03:47 +03:00
}
impl RepetitionsState {
pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState {
2026-08-16 14:23:00 +03:00
let state_ = state.lock().unwrap();
let count = state_.card_sets.len();
let mut map = HashMap::with_capacity(state_.dictionary.len());
2026-08-18 12:14:35 +03:00
state_
.dictionary
.iter()
.enumerate()
.for_each(|(index, word)| {
map.insert(word.id, index);
});
let mut local_settings = HashMap::with_capacity(state_.card_sets.len());
state_.card_sets.iter().for_each(|card_set| {
local_settings.insert(card_set.id, Default::default());
});
2026-08-16 14:23:00 +03:00
drop(state_);
2026-08-13 22:03:47 +03:00
RepetitionsState {
2026-08-18 12:14:35 +03:00
selected_set_index: None,
2026-08-13 22:03:47 +03:00
correct_filters: vec![true; count],
2026-08-15 21:32:24 +03:00
current_sets_cards_cache: Default::default(),
2026-08-16 14:23:00 +03:00
word_id_index_map: map,
2026-08-18 12:14:35 +03:00
local_settings,
view_data: None,
2026-08-13 22:03:47 +03:00
state,
2026-08-18 12:14:35 +03:00
set_names: vec![],
2026-08-13 22:03:47 +03:00
}
}
}
impl RepetitionsState {
2026-08-18 12:14:35 +03:00
fn launch_delete_button(&self, set: &DeckSettings) -> Element<'_, RepetitionsMessage> {
2026-08-06 19:12:23 +03:00
if set.id != 0 {
2026-08-06 11:31:11 +03:00
return row![
space().width(Fill),
button(text!("Начать повторение").width(200).center())
.style(cta_button)
.on_press(GoToRepetition)
]
.into();
2026-04-09 22:45:31 +03:00
}
2026-08-06 11:31:11 +03:00
button("Удалить").style(danger).on_press(DeleteSet).into()
2026-04-09 22:45:31 +03:00
}
fn selected_set_view(&self) -> Element<'_, RepetitionsMessage> {
2026-08-18 12:14:35 +03:00
if let Some(set) = &self.view_data {
2026-04-09 22:45:31 +03:00
return column![
scrollable(
column![
2026-08-04 14:09:40 +03:00
column![
text!("Название набора"),
2026-08-04 16:53:09 +03:00
row![
text_input("", &set.name).on_input(SetName),
2026-08-06 11:31:11 +03:00
button(svg(Handle::from_memory(SETTINGS_ICON)))
.width(43)
.on_press(GoToSettings),
2026-08-04 16:53:09 +03:00
]
.spacing(HALF_SPACING)
2026-08-04 14:09:40 +03:00
]
.spacing(QUARTER_SPACING),
2026-08-06 11:31:11 +03:00
{
if set.id == 0 {
column![
column![
text!("Передняя сторона"),
text_input("", &set.forward).on_input(SetForward),
]
.spacing(QUARTER_SPACING),
column![
text!("Задняя сторона"),
text_input("", &set.backward).on_input(SetBackward),
]
.spacing(QUARTER_SPACING),
column![
text!("Фильтр"),
text_input("", &set.filter).on_input(SetFilter),
button("Проверить фильтр")
.style(jl_button)
.on_press(TryFilter),
2026-08-18 12:47:06 +03:00
self.count_view(set),
2026-08-06 11:31:11 +03:00
]
.spacing(QUARTER_SPACING),
]
.spacing(DEFAULT_SPACING)
} else {
2026-08-15 21:32:24 +03:00
column![
2026-08-18 12:47:06 +03:00
self.filled_set_data_view(set),
self.word_append_panel(set),
2026-08-15 21:32:24 +03:00
radio(
"Обычный режим",
OrderMode::Default,
Some(set.open_mode),
SetOpenMode
),
radio(
"Начать с плохих слов",
OrderMode::TrainWorstFirst,
Some(set.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
OrderMode::FullRandom,
Some(set.open_mode),
SetOpenMode
),
button("История").style(jl_button).on_press(GoToHistory),
]
.spacing(HALF_SPACING)
2026-08-06 11:31:11 +03:00
}
},
2026-08-15 20:16:48 +03:00
// self.words_words_view(&set),
2026-04-09 22:45:31 +03:00
]
2026-04-16 09:56:57 +03:00
.spacing(DEFAULT_SPACING)
2026-08-04 14:09:40 +03:00
.padding(Padding {
top: 0.0,
right: DEFAULT_SPACING,
bottom: 0.0,
left: 0.0,
})
2026-04-09 22:45:31 +03:00
)
.height(Fill),
2026-04-13 22:25:58 +03:00
row![
2026-08-06 11:31:11 +03:00
button("Сохранить").style(jl_button).on_press(Save),
self.launch_delete_button(&set)
2026-04-13 22:25:58 +03:00
]
2026-04-16 09:56:57 +03:00
.spacing(DEFAULT_SPACING),
2026-04-09 22:45:31 +03:00
]
2026-04-16 09:56:57 +03:00
.spacing(DEFAULT_SPACING)
2026-08-16 14:23:00 +03:00
.width(Length::FillPortion(2))
2026-04-13 22:25:58 +03:00
.into();
2026-04-09 22:45:31 +03:00
}
2026-08-16 14:23:00 +03:00
space().width(Length::FillPortion(2)).into()
2026-04-09 22:45:31 +03:00
}
2026-08-18 12:14:35 +03:00
fn filled_set_data_view(&self, set: &DeckSettings) -> Column<'_, RepetitionsMessage> {
2026-08-15 21:32:24 +03:00
column![self.activity_bar(set), self.count_comparator_view()]
.align_x(Center)
2026-08-06 19:12:23 +03:00
.width(Fill)
.spacing(DEFAULT_SPACING)
}
2026-08-18 12:14:35 +03:00
fn activity_bar(&self, set: &DeckSettings) -> Element<'_, RepetitionsMessage> {
2026-08-09 14:34:38 +03:00
const MAX_DAY_COUNT: f32 = 128.0;
2026-08-06 19:12:23 +03:00
let state = self.state.lock().unwrap();
let history = state.activity.get(&set.id);
let mut counts: Vec<u32> = vec![0; 30 * 7];
let now = Local::now().date_naive();
if let Some(history) = history {
for (date, activity) in history {
2026-08-06 23:20:14 +03:00
let distance = now - *date;
2026-08-06 19:12:23 +03:00
let index = counts.len() as i64 - distance.num_days() - 1;
2026-08-06 23:20:14 +03:00
if index == 210 {
println!("invalid index")
}
2026-08-06 19:12:23 +03:00
if index < 0 {
continue;
}
counts[index as usize] = *activity;
}
}
2026-08-09 14:34:38 +03:00
lazy((counts, now), |(counts, now)| {
let mut row = Row::new()
.padding(Padding {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: DEFAULT_SPACING,
})
.spacing(QUARTER_SPACING);
2026-08-06 19:12:23 +03:00
2026-08-15 13:22:59 +03:00
let mut iter = counts.iter();
2026-08-09 14:34:38 +03:00
for i in 0..30 {
let mut column = Column::new().spacing(QUARTER_SPACING);
2026-08-06 19:12:23 +03:00
2026-08-09 14:34:38 +03:00
for j in 0..7 {
let value = *iter.next().unwrap() as f32;
let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1;
2026-08-06 19:12:23 +03:00
2026-08-15 21:32:24 +03:00
let date = (*now)
.checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1))
.unwrap();
2026-08-06 19:12:23 +03:00
2026-08-09 14:34:38 +03:00
column = column.push(tooltip(
iced::widget::container(space().height(15).width(15)).style(
move |x: &Theme| container::Style {
text_color: None,
2026-08-15 21:32:24 +03:00
background: Some(Background::Color(
x.palette().primary.scale_alpha(k),
)),
2026-08-09 14:34:38 +03:00
border: Border {
color: Default::default(),
width: 0.0,
radius: Radius::new(5),
},
shadow: Default::default(),
snap: false,
2026-08-06 19:12:23 +03:00
},
2026-08-09 14:34:38 +03:00
),
text!("{} {} карточки", date.format("%Y.%m.%d"), value),
Top,
));
}
row = row.push(column);
2026-08-06 19:12:23 +03:00
}
2026-08-15 21:32:24 +03:00
scrollable(
column!["Карта активности", row]
.spacing(QUARTER_SPACING)
.align_x(Center),
)
})
.into()
2026-08-06 11:31:11 +03:00
}
2026-08-18 12:14:35 +03:00
fn word_append_panel(&self, set: &DeckSettings) -> Element<'_, RepetitionsMessage> {
2026-08-15 20:16:48 +03:00
column![
text!("Режим добавления карточек"),
2026-08-15 21:32:24 +03:00
row![
radio(
"Добавлять все доступные",
AppendMode::Full,
2026-08-18 12:14:35 +03:00
Some(self.local_settings[&set.id].append_mode),
2026-08-15 21:32:24 +03:00
SetAppendMode
),
radio(
"Добавлять вручную",
AppendMode::Manual,
2026-08-18 12:14:35 +03:00
Some(self.local_settings[&set.id].append_mode),
2026-08-15 21:32:24 +03:00
SetAppendMode
)
]
.spacing(HALF_SPACING),
2026-08-16 14:23:00 +03:00
self.adder_panel(set),
2026-08-15 21:32:24 +03:00
]
.spacing(HALF_SPACING)
.into()
2026-08-15 20:16:48 +03:00
}
2026-08-18 12:14:35 +03:00
fn adder_panel(&self, set: &DeckSettings) -> Element<'_, RepetitionsMessage> {
match self.local_settings[&set.id].append_mode {
2026-08-15 21:32:24 +03:00
AppendMode::Full => space().into(),
AppendMode::Manual => row![
button("+5").on_press(AppendWords(5)),
button("+10").on_press(AppendWords(10)),
button("+15").on_press(AppendWords(15)),
button("+20").on_press(AppendWords(20))
]
.spacing(HALF_SPACING)
.into(),
}
}
fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
2026-08-18 12:14:35 +03:00
let cache = &self.current_sets_cards_cache[&self.selected_set_index.unwrap()];
2026-08-15 21:32:24 +03:00
let now = cache.0.len();
let available = cache.1.len();
text!("{} слова добавлено из {}", now, available).into()
}
2026-08-18 12:14:35 +03:00
fn count_view(&self, set: &DeckSettings) -> Element<'_, RepetitionsMessage> {
2026-04-13 22:25:58 +03:00
if let Some(count) = set.count {
2026-08-01 19:36:43 +03:00
return text!("Количество слов: {}", count).into();
2026-04-09 22:45:31 +03:00
}
space().into()
}
fn sets_list(&self) -> Column<'_, RepetitionsMessage> {
let mut column = Column::new();
2026-08-15 13:22:59 +03:00
2026-08-18 12:14:35 +03:00
for (i, set) in self.set_names.iter().enumerate() {
2026-04-09 22:45:31 +03:00
column = column.push(
2026-08-18 12:14:35 +03:00
button(text!("{}", set.clone()))
2026-08-15 13:22:59 +03:00
.on_press_with(move || SelectSet(i))
2026-08-01 19:43:07 +03:00
.style(move |_x: &Theme, status: Status| Style {
background: if status == Status::Hovered {
2026-08-04 14:09:40 +03:00
Some(Background::Color(Color::WHITE.scale_alpha(0.2)))
2026-08-01 19:43:07 +03:00
} else {
None
},
2026-08-15 13:22:59 +03:00
text_color: if self.correct_filters[i] {
2026-05-12 16:57:05 +03:00
_x.palette().primary
2026-04-09 22:45:31 +03:00
} else {
_x.palette().warning
},
2026-08-01 19:43:07 +03:00
border: Border {
2026-08-01 13:04:18 +03:00
color: Default::default(),
width: 0.0,
2026-08-04 14:09:40 +03:00
radius: BUTTON_RADIUS.into(),
2026-08-01 13:04:18 +03:00
},
2026-04-09 22:45:31 +03:00
shadow: Shadow::default(),
snap: false,
}),
);
}
column
}
}
2026-04-14 15:19:46 +03:00
2026-08-18 12:14:35 +03:00
impl RepetitionsState {
fn append_all_words(&self, set: &DeckSettings) {
let cache = &self.current_sets_cards_cache[&index];
let mut created_set = HashSet::with_capacity(cache.0.len());
cache.0.iter().for_each(|c| {
created_set.insert(c);
});
let required = cache.1.iter().filter(|i| !created_set.contains(i)).cloned();
Self::append_words(&self.state.lock().unwrap(), set, required);
}
fn append_words(state: &AppState, set: &DeckSettings, indices: impl Iterator<Item = usize>) {
let words = &state.dictionary;
let stats = &mut indices
.map(|i| {
let word = words.get(i).unwrap();
CardStatistics {
id: 0,
word_id: word.id,
last_open: Utc::now(),
score: 1,
set_id: set.id,
}
})
.collect::<Vec<_>>();
if !stats.is_empty() {
add_stat_list(stats, &state.connection);
}
}
fn select_set(&mut self, index: usize) {
let state = self.state.lock().unwrap();
if let Some(set) = state.card_sets.get(index) {
}
}
fn clear_selection(&mut self) {
2026-08-18 12:47:06 +03:00
self.view_data = None;
2026-08-18 12:14:35 +03:00
}
}
2026-05-25 12:23:32 +03:00
#[derive(Clone)]
2026-04-09 22:45:31 +03:00
pub enum RepetitionsMessage {
Next,
Back,
GoToRepetition,
CreateSet,
DeleteSet,
SetName(String),
SelectSet(usize),
Save,
SetForward(String),
SetBackward(String),
SetFilter(String),
TryFilter,
2026-08-15 20:16:48 +03:00
SetOpenMode(OrderMode),
SetAppendMode(AppendMode),
2026-07-05 01:58:32 +03:00
GoToHistory,
2026-08-04 16:53:09 +03:00
GoToSettings,
2026-08-15 21:32:24 +03:00
AppendWords(usize),
2026-04-09 22:45:31 +03:00
}
2026-08-18 12:14:35 +03:00
#[derive(Clone, Default)]
struct DeckLocalSetting {
append_mode: AppendMode,
append_warning: bool,
}
#[derive(Clone)]
struct SetViewData{
set_local_settings: DeckLocalSetting,
set_settings: DeckSettings,
existing_words_indices: Vec<usize>,
available_words_indices: Vec<usize>,
}
impl Deref for SetViewData {
type Target = DeckSettings;
fn deref(&self) -> &Self::Target {
&self.set_settings
}
}