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

feat(assets): add new "dynamic" illustrations for start screen #3631

Conversation

FussuChalice
Copy link
Contributor

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published in downstream modules

@rhahao
Copy link
Member

rhahao commented Feb 15, 2025

Copy link

vercel bot commented Feb 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
organized-app ✅ Ready (Inspect) Visit Preview Feb 17, 2025 4:33pm
staging-organized-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 17, 2025 4:33pm
test-organized-app ✅ Ready (Inspect) Visit Preview Feb 17, 2025 4:33pm

Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Walkthrough

This pull request introduces a new React component called SVGAsImage that converts an SVG source into a base64-encoded image using a custom React hook, useSVGAsImage. Alongside its dedicated type alias, SVGAsImageProps, the implementation handles fetching the SVG, substituting CSS variables, and encoding it for rendering as an HTML <img> element. Additionally, the changes update an existing illustration component to utilize SVGAsImage and remove a previously used image asset.

Changes

File(s) Summary
src/components/svg_as_image/index.tsx, src/components/svg_as_image/index.types.ts, src/components/svg_as_image/useSVGAsImage.tsx Added the SVGAsImage component, its type alias SVGAsImageProps, and the useSVGAsImage hook to fetch, process, and encode SVGs for rendering.
src/features/app_start/shared/illustration/index.tsx Updated the StartupIllustration component to import and use SVGAsImage instead of an <img> tag, and modified the background style to use a CSS variable.
src/features/app_start/shared/illustration/useIllustration.tsx Commented out the import and slide object for the Territories SVG illustration, effectively removing it from the slides.

Sequence Diagram(s)

sequenceDiagram
    participant UI as SVGAsImage Component
    participant Hook as useSVGAsImage Hook
    participant Fetch as Network/Fetch
    participant Util as getCSSPropertyValue Utility

    UI->>Hook: Provide SVG source via props
    Hook->>Fetch: Fetch SVG content
    Fetch-->>Hook: Return raw SVG data
    Hook->>Util: Substitute CSS variable references in SVG
    Util-->>Hook: Return processed SVG text
    Hook->>Hook: Encode SVG text to base64
    Hook-->>UI: Return encoded SVG data
    UI->>UI: Render <img> element with encoded src
Loading

Possibly related PRs

Suggested labels

released


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

🧹 Nitpick comments (3)
src/components/svg_as_image/index.tsx (1)

12-16: Optimize props handling for better performance.

While the implementation is correct, we can optimize the props destructuring:

