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

docs(grid): [grid] add updateFooter demo #2753

Closed
wants to merge 4 commits into from
Closed

Conversation

gimmyhehe
Copy link
Member

@gimmyhehe gimmyhehe commented Jan 7, 2025

PR

新增表格updateFooter文档

updateFooter这个API一直存在,但是缺少文档说明与demo。

image

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)

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:

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

close #2078

Summary by CodeRabbit

  • New Features

    • Added mobile-first support for grid components.
    • Introduced new grid footer functionality with manual data update capability.
    • Enhanced grid footer methods to dynamically calculate and update footer data.
    • New Vue component for displaying a data table with a footer.
    • Added a demo entry for manual footer data updates.
  • Bug Fixes

    • Simplified footer calculation logic across multiple grid components.
    • Improved column index referencing in footer methods.
  • Tests

    • Added a new test case to verify grid footer merging functionality.

Copy link

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces enhancements to the grid components across multiple files, focusing on mobile-first support and footer calculation improvements. The changes primarily involve updating mode properties to support both 'pc' and 'mobile-first' configurations, modifying footer method calculations, and adding new demo components for grid footer functionality. These modifications aim to improve the grid component's flexibility and responsiveness across different device types.

Changes

File Change Summary
examples/sites/demos/apis/grid.js Updated mode properties for grid, grid-column, and grid-toolbar components to support both 'pc' and 'mobile-first' modes
examples/sites/demos/pc/app/grid/footer/* Modified footer method calculations in multiple Vue components, simplifying logic for employee count and rowspan/colspan
examples/sites/demos/pc/app/grid/webdoc/grid-footer.js Added new demo entry for manual footer data updates
examples/sites/demos/pc/app/grid/footer/update-footer.vue Introduced new Vue component for grid footer with dynamic updates based on user input
examples/sites/demos/pc/app/grid/footer/update-footer-composition-api.vue Added a new Vue component utilizing TinyGrid for displaying a data table with a footer
examples/sites/demos/pc/app/grid/footer/update-footer.spec.ts Added a new test case for verifying merging rows or columns in a grid footer

Assessment against linked issues

Objective Addressed Explanation
Provide method to recalculate footer row [#2078]

Possibly related PRs

Suggested labels

documentation

Suggested reviewers

  • zzcr

Poem

🐰 Griddy Rabbit's Mobile Dance
Rows and columns leap with grace,
Mobile-first, a responsive embrace!
Footer calculates with playful might,
Flexibility shining ever so bright!
Grid components dance, both PC and small,
Responsive magic conquering all! 🌟


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

Walkthrough

此PR为updateFooter API添加了缺失的文档和示例。主要更新包括在多个文件中添加了关于updateFooter的使用示例和测试用例,确保该API的功能在文档中得到充分展示。

Changes

文件 概要
examples/sites/demos/apis/grid.js 更新了多个API的mode属性以支持mobile-first
examples/sites/demos/pc/app/grid/footer/footer-row-or-column-span-composition-api.vue
examples/sites/demos/pc/app/grid/footer/footer-row-or-column-span.vue
修改了表尾合并行或列的逻辑。
examples/sites/demos/pc/app/grid/footer/update-footer-composition-api.vue
examples/sites/demos/pc/app/grid/footer/update-footer.vue
新增了updateFooter的示例文件。
examples/sites/demos/pc/app/grid/footer/update-footer.spec.ts 添加了针对updateFooter功能的测试用例。
examples/sites/demos/pc/app/grid/webdoc/grid-footer.js 更新了文档以包含updateFooter的描述和示例。

if (column.property === 'employees') {
return data.map((item) => item[column.property]).reduce((acc, item) => acc + item)
if (columnIndex === 2) {
return data.map((item) => item.employees).reduce((acc, item) => acc + item)

Choose a reason for hiding this comment

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

使用columnIndex代替column.property来判断列是否为employees,确保逻辑的一致性和简洁性。

@gimmyhehe gimmyhehe added the documentation 对文档的改进或补充 label Jan 7, 2025
@github-actions github-actions bot removed the documentation 对文档的改进或补充 label Jan 7, 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: 3

🧹 Nitpick comments (3)
examples/sites/demos/pc/app/grid/footer/update-footer.spec.ts (1)

3-11: Add more test scenarios and assertions.

While the test covers basic functionality, consider adding:

  1. Test for empty data state
  2. Test for multiple cell updates
  3. Verification of other cells remaining unchanged
  4. Error scenarios (e.g., invalid input)
 test('表尾合并行或列', async ({ page }) => {
   page.on('pageerror', (exception) => expect(exception).toBeNull())
   const demo = page.locator('#update-footer')
   await page.goto('grid-footer#update-footer')
+  // Test initial state
   await expect(demo.getByRole('cell', { name: '5310' })).toBeVisible()
+
+  // Test empty data state
+  await demo.getByRole('button', { name: 'Clear Data' }).click()
+  await expect(demo.getByRole('cell', { name: '0' })).toBeVisible()
+
+  // Test single update
   await demo.getByRole('cell', { name: '1300' }).click()
   await demo.locator('.tiny-numeric__increase').click()
   await expect(demo.getByRole('cell', { name: '5311' })).toBeVisible()
+
+  // Test multiple updates
+  await demo.getByRole('cell', { name: '800' }).click()
+  await demo.locator('.tiny-numeric__increase').click()
+  await expect(demo.getByRole('cell', { name: '5312' })).toBeVisible()
+
+  // Verify other cells unchanged
+  await expect(demo.getByRole('cell', { name: 'GFD 科技 YX 公司' })).toBeVisible()
 })
examples/sites/demos/pc/app/grid/footer/update-footer-composition-api.vue (2)

85-103: Optimize footerMethod implementation.

The current implementation has several areas for improvement:

  1. Memoize calculations to avoid unnecessary recalculations
  2. Use more efficient array reduction
  3. Add input validation
+import { computed } from 'vue'
+
+const totalEmployees = computed(() => {
+  return tableData.value.reduce((sum, item) => sum + (item.employees || 0), 0)
+})
+
 function footerMethod({ columns, data }) {
+  if (!Array.isArray(data) || !Array.isArray(columns)) {
+    console.warn('Invalid input to footerMethod')
+    return [['和值', '', '', 0]]
+  }
+
   if (data.length === 0) {
     return [['和值', '', '', 0]]
   }

   return [
     columns.map((column, columnIndex) => {
       if (columnIndex === 0) {
         return '和值'
       }

       if (column.property === 'employees') {
-        return data.map((item) => item[column.property]).reduce((acc, item) => acc + item)
+        return totalEmployees.value
       }

       return null
     })
   ]
 }

3-14: Add loading state handling.

The grid should indicate when footer updates are in progress, especially for large datasets.

 <tiny-grid 
   ref="gridRef" 
   :data="tableData" 
   show-footer 
   :footer-method="footerMethod" 
   border 
-  :edit-config="{}"
+  :edit-config="{ loading: updating }"
   >

Add the following to the script section:

const updating = ref(false)

async function handleChange() {
  updating.value = true
  try {
    await gridRef.value.updateFooter()
  } finally {
    updating.value = false
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e29e24 and 777ece7.

📒 Files selected for processing (7)
  • examples/sites/demos/apis/grid.js (133 hunks)
  • examples/sites/demos/pc/app/grid/footer/footer-row-or-column-span-composition-api.vue (2 hunks)
  • examples/sites/demos/pc/app/grid/footer/footer-row-or-column-span.vue (2 hunks)
  • examples/sites/demos/pc/app/grid/footer/update-footer-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/grid/footer/update-footer.spec.ts (1 hunks)
  • examples/sites/demos/pc/app/grid/footer/update-footer.vue (1 hunks)
  • examples/sites/demos/pc/app/grid/webdoc/grid-footer.js (1 hunks)
👮 Files not reviewed due to content moderation or server errors (3)
  • examples/sites/demos/pc/app/grid/footer/footer-row-or-column-span.vue
  • examples/sites/demos/pc/app/grid/footer/update-footer.vue
  • examples/sites/demos/apis/grid.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)

Comment on lines +35 to +42
'demoId': 'update-footer',
'name': { 'zh-CN': '手动更新表尾数据', 'en-US': '' },
'desc': {
'zh-CN':
'<p>默认情况下,只有当编辑失焦后才会更新表尾数据,通过 <code>updateFooter</code> 可以手动更新表尾数据。</p>\n',
'en-US': '<p></p>'
},
'codeFiles': ['footer/update-footer.vue']
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 English translations for the new demo.

The demo configuration is missing English translations for both name and description. This affects accessibility for non-Chinese users.

 {
   'demoId': 'update-footer',
-  'name': { 'zh-CN': '手动更新表尾数据', 'en-US': '' },
+  'name': { 'zh-CN': '手动更新表尾数据', 'en-US': 'Manually Update Footer Data' },
   'desc': {
     'zh-CN':
       '<p>默认情况下,只有当编辑失焦后才会更新表尾数据,通过 <code>updateFooter</code> 可以手动更新表尾数据。</p>\n',
-    'en-US': '<p></p>'
+    'en-US': '<p>By default, footer data is only updated when editing loses focus. You can manually update footer data using the <code>updateFooter</code> method.</p>\n'
   },
   'codeFiles': ['footer/update-footer.vue']
 }
📝 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
'demoId': 'update-footer',
'name': { 'zh-CN': '手动更新表尾数据', 'en-US': '' },
'desc': {
'zh-CN':
'<p>默认情况下,只有当编辑失焦后才会更新表尾数据,通过 <code>updateFooter</code> 可以手动更新表尾数据。</p>\n',
'en-US': '<p></p>'
},
'codeFiles': ['footer/update-footer.vue']
'demoId': 'update-footer',
'name': { 'zh-CN': '手动更新表尾数据', 'en-US': 'Manually Update Footer Data' },
'desc': {
'zh-CN':
'<p>默认情况下,只有当编辑失焦后才会更新表尾数据,通过 <code>updateFooter</code> 可以手动更新表尾数据。</p>\n',
'en-US': '<p>By default, footer data is only updated when editing loses focus. You can manually update footer data using the <code>updateFooter</code> method.</p>\n'
},
'codeFiles': ['footer/update-footer.vue']

Comment on lines +88 to +89
if (columnIndex === 2) {
return data.map((item) => item.employees).reduce((acc, item) => acc + item)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid hardcoding column indices.

Using hardcoded column indices (columnIndex === 2) makes the code brittle. If columns are reordered or new columns are added, this logic will break.

-      if (columnIndex === 2) {
-        return data.map((item) => item.employees).reduce((acc, item) => acc + item)
+      if (column.property === 'employees') {
+        return data.map((item) => item[column.property]).reduce((acc, item) => acc + item)
       }

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

Comment on lines +82 to +84
function handleChange() {
gridRef.value.updateFooter()
}
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 error handling to handleChange function.

The current implementation doesn't handle potential errors if the grid reference is undefined or if updateFooter fails.

 function handleChange() {
+  try {
+    if (!gridRef.value) {
+      console.error('Grid reference is not available')
+      return
+    }
     gridRef.value.updateFooter()
+  } catch (error) {
+    console.error('Failed to update footer:', error)
+  }
 }
📝 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 handleChange() {
gridRef.value.updateFooter()
}
function handleChange() {
try {
if (!gridRef.value) {
console.error('Grid reference is not available')
return
}
gridRef.value.updateFooter()
} catch (error) {
console.error('Failed to update footer:', error)
}
}

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 (1)
packages/vue/src/grid/src/grid/grid.ts (1)

524-525: LGTM! Consider adding a fallback mechanism.

The addition of the IntersectionObserver availability check is a good defensive programming practice that prevents runtime errors in unsupported environments.

Consider implementing a fallback mechanism for browsers that don't support IntersectionObserver. For example:

     addIntersectionObserver() {
       if ((this.intersectionOption && this.intersectionOption.disabled) || typeof IntersectionObserver === 'undefined')
-        return
+        return this.handleVisibilityChange(true, { isIntersecting: true })

       this.intersectionObserver = new IntersectionObserver((entries) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 777ece7 and e80739a.

📒 Files selected for processing (1)
  • packages/vue/src/grid/src/grid/grid.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)

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 (1)
packages/vue/src/grid/src/adapter/src/renderer.ts (1)

113-128: Consider enhancing the empty option handling.

The selection tracking and default empty option logic is good, but could be improved further.

Consider these enhancements:

  1. Make the empty option's text configurable through props
  2. Move the display:none style to CSS classes
-    optionsList.unshift(h('option', { style: 'display:none', selected: true }, ''))
+    const emptyOptionText = renderOpts.emptyOptionText || ''
+    optionsList.unshift(h('option', { 
+      class: 'tiny-grid-select-empty-option',
+      selected: true 
+    }, emptyOptionText))

Add to your CSS:

.tiny-grid-select-empty-option {
  display: none;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e80739a and b227b52.

📒 Files selected for processing (1)
  • packages/vue/src/grid/src/adapter/src/renderer.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)
🔇 Additional comments (2)
packages/vue/src/grid/src/adapter/src/renderer.ts (2)

103-108: LGTM! Good improvement in variable declarations.

Converting to const improves code safety by preventing accidental reassignment of these configuration values.


103-128: Verify alignment with PR objectives.

The changes improve select option rendering, but the PR objective mentions adding documentation and demo for the updateFooter API. Could you clarify how these changes relate to the updateFooter functionality?

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: 1

🧹 Nitpick comments (1)
packages/vue/src/grid/__tests__/grid.test.tsx (1)

93-93: Remove redundant nextTick call.

The second nextTick call is redundant as the first one already ensures the component has been updated.

-    await nextTick()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b227b52 and 5d19854.

📒 Files selected for processing (1)
  • packages/vue/src/grid/__tests__/grid.test.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)

Comment on lines +79 to +89
<GridColumn type="index" title="序号" width="100"></GridColumn>
<GridColumn field="name" title="名称" width="100">
{{
default: (data) => (
<span class="pink-cell" style="color:pink">
{data.row.name}
</span>
)
}}></GridColumn>
<GridColumn field="city" titile="城市" width="100"></GridColumn>
}}
</GridColumn>
<GridColumn field="city" title="城市" width="100"></GridColumn>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for slot functionality.

While the test verifies basic slot rendering, it should also verify:

  1. The correct rendering of the custom cell content
  2. The proper data binding in the slot scope
  3. The column width prop application

Consider expanding the test assertions:

     await nextTick()
     expect(wrapper.find('.pink-cell').exists()).toBeTruthy()
+    // Verify cell content
+    expect(wrapper.find('.pink-cell').text()).toBe('GFD科技YX公司')
+    // Verify column width
+    const nameColumn = wrapper.findAll('.tiny-grid-header__column')[1]
+    expect(nameColumn.attributes('style')).toContain('width: 100px')

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

@gimmyhehe gimmyhehe closed this Jan 7, 2025
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.

✨ [Feature]: 合计行重算方法
1 participant