ant-design-vue/components/vc-menu/DOMWrap.jsx
tangjinzhou 73bef787cd
Feat 1.5.0 (#1853)
* feat: add Result component

* fix: update md template tag html>tpl
- fix `result` typo
- update jest `result` snapshots

* refactor: svg file to functional component icon
- update jest snapshot

* feat: add result

* Feat descriptions (#1251)

* feat: add descriptions

* fix: add descriptions types and fix docs

* fix: lint change code

* fix: demo warning

* fix: update demo, snapshot and remove classnames

* test: add descriptions test

* fix: descriptions demo (#1498)

* feat: add page header (#1250)

* feat: add page-header component

* update site: page-header

* ts definition update: page-header

* get page-header props with getComponentFromProp func

* optimize page-header

* doc: add page-header actions.md responsive.md

* breadcrumb itemRender add pure function support

* style: format code

* feat: update style to 3.23.6 from 2.13.6

* feat: update style to 3.26.8 from 3.23.6

* chore: update util

* chore: update util

* feat: update affix

* feat: update alert

* feat: update anchor

* feat: update auto-complete

* feat: update avatar

* feat: update back-top

* feat: update badge

* feat: update button

* feat: update breadcrumb

* feat: update ts

* docs: update doc

* feat: update calendat

* feat: update card

* feat: update carousel

* feat: update carousel

* feat: update checkbox

* feat: update comment

* feat: update config-provider

* docs: update doc

* feat: update collapse

* feat: update locale

* feat: update date-picker

* feat: update divider

* feat: update drawer

* feat: update dropdown

* feat: update rc-trigger

* feat: update dropdown

* feat: update empty

* test: add empty test

* feat: update form

* feat: update form

* feat: update spin

* feat: update grid

* docs: update grid doc

* feat: update icon

* feat: update slider

* feat: update textarea

* feat: update input-number

* feat: update layout

* feat: update list

* feat: update menu

* feat: meaage add key for update content

* feat: modal add closeIcon support

* feat: update notification

* feat: add pagination disabled support

* feat: popconfirm add disabled support

* test: update popover

* feat: progress support custom line-gradiend

* feat: update radio

* test: update radio test

* docs: update rate demo

* feat: skeleton add avatar support number type

* test: add switch test

* test: update statistic test

* fix: input clear icon event

* feat: steps add type、 v-model、subTitle

* feat: delete typography component

* feat: delete Typography style

* perf: update select

* feat: add download transformFile previewFile actio

* docs: update upload

* feat: update  tree-select

* docs: update tree-select

* feat: tree add blockNode selectable

* docs: add tree demo

* test: update snap

* docs: updatedoc

* feat: update tag

* docs: update ad doc

* feat: update tooltip

* feat: update timeline

* feat: time-picker add clearIcon

* docs: update tabs

* feat: transfer support custom children

* test: update transfer test

* feat: update table

* test: update table test

* test: update test

* feat: calendar update locale

* test: update test snap

* feat: add mentions (#1790)

* feat: mentions style

* feat: theme default

* feat: add mentions component

* feat: mentions API

* feat: add unit test for mentions

* feat: update mentions demo

* perf: model and inheritAttrs for mentions

* perf: use getComponentFromProp instead of this.$props

* perf: mentions rm defaultProps

* feat: rm rows in mentionsProps

* fix: mentions keyDown didn't work

* docs: update mentions api

* perf: mentions code

* feat: update mentions

* bump 1.5.0-alpha.1

* feat: pageheader add ghost prop

* docs: update descriptions demo

* chore: page-header add ghost type

* fix: color error

* feat: update to 3.26.12

* fix: some prop default value

* fix(typo): form, carousel, upload. duplicate identifier (#1848)

* Add Mentions Type (#1845)

* feat: add mentions type

* feat: add mentions in ant-design-vue.d.ts

* docs: update doc

* docs: add changelog

* fix: mentions getPopupCotainer value (#1850)

* docs: update doc

* docs: uptate demo

* docs: update demo

* docs: delete demo

* docs: delete doc

* test: update snapshots

* style: format code

* chore: update travis

* docs: update demo

Co-authored-by: Sendya <18x@loacg.com>
Co-authored-by: zkwolf <chenhao5866@gmail.com>
Co-authored-by: drafish <xwlyy1991@163.com>
Co-authored-by: Amour1688 <31695475+Amour1688@users.noreply.github.com>
2020-03-07 19:45:13 +08:00

308 lines
9.1 KiB
Vue

import PropTypes from '../_util/vue-types';
import ResizeObserver from 'resize-observer-polyfill';
import SubMenu from './SubMenu';
import BaseMixin from '../_util/BaseMixin';
import { getWidth, setStyle, menuAllProps } from './util';
import { cloneElement } from '../_util/vnode';
import { getClass, getPropsData, getEvents, getListeners } from '../_util/props-util';
const canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
const MENUITEM_OVERFLOWED_CLASSNAME = 'menuitem-overflowed';
const FLOAT_PRECISION_ADJUST = 0.5;
// Fix ssr
if (canUseDOM) {
require('mutationobserver-shim');
}
const DOMWrap = {
name: 'DOMWrap',
mixins: [BaseMixin],
data() {
this.resizeObserver = null;
this.mutationObserver = null;
// original scroll size of the list
this.originalTotalWidth = 0;
// copy of overflowed items
this.overflowedItems = [];
// cache item of the original items (so we can track the size and order)
this.menuItemSizes = [];
return {
lastVisibleIndex: undefined,
};
},
mounted() {
this.$nextTick(() => {
this.setChildrenWidthAndResize();
if (this.level === 1 && this.mode === 'horizontal') {
const menuUl = this.$el;
if (!menuUl) {
return;
}
this.resizeObserver = new ResizeObserver(entries => {
entries.forEach(this.setChildrenWidthAndResize);
});
[].slice
.call(menuUl.children)
.concat(menuUl)
.forEach(el => {
this.resizeObserver.observe(el);
});
if (typeof MutationObserver !== 'undefined') {
this.mutationObserver = new MutationObserver(() => {
this.resizeObserver.disconnect();
[].slice
.call(menuUl.children)
.concat(menuUl)
.forEach(el => {
this.resizeObserver.observe(el);
});
this.setChildrenWidthAndResize();
});
this.mutationObserver.observe(menuUl, {
attributes: false,
childList: true,
subTree: false,
});
}
}
});
},
beforeDestroy() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
if (this.mutationObserver) {
this.mutationObserver.disconnect();
}
},
methods: {
// get all valid menuItem nodes
getMenuItemNodes() {
const { prefixCls } = this.$props;
const ul = this.$el;
if (!ul) {
return [];
}
// filter out all overflowed indicator placeholder
return [].slice
.call(ul.children)
.filter(node => node.className.split(' ').indexOf(`${prefixCls}-overflowed-submenu`) < 0);
},
getOverflowedSubMenuItem(keyPrefix, overflowedItems, renderPlaceholder) {
const { overflowedIndicator, level, mode, prefixCls, theme } = this.$props;
if (level !== 1 || mode !== 'horizontal') {
return null;
}
// put all the overflowed item inside a submenu
// with a title of overflow indicator ('...')
const copy = this.$slots.default[0];
const { title, ...rest } = getPropsData(copy); // eslint-disable-line no-unused-vars
let style = {};
let key = `${keyPrefix}-overflowed-indicator`;
let eventKey = `${keyPrefix}-overflowed-indicator`;
if (overflowedItems.length === 0 && renderPlaceholder !== true) {
style = {
display: 'none',
};
} else if (renderPlaceholder) {
style = {
visibility: 'hidden',
// prevent from taking normal dom space
position: 'absolute',
};
key = `${key}-placeholder`;
eventKey = `${eventKey}-placeholder`;
}
const popupClassName = theme ? `${prefixCls}-${theme}` : '';
const props = {};
menuAllProps.props.forEach(k => {
if (rest[k] !== undefined) {
props[k] = rest[k];
}
});
const subMenuProps = {
props: {
title: overflowedIndicator,
popupClassName,
...props,
eventKey,
disabled: false,
},
class: `${prefixCls}-overflowed-submenu`,
key,
style,
on: getEvents(copy),
};
return <SubMenu {...subMenuProps}>{overflowedItems}</SubMenu>;
},
// memorize rendered menuSize
setChildrenWidthAndResize() {
if (this.mode !== 'horizontal') {
return;
}
const ul = this.$el;
if (!ul) {
return;
}
const ulChildrenNodes = ul.children;
if (!ulChildrenNodes || ulChildrenNodes.length === 0) {
return;
}
const lastOverflowedIndicatorPlaceholder = ul.children[ulChildrenNodes.length - 1];
// need last overflowed indicator for calculating length;
setStyle(lastOverflowedIndicatorPlaceholder, 'display', 'inline-block');
const menuItemNodes = this.getMenuItemNodes();
// reset display attribute for all hidden elements caused by overflow to calculate updated width
// and then reset to original state after width calculation
const overflowedItems = menuItemNodes.filter(
c => c.className.split(' ').indexOf(MENUITEM_OVERFLOWED_CLASSNAME) >= 0,
);
overflowedItems.forEach(c => {
setStyle(c, 'display', 'inline-block');
});
this.menuItemSizes = menuItemNodes.map(c => getWidth(c));
overflowedItems.forEach(c => {
setStyle(c, 'display', 'none');
});
this.overflowedIndicatorWidth = getWidth(ul.children[ul.children.length - 1]);
this.originalTotalWidth = this.menuItemSizes.reduce((acc, cur) => acc + cur, 0);
this.handleResize();
// prevent the overflowed indicator from taking space;
setStyle(lastOverflowedIndicatorPlaceholder, 'display', 'none');
},
handleResize() {
if (this.mode !== 'horizontal') {
return;
}
const ul = this.$el;
if (!ul) {
return;
}
const width = getWidth(ul);
this.overflowedItems = [];
let currentSumWidth = 0;
// index for last visible child in horizontal mode
let lastVisibleIndex;
// float number comparison could be problematic
// e.g. 0.1 + 0.2 > 0.3 =====> true
// thus using FLOAT_PRECISION_ADJUST as buffer to help the situation
if (this.originalTotalWidth > width + FLOAT_PRECISION_ADJUST) {
lastVisibleIndex = -1;
this.menuItemSizes.forEach(liWidth => {
currentSumWidth += liWidth;
if (currentSumWidth + this.overflowedIndicatorWidth <= width) {
lastVisibleIndex += 1;
}
});
}
this.setState({ lastVisibleIndex });
},
renderChildren(children) {
// need to take care of overflowed items in horizontal mode
const { lastVisibleIndex } = this.$data;
const className = getClass(this);
return (children || []).reduce((acc, childNode, index) => {
let item = childNode;
const eventKey = getPropsData(childNode).eventKey;
if (this.mode === 'horizontal') {
let overflowed = this.getOverflowedSubMenuItem(eventKey, []);
if (lastVisibleIndex !== undefined && className[`${this.prefixCls}-root`] !== -1) {
if (index > lastVisibleIndex) {
item = cloneElement(
childNode,
// 这里修改 eventKey 是为了防止隐藏状态下还会触发 openkeys 事件
{
style: { display: 'none' },
props: { eventKey: `${eventKey}-hidden` },
class: MENUITEM_OVERFLOWED_CLASSNAME,
},
);
}
if (index === lastVisibleIndex + 1) {
this.overflowedItems = children.slice(lastVisibleIndex + 1).map(c => {
return cloneElement(
c,
// children[index].key will become '.$key' in clone by default,
// we have to overwrite with the correct key explicitly
{ key: getPropsData(c).eventKey, props: { mode: 'vertical-left' } },
);
});
overflowed = this.getOverflowedSubMenuItem(eventKey, this.overflowedItems);
}
}
const ret = [...acc, overflowed, item];
if (index === children.length - 1) {
// need a placeholder for calculating overflowed indicator width
ret.push(this.getOverflowedSubMenuItem(eventKey, [], true));
}
return ret;
}
return [...acc, item];
}, []);
},
},
render() {
const Tag = this.$props.tag;
const tagProps = {
on: getListeners(this),
};
return <Tag {...tagProps}>{this.renderChildren(this.$slots.default)}</Tag>;
},
};
DOMWrap.props = {
mode: PropTypes.oneOf(['horizontal', 'vertical', 'vertical-left', 'vertical-right', 'inline']),
prefixCls: PropTypes.string,
level: PropTypes.number,
theme: PropTypes.string,
overflowedIndicator: PropTypes.node,
visible: PropTypes.bool,
hiddenClassName: PropTypes.string,
tag: PropTypes.string.def('div'),
};
export default DOMWrap;