Skip to content
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

add tailwind to wave, support shadcn + donut chart as a POC #1775

Merged
merged 25 commits into from
Feb 5, 2025
Merged

Conversation

sawka
Copy link
Member

@sawka sawka commented Jan 20, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Warning

Rate limit exceeded

@sawka has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f15a0e2 and 1f7373f.

📒 Files selected for processing (1)
  • frontend/tailwindsetup.css (1 hunks)

Walkthrough

This pull request integrates Tailwind CSS into various aspects of the application. A new CSS import is added in the global stylesheet, and the VS Code settings now associate CSS files with Tailwind CSS. The Electron Vite configuration has been updated to include the Tailwind CSS plugin and SCSS preprocessor options. Additionally, the main application file now imports the Tailwind setup. New components are introduced, including the DonutChart component and its corresponding Storybook configuration. Updates to the global reset stylesheet add new CSS rules and adjustments for improved consistency. A new chart component using Recharts is also introduced, featuring configurations, context management, tooltips, and legends. Font loading utilities have been modified by removing certain functions. Finally, updates to package dependencies, PostCSS configuration, and TypeScript aliases support the integration of these new styling and charting features.


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.

@sawka sawka marked this pull request as ready for review February 4, 2025 05:25
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: 1

🔭 Outside diff range comments (1)
.storybook/global.css (1)

19-21: Relocate @import for Valid CSS.
Static analysis flagged the @import "../frontend/tailwindsetup.css"; as being in the wrong position. According to CSS standards, all @import statements must precede other style rules (aside from @charset and @layer). You should move the @import rule to the very top of the file to ensure correct loading order and validity.

Below is a suggested diff:

@@ .storybook/global.css @@
- body {
-     height: 100vh;
-     padding: 0;
-     overflow: auto;
- }
- 
- #storybook-root {
-     height: 100%;
- }
- 
- .grid-item {
-     background-color: aquamarine;
-     border: 1px black solid;
- 
-     &.react-grid-placeholder {
-         background-color: orange;
-     }
- }
- @import "../frontend/tailwindsetup.css";
+@import "../frontend/tailwindsetup.css";
+
+body {
+    height: 100vh;
+    padding: 0;
+    overflow: auto;
+}
+
+#storybook-root {
+    height: 100%;
+}
+
+.grid-item {
+    background-color: aquamarine;
+    border: 1px black solid;
+
+    &.react-grid-placeholder {
+        background-color: orange;
+    }
+}
🧰 Tools
🪛 Biome (1.9.4)

[error] 20-20: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

🧹 Nitpick comments (7)
frontend/app/shadcn/chart.tsx (1)

94-233: Consider breaking down ChartTooltipContent into smaller, more focused components.

While the current logic is correct, the function is fairly large. Splitting out the item rendering and label logic into sub-components or utility functions would reduce complexity and improve readability.

frontend/app/element/donutchart.stories.tsx (1)

52-73: Suggest referencing brand or theme-based color variables.

While these hardcoded color values work, referencing theme tokens or shared color variables can improve consistency and maintainability across the application.

frontend/app/view/shape/shape.tsx (3)

4-8: Consider organizing imports.

The imports could be better organized by grouping them into:

  1. External dependencies (React, Jotai)
  2. Internal dependencies (@/store, @/util)
-import { WOS } from "@/store/global";
-import { ObjectService } from "@/store/services";
-import { fireAndForget } from "@/util/util";
-import { atom, Atom, useAtomValue } from "jotai";
-import React from "react";
+import React from "react";
+import { atom, Atom, useAtomValue } from "jotai";
+
+import { WOS } from "@/store/global";
+import { ObjectService } from "@/store/services";
+import { fireAndForget } from "@/util/util";

11-59: Consider adding type safety for meta property.

The meta property access in the view model could benefit from type safety to prevent runtime errors.

