-
Notifications
You must be signed in to change notification settings - Fork 368
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
Conversation
WalkthroughThis 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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
📒 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")
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; | ||
}; |
There was a problem hiding this comment.
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:
- Missing type annotations for parameters
- Direct state mutation could lead to bugs
- 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.
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; | |
}; |
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; |
There was a problem hiding this comment.
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:
- Missing prop types
- Array index as key could cause issues with React reconciliation
- 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.
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); |
No description provided.