Skip to content

refactor(tooltip): use composition api #4059

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 3 commits into from
Jun 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions components/slider/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ describe('Slider', () => {
await asyncExpect(() => {
expect(document.body.innerHTML).toMatchSnapshot();
wrapper.findAll('.ant-slider-handle')[0].trigger('mouseleave');
}, 0);
}, 100);
await asyncExpect(() => {
expect(document.body.innerHTML).toMatchSnapshot();
}, 0);
}, 100);
});
});
223 changes: 105 additions & 118 deletions components/tooltip/Tooltip.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import { defineComponent, ExtractPropTypes, inject, CSSProperties } from 'vue';
import { defineComponent, ExtractPropTypes, CSSProperties, onMounted, ref } from 'vue';
import VcTooltip from '../vc-tooltip';
import classNames from '../_util/classNames';
import getPlacements from './placements';
import PropTypes from '../_util/vue-types';
import { PresetColorTypes } from '../_util/colors';
import {
hasProp,
getComponent,
getStyle,
filterEmpty,
getSlot,
isValidElement,
} from '../_util/props-util';
import warning from '../_util/warning';
import { getPropsSlot, getStyle, filterEmpty, isValidElement } from '../_util/props-util';
import { cloneElement } from '../_util/vnode';
import { defaultConfigProvider } from '../config-provider';
import abstractTooltipProps from './abstractTooltipProps';
import abstractTooltipProps, { triggerTypes, placementTypes } from './abstractTooltipProps';
import useConfigInject from '../_util/hooks/useConfigInject';