+interface BlockMeta {
+    shape?: "circle" | "square";
+}
+
+interface Block {
+    meta: BlockMeta;
+}
+
 export class ShapesViewModel implements ViewModel {
     viewType: string;
     blockId: string;
-    blockAtom: Atom<Block>;
+    blockAtom: Atom<Block>;

67-91: Consider using Tailwind CSS classes instead of inline styles.

Since we're adding Tailwind CSS support, consider using Tailwind classes for styling instead of inline styles.

-    const containerStyle = {
-        display: "flex",
-        alignItems: "center",
-        justifyContent: "center",
-        height: "24rem",
-        width: "100%",
-    };
-
-    const shapeStyle = {
-        width: "8rem",
-        height: "8rem",
-        backgroundColor: "#3b82f6",
-        borderRadius: currentShape === "circle" ? "50%" : "0",
-    };
-
     return (
-        <div style={containerStyle}>
-            <div style={shapeStyle} />
+        <div className="flex items-center justify-center h-96 w-full">
+            <div 
+                className={`w-32 h-32 bg-blue-500 ${
+                    currentShape === "circle" ? "rounded-full" : "rounded-none"
+                }`}
+            />
         </div>
     );
frontend/app/element/donutchart.tsx (1)

83-83: Consider making animation configurable.

The animation is hardcoded to be disabled. Consider making it configurable through props.

+interface DonutChartProps {
+    data: DonutChartData[];
+    config: ChartConfig;
+    innerLabel?: string;
+    innerSubLabel?: string;
+    dataKey: string;
+    nameKey: string;
+    isAnimationActive?: boolean;
+}

-                        isAnimationActive={false}
+                        isAnimationActive={props.isAnimationActive ?? false}
frontend/tailwindsetup.css (1)

14-16: Consider documenting the transition strategy.

The comment about the wrapper class could be more descriptive about the transition strategy and timeline.

-/* added this wrapper while we transition */
+/* TODO: Remove .tw wrapper class after completing the Tailwind CSS migration.
+ * This wrapper is temporarily used to scope Tailwind CSS styles during the transition phase.
+ * Track the migration progress in issue #XXXX
+ */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7a9006 and 8e7a79a.

⛔ Files ignored due to path filters (6)
  • public/fonts/MartianMono-VariableFont_wdth,wght.ttf is excluded by !**/*.ttf
  • public/fonts/hack-bold.woff2 is excluded by !**/*.woff2
  • public/fonts/hack-bolditalic.woff2 is excluded by !**/*.woff2
  • public/fonts/hack-italic.woff2 is excluded by !**/*.woff2
  • public/fonts/hack-regular.woff2 is excluded by !**/*.woff2
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (16)
  • .storybook/global.css (1 hunks)
  • .vscode/settings.json (1 hunks)
  • electron.vite.config.ts (2 hunks)
  • frontend/app/app.tsx (1 hunks)
  • frontend/app/element/donutchart.scss (1 hunks)
  • frontend/app/element/donutchart.stories.tsx (1 hunks)
  • frontend/app/element/donutchart.tsx (1 hunks)
  • frontend/app/reset.scss (1 hunks)
  • frontend/app/shadcn/chart.tsx (1 hunks)
  • frontend/app/tab/tabbar.scss (1 hunks)
  • frontend/app/view/shape/shape.tsx (1 hunks)
  • frontend/tailwindsetup.css (1 hunks)
  • frontend/util/fontutil.ts (0 hunks)
  • package.json (5 hunks)
  • postcss.config.cjs (1 hunks)
  • tsconfig.json (1 hunks)
💤 Files with no reviewable changes (1)
  • frontend/util/fontutil.ts
✅ Files skipped from review due to trivial changes (3)
  • postcss.config.cjs
  • frontend/app/app.tsx
  • frontend/app/element/donutchart.scss
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/app/shadcn/chart.tsx

[error] 72-72: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

.storybook/global.css

[error] 20-20: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

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

63-91: Avoid using dangerouslySetInnerHTML unless absolutely necessary.

This approach can introduce potential XSS risks if the CSS is ever derived from non-trusted sources. If you're only injecting known CSS, it’s relatively safe, but consider using style objects, a CSS-in-JS library, or a more controlled solution to generate styles.

Would you like me to generate a script to confirm no untrusted content flows into ChartStyle from elsewhere in the codebase?

🧰 Tools
🪛 Biome (1.9.4)

[error] 72-72: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)


236-290: LGTM!

The ChartLegendContent component cleanly handles the legend functionality and dynamic icon display with clarity.


291-315: Helper function works as intended.

The getPayloadConfigFromPayload utility safely retrieves config data based on the key. No issues found.

electron.vite.config.ts (3)

4-4: Successful Tailwind plugin import.

Importing @tailwindcss/vite aligns with your objective to integrate Tailwind into the build. No issues found.


67-73: SCSS preprocessor options look good.

You can add additional variables or global mixins here if needed. Currently, no issues are detected.


81-81: Ensuring TailwindCSS is placed correctly in the plugin list.

Tailwind is properly placed before the React plugin. This ordering is typically recommended for optimum performance.

tsconfig.json (1)

23-24: LGTM! Path alias addition looks good.

The new path alias for shadcn components is correctly configured.

.vscode/settings.json (1)

48-51: Associate CSS Files with Tailwind CSS.
The addition of "files.associations": { "*.css": "tailwindcss" } correctly informs VS Code to treat CSS files with the Tailwind CSS language mode. This should enhance syntax highlighting and autocompletion for Tailwind directives.

frontend/app/tab/tabbar.scss (1)

19-20: Enhance Error Message Header Styling.
Adding font-weight: bold; and font-size: 16px; to the h3 within .config-error-message makes error messages more prominent. Ensure these styles align with your overall design system.

frontend/app/reset.scss (4)

1-11: Update for Consistent Baseline Styles.
Updating the copyright
comment to 2025 and incorporating the pseudo-elements (::after, ::before, ::backdrop, ::file-selector-button) into the reset—with a uniform border: 0 solid;—ensures a consistent styling baseline across elements.


13-20: Uniform Spacing Resets.
Resetting margin and padding for both elements and several pseudo-elements reinforces consistency across browsers. This approach is standard in modern CSS resets.


118-121: Verify Modern CSS Function Usage.
The use of color: color-mix(in oklab, currentColor 50%, transparent); is a modern and powerful approach to color manipulation. However, ensure that the target browsers in your support matrix fully support the color-mix function, or consider adding fallbacks if necessary.


21-196: Comprehensive Reset Coverage.
The remaining reset styles cover a wide range of HTML elements and interactive components, ensuring predictable cross-browser behavior. The resets for typography, layout elements, form controls, and miscellaneous elements help maintain a clean slate for further styling.

package.json (5)

18-20: Define Target Browser Support.
Adding "browserslist": ["Chrome >= 128"] explicitly sets the baseline browser support, which can help optimize build outputs and ensure modern CSS/JS features are used appropriately.


45-47: Integrate Tailwind CSS Plugins.
Including @tailwindcss/postcss and @tailwindcss/vite in the devDependencies is essential for integrating Tailwind CSS with both PostCSS and your Vite build process. This addition will streamline the CSS compilation and development experience.


71-71: Ensure PostCSS Compatibility.
The addition of "postcss": "^8.5.1" is required for Tailwind CSS integration. Please verify that this version is compatible with other PostCSS plugins used in your project.


80-81: Enable Tailwind CSS and Animations.
Adding "tailwindcss": "^4.0.3" along with "tailwindcss-animate": "^1.0.7" further reinforces the project's shift toward using a utility-first styling approach with dynamic animations.


139-139: Support Donut Chart Visualization.
Introducing "recharts": "^2.15.0" as a dependency supports the new DonutChart component functionality by leveraging a robust charting library for data visualization.

Comment on lines +56 to +62
data: any[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
}) => {
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

Consider adding proper TypeScript types for data prop.

The data prop is typed as any[] which loses type safety. Consider creating a proper interface for the data structure.

+interface DonutChartData {
+    [key: string]: string | number;
+}
+
 const DonutChart = ({
     data,
     config,
     innerLabel,
     innerSubLabel,
     dataKey,
     nameKey,
 }: {
-    data: any[];
+    data: DonutChartData[];
     config: ChartConfig;
     innerLabel?: string;
     innerSubLabel?: string;
     dataKey: string;
     nameKey: string;
 }) => {
📝 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
data: any[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
}) => {
interface DonutChartData {
[key: string]: string | number;
}
const DonutChart = ({
data,
config,
innerLabel,
innerSubLabel,
dataKey,
nameKey,
}: {
data: DonutChartData[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
}) => {
// ... implementation details
}

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: 0

🧹 Nitpick comments (3)
frontend/app/shadcn/chart.tsx (3)

34-61: Consider extracting the long className string into a constant.

The className string at line 50 is quite long and could be harder to maintain. Consider extracting it into a constant or using a CSS module for better maintainability.

+const CHART_BASE_CLASSES = "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-hidden [&_.recharts-surface]:outline-hidden";

 const ChartContainer = React.forwardRef<
   // ...
   className={cn(
-    "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-hidden [&_.recharts-surface]:outline-hidden",
+    CHART_BASE_CLASSES,
     className
   )}

94-234: Consider extracting tooltip content rendering into smaller components.

The ChartTooltipContent component is quite complex. Consider breaking down the JSX into smaller components for better maintainability:

  • TooltipLabel (lines 125-147)
  • TooltipItem (lines 165-228)

Example extraction for TooltipLabel:

const TooltipLabel: React.FC<{
  hideLabel: boolean;
  payload: any[];
  labelFormatter?: (value: any, payload: any[]) => React.ReactNode;
  labelClassName?: string;
  label?: string;
  config: ChartConfig;
  labelKey?: string;
}> = ({ hideLabel, payload, labelFormatter, labelClassName, label, config, labelKey }) => {
  if (hideLabel || !payload?.length) {
    return null;
  }

  const [item] = payload;
  const key = `${labelKey || item.dataKey || item.name || "value"}`;
  const itemConfig = getPayloadConfigFromPayload(config, item, key);
  const value = !labelKey && typeof label === "string"
    ? config[label as keyof typeof config]?.label || label
    : itemConfig?.label;

  if (labelFormatter) {
    return <div className={cn("font-medium", labelClassName)}>{labelFormatter(value, payload)}</div>;
  }

  if (!value) {
    return null;
  }

  return <div className={cn("font-medium", labelClassName)}>{value}</div>;
};

291-318: Consider improving type safety in the helper function.

The getPayloadConfigFromPayload function uses type assertions that could be made safer:

  1. Consider creating a type for the expected payload structure
  2. Use type guards instead of type assertions

Example improvement:

type ChartPayload = {
  payload?: Record<string, unknown>;
  [key: string]: unknown;
};

function isChartPayload(payload: unknown): payload is ChartPayload {
  return typeof payload === "object" && payload !== null;
}

function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
  if (!isChartPayload(payload)) {
    return undefined;
  }
  // ... rest of the implementation
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff3c47b and 377b2e1.

📒 Files selected for processing (3)
  • frontend/app/shadcn/chart.tsx (1 hunks)
  • frontend/tailwindsetup.css (1 hunks)
  • index.html (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • index.html
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/tailwindsetup.css
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/app/shadcn/chart.tsx

[error] 72-72: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

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

11-32: LGTM! Well-structured type definitions and context setup.

The type definitions are flexible and the context setup follows React best practices with proper error handling.


236-290: LGTM! Clean legend implementation.

The ChartLegend and ChartLegendContent components are well-implemented with:

  • Proper null checks for payload
  • Flexible icon support
  • Clean styling approach

63-90: Regarding the use of dangerouslySetInnerHTML for dynamic styles.

While static analysis flags this as a potential XSS vulnerability, the implementation is safe because:

  1. The HTML content is derived from controlled inputs (config object and theme constants).
  2. The generated content is strictly CSS variables.
  3. This is a common pattern for dynamic theming.

To verify the safety of the dynamic styles, run this script to check if the config values are properly sanitized:

✅ Verification successful

Dynamic style injection is safe in this implementation.

The generated CSS is constructed only from controlled sources—the internal theme constants and the configuration for colors—which strictly results in CSS variable declarations. There's no user-supplied HTML or script, and the string construction is limited to template literals for CSS styles only.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if ChartStyle component properly sanitizes CSS values
# Look for direct value assignments without sanitization

ast-grep --pattern $'style
  dangerouslySetInnerHTML={{
    __html: $$$
  }}'

Length of output: 78


Script:

#!/bin/bash
# Retrieve the full context of the ChartStyle component in the file to better assess how CSS values are constructed
rg "const ChartStyle" -A 50 frontend/app/shadcn/chart.tsx

Length of output: 1454

🧰 Tools
🪛 Biome (1.9.4)

[error] 72-72: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

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: 1

🧹 Nitpick comments (1)
electron.vite.config.ts (1)

66-72: Consider documenting the SCSS configuration.

The SCSS configuration silences mixed declarations warnings. Consider adding a comment explaining why this configuration is necessary to help future maintainers understand the decision.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c6e345 and f186458.

⛔ Files ignored due to path filters (5)
  • public/fonts/firacode-bold.woff2 is excluded by !**/*.woff2
  • public/fonts/firacode-regular.woff2 is excluded by !**/*.woff2
  • public/fonts/lato-bold.woff is excluded by !**/*.woff
  • public/fonts/lato-regular.woff is excluded by !**/*.woff
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • electron.vite.config.ts (5 hunks)
  • frontend/app/app.tsx (1 hunks)
  • frontend/app/reset.scss (1 hunks)
  • frontend/tailwindsetup.css (1 hunks)
  • frontend/util/fontutil.ts (0 hunks)
  • package.json (4 hunks)
💤 Files with no reviewable changes (1)
  • frontend/util/fontutil.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/app/app.tsx
  • package.json
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/tailwindsetup.css

[error] 39-39: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (4)
electron.vite.config.ts (1)

4-4: LGTM! Tailwind CSS integration looks good.

The addition of the Tailwind CSS plugin and its configuration in the renderer plugins array is correctly implemented.

Also applies to: 81-81

frontend/tailwindsetup.css (1)

4-37: Well-structured theme variables!

The theme variables are well-organized with a comprehensive color system, typography settings, and consistent naming conventions.

frontend/app/reset.scss (2)

4-197: Excellent reset styles implementation!

The reset styles are comprehensive and well-structured:

  • Proper use of @layer base for Tailwind integration
  • Good accessibility considerations (e.g., text-size-adjust, tap-highlight-color)
  • Modern CSS features (color-mix, logical properties)

119-122: Consider browser support for color-mix.

The use of color-mix() is modern but might need a fallback for older browsers.

✅ Verification successful

Browser Support for color-mix() Verified – Fallbacks Optional for Legacy Targets

Modern browsers now fully support color-mix() (Chrome 111+, Edge 111+, Firefox 113+, Safari 16.2+, Opera 97+). While its usage is safe for most users, if your audience might include those on older browsers, consider adding fallback declarations (e.g., a dual declaration or using feature queries).

  • Modern browser support is broad as of mid‑2023.
  • Fallback strategies (like setting a plain color or using an @supports block) are recommended if legacy browser compatibility is a requirement.
🏁 Scripts executed

The following scripts were executed for the analysis:

Web query:

What is the current browser support for CSS color-mix()?

Length of output: 4518

--radius: 8px;
}

@import "tailwindcss";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Move @import statement to the top of the file.

The @import rule must precede all other rules in a stylesheet. Move it before the @theme block to ensure proper CSS processing.

-@theme {
+@import "tailwindcss";
+
+@theme {
    /* ... theme variables ... */
}
-
-@import "tailwindcss";
📝 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
@import "tailwindcss";
@import "tailwindcss";
@theme {
/* ... theme variables ... */
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 39-39: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

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: 0

♻️ Duplicate comments (1)
frontend/tailwindsetup.css (1)

40-40: ⚠️ Potential issue

Move @import statement to the top of the file.

The @import rule must precede all other rules in a stylesheet. Move it before the @theme block to ensure proper CSS processing.

-@theme {
+@import "tailwindcss";
+
+@theme {
    /* ... theme variables ... */
}
-
-@import "tailwindcss";
🧰 Tools
🪛 Biome (1.9.4)

[error] 40-40: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

🧹 Nitpick comments (1)
frontend/app/workspace/workspace.tsx (1)

82-85: LGTM! Consider extracting common widget styles.

The migration to Tailwind utility classes is well-done. However, since these widget styles might be reused elsewhere, consider extracting them into a reusable class using Tailwind's @apply directive.

Example:

/* In tailwindsetup.css */
.widget-base {
  @apply flex flex-col justify-center items-center w-full py-1.5 pr-0.5 text-secondary text-lg overflow-hidden rounded-sm hover:bg-highlightbg hover:text-white cursor-pointer;
}

Then use it with clsx:

-className={clsx(
-  "flex flex-col justify-center items-center w-full py-1.5 pr-0.5 text-secondary text-lg overflow-hidden rounded-sm hover:bg-highlightbg hover:text-white cursor-pointer",
-  widget["display:hidden"] && "hidden"
-)}
+className={clsx(
+  "widget-base",
+  widget["display:hidden"] && "hidden"
+)}

Also applies to: 89-96

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f186458 and 6c19cba.

📒 Files selected for processing (3)
  • frontend/app/workspace/workspace.scss (0 hunks)
  • frontend/app/workspace/workspace.tsx (4 hunks)
  • frontend/tailwindsetup.css (1 hunks)
💤 Files with no reviewable changes (1)
  • frontend/app/workspace/workspace.scss
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/tailwindsetup.css

[error] 40-40: This @import is in the wrong position.

Any @import rules must precede all other valid at-rules and style rules in a stylesheet (ignoring @charset and @layer), or else the @import rule is invalid.
Consider moving import position.

(lint/correctness/noInvalidPositionAtImportRule)

⏰ 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/workspace/workspace.tsx (2)

60-60: LGTM! Clean migration to Tailwind CSS.

The changes successfully migrate the component from SCSS to Tailwind utility classes while maintaining the same layout and functionality.

Also applies to: 64-64


105-105: LGTM! Improved layout and type safety.

The changes successfully migrate the layout to Tailwind utility classes while improving type safety with strict equality comparison.

Also applies to: 107-107, 109-109

frontend/tailwindsetup.css (1)

4-38: LGTM! Well-organized theme setup.

The theme setup is comprehensive and well-organized with:

  • A consistent color palette with accent variations
  • Clear font family definitions
  • Standardized text sizes
  • Common UI variables

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: 1

🧹 Nitpick comments (2)
frontend/app/element/donutchart.tsx (2)

6-17: Consider enhancing color constants with types and documentation.

The color constants could benefit from the following improvements:

  1. Add TypeScript types for color values
  2. Add JSDoc comments explaining the purpose of each color
  3. Consider color-blind friendly alternatives
+/** Colors used for chart segments. Ensure these are accessible and color-blind friendly. */
+type ChartColor = `#${string}`;
+const DEFAULT_COLORS: ChartColor[] = [
-const DEFAULT_COLORS = [
     "#3498db", // blue
     "#2ecc71", // green
     "#e74c3c", // red
     "#f1c40f", // yellow
     "#9b59b6", // purple
     "#1abc9c", // turquoise
     "#e67e22", // orange
     "#34495e", // dark blue
 ];

+/** Color used when no data is available */
+const NO_DATA_COLOR: ChartColor = "#E0E0E0";
-const NO_DATA_COLOR = "#E0E0E0";

19-46: Consider memoizing PieInnerLabel and adding documentation.

The component could benefit from memoization and proper documentation.

+/**
+ * Renders the inner label and optional sub-label of a pie chart.
+ * @param innerLabel - The main text to display in the center
+ * @param innerSubLabel - Optional secondary text below the main label
+ * @param viewBox - The chart's viewBox for positioning
+ * @returns The rendered label or null if conditions aren't met
+ */
+const PieInnerLabel: React.FC<{
+    innerLabel: string;
+    innerSubLabel: string;
+    viewBox: ViewBox;
+}> = React.memo(({
-const PieInnerLabel = ({
     innerLabel,
     innerSubLabel,
     viewBox,
-}: {
-    innerLabel: string;
-    innerSubLabel: string;
-    viewBox: ViewBox;
-}) => {
+}) => {
     if (isBlank(innerLabel)) {
         return null;
     }
     if (!viewBox || !("cx" in viewBox) || !("cy" in viewBox)) {
         return null;
     }
     return (
         <text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle">
             <tspan x={viewBox.cx} y={viewBox.cy} fill="white" className="fill-foreground text-2xl font-bold">
                 {innerLabel}
             </tspan>
             {innerSubLabel && (
                 <tspan x={viewBox.cx} y={(viewBox.cy || 0) + 24} className="fill-muted-foreground">
                     {innerSubLabel}
                 </tspan>
             )}
         </text>
     );
-};
+});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c19cba and f15a0e2.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • electron.vite.config.ts (2 hunks)
  • frontend/app/element/donutchart.tsx (1 hunks)
  • package.json (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (3)
electron.vite.config.ts (2)

4-4: LGTM! Import of Tailwind CSS plugin.

The import aligns with the PR objective of adding Tailwind CSS support.


67-73: Verify the necessity of silencing SCSS mixed declarations warnings.

While silencing deprecation warnings can reduce noise, it might hide potential issues. Consider addressing the mixed declarations instead of silencing them.

Run this script to find mixed declarations in SCSS files:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for potential mixed declarations in SCSS files
fd -e scss -x rg -l '^\s*\$.*:.*;\s*$' {} \; | while read -r file; do
  echo "=== $file ==="
  rg '^\s*\$.*:.*;\s*$' "$file"
done

Length of output: 326


Mixed declarations suppression appears to be unnecessary based on current SCSS code findings.

  • The executed script shows only standard variable declarations (as in typingindicator.scss), with no instances of mixed declarations.
  • There’s no evidence from the codebase that typical mixed declarations warnings are triggered.
  • Consider revisiting this configuration if future updates to the Sass compiler start emitting mixed declarations warnings.
frontend/app/element/donutchart.tsx (1)

56-62: Add proper TypeScript types for data prop.

The data prop is typed as any[] which loses type safety.

Comment on lines +48 to +90
const DonutChart = ({
data,
config,
innerLabel,
innerSubLabel,
dataKey,
nameKey,
}: {
data: any[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
}) => {
return (
<div className="flex flex-col items-center w-full h-full">
<ChartContainer config={config} className="mx-auto w-full h-full aspect-square max-h-[250px]">
<PieChart>
<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
<Pie
data={data}
dataKey={dataKey}
nameKey={nameKey}
innerRadius={60}
strokeWidth={5}
isAnimationActive={false}
>
<Label
content={({ viewBox }) => (
<PieInnerLabel
innerLabel={innerLabel}
innerSubLabel={innerSubLabel}
viewBox={viewBox}
/>
)}
/>
</Pie>
</PieChart>
</ChartContainer>
</div>
);
};
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 error handling and customization options.

Consider the following improvements:

  1. Add error handling for empty data
  2. Allow color customization
  3. Add proper documentation
+/**
+ * A donut chart component that displays data in a circular format with an optional inner label.
+ * @param data - Array of data points to display
+ * @param config - Chart configuration
+ * @param innerLabel - Optional text to display in the center
+ * @param innerSubLabel - Optional secondary text below the inner label
+ * @param dataKey - Key to use for data values
+ * @param nameKey - Key to use for segment names
+ * @param colors - Optional array of colors to override defaults
+ */
 const DonutChart = ({
     data,
     config,
     innerLabel,
     innerSubLabel,
     dataKey,
     nameKey,
+    colors = DEFAULT_COLORS,
 }: {
     data: any[];
     config: ChartConfig;
     innerLabel?: string;
     innerSubLabel?: string;
     dataKey: string;
     nameKey: string;
+    colors?: string[];
 }) => {
+    if (!data?.length) {
+        return (
+            <div className="flex items-center justify-center w-full h-full text-muted-foreground">
+                No data available
+            </div>
+        );
+    }
+
     return (
         <div className="flex flex-col items-center w-full h-full">
             <ChartContainer config={config} className="mx-auto w-full h-full aspect-square max-h-[250px]">
                 <PieChart>
                     <ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
                     <Pie
                         data={data}
                         dataKey={dataKey}
                         nameKey={nameKey}
                         innerRadius={60}
                         strokeWidth={5}
                         isAnimationActive={false}
+                        fill={NO_DATA_COLOR}
+                    >
+                        {data.map((_, index) => (
+                            <Cell key={`cell-${index}`} fill={colors[index % colors.length]} />
+                        ))}
-                    >
📝 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 DonutChart = ({
data,
config,
innerLabel,
innerSubLabel,
dataKey,
nameKey,
}: {
data: any[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
}) => {
return (
<div className="flex flex-col items-center w-full h-full">
<ChartContainer config={config} className="mx-auto w-full h-full aspect-square max-h-[250px]">
<PieChart>
<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
<Pie
data={data}
dataKey={dataKey}
nameKey={nameKey}
innerRadius={60}
strokeWidth={5}
isAnimationActive={false}
>
<Label
content={({ viewBox }) => (
<PieInnerLabel
innerLabel={innerLabel}
innerSubLabel={innerSubLabel}
viewBox={viewBox}
/>
)}
/>
</Pie>
</PieChart>
</ChartContainer>
</div>
);
};
/**
* A donut chart component that displays data in a circular format with an optional inner label.
* @param data - Array of data points to display
* @param config - Chart configuration
* @param innerLabel - Optional text to display in the center
* @param innerSubLabel - Optional secondary text below the inner label
* @param dataKey - Key to use for data values
* @param nameKey - Key to use for segment names
* @param colors - Optional array of colors to override defaults
*/
const DonutChart = ({
data,
config,
innerLabel,
innerSubLabel,
dataKey,
nameKey,
colors = DEFAULT_COLORS,
}: {
data: any[];
config: ChartConfig;
innerLabel?: string;
innerSubLabel?: string;
dataKey: string;
nameKey: string;
colors?: string[];
}) => {
if (!data?.length) {
return (
<div className="flex items-center justify-center w-full h-full text-muted-foreground">
No data available
</div>
);
}
return (
<div className="flex flex-col items-center w-full h-full">
<ChartContainer config={config} className="mx-auto w-full h-full aspect-square max-h-[250px]">
<PieChart>
<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
<Pie
data={data}
dataKey={dataKey}
nameKey={nameKey}
innerRadius={60}
strokeWidth={5}
isAnimationActive={false}
fill={NO_DATA_COLOR}
>
{data.map((_, index) => (
<Cell key={`cell-${index}`} fill={colors[index % colors.length]} />
))}
<Label
content={({ viewBox }) => (
<PieInnerLabel
innerLabel={innerLabel}
innerSubLabel={innerSubLabel}
viewBox={viewBox}
/>
)}
/>
</Pie>
</PieChart>
</ChartContainer>
</div>
);
};

@sawka sawka merged commit 6e2ff6c into main Feb 5, 2025
9 of 10 checks passed
@sawka sawka deleted the sawka/tailwind branch February 5, 2025 01:58
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