1
1
mirror of https://github.com/go-gitea/gitea synced 2024-11-14 14:14:25 +00:00
gitea/web_src/js/render/ansi.js
silverwind fdab4e3d84
Add custom ansi colors and CSS variables for them (#25546)
Use our existing color palette to map to the 16 basic ansi colors. This
is backwards-compatible because it aliases the existing color names.

Side note: I think the colors in `console.css` for console file
rendering are incomplete, but fixing those is out of scope here imo.

Before and after:

<img width="542" alt="Screenshot 2023-06-28 at 00 26 12"
src="https://github.com/go-gitea/gitea/assets/115237/86d41884-bc47-4e85-8aec-621eb7320f0b">

<img width="546" alt="Screenshot 2023-06-28 at 00 28 24"
src="https://github.com/go-gitea/gitea/assets/115237/39fa3b37-d49e-49b1-b6bc-390ac8ca24b2">

---------

Co-authored-by: Giteabot <teabot@gitea.io>
2023-06-28 15:38:55 +02:00

46 lines
1.4 KiB
JavaScript

import AnsiUp from 'ansi_up';
const replacements = [
[/\x1b\[\d+[A-H]/g, ''], // Move cursor, treat them as no-op
[/\x1b\[\d?[JK]/g, '\r'], // Erase display/line, treat them as a Carriage Return
];
// render ANSI to HTML
export function renderAnsi(line) {
// create a fresh ansi_up instance because otherwise previous renders can influence
// the output of future renders, because ansi_up is stateful and remembers things like
// unclosed opening tags for colors.
const ansi_up = new (AnsiUp.default || AnsiUp)();
ansi_up.use_classes = true;
if (line.endsWith('\r\n')) {
line = line.substring(0, line.length - 2);
} else if (line.endsWith('\n')) {
line = line.substring(0, line.length - 1);
}
if (line.includes('\x1b')) {
for (const [regex, replacement] of replacements) {
line = line.replace(regex, replacement);
}
}
if (!line.includes('\r')) {
return ansi_up.ansi_to_html(line);
}
// handle "\rReading...1%\rReading...5%\rReading...100%",
// convert it into a multiple-line string: "Reading...1%\nReading...5%\nReading...100%"
const lines = [];
for (const part of line.split('\r')) {
if (part === '') continue;
const partHtml = ansi_up.ansi_to_html(part);
if (partHtml !== '') {
lines.push(partHtml);
}
}
// the log message element is with "white-space: break-spaces;", so use "\n" to break lines
return lines.join('\n');
}