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

🚨 Fix some lint warning #240

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

🚨 Fix some lint warning #240

wants to merge 1 commit into from

Conversation

FelixLgr
Copy link
Collaborator

@FelixLgr FelixLgr commented Dec 17, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced selection handling in the Select component for improved user experience.
  • Bug Fixes

    • Addressed cursor jump issues in the Input component during text input.
  • Documentation

    • Updated prop documentation across several components to reflect changes in parameters and imports.
  • Style

    • Standardized quotation marks in JSX attributes across multiple components for consistency.
  • Chores

    • Removed unused imports and props from various components to streamline code.
  • Refactor

    • Simplified logic in the Modal and Link components for better maintainability.
  • Tests

    • Improved type safety in several components, including Radio and ProgressRadial.

@FelixLgr FelixLgr self-assigned this Dec 17, 2024
Copy link

coderabbitai bot commented Dec 17, 2024

Walkthrough

This pull request encompasses a series of minor modifications across multiple React components in the packages directory. The changes primarily involve formatting adjustments, such as switching quotation marks from double to single, removing unused imports, and making subtle type refinements. These modifications aim to improve code consistency, remove unnecessary code, and enhance type safety without significantly altering the core functionality of the components.

Changes

File Change Summary
packages/react/components/badge/Badge.native.tsx Reformatted import statements
packages/react/components/breadcrumb/Breadcrumb.tsx Changed role attribute quotes from double to single
packages/react/components/chips/list/ChipsList.tsx Changed role attribute quotes from double to single
packages/react/components/columns/Columns.native.tsx Added type annotation for child parameter in React.Children.map
packages/react/components/divider/Divider.native.tsx Removed inverted prop from component signature
packages/react/components/icon/Icon.tsx Changed aria-hidden attribute quotes from double to single
packages/react/components/icon/IconProps.ts Removed imports for IconStatus and IconStatusValues
packages/react/components/input/Input.tsx Added textContentType prop, changed quotation marks
packages/react/components/link/Link.native.tsx Removed linkLevels and getHeightLinkAndroid functions
packages/react/components/modal/Modal.tsx Removed onOpen and unClosable parameters
packages/react/components/price/Price.native.tsx Updated import statements, removed TypographyColor
packages/react/components/price/Price.tsx Removed TypographyBold and TypographyColor imports
packages/react/components/progress/Progress.tsx Changed class name attribute quotes from double to single
packages/react/components/progress/radial/ProgressRadial.tsx Updated animationFrameId type from any to number
packages/react/components/radio/Radio.native.tsx Updated value parameter type in handleClick
packages/react/components/radio/list/RadioList.native.tsx Consolidated import statements
packages/react/components/select/Select.native.tsx Refined selection logic
packages/react/components/select/option/SelectOption.tsx Changed role attribute quotes from double to single
packages/react/components/select/web/SelectDynamic.tsx Removed focusedIndex state and related logic
packages/react/components/stepper/Stepper.tsx Changed class name quotes from double to single
packages/react/components/tag/Tag.native.tsx Removed iconName prop
packages/react/components/title/Title.native.tsx Removed titleTestId variable
packages/react/objects/Typography/TypographyBold.tsx Removed TextLevels imports, updated style function
packages/react/objects/Typography/TypographyColor.ts Updated import statement formatting
packages/react/objects/facets/Color.tsx Updated colors type definition

Possibly related PRs

Suggested Reviewers

  • JulienMora

Poem

🐰 A Rabbit's Code Refrain 🐰

With single quotes and types so neat,
We trim the code, make logic sweet
Imports removed, functions refined
A cleaner codebase, carefully designed
Hop along, code rabbit, with glee!

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

@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 (13)
packages/react/components/columns/Columns.native.tsx (1)

91-91: Consider using proper React types instead of 'any'

While the eslint-disable comment fixes the immediate lint warning, using any type bypasses TypeScript's type checking benefits. Consider using proper React types for better type safety:

- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (child: any) =>
+ (child: React.ReactElement) =>

This would provide better type safety while still resolving the lint warning.

packages/react/components/radio/Radio.native.tsx (2)

Line range hint 59-71: Good type refinement, consider adding value validation.

The change from any to string type improves type safety and matches the component's props interface.

Consider adding validation for empty string values:

