Skip to content

feat(pager): reconstruct the multi-terminal template of the pager component from the vue template #3422

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

Merged
merged 6 commits into from
May 17, 2025

Conversation

zzcr
Copy link
Member

@zzcr zzcr commented May 14, 2025

feat(pager): 将pager组件多端模板重构从vue模板,并改成成setup函数格式

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)

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

Summary by CodeRabbit

  • Refactor

    • Updated the pagination component to use Vue 3 Composition API and template syntax for improved modularity and readability, while preserving existing pagination features and event support.
  • Accessibility

    • Removed the aria-hidden attribute from the popover tooltip, which may affect how assistive technologies interpret its visibility.
  • Style

    • Minor formatting change: removed a trailing newline from a configuration file.
  • Chores

    • Removed several pagination demo components and their related entries from the demo configuration, streamlining the example set.

Copy link

coderabbitai bot commented May 14, 2025

Walkthrough

This update refactors the mobile-first.vue pager component from the Options API with JSX to the Composition API with a Vue template and TypeScript, reorganizing its logic, state management, and event handling. It removes the dynamic aria-hidden attribute from the popover tooltip container, deletes several demo pager components and their references, and removes a trailing newline from a package manifest file.

Changes

File(s) Change Summary
packages/vue/package.json Removed a trailing newline at the end of the file.
packages/vue/src/pager/src/mobile-first.vue Refactored from Options API with JSX to Composition API with a template and TypeScript; reorganized logic, state, and emits.
packages/vue/src/popover/src/mobile-first.vue Removed the dynamic aria-hidden attribute from the tooltip container element.
examples/sites/demos/mobile-first/app/pager/current-change.vue Deleted entire component demonstrating current-change event handling with TinyPager and modal.
examples/sites/demos/mobile-first/app/pager/next-click.vue Deleted entire component demonstrating next-click event handling with TinyPager and modal.
examples/sites/demos/mobile-first/app/pager/prev-click.vue Deleted entire component demonstrating prev-click event handling with TinyPager and modal.
examples/sites/demos/mobile-first/app/pager/webdoc/pager.js Removed demo entries for current-change, prev-click, next-click, and before-page-change from demos array.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MobileFirstPager
    participant ParentComponent

    User->>MobileFirstPager: Interact with pager controls (prev/next, size, jumper)
    MobileFirstPager->>MobileFirstPager: Update reactive state, validate input
    MobileFirstPager->>ParentComponent: Emit events (before-change, page-change, size-change, etc.)
    ParentComponent-->>MobileFirstPager: Update props (currentPage, pageSize, total)
    MobileFirstPager->>MobileFirstPager: Sync internal state with props via watchers
Loading

Poem

A hop, a skip, a code refactor spree,
The pager now glides with Composition API!
Popover whispers less to ARIA’s ear,
While package.json’s end is crystal clear.
Demo hops away, no more to show,
Our code is cleaner, watch it grow!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/vue/src/pager/src/mobile-first.vue

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 85cf7de and fd8d965.

📒 Files selected for processing (1)
  • packages/vue/src/pager/src/mobile-first.vue (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/vue/src/pager/src/mobile-first.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)

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 14, 2025
@zzcr zzcr marked this pull request as draft May 14, 2025 02:38
Copy link

  • Walkthrough: This PR refactors the pager component's multi-terminal template from a Vue template to a setup function format, enhancing the component's structure and reactivity.
  • Changes:
    Files Summary
    packages/vue/package.json Updated dependencies.
    packages/vue/src/pager/src/mobile-first.vue Refactored the pager component to use the setup function, added new templates and handlers for pagination features.
    packages/vue/src/popover/src/mobile-first.vue Minor changes to popover component's tooltip handling.

<input
ref="jumperInput"
type="tel"
:disabled="disabled"

Choose a reason for hiding this comment

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

Ensure that the input value is validated correctly to prevent any potential security vulnerabilities such as injection attacks. Consider using a more robust validation method.

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

🧹 Nitpick comments (3)
packages/vue/package.json (1)

240-240: Preserve POSIX-style trailing newline

Removing the final newline is harmless for Node, but most *nix tools (git-diff, POSIX text utilities, editors) expect every text file to end with \n. Keeping it avoids spurious diffs like this one.

packages/vue/src/pager/src/mobile-first.vue (2)

680-687: internalPageCount coerces to ≥ 1 – edge-case for empty datasets

When total === 0, internalPageCount becomes 1, so the pager shows a single page even though there are no records. This can confuse users and defeats hideOnSinglePage (it never hides).

Consider returning 0 when there is no page at all and update the UI guards accordingly.


272-799: Component is >750 LOC – extract composables for maintainability

Business logic (jumper, size selector, navigation) is intertwined with rendering, making the file hard to reason about and test. Splitting the reactive state & handlers into useJumper(), usePageSize(), etc., would:

• improve cohesion
• enable unit-testing of logic without mounting the component
• allow reuse in desktop/other variants of the pager.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44bad19 and 9ebf7fc.

📒 Files selected for processing (3)
  • packages/vue/package.json (1 hunks)
  • packages/vue/src/pager/src/mobile-first.vue (8 hunks)
  • packages/vue/src/popover/src/mobile-first.vue (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/vue/src/popover/src/mobile-first.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)
🔇 Additional comments (1)
packages/vue/src/pager/src/mobile-first.vue (1)

712-739: Watch-loop risk: emitting update:currentPage immediately after syncing the prop

watch(props.currentPage) sets internalCurrentPage, and the next watcher immediately emits update:currentPage, re-notifying the parent with the same value.
Although Vue’s diffing prevents an infinite loop, it still produces an unnecessary extra event per change.

Consider either
• removing the second watcher’s immediate: true, or
• gating the emit with a value difference check.

Comment on lines 377 to 408
emit('update:pageSize', val)
emit('size-change', val)
emit('page-change', {
currentPage: state.internalCurrentPage,
pageSize: val,
total: state.internalTotal
})
if (sizesList.value) {
sizesList.value.hide()
}
}
},
render() {
return h('div', { class: ['h-7 leading-7 inline-block align-middle text-xs'] }, [
h('div', { class: ['text-[0] h-7'] }, [
h(
'span',
{
class: ['text-xs pl-4 pr-2 text-color-text-primary']
},
[t('ui.page.jump')]
),
h('input', {
class: [
'w-8 h-7 text-center align-top rounded-sm inline-block border border-solid border-color-border hover:text-color-icon-primary hover:border-color-icon-primary',
'text-color-text-primary text-xs transition-[border] duration-300 outline-0 box-border mr-0 focus:border-color-border-focus'
],
domProps: {
value: this.value
},
attrs: {
type: 'tel',
disabled: this.disabled
},
on: {
focus: this.handleFocus,
input: this.handleInput,
change: this.handleChange
},
ref: 'input'
})
])
])
}
},
Total: {
mounted() {
if (document.querySelector('[data-tag="tiny-pager-total-loading"]')) {
Loading.service({
target: document.querySelector('[data-tag="tiny-pager-total-loading"]')
})

if (props.isBeforePageChange) {
const newPageSize = val
const currentPageSize = state.internalPageSize
const params = { newPageSize, currentPageSize, callback }
beforeSizeChangeHandler(params)
} else {
callback()
}
},
render() {
return typeof this.$parent.internalTotal === 'number' ? (
this.$parent.showTotalLoading ? (
<div class="inline-block align-middle text-xs h-7 leading-7 float-left">
<div class="h-7 leading-7 text-xs text-color-text-primary">
<div
data-tag="tiny-pager-total-loading"
class="inline-block align-baseline h-3.5 w-3.5 mr-1.5 top-0.5 [&_[data-tag=tiny-loading-icon]]:h-3.5 [&_[data-tag=tiny-loading-icon]]:w-3.5"></div>
<span class="text-color-text-secondary">{t('ui.page.loadingTotals')}</span>
</div>
</div>
) : (
<div class="inline-block align-middle text-xs h-7 leading-7 float-left">
{' '}
<div class="h-7 leading-7 text-xs text-color-text-primary">
<span>{t('ui.page.total')}</span>
<span class="my-0 mx-1">
{this.$parent.customTotal ? this.$parent.totalText : this.$parent.internalTotal}
</span>
<span>{t('ui.page.item')}</span>
</div>
</div>
)
) : (
''
)
}
},
Pager
},
methods: {
canJumperGo() {
const inputValue = Number(this.$refs.jumper.$refs.input.value || 0)
const currentPage = Number(this.internalCurrentPage || 0)
return this.accurateJumper ? inputValue !== currentPage : true
},
beforeSizeChangeHandler(params) {
const { newPageSize, currentPageSize, callback } = params
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

beforeChangeHandler() receives a dummy value, breaking consumers that rely on the new page number

Inside handleSizeChange the pre-change guard is invoked with its default -1, not the actual upcoming page (state.internalCurrentPage), so any listener comparing newPage with the current page will mis-behave.

-          if (!beforeChangeHandler()) {
+          if (!beforeChangeHandler(state.internalCurrentPage)) {

Pass the real page so downstream hooks get accurate context.

📝 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 handleSizeChange = (val: number) => {
if (val !== state.internalPageSize) {
const callback = () => {
if (!beforeChangeHandler()) {
return false
}
if (value >= max) {
this.value = max
} else if (value <= min) {
this.value = min
} else {
this.value = value
state.internalPageSize = val
state.userChangePageSize = true
state.showSizes = false
emit('update:pageSize', val)
emit('size-change', val)
emit('page-change', {
currentPage: state.internalCurrentPage,
pageSize: val,
total: state.internalTotal
})
if (sizesList.value) {
sizesList.value.hide()
}
}
},
render() {
return h('div', { class: ['h-7 leading-7 inline-block align-middle text-xs'] }, [
h('div', { class: ['text-[0] h-7'] }, [
h(
'span',
{
class: ['text-xs pl-4 pr-2 text-color-text-primary']
},
[t('ui.page.jump')]
),
h('input', {
class: [
'w-8 h-7 text-center align-top rounded-sm inline-block border border-solid border-color-border hover:text-color-icon-primary hover:border-color-icon-primary',
'text-color-text-primary text-xs transition-[border] duration-300 outline-0 box-border mr-0 focus:border-color-border-focus'
],
domProps: {
value: this.value
},
attrs: {
type: 'tel',
disabled: this.disabled
},
on: {
focus: this.handleFocus,
input: this.handleInput,
change: this.handleChange
},
ref: 'input'
})
])
])
}
},
Total: {
mounted() {
if (document.querySelector('[data-tag="tiny-pager-total-loading"]')) {
Loading.service({
target: document.querySelector('[data-tag="tiny-pager-total-loading"]')
})
if (props.isBeforePageChange) {
const newPageSize = val
const currentPageSize = state.internalPageSize
const params = { newPageSize, currentPageSize, callback }
beforeSizeChangeHandler(params)
} else {
callback()
}
},
render() {
return typeof this.$parent.internalTotal === 'number' ? (
this.$parent.showTotalLoading ? (
<div class="inline-block align-middle text-xs h-7 leading-7 float-left">
<div class="h-7 leading-7 text-xs text-color-text-primary">
<div
data-tag="tiny-pager-total-loading"
class="inline-block align-baseline h-3.5 w-3.5 mr-1.5 top-0.5 [&_[data-tag=tiny-loading-icon]]:h-3.5 [&_[data-tag=tiny-loading-icon]]:w-3.5"></div>
<span class="text-color-text-secondary">{t('ui.page.loadingTotals')}</span>
</div>
</div>
) : (
<div class="inline-block align-middle text-xs h-7 leading-7 float-left">
{' '}
<div class="h-7 leading-7 text-xs text-color-text-primary">
<span>{t('ui.page.total')}</span>
<span class="my-0 mx-1">
{this.$parent.customTotal ? this.$parent.totalText : this.$parent.internalTotal}
</span>
<span>{t('ui.page.item')}</span>
</div>
</div>
)
) : (
''
)
}
},
Pager
},
methods: {
canJumperGo() {
const inputValue = Number(this.$refs.jumper.$refs.input.value || 0)
const currentPage = Number(this.internalCurrentPage || 0)
return this.accurateJumper ? inputValue !== currentPage : true
},
beforeSizeChangeHandler(params) {
const { newPageSize, currentPageSize, callback } = params
}
const handleSizeChange = (val: number) => {
if (val !== state.internalPageSize) {
const callback = () => {
if (!beforeChangeHandler(state.internalCurrentPage)) {
return false
}
state.internalPageSize = val
state.userChangePageSize = true
state.showSizes = false
emit('update:pageSize', val)
emit('size-change', val)
emit('page-change', {
currentPage: state.internalCurrentPage,
pageSize: val,
total: state.internalTotal
})
if (sizesList.value) {
sizesList.value.hide()
}
}
if (props.isBeforePageChange) {
const newPageSize = val
const currentPageSize = state.internalPageSize
const params = { newPageSize, currentPageSize, callback }
beforeSizeChangeHandler(params)
} else {
callback()
}
}
}

Comment on lines +756 to +766
// 生命周期钩子
onMounted(() => {
if (document.querySelector('[data-tag="tiny-pager-total-loading"]')) {
const target = document.querySelector('[data-tag="tiny-pager-total-loading"]')
if (target) {
Loading.service({
target: target as HTMLElement
})
}
}
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Loading.service instance is never disposed – potential memory leak & redundant DOM query

onMounted reaches into the DOM twice with document.querySelector, creates a Loading.service, and never tears it down.
• Re-querying the DOM is brittle – the target can be obtained via a ref.
• Without calling close() on the service in onUnmounted, the overlay and its timers stay in memory when the component is destroyed.

-    onMounted(() => {
-      if (document.querySelector('[data-tag="tiny-pager-total-loading"]')) {
-        const target = document.querySelector('[data-tag="tiny-pager-total-loading"]')
-        if (target) {
-          Loading.service({
-            target: target as HTMLElement
-          })
-        }
-      }
-    })
+    const loadingInstance = ref<any>(null)
+
+    onMounted(() => {
+      const target = document.querySelector('[data-tag="tiny-pager-total-loading"]') as HTMLElement | null
+      if (target) {
+        loadingInstance.value = Loading.service({ target })
+      }
+    })
+
+    onUnmounted(() => {
+      loadingInstance.value?.close?.()
+    })

Also extend the hooks destructuring to include onUnmounted.

📝 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
// 生命周期钩子
onMounted(() => {
if (document.querySelector('[data-tag="tiny-pager-total-loading"]')) {
const target = document.querySelector('[data-tag="tiny-pager-total-loading"]')
if (target) {
Loading.service({
target: target as HTMLElement
})
}
}
})
// 生命周期钩子
const loadingInstance = ref<any>(null)
onMounted(() => {
const target = document.querySelector('[data-tag="tiny-pager-total-loading"]') as HTMLElement | null
if (target) {
loadingInstance.value = Loading.service({ target })
}
})
onUnmounted(() => {
loadingInstance.value?.close?.()
})

@zzcr zzcr marked this pull request as ready for review May 14, 2025 08:51
@zzcr zzcr changed the title feat(pager): Reconstruct the multi-terminal template of the pager component from the vue template feat(pager): reconstruct the multi-terminal template of the pager component from the vue template May 14, 2025
@zzcr zzcr merged commit b018aab into dev May 17, 2025
5 checks passed
@zzcr zzcr deleted the change-pager-to-setup-0513 branch May 17, 2025 02:55
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