diff --git a/package.json b/package.json index e3763506..311317fd 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,6 @@ "@lezer/highlight": "^1.2.5", "@phosphor-icons/react": "^2.1.10", "cmdk": "^1.1.1", - "codemirror": "^6.0.2", "jotai": "^3.0.1", "motion": "^14.0.0", "react": "^19.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f041acc5..5cc356ce 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,9 +44,6 @@ importers: cmdk: specifier: ^1.1.1 version: 1.1.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - codemirror: - specifier: ^6.0.2 - version: 6.0.2 jotai: specifier: ^3.0.1 version: 3.0.1(@types/react@19.3.0)(react@19.3.0) @@ -815,9 +812,6 @@ packages: '@codemirror/lint@6.9.7': resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==} - '@codemirror/search@6.7.2': - resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==} - '@codemirror/state@6.7.6': resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==} @@ -2172,9 +2166,6 @@ packages: react: ^18 || ^19 || ^19.0.0-rc react-dom: ^18 || ^19 || ^19.0.0-rc - codemirror@6.0.2: - resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==} - color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -4697,12 +4688,6 @@ snapshots: '@codemirror/view': 6.43.13 crelt: 1.0.7 - '@codemirror/search@6.7.2': - dependencies: - '@codemirror/state': 6.7.6 - '@codemirror/view': 6.43.13 - crelt: 1.0.7 - '@codemirror/state@6.7.6': dependencies: '@marijn/find-cluster-break': 1.0.4 @@ -5854,16 +5839,6 @@ snapshots: - '@types/react' - '@types/react-dom' - codemirror@6.0.2: - dependencies: - '@codemirror/autocomplete': 6.20.3 - '@codemirror/commands': 6.11.1 - '@codemirror/language': 6.12.4 - '@codemirror/lint': 6.9.7 - '@codemirror/search': 6.7.2 - '@codemirror/state': 6.7.6 - '@codemirror/view': 6.43.13 - color-convert@2.0.1: dependencies: color-name: 1.1.4 diff --git a/src/features/editor/codemirror/tasklist/task-close.ts b/src/features/editor/codemirror/tasklist/task-close.ts index 13f5fa79..3f82504c 100644 --- a/src/features/editor/codemirror/tasklist/task-close.ts +++ b/src/features/editor/codemirror/tasklist/task-close.ts @@ -6,7 +6,7 @@ import { type DecorationSet, type PluginValue, } from "@codemirror/view"; -import { StateEffect, StateField, RangeSetBuilder } from "@codemirror/state"; +import { StateEffect, StateField, RangeSetBuilder, type Line } from "@codemirror/state"; import { findTaskSection } from "./task-section-utils"; import type { OnTaskClosed } from "."; @@ -15,7 +15,7 @@ export type TaskHandler = { onTaskOpen: (taskContent: string) => void; }; -// use utils +// Differs from TASK_LINE_REGEX in task-list-utils on purpose: no padding inside the brackets, any spacing after the bullet const taskItemRegex = /^(\s*[-*]\s+)\[([ xX])\]/; type TaskInfo = { @@ -53,7 +53,7 @@ export const registerTaskHandler = (handler: TaskHandler | undefined): void => { globalTaskHandler = handler; }; -export const getRegisteredTaskHandler = (): TaskHandler | undefined => { +const getRegisteredTaskHandler = (): TaskHandler | undefined => { return globalTaskHandler; }; @@ -62,6 +62,24 @@ const getTaskKey = (lineNumber: number, content: string): string => { return `${lineNumber}:${content.trim()}`; }; +const parseTaskInfo = (line: Line): TaskInfo | null => { + const match = line.text.match(taskItemRegex); + if (!match) return null; + + // Position of '[' + const taskStartPos = (match.index || 0) + match[1].length; + const from = line.from + taskStartPos; + const checkChar = match[2]; + return { + from, + to: from + 3, // '[' + content + ']' = 3 chars + contentPos: from + 1, // next of '[' + checked: checkChar === "x" || checkChar === "X", + line: line.number, + key: getTaskKey(line.number, line.text.substring(taskStartPos + 3)), + }; +}; + export const taskDecoration = ViewPlugin.fromClass( class { taskes: TaskInfo[] = []; @@ -80,31 +98,8 @@ export const taskDecoration = ViewPlugin.fromClass( for (const { from, to } of view.visibleRanges) { for (let pos = from; pos <= to; ) { const line = doc.lineAt(pos); - const match = line.text.match(taskItemRegex); - - if (match) { - // Search for the entire task pattern to determine the exact position - const matchIndex = match.index || 0; - const prefixLength = match[1].length; - - // Calculate the position of '[' - const taskStartPos = matchIndex + prefixLength; - const taskFrom = line.from + taskStartPos; - const contentPos = taskFrom + 1; // next of '[' - const taskTo = taskFrom + 3; // '[' + content + ']' = 3 chars - - const checkChar = match[2]; - const taskContent = line.text.substring(matchIndex + prefixLength + 3).trim(); - - result.push({ - from: taskFrom, - to: taskTo, - contentPos, - checked: checkChar === "x" || checkChar === "X", - line: line.number, - key: getTaskKey(line.number, taskContent), - }); - } + const task = parseTaskInfo(line); + if (task) result.push(task); pos = line.to + 1; } @@ -183,31 +178,8 @@ export const taskMouseInteraction = (taskHandler?: TaskHandler) => { } getTaskAt(pos: number): TaskInfo | null { - const line = this.view.state.doc.lineAt(pos); - const match = line.text.match(taskItemRegex); - if (!match) return null; - - const matchIndex = match.index || 0; - const prefixLength = match[1].length; - const taskStartPos = matchIndex + prefixLength; - const from = line.from + taskStartPos; - const contentPos = from + 1; - const to = from + 3; // next of ']' - - if (pos >= from && pos < to) { - const checkChar = match[2]; - const taskContent = line.text.substring(matchIndex + prefixLength + 3).trim(); - - return { - from, - to, - contentPos, - checked: checkChar === "x" || checkChar === "X", - line: line.number, - key: getTaskKey(line.number, taskContent), - }; - } - return null; + const task = parseTaskInfo(this.view.state.doc.lineAt(pos)); + return task && pos >= task.from && pos < task.to ? task : null; } handleMouseMove(event: MouseEvent) { diff --git a/src/features/editor/codemirror/tasklist/task-reorder.ts b/src/features/editor/codemirror/tasklist/task-reorder.ts index 64d37776..58e8affd 100644 --- a/src/features/editor/codemirror/tasklist/task-reorder.ts +++ b/src/features/editor/codemirror/tasklist/task-reorder.ts @@ -1,8 +1,8 @@ import type { EditorView } from "@codemirror/view"; import type { Text } from "@codemirror/state"; import { isTaskLine, isRegularListLine, parseTaskLine, parseRegularListLine } from "./task-list-utils"; +import { isHeadingLine } from "./task-section-utils"; -const MARKDOWN_HEADING = /^#{1,6}\s+\S/; const EMPTY_LINE = /^\s*$/u; type BlockRange = { @@ -12,7 +12,6 @@ type BlockRange = { }; const isListLine = (text: string): boolean => isTaskLine(text) || isRegularListLine(text); -const isHeadingLine = (text: string): boolean => MARKDOWN_HEADING.test(text); const isEmptyLine = (text: string): boolean => EMPTY_LINE.test(text); /** diff --git a/src/features/editor/codemirror/tasklist/task-section-utils.ts b/src/features/editor/codemirror/tasklist/task-section-utils.ts index ee5d44c7..314ad17e 100644 --- a/src/features/editor/codemirror/tasklist/task-section-utils.ts +++ b/src/features/editor/codemirror/tasklist/task-section-utils.ts @@ -2,6 +2,8 @@ import type { EditorView } from "@codemirror/view"; const MARKDOWN_HEADING = /^#{1,6}\s+\S/; +export const isHeadingLine = (text: string): boolean => MARKDOWN_HEADING.test(text); + /** * Return the nearest markdown heading above `lineNumber`. * `undefined` if none exists. @@ -11,6 +13,6 @@ export const findTaskSection = (view: EditorView, lineNumber: number): string | for (let i = lineNumber; i >= 1; i--) { const text = doc.line(i).text.trim(); - if (MARKDOWN_HEADING.test(text)) return text; + if (isHeadingLine(text)) return text; } }; diff --git a/src/features/editor/codemirror/use-cursor-position.ts b/src/features/editor/codemirror/use-cursor-position.ts deleted file mode 100644 index 2645191b..00000000 --- a/src/features/editor/codemirror/use-cursor-position.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { EditorView } from "@codemirror/view"; -import { atomWithStorage } from "jotai/utils"; -import { useAtom } from "jotai"; -import { useLayoutEffect } from "react"; -import { LOCAL_STORAGE_KEYS } from "../../../utils/constants"; - -const INITIAL_CURSOR_POSITION = { from: 0, to: 0 }; -const cursorAtom = atomWithStorage<{ from: number; to: number }>( - LOCAL_STORAGE_KEYS.CURSOR_POSITION, - INITIAL_CURSOR_POSITION, -); - -export const useCursorPosition = (view?: EditorView) => { - const [cursorPosition, setCursorPosition] = useAtom(cursorAtom); - - useLayoutEffect(() => { - if (typeof window === "undefined" || !view) return; - - if (cursorPosition.from || cursorPosition.to) { - const len = view.state.doc.length; - view.dispatch({ - selection: { - anchor: Math.min(cursorPosition.from, len), - head: Math.min(cursorPosition.to, len), - }, - scrollIntoView: true, - }); - } - - const save = () => { - const { from, to } = view.state.selection.main; - setCursorPosition((prev) => (prev.from === from && prev.to === to ? prev : { from, to })); - }; - - // only save cursor position when the page is hidden - window.addEventListener("pagehide", save); - return () => window.removeEventListener("pagehide", save); - }, [view, cursorPosition, setCursorPosition]); - - const resetCursorPosition = () => setCursorPosition(INITIAL_CURSOR_POSITION); - - return { cursorPosition, resetCursorPosition }; -}; diff --git a/src/features/editor/codemirror/use-markdown-editor.ts b/src/features/editor/codemirror/use-markdown-editor.ts index 5207ff87..c4f05c4e 100644 --- a/src/features/editor/codemirror/use-markdown-editor.ts +++ b/src/features/editor/codemirror/use-markdown-editor.ts @@ -8,12 +8,12 @@ import { useRef, useEffect, useLayoutEffect, useState } from "react"; import { showToast } from "../../../utils/components/toast"; import { useEditorWidth } from "../../../utils/hooks/use-editor-width"; import { useTheme } from "../../../utils/hooks/use-theme"; -import { DprintMarkdownFormatter } from "../markdown/formatter/dprint-markdown-formatter"; +import { formatEditorView, useMarkdownFormatter } from "../markdown/formatter/format-editor"; import { getRandomQuote } from "../quotes"; import { taskStorage } from "../tasks/task-storage"; import { createDefaultTaskHandler, createChecklistPlugin } from "./tasklist"; import { registerTaskHandler } from "./tasklist/task-close"; -import { snapshotStorage } from "../../snapshots/snapshot-storage"; +import { saveSnapshotWithToast } from "../../snapshots/snapshot-storage"; import { useEditorTheme } from "./use-editor-theme"; import { useTaskAutoFlush } from "../../../utils/hooks/use-task-auto-flush"; import { useMobileDetector } from "../../../utils/hooks/use-mobile-detector"; @@ -27,24 +27,6 @@ import { useFocusMode } from "../../../utils/hooks/use-focus-mode"; import { focusModeExtension } from "./focus-mode"; import { usePaperMode } from "../../../utils/hooks/use-paper-mode"; -const useMarkdownFormatter = () => { - const ref = useRef(null); - useEffect(() => { - let alive = true; - (async () => { - const fmt = await DprintMarkdownFormatter.getInstance(); - if (alive) { - ref.current = fmt; - } - })(); - return () => { - alive = false; - ref.current = null; - }; - }, []); - return ref; -}; - const useTaskHandler = () => { const { taskAutoFlushMode } = useTaskAutoFlush(); const handlerRef = useRef(createDefaultTaskHandler(taskStorage, taskAutoFlushMode)); @@ -111,9 +93,7 @@ export const useMarkdownEditor = ( // Only update if content actually changed to prevent unnecessary updates setContent((prevContent) => (prevContent !== newContent ? newContent : prevContent)); // Call onChange callback if provided (for multi-editor) - if (onChange) { - onChange(newContent); - } + onChange?.(newContent); }, 300); useEffect(() => { @@ -130,39 +110,12 @@ export const useMarkdownEditor = ( return false; } try { - // format - const { state } = view; - const scrollTop = view.scrollDOM.scrollTop; - const cursorPos = state.selection.main.head; - const cursorLine = state.doc.lineAt(cursorPos); - const cursorLineNumber = cursorLine.number; - const cursorColumn = cursorPos - cursorLine.from; - const currentText = state.doc.toString(); - const formattedText = await formatterRef.current.formatMarkdown(currentText); - if (formattedText !== currentText) { - view.dispatch({ - changes: { from: 0, to: state.doc.length, insert: formattedText }, - }); + const formattedText = await formatEditorView(view, formatterRef.current); + if (formattedText !== null) { // Persist formatted content to state/storage and notify listeners lastWroteFromEditorRef.current = formattedText; setContent((prevContent) => (prevContent !== formattedText ? formattedText : prevContent)); - if (onChange) { - onChange(formattedText); - } - // Restore cursor position after formatting - try { - const newState = view.state; - const newDocLineCount = newState.doc.lines; - if (cursorLineNumber <= newDocLineCount) { - const newLine = newState.doc.line(cursorLineNumber); - const newColumn = Math.min(cursorColumn, newLine.length); - const newPos = newLine.from + newColumn; - view.dispatch({ selection: { anchor: newPos, head: newPos } }); - } - } catch (_selectionError) { - view.dispatch({ selection: { anchor: 0, head: 0 } }); - } - view.scrollDOM.scrollTop = Math.min(scrollTop, view.scrollDOM.scrollHeight - view.scrollDOM.clientHeight); + onChange?.(formattedText); } return true; } catch (error) { @@ -175,26 +128,7 @@ export const useMarkdownEditor = ( const onSaveSnapshot = async () => { const view = viewRef.current; if (!view) return false; - try { - const currentText = view.state.doc.toString(); - if (!currentText) { - showToast("No content to save", "error"); - return false; - } - - // snapshot - snapshotStorage.save({ - content: currentText, - charCount: currentText.length, - }); - - showToast("Snapshot saved", "default"); - return true; - } catch (error) { - const message = error instanceof Error ? error.message : "unknown"; - showToast(`Error saving snapshot: ${message}`, "error"); - return false; - } + return saveSnapshotWithToast(view.state.doc.toString()); }; useLayoutEffect(() => { diff --git a/src/features/editor/codemirror/use-toc.ts b/src/features/editor/codemirror/use-toc.ts deleted file mode 100644 index 9b351d6b..00000000 --- a/src/features/editor/codemirror/use-toc.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { useState, useEffect, useCallback } from "react"; -import { EditorView } from "@codemirror/view"; - -export type TocItem = { - level: number; - text: string; - from: number; -}; - -type UseTableOfContentsProps = { - editorView: EditorView; - content: string; -}; - -const HEADING_REGEX = /^(#{1,6})\s+(.+)$/; - -export const useTableOfContentsCodeMirror = ({ editorView, content }: UseTableOfContentsProps) => { - const [tocItems, setTocItems] = useState([]); - - // 1. Parse table of contents items from content (calculate from position) - const parseTocItems = useCallback((text: string): TocItem[] => { - if (!text) return []; - const lines = text.split("\n"); - const items: TocItem[] = []; - let currentPos = 0; - - for (const lineText of lines) { - const match = HEADING_REGEX.exec(lineText); - if (match) { - items.push({ - level: match[1].length, - text: match[2].trim(), - from: currentPos, - }); - } - currentPos += lineText.length + 1; - } - return items; - }, []); - - // 2. Effect to regenerate table of contents items when content changes - useEffect(() => { - const newItems = parseTocItems(content); - setTocItems(newItems); - }, [content, parseTocItems]); - - // 3. Function to focus on section when table of contents item is clicked (using CodeMirror API) - const focusOnSection = useCallback( - (from: number) => { - if (!editorView) return; - - const transaction = editorView.state.update({ - // Move cursor to the beginning of the heading line - selection: { anchor: from }, - // Scroll so the specified position is centered in the viewport - effects: EditorView.scrollIntoView(from, { y: "center" }), - // Specify user event type if needed - // userEvent: "select.toc" - }); - - editorView.dispatch(transaction); - editorView.focus(); - }, - [editorView], - ); - - return { - tocItems, - focusOnSection, - }; -}; diff --git a/src/features/editor/editor-ref.ts b/src/features/editor/editor-ref.ts index 08999b44..10c58063 100644 --- a/src/features/editor/editor-ref.ts +++ b/src/features/editor/editor-ref.ts @@ -1,6 +1,6 @@ import type { EditorView } from "@codemirror/view"; -export type BaseEditorRef = { +type BaseEditorRef = { view: EditorView | null; getCurrentContent: () => string; setContent: (content: string) => void; diff --git a/src/features/editor/markdown/formatter/format-editor.ts b/src/features/editor/markdown/formatter/format-editor.ts new file mode 100644 index 00000000..f8f1ca27 --- /dev/null +++ b/src/features/editor/markdown/formatter/format-editor.ts @@ -0,0 +1,61 @@ +import type { TransactionSpec } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { useEffect, useRef } from "react"; +import { DprintMarkdownFormatter } from "./dprint-markdown-formatter"; + +export const useMarkdownFormatter = () => { + const ref = useRef(null); + useEffect(() => { + let alive = true; + (async () => { + const fmt = await DprintMarkdownFormatter.getInstance(); + if (alive) { + ref.current = fmt; + } + })(); + return () => { + alive = false; + ref.current = null; + }; + }, []); + return ref; +}; + +/** + * Formats the whole document in place, keeping the cursor's line/column and the scroll position. + * Returns the formatted text, or null when formatting changed nothing. + */ +export const formatEditorView = async ( + view: EditorView, + formatter: DprintMarkdownFormatter, + annotations?: TransactionSpec["annotations"], +): Promise => { + const { state } = view; + const scrollTop = view.scrollDOM.scrollTop; + const cursorPos = state.selection.main.head; + const cursorLine = state.doc.lineAt(cursorPos); + const cursorLineNumber = cursorLine.number; + const cursorColumn = cursorPos - cursorLine.from; + const currentText = state.doc.toString(); + const formattedText = await formatter.formatMarkdown(currentText); + if (formattedText === currentText) return null; + + view.dispatch({ + changes: { from: 0, to: state.doc.length, insert: formattedText }, + annotations, + }); + + // Restore cursor position after formatting + try { + const newState = view.state; + if (cursorLineNumber <= newState.doc.lines) { + const newLine = newState.doc.line(cursorLineNumber); + const newPos = newLine.from + Math.min(cursorColumn, newLine.length); + view.dispatch({ selection: { anchor: newPos, head: newPos } }); + } + } catch (_selectionError) { + view.dispatch({ selection: { anchor: 0, head: 0 } }); + } + view.scrollDOM.scrollTop = Math.min(scrollTop, view.scrollDOM.scrollHeight - view.scrollDOM.clientHeight); + return formattedText; +}; diff --git a/src/features/editor/multi/dock-menu.tsx b/src/features/editor/multi/dock-menu.tsx index afa6f9b0..6b06aa68 100644 --- a/src/features/editor/multi/dock-menu.tsx +++ b/src/features/editor/multi/dock-menu.tsx @@ -22,12 +22,12 @@ type CardStyle = { zIndex: number; }; -export const generatePreviewContent = (content: string): string => { +const generatePreviewContent = (content: string): string => { const lines = content.split("\n").slice(0, 5).join("\n"); return lines.length > 100 ? `${lines.substring(0, 100)}...` : lines; }; -export const calculateCardStyle = ( +const calculateCardStyle = ( index: number, total: number, hoveredIndex: number | null, @@ -49,7 +49,7 @@ export const calculateCardStyle = ( return { x, y, rotate: rotation, scale, zIndex }; }; -export const getCardButtonClasses = (isActive: boolean, isDockHovered: boolean): string => { +const getCardButtonClasses = (isActive: boolean, isDockHovered: boolean): string => { const baseClasses = "w-full h-full relative overflow-hidden"; const shapeClasses = isDockHovered ? "rounded-lg border shadow-lg backdrop-blur-sm" : "rounded-md"; diff --git a/src/features/editor/table-of-contents.tsx b/src/features/editor/table-of-contents.tsx deleted file mode 100644 index 36ff5ba4..00000000 --- a/src/features/editor/table-of-contents.tsx +++ /dev/null @@ -1,95 +0,0 @@ -"use client"; - -import type React from "react"; -import { useState, useEffect, useRef, useCallback } from "react"; -import { useTheme } from "../../utils/hooks/use-theme"; - -type TocItem = { - level: number; - text: string; - line: number; -}; - -type TocProps = { - content: string; - onItemClick: (line: number) => void; - isVisible: boolean; -}; - -const HEADING_REGEX = /^(#{1,6})\s+(.+)$/; - -export const TableOfContents: React.FC = ({ content, onItemClick, isVisible }) => { - const [tocItems, setTocItems] = useState([]); - const { isDarkMode } = useTheme(); - const prevContentRef = useRef(""); - const hasInitializedRef = useRef(false); - - const parseTocItems = useCallback((content: string): TocItem[] => { - if (!content) return []; - - const lines = content.split("\n"); - const items: TocItem[] = []; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - const match = HEADING_REGEX.exec(line); - if (match) { - items.push({ - level: match[1].length, - text: match[2].trim(), - line: i, - }); - } - } - - return items; - }, []); - - // Always parse content on initial render and when content changes - useEffect(() => { - // Always parse content regardless of visibility - if (!content) { - setTocItems([]); - return; - } - - // Always parse on initial load or when content changes - const shouldUpdate = !hasInitializedRef.current || content !== prevContentRef.current; - - if (shouldUpdate) { - const newItems = parseTocItems(content); - setTocItems(newItems); - prevContentRef.current = content; - hasInitializedRef.current = true; - } - }, [content, parseTocItems]); - - const shouldRender = isVisible && tocItems.length > 0 && !!content; - if (!shouldRender) { - return null; - } - - return ( -
-
    - {tocItems.map((item) => ( -
  • - -
  • - ))} -
