lol-cal
terminal lolesports schedule viewer
git clone https://jhhm.no/repos/lol-cal.git
lol-cal/src/widgets/events.rs
get raw file: events.rs
1use chrono::{DateTime, Local, NaiveDate}; 2use ratatui::{ 3 buffer::Buffer, 4 layout::{Constraint, Layout, Rect}, 5 style::{Color, Modifier, Stylize}, 6 symbols::line, 7 text::{Line, Text}, 8 widgets::{Block, Borders, Clear, StatefulWidgetRef, Widget, WidgetRef}, 9}; 10use serde::{Deserialize, Serialize}; 11use std::{collections::HashMap, rc::Rc}; 12use tracing::{debug, info}; 13 14use crate::config::Config; 15 16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 17pub enum StratType { 18 BestOf(String), 19 PlayAll(String), 20 Unknown(String), 21} 22 23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 24pub struct Strategy { 25 pub strat_type: StratType, 26 pub count: u16, 27} 28 29impl StratType { 30 pub fn get_string(&self) -> &str { 31 match self { 32 StratType::BestOf(s) => s, 33 StratType::PlayAll(s) => s, 34 StratType::Unknown(s) => s, 35 } 36 } 37} 38 39impl From<String> for StratType { 40 fn from(name: String) -> Self { 41 match name.as_str() { 42 "bestOf" => StratType::BestOf("Best of".to_string()), 43 "playAll" => StratType::PlayAll("Play all".to_string()), 44 _ => StratType::Unknown(name), 45 } 46 } 47} 48 49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 50pub enum MatchState { 51 Completed(String), 52 InProgress(String), 53 Unstarted(String), 54 Unknown(String), 55} 56 57impl MatchState { 58 pub fn get_string(&self) -> &str { 59 match self { 60 MatchState::Completed(s) => s, 61 MatchState::InProgress(s) => s, 62 MatchState::Unstarted(s) => s, 63 MatchState::Unknown(s) => s, 64 } 65 } 66} 67 68impl From<String> for MatchState { 69 fn from(name: String) -> Self { 70 match name.as_str() { 71 "completed" => MatchState::Completed("Completed".to_string()), 72 "inProgress" => MatchState::InProgress("In progress".to_string()), 73 "unstarted" => MatchState::Unstarted("Unstarted".to_string()), 74 _ => MatchState::Unknown(name), 75 } 76 } 77} 78 79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 80pub struct Team { 81 pub name: String, 82 pub short: String, 83} 84 85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 86pub struct MatchResult { 87 pub game_wins: (u16, u16), 88} 89 90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 91pub struct Event { 92 pub start_time: DateTime<Local>, 93 pub league_name: String, 94 pub block_name: String, 95 pub strategy: Strategy, 96 pub state: MatchState, 97 pub result: Option<MatchResult>, 98 pub teams: Vec<Team>, 99} 100 101#[derive(Debug, Default)] 102pub struct ScheduleState { 103 pub focused: bool, 104 pub spoil_results: bool, 105 pub spoil_matches: bool, 106 pub offset: usize, 107 pub selected: Option<usize>, 108} 109 110#[derive(Debug)] 111pub struct Events { 112 active: Vec<String>, 113 events: HashMap<String, Vec<Event>>, 114 config: Rc<Config>, 115} 116 117impl ScheduleState { 118 pub fn select(&mut self, index: Option<usize>) { 119 self.selected = index; 120 if index.is_none() { 121 self.offset = 0; 122 } 123 } 124 125 pub fn select_today(&mut self, events: &Events) { 126 let today = Local::now(); 127 128 debug!("active: {:?}", events.active); 129 let mut events: Vec<&Event> = events 130 .events 131 .iter() 132 .filter(|(key, _)| events.active.contains(key)) 133 .flat_map(|(_, event_list)| event_list.iter()) 134 .collect(); 135 136 events.sort_by_key(|event| event.start_time); 137 138 if events.is_empty() { 139 return; 140 } 141 142 let sel = events 143 .iter() 144 .position(|e| e.start_time >= today || matches!(e.state, MatchState::InProgress(_))); 145 146 self.selected = Some(sel.unwrap_or(events.len() - 1)); 147 self.offset = self.selected.unwrap_or_default(); 148 } 149 150 pub fn scroll_up_by(&mut self, amount: u16) { 151 match self.selected { 152 Some(sel) => self.selected = Some(sel.saturating_sub(amount as usize)), 153 None => self.selected = Some(self.offset), 154 } 155 } 156 157 pub fn scroll_down_by(&mut self, amount: u16) { 158 match self.selected { 159 Some(sel) => self.selected = Some(sel.saturating_add(amount as usize)), 160 None => self.selected = Some(self.offset), 161 } 162 } 163} 164 165impl Events { 166 pub fn new(config: Rc<Config>) -> Self { 167 Self { 168 active: Vec::new(), 169 events: HashMap::new(), 170 config: config, 171 } 172 } 173 174 pub fn add_events(&mut self, slug: String, events: Vec<Event>) { 175 self.events.insert(slug, events); 176 debug!("Inserted new events: {:?}", self.events); 177 } 178 179 pub fn set_active(&mut self, slug: String) { 180 info!("Inserting new active: '{}'", slug); 181 if !self.active.contains(&slug) { 182 self.active.push(slug); 183 } 184 } 185 186 pub fn unset_active(&mut self, slug: &str) { 187 info!("Removing active: '{}'", slug); 188 if let Some(pos) = self.active.iter().position(|x| x == slug) { 189 self.active.remove(pos); 190 } 191 } 192 193 fn get_events_bounds( 194 &self, 195 events: &Vec<&Event>, 196 selected: Option<usize>, 197 offset: usize, 198 max_height: usize, 199 ) -> (usize, usize) { 200 let offset = offset.min(events.len().saturating_sub(1)); 201 202 let mut first_visible_index = offset; 203 let mut last_visible_index = offset; 204 205 let mut height_from_offset = 0; 206 207 let mut last_date: Option<NaiveDate> = None; 208 209 for event in events.iter().skip(offset) { 210 if height_from_offset + EVENT_HEIGHT > max_height { 211 break; 212 } 213 214 let current_date: NaiveDate = event.start_time.date_naive(); 215 216 if Some(current_date) != last_date { 217 if height_from_offset + DATE_HEIGHT + EVENT_HEIGHT > max_height { 218 break; 219 } 220 height_from_offset += DATE_HEIGHT; 221 last_date = Some(current_date); 222 } 223 height_from_offset += EVENT_HEIGHT; 224 last_visible_index += 1; 225 } 226 227 let index_to_display = selected.unwrap_or(first_visible_index); 228 229 while index_to_display >= last_visible_index { 230 let date: NaiveDate = events[last_visible_index].start_time.date_naive(); 231 232 if Some(date) != last_date { 233 height_from_offset = height_from_offset.saturating_add(DATE_HEIGHT); 234 last_date = Some(date); 235 } 236 237 height_from_offset = height_from_offset.saturating_add(EVENT_HEIGHT); 238 last_visible_index += 1; 239 240 while height_from_offset > max_height { 241 let first_date = events[first_visible_index].start_time.date_naive(); 242 243 let second_last_date = if first_visible_index + 1 <= last_visible_index { 244 Some(events[first_visible_index + 1].start_time.date_naive()) 245 } else { 246 None 247 }; 248 249 if Some(first_date) != second_last_date { 250 height_from_offset = height_from_offset.saturating_sub(DATE_HEIGHT); 251 } 252 253 height_from_offset = height_from_offset.saturating_sub(EVENT_HEIGHT); 254 first_visible_index += 1; 255 } 256 } 257 258 while index_to_display < first_visible_index { 259 let first_date = events[first_visible_index - 1].start_time.date_naive(); 260 261 if first_date != events[first_visible_index].start_time.date_naive() { 262 height_from_offset = height_from_offset.saturating_add(DATE_HEIGHT); 263 } 264 265 height_from_offset = height_from_offset.saturating_add(EVENT_HEIGHT); 266 first_visible_index -= 1; 267 268 while height_from_offset > max_height { 269 last_visible_index -= 1; 270 let last_date = events[last_visible_index].start_time.date_naive(); 271 if last_date != events[last_visible_index - 1].start_time.date_naive() { 272 height_from_offset = height_from_offset.saturating_sub(DATE_HEIGHT); 273 } 274 height_from_offset = height_from_offset.saturating_sub(EVENT_HEIGHT); 275 } 276 } 277 278 (first_visible_index, last_visible_index) 279 } 280} 281 282const DATE_HEIGHT: usize = 2; 283const EVENT_HEIGHT: usize = 2; 284 285impl StatefulWidgetRef for &Events { 286 type State = ScheduleState; 287 288 fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { 289 if area.is_empty() { 290 return; 291 } 292 293 let styles = &self.config.style; 294 295 let mut events: Vec<&Event> = self 296 .events 297 .iter() 298 .filter(|(slug, _)| self.active.contains(slug)) 299 .flat_map(|(_, events)| events.iter()) 300 .collect(); 301 302 let inner_area = { 303 if let (Some(block), Some(set)) = (styles.border, styles.border_set) { 304 let border_style = if state.focused { 305 styles.highlight.bg(Color::Reset) 306 } else { 307 styles.default 308 }; 309 let block = Block::new() 310 .borders(Borders::all()) 311 .border_type(block) 312 .border_style(border_style); 313 block.render_ref(area, buf); 314 let mut inner = block.inner(area); 315 if inner.height >= 2 { 316 let hor = set.horizontal; 317 let left = set.vertical_right; 318 let right = set.vertical_left; 319 320 let title_area: Rect = Rect { 321 x: area.left(), 322 y: area.top() + 2, 323 width: area.width, 324 height: 1 as u16, 325 }; 326 327 let title_line = Line::from(format!( 328 "{}{}{}", 329 left, 330 hor.repeat(area.width.saturating_sub(2) as usize), 331 right 332 )) 333 .style(border_style); 334 title_line.render_ref(title_area, buf); 335 336 let total_events: Vec<&Event> = self 337 .events 338 .iter() 339 .flat_map(|(_, events)| events.iter()) 340 .collect(); 341 342 let content = format!("({}/{})", events.len(), total_events.len()); 343 344 if area.width as usize >= content.len() + 4 { 345 let showing_area: Rect = Rect { 346 x: title_area.x + area.width.saturating_sub(content.len() as u16 + 2), 347 y: title_area.y, 348 width: title_area.width.saturating_sub(4).min(content.len() as u16), 349 height: 1 as u16, 350 }; 351 352 let showing_header = 353 Line::from(content).right_aligned().style(styles.highlight); 354 showing_header.render_ref(showing_area, buf); 355 } 356 357 let title_area: Rect = Rect { 358 x: area.left() + 1, 359 y: area.top() + 1, 360 width: area.width.saturating_sub(2), 361 height: 1 as u16, 362 }; 363 364 let title = Line::from("Schedule") 365 .centered() 366 .style(styles.highlight.bg(Color::Reset)); 367 title.render_ref(title_area, buf); 368 369 inner.y += 2; 370 inner.height = inner.height.saturating_sub(2); 371 } else { 372 inner.y += 1; 373 inner.height = inner.height.saturating_sub(1); 374 } 375 inner 376 } else { 377 area 378 } 379 }; 380 if inner_area.is_empty() { 381 return; 382 } 383 384 Clear.render(inner_area, buf); 385 386 events.sort_by_key(|event| event.start_time); 387 388 if events.is_empty() { 389 state.selected = None; 390 return; 391 } 392 393 // If the selected index is out of bounds, set it to the last item 394 if state.selected.is_some_and(|s| s >= events.len()) { 395 state.select(Some(events.len().saturating_sub(1))); 396 } 397 398 let max_height = inner_area.height as usize; 399 400 let (first_visible_index, _) = 401 self.get_events_bounds(&events, state.selected, state.offset, max_height); 402 403 state.offset = first_visible_index; 404 405 let mut current_height: u16 = 0; 406 let mut last_date: Option<NaiveDate> = None; 407 408 let hor_layout = Layout::horizontal([ 409 Constraint::Length(3), // - or * 410 Constraint::Length(5), // time 411 Constraint::Min(4), // team0 412 Constraint::Length(4), // vs 413 Constraint::Min(4), // team1 414 Constraint::Length(11), // empty 415 ]) 416 .split(inner_area); 417 418 let hor = if let Some(set) = styles.border_set { 419 set.horizontal 420 } else { 421 line::HORIZONTAL 422 }; 423 424 let date_header = 425 Line::from(format!("{}", hor.repeat(inner_area.width as usize))).style(styles.default); 426 427 for (i, event) in events.iter().enumerate().skip(state.offset) { 428 let date: NaiveDate = event.start_time.date_naive(); 429 430 // If new date, render date header 431 if Some(date) != last_date { 432 if last_date != None { 433 if current_height as usize + 1 > max_height { 434 break; 435 } 436 let date_area: Rect = Rect { 437 x: inner_area.left(), 438 y: inner_area.top() + current_height, 439 width: inner_area.width, 440 height: 1 as u16, 441 }; 442 443 date_header.render_ref(date_area, buf); 444 current_height += 1; 445 } 446 447 if current_height as usize + 1 > max_height { 448 break; 449 } 450 451 let style = if state 452 .selected 453 .is_some_and(|s| events[s].start_time.date_naive() == date) 454 { 455 styles.selected 456 } else { 457 styles.highlight.bg(Color::Reset) 458 }; 459 460 let date_line = Line::from(event.start_time.format("%A - %d %B").to_string()) 461 .right_aligned() 462 .style(style); 463 464 let date_area: Rect = Rect { 465 x: inner_area.left() 466 + (inner_area 467 .width 468 .saturating_sub(date_line.width() as u16 + 1)), 469 y: inner_area.top() + current_height, 470 width: date_line.width().min(inner_area.width as usize) as u16, 471 height: 1 as u16, 472 }; 473 current_height += 1; 474 date_line.render(date_area, buf); 475 last_date = Some(date); 476 } 477 478 if current_height as usize + 1 > max_height { 479 break; 480 } 481 482 let event_top_layout: Rc<[Rect]> = hor_layout 483 .iter() 484 .map(|r| Rect { 485 x: r.x, 486 y: inner_area.top() + current_height, 487 width: r.width, 488 height: 1, 489 }) 490 .collect(); 491 492 let style = if state.selected.is_some_and(|s| s == i) && state.focused { 493 styles.highlight 494 } else { 495 styles.default 496 }; 497 498 let (mut team0, mut team1) = 499 if event_top_layout[2].width > 30 && event_top_layout[4].width > 30 { 500 (event.teams[0].name.clone(), event.teams[1].name.clone()) 501 } else { 502 (event.teams[0].short.clone(), event.teams[1].short.clone()) 503 }; 504 505 let mut style0 = style; 506 let mut style1 = style; 507 508 if state.spoil_results && !matches!(event.state, MatchState::Unstarted(_)) { 509 (team0, team1) = match &event.result { 510 Some(res) => { 511 if matches!(event.state, MatchState::Completed(_)) { 512 if res.game_wins.0 > res.game_wins.1 { 513 if let Some(style_winner) = styles.winner { 514 style0 = style_winner; 515 } 516 if let Some(style_loser) = styles.loser { 517 style1 = style_loser.bg(Color::Reset); 518 } 519 } else if res.game_wins.1 > res.game_wins.0 { 520 if let Some(style_winner) = styles.winner { 521 style1 = style_winner.bg(Color::Reset); 522 } 523 if let Some(style_loser) = styles.loser { 524 style0 = style_loser.bg(Color::Reset); 525 } 526 } 527 } 528 ( 529 format!("{} - {}", res.game_wins.0, team0), 530 format!("{} - {}", team1, res.game_wins.1), 531 ) 532 } 533 None => (team0, team1), 534 }; 535 } 536 537 if state.selected.is_some_and(|s| s == i) && state.focused { 538 style0.bg = styles.highlight.bg; 539 style1.bg = styles.highlight.bg; 540 } 541 542 if !state.spoil_matches && matches!(event.state, MatchState::Unstarted(_)) { 543 if event.teams[0].name != "TBD" { 544 team0 = "???".to_string(); 545 } 546 if event.teams[1].name != "TBD" { 547 team1 = "???".to_string(); 548 } 549 } 550 551 Text::from(if state.selected.is_some_and(|s| s == i) { 552 " * " 553 } else { 554 " - " 555 }) 556 .style(style) 557 .render(event_top_layout[0], buf); 558 Text::from(event.start_time.format("%H:%M").to_string()) 559 .style(style) 560 .add_modifier(Modifier::BOLD) 561 .left_aligned() 562 .render(event_top_layout[1], buf); 563 Text::from(team0) 564 .style(style0) 565 .right_aligned() 566 .render(event_top_layout[2], buf); 567 Text::from(" vs ") 568 .style(style) 569 .centered() 570 .render(event_top_layout[3], buf); 571 Text::from(team1) 572 .style(style1) 573 .left_aligned() 574 .render(event_top_layout[4], buf); 575 Text::from(event.state.get_string()) 576 .style(style) 577 .right_aligned() 578 .render(event_top_layout[5], buf); 579 current_height += 1; 580 581 if current_height as usize + 1 > max_height { 582 break; 583 } 584 585 let event_low_area = Rect { 586 x: inner_area.left(), 587 y: inner_area.top() + current_height, 588 width: inner_area.width, 589 height: 1, 590 }; 591 592 Text::from(format!( 593 " {} {}", 594 event.strategy.strat_type.get_string(), 595 event.strategy.count 596 )) 597 .left_aligned() 598 .style(style) 599 .render(event_low_area, buf); 600 601 Text::from(format!( 602 "{} - {}", 603 event.block_name.to_owned(), 604 event.league_name, 605 )) 606 .right_aligned() 607 .style(style) 608 .render(event_low_area, buf); 609 610 current_height += 1; 611 } 612 } 613}