Skip to content

ansiline implementation, new ansi tailwind colors #1996

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2025
Merged

Conversation

sawka
Copy link
Member

@sawka sawka commented Feb 19, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

This pull request introduces a React component that renders text with ANSI color codes and extends the Tailwind CSS setup with custom ANSI color properties. The new React component parses ANSI sequences from input text, maps them using a predefined ANSI-to-Tailwind class mapping, and manages state to reflect changes in text modifiers, colors, and reverse modes. Utility functions are implemented to initialize state, update it with ANSI codes, and generate corresponding CSS classes for rendering. In parallel, the Tailwind CSS file is updated to include custom properties for both standard and bright variants of ANSI colors, thus expanding the theme's color palette. These changes collectively enable dynamic styling of text based on ANSI color codes and provide a consistent dark palette for color customization.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
frontend/app/element/ansiline.tsx (3)

1-50: LGTM! Consider adding support for additional ANSI codes.

The ANSI-to-Tailwind mapping is comprehensive and well-organized. However, some ANSI codes are not included:

  • Code 5 (blink)
  • Code 22 (normal intensity)
  • Code 23 (not italic)
  • Code 24 (not underlined)
  • Code 27 (not reversed)
  • Code 28 (reveal)
  • Code 29 (not crossed out)

64-69: Consider removing redundant type annotation.

The return type annotation is redundant as TypeScript can infer it from the object structure.

