refactor: portal

pull/2245/head
tanjinzhou 2020-05-13 18:36:53 +08:00
parent 8d050f1f49
commit 529f81cb54
19 changed files with 1038 additions and 200 deletions

@ -1 +1 @@
Subproject commit a9b18346fb0783422b08a99d785a0e3d21013b90
Subproject commit 6213d13ef5f287b16a05ff5509b444a662570944

View File

@ -0,0 +1,52 @@
import PropTypes from './vue-types';
import { cloneElement } from './vnode';
export default {
name: 'Portal',
props: {
getContainer: PropTypes.func.isRequired,
children: PropTypes.any.isRequired,
didUpdate: PropTypes.func,
},
mounted() {
this.createContainer();
},
updated() {
const { didUpdate } = this.$props;
if (didUpdate) {
this.$nextTick(() => {
didUpdate(this.$props);
});
}
},
beforeDestroy() {
this.removeContainer();
},
methods: {
createContainer() {
this._container = this.$props.getContainer();
this.$forceUpdate();
},
removeContainer() {
if (this._container) {
this._container.parentNode.removeChild(this._container);
}
},
},
render() {
if (this._container) {
return cloneElement(this.$props.children, {
directives: [
{
name: 'ant-portal',
value: this._container,
},
],
});
}
return null;
},
};

View File

@ -0,0 +1,156 @@
import PropTypes from './vue-types';
import switchScrollingEffect from './switchScrollingEffect';
import setStyle from './setStyle';
import Portal from './Portal';
let openCount = 0;
const windowIsUndefined = !(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
// https://github.com/ant-design/ant-design/issues/19340
// https://github.com/ant-design/ant-design/issues/19332
let cacheOverflow = {};
export default {
name: 'PortalWrapper',
props: {
wrapperClassName: PropTypes.string,
forceRender: PropTypes.bool,
getContainer: PropTypes.any,
children: PropTypes.func,
visible: PropTypes.bool,
},
data() {
const { visible } = this.$props;
openCount = visible ? openCount + 1 : openCount;
return {};
},
updated() {
this.setWrapperClassName();
},
watch: {
visible(val) {
openCount = val ? openCount + 1 : openCount - 1;
},
getContainer(getContainer, prevGetContainer) {
const getContainerIsFunc =
typeof getContainer === 'function' && typeof prevGetContainer === 'function';
if (
getContainerIsFunc
? getContainer.toString() !== prevGetContainer.toString()
: getContainer !== prevGetContainer
) {
this.removeCurrentContainer(false);
}
},
},
beforeDestroy() {
const { visible } = this.$props;
// 离开时不会 render 导到离开时数值不变,改用 func 。。
openCount = visible && openCount ? openCount - 1 : openCount;
this.removeCurrentContainer(visible);
},
methods: {
getParent() {
const { getContainer } = this.$props;
if (getContainer) {
if (typeof getContainer === 'string') {
return document.querySelectorAll(getContainer)[0];
}
if (typeof getContainer === 'function') {
return getContainer();
}
if (typeof getContainer === 'object' && getContainer instanceof window.HTMLElement) {
return getContainer;
}
}
return document.body;
},
getDomContainer() {
if (windowIsUndefined) {
return null;
}
if (!this.container) {
this.container = document.createElement('div');
const parent = this.getParent();
if (parent) {
parent.appendChild(this.container);
}
}
this.setWrapperClassName();
return this.container;
},
setWrapperClassName() {
const { wrapperClassName } = this.$props;
if (this.container && wrapperClassName && wrapperClassName !== this.container.className) {
this.container.className = wrapperClassName;
}
},
savePortal(c) {
// Warning: don't rename _component
// https://github.com/react-component/util/pull/65#discussion_r352407916
this._component = c;
},
removeCurrentContainer() {
this.container = null;
this._component = null;
},
/**
* Enhance ./switchScrollingEffect
* 1. Simulate document body scroll bar with
* 2. Record body has overflow style and recover when all of PortalWrapper invisible
* 3. Disable body scroll when PortalWrapper has open
*
* @memberof PortalWrapper
*/
switchScrollingEffect() {
if (openCount === 1 && !Object.keys(cacheOverflow).length) {
switchScrollingEffect();
// Must be set after switchScrollingEffect
cacheOverflow = setStyle({
overflow: 'hidden',
overflowX: 'hidden',
overflowY: 'hidden',
});
} else if (!openCount) {
setStyle(cacheOverflow);
cacheOverflow = {};
switchScrollingEffect(true);
}
},
},
render() {
const { children, forceRender, visible } = this.$props;
let portal = null;
const childProps = {
getOpenCount: () => openCount,
getContainer: this.getDomContainer,
switchScrollingEffect: this.switchScrollingEffect,
};
if (forceRender || visible || this._component) {
portal = (
<Portal
getContainer={this.getDomContainer}
children={children(childProps)}
{...{
directives: [
{
name: 'ant-ref',
value: this.savePortal,
},
],
}}
></Portal>
);
}
return portal;
},
};

View File

@ -1,11 +1,13 @@
import ref from 'vue-ref';
import { antInput } from './antInputDirective';
import { antDecorator } from './FormDecoratorDirective';
import { antPortal } from './portalDirective';
export default {
install: Vue => {
Vue.use(ref, { name: 'ant-ref' });
antInput(Vue);
antDecorator(Vue);
antPortal(Vue);
},
};

View File

@ -0,0 +1,24 @@
export function antPortal(Vue) {
return Vue.directive('ant-portal', {
inserted(el, binding) {
const { value } = binding;
const parentNode = typeof value === 'function' ? value(el) : value;
if (parentNode !== el.parentNode) {
parentNode.appendChild(el);
}
},
componentUpdated(el, binding) {
const { value } = binding;
const parentNode = typeof value === 'function' ? value(el) : value;
if (parentNode !== el.parentNode) {
parentNode.appendChild(el);
}
},
});
}
export default {
install: Vue => {
antPortal(Vue);
},
};

View File

@ -0,0 +1,25 @@
/**
* Easy to set element style, return previous style
* IE browser compatible(IE browser doesn't merge overflow style, need to set it separately)
* https://github.com/ant-design/ant-design/issues/19393
*
*/
function setStyle(style, options = {}) {
const { element = document.body } = options;
const oldStyle = {};
const styleKeys = Object.keys(style);
// IE browser compatible
styleKeys.forEach(key => {
oldStyle[key] = element.style[key];
});
styleKeys.forEach(key => {
element.style[key] = style[key];
});
return oldStyle;
}
export default setStyle;

View File

@ -129,6 +129,9 @@ export function cloneElement(n, nodeProps = {}, deep) {
node.componentOptions.children = children;
}
} else {
if (children) {
node.children = children;
}
node.data.on = { ...(node.data.on || {}), ...on };
}

View File

@ -1,7 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Drawer class is test_drawer 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right test_drawer">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">
@ -19,7 +19,7 @@ exports[`Drawer class is test_drawer 1`] = `
`;
exports[`Drawer closable is false 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">
@ -34,7 +34,7 @@ exports[`Drawer closable is false 1`] = `
`;
exports[`Drawer destroyOnClose is true 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">
@ -49,7 +49,7 @@ exports[`Drawer destroyOnClose is true 1`] = `
`;
exports[`Drawer have a title 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">
@ -69,7 +69,7 @@ exports[`Drawer have a title 1`] = `
`;
exports[`Drawer render correctly 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 400px;">
@ -87,7 +87,7 @@ exports[`Drawer render correctly 1`] = `
`;
exports[`Drawer render top drawer 1`] = `
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-top">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateY(-100%); height: 400px;">

View File

@ -2,7 +2,7 @@
exports[`Drawer render correctly 1`] = `
<div><button type="button" class="ant-btn" ant-click-animating-without-extra-node="false"><span>open</span></button>
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">

View File

@ -40,7 +40,7 @@ exports[`renders ./antdv-demo/docs/drawer/demo/render-in-current.md correctly 1`
<div style="height: 200px; overflow: hidden; position: relative; border: 1px solid #ebedf0; border-radius: 2px; padding: 48px; text-align: center; background: rgb(250, 250, 250);">
Render in this
<div style="margin-top: 16px;"><button type="button" class="ant-btn ant-btn-primary"><span>Open</span></button></div>
<div tabindex="-1" class="">
<div class="">
<div tabindex="-1" class="ant-drawer ant-drawer-right" style="position: absolute;">
<div class="ant-drawer-mask"></div>
<div class="ant-drawer-content-wrapper" style="transform: translateX(100%); width: 256px;">

View File

@ -964,7 +964,6 @@ exports[`Locale Provider should display the text as ar 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -1398,7 +1397,6 @@ exports[`Locale Provider should display the text as bg 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -1832,7 +1830,6 @@ exports[`Locale Provider should display the text as ca 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -2266,7 +2263,6 @@ exports[`Locale Provider should display the text as cs 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -2700,7 +2696,6 @@ exports[`Locale Provider should display the text as da 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -3134,7 +3129,6 @@ exports[`Locale Provider should display the text as de 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -3568,7 +3562,6 @@ exports[`Locale Provider should display the text as el 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -4002,7 +3995,6 @@ exports[`Locale Provider should display the text as en 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -4436,7 +4428,6 @@ exports[`Locale Provider should display the text as en-gb 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -4870,7 +4861,6 @@ exports[`Locale Provider should display the text as es 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -5304,7 +5294,6 @@ exports[`Locale Provider should display the text as et 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -5738,7 +5727,6 @@ exports[`Locale Provider should display the text as fa 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -6172,7 +6160,6 @@ exports[`Locale Provider should display the text as fi 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -6606,7 +6593,6 @@ exports[`Locale Provider should display the text as fr 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -7040,7 +7026,6 @@ exports[`Locale Provider should display the text as fr 2`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -7474,7 +7459,6 @@ exports[`Locale Provider should display the text as he 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -7908,7 +7892,6 @@ exports[`Locale Provider should display the text as hi 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -8342,7 +8325,6 @@ exports[`Locale Provider should display the text as hr 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -8776,7 +8758,6 @@ exports[`Locale Provider should display the text as hu 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -9210,7 +9191,6 @@ exports[`Locale Provider should display the text as hy 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -9644,7 +9624,6 @@ exports[`Locale Provider should display the text as id 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -10078,7 +10057,6 @@ exports[`Locale Provider should display the text as is 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -10512,7 +10490,6 @@ exports[`Locale Provider should display the text as it 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -10946,7 +10923,6 @@ exports[`Locale Provider should display the text as ja 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -11380,7 +11356,6 @@ exports[`Locale Provider should display the text as kn 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -11814,7 +11789,6 @@ exports[`Locale Provider should display the text as ko 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -12248,7 +12222,6 @@ exports[`Locale Provider should display the text as ku-iq 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -12682,7 +12655,6 @@ exports[`Locale Provider should display the text as lv 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -13116,7 +13088,6 @@ exports[`Locale Provider should display the text as mk 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -13550,7 +13521,6 @@ exports[`Locale Provider should display the text as mn-mn 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -13984,7 +13954,6 @@ exports[`Locale Provider should display the text as ms-my 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -14418,7 +14387,6 @@ exports[`Locale Provider should display the text as nb 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -14852,7 +14820,6 @@ exports[`Locale Provider should display the text as ne-np 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -15286,7 +15253,6 @@ exports[`Locale Provider should display the text as nl 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -15720,7 +15686,6 @@ exports[`Locale Provider should display the text as nl-be 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -16154,7 +16119,6 @@ exports[`Locale Provider should display the text as pl 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -16588,7 +16552,6 @@ exports[`Locale Provider should display the text as pt 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -17022,7 +16985,6 @@ exports[`Locale Provider should display the text as pt-br 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -17456,7 +17418,6 @@ exports[`Locale Provider should display the text as ro 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -17890,7 +17851,6 @@ exports[`Locale Provider should display the text as ru 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -18324,7 +18284,6 @@ exports[`Locale Provider should display the text as sk 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -18758,7 +18717,6 @@ exports[`Locale Provider should display the text as sl 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -19192,7 +19150,6 @@ exports[`Locale Provider should display the text as sr 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -19626,7 +19583,6 @@ exports[`Locale Provider should display the text as sv 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -20060,7 +20016,6 @@ exports[`Locale Provider should display the text as ta 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -20494,7 +20449,6 @@ exports[`Locale Provider should display the text as th 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -20928,7 +20882,6 @@ exports[`Locale Provider should display the text as tr 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -21362,7 +21315,6 @@ exports[`Locale Provider should display the text as uk 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -21796,7 +21748,6 @@ exports[`Locale Provider should display the text as vi 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -22230,7 +22181,6 @@ exports[`Locale Provider should display the text as zh-cn 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -22664,6 +22614,5 @@ exports[`Locale Provider should display the text as zh-tw 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;

View File

@ -2,6 +2,7 @@ import { mount } from '@vue/test-utils';
import Vue from 'vue';
import moment from 'moment';
import MockDate from 'mockdate';
import { sleep } from '../../../tests/utils';
import {
LocaleProvider,
Pagination,
@ -188,7 +189,7 @@ describe('Locale Provider', () => {
);
},
},
{ sync: false },
{ sync: false, attachToDocument: true },
);
Vue.nextTick(() => {
expect(wrapper.html()).toMatchSnapshot();
@ -197,7 +198,7 @@ describe('Locale Provider', () => {
});
});
it('should change locale of Modal.xxx', () => {
it('should change locale of Modal.xxx', async () => {
const ModalDemo = {
mounted() {
Modal.confirm({
@ -208,7 +209,8 @@ describe('Locale Provider', () => {
return null;
},
};
locales.forEach(locale => {
for (let locale of locales) {
document.body.innerHTML = '';
mount(
{
render() {
@ -219,8 +221,9 @@ describe('Locale Provider', () => {
);
},
},
{ sync: false },
{ sync: false, attachToDocument: true },
);
await sleep();
const currentConfirmNode = document.querySelectorAll('.ant-modal-confirm')[
document.querySelectorAll('.ant-modal-confirm').length - 1
];
@ -234,10 +237,10 @@ describe('Locale Provider', () => {
}
expect(cancelButtonText).toBe(locale.Modal.cancelText);
expect(okButtonText).toBe(locale.Modal.okText);
});
}
});
it('set moment locale when locale changes', done => {
it('set moment locale when locale changes', async () => {
document.body.innerHTML = '';
const Test = {
data() {
@ -256,17 +259,13 @@ describe('Locale Provider', () => {
},
};
const wrapper = mount(Test, { sync: false, attachToDocument: true });
setTimeout(() => {
expect(document.body.innerHTML).toMatchSnapshot();
wrapper.setData({ locale: frFR });
setTimeout(() => {
expect(document.body.innerHTML).toMatchSnapshot();
wrapper.setData({ locale: null });
setTimeout(() => {
expect(document.body.innerHTML).toMatchSnapshot();
done();
});
});
});
await sleep(50);
expect(document.body.innerHTML).toMatchSnapshot();
wrapper.setData({ locale: frFR });
await sleep(50);
expect(document.body.innerHTML).toMatchSnapshot();
wrapper.setData({ locale: null });
await sleep(50);
expect(document.body.innerHTML).toMatchSnapshot();
});
});

View File

@ -1,6 +1,7 @@
import { mount } from '@vue/test-utils';
import Modal from '..';
import mountTest from '../../../tests/shared/mountTest';
import { asyncExpect } from '@/tests/utils';
const ModalTester = {
props: ['footer', 'visible'],
@ -27,30 +28,43 @@ const ModalTester = {
describe('Modal', () => {
mountTest(Modal);
it('render correctly', done => {
const wrapper = mount({
render() {
return <ModalTester visible />;
it('render correctly', async () => {
const wrapper = mount(
{
render() {
return <ModalTester visible />;
},
},
{
sync: false,
attachToDocument: true,
},
);
await asyncExpect(() => {
expect(wrapper.html()).toMatchSnapshot();
});
expect(wrapper.html()).toMatchSnapshot();
// https://github.com/vuejs/vue-test-utils/issues/624
const wrapper1 = mount(ModalTester, {
sync: false,
attachToDocument: true,
});
wrapper1.setProps({ visible: true });
setTimeout(() => {
await asyncExpect(() => {
expect(wrapper1.html()).toMatchSnapshot();
done();
}, 10);
});
});
it('render without footer', () => {
const wrapper = mount({
render() {
return <ModalTester visible footer={null} />;
it('render without footer', async () => {
const wrapper = mount(
{
render() {
return <ModalTester visible footer={null} />;
},
},
{ attachToDocument: true, sync: true },
);
await asyncExpect(() => {
expect(wrapper.html()).toMatchSnapshot();
});
expect(wrapper.html()).toMatchSnapshot();
});
});

View File

@ -21,7 +21,6 @@ exports[`Modal render correctly 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -46,7 +45,6 @@ exports[`Modal render correctly 2`] = `
</div>
</div>
</div>
<!---->
</div>
`;
@ -68,6 +66,5 @@ exports[`Modal render without footer 1`] = `
</div>
</div>
</div>
<!---->
</div>
`;

View File

@ -1,5 +1,6 @@
import Modal from '..';
import { asyncExpect } from '@/tests/utils';
import { sleep } from '../../../tests/utils';
const { confirm } = Modal;
describe('Modal.confirm triggers callbacks correctly', () => {
@ -26,76 +27,80 @@ describe('Modal.confirm triggers callbacks correctly', () => {
});
}
it('trigger onCancel once when click on cancel button', () => {
it('trigger onCancel once when click on cancel button', async () => {
const onCancel = jest.fn();
const onOk = jest.fn();
open({
onCancel,
onOk,
});
await sleep();
// first Modal
$$('.ant-btn')[0].click();
expect(onCancel.mock.calls.length).toBe(1);
expect(onOk.mock.calls.length).toBe(0);
});
it('trigger onOk once when click on ok button', () => {
it('trigger onOk once when click on ok button', async () => {
const onCancel = jest.fn();
const onOk = jest.fn();
open({
onCancel,
onOk,
});
await sleep();
// second Modal
$$('.ant-btn-primary')[0].click();
expect(onCancel.mock.calls.length).toBe(0);
expect(onOk.mock.calls.length).toBe(1);
});
it('should allow Modal.comfirm without onCancel been set', () => {
it('should allow Modal.comfirm without onCancel been set', async () => {
open();
await sleep();
// Third Modal
$$('.ant-btn')[0].click();
expect(errorSpy).not.toHaveBeenCalled();
});
it('should allow Modal.comfirm without onOk been set', () => {
it('should allow Modal.comfirm without onOk been set', async () => {
open();
await sleep();
// Fourth Modal
$$('.ant-btn-primary')[0].click();
expect(errorSpy).not.toHaveBeenCalled();
});
it('ok only', () => {
it('ok only', async () => {
open({ okCancel: false });
await sleep();
expect($$('.ant-btn')).toHaveLength(1);
expect($$('.ant-btn')[0].innerHTML).toContain('OK');
});
it('allows extra props on buttons', () => {
it('allows extra props on buttons', async () => {
open({
okButtonProps: { props: { disabled: true } },
cancelButtonProps: { attrs: { 'data-test': 'baz' } },
});
await sleep();
expect($$('.ant-btn')).toHaveLength(2);
expect($$('.ant-btn')[0].attributes['data-test'].value).toBe('baz');
expect($$('.ant-btn')[1].disabled).toBe(true);
});
it('trigger onCancel once when click on cancel button', () => {
jest.useFakeTimers();
['info', 'success', 'warning', 'error'].forEach(async type => {
fit('trigger onCancel once when click on cancel button', async () => {
const arr = ['info', 'success', 'warning', 'error'];
for (let type of arr) {
Modal[type]({
title: 'title',
content: 'content',
});
await sleep();
expect($$(`.ant-modal-confirm-${type}`)).toHaveLength(1);
$$('.ant-btn')[0].click();
jest.runAllTimers();
await asyncExpect(() => {
expect($$(`.ant-modal-confirm-${type}`)).toHaveLength(0);
});
});
jest.useRealTimers();
await sleep();
expect($$(`.ant-modal-confirm-${type}`)).toHaveLength(0);
}
});
});

View File

@ -263,11 +263,10 @@ export default {
);
}
const style = { ...this.dialogStyle, ...dest };
const style = dest;
const sentinelStyle = { width: 0, height: 0, overflow: 'hidden' };
const cls = {
[prefixCls]: true,
...this.dialogClass,
};
const transitionName = this.getTransitionName();
const dialogElement = (

View File

@ -1,87 +1,43 @@
import Dialog from './Dialog';
import ContainerRender from '../_util/ContainerRender';
import getDialogPropTypes from './IDialogPropTypes';
import { getStyle, getClass, getListeners } from '../_util/props-util';
import { getListeners } from '../_util/props-util';
import Portal from '../_util/PortalWrapper';
const IDialogPropTypes = getDialogPropTypes();
let openCount = 0;
const DialogWrap = {
inheritAttrs: false,
props: {
...IDialogPropTypes,
visible: IDialogPropTypes.visible.def(false),
},
data() {
openCount = this.visible ? openCount + 1 : openCount;
this.renderComponent = () => {};
this.removeContainer = () => {};
return {};
},
watch: {
visible(val, preVal) {
openCount = val && !preVal ? openCount + 1 : openCount - 1;
},
},
beforeDestroy() {
if (this.visible) {
openCount = openCount ? openCount - 1 : openCount;
this.renderComponent({
afterClose: this.removeContainer,
visible: false,
on: {
close() {},
},
});
} else {
this.removeContainer();
}
},
methods: {
getComponent(extra = {}) {
const { $attrs, $props, $slots, getContainer } = this;
const { on, ...otherProps } = extra;
const dialogProps = {
props: {
...$props,
dialogClass: getClass(this),
dialogStyle: getStyle(this),
...otherProps,
getOpenCount: getContainer === false ? () => 2 : () => openCount,
},
attrs: $attrs,
ref: '_component',
key: 'dialog',
on: {
...getListeners(this),
...on,
},
};
return <Dialog {...dialogProps}>{$slots.default}</Dialog>;
},
getContainer2() {
const container = document.createElement('div');
if (this.getContainer) {
this.getContainer().appendChild(container);
} else {
document.body.appendChild(container);
}
return container;
},
},
render() {
const { visible } = this;
const { visible, getContainer, forceRender } = this.$props;
const dialogProps = {
props: this.$props,
attrs: this.$attrs,
ref: '_component',
key: 'dialog',
on: getListeners(this),
};
// dom
if (getContainer === false) {
return (
<Dialog
{...dialogProps}
getOpenCount={() => 2} // body
>
{this.$slots.default}
</Dialog>
);
}
return (
<ContainerRender
parent={this}
<Portal
visible={visible}
autoDestroy={false}
getComponent={this.getComponent}
getContainer={this.getContainer2}
children={({ renderComponent, removeContainer }) => {
this.renderComponent = renderComponent;
this.removeContainer = removeContainer;
return null;
forceRender={forceRender}
getContainer={getContainer}
children={childProps => {
dialogProps.props = { ...dialogProps.props, ...childProps };
return <Dialog {...dialogProps}>{this.$slots.default}</Dialog>;
}}
/>
);

View File

@ -4,7 +4,6 @@ import ref from 'vue-ref';
import BaseMixin from '../../_util/BaseMixin';
import { initDefaultProps, getEvents, getListeners } from '../../_util/props-util';
import { cloneElement } from '../../_util/vnode';
import ContainerRender from '../../_util/ContainerRender';
import getScrollBarSize from '../../_util/getScrollBarSize';
import { IDrawerProps } from './IDrawerPropTypes';
import KeyCode from '../../_util/KeyCode';
@ -17,6 +16,7 @@ import {
transformArguments,
isNumeric,
} from './utils';
import Portal from '../../_util/Portal';
function noop() {}
@ -610,8 +610,9 @@ const Drawer = {
},
render() {
const { getContainer, wrapperClassName } = this.$props;
const { getContainer, wrapperClassName, handler, forceRender } = this.$props;
const open = this.getOpen();
let portal = null;
currentDrawer[this.drawerId] = open ? this.container : open;
const children = this.getChildToRender(this.sFirstEnter ? open : false);
if (!getContainer) {
@ -624,7 +625,7 @@ const Drawer = {
},
];
return (
<div tabIndex={-1} class={wrapperClassName} {...{ directives }}>
<div class={wrapperClassName} {...{ directives }}>
{children}
</div>
);
@ -632,21 +633,12 @@ const Drawer = {
if (!this.container || (!open && !this.sFirstEnter)) {
return null;
}
return (
<ContainerRender
parent={this}
visible
autoMount
autoDestroy={false}
getComponent={() => children}
getContainer={this.getSelfContainer}
children={({ renderComponent, removeContainer }) => {
this.renderComponent = renderComponent;
this.removeContainer = removeContainer;
return null;
}}
/>
);
// 如果有 handler 为内置强制渲染;
const $forceRender = !!handler || forceRender;
if ($forceRender || open || this.dom) {
portal = <Portal getContainer={this.getSelfContainer} children={children}></Portal>;
}
return portal;
},
};

665
components/vc-trigger/t.js Normal file
View File

@ -0,0 +1,665 @@
import Vue from 'vue';
import ref from 'vue-ref';
import PropTypes from '../_util/vue-types';
import contains from '../vc-util/Dom/contains';
import {
hasProp,
getComponentFromProp,
getEvents,
filterEmpty,
getListeners,
} from '../_util/props-util';
import { requestAnimationTimeout, cancelAnimationTimeout } from '../_util/requestAnimationTimeout';
import addEventListener from '../vc-util/Dom/addEventListener';
import warning from '../_util/warning';
import Popup from './Popup';
import { getAlignFromPlacement, getAlignPopupClassName, noop } from './utils';
import BaseMixin from '../_util/BaseMixin';
import { cloneElement } from '../_util/vnode';
import Portal from '../_util/Portal';
Vue.use(ref, { name: 'ant-ref' });
function returnEmptyString() {
return '';
}
function returnDocument() {
return window.document;
}
const ALL_HANDLERS = [
'click',
'mousedown',
'touchstart',
'mouseenter',
'mouseleave',
'focus',
'blur',
'contextmenu',
];
export default {
name: 'Trigger',
mixins: [BaseMixin],
props: {
action: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]).def([]),
showAction: PropTypes.any.def([]),
hideAction: PropTypes.any.def([]),
getPopupClassNameFromAlign: PropTypes.any.def(returnEmptyString),
// onPopupVisibleChange: PropTypes.func.def(noop),
afterPopupVisibleChange: PropTypes.func.def(noop),
popup: PropTypes.any,
popupStyle: PropTypes.object.def(() => ({})),
prefixCls: PropTypes.string.def('rc-trigger-popup'),
popupClassName: PropTypes.string.def(''),
popupPlacement: PropTypes.string,
builtinPlacements: PropTypes.object,
popupTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
popupAnimation: PropTypes.any,
mouseEnterDelay: PropTypes.number.def(0),
mouseLeaveDelay: PropTypes.number.def(0.1),
zIndex: PropTypes.number,
focusDelay: PropTypes.number.def(0),
blurDelay: PropTypes.number.def(0.15),
getPopupContainer: PropTypes.func,
getDocument: PropTypes.func.def(returnDocument),
forceRender: PropTypes.bool,
destroyPopupOnHide: PropTypes.bool.def(false),
mask: PropTypes.bool.def(false),
maskClosable: PropTypes.bool.def(true),
// onPopupAlign: PropTypes.func.def(noop),
popupAlign: PropTypes.object.def(() => ({})),
popupVisible: PropTypes.bool,
defaultPopupVisible: PropTypes.bool.def(false),
maskTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
maskAnimation: PropTypes.string,
stretch: PropTypes.string,
alignPoint: PropTypes.bool, // Maybe we can support user pass position in the future
},
provide() {
return {
vcTriggerContext: this,
};
},
inject: {
vcTriggerContext: { default: () => ({}) },
savePopupRef: { default: () => noop },
dialogContext: { default: () => null },
},
data() {
const props = this.$props;
let popupVisible;
if (hasProp(this, 'popupVisible')) {
popupVisible = !!props.popupVisible;
} else {
popupVisible = !!props.defaultPopupVisible;
}
ALL_HANDLERS.forEach(h => {
this[`fire${h}`] = e => {
this.fireEvents(h, e);
};
});
return {
prevPopupVisible: popupVisible,
sPopupVisible: popupVisible,
point: null,
};
},
watch: {
popupVisible(val) {
if (val !== undefined) {
this.prevPopupVisible = this.sPopupVisible;
this.sPopupVisible = val;
}
},
},
deactivated() {
this.setPopupVisible(false);
},
mounted() {
this.$nextTick(() => {
this.updatedCal();
});
},
updated() {
this.$nextTick(() => {
this.updatedCal();
});
},
beforeDestroy() {
this.clearDelayTimer();
this.clearOutsideHandler();
clearTimeout(this.mouseDownTimeout);
},
methods: {
updatedCal() {
const props = this.$props;
const state = this.$data;
// We must listen to `mousedown` or `touchstart`, edge case:
// https://github.com/ant-design/ant-design/issues/5804
// https://github.com/react-component/calendar/issues/250
// https://github.com/react-component/trigger/issues/50
if (state.sPopupVisible) {
let currentDocument;
if (!this.clickOutsideHandler && (this.isClickToHide() || this.isContextmenuToShow())) {
currentDocument = props.getDocument();
this.clickOutsideHandler = addEventListener(
currentDocument,
'mousedown',
this.onDocumentClick,
);
}
// always hide on mobile
if (!this.touchOutsideHandler) {
currentDocument = currentDocument || props.getDocument();
this.touchOutsideHandler = addEventListener(
currentDocument,
'touchstart',
this.onDocumentClick,
);
}
// close popup when trigger type contains 'onContextmenu' and document is scrolling.
if (!this.contextmenuOutsideHandler1 && this.isContextmenuToShow()) {
currentDocument = currentDocument || props.getDocument();
this.contextmenuOutsideHandler1 = addEventListener(
currentDocument,
'scroll',
this.onContextmenuClose,
);
}
// close popup when trigger type contains 'onContextmenu' and window is blur.
if (!this.contextmenuOutsideHandler2 && this.isContextmenuToShow()) {
this.contextmenuOutsideHandler2 = addEventListener(
window,
'blur',
this.onContextmenuClose,
);
}
} else {
this.clearOutsideHandler();
}
},
onMouseenter(e) {
const { mouseEnterDelay } = this.$props;
this.fireEvents('mouseenter', e);
this.delaySetPopupVisible(true, mouseEnterDelay, mouseEnterDelay ? null : e);
},
onMouseMove(e) {
this.fireEvents('mousemove', e);
this.setPoint(e);
},
onMouseleave(e) {
this.fireEvents('mouseleave', e);
this.delaySetPopupVisible(false, this.$props.mouseLeaveDelay);
},
onPopupMouseenter() {
this.clearDelayTimer();
},
onPopupMouseleave(e) {
if (
e &&
e.relatedTarget &&
!e.relatedTarget.setTimeout &&
this._component &&
this._component.getPopupDomNode &&
contains(this._component.getPopupDomNode(), e.relatedTarget)
) {
return;
}
this.delaySetPopupVisible(false, this.$props.mouseLeaveDelay);
},
onFocus(e) {
this.fireEvents('focus', e);
// incase focusin and focusout
this.clearDelayTimer();
if (this.isFocusToShow()) {
this.focusTime = Date.now();
this.delaySetPopupVisible(true, this.$props.focusDelay);
}
},
onMousedown(e) {
this.fireEvents('mousedown', e);
this.preClickTime = Date.now();
},
onTouchstart(e) {
this.fireEvents('touchstart', e);
this.preTouchTime = Date.now();
},
onBlur(e) {
if (!contains(e.target, e.relatedTarget || document.activeElement)) {
this.fireEvents('blur', e);
this.clearDelayTimer();
if (this.isBlurToHide()) {
this.delaySetPopupVisible(false, this.$props.blurDelay);
}
}
},
onContextmenu(e) {
e.preventDefault();
this.fireEvents('contextmenu', e);
this.setPopupVisible(true, e);
},
onContextmenuClose() {
if (this.isContextmenuToShow()) {
this.close();
}
},
onClick(event) {
this.fireEvents('click', event);
// focus will trigger click
if (this.focusTime) {
let preTime;
if (this.preClickTime && this.preTouchTime) {
preTime = Math.min(this.preClickTime, this.preTouchTime);
} else if (this.preClickTime) {
preTime = this.preClickTime;
} else if (this.preTouchTime) {
preTime = this.preTouchTime;
}
if (Math.abs(preTime - this.focusTime) < 20) {
return;
}
this.focusTime = 0;
}
this.preClickTime = 0;
this.preTouchTime = 0;
// Only prevent default when all the action is click.
// https://github.com/ant-design/ant-design/issues/17043
// https://github.com/ant-design/ant-design/issues/17291
if (
this.isClickToShow() &&
(this.isClickToHide() || this.isBlurToHide()) &&
event &&
event.preventDefault
) {
event.preventDefault();
}
if (event && event.domEvent) {
event.domEvent.preventDefault();
}
const nextVisible = !this.$data.sPopupVisible;
if ((this.isClickToHide() && !nextVisible) || (nextVisible && this.isClickToShow())) {
this.setPopupVisible(!this.$data.sPopupVisible, event);
}
},
onPopupMouseDown(...args) {
const { vcTriggerContext = {} } = this;
this.hasPopupMouseDown = true;
clearTimeout(this.mouseDownTimeout);
this.mouseDownTimeout = setTimeout(() => {
this.hasPopupMouseDown = false;
}, 0);
if (vcTriggerContext.onPopupMouseDown) {
vcTriggerContext.onPopupMouseDown(...args);
}
},
onDocumentClick(event) {
if (this.$props.mask && !this.$props.maskClosable) {
return;
}
const target = event.target;
const root = this.$el;
if (!contains(root, target) && !this.hasPopupMouseDown) {
this.close();
}
},
getPopupDomNode() {
if (this._component && this._component.getPopupDomNode) {
return this._component.getPopupDomNode();
}
return null;
},
getRootDomNode() {
return this.$el;
// return this.$el.children[0] || this.$el
},
handleGetPopupClassFromAlign(align) {
const className = [];
const props = this.$props;
const {
popupPlacement,
builtinPlacements,
prefixCls,
alignPoint,
getPopupClassNameFromAlign,
} = props;
if (popupPlacement && builtinPlacements) {
className.push(getAlignPopupClassName(builtinPlacements, prefixCls, align, alignPoint));
}
if (getPopupClassNameFromAlign) {
className.push(getPopupClassNameFromAlign(align));
}
return className.join(' ');
},
getPopupAlign() {
const props = this.$props;
const { popupPlacement, popupAlign, builtinPlacements } = props;
if (popupPlacement && builtinPlacements) {
return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign);
}
return popupAlign;
},
savePopup(node) {
this._component = node;
this.savePopupRef(node);
},
getComponent() {
const self = this;
const mouseProps = {};
if (this.isMouseEnterToShow()) {
mouseProps.mouseenter = self.onPopupMouseenter;
}
if (this.isMouseLeaveToHide()) {
mouseProps.mouseleave = self.onPopupMouseleave;
}
mouseProps.mousedown = this.onPopupMouseDown;
mouseProps.touchstart = this.onPopupMouseDown;
const { handleGetPopupClassFromAlign, getRootDomNode, getContainer } = self;
const {
prefixCls,
destroyPopupOnHide,
popupClassName,
action,
popupAnimation,
popupTransitionName,
popupStyle,
mask,
maskAnimation,
maskTransitionName,
zIndex,
stretch,
alignPoint,
} = self.$props;
const { sPopupVisible, point } = this.$data;
const align = this.getPopupAlign();
const popupProps = {
props: {
prefixCls,
destroyPopupOnHide,
visible: sPopupVisible,
point: alignPoint && point,
action,
align,
animation: popupAnimation,
getClassNameFromAlign: handleGetPopupClassFromAlign,
stretch,
getRootDomNode,
mask,
zIndex,
transitionName: popupTransitionName,
maskAnimation,
maskTransitionName,
getContainer,
popupClassName,
popupStyle,
},
on: {
align: getListeners(this).popupAlign || noop,
...mouseProps,
},
directives: [
{
name: 'ant-ref',
value: this.savePopup,
},
],
};
return <Popup {...popupProps}>{getComponentFromProp(self, 'popup')}</Popup>;
},
getContainer() {
const { $props: props, dialogContext } = this;
const popupContainer = document.createElement('div');
// Make sure default popup container will never cause scrollbar appearing
// https://github.com/react-component/trigger/issues/41
popupContainer.style.position = 'absolute';
popupContainer.style.top = '0';
popupContainer.style.left = '0';
popupContainer.style.width = '100%';
const mountNode = props.getPopupContainer
? props.getPopupContainer(this.$el, dialogContext)
: props.getDocument().body;
mountNode.appendChild(popupContainer);
this.popupContainer = popupContainer;
return popupContainer;
},
setPopupVisible(sPopupVisible, event) {
const { alignPoint, sPopupVisible: prevPopupVisible } = this;
this.clearDelayTimer();
if (prevPopupVisible !== sPopupVisible) {
if (!hasProp(this, 'popupVisible')) {
this.setState({
sPopupVisible,
prevPopupVisible,
});
}
const listeners = getListeners(this);
listeners.popupVisibleChange && listeners.popupVisibleChange(sPopupVisible);
}
// Always record the point position since mouseEnterDelay will delay the show
if (alignPoint && event) {
this.setPoint(event);
}
},
setPoint(point) {
const { alignPoint } = this.$props;
if (!alignPoint || !point) return;
this.setState({
point: {
pageX: point.pageX,
pageY: point.pageY,
},
});
},
handlePortalUpdate() {
if (this.prevPopupVisible !== this.sPopupVisible) {
this.afterPopupVisibleChange(this.sPopupVisible);
}
},
delaySetPopupVisible(visible, delayS, event) {
const delay = delayS * 1000;
this.clearDelayTimer();
if (delay) {
const point = event ? { pageX: event.pageX, pageY: event.pageY } : null;
this.delayTimer = requestAnimationTimeout(() => {
this.setPopupVisible(visible, point);
this.clearDelayTimer();
}, delay);
} else {
this.setPopupVisible(visible, event);
}
},
clearDelayTimer() {
if (this.delayTimer) {
cancelAnimationTimeout(this.delayTimer);
this.delayTimer = null;
}
},
clearOutsideHandler() {
if (this.clickOutsideHandler) {
this.clickOutsideHandler.remove();
this.clickOutsideHandler = null;
}
if (this.contextmenuOutsideHandler1) {
this.contextmenuOutsideHandler1.remove();
this.contextmenuOutsideHandler1 = null;
}
if (this.contextmenuOutsideHandler2) {
this.contextmenuOutsideHandler2.remove();
this.contextmenuOutsideHandler2 = null;
}
if (this.touchOutsideHandler) {
this.touchOutsideHandler.remove();
this.touchOutsideHandler = null;
}
},
createTwoChains(event) {
let fn = () => {};
const events = getListeners(this);
if (this.childOriginEvents[event] && events[event]) {
return this[`fire${event}`];
}
fn = this.childOriginEvents[event] || events[event] || fn;
return fn;
},
isClickToShow() {
const { action, showAction } = this.$props;
return action.indexOf('click') !== -1 || showAction.indexOf('click') !== -1;
},
isContextmenuToShow() {
const { action, showAction } = this.$props;
return action.indexOf('contextmenu') !== -1 || showAction.indexOf('contextmenu') !== -1;
},
isClickToHide() {
const { action, hideAction } = this.$props;
return action.indexOf('click') !== -1 || hideAction.indexOf('click') !== -1;
},
isMouseEnterToShow() {
const { action, showAction } = this.$props;
return action.indexOf('hover') !== -1 || showAction.indexOf('mouseenter') !== -1;
},
isMouseLeaveToHide() {
const { action, hideAction } = this.$props;
return action.indexOf('hover') !== -1 || hideAction.indexOf('mouseleave') !== -1;
},
isFocusToShow() {
const { action, showAction } = this.$props;
return action.indexOf('focus') !== -1 || showAction.indexOf('focus') !== -1;
},
isBlurToHide() {
const { action, hideAction } = this.$props;
return action.indexOf('focus') !== -1 || hideAction.indexOf('blur') !== -1;
},
forcePopupAlign() {
if (this.$data.sPopupVisible && this._component && this._component.$refs.alignInstance) {
this._component.$refs.alignInstance.forceAlign();
}
},
fireEvents(type, e) {
if (this.childOriginEvents[type]) {
this.childOriginEvents[type](e);
}
this.__emit(type, e);
},
close() {
this.setPopupVisible(false);
},
},
render() {
const { sPopupVisible } = this;
const children = filterEmpty(this.$slots.default);
const { forceRender, alignPoint } = this.$props;
if (children.length > 1) {
warning(false, 'Trigger $slots.default.length > 1, just support only one default', true);
}
const child = children[0];
this.childOriginEvents = getEvents(child);
const newChildProps = {
props: {},
on: {},
key: 'trigger',
};
if (this.isContextmenuToShow()) {
newChildProps.on.contextmenu = this.onContextmenu;
} else {
newChildProps.on.contextmenu = this.createTwoChains('contextmenu');
}
if (this.isClickToHide() || this.isClickToShow()) {
newChildProps.on.click = this.onClick;
newChildProps.on.mousedown = this.onMousedown;
newChildProps.on.touchstart = this.onTouchstart;
} else {
newChildProps.on.click = this.createTwoChains('click');
newChildProps.on.mousedown = this.createTwoChains('mousedown');
newChildProps.on.touchstart = this.createTwoChains('onTouchstart');
}
if (this.isMouseEnterToShow()) {
newChildProps.on.mouseenter = this.onMouseenter;
if (alignPoint) {
newChildProps.on.mousemove = this.onMouseMove;
}
} else {
newChildProps.on.mouseenter = this.createTwoChains('mouseenter');
}
if (this.isMouseLeaveToHide()) {
newChildProps.on.mouseleave = this.onMouseleave;
} else {
newChildProps.on.mouseleave = this.createTwoChains('mouseleave');
}
if (this.isFocusToShow() || this.isBlurToHide()) {
newChildProps.on.focus = this.onFocus;
newChildProps.on.blur = this.onBlur;
} else {
newChildProps.on.focus = this.createTwoChains('focus');
newChildProps.on.blur = e => {
if (e && (!e.relatedTarget || !contains(e.target, e.relatedTarget))) {
this.createTwoChains('blur')(e);
}
};
}
const trigger = cloneElement(child, newChildProps);
let portal;
// prevent unmounting after it's rendered
if (sPopupVisible || this._component || forceRender) {
portal = (
<Portal
key="portal"
children={this.getComponent()}
getContainer={this.getContainer}
didUpdate={this.handlePortalUpdate}
></Portal>
);
}
return portal
? cloneElement(trigger, {
children: [
...((trigger.componentOptions ? trigger.componentOptions.children : trigger.children) ||
[]),
portal,
],
})
: trigger;
},
};