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

Allow users to close windows without confirming, delete last window #1598

Merged
merged 5 commits into from
Dec 20, 2024

Conversation

esimkowitz
Copy link
Member

@esimkowitz esimkowitz commented Dec 20, 2024

Adds window:savelastwindow and window:confirmclose settings, which can be used to alter the default window close behavior. Both of these default to true to maintain the existing default behavior.

If window:savelastwindow is unset, the same logic will be used as if the user had more than one window remaining (see below).

If window:confirmonclose is unset, the user will no longer be prompted to confirm if they are closing a window whose workspace has unsaved changes (the workspace is not named and it has more than one tab).

Copy link

coderabbitai bot commented Dec 20, 2024

Walkthrough

The pull request introduces enhanced window management configuration options across multiple files in the project. The changes focus on adding two new settings: window:confirmclose and window:savelastwindow, which provide more control over window closure behavior.

The modifications span several components of the application:

  1. In the frontend types (gotypes.d.ts), two optional boolean properties are added to the SettingsType interface to support the new configuration options.

  2. The default configuration file (settings.json) is updated to include these new properties, both set to true by default.

  3. In the backend configuration package (metaconsts.go), corresponding constants are defined for the new configuration keys.

  4. The settings configuration struct (settingsconfig.go) is extended to include two new boolean fields that align with the new configuration options.

  5. The main window implementation (emain-window.ts) is updated to incorporate logic for handling window closure based on these new settings, including user confirmation dialogs and more sophisticated window closing conditions.

These changes provide users with more granular control over window management, specifically around closing windows with unsaved changes and preserving the last window's state.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9af09e6 and ce3aa60.

📒 Files selected for processing (1)
  • docs/docs/config.mdx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/docs/config.mdx

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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 (3)
pkg/wconfig/defaultconfig/settings.json (1)

21-22: LGTM! Consider adding documentation.

The default values for the new window settings are appropriate:

  • window:confirmonclose: true (safer default)
  • window:savelastwindowonclose: true (better UX)

Consider adding comments in the JSON to document these settings' purposes and their impact on user experience.

pkg/wconfig/settingsconfig.go (1)

109-110: Consider grouping with other window-related fields.

While the implementation is correct, consider moving these fields to be grouped with other window-related fields (around line 90) for better code organization and maintainability.

 	WindowDisableHardwareAcceleration   bool     `json:"window:disablehardwareacceleration,omitempty"`
 	WindowMaxTabCacheSize               int      `json:"window:maxtabcachesize,omitempty"`
+	WindowConfirmOnClose                bool     `json:"window:confirmonclose,omitempty"`
+	WindowSaveLastWindowOnClose         bool     `json:"window:savelastwindowonclose,omitempty"`
 	WindowMagnifiedBlockOpacity         *float64 `json:"window:magnifiedblockopacity,omitempty"`
 	WindowMagnifiedBlockSize            *float64 `json:"window:magnifiedblocksize,omitempty"`
 	WindowMagnifiedBlockBlurPrimaryPx   *int64   `json:"window:magnifiedblockblurprimarypx,omitempty"`
 	WindowMagnifiedBlockBlurSecondaryPx *int64   `json:"window:magnifiedblockblursecondarypx,omitempty"`
-	WindowConfirmOnClose                bool     `json:"window:confirmonclose,omitempty"`
-	WindowSaveLastWindowOnClose         bool     `json:"window:savelastwindowonclose,omitempty"`
emain/emain-window.ts (1)

Line range hint 232-252: Consider improving maintainability and user experience.

  1. Extract the confirmation logic into a separate method for better maintainability.
  2. Enhance the confirmation dialog message to be more descriptive.
  3. Structure debug logging consistently.

Here's a suggested refactor:

