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
|
/*
* Ricochet - A minimalist CLI web browser for fast, distraction-free navigation.
* Copyright (C) 2026 Richard Qin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "ricochet/parser/tree_builder.hh"
#include "ricochet/parser/dom_tree.hh"
#include <utility>
#include <vector>
namespace ricochet::parser {
namespace {
struct TokenVisitor
{
std::vector<DomNode>* stack;
void operator()( const TextToken& token ) const
{
stack->back().children.emplace_back(
DomNode { .tag_name = "", .text_content = token.content, .children = {} } );
}
void operator()( const TagOpenToken& token ) const
{
const std::size_t space_pos = token.name.find( ' ' );
const std::string base_name
= ( space_pos == std::string::npos ) ? token.name : token.name.substr( 0, space_pos );
DomNode new_node { .tag_name = token.name, .text_content = "", .children = {} };
if ( base_name == "meta" || base_name == "link" || base_name == "img" || base_name == "br" || base_name == "hr"
|| base_name == "input" || base_name == "base" || base_name == "col" ) {
stack->back().children.push_back( std::move( new_node ) );
} else {
stack->push_back( std::move( new_node ) );
}
}
void operator()( const TagCloseToken& /*token*/ ) const
{
if ( stack->size() > 1 ) {
DomNode completed_node = std::move( stack->back() );
stack->pop_back();
stack->back().children.push_back( std::move( completed_node ) );
}
}
};
} // namespace
DomNode TreeBuilder::build( // NOLINT(readability-convert-member-functions-to-static)
const std::vector<HtmlToken>& tokens ) const
{
std::vector<DomNode> stack;
stack.emplace_back( DomNode { .tag_name = "Document", .text_content = "", .children = {} } );
TokenVisitor visitor { &stack };
for ( const auto& token : tokens ) {
std::visit( visitor, token );
}
while ( stack.size() > 1 ) {
DomNode completed_node = std::move( stack.back() );
stack.pop_back();
stack.back().children.push_back( std::move( completed_node ) );
}
return std::move( stack.front() );
}
} // namespace ricochet::parser
|