Skip to content

feat: 优化全局状态管理机制 #1305

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Ljhhhhhh
Copy link
Contributor

@Ljhhhhhh Ljhhhhhh commented Apr 12, 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?

调整了全局路由的管理方式,统一到一个module中,管理和使用更加简单

Issue Number: N/A

What is the new behavior?

  1. 重构全局状态管理,将多个独立 store 合并为单一 globalState
  2. 在 schema 中添加 globalState 引用,指向 stores 以支持全局状态访问
  3. 修改变量配置器中的状态引用路径从 this.stores 改为 this.globalState
  4. 更新页面生成器,在上下文中添加 globalState 支持
  5. 优化 genGlobalState 插件,生成统一的全局状态管理文件
  6. 在 lowcode.js 中集成 globalState 并暴露给组件使用

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a unified global state management feature that improves state consistency and ensures seamless data flow across app components, enhancing overall user experience.
  • Refactor

    • Simplified application state handling by consolidating previously separate state streams into a single, robust global store, contributing to improved performance, easier maintenance, and smoother configuration.

1. 重构全局状态管理,将多个独立 store 合并为单一 globalState
2. 在 schema 中添加 globalState 引用,指向 stores 以支持全局状态访问
3. 修改变量配置器中的状态引用路径从 this.stores 改为 this.globalState
4. 更新页面生成器,在上下文中添加 globalState 支持
5. 优化 genGlobalState 插件,生成统一的全局状态管理文件
6. 在 lowcode.js 中集成 globalState 并暴露给组件使用
此更新使低代码平台具备更统一、更直观的全局状态管理能力,简化了状态访问路径。
Copy link
Contributor

coderabbitai bot commented Apr 12, 2025

Walkthrough

This pull request integrates a consolidated global state management approach across multiple modules. A new globalState parameter is added to the useSchema function context, and various components have been updated to reference the global state instead of a local store. Changes include constant updates, modifications to context arrays, and the introduction of a unified global state store using Pinia, along with its proper export and initialization in low-code configurations.

Changes

File(s) Change Summary
packages/canvas/.../schema.ts
packages/vue-generator/src/generator/page.js
Added a globalState parameter to the context (and injection) to support global state management.
packages/configurator/src/variable-configurator/VariableConfigurator.vue Updated the STORE constant from 'this.stores.' to 'this.globalState.' to shift the reference from a local to a global state.
packages/vue-generator/src/plugins/genGlobalState.js Consolidated individual state stores into a single global state store using Pinia; added exports for globalState and useGlobalState.
packages/vue-generator/src/templates/vue-template/.../lowcodeConfig/lowcode.js Imported useGlobalState and initialized a new globalState in the low-code configuration, integrating it with other context properties.

Sequence Diagram(s)

sequenceDiagram
    participant C as Vue Component
    participant S as useSchema
    participant G as GlobalState Store
    participant V as Vue Generator (page.js)
    participant L as Lowcode Config

    C->>S: Invoke useSchema(context with globalState)
    Note right of S: globalState is now part of the context
    V->>G: Retrieve global state via useGlobalState()
    L->>G: Import global state for configuration
Loading

Poem

Hoppity code in fields so wide,
Global state now walks beside.
From schema to config, every line's bright,
A single store makes our app feel light.
With each new hop in this refined ride,
The rabbit sings in pure delight!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@github-actions github-actions bot added the enhancement New feature or request label Apr 12, 2025
Copy link
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 (3)
packages/vue-generator/src/plugins/genGlobalState.js (3)

44-60: Consider more robust 'this' reference replacement

The current approach of replacing all occurrences of this. with this.${id}. may cause issues if 'this' appears in string literals or comments rather than actual code references.

Consider using a more targeted approach for replacing 'this' references, possibly with regex that specifically targets property access patterns:

