-
Notifications
You must be signed in to change notification settings - Fork 7
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
Conversation
Updated to use zustand store for managing frames Updated to use hasFrames rather than isFrame
WalkthroughThe changes in this pull request involve significant updates to the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Performance Comparison ReportSignificant Changes To DurationThere are no entries Meaningless Changes To DurationShow entries
Show details
Render Count ChangesThere are no entries Render IssuesThere are no entries Added ScenariosThere are no entries Removed ScenariosThere are no entries |
There was a problem hiding this 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 annotationThe 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 strategyThe implementation of
setMessageFramesMap
is correct and follows proper immutable state update patterns. However, consider implementing a cleanup strategy to prevent unlimited growth of themessageFramesMap
.Consider these improvements:
- Add a maximum limit for stored messages
- Implement an LRU cache mechanism
- 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:
- Frame fetching and validation
- State management
- Transaction handling
- Metadata persistence
Consider splitting this into separate modules:
framesFetcher.ts
: Handle URL extraction and frame fetchingframesValidator.ts
: Frame validation logicframesStore.ts
: State management (already exists but could be enhanced)framesTransaction.ts
: Transaction-related logicframesMetadata.ts
: Metadata persistenceThis would improve maintainability and make the codebase more modular.
components/Chat/Chat.tsx (1)
386-388
: Maintain consistent property order in store selectionsWhile 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 detectionThe 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 logicThe 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 configurableThe 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
📒 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 definitionsThe new type definitions for
messageFramesMap
andsetMessageFramesMap
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 configurationLet'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 fetchingcomponents/Chat/Frame/FramesPreviews.tsx
: During frame preview handlingNo 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 tsLength 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 tsLength of output: 1405
components/Chat/Chat.tsx (2)
75-83
: LGTM: Clean type definition for messageFramesMapThe replacement of framesStore with messageFramesMap and its type definition is well-structured and improves type safety.
97-97
: LGTM: Proper dependency managementThe 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 semanticsThe renaming from
isFrame
tohasFrames
better represents the boolean state of frame existence for a message.Also applies to: 555-555, 579-579, 596-596, 603-603
useEffect(() => { | ||
if (message.id !== messageId.current) { | ||
messageId.current = message.id; | ||
fetchTagsIfNeeded(); | ||
} | ||
}, [message.id, fetchTagsIfNeeded, message.converseMetadata?.frames]); |
There was a problem hiding this comment.
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.
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]); |
There was a problem hiding this 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 structureThe 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
📒 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-structuredThe new type definitions properly support the message-to-frames mapping functionality while maintaining type safety.
Line range hint
69-73
: Verify persistence of messageFramesMapThe 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 suggestionAdd validation and cleanup mechanism
The current implementation could benefit from additional safeguards and maintenance features:
- Input validation for messageId and frames
- Deduplication of frames
- 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 improvementsThe addition of
messageHasFrames
utility function improves code reusability and addresses the previous review suggestion.
75-83
: LGTM! Parameter updates improve type safety and abstractionThe 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-implementedThe 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 codebaseLet'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 inutils/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 consistencyThe 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 5Length 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
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), | ||
}, | ||
}; |
There was a problem hiding this comment.
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:
- The deep equality check could be extended to compare the messageFramesMap entries to prevent unnecessary updates.
- Frame URL case handling should be consistent between setFrames and getFramesForURLs.
- 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.
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, | |
}, | |
}; |
* fix: Frames Renders on initial Send Updated to use zustand store for managing frames Updated to use hasFrames rather than isFrame * cleanup
Updated to use zustand store for managing frames
Updated to use hasFrames rather than isFrame
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Refactor
FramesPreviews
component, reducing unnecessary updates.