diff --git a/package-lock.json b/package-lock.json index ca383f46..f05f8299 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,7 +34,8 @@ "octokit": "^3.1.2", "react": "^18.2.0", "react-dom": "^18.2.0", - "react-markdown": "^9.0.1" + "react-markdown": "^9.0.1", + "remark-breaks": "^4.0.0" }, "devDependencies": { "@octokit/request": "^9.2.4", @@ -5310,6 +5311,18 @@ "node": ">=6" } }, + "node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", @@ -6831,6 +6844,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/mdast-util-find-and-replace": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz", + "integrity": "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "escape-string-regexp": "^5.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/mdast-util-from-markdown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz", @@ -6911,6 +6940,20 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/mdast-util-newline-to-break": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-newline-to-break/-/mdast-util-newline-to-break-2.0.0.tgz", + "integrity": "sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-find-and-replace": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/mdast-util-phrasing": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", @@ -8549,6 +8592,21 @@ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", "license": "MIT" }, + "node_modules/remark-breaks": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/remark-breaks/-/remark-breaks-4.0.0.tgz", + "integrity": "sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-newline-to-break": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/remark-parse": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", @@ -9661,9 +9719,9 @@ } }, "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", diff --git a/package.json b/package.json index 17886c5f..e509247e 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,8 @@ "octokit": "^3.1.2", "react": "^18.2.0", "react-dom": "^18.2.0", - "react-markdown": "^9.0.1" + "react-markdown": "^9.0.1", + "remark-breaks": "^4.0.0" }, "devDependencies": { "@octokit/request": "^9.2.4", diff --git a/src/components/islands/word-editor.jsx b/src/components/islands/word-editor.jsx index ce140e99..8c2baff0 100644 --- a/src/components/islands/word-editor.jsx +++ b/src/components/islands/word-editor.jsx @@ -5,11 +5,18 @@ * @exports TogglePreview - Mobile preview toggle for responsive editor experience */ -import { useEffect } from "react"; +import { useEffect, useRef, useState } from "react"; import Markdown from "react-markdown"; +import remarkBreaks from "remark-breaks"; import { useStore } from "@nanostores/react"; import useRouter from "../../lib/hooks/use-router.js"; -import { capitalizeText } from "../../lib/utils/index.js"; +import { + capitalizeText, + toggleMarkdownListPrefix, + continueMarkdownListOnEnter, + toggleMarkdownWrap, + toggleMarkdownCodeBlock, +} from "../../lib/utils/index.js"; import useWordEditor from "../../lib/hooks/use-word-editor.js"; import { $isWordSubmitLoading, @@ -35,7 +42,7 @@ export default function WordEditor({ eTitle={title} eContent={content} eMetadata={metadata} - className={` ${!togglePreview ? "flex" : "hidden"} w-full h-full lg:!flex flex-col p-5 border-r`} + className={` ${!togglePreview ? "flex" : "hidden"} w-full h-full lg:!flex flex-col py-5 border-r`} /> { - setTitle(eTitle); - setContent(eContent); + let draft; + try { + const savedDraft = window.localStorage.getItem(draftKey); + draft = savedDraft ? JSON.parse(savedDraft) : null; + } catch { + draft = null; + } + + setTitle(typeof draft?.title === "string" ? draft.title : eTitle); + setContent(typeof draft?.content === "string" ? draft.content : eContent); setInitialContent(eContent); - }, []); + history.current = { undo: [], redo: [] }; + draftReady.current = true; + }, [draftKey]); + + useEffect(() => { + const backLink = document.querySelector("[data-word-editor-back]"); + if (!backLink) return; + + function handleBackClick(event) { + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey || + (title === eTitle && content === eContent) + ) { + return; + } + + event.preventDefault(); + if ( + !window.confirm( + "You have unsaved changes. Going back will discard this draft. Continue?", + ) + ) { + return; + } + + clearDraft(); + window.location.assign(backLink.href); + } + + backLink.addEventListener("click", handleBackClick); + return () => backLink.removeEventListener("click", handleBackClick); + }, [content, title, eContent, eTitle, draftKey]); + + useEffect(() => { + const textarea = textareaRef.current; + const selection = pendingSelection.current; + + if (!textarea || !selection) return; + + textarea.focus(); + textarea.setSelectionRange(selection.start, selection.end); + pendingSelection.current = null; + }, [content]); + + function updateHistoryState() { + setHistoryState({ + canUndo: history.current.undo.length > 0, + canRedo: history.current.redo.length > 0, + }); + } + + function recordCurrentContent(selection) { + const textarea = textareaRef.current; + history.current.undo.push({ + value: content, + start: selection?.start ?? textarea?.selectionStart ?? 0, + end: selection?.end ?? textarea?.selectionEnd ?? 0, + }); + if (history.current.undo.length > 100) history.current.undo.shift(); + history.current.redo = []; + updateHistoryState(); + } + + function commitEdit(result) { + if (result.value === content) return; + + recordCurrentContent(); + pendingSelection.current = result; + setContent(result.value); + persistDraft(title, result.value); + } + + function persistDraft(draftTitle, draftContent) { + if (!draftReady.current) return; + + try { + if (draftTitle === eTitle && draftContent === eContent) { + window.localStorage.removeItem(draftKey); + return; + } + + window.localStorage.setItem( + draftKey, + JSON.stringify({ title: draftTitle, content: draftContent }), + ); + } catch { + // Draft persistence is best-effort when browser storage is unavailable. + } + } + + function clearDraft() { + try { + window.localStorage.removeItem(draftKey); + } catch { + // Ignore unavailable browser storage. + } + } + + function handleTitleChange(event) { + const nextTitle = event.target.value; + setTitle(nextTitle); + persistDraft(nextTitle, content); + } + + function handleTextareaBeforeInput(event) { + beforeInputSelection.current = { + start: event.currentTarget.selectionStart, + end: event.currentTarget.selectionEnd, + }; + } + + function handleTextareaChange(event) { + const nextContent = event.currentTarget.value; + + if (nextContent !== content) { + recordCurrentContent(beforeInputSelection.current); + persistDraft(title, nextContent); + } + + beforeInputSelection.current = null; + setContent(nextContent); + } + + function applyHistory(direction) { + const source = history.current[direction]; + if (isDone || source.length === 0) return; + + const textarea = textareaRef.current; + const target = direction === "undo" ? "redo" : "undo"; + history.current[target].push({ + value: content, + start: textarea?.selectionStart ?? 0, + end: textarea?.selectionEnd ?? 0, + }); + pendingSelection.current = source.pop(); + setContent(pendingSelection.current.value); + persistDraft(title, pendingSelection.current.value); + updateHistoryState(); + } + + function applyMarkdownWrap(marker) { + const textarea = textareaRef.current; + if (!textarea || isDone) return; + + const result = toggleMarkdownWrap( + content, + textarea.selectionStart, + textarea.selectionEnd, + marker, + ); + commitEdit(result); + } + + function applyMarkdownCodeBlock() { + const textarea = textareaRef.current; + if (!textarea || isDone) return; + + const result = toggleMarkdownCodeBlock( + content, + textarea.selectionStart, + textarea.selectionEnd, + ); + commitEdit(result); + } + + function applyMarkdownListPrefix(prefix) { + const textarea = textareaRef.current; + if (!textarea || isDone) return; + + const result = toggleMarkdownListPrefix( + content, + textarea.selectionStart, + textarea.selectionEnd, + prefix, + ); + commitEdit(result); + } + + function handleTextareaKeyDown(event) { + if (isDone) return; + + if ( + event.key === "Enter" && + !event.shiftKey && + !event.ctrlKey && + !event.metaKey && + !event.altKey + ) { + const { selectionStart, selectionEnd, value } = event.currentTarget; + const result = continueMarkdownListOnEnter( + value, + selectionStart, + selectionEnd, + ); + + if (result) { + event.preventDefault(); + commitEdit(result); + return; + } + } + + if ((!event.ctrlKey && !event.metaKey) || event.altKey) { + return; + } + + const key = event.key.toLowerCase(); + if (key === "z" || key === "y") { + event.preventDefault(); + applyHistory(key === "y" || event.shiftKey ? "redo" : "undo"); + return; + } + + if (event.shiftKey) return; + + const markerByKey = { + b: "**", + i: "_", + }; + const marker = markerByKey[key]; + + if (!marker) return; + + event.preventDefault(); + applyMarkdownWrap(marker); + } /** * Word Submit Handler @@ -150,6 +409,7 @@ function Editor({ eTitle, eContent, eMetadata, className, action, ...props }) { body: formData, }); if (response && response.status === 200) { + clearDraft(); $isWordSubmitted.set(true); $isWordSubmitLoading.set(false); router.push("/editor"); @@ -202,19 +462,117 @@ function Editor({ eTitle, eContent, eMetadata, className, action, ...props }) { id="title" name="title" value={title} - placeholder="New Word" - onChange={(e) => setTitle(e.target.value)} + placeholder="New word here..." + onChange={handleTitleChange} readOnly={action === "edit" || isDone} - className={`${(action === "edit" || isDone) && "cursor-not-allowed"} block w-full pb-2 mb-3 text-gray-900 border-b text-lg font-bold focus:outline-none`} + className={`${(action === "edit" || isDone) && "cursor-not-allowed"} block w-full pb-2 px-5 text-gray-900 border-b text-lg font-bold focus:outline-none`} /> +
+ {/* TEMPORARILY DISABLED UNDO/REDO BUTTONS */} + {/* applyHistory("undo")} + > + + + applyHistory("redo")} + > + + */} + applyMarkdownWrap("**")} + > + + + applyMarkdownWrap("_")} + > + + + applyMarkdownListPrefix("- ")} + > + + + applyMarkdownListPrefix("1. ")} + > + + + applyMarkdownWrap("`")} + > + + + + + +