From c1b0e180ba64d2ea7e815e2c2e93087ae9a26500 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 29 Jul 2024 10:18:25 -0400 Subject: [PATCH] LibWebView: Insert line numbers before each line in about:srcdoc The behavior chosen here (fixed-width counters, alignment, etc.) matches Firefox. --- .../LibWebView/SourceHighlighter.cpp | 49 ++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibWebView/SourceHighlighter.cpp b/Userland/Libraries/LibWebView/SourceHighlighter.cpp index c482fa64499..b45ca6ba11e 100644 --- a/Userland/Libraries/LibWebView/SourceHighlighter.cpp +++ b/Userland/Libraries/LibWebView/SourceHighlighter.cpp @@ -11,6 +11,47 @@ namespace WebView { +static String generate_style() +{ + StringBuilder builder; + + builder.append(HTML_HIGHLIGHTER_STYLE); + builder.append(R"~~~( + .html { + counter-reset: line; + } + + .line { + counter-increment: line; + white-space: nowrap; + } + + .line::before { + content: counter(line) " "; + + display: inline-block; + width: 2.5em; + + padding-right: 0.5em; + text-align: right; + } + + @media (prefers-color-scheme: dark) { + .line::before { + color: darkgrey; + } + } + + @media (prefers-color-scheme: light) { + .line::before { + color: dimgray; + } + } +)~~~"sv); + + return MUST(builder.to_string()); +} + String highlight_source(URL::URL const& url, StringView source) { Web::HTML::HTMLTokenizer tokenizer { source, "utf-8"sv }; @@ -23,12 +64,12 @@ String highlight_source(URL::URL const& url, StringView source) )~~~"sv); builder.appendff("View Source - {}", url); - builder.appendff("", HTML_HIGHLIGHTER_STYLE); + builder.appendff("", generate_style()); builder.append(R"~~~(
-)~~~"sv);
+)~~~"sv);
 
     size_t previous_position = 0;
 
@@ -50,6 +91,8 @@ String highlight_source(URL::URL const& url, StringView source)
                 builder.append("<"sv);
             else if (code_point == '>')
                 builder.append(">"sv);
+            else if (code_point == '\n')
+                builder.append("\n"sv);
             else
                 builder.append_code_point(code_point);
         }
@@ -83,12 +126,14 @@ String highlight_source(URL::URL const& url, StringView source)
             append_source(token->end_position().byte_offset);
         } else {
             append_source(token->end_position().byte_offset);
+
             if (token->is_end_of_file())
                 break;
         }
     }
 
     builder.append(R"~~~(
+