1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
|
// Example: Building a terminal habit tracker similar to dijo
use std::collections::HashMap;
use std::io::{self, Write};
use chrono::{Local, NaiveDate, Duration};
use crossterm::{
event::{self, KeyCode, KeyEvent},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use tui::{
backend::{Backend, CrosstermBackend},
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::{Block, Borders, Calendar, Clear, List, ListItem, Paragraph},
Frame, Terminal,
};
#[derive(Debug, Clone)]
struct Habit {
name: String,
target_frequency: u32, // times per week
completed_dates: Vec<NaiveDate>,
created_date: NaiveDate,
}
impl Habit {
fn new(name: String, target_frequency: u32) -> Self {
Self {
name,
target_frequency,
completed_dates: Vec::new(),
created_date: Local::now().date_naive(),
}
}
fn mark_completed(&mut self, date: NaiveDate) {
if !self.completed_dates.contains(&date) {
self.completed_dates.push(date);
self.completed_dates.sort();
}
}
fn is_completed_on(&self, date: NaiveDate) -> bool {
self.completed_dates.contains(&date)
}
fn weekly_completion_rate(&self, week_start: NaiveDate) -> f32 {
let week_end = week_start + Duration::days(6);
let completed_this_week = self.completed_dates
.iter()
.filter(|&&date| date >= week_start && date <= week_end)
.count() as f32;
(completed_this_week / self.target_frequency as f32).min(1.0)
}
fn streak(&self) -> u32 {
let today = Local::now().date_naive();
let mut streak = 0;
let mut current_date = today;
while self.is_completed_on(current_date) {
streak += 1;
current_date = current_date - Duration::days(1);
}
streak
}
}
struct HabitTracker {
habits: HashMap<String, Habit>,
selected_habit: Option<String>,
mode: AppMode,
input_buffer: String,
}
#[derive(Debug, Clone, PartialEq)]
enum AppMode {
Normal,
AddingHabit,
ViewingCalendar,
}
impl HabitTracker {
fn new() -> Self {
let mut tracker = Self {
habits: HashMap::new(),
selected_habit: None,
mode: AppMode::Normal,
input_buffer: String::new(),
};
// Add some sample habits
tracker.add_habit("Exercise".to_string(), 5);
tracker.add_habit("Read".to_string(), 7);
tracker.add_habit("Meditate".to_string(), 7);
tracker.add_habit("Code".to_string(), 5);
tracker
}
fn add_habit(&mut self, name: String, frequency: u32) {
let habit = Habit::new(name.clone(), frequency);
self.habits.insert(name.clone(), habit);
if self.selected_habit.is_none() {
self.selected_habit = Some(name);
}
}
fn toggle_habit_today(&mut self) {
if let Some(habit_name) = &self.selected_habit {
if let Some(habit) = self.habits.get_mut(habit_name) {
let today = Local::now().date_naive();
if habit.is_completed_on(today) {
habit.completed_dates.retain(|&date| date != today);
} else {
habit.mark_completed(today);
}
}
}
}
fn next_habit(&mut self) {
if let Some(current) = &self.selected_habit {
let habit_names: Vec<_> = self.habits.keys().collect();
if let Some(current_index) = habit_names.iter().position(|&name| name == current) {
let next_index = (current_index + 1) % habit_names.len();
self.selected_habit = Some(habit_names[next_index].clone());
}
}
}
fn previous_habit(&mut self) {
if let Some(current) = &self.selected_habit {
let habit_names: Vec<_> = self.habits.keys().collect();
if let Some(current_index) = habit_names.iter().position(|&name| name == current) {
let prev_index = if current_index == 0 {
habit_names.len() - 1
} else {
current_index - 1
};
self.selected_habit = Some(habit_names[prev_index].clone());
}
}
}
}
// Terminal UI rendering
fn ui<B: Backend>(f: &mut Frame<B>, app: &HabitTracker) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([
Constraint::Length(3),
Constraint::Min(10),
Constraint::Length(3),
].as_ref())
.split(f.size());
// Title
let title = Paragraph::new("๐ฏ Habit Tracker")
.style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD))
.alignment(Alignment::Center)
.block(Block::default().borders(Borders::ALL));
f.render_widget(title, chunks[0]);
// Main content
let main_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(60), Constraint::Percentage(40)].as_ref())
.split(chunks[1]);
// Habit list
let habits_list = render_habits_list(app);
f.render_widget(habits_list, main_chunks[0]);
// Statistics panel
let stats_panel = render_statistics(app);
f.render_widget(stats_panel, main_chunks[1]);
// Status bar
let status = match app.mode {
AppMode::Normal => "Press 'a' to add habit, 'space' to toggle, 'q' to quit",
AppMode::AddingHabit => "Enter habit name, then press Enter",
AppMode::ViewingCalendar => "Press 'Esc' to return",
};
let status_bar = Paragraph::new(status)
.style(Style::default().fg(Color::Gray))
.alignment(Alignment::Center)
.block(Block::default().borders(Borders::ALL));
f.render_widget(status_bar, chunks[2]);
}
fn render_habits_list(app: &HabitTracker) -> List {
let today = Local::now().date_naive();
let items: Vec<ListItem> = app.habits
.iter()
.map(|(name, habit)| {
let is_selected = app.selected_habit.as_ref() == Some(name);
let is_completed_today = habit.is_completed_on(today);
let streak = habit.streak();
let completion_indicator = if is_completed_today { "โ
" } else { "โญ" };
let streak_text = if streak > 0 { format!(" ๐ฅ{}", streak) } else { String::new() };
let content = format!("{} {} ({}x/week){}",
completion_indicator, name, habit.target_frequency, streak_text);
let style = if is_selected {
Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
} else if is_completed_today {
Style::default().fg(Color::Green)
} else {
Style::default().fg(Color::White)
};
ListItem::new(content).style(style)
})
.collect();
List::new(items)
.block(Block::default().borders(Borders::ALL).title("Habits"))
.highlight_style(Style::default().add_modifier(Modifier::REVERSED))
}
fn render_statistics(app: &HabitTracker) -> Paragraph {
let today = Local::now().date_naive();
let week_start = today - Duration::days(today.weekday().num_days_from_monday() as i64);
let total_habits = app.habits.len();
let completed_today = app.habits.values()
.filter(|habit| habit.is_completed_on(today))
.count();
let weekly_rates: Vec<_> = app.habits.values()
.map(|habit| habit.weekly_completion_rate(week_start))
.collect();
let avg_weekly_rate = if !weekly_rates.is_empty() {
weekly_rates.iter().sum::<f32>() / weekly_rates.len() as f32
} else {
0.0
};
let stats_text = format!(
"๐ Statistics\n\n\
Today: {}/{} habits completed\n\
Weekly average: {:.1}%\n\
Total habits: {}\n\n\
๐
This Week:\n{}",
completed_today,
total_habits,
avg_weekly_rate * 100.0,
total_habits,
render_week_view(&app.habits, week_start)
);
Paragraph::new(stats_text)
.block(Block::default().borders(Borders::ALL).title("Statistics"))
.style(Style::default().fg(Color::Cyan))
}
fn render_week_view(habits: &HashMap<String, Habit>, week_start: NaiveDate) -> String {
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let mut week_view = String::new();
for (i, day) in days.iter().enumerate() {
let date = week_start + Duration::days(i as i64);
let completed_count = habits.values()
.filter(|habit| habit.is_completed_on(date))
.count();
week_view.push_str(&format!("{}: {} ", day, completed_count));
}
week_view
}
// Main application event loop
fn run_app() -> Result<(), Box<dyn std::error::Error>> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut app = HabitTracker::new();
loop {
terminal.draw(|f| ui(f, &app))?;
if let event::Event::Key(key) = event::read()? {
match app.mode {
AppMode::Normal => {
match key.code {
KeyCode::Char('q') => break,
KeyCode::Char(' ') => app.toggle_habit_today(),
KeyCode::Down | KeyCode::Char('j') => app.next_habit(),
KeyCode::Up | KeyCode::Char('k') => app.previous_habit(),
KeyCode::Char('a') => {
app.mode = AppMode::AddingHabit;
app.input_buffer.clear();
},
_ => {}
}
},
AppMode::AddingHabit => {
match key.code {
KeyCode::Enter => {
if !app.input_buffer.is_empty() {
app.add_habit(app.input_buffer.clone(), 5); // Default 5x/week
app.input_buffer.clear();
app.mode = AppMode::Normal;
}
},
KeyCode::Esc => {
app.mode = AppMode::Normal;
app.input_buffer.clear();
},
KeyCode::Char(c) => {
app.input_buffer.push(c);
},
KeyCode::Backspace => {
app.input_buffer.pop();
},
_ => {}
}
},
_ => {}
}
}
}
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
Ok(())
}
// Command-line interface
use clap::{App, Arg, SubCommand};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("habit-tracker")
.version("1.0")
.about("Terminal-based habit tracker")
.subcommand(
SubCommand::with_name("add")
.about("Add a new habit")
.arg(Arg::with_name("name")
.required(true)
.help("Name of the habit"))
.arg(Arg::with_name("frequency")
.short("f")
.long("frequency")
.value_name("TIMES_PER_WEEK")
.help("Target frequency per week")
.default_value("5"))
)
.subcommand(
SubCommand::with_name("list")
.about("List all habits")
)
.subcommand(
SubCommand::with_name("toggle")
.about("Toggle completion for today")
.arg(Arg::with_name("habit")
.required(true)
.help("Name of the habit to toggle"))
)
.subcommand(
SubCommand::with_name("stats")
.about("Show statistics")
)
.subcommand(
SubCommand::with_name("tui")
.about("Launch terminal UI")
)
.get_matches();
match matches.subcommand() {
("tui", _) => {
run_app()?;
},
("add", Some(sub_m)) => {
let name = sub_m.value_of("name").unwrap();
let frequency: u32 = sub_m.value_of("frequency").unwrap().parse()?;
println!("Added habit: {} ({}x/week)", name, frequency);
},
("list", _) => {
println!("๐ Your Habits:");
println!("โข Exercise (5x/week) โ
");
println!("โข Read (7x/week) โญ");
println!("โข Meditate (7x/week) โ
");
},
("toggle", Some(sub_m)) => {
let habit = sub_m.value_of("habit").unwrap();
println!("Toggled completion for: {}", habit);
},
("stats", _) => {
println!("๐ Habit Statistics:");
println!("Today: 2/4 habits completed");
println!("Weekly average: 78.5%");
println!("Current streak: Exercise (5 days)");
},
_ => {
run_app()?;
}
}
Ok(())
}
|