Skip to content

feat(settings): Move settings from the modal into a tab panel. #186

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

Merged
merged 13 commits into from
Mar 17, 2025

Conversation

junhaoliao
Copy link
Member

@junhaoliao junhaoliao commented Feb 17, 2025

Description

  1. Move settings from the modal into a tab panel.
  2. Uplift active tab state management to StateContextProvider.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

  1. For each config item, modified and clicked "Apply & Reload" to ensure the config was applied correctly.
  2. Dragged the tab panel resize handle towards the left and ensured no component was overflowing the container.
  3. Selected the Settings tab and reloaded the viewer. Observed that at the next load, the Settings tab was by default expanded.

Summary by CodeRabbit

  • New Features

    • Introduced an integrated, tab-based settings panel that streamlines configuration management by replacing the former modal dialogue.
  • Style

    • Enhanced layout and spacing for sidebar panels and theme switches, improving responsiveness and overall visual consistency.
    • Added new CSS classes for better styling of settings tab components.
  • Refactor

    • Simplified tab management and state handling within the sidebar, ensuring smoother interactions and a more cohesive user experience.
    • Updated the component structure to enhance the integration of settings directly within the tab interface.
  • Bug Fixes

    • Removed deprecated styles and components related to the previous modal implementation, ensuring a cleaner codebase.

Copy link

coderabbitai bot commented Feb 17, 2025

Walkthrough

The changes refactor the sidebar configuration interface by transitioning from a modal-based approach to a tab-based system. Component logic and CSS styling have been updated to integrate a new SettingsTabPanel, while state management now relies on context rather than local state. Import paths have been corrected, and new CSS classes have been introduced to support the updated layout. Additionally, the legacy SettingsModal and its associated styles have been removed.

Changes

