Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
25 changes: 0 additions & 25 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

78 changes: 25 additions & 53 deletions src/features/editor/codemirror/tasklist/task-close.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ".";

Expand All @@ -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 = {
Expand Down Expand Up @@ -53,7 +53,7 @@ export const registerTaskHandler = (handler: TaskHandler | undefined): void => {
globalTaskHandler = handler;
};

export const getRegisteredTaskHandler = (): TaskHandler | undefined => {
const getRegisteredTaskHandler = (): TaskHandler | undefined => {
return globalTaskHandler;
};

Expand All @@ -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[] = [];
Expand All @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 1 addition & 2 deletions src/features/editor/codemirror/tasklist/task-reorder.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
};
43 changes: 0 additions & 43 deletions src/features/editor/codemirror/use-cursor-position.ts

This file was deleted.

80 changes: 7 additions & 73 deletions src/features/editor/codemirror/use-markdown-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<DprintMarkdownFormatter | null>(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));
Expand Down Expand Up @@ -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(() => {
Expand All @@ -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) {
Expand All @@ -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(() => {
Expand Down
Loading
Loading