index.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import React from 'react';
  2. import { cloneDeepWith, set, get } from 'lodash';
  3. import warning from '@douyinfe/semi-foundation/utils/warning';
  4. import { findAll } from '@douyinfe/semi-foundation/utils/getHighlight';
  5. import { isHTMLElement } from '@douyinfe/semi-foundation/utils/dom';
  6. /**
  7. * stop propagation
  8. *
  9. * @param {React.MouseEvent<HTMLElement>} e React mouse event object
  10. * @param {boolean} noImmediate Skip stopping immediate propagation
  11. */
  12. export function stopPropagation(e: React.MouseEvent | React.FocusEvent<HTMLElement>, noImmediate?: boolean) {
  13. if (e && typeof e.stopPropagation === 'function') {
  14. e.stopPropagation();
  15. }
  16. if (!noImmediate && e.nativeEvent && typeof e.nativeEvent.stopImmediatePropagation === 'function') {
  17. e.nativeEvent.stopImmediatePropagation();
  18. }
  19. }
  20. /**
  21. * use in Table, Form, Navigation
  22. *
  23. * skip clone function and react element
  24. */
  25. export function cloneDeep<T>(value: T): T;
  26. export function cloneDeep<T>(value: T, customizer: (value: any) => any): any;
  27. export function cloneDeep(value: any, customizer?: (value: any) => any) {
  28. return cloneDeepWith(value, v => {
  29. if (typeof customizer === 'function') {
  30. return customizer(v);
  31. }
  32. if (typeof v === 'function' || React.isValidElement(v)) {
  33. return v;
  34. }
  35. if (Object.prototype.toString.call(v) === '[object Error]') {
  36. return v;
  37. }
  38. // it is tricky
  39. // when array length beyond max length, array.length will be 0
  40. if (Array.isArray(v) && v.length === 0) {
  41. const keys: string[] = Object.keys(v);
  42. if (keys.length) {
  43. const newArray: any[] = [];
  44. keys.forEach(key => {
  45. set(newArray, key, v[key]);
  46. });
  47. // internal-issues:887
  48. try {
  49. warning(
  50. get(process, 'env.NODE_ENV') !== 'production',
  51. `[Semi] You may use an out-of-bounds array. In some cases, your program may not behave as expected.
  52. The maximum length of an array is 4294967295.
  53. Please check whether the array subscript in your data exceeds the maximum value of the JS array subscript`
  54. );
  55. } catch (e) {
  56. }
  57. return newArray;
  58. } else {
  59. return undefined;
  60. }
  61. }
  62. return undefined;
  63. });
  64. }
  65. /**
  66. * [getHighLightTextHTML description]
  67. *
  68. * @param {string} sourceString [source content text]
  69. * @param {Array<string>} searchWords [keywords to be highlighted]
  70. * @param {object} option
  71. * @param {true} option.highlightTag [The tag wrapped by the highlighted content, mark is used by default]
  72. * @param {true} option.highlightClassName
  73. * @param {true} option.highlightStyle
  74. * @param {boolean} option.caseSensitive
  75. *
  76. * @return {Array<object>}
  77. */
  78. export const getHighLightTextHTML = ({
  79. sourceString = '',
  80. searchWords = [],
  81. option = { autoEscape: true, caseSensitive: false }
  82. }: GetHighLightTextHTMLProps) => {
  83. const chunks: HighLightTextHTMLChunk[] = findAll({ sourceString, searchWords, ...option });
  84. const markEle = option.highlightTag || 'mark';
  85. const highlightClassName = option.highlightClassName || '';
  86. const highlightStyle = option.highlightStyle || {};
  87. return chunks.map((chunk: HighLightTextHTMLChunk, index: number) => {
  88. const { end, start, highlight } = chunk;
  89. const text = sourceString.substr(start, end - start);
  90. if (highlight) {
  91. return React.createElement(
  92. markEle,
  93. {
  94. style: highlightStyle,
  95. className: highlightClassName,
  96. key: text + index
  97. },
  98. text
  99. );
  100. } else {
  101. return text;
  102. }
  103. });
  104. };
  105. export interface RegisterMediaQueryOption {
  106. match?: (e: MediaQueryList | MediaQueryListEvent) => void;
  107. unmatch?: (e: MediaQueryList | MediaQueryListEvent) => void;
  108. callInInit?: boolean
  109. }
  110. /**
  111. * register matchFn and unMatchFn callback while media query
  112. * @param {string} media media string
  113. * @param {object} param param object
  114. * @returns function
  115. */
  116. export const registerMediaQuery = (media: string, { match, unmatch, callInInit = true }: RegisterMediaQueryOption): () => void => {
  117. if (typeof window !== 'undefined') {
  118. const mediaQueryList = window.matchMedia(media);
  119. function handlerMediaChange(e: MediaQueryList | MediaQueryListEvent): void {
  120. if (e.matches) {
  121. match && match(e);
  122. } else {
  123. unmatch && unmatch(e);
  124. }
  125. }
  126. callInInit && handlerMediaChange(mediaQueryList);
  127. if (Object.prototype.hasOwnProperty.call(mediaQueryList, 'addEventListener')) {
  128. mediaQueryList.addEventListener('change', handlerMediaChange);
  129. return (): void => mediaQueryList.removeEventListener('change', handlerMediaChange);
  130. }
  131. mediaQueryList.addListener(handlerMediaChange);
  132. return (): void => mediaQueryList.removeListener(handlerMediaChange);
  133. }
  134. return () => undefined;
  135. };
  136. export interface GetHighLightTextHTMLProps {
  137. sourceString?: string;
  138. searchWords?: string[];
  139. option: HighLightTextHTMLOption
  140. }
  141. export interface HighLightTextHTMLOption {
  142. highlightTag?: string;
  143. highlightClassName?: string;
  144. highlightStyle?: React.CSSProperties;
  145. caseSensitive: boolean;
  146. autoEscape: boolean
  147. }
  148. export interface HighLightTextHTMLChunk {
  149. start?: number;
  150. end?: number;
  151. highlight?: any
  152. }
  153. /**
  154. * Determine whether the incoming element is a built-in icon
  155. * @param icon 元素
  156. * @returns boolean
  157. */
  158. export const isSemiIcon = (icon: any): boolean => React.isValidElement(icon) && get(icon.type, 'elementType') === 'Icon';
  159. export function getActiveElement(): HTMLElement | null {
  160. return document ? document.activeElement as HTMLElement : null;
  161. }
  162. export function isNodeContainsFocus(node: HTMLElement) {
  163. const activeElement = getActiveElement();
  164. return activeElement === node || node.contains(activeElement);
  165. }
  166. export function getFocusableElements(node: HTMLElement) {
  167. if (!isHTMLElement(node)) {
  168. return [];
  169. }
  170. const focusableSelectorsList = [
  171. "input:not([disabled]):not([tabindex='-1'])",
  172. "textarea:not([disabled]):not([tabindex='-1'])",
  173. "button:not([disabled]):not([tabindex='-1'])",
  174. "a[href]:not([tabindex='-1'])",
  175. "select:not([disabled]):not([tabindex='-1'])",
  176. "area[href]:not([tabindex='-1'])",
  177. "iframe:not([tabindex='-1'])",
  178. "object:not([tabindex='-1'])",
  179. "*[tabindex]:not([tabindex='-1'])",
  180. "*[contenteditable]:not([tabindex='-1'])",
  181. ];
  182. const focusableSelectorsStr = focusableSelectorsList.join(',');
  183. // we are not filtered elements which are invisible
  184. const focusableElements = Array.from(node.querySelectorAll<HTMLElement>(focusableSelectorsStr));
  185. return focusableElements;
  186. }
  187. export function getScrollbarWidth() {
  188. if (globalThis && Object.prototype.toString.call(globalThis) === '[object Window]') {
  189. return window.innerWidth - document.documentElement.clientWidth;
  190. }
  191. return 0;
  192. }