Add interactive task lists and table insertion to markdown editor

- Enable task list checkbox toggling in preview mode with live content updates
- Add task list and table insertion buttons to InsertToolbar
- Implement smart block snippet insertion with automatic newline handling
- Add horizontal scroll wrapper for wide tables in preview
- Fix editor scroll position preservation during content updates
- Use useLayoutEffect to prevent scroll jumps when textarea auto-resizes
- Update task list styling
This commit is contained in:
drelich
2026-04-06 16:15:43 +02:00
parent aba090a8ad
commit 6bc67a3118
5 changed files with 275 additions and 33 deletions

View File

@@ -3,6 +3,8 @@ import { useEffect, useState, useRef, RefObject } from 'react';
interface InsertToolbarProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
onInsertLink: (text: string, url: string) => void;
onInsertTodoItem: () => void;
onInsertTable: () => void;
onInsertFile: () => void;
isUploading?: boolean;
}
@@ -13,7 +15,7 @@ interface LinkModalState {
url: string;
}
export function InsertToolbar({ textareaRef, onInsertLink, onInsertFile, isUploading }: InsertToolbarProps) {
export function InsertToolbar({ textareaRef, onInsertLink, onInsertTodoItem, onInsertTable, onInsertFile, isUploading }: InsertToolbarProps) {
const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
const [isVisible, setIsVisible] = useState(false);
const [linkModal, setLinkModal] = useState<LinkModalState>({ isOpen: false, text: '', url: '' });
@@ -58,7 +60,7 @@ export function InsertToolbar({ textareaRef, onInsertLink, onInsertFile, isUploa
const left = textareaRect.left + paddingLeft + (currentLineText.length * charWidth) + 20;
// Keep toolbar within viewport
const toolbarWidth = 100;
const toolbarWidth = 196;
const adjustedLeft = Math.min(left, window.innerWidth - toolbarWidth - 20);
let adjustedTop = top - 16; // Center vertically with cursor line
@@ -137,6 +139,16 @@ export function InsertToolbar({ textareaRef, onInsertLink, onInsertFile, isUploa
setIsVisible(false);
};
const handleTodoClick = () => {
onInsertTodoItem();
setIsVisible(false);
};
const handleTableClick = () => {
onInsertTable();
setIsVisible(false);
};
if (!isVisible || !position) return null;
// Link Modal
@@ -218,6 +230,28 @@ export function InsertToolbar({ textareaRef, onInsertLink, onInsertFile, isUploa
</svg>
</button>
<button
onClick={handleTodoClick}
className="p-2 rounded hover:bg-gray-700 dark:hover:bg-gray-600 text-white transition-colors"
title="Insert To-Do Item"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 7h11M9 12h11M9 17h11M4 7h.01M4 12h.01M4 17h.01" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m3.5 12.5 1.5 1.5 3-3" />
</svg>
</button>
<button
onClick={handleTableClick}
className="p-2 rounded hover:bg-gray-700 dark:hover:bg-gray-600 text-white transition-colors"
title="Insert Table"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5h16v14H4V5Z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 10h16M10 5v14" />
</svg>
</button>
<button
onClick={handleFileClick}
disabled={isUploading}

View File

@@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useLayoutEffect, useRef } from 'react';
import { marked } from 'marked';
import { Note } from '../types';
import { NextcloudAPI } from '../api/nextcloud';
@@ -34,12 +34,80 @@ interface NoteEditorProps {
const imageCache = new Map<string, string>();
const TASK_LIST_ITEM_REGEX = /^(\s*(?:[-+*]|\d+\.)\s)\[( |x|X)\]\s/;
// Configure marked to support task lists
marked.use({
gfm: true,
breaks: true,
});
function getTaskListMarkers(markdown: string) {
const markers: Array<{ markerStart: number; markerEnd: number }> = [];
const lines = markdown.split('\n');
let offset = 0;
let activeFence: string | null = null;
lines.forEach((line, index) => {
const fenceMatch = line.match(/^\s*(`{3,}|~{3,})/);
if (fenceMatch) {
const fence = fenceMatch[1];
if (!activeFence) {
activeFence = fence;
} else if (fence[0] === activeFence[0] && fence.length >= activeFence.length) {
activeFence = null;
}
} else if (!activeFence) {
const taskMatch = line.match(TASK_LIST_ITEM_REGEX);
if (taskMatch) {
const markerStart = offset + taskMatch[1].length;
markers.push({
markerStart,
markerEnd: markerStart + 3,
});
}
}
offset += line.length;
if (index < lines.length - 1) {
offset += 1;
}
});
return markers;
}
function toggleTaskListMarker(markdown: string, taskIndex: number, checked: boolean) {
const taskMarker = getTaskListMarkers(markdown)[taskIndex];
if (!taskMarker) {
return markdown;
}
const nextMarker = checked ? '[x]' : '[ ]';
return `${markdown.slice(0, taskMarker.markerStart)}${nextMarker}${markdown.slice(taskMarker.markerEnd)}`;
}
function renderPreviewHtml(markdown: string) {
const parsedHtml = marked.parse(markdown || '', { async: false }) as string;
const documentFragment = new DOMParser().parseFromString(parsedHtml, 'text/html');
documentFragment.querySelectorAll<HTMLInputElement>('input[type="checkbox"]').forEach((input, index) => {
input.removeAttribute('disabled');
input.classList.add('markdown-task-checkbox');
input.setAttribute('data-task-index', String(index));
input.setAttribute('aria-label', `Toggle task ${index + 1}`);
});
documentFragment.querySelectorAll('table').forEach((table) => {
const wrapper = documentFragment.createElement('div');
wrapper.className = 'markdown-table-wrapper';
table.parentNode?.insertBefore(wrapper, table);
wrapper.appendChild(table);
});
return documentFragment.body.innerHTML;
}
export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onToggleFavorite, categories, isFocusMode, onToggleFocusMode, editorFont = 'Source Code Pro', editorFontSize = 14, previewFont = 'Merriweather', previewFontSize = 16, api }: NoteEditorProps) {
const [localContent, setLocalContent] = useState('');
const [localCategory, setLocalCategory] = useState('');
@@ -51,7 +119,10 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
const [isUploading, setIsUploading] = useState(false);
const previousDraftIdRef = useRef<string | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const editorScrollContainerRef = useRef<HTMLDivElement>(null);
const previewContentRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const pendingScrollTopRef = useRef<number | null>(null);
const desktopRuntime = getDesktopRuntime();
const exportActionLabel = desktopRuntime === 'electron' ? 'Export PDF' : 'Print Note';
const hasUnsavedChanges = Boolean(note?.pendingSave);
@@ -71,26 +142,39 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isFocusMode, onToggleFocusMode]);
// Auto-resize textarea when content changes, switching from preview to edit, or font size changes
useEffect(() => {
if (textareaRef.current && !isPreviewMode) {
// Use setTimeout to ensure DOM has updated
setTimeout(() => {
if (textareaRef.current) {
// Save cursor position and scroll position
const cursorPosition = textareaRef.current.selectionStart;
const scrollTop = textareaRef.current.scrollTop;
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px';
// Restore cursor position and scroll position
textareaRef.current.setSelectionRange(cursorPosition, cursorPosition);
textareaRef.current.scrollTop = scrollTop;
const captureEditorScrollPosition = () => {
if (editorScrollContainerRef.current) {
pendingScrollTopRef.current = editorScrollContainerRef.current.scrollTop;
}
}, 0);
};
// Keep the editor pane anchored when the textarea grows with new content.
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea || isPreviewMode) {
pendingScrollTopRef.current = null;
return;
}
}, [localContent, isPreviewMode, editorFontSize]);
const selectionStart = textarea.selectionStart;
const selectionEnd = textarea.selectionEnd;
const shouldRestoreSelection = document.activeElement === textarea;
const scrollContainer = editorScrollContainerRef.current;
const scrollTop = pendingScrollTopRef.current ?? scrollContainer?.scrollTop ?? null;
textarea.style.height = 'auto';
textarea.style.height = `${textarea.scrollHeight}px`;
if (scrollContainer && scrollTop !== null) {
scrollContainer.scrollTop = scrollTop;
}
if (shouldRestoreSelection) {
textarea.setSelectionRange(selectionStart, selectionEnd);
}
pendingScrollTopRef.current = null;
}, [localContent, isPreviewMode, editorFontSize, note?.draftId]);
// Process images when entering preview mode or content changes
useEffect(() => {
@@ -175,6 +259,36 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
}
}, [note?.draftId, note?.content, note?.category, note?.favorite, localCategory, localContent, localFavorite]);
useEffect(() => {
const previewElement = previewContentRef.current;
if (!previewElement || !isPreviewMode) {
return;
}
const handleTaskToggle = (event: Event) => {
const target = event.target;
if (!(target instanceof HTMLInputElement) || target.type !== 'checkbox') {
return;
}
const taskIndex = Number(target.dataset.taskIndex);
if (Number.isNaN(taskIndex)) {
return;
}
const newContent = toggleTaskListMarker(localContent, taskIndex, target.checked);
if (newContent === localContent) {
return;
}
setLocalContent(newContent);
emitNoteChange(newContent, localCategory, localFavorite);
};
previewElement.addEventListener('change', handleTaskToggle);
return () => previewElement.removeEventListener('change', handleTaskToggle);
}, [isPreviewMode, localContent, localCategory, localFavorite]);
const emitNoteChange = (content: string, category: string, favorite: boolean) => {
if (!note) {
return;
@@ -190,6 +304,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
};
const handleContentChange = (value: string) => {
captureEditorScrollPosition();
setLocalContent(value);
emitNoteChange(value, localCategory, localFavorite);
};
@@ -298,6 +413,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
// Insert at cursor position or end of content
const textarea = textareaRef.current;
if (textarea) {
captureEditorScrollPosition();
const cursorPos = textarea.selectionStart;
const newContent = localContent.slice(0, cursorPos) + markdownLink + localContent.slice(cursorPos);
setLocalContent(newContent);
@@ -339,6 +455,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
const textarea = textareaRef.current;
if (!textarea) return;
captureEditorScrollPosition();
const cursorPos = textarea.selectionStart;
const markdownLink = `[${text}](${url})`;
const newContent = localContent.slice(0, cursorPos) + markdownLink + localContent.slice(cursorPos);
@@ -356,6 +473,44 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
fileInputRef.current?.click();
};
const insertBlockSnippet = (snippet: string, selectionStartOffset: number, selectionEndOffset: number) => {
const textarea = textareaRef.current;
const cursorPos = textarea?.selectionStart ?? localContent.length;
const needsLeadingNewline = cursorPos > 0 && localContent[cursorPos - 1] !== '\n';
const needsTrailingNewline = cursorPos < localContent.length && localContent[cursorPos] !== '\n';
const prefix = needsLeadingNewline ? '\n' : '';
const suffix = needsTrailingNewline ? '\n' : '';
const insertedText = `${prefix}${snippet}${suffix}`;
const newContent = `${localContent.slice(0, cursorPos)}${insertedText}${localContent.slice(cursorPos)}`;
captureEditorScrollPosition();
setLocalContent(newContent);
emitNoteChange(newContent, localCategory, localFavorite);
if (!textarea) {
return;
}
setTimeout(() => {
textarea.focus();
const selectionStart = cursorPos + prefix.length + selectionStartOffset;
const selectionEnd = cursorPos + prefix.length + selectionEndOffset;
textarea.setSelectionRange(selectionStart, selectionEnd);
}, 0);
};
const handleInsertTodoItem = () => {
const snippet = '- [ ] Task';
const placeholderStart = snippet.indexOf('Task');
insertBlockSnippet(snippet, placeholderStart, placeholderStart + 'Task'.length);
};
const handleInsertTable = () => {
const snippet = '| Column 1 | Column 2 |\n| --- | --- |\n| Value 1 | Value 2 |';
const placeholderStart = snippet.indexOf('Column 1');
insertBlockSnippet(snippet, placeholderStart, placeholderStart + 'Column 1'.length);
};
const handleFormat = (format: 'bold' | 'italic' | 'strikethrough' | 'code' | 'codeblock' | 'quote' | 'ul' | 'ol' | 'link' | 'h1' | 'h2' | 'h3') => {
if (!textareaRef.current) return;
@@ -482,6 +637,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
}
const newContent = localContent.substring(0, start) + formattedText + localContent.substring(end);
captureEditorScrollPosition();
setLocalContent(newContent);
emitNoteChange(newContent, localCategory, localFavorite);
@@ -693,7 +849,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
</div>
</div>
<div className="flex-1 overflow-y-auto">
<div ref={editorScrollContainerRef} className="flex-1 overflow-y-auto">
<div className={`min-h-full ${isFocusMode ? 'max-w-3xl mx-auto w-full' : ''}`}>
{isPreviewMode ? (
<div className="relative">
@@ -707,10 +863,11 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
</div>
)}
<div
ref={previewContentRef}
className={`prose prose-slate dark:prose-invert p-8 ${isFocusMode ? '' : 'max-w-none'} [&_code]:font-mono [&_pre]:font-mono [&_code]:py-0 [&_code]:px-1 [&_code]:align-baseline [&_code]:leading-none [&_img]:max-w-full [&_img]:rounded-lg [&_img]:shadow-md`}
style={{ fontSize: `${previewFontSize}px`, fontFamily: previewFont }}
dangerouslySetInnerHTML={{
__html: marked.parse(processedContent || '', { async: false }) as string
__html: renderPreviewHtml(processedContent || '')
}}
/>
</div>
@@ -720,6 +877,8 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
<InsertToolbar
textareaRef={textareaRef}
onInsertLink={handleInsertLink}
onInsertTodoItem={handleInsertTodoItem}
onInsertTable={handleInsertTable}
onInsertFile={handleInsertFile}
isUploading={isUploading}
/>
@@ -733,12 +892,7 @@ export function NoteEditor({ note, onChangeNote, onSaveNote, onDiscardNote, onTo
<textarea
ref={textareaRef}
value={localContent}
onChange={(e) => {
handleContentChange(e.target.value);
// Auto-resize textarea to fit content
e.target.style.height = 'auto';
e.target.style.height = e.target.scrollHeight + 'px';
}}
onChange={(e) => handleContentChange(e.target.value)}
className="w-full resize-none border-none outline-none focus:ring-0 bg-transparent text-gray-900 dark:text-gray-100 overflow-hidden"
style={{ fontSize: `${editorFontSize}px`, lineHeight: '1.6', minHeight: '100%', fontFamily: editorFont }}
placeholder="Start writing in markdown..."

View File

@@ -289,6 +289,28 @@ export function PrintView({ jobId }: PrintViewProps) {
color: #334155;
}
.print-note ul:has(> li > input[type="checkbox"]) {
list-style: none;
padding-left: 0;
}
.print-note li:has(> input[type="checkbox"]) {
list-style: none;
display: flex;
align-items: flex-start;
gap: 0.55em;
padding-left: 0;
}
.print-note li:has(> input[type="checkbox"])::marker {
content: '';
}
.print-note li > input[type="checkbox"] {
flex-shrink: 0;
margin: 0.3em 0 0;
}
.print-note blockquote {
margin: 1.15em 0;
padding-left: 1em;

View File

@@ -232,10 +232,20 @@ code {
height: 1.25rem;
margin-right: 0.75rem;
margin-top: 0.32rem;
cursor: default;
cursor: pointer;
flex-shrink: 0;
}
.prose input[type="checkbox"]:checked {
accent-color: #16a34a;
}
.prose .markdown-table-wrapper {
overflow-x: auto;
margin: 1.5em 0;
}
.prose .markdown-table-wrapper table {
margin: 0;
min-width: 100%;
}

View File

@@ -261,6 +261,28 @@ export const buildPrintDocument = (payload: PrintExportPayload) => {
color: #334155;
}
.print-note ul:has(> li > input[type="checkbox"]) {
list-style: none;
padding-left: 0;
}
.print-note li:has(> input[type="checkbox"]) {
list-style: none;
display: flex;
align-items: flex-start;
gap: 0.55em;
padding-left: 0;
}
.print-note li:has(> input[type="checkbox"])::marker {
content: '';
}
.print-note li > input[type="checkbox"] {
flex-shrink: 0;
margin: 0.3em 0 0;
}
.print-note blockquote {
margin: 1.15em 0;
padding-left: 1em;