Skip to content

fix: undo or reply to save button tag display logic optimization#1185

Merged
hexqi merged 5 commits intoopentiny:release/v2.3.0from
SonyLeo:fix/save-badge
Mar 7, 2025
Merged

fix: undo or reply to save button tag display logic optimization#1185
hexqi merged 5 commits intoopentiny:release/v2.3.0from
SonyLeo:fix/save-badge

Conversation

@SonyLeo
Copy link
Copy Markdown
Contributor

@SonyLeo SonyLeo commented Mar 5, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

  1. 点击恢复( redo)时,未保存代码时,右上角保存代码 红点 消失
  2. 点击撤销(undo)时,取消新增的修改,右上角保存代码 红点 不消失

Issue Number: N/A

What is the new behavior?

  1. 点击恢复( redo)时,未保存代码时,右上角保存代码 红点 不消失
  2. 点击撤销(undo)时,取消新增的修改、右上角保存代码 红点 消失

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Improved notifications during page and block initialization for enhanced synchronization across the design interface.
    • Enhanced subscription handling in the save workflow for more reliable and accurate state tracking.
  • Refactor

    • Streamlined history navigation by eliminating redundant operations, resulting in a smoother user experience during editing.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 5, 2025

Walkthrough

This pull request refactors state management and messaging in several modules. The history functions no longer update the saved state unnecessarily. Additionally, new publish calls have been introduced in the canvas and block modules to emit a pageOrBlockInit event. The save toolbar component now subscribes to multiple messaging topics—including the initialization event and schema changes—to manage schema updates and cleanup subscriptions.

Changes

Files Change Summary
packages/toolbars/.../useHistory.js Removed calls to useCanvas().setSaved(false) in back, forward, and addHistory, streamlining save state handling during history navigation.
packages/canvas/.../useCanvas.js, packages/plugins/block/.../useBlock.js Added functionality to publish a pageOrBlockInit message (with schema in the canvas and block content in the block module) to notify subscribers of initialization events.
packages/toolbars/save/.../Main.vue Introduced useMessage for messaging; updated the setup to subscribe to pageOrBlockInit, schemaChange, and schemaImport topics, and added schema state management and cleanup logic.

Sequence Diagram(s)

sequenceDiagram
    participant Canvas
    participant Block
    participant MessageBus
    participant SaveToolbar

    Canvas->>MessageBus: publish 'pageOrBlockInit' with schema
    Block->>MessageBus: publish 'pageOrBlockInit' with block content
    MessageBus->>SaveToolbar: deliver 'pageOrBlockInit' event
    SaveToolbar->>SaveToolbar: Update saved state & perform schema comparison
Loading

Possibly related PRs

Suggested labels

refactor-main

Suggested reviewers

  • hexqi
  • chilingling
  • rhlin

Poem

Oh, I’m a rabbit in the code garden, hopping free,
Skipping through branches of history with glee.
Messages dance like carrots in the air,
Saving and updating with the greatest of care.
With each little change, my heart beats bright—
Coding adventures make every day light!
🐰💻


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

@SonyLeo SonyLeo changed the title Fix/save badge fix: undo or reply to save button tag display logic optimization Mar 5, 2025
@github-actions github-actions Bot added the bug Something isn't working label Mar 5, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/toolbars/redoundo/src/composable/useHistory.js (2)

95-101: Implementation looks good but needs error handling for localStorage.

The new toggleSaveBadgeStatus function effectively determines whether to show the save badge by comparing the current schema with the original. This addresses both issues mentioned in the PR:

  1. The save badge remains visible after "redo" if changes haven't been saved
  2. The save badge disappears after "undo" if all changes are canceled

However, consider adding error handling for localStorage parsing:

const toggleSaveBadgeStatus = () => {
  const { setSaved, getSchemaDiff } = useCanvas()
-  const initSchema = JSON.parse(localStorage.getItem(constants.PAGE_ORIGIN_SCHEMA))
+  let initSchema
+  try {
+    initSchema = JSON.parse(localStorage.getItem(constants.PAGE_ORIGIN_SCHEMA))
+  } catch (error) {
+    initSchema = null
+  }
  const diffContent = initSchema && getSchemaDiff(initSchema)

  setSaved(!diffContent)
}

95-132: Consider adding documentation for the new functionality.

The implementation itself is solid, but adding some comments explaining the purpose of the toggleSaveBadgeStatus function and how it addresses the save badge issues would help future developers understand this code better.

