src/items/singleitem.rs

1057 lines · 38829 bytes

   1use std::fs;
   2
   3use super::ItemInfo;
   4use crate::{
   5    config::*,
   6    global::{functions::*, structs::*, traits::Collection},
   7};
   8use home::home_dir;
   9use ratatui::{
  10    layout::{Constraint, Rect},
  11    style::Style,
  12    widgets::{Block, Borders},
  13};
  14use tui_additions::{
  15    framework::{FrameworkClean, FrameworkItem},
  16    widgets::{Grid, TextList},
  17};
  18
  19impl Default for SingleItem {
  20    fn default() -> Self {
  21        Self {
  22            item: None,
  23            iteminfo: ItemInfo::default(),
  24            grid: Grid::new(
  25                vec![Constraint::Percentage(30), Constraint::Percentage(70)],
  26                vec![Constraint::Percentage(100)],
  27            )
  28            .unwrap(),
  29            r#type: SingleItemType::None,
  30        }
  31    }
  32}
  33
  34/// main item in the `SingleItem(_)` page
  35#[derive(Clone)]
  36pub struct SingleItem {
  37    pub item: Option<Item>,
  38    pub iteminfo: ItemInfo,
  39    pub grid: Grid,
  40    pub r#type: SingleItemType,
  41}
  42
  43/// variations that the struct can hold
  44#[derive(Clone)]
  45pub enum SingleItemType {
  46    None,
  47    Video(SingleVideoItem),
  48    Playlist(Box<SinglePlaylistItem>),
  49}
  50
  51#[derive(Clone)]
  52pub struct SingleVideoItem {
  53    pub textlist: TextList,
  54    pub commands: Vec<(String, String)>,
  55}
  56
  57#[derive(Clone)]
  58pub struct SinglePlaylistItem {
  59    pub commands_view: TextList,
  60    pub videos_view: TextList,
  61    pub commands: Vec<(String, String)>,
  62    pub is_commands_view: bool,
  63    pub hovered_video: ItemInfo,
  64}
  65
  66impl SingleVideoItem {
  67    pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig, id: &str) -> Self {
  68        let saved = (|| -> Option<()> {
  69            fs::read_dir(
  70                home_dir()
  71                    .unwrap()
  72                    .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
  73            )
  74            .ok()?
  75            .filter_map(|entry| Some(entry.ok()?.path().file_stem()?.to_os_string()))
  76            .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))?;
  77            Some(())
  78        })()
  79        .is_some();
  80        if saved {
  81            Self::new_with_map(
  82                commands
  83                    .saved_video
  84                    .clone()
  85                    .into_iter()
  86                    .map(|(display, command)| (display, command))
  87                    .collect(),
  88            )
  89        } else {
  90            Self::new_with_map(
  91                commands
  92                    .video
  93                    .clone()
  94                    .into_iter()
  95                    .map(|(display, command)| (display, command))
  96                    .collect(),
  97            )
  98        }
  99    }
 100
 101    pub fn new_with_map(commands: Vec<(String, String)>) -> Self {
 102        Self {
 103            textlist: TextList::default()
 104                .items(
 105                    &commands
 106                        .iter()
 107                        .map(|command| &command.0)
 108                        .collect::<Vec<_>>(),
 109                )
 110                .unwrap(),
 111            commands,
 112        }
 113    }
 114
 115    /// find all occurances of ${provider}
 116    pub fn update_provider(&mut self) -> Vec<usize> {
 117        self.commands
 118            .iter()
 119            .enumerate()
 120            .filter(|(_index, (display, _command))| display.contains("${provider}"))
 121            .map(|(index, _)| index)
 122            .collect()
 123    }
 124
 125    pub fn update_appearance(
 126        &mut self,
 127        appearance: &AppearanceConfig,
 128        iteminfo: &tui_additions::framework::ItemInfo,
 129    ) {
 130        self.textlist.set_border_type(appearance.borders);
 131        self.textlist
 132            .set_style(Style::default().fg(appearance.colors.text));
 133
 134        if iteminfo.selected {
 135            self.textlist
 136                .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
 137            self.textlist
 138                .set_selected_style(Style::default().fg(appearance.colors.text_special));
 139        } else {
 140            self.textlist
 141                .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
 142            self.textlist
 143                .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
 144        }
 145    }
 146
 147    /// creates a hashmap from `self`, containing info of the current item
 148    pub fn inflate_load(
 149        &self,
 150        mainconfig: &MainConfig,
 151        status: &Status,
 152        item: &Item,
 153    ) -> Vec<(String, String)> {
 154        let video_item = item.fullvideo().unwrap();
 155
 156        vec![
 157            (
 158                String::from("url"),
 159                match status.provider {
 160                    Provider::Invidious => format!(
 161                        "{}/watch?v={}",
 162                        mainconfig.invidious_instance, video_item.id
 163                    ),
 164                    Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
 165                },
 166            ),
 167            (String::from("id"), video_item.id.clone()),
 168            (
 169                String::from("embed-url"),
 170                match status.provider {
 171                    Provider::Invidious => {
 172                        format!("{}/embed/{}", mainconfig.invidious_instance, video_item.id)
 173                    }
 174                    Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
 175                },
 176            ),
 177            (String::from("channel-id"), video_item.channel_id.clone()),
 178            (String::from("title"), video_item.title.clone()),
 179            (
 180                String::from("channel-url"),
 181                match status.provider {
 182                    Provider::YouTube => {
 183                        format!("https://www.youtube.com/channel/{}", video_item.channel_id)
 184                    }
 185                    Provider::Invidious => format!(
 186                        "{}/channel/{}",
 187                        mainconfig.invidious_instance, video_item.channel_id
 188                    ),
 189                },
 190            ),
 191        ]
 192    }
 193}
 194
 195impl SinglePlaylistItem {
 196    pub fn new(
 197        commands: &CommandsConfig,
 198        mainconfig: &MainConfig,
 199        id: &str,
 200        playlist_items: &[Item],
 201    ) -> Self {
 202        let saved = (|| -> Option<()> {
 203            fs::read_dir(
 204                home_dir()
 205                    .unwrap()
 206                    .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
 207            )
 208            .ok()?
 209            .filter_map(|entry| Some(entry.ok()?.path().file_stem()?.to_os_string()))
 210            .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))?;
 211            Some(())
 212        })()
 213        .is_some();
 214        if saved {
 215            Self::new_with_map(
 216                commands
 217                    .saved_playlist
 218                    .clone()
 219                    .into_iter()
 220                    .map(|(display, command)| (display, command))
 221                    .collect(),
 222                playlist_items,
 223            )
 224        } else {
 225            Self::new_with_map(
 226                commands
 227                    .playlist
 228                    .clone()
 229                    .into_iter()
 230                    .map(|(display, command)| (display, command))
 231                    .collect(),
 232                playlist_items,
 233            )
 234        }
 235    }
 236
 237    pub fn new_with_map(commands: Vec<(String, String)>, playlist_items: &[Item]) -> Self {
 238        let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
 239            None
 240        } else {
 241            Some(playlist_items[0].clone())
 242        });
 243
 244        Self {
 245            commands_view: TextList::default()
 246                .items(
 247                    &commands
 248                        .iter()
 249                        .map(|command| &command.0)
 250                        .collect::<Vec<_>>(),
 251                )
 252                .unwrap(),
 253            videos_view: TextList::default()
 254                .items(&{
 255                    let mut items = vec!["Switch view"];
 256                    items.extend(
 257                        playlist_items
 258                            .iter()
 259                            .map(|item| item.minivideo().unwrap().title.as_str()),
 260                    );
 261                    items
 262                })
 263                .unwrap(),
 264            commands,
 265            hovered_video,
 266            is_commands_view: true,
 267        }
 268    }
 269
 270    pub fn update_appearance(
 271        &mut self,
 272        appearance: &AppearanceConfig,
 273        iteminfo: &tui_additions::framework::ItemInfo,
 274        grid: &mut Grid,
 275    ) {
 276        if self.is_commands_view {
 277            grid.widths = vec![Constraint::Percentage(30), Constraint::Percentage(70)];
 278            self.commands_view.set_border_type(appearance.borders);
 279            self.commands_view
 280                .set_style(Style::default().fg(appearance.colors.text));
 281
 282            if iteminfo.selected {
 283                self.commands_view
 284                    .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
 285                self.commands_view
 286                    .set_selected_style(Style::default().fg(appearance.colors.text_special));
 287            } else {
 288                self.commands_view
 289                    .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
 290                self.commands_view
 291                    .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
 292            }
 293        } else {
 294            grid.widths = if self.videos_view.selected == 0 {
 295                vec![Constraint::Percentage(30), Constraint::Percentage(70)]
 296            } else {
 297                vec![
 298                    Constraint::Percentage(30),
 299                    Constraint::Percentage(40),
 300                    Constraint::Percentage(30),
 301                ]
 302            };
 303            self.videos_view.set_border_type(appearance.borders);
 304            self.videos_view
 305                .set_style(Style::default().fg(appearance.colors.text));
 306
 307            if iteminfo.selected {
 308                self.videos_view
 309                    .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
 310                self.videos_view
 311                    .set_selected_style(Style::default().fg(appearance.colors.text_special));
 312            } else {
 313                self.videos_view
 314                    .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
 315                self.videos_view
 316                    .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
 317            }
 318        }
 319    }
 320
 321    /// find all occurances of ${provider}
 322    pub fn update_provider(&mut self) -> Vec<usize> {
 323        self.commands
 324            .iter()
 325            .enumerate()
 326            .filter(|(_index, (display, _command))| display.contains("${provider}"))
 327            .map(|(index, _)| index)
 328            .collect()
 329    }
 330
 331    /// creates a hashmap from `self`, containing info of the current item
 332    pub fn inflate_load(&self, item: &Item) -> Vec<(String, String)> {
 333        let playlist_item = item.fullplaylist().unwrap();
 334
 335        vec![
 336            (String::from("id"), playlist_item.id.clone()),
 337            (String::from("channel-id"), playlist_item.channel_id.clone()),
 338            (String::from("title"), playlist_item.title.clone()),
 339            (
 340                String::from("all-ids"),
 341                playlist_item
 342                    .videos
 343                    .iter()
 344                    .map(|video| video.minivideo().unwrap().id.as_str())
 345                    .collect::<Vec<&str>>()
 346                    .join(" "),
 347            ),
 348        ]
 349    }
 350}
 351
 352impl SingleItemType {
 353    /// self is none
 354    pub fn is_none(&self) -> bool {
 355        matches!(self, Self::None)
 356    }
 357
 358    /// update colours every render
 359    pub fn update_appearance(
 360        &mut self,
 361        appearance: &AppearanceConfig,
 362        iteminfo: &tui_additions::framework::ItemInfo,
 363        grid: &mut Grid,
 364    ) {
 365        match self {
 366            Self::None => {}
 367            Self::Playlist(playlistitem) => {
 368                playlistitem.update_appearance(appearance, iteminfo, grid)
 369            }
 370            Self::Video(videoitem) => videoitem.update_appearance(appearance, iteminfo),
 371        }
 372    }
 373
 374    pub fn inflate_load(
 375        &self,
 376        mainconfig: &MainConfig,
 377        status: &Status,
 378        item: &Option<Item>,
 379    ) -> Vec<(String, String)> {
 380        let item = if let Some(item) = item.as_ref() {
 381            item
 382        } else {
 383            return Vec::new();
 384        };
 385
 386        match self {
 387            Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item),
 388            Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate_load(item),
 389            Self::None => Vec::new(),
 390        }
 391    }
 392}
 393
 394impl SingleItem {
 395    fn infalte_item_update(
 396        &self,
 397        mainconfig: &MainConfig,
 398        status: &Status,
 399    ) -> Vec<(String, String)> {
 400        if let SingleItemType::Playlist(singleplaylistitem) = &self.r#type {
 401            if singleplaylistitem.videos_view.selected == 0 {
 402                return vec![(String::from("hover-url"), String::from("not avaliable"))];
 403            }
 404            vec![(
 405                String::from("hover-url"),
 406                match &self.item {
 407                    Some(item) => format!(
 408                        "{}/watch?v={}",
 409                        match status.provider {
 410                            Provider::YouTube => "https://youtube.com",
 411                            Provider::Invidious => &mainconfig.invidious_instance,
 412                        },
 413                        item.fullplaylist().unwrap().videos
 414                            [singleplaylistitem.videos_view.selected - 1]
 415                            .minivideo()
 416                            .unwrap()
 417                            .id
 418                    ),
 419                    None => String::from("not avaliable"),
 420                },
 421            )]
 422        } else {
 423            vec![(String::from("hover-url"), String::from("not avaliable"))]
 424        }
 425    }
 426    /// update colours and layout every render
 427    fn update_appearance(
 428        &mut self,
 429        appearance: &AppearanceConfig,
 430        iteminfo: &tui_additions::framework::ItemInfo,
 431    ) {
 432        self.grid.set_border_type(appearance.borders);
 433
 434        if iteminfo.selected {
 435            self.grid
 436                .set_border_style(Style::default().fg(appearance.colors.outline_selected));
 437        } else if iteminfo.hover {
 438            self.grid
 439                .set_border_style(Style::default().fg(appearance.colors.outline_hover));
 440        } else {
 441            self.grid
 442                .set_border_style(Style::default().fg(appearance.colors.outline));
 443        }
 444
 445        self.r#type
 446            .update_appearance(appearance, iteminfo, &mut self.grid);
 447    }
 448
 449    /// update hover item preview
 450    fn update(&mut self) {
 451        if let SingleItemType::Playlist(singleplaylistitem) = &mut self.r#type {
 452            let SinglePlaylistItem {
 453                hovered_video,
 454                videos_view,
 455                ..
 456            } = &mut **singleplaylistitem;
 457            if videos_view.items.is_empty() || videos_view.selected == 0 {
 458                hovered_video.item = None;
 459                return;
 460            }
 461
 462            if hovered_video.item.is_none()
 463                || self.item.as_ref().unwrap().fullplaylist().unwrap().videos
 464                    [videos_view.selected - 1]
 465                    .id()
 466                    != hovered_video.item.as_ref().unwrap().id()
 467            {
 468                hovered_video.item = Some(
 469                    self.item.as_ref().unwrap().fullplaylist().unwrap().videos
 470                        [videos_view.selected - 1]
 471                        .clone(),
 472                );
 473            }
 474        }
 475    }
 476
 477    /// handle enter presses
 478    fn select_at_cursor(
 479        &mut self,
 480        framework: &mut FrameworkClean,
 481        // info: tui_additions::framework::ItemInfo,
 482    ) {
 483        match &mut self.r#type {
 484            SingleItemType::Video(singlevideoitem) => {
 485                let command_string = singlevideoitem.commands[singlevideoitem.textlist.selected]
 486                    .1
 487                    .clone();
 488
 489                // check if the command starts with an ':' which case should be captured
 490                framework
 491                    .data
 492                    .state
 493                    .get_mut::<Tasks>()
 494                    .unwrap()
 495                    .priority
 496                    .push(Task::Command(apply_envs(command_string)));
 497            }
 498            SingleItemType::Playlist(singleplaylistitem) => {
 499                let command_string = singleplaylistitem.commands
 500                    [singleplaylistitem.commands_view.selected]
 501                    .1
 502                    .clone();
 503
 504                // checks for special cases
 505                match command_string.as_str() {
 506                    "%switch-view%" => {
 507                        singleplaylistitem.is_commands_view = !singleplaylistitem.is_commands_view;
 508                        // self.update_appearance(
 509                        //     framework.data.global.get::<AppearanceConfig>().unwrap(),
 510                        //     &info,
 511                        // );
 512                        *framework.data.global.get_mut::<Message>().unwrap() =
 513                            Message::Success(String::from("Switched view"));
 514                    }
 515                    _ => {
 516                        // check if the command starts with an ':' which case should be captured
 517                        framework
 518                            .data
 519                            .state
 520                            .get_mut::<Tasks>()
 521                            .unwrap()
 522                            .priority
 523                            .push(Task::Command(apply_envs(command_string)));
 524                    }
 525                };
 526            }
 527            _ => return,
 528        }
 529
 530        framework
 531            .data
 532            .state
 533            .get_mut::<Tasks>()
 534            .unwrap()
 535            .priority
 536            .push(Task::RenderAll);
 537    }
 538}
 539
 540impl FrameworkItem for SingleItem {
 541    fn render(
 542        &mut self,
 543        frame: &mut ratatui::Frame<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
 544        framework: &mut tui_additions::framework::FrameworkClean,
 545        area: ratatui::layout::Rect,
 546        popup_render: bool,
 547        info: tui_additions::framework::ItemInfo,
 548    ) {
 549        let status = framework.data.global.get::<Status>().unwrap();
 550        if popup_render {
 551            return;
 552        }
 553
 554        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
 555
 556        if self.item.is_none() {
 557            frame.render_widget(
 558                Block::default()
 559                    .borders(Borders::ALL)
 560                    .border_type(appearance.borders),
 561                area,
 562            );
 563            return;
 564        }
 565
 566        if status.provider_updated {
 567            set_envs(
 568                self.infalte_item_update(
 569                    framework.data.global.get::<MainConfig>().unwrap(),
 570                    status,
 571                )
 572                .into_iter(),
 573                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
 574            );
 575        }
 576
 577        self.update_appearance(appearance, &info);
 578
 579        let chunks = self.grid.chunks(area).unwrap()[0].clone();
 580
 581        frame.render_widget(self.grid.clone(), area);
 582
 583        match &mut self.r#type {
 584            SingleItemType::Video(typeinfo) => {
 585                // 2 by 1 grid, item info in the first cell and textlist at the second
 586                if status.provider_updated {
 587                    typeinfo.update_provider().into_iter().for_each(|index| {
 588                        typeinfo.textlist.items[index] = typeinfo.commands[index].0.clone().replace(
 589                            "${provider}",
 590                            framework
 591                                .data
 592                                .global
 593                                .get::<Status>()
 594                                .unwrap()
 595                                .provider
 596                                .as_str(),
 597                        )
 598                    });
 599                }
 600                self.iteminfo
 601                    .render(frame, framework, chunks[0], popup_render, info);
 602                typeinfo.textlist.set_height(chunks[1].height);
 603                frame.render_widget(typeinfo.textlist.clone(), chunks[1]);
 604            }
 605            SingleItemType::Playlist(typeinfo) => {
 606                // 3 by 1 grid if hovering a video inside the playlist
 607                // if not then 2 by 1
 608                //
 609                // item info in the first cell, textlists in the second, hovering video on 3rd (if
 610                // present)
 611                if typeinfo.is_commands_view {
 612                    if status.provider_updated {
 613                        typeinfo.update_provider().into_iter().for_each(|index| {
 614                            typeinfo.commands_view.items[index] =
 615                                typeinfo.commands[index].0.clone().replace(
 616                                    "${provider}",
 617                                    framework
 618                                        .data
 619                                        .global
 620                                        .get::<Status>()
 621                                        .unwrap()
 622                                        .provider
 623                                        .as_str(),
 624                                )
 625                        });
 626                    }
 627                    typeinfo.commands_view.set_height(chunks[1].height);
 628                    frame.render_widget(typeinfo.commands_view.clone(), chunks[1]);
 629                } else {
 630                    typeinfo.videos_view.set_height(chunks[1].height);
 631                    frame.render_widget(typeinfo.videos_view.clone(), chunks[1]);
 632
 633                    if typeinfo.videos_view.selected != 0 {
 634                        typeinfo.hovered_video.render(
 635                            frame,
 636                            framework,
 637                            chunks[2],
 638                            popup_render,
 639                            info,
 640                        );
 641                    }
 642                }
 643                self.iteminfo
 644                    .render(frame, framework, chunks[0], popup_render, info);
 645            }
 646            SingleItemType::None => {}
 647        }
 648    }
 649
 650    fn load_item(
 651        &mut self,
 652        framework: &mut tui_additions::framework::FrameworkClean,
 653        _info: tui_additions::framework::ItemInfo,
 654    ) -> Result<(), Box<dyn std::error::Error>> {
 655        *self = Self::default();
 656
 657        let page = framework.data.state.get::<Page>().unwrap();
 658
 659        let r#type = if let Page::SingleItem(r#type) = page {
 660            r#type
 661        } else {
 662            unreachable!("item `SingleItem` cannot be used in {page:?}")
 663        };
 664
 665        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
 666        // load items using the invidious api
 667        // gets the item that it needs to load from `data.state.Page`
 668        let (item, r#type) = match r#type {
 669            SingleItemPage::Video(id) => {
 670                let home_dir = home_dir().unwrap();
 671                let path = home_dir.join(format!(".cache/youtube-tui/info/{id}.json"));
 672
 673                let video = if path.exists() {
 674                    serde_json::from_str(&fs::read_to_string(path)?)?
 675                } else {
 676                    load_video(
 677                        &framework.data.global.get::<InvidiousClient>().unwrap().0,
 678                        id,
 679                        mainconfig,
 680                    )?
 681                };
 682                (
 683                    video,
 684                    SingleItemType::Video(SingleVideoItem::new(
 685                        framework.data.global.get::<CommandsConfig>().unwrap(),
 686                        mainconfig,
 687                        id,
 688                    )),
 689                )
 690            }
 691            SingleItemPage::Playlist(id) => {
 692                let path = home_dir()
 693                    .unwrap()
 694                    .join(format!(".cache/youtube-tui/info/{id}.json"));
 695
 696                let playlist = if path.exists() {
 697                    serde_json::from_str(&fs::read_to_string(path)?)?
 698                } else {
 699                    load_playlist(
 700                        &framework.data.global.get::<InvidiousClient>().unwrap().0,
 701                        id,
 702                        mainconfig,
 703                    )?
 704                };
 705                let r#type = SingleItemType::Playlist(
 706                    SinglePlaylistItem::new(
 707                        framework.data.global.get::<CommandsConfig>().unwrap(),
 708                        mainconfig,
 709                        id,
 710                        &playlist.fullplaylist().unwrap().videos,
 711                    )
 712                    .into(),
 713                );
 714
 715                (playlist, r#type)
 716            }
 717        };
 718
 719        self.item = Some(item);
 720        self.r#type = r#type;
 721        self.iteminfo.item = self.item.clone();
 722
 723        if let Some(item) = &self.item {
 724            if item.is_unknown() {
 725                return Ok(());
 726            }
 727
 728            let item = item.clone();
 729            let max_watch_history = framework
 730                .data
 731                .global
 732                .get::<MainConfig>()
 733                .unwrap()
 734                .max_watch_history;
 735
 736            // push to watch history
 737            let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
 738            watch_history.push(item, Some(max_watch_history))?;
 739            watch_history.save()?;
 740        }
 741
 742        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
 743        // need to update provider every time the item loads or else it will display `${provider}`
 744        // instead of the actual provider (e.g. `YouTube`)
 745
 746        set_envs(
 747            self.r#type
 748                .inflate_load(
 749                    mainconfig,
 750                    framework.data.global.get::<Status>().unwrap(),
 751                    &self.item,
 752                )
 753                .into_iter(),
 754            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
 755        );
 756
 757        set_envs(
 758            self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
 759                .into_iter(),
 760            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
 761        );
 762
 763        Ok(())
 764    }
 765
 766    fn key_event(
 767        &mut self,
 768        framework: &mut tui_additions::framework::FrameworkClean,
 769        key: crossterm::event::KeyEvent,
 770        info: tui_additions::framework::ItemInfo,
 771    ) -> Result<(), Box<dyn std::error::Error>> {
 772        // discard any key inputs if `self.is_none()` becuase nothing can happen if self is none
 773        if self.r#type.is_none() {
 774            return Ok(());
 775        }
 776
 777        let action = if let Some(action) = framework
 778            .data
 779            .global
 780            .get::<KeyBindingsConfig>()
 781            .unwrap()
 782            .get(key)
 783        {
 784            action
 785        } else {
 786            return Ok(());
 787        };
 788
 789        let updated = match &mut self.r#type {
 790            SingleItemType::Video(singlevideoitem) => match action {
 791                // move the cursor in the textlist, only update the screen if it is changed
 792                KeyAction::MoveUp => singlevideoitem.textlist.up().is_ok(),
 793                KeyAction::MoveDown => singlevideoitem.textlist.down().is_ok(),
 794                KeyAction::MoveLeft | KeyAction::First => singlevideoitem.textlist.first().is_ok(),
 795                KeyAction::MoveRight | KeyAction::End => singlevideoitem.textlist.last().is_ok(),
 796                KeyAction::Select => {
 797                    self.select_at_cursor(framework);
 798                    return Ok(());
 799                }
 800                _ => false,
 801            },
 802            SingleItemType::Playlist(singleplaylistitem) => {
 803                // there are 2 possible states in a playlist item
 804                // they are handelled separately
 805                if singleplaylistitem.is_commands_view {
 806                    match action {
 807                        KeyAction::MoveUp => singleplaylistitem.commands_view.up().is_ok(),
 808                        KeyAction::MoveDown => singleplaylistitem.commands_view.down().is_ok(),
 809                        KeyAction::MoveLeft | KeyAction::First => {
 810                            singleplaylistitem.commands_view.first().is_ok()
 811                        }
 812                        KeyAction::MoveRight | KeyAction::End => {
 813                            singleplaylistitem.commands_view.last().is_ok()
 814                        }
 815                        KeyAction::Select => {
 816                            self.select_at_cursor(framework);
 817                            return Ok(());
 818                        }
 819                        _ => false,
 820                    }
 821                } else {
 822                    let updated = match action {
 823                        // checks if it is updated, if it is and selected is not 0 (is hovering on
 824                        // a video), then also need to update the iteminfo
 825                        KeyAction::MoveUp => {
 826                            if singleplaylistitem.videos_view.selected == 1 {
 827                                // going from a hovering video to not hovering will make the image
 828                                // stay on the screen, therefore it needs to be removed by clearing
 829                                // the screen
 830                                framework
 831                                    .data
 832                                    .state
 833                                    .get_mut::<Tasks>()
 834                                    .unwrap()
 835                                    .priority
 836                                    .push(Task::ClearPage);
 837                            } else if singleplaylistitem.videos_view.selected == 0 {
 838                                return Ok(());
 839                            }
 840
 841                            let updated = singleplaylistitem.videos_view.up().is_ok();
 842                            if singleplaylistitem.videos_view.selected != 0 {
 843                                singleplaylistitem.hovered_video.item = Some(
 844                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 845                                        [singleplaylistitem.videos_view.selected - 1]
 846                                        .clone(),
 847                                );
 848                            }
 849                            updated
 850                        }
 851                        KeyAction::MoveDown => {
 852                            if singleplaylistitem.videos_view.selected
 853                                == singleplaylistitem.videos_view.items.len() - 1
 854                            {
 855                                return Ok(());
 856                            }
 857
 858                            let updated = singleplaylistitem.videos_view.down().is_ok();
 859                            if updated && singleplaylistitem.videos_view.selected != 0 {
 860                                singleplaylistitem.hovered_video.item = Some(
 861                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 862                                        [singleplaylistitem.videos_view.selected - 1]
 863                                        .clone(),
 864                                );
 865                            }
 866                            updated
 867                        }
 868                        KeyAction::MoveLeft => {
 869                            if singleplaylistitem.videos_view.selected != 0 {
 870                                framework
 871                                    .data
 872                                    .state
 873                                    .get_mut::<Tasks>()
 874                                    .unwrap()
 875                                    .priority
 876                                    .push(Task::ClearPage);
 877                            } else if singleplaylistitem.videos_view.selected == 0 {
 878                                return Ok(());
 879                            }
 880
 881                            let updated = singleplaylistitem.videos_view.first().is_ok();
 882                            singleplaylistitem.hovered_video.item = None;
 883                            updated
 884                        }
 885                        KeyAction::MoveRight => {
 886                            if singleplaylistitem.videos_view.selected
 887                                == singleplaylistitem.videos_view.items.len() - 1
 888                            {
 889                                return Ok(());
 890                            }
 891                            let updated = singleplaylistitem.videos_view.last().is_ok();
 892                            if updated && singleplaylistitem.videos_view.selected != 0 {
 893                                singleplaylistitem.hovered_video.item = Some(
 894                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 895                                        [singleplaylistitem.videos_view.selected - 1]
 896                                        .clone(),
 897                                );
 898                            }
 899                            updated
 900                        }
 901                        KeyAction::Select => {
 902                            if singleplaylistitem.videos_view.selected == 0 {
 903                                singleplaylistitem.is_commands_view =
 904                                    !singleplaylistitem.is_commands_view;
 905                                self.update_appearance(
 906                                    framework.data.global.get::<AppearanceConfig>().unwrap(),
 907                                    &info,
 908                                );
 909                                *framework.data.global.get_mut::<Message>().unwrap() =
 910                                    Message::Success(String::from("Switched view"));
 911                            } else {
 912                                framework
 913                                    .data
 914                                    .state
 915                                    .get_mut::<Tasks>()
 916                                    .unwrap()
 917                                    .priority
 918                                    .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
 919                                        self.item.as_ref().unwrap().fullplaylist()?.videos
 920                                            [singleplaylistitem.videos_view.selected - 1]
 921                                            .minivideo()?
 922                                            .id
 923                                            .clone(),
 924                                    ))));
 925                            }
 926
 927                            true
 928                        }
 929                        _ => false,
 930                    };
 931
 932                    if updated {
 933                        framework
 934                            .data
 935                            .global
 936                            .get_mut::<Status>()
 937                            .unwrap()
 938                            .render_image = true;
 939                        set_envs(
 940                            self.infalte_item_update(
 941                                framework.data.global.get::<MainConfig>().unwrap(),
 942                                framework.data.global.get::<Status>().unwrap(),
 943                            )
 944                            .into_iter(),
 945                            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
 946                        );
 947                    }
 948
 949                    updated
 950                }
 951            }
 952            SingleItemType::None => false,
 953        };
 954
 955        if updated {
 956            framework
 957                .data
 958                .state
 959                .get_mut::<Tasks>()
 960                .unwrap()
 961                .priority
 962                .push(Task::RenderAll);
 963        }
 964
 965        Ok(())
 966    }
 967
 968    fn mouse_event(
 969        &mut self,
 970        framework: &mut FrameworkClean,
 971        x: u16,
 972        y: u16,
 973        _absolute_x: u16,
 974        _absolute_y: u16,
 975    ) -> bool {
 976        let chunk = self
 977            .grid
 978            .chunks(
 979                if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
 980                {
 981                    prev_frame
 982                } else {
 983                    return false;
 984                },
 985            )
 986            .unwrap()[0][1];
 987
 988        if !chunk.intersects(Rect::new(x, y, 1, 1)) {
 989            return false;
 990        }
 991
 992        let textlist = match &mut self.r#type {
 993            SingleItemType::Video(SingleVideoItem { textlist, .. }) => textlist,
 994            SingleItemType::Playlist(singleplaylistitem) => {
 995                if singleplaylistitem.is_commands_view {
 996                    &mut singleplaylistitem.commands_view
 997                } else {
 998                    let y = (y - chunk.y) as usize + singleplaylistitem.videos_view.scroll;
 999                    if singleplaylistitem.videos_view.selected != 0 && y == 0 {
1000                        framework
1001                            .data
1002                            .state
1003                            .get_mut::<Tasks>()
1004                            .unwrap()
1005                            .priority
1006                            .push(Task::ClearPage);
1007                    }
1008                    &mut singleplaylistitem.videos_view
1009                }
1010            }
1011            _ => return false,
1012        };
1013
1014        let y = (y - chunk.y) as usize + textlist.scroll;
1015
1016        // clicking on already selected item
1017        if y == textlist.selected || y == textlist.selected + 2 || y == textlist.selected + 1 {
1018            self.select_at_cursor(framework);
1019            return true;
1020        }
1021
1022        // clicking on rows after the last item
1023        if y > textlist.items.len() + 1 {
1024            return false;
1025        }
1026
1027        // moving the cursor
1028        if y <= textlist.selected {
1029            textlist.selected = y;
1030        }
1031
1032        if y >= textlist.selected + 2 {
1033            textlist.selected = y - 2;
1034        }
1035
1036        self.update();
1037
1038        set_envs(
1039            self.infalte_item_update(
1040                framework.data.global.get::<MainConfig>().unwrap(),
1041                framework.data.global.get::<Status>().unwrap(),
1042            )
1043            .into_iter(),
1044            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
1045        );
1046
1047        // render the new image
1048        framework
1049            .data
1050            .global
1051            .get_mut::<Status>()
1052            .unwrap()
1053            .render_image = true;
1054
1055        true
1056    }
1057}