Skip to content
Open
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
18 changes: 13 additions & 5 deletions apps/api/src/routes/notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ProviderFactory } from 'llm';
import type { TokenTrackingService } from '../services/token-tracking-service.js';
import { asyncHandler } from '../utils/async-handler.js';
import { validateBody, ApiError } from '../middleware/index.js';
import { slateJsonToPlainText } from '../utils/slateUtils.js';
import { NotesService } from '../services/notes-service.js';
import { createLogger } from '../utils/logger.js';

Expand Down Expand Up @@ -48,9 +49,10 @@ export function createNotesRouter(db: Database, notesRepo: OrganizedNotesReposit
validateBody(createOrganizedNoteSchema),
asyncHandler(async (req, res) => {
const userId = 'test-user-1'; // TODO: Get from auth context
const { title, content, tags, date } = req.body;
const { title, content, contentFormat, tags, date } = req.body;
const contentPlain = contentFormat === 'slate_json' ? slateJsonToPlainText(content) : null;

const note = await notesRepo.create({ userId, title, content, tags, date });
const note = await notesRepo.create({ userId, title, content, contentFormat, contentPlain, tags, date });
res.status(201).json(note);
})
);
Expand Down Expand Up @@ -91,9 +93,15 @@ export function createNotesRouter(db: Database, notesRepo: OrganizedNotesReposit
validateBody(updateOrganizedNoteSchema),
asyncHandler(async (req, res) => {
const { id } = req.params;
const { title, content, tags } = req.body;

const note = await notesRepo.update(id, { title, content, tags });
const { title, content, contentFormat, tags } = req.body;
const contentPlain =
content !== undefined
? contentFormat === 'slate_json'
? slateJsonToPlainText(content)
: null
: undefined;

const note = await notesRepo.update(id, { title, content, contentFormat, contentPlain, tags });
if (!note) {
throw new ApiError(404, 'Note not found');
}
Expand Down
27 changes: 27 additions & 0 deletions apps/api/src/utils/slateUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Extracts plain text from a serialized Slate JSON document string.
* Used to populate content_plain for full-text search indexing,
* avoiding noise from JSON structural keywords in the tsvector.
*/
export function slateJsonToPlainText(content: string): string {
try {
const doc = JSON.parse(content);
if (!Array.isArray(doc)) return '';
return extractText(doc);
} catch {
return '';
}
}

function extractText(nodes: unknown[]): string {
return nodes
.map((node) => {
if (typeof node !== 'object' || node === null) return '';
const n = node as Record<string, unknown>;
if (typeof n.text === 'string') return n.text;
if (Array.isArray(n.children)) return extractText(n.children);
return '';
})
.filter(Boolean)
.join(' ');
}
3 changes: 3 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
"react-markdown": "^10.1.0",
"react-router-dom": "^7.13.0",
"remark-gfm": "^4.0.1",
"slate": "^0.123.0",
"slate-history": "^0.113.1",
"slate-react": "^0.123.0",
"types": "workspace:*"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ export const notesAPI = {
list: (tag?: string) =>
fetchAPI<any[]>(`/notes${tag ? `?tag=${tag}` : ''}`),
get: (id: string) => fetchAPI<any>(`/notes/${id}`),
create: (data: { title: string; content: string; tags?: string[] }) =>
create: (data: { title: string; content: string; contentFormat?: 'markdown' | 'slate_json'; tags?: string[] }) =>
fetchAPI('/notes', { method: 'POST', body: JSON.stringify(data) }),
append: (data: {title: string, contentToAppend: string}) =>
fetchAPI('/notes/append', { method: 'POST', body: JSON.stringify(data) }),
update: (id: string, data: { title?: string; content?: string; tags?: string[] }) =>
update: (id: string, data: { title?: string; content?: string; contentFormat?: 'markdown' | 'slate_json'; tags?: string[] }) =>
fetchAPI(`/notes/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
delete: (id: string) => fetchAPI(`/notes/${id}`, { method: 'DELETE' }),
refine: (id: string, prompt: string) =>
Expand Down
60 changes: 46 additions & 14 deletions apps/web/src/components/NoteForm.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,75 @@
import { useState } from 'react';
import type { Descendant } from 'slate';
import TagEditor from './TagEditor';
import { SlateEditor } from './editor/SlateEditor';
import {
EMPTY_SLATE_DOCUMENT,
deserializeFromString,
serializeToString,
slateToPlainText,
} from './editor/slateSerializer';

interface NoteFormProps {
initialTitle?: string;
initialContent?: string;
initialSlateValue?: Descendant[];
initialContentFormat?: 'markdown' | 'slate_json';
initialTags?: string[];
onSubmit: (data: { title: string; content: string; tags?: string[] }) => Promise<void>;
onSubmit: (data: {
title: string;
content: string;
contentFormat: 'markdown' | 'slate_json';
tags?: string[];
}) => Promise<void>;
onCancel: () => void;
submitLabel?: string;
}

export default function NoteForm({
initialTitle = '',
initialContent = '',
initialSlateValue,
initialContentFormat = 'slate_json',
initialTags = [],
onSubmit,
onCancel,
submitLabel = 'Save Note',
}: NoteFormProps) {
const [title, setTitle] = useState(initialTitle);
const [content, setContent] = useState(initialContent);
const [tags, setTags] = useState<string[]>(initialTags);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);

// Resolve initial editor value:
// 1. If a parsed Slate document was provided, use it directly
// 2. If existing content is slate_json, deserialize it
// 3. If existing content is markdown (or plain text), wrap in a paragraph
// 4. Otherwise, start empty
const [editorValue, setEditorValue] = useState<Descendant[]>(() => {
if (initialSlateValue) return initialSlateValue;
if (initialContentFormat === 'slate_json' && initialContent) {
return deserializeFromString(initialContent);
}
if (initialContent) {
// Markdown note being opened for editing — load as plain paragraph
return [{ type: 'paragraph', children: [{ text: initialContent }] }];
}
return EMPTY_SLATE_DOCUMENT;
});

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim() || !content.trim()) return;
const plainText = slateToPlainText(editorValue).trim();
if (!title.trim() || !plainText) return;

setIsSubmitting(true);
setError(null);

try {
await onSubmit({
title: title.trim(),
content: content.trim(),
content: serializeToString(editorValue),
contentFormat: 'slate_json',
tags: tags.length > 0 ? tags : undefined,
});
} catch (err) {
Expand All @@ -43,6 +78,8 @@ export default function NoteForm({
}
};

const isEmpty = slateToPlainText(editorValue).trim().length === 0;

return (
<form onSubmit={handleSubmit} className="space-y-6 max-w-2xl">
{error && (
Expand All @@ -67,16 +104,11 @@ export default function NoteForm({
</div>

<div>
<label htmlFor="content" className="block text-sm font-medium text-gray-300 mb-2">
Content
</label>
<textarea
id="content"
value={content}
onChange={(e) => setContent(e.target.value)}
<label className="block text-sm font-medium text-gray-300 mb-2">Content</label>
<SlateEditor
value={editorValue}
onChange={setEditorValue}
placeholder="Write your note..."
rows={12}
className="input-accent w-full px-4 py-3 resize-y"
/>
</div>

Expand All @@ -90,7 +122,7 @@ export default function NoteForm({
<div className="flex gap-3">
<button
type="submit"
disabled={isSubmitting || !title.trim() || !content.trim()}
disabled={isSubmitting || !title.trim() || isEmpty}
className="btn-accent px-6 py-3 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Saving...' : submitLabel}
Expand Down
135 changes: 135 additions & 0 deletions apps/web/src/components/editor/CommandPalette.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { useEffect, useRef, useState } from 'react';
import { Transforms } from 'slate';
import { ReactEditor } from 'slate-react';
import type { Editor } from 'slate';
import { todosAPI } from '../../api/client';

interface Todo {
id: string;
content: string;
status: string;
dueDate?: string | null;
}

interface Props {
editor: Editor;
triggerPath: number[];
onClose: () => void;
}

export function CommandPalette({ editor, triggerPath, onClose }: Props) {
const [todos, setTodos] = useState<Todo[]>([]);
const [query, setQuery] = useState('');
const [activeIndex, setActiveIndex] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const containerRef = useRef<HTMLDivElement>(null);

// Position palette near the slash character
const [position, setPosition] = useState({ top: 0, left: 0 });

useEffect(() => {
try {
const domNode = ReactEditor.toDOMNode(editor, editor);
const rect = domNode.getBoundingClientRect();
setPosition({ top: rect.top + 24, left: rect.left });
} catch {
// use default position
}
}, [editor]);

useEffect(() => {
todosAPI.list('pending').then((data: Todo[]) => setTodos(data)).catch(() => {});
inputRef.current?.focus();
}, []);

const filtered = todos.filter((t) =>
t.content.toLowerCase().includes(query.toLowerCase())
);

function insertTaskCard(todo: Todo) {
// Delete the '/' character that triggered the palette
Transforms.select(editor, { path: triggerPath, offset: 0 });
Transforms.delete(editor, { unit: 'character' });

// Insert the task-card void element
Transforms.insertNodes(editor, {
type: 'task-card',
todoId: todo.id,
children: [{ text: '' }],
} as import('./types').TaskCardElement);

// Move cursor past the void
Transforms.move(editor, { unit: 'offset' });

onClose();
}

function handleKeyDown(e: React.KeyboardEvent) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setActiveIndex((i) => Math.min(i + 1, filtered.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActiveIndex((i) => Math.max(i - 1, 0));
} else if (e.key === 'Enter') {
e.preventDefault();
if (filtered[activeIndex]) insertTaskCard(filtered[activeIndex]);
} else if (e.key === 'Escape') {
e.preventDefault();
onClose();
}
}

// Close on outside click
useEffect(() => {
function handleClick(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
onClose();
}
}
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, [onClose]);

return (
<div
ref={containerRef}
style={{ position: 'fixed', top: position.top, left: position.left, zIndex: 50 }}
className="w-72 bg-gray-900 border border-gray-700 rounded-xl shadow-2xl overflow-hidden"
>
<div className="px-3 py-2 border-b border-gray-700">
<input
ref={inputRef}
value={query}
onChange={(e) => { setQuery(e.target.value); setActiveIndex(0); }}
onKeyDown={handleKeyDown}
placeholder="Search todos..."
className="w-full bg-transparent text-gray-200 text-sm outline-none placeholder-gray-500"
/>
</div>
<ul className="max-h-56 overflow-y-auto">
{filtered.length === 0 ? (
<li className="px-3 py-2 text-gray-500 text-sm">No pending todos found</li>
) : (
filtered.map((todo, i) => (
<li key={todo.id}>
<button
onMouseDown={(e) => { e.preventDefault(); insertTaskCard(todo); }}
className={`w-full text-left px-3 py-2 text-sm transition-colors ${
i === activeIndex ? 'bg-gray-700 text-white' : 'text-gray-300 hover:bg-gray-800'
}`}
>
<span className="line-clamp-2">{todo.content}</span>
{todo.dueDate && (
<span className="text-xs text-gray-500 block mt-0.5">
Due {new Date(todo.dueDate).toLocaleDateString()}
</span>
)}
</button>
</li>
))
)}
</ul>
</div>
);
}
Loading
Loading