Create a view model for the day details #161

Merged
savanni merged 3 commits from fitnesstrax/detail-view-model into main 2024-01-20 20:17:27 +00:00
19 changed files with 87 additions and 158 deletions
Showing only changes of commit 9bedb7a76c - Show all commits

View File

@ -108,7 +108,7 @@ where
Ok(line_) => { Ok(line_) => {
match serde_json::from_str::<RecordOnDisk<T>>(line_.as_ref()) match serde_json::from_str::<RecordOnDisk<T>>(line_.as_ref())
.map_err(EmseriesReadError::JSONParseError) .map_err(EmseriesReadError::JSONParseError)
.and_then(|record| Record::try_from(record)) .and_then(Record::try_from)
{ {
Ok(record) => records.insert(record.id.clone(), record.clone()), Ok(record) => records.insert(record.id.clone(), record.clone()),
Err(EmseriesReadError::RecordDeleted(id)) => records.remove(&id), Err(EmseriesReadError::RecordDeleted(id)) => records.remove(&id),

View File

@ -11,9 +11,6 @@ You should have received a copy of the GNU General Public License along with Lum
*/ */
use chrono::{DateTime, FixedOffset, NaiveDate}; use chrono::{DateTime, FixedOffset, NaiveDate};
use chrono_tz::UTC;
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use std::{cmp::Ordering, fmt, io, str}; use std::{cmp::Ordering, fmt, io, str};
use thiserror::Error; use thiserror::Error;
use uuid::Uuid; use uuid::Uuid;
@ -93,33 +90,9 @@ impl str::FromStr for Timestamp {
} }
} }
/*
impl PartialEq for Timestamp {
fn eq(&self, other: &Timestamp) -> bool {
match (self, other) {
(Timestamp::DateTime(dt1), Timestamp::DateTime(dt2)) => {
dt1.with_timezone(&UTC) == dt2.with_timezone(&UTC)
}
// It's not clear to me what would make sense when I'm comparing a date and a
// timestamp. I'm going with a naive date comparison on the idea that what I'm wanting
// here is human scale, again.
(Timestamp::DateTime(dt1), Timestamp::Date(dt2)) => dt1.date_naive() == *dt2,
(Timestamp::Date(dt1), Timestamp::DateTime(dt2)) => *dt1 == dt2.date_naive(),
(Timestamp::Date(dt1), Timestamp::Date(dt2)) => *dt1 == *dt2,
}
}
}
*/
impl PartialOrd for Timestamp { impl PartialOrd for Timestamp {
fn partial_cmp(&self, other: &Timestamp) -> Option<Ordering> { fn partial_cmp(&self, other: &Timestamp) -> Option<Ordering> {
// Some(self.cmp(other)) Some(self.cmp(other))
match (self, other) {
(Timestamp::DateTime(dt1), Timestamp::DateTime(dt2)) => dt1.partial_cmp(dt2),
(Timestamp::DateTime(dt1), Timestamp::Date(dt2)) => dt1.date_naive().partial_cmp(dt2),
(Timestamp::Date(dt1), Timestamp::DateTime(dt2)) => dt1.partial_cmp(&dt2.date_naive()),
(Timestamp::Date(dt1), Timestamp::Date(dt2)) => dt1.partial_cmp(dt2),
}
} }
} }

View File

@ -14,7 +14,6 @@ General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/ */
use crate::types::DayInterval;
use chrono::NaiveDate; use chrono::NaiveDate;
use emseries::{time_range, Record, RecordId, Series, Timestamp}; use emseries::{time_range, Record, RecordId, Series, Timestamp};
use ft_core::TraxRecord; use ft_core::TraxRecord;
@ -52,12 +51,10 @@ impl App {
.unwrap(), .unwrap(),
); );
let s = Self { Self {
runtime, runtime,
database: Arc::new(RwLock::new(database)), database: Arc::new(RwLock::new(database)),
}; }
s
} }
pub async fn records( pub async fn records(
@ -76,7 +73,7 @@ impl App {
Timestamp::Date(end), Timestamp::Date(end),
true, true,
)) ))
.map(|record| record.clone()) .cloned()
.collect::<Vec<Record<TraxRecord>>>(); .collect::<Vec<Record<TraxRecord>>>();
Ok(records) Ok(records)
} else { } else {

View File

@ -81,7 +81,7 @@ impl AppWindow {
.orientation(gtk::Orientation::Vertical) .orientation(gtk::Orientation::Vertical)
.build(); .build();
let initial_view = View::Placeholder(PlaceholderView::new().upcast()); let initial_view = View::Placeholder(PlaceholderView::default().upcast());
layout.append(&initial_view.widget()); layout.append(&initial_view.widget());
@ -115,9 +115,10 @@ impl AppWindow {
s.navigation.connect_popped({ s.navigation.connect_popped({
let s = s.clone(); let s = s.clone();
move |_, _| match *s.current_view.borrow() { move |_, _| {
View::Historical(_) => s.load_records(), if let View::Historical(_) = *s.current_view.borrow() {
_ => {} s.load_records();
}
} }
}); });
@ -191,22 +192,4 @@ impl AppWindow {
} }
}); });
} }
fn on_put_record(&self, record: TraxRecord) {
glib::spawn_future_local({
let s = self.clone();
async move {
s.app.put_record(record).await;
}
});
}
fn on_update_record(&self, record: Record<TraxRecord>) {
glib::spawn_future_local({
let s = self.clone();
async move {
s.app.update_record(record).await;
}
});
}
} }

