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: Frames Renders on initial Send #1113

Merged
merged 3 commits into from
Oct 28, 2024
Merged

fix: Frames Renders on initial Send #1113

merged 3 commits into from
Oct 28, 2024

Conversation

alexrisch
Copy link
Collaborator

@alexrisch alexrisch commented Oct 27, 2024

Updated to use zustand store for managing frames
Updated to use hasFrames rather than isFrame

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced handling of message frames in the chat component for improved clarity and performance.
    • Introduced a new mapping system for associating messages with their corresponding frames.
  • Bug Fixes

    • Refined logic for determining frame presence in messages, ensuring accurate rendering.
  • Refactor

    • Streamlined state management in the FramesPreviews component, reducing unnecessary updates.
    • Improved code structure for swipe actions in the message component for better maintainability.

Updated to use zustand store for managing frames
Updated to use hasFrames rather than isFrame
@alexrisch alexrisch requested a review from a team as a code owner October 27, 2024 15:27
Copy link
Contributor

coderabbitai bot commented Oct 27, 2024

Walkthrough

The changes in this pull request involve significant updates to the Chat.tsx, FramesPreviews.tsx, Message.tsx, framesStore.ts, and frames.ts components. Key modifications include the introduction of messageFramesMap for managing message frames, updates to function parameters and types, and enhancements to state management using Zustand. The refactoring aims to streamline the handling of message frames, improve data clarity, and optimize performance across the components involved.

Changes

File Path Change Summary
components/Chat/Chat.tsx Updated useRenderItem to use messageFramesMap; modified getItemType to accept new frame data structure; updated useFramesStore return value.
components/Chat/Frame/FramesPreviews.tsx Changed export to named; replaced useState with useFramesStore and useShallow; refactored logic for fetching frames.
components/Chat/Message/Message.tsx Renamed isFrame to hasFrames; introduced useFramesStore for frame checks; refactored rendering logic for swipe actions.
data/store/framesStore.ts Added messageFramesMap to FramesStoreType; introduced setMessageFramesMap method for state updates; modified setFrames method to include messageId.
utils/frames.ts Modified fetchFramesForMessage to update the frames store with message ID; added messageHasFrames utility function.

Possibly related PRs

Suggested labels

2.0.7

Suggested reviewers

  • thierryskoda

🐰 In the land of chat, where frames do play,
A map was drawn to show the way.
With hooks and stores, we dance and weave,
In clearer paths, we now believe.
So hop along, let messages flow,
For frames and chats, together we grow! 🌟


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

github-actions bot commented Oct 27, 2024

Performance Comparison Report

  • Current: 6b34563 - 2024-10-28 14:33:08Z
  • Baseline: main (6825113) - 2024-10-28 14:32:29Z

Significant Changes To Duration

There are no entries

Meaningless Changes To Duration

Show entries
Name Type Duration Count
Avatar Image 10 runs render 1.4 ms → 1.2 ms (-0.2 ms, -14.3%) 1 → 1
Avatar Image 50 runs render 1.1 ms → 1.1 ms (-0.0 ms, -1.9%) 1 → 1
Empty Avatar 10 runs render 1.2 ms → 1.0 ms (-0.2 ms, -16.7%) 🟢 1 → 1
Empty Avatar 50 runs render 0.8 ms → 0.6 ms (-0.2 ms, -24.4%) 🟢 1 → 1
Show details
Name Type Duration Count
Avatar Image 10 runs render Baseline
Mean: 1.4 ms
Stdev: 0.5 ms (36.9%)
Runs: 1 1 2 2 1 1 2 2 1 1
Warmup runs: 2

Current
Mean: 1.2 ms
Stdev: 0.4 ms (35.1%)
Runs: 1 2 1 1 1 1 1 2 1 1
Warmup runs: 2
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Avatar Image 50 runs render Baseline
Mean: 1.1 ms
Stdev: 0.3 ms (31.5%)
Runs: 1 1 1 1 1 1 1 1 2 1 1 2 1 1 2 1 2 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1
Warmup runs: 2

