All files / src/components/common/CodeAccordion index.tsx

0% Statements 0/18
0% Branches 0/14
0% Functions 0/4
0% Lines 0/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                                                                                       
import React, { forwardRef, useState } from "react";
import Editor from "react-simple-code-editor";
import hljs from "highlight.js/lib/core";
import python from "highlight.js/lib/languages/python";
import json from "highlight.js/lib/languages/json";
import { CodeAccordionPropTypes, LanguageTypes } from "./types/index.ts";
import isJSONString from "./utils/isJSONString.ts";
import { KeyboardArrowDown } from "@mui/icons-material";
 
hljs.registerLanguage("python", python as any);
hljs.registerLanguage("json", json as any);
 
const CodeAccordion = forwardRef<HTMLDivElement, CodeAccordionPropTypes>(
  (
    {
      code,
      language,
      label,
      onValueChange = () => {},
      disabled = false,
      className = "",
      defaultOpen = false,
      children,
      placeholder,
    },
    ref,
  ) => {
    const [isOpen, setIsOpen] = useState(defaultOpen);
 
    const toggle = () => setIsOpen(!isOpen);
 
    const value =
      language === LanguageTypes.JSON
        ? isJSONString(code)
          ? JSON.parse(JSON.stringify(code, null, 2))
          : typeof code !== "string"
          ? JSON.stringify(code, null, 2)
          : code
        : code;
 
    return (
      <div ref={ref}>
        <p
          onClick={toggle}
          className="font-semibold text-violet-500 text-xs transition-all cursor-pointer flex items-center">
          <KeyboardArrowDown
            className={`${isOpen ? "rotate-180" : "rotate-0"} !transition-all`}
            fontSize="small"
          />{" "}
          {label}
        </p>
        {isOpen && (
          <div className="flex flex-col gap-2 !text-xs">
            <Editor
              value={value}
              placeholder={placeholder}
              className={`${className} border rounded outline-none`}
              onValueChange={onValueChange}
              highlight={(code: string) =>
                hljs.highlight(code, {
                  language,
                }).value
              }
              disabled={disabled}
              padding={10}
            />
            {children}
          </div>
        )}
      </div>
    );
  },
);
 
export default CodeAccordion;