Skip to content

fix(Axistip): add supports the formatter and fix the tips display abnormally #248

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

Closed
wants to merge 1 commit into from

Conversation

ader-h
Copy link
Contributor

@ader-h ader-h commented Apr 18, 2025

Summary by CodeRabbit

  • New Features

    • Axis tooltips now support custom label formatting, displaying axis values using configured formatter functions when available.
  • Bug Fixes

    • Tooltip content more accurately reflects axis label formatting, improving clarity and consistency when hovering over axis elements.

Copy link

coderabbitai bot commented Apr 18, 2025

Walkthrough

A new mechanism for handling axis label formatting has been added to the axis tip feature. Formatter functions for axis labels are now collected and stored by axis type. When displaying tooltips on mouse movement, the code checks for a custom formatter for the relevant axis and uses it to format the tooltip content if available. If no formatter is set, it defaults to displaying the raw value. The rest of the tooltip behavior, including positioning and event triggering, remains unchanged.

Changes

File(s) Change Summary
src/feature/axistip/index.js Introduced a textFormatter object to manage axis label formatters; updated tooltip content logic to use formatters if present; added guard to skip disabled axis tips; maintained existing tooltip positioning and event logic.

Poem

In fields of code where axes meet,
A rabbit hops with nimble feet.
Now tooltips sparkle, smart and bright,
With custom text to show what's right.
Formatters tucked in every row—
The data sings, the values glow!
🐇✨

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.

src/feature/axistip/index.js