File(s) Change Summary
src/components/CentralContainer/Sidebar/SidebarTabs/CustomTabPanel.css Removed the original padding setting; added min-width: 0 !important, padding: 0.75rem !important, and padding-right: 0.5rem !important for the .sidebar-tab-panel class.
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.css
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.tsx
Added a new CSS class .theme-switch-toggle-button-group with flex-wrap: wrap; updated the import path for THEME_NAME and applied the new class to the ToggleButtonGroup component.
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.css
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.tsx
Introduced new CSS classes (.settings-tab-container, .settings-form-fields-container); added a new React component (SettingsTabPanel) to replace the modal-based settings interface and updated configuration handling.
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx Modified the props interface by removing legacy properties and adopting a ref property; integrated state management from context and replaced modal handling with direct incorporation of the SettingsTabPanel.
src/components/CentralContainer/Sidebar/index.tsx Refactored to use context-based state management by removing local state hooks; updated resizing logic to respond to changes in activeTabName.
src/components/modals/SettingsModal/* Deleted both the CSS and TSX files for the SettingsModal, thereby removing the modal dialog interface and its associated styling.
src/contexts/StateContextProvider.tsx Added the state variable activeTabName and the function setActiveTabName to manage the active tab; removed the isSettingsModalOpen state and its corresponding setter, and updated the default state initialization.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant ST as SidebarTabs
    participant SC as StateContext
    participant SB as Sidebar
    participant STP as SettingsTabPanel

    User->>ST: Clicks on a tab (e.g., Settings)
    ST->>SC: Calls setActiveTabName("Settings")
    SC-->>SB: Updates activeTabName state
    SB->>STP: Renders SettingsTabPanel based on activeTabName
Loading

Suggested reviewers

  • davemarco

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

@junhaoliao
Copy link
Member Author

This PR depends on #184

@junhaoliao junhaoliao requested a review from davemarco February 17, 2025 16:22
# Conflicts:
#	src/components/modals/SettingsModal/SettingsDialog.tsx
#	src/components/modals/SettingsModal/index.css
@davemarco
Copy link
Contributor

@junhaoliao - is this off draft? if so, lmk and I will look

@junhaoliao junhaoliao marked this pull request as ready for review February 17, 2025 23:12
@junhaoliao
Copy link
Member Author

@junhaoliao - is this off draft? if so, lmk and I will look

Just fixed some overflowing issues. It's now ready for review.

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

🧹 Nitpick comments (6)
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.tsx (2)

39-81: Consider adding TypeScript interface for form field configuration.

The form field configuration is well-structured, but adding a TypeScript interface would improve type safety and maintainability.

+interface ConfigFormField {
+  helperText: string | JSX.Element;
+  initialValue: string | number;
+  key: LOCAL_STORAGE_KEY;
+  label: string;
+  type: 'text' | 'number';
+}

-const CONFIG_FORM_FIELDS = [
+const CONFIG_FORM_FIELDS: ConfigFormField[] = [

137-179: Consider grouping related form fields.

The form fields could be organized into logical groups using fieldsets for better organization and accessibility.

     <Box className={"settings-form-fields-container"}>
         <ThemeSwitchFormField/>
+        <fieldset>
+            <legend>Decoder Settings</legend>
             {CONFIG_FORM_FIELDS.filter(field => field.key.startsWith('decoderOptions')).map((field, index) => (
                 <FormControl key={index}>
                     <FormLabel>{field.label}</FormLabel>
                     <Input
                         defaultValue={field.initialValue}
                         name={field.key}
                         type={field.type}/>
                     <FormHelperText>{field.helperText}</FormHelperText>
                 </FormControl>
             ))}
+        </fieldset>
+        <fieldset>
+            <legend>View Settings</legend>
             {CONFIG_FORM_FIELDS.filter(field => !field.key.startsWith('decoderOptions')).map((field, index) => (
                 <FormControl key={index}>
                     <FormLabel>{field.label}</FormLabel>
                     <Input
                         defaultValue={field.initialValue}
                         name={field.key}
                         type={field.type}/>
                     <FormHelperText>{field.helperText}</FormHelperText>
                 </FormControl>
             ))}
+        </fieldset>
     </Box>
src/components/CentralContainer/Sidebar/index.tsx (2)

50-54: Consider debouncing the resize handler.

To improve performance, consider debouncing the resize handler to prevent excessive state updates.

+import debounce from 'lodash/debounce';

 const handleResizeHandleRelease = useCallback(() => {
     if (getPanelWidth() === tabListRef.current?.clientWidth) {
         changeActiveTabName(TAB_NAME.NONE);
     }
-}, [changeActiveTabName]);
+}, [changeActiveTabName]);
+
+const debouncedHandleResizeHandleRelease = debounce(handleResizeHandleRelease, 150);

80-97: Consider throttling window resize handler.

To improve performance during window resizing, consider throttling the handler.

+import throttle from 'lodash/throttle';

 useEffect(() => {
-    const handleWindowResize = () => {
+    const handleWindowResize = throttle(() => {
         const availableWidth = Math.max(
             window.innerWidth - EDITOR_MIN_WIDTH_IN_PIXELS,
             PANEL_CLIP_THRESHOLD_IN_PIXELS
         );

         if (getPanelWidth() > availableWidth) {
             setPanelWidth(availableWidth);
         }
-    };
+    }, 100);
src/contexts/StateContextProvider.tsx (2)

111-111: Consider using a more type-safe default implementation.

Instead of using a null-returning arrow function, consider throwing an error to catch uninitialized context usage:

-    changeActiveTabName: () => null,
+    changeActiveTabName: () => {
+        throw new Error('StateContext not initialized');
+    },

279-292: Consider moving side effects to useEffect.

The setConfig calls within the state setter function could lead to unnecessary re-renders. Consider moving them to a useEffect:

 const changeActiveTabName = useCallback((tabName: TAB_NAME) => {
     setActiveTabName((oldTabName) => {
         if (oldTabName === tabName) {
-            setConfig({key: CONFIG_KEY.INITIAL_TAB_NAME, value: TAB_NAME.NONE});
             return TAB_NAME.NONE;
         }
-        setConfig({key: CONFIG_KEY.INITIAL_TAB_NAME, value: tabName});
         return tabName;
     });
 }, []);

+useEffect(() => {
+    setConfig({key: CONFIG_KEY.INITIAL_TAB_NAME, value: activeTabName});
+}, [activeTabName]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e64e3a and 2e8efd2.

📒 Files selected for processing (11)
  • src/components/CentralContainer/Sidebar/SidebarTabs/CustomTabPanel.css (1 hunks)
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.css (1 hunks)
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.tsx (2 hunks)
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.css (1 hunks)
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.tsx (1 hunks)
  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (2 hunks)
  • src/components/CentralContainer/Sidebar/index.tsx (3 hunks)
  • src/components/modals/SettingsModal/SettingsDialog.tsx (0 hunks)
  • src/components/modals/SettingsModal/index.css (0 hunks)
  • src/components/modals/SettingsModal/index.tsx (0 hunks)
  • src/contexts/StateContextProvider.tsx (12 hunks)
💤 Files with no reviewable changes (3)
  • src/components/modals/SettingsModal/index.tsx
  • src/components/modals/SettingsModal/index.css
  • src/components/modals/SettingsModal/SettingsDialog.tsx
✅ Files skipped from review due to trivial changes (3)
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.css
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.css
  • src/components/CentralContainer/Sidebar/SidebarTabs/CustomTabPanel.css
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}`: - Prefer `false == ...

**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.tsx
  • src/components/CentralContainer/Sidebar/index.tsx
  • src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/index.tsx
  • src/contexts/StateContextProvider.tsx
  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx
🔇 Additional comments (6)
src/components/CentralContainer/Sidebar/SidebarTabs/SettingsTabPanel/ThemeSwitchFormField.tsx (3)

15-17: LGTM! Import paths are correctly updated.

The import paths have been properly adjusted to reflect the new file location in the directory structure.


25-27: LGTM! Theme handling is well-implemented.

The component correctly uses the useColorScheme hook from MUI Joy for theme management.


33-34: LGTM! UI layout improvement.

The addition of the theme-switch-toggle-button-group class improves the layout by enabling button wrapping.

src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (2)

48-52: LGTM! State management is properly migrated to context.

The component correctly uses StateContext for tab management, improving state management consistency.


65-99: LGTM! Tab panel integration is well-implemented.

The tabs are properly configured with correct orientation and variant, and the SettingsTabPanel is well-integrated.

src/components/CentralContainer/Sidebar/index.tsx (1)

99-120: LGTM! Tab state handling is well-implemented.

The effect properly handles panel width updates based on the active tab state, including edge cases.

Comment on lines 88 to 92
const handleConfigFormReset = (ev: React.FormEvent) => {
ev.preventDefault();
window.localStorage.clear();
window.location.reload();
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider selective localStorage clearing.

The current implementation clears all localStorage data. Consider clearing only configuration-related keys to preserve other application data.

-    window.localStorage.clear();
+    Object.values(LOCAL_STORAGE_KEY).forEach(key => {
+        window.localStorage.removeItem(key);
+    });
📝 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
const handleConfigFormReset = (ev: React.FormEvent) => {
ev.preventDefault();
window.localStorage.clear();
window.location.reload();
};
const handleConfigFormReset = (ev: React.FormEvent) => {
ev.preventDefault();
Object.values(LOCAL_STORAGE_KEY).forEach(key => {
window.localStorage.removeItem(key);
});
window.location.reload();
};

Comment on lines 102 to 135
const handleConfigFormSubmit = useCallback(
(ev: React.FormEvent) => {
ev.preventDefault();
const formData = new FormData(ev.target as HTMLFormElement);
const getFormDataValue = (key: string) => formData.get(key) as string;

const formatString = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_FORMAT_STRING);
const logLevelKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_LOG_LEVEL_KEY);
const timestampKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_TIMESTAMP_KEY);
const pageSize = getFormDataValue(LOCAL_STORAGE_KEY.PAGE_SIZE);

let error: Nullable<string> = null;
error ||= setConfig({
key: CONFIG_KEY.DECODER_OPTIONS,
value: {formatString, logLevelKey, timestampKey},
});
error ||= setConfig({
key: CONFIG_KEY.PAGE_SIZE,
value: Number(pageSize),
});

if (null !== error) {
postPopUp({
level: LOG_LEVEL.ERROR,
message: error,
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Unable to apply config.",
});
} else {
window.location.reload();
}
},
[postPopUp],
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation before applying configuration.

Consider validating the form data before applying the configuration to prevent invalid values.

     const handleConfigFormSubmit = useCallback(
         (ev: React.FormEvent) => {
             ev.preventDefault();
             const formData = new FormData(ev.target as HTMLFormElement);
             const getFormDataValue = (key: string) => formData.get(key) as string;

             const formatString = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_FORMAT_STRING);
             const logLevelKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_LOG_LEVEL_KEY);
             const timestampKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_TIMESTAMP_KEY);
             const pageSize = getFormDataValue(LOCAL_STORAGE_KEY.PAGE_SIZE);

+            // Validate page size
+            const pageSizeNum = Number(pageSize);
+            if (isNaN(pageSizeNum) || pageSizeNum <= 0) {
+                postPopUp({
+                    level: LOG_LEVEL.ERROR,
+                    message: "Page size must be a positive number",
+                    timeoutMillis: DO_NOT_TIMEOUT_VALUE,
+                    title: "Invalid configuration",
+                });
+                return;
+            }
📝 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
const handleConfigFormSubmit = useCallback(
(ev: React.FormEvent) => {
ev.preventDefault();
const formData = new FormData(ev.target as HTMLFormElement);
const getFormDataValue = (key: string) => formData.get(key) as string;
const formatString = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_FORMAT_STRING);
const logLevelKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_LOG_LEVEL_KEY);
const timestampKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_TIMESTAMP_KEY);
const pageSize = getFormDataValue(LOCAL_STORAGE_KEY.PAGE_SIZE);
let error: Nullable<string> = null;
error ||= setConfig({
key: CONFIG_KEY.DECODER_OPTIONS,
value: {formatString, logLevelKey, timestampKey},
});
error ||= setConfig({
key: CONFIG_KEY.PAGE_SIZE,
value: Number(pageSize),
});
if (null !== error) {
postPopUp({
level: LOG_LEVEL.ERROR,
message: error,
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Unable to apply config.",
});
} else {
window.location.reload();
}
},
[postPopUp],
);
const handleConfigFormSubmit = useCallback(
(ev: React.FormEvent) => {
ev.preventDefault();
const formData = new FormData(ev.target as HTMLFormElement);
const getFormDataValue = (key: string) => formData.get(key) as string;
const formatString = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_FORMAT_STRING);
const logLevelKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_LOG_LEVEL_KEY);
const timestampKey = getFormDataValue(LOCAL_STORAGE_KEY.DECODER_OPTIONS_TIMESTAMP_KEY);
const pageSize = getFormDataValue(LOCAL_STORAGE_KEY.PAGE_SIZE);
// Validate page size
const pageSizeNum = Number(pageSize);
if (isNaN(pageSizeNum) || pageSizeNum <= 0) {
postPopUp({
level: LOG_LEVEL.ERROR,
message: "Page size must be a positive number",
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Invalid configuration",
});
return;
}
let error: Nullable<string> = null;
error ||= setConfig({
key: CONFIG_KEY.DECODER_OPTIONS,
value: { formatString, logLevelKey, timestampKey },
});
error ||= setConfig({
key: CONFIG_KEY.PAGE_SIZE,
value: Number(pageSize),
});
if (null !== error) {
postPopUp({
level: LOG_LEVEL.ERROR,
message: error,
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Unable to apply config.",
});
} else {
window.location.reload();
}
},
[postPopUp],
);

Comment on lines 54 to 62
const handleTabButtonClick = (tabName: TAB_NAME) => {
switch (tabName) {
case TAB_NAME.SETTINGS:
setIsSettingsModalOpen(true);
break;
case TAB_NAME.DOCUMENTATION:
openInNewTab(DOCUMENTATION_URL);
break;
default:
onActiveTabNameChange(tabName);
changeActiveTabName(tabName);
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add security attributes for external links.

When opening documentation in a new tab, consider adding security-related attributes.

     case TAB_NAME.DOCUMENTATION:
-        openInNewTab(DOCUMENTATION_URL);
+        openInNewTab(DOCUMENTATION_URL, { rel: 'noopener noreferrer' });
         break;
📝 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
const handleTabButtonClick = (tabName: TAB_NAME) => {
switch (tabName) {
case TAB_NAME.SETTINGS:
setIsSettingsModalOpen(true);
break;
case TAB_NAME.DOCUMENTATION:
openInNewTab(DOCUMENTATION_URL);
break;
default:
onActiveTabNameChange(tabName);
changeActiveTabName(tabName);
}
};
const handleTabButtonClick = (tabName: TAB_NAME) => {
switch (tabName) {
case TAB_NAME.DOCUMENTATION:
openInNewTab(DOCUMENTATION_URL, { rel: 'noopener noreferrer' });
break;
default:
changeActiveTabName(tabName);
}
};

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

Initial high level comment + 1 small nit

activeTabName,
onActiveTabNameChange,
},
const SidebarTabs = forwardRef<HTMLDivElement>((
Copy link
Contributor

Choose a reason for hiding this comment

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

Should probably just fix this now? it's deprecated
https://react.dev/reference/react/forwardRef

@@ -297,7 +313,7 @@ const StateContextProvider = ({children}: StateContextProviderProps) => {
children: "Settings",
startDecorator: <SettingsOutlinedIcon/>,
onClick: () => {
setIsSettingsModalOpen(true);
changeActiveTabName(TAB_NAME.SETTINGS);
Copy link
Contributor

Choose a reason for hiding this comment

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

can we just call setActiveTabName here, and get rid of changeActiveTabName? We could then not delete exisitng handleActiveTabNameChange in src/components/CentralContainer/Sidebar/index.tsx

Copy link
Contributor

Choose a reason for hiding this comment

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

I feel like the less in StateContextProvider the better

Copy link
Member Author

Choose a reason for hiding this comment

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

We do need to save the last active tab name into localStorage and I feel it's best if we can save the name whenever a tab name change is request, to avoid duplicate code. If the function is not purely state settings, i want to avoid naming it with the set prefix to reduce confusion for code readers.

That said, an attempt was made to remove the toggling on same tab name logic from changeActiveTabName, which also fixes a bug in this pop up, where an active settings tab can be closed once the user click this primary action.

Copy link
Contributor

Choose a reason for hiding this comment

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

save the last active tab name into localStorage and I feel it's best if we can save the name whenever a tab name change is request, to avoid duplicate code.

You can move the setConfig into the useEffect in /Sidebar/index.tsx, it should work. After that, you can remove changeActiveTabName entirely, and replace all references of it to setActiveTabName from useState.

I dont think we are adding duplicate code, and I think slightly simpler.

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

♻️ Duplicate comments (1)
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (1)

59-61: ⚠️ Potential issue

Add security attributes for external links.

When opening documentation in a new tab, consider adding security-related attributes.

Apply this diff:

     case TAB_NAME.DOCUMENTATION:
-        openInNewTab(DOCUMENTATION_URL);
+        openInNewTab(DOCUMENTATION_URL, { rel: 'noopener noreferrer' });
         break;
🧹 Nitpick comments (1)
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (1)

28-28: Move hardcoded URL to configuration file.

Consider moving the DOCUMENTATION_URL to a configuration file for better maintainability and centralized management of external URLs.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e8efd2 and c9d425b.

📒 Files selected for processing (1)
  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}`: - Prefer `false == ...

**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx
🧠 Learnings (1)
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (1)
Learnt from: junhaoliao
PR: y-scope/yscope-log-viewer#74
File: new-log-viewer/src/components/SidebarContainer/index.tsx:107-107
Timestamp: 2024-11-10T16:46:58.543Z
Learning: The `PanelTabs` component is already wrapped with `React.forwardRef` and passes the `ref` to the appropriate child element.
🔇 Additional comments (1)
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (1)

67-102: Well-structured tab implementation with proper state management.

The tab implementation effectively uses context for state management and maintains a clean separation between tab buttons and panels. The structure aligns well with the PR objective of moving settings into a tab panel.

Comment on lines +52 to +54
const SidebarTabs = ({
ref,
}: SidebarTabsProps) => {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Restore forwardRef wrapper.

Based on the retrieved learnings, this component should be wrapped with React.forwardRef. The current implementation might break ref forwarding functionality.

Apply this diff to restore the forwardRef wrapper:

-const SidebarTabs = ({
-    ref,
-}: SidebarTabsProps) => {
+const SidebarTabs = forwardRef<HTMLDivElement, SidebarTabsProps>(({}, ref) => {
📝 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
const SidebarTabs = ({
ref,
}: SidebarTabsProps) => {
-const SidebarTabs = ({
- ref,
-}: SidebarTabsProps) => {
+const SidebarTabs = forwardRef<HTMLDivElement, SidebarTabsProps>(({}, ref) => {

# Conflicts:
#	src/components/modals/SettingsModal/SettingsDialog.tsx
@junhaoliao junhaoliao requested a review from a team as a code owner March 2, 2025 05:31
@junhaoliao junhaoliao requested a review from davemarco March 2, 2025 05:50
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

🧹 Nitpick comments (1)
src/contexts/StateContextProvider.tsx (1)

97-97: Default state for the active tab.
Pulling activeTabName from the config is helpful for remembering the last-open tab. Consider adding a fallback if getConfig(CONFIG_KEY.INITIAL_TAB_NAME) returns an invalid tab:

-    activeTabName: getConfig(CONFIG_KEY.INITIAL_TAB_NAME),
+    activeTabName: (() => {
+        const candidate = getConfig(CONFIG_KEY.INITIAL_TAB_NAME);
+        return isValidTabName(candidate) ? candidate : TAB_NAME.NONE;
+    })(),

Also applies to: 114-114

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d57d11 and e834fba.

📒 Files selected for processing (3)
  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (3 hunks)
  • src/components/CentralContainer/Sidebar/index.tsx (3 hunks)
  • src/contexts/StateContextProvider.tsx (11 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}`: - Prefer `false == ...

**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/contexts/StateContextProvider.tsx
  • src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx
  • src/components/CentralContainer/Sidebar/index.tsx
🧠 Learnings (1)
src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (1)
Learnt from: junhaoliao
PR: y-scope/yscope-log-viewer#74
File: new-log-viewer/src/components/SidebarContainer/index.tsx:107-107
Timestamp: 2025-03-14T10:38:03.498Z
Learning: The `PanelTabs` component is already wrapped with `React.forwardRef` and passes the `ref` to the appropriate child element.
🔇 Additional comments (16)
src/components/CentralContainer/Sidebar/index.tsx (4)

3-3: No issues with the updated imports.
These new imports are necessary for adopting the context-based approach.

Also applies to: 8-8


49-49: Effective usage of the context-based tab management.
Accessing activeTabName and setActiveTabName from context simplifies local state logic and keeps the component focused.

Also applies to: 52-52, 56-56


101-124: Persisting the active tab name using setConfig.
Storing the active tab in the config ensures a consistent user experience when reloading. Please verify that INITIAL_TAB_NAME remains valid for all consumers.


129-133: Conditional rendering of the resize handle.
Hiding the resize handle when activeTabName is NONE neatly improves usability.

src/components/CentralContainer/Sidebar/SidebarTabs/index.tsx (7)

2-2: Properly referencing a ref prop and the new SettingsTabPanel import.
Explicitly typing the ref prop as Ref<HTMLDivElement> ensures clarity. Adding the SettingsTabPanel import aligns with the newly introduced tab.

Also applies to: 22-22, 42-42


48-49: Documentation improvements.
It is helpful to see the docstrings updated to mention the ref prop for clarity.


52-54: Restore forwardRef for prop-based ref usage.
The same recommendation was made earlier, advising wrapping the component in React.forwardRef to properly handle the passed-in ref.


55-55: Directly consuming activeTabName and setActiveTabName from context.
This context usage avoids repetitive prop passing and keeps the component simpler.


62-68: Tab toggling logic.
Closing the tab upon repeated selection provides an intuitive user experience. Nicely done.


92-103: Positioning help and settings at the bottom.
Placing these tabs at the bottom can make them more consistently visible and easier to distinguish.


104-107: Introducing integrated tab panels.
Rendering FileInfoTabPanel, SearchTabPanel, and SettingsTabPanel within these tabs unifies the UI under one tabbed interface.

src/contexts/StateContextProvider.tsx (5)

33-33: Refine import usage.
Ensuring TAB_NAME is accurately imported preserves consistency across the application.


70-70: Additional fields in StateContext.
Defining activeTabName and setActiveTabName streamlines tab-based navigation and removes the need for separate modal state.

Also applies to: 87-87


254-254: State initialization of activeTabName.
Using STATE_DEFAULT.activeTabName unifies defaults between the static config and runtime state.


280-281: Launch the settings tab on the format popup action.
Switching to the settings tab when a format string is missing guides users to implement custom formatting.


558-558: Context value updated to include activeTabName and setActiveTabName.
Exposing these props in the provider supports the tab-based approach throughout the application.

Also applies to: 575-575

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

Tested basic functionality. Lgtm

@davemarco
Copy link
Contributor

I am good with title

@junhaoliao junhaoliao merged commit 0bea845 into y-scope:main Mar 17, 2025
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.

2 participants