Current
Mean: 1.1 ms
Stdev: 0.2 ms (22.6%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 2 1 1 1 1
Warmup runs: 2
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 10 runs render Baseline
Mean: 1.2 ms
Stdev: 0.4 ms (35.1%)
Runs: 1 2 2 1 1 1 1 1 1 1
Warmup runs: 79

Current
Mean: 1.0 ms
Stdev: 0.0 ms (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Warmup runs: 8
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1
Render issues:
Empty Avatar 50 runs render Baseline
Mean: 0.8 ms
Stdev: 0.4 ms (47.3%)
Runs: 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 0 1 1 0 1 1 0 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1
Warmup runs: 1

Current
Mean: 0.6 ms
Stdev: 0.5 ms (79.1%)
Runs: 0 0 1 0 1 1 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 0 1 0 1 1 1 0 0 1 1
Warmup runs: 1
Baseline
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Current
Mean: 1
Stdev: 0 (0.0%)
Runs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Render issues:

Render Count Changes

There are no entries

Render Issues

There are no entries

Added Scenarios

There are no entries

Removed Scenarios

There are no entries

Generated by 🚫 dangerJS against 5e5d353

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

🧹 Outside diff range and nitpick comments (7)
data/store/framesStore.ts (2)

25-25: Consider adding explicit type annotation

The initialization looks good, but consider adding an explicit type annotation for better code clarity:

-      messageFramesMap: {},
+      messageFramesMap: {} as FramesStoreType['messageFramesMap'],

The modification to return the full state in setFrames is a good improvement for maintaining state consistency.

Also applies to: 30-30


43-52: Consider adding message cleanup strategy

The implementation of setMessageFramesMap is correct and follows proper immutable state update patterns. However, consider implementing a cleanup strategy to prevent unlimited growth of the messageFramesMap.

Consider these improvements:

  1. Add a maximum limit for stored messages
  2. Implement an LRU cache mechanism
  3. Add a cleanup method to remove frames for deleted messages

Would you like me to provide an example implementation of any of these suggestions?

utils/frames.ts (1)

Line range hint 1-262: Consider architectural improvements for frame management.

The current implementation mixes several concerns:

  1. Frame fetching and validation
  2. State management
  3. Transaction handling
  4. Metadata persistence

Consider splitting this into separate modules:

  • framesFetcher.ts: Handle URL extraction and frame fetching
  • framesValidator.ts: Frame validation logic
  • framesStore.ts: State management (already exists but could be enhanced)
  • framesTransaction.ts: Transaction-related logic
  • framesMetadata.ts: Metadata persistence

This would improve maintainability and make the codebase more modular.

components/Chat/Chat.tsx (1)

386-388: Maintain consistent property order in store selections

While both useFramesStore calls are correct, they select properties in different orders:

  • Chat: messageFramesMap, frames
  • ChatPreview: frames, messageFramesMap

Consider maintaining consistent property order across components for better maintainability.

  // In ChatPreview component
  const { frames: framesStore, messageFramesMap } = useFramesStore(
-   useSelect(["frames", "messageFramesMap"])
+   useSelect(["messageFramesMap", "frames"])
  );

Also applies to: 544-546

components/Chat/Message/Message.tsx (3)

168-171: Enhance comment clarity for frame detection

The current comment could be more descriptive about the frame detection logic and its purpose.

Consider updating the comment to:

-  // The content is completely a frame so a larger full width frame will be shown
+  // Check if message content matches a known frame URL (normalized to lowercase)
+  // When true, the message will be rendered as a full-width frame

Line range hint 290-309: Simplify messageMaxWidth logic

The messageMaxWidth determination could be simplified using a more declarative approach.

Consider refactoring to:

-  let messageMaxWidth: DimensionValue;
-  if (isDesktop) {
-    if (isAttachment) {
-      messageMaxWidth = 366;
-    } else {
-      messageMaxWidth = 588;
-    }
-  } else {
-    if (isAttachment) {
-      messageMaxWidth = "60%";
-    } else {
-      if (isFrame) {
-        messageMaxWidth = "100%";
-      } else messageMaxWidth = "85%";
-    }
-  }
+  const messageMaxWidth: DimensionValue = (() => {
+    if (isDesktop) {
+      return isAttachment ? 366 : 588;
+    }
+    if (isAttachment) return "60%";
+    return isFrame ? "100%" : "85%";
+  })();

Line range hint 563-565: Make cache size configurable

The cache size is hardcoded to 50 entries. Consider making this configurable for different use cases and memory constraints.

+const DEFAULT_CACHE_SIZE = 50;
+const MESSAGE_CACHE_SIZE = typeof process !== 'undefined' 
+  ? process.env.REACT_APP_MESSAGE_CACHE_SIZE || DEFAULT_CACHE_SIZE
+  : DEFAULT_CACHE_SIZE;

-const renderedMessages = new LimitedMap<string, RenderedChatMessage>(50);
+const renderedMessages = new LimitedMap<string, RenderedChatMessage>(MESSAGE_CACHE_SIZE);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1ff4410 and b6a1e94.

📒 Files selected for processing (5)
  • components/Chat/Chat.tsx (6 hunks)
  • components/Chat/Frame/FramesPreviews.tsx (1 hunks)
  • components/Chat/Message/Message.tsx (11 hunks)
  • data/store/framesStore.ts (2 hunks)
  • utils/frames.ts (1 hunks)
🔇 Additional comments (8)
data/store/framesStore.ts (2)

13-15: LGTM: Well-structured type definitions

The new type definitions for messageFramesMap and setMessageFramesMap are well-structured and provide good type safety for message-frame relationships.

Also applies to: 18-18


Line range hint 54-59: Verify store persistence configuration

Let's ensure the store name is unique and the persistence is working as expected.

✅ Verification successful

Let me check the store names used in other persist configurations to ensure uniqueness.


Let me try a different approach to check the store configurations.


Let me check the storage configuration for all stores.


Store persistence configuration is properly implemented

The verification shows that:

  • The store name store-frames is unique among non-account-based stores
  • The storage is consistently configured using zustandMMKVStorage across all stores
  • The persistence middleware is properly implemented with both name and storage configuration

The implementation follows the same pattern as other stores in the codebase, using the standard persistence configuration with MMKV storage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential store name conflicts
rg -g '!framesStore.ts' "store-frames" .

# Check for other persist middleware configurations
rg "persist\(" .

Length of output: 438


Script:

#!/bin/bash
# Get the store names from persist configurations
rg -A 2 "persist\(" . | grep -E "name:|storage:"

Length of output: 50


Script:

#!/bin/bash
# Search for persist configurations with more context
rg -A 5 "persist\(" .

Length of output: 3238


Script:

#!/bin/bash
# Search for storage configurations in persist middleware
rg -B 5 "storage:" .

Length of output: 9302

components/Chat/Frame/FramesPreviews.tsx (2)

2-2: LGTM! Good practice using named exports.

The switch to named exports and the updated imports align well with React best practices and the new store-based architecture.

Also applies to: 4-4, 16-16


22-24: LGTM! Efficient store access implementation.

Good use of useShallow for performance optimization and proper null handling with the ?? operator.

utils/frames.ts (1)

125-125: LGTM! The store update is well-placed.

The addition of setMessageFramesMap complements the existing frame storage mechanisms and aligns with the PR's objective of improving frame management using Zustand store.

Let's verify the store update is used consistently:

✅ Verification successful

Store update is properly integrated and consistently used

The verification shows that setMessageFramesMap is:

  • Correctly defined in the store interface with proper typing
  • Implemented in the Zustand store with proper state updates
  • Used consistently in two locations:
    • utils/frames.ts: During frame fetching
    • components/Chat/Frame/FramesPreviews.tsx: During frame preview handling

No direct frame array manipulations were found that bypass the store, indicating proper encapsulation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of messageFramesMap across the codebase

# Test 1: Verify the store property exists
echo "Checking for messageFramesMap definition..."
rg "messageFramesMap.*:" -A 3

# Test 2: Check for proper usage of the mapping
echo "Checking for messageFramesMap usage..."
rg "messageFramesMap.*\(" -A 3

# Test 3: Verify no direct frame access bypassing the map
echo "Checking for potential direct frame access..."
rg "frames\s*=\s*\[" --type ts

Length of output: 2042


Script:

#!/bin/bash
# Let's verify the setMessageFramesMap usage and its integration

# Check for setMessageFramesMap usage
echo "Checking setMessageFramesMap usage..."
rg "setMessageFramesMap" -A 3

# Check the store's interface and implementation
echo "Checking store interface..."
ast-grep --pattern 'interface $_ {
  $$$
  setMessageFramesMap: $_
  $$$
}'

# Check for any direct frame array assignments that might bypass the store
echo "Checking frame assignments..."
rg "frames\s*=\s*\[\]|frames\.push|frames\.concat" --type ts

Length of output: 1405

components/Chat/Chat.tsx (2)

75-83: LGTM: Clean type definition for messageFramesMap

The replacement of framesStore with messageFramesMap and its type definition is well-structured and improves type safety.


97-97: LGTM: Proper dependency management

The messageFramesMap dependency is correctly added to the useCallback dependency array, ensuring proper re-rendering when frames data changes.

components/Chat/Message/Message.tsx (1)

89-89: LGTM: Improved prop naming for better semantics

The renaming from isFrame to hasFrames better represents the boolean state of frame existence for a message.

Also applies to: 555-555, 579-579, 596-596, 603-603

Comment on lines 40 to 45
useEffect(() => {
if (message.id !== messageId.current) {
messageId.current = message.id;
fetchTagsIfNeeded();
}
}, [message.id, fetchTagsIfNeeded, message.converseMetadata?.frames]);
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

Consider optimizing effect dependencies.

The effect's dependency array includes message.converseMetadata?.frames which might trigger unnecessary reruns. Since you're only checking for message ID changes, you could simplify this:

  useEffect(() => {
    if (message.id !== messageId.current) {
      messageId.current = message.id;
      fetchTagsIfNeeded();
    }
- }, [message.id, fetchTagsIfNeeded, message.converseMetadata?.frames]);
+ }, [message.id, fetchTagsIfNeeded]);
📝 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
useEffect(() => {
if (message.id !== messageId.current) {
messageId.current = message.id;
fetchTagsIfNeeded();
}
}, [message.id, fetchTagsIfNeeded, message.converseMetadata?.frames]);
useEffect(() => {
if (message.id !== messageId.current) {
messageId.current = message.id;
fetchTagsIfNeeded();
}
}, [message.id, fetchTagsIfNeeded]);