View File

@ -14,6 +14,8 @@ General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/ */
//! ActionGroup and related structures
use glib::Object; use glib::Object;
use gtk::{prelude::*, subclass::prelude::*}; use gtk::{prelude::*, subclass::prelude::*};

View File

@ -23,7 +23,7 @@ use crate::{
use emseries::Record; use emseries::Record;
use glib::Object; use glib::Object;
use gtk::{prelude::*, subclass::prelude::*}; use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, rc::Rc}; use std::cell::RefCell;
use super::weight::WeightEdit; use super::weight::WeightEdit;
@ -60,8 +60,8 @@ glib::wrapper! {
pub struct DaySummary(ObjectSubclass<DaySummaryPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable; pub struct DaySummary(ObjectSubclass<DaySummaryPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
} }
impl DaySummary { impl Default for DaySummary {
pub fn new() -> Self { fn default() -> Self {
let s: Self = Object::builder().build(); let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical); s.set_orientation(gtk::Orientation::Vertical);
s.set_css_classes(&["day-summary"]); s.set_css_classes(&["day-summary"]);
@ -70,6 +70,12 @@ impl DaySummary {
s s
} }
}
impl DaySummary {
pub fn new() -> Self {
Self::default()
}
pub fn set_data(&self, date: chrono::NaiveDate, records: Vec<Record<ft_core::TraxRecord>>) { pub fn set_data(&self, date: chrono::NaiveDate, records: Vec<Record<ft_core::TraxRecord>>) {
self.imp() self.imp()
@ -83,11 +89,11 @@ impl DaySummary {
if let Some(Record { if let Some(Record {
data: ft_core::TraxRecord::Weight(weight_record), data: ft_core::TraxRecord::Weight(weight_record),
.. ..
}) = records.iter().filter(|f| f.data.is_weight()).next() }) = records.iter().find(|f| f.data.is_weight())
{ {
let label = gtk::Label::builder() let label = gtk::Label::builder()
.halign(gtk::Align::Start) .halign(gtk::Align::Start)
.label(&format!("{}", weight_record.weight)) .label(weight_record.weight.to_string())
.css_classes(["day-summary__weight"]) .css_classes(["day-summary__weight"])
.build(); .build();
self.append(&label); self.append(&label);
@ -134,7 +140,7 @@ impl DayDetail {
s.append( s.append(
&ActionGroup::builder() &ActionGroup::builder()
.primary_action("Edit", Box::new(move || on_edit())) .primary_action("Edit", Box::new(on_edit))
.build(), .build(),
); );

View File

@ -1,22 +0,0 @@
/*
Copyright 2023, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of FitnessTrax.
FitnessTrax is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
FitnessTrax is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/
#[derive(Clone)]
pub enum EditView<View, Edit> {
Unconfigured,
View(View),
Edit(Edit),
}

View File

@ -20,9 +20,6 @@ pub use action_group::ActionGroup;
mod day; mod day;
pub use day::{DayDetail, DayEdit, DaySummary}; pub use day::{DayDetail, DayEdit, DaySummary};
mod edit_view;
pub use edit_view::EditView;
mod singleton; mod singleton;
pub use singleton::{Singleton, SingletonImpl}; pub use singleton::{Singleton, SingletonImpl};

View File

@ -20,12 +20,16 @@ use std::{cell::RefCell, rc::Rc};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ParseError; pub struct ParseError;
type Renderer<T> = dyn Fn(&T) -> String;
type Parser<T> = dyn Fn(&str) -> Result<T, ParseError>;
#[derive(Clone)] #[derive(Clone)]
pub struct TextEntry<T: Clone + std::fmt::Debug> { pub struct TextEntry<T: Clone + std::fmt::Debug> {
value: Rc<RefCell<Option<T>>>, value: Rc<RefCell<Option<T>>>,
widget: gtk::Entry, widget: gtk::Entry,
renderer: Rc<Box<dyn Fn(&T) -> String>>, #[allow(unused)]
parser: Rc<Box<dyn Fn(&str) -> Result<T, ParseError>>>, renderer: Rc<Renderer<T>>,
parser: Rc<Parser<T>>,
} }
impl<T: Clone + std::fmt::Debug> std::fmt::Debug for TextEntry<T> { impl<T: Clone + std::fmt::Debug> std::fmt::Debug for TextEntry<T> {
@ -46,16 +50,15 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
V: Fn(&str) -> Result<T, ParseError> + 'static, V: Fn(&str) -> Result<T, ParseError> + 'static,
{ {
let widget = gtk::Entry::builder().placeholder_text(placeholder).build(); let widget = gtk::Entry::builder().placeholder_text(placeholder).build();
match value { if let Some(ref v) = value {
Some(ref v) => widget.set_text(&renderer(&v)), widget.set_text(&renderer(v))
None => {}
} }
let s = Self { let s = Self {
value: Rc::new(RefCell::new(value)), value: Rc::new(RefCell::new(value)),
widget, widget,
renderer: Rc::new(Box::new(renderer)), renderer: Rc::new(renderer),
parser: Rc::new(Box::new(parser)), parser: Rc::new(parser),
}; };
s.widget.buffer().connect_text_notify({ s.widget.buffer().connect_text_notify({
@ -84,19 +87,20 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
} }
} }
#[allow(unused)]
pub fn value(&self) -> Option<T> { pub fn value(&self) -> Option<T> {
let v = self.value.borrow().clone(); let v = self.value.borrow().clone();
self.value.borrow().clone() self.value.borrow().clone()
} }
pub fn set_value(&self, value: Option<T>) { pub fn set_value(&self, value: Option<T>) {
match value { if let Some(ref v) = value {
Some(ref v) => self.widget.set_text(&(self.renderer)(&v)), self.widget.set_text(&(self.renderer)(v))
None => {}
} }
*self.value.borrow_mut() = value; *self.value.borrow_mut() = value;
} }
#[allow(unused)]
pub fn grab_focus(&self) { pub fn grab_focus(&self) {
self.widget.grab_focus(); self.widget.grab_focus();
} }

View File

@ -24,6 +24,7 @@ use std::cell::RefCell;
#[derive(Default)] #[derive(Default)]
pub struct TimeDistanceViewPrivate { pub struct TimeDistanceViewPrivate {
#[allow(unused)]
record: RefCell<Option<TimeDistance>>, record: RefCell<Option<TimeDistance>>,
} }
@ -53,7 +54,7 @@ impl TimeDistanceView {
first_row.append( first_row.append(
&gtk::Label::builder() &gtk::Label::builder()
.halign(gtk::Align::Start) .halign(gtk::Align::Start)
.label(&record.datetime.format("%H:%M").to_string()) .label(record.datetime.format("%H:%M").to_string())
.build(), .build(),
); );
@ -96,7 +97,7 @@ impl TimeDistanceView {
.label( .label(
record record
.comments .comments
.map(|comments| format!("{}", comments)) .map(|comments| comments.to_string())
.unwrap_or("".to_owned()), .unwrap_or("".to_owned()),
) )
.build(), .build(),

View File

@ -14,12 +14,9 @@ General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/ */
use crate::components::{EditView, ParseError, Singleton, TextEntry}; use crate::components::{ParseError, TextEntry};
use chrono::{Local, NaiveDate};
use dimensioned::si; use dimensioned::si;
use glib::{object::ObjectRef, Object}; use gtk::prelude::*;
use gtk::{prelude::*, subclass::prelude::*};
use std::{borrow::Borrow, cell::RefCell};
#[derive(Default)] #[derive(Default)]
pub struct WeightViewPrivate {} pub struct WeightViewPrivate {}
@ -77,6 +74,7 @@ impl WeightEdit {
} }
} }
#[allow(unused)]
pub fn set_value(&self, value: Option<si::Kilogram<f64>>) { pub fn set_value(&self, value: Option<si::Kilogram<f64>>) {
self.entry.set_value(value); self.entry.set_value(value);
} }

View File

@ -21,8 +21,8 @@ impl Default for DayInterval {
impl DayInterval { impl DayInterval {
pub fn days(&self) -> impl Iterator<Item = NaiveDate> { pub fn days(&self) -> impl Iterator<Item = NaiveDate> {
DayIterator { DayIterator {
current: self.start.clone(), current: self.start,
end: self.end.clone(), end: self.end,
} }
} }
} }
@ -37,7 +37,7 @@ impl Iterator for DayIterator {
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.current <= self.end { if self.current <= self.end {
let val = self.current.clone(); let val = self.current;
self.current += Duration::days(1); self.current += Duration::days(1);
Some(val) Some(val)
} else { } else {

View File

@ -29,10 +29,12 @@ enum RecordState<T: Clone + Recordable> {
Original(Record<T>), Original(Record<T>),
New(T), New(T),
Updated(Record<T>), Updated(Record<T>),
#[allow(unused)]
Deleted(Record<T>), Deleted(Record<T>),
} }
impl<T: Clone + emseries::Recordable> RecordState<T> { impl<T: Clone + emseries::Recordable> RecordState<T> {
#[allow(unused)]
fn id(&self) -> Option<&RecordId> { fn id(&self) -> Option<&RecordId> {
match self { match self {
RecordState::Original(ref r) => Some(&r.id), RecordState::Original(ref r) => Some(&r.id),
@ -51,6 +53,7 @@ impl<T: Clone + emseries::Recordable> RecordState<T> {
} }
} }
#[allow(unused)]
fn with_delete(self) -> Option<RecordState<T>> { fn with_delete(self) -> Option<RecordState<T>> {
match self { match self {
RecordState::Original(r) => Some(RecordState::Deleted(r)), RecordState::Original(r) => Some(RecordState::Deleted(r)),
@ -66,7 +69,7 @@ impl<T: Clone + emseries::Recordable> Deref for RecordState<T> {
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
match self { match self {
RecordState::Original(ref r) => &r.data, RecordState::Original(ref r) => &r.data,
RecordState::New(ref r) => &r, RecordState::New(ref r) => r,
RecordState::Updated(ref r) => &r.data, RecordState::Updated(ref r) => &r.data,
RecordState::Deleted(ref r) => &r.data, RecordState::Deleted(ref r) => &r.data,
} }
@ -123,21 +126,18 @@ impl DayDetailViewModel {
} }
pub fn weight(&self) -> Option<si::Kilogram<f64>> { pub fn weight(&self) -> Option<si::Kilogram<f64>> {
match *self.weight.read().unwrap() { (*self.weight.read().unwrap()).as_ref().map(|w| w.weight)
Some(ref w) => Some((*w).weight),
None => None,
}
} }
pub fn set_weight(&self, new_weight: si::Kilogram<f64>) { pub fn set_weight(&self, new_weight: si::Kilogram<f64>) {
let mut record = self.weight.write().unwrap(); let mut record = self.weight.write().unwrap();
let new_record = match *record { let new_record = match *record {
Some(ref rstate) => rstate.clone().with_value(ft_core::Weight { Some(ref rstate) => rstate.clone().with_value(ft_core::Weight {
date: self.date.clone(), date: self.date,
weight: new_weight, weight: new_weight,
}), }),
None => RecordState::New(ft_core::Weight { None => RecordState::New(ft_core::Weight {
date: self.date.clone(), date: self.date,
weight: new_weight, weight: new_weight,
}), }),
}; };
@ -145,21 +145,18 @@ impl DayDetailViewModel {
} }
pub fn steps(&self) -> Option<u32> { pub fn steps(&self) -> Option<u32> {
match *self.steps.read().unwrap() { (*self.steps.read().unwrap()).as_ref().map(|w| w.count)
Some(ref w) => Some((*w).count),
None => None,
}
} }
pub fn set_steps(&self, new_count: u32) { pub fn set_steps(&self, new_count: u32) {
let mut record = self.steps.write().unwrap(); let mut record = self.steps.write().unwrap();
let new_record = match *record { let new_record = match *record {
Some(ref rstate) => rstate.clone().with_value(ft_core::Steps { Some(ref rstate) => rstate.clone().with_value(ft_core::Steps {
date: self.date.clone(), date: self.date,
count: new_count, count: new_count,
}), }),
None => RecordState::New(ft_core::Steps { None => RecordState::New(ft_core::Steps {
date: self.date.clone(), date: self.date,
count: new_count, count: new_count,
}), }),
}; };

View File

@ -15,22 +15,12 @@ You should have received a copy of the GNU General Public License along with Fit
*/ */
use crate::{ use crate::{
app::App,
components::{DayDetail, DayEdit, Singleton, SingletonImpl}, components::{DayDetail, DayEdit, Singleton, SingletonImpl},
view_models::DayDetailViewModel, view_models::DayDetailViewModel,
}; };
use dimensioned::si;
use emseries::{Record, RecordId};
use ft_core::TraxRecord;
use glib::Object; use glib::Object;
use gtk::{prelude::*, subclass::prelude::*}; use gtk::{prelude::*, subclass::prelude::*};
use std::{ use std::cell::RefCell;
cell::RefCell,
collections::HashMap,
ops::Deref,
rc::Rc,
sync::{Arc, RwLock},
};
#[derive(Default)] #[derive(Default)]
pub struct DayDetailViewPrivate { pub struct DayDetailViewPrivate {

View File

@ -15,7 +15,7 @@ You should have received a copy of the GNU General Public License along with Fit
*/ */
use crate::{components::DaySummary, types::DayInterval}; use crate::{components::DaySummary, types::DayInterval};
use chrono::{Duration, Local, NaiveDate}; use chrono::NaiveDate;
use emseries::Record; use emseries::Record;
use ft_core::TraxRecord; use ft_core::TraxRecord;
use glib::Object; use glib::Object;
@ -161,7 +161,7 @@ impl DayRecords {
} }
pub fn date(&self) -> chrono::NaiveDate { pub fn date(&self) -> chrono::NaiveDate {
self.imp().date.borrow().clone() *self.imp().date.borrow()
} }
pub fn records(&self) -> Vec<Record<TraxRecord>> { pub fn records(&self) -> Vec<Record<TraxRecord>> {
@ -204,11 +204,11 @@ impl GroupedRecords {
self self
} }
fn items<'a>(&'a self) -> impl Iterator<Item = DayRecords> + 'a { fn items(&self) -> impl Iterator<Item = DayRecords> + '_ {
self.interval.days().map(|date| { self.interval.days().map(|date| {
self.data self.data
.get(&date) .get(&date)
.map(|rec| rec.clone()) .cloned()
.unwrap_or(DayRecords::new(date, vec![])) .unwrap_or(DayRecords::new(date, vec![]))
}) })
} }
@ -217,6 +217,7 @@ impl GroupedRecords {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::GroupedRecords; use super::GroupedRecords;
use crate::types::DayInterval;
use chrono::{FixedOffset, NaiveDate, TimeZone}; use chrono::{FixedOffset, NaiveDate, TimeZone};
use dimensioned::si::{KG, M, S}; use dimensioned::si::{KG, M, S};
use emseries::{Record, RecordId}; use emseries::{Record, RecordId};
@ -272,7 +273,12 @@ mod test {
}, },
]; ];
let groups = GroupedRecords::from(records).0; let groups = GroupedRecords::new(DayInterval {
start: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
end: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
})
.with_data(records)
.data;
assert_eq!(groups.len(), 3); assert_eq!(groups.len(), 3);
} }
} }

View File

@ -38,8 +38,8 @@ glib::wrapper! {
pub struct PlaceholderView(ObjectSubclass<PlaceholderViewPrivate>) @extends gtk::Box, gtk::Widget; pub struct PlaceholderView(ObjectSubclass<PlaceholderViewPrivate>) @extends gtk::Box, gtk::Widget;
} }
impl PlaceholderView { impl Default for PlaceholderView {
pub fn new() -> Self { fn default() -> Self {
let s: Self = Object::builder().build(); let s: Self = Object::builder().build();
s s
} }

View File

@ -14,7 +14,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/ */
use crate::{app::App, components::FileChooserRow}; use crate::components::FileChooserRow;
use glib::Object; use glib::Object;
use gtk::{prelude::*, subclass::prelude::*}; use gtk::{prelude::*, subclass::prelude::*};
use std::path::PathBuf; use std::path::PathBuf;

View File

@ -1,23 +1,25 @@
use crate::types;
#[cfg(test)] #[cfg(test)]
mod test { mod test {
#[test] #[test]
#[ignore]
fn read_a_legacy_set_rep_record() { fn read_a_legacy_set_rep_record() {
unimplemented!() unimplemented!()
} }
#[test] #[test]
#[ignore]
fn read_a_legacy_steps_record() { fn read_a_legacy_steps_record() {
unimplemented!() unimplemented!()
} }
#[test] #[test]
#[ignore]
fn read_a_legacy_time_distance_record() { fn read_a_legacy_time_distance_record() {
unimplemented!() unimplemented!()
} }
#[test] #[test]
#[ignore]
fn read_a_legacy_weight_record() { fn read_a_legacy_weight_record() {
unimplemented!() unimplemented!()
} }

View File

@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
/// SetRep represents workouts like pushups or situps, which involve doing a "set" of a number of /// SetRep represents workouts like pushups or situps, which involve doing a "set" of a number of
/// actions, resting, and then doing another set. /// actions, resting, and then doing another set.
#[allow(dead_code)]
pub struct SetRep { pub struct SetRep {
/// I assume that a set/rep workout is only done once in a day. /// I assume that a set/rep workout is only done once in a day.
date: NaiveDate, date: NaiveDate,
@ -24,7 +25,7 @@ pub struct Steps {
impl Recordable for Steps { impl Recordable for Steps {
fn timestamp(&self) -> Timestamp { fn timestamp(&self) -> Timestamp {
Timestamp::Date(self.date.clone()) Timestamp::Date(self.date)
} }
fn tags(&self) -> Vec<String> { fn tags(&self) -> Vec<String> {
@ -66,7 +67,7 @@ pub struct Weight {
impl Recordable for Weight { impl Recordable for Weight {
fn timestamp(&self) -> Timestamp { fn timestamp(&self) -> Timestamp {
Timestamp::Date(self.date.clone()) Timestamp::Date(self.date)
} }
fn tags(&self) -> Vec<String> { fn tags(&self) -> Vec<String> {
@ -111,29 +112,23 @@ impl TraxRecord {
} }
pub fn is_weight(&self) -> bool { pub fn is_weight(&self) -> bool {
match self { matches!(self, TraxRecord::Weight(_))
TraxRecord::Weight(_) => true,
_ => false,
}
} }
pub fn is_steps(&self) -> bool { pub fn is_steps(&self) -> bool {
match self { matches!(self, TraxRecord::Steps(_))
TraxRecord::Steps(_) => true,
_ => false,
}
} }
} }
impl Recordable for TraxRecord { impl Recordable for TraxRecord {
fn timestamp(&self) -> Timestamp { fn timestamp(&self) -> Timestamp {
match self { match self {
TraxRecord::BikeRide(rec) => Timestamp::DateTime(rec.datetime.clone()), TraxRecord::BikeRide(rec) => Timestamp::DateTime(rec.datetime),
TraxRecord::Row(rec) => Timestamp::DateTime(rec.datetime.clone()), TraxRecord::Row(rec) => Timestamp::DateTime(rec.datetime),
TraxRecord::Run(rec) => Timestamp::DateTime(rec.datetime.clone()), TraxRecord::Run(rec) => Timestamp::DateTime(rec.datetime),
TraxRecord::Steps(rec) => rec.timestamp(), TraxRecord::Steps(rec) => rec.timestamp(),
TraxRecord::Swim(rec) => Timestamp::DateTime(rec.datetime.clone()), TraxRecord::Swim(rec) => Timestamp::DateTime(rec.datetime),
TraxRecord::Walk(rec) => Timestamp::DateTime(rec.datetime.clone()), TraxRecord::Walk(rec) => Timestamp::DateTime(rec.datetime),
TraxRecord::Weight(rec) => rec.timestamp(), TraxRecord::Weight(rec) => rec.timestamp(),
} }
} }
@ -162,6 +157,6 @@ mod test {
let id = series.put(record.clone()).unwrap(); let id = series.put(record.clone()).unwrap();
let record_ = series.get(&id).unwrap(); let record_ = series.get(&id).unwrap();
assert_eq!(record_, record); assert_eq!(record_.data, record);
} }
} }