const splitObject = (obj: any, keys: string[]) => {
const picked = {};
const omitted = { ...obj };
keys.forEach(key => {
keys.forEach((key) => {
if (obj && key in obj) {
picked[key] = obj[key];
delete omitted[key];
Expand All @@ -36,59 +30,67 @@ const tooltipProps = {
title: PropTypes.VNodeChild,
};

export type TriggerTypes = typeof triggerTypes[number];

export type PlacementTypes = typeof placementTypes[number];

export type TooltipProps = Partial<ExtractPropTypes<typeof tooltipProps>>;

export default defineComponent({
name: 'ATooltip',
inheritAttrs: false,
props: tooltipProps,
emits: ['update:visible', 'visibleChange'],
setup() {
return {
configProvider: inject('configProvider', defaultConfigProvider),
setup(props, { slots, emit, attrs, expose }) {
const { prefixCls, getTargetContainer } = useConfigInject('tooltip', props);

const visible = ref(props.visible);

const tooltip = ref();

onMounted(() => {
warning(
!('default-visible' in attrs) || !('defaultVisible' in attrs),
'Tooltip',
`'defaultVisible' is deprecated, please use 'v-model:visible'`,
);
});

const handleVisibleChange = (bool: boolean) => {
visible.value = isNoTitle() ? false : bool;
if (!isNoTitle()) {
emit('update:visible', bool);
emit('visibleChange', bool);
}
};
},
data() {
return {
sVisible: !!this.$props.visible || !!this.$props.defaultVisible,

const isNoTitle = () => {
const title = getPropsSlot(slots, props, 'title');
return !title && title !== 0;
};

const getPopupDomNode = () => {
return tooltip.value.getPopupDomNode();
};

const getVisible = () => {
return !!visible.value;
};
},
watch: {
visible(val) {
this.sVisible = val;
},
},
methods: {
handleVisibleChange(visible: boolean) {
if (!hasProp(this, 'visible')) {
this.sVisible = this.isNoTitle() ? false : visible;
}
if (!this.isNoTitle()) {
this.$emit('update:visible', visible);
this.$emit('visibleChange', visible);
}
},

getPopupDomNode() {
return (this.$refs.tooltip as any).getPopupDomNode();
},
expose({ getPopupDomNode, getVisible });

getPlacements() {
const { builtinPlacements, arrowPointAtCenter, autoAdjustOverflow } = this.$props;
const getTooltipPlacements = () => {
const { builtinPlacements, arrowPointAtCenter, autoAdjustOverflow } = props;
return (
builtinPlacements ||
getPlacements({
arrowPointAtCenter,
verticalArrowShift: 8,
autoAdjustOverflow,
})
);
},
};

// Fix Tooltip won't hide at disabled button
// mouse events don't trigger at disabled button in Chrome
// https://github.com/react-component/tooltip/issues/18
getDisabledCompatibleChildren(ele: any) {
const getDisabledCompatibleChildren = (ele: any) => {
if (
((typeof ele.type === 'object' &&
(ele.type.__ANT_BUTTON === true ||
Expand Down Expand Up @@ -130,27 +132,21 @@ export default defineComponent({
return <span style={spanStyle}>{child}</span>;
}
return ele;
},

isNoTitle() {
const title = getComponent(this, 'title');
return !title && title !== 0;
},
};

getOverlay() {
const title = getComponent(this, 'title');
const getOverlay = () => {
const title = getPropsSlot(slots, props, 'title');
if (title === 0) {
return title;
}
return title || '';
},
};

// 动态设置动画点
onPopupAlign(domNode: HTMLElement, align: any) {
const placements = this.getPlacements();
const onPopupAlign = (domNode: HTMLElement, align: any) => {
const placements = getTooltipPlacements();
// 当前返回的位置
const placement = Object.keys(placements).filter(
key =>
(key) =>
placements[key].points[0] === align.points[0] &&
placements[key].points[1] === align.points[1],
)[0];
Expand All @@ -174,67 +170,58 @@ export default defineComponent({
transformOrigin.left = `${-align.offset[0]}px`;
}
domNode.style.transformOrigin = `${transformOrigin.left} ${transformOrigin.top}`;
},
},
};

render() {
const { $props, $data, $attrs } = this;
const {
prefixCls: customizePrefixCls,
openClassName,
getPopupContainer,
color,
overlayClassName,
} = $props;
const { getPopupContainer: getContextPopupContainer } = this.configProvider;
const getPrefixCls = this.configProvider.getPrefixCls;
const prefixCls = getPrefixCls('tooltip', customizePrefixCls);
let children = this.children || filterEmpty(getSlot(this));
children = children.length === 1 ? children[0] : children;
let sVisible = $data.sVisible;
// Hide tooltip when there is no title
if (!hasProp(this, 'visible') && this.isNoTitle()) {
sVisible = false;
}
if (!children) {
return null;
}
const child = this.getDisabledCompatibleChildren(
isValidElement(children) ? children : <span>{children}</span>,
);
const childCls = classNames({
[openClassName || `${prefixCls}-open`]: sVisible,
[child.props && child.props.class]: child.props && child.props.class,
});
const customOverlayClassName = classNames(overlayClassName, {
[`${prefixCls}-${color}`]: color && PresetColorRegex.test(color),
});
let formattedOverlayInnerStyle: CSSProperties;
let arrowContentStyle: CSSProperties;
if (color && !PresetColorRegex.test(color)) {
formattedOverlayInnerStyle = { backgroundColor: color };
arrowContentStyle = { backgroundColor: color };
}
return () => {
const { openClassName, getPopupContainer, color, overlayClassName } = props;
let children = filterEmpty(slots.default?.()) ?? null;
children = children.length === 1 ? children[0] : children;
// Hide tooltip when there is no title
if (!('visible' in props) && isNoTitle()) {
visible.value = false;
}
if (!children) {
return null;
}
const child = getDisabledCompatibleChildren(
isValidElement(children) ? children : <span>{children}</span>,
);
const childCls = classNames({
[openClassName || `${prefixCls.value}-open`]: visible.value,
[child.props && child.props.class]: child.props && child.props.class,
});
const customOverlayClassName = classNames(overlayClassName, {
[`${prefixCls.value}-${color}`]: color && PresetColorRegex.test(color),
});
let formattedOverlayInnerStyle: CSSProperties;
let arrowContentStyle: CSSProperties;
if (color && !PresetColorRegex.test(color)) {
formattedOverlayInnerStyle = { backgroundColor: color };
arrowContentStyle = { backgroundColor: color };
}

const vcTooltipProps = {
...$attrs,
...$props,
prefixCls,
getTooltipContainer: getPopupContainer || getContextPopupContainer,
builtinPlacements: this.getPlacements(),
overlay: this.getOverlay(),
visible: sVisible,
ref: 'tooltip',
overlayClassName: customOverlayClassName,
overlayInnerStyle: formattedOverlayInnerStyle,
arrowContent: <span class={`${prefixCls}-arrow-content`} style={arrowContentStyle}></span>,
onVisibleChange: this.handleVisibleChange,
onPopupAlign: this.onPopupAlign,
const vcTooltipProps = {
...attrs,
...props,
prefixCls: prefixCls.value,
getTooltipContainer: getPopupContainer || getTargetContainer.value,
builtinPlacements: getTooltipPlacements(),
overlay: getOverlay(),
visible: visible.value,
ref: tooltip,
overlayClassName: customOverlayClassName,
overlayInnerStyle: formattedOverlayInnerStyle,
arrowContent: (
<span class={`${prefixCls.value}-arrow-content`} style={arrowContentStyle}></span>
),
onVisibleChange: handleVisibleChange,
onPopupAlign,
};
return (
<VcTooltip {...vcTooltipProps}>
{visible.value ? cloneElement(child, { class: childCls }) : child}
</VcTooltip>
);
};
return (
<VcTooltip {...vcTooltipProps}>
{sVisible ? cloneElement(child, { class: childCls }) : child}
</VcTooltip>
);
},
});
14 changes: 7 additions & 7 deletions components/tooltip/__tests__/tooltip.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ describe('Tooltip', () => {
});
await asyncExpect(() => {
expect(onVisibleChange).not.toHaveBeenCalled();
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(false);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(false);
});
await asyncExpect(() => {
div.dispatchEvent(new MouseEvent('mouseleave'));
});
await asyncExpect(() => {
expect(onVisibleChange).not.toHaveBeenCalled();
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(false);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(false);
});
await asyncExpect(() => {
// update `title` value.
Expand All @@ -62,14 +62,14 @@ describe('Tooltip', () => {
});
await asyncExpect(() => {
expect(onVisibleChange).toHaveBeenLastCalledWith(true);
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(true);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(true);
}, 0);
await asyncExpect(() => {
wrapper.findAll('#hello')[0].element.dispatchEvent(new MouseEvent('mouseleave'));
});
await asyncExpect(() => {
expect(onVisibleChange).toHaveBeenLastCalledWith(false);
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(false);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(false);
});
await asyncExpect(() => {
// add `visible` props.
Expand All @@ -80,16 +80,16 @@ describe('Tooltip', () => {
});
await asyncExpect(() => {
expect(onVisibleChange).toHaveBeenLastCalledWith(true);
lastCount = onVisibleChange.mock.calls.length;
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(false);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(true);
});
await asyncExpect(() => {
// always trigger onVisibleChange
wrapper.findAll('#hello')[0].element.dispatchEvent(new MouseEvent('mouseleave'));
lastCount = onVisibleChange.mock.calls.length;
});
await asyncExpect(() => {
expect(onVisibleChange.mock.calls.length).toBe(lastCount); // no change with lastCount
expect(wrapper.vm.$refs.tooltip.$refs.tooltip.visible).toBe(false);
expect(wrapper.vm.$refs.tooltip.getVisible()).toBe(false);
});
});
});
Loading