diff --git a/pages/index.js b/pages/index.js new file mode 100644 index 0000000..0971c2a --- /dev/null +++ b/pages/index.js @@ -0,0 +1,176 @@ +import { useState, useRef, useEffect } from 'react'; +import { useRouter } from 'next/router'; +import Head from 'next/head'; +import Editor, { loader } from "@monaco-editor/react"; +import { SITE_CONFIG } from '../config'; +import { nanoid } from 'nanoid'; + +export default function Home() { + const [filename, setFilename] = useState('script.js'); + const [code, setCode] = useState(''); + const [lang, setLang] = useState('javascript'); + const [indentMode, setIndentMode] = useState('spaces'); + const [indentSize, setIndentSize] = useState(4); + const [expiry, setExpiry] = useState(SITE_CONFIG.expiryOptions[0].value); + const [allowDiscussions, setAllowDiscussions] = useState(false); + const [availableLanguages, setAvailableLanguages] = useState([]); + const [mounted, setMounted] = useState(false); + + const editorRef = useRef(null); + const router = useRouter(); + + useEffect(() => { + setMounted(true); + loader.init().then((monaco) => { + const languages = monaco.languages.getLanguages(); + const sorted = languages.map(l => l.id).sort((a, b) => a.localeCompare(b)); + setAvailableLanguages(sorted); + }); + }, []); + + const handleIndentSizeChange = (newSize) => { + const oldSize = indentSize; + setIndentSize(newSize); + if (editorRef.current && indentMode === 'spaces') { + const model = editorRef.current.getModel(); + const currentCode = model.getValue(); + const updatedLines = currentCode.split('\n').map(line => { + const match = line.match(/^ +/); + if (match) { + const spaceCount = match[0].length; + const newSpaceCount = Math.round((spaceCount / oldSize) * newSize); + return ' '.repeat(newSpaceCount) + line.slice(spaceCount); + } + return line; + }); + model.setValue(updatedLines.join('\n')); + } + }; + + const save = async () => { + if (!code.trim()) return alert("Paste cannot be empty!"); + + const deleteToken = nanoid(32); + const res = await fetch('/api/pastes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + content: code, + language: lang, + filename, + expiry, + allowDiscussions, + deleteToken + }) + }); + const data = await res.json(); + + localStorage.setItem(`delete_token_${data.id}`, deleteToken); + router.push(`/paste/${data.id}`); + }; + + if (!mounted) return null; + + return ( +
{SITE_CONFIG.editorTitle}
+