src/items/singleitem.rs

1053 lines · 38647 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 => singlevideoitem.textlist.first().is_ok(),
 795                KeyAction::MoveRight => 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 => singleplaylistitem.commands_view.first().is_ok(),
 810                        KeyAction::MoveRight => singleplaylistitem.commands_view.last().is_ok(),
 811                        KeyAction::Select => {
 812                            self.select_at_cursor(framework);
 813                            return Ok(());
 814                        }
 815                        _ => false,
 816                    }
 817                } else {
 818                    let updated = match action {
 819                        // checks if it is updated, if it is and selected is not 0 (is hovering on
 820                        // a video), then also need to update the iteminfo
 821                        KeyAction::MoveUp => {
 822                            if singleplaylistitem.videos_view.selected == 1 {
 823                                // going from a hovering video to not hovering will make the image
 824                                // stay on the screen, therefore it needs to be removed by clearing
 825                                // the screen
 826                                framework
 827                                    .data
 828                                    .state
 829                                    .get_mut::<Tasks>()
 830                                    .unwrap()
 831                                    .priority
 832                                    .push(Task::ClearPage);
 833                            } else if singleplaylistitem.videos_view.selected == 0 {
 834                                return Ok(());
 835                            }
 836
 837                            let updated = singleplaylistitem.videos_view.up().is_ok();
 838                            if singleplaylistitem.videos_view.selected != 0 {
 839                                singleplaylistitem.hovered_video.item = Some(
 840                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 841                                        [singleplaylistitem.videos_view.selected - 1]
 842                                        .clone(),
 843                                );
 844                            }
 845                            updated
 846                        }
 847                        KeyAction::MoveDown => {
 848                            if singleplaylistitem.videos_view.selected
 849                                == singleplaylistitem.videos_view.items.len() - 1
 850                            {
 851                                return Ok(());
 852                            }
 853
 854                            let updated = singleplaylistitem.videos_view.down().is_ok();
 855                            if updated && singleplaylistitem.videos_view.selected != 0 {
 856                                singleplaylistitem.hovered_video.item = Some(
 857                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 858                                        [singleplaylistitem.videos_view.selected - 1]
 859                                        .clone(),
 860                                );
 861                            }
 862                            updated
 863                        }
 864                        KeyAction::MoveLeft => {
 865                            if singleplaylistitem.videos_view.selected != 0 {
 866                                framework
 867                                    .data
 868                                    .state
 869                                    .get_mut::<Tasks>()
 870                                    .unwrap()
 871                                    .priority
 872                                    .push(Task::ClearPage);
 873                            } else if singleplaylistitem.videos_view.selected == 0 {
 874                                return Ok(());
 875                            }
 876
 877                            let updated = singleplaylistitem.videos_view.first().is_ok();
 878                            singleplaylistitem.hovered_video.item = None;
 879                            updated
 880                        }
 881                        KeyAction::MoveRight => {
 882                            if singleplaylistitem.videos_view.selected
 883                                == singleplaylistitem.videos_view.items.len() - 1
 884                            {
 885                                return Ok(());
 886                            }
 887                            let updated = singleplaylistitem.videos_view.last().is_ok();
 888                            if updated && singleplaylistitem.videos_view.selected != 0 {
 889                                singleplaylistitem.hovered_video.item = Some(
 890                                    self.item.as_ref().unwrap().fullplaylist()?.videos
 891                                        [singleplaylistitem.videos_view.selected - 1]
 892                                        .clone(),
 893                                );
 894                            }
 895                            updated
 896                        }
 897                        KeyAction::Select => {
 898                            if singleplaylistitem.videos_view.selected == 0 {
 899                                singleplaylistitem.is_commands_view =
 900                                    !singleplaylistitem.is_commands_view;
 901                                self.update_appearance(
 902                                    framework.data.global.get::<AppearanceConfig>().unwrap(),
 903                                    &info,
 904                                );
 905                                *framework.data.global.get_mut::<Message>().unwrap() =
 906                                    Message::Success(String::from("Switched view"));
 907                            } else {
 908                                framework
 909                                    .data
 910                                    .state
 911                                    .get_mut::<Tasks>()
 912                                    .unwrap()
 913                                    .priority
 914                                    .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
 915                                        self.item.as_ref().unwrap().fullplaylist()?.videos
 916                                            [singleplaylistitem.videos_view.selected - 1]
 917                                            .minivideo()?
 918                                            .id
 919                                            .clone(),
 920                                    ))));
 921                            }
 922
 923                            true
 924                        }
 925                        _ => false,
 926                    };
 927
 928                    if updated {
 929                        framework
 930                            .data
 931                            .global
 932                            .get_mut::<Status>()
 933                            .unwrap()
 934                            .render_image = true;
 935                        set_envs(
 936                            self.infalte_item_update(
 937                                framework.data.global.get::<MainConfig>().unwrap(),
 938                                framework.data.global.get::<Status>().unwrap(),
 939                            )
 940                            .into_iter(),
 941                            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
 942                        );
 943                    }
 944
 945                    updated
 946                }
 947            }
 948            SingleItemType::None => false,
 949        };
 950
 951        if updated {
 952            framework
 953                .data
 954                .state
 955                .get_mut::<Tasks>()
 956                .unwrap()
 957                .priority
 958                .push(Task::RenderAll);
 959        }
 960
 961        Ok(())
 962    }
 963
 964    fn mouse_event(
 965        &mut self,
 966        framework: &mut FrameworkClean,
 967        x: u16,
 968        y: u16,
 969        _absolute_x: u16,
 970        _absolute_y: u16,
 971    ) -> bool {
 972        let chunk = self
 973            .grid
 974            .chunks(
 975                if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
 976                {
 977                    prev_frame
 978                } else {
 979                    return false;
 980                },
 981            )
 982            .unwrap()[0][1];
 983
 984        if !chunk.intersects(Rect::new(x, y, 1, 1)) {
 985            return false;
 986        }
 987
 988        let textlist = match &mut self.r#type {
 989            SingleItemType::Video(SingleVideoItem { textlist, .. }) => textlist,
 990            SingleItemType::Playlist(singleplaylistitem) => {
 991                if singleplaylistitem.is_commands_view {
 992                    &mut singleplaylistitem.commands_view
 993                } else {
 994                    let y = (y - chunk.y) as usize + singleplaylistitem.videos_view.scroll;
 995                    if singleplaylistitem.videos_view.selected != 0 && y == 0 {
 996                        framework
 997                            .data
 998                            .state
 999                            .get_mut::<Tasks>()
1000                            .unwrap()
1001                            .priority
1002                            .push(Task::ClearPage);
1003                    }
1004                    &mut singleplaylistitem.videos_view
1005                }
1006            }
1007            _ => return false,
1008        };
1009
1010        let y = (y - chunk.y) as usize + textlist.scroll;
1011
1012        // clicking on already selected item
1013        if y == textlist.selected || y == textlist.selected + 2 || y == textlist.selected + 1 {
1014            self.select_at_cursor(framework);
1015            return true;
1016        }
1017
1018        // clicking on rows after the last item
1019        if y > textlist.items.len() + 1 {
1020            return false;
1021        }
1022
1023        // moving the cursor
1024        if y <= textlist.selected {
1025            textlist.selected = y;
1026        }
1027
1028        if y >= textlist.selected + 2 {
1029            textlist.selected = y - 2;
1030        }
1031
1032        self.update();
1033
1034        set_envs(
1035            self.infalte_item_update(
1036                framework.data.global.get::<MainConfig>().unwrap(),
1037                framework.data.global.get::<Status>().unwrap(),
1038            )
1039            .into_iter(),
1040            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
1041        );
1042
1043        // render the new image
1044        framework
1045            .data
1046            .global
1047            .get_mut::<Status>()
1048            .unwrap()
1049            .render_image = true;
1050
1051        true
1052    }
1053}