index.tsx 8.9 KB

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