aboutsummaryrefslogtreecommitdiff
path: root/client/src/components/Editor/Editor.jsx
blob: c2918722600092a23045de3476e9af09b4b17907 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { useState, useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Prism from "prismjs";
import styles from "./Editor.module.css";
import "../prism-themes/prism-gruvbox-dark.css";
import { SERVER_BASE_URL, SUPPORTED_LANGUAGES } from "../../utils/constants";

const Editor = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [text, setText] = useState("");
  const [language, setLanguage] = useState("js");
  const textareaRef = useRef(null);
  const lineNumberRef = useRef(null);

  const handleTextChange = (event) => {
    setText(event.target.value);
  };

  const handleScroll = () => {
    if (textareaRef.current && lineNumberRef.current) {
      lineNumberRef.current.scrollTop = textareaRef.current.scrollTop;
    }
  };

  const handleClick = async () => {
    const response = await fetch(`${SERVER_BASE_URL}/bin`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        language,
        content: text,
      }),
    });
    const data = await response.json();
    if (response.ok) {
      navigate(`/${data.id}`);
    } else {
      console.error(data);
    }
  };

  const handleLanguageChange = (event) => {
    setLanguage(event.target.value);
  };

  useEffect(() => {
    Prism.highlightAll();
  }, [text, language]);

  useEffect(() => {
    if (params.id) fetchData();
    else {
      textareaRef.current.value = "";
      setText("");
    }
  }, [params.id]);

  const fetchData = async () => {
    const response = await fetch(`${SERVER_BASE_URL}/bin/${params.id}`);
    const data = await response.json();
    if (response.ok) {
      setLanguage(data.language);
      setText(data.content);
    }
  };

  const lines = text.split("\n");

  return (
    <div className={styles.container}>
      {!params.id && (
        <>
          <select
            className={styles.languages}
            onChange={(event) => handleLanguageChange(event)}
          >
            {Object.keys(SUPPORTED_LANGUAGES).map((language) => (
              <option
                className={styles.languages__option}
                key={language}
                value={language}
              >
                {SUPPORTED_LANGUAGES[language]}
              </option>
            ))}
          </select>
          <button className={styles.btn__save} onClick={() => handleClick()}>
            <img src="assets/icons/save.svg" className={styles.btn__icon} />
          </button>
        </>
      )}

      <div className={styles.editor}>
        <div
          className={styles.line__numbers}
          ref={lineNumberRef}
          onScroll={handleScroll}
        >
          {lines.map((_, index) => (
            <div key={index + 1} className={styles.line__number}>
              {index + 1}
            </div>
          ))}
        </div>
        <div className={styles.codespace}>
          <textarea
            className={styles.codespace__textarea}
            onChange={handleTextChange}
            onScroll={handleScroll}
            hidden={params.id ? true : false}
            spellCheck="false"
            ref={textareaRef}
            placeholder="Type your text here..."
          />
          <pre className={styles.codespace__pre}>
            <code className={`${styles.codespace__code} language-${language}`}>
              {text}
            </code>
          </pre>
        </div>
      </div>
    </div>
  );
};

export default Editor;