-
- ); -}; diff --git a/src/features/editor/tasks/task-storage.ts b/src/features/editor/tasks/task-storage.ts index 14affd6a..bfa688bc 100644 --- a/src/features/editor/tasks/task-storage.ts +++ b/src/features/editor/tasks/task-storage.ts @@ -1,13 +1,5 @@ import { LOCAL_STORAGE_KEYS } from "../../../utils/constants"; -import { - createBrowserLocalStorage, - createStorage, - type DateFilter, - defaultStorageProvider, - filterItemsByDate, - groupItemsByDate, - type StorageProvider, -} from "../../../utils/storage"; +import { createStorage, type DateFilter, defaultStorageProvider, type StorageProvider } from "../../../utils/storage"; export type TaskStorage = { getAll: () => CompletedTask[]; @@ -32,18 +24,9 @@ export const generateTaskIdentifier = (taskContent: string): string => { }; // Task Storage factory function -const createTaskStorage = (storage: StorageProvider = createBrowserLocalStorage()): TaskStorage => { +const createTaskStorage = (storage: StorageProvider): TaskStorage => { const baseStorage = createStorage(storage, LOCAL_STORAGE_KEYS.COMPLETED_TASKS); - // Task specific operations - const save = (task: CompletedTask): void => { - baseStorage.save(task); - }; - - const deleteItem = (id: string): void => { - baseStorage.deleteById(id); - }; - const deleteByIdentifier = (taskIdentifier: string): void => { try { const tasks = baseStorage.getAll(); @@ -54,23 +37,9 @@ const createTaskStorage = (storage: StorageProvider = createBrowserLocalStorage( } }; - const purgeAll = (): void => { - baseStorage.deleteAll(); - }; - - const getByDate = (filter?: DateFilter): Record => { - const tasks = baseStorage.getAll(); - const filteredTasks = filterItemsByDate(tasks, filter); - return groupItemsByDate(filteredTasks); - }; - return { ...baseStorage, - save, - deleteById: deleteItem, deleteByIdentifier, - deleteAll: purgeAll, - getByDate, }; }; diff --git a/src/features/history/use-history-data.ts b/src/features/history/use-history-data.ts index aae53c05..6dd57e4e 100644 --- a/src/features/history/use-history-data.ts +++ b/src/features/history/use-history-data.ts @@ -4,19 +4,10 @@ import { type CompletedTask, taskStorage } from "../editor/tasks/task-storage"; import { LOCAL_STORAGE_KEYS } from "../../utils/constants"; import { showToast } from "../../utils/components/toast"; -// Type definition for grouped items -export type DateGroupedItems = { - today: T[]; - yesterday: T[]; - older: { date: string; items: T[] }[]; -}; - // History data type type HistoryData = { snapshots: Snapshot[]; tasks: CompletedTask[]; - groupedSnapshots: DateGroupedItems; - groupedTasks: DateGroupedItems; isLoading: boolean; handleRestoreSnapshot: (snapshot: Snapshot) => void; handleDeleteSnapshot: (id: string) => void; @@ -25,135 +16,29 @@ type HistoryData = { handleDeleteAllTasks: () => void; }; -// Cache for date strings to avoid recreating them repeatedly -const dateStringCache = new Map(); - -// Helper to get date string for grouping with caching -const getDateString = (date: Date): string => { - const time = date.getTime(); - const cacheKey = `date_${time}`; - - const cachedDate = dateStringCache.get(cacheKey); - if (cachedDate) { - return cachedDate; - } - - const dateStr = date.toISOString().split("T")[0]; // YYYY-MM-DD - dateStringCache.set(cacheKey, dateStr); - - // Cleanup cache if it gets too large - if (dateStringCache.size > 100) { - // Get the oldest keys and remove them - const keys = Array.from(dateStringCache.keys()).slice(0, 50); - keys.forEach((key) => { - dateStringCache.delete(key); - }); - } - - return dateStr; -}; - -// Function to group items by date -const groupItemsByDate = (items: T[]): DateGroupedItems => { - const now = new Date(); - const today = getDateString(now); - - const yesterday = new Date(now); - yesterday.setDate(yesterday.getDate() - 1); - const yesterdayStr = getDateString(yesterday); - - const result: DateGroupedItems = { - today: [], - yesterday: [], - older: [], - }; - - // Temporary storage for older dates - const olderDates: Record = {}; - - items.forEach((item) => { - // Get the date string from item (handle both snapshot and task) - const dateStr = item.timestamp - ? getDateString(new Date(item.timestamp)) - : item.completedAt - ? getDateString(new Date(item.completedAt)) - : ""; - - if (dateStr === today) { - result.today.push(item); - } else if (dateStr === yesterdayStr) { - result.yesterday.push(item); - } else if (dateStr) { - // Group by date for older items - if (!olderDates[dateStr]) { - olderDates[dateStr] = []; - } - olderDates[dateStr].push(item); - } - }); - - // Convert older dates to array and sort by date (newest first) - result.older = Object.entries(olderDates) - .map(([date, items]) => ({ date, items })) - .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); - - return result; -}; - export const useHistoryData = (isOpen: boolean): HistoryData => { const [snapshots, setSnapshots] = useState([]); const [tasks, setTasks] = useState([]); const [isLoading, setIsLoading] = useState(true); - const groupedSnapshots = groupItemsByDate(snapshots); - const groupedTasks = groupItemsByDate(tasks); - - // Load data from storage with optimizations const loadData = () => { - setIsLoading(true); - let loadingComplete = false; - - // Create a timeout to ensure we don't show loading state for too long - const loadingTimeout = setTimeout(() => { - if (!loadingComplete) { - setIsLoading(false); - } - }, 500); - - // Performance optimization: Use promise.all to load data in parallel - Promise.all([ - // Load snapshots with caching - new Promise((resolve) => { - try { - const allSnapshots = snapshotStorage - .getAll() - .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()); - setSnapshots(allSnapshots); - } catch (snapshotError) { - console.error("Error loading snapshots:", snapshotError); - setSnapshots([]); - } - resolve(); - }), - - // Load tasks with caching - new Promise((resolve) => { - try { - const allTasks = taskStorage - .getAll() - .sort((a, b) => new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime()); - setTasks(allTasks); - } catch (taskError) { - console.error("Error loading tasks:", taskError); - setTasks([]); - } - resolve(); - }), - ]).then(() => { - loadingComplete = true; - clearTimeout(loadingTimeout); - setIsLoading(false); - }); + try { + setSnapshots( + snapshotStorage.getAll().sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()), + ); + } catch (snapshotError) { + console.error("Error loading snapshots:", snapshotError); + setSnapshots([]); + } + try { + setTasks( + taskStorage.getAll().sort((a, b) => new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime()), + ); + } catch (taskError) { + console.error("Error loading tasks:", taskError); + setTasks([]); + } + setIsLoading(false); }; // Initialize data @@ -251,8 +136,6 @@ export const useHistoryData = (isOpen: boolean): HistoryData => { return { snapshots, tasks, - groupedSnapshots, - groupedTasks, isLoading, handleRestoreSnapshot, handleDeleteSnapshot, diff --git a/src/features/integration/github/github-api.ts b/src/features/integration/github/github-api.ts index 47805212..5063d6c8 100644 --- a/src/features/integration/github/github-api.ts +++ b/src/features/integration/github/github-api.ts @@ -17,7 +17,7 @@ export type GitHubIssue = { * @param github_user_id The GitHub user ID to fetch issues for * @returns Promise with the list of issues assigned to the user */ -export const fetchAssignedIssues = async (github_user_id: string): Promise => { +const fetchAssignedIssues = async (github_user_id: string): Promise => { try { const response = await fetch(`https://api.github.com/search/issues?q=assignee:${github_user_id}+state:open`); diff --git a/src/features/menu/command-menu.tsx b/src/features/menu/command-menu.tsx index 78478f52..9547db52 100644 --- a/src/features/menu/command-menu.tsx +++ b/src/features/menu/command-menu.tsx @@ -7,10 +7,10 @@ import { showToast } from "../../utils/components/toast"; import { usePaperMode } from "../../utils/hooks/use-paper-mode"; import { COLOR_THEME } from "../../utils/theme-initializer"; import { useEditorWidth } from "../../utils/hooks/use-editor-width"; -import { FONT_FAMILIES, FONT_FAMILY_OPTIONS, fontFamilyAtom } from "../../utils/hooks/use-font"; +import { FONT_FAMILIES, fontFamilyAtom, nextFontFamily } from "../../utils/hooks/use-font"; import type { EditorView } from "@codemirror/view"; import { fetchGitHubIssuesTaskList } from "../integration/github/github-api"; -import { DprintMarkdownFormatter } from "../editor/markdown/formatter/dprint-markdown-formatter"; +import { formatEditorView, useMarkdownFormatter } from "../editor/markdown/formatter/format-editor"; import { Transaction } from "@codemirror/state"; import { CheckCircleIcon, @@ -28,29 +28,10 @@ import { GithubLogoIcon, CrosshairSimpleIcon, } from "@phosphor-icons/react"; -import { snapshotStorage } from "../snapshots/snapshot-storage"; +import { saveSnapshotWithToast } from "../snapshots/snapshot-storage"; import { useFocusMode } from "../../utils/hooks/use-focus-mode"; import { useAtom } from "jotai"; -// Custom hook for markdown formatter -const useMarkdownFormatter = () => { - const ref = useRef(null); - useEffect(() => { - let alive = true; - (async () => { - const fmt = await DprintMarkdownFormatter.getInstance(); - if (alive) { - ref.current = fmt; - } - })(); - return () => { - alive = false; - ref.current = null; - }; - }, []); - return ref; -}; - type CommandMenuProps = { open: boolean; onClose?: () => void; @@ -105,11 +86,7 @@ export const CommandMenu = ({ // which trips jsx-a11y/no-autofocus. const raf = requestAnimationFrame(() => inputRef.current?.focus()); const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - onClose(); - } else if (e.key === "k" && (e.ctrlKey || e.metaKey)) { + if (e.key === "Escape" || (e.key === "k" && (e.ctrlKey || e.metaKey))) { e.preventDefault(); e.stopPropagation(); onClose(); @@ -138,31 +115,17 @@ export const CommandMenu = ({ }; const cycleFont = () => { - const fontKeys = FONT_FAMILY_OPTIONS; - const currentIndex = fontKeys.indexOf(fontFamily); - const nextIndex = (currentIndex + 1) % fontKeys.length; - setFontFamily(fontKeys[nextIndex]); + setFontFamily(nextFontFamily(fontFamily)); onClose(); }; - const openTaskModal = () => { + const openHistoryTab = (tabIndex: number) => { if (!onOpenHistoryModal) return; onClose(); // Close command menu first // Use requestAnimationFrame to ensure command menu has completed its close animation requestAnimationFrame(() => { requestAnimationFrame(() => { - onOpenHistoryModal(0); - }); - }); - }; - - const openSnapshotModal = () => { - if (!onOpenHistoryModal) return; - onClose(); // Close command menu first - // Use requestAnimationFrame to ensure command menu has completed its close animation - requestAnimationFrame(() => { - requestAnimationFrame(() => { - onOpenHistoryModal(1); + onOpenHistoryModal(tabIndex); }); }); }; @@ -200,39 +163,7 @@ export const CommandMenu = ({ return; } try { - const { state } = editorView; - const scrollTop = editorView.scrollDOM.scrollTop; - const cursorPos = state.selection.main.head; - const cursorLine = state.doc.lineAt(cursorPos); - const cursorLineNumber = cursorLine.number; - const cursorColumn = cursorPos - cursorLine.from; - const currentText = state.doc.toString(); - const formattedText = await formatterRef.current.formatMarkdown(currentText); - - if (formattedText !== currentText) { - editorView.dispatch({ - changes: { from: 0, to: state.doc.length, insert: formattedText }, - annotations: Transaction.userEvent.of("input"), - }); - - // Restore cursor position after formatting - try { - const newState = editorView.state; - const newDocLineCount = newState.doc.lines; - if (cursorLineNumber <= newDocLineCount) { - const newLine = newState.doc.line(cursorLineNumber); - const newColumn = Math.min(cursorColumn, newLine.length); - const newPos = newLine.from + newColumn; - editorView.dispatch({ selection: { anchor: newPos, head: newPos } }); - } - } catch (_selectionError) { - editorView.dispatch({ selection: { anchor: 0, head: 0 } }); - } - editorView.scrollDOM.scrollTop = Math.min( - scrollTop, - editorView.scrollDOM.scrollHeight - editorView.scrollDOM.clientHeight, - ); - } + await formatEditorView(editorView, formatterRef.current, Transaction.userEvent.of("input")); } catch (error) { const message = error instanceof Error ? error.message : "unknown"; showToast(`Error formatting document: ${message}`, "error"); @@ -283,24 +214,8 @@ export const CommandMenu = ({ }; const handleSaveSnapshot = () => { - if (!editorContent) { - showToast("No content to save", "error"); - onClose(); - return; - } - - try { - snapshotStorage.save({ - content: editorContent, - charCount: editorContent.length, - }); - showToast("Snapshot saved", "default"); - } catch (error) { - const message = error instanceof Error ? error.message : "unknown"; - showToast(`Error saving snapshot: ${message}`, "error"); - } finally { - onClose(); - } + saveSnapshotWithToast(editorContent); + onClose(); }; const commandsList = (): CommandItem[] => { @@ -377,14 +292,14 @@ export const CommandMenu = ({ id: "open-tasks", name: "Open task modal", icon: , - perform: openTaskModal, + perform: () => openHistoryTab(0), }); list.push({ id: "open-snapshots", name: "Open snapshot modal", icon: , - perform: openSnapshotModal, + perform: () => openHistoryTab(1), }); list.push({ diff --git a/src/features/menu/system-menu.tsx b/src/features/menu/system-menu.tsx index 8481af39..f8e1d239 100644 --- a/src/features/menu/system-menu.tsx +++ b/src/features/menu/system-menu.tsx @@ -5,7 +5,7 @@ import { usePaperMode, type PaperMode } from "../../utils/hooks/use-paper-mode"; import { useEditorWidth, type EditorWidth } from "../../utils/hooks/use-editor-width"; import { useCharCount } from "../../utils/hooks/use-char-count"; import { useWordCount } from "../../utils/hooks/use-word-count"; -import { FONT_FAMILY_OPTIONS, fontFamilyAtom, currentFontDisplayValueAtom } from "../../utils/hooks/use-font"; +import { fontFamilyAtom, currentFontDisplayValueAtom, nextFontFamily } from "../../utils/hooks/use-font"; import { CURSOR_COLORS, CURSOR_COLOR_OPTIONS, @@ -28,6 +28,7 @@ import { } from "@phosphor-icons/react"; import { taskStorage } from "../editor/tasks/task-storage"; import { snapshotStorage } from "../snapshots/snapshot-storage"; +import { formatDateKey } from "../../utils/storage"; import { useTaskAutoFlush, type TaskAutoFlushMode } from "../../utils/hooks/use-task-auto-flush"; import { useFocusMode, type FocusMode } from "../../utils/hooks/use-focus-mode"; import { useAtom, useAtomValue } from "jotai"; @@ -86,12 +87,7 @@ const useTodayCompletedTasks = (menuOpen: boolean) => { month: today.getMonth() + 1, day: today.getDate(), }); - const todayDateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart( - 2, - "0", - )}-${String(today.getDate()).padStart(2, "0")}`; - - setTodayCompletedTasks(tasksByDate[todayDateStr]?.length ?? 0); + setTodayCompletedTasks(tasksByDate[formatDateKey(today)]?.length ?? 0); }, [menuOpen]); return { todayCompletedTasks }; @@ -313,14 +309,14 @@ export const SystemMenu = ({ }; const cycleFont = () => { - const currentIndex = FONT_FAMILY_OPTIONS.indexOf(fontFamily); - setFontFamily(FONT_FAMILY_OPTIONS[(currentIndex + 1) % FONT_FAMILY_OPTIONS.length]); + setFontFamily(nextFontFamily(fontFamily)); restoreEditorFocusSoon(); }; useEffect(() => { + if (!menuOpen) return; const handleClickOutside = (event: MouseEvent) => { - if (menuRef.current && !menuRef.current.contains(event.target as Node) && menuOpen) { + if (menuRef.current && !menuRef.current.contains(event.target as Node)) { setMenuOpen(false); } }; diff --git a/src/features/snapshots/snapshot-storage.ts b/src/features/snapshots/snapshot-storage.ts index bcd81939..4d65a81f 100644 --- a/src/features/snapshots/snapshot-storage.ts +++ b/src/features/snapshots/snapshot-storage.ts @@ -1,13 +1,6 @@ import { LOCAL_STORAGE_KEYS } from "../../utils/constants"; -import { - type StorageProvider, - createBrowserLocalStorage, - createStorage, - type DateFilter, - filterItemsByDate, - groupItemsByDate, - defaultStorageProvider, -} from "../../utils/storage"; +import { showToast } from "../../utils/components/toast"; +import { type StorageProvider, createStorage, type DateFilter, defaultStorageProvider } from "../../utils/storage"; type SnapshotStorage = { getAll: () => Snapshot[]; @@ -19,7 +12,7 @@ type SnapshotStorage = { }; // Snapshot Storage factory function -const createSnapshotStorage = (storage: StorageProvider = createBrowserLocalStorage()): SnapshotStorage => { +const createSnapshotStorage = (storage: StorageProvider): SnapshotStorage => { const baseStorage = createStorage(storage, LOCAL_STORAGE_KEYS.SNAPSHOTS); const save = (snapshot: Omit): void => { @@ -35,16 +28,9 @@ const createSnapshotStorage = (storage: StorageProvider = createBrowserLocalStor baseStorage.save(newSnapshot); }; - const getByDate = (filter?: DateFilter): Record => { - const snapshots = baseStorage.getAll(); - const filteredSnapshots = filterItemsByDate(snapshots, filter); - return groupItemsByDate(filteredSnapshots); - }; - return { ...baseStorage, save, - getByDate, }; }; @@ -56,3 +42,20 @@ export type Snapshot = { content: string; charCount: number; }; + +/** Saves `content` as a snapshot and reports the result with a toast. Returns whether it was saved. */ +export const saveSnapshotWithToast = (content: string): boolean => { + if (!content) { + showToast("No content to save", "error"); + return false; + } + try { + snapshotStorage.save({ content, charCount: content.length }); + showToast("Snapshot saved", "default"); + return true; + } catch (error) { + const message = error instanceof Error ? error.message : "unknown"; + showToast(`Error saving snapshot: ${message}`, "error"); + return false; + } +}; diff --git a/src/page/editor-page.tsx b/src/page/editor-page.tsx index cdfc6df7..c21eae4b 100644 --- a/src/page/editor-page.tsx +++ b/src/page/editor-page.tsx @@ -67,8 +67,7 @@ export const EditorPage = () => { // Unified snapshot restore event handler useEffect(() => { const handleContentRestored = (event: CustomEvent<{ content: string }>) => { - const customEvent = event; - const restoredContent = customEvent.detail.content; + const restoredContent = event.detail.content; // Route to appropriate editor based on mode if (editorMode === "multi" && multiEditorRef.current) { multiEditorRef.current.setContent(restoredContent); diff --git a/src/utils/atoms/active-content.ts b/src/utils/atoms/active-content.ts new file mode 100644 index 00000000..91355391 --- /dev/null +++ b/src/utils/atoms/active-content.ts @@ -0,0 +1,12 @@ +import { atom } from "jotai"; +import { editorModeAtom } from "../hooks/use-editor-mode"; +import { editorContentAtom } from "./editor"; +import { activeDocumentIndexAtom, documentsAtom } from "./multi-document"; + +// Content of the document currently being edited, in either editor mode +export const activeContentAtom = atom((get) => { + if (get(editorModeAtom) === "multi") { + return get(documentsAtom)[get(activeDocumentIndexAtom)]?.content ?? ""; + } + return get(editorContentAtom); +}); diff --git a/src/utils/atoms/cross-tab-storage.ts b/src/utils/atoms/cross-tab-storage.ts new file mode 100644 index 00000000..d1001c08 --- /dev/null +++ b/src/utils/atoms/cross-tab-storage.ts @@ -0,0 +1,48 @@ +// localStorage-backed jotai storage that also syncs changes made in other tabs +export const createCrossTabStorage = () => { + return { + getItem: (key: string, initialValue: T): T => { + if (typeof window === "undefined") { + return initialValue; + } + const item = localStorage.getItem(key); + if (item === null) { + return initialValue; + } + try { + return JSON.parse(item); + } catch { + return initialValue; + } + }, + setItem: (key: string, value: T): void => { + if (typeof window === "undefined") { + return; + } + localStorage.setItem(key, JSON.stringify(value)); + }, + removeItem: (key: string): void => { + if (typeof window === "undefined") { + return; + } + localStorage.removeItem(key); + }, + subscribe: (key: string, callback: (value: T) => void, initialValue: T): (() => void) => { + if (typeof window === "undefined" || typeof window.addEventListener !== "function") { + return () => {}; + } + const handler = (e: StorageEvent) => { + if (e.storageArea === localStorage && e.key === key) { + try { + const newValue = e.newValue ? JSON.parse(e.newValue) : initialValue; + callback(newValue); + } catch { + callback(initialValue); + } + } + }; + window.addEventListener("storage", handler); + return () => window.removeEventListener("storage", handler); + }, + }; +}; diff --git a/src/utils/atoms/editor.ts b/src/utils/atoms/editor.ts index 3fcae9ca..477bb541 100644 --- a/src/utils/atoms/editor.ts +++ b/src/utils/atoms/editor.ts @@ -1,27 +1,9 @@ -import { atomWithStorage, createJSONStorage } from "jotai/utils"; +import { atomWithStorage } from "jotai/utils"; import { LOCAL_STORAGE_KEYS } from "../constants"; +import { createCrossTabStorage } from "./cross-tab-storage"; -const storage = createJSONStorage(() => localStorage); - -const crossTabStorage = { - ...storage, - subscribe: (key: string, callback: (value: string) => void, initialValue: string): (() => void) => { - if (typeof window === "undefined" || typeof window.addEventListener !== "function") { - return () => {}; - } - const handler = (e: StorageEvent) => { - if (e.storageArea === localStorage && e.key === key) { - try { - const newValue = e.newValue ? JSON.parse(e.newValue) : initialValue; - callback(newValue); - } catch { - callback(initialValue); - } - } - }; - window.addEventListener("storage", handler); - return () => window.removeEventListener("storage", handler); - }, -}; - -export const editorContentAtom = atomWithStorage(LOCAL_STORAGE_KEYS.EDITOR_CONTENT, "", crossTabStorage); +export const editorContentAtom = atomWithStorage( + LOCAL_STORAGE_KEYS.EDITOR_CONTENT, + "", + createCrossTabStorage(), +); diff --git a/src/utils/atoms/multi-document.ts b/src/utils/atoms/multi-document.ts index 9a2caa83..686bd44f 100644 --- a/src/utils/atoms/multi-document.ts +++ b/src/utils/atoms/multi-document.ts @@ -1,54 +1,6 @@ import { atomWithStorage } from "jotai/utils"; import { LOCAL_STORAGE_KEYS } from "../constants"; - -// Create cross-tab storage adapter for multi-document support -const createCrossTabStorage = () => { - return { - getItem: (key: string, initialValue: T): T => { - if (typeof window === "undefined") { - return initialValue; - } - const item = localStorage.getItem(key); - if (item === null) { - return initialValue; - } - try { - return JSON.parse(item); - } catch { - return initialValue; - } - }, - setItem: (key: string, value: T): void => { - if (typeof window === "undefined") { - return; - } - localStorage.setItem(key, JSON.stringify(value)); - }, - removeItem: (key: string): void => { - if (typeof window === "undefined") { - return; - } - localStorage.removeItem(key); - }, - subscribe: (key: string, callback: (value: T) => void, initialValue: T): (() => void) => { - if (typeof window === "undefined" || typeof window.addEventListener !== "function") { - return () => {}; - } - const handler = (e: StorageEvent) => { - if (e.storageArea === localStorage && e.key === key) { - try { - const newValue = e.newValue ? JSON.parse(e.newValue) : initialValue; - callback(newValue); - } catch { - callback(initialValue); - } - } - }; - window.addEventListener("storage", handler); - return () => window.removeEventListener("storage", handler); - }, - }; -}; +import { createCrossTabStorage } from "./cross-tab-storage"; // Document interface for multi-document support export type Document = { @@ -58,7 +10,7 @@ export type Document = { }; // Default documents initialization -export const DEFAULT_DOCUMENTS: Document[] = Array.from({ length: 5 }, (_, i) => ({ +const DEFAULT_DOCUMENTS: Document[] = Array.from({ length: 5 }, (_, i) => ({ id: `doc-${i}`, content: "", lastModified: Date.now(), diff --git a/src/utils/components/error-boundary.tsx b/src/utils/components/error-boundary.tsx deleted file mode 100644 index 24452532..00000000 --- a/src/utils/components/error-boundary.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { Component, type ErrorInfo, type ReactNode } from "react"; - -type Props = { - children: ReactNode; - fallback?: ReactNode; -}; - -type State = { - hasError: boolean; - error?: Error; -}; - -export class ErrorBoundary extends Component { - constructor(props: Props) { - super(props); - this.state = { hasError: false }; - } - - static getDerivedStateFromError(error: Error): State { - return { hasError: true, error }; - } - - componentDidCatch(error: Error, errorInfo: ErrorInfo): void { - console.error("Error caught by ErrorBoundary:", error, errorInfo); - } - - render(): ReactNode { - if (this.state.hasError) { - return ( - this.props.fallback || ( -
-

Something went wrong.

-
- Error details -
{this.state.error?.toString()}
-
- -
- ) - ); - } - - return this.props.children; - } -} diff --git a/src/utils/components/loading.tsx b/src/utils/components/loading.tsx deleted file mode 100644 index 9bd8cf41..00000000 --- a/src/utils/components/loading.tsx +++ /dev/null @@ -1,11 +0,0 @@ -type LoadingProps = { - className?: string; -}; - -export const Loading = ({ className }: LoadingProps) => { - return ( -
-
-
- ); -}; diff --git a/src/utils/hooks/use-char-count.ts b/src/utils/hooks/use-char-count.ts index 36d28731..d7abfd3c 100644 --- a/src/utils/hooks/use-char-count.ts +++ b/src/utils/hooks/use-char-count.ts @@ -1,19 +1,7 @@ -import { useAtomValue } from "jotai"; -import { atom } from "jotai"; -import { editorModeAtom } from "./use-editor-mode"; -import { activeDocumentIndexAtom, documentsAtom } from "../atoms/multi-document"; -import { editorContentAtom } from "../atoms/editor"; +import { atom, useAtomValue } from "jotai"; +import { activeContentAtom } from "../atoms/active-content"; -const charCountAtom = atom((get) => { - const mode = get(editorModeAtom); - - if (mode === "multi") { - const docs = get(documentsAtom); - const idx = get(activeDocumentIndexAtom); - return (docs[idx]?.content ?? "").length; - } - return get(editorContentAtom).length; -}); +const charCountAtom = atom((get) => get(activeContentAtom).length); export const useCharCount = () => { const charCount = useAtomValue(charCountAtom); diff --git a/src/utils/hooks/use-focus-mode.ts b/src/utils/hooks/use-focus-mode.ts index 3192718a..e16701ea 100644 --- a/src/utils/hooks/use-focus-mode.ts +++ b/src/utils/hooks/use-focus-mode.ts @@ -4,7 +4,7 @@ import { useAtom } from "jotai"; export type FocusMode = "off" | "on"; -export const focusModeAtom = atomWithStorage(LOCAL_STORAGE_KEYS.FOCUS_MODE, "off"); +const focusModeAtom = atomWithStorage(LOCAL_STORAGE_KEYS.FOCUS_MODE, "off"); export const useFocusMode = () => { const [focusMode, setFocusMode] = useAtom(focusModeAtom); diff --git a/src/utils/hooks/use-font.ts b/src/utils/hooks/use-font.ts index a255345b..2d9c265e 100644 --- a/src/utils/hooks/use-font.ts +++ b/src/utils/hooks/use-font.ts @@ -26,6 +26,9 @@ export const FONT_FAMILIES = { export type FontFamily = keyof typeof FONT_FAMILIES; export const FONT_FAMILY_OPTIONS = Object.keys(FONT_FAMILIES) as (keyof typeof FONT_FAMILIES)[]; +export const nextFontFamily = (current: FontFamily): FontFamily => + FONT_FAMILY_OPTIONS[(FONT_FAMILY_OPTIONS.indexOf(current) + 1) % FONT_FAMILY_OPTIONS.length]; + export const fontFamilyAtom = atomWithStorage(LOCAL_STORAGE_KEYS.FONT_FAMILY, "IA_WRITER_MONO"); export const currentFontValueAtom = atom((get) => FONT_FAMILIES[get(fontFamilyAtom)].value); diff --git a/src/utils/hooks/use-task-auto-flush.ts b/src/utils/hooks/use-task-auto-flush.ts index 730ffd67..cf1057ef 100644 --- a/src/utils/hooks/use-task-auto-flush.ts +++ b/src/utils/hooks/use-task-auto-flush.ts @@ -4,7 +4,7 @@ import { useAtom } from "jotai"; export type TaskAutoFlushMode = "off" | "instant"; -export const taskAutoFlushAtom = atomWithStorage(LOCAL_STORAGE_KEYS.TASK_AUTO_FLUSH_MODE, "off"); +const taskAutoFlushAtom = atomWithStorage(LOCAL_STORAGE_KEYS.TASK_AUTO_FLUSH_MODE, "off"); export const useTaskAutoFlush = () => { const [taskAutoFlushMode, setTaskAutoFlushMode] = useAtom(taskAutoFlushAtom); diff --git a/src/utils/hooks/use-word-count.ts b/src/utils/hooks/use-word-count.ts index b37010d6..bcb001b2 100644 --- a/src/utils/hooks/use-word-count.ts +++ b/src/utils/hooks/use-word-count.ts @@ -1,23 +1,8 @@ -import { useAtomValue } from "jotai"; -import { atom } from "jotai"; -import { editorContentAtom } from "../atoms/editor"; -import { editorModeAtom } from "./use-editor-mode"; -import { documentsAtom, activeDocumentIndexAtom } from "../atoms/multi-document"; +import { atom, useAtomValue } from "jotai"; +import { activeContentAtom } from "../atoms/active-content"; // Derive word count from editor content -export const wordCountAtom = atom((get) => { - const mode = get(editorModeAtom); - - if (mode === "multi") { - const docs = get(documentsAtom); - const idx = get(activeDocumentIndexAtom); - const content = docs[idx]?.content; - return countWords(content); - } - - const singleEditorContent = get(editorContentAtom); - return countWords(singleEditorContent); -}); +const wordCountAtom = atom((get) => countWords(get(activeContentAtom))); // Hook to use word count export const useWordCount = () => { diff --git a/src/utils/storage/index.ts b/src/utils/storage/index.ts index f206dda9..5fd93719 100644 --- a/src/utils/storage/index.ts +++ b/src/utils/storage/index.ts @@ -17,10 +17,11 @@ type Storage = { save: (item: T) => void; deleteById: (id: string) => void; deleteAll: () => void; + getByDate: (filter?: DateFilter) => Record; }; // Create browser local storage provider -export const createBrowserLocalStorage = (): StorageProvider => ({ +const createBrowserLocalStorage = (): StorageProvider => ({ getItem: (key: string): string | null => localStorage.getItem(key), setItem: (key: string, value: string): void => localStorage.setItem(key, value), }); @@ -29,19 +30,15 @@ export const createBrowserLocalStorage = (): StorageProvider => ({ export const formatDateKey = (date: Date): string => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; -export const filterItemsByDate = ( - items: T[], - filter?: DateFilter, -): T[] => { +type DatedItem = { timestamp?: string; completedAt?: string }; + +const getItemDate = (item: DatedItem): string => item.timestamp || item.completedAt || ""; + +export const filterItemsByDate = (items: T[], filter?: DateFilter): T[] => { if (!filter) return items; return items.filter((item) => { - const dateStr = - "timestamp" in item && item.timestamp - ? item.timestamp - : "completedAt" in item && item.completedAt - ? item.completedAt - : ""; + const dateStr = getItemDate(item); if (!dateStr) return false; @@ -59,18 +56,11 @@ export const filterItemsByDate = ( - items: T[], -): Record => { +export const groupItemsByDate = (items: T[]): Record => { const itemsByDate: Record = {}; for (const item of items) { - const dateStr = - "timestamp" in item && item.timestamp - ? item.timestamp - : "completedAt" in item && item.completedAt - ? item.completedAt - : ""; + const dateStr = getItemDate(item); if (!dateStr) continue; @@ -87,7 +77,10 @@ export const groupItemsByDate = (storage: StorageProvider, storageKey: string): Storage => { +export const createStorage = ( + storage: StorageProvider, + storageKey: string, +): Storage => { const getAll = (): T[] => { try { const itemsJson = storage.getItem(storageKey); @@ -130,12 +123,15 @@ export const createStorage = (storage: StorageProvider } }; + const getByDate = (filter?: DateFilter): Record => groupItemsByDate(filterItemsByDate(getAll(), filter)); + return { getAll, getById, save, - deleteById: deleteById, - deleteAll: deleteAll, + deleteById, + deleteAll, + getByDate, }; };