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

Implement photo pagination and dynamic loading in Expo app #374

Conversation

jaronheard
Copy link
Owner

@jaronheard jaronheard commented Jan 7, 2025

  • ✨ feat: implement infinite scroll for photo gallery with pagination
  • ♻️ refactor(store): reorganize state and actions into logical groupings

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced photo browsing experience with dynamic photo loading
    • Improved photo selection and media library management
  • Improvements

    • Added pagination support for recent photos
    • Optimized photo loading with better performance controls
    • Expanded state management for media and calendar interactions
  • User Experience

    • Smoother scrolling and loading of photos in event creation
    • More robust media permission and library handling

The commit adds infinite scroll functionality to the photo gallery, including:
- Paginated photo loading with cursor-based navigation
- Loading indicators and proper error handling
- Performance optimizations for FlatList rendering
Copy link

vercel bot commented Jan 7, 2025

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

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
soonlist-turbo ⬜️ Skipped (Inspect) Jan 7, 2025 3:02am

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

This pull request introduces enhanced photo loading functionality in the Expo application, focusing on the NewEventModal and PhotoGrid components. The changes implement pagination for recent photos, adding state management for loading more images dynamically. The modifications include updating the AppState interface in the store to support new photo-related states, introducing loading indicators, and implementing a mechanism to fetch photos incrementally as the user scrolls.

Changes

File Changes
apps/expo/src/app/new.tsx - Added onEndReached and isLoadingMore props to PhotoGrid
- Implemented pagination logic in loadRecentPhotos
- Added PHOTOS_PER_PAGE constant
- Introduced new state variables for photo loading management
apps/expo/src/store.ts - Expanded AppState interface with numerous new photo and media-related properties
- Added methods for managing new state properties
- Updated resetStore functionality

Sequence Diagram

sequenceDiagram
    participant User
    participant PhotoGrid
    participant NewEventModal
    participant MediaLibrary

    User->>PhotoGrid: Scroll near list end
    PhotoGrid->>NewEventModal: Trigger onEndReached
    NewEventModal->>MediaLibrary: Request more photos
    MediaLibrary-->>NewEventModal: Return additional photos
    NewEventModal->>PhotoGrid: Update photo list
    PhotoGrid->>User: Display new photos
Loading

Possibly related PRs


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

linear bot commented Jan 7, 2025

@coderabbitai coderabbitai bot changed the title @coderabbitai Implement photo pagination and dynamic loading in Expo app Jan 7, 2025
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)
apps/expo/src/store.ts (1)

201-207: Avoid using JSON.stringify for state comparison in setRecentPhotos

Using JSON.stringify to compare recentPhotos arrays can lead to performance issues as the data grows. Consider using a more efficient deep equality check or a library like lodash.isequal. Alternatively, if shallow comparison suffices, you can compare array lengths and elements directly.

Apply this diff to optimize the comparison:

