Overflow.js 12 KB

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