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(use-image): cached image flashing #3444

Closed
wants to merge 1 commit into from

Conversation

rkkautsar
Copy link
Contributor

@rkkautsar rkkautsar commented Jul 11, 2024

Closes #3437

📝 Description

As mentioned in #3437, avatars may flicker even if its already cached. The fix was to check the image loading status immediately after creating the image to see if it's instantly loaded (when the image is cached), and use it to initialize the state. This will affect Avatar, AvatarGroup, and Image components.

Also added test for use-image too since it doesn't exist before.

Before After
nextui-flashing-before nextui-flashing-after

⛳️ Current behavior (updates)

Image flickers due to use-image initializes with pending and only updated the status in useLayoutEffect.

🚀 New behavior

Initialize image loading status with loaded if possible.

💣 Is this a breaking change (Yes/No): No

📝 Additional Information

Summary by CodeRabbit

  • Bug Fixes

    • Resolved issue where cached images were flashing due to improper initialization of the image's loaded state.
  • Tests

    • Added comprehensive tests for the useImage hook covering scenarios like missing source, loading, errors, and cached images.
  • Chores

    • Updated use-image package devDependencies to include @nextui-org/test-utils.
  • Refactor

    • Refined image loading logic in the useImage function to improve the image initialization and status determination process.

@rkkautsar rkkautsar requested a review from jrgarciadev as a code owner July 11, 2024 07:42
Copy link

changeset-bot bot commented Jul 11, 2024

🦋 Changeset detected

Latest commit: 431a5e0

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
Name Type
@nextui-org/use-image Patch
@nextui-org/test-utils Patch
@nextui-org/avatar Patch
@nextui-org/image Patch
@nextui-org/user Patch
@nextui-org/react Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Jul 11, 2024

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

Name Status Preview Comments Updated (UTC)
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 11, 2024 7:45am

Copy link

vercel bot commented Jul 11, 2024

@rkkautsar is attempting to deploy a commit to the NextUI Inc Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Jul 11, 2024

Walkthrough

The changes address an issue with cached images flashing in the use-image package. The updates ensure the image loading state is initialized correctly, eliminating flicker. The useImage hook logic has been refactored to improve handling of image loading and error statuses. New tests were introduced to cover various scenarios, including cached images. Additionally, a mock image utility was enhanced to support better testing.

Changes

Files Change Summary
.changeset/pink-beans-sit.md Added a summary of the changes and their impacts.
packages/hooks/use-image/__tests__/use-image.test.tsx Introduced tests for the useImage hook functionality.
packages/hooks/use-image/package.json Added "@nextui-org/test-utils": "workspace:*" to devDependencies and updated dependencies.
packages/hooks/use-image/src/index.ts Refactored useImage function to handle image loading and error statuses more effectively.
packages/utilities/test-utils/src/mocks/image.ts Enhanced mockImage function with naturalWidth property and complete getter for status checks.

Assessment against linked issues

Objective Addressed Explanation
Fix flashing when image is already cached (#3437)

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 134f371 and 431a5e0.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (5)
  • .changeset/pink-beans-sit.md (1 hunks)
  • packages/hooks/use-image/tests/use-image.test.tsx (1 hunks)
  • packages/hooks/use-image/package.json (2 hunks)
  • packages/hooks/use-image/src/index.ts (3 hunks)
  • packages/utilities/test-utils/src/mocks/image.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • .changeset/pink-beans-sit.md
  • packages/hooks/use-image/package.json
Additional comments not posted (15)
packages/utilities/test-utils/src/mocks/image.ts (1)

17-20: Enhance mockImage to simulate image properties.

The addition of naturalWidth and the complete getter improves the simulation of image loading behavior. This change aligns with the PR objectives to handle cached images more effectively.

packages/hooks/use-image/__tests__/use-image.test.tsx (8)

1-2: Add necessary imports for the tests.

The added imports ensure the testing utilities and the useImage hook are available for the test cases.


6-7: Initialize mockImage for each test case.

The mockImage initialization ensures that each test case starts with a clean state.


10-11: Set up mockImage before each test case.

This ensures that the mock image functionality is correctly set up before each test case runs.


12-14: Restore mockImage after each test case.

Restoring the mock image ensures that the tests do not interfere with each other by leaving residual state.


16-20: Test handling of missing src.

This test case ensures that the useImage hook correctly handles scenarios where the image source is missing.


22-28: Test handling of loading image.

This test case ensures that the useImage hook correctly handles scenarios where the image is in the process of loading.


30-36: Test handling of error image.

This test case ensures that the useImage hook correctly handles scenarios where the image fails to load.


38-43: Test handling of cached image.

This test case ensures that the useImage hook correctly handles scenarios where the image is already cached.

packages/hooks/use-image/src/index.ts (6)

4-4: Add necessary import for MutableRefObject.

The addition of MutableRefObject is necessary for the new function handling image initialization and status determination.


6-6: Ensure correct imports.

The imports ensure that the required hooks and utilities are available for the useImage hook.


70-71: Initialize state with image status.

The state initialization now checks the image loading status upon creation, addressing the cached image flashing issue.


73-85: Update useSafeLayoutEffect dependencies.

The updated dependencies ensure that the image status is re-evaluated when relevant properties change.


87-99: Handle image load and error events.

The event handlers ensure that the image status is correctly updated when the image loads or fails to load.


116-139: Add function to set image and get initial status.

The new function setImageAndGetInitialStatus determines the initial status of the image based on its properties, improving the handling of cached images.

Copy link
Member

@wingkwong wingkwong left a comment

Choose a reason for hiding this comment

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

I tested it on your PR changes following your video. I still see a few images flashing while most look same as your video. Have you encountered this issue?

@wingkwong wingkwong removed their assignment Jul 17, 2024
@rkkautsar
Copy link
Contributor Author

@wingkwong yes, I think it had to do with the actual image caching behaviour of each browser. I used chrome, and from what I can see the caching seems to be size limited, if I were to guess it's because there is a few level of caching, the one that is instant is memory-cached, while the other one that still flashes is disk-cached.

If I show a big image (like in <Image/> component) it can only cache one image at a time, so switching between different image will flash. But switching components that is showing the same image won't flash.

Conversely, for small image like in avatars (and avatar groups), it seems that most of the small images is cached in memory so it always never flash (unless you load a big image and come back, the big image will replace the memory cache I think)

@rkkautsar rkkautsar requested a review from wingkwong July 25, 2024 03:11
@wingkwong wingkwong self-assigned this Aug 6, 2024
@wingkwong wingkwong added this to the v2.4.7 milestone Aug 19, 2024
@wingkwong wingkwong modified the milestones: v2.4.7, v2.5.0 Sep 7, 2024
@wingkwong
Copy link
Member

will revisit this PR after the one in Radix is merged. May check if those comments can be applied here or not.

@jrgarciadev jrgarciadev mentioned this pull request Nov 4, 2024
@jrgarciadev
Copy link
Member

Hey @rkkautsar thanks for you great contribution, we had to create the PR internally to move things a bit faster #3987 but do not worry we will add you to the contributors list, thanks 🙏🏻

@jrgarciadev jrgarciadev closed this Nov 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Avatar] Fix flashing when image is already cached
3 participants