components/Chat/Frame/FramesPreviews.tsx Outdated Show resolved Hide resolved
utils/frames.ts Outdated Show resolved Hide resolved
components/Chat/Chat.tsx Outdated Show resolved Hide resolved
components/Chat/Message/Message.tsx 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: 1

🧹 Outside diff range and nitpick comments (1)
components/Chat/Chat.tsx (1)

Line range hint 102-103: Update getItemType parameter type to match new store structure

The function's parameter type still uses the old structure { [frameUrl: string]: FrameWithType } while the rest of the code has moved to { [messageId: string]: FrameWithType[] }.

Update the parameter type to match the new structure:

-const getItemType = (framesStore: { [frameUrl: string]: FrameWithType }) =>
+const getItemType = (framesStore: { [messageId: string]: FrameWithType[] }) =>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b6a1e94 and 0cecad2.

📒 Files selected for processing (4)
  • components/Chat/Chat.tsx (7 hunks)
  • components/Chat/Frame/FramesPreviews.tsx (1 hunks)
  • data/store/framesStore.ts (2 hunks)
  • utils/frames.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • components/Chat/Frame/FramesPreviews.tsx
  • utils/frames.ts
🔇 Additional comments (7)
data/store/framesStore.ts (3)

13-21: LGTM: Type definitions are well-structured