-                const fullConfig = await FileService.GetFullConfig();
-                if (
-                    fullConfig.settings["window:confirmonclose"] &&
-                    (numWindows > 1 || !fullConfig.settings["window:savelastwindowonclose"])
-                ) {
-                    console.log("numWindows > 1", numWindows);
-                    const workspace = await WorkspaceService.GetWorkspace(this.workspaceId);
-                    console.log("workspace", workspace);
-                    if (isNonEmptyUnsavedWorkspace(workspace)) {
-                        console.log("workspace has no name, icon, and multiple tabs", workspace);
-                        const choice = dialog.showMessageBoxSync(this, {
-                            type: "question",
-                            buttons: ["Cancel", "Close Window"],
-                            title: "Confirm",
-                            message: "Window has unsaved tabs, closing window will delete existing tabs.\n\nContinue?",
-                        });
-                        if (choice === 0) {
-                            console.log("user cancelled close window", this.waveWindowId);
-                            return;
-                        }
-                    }
-                    console.log("deleteAllowed = true", this.waveWindowId);
-                    this.deleteAllowed = true;
-                }
+                const fullConfig = await FileService.GetFullConfig();
+                if (await this.shouldConfirmWindowClose(fullConfig, numWindows)) {
+                    const workspace = await WorkspaceService.GetWorkspace(this.workspaceId);
+                    if (await this.confirmCloseUnsavedWorkspace(workspace)) {
+                        this.deleteAllowed = true;
+                    } else {
+                        return;
+                    }
+                }