setRecentPhotos: (photos) =>
  set((state) => {
-    if (JSON.stringify(state.recentPhotos) === JSON.stringify(photos)) {
+    if (
+      state.recentPhotos.length === photos.length &&
+      state.recentPhotos.every((photo, index) => photo.id === photos[index].id)
+    ) {
      return state;
    }
    return { recentPhotos: photos };
  }),
apps/expo/src/app/new.tsx (1)

Line range hint 443-492: Refactor duplicated photo loading logic into a reusable function

The logic for checking permissions and loading recent photos in useFocusEffect is similar to loadRecentPhotos. Consider refactoring this into a shared function or custom hook to reduce code duplication and enhance maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baca4b5 and cbce538.

📒 Files selected for processing (2)
  • apps/expo/src/app/new.tsx (6 hunks)
  • apps/expo/src/store.ts (6 hunks)
🔇 Additional comments (2)
apps/expo/src/store.ts (1)

Line range hint 218-246: The resetStore function correctly resets the state

The resetStore action properly initializes all state properties to their default values, ensuring a clean state.

apps/expo/src/app/new.tsx (1)

204-219: Verify the use of removeClippedSubviews in FlatList

While removeClippedSubviews can improve performance by unmounting components outside the viewport, it may cause rendering issues, especially with images and dynamic content. Ensure that enabling this prop does not introduce visual glitches in the PhotoGrid component.

Comment on lines +523 to +566
if (isLoadingMore || !hasMorePhotos) return;

setIsLoadingMore(true);

try {
const { assets } = await MediaLibrary.getAssetsAsync({
first: 15,
const {
assets,
hasNextPage,
endCursor: newEndCursor,
} = await MediaLibrary.getAssetsAsync({
first: PHOTOS_PER_PAGE,
after: endCursor,
sortBy: MediaLibrary.SortBy.creationTime,
mediaType: [MediaLibrary.MediaType.photo],
});
const photos: RecentPhoto[] = assets.map((asset) => ({
id: asset.id,
uri: asset.uri,
}));
setRecentPhotos(photos);

// Validate each asset
const accessibleAssets = await Promise.all(
assets.map(async (asset) => {
try {
const assetInfo = await MediaLibrary.getAssetInfoAsync(asset);
return assetInfo.localUri
? { id: asset.id, uri: assetInfo.localUri }
: null;
} catch {
return null;
}
}),
);

const photos: RecentPhoto[] = accessibleAssets.filter(
(asset): asset is RecentPhoto => asset !== null,
);

setRecentPhotos([...recentPhotos, ...photos]);
setHasMorePhotos(hasNextPage);
setEndCursor(newEndCursor);
} catch (error) {
console.error("Error loading recent photos:", error);
toast.error("Failed to load photos.");
} finally {
setIsLoadingMore(false);
}
}, [
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

Optimize photo loading by eliminating unnecessary asset info requests

In loadRecentPhotos, calling MediaLibrary.getAssetInfoAsync for each asset can significantly slow down loading times. Since MediaLibrary.getAssetsAsync already provides the uri property, you can use it directly to improve performance.

Apply this diff to optimize the photo loading:

        try {
          const {
            assets,
            hasNextPage,
            endCursor: newEndCursor,
          } = await MediaLibrary.getAssetsAsync({
            first: PHOTOS_PER_PAGE,
            after: endCursor,
            sortBy: MediaLibrary.SortBy.creationTime,
            mediaType: [MediaLibrary.MediaType.photo],
          });

-         // Validate each asset
-         const accessibleAssets = await Promise.all(
-           assets.map(async (asset) => {
-             try {
-               const assetInfo = await MediaLibrary.getAssetInfoAsync(asset);
-               return assetInfo.localUri
-                 ? { id: asset.id, uri: assetInfo.localUri }
-                 : null;
-             } catch {
-               return null;
-             }
-           }),
-         );

-         const photos: RecentPhoto[] = accessibleAssets.filter(
-           (asset): asset is RecentPhoto => asset !== null,
-         );
+         const photos: RecentPhoto[] = assets.map((asset) => ({
+           id: asset.id,
+           uri: asset.uri,
+         }));

          setRecentPhotos([...recentPhotos, ...photos]);
          setHasMorePhotos(hasNextPage);
          setEndCursor(newEndCursor);
        } catch (error) {
          console.error("Error loading recent photos:", error);
          toast.error("Failed to load photos.");
        } finally {
          setIsLoadingMore(false);
        }
📝 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
if (isLoadingMore || !hasMorePhotos) return;
setIsLoadingMore(true);
try {
const { assets } = await MediaLibrary.getAssetsAsync({
first: 15,
const {
assets,
hasNextPage,
endCursor: newEndCursor,
} = await MediaLibrary.getAssetsAsync({
first: PHOTOS_PER_PAGE,
after: endCursor,
sortBy: MediaLibrary.SortBy.creationTime,
mediaType: [MediaLibrary.MediaType.photo],
});
const photos: RecentPhoto[] = assets.map((asset) => ({
id: asset.id,
uri: asset.uri,
}));
setRecentPhotos(photos);
// Validate each asset
const accessibleAssets = await Promise.all(
assets.map(async (asset) => {
try {
const assetInfo = await MediaLibrary.getAssetInfoAsync(asset);
return assetInfo.localUri
? { id: asset.id, uri: assetInfo.localUri }
: null;
} catch {
return null;
}
}),
);
const photos: RecentPhoto[] = accessibleAssets.filter(
(asset): asset is RecentPhoto => asset !== null,
);
setRecentPhotos([...recentPhotos, ...photos]);
setHasMorePhotos(hasNextPage);
setEndCursor(newEndCursor);
} catch (error) {
console.error("Error loading recent photos:", error);
toast.error("Failed to load photos.");
} finally {
setIsLoadingMore(false);
}
}, [
if (isLoadingMore || !hasMorePhotos) return;
setIsLoadingMore(true);
try {
const {
assets,
hasNextPage,
endCursor: newEndCursor,
} = await MediaLibrary.getAssetsAsync({
first: PHOTOS_PER_PAGE,
after: endCursor,
sortBy: MediaLibrary.SortBy.creationTime,
mediaType: [MediaLibrary.MediaType.photo],
});
const photos: RecentPhoto[] = assets.map((asset) => ({
id: asset.id,
uri: asset.uri,
}));
setRecentPhotos([...recentPhotos, ...photos]);
setHasMorePhotos(hasNextPage);
setEndCursor(newEndCursor);
} catch (error) {
console.error("Error loading recent photos:", error);
toast.error("Failed to load photos.");
} finally {
setIsLoadingMore(false);
}
}, [

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