The new type definitions properly support the message-to-frames mapping functionality while maintaining type safety.


Line range hint 69-73: Verify persistence of messageFramesMap

The store uses persistence middleware with MMKV storage. Ensure that the new messageFramesMap state is properly persisted and restored, especially for large message histories.

Let's check the storage implementation:

#!/bin/bash
# Check MMKV storage implementation and usage
rg -A 5 "zustandMMKVStorage" --type ts

57-66: 🛠️ Refactor suggestion

Add validation and cleanup mechanism

The current implementation could benefit from additional safeguards and maintenance features:

  1. Input validation for messageId and frames
  2. Deduplication of frames
  3. Cleanup mechanism for old message frames

Let's check if there's any cleanup logic elsewhere in the codebase:

Consider adding these safety measures:

 setMessageFramesMap: (messageId: string, frames: FrameWithType[]) =>
   set((state) => {
+    if (!messageId || !Array.isArray(frames)) {
+      console.warn('Invalid arguments to setMessageFramesMap');
+      return state;
+    }
+    // Deduplicate frames by URL
+    const uniqueFrames = Array.from(
+      new Map(frames.map(frame => [frame.url, frame])).values()
+    );
     return {
       ...state,
       messageFramesMap: {
         ...state.messageFramesMap,
-        [messageId]: frames,
+        [messageId]: uniqueFrames,
       },
     };
   }),
components/Chat/Chat.tsx (4)

9-9: LGTM! Import changes align with frame management improvements

The addition of messageHasFrames utility function improves code reusability and addresses the previous review suggestion.


75-83: LGTM! Parameter updates improve type safety and abstraction

The changes properly type the messageFramesMap and utilize the messageHasFrames utility, making the code more maintainable and type-safe.

Also applies to: 93-93, 97-97


386-388: LGTM! Zustand store integration is well-implemented

The consistent use of useFramesStore with useSelect demonstrates good state management practices and optimizes performance by selecting only the needed state slices.

Also applies to: 544-546


Line range hint 102-138: Verify consistent frame type usage across the codebase

Let's ensure the new frame type structure is consistently used across all components that interact with frames.

✅ Verification successful

Based on the search results, I can now generate the final response as we have sufficient information about frame type usage across the codebase.

Frame type implementation is consistent across the codebase

