Skip to content

refactor(v3/avatar): refactor using composition api #4052

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 2 commits into from
May 10, 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
291 changes: 148 additions & 143 deletions components/avatar/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -1,170 +1,175 @@
import { tuple, VueNode } from '../_util/type';
import { CSSProperties, defineComponent, inject, nextTick, PropType } from 'vue';
import {
CSSProperties,
defineComponent,
ExtractPropTypes,
inject,
nextTick,
onMounted,
onUpdated,
PropType,
ref,
watch,
} from 'vue';
import { defaultConfigProvider } from '../config-provider';
import { getComponent } from '../_util/props-util';
import { getPropsSlot } from '../_util/props-util';
import PropTypes from '../_util/vue-types';

export default defineComponent({
name: 'AAvatar',
props: {
prefixCls: PropTypes.string,
shape: PropTypes.oneOf(tuple('circle', 'square')),
size: {
type: [Number, String] as PropType<'large' | 'small' | 'default' | number>,
default: 'default',
},
src: PropTypes.string,
/** Srcset of image avatar */
srcset: PropTypes.string,
/** @deprecated please use `srcset` instead `srcSet` */
srcSet: PropTypes.string,
icon: PropTypes.VNodeChild,
alt: PropTypes.string,
loadError: {
type: Function as PropType<() => boolean>,
},
},
setup() {
return {
configProvider: inject('configProvider', defaultConfigProvider),
};
},
data() {
return {
isImgExist: true,
isMounted: false,
scale: 1,
lastChildrenWidth: undefined,
lastNodeWidth: undefined,
};
},
watch: {
src() {
nextTick(() => {
this.isImgExist = true;
this.scale = 1;
// force uodate for position
this.$forceUpdate();
});
},
},
mounted() {
nextTick(() => {
this.setScale();
this.isMounted = true;
});
const avatarProps = {
prefixCls: PropTypes.string,
shape: PropTypes.oneOf(tuple('circle', 'square')),
size: {
type: [Number, String] as PropType<'large' | 'small' | 'default' | number>,
default: 'default',
},
updated() {
nextTick(() => {
this.setScale();
});
src: PropTypes.string,
/** Srcset of image avatar */
srcset: PropTypes.string,
icon: PropTypes.VNodeChild,
alt: PropTypes.string,
loadError: {
type: Function as PropType<() => boolean>,
},
methods: {
setScale() {
if (!this.$refs.avatarChildren || !this.$refs.avatarNode) {
};

export type AvatarProps = Partial<ExtractPropTypes<typeof avatarProps>>;

const Avatar = defineComponent({
name: 'AAvatar',
props: avatarProps,
setup(props, { slots }) {
const isImgExist = ref(true);
const isMounted = ref(false);
const scale = ref(1);
const lastChildrenWidth = ref<number>(undefined);
const lastNodeWidth = ref<number>(undefined);

const avatarChildrenRef = ref<HTMLElement>(null);
const avatarNodeRef = ref<HTMLElement>(null);

const configProvider = inject('configProvider', defaultConfigProvider);

const setScale = () => {
if (!avatarChildrenRef.value || !avatarNodeRef.value) {
return;
}
const childrenWidth = (this.$refs.avatarChildren as HTMLElement).offsetWidth; // offsetWidth avoid affecting be transform scale
const nodeWidth = (this.$refs.avatarNode as HTMLElement).offsetWidth;
const childrenWidth = avatarChildrenRef.value.offsetWidth; // offsetWidth avoid affecting be transform scale
const nodeWidth = avatarNodeRef.value.offsetWidth;
// denominator is 0 is no meaning
if (
childrenWidth === 0 ||
nodeWidth === 0 ||
(this.lastChildrenWidth === childrenWidth && this.lastNodeWidth === nodeWidth)
(lastChildrenWidth.value === childrenWidth && lastNodeWidth.value === nodeWidth)
) {
return;
}
this.lastChildrenWidth = childrenWidth;
this.lastNodeWidth = nodeWidth;
lastChildrenWidth.value = childrenWidth;
lastNodeWidth.value = nodeWidth;
// add 4px gap for each side to get better performance
this.scale = nodeWidth - 8 < childrenWidth ? (nodeWidth - 8) / childrenWidth : 1;
},
handleImgLoadError() {
const { loadError } = this.$props;
const errorFlag = loadError ? loadError() : undefined;
scale.value = nodeWidth - 8 < childrenWidth ? (nodeWidth - 8) / childrenWidth : 1;
};

const handleImgLoadError = () => {
const { loadError } = props;
const errorFlag = loadError?.();
if (errorFlag !== false) {
this.isImgExist = false;
isImgExist.value = false;
}
},
},
render() {
const { prefixCls: customizePrefixCls, shape, size, src, alt, srcset, srcSet } = this.$props;
const icon = getComponent(this, 'icon');
const getPrefixCls = this.configProvider.getPrefixCls;
const prefixCls = getPrefixCls('avatar', customizePrefixCls);
};

const { isImgExist, scale, isMounted } = this.$data;
watch(
() => props.src,
() => {
nextTick(() => {
isImgExist.value = true;
scale.value = 1;
});
},
);

const sizeCls = {
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
};
onMounted(() => {
nextTick(() => {
setScale();
isMounted.value = true;
});
});

const classString = {
[prefixCls]: true,
...sizeCls,
[`${prefixCls}-${shape}`]: shape,
[`${prefixCls}-image`]: src && isImgExist,
[`${prefixCls}-icon`]: icon,
};
onUpdated(() => {
nextTick(() => {
setScale();
});
});

const sizeStyle: CSSProperties =
typeof size === 'number'
? {
width: `${size}px`,
height: `${size}px`,
lineHeight: `${size}px`,
fontSize: icon ? `${size / 2}px` : '18px',
}
: {};

let children: VueNode = this.$slots.default?.();
if (src && isImgExist) {
children = (
<img src={src} srcset={srcset || srcSet} onError={this.handleImgLoadError} alt={alt} />
);
} else if (icon) {
children = icon;
} else {
const childrenNode = this.$refs.avatarChildren;
if (childrenNode || scale !== 1) {
const transformString = `scale(${scale}) translateX(-50%)`;
const childrenStyle: CSSProperties = {
msTransform: transformString,
WebkitTransform: transformString,
transform: transformString,
};
const sizeChildrenStyle =
typeof size === 'number'
? {
lineHeight: `${size}px`,
}
: {};
children = (
<span
class={`${prefixCls}-string`}
ref="avatarChildren"
style={{ ...sizeChildrenStyle, ...childrenStyle }}
>
{children}
</span>
);
return () => {
const { prefixCls: customizePrefixCls, shape, size, src, alt, srcset } = props;
const icon = getPropsSlot(slots, props, 'icon');
const getPrefixCls = configProvider.getPrefixCls;
const prefixCls = getPrefixCls('avatar', customizePrefixCls);

const classString = {
[prefixCls]: true,
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
[`${prefixCls}-${shape}`]: shape,
[`${prefixCls}-image`]: src && isImgExist.value,
[`${prefixCls}-icon`]: icon,
};

const sizeStyle: CSSProperties =
typeof size === 'number'
? {
width: `${size}px`,
height: `${size}px`,
lineHeight: `${size}px`,
fontSize: icon ? `${size / 2}px` : '18px',
}
: {};

let children: VueNode = slots.default?.();
if (src && isImgExist.value) {
children = <img src={src} srcset={srcset} onError={handleImgLoadError} alt={alt} />;
} else if (icon) {
children = icon;
} else {
const childrenStyle: CSSProperties = {};
if (!isMounted) {
childrenStyle.opacity = 0;
const childrenNode = avatarChildrenRef.value;

if (childrenNode || scale.value !== 1) {
const transformString = `scale(${scale.value}) translateX(-50%)`;
const childrenStyle: CSSProperties = {
msTransform: transformString,
WebkitTransform: transformString,
transform: transformString,
};
const sizeChildrenStyle =
typeof size === 'number'
? {
lineHeight: `${size}px`,
}
: {};
children = (
<span
class={`${prefixCls}-string`}
ref={avatarChildrenRef}
style={{ ...sizeChildrenStyle, ...childrenStyle }}
>
{children}
</span>
);
} else {
children = (
<span class={`${prefixCls}-string`} ref={avatarChildrenRef} style={{ opacity: 0 }}>
{children}
</span>
);
}
children = (
<span class={`${prefixCls}-string`} ref="avatarChildren" style={{ opacity: 0 }}>
{children}
</span>
);
}
}
return (
<span ref="avatarNode" class={classString} style={sizeStyle}>
{children}
</span>
);
return (
<span ref={avatarNodeRef} class={classString} style={sizeStyle}>
{children}
</span>
);
};
},
});

export default Avatar;
26 changes: 5 additions & 21 deletions components/avatar/__tests__/Avatar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,31 +41,16 @@ describe('Avatar Render', () => {
props: {
src: 'http://error.url',
},
sync: false,
attachTo: 'body',
});
wrapper.vm.setScale = jest.fn(() => {
if (wrapper.vm.scale === 0.5) {
return;
}
wrapper.vm.scale = 0.5;
wrapper.vm.$forceUpdate();
});
await asyncExpect(() => {
wrapper.find('img').trigger('error');
}, 0);
await asyncExpect(() => {
const children = wrapper.findAll('.ant-avatar-string');
expect(children.length).toBe(1);
expect(children[0].text()).toBe('Fallback');
expect(wrapper.vm.setScale).toHaveBeenCalled();
});
await asyncExpect(() => {
expect(global.document.body.querySelector('.ant-avatar-string').style.transform).toContain(
'scale(0.5)',
);
global.document.body.innerHTML = '';
}, 1000);
});
it('should handle onError correctly', async () => {
global.document.body.innerHTML = '';
Expand All @@ -91,17 +76,17 @@ describe('Avatar Render', () => {
},
};

const wrapper = mount(Foo, { sync: false, attachTo: 'body' });
const wrapper = mount(Foo, { attachTo: 'body' });
await asyncExpect(() => {
// mock img load Error, since jsdom do not load resource by default
// https://github.com/jsdom/jsdom/issues/1816
wrapper.find('img').trigger('error');
}, 0);
await asyncExpect(() => {
expect(wrapper.findComponent({ name: 'AAvatar' }).vm.isImgExist).toBe(true);
expect(wrapper.find('img')).not.toBeNull();
}, 0);
await asyncExpect(() => {
expect(global.document.body.querySelector('img').getAttribute('src')).toBe(LOAD_SUCCESS_SRC);
expect(wrapper.find('img').attributes('src')).toBe(LOAD_SUCCESS_SRC);
}, 0);
});

Expand All @@ -126,17 +111,16 @@ describe('Avatar Render', () => {
await asyncExpect(() => {
wrapper.find('img').trigger('error');
}, 0);

await asyncExpect(() => {
expect(wrapper.findComponent({ name: 'AAvatar' }).vm.isImgExist).toBe(false);
expect(wrapper.findComponent({ name: 'AAvatar' }).findAll('img').length).toBe(0);
expect(wrapper.findAll('.ant-avatar-string').length).toBe(1);
}, 0);

await asyncExpect(() => {
wrapper.vm.src = LOAD_SUCCESS_SRC;
});
await asyncExpect(() => {
expect(wrapper.findComponent({ name: 'AAvatar' }).vm.isImgExist).toBe(true);
expect(wrapper.findComponent({ name: 'AAvatar' }).findAll('img').length).toBe(1);
expect(wrapper.findAll('.ant-avatar-image').length).toBe(1);
}, 0);
});
Expand Down
2 changes: 2 additions & 0 deletions components/avatar/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Avatar from './Avatar';
import { withInstall } from '../_util/type';

export { AvatarProps } from './Avatar';

export default withInstall(Avatar);