-const makeInitialState: () => InternalStateType = () => ({
+const makeInitialState = () => ({

100-114: Improve readability with destructuring.

The function logic is correct but could be more concise.

-const stateToClasses = (state: InternalStateType) => {
+const stateToClasses = ({ modifiers, textColor, bgColor, reverse }: InternalStateType) => {
   const classes = [];
-  classes.push(...Array.from(state.modifiers));
+  classes.push(...Array.from(modifiers));

-  let textColor = state.textColor;
-  let bgColor = state.bgColor;
-  if (state.reverse) {
-    [textColor, bgColor] = [bgColor, textColor];
+  if (reverse) {
+    [textColor, bgColor] = [bgColor, textColor];
   }
   if (textColor) classes.push(textColor);
   if (bgColor) classes.push(bgColor);

   return classes.join(" ");
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 119b1ec and 89d3ea3.

📒 Files selected for processing (2)
  • frontend/app/element/ansiline.tsx (1 hunks)
  • frontend/tailwindsetup.css (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/app/element/ansiline.tsx

[error] 116-116: Unexpected control character in a regular expression.

Control characters are unusual and potentially incorrect inputs, so they are disallowed.

(lint/suspicious/noControlCharactersInRegex)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build for TestDriver.ai
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
frontend/app/element/ansiline.tsx (2)

52-62: LGTM! Types are well-defined and efficient.

The types effectively capture the state requirements and segment structure. Using Set for modifiers ensures uniqueness, and nullable colors allow for proper state reset.


116-116: Control character usage is valid for ANSI escape sequences.

The static analysis tool flags the control character \x1b, but this is the correct escape sequence for ANSI codes. Consider adding a comment to document this and suppress the linter warning.

+// eslint-disable-next-line no-control-regex
 const ansiRegex = /\x1b\[([0-9;]+)m/g;
🧰 Tools
🪛 Biome (1.9.4)

[error] 116-116: Unexpected control character in a regular expression.

Control characters are unusual and potentially incorrect inputs, so they are disallowed.

(lint/suspicious/noControlCharactersInRegex)

frontend/tailwindsetup.css (1)

45-61: Verify color contrast ratios for accessibility.

The ANSI colors need to be checked against both light and dark backgrounds to ensure they meet WCAG contrast requirements.

#!/usr/bin/env python3
import colorsys
import math

def hex_to_rgb(hex_color):
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

def relative_luminance(r, g, b):
    r = r / 255
    g = g / 255
    b = b / 255
    r = r / 12.92 if r <= 0.03928 else ((r + 0.055) / 1.055) ** 2.4
    g = g / 12.92 if g <= 0.03928 else ((g + 0.055) / 1.055) ** 2.4
    b = b / 12.92 if b <= 0.03928 else ((b + 0.055) / 1.055) ** 2.4
    return 0.2126 * r + 0.7152 * g + 0.0722 * b

def contrast_ratio(color1, color2):
    l1 = relative_luminance(*hex_to_rgb(color1))
    l2 = relative_luminance(*hex_to_rgb(color2))
    lighter = max(l1, l2)
    darker = min(l1, l2)
    return (lighter + 0.05) / (darker + 0.05)

# Background colors
bg_dark = "#222222"  # --color-background
bg_light = "#f7f7f7" # --color-white

# ANSI colors to test
ansi_colors = {
    "black": "#757575",
    "red": "#cc685c",
    "green": "#76c266",
    "yellow": "#cbca9b",
    "blue": "#85aacb",
    "magenta": "#cc72ca",
    "cyan": "#74a7cb",
    "white": "#c1c1c1",
    "brightblack": "#727272",
    "brightred": "#cc9d97",
    "brightgreen": "#a3dd97",
    "brightyellow": "#cbcaaa",
    "brightblue": "#9ab6cb",
    "brightmagenta": "#cc8ecb",
    "brightcyan": "#b7b8cb",
    "brightwhite": "#f0f0f0"
}

print("WCAG Contrast Ratio Requirements:")
print("- Normal text (AA): 4.5:1")
print("- Large text (AA): 3:1")
print("\nContrast Ratios Against Dark Background (#222222):")
for name, color in ansi_colors.items():
    ratio = contrast_ratio(color, bg_dark)
    print(f"{name}: {ratio:.2f}:1")

print("\nContrast Ratios Against Light Background (#f7f7f7):")
for name, color in ansi_colors.items():
    ratio = contrast_ratio(color, bg_light)
    print(f"{name}: {ratio:.2f}:1")

Comment on lines +71 to +98
const updateStateWithCodes = (state, codes) => {
codes.forEach((code) => {
if (code === 0) {
// Reset state
state.modifiers.clear();
state.textColor = null;
state.bgColor = null;
state.reverse = false;
return;
}
// Instead of swapping immediately, we set a flag
if (code === 7) {
state.reverse = true;
return;
}
const tailwindClass = ANSI_TAILWIND_MAP[code];
if (tailwindClass && tailwindClass !== "reset") {
if (tailwindClass.startsWith("text-")) {
state.textColor = tailwindClass;
} else if (tailwindClass.startsWith("bg-")) {
state.bgColor = tailwindClass;
} else {
state.modifiers.add(tailwindClass);
}
}
});
return state;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve type safety and consider immutability.

The function has several potential improvements:

  1. Missing type annotations for parameters
  2. Direct state mutation could lead to bugs
  3. Redundant state return as it's mutated in-place

Consider this refactored version:

-const updateStateWithCodes = (state, codes) => {
+const updateStateWithCodes = (state: InternalStateType, codes: number[]): InternalStateType => {
+  const newState = {
+    modifiers: new Set(state.modifiers),
+    textColor: state.textColor,
+    bgColor: state.bgColor,
+    reverse: state.reverse,
+  };
   codes.forEach((code) => {
     if (code === 0) {
-      state.modifiers.clear();
-      state.textColor = null;
-      state.bgColor = null;
-      state.reverse = false;
+      newState.modifiers.clear();
+      newState.textColor = null;
+      newState.bgColor = null;
+      newState.reverse = false;
       return;
     }
     if (code === 7) {
-      state.reverse = true;
+      newState.reverse = true;
       return;
     }
     const tailwindClass = ANSI_TAILWIND_MAP[code];
     if (tailwindClass && tailwindClass !== "reset") {
       if (tailwindClass.startsWith("text-")) {
-        state.textColor = tailwindClass;
+        newState.textColor = tailwindClass;
       } else if (tailwindClass.startsWith("bg-")) {
-        state.bgColor = tailwindClass;
+        newState.bgColor = tailwindClass;
       } else {
-        state.modifiers.add(tailwindClass);
+        newState.modifiers.add(tailwindClass);
       }
     }
   });
-  return state;
+  return newState;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const updateStateWithCodes = (state, codes) => {
codes.forEach((code) => {
if (code === 0) {
// Reset state
state.modifiers.clear();
state.textColor = null;
state.bgColor = null;
state.reverse = false;
return;
}
// Instead of swapping immediately, we set a flag
if (code === 7) {
state.reverse = true;
return;
}
const tailwindClass = ANSI_TAILWIND_MAP[code];
if (tailwindClass && tailwindClass !== "reset") {
if (tailwindClass.startsWith("text-")) {
state.textColor = tailwindClass;
} else if (tailwindClass.startsWith("bg-")) {
state.bgColor = tailwindClass;
} else {
state.modifiers.add(tailwindClass);
}
}
});
return state;
};
const updateStateWithCodes = (state: InternalStateType, codes: number[]): InternalStateType => {
const newState = {
modifiers: new Set(state.modifiers),
textColor: state.textColor,
bgColor: state.bgColor,
reverse: state.reverse,
};
codes.forEach((code) => {
if (code === 0) {
newState.modifiers.clear();
newState.textColor = null;
newState.bgColor = null;
newState.reverse = false;
return;
}
if (code === 7) {
newState.reverse = true;
return;
}
const tailwindClass = ANSI_TAILWIND_MAP[code];
if (tailwindClass && tailwindClass !== "reset") {
if (tailwindClass.startsWith("text-")) {
newState.textColor = tailwindClass;
} else if (tailwindClass.startsWith("bg-")) {
newState.bgColor = tailwindClass;
} else {
newState.modifiers.add(tailwindClass);
}
}
});
return newState;
};

Comment on lines +118 to +154
const AnsiLine = ({ line }) => {
const segments: SegmentType[] = [];
let lastIndex = 0;
let currentState = makeInitialState();

let match: RegExpExecArray;
while ((match = ansiRegex.exec(line)) !== null) {
if (match.index > lastIndex) {
segments.push({
text: line.substring(lastIndex, match.index),
classes: stateToClasses(currentState),
});
}
const codes = match[1].split(";").map(Number);
updateStateWithCodes(currentState, codes);
lastIndex = ansiRegex.lastIndex;
}

if (lastIndex < line.length) {
segments.push({
text: line.substring(lastIndex),
classes: stateToClasses(currentState),
});
}

return (
<div>
{segments.map((seg, idx) => (
<span key={idx} className={seg.classes}>
{seg.text}
</span>
))}
</div>
);
};

export default AnsiLine;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add prop types and optimize performance.

Several improvements could enhance the component:

  1. Missing prop types
  2. Array index as key could cause issues with React reconciliation
  3. Could benefit from memoization
+type AnsiLineProps = {
+  line: string;
+};

-const AnsiLine = ({ line }) => {
+const AnsiLine = ({ line }: AnsiLineProps) => {
   const segments: SegmentType[] = [];
   let lastIndex = 0;
   let currentState = makeInitialState();

   let match: RegExpExecArray;
   while ((match = ansiRegex.exec(line)) !== null) {
     if (match.index > lastIndex) {
       segments.push({
         text: line.substring(lastIndex, match.index),
         classes: stateToClasses(currentState),
       });
     }
     const codes = match[1].split(";").map(Number);
     currentState = updateStateWithCodes(currentState, codes);
     lastIndex = ansiRegex.lastIndex;
   }

   if (lastIndex < line.length) {
     segments.push({
       text: line.substring(lastIndex),
       classes: stateToClasses(currentState),
     });
   }

   return (
     <div>
       {segments.map((seg, idx) => (
-        <span key={idx} className={seg.classes}>
+        <span key={`${idx}-${seg.text}`} className={seg.classes}>
           {seg.text}
         </span>
       ))}
     </div>
   );
 };

+export default React.memo(AnsiLine);
-export default AnsiLine;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const AnsiLine = ({ line }) => {
const segments: SegmentType[] = [];
let lastIndex = 0;
let currentState = makeInitialState();
let match: RegExpExecArray;
while ((match = ansiRegex.exec(line)) !== null) {
if (match.index > lastIndex) {
segments.push({
text: line.substring(lastIndex, match.index),
classes: stateToClasses(currentState),
});
}
const codes = match[1].split(";").map(Number);
updateStateWithCodes(currentState, codes);
lastIndex = ansiRegex.lastIndex;
}
if (lastIndex < line.length) {
segments.push({
text: line.substring(lastIndex),
classes: stateToClasses(currentState),
});
}
return (
<div>
{segments.map((seg, idx) => (
<span key={idx} className={seg.classes}>
{seg.text}
</span>
))}
</div>
);
};
export default AnsiLine;
type AnsiLineProps = {
line: string;
};
const AnsiLine = ({ line }: AnsiLineProps) => {
const segments: SegmentType[] = [];
let lastIndex = 0;
let currentState = makeInitialState();
let match: RegExpExecArray;
while ((match = ansiRegex.exec(line)) !== null) {
if (match.index > lastIndex) {
segments.push({
text: line.substring(lastIndex, match.index),
classes: stateToClasses(currentState),
});
}
const codes = match[1].split(";").map(Number);
currentState = updateStateWithCodes(currentState, codes);
lastIndex = ansiRegex.lastIndex;
}
if (lastIndex < line.length) {
segments.push({
text: line.substring(lastIndex),
classes: stateToClasses(currentState),
});
}
return (
<div>
{segments.map((seg, idx) => (
<span key={`${idx}-${seg.text}`} className={seg.classes}>
{seg.text}
</span>
))}
</div>
);
};
export default React.memo(AnsiLine);

@sawka sawka merged commit ce9775c into main Feb 19, 2025
8 checks passed
@sawka sawka deleted the sawka/ansiline branch February 19, 2025 20:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant