summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibMarkdown/Table.cpp
blob: 6c08723123a6245c44f8ae82787c1f0f1159e89e (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Debug.h>
#include <AK/StringBuilder.h>
#include <LibMarkdown/Table.h>

namespace Markdown {

String Table::render_for_terminal(size_t view_width) const
{
    auto unit_width_length = view_width == 0 ? 4 : ((float)(view_width - m_columns.size()) / (float)m_total_width);
    StringBuilder builder;

    auto write_aligned = [&](const auto& text, auto width, auto alignment) {
        size_t original_length = 0;
        for (auto& span : text.spans())
            original_length += span.text.length();
        auto string = text.render_for_terminal();
        if (alignment == Alignment::Center) {
            auto padding_length = (width - original_length) / 2;
            // FIXME: We're using a StringView literal to bypass the compile-time AK::Format checking here, since it can't handle the "}}"
            builder.appendff("{:{1}}"sv, "", (int)padding_length);
            builder.append(string);
            builder.appendff("{:{1}}"sv, "", (int)padding_length);
            if ((width - original_length) % 2)
                builder.append(' ');
        } else {
            // FIXME: We're using StringView literals to bypass the compile-time AK::Format checking here, since it can't handle the "}}"
            builder.appendff(alignment == Alignment::Left ? "{:<{1}}"sv : "{:>{1}}"sv, string, (int)(width + (string.length() - original_length)));
        }
    };

    bool first = true;
    for (auto& col : m_columns) {
        if (!first)
            builder.append('|');
        first = false;
        size_t width = col.relative_width * unit_width_length;
        write_aligned(col.header, width, col.alignment);
    }

    builder.append("\n");
    for (size_t i = 0; i < view_width; ++i)
        builder.append('-');
    builder.append("\n");

    for (size_t i = 0; i < m_row_count; ++i) {
        bool first = true;
        for (auto& col : m_columns) {
            VERIFY(i < col.rows.size());
            auto& cell = col.rows[i];

            if (!first)
                builder.append('|');
            first = false;

            size_t width = col.relative_width * unit_width_length;
            write_aligned(cell, width, col.alignment);
        }
        builder.append("\n");
    }

    return builder.to_string();
}

String Table::render_to_html() const
{
    StringBuilder builder;

    builder.append("<table>");
    builder.append("<thead>");
    builder.append("<tr>");
    for (auto& column : m_columns) {
        builder.append("<th>");
        builder.append(column.header.render_to_html());
        builder.append("</th>");
    }
    builder.append("</tr>");
    builder.append("</thead>");
    builder.append("<tbody>");
    for (size_t i = 0; i < m_row_count; ++i) {
        builder.append("<tr>");
        for (auto& column : m_columns) {
            VERIFY(i < column.rows.size());
            builder.append("<td>");
            builder.append(column.rows[i].render_to_html());
            builder.append("</td>");
        }
        builder.append("</tr>");
    }
    builder.append("</tbody>");
    builder.append("</table>");

    return builder.to_string();
}

OwnPtr<Table> Table::parse(Vector<StringView>::ConstIterator& lines)
{
    auto peek_it = lines;
    auto first_line = *peek_it;
    if (!first_line.starts_with('|'))
        return {};

    ++peek_it;

    if (peek_it.is_end())
        return {};

    auto header_segments = first_line.split_view('|', true);
    auto header_delimiters = peek_it->split_view('|', true);

    if (!header_segments.is_empty())
        header_segments.take_first();
    if (!header_segments.is_empty() && header_segments.last().is_empty())
        header_segments.take_last();

    if (!header_delimiters.is_empty())
        header_delimiters.take_first();
    if (!header_delimiters.is_empty() && header_delimiters.last().is_empty())
        header_delimiters.take_last();

    ++peek_it;

    if (header_delimiters.size() != header_segments.size())
        return {};

    if (header_delimiters.is_empty())
        return {};

    size_t total_width = 0;

    auto table = make<Table>();
    table->m_columns.resize(header_delimiters.size());

    for (size_t i = 0; i < header_segments.size(); ++i) {
        auto text_option = Text::parse(header_segments[i]);
        if (!text_option.has_value())
            return {}; // An invalid 'text' in the header should just fail the table parse.

        auto text = text_option.release_value();
        auto& column = table->m_columns[i];

        column.header = move(text);

        auto delimiter = header_delimiters[i].trim_whitespace();

        auto align_left = delimiter.starts_with(':');
        auto align_right = delimiter != ":" && delimiter.ends_with(':');

        if (align_left)
            delimiter = delimiter.substring_view(1, delimiter.length() - 1);
        if (align_right)
            delimiter = delimiter.substring_view(0, delimiter.length() - 1);

        if (align_left && align_right)
            column.alignment = Alignment::Center;
        else if (align_right)
            column.alignment = Alignment::Right;
        else
            column.alignment = Alignment::Left;

        size_t relative_width = delimiter.length();
        for (auto ch : delimiter) {
            if (ch != '-') {
                dbgln_if(MARKDOWN_DEBUG, "Invalid character _{}_ in table heading delimiter (ignored)", ch);
                --relative_width;
            }
        }

        column.relative_width = relative_width;
        total_width += relative_width;
    }

    table->m_total_width = total_width;

    for (off_t i = 0; i < peek_it - lines; ++i)
        ++lines;

    size_t row_count = 0;
    ++lines;
    while (!lines.is_end()) {
        auto& line = *lines;
        if (!line.starts_with('|'))
            break;

        ++lines;

        auto segments = line.split_view('|', true);
        segments.take_first();
        if (!segments.is_empty() && segments.last().is_empty())
            segments.take_last();
        ++row_count;

        for (size_t i = 0; i < header_segments.size(); ++i) {
            if (i >= segments.size()) {
                // Ran out of segments, but still have headers.
                // Just make an empty cell.
                table->m_columns[i].rows.append(Text { "" });
            } else {
                auto text_option = Text::parse(segments[i]);
                // We treat an invalid 'text' as a literal.
                if (text_option.has_value()) {
                    auto text = text_option.release_value();
                    table->m_columns[i].rows.append(move(text));
                } else {
                    table->m_columns[i].rows.append(Text { segments[i] });
                }
            }
        }
    }

    table->m_row_count = row_count;

    return table;
}

}