Overflow.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
  2. import _extends from "@babel/runtime/helpers/esm/extends";
  3. import { resolveDirective as _resolveDirective, createVNode as _createVNode } from "vue";
  4. var __rest = this && this.__rest || function (s, e) {
  5. var t = {};
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  7. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  8. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  9. }
  10. return t;
  11. };
  12. import { computed, defineComponent, shallowRef, watch } from 'vue';
  13. import ResizeObserver from '../vc-resize-observer';
  14. import classNames from '../_util/classNames';
  15. import PropTypes from '../_util/vue-types';
  16. import { OverflowContextProvider } from './context';
  17. import Item from './Item';
  18. import RawItem from './RawItem';
  19. const RESPONSIVE = 'responsive';
  20. const INVALIDATE = 'invalidate';
  21. function defaultRenderRest(omittedItems) {
  22. return `+ ${omittedItems.length} ...`;
  23. }
  24. const overflowProps = () => {
  25. return {
  26. id: String,
  27. prefixCls: String,
  28. data: Array,
  29. itemKey: [String, Number, Function],
  30. /** Used for `responsive`. It will limit render node to avoid perf issue */
  31. itemWidth: {
  32. type: Number,
  33. default: 10
  34. },
  35. renderItem: Function,
  36. /** @private Do not use in your production. Render raw node that need wrap Item by developer self */
  37. renderRawItem: Function,
  38. maxCount: [Number, String],
  39. renderRest: Function,
  40. /** @private Do not use in your production. Render raw node that need wrap Item by developer self */
  41. renderRawRest: Function,
  42. suffix: PropTypes.any,
  43. component: String,
  44. itemComponent: PropTypes.any,
  45. /** @private This API may be refactor since not well design */
  46. onVisibleChange: Function,
  47. /** When set to `full`, ssr will render full items by default and remove at client side */
  48. ssr: String,
  49. onMousedown: Function,
  50. role: String
  51. };
  52. };
  53. const Overflow = defineComponent({
  54. name: 'Overflow',
  55. inheritAttrs: false,
  56. props: overflowProps(),
  57. emits: ['visibleChange'],
  58. setup(props, _ref) {
  59. let {
  60. attrs,
  61. emit,
  62. slots
  63. } = _ref;
  64. const fullySSR = computed(() => props.ssr === 'full');
  65. const containerWidth = shallowRef(null);
  66. const mergedContainerWidth = computed(() => containerWidth.value || 0);
  67. const itemWidths = shallowRef(new Map());
  68. const prevRestWidth = shallowRef(0);
  69. const restWidth = shallowRef(0);
  70. const suffixWidth = shallowRef(0);
  71. const suffixFixedStart = shallowRef(null);
  72. const displayCount = shallowRef(null);
  73. const mergedDisplayCount = computed(() => {
  74. if (displayCount.value === null && fullySSR.value) {
  75. return Number.MAX_SAFE_INTEGER;
  76. }
  77. return displayCount.value || 0;
  78. });
  79. const restReady = shallowRef(false);
  80. const itemPrefixCls = computed(() => `${props.prefixCls}-item`);
  81. // Always use the max width to avoid blink
  82. const mergedRestWidth = computed(() => Math.max(prevRestWidth.value, restWidth.value));
  83. // ================================= Data =================================
  84. const isResponsive = computed(() => !!(props.data.length && props.maxCount === RESPONSIVE));
  85. const invalidate = computed(() => props.maxCount === INVALIDATE);
  86. /**
  87. * When is `responsive`, we will always render rest node to get the real width of it for calculation
  88. */
  89. const showRest = computed(() => isResponsive.value || typeof props.maxCount === 'number' && props.data.length > props.maxCount);
  90. const mergedData = computed(() => {
  91. let items = props.data;
  92. if (isResponsive.value) {
  93. if (containerWidth.value === null && fullySSR.value) {
  94. items = props.data;
  95. } else {
  96. items = props.data.slice(0, Math.min(props.data.length, mergedContainerWidth.value / props.itemWidth));
  97. }
  98. } else if (typeof props.maxCount === 'number') {
  99. items = props.data.slice(0, props.maxCount);
  100. }
  101. return items;
  102. });
  103. const omittedItems = computed(() => {
  104. if (isResponsive.value) {
  105. return props.data.slice(mergedDisplayCount.value + 1);
  106. }
  107. return props.data.slice(mergedData.value.length);
  108. });
  109. // ================================= Item =================================
  110. const getKey = (item, index) => {
  111. var _a;
  112. if (typeof props.itemKey === 'function') {
  113. return props.itemKey(item);
  114. }
  115. return (_a = props.itemKey && (item === null || item === void 0 ? void 0 : item[props.itemKey])) !== null && _a !== void 0 ? _a : index;
  116. };
  117. const mergedRenderItem = computed(() => props.renderItem || (item => item));
  118. const updateDisplayCount = (count, notReady) => {
  119. displayCount.value = count;
  120. if (!notReady) {
  121. restReady.value = count < props.data.length - 1;
  122. emit('visibleChange', count);
  123. }
  124. };
  125. // ================================= Size =================================
  126. const onOverflowResize = (_, element) => {
  127. containerWidth.value = element.clientWidth;
  128. };
  129. const registerSize = (key, width) => {
  130. const clone = new Map(itemWidths.value);
  131. if (width === null) {
  132. clone.delete(key);
  133. } else {
  134. clone.set(key, width);
  135. }
  136. itemWidths.value = clone;
  137. };
  138. const registerOverflowSize = (_, width) => {
  139. prevRestWidth.value = restWidth.value;
  140. restWidth.value = width;
  141. };
  142. const registerSuffixSize = (_, width) => {
  143. suffixWidth.value = width;
  144. };
  145. // ================================ Effect ================================
  146. const getItemWidth = index => {
  147. return itemWidths.value.get(getKey(mergedData.value[index], index));
  148. };
  149. watch([mergedContainerWidth, itemWidths, restWidth, suffixWidth, () => props.itemKey, mergedData], () => {
  150. if (mergedContainerWidth.value && mergedRestWidth.value && mergedData.value) {
  151. let totalWidth = suffixWidth.value;
  152. const len = mergedData.value.length;
  153. const lastIndex = len - 1;
  154. // When data count change to 0, reset this since not loop will reach
  155. if (!len) {
  156. updateDisplayCount(0);
  157. suffixFixedStart.value = null;
  158. return;
  159. }
  160. for (let i = 0; i < len; i += 1) {
  161. const currentItemWidth = getItemWidth(i);
  162. // Break since data not ready
  163. if (currentItemWidth === undefined) {
  164. updateDisplayCount(i - 1, true);
  165. break;
  166. }
  167. // Find best match
  168. totalWidth += currentItemWidth;
  169. if (
  170. // Only one means `totalWidth` is the final width
  171. lastIndex === 0 && totalWidth <= mergedContainerWidth.value ||
  172. // Last two width will be the final width
  173. i === lastIndex - 1 && totalWidth + getItemWidth(lastIndex) <= mergedContainerWidth.value) {
  174. // Additional check if match the end
  175. updateDisplayCount(lastIndex);
  176. suffixFixedStart.value = null;
  177. break;
  178. } else if (totalWidth + mergedRestWidth.value > mergedContainerWidth.value) {
  179. // Can not hold all the content to show rest
  180. updateDisplayCount(i - 1);
  181. suffixFixedStart.value = totalWidth - currentItemWidth - suffixWidth.value + restWidth.value;
  182. break;
  183. }
  184. }
  185. if (props.suffix && getItemWidth(0) + suffixWidth.value > mergedContainerWidth.value) {
  186. suffixFixedStart.value = null;
  187. }
  188. }
  189. });
  190. return () => {
  191. // ================================ Render ================================
  192. const displayRest = restReady.value && !!omittedItems.value.length;
  193. const {
  194. itemComponent,
  195. renderRawItem,
  196. renderRawRest,
  197. renderRest,
  198. prefixCls = 'rc-overflow',
  199. suffix,
  200. component: Component = 'div',
  201. id,
  202. onMousedown
  203. } = props;
  204. const {
  205. class: className,
  206. style
  207. } = attrs,
  208. restAttrs = __rest(attrs, ["class", "style"]);
  209. let suffixStyle = {};
  210. if (suffixFixedStart.value !== null && isResponsive.value) {
  211. suffixStyle = {
  212. position: 'absolute',
  213. left: `${suffixFixedStart.value}px`,
  214. top: 0
  215. };
  216. }
  217. const itemSharedProps = {
  218. prefixCls: itemPrefixCls.value,
  219. responsive: isResponsive.value,
  220. component: itemComponent,
  221. invalidate: invalidate.value
  222. };
  223. // >>>>> Choice render fun by `renderRawItem`
  224. const internalRenderItemNode = renderRawItem ? (item, index) => {
  225. const key = getKey(item, index);
  226. return _createVNode(OverflowContextProvider, {
  227. "key": key,
  228. "value": _extends(_extends({}, itemSharedProps), {
  229. order: index,
  230. item,
  231. itemKey: key,
  232. registerSize,
  233. display: index <= mergedDisplayCount.value
  234. })
  235. }, {
  236. default: () => [renderRawItem(item, index)]
  237. });
  238. } : (item, index) => {
  239. const key = getKey(item, index);
  240. return _createVNode(Item, _objectSpread(_objectSpread({}, itemSharedProps), {}, {
  241. "order": index,
  242. "key": key,
  243. "item": item,
  244. "renderItem": mergedRenderItem.value,
  245. "itemKey": key,
  246. "registerSize": registerSize,
  247. "display": index <= mergedDisplayCount.value
  248. }), null);
  249. };
  250. // >>>>> Rest node
  251. let restNode = () => null;
  252. const restContextProps = {
  253. order: displayRest ? mergedDisplayCount.value : Number.MAX_SAFE_INTEGER,
  254. className: `${itemPrefixCls.value} ${itemPrefixCls.value}-rest`,
  255. registerSize: registerOverflowSize,
  256. display: displayRest
  257. };
  258. if (!renderRawRest) {
  259. const mergedRenderRest = renderRest || defaultRenderRest;
  260. restNode = () => _createVNode(Item, _objectSpread(_objectSpread({}, itemSharedProps), restContextProps), {
  261. default: () => typeof mergedRenderRest === 'function' ? mergedRenderRest(omittedItems.value) : mergedRenderRest
  262. });
  263. } else if (renderRawRest) {
  264. restNode = () => _createVNode(OverflowContextProvider, {
  265. "value": _extends(_extends({}, itemSharedProps), restContextProps)
  266. }, {
  267. default: () => [renderRawRest(omittedItems.value)]
  268. });
  269. }
  270. const overflowNode = () => {
  271. var _a;
  272. return _createVNode(Component, _objectSpread({
  273. "id": id,
  274. "class": classNames(!invalidate.value && prefixCls, className),
  275. "style": style,
  276. "onMousedown": onMousedown,
  277. "role": props.role
  278. }, restAttrs), {
  279. default: () => [mergedData.value.map(internalRenderItemNode), showRest.value ? restNode() : null, suffix && _createVNode(Item, _objectSpread(_objectSpread({}, itemSharedProps), {}, {
  280. "order": mergedDisplayCount.value,
  281. "class": `${itemPrefixCls.value}-suffix`,
  282. "registerSize": registerSuffixSize,
  283. "display": true,
  284. "style": suffixStyle
  285. }), {
  286. default: () => suffix
  287. }), (_a = slots.default) === null || _a === void 0 ? void 0 : _a.call(slots)]
  288. });
  289. };
  290. // 使用 disabled 避免结构不一致 导致子组件 rerender
  291. return _createVNode(ResizeObserver, {
  292. "disabled": !isResponsive.value,
  293. "onResize": onOverflowResize
  294. }, {
  295. default: overflowNode
  296. });
  297. };
  298. }
  299. });
  300. Overflow.Item = RawItem;
  301. Overflow.RESPONSIVE = RESPONSIVE;
  302. Overflow.INVALIDATE = INVALIDATE;
  303. export default Overflow;