- if (gettersValue[key].value.includes('this')) {
-   gettersValue[key].value = gettersValue[key].value.replace(/this\./g, `this.${id}.`)
+ if (gettersValue[key].value.includes('this.')) {
+   gettersValue[key].value = gettersValue[key].value.replace(/\bthis\./g, `this.${id}.`)

66-72: Improve code generation formatting for better readability

The current string concatenation approach for getters and actions might produce hard-to-read code in the generated files, especially for complex implementations.

Consider adding proper indentation:

- export const globalState = defineStore('globalState', {
-    state: () => (${JSON.stringify(state, null, 2)}),
-    getters: {${Object.entries(getters)
-      .map(([key, value]) => `${key}: ${value}`)
-      .join(',')}},
-    actions: {${Object.entries(actions)
-      .map(([key, value]) => `${key}: ${value}`)
-      .join(',')}}
-  })
+ export const globalState = defineStore('globalState', {
+    state: () => (${JSON.stringify(state, null, 2)}),
+    getters: {
+      ${Object.entries(getters)
+        .map(([key, value]) => `${key}: ${value}`)
+        .join(',\n      ')}
+    },
+    actions: {
+      ${Object.entries(actions)
+        .map(([key, value]) => `${key}: ${value}`)
+        .join(',\n      ')}
+    }
+  })

75-80: useGlobalState function may be redundant

The useGlobalState function doesn't seem to add significant value beyond what globalState() already provides directly.

Consider if this wrapper function is necessary, or if it will have additional functionality in the future. If it's meant to provide a consistent API, that's a valid reason to keep it.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8a3f47b and 3196315.

📒 Files selected for processing (5)
  • packages/canvas/render/src/page-block-function/schema.ts (1 hunks)
  • packages/configurator/src/variable-configurator/VariableConfigurator.vue (1 hunks)
  • packages/vue-generator/src/generator/page.js (2 hunks)
  • packages/vue-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/lowcode.js (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/canvas/render/src/page-block-function/schema.ts (1)
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/lowcode.js (1)
  • stores (84-84)
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/lowcode.js (2)
packages/vue-generator/src/plugins/genGlobalState.js (1)
  • globalState (9-9)
packages/canvas/render/src/application-function/global-state.ts (1)
  • useGlobalState (6-31)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (11)
packages/configurator/src/variable-configurator/VariableConfigurator.vue (1)

145-145: LGTM: Updated reference to globalState

The constant STORE has been updated from 'this.stores.' to 'this.globalState.', which aligns with the PR objective of consolidating multiple stores into a single global state management approach.

packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/lowcode.js (3)

20-20: LGTM: Added import for useGlobalState

Successfully imported useGlobalState from the globalState module, enabling access to the consolidated global state management functionality.


85-85: LGTM: Initialize globalState

Added initialization of the globalState by calling useGlobalState(), which properly sets up the consolidated global state management.


87-87: LGTM: Export globalState in returned object

The globalState is now correctly included in the returned object alongside existing elements, making it accessible for component usage as intended.

packages/canvas/render/src/page-block-function/schema.ts (1)

75-77: LGTM: Added globalState to context

Good addition of the globalState parameter to the context object, with a clear comment explaining its purpose for global state management. This properly implements the PR objective of providing global state access within the schema.

packages/vue-generator/src/generator/page.js (2)

410-410: LGTM: Updated contextArr to include globalState

Added 'globalState' to the contextArr array, ensuring that the global state will be properly included in the wrapped context for component usage.


423-423: LGTM: Added globalState to destructuring assignment

Updated the destructuring assignment to include globalState from the vue.inject(I18nInjectionKey).lowcode() method, making it available in the component's scope.

packages/vue-generator/src/plugins/genGlobalState.js (4)

34-38: Good setup for consolidated state management

The new approach of using Pinia's defineStore with consolidated state, getters, and actions objects is a cleaner architecture than maintaining separate stores.


42-43: Good defensive programming with default empty arrays

Providing default empty arrays for getters and actions prevents potential undefined errors during processing.


84-95: Good file organization and exports

The approach to generate separate files for the store implementation and exports is clean and maintainable.


63-82:

✅ Verification successful

Potential issues with JSON.stringify for state serialization

Using JSON.stringify for the state object might cause problems with non-serializable values (functions, complex objects with circular references, etc.).

Consider if any of your state values might contain functions or complex objects:


🏁 Script executed:

#!/bin/bash
# Check for potential non-serializable values in state definitions
rg -A 10 -B 10 "globalState" | grep -A 20 "state:" | grep -E "function|=>|\(\)|new [A-Z]"

Length of output: 3505


Final Verification: Safe Use of JSON.stringify for Global State Serialization

After running the grep check for non-serializable constructs near the state definition in packages/vue-generator/src/plugins/genGlobalState.js, no occurrences of functions, arrow functions, or new [A-Z] patterns appeared. This indicates that the current usage of JSON.stringify(state, null, 2) is handling serializable data as expected.

• The generated state appears to consist only of serializable values.
• For future changes, ensure that any new state properties remain serializable, or consider alternative approaches if non-serializable values are needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant