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(filter): Clear existing log level filter when opening a new file (fixes #133). #141

Merged
merged 9 commits into from
Dec 3, 2024

Conversation

davemarco
Copy link
Contributor

@davemarco davemarco commented Nov 29, 2024

Description

Log level filter was persisting across files.

Moreover, the filter was not actually applied to the new file. It just remained in UI selector.

I modified so now when you open a new file, the filter is cleared. I had to take some care so that the reset does not trigger a new filtering request to the backend. The reset only clears the selected levels in the UI, it does not actually send a filtering request.

fixes #133

Validation performed

Tested levels are cleared with new file. Tested i did not break filtering.

Summary by CodeRabbit

  • New Features

    • Introduced a streamlined log level filtering mechanism in the StatusBar component.
    • Added a new method for filtering logs based on selected log levels.
  • Bug Fixes

    • Improved state management for log levels, ensuring accurate filtering when loading new files.

These updates enhance user experience by providing clearer and more efficient log level controls.

@davemarco davemarco requested a review from junhaoliao November 29, 2024 20:39
Copy link

coderabbitai bot commented Nov 29, 2024

Walkthrough

The pull request introduces modifications to the LogLevelSelect component and the StateContextProvider. The LogLevelSelect component has been refactored to enhance state management by removing the setLogLevelFilter function and replacing it with a new filterLogs method. This change streamlines how log levels are updated and filtered in response to user interactions. Additionally, the StateContextProvider has been updated to include the new filterLogs method, ensuring that it is accessible to components that consume the context.

Changes

File Path Change Summary
src/components/StatusBar/LogLevelSelect/index.tsx Removed setLogLevelFilter from context; added updateFilter function; updated event handlers to use updateFilter.
src/contexts/StateContextProvider.tsx Introduced filterLogs method; removed setLogLevelFilter; updated context provider values to include filterLogs.

Assessment against linked issues

Objective Addressed Explanation
Log level filter should reset when loading another file (Issue #133)

Possibly related PRs

Suggested reviewers

  • junhaoliao
  • kirkrodrigues

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 22848ca and b7373cc.

📒 Files selected for processing (1)
  • src/components/StatusBar/LogLevelSelect/index.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/StatusBar/LogLevelSelect/index.tsx

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

@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

🧹 Outside diff range and nitpick comments (3)
src/components/StatusBar/LogLevelSelect/index.tsx (2)

169-179: Consider adding error handling for the backend filter operation.

While the function effectively manages both UI state and backend filtering, it would be more robust with error handling for the backend operation. This ensures graceful degradation if the backend filtering fails.

 const updateFilter = useCallback((logLevels: LOG_LEVEL[]) => {
     setSelectedLogLevels(logLevels);

     // Filter logs in backend worker.
-    filterLogs((0 === logLevels.length ?
-        null :
-        logLevels));
+    try {
+        filterLogs((0 === logLevels.length ? null : logLevels));
+    } catch (error) {
+        console.error('Failed to apply log level filter:', error);
+        // Consider adding user feedback here
+    }
 }, [
     filterLogs,
     setSelectedLogLevels,
 ]);

211-212: Consider enhancing error handling with user feedback.

While the function correctly handles the undefined value case, consider providing user feedback when errors occur.

 if ("undefined" === typeof currentTarget.dataset.value) {
-    console.error("Unexpected undefined value for \"data-value\" attribute");
+    const errorMessage = "Failed to apply log level filter due to invalid selection";
+    console.error(errorMessage);
+    // Consider using a toast notification or similar UI feedback
     return;
 }
src/contexts/StateContextProvider.tsx (1)

Line range hint 456-464: Consider adding error handling for null worker

The filterLogs implementation silently returns when the worker is null. Consider logging an error message for debugging purposes.

 const filterLogs = useCallback((filter: LogLevelFilter) => {
     if (null === mainWorkerRef.current) {
+        console.error("Unexpected null mainWorkerRef.current in filterLogs");
         return;
     }
     setUiState(UI_STATE.FAST_LOADING);
     workerPostReq(mainWorkerRef.current, WORKER_REQ_CODE.SET_FILTER, {
         cursor: {code: CURSOR_CODE.EVENT_NUM, args: {eventNum: logEventNumRef.current ?? 1}},
         logLevelFilter: filter,
     });
 }, []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 969ff35 and 90fd230.

📒 Files selected for processing (2)
  • src/components/StatusBar/LogLevelSelect/index.tsx (4 hunks)
  • src/contexts/StateContextProvider.tsx (6 hunks)
🔇 Additional comments (8)
src/components/StatusBar/LogLevelSelect/index.tsx (3)

152-152: Well-structured migration to context-based state management!

The shift from local state to context management is a solid architectural choice that enables centralized control of log level filters, which is crucial for implementing the filter reset functionality when opening new files.


196-200: Clean integration with the new updateFilter function!

The changes maintain the existing functionality while properly integrating with the new filtering mechanism. The sort operation ensures consistent ordering of log levels.


214-216: Effective implementation of filter clearing!

The simplified implementation properly integrates with the new filtering mechanism and supports the PR's objective of clearing filters.

src/contexts/StateContextProvider.tsx (5)

76-76: LGTM: Interface updates align with requirements

The additions to StateContextType interface properly define the contract for managing log level filtering:

  • selectedLogLevels for state tracking
  • filterLogs for applying filters
  • setSelectedLogLevels for direct state updates

Also applies to: 81-81, 85-85


105-105: LGTM: Default state initialization is correct

The default values are properly initialized:

  • Empty array for selectedLogLevels
  • Null functions for filterLogs and setSelectedLogLevels

Also applies to: 109-109, 113-113


266-267: LGTM: State management implementation

The useState hook is correctly implemented for selectedLogLevels with proper typing.


416-416: LGTM: Filter reset implementation matches requirements

The loadFile function correctly resets selectedLogLevels to default state when opening a new file, which addresses the core issue from PR #133.


556-556: LGTM: Context value updates are complete

The StateContext.Provider value object correctly includes all new properties and methods.

Also applies to: 560-560, 564-564

Copy link
Member

@junhaoliao junhaoliao left a comment

Choose a reason for hiding this comment

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

Have we considered handling this completely within <LogLevelSelect/>?

We can add an useEffect hook that subscribes to uiState changes. When it is UI_STATE.FILE_LOADING, we setSelectedLogLevels([]).

If the existing useEffect(()=>setLogLevelFilter()), [..., selectedLogLevels]) hook would be triggered when we set the empty array, we can add a ref boolean variable isClearingSelectedLogLevels to temporarily supress sending the log filter update request.

@junhaoliao
Copy link
Member

By the way, setLogLevelFilter seems like a React state variable setter. Shall we submit an issue for changing the name to something like changeLogLevelFilter in another PR?

@davemarco
Copy link
Contributor Author

We can add an useEffect hook that subscribes to uiState changes. When it is UI_STATE.FILE_LOADING, we setSelectedLogLevels([]).

I'm happy to do this. It will add an extra render since we are setting in a hook vs. at the same time we set ui state file loading, but it does allow us to not lift up SelectedLogLevels, which is cleaner.

If the existing useEffect(()=>setLogLevelFilter()), [..., selectedLogLevels]) hook would be triggered when we set the empty array, we can add a ref boolean variable isClearingSelectedLogLevels to temporarily supress sending the log filter update request.

I think the updateFilter() method I added will still work, even after the first change. The updateFilter() method gets rid of the hook entirely. I think i prefer just getting rid of the hook, but let me know if you think use effect is cleaner.

@davemarco
Copy link
Contributor Author

By the way, setLogLevelFilter seems like a React state variable setter. Shall we submit an issue for changing the name to something like changeLogLevelFilter in another PR?

Yes I thought it was weird as well. I changed to filterLogs() in this PR? Does that work. I tried to make it sound more like loadPage() implying it is doing something in the backend.

@junhaoliao
Copy link
Member

By the way, setLogLevelFilter seems like a React state variable setter. Shall we submit an issue for changing the name to something like changeLogLevelFilter in another PR?

Yes I thought it was weird as well. I changed to filterLogs() in this PR? Does that work. I tried to make it sound more like loadPage() implying it is doing something in the backend.

filterLogs sounds good

@junhaoliao
Copy link
Member

I think the updateFilter() method I added will still work, even after the first change. The updateFilter() method gets rid of the hook entirely. I think i prefer just getting rid of the hook, but let me know if you think use effect is cleaner.

Sounds good. I agree the updateFilter() method is cleaner than the useEffect hook.

Copy link

@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

🧹 Outside diff range and nitpick comments (3)
src/components/StatusBar/LogLevelSelect/index.tsx (3)

157-157: Consider consolidating state management

While the change to use filterLogs is good, consider moving selectedLogLevels to the context to maintain a single source of truth for all log level related state.


Line range hint 186-218: Consider enhancing error handling

The event handlers are well-refactored to use the centralized updateFilter. However, consider adding error boundaries or try-catch blocks around the numeric conversions to handle potential invalid values gracefully.

Example enhancement for handleOptionClick:

 const handleOptionClick = useCallback((ev: React.MouseEvent) => {
     const currentTarget = ev.currentTarget as HTMLElement;
     if ("undefined" === typeof currentTarget.dataset.value) {
         console.error("Unexpected undefined value for \"data-value\" attribute");
         return;
     }
-    const selectedValue = Number(currentTarget.dataset.value);
+    try {
+        const selectedValue = Number(currentTarget.dataset.value);
+        if (isNaN(selectedValue)) {
+            throw new Error("Invalid log level value");
+        }
+        updateFilter(range({begin: selectedValue, end: 1 + MAX_LOG_LEVEL}));
+    } catch (error) {
+        console.error("Failed to process log level selection:", error);
+    }
-    updateFilter(range({begin: selectedValue, end: 1 + MAX_LOG_LEVEL}));
 }, [updateFilter]);

224-229: Consider adding a cleanup function to the effect

The effect successfully addresses the filter persistence issue. However, consider adding a cleanup function to handle potential race conditions during rapid file switches.

 useEffect(() => {
     if (UI_STATE.FILE_LOADING === uiState) {
         setSelectedLogLevels([]);
     }
+    return () => {
+        // Cancel any pending state updates if the component unmounts
+        // or if the effect re-runs
+    };
 }, [uiState]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 90fd230 and db8eecc.

📒 Files selected for processing (2)
  • src/components/StatusBar/LogLevelSelect/index.tsx (5 hunks)
  • src/contexts/StateContextProvider.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/contexts/StateContextProvider.tsx
🔇 Additional comments (3)
src/components/StatusBar/LogLevelSelect/index.tsx (3)

35-38: LGTM: Clean import organization

The new imports are properly organized and necessary for the UI state management functionality.


175-185: LGTM: Well-optimized filter update logic

The updateFilter implementation efficiently combines UI state updates with backend filtering. The null check for empty log levels is a good optimization.


224-229: Verify the fix across different file loading scenarios

While the implementation looks correct, please verify these scenarios:

  1. Rapid file switching
  2. Large files that take longer to load
  3. Drag and drop vs. regular file opening
✅ Verification successful

Let me gather more information about file loading implementation to verify the scenarios mentioned.


Let me search for more specific information about file loading state transitions and error handling.


Based on the gathered information, I can now provide a final response about the file loading scenarios.

The implementation correctly handles file loading state transitions

The code review shows robust handling of file loading scenarios:

  • The UI state transitions properly handle both regular and drag-and-drop file loading
  • Multiple loading states (FILE_LOADING, SLOW_LOADING, FAST_LOADING) are managed to handle different scenarios
  • The LogLevelSelect component correctly clears selected levels during FILE_LOADING state
  • Drag and drop implementation includes proper disabled state handling during loading

Key findings:

  • File loading state is properly managed in StateContextProvider
  • Drag and drop operations are properly guarded against concurrent operations
  • State transitions ensure consistent UI updates across different loading methods
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for file loading related code to ensure consistent behaviour
rg -A 5 "FILE_LOADING" --type ts

Length of output: 2366


Script:

#!/bin/bash
# Search for drag and drop related file loading
rg -A 10 "onDrop" --type ts

# Search for file size handling
rg -A 5 "fileSizeInBytes|onDiskFileSizeInBytes" --type ts

# Search for file loading error handling
rg -A 5 "catch.*file" --type ts

Length of output: 9390


Script:

#!/bin/bash
# Search for file loading state transitions
ast-grep --pattern 'setUiState(UI_STATE.$_)'

# Search for handleDrop implementation
ast-grep --pattern 'const handleDrop = $_'

# Search for error handling during file loading
rg -A 10 "catch.*{" --type ts

Length of output: 2331

@davemarco davemarco requested a review from junhaoliao December 2, 2024 20:16
Copy link

@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 (2)
src/components/StatusBar/LogLevelSelect/index.tsx (2)

175-185: Consider adding documentation for null conversion.

The implementation is clean and efficient. However, the conversion of an empty array to null for the backend could benefit from a brief comment explaining why this is necessary.

Add a comment above line 179 explaining the null conversion:

        setSelectedLogLevels(logLevels);

+       // Convert empty array to null as backend expects null for no filter
        // Filter logs in backend worker.
        filterLogs((0 === logLevels.length ?

224-229: LGTM! Core fix implemented efficiently.

The effect correctly implements the PR's main objective by clearing the log level filter when loading a new file, without triggering unnecessary backend requests.

Would you like me to help create a test case to verify this behaviour? We could test that:

  1. The filter is cleared when uiState changes to FILE_LOADING
  2. No backend request is made during this clearing process
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between db8eecc and 22848ca.

📒 Files selected for processing (1)
  • src/components/StatusBar/LogLevelSelect/index.tsx (5 hunks)
🔇 Additional comments (2)
src/components/StatusBar/LogLevelSelect/index.tsx (2)

35-38: LGTM! Necessary imports added for UI state handling.

The new imports are properly organized and required for the UI state management functionality.


157-157: LGTM! Improved context usage with more descriptive naming.

The replacement of setLogLevelFilter with filterLogs better represents the action being performed and aligns with the PR's objectives.

Comment on lines +202 to +206
updateFilter(newSelectedLogLevels.sort((a, b) => a - b));
}, [
selectedLogLevels,
updateFilter,
]);
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Sorting log levels is unnecessary and can be removed

The log level filtering is implemented through a worker interface that simply accepts an array of log levels as a filter, with no indication that order matters. The filterLogs function in StateContextProvider passes the log levels directly to the worker without any ordering requirements.

  • Remove the .sort((a, b) => a - b) from line 202 in src/components/StatusBar/LogLevelSelect/index.tsx
  • The order of log levels in the filter array doesn't affect the filtering functionality
🔗 Analysis chain

Verify the necessity of sorting log levels.

The implementation looks correct, but let's verify if sorting the log levels is necessary for the backend processing.

Also applies to: 217-218, 221-221

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for log level array usage in backend processing
rg -A 5 "logLevels?.sort" 
# Search for order-dependent log level processing
ast-grep --pattern 'function $_(logLevels: $_) {
  $$$
  for ($_ of logLevels) {
    $$$
  }
  $$$
}'

Length of output: 131


Script:

#!/bin/bash
# Search for log level filtering or processing patterns
rg -A 5 "logLevel.*filter" 

# Search for any log level array handling
rg -A 5 "LogLevel\[]"

# Look for log level type definitions and interfaces
ast-grep --pattern 'type $_ = {
  $$$
  logLevel$_: $_
  $$$
}'

# Search for log level comparisons or ordering
rg -A 5 "LogLevel.*compare|LogLevel.*order"

Length of output: 531


Script:

#!/bin/bash
# Search for the LogLevelSelect component's interface and state handling
rg -A 10 "interface.*LogLevelSelect" 

# Look for filter state updates in the context
rg -A 10 "updateFilter.*LogLevel" 

# Search for log level enum or type definition
ast-grep --pattern 'enum LogLevel {
  $$$
}'

# Check how log levels are used in filtering
rg -A 10 "filterLogs|applyFilter.*logLevel"

Length of output: 6574

junhaoliao
junhaoliao previously approved these changes Dec 3, 2024
Copy link
Member

@junhaoliao junhaoliao left a comment

Choose a reason for hiding this comment

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

The changes look clean to me. The title is good for the final message or we could also write fix(filter) if you agree.

src/components/StatusBar/LogLevelSelect/index.tsx Outdated Show resolved Hide resolved
@davemarco davemarco requested a review from junhaoliao December 3, 2024 16:02
@davemarco davemarco changed the title fix: Clear existing log level filter when opening a new file (fixes #133). fix(filter): Clear existing log level filter when opening a new file (fixes #133). Dec 3, 2024
@davemarco davemarco merged commit f5dd33c into y-scope:main Dec 3, 2024
4 checks passed
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.

Bug: log level filter level doesn't reset when loading another file using drag and drop
2 participants