Oops! Something went wrong! :(

ESLint: 8.56.0

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///eslint.config.js?mtime=1744078840000:1:15
at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
at async onImport.tracePromise.proto (node:internal/modules/esm/loader:483:26)
at async loadFlatConfigFile (/node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/flat-eslint.js:299:21)
at async calculateConfigArray (/node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/flat-eslint.js:378:28)
at async FlatESLint.lintFiles (/node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/flat-eslint.js:741:25)
at async Object.execute (/node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli.js:421:23)
at async main (/node_modules/.pnpm/[email protected]/node_modules/eslint/bin/eslint.js:152:22)

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

@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

🔭 Outside diff range comments (1)
src/feature/axistip/index.js (1)

93-104: 💡 Verification agent

🧩 Analysis chain

Verify event listener cleanup on chart recreation

The current implementation adds event listeners each time axistip is called, but doesn't remove previous ones. This could lead to memory leaks and duplicate tooltips if the same chart instance is reused.


🏁 Script executed:

#!/bin/bash
# Check if there are any calls to remove event listeners

echo "Checking for event listener cleanup..."
rg -A 3 -B 3 "echartsIns\.off|removeEventListener" src/

echo "Checking if axistip function is called multiple times for the same chart instance..."
rg -A 3 -B 3 "axistip\(" src/ | grep -v "function axistip"

Length of output: 5760


Add cleanup for prior ‘mousemove’ listener before rebinding

Before registering the new handler you should remove any existing listener to prevent duplicates or leaks:

• File: src/feature/axistip/index.js
Insert a call to echartsIns.off('mousemove') (or pass the same callback reference) immediately before echartsIns.on('mousemove', …).

Suggested diff:

   tipContainer.style.opacity = '0';
-  echartsIns.on('mousemove', (param) => {
+  // remove any previously bound mousemove handler
+  echartsIns.off('mousemove');
+  // define handler so it can be unbound later if needed
+  const handleMouseMove = (param) => {
     let type = param.componentType;
     if (param.name) {
       tipContainer.textContent = param.name;
@@
     if (axisType.indexOf(param.componentType) !== -1) {
       setPosition(tipContainer, echartsDom, param);
     }
-  });
+  };
+  echartsIns.on('mousemove', handleMouseMove);

This ensures each chart recreation only has one active tooltip listener.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8472fa9 and 4f03573.

📒 Files selected for processing (1)
  • src/feature/axistip/index.js (3 hunks)
🔇 Additional comments (1)
src/feature/axistip/index.js (1)

86-86: LGTM - Guard clause to skip processing falsy axis types

This is a good addition that ensures we only process axis types that are explicitly enabled.

@@ -15,12 +15,17 @@ import { isArray, isBoolean } from '../../util/type';
const distanceX = 16; // 鼠标与气泡框之间的左右偏移量
const distanceY = 24; // 鼠标与气泡框之间的上偏移量
const axisType = ['xAxis', 'yAxis'];
let textFormatter = {};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider scoping textFormatter to avoid state persistence between calls

The textFormatter variable is declared at module scope using let, which means its state will persist between multiple calls to the axistip function. This could lead to unexpected behavior if formatters from previous chart instances are applied to new charts.

-let textFormatter = {};

Move the declaration inside the axistip function to reset it on each call:

function axistip(echartsDom, echartsIns, eChartOption, axistip) {
  if (!axistip) return;
+  let textFormatter = {};
  
  if (isBoolean(axistip)) {
    axistip = {};
    axisType.forEach(item => {
      axistip[item] = true;
    })
  }
📝 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
let textFormatter = {};
// --- Remove this module‑scope line:
//- let textFormatter = {};
// Move into the function to reset on each call:
function axistip(echartsDom, echartsIns, eChartOption, axistip) {
if (!axistip) return;
let textFormatter = {};
if (isBoolean(axistip)) {
axistip = {};
axisType.forEach(item => {
axistip[item] = true;
});
}
// …rest of axistip implementation that uses textFormatter…
}

Comment on lines +95 to +100
let type = param.componentType;
if(param.name){
tipContainer.textContent = param.name;
}else{
tipContainer.textContent = textFormatter[type] ? textFormatter[type](param.value) : param.value;
}
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 for formatter functions

The current implementation directly calls the formatter function without any error handling. If the formatter throws an error, it could break the entire chart's functionality.

-tipContainer.textContent = textFormatter[type] ? textFormatter[type](param.value) : param.value;
+try {
+  tipContainer.textContent = textFormatter[type] ? textFormatter[type](param.value) : param.value;
+} catch (error) {
+  console.error('Error applying axis formatter:', error);
+  tipContainer.textContent = param.value;
+}

Also, maintain consistent use of spaces in conditional expressions:

-if(param.name){
+if (param.name) {
📝 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
let type = param.componentType;
if(param.name){
tipContainer.textContent = param.name;
}else{
tipContainer.textContent = textFormatter[type] ? textFormatter[type](param.value) : param.value;
}
let type = param.componentType;
if (param.name) {
tipContainer.textContent = param.name;
} else {
try {
tipContainer.textContent = textFormatter[type]
? textFormatter[type](param.value)
: param.value;
} catch (error) {
console.error('Error applying axis formatter:', error);
tipContainer.textContent = param.value;
}
}

Comment on lines +25 to +28
textFormatter[type] = undefined;
if(subitem.axisLabel?.formatter){
textFormatter[type] = subitem.axisLabel.formatter
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add formatter handling for non-array axis configuration

The formatter is only extracted when eChartOption[type] is an array, but not when it's a single object. This is inconsistent with how triggerEvent is handled.

} else {
+  textFormatter[type] = undefined;
+  if(eChartOption[type].axisLabel?.formatter){
+    textFormatter[type] = eChartOption[type].axisLabel.formatter
+  }
  eChartOption[type].triggerEvent = true;
}
📝 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
textFormatter[type] = undefined;
if(subitem.axisLabel?.formatter){
textFormatter[type] = subitem.axisLabel.formatter
}
} else {
textFormatter[type] = undefined;
if (eChartOption[type].axisLabel?.formatter) {
textFormatter[type] = eChartOption[type].axisLabel.formatter
}
eChartOption[type].triggerEvent = true;
}

@lingdan33 lingdan33 changed the title fix(axistip): tips display abnormally; add supports the formatter fix(axistip): add supports the formatter and fix the tips display abnormally Apr 18, 2025
@lingdan33 lingdan33 changed the title fix(axistip): add supports the formatter and fix the tips display abnormally fix(Axistip): add supports the formatter and fix the tips display abnormally Apr 18, 2025
@ader-h ader-h closed this Apr 22, 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.

1 participant