src/items/singleitem.rs

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