import React, { useState, useEffect, useRef } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import Prism from "prismjs";
import styles from "./Editor.module.css";
import "../prism-themes/prism-gruvbox-dark.css";
import "../prism-themes/prism-line-numbers.css";
import {
BASE_URL,
URL_REGEX,
} from "../../utils/constants";
import Header from "../Header/Header";
const Editor = () => {
const { id } = useParams();
const navigate = useNavigate();
const location = useLocation();
const [text, setText] = useState("");
const [language, setLanguage] = useState("none");
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 () => {
if (!text) {
alert("Please enter some text!");
return;
}
const response = await fetch(`${BASE_URL}/bin`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
language,
content: text,
}),
});
const data = await response.json();
if (response.ok) {
const isURL = URL_REGEX.test(text);
if (isURL) {
navigator.clipboard.writeText(`${BASE_URL}/r/${data.id}`).then(
function () {
alert("Short URL copied to clipboard!");
},
function (err) {
try {
var successful = document.execCommand("copy");
alert("Short URL copied to clipboard!");
} catch (err) {
console.log("Oops, unable to copy");
}
},
);
} else {
navigator.clipboard.writeText(`${BASE_URL}/r/${data.id}`).then(
function () {
navigator.clipboard.writeText(`${BASE_URL}/${data.id}`);
alert("URL copied to clipboard!");
},
function (err) {
try {
var successful = document.execCommand("copy");
alert("URL copied to clipboard!");
} catch (err) {
console.log("Oops, unable to copy");
}
},
);
}
navigate(`/${data.id}`);
} else {
console.error(data);
}
};
const handleLanguageChange = (value) => {
setLanguage(value);
};
useEffect(() => {
Prism.highlightAll();
}, [text, language]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`${BASE_URL}/bin/${id}`);
const data = await response.json();
if (response.ok) {
const isURL = URL_REGEX.test(data.content);
if (isURL) {
setText(`Your shortened URL: ${BASE_URL}/r/${id}`);
} else {
setLanguage(data.language);
setText(data.content);
}
}
};
if (id) {
fetchData();
} else {
textareaRef.current.value = "";
setText("");
}
}, [id]);
return (
<>
{text + "\n"}