-  const handleClick = (value: string) => {
+  const handleClick = (value: string) => {
+    if (!value.trim()) {
+      return;
+    }
     if (!readonly) {
       if (onChange) {
         onChange({
           radioId: id,
           radioValue: value,
           radioName: name || '',
           radioChecked: true,
         })
       }
     }
   }

73-73: Good operator change, consider memoizing the handler.

The switch to nullish coalescing (??) is more precise than logical OR for handling undefined/null values.

Consider memoizing the onPress handler to prevent unnecessary re-renders:

+  const onPressHandler = React.useCallback(() => handleClick(value ?? ''), [value, handleClick]);
-    <TouchableOpacity disabled={disabled} style={styles.container} onPress={() => handleClick(value ?? '')}>
+    <TouchableOpacity disabled={disabled} style={styles.container} onPress={onPressHandler}>
packages/react/components/select/Select.native.tsx (1)

61-63: Simplify the type checking logic

The current implementation has complex type checking that could be simplified for better readability and maintainability.

Consider this cleaner implementation:

-      (multiple && selectedValues && typeof selectedValues !== 'string' && typeof selectedValues !== 'number'
-        ? selectedValues?.includes(value)
-        : selectedValues === value),
+      multiple && Array.isArray(selectedValues)
+        ? selectedValues?.includes(value)
+        : selectedValues === value,

This change:

  • Uses Array.isArray() instead of multiple type checks
  • Maintains the same functionality
  • Is more readable and less prone to lint warnings
packages/react/components/select/web/SelectDynamic.tsx (2)

177-177: Remove extra space in role attribute

There's an extra space between role='listbox' and the className prop.

-      {focused && <ul role='listbox'  className={hashClass(styled, clsx('select-options'))}>{options}</ul>}
+      {focused && <ul role='listbox' className={hashClass(styled, clsx('select-options'))}>{options}</ul>}

2-7: Consider extracting shared logic into custom hooks

Both Select.native.tsx and SelectDynamic.tsx share similar logic for handling selections and state management. Consider creating custom hooks to:

  • Manage selection state
  • Handle focus state
  • Process options

This would:

  • Reduce code duplication
  • Improve maintainability
  • Make the components more focused

Example structure:

// useSelect.ts
export const useSelect = (props: SelectProps) => {
  const [selectedValues, setSelectedValues] = useState<SelectedValue>(props.selected);
  const [selectedNames, setSelectedNames] = useState<string[]>([]);
  
  // ... shared logic for isChecked, setNewSelectedValues, etc.
  
  return {
    selectedValues,
    selectedNames,
    isChecked,
    setNewSelectedValues,
    // ... other shared functionality
  };
};
packages/react/components/input/Input.tsx (2)

Line range hint 301-302: Consider improving type safety

The type assertion as unknown as IconName is a code smell that might indicate underlying type issues. Consider defining proper types for iconNameLeft and iconNameRight props instead of using type assertions.

- {iconNameLeft && !loading && <IconWrapper className={'icon-left'} name={iconNameLeft as unknown as IconName} />}
+ {iconNameLeft && !loading && <IconWrapper className={'icon-left'} name={iconNameLeft} />}

This would require updating the InputProp interface to properly type these props:

interface InputProp extends Accessibility, InputProps, InputWebEvents {
  iconNameLeft?: IconName;
  iconNameRight?: IconName;
}

Line range hint 1-324: Consider consolidating state management

The component uses multiple useState hooks that are closely related. Consider using useReducer to manage related state in a more maintainable way, particularly for:

  • isFocused, isDirty, and isTouched
  • inputType and isShowPwd
packages/react/components/tag/Tag.native.tsx (1)

Line range hint 8-18: Update JSDoc to match implementation

The JSDoc still documents the iconName parameter but according to the AI summary, this prop was intended to be removed.

- * @param iconName {IconName} display icon
packages/react/components/price/Price.tsx (1)

Line range hint 147-150: Consider extracting accessibility text generation

The accessibility label logic could be extracted into a helper function for better maintainability.

+const getPriceAccessibilityLabel = (accessibilityLabel: string | undefined, priceText: string): string => {
+  return accessibilityLabel || priceText || 'NotSpecified'
+}
+
 const Price = ({
   // ...props
 }) => {
   // ...
   const priceText = `${whole}€${hideCents ? cents : ''}${mention ? mention : ''}${period ? ` / ${period}` : ''}`
   const priceTestId = testId ? testId : priceText ? priceText : 'NotSpecified'
-  const priceAccessibilityLabel = accessibilityLabel ? accessibilityLabel : priceText ? priceText : 'NotSpecified'
+  const priceAccessibilityLabel = getPriceAccessibilityLabel(accessibilityLabel, priceText)
packages/react/components/price/Price.native.tsx (2)

Line range hint 108-166: Consider extracting level-based style calculations

The price level calculations are complex and repeated. Consider extracting them into helper functions for better maintainability.

+const getPriceLevelSize = (level: PriceLevel): number => {
+  switch(level) {
+    case PriceLevel.ONE: return 64;
+    case PriceLevel.TWO: return 56;
+    case PriceLevel.THREE: return 44;
+    case PriceLevel.FOUR: return 32;
+    case PriceLevel.FIVE: return 28;
+    case PriceLevel.SIX: return 24;
+    case PriceLevel.SEVEN: return 20;
+    default: return 44;
+  }
+}

 const Price = ({
   // ...props
 }) => {
   // ...
-  const priceLevel =
-    (level == PriceLevel.ONE && 64) ||
-    (level == PriceLevel.TWO && 56) ||
-    (level == PriceLevel.THREE && 44) ||
-    (level == PriceLevel.FOUR && 32) ||
-    (level == PriceLevel.FIVE && 28) ||
-    (level == PriceLevel.SIX && 24) ||
-    (level == PriceLevel.SEVEN && 20) ||
-    44
+  const priceLevel = getPriceLevelSize(level)

Line range hint 168-219: Extract rotation and position calculations

The strikedRotateByLevel and strikedBottomByLevel functions contain complex conditional logic that could be simplified using lookup tables or helper functions.

+const ROTATION_MAP = {
+  [PriceLevel.SEVEN]: { withCents: '-18deg', default: '-22deg' },
+  [PriceLevel.SIX]: { withCents: '-19deg', default: '-22deg' },
+  // ... add other levels
+};

+const getStrikedRotation = (level: PriceLevel, hasCents: boolean): string => {
+  if (!level) return hasCents ? '-15deg' : '-20deg';
+  return ROTATION_MAP[level]?.[hasCents ? 'withCents' : 'default'] ?? '-20deg';
+}

 const Price = ({
   // ...props
 }) => {
   // ...
-  const strikedRotateByLevel = () => {
-    return (
-      (level == PriceLevel.SEVEN && (hideCents || period) && '-18deg') ||
-      // ... existing conditions
-      '-20deg'
-    )
-  }
+  const strikedRotation = getStrikedRotation(level, hideCents || !!period)
packages/react/objects/facets/Color.tsx (1)

Line range hint 126-132: Consider improving browser detection and error handling.

The current browser detection logic using navigator.userAgent === undefined seems unusual and might not reliably detect all environments.

Consider:

  1. Using a more standard approach for environment detection
  2. Adding proper error handling for undefined color values
 export const getColorStyle = (trilogyColor: TrilogyColor | TrilogyColorValues): string => {
-  if (typeof navigator !== 'undefined' && navigator.userAgent === undefined) {
+  if (typeof window !== 'undefined') {
     const { theme } = useContext(TrilogyThemeContext)
     const colorsStyle = theme?.colors || colors
 
-    const colorArray = colorsStyle[trilogyColor] || colorsStyle.default
-    if (!trilogyColor || !colors[trilogyColor]) {
-      return colorsStyle.default
+    if (!trilogyColor || !colorsStyle[trilogyColor]) {
+      return colorsStyle[TrilogyColor.MAIN][0]
     }
-    return colorArray[0]
+    return colorsStyle[trilogyColor][0]
   } else {
     return colors[trilogyColor][0] || colors[TrilogyColor.MAIN][0]
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44f4c6f and 88e8ce1.

📒 Files selected for processing (25)
  • packages/react/components/badge/Badge.native.tsx (1 hunks)
  • packages/react/components/breadcrumb/Breadcrumb.tsx (1 hunks)
  • packages/react/components/chips/list/ChipsList.tsx (1 hunks)
  • packages/react/components/columns/Columns.native.tsx (1 hunks)
  • packages/react/components/divider/Divider.native.tsx (0 hunks)
  • packages/react/components/icon/Icon.tsx (1 hunks)
  • packages/react/components/icon/IconProps.ts (1 hunks)
  • packages/react/components/input/Input.tsx (2 hunks)
  • packages/react/components/link/Link.native.tsx (0 hunks)
  • packages/react/components/modal/Modal.tsx (0 hunks)
  • packages/react/components/price/Price.native.tsx (1 hunks)
  • packages/react/components/price/Price.tsx (1 hunks)
  • packages/react/components/progress/Progress.tsx (1 hunks)
  • packages/react/components/progress/radial/ProgressRadial.tsx (1 hunks)
  • packages/react/components/radio/Radio.native.tsx (2 hunks)
  • packages/react/components/radio/list/RadioList.native.tsx (1 hunks)
  • packages/react/components/select/Select.native.tsx (1 hunks)
  • packages/react/components/select/option/SelectOption.tsx (2 hunks)
  • packages/react/components/select/web/SelectDynamic.tsx (3 hunks)
  • packages/react/components/stepper/Stepper.tsx (1 hunks)
  • packages/react/components/tag/Tag.native.tsx (1 hunks)
  • packages/react/components/title/Title.native.tsx (0 hunks)
  • packages/react/objects/Typography/TypographyBold.tsx (0 hunks)
  • packages/react/objects/Typography/TypographyColor.ts (1 hunks)
  • packages/react/objects/facets/Color.tsx (2 hunks)
💤 Files with no reviewable changes (5)
  • packages/react/components/link/Link.native.tsx
  • packages/react/components/divider/Divider.native.tsx
  • packages/react/components/title/Title.native.tsx
  • packages/react/objects/Typography/TypographyBold.tsx
  • packages/react/components/modal/Modal.tsx
✅ Files skipped from review due to trivial changes (9)
  • packages/react/components/breadcrumb/Breadcrumb.tsx
  • packages/react/components/chips/list/ChipsList.tsx
  • packages/react/components/stepper/Stepper.tsx
  • packages/react/components/select/option/SelectOption.tsx
  • packages/react/components/badge/Badge.native.tsx
  • packages/react/components/radio/list/RadioList.native.tsx
  • packages/react/components/icon/Icon.tsx
  • packages/react/objects/Typography/TypographyColor.ts
  • packages/react/components/progress/Progress.tsx
🔇 Additional comments (9)
packages/react/components/progress/radial/ProgressRadial.tsx (1)

68-68: LGTM! Good type safety improvement

The explicit number type for animationFrameId correctly matches the return type of requestAnimationFrame. This improves type safety without needing eslint-disable comments.

packages/react/components/input/Input.tsx (1)

213-213: LGTM: Quote style consistency changes

The changes from double to single quotes align with the PR's objective of fixing lint warnings.

Also applies to: 223-223

packages/react/components/icon/IconProps.ts (2)

Line range hint 8-18: LGTM! Interface definition is well-structured.

The IconProps interface is properly typed with all necessary imports present for the defined properties.


1-3: LGTM! Removal of unused imports.

The removal of IconStatus and IconStatusValues imports aligns with fixing lint warnings, as these types are not used in the interface definition.

Let's verify there are no remaining references to these removed types:

packages/react/components/price/Price.tsx (1)

6-6: LGTM! Import cleanup aligns with lint fixes

The simplified import from '@/objects' improves code organization.

packages/react/components/price/Price.native.tsx (1)

Line range hint 7-12: LGTM! Import organization improved

The imports are now properly organized using the @/objects alias.

packages/react/objects/facets/Color.tsx (3)

32-32: Great type safety improvement!

Replacing Record<any, string[]> with Record<TrilogyColor, string[]> enforces proper type checking and removes the unsafe any type. This change aligns with TypeScript best practices.


131-131: Good use of enum value for type safety.

Using TrilogyColor.MAIN instead of string literal improves type safety and maintainability.


Line range hint 1-171: Verify remaining lint warnings.

Let's check if there are any remaining lint issues in the file.

✅ Verification successful

No significant lint issues found in Color.tsx

The file appears to be well-typed and follows TypeScript best practices:

  • All enums, types, and function parameters have explicit type annotations
  • Return types are properly specified
  • The only undefined check is intentional for environment detection
  • No TODO/FIXME comments or lint-disable directives
  • No usage of any type
  • Imports are properly typed and used

The only potential improvement would be to make the environment check more idiomatic, but it's not a lint issue.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining lint warnings in the file

# Look for any TODO, FIXME, or lint-disable comments
rg -i "todo|fixme|lint|tslint|eslint" "packages/react/objects/facets/Color.tsx"

# Look for any 'any' types that might trigger lint warnings
rg "any" "packages/react/objects/facets/Color.tsx"

# Look for potential unused variables/imports
ast-grep --pattern 'import { $_ } from $_'

Length of output: 173


Script:

#!/bin/bash
# Let's try a more comprehensive analysis

# Check TypeScript-specific patterns that might indicate lint issues
echo "=== Checking function parameters without explicit types ==="
ast-grep --pattern 'function $name($params) { $$$}'

echo "=== Checking variable declarations without types ==="
ast-grep --pattern 'const $name = $_'

echo "=== Checking imports ==="
ast-grep --pattern 'import { $_ } from "$_"'
ast-grep --pattern "import { $_ } from '@_'"

echo "=== Checking function return types ==="
ast-grep --pattern 'function $name($_): $_ { $$$}'
ast-grep --pattern 'const $name = ($_): $_ => $_'

echo "=== Checking for potential undefined checks ==="
rg "undefined" "packages/react/objects/facets/Color.tsx"

echo "=== Checking ESLint configuration ==="
fd -e .eslintrc -e .eslintrc.js -e .eslintrc.json

Length of output: 26683

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