index.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import * as React from 'react';
  2. import BaseComponent from '../_base/baseComponent';
  3. import CodeHighlightFoundation, {
  4. CodeHighlightAdapter,
  5. CodeHighlightBaseProps,
  6. CodeHighlightBaseState,
  7. } from '@douyinfe/semi-foundation/codeHighlight';
  8. import { CSSProperties } from 'react';
  9. import "@douyinfe/semi-foundation/codeHighlight/codeHighlight.scss";
  10. import { getDefaultPropsFromGlobalConfig } from '../_utils';
  11. import PropTypes from 'prop-types';
  12. import cls from "classnames";
  13. import { cssClasses } from "@douyinfe/semi-foundation/codeHighlight/constants";
  14. interface CodeHighlightProps extends CodeHighlightBaseProps {
  15. className?: string;
  16. style?: CSSProperties;
  17. defaultTheme?: boolean
  18. }
  19. interface CodeHighlightState extends CodeHighlightBaseState {
  20. }
  21. class CodeHighlight extends BaseComponent<CodeHighlightProps, CodeHighlightState> {
  22. codeRef = React.createRef<HTMLElement>()
  23. foundation = new CodeHighlightFoundation(this.adapter)
  24. static __SemiComponentName__ = "CodeHighlight";
  25. static propTypes = {
  26. className: PropTypes.string,
  27. style: PropTypes.any,
  28. code: PropTypes.string,
  29. language: PropTypes.string,
  30. lineNumber: PropTypes.bool,
  31. defaultTheme: PropTypes.bool,
  32. }
  33. static defaultProps = getDefaultPropsFromGlobalConfig(CodeHighlight.__SemiComponentName__, {
  34. lineNumber: true,
  35. defaultTheme: true
  36. })
  37. constructor(props: CodeHighlightProps) {
  38. super(props);
  39. this.state = {};
  40. }
  41. get adapter(): CodeHighlightAdapter<CodeHighlightProps, CodeHighlightState> {
  42. return {
  43. ...super.adapter
  44. };
  45. }
  46. componentDidMount() {
  47. super.componentDidMount();
  48. if (this.codeRef.current) {
  49. this.foundation.highlightCode(this.codeRef.current, this.props.language);
  50. }
  51. }
  52. componentDidUpdate(prevProps: Readonly<CodeHighlightProps>, prevState: Readonly<CodeHighlightState>, snapshot?: any) {
  53. if (this.codeRef.current && prevProps.code !== this.props.code || this.props.language !== this.props.language) {
  54. this.foundation.highlightCode(this.codeRef.current, this.props.language);
  55. }
  56. }
  57. render() {
  58. return <div style={this.props.style} className={cls(this.props.className, cssClasses.PREFIX, "semi-light-scrollbar", { [`${cssClasses.PREFIX}-defaultTheme`]: this.props.defaultTheme })} {...this.getDataAttr(this.props)}>
  59. <pre>
  60. <code ref={this.codeRef}>
  61. {this.props.code}
  62. </code>
  63. </pre>
  64. </div>;
  65. }
  66. }
  67. export default CodeHighlight;