summaryrefslogtreecommitdiff
path: root/src/component.cpp
blob: 9247a1d3c672a18de8dfde020a8799d2c3fc078b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <ftxui/component/screen_interactive.hpp>
#include "component.h"

namespace katja
{
    PackageList::PackageList(const std::vector<std::string>& header, const std::vector<std::vector<std::string>>& data)
        : m_data(data), m_header(header)
    {
    }

    ftxui::Element PackageList::Render()
    {
        std::vector<std::vector<std::string>> data{ m_header };

        std::size_t dimy = ftxui::ScreenInteractive::Active()->dimy();
        if (dimy == 0)
        {
            dimy = ftxui::Terminal::Size().dimy;
        }
        if (dimy > 4) // 4 = headers and borders.
        {
            std::size_t row_count = std::min(m_data.size() - top_line, dimy - 4 + top_line);

            std::copy(m_data.cbegin() + top_line, m_data.cbegin() + row_count, std::back_inserter(data));
        }
        ftxui::Table table{ data };
        table.SelectAll().Border(ftxui::LIGHT);

        // Add border around the first column.
        table.SelectColumn(0).Border(ftxui::LIGHT);

        // Make first row bold with a double border.
        table.SelectRow(0).Decorate(ftxui::bold);
        table.SelectRow(0).SeparatorVertical(ftxui::LIGHT);
        table.SelectRow(0).Border(ftxui::DOUBLE);

        // Align right the "Release date" column.
        table.SelectColumn(2).DecorateCells(ftxui::align_right);

        // Select row from the second to the last.
        auto content = table.SelectRows(1, -1);
        // Alternate in between 3 colors.
        content.DecorateCellsAlternateRow(color(ftxui::Color::Blue), 3, 0);
        content.DecorateCellsAlternateRow(color(ftxui::Color::Cyan), 3, 1);
        content.DecorateCellsAlternateRow(color(ftxui::Color::White), 3, 2);

        return table.Render();
    }

    bool PackageList::OnEvent(ftxui::Event event)
    {
        if (event == ftxui::Event::Character('q') || event == ftxui::Event::Escape)
        {
            event.screen_->ExitLoopClosure()();
        }
        else if (event == ftxui::Event::Character('j') || event == ftxui::Event::ArrowDown)
        {
            if (m_data.size() > 0 && top_line < (m_data.size() - 1))
            {
                ++top_line;
            }
        }
        else if (event == ftxui::Event::Character('k') || event == ftxui::Event::ArrowUp)
        {
            if (top_line > 0)
            {
                --top_line;
            }
        }
        else
        {
            return false;
        }
        return true;
    }
}