Skip to content

feat: app state only allow json object #1443

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

chilingling
Copy link
Member

@chilingling chilingling commented May 28, 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?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Enhanced form validation for state JSON input, providing clear error messages for empty, invalid, or incorrectly formatted content.
    • Updated tips section to display context-specific guidance based on usage type, including a JSON object example for app usage.
  • Style

    • Introduced new highlight color for state tips to improve visual emphasis.

Copy link
Contributor

coderabbitai bot commented May 28, 2025

Walkthrough

The updates introduce enhanced JSON validation for state input in the CreateStore form, ensuring the content is a non-empty, valid, non-array object. The StateTips component now displays different tips based on a new type prop, supporting both "page" and "app" contexts. A CSS variable for tip highlight color is added.

Changes

File(s) Change Summary
packages/plugins/state/src/CreateStore.vue Added comprehensive JSON validation for state input; updated StateTips usage with type="app".
packages/plugins/state/src/StateTips.vue Added type prop to render context-specific tips; introduced new styles for app tips.
packages/plugins/state/src/styles/vars.less Introduced --te-state-tip-highlight-color CSS variable.

Poem

In the warren of code, a new rule appears,
JSON must be valid—no arrays, please, dears!
Tips now adapt, for app or for page,
With colors that highlight, front and center stage.
A carrot for effort, a hop for delight,
This bunny approves: the state feels just right! 🥕


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@github-actions github-actions bot added the enhancement New feature or request label May 28, 2025
@chilingling chilingling marked this pull request as ready for review July 11, 2025 03:42
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: 1

🧹 Nitpick comments (2)
packages/plugins/state/src/StateTips.vue (1)

27-30: Consider defining constants outside the component for better maintainability.

The TIPS_TYPE constant definition is correct, but consider moving it to a shared constants file if it's used in multiple components, or use an enum-like structure for better type safety.

+// Consider moving to a shared constants file
+export const TIPS_TYPE = {
+  PAGE: 'page',
+  APP: 'app'
+} as const
+
+export type TipsType = typeof TIPS_TYPE[keyof typeof TIPS_TYPE]
packages/plugins/state/src/CreateStore.vue (1)

245-253: Consider refactoring redundant validation logic.

The editorDidMount function contains similar editor value processing logic as the new validateState function. Consider consolidating this logic to reduce code duplication.

+const getEditorValue = () => {
+  return variableEditor.value.getEditor().getValue()
+}
+
+const getCleanedEditorValue = () => {
+  return getEditorValue().replace(/\r\n|\s/g, '')
+}
+
const editorDidMount = () => {
-  const variable = variableEditor.value
-    .getEditor()
-    .getValue()
-    .replace(new RegExp('\\r\\n', 'g', ''), '')
-    .replace(/\s/g, '')
+  const variable = getCleanedEditorValue()

  return Object.prototype.toString.call(variable) === '[object Object]'
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 770a0bf and c5dd958.

📒 Files selected for processing (3)
  • packages/plugins/state/src/CreateStore.vue (2 hunks)
  • packages/plugins/state/src/StateTips.vue (2 hunks)
  • packages/plugins/state/src/styles/vars.less (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: gene9831
PR: opentiny/tiny-engine#1041
File: packages/plugins/datasource/src/DataSourceList.vue:138-138
Timestamp: 2025-01-14T10:06:25.508Z
Learning: PR #1041 in opentiny/tiny-engine is specifically for reverting Prettier v3 formatting to v2, without any logical code changes or syntax improvements.
Learnt from: rhlin
PR: opentiny/tiny-engine#1011
File: packages/canvas/render/src/RenderMain.ts:82-88
Timestamp: 2025-01-14T08:50:50.226Z
Learning: For PR #1011, the focus is on resolving conflicts and migrating code, with architectural improvements deferred for future PRs.
Learnt from: gene9831
PR: opentiny/tiny-engine#1038
File: packages/plugins/block/index.js:24-24
Timestamp: 2025-01-14T08:42:18.574Z
Learning: In the tiny-engine project, breaking changes are documented in the changelog rather than in JSDoc comments or separate migration guides.
packages/plugins/state/src/CreateStore.vue (4)
Learnt from: rhlin
PR: opentiny/tiny-engine#1011
File: packages/canvas/render/src/application-function/global-state.ts:12-25
Timestamp: 2025-01-14T08:45:57.032Z
Learning: The code in `packages/canvas/render/src/application-function/global-state.ts` is migrated from an existing codebase and should be handled with care when making modifications.
Learnt from: gene9831
PR: opentiny/tiny-engine#1011
File: packages/configurator/src/router-select-configurator/RouterSelectConfigurator.vue:95-98
Timestamp: 2025-01-14T06:55:59.692Z
Learning: The tiny-select component from @opentiny/vue library ensures selected options are valid internally, requiring no additional validation in the change handler.
Learnt from: yy-wow
PR: opentiny/tiny-engine#886
File: packages/plugins/state/src/js/http.js:19-19
Timestamp: 2024-10-30T02:19:37.775Z
Learning: In the `packages/plugins/state/src/js/http.js` file, errors for the `requestGlobalState` function are handled by the user, so additional error handling is unnecessary.
Learnt from: rhlin
PR: opentiny/tiny-engine#1011
File: packages/canvas/render/src/canvas-function/design-mode.ts:6-13
Timestamp: 2025-01-14T06:55:14.457Z
Learning: The code in `packages/canvas/render/src/canvas-function/design-mode.ts` is migrated code that should be preserved in its current form during the migration process. Refactoring suggestions for type safety and state management improvements should be considered in future PRs.
packages/plugins/state/src/StateTips.vue (4)
Learnt from: gene9831
PR: opentiny/tiny-engine#1233
File: packages/canvas/container/src/components/CanvasDivider.vue:184-185
Timestamp: 2025-03-20T07:20:12.221Z
Learning: In CanvasDivider.vue, even though state.verLeft and state.horizontalTop already include 'px' suffix, the CSS properties in state.dividerStyle still need to append 'px' again according to gene9831, suggesting that these state variables might be processed differently than expected when used in style binding.
Learnt from: gene9831
PR: opentiny/tiny-engine#830
File: packages/common/component/MetaChildItem.vue:50-56
Timestamp: 2024-10-15T02:45:17.168Z
Learning: In `packages/common/component/MetaChildItem.vue`, when checking if `text` is an object in the computed property `title`, ensure that `text` is not `null` because `typeof null === 'object'` in JavaScript. Use checks like `text && typeof text === 'object'` to safely handle `null` values.
Learnt from: rhlin
PR: opentiny/tiny-engine#1011
File: packages/canvas/render/src/canvas-function/design-mode.ts:6-13
Timestamp: 2025-01-14T06:55:14.457Z
Learning: The code in `packages/canvas/render/src/canvas-function/design-mode.ts` is migrated code that should be preserved in its current form during the migration process. Refactoring suggestions for type safety and state management improvements should be considered in future PRs.
Learnt from: yy-wow
PR: opentiny/tiny-engine#850
File: packages/toolbars/preview/src/Main.vue:0-0
Timestamp: 2024-10-10T02:48:10.881Z
Learning: 在 `packages/toolbars/preview/src/Main.vue` 文件中,使用 `useNotify` 而不是 `console` 来记录错误日志。
🔇 Additional comments (5)
packages/plugins/state/src/styles/vars.less (1)

32-32: LGTM! CSS variable addition follows design system conventions.

The new --te-state-tip-highlight-color variable is properly named and references the existing design system variable, ensuring consistency across the application.

packages/plugins/state/src/StateTips.vue (2)

12-24: LGTM! Well-structured conditional rendering with appropriate styling.

The app-tips variant provides clear guidance about JSON object requirements with a practical example. The styling properly uses the new CSS variable for highlighting.


32-37: Props definition follows Vue 3 best practices.

The props definition is correctly structured with proper typing and default value.

packages/plugins/state/src/CreateStore.vue (2)

40-40: LGTM! Proper integration with enhanced StateTips component.

The type="app" attribute correctly utilizes the new StateTips functionality to display JSON object-specific guidance.

Also applies to: 44-44


189-189: Form validation rule correctly updated.

The form rule properly integrates the new validateState function to enforce JSON object validation.

Comment on lines +160 to +185
const validateState = (rule: any, value: string, callback: (error?: Error) => void) => {
const stateValue = variableEditor.value
.getEditor()
.getValue()
.replace(new RegExp('\\r\\n', 'g'), '')
.replace(/\s/g, '')

if (!stateValue || !stateValue.trim()) {
callback(new Error('状态内容不能为空'))
return
}

try {
const parsed = JSON.parse(stateValue)

// 检查是否为对象且不是数组和null
if (typeof parsed !== 'object' || Array.isArray(parsed) || parsed === null) {
callback(new Error('状态必须是一个JSON对象'))
return
}

callback()
} catch (error) {
callback(new Error('状态格式不正确,请输入有效的JSON对象'))
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize validation function for better performance and maintainability.

The validation logic is correct, but there are several areas for improvement:

  1. Redundant editor value retrieval: The editor value is retrieved and processed multiple times
  2. Inefficient string processing: Multiple regex replacements could be combined
  3. Code duplication: Similar logic exists in editorDidMount function
const validateState = (rule: any, value: string, callback: (error?: Error) => void) => {
-  const stateValue = variableEditor.value
-    .getEditor()
-    .getValue()
-    .replace(new RegExp('\\r\\n', 'g'), '')
-    .replace(/\s/g, '')
+  const rawValue = variableEditor.value.getEditor().getValue()
+  const stateValue = rawValue.replace(/\r\n|\s/g, '')

  if (!stateValue || !stateValue.trim()) {
    callback(new Error('状态内容不能为空'))
    return
  }

  try {
-    const parsed = JSON.parse(stateValue)
+    const parsed = JSON.parse(rawValue) // Use raw value for parsing, not cleaned value

    // 检查是否为对象且不是数组和null
    if (typeof parsed !== 'object' || Array.isArray(parsed) || parsed === null) {
      callback(new Error('状态必须是一个JSON对象'))
      return
    }

    callback()
  } catch (error) {
    callback(new Error('状态格式不正确,请输入有效的JSON对象'))
  }
}
📝 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 validateState = (rule: any, value: string, callback: (error?: Error) => void) => {
const stateValue = variableEditor.value
.getEditor()
.getValue()
.replace(new RegExp('\\r\\n', 'g'), '')
.replace(/\s/g, '')
if (!stateValue || !stateValue.trim()) {
callback(new Error('状态内容不能为空'))
return
}
try {
const parsed = JSON.parse(stateValue)
// 检查是否为对象且不是数组和null
if (typeof parsed !== 'object' || Array.isArray(parsed) || parsed === null) {
callback(new Error('状态必须是一个JSON对象'))
return
}
callback()
} catch (error) {
callback(new Error('状态格式不正确,请输入有效的JSON对象'))
}
}
const validateState = (rule: any, value: string, callback: (error?: Error) => void) => {
const rawValue = variableEditor.value.getEditor().getValue()
const stateValue = rawValue.replace(/\r\n|\s/g, '')
if (!stateValue || !stateValue.trim()) {
callback(new Error('状态内容不能为空'))
return
}
try {
const parsed = JSON.parse(rawValue) // Use raw value for parsing, not cleaned value
// 检查是否为对象且不是数组和null
if (typeof parsed !== 'object' || Array.isArray(parsed) || parsed === null) {
callback(new Error('状态必须是一个JSON对象'))
return
}
callback()
} catch (error) {
callback(new Error('状态格式不正确,请输入有效的JSON对象'))
}
}
🤖 Prompt for AI Agents
In packages/plugins/state/src/CreateStore.vue between lines 160 and 185,
optimize the validateState function by retrieving the editor value once and
storing it in a variable before processing. Combine the regex replacements into
a single operation to improve efficiency. Refactor the validation logic to avoid
duplication by extracting common code shared with the editorDidMount function
into a reusable helper function.

@hexqi hexqi added this to the v2.8.0 milestone Jul 22, 2025
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.

2 participants