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

chore(fix): optimise images #36

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

chore(fix): optimise images #36

wants to merge 3 commits into from

Conversation

losndu
Copy link
Contributor

@losndu losndu commented Dec 18, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced image optimization for article thumbnails in both ArticleCard and ArticleSpotlight components.
    • Introduced responsive image loading using <picture> element for hero images.
  • Improvements

    • Added lazy loading and explicit dimensions for images to improve performance.
    • New options for image quality and dimensions with the introduction of dpr parameter.
  • Bug Fixes

    • Ensured legacy functionality remains intact while accommodating new features.

Copy link

vercel bot commented Dec 18, 2024

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

Name Status Preview Comments Updated (UTC)
research-rework ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 18, 2024 0:37am

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces a comprehensive image optimization utility for Cloudinary URLs across multiple Svelte components. The changes focus on creating a centralized optimise-cloudinary.ts utility that provides flexible image transformation options. The implementation adds support for different image types (card, spotlight, hero), includes device pixel ratio (DPR) optimization, and enhances image loading performance through responsive techniques in components like ArticleCard, ArticleSpotlight, and the homepage.

Changes

File Change Summary
src/lib/utils/optimise-cloudinary.ts Added new ImageType type, TransformOptions interface, TRANSFORM_PRESETS constant, and utility functions for URL optimization
src/lib/components/ui/ArticleCard.svelte Imported optimizeCloudinaryUrl, added lazy loading, explicit dimensions, and image URL optimization
src/lib/components/ui/ArticleSpotlight.svelte Imported optimizeCloudinaryUrl, added srcset, sizes, and explicit image dimensions
src/routes/+page.svelte Introduced <picture> element with responsive image sources using optimizeHeroImage and optimizeCloudinaryUrl

Sequence Diagram

sequenceDiagram
    participant Component as Svelte Component
    participant Utility as optimise-cloudinary.ts
    participant Cloudinary as Cloudinary URL

    Component->>Utility: Call optimizeCloudinaryUrl()
    Utility-->>Component: Return optimized URL
    Component->>Cloudinary: Request optimized image
    Cloudinary-->>Component: Serve transformed image
Loading

Possibly related PRs

  • No strongly related PRs identified in the provided context.

Poem

🐰 Cloudinary's Carrot Patch 🥕

Pixels dance with rabbit's might,
Transforming images so bright!
Lazy loading, dimensions clear,
Optimization brings us cheer!
A web performance delight! 🌟

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f66b172 and cac9311.

⛔ Files ignored due to path filters (1)
  • static/hero.png is excluded by !**/*.png
📒 Files selected for processing (5)
  • src/lib/components/ui/ArticleCard.svelte (2 hunks)
  • src/lib/components/ui/ArticleSpotlight.svelte (1 hunks)
  • src/lib/services/article.service.ts (1 hunks)
  • src/lib/utils/optimise-cloudinary.ts (1 hunks)
  • src/routes/+page.svelte (2 hunks)
🧰 Additional context used
🪛 eslint
src/routes/+page.svelte

[error] 11-11: 'optimizeCloudinaryUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 13-13: 'heroImage' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

🔇 Additional comments (4)
src/lib/components/ui/ArticleSpotlight.svelte (1)

4-4: LGTM! Good use of image optimization utility

The implementation correctly uses the optimizeCloudinaryUrl utility with the 'spotlight' type parameter.

Also applies to: 12-12

src/lib/utils/optimise-cloudinary.ts (2)

1-7: LGTM! Well-structured type definitions.

The types are well-defined and properly constrained for the image optimization use case.


39-46: LGTM! Clean URL construction with backward compatibility.

The URL construction logic is correct, and the legacy function is well-documented.

src/routes/+page.svelte (1)

11-14: ⚠️ Potential issue

Remove unused imports and constants.

The following items are imported/defined but never used:

  1. optimizeCloudinaryUrl import
  2. heroImage constant

This suggests the image optimization implementation might be incomplete.

✅ Verification successful

Remove unused imports and constants

The following items are defined but never used in the code:

  1. optimizeCloudinaryUrl import
  2. heroImage constant

The heroImage constant is only defined but never referenced in the code, and the hero image is instead loaded from static files (/hero-720w.webp). The optimizeCloudinaryUrl import is also unused in this file, though it is actively used in other components like ArticleSpotlight and ArticleCard.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if heroImage is used elsewhere in the codebase
rg "heroImage" --type svelte

Length of output: 59


Script:

#!/bin/bash
# Check if heroImage is used in the file content
rg "heroImage"

# Check if optimizeCloudinaryUrl is used in the file content
rg "optimizeCloudinaryUrl"

# Show the content of the file to verify usage
cat "src/routes/+page.svelte"

Length of output: 3297

🧰 Tools
🪛 eslint

[error] 11-11: 'optimizeCloudinaryUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 13-13: 'heroImage' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

src/lib/services/article.service.ts Outdated Show resolved Hide resolved
src/lib/components/ui/ArticleSpotlight.svelte Outdated Show resolved Hide resolved
src/lib/components/ui/ArticleCard.svelte Show resolved Hide resolved
src/lib/components/ui/ArticleCard.svelte Outdated Show resolved Hide resolved
src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/routes/+page.svelte Outdated Show resolved Hide resolved
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cac9311 and 659fb50.

📒 Files selected for processing (4)
  • src/lib/components/ui/ArticleCard.svelte (2 hunks)
  • src/lib/components/ui/ArticleSpotlight.svelte (1 hunks)
  • src/lib/utils/optimise-cloudinary.ts (1 hunks)
  • src/routes/+page.svelte (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/lib/utils/optimise-cloudinary.ts

[error] 38-38: This let declares a variable that is only assigned once.

'transformParams' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

🪛 eslint
src/lib/utils/optimise-cloudinary.ts

[error] 38-38: 'transformParams' is never reassigned. Use 'const' instead.

(prefer-const)

🔇 Additional comments (8)
src/lib/utils/optimise-cloudinary.ts (2)

1-1: Good addition of 'hero' to the ImageType union.
This enhances flexibility by allowing hero images to be separately categorized.


7-7: DPR parameter inclusion looks good.
Allowing an optional device pixel ratio helps in delivering sharper images on high-resolution displays. Ensure to default it to 1 in the calling code if no dpr value is provided.

src/lib/components/ui/ArticleSpotlight.svelte (1)

4-4: Import statement is correct.
Bringing in the optimizeCloudinaryUrl function centrally unifies the image transformation logic across components.

src/lib/components/ui/ArticleCard.svelte (2)

5-5: Consistent import usage.
Importing from '$lib/utils/optimise-cloudinary' stresses a single source of truth for image handling.


17-23: Properly specifying the card preset.
Passing { type: 'card' } ensures consistent transformation across the codebase. Including explicit width/height to prevent CLS is also good practice. If the component design evolves, consider a responsive approach similar to ArticleSpotlight.

src/routes/+page.svelte (3)

11-12: Centralizing image utilities is good design.
Importing optimizeCloudinaryUrl and optimizeHeroImage ensures the same transformations are applied consistently across the app.


13-14: Hero image reference identified.
Defining heroImage in one place makes it easier to change or update the hero image across the site.


39-69: Responsive block is well structured.
Specifying multiple tags accommodates both high-density (2x) and standard displays. Using optimizeHeroImage is coherent with the rest of the codebase. If performance is a concern, consider lazy loading for images below the fold.

src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/lib/utils/optimise-cloudinary.ts Outdated Show resolved Hide resolved
src/lib/components/ui/ArticleSpotlight.svelte Show resolved Hide resolved
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: 5

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 659fb50 and a09c8df.

📒 Files selected for processing (2)
  • src/lib/components/ui/ArticleCard.svelte (2 hunks)
  • src/lib/utils/optimise-cloudinary.ts (1 hunks)
🔇 Additional comments (5)
src/lib/utils/optimise-cloudinary.ts (4)

1-1: Great use of a discriminated union type for ImageType.
Defining a strictly limited set of valid image types helps you catch errors at compile-time. This is a straightforward and robust solution.


16-18: Simple and effective guard for invalid or non-Cloudinary URLs.
The early return for unsupported URLs ensures stable behavior across a broader range of content.


37-45: Flexible preset application.
The code caters to preset usage or manually specified dimensions while falling back to the 'card' preset. This covers typical usage scenarios elegantly.


52-54: Intuitive final URL construction.
Appending the transformation segment and optionally adding the 'coverImage/' prefix is clear. If you add other transformations or fluid breakpoints in the future, consider a well-structured approach (e.g., a partial path builder function) to keep complexity low.

src/lib/components/ui/ArticleCard.svelte (1)

5-5: Consistent usage of optimizeCloudinaryUrl.
Importing and reusing the existing utility function ensures a single source of truth for image optimizations, improving maintainability.

src/lib/utils/optimise-cloudinary.ts Show resolved Hide resolved
Comment on lines +10 to +14
const TRANSFORM_PRESETS: Record<ImageType, string> = {
card: 'w_464,h_464,c_fill,ar_1:1,g_center,q_auto,f_auto',
spotlight: 'w_640,h_475,c_fill,f_auto,q_auto',
hero: 'w_720,h_542,c_fill,g_auto,fl_progressive,q_auto:best,f_auto'
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider clarifying the hero preset.
The hero preset uses relatively large dimensions and a combination of progressive loading plus q_auto:best. This is ideal for high-resolution hero images. However, be cautious with large file sizes for slower connections. Consider offering multiple sizes via responsive techniques or limiting q_auto:best for data-constrained users.

Comment on lines +19 to +36
let baseUrl: string;
let path: string;

const uploadIndex = url.lastIndexOf('/upload/');
const coverImageIndex = url.lastIndexOf('/coverImage/');

if (uploadIndex !== -1) {
baseUrl = url.substring(0, uploadIndex + '/upload'.length);
path = url.substring(uploadIndex + '/upload/'.length);
} else if (coverImageIndex !== -1) {
baseUrl = url.substring(0, coverImageIndex);
path = url.substring(coverImageIndex + '/coverImage/'.length);
} else {
return url;
}

if (!path) return url;

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Path extraction logic is intuitive.
Your fallback to directly return the original URL if neither '/upload/' nor '/coverImage/' is found helps avoid unintended breakage. Just watch out for future expansions if other paths (e.g., '/someOtherPath/') become relevant.

Comment on lines +47 to +50
if (options.dpr) {
const sanitizedDpr = Math.max(1, Math.min(Math.abs(options.dpr), 3));
transformParams.push(`dpr_${sanitizedDpr.toFixed(1)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Smart DPR sanitization.
Clamping the DPR between 1 and 3 is a nice safeguard. However, in some edge cases (e.g., “super retina” devices), a higher DPR might be desired. Keep an eye on future device evolutions and be prepared to bump the upper limit if needed.

Comment on lines +17 to +24
<img
src={optimizeCloudinaryUrl(article.thumb, { type: 'card' })}
loading="lazy"
alt={article.title}
class="aspect-square w-full object-cover"
width={464}
height={464}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Good use of lazy loading and explicit dimensions.
Specifying width/height prevents layout shifts, and “lazy” loading optimizes performance. For an even more responsive approach, consider adding a srcset to leverage varying screen resolutions and reduce bandwidth usage for smaller devices.

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