The frame type structure is consistently implemented:

  • The base type FrameWithType is properly defined in utils/frames.ts and extended where needed
  • All frame store usages in components correctly use the { [frameUrl: string]: FrameWithType } type structure
  • Frame-related components in components/Chat/Frame/ consistently use the proper types
  • The store implementation in data/store/framesStore.ts maintains type consistency

The changes in the reviewed code align with the codebase's type system and don't introduce any inconsistencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential inconsistencies in frame type usage
echo "Searching for old frame type structure..."
rg --type typescript --type tsx "frameUrl: string\]: FrameWithType[^[]"

echo "Searching for frame-related type definitions..."
rg --type typescript --type tsx "type.*Frame.*=.*{" -A 5

Length of output: 563


Script:

#!/bin/bash
# Search for frame type usage patterns
echo "Searching for frame type definitions..."
rg --type typescript --type tsx "type.*Frame"

echo "Searching for frame store usage..."
rg --type typescript --type tsx "framesStore\["

echo "Searching for FrameWithType usage..."
rg --type typescript --type tsx "FrameWithType"

Length of output: 501


Script:

#!/bin/bash
# Search for frame type usage patterns without specifying file types
echo "Searching for frame type definitions..."
rg "type.*Frame"

echo "Searching for frame store usage..."
rg "framesStore\["

echo "Searching for FrameWithType usage..."
rg "FrameWithType"

# Find TypeScript/TSX files that might contain frame-related code
echo "Finding TypeScript files..."
fd "\.(ts|tsx)$"

Length of output: 17604

Comment on lines +28 to +44
messageFramesMap: {},
setFrames: (
messageId: string,
framesToSet: { [frameUrl: string]: FrameWithType }
) =>
set((state) => {
const existingFrames = pick(state.frames, Object.keys(framesToSet));

if (isDeepEqual(existingFrames, framesToSet)) return {};
return { frames: { ...state.frames, ...framesToSet } };
return {
...state,
frames: { ...state.frames, ...framesToSet },
messageFramesMap: {
...state.messageFramesMap,
[messageId]: Object.values(framesToSet),
},
};
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

Consider optimizing state updates and handling edge cases

A few suggestions to improve robustness and performance:

  1. The deep equality check could be extended to compare the messageFramesMap entries to prevent unnecessary updates.
  2. Frame URL case handling should be consistent between setFrames and getFramesForURLs.
  3. Consider using immer or selective state updates to minimize re-renders.

Here's a suggested optimization:

 setFrames: (
   messageId: string,
   framesToSet: { [frameUrl: string]: FrameWithType }
 ) =>
   set((state) => {
     const existingFrames = pick(state.frames, Object.keys(framesToSet));
+    const existingMessageFrames = state.messageFramesMap[messageId] || [];
+    const newMessageFrames = Object.values(framesToSet);
 
-    if (isDeepEqual(existingFrames, framesToSet)) return {};
+    if (
+      isDeepEqual(existingFrames, framesToSet) &&
+      isDeepEqual(existingMessageFrames, newMessageFrames)
+    ) {
+      return {};
+    }
 
     return {
       ...state,
       frames: { ...state.frames, ...framesToSet },
       messageFramesMap: {
         ...state.messageFramesMap,
-        [messageId]: Object.values(framesToSet),
+        [messageId]: newMessageFrames,
       },
     };
   }),
📝 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
messageFramesMap: {},
setFrames: (
messageId: string,
framesToSet: { [frameUrl: string]: FrameWithType }
) =>
set((state) => {
const existingFrames = pick(state.frames, Object.keys(framesToSet));
if (isDeepEqual(existingFrames, framesToSet)) return {};
return { frames: { ...state.frames, ...framesToSet } };
return {
...state,
frames: { ...state.frames, ...framesToSet },
messageFramesMap: {
...state.messageFramesMap,
[messageId]: Object.values(framesToSet),
},
};
messageFramesMap: {},
setFrames: (
messageId: string,
framesToSet: { [frameUrl: string]: FrameWithType }
) =>
set((state) => {
const existingFrames = pick(state.frames, Object.keys(framesToSet));
const existingMessageFrames = state.messageFramesMap[messageId] || [];
const newMessageFrames = Object.values(framesToSet);
if (
isDeepEqual(existingFrames, framesToSet) &&
isDeepEqual(existingMessageFrames, newMessageFrames)
) {
return {};
}
return {
...state,
frames: { ...state.frames, ...framesToSet },
messageFramesMap: {
...state.messageFramesMap,
[messageId]: newMessageFrames,
},
};

technoplato pushed a commit that referenced this pull request Dec 17, 2024
* fix: Frames Renders on initial Send

Updated to use zustand store for managing frames
Updated to use hasFrames rather than isFrame

* cleanup
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