document-level notes

This commit is contained in:
2026-03-20 11:11:30 +10:00
parent ce2917505b
commit be8b47f8fb
9 changed files with 312 additions and 44 deletions

View File

@@ -21,7 +21,8 @@ function badgeColor(type: TextAnnotation['type']): string {
case 'show_tell': return 'rgba(255, 140, 30, 0.75)'
case 'critique': return 'rgba(160, 80, 220, 0.75)'
case 'custom': return 'rgba(30, 200, 150, 0.8)'
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
case 'document_note': return 'rgba(80, 180, 240, 0.85)'
}
}
@@ -95,11 +96,13 @@ function ChatMessageItemInner({ message, linkedAnnotations }: Props): JSX.Elemen
>
{ann.type.replace(/_/g, ' ')}
</span>
<span className="chat-suggestion-excerpt">
"{ann.matchedText.length > 40
? ann.matchedText.slice(0, 38) + '…'
: ann.matchedText}"
</span>
{ann.matchedText && (
<span className="chat-suggestion-excerpt">
"{ann.matchedText.length > 40
? ann.matchedText.slice(0, 38) + '…'
: ann.matchedText}"
</span>
)}
{ann.applied && (
<span className="chat-suggestion-applied">Applied</span>
)}

View File

@@ -35,11 +35,14 @@ const rawAnnotationsField = StateField.define<TextAnnotation[]>({
}
if (tr.docChanged && annotations.length > 0) {
const oldLen = tr.changes.length
return annotations.map(a => ({
...a,
from: tr.changes.mapPos(Math.min(a.from, oldLen), -1),
to: tr.changes.mapPos(Math.min(a.to, oldLen), 1)
}))
return annotations.map(a => {
if (a.from === undefined || a.to === undefined) return a
return {
...a,
from: tr.changes.mapPos(Math.min(a.from, oldLen), -1),
to: tr.changes.mapPos(Math.min(a.to, oldLen), 1)
}
})
}
return annotations
}
@@ -159,6 +162,7 @@ export function scrollToAnnotation(ann: TextAnnotation): void {
const view = currentEditorView
if (!view) return
const tracked = view.state.field(rawAnnotationsField).find(a => a.id === ann.id) ?? ann
if (tracked.from === undefined) return
view.dispatch({
selection: { anchor: tracked.from },
effects: EditorView.scrollIntoView(tracked.from, { y: 'center' })
@@ -176,14 +180,14 @@ export function applyAnnotation(ann: TextAnnotation, suggestion: string): void {
const { markAnnotationApplied } = useEditorStore.getState()
const cmAnnotations = view.state.field(rawAnnotationsField)
const tracked = cmAnnotations.find(a => a.id === ann.id)
if (!tracked) return
if (!tracked || tracked.from === undefined || tracked.to === undefined) return
const changeSpec = { from: tracked.from, to: tracked.to, insert: suggestion }
// Map surviving annotation positions through the text change so
// their from/to reflect the new document offsets.
const changeSet = view.state.changes(changeSpec)
const remaining = cmAnnotations
.filter(a => a.id !== ann.id)
.map(a => ({ ...a, from: changeSet.mapPos(a.from), to: changeSet.mapPos(a.to) }))
.map(a => a.from === undefined || a.to === undefined ? a : { ...a, from: changeSet.mapPos(a.from), to: changeSet.mapPos(a.to) })
// Combine text replacement + annotation update in one transaction
// so CM history treats them as a single undoable unit.
view.dispatch({
@@ -200,7 +204,7 @@ export function applyAnnotation(ann: TextAnnotation, suggestion: string): void {
const annotationHoverTooltip = hoverTooltip(
(view, pos) => {
const annotations = view.state.field(rawAnnotationsField)
const found = annotations.find(a => pos >= a.from && pos <= a.to)
const found = annotations.find(a => a.from !== undefined && a.to !== undefined && pos >= a.from && pos <= a.to)
if (!found) return null
// Capture in a new const so TypeScript preserves the non-undefined type
// across the nested create() closure without requiring non-null assertions.
@@ -337,8 +341,9 @@ const annotationHoverTooltip = hoverTooltip(
// Build a DecorationSet from an annotation list, clamped to docLen.
function buildDecoSet(annotations: TextAnnotation[], docLen: number): DecorationSet {
const builder = new RangeSetBuilder<Decoration>()
const sorted = [...annotations].sort((a, b) => a.from - b.from)
const sorted = [...annotations].sort((a, b) => (a.from ?? -1) - (b.from ?? -1))
for (const ann of sorted) {
if (ann.from === undefined || ann.to === undefined) continue
const from = Math.max(0, Math.min(ann.from, docLen))
const to = Math.max(from, Math.min(ann.to, docLen))
if (from < to) {
@@ -721,7 +726,7 @@ export function MarkdownEditor(): JSX.Element {
if (tr.annotation(Transaction.addToHistory) === false) continue
tr.changes.iterChangedRanges((fromA, toA) => {
for (const ann of preAnnotations) {
if (fromA < ann.to && toA > ann.from) {
if (ann.from !== undefined && ann.to !== undefined && fromA < ann.to && toA > ann.from) {
schedulePendingDismiss(ann.id)
}
}
@@ -806,7 +811,7 @@ export function MarkdownEditor(): JSX.Element {
const trackedById = new Map(view.state.field(rawAnnotationsField).map(a => [a.id, a]))
const toDispatch = reanchored.map(a => {
const tracked = trackedById.get(a.id)
return (tracked && tracked.from >= 0 && tracked.to <= docLen) ? tracked : a
return (tracked && tracked.from !== undefined && tracked.from >= 0 && tracked.to !== undefined && tracked.to <= docLen) ? tracked : a
})
view.dispatch({
effects: setAnnotationsEffect.of(toDispatch),

View File

@@ -427,3 +427,107 @@
white-space: pre-wrap;
word-break: break-word;
}
/* ── Add document note ───────────────────────────────── */
.fb-add-note-section {
flex-shrink: 0;
padding: 8px 12px;
border-top: 1px solid var(--border);
}
.fb-add-note-btn {
background: none;
border: 1px dashed var(--border);
border-radius: 4px;
color: var(--text-muted);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
padding: 5px 10px;
width: 100%;
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
}
.fb-add-note-btn:hover {
color: rgba(80, 180, 240, 0.9);
border-color: rgba(80, 180, 240, 0.4);
}
.fb-note-form {
display: flex;
flex-direction: column;
gap: 6px;
}
.fb-note-textarea {
width: 100%;
background: var(--message-bg);
border: 1px solid var(--border);
border-radius: 4px;
color: var(--text-primary);
font-family: var(--font-sans);
font-size: 12.5px;
line-height: 1.6;
padding: 6px 8px;
resize: none;
box-sizing: border-box;
outline: none;
transition: border-color 0.15s;
}
.fb-note-textarea:focus {
border-color: rgba(80, 180, 240, 0.5);
}
.fb-note-textarea::placeholder {
color: var(--text-muted);
font-style: italic;
}
.fb-note-form-actions {
display: flex;
gap: 6px;
justify-content: flex-end;
}
.fb-note-save-btn {
background: rgba(80, 180, 240, 0.15);
border: 1px solid rgba(80, 180, 240, 0.4);
border-radius: 4px;
color: rgba(80, 180, 240, 0.9);
font-size: 11px;
font-weight: 600;
padding: 3px 10px;
cursor: pointer;
transition: background 0.15s;
}
.fb-note-save-btn:hover {
background: rgba(80, 180, 240, 0.25);
}
.fb-note-cancel-btn {
background: none;
border: 1px solid var(--border);
border-radius: 4px;
color: var(--text-muted);
font-size: 11px;
font-weight: 600;
padding: 3px 10px;
cursor: pointer;
transition: color 0.15s;
}
.fb-note-cancel-btn:hover {
color: var(--text-primary);
}
/* ── Document note card: no hover jump affordance ───── */
.fb-card-header--no-jump {
cursor: default;
}
.fb-card-header--no-jump:hover {
background: transparent;
}

View File

@@ -19,13 +19,14 @@ type AnalysisState =
function badgeColor(type: TextAnnotation['type']): string {
switch (type) {
case 'passive_voice': return 'rgba(255, 200, 0, 0.75)'
case 'consistency': return 'rgba(220, 80, 80, 0.75)'
case 'style': return 'rgba(80, 160, 255, 0.75)'
case 'show_tell': return 'rgba(255, 140, 30, 0.75)'
case 'critique': return 'rgba(160, 80, 220, 0.75)'
case 'custom': return 'rgba(30, 200, 150, 0.8)'
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
case 'passive_voice': return 'rgba(255, 200, 0, 0.75)'
case 'consistency': return 'rgba(220, 80, 80, 0.75)'
case 'style': return 'rgba(80, 160, 255, 0.75)'
case 'show_tell': return 'rgba(255, 140, 30, 0.75)'
case 'critique': return 'rgba(160, 80, 220, 0.75)'
case 'custom': return 'rgba(30, 200, 150, 0.8)'
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
case 'document_note': return 'rgba(80, 180, 240, 0.85)'
}
}
@@ -197,6 +198,36 @@ function UserCommentCard({ ann, onDismiss }: UserCommentCardProps): JSX.Element
)
}
interface DocumentNoteCardProps {
ann: TextAnnotation
onDismiss: () => void
}
function DocumentNoteCard({ ann, onDismiss }: DocumentNoteCardProps): JSX.Element {
return (
<div
className="fb-card fb-card-document_note"
style={{ '--badge-color': 'rgba(80, 180, 240, 0.85)' } as React.CSSProperties}
>
<div className="fb-card-header fb-card-header--no-jump">
<div className="fb-card-header-top">
<div className="fb-card-header-badges">
<span className="fb-card-badge">Document note</span>
</div>
<button
className="fb-card-dismiss"
onClick={onDismiss}
title="Dismiss"
>
×
</button>
</div>
</div>
<div className="fb-card-user-comment-body">{ann.comment}</div>
</div>
)
}
interface ArchiveCardProps {
ann: TextAnnotation
onRemove?: () => void
@@ -222,7 +253,9 @@ function ArchiveCard({ ann, onRemove }: ArchiveCardProps): JSX.Element {
</button>
)}
</div>
<span className="fb-archive-card-excerpt">"{ann.matchedText}"</span>
{ann.matchedText && (
<span className="fb-archive-card-excerpt">"{ann.matchedText}"</span>
)}
{ann.comment && (
<span className="fb-archive-card-comment">{ann.comment}</span>
)}
@@ -242,8 +275,34 @@ export function FeedbackPanel(): JSX.Element {
removeAnnotation,
clearArchivedAnnotations,
removeArchivedAnnotation,
addDocumentNote,
} = useEditorStore()
const [analyseAll, setAnalyseAll] = useState(false)
const [addingNote, setAddingNote] = useState(false)
const [noteText, setNoteText] = useState('')
const noteTextareaRef = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
if (addingNote) noteTextareaRef.current?.focus()
}, [addingNote])
function handleSaveNote(): void {
const trimmed = noteText.trim()
if (trimmed) addDocumentNote(trimmed)
setNoteText('')
setAddingNote(false)
}
function handleNoteKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>): void {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleSaveNote()
}
if (e.key === 'Escape') {
setNoteText('')
setAddingNote(false)
}
}
const archivedAnnotations = activeFilePath
? (annotationsByFile[activeFilePath]?.annotations ?? []).filter(a => a.applied || a.dismissed)
@@ -275,6 +334,29 @@ export function FeedbackPanel(): JSX.Element {
<p>No feedback yet.</p>
<p>Run a critique from the toolbar to highlight issues in your text.</p>
</div>
<div className="fb-add-note-section">
{addingNote ? (
<div className="fb-note-form">
<textarea
ref={noteTextareaRef}
className="fb-note-textarea"
placeholder="Write a note about this document…"
value={noteText}
onChange={(e) => setNoteText(e.target.value)}
onKeyDown={handleNoteKeyDown}
rows={3}
/>
<div className="fb-note-form-actions">
<button className="fb-note-save-btn" onClick={handleSaveNote}>Save</button>
<button className="fb-note-cancel-btn" onClick={() => { setNoteText(''); setAddingNote(false) }}>Cancel</button>
</div>
</div>
) : (
<button className="fb-add-note-btn" onClick={() => setAddingNote(true)}>
+ Add document note
</button>
)}
</div>
</div>
)
}
@@ -302,24 +384,62 @@ export function FeedbackPanel(): JSX.Element {
</div>
<div className="fb-list">
{[...annotations].sort((a, b) => a.from - b.from).map(ann =>
ann.type === 'user_comment'
? <UserCommentCard
{[...annotations].sort((a, b) => (a.from ?? -1) - (b.from ?? -1)).map(ann => {
if (ann.type === 'document_note') {
return (
<DocumentNoteCard
key={ann.id}
ann={ann}
onDismiss={() => removeAnnotation(ann.id)}
/>
)
}
if (ann.type === 'user_comment') {
return (
<UserCommentCard
key={ann.id}
ann={ann}
onDismiss={() => { cancelPendingDismiss(ann.id); removeAnnotation(ann.id) }}
/>
: <FeedbackCard
key={ann.id}
ann={ann}
autoAnalyse={analyseAll || ann.autoAnalyse === true}
onDismiss={() => { cancelPendingDismiss(ann.id); removeAnnotation(ann.id); tooltipAnalysisCache.delete(ann.id) }}
/>
)}
)
}
return (
<FeedbackCard
key={ann.id}
ann={ann}
autoAnalyse={analyseAll || ann.autoAnalyse === true}
onDismiss={() => { cancelPendingDismiss(ann.id); removeAnnotation(ann.id); tooltipAnalysisCache.delete(ann.id) }}
/>
)
})}
</div>
</>
)}
<div className="fb-add-note-section">
{addingNote ? (
<div className="fb-note-form">
<textarea
ref={noteTextareaRef}
className="fb-note-textarea"
placeholder="Write a note about this document…"
value={noteText}
onChange={(e) => setNoteText(e.target.value)}
onKeyDown={handleNoteKeyDown}
rows={3}
/>
<div className="fb-note-form-actions">
<button className="fb-note-save-btn" onClick={handleSaveNote}>Save</button>
<button className="fb-note-cancel-btn" onClick={() => { setNoteText(''); setAddingNote(false) }}>Cancel</button>
</div>
</div>
) : (
<button className="fb-add-note-btn" onClick={() => setAddingNote(true)}>
+ Add document note
</button>
)}
</div>
{hasArchive && (
<details className="fb-archive">
<summary className="fb-archive-header">

View File

@@ -44,6 +44,7 @@ interface EditorState {
clearArchivedAnnotations: () => void
removeArchivedAnnotation: (id: string) => void
setAnnotationAnalysis: (id: string, result: { text: string; suggestion: string | null }) => void
addDocumentNote: (note: string) => void
// Analysis mode
analysisMode: AnalysisMode
@@ -529,6 +530,36 @@ export const useEditorStore = create<EditorState>((set, get) => ({
})
},
addDocumentNote: (note) => {
const ann: import('../types/editor').TextAnnotation = {
id: `doc-note-${Date.now()}`,
type: 'document_note',
message: note,
comment: note,
}
set((s) => {
const annotations = [...s.annotations, ann]
const existingAll = s.activeFilePath
? (s.annotationsByFile[s.activeFilePath]?.annotations ?? [])
: []
const merged = [...existingAll, ann]
const annotationsByFile = s.activeFilePath
? { ...s.annotationsByFile, [s.activeFilePath]: { mode: s.analysisMode, annotations: merged } }
: s.annotationsByFile
return { annotations, annotationsByFile }
})
scheduleSave(() => {
const st = get()
return {
activeFilePath: st.activeFilePath,
scrollPositions: st.scrollPositions,
chatSessionsByFile: st.chatSessionsByFile,
activeSessionIdByFile: st.activeSessionIdByFile,
annotationsByFile: st.annotationsByFile
}
})
},
analysisMode: 'none',
setAnalysisMode: (analysisMode) => {
set((s) => {

View File

@@ -34,21 +34,21 @@ export interface ChatSession {
messages: ChatMessage[]
}
export type AnnotationType = 'passive_voice' | 'consistency' | 'style' | 'show_tell' | 'critique' | 'custom' | 'user_comment'
export type AnnotationType = 'passive_voice' | 'consistency' | 'style' | 'show_tell' | 'critique' | 'custom' | 'user_comment' | 'document_note'
export interface TextAnnotation {
id: string
type: AnnotationType
from: number
to: number
matchedText: string
from?: number // undefined for document_note (not anchored to text)
to?: number // undefined for document_note
matchedText?: string // undefined for document_note
message: string
suggestion?: string
applied?: boolean // true when the suggestion has been applied to the document
dismissed?: boolean // true when the user dismissed this annotation (archived)
autoAnalyse?: boolean // true when created via context menu — FeedbackCard starts AI analysis immediately
analysisCache?: { text: string; suggestion: string | null } // persisted AI analysis result
comment?: string // user-written note text (only set for user_comment type)
comment?: string // user-written note text (only set for user_comment and document_note types)
}
export type AnalysisMode = 'none' | 'passive_voice' | 'consistency' | 'style' | 'show_tell' | 'critique'

View File

@@ -71,10 +71,11 @@ export function parseAnnotationsFromAIResponse(
function deduplicateOverlapping(annotations: TextAnnotation[]): TextAnnotation[] {
// Process largest spans first so the bigger annotation always wins over any
// overlapping smaller one (e.g. a full sentence beats a sub-phrase within it).
const sorted = [...annotations].sort((a, b) => (b.to - b.from) - (a.to - a.from))
const sorted = [...annotations].sort((a, b) => ((b.to ?? 0) - (b.from ?? 0)) - ((a.to ?? 0) - (a.from ?? 0)))
const kept: TextAnnotation[] = []
for (const ann of sorted) {
const overlaps = kept.some(k => ann.from < k.to && ann.to > k.from)
if (ann.from === undefined || ann.to === undefined) { kept.push(ann); continue }
const overlaps = kept.some(k => k.from !== undefined && k.to !== undefined && ann.from! < k.to && ann.to! > k.from)
if (!overlaps) kept.push(ann)
}
return kept
@@ -133,6 +134,10 @@ export function reanchorAnnotations(
content: string
): TextAnnotation[] {
return annotations.flatMap(ann => {
// Document notes have no position — keep them as-is
if (ann.from === undefined || ann.to === undefined || ann.matchedText === undefined) {
return [ann]
}
// Fast path: stored position still matches the original text exactly (O(1))
if (
ann.from >= 0 &&

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long