-const SVGAsImage = (props: SVGAsImageProps) => {
-  const { encodedSVG } = useSVGAsImage({ src: props.src });
-
-  return <img src={encodedSVG} alt={props.alt} style={props.style} />;
+const SVGAsImage = ({ src, alt, style, ...rest }: SVGAsImageProps) => {
+  const { encodedSVG } = useSVGAsImage({ src });
+
+  return <img src={encodedSVG} alt={alt} style={style} {...rest} />;

This change:

  1. Destructures props at the parameter level
  2. Spreads remaining props to support additional img attributes
  3. Reduces prop access overhead
src/components/svg_as_image/useSVGAsImage.tsx (1)

11-33: Implement caching mechanism for performance optimization.

The current implementation fetches and converts the SVG on every mount and theme change. Consider implementing a caching mechanism.

+const svgCache = new Map<string, string>();
+
 const convertSvgToBase64 = async (svgUrl: string): Promise<string> => {
   try {
+    const cacheKey = `${svgUrl}-${theme}`;
+    if (svgCache.has(cacheKey)) {
+      return svgCache.get(cacheKey)!;
+    }
+
     const response = await fetch(svgUrl);
     let svgText = await response.text();
     const regex = /var\(--([^)]*)\)/g;
     let match;

     while ((match = regex.exec(svgText)) !== null) {
       const varName = match[1];
       const value = getCSSPropertyValue(`--${varName}`);
       svgText = svgText.replace(match[0], value);
     }

     const encodedSvg = encodeURIComponent(svgText)
       .replace(/'/g, '%27')
       .replace(/"/g, '%22');

-    return `data:image/svg+xml;charset=utf-8,${encodedSvg}`;
+    const result = `data:image/svg+xml;charset=utf-8,${encodedSvg}`;
+    svgCache.set(cacheKey, result);
+    return result;
   } catch (error) {
     console.error('Error fetching or converting SVG:', error);
+    setError(error instanceof Error ? error : new Error('Failed to convert SVG'));
     return '';
   }
 };
src/features/app_start/shared/illustration/index.tsx (1)

72-75: Handle loading states and implement lazy loading.

The SVGAsImage implementation should handle loading states and implement lazy loading for better performance.

 <SVGAsImage
   src={slide.src}
-  style={{ width: '100%', height: 'auto' }}
+  style={{ 
+    width: '100%', 
+    height: 'auto',
+    opacity: isLoading ? 0.5 : 1,
+    transition: 'opacity 0.2s ease-in-out'
+  }}
+  loading="lazy"
 />

Also, consider handling the loading and error states:

const { encodedSVG, isLoading, error } = useSVGAsImage({ src: slide.src });
if (error) {
  console.error('Failed to load illustration:', error);
  // Render fallback illustration
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 17208e5 and 9ab7ff1.

⛔ Files ignored due to path filters (6)
  • src/assets/img/illustration_meetingSchedules.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_ministryAssignments.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_multiPlattform.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_otherSchedules.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_secretary.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_territories.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (6)
  • src/components/svg_as_image/index.tsx (1 hunks)
  • src/components/svg_as_image/index.types.ts (1 hunks)
  • src/components/svg_as_image/useSVGAsImage.tsx (1 hunks)
  • src/features/app_start/shared/illustration/index.tsx (3 hunks)
  • src/features/app_start/shared/illustration/useIllustration.tsx (2 hunks)
  • src/features/meetings/my_assignments/index.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/features/app_start/shared/illustration/useIllustration.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Code QL
  • GitHub Check: Summary
🔇 Additional comments (3)
src/components/svg_as_image/index.types.ts (1)

1-6: LGTM! Well-structured type definition.

The type definition correctly extends React's built-in types for HTML image elements, providing comprehensive type safety for the SVGAsImage component.

src/features/meetings/my_assignments/index.tsx (2)

12-13: LGTM! Import changes align with new SVG handling approach.

The shift from ?component to ?url and addition of SVGAsImage aligns with the PR's objective of standardizing dynamic illustration handling.


85-85: LGTM! SVG rendering updated with consistent dimensions.

The implementation properly uses the new SVGAsImage component with explicit width and height, ensuring consistent rendering.

@rhahao
Copy link
Member

rhahao commented Feb 16, 2025

Hi @FussuChalice: please could you explain a little bit the purpose of this PR? I failed to get it correctly on first look. Thank you.

@FussuChalice
Copy link
Contributor Author

Hi @FussuChalice: please could you explain a little bit the purpose of this PR? I failed to get it correctly on first look. Thank you.

Added new "dynamic" illustrations for the start screen. The SVG illustrations now use CSS variables, allowing them to change automatically when the theme is updated.

For more details, you can check with Vlad.

@rhahao
Copy link
Member

rhahao commented Feb 17, 2025

@FussuChalice: Yes, I understand that this part of the ClickUp task linked above, but the I do not fully understand the purpose of the changes here. Like in the already working No Notification icon, we just simply import the svg file as a component, and that’s already enough. So that’s why I am wondering do we really this need change, or is there an issue with the current approach that require this new one? Thanks.

@FussuChalice
Copy link
Contributor Author

@FussuChalice: Yes, I understand that this part of the ClickUp task linked above, but the I do not fully understand the purpose of the changes here. Like in the already working No Notification icon, we just simply import the svg file as a component, and that’s already enough. So that’s why I am wondering do we really this need change, or is there an issue with the current approach that require this new one? Thanks.

Sorry, that's a typo, I meant NoAssigmentsImg.
I wrote earlier because I made code that didn't match the code in other components. The size of the illustration was 200 and became 128 (as it was before). This corrected the fact that the picture was getting out of bounds.

@ux-git
Copy link
Member

ux-git commented Feb 17, 2025

This corrected the fact that the picture was getting out of bounds.

@rhahao this should be fixed with this PR:
photo_2025-02-17 09 25 30

@rhahao rhahao force-pushed the CU-86c0wjqg8_FEAT-Link-color-variables-of-SVG-illustrations_Max-Makaluk branch from 334ba31 to ef81feb Compare February 17, 2025 16:31
Copy link

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)
src/components/svg_as_image/index.tsx (1)

4-11: Enhance component documentation with additional details.

While the documentation follows JSDoc conventions, consider adding:

  • Expected format/requirements for the SVG source
  • Loading state handling
  • Error scenarios and their handling
 /**
  * A React component that converts an SVG source into an encoded image and renders it.
  *
+ * @remarks
+ * The SVG source should be a valid SVG file accessible via URL or file path.
+ * The component will show nothing while the SVG is being loaded.
+ * If the SVG fails to load or encode, an error will be thrown.
  *
  * @component
  * @param {SVGAsImageProps} props - The properties for the component.
+ * @param {string} props.src - The source URL or path to the SVG file
+ * @param {string} props.alt - Alternative text for accessibility
+ * @param {React.CSSProperties} [props.style] - Optional CSS styles to apply
  *
  * @returns {JSX.Element} The rendered image element.
  */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ab7ff1 and ef81feb.

⛔ Files ignored due to path filters (7)
  • src/assets/img/illustration_meetingSchedules.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_ministryAssignments.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_multiPlattform.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_no_assigments.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_otherSchedules.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_secretary.svg is excluded by !**/*.svg, !**/*.svg
  • src/assets/img/illustration_territories.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (5)
  • src/components/svg_as_image/index.tsx (1 hunks)
  • src/components/svg_as_image/index.types.ts (1 hunks)
  • src/components/svg_as_image/useSVGAsImage.tsx (1 hunks)
  • src/features/app_start/shared/illustration/index.tsx (3 hunks)
  • src/features/app_start/shared/illustration/useIllustration.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/components/svg_as_image/index.types.ts
  • src/features/app_start/shared/illustration/useIllustration.tsx
  • src/features/app_start/shared/illustration/index.tsx
  • src/components/svg_as_image/useSVGAsImage.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Code QL
  • GitHub Check: Summary
🔇 Additional comments (3)
src/components/svg_as_image/index.tsx (3)

1-2: LGTM! Clean imports with good separation of concerns.

The imports are well-organized, with types properly separated into their own file.


18-18: LGTM! Clean export.

The export follows React conventions.


1-18:

❓ Verification inconclusive

Verify dynamic theming and size constraints.

Based on the PR objectives:

  1. Ensure the useSVGAsImage hook properly handles CSS variables for theme changes
  2. Verify that the component respects size constraints to prevent out-of-bounds issues

Let's verify the implementation:


🏁 Script executed:

#!/bin/bash
# Check if the useSVGAsImage hook handles CSS variables
ast-grep --pattern 'function useSVGAsImage($props) {
  $$$
  // Look for CSS variable handling
  $$$
}'

# Check for size constraints in the StartupIllustration component
rg -A 5 'StartupIllustration.*style'

Length of output: 144


Double-check dynamic theming in the SVG image and ensure image sizing prevents overflow.

Based on the PR objectives, please verify the following:

  • Dynamic Theming:
    Confirm that the useSVGAsImage hook correctly interprets CSS variables (or equivalent theme parameters) so that theme changes automatically update the SVG illustration.

  • Size Constraints:
    Ensure that any rendered images (including usage within components like StartupIllustration) apply size constraints to avert out-of-bounds rendering.

Note: Automated searches for CSS variable handling and references to a StartupIllustration component returned no conclusive evidence. Please manually verify that:

  • The underlying hook (useSVGAsImage) implements theme-aware logic (e.g., using CSS custom properties or similar techniques).
  • Image sizing is managed appropriately either within this component or via its parent component(s).

Comment on lines +12 to +16
const SVGAsImage = (props: SVGAsImageProps) => {
const { encodedSVG } = useSVGAsImage({ src: props.src });

return <img src={encodedSVG} alt={props.alt} style={props.style} />;
};
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 performance optimizations.

The component needs additional robustness and performance improvements:

  1. Add loading state handling
  2. Implement error handling
  3. Optimize with memo for large SVGs
  4. Handle undefined props safely
-const SVGAsImage = (props: SVGAsImageProps) => {
-  const { encodedSVG } = useSVGAsImage({ src: props.src });
+const SVGAsImage = React.memo((props: SVGAsImageProps) => {
+  const { encodedSVG, isLoading, error } = useSVGAsImage({ src: props.src });
+
+  if (error) {
+    console.error('Failed to load SVG:', error);
+    return null; // or fallback image
+  }
+
+  if (isLoading) {
+    return null; // or loading spinner
+  }

-  return <img src={encodedSVG} alt={props.alt} style={props.style} />;
+  return (
+    <img 
+      src={encodedSVG} 
+      alt={props.alt ?? ''} 
+      style={props.style}
+      onError={(e) => {
+        console.error('Failed to render encoded SVG');
+        e.currentTarget.style.display = 'none';
+      }}
+    />
+  );
-};
+});
+
+SVGAsImage.displayName = 'SVGAsImage';
📝 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 SVGAsImage = (props: SVGAsImageProps) => {
const { encodedSVG } = useSVGAsImage({ src: props.src });
return <img src={encodedSVG} alt={props.alt} style={props.style} />;
};
const SVGAsImage = React.memo((props: SVGAsImageProps) => {
const { encodedSVG, isLoading, error } = useSVGAsImage({ src: props.src });
if (error) {
console.error('Failed to load SVG:', error);
return null; // or fallback image
}
if (isLoading) {
return null; // or loading spinner
}
return (
<img
src={encodedSVG}
alt={props.alt ?? ''}
style={props.style}
onError={(e) => {
console.error('Failed to render encoded SVG');
e.currentTarget.style.display = 'none';
}}
/>
);
});
SVGAsImage.displayName = 'SVGAsImage';

@rhahao
Copy link
Member

rhahao commented Feb 17, 2025

@FussuChalice, @ux-git : The clipped image above can be fixed by simply adjusting the viewBox property to match the actual value inside the svg file. I suggest fixing that separately in another PR.

About the approach of dynamically changing the colors for the startup illustration, the current approach in this PR works, but I think it’s too complex and heavy. So I would suggest creating standalone SVG components for each illustration using the the SvgIcon from MUI, a similar method we use for all icons. We can also fine-tune and fix some colors assigned to some illustrations.

Thanks.

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.

3 participants