+    private async shouldConfirmWindowClose(fullConfig: FullConfigType, numWindows: number): Promise<boolean> {
+        return fullConfig.settings["window:confirmonclose"] &&
+            (numWindows > 1 || !fullConfig.settings["window:savelastwindowonclose"]);
+    }
+
+    private async confirmCloseUnsavedWorkspace(workspace: Workspace): Promise<boolean> {
+        if (!isNonEmptyUnsavedWorkspace(workspace)) {
+            return true;
+        }
+
+        console.log("[Window] Confirming close of unsaved workspace", {
+            windowId: this.waveWindowId,
+            workspace
+        });
+
+        const choice = dialog.showMessageBoxSync(this, {
+            type: "question",
+            buttons: ["Cancel", "Close Window"],
+            title: "Confirm Close Window",
+            message: [
+                "This window contains unsaved tabs that will be permanently deleted.",
+                "",
+                "• The workspace has not been saved",
+                "• Multiple tabs are open",
+                "",
+                "Would you like to close this window and delete all tabs?"
+            ].join("\n"),
+            defaultId: 0,
+            cancelId: 0
+        });
+
+        const confirmed = choice === 1;
+        console.log("[Window] User response to close confirmation", {
+            windowId: this.waveWindowId,
+            confirmed
+        });
+
+        return confirmed;
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9793f98 and a8d30d1.

📒 Files selected for processing (5)
  • emain/emain-window.ts (1 hunks)
  • frontend/types/gotypes.d.ts (1 hunks)
  • pkg/wconfig/defaultconfig/settings.json (2 hunks)
  • pkg/wconfig/metaconsts.go (1 hunks)
  • pkg/wconfig/settingsconfig.go (1 hunks)
🔇 Additional comments (3)
pkg/wconfig/metaconsts.go (1)

82-83: LGTM! Constants are well-defined.

The new constants follow the established naming conventions and are properly grouped with other window-related constants.

frontend/types/gotypes.d.ts (1)

682-683: LGTM! Well-structured window management settings.

The new optional properties are well-organized within the window:* settings group and follow the established naming conventions.

emain/emain-window.ts (1)

232-236: LGTM! Well-implemented window close confirmation logic.

The implementation correctly handles the window close confirmation based on the new settings and workspace state.

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 (2)
docs/docs/config.mdx (1)

83-83: Add a comma after "For reference".

Minor grammatical improvement needed.

-For reference this is the current default configuration (v0.10.4):
+For reference, this is the current default configuration (v0.10.4):
🧰 Tools
🪛 LanguageTool

[uncategorized] ~83-~83: Possible missing comma found.
Context: ... | For reference this is the current default configurati...

(AI_HYDRA_LEO_MISSING_COMMA)

emain/emain-window.ts (1)

234-240: Consider using structured logging for better debugging.

The current implementation uses multiple console.log statements. Consider using structured logging for better debugging in production.

-                    console.log("numWindows > 1 or user does not want last window saved", numWindows);
-                    if (fullConfig.settings["window:confirmclose"]) {
-                        console.log("confirmclose", this.waveWindowId);
-                        const workspace = await WorkspaceService.GetWorkspace(this.workspaceId);
-                        console.log("workspace", workspace);
-                        if (isNonEmptyUnsavedWorkspace(workspace)) {
-                            console.log("workspace has no name, icon, and multiple tabs", workspace);
+                    log({
+                        event: "window_close_check",
+                        numWindows,
+                        windowId: this.waveWindowId,
+                        confirmClose: fullConfig.settings["window:confirmclose"]
+                    });
+                    if (fullConfig.settings["window:confirmclose"]) {
+                        const workspace = await WorkspaceService.GetWorkspace(this.workspaceId);
+                        if (isNonEmptyUnsavedWorkspace(workspace)) {
+                            log({
+                                event: "unsaved_workspace_check",
+                                windowId: this.waveWindowId,
+                                workspaceId: workspace.oid,
+                                numTabs: workspace.tabids?.length
+                            });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8d30d1 and 9af09e6.

📒 Files selected for processing (6)
  • docs/docs/config.mdx (3 hunks)
  • emain/emain-window.ts (1 hunks)
  • frontend/types/gotypes.d.ts (1 hunks)
  • pkg/wconfig/defaultconfig/settings.json (2 hunks)
  • pkg/wconfig/metaconsts.go (1 hunks)
  • pkg/wconfig/settingsconfig.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/wconfig/defaultconfig/settings.json
  • pkg/wconfig/metaconsts.go
  • frontend/types/gotypes.d.ts
  • pkg/wconfig/settingsconfig.go
🧰 Additional context used
🪛 LanguageTool
docs/docs/config.mdx

[uncategorized] ~83-~83: Possible missing comma found.
Context: ... | For reference this is the current default configurati...

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (3)
docs/docs/config.mdx (2)

79-80: LGTM! Clear and well-documented configuration keys.

The new configuration keys are well-documented with clear descriptions of their functionality and default values.


106-107: LGTM! Default configuration values are appropriate.

The default values align with common UX patterns where users should be prompted before potentially destructive actions.

emain/emain-window.ts (1)

232-251: Verify edge case: Multiple windows with unsaved changes.

The window close logic is well-implemented with appropriate checks for configuration settings and unsaved changes. However, there's a potential edge case to consider.

Run the following script to check for similar window close confirmation implementations:

Consider enhancing the confirmation dialog message to show the number of unsaved tabs:

-                                    "Window has unsaved tabs, closing window will delete existing tabs.\n\nContinue?",
+                                    `Window has ${workspace.tabids.length + workspace.pinnedtabids.length} unsaved tabs, closing window will delete existing tabs.\n\nContinue?`,
✅ Verification successful

Window close confirmation is properly implemented with consistent behavior

The code correctly handles the edge case of multiple windows with unsaved changes:

  1. The window:confirmclose setting is properly defined and used across the codebase
  2. The isNonEmptyUnsavedWorkspace function has clear logic to identify unsaved workspaces (no name, no icon, and multiple tabs)
  3. The confirmation dialog is shown only when necessary - when there are unsaved changes and the setting is enabled
  4. The implementation prevents accidental data loss by giving users a chance to cancel

The suggestion to show the number of unsaved tabs is not necessary since the current message clearly conveys the risk of data loss, which is the key information users need to make a decision.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent window close confirmation handling across the codebase.

# Search for window close confirmation dialogs
rg -A 5 'showMessageBoxSync.*Close Window'

# Search for workspace state checks
ast-grep --pattern 'isNonEmptyUnsavedWorkspace($workspace)'

Length of output: 106


Script:

#!/bin/bash
# Let's try a broader search for dialog-related code and workspace checks

# Search for dialog-related code
rg -A 5 "dialog\.showMessageBox"

# Search for workspace-related checks in a different way
rg -A 5 "isNonEmptyUnsavedWorkspace"

# Search for window close handling
rg -A 5 "window.*close"

Length of output: 121328


Script:

#!/bin/bash
# Let's try a more focused search for window close and workspace handling

# Search for window close confirmation implementation
rg -A 5 "window:confirmclose"

# Search for workspace state checks with context
rg -A 10 "isNonEmptyUnsavedWorkspace" --no-filename

# Search for workspace-related functions
ast-grep --pattern 'GetWorkspace($workspaceId)'

Length of output: 4247

@esimkowitz esimkowitz merged commit 62dcf13 into main Dec 20, 2024
9 of 10 checks passed
@esimkowitz esimkowitz deleted the evan/close-last-window branch December 20, 2024 22:02
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