+/**
+ * Toggles the save badge status based on whether there are differences 
+ * between the current schema and the original schema from localStorage.
+ * - Shows the badge when there are unsaved changes
+ * - Hides the badge when there are no differences (i.e., all changes are saved or undone)
+ */
const toggleSaveBadgeStatus = () => {
  const { setSaved, getSchemaDiff } = useCanvas()
  const initSchema = JSON.parse(localStorage.getItem(constants.PAGE_ORIGIN_SCHEMA))
  const diffContent = initSchema && getSchemaDiff(initSchema)

  setSaved(!diffContent)
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 71c5c2b and 34af5a3.

📒 Files selected for processing (5)
  • packages/canvas/render/src/material-function/page-getter.ts (2 hunks)
  • packages/toolbars/redoundo/package.json (1 hunks)
  • packages/toolbars/redoundo/src/composable/useHistory.js (3 hunks)
  • packages/toolbars/save/src/js/index.js (1 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (8)
packages/utils/src/constants/index.js (1)

104-104: Well-structured constant addition for schema persistence.

This new constant will be used to store the original page schema in local storage, providing a reference point to determine if the page has unsaved changes. This is essential for fixing the save badge visibility issues described in the PR objectives.

packages/toolbars/redoundo/package.json (1)

29-30: Appropriate dependency addition.

Adding the @opentiny/tiny-engine-utils dependency allows access to the constants needed for the save badge functionality fix. This change aligns perfectly with the PR objectives.

packages/toolbars/save/src/js/index.js (1)

74-74: Key implementation for save badge persistence.

This line saves the page schema to local storage when not in block mode, which is crucial for tracking unsaved changes. When comparing this stored schema with the current one, the application can accurately determine whether to show the save badge after redo/undo operations.

This directly addresses the PR objective of ensuring the save badge remains visible after redo operations when there are unsaved changes.

packages/canvas/render/src/material-function/page-getter.ts (2)

2-2: Appropriate utility import for constants access.

This import provides access to the constants needed for consistent schema storage across different parts of the application.


36-36: Crucial implementation for schema persistence on page load.

This line stores the original page schema in local storage whenever a page is fetched, establishing a baseline for comparison. This is essential for correctly determining when the save badge should appear or disappear during undo/redo operations.

This directly addresses the PR objective of ensuring the save badge disappears when undoing to the original state and remains visible when redoing changes.

packages/toolbars/redoundo/src/composable/useHistory.js (3)

14-14: Great addition of the constants import.

This import allows for consistent usage of the PAGE_ORIGIN_SCHEMA constant across the codebase, reducing the risk of string literal mismatches.


104-104: Good placement of the toggle function call.

Adding toggleSaveBadgeStatus() at the beginning of the addHistory function ensures that the save badge status is updated whenever history is modified.


118-118: Excellent implementation for monitoring history changes.

Adding the toggleSaveBadgeStatus() call in the watch function ensures the save badge is properly updated when navigating through history (undo/redo operations). This directly addresses the issues mentioned in the PR objectives.

Comment thread packages/toolbars/redoundo/src/composable/useHistory.js Outdated
Comment thread packages/toolbars/save/src/js/index.js Outdated
Comment thread packages/toolbars/save/src/Main.vue Outdated
Comment thread packages/toolbars/save/src/Main.vue Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/toolbars/save/src/Main.vue (2)

109-114: Well-structured state management setup.

Good approach to extract additional methods from useCanvas() and set up the message subscription system. Using ref(null) for originSchema is appropriate for tracking the initial schema state.

Note: Consider using const originSchema = ref(null) instead of let since you're not reassigning the ref itself, only its value.


116-150: Improve variable naming in schema comparison logic.

The variable name hasChange is misleading - when the comparison returns true, it means there are NO changes (schemas are identical). This might cause confusion for other developers.

-          const hasChange = JSON.stringify(getSchema()) === originSchema.value
-          setSaved(hasChange)
+          const isUnchanged = JSON.stringify(getSchema()) === originSchema.value
+          setSaved(isUnchanged)

Additionally, consider extracting the duplicate comparison logic from the schemaChange and schemaImport callbacks into a single function to improve maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f77856a and 5fecc8b.

📒 Files selected for processing (1)
  • packages/toolbars/save/src/Main.vue (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (3)
packages/toolbars/save/src/Main.vue (3)

61-61: Good import addition.

Adding useMessage is appropriate for implementing the subscription-based approach to track save state changes.


132-135: The fix aligns with PR objectives.

This logic correctly addresses the "undo/redo" save badge issues mentioned in the PR objectives by properly tracking schema changes and updating the saved state.


152-156: Good cleanup of subscriptions.

Properly unsubscribing from all topics prevents memory leaks and ensures that the event handlers won't be called after the component is unmounted.

@hexqi hexqi merged commit 5ff9824 into opentiny:release/v2.3.0 Mar 7, 2025
SonyLeo added a commit to SonyLeo/tiny-engine that referenced this pull request Mar 7, 2025
SonyLeo added a commit to SonyLeo/tiny-engine that referenced this pull request Mar 7, 2025
1degrees pushed a commit to 1degrees/tiny-engine that referenced this pull request Mar 13, 2025
@SonyLeo SonyLeo deleted the fix/save-badge branch March 23, 2025 12:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants