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

chore: add ma-key-value component #538

Merged
merged 1 commit into from
Jan 16, 2025
Merged

Conversation

westng
Copy link
Contributor

@westng westng commented Jan 16, 2025

image
image
image

Summary by CodeRabbit

  • 新功能

    • 添加了一个用于管理键值对的新组件
    • 引入了JSON编辑和格式化功能
    • 支持解析和验证JSON数据
  • 改进

    • 增加了对JSON内容的错误处理机制
    • 提供了国际化支持(英语、简体中文、繁体中文)
  • 用户体验

    • 新增对话框,可以添加和编辑键值对
    • 支持动态添加和删除键值对条目

Copy link

coderabbitai bot commented Jan 16, 2025

📝 Walkthrough

概述

演练

这些变更引入了一个新的 Vue 组件系统,用于管理和编辑 JSON 数据。新组件包括一个 JSON 编辑器、键值对管理界面和一个 JSON 格式化实用工具。该系统允许用户解析和格式化 JSON 数据,提供交互式表单和错误处理机制,支持多语言国际化。

变更

文件 变更摘要
web/src/components/ma-key-value/components/form.vue 新增 JSON 编辑器组件,包含内容格式化、验证和错误处理功能
web/src/components/ma-key-value/index.vue 添加键值对管理组件,支持添加、删除和解析数据
web/src/components/ma-key-value/utils/formatJson.ts 创建 JSON 格式化实用函数,处理 JSON 转换和错误场景

诗歌

🐰 JSON 的魔法,代码的舞蹈
格式化,转换,错误不慌
键值对跳跃,编辑如歌
兔子微笑,代码飞扬
技术之美,尽在掌中 🌈

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (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 or PR title anywhere in the PR title to generate the title automatically.

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.

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jan 16, 2025
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: 4

🧹 Nitpick comments (3)
web/src/components/ma-key-value/utils/formatJson.ts (1)

10-19: 建议改进错误处理机制

当前的错误处理比较简单,建议做以下改进:

  1. 区分不同类型的错误(如语法错误、类型错误等)
  2. 提供更详细的错误信息,便于调试

建议按照以下方式修改:

 export default function formatJson(json: Record<string, any>): string {
   try {
     return JSON.stringify(json, null, 2)
   }
   catch (error) {
-    // 如果解析失败,返回原始字符串并附带错误信息
-    console.error('Invalid JSON string:', error)
-    return `/* Invalid JSON: ${json} */`
+    // 区分错误类型并提供详细信息
+    const errorMessage = error instanceof Error ? error.message : '未知错误'
+    console.error('JSON格式化失败:', { error, input: json })
+    return `/* 无效的JSON格式: ${errorMessage}\n原始输入: ${JSON.stringify(json)} */`
   }
 }
web/src/components/ma-key-value/components/form.vue (1)

78-78: 建议为编辑器添加基础配置

当前编辑器配置较为简单,建议添加一些基础配置以提升用户体验。

建议修改为:

-  <VAceEditor v-model:value="content" lang="json" :theme="theme" class="mt-2 h-500px text-base" />
+  <VAceEditor
+    v-model:value="content"
+    lang="json"
+    :theme="theme"
+    class="mt-2 h-500px text-base"
+    :options="{
+      showPrintMargin: false,
+      showGutter: true,
+      tabSize: 2,
+      useSoftTabs: true,
+      showInvisibles: false,
+    }"
+    @init="editorInit"
+  />
web/src/components/ma-key-value/index.vue (1)

41-43: 建议在addKeyValue方法中添加验证

当前直接添加空的键值对可能导致数据不一致。

建议修改为:

 function addKeyValue() {
+  if (!model.value) {
+    model.value = [];
+  }
+  if (model.value.length >= 50) {
+    ElMessage.warning('最多只能添加50个键值对');
+    return;
+  }
   model.value = [...model.value, { label: '', value: '' }];
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bbd4724 and ce0fbda.

📒 Files selected for processing (3)
  • web/src/components/ma-key-value/components/form.vue (1 hunks)
  • web/src/components/ma-key-value/index.vue (1 hunks)
  • web/src/components/ma-key-value/utils/formatJson.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Test on PHP8.1 Swoole-master
  • GitHub Check: Test on PHP8.1 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.1 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.2 Swoole-master
  • GitHub Check: Test on PHP8.2 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.2 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.1 Swow-develop
  • GitHub Check: Test on PHP8.3 Swoole-master
  • GitHub Check: Test on PHP8.2 Swow-develop
  • GitHub Check: Test on PHP8.3 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.3 Swow-develop
  • GitHub Check: build Code coverage report (ubuntu-latest, 8.1, v5.1.3)
  • GitHub Check: build
  • GitHub Check: Codacy Static Code Analysis

Comment on lines +26 to +33
watch(content, (newValue) => {
try {
const parsedJson = JSON.parse(newValue);
content.value = formatJson(parsedJson); // Format the JSON
} catch (error) {
// Handle invalid JSON format if necessary
}
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

watch函数中的错误处理需要完善

当前的错误处理是空的,这可能会导致用户无法得知输入的JSON格式是否有误。

建议修改为:

 watch(content, (newValue) => {
   try {
     const parsedJson = JSON.parse(newValue);
     content.value = formatJson(parsedJson);
   } catch (error) {
-    // Handle invalid JSON format if necessary
+    console.warn('JSON格式无效:', error);
+    // 可以通过UI提示用户输入的JSON格式有误
+    ElMessage.warning('请输入有效的JSON格式');
   }
 });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +38 to +68
function add(): Promise<any> {
return new Promise((resolve, reject) => {
try {
// 将 JSON 字符串转换为数组
const parsedArray = JSON.parse(content.value)

// 如果转换成功,并且是数组,则返回成功的响应
if (Array.isArray(parsedArray)) {
resolve({
code: 200,
success: true,
message: 'success',
data: parsedArray,
})
convertArray.value = parsedArray
} else {
reject({
code: 404,
success: false,
message: 'Parsed content is not an array',
})
}
} catch (error) {
reject({
code: 404,
success: false,
message: 'Invalid JSON format',
})
}
})
}
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方法的实现

当前实现存在以下问题:

  1. 缺少输入验证
  2. 错误码使用不一致(404用于格式错误不合适)
  3. 未处理loading状态

建议按照以下方式修改:

-function add(): Promise<any> {
+function add(): Promise<{ code: number; success: boolean; message: string; data?: any[] }> {
   return new Promise((resolve, reject) => {
     try {
+      if (!content.value?.trim()) {
+        reject({
+          code: 400,
+          success: false,
+          message: '请输入JSON内容',
+        });
+        return;
+      }
+
       const parsedArray = JSON.parse(content.value)
 
       if (Array.isArray(parsedArray)) {
+        // 验证数组元素的格式
+        if (!parsedArray.every(item => item && typeof item === 'object')) {
+          reject({
+            code: 400,
+            success: false,
+            message: '数组元素必须是对象类型',
+          });
+          return;
+        }
         resolve({
           code: 200,
           success: true,
           message: 'success',
           data: parsedArray,
         })
         convertArray.value = parsedArray
       } else {
         reject({
-          code: 404,
+          code: 400,
           success: false,
           message: 'Parsed content is not an array',
         })
       }
     } catch (error) {
       reject({
-        code: 404,
+        code: 400,
         success: false,
-        message: 'Invalid JSON format',
+        message: '无效的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
function add(): Promise<any> {
return new Promise((resolve, reject) => {
try {
// 将 JSON 字符串转换为数组
const parsedArray = JSON.parse(content.value)
// 如果转换成功,并且是数组,则返回成功的响应
if (Array.isArray(parsedArray)) {
resolve({
code: 200,
success: true,
message: 'success',
data: parsedArray,
})
convertArray.value = parsedArray
} else {
reject({
code: 404,
success: false,
message: 'Parsed content is not an array',
})
}
} catch (error) {
reject({
code: 404,
success: false,
message: 'Invalid JSON format',
})
}
})
}
function add(): Promise<{ code: number; success: boolean; message: string; data?: any[] }> {
return new Promise((resolve, reject) => {
try {
if (!content.value?.trim()) {
reject({
code: 400,
success: false,
message: '请输入JSON内容',
});
return;
}
const parsedArray = JSON.parse(content.value)
if (Array.isArray(parsedArray)) {
// 验证数组元素的格式
if (!parsedArray.every(item => item && typeof item === 'object')) {
reject({
code: 400,
success: false,
message: '数组元素必须是对象类型',
});
return;
}
resolve({
code: 200,
success: true,
message: 'success',
data: parsedArray,
})
convertArray.value = parsedArray
} else {
reject({
code: 400,
success: false,
message: 'Parsed content is not an array',
})
}
} catch (error) {
reject({
code: 400,
success: false,
message: '无效的JSON格式',
})
}
})
}


defineOptions({ name: 'MaKeyValue' })

const model = defineModel<any>()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议添加更具体的类型定义

当前使用 any 类型不够严谨,建议定义具体的接口类型。

建议添加以下类型定义:

+interface KeyValuePair {
+  label: string;
+  value: string;
+}
-const model = defineModel<any>()
+const model = defineModel<KeyValuePair[]>()

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +69 to +77
<div class="flex flex-row justify-between" v-for="(item, index) in model" :key="index">
<div class="key-value-input flex flex-row gap-4">
<el-input v-model="item.label" :placeholder="`label ${index + 1}`" />
<el-input v-model="item.value" :placeholder="`Value ${index + 1}`" />
</div>
<el-button circle type="danger" @click="removeKeyValue(index)">
<ma-svg-icon name="i-heroicons:trash" />
</el-button>
</div>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议优化键值对输入验证

当前实现没有对输入值进行验证,建议添加必要的验证逻辑。

建议修改为:

 <div class="flex flex-row justify-between" v-for="(item, index) in model" :key="index">
   <div class="key-value-input flex flex-row gap-4">
-    <el-input v-model="item.label" :placeholder="`label ${index + 1}`" />
-    <el-input v-model="item.value" :placeholder="`Value ${index + 1}`" />
+    <el-input
+      v-model="item.label"
+      :placeholder="`label ${index + 1}`"
+      :maxlength="50"
+      show-word-limit
+      @blur="validateKeyValue(index)"
+    />
+    <el-input
+      v-model="item.value"
+      :placeholder="`Value ${index + 1}`"
+      :maxlength="200"
+      show-word-limit
+      @blur="validateKeyValue(index)"
+    />
   </div>
   <el-button circle type="danger" @click="removeKeyValue(index)">
     <ma-svg-icon name="i-heroicons:trash" />
   </el-button>
 </div>

Committable suggestion skipped: line range outside the PR's diff.

@dosubot dosubot bot added the enhancement label Jan 16, 2025
@kanyxmo kanyxmo merged commit 85f06a2 into mineadmin:master Jan 16, 2025
16 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants