util.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import ReactDOM from 'react-dom';
  2. import React from 'react';
  3. import { omit } from 'lodash';
  4. /**
  5. * The logic of JS for text truncation is referenced from antd typography
  6. * https://github.com/ant-design/ant-design/blob/master/components/typography/util.tsx
  7. *
  8. * For more thinking and analysis about this function, please refer to Feishu document
  9. * https://bytedance.feishu.cn/docs/doccnqovjjyoKm2U5O13bj30aTh
  10. */
  11. let ellipsisContainer: HTMLElement;
  12. function pxToNumber(value: string) {
  13. if (!value) {
  14. return 0;
  15. }
  16. const match = value.match(/^\d*(\.\d*)?/);
  17. return match ? Number(match[0]) : 0;
  18. }
  19. function styleToString(style: CSSStyleDeclaration): string {
  20. // There are some different behavior between Firefox & Chrome.
  21. // We have to handle this ourself.
  22. const styleNames = Array.prototype.slice.apply(style);
  23. return styleNames.map((name: string) => `${name}: ${style.getPropertyValue(name)};`).join('');
  24. }
  25. const getRenderText = (
  26. originEle: HTMLElement,
  27. rows: number,
  28. content = '',
  29. fixedContent: {
  30. expand: Node;
  31. copy: Node
  32. },
  33. ellipsisStr: string,
  34. suffix: string,
  35. ellipsisPos: string
  36. ) => {
  37. if (content.length === 0) {
  38. return '';
  39. }
  40. if (!ellipsisContainer) {
  41. ellipsisContainer = document.createElement('div');
  42. ellipsisContainer.setAttribute('aria-hidden', 'true');
  43. document.body.appendChild(ellipsisContainer);
  44. }
  45. // Get origin style
  46. const originStyle = window.getComputedStyle(originEle);
  47. const originCSS = styleToString(originStyle);
  48. const lineHeight = pxToNumber(originStyle.lineHeight);
  49. const maxHeight = Math.round(
  50. lineHeight * (rows + 1) +
  51. pxToNumber(originStyle.paddingTop) +
  52. pxToNumber(originStyle.paddingBottom)
  53. );
  54. // Set shadow
  55. ellipsisContainer.setAttribute('style', originCSS);
  56. ellipsisContainer.style.position = 'fixed';
  57. ellipsisContainer.style.left = '0';
  58. ellipsisContainer.style.height = 'auto';
  59. ellipsisContainer.style.top = '-999999px';
  60. ellipsisContainer.style.zIndex = '-1000';
  61. // clean up css overflow
  62. ellipsisContainer.style.textOverflow = 'clip';
  63. ellipsisContainer.style.webkitLineClamp = 'none';
  64. // Render fake container
  65. ReactDOM.render(
  66. <></>,
  67. ellipsisContainer
  68. );
  69. // Check if ellipsis in measure div is enough for content
  70. function inRange() {
  71. // If content does not wrap due to line break strategy, width should be judged to determine whether it's in range
  72. const widthInRange = ellipsisContainer.scrollWidth <= ellipsisContainer.offsetWidth;
  73. const heightInRange = ellipsisContainer.scrollHeight < maxHeight;
  74. return rows === 1 ? widthInRange && heightInRange : heightInRange;
  75. }
  76. // ========================= Find match ellipsis content =========================
  77. // Create origin content holder
  78. const ellipsisContentHolder = document.createElement('span');
  79. const textNode = document.createTextNode(content);
  80. ellipsisContentHolder.appendChild(textNode);
  81. if (suffix.length > 0) {
  82. const ellipsisTextNode = document.createTextNode(suffix);
  83. ellipsisContentHolder.appendChild(ellipsisTextNode);
  84. }
  85. ellipsisContainer.appendChild(ellipsisContentHolder);
  86. // Expand node needs to be added only when text needTruncated
  87. Object.values(omit(fixedContent, 'expand')).map(
  88. node => node && ellipsisContainer.appendChild(node.cloneNode(true))
  89. );
  90. function appendExpandNode() {
  91. ellipsisContainer.innerHTML = '';
  92. ellipsisContainer.appendChild(ellipsisContentHolder);
  93. Object.values(fixedContent).map(node => node && ellipsisContainer.appendChild(node.cloneNode(true)));
  94. }
  95. function getCurrentText(text: string, pos: number) {
  96. const end = text.length;
  97. if (!pos) {
  98. return ellipsisStr;
  99. }
  100. if (ellipsisPos === 'end') {
  101. return text.slice(0, pos) + ellipsisStr;
  102. }
  103. return text.slice(0, pos) + ellipsisStr + text.slice(end - pos, end);
  104. }
  105. // Get maximum text
  106. function measureText(
  107. textNode: Text,
  108. fullText: string,
  109. startLoc = 0,
  110. endLoc = fullText.length,
  111. lastSuccessLoc = 0
  112. ): string {
  113. const midLoc = Math.floor((startLoc + endLoc) / 2);
  114. const currentText = getCurrentText(fullText, midLoc);
  115. textNode.textContent = currentText;
  116. // console.log('calculating....', currentText);
  117. if (startLoc >= endLoc - 1 && endLoc > 0) { // Loop when step is small
  118. for (let step = endLoc; step >= startLoc; step -= 1) {
  119. const currentStepText = getCurrentText(fullText, step);
  120. textNode.textContent = currentStepText;
  121. if (inRange()) {
  122. return currentStepText;
  123. }
  124. }
  125. } else if (endLoc === 0) {
  126. return ellipsisStr;
  127. }
  128. if (inRange()) {
  129. return measureText(textNode, fullText, midLoc, endLoc, midLoc);
  130. }
  131. return measureText(textNode, fullText, startLoc, midLoc, lastSuccessLoc);
  132. }
  133. let resText = content;
  134. // First judge whether the total length of fullText, plus suffix (possible)
  135. // and copied icon (possible) meets expectations?
  136. // If it does not meet expectations, add an expand button to find the largest content that meets size limit
  137. // 首先判断总文本长度,加上可能有的 suffix,复制按钮长度,看结果是否符合预期
  138. // 如果不符合预期,则再加上展开按钮,找最大符合尺寸的内容
  139. if (!inRange()) {
  140. appendExpandNode();
  141. resText = measureText(textNode, content, 0, ellipsisPos === 'middle' ? Math.floor((content.length) / 2) : content.length);
  142. }
  143. ellipsisContainer.innerHTML = '';
  144. return resText;
  145. };
  146. export default getRenderText;