"use client"; import { Textarea } from "@/components/ui/textarea"; import { useEffect, useRef, useState } from "react"; import { marked } from "marked"; import DOMPurify from "isomorphic-dompurify"; import { Button } from "@/components/ui/button"; import { Bold, Italic, Strikethrough, Underline } from "lucide-react"; enum Command { Italic = "*", Bold = "**", Strikethrough = "~~", Underline = "__", } export default function NewBlog() { const ref = useRef(null); const [text, setText] = useState(""); const [cursor, setCursor] = useState<{ line: number; column: number }>({ line: 0, column: 0, }); const [selection, setSelection] = useState<{ start: number; end: number; } | null>(null); const getCursorPosition = ( event: React.ChangeEvent, ) => { const textarea = event.target; const text = textarea.value; const cursorPos = textarea.selectionStart; const lines = text.substring(0, cursorPos).split("\n"); const line = lines.length; // Current line number (1-based) const column = lines[lines.length - 1].length + 1; // Current column (1-based) setCursor({ line, column }); }; const onSelect = (event: React.ChangeEvent) => { const { selectionStart, selectionEnd } = event.currentTarget; if (selectionStart === selectionEnd) return; setSelection({ start: selectionStart, end: selectionEnd }); }; useEffect(() => { setSelection(null); }, [text]); const moveCursor = (newPos: number) => { if (!ref.current) return; ref.current.selectionEnd = newPos; ref.current.focus(); }; const execCommand = (command: Command, symetry: boolean = true) => { if (selection) { const selectedText = text.substring(selection.start, selection.end); const pre = text.slice(0, selection.start); const post = text.slice(selection.end); const newSelectedText = `${command}${selectedText}${symetry ? command : ""}`; setText(pre + newSelectedText + post); return; } const pre = text.slice(0, cursor.column); const post = text.slice(cursor.column); if (!symetry) setText(pre + command + post); else { const t = pre + command + command + post; setText(t); } console.log(pre.length + command.length); moveCursor(cursor.column + 2); }; const sanitized = DOMPurify.sanitize(marked(text, { async: false })); return (
{/* */}