index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import React from 'react';
  2. import classNames from 'classnames';
  3. import JsonViewerFoundation, {
  4. JsonViewerOptions,
  5. JsonViewerAdapter,
  6. } from '@douyinfe/semi-foundation/jsonViewer/foundation';
  7. import '@douyinfe/semi-foundation/jsonViewer/jsonViewer.scss';
  8. import { cssClasses } from '@douyinfe/semi-foundation/jsonViewer/constants';
  9. import ButtonGroup from '../button/buttonGroup';
  10. import Button from '../button';
  11. import Input from '../input';
  12. import DragMove from '../dragMove';
  13. import {
  14. IconCaseSensitive,
  15. IconChevronLeft,
  16. IconChevronRight,
  17. IconClose,
  18. IconRegExp,
  19. IconSearch,
  20. IconWholeWord,
  21. } from '@douyinfe/semi-icons';
  22. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  23. import { createPortal } from 'react-dom';
  24. import { isEqual } from "lodash";
  25. import LocaleConsumer from '../locale/localeConsumer';
  26. import { Locale } from '../locale/interface';
  27. const prefixCls = cssClasses.PREFIX;
  28. export type { JsonViewerOptions };
  29. export interface JsonViewerProps extends BaseProps {
  30. value: string;
  31. width: number | string;
  32. height: number | string;
  33. showSearch?: boolean;
  34. className?: string;
  35. style?: React.CSSProperties;
  36. onChange?: (value: string) => void;
  37. renderTooltip?: (value: string, el: HTMLElement) => HTMLElement;
  38. options?: JsonViewerOptions
  39. }
  40. export interface JsonViewerState {
  41. searchOptions: SearchOptions;
  42. showSearchBar: boolean;
  43. customRenderMap: Map<HTMLElement, React.ReactNode>
  44. }
  45. export interface SearchOptions {
  46. caseSensitive: boolean;
  47. wholeWord: boolean;
  48. regex: boolean
  49. }
  50. class JsonViewerCom extends BaseComponent<JsonViewerProps, JsonViewerState> {
  51. static defaultProps: Partial<JsonViewerProps> = {
  52. width: 400,
  53. height: 400,
  54. value: '',
  55. options: {
  56. readOnly: false,
  57. autoWrap: true
  58. }
  59. };
  60. private editorRef: React.RefObject<HTMLDivElement>;
  61. private searchInputRef: React.RefObject<HTMLInputElement>;
  62. private replaceInputRef: React.RefObject<HTMLInputElement>;
  63. private isComposing: boolean = false;
  64. foundation: JsonViewerFoundation;
  65. constructor(props: JsonViewerProps) {
  66. super(props);
  67. this.editorRef = React.createRef();
  68. this.searchInputRef = React.createRef();
  69. this.replaceInputRef = React.createRef();
  70. this.foundation = new JsonViewerFoundation(this.adapter);
  71. this.state = {
  72. searchOptions: {
  73. caseSensitive: false,
  74. wholeWord: false,
  75. regex: false,
  76. },
  77. showSearchBar: false,
  78. customRenderMap: new Map(),
  79. };
  80. }
  81. componentDidMount() {
  82. this.foundation.init();
  83. }
  84. componentDidUpdate(prevProps: JsonViewerProps): void {
  85. if (!isEqual(prevProps.options, this.props.options) || this.props.value !== prevProps.value) {
  86. this.foundation.jsonViewer.dispose();
  87. this.foundation.init();
  88. }
  89. }
  90. get adapter(): JsonViewerAdapter<JsonViewerProps, JsonViewerState> {
  91. return {
  92. ...super.adapter,
  93. getEditorRef: () => this.editorRef.current,
  94. getSearchRef: () => this.searchInputRef.current,
  95. notifyChange: value => {
  96. this.props.onChange?.(value);
  97. },
  98. notifyHover: (value, el) => {
  99. const res = this.props.renderTooltip?.(value, el);
  100. return res;
  101. },
  102. notifyCustomRender: (customRenderMap) => {
  103. this.setState({ customRenderMap });
  104. },
  105. setSearchOptions: (key: string) => {
  106. this.setState(
  107. {
  108. searchOptions: {
  109. ...this.state.searchOptions,
  110. [key]: !this.state.searchOptions[key],
  111. },
  112. },
  113. () => {
  114. this.searchHandler();
  115. }
  116. );
  117. },
  118. showSearchBar: () => {
  119. this.setState({ showSearchBar: !this.state.showSearchBar });
  120. this.setState({ searchOptions: {
  121. caseSensitive: false,
  122. wholeWord: false,
  123. regex: false,
  124. } });
  125. },
  126. };
  127. }
  128. getValue() {
  129. return this.foundation.jsonViewer.getModel().getValue();
  130. }
  131. format() {
  132. this.foundation.jsonViewer.format();
  133. }
  134. search(searchText: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) {
  135. this.foundation.search(searchText, caseSensitive, wholeWord, regex);
  136. }
  137. getSearchResults() {
  138. return this.foundation.getSearchResults();
  139. }
  140. prevSearch(step?: number) {
  141. this.foundation.prevSearch(step);
  142. }
  143. nextSearch(step?: number) {
  144. this.foundation.nextSearch(step);
  145. }
  146. replace(replaceText: string) {
  147. this.foundation.replace(replaceText);
  148. }
  149. replaceAll(replaceText: string) {
  150. this.foundation.replaceAll(replaceText);
  151. }
  152. getStyle() {
  153. const { width, height } = this.props;
  154. return {
  155. width,
  156. height,
  157. };
  158. }
  159. searchHandler = () => {
  160. const value = this.searchInputRef.current?.value;
  161. this.foundation.search(value);
  162. };
  163. changeSearchOptions = (key: string) => {
  164. this.foundation.setSearchOptions(key);
  165. };
  166. renderSearchBox() {
  167. return (
  168. <div className={`${prefixCls}-search-bar-container`} style={{ position: 'absolute', top: 20, right: 20 }}>
  169. {this.renderSearchBar()}
  170. {this.renderReplaceBar()}
  171. </div>
  172. );
  173. }
  174. renderSearchOptions() {
  175. const searchOptionItems = [
  176. {
  177. key: 'caseSensitive',
  178. icon: IconCaseSensitive,
  179. },
  180. {
  181. key: 'regex',
  182. icon: IconRegExp,
  183. },
  184. {
  185. key: 'wholeWord',
  186. icon: IconWholeWord,
  187. },
  188. ];
  189. return (
  190. <ul className={`${prefixCls}-search-options`}>
  191. {searchOptionItems.map(({ key, icon: Icon }) => (
  192. <li
  193. key={key}
  194. className={classNames(`${prefixCls}-search-options-item`, {
  195. [`${prefixCls}-search-options-item-active`]: this.state.searchOptions[key],
  196. })}
  197. >
  198. <Icon onClick={() => this.changeSearchOptions(key)} />
  199. </li>
  200. ))}
  201. </ul>
  202. );
  203. }
  204. renderSearchBar() {
  205. return (
  206. <LocaleConsumer
  207. componentName="JsonViewer"
  208. >
  209. {(locale: Locale['JsonViewer'], localeCode: Locale['code']) => (
  210. <div className={`${prefixCls}-search-bar`}>
  211. <Input
  212. placeholder={locale.search}
  213. className={`${prefixCls}-search-bar-input`}
  214. onChange={(_value, e) => {
  215. e.preventDefault();
  216. if (!this.isComposing) {
  217. this.searchHandler();
  218. }
  219. this.searchInputRef.current?.focus();
  220. }}
  221. onCompositionStart={() => {
  222. this.isComposing = true;
  223. }}
  224. onCompositionEnd={() => {
  225. this.isComposing = false;
  226. this.searchHandler();
  227. this.searchInputRef.current?.focus();
  228. }}
  229. ref={this.searchInputRef}
  230. />
  231. {this.renderSearchOptions()}
  232. <ButtonGroup>
  233. <Button
  234. icon={<IconChevronLeft />}
  235. onClick={e => {
  236. e.preventDefault();
  237. this.foundation.prevSearch();
  238. }}
  239. />
  240. <Button
  241. icon={<IconChevronRight />}
  242. onClick={e => {
  243. e.preventDefault();
  244. this.foundation.nextSearch();
  245. }}
  246. />
  247. </ButtonGroup>
  248. <Button
  249. icon={<IconClose />}
  250. size="small"
  251. theme={'borderless'}
  252. type={'tertiary'}
  253. onClick={() => this.foundation.showSearchBar()}
  254. />
  255. </div>
  256. )}
  257. </LocaleConsumer>
  258. );
  259. }
  260. renderReplaceBar() {
  261. const { readOnly } = this.props.options;
  262. return (
  263. <LocaleConsumer
  264. componentName="JsonViewer"
  265. >
  266. {(locale: Locale['JsonViewer'], localeCode: Locale['code']) => (
  267. <div className={`${prefixCls}-replace-bar`}>
  268. <Input
  269. placeholder={locale.replace}
  270. className={`${prefixCls}-replace-bar-input`}
  271. onChange={(value, e) => {
  272. e.preventDefault();
  273. }}
  274. ref={this.replaceInputRef}
  275. />
  276. <Button
  277. style={{ width: 'fit-content' }}
  278. disabled={readOnly}
  279. onClick={() => {
  280. const value = this.replaceInputRef.current?.value;
  281. this.foundation.replace(value);
  282. }}
  283. >
  284. {locale.replace}
  285. </Button>
  286. <Button
  287. style={{ width: 'fit-content' }}
  288. disabled={readOnly}
  289. onClick={() => {
  290. const value = this.replaceInputRef.current?.value;
  291. this.foundation.replaceAll(value);
  292. }}
  293. >
  294. {locale.replaceAll}
  295. </Button>
  296. </div>
  297. )}
  298. </LocaleConsumer>
  299. );
  300. }
  301. render() {
  302. let isDragging = false;
  303. const { width, className, style, showSearch = true, ...rest } = this.props;
  304. return (
  305. <>
  306. <div style={{ ...this.getStyle(), position: 'relative', ...style }} className={className} {...this.getDataAttr(rest)}>
  307. <div
  308. style={{ ...this.getStyle(), padding: '12px 0' }}
  309. ref={this.editorRef}
  310. className={classNames(prefixCls, `${prefixCls}-background`)}
  311. ></div>
  312. {showSearch && (
  313. <DragMove
  314. onMouseDown={() => {
  315. isDragging = false;
  316. }}
  317. onMouseMove={() => {
  318. isDragging = true;
  319. }}
  320. >
  321. <div style={{ position: 'absolute', top: 0, left: width }}>
  322. {!this.state.showSearchBar ? (
  323. <Button
  324. className={`${prefixCls}-search-bar-trigger`}
  325. onClick={e => {
  326. e.preventDefault();
  327. if (isDragging) {
  328. e.stopPropagation();
  329. e.preventDefault();
  330. return;
  331. }
  332. this.foundation.showSearchBar();
  333. }}
  334. icon={<IconSearch />}
  335. style={{ position: 'absolute', top: 20, right: 20 }}
  336. />
  337. ) : (
  338. this.renderSearchBox()
  339. )}
  340. </div>
  341. </DragMove>
  342. )}
  343. </div>
  344. {Array.from(this.state.customRenderMap.entries()).map(([key, value]) => {
  345. // key.innerHTML = '';
  346. return createPortal(value, key);
  347. })}
  348. </>
  349. );
  350. }
  351. }
  352. export default JsonViewerCom;