Porytiles
Loading...
Searching...
No Matches
ansi_styled_text_formatter.cpp
Go to the documentation of this file.
2
3#include <array>
4#include <string>
5
6namespace {
7
8using namespace porytiles2;
9
10// ANSI reset code
11const std::string ansi_reset = "\033[0m";
12
13// Ordered list of style flags to check (bold first, then colors)
14const std::array<std::pair<Style, std::string>, 8> style_mappings = {
15 {{Style::bold, "\033[1m"},
16 {Style::italic, "\033[3m"},
17 {Style::red, "\033[31m"},
18 {Style::green, "\033[32m"},
19 {Style::blue, "\033[34m"},
20 {Style::yellow, "\033[33m"},
21 {Style::cyan, "\033[36m"},
22 {Style::magenta, "\033[35m"}}};
23
24} // namespace
25
26namespace porytiles2 {
27
28std::string AnsiStyledTextFormatter::style(const std::string &text, Style styles) const
29{
30 // If no styles are set, return text unchanged
31 if (styles == Style::none) {
32 return text;
33 }
34
35 // Build the ANSI code prefix by checking each style flag
36 std::string prefix;
37 for (const auto &[flag, ansi_code] : style_mappings) {
38 if (has_style(styles, flag)) {
39 prefix += ansi_code;
40 }
41 }
42
43 return prefix + text + ansi_reset;
44}
45
46} // namespace porytiles2
std::string style(const std::string &text, Style styles) const override
Applies ANSI escape codes to style text according to the specified Style flags.
Style
Bitmask flags for text styling options.
@ none
No styling applied.
constexpr bool has_style(Style styles, Style flag)
Checks if a specific style flag is set in a Style value.