diff --git a/common/changes/@visactor/vchart/fix-dom-tooltip-autowidth-of-title_2025-04-09-04-04.json b/common/changes/@visactor/vchart/fix-dom-tooltip-autowidth-of-title_2025-04-09-04-04.json new file mode 100644 index 0000000000..19d7262f74 --- /dev/null +++ b/common/changes/@visactor/vchart/fix-dom-tooltip-autowidth-of-title_2025-04-09-04-04.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "comment": "fix: the width of title label should auto fit content width when `autoWidth` is true, fix #3880\n\n", + "type": "none", + "packageName": "@visactor/vchart" + } + ], + "packageName": "@visactor/vchart", + "email": "dingling112@gmail.com" +} \ No newline at end of file diff --git a/packages/vchart/src/plugin/components/tooltip-handler/dom-tooltip-handler.ts b/packages/vchart/src/plugin/components/tooltip-handler/dom-tooltip-handler.ts index e59b1bcaac..b87b741d23 100644 --- a/packages/vchart/src/plugin/components/tooltip-handler/dom-tooltip-handler.ts +++ b/packages/vchart/src/plugin/components/tooltip-handler/dom-tooltip-handler.ts @@ -304,17 +304,32 @@ export class DomTooltipHandler extends BaseTooltipHandler { } protected _updateDomStyle(sizeKey: 'width' | 'height' = 'width') { const rootDom = this._rootDom; - const contentDom = [...(rootDom.children as any)].find(child => child.className.includes(TOOLTIP_CONTENT_BOX_CLASS_NAME) ); + const titleDom = [...(rootDom.children as any)].find(child => child.className.includes(TOOLTIP_TITLE_CLASS_NAME)); if (contentDom) { const tooltipSpec = this._component.getSpec() as ITooltipSpec; const contentStyle: Partial = {}; + const titleLabel = tooltipSpec.style?.titleLabel; + const autoFixTitleWidth = titleLabel && titleLabel.autoWidth && titleLabel.multiLine !== false; + + if (autoFixTitleWidth && titleDom) { + const maxWidth = [...(contentDom.children as any)].reduce((res, col) => { + return sizeKey === 'height' + ? res + col.getBoundingClientRect().width + : Math.max(res, col.getBoundingClientRect().width); + }, 0); + + if (maxWidth > 0) { + titleDom.style.maxWidth = `${maxWidth}px`; + // 需要再计算一次,因为之前可能因为没有设置maxWidth, content的dom被撑宽了 + titleDom.style.maxWidth = `${Math.ceil(contentDom.getBoundingClientRect().width)}px`; + } + } if (isValid(tooltipSpec?.style?.maxContentHeight)) { - const titleDom = rootDom.children[0]; const titleHeight = titleDom && titleDom.className.includes(TOOLTIP_TITLE_CLASS_NAME) ? titleDom.getBoundingClientRect().height + (tooltipSpec.style.spaceRow ?? 0)