-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathApp.tsx
More file actions
1853 lines (1687 loc) · 80.6 KB
/
App.tsx
File metadata and controls
1853 lines (1687 loc) · 80.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { type Origin, getAgentName, getAgentBadge } from '@plannotator/shared/agents';
import { parseMarkdownToBlocks, exportAnnotations, exportLinkedDocAnnotations, exportEditorAnnotations, extractFrontmatter, wrapFeedbackForAgent, Frontmatter } from '@plannotator/ui/utils/parser';
import { Viewer, ViewerHandle } from '@plannotator/ui/components/Viewer';
import { AnnotationPanel } from '@plannotator/ui/components/AnnotationPanel';
import { ExportModal } from '@plannotator/ui/components/ExportModal';
import { ImportModal } from '@plannotator/ui/components/ImportModal';
import { ConfirmDialog } from '@plannotator/ui/components/ConfirmDialog';
import { Annotation, Block, EditorMode, type InputMethod, type ImageAttachment } from '@plannotator/ui/types';
import { ThemeProvider } from '@plannotator/ui/components/ThemeProvider';
import { ModeToggle } from '@plannotator/ui/components/ModeToggle';
import { AnnotationToolstrip } from '@plannotator/ui/components/AnnotationToolstrip';
import { TaterSpriteRunning } from '@plannotator/ui/components/TaterSpriteRunning';
import { TaterSpritePullup } from '@plannotator/ui/components/TaterSpritePullup';
import { Settings } from '@plannotator/ui/components/Settings';
import { FeedbackButton, ApproveButton } from '@plannotator/ui/components/ToolbarButtons';
import { useSharing } from '@plannotator/ui/hooks/useSharing';
import { getCallbackConfig, CallbackAction, executeCallback, type ToastPayload } from '@plannotator/ui/utils/callback';
import { useAgents } from '@plannotator/ui/hooks/useAgents';
import { useActiveSection } from '@plannotator/ui/hooks/useActiveSection';
import { storage } from '@plannotator/ui/utils/storage';
import { configStore } from '@plannotator/ui/config';
import { CompletionOverlay } from '@plannotator/ui/components/CompletionOverlay';
import { UpdateBanner } from '@plannotator/ui/components/UpdateBanner';
import { getObsidianSettings, getEffectiveVaultPath, isObsidianConfigured, CUSTOM_PATH_SENTINEL } from '@plannotator/ui/utils/obsidian';
import { getBearSettings } from '@plannotator/ui/utils/bear';
import { getOctarineSettings, isOctarineConfigured } from '@plannotator/ui/utils/octarine';
import { getDefaultNotesApp } from '@plannotator/ui/utils/defaultNotesApp';
import { getAgentSwitchSettings, getEffectiveAgentName } from '@plannotator/ui/utils/agentSwitch';
import { getPlanSaveSettings } from '@plannotator/ui/utils/planSave';
import { getUIPreferences, type UIPreferences, type PlanWidth } from '@plannotator/ui/utils/uiPreferences';
import { getEditorMode, saveEditorMode } from '@plannotator/ui/utils/editorMode';
import { getInputMethod, saveInputMethod } from '@plannotator/ui/utils/inputMethod';
import { useInputMethodSwitch } from '@plannotator/ui/hooks/useInputMethodSwitch';
import { usePrintMode } from '@plannotator/ui/hooks/usePrintMode';
import { modKey } from '@plannotator/ui/utils/platform';
import { useResizablePanel } from '@plannotator/ui/hooks/useResizablePanel';
import { ResizeHandle } from '@plannotator/ui/components/ResizeHandle';
import { MobileMenu } from '@plannotator/ui/components/MobileMenu';
import {
getPermissionModeSettings,
needsPermissionModeSetup,
type PermissionMode,
} from '@plannotator/ui/utils/permissionMode';
import { PermissionModeSetup } from '@plannotator/ui/components/PermissionModeSetup';
import { ImageAnnotator } from '@plannotator/ui/components/ImageAnnotator';
import { deriveImageName } from '@plannotator/ui/components/AttachmentsButton';
import { useSidebar } from '@plannotator/ui/hooks/useSidebar';
import { usePlanDiff, type VersionInfo } from '@plannotator/ui/hooks/usePlanDiff';
import { useLinkedDoc } from '@plannotator/ui/hooks/useLinkedDoc';
import { useVaultBrowser } from '@plannotator/ui/hooks/useVaultBrowser';
import { useAnnotationDraft } from '@plannotator/ui/hooks/useAnnotationDraft';
import { useArchive } from '@plannotator/ui/hooks/useArchive';
import { useEditorAnnotations } from '@plannotator/ui/hooks/useEditorAnnotations';
import { useExternalAnnotations } from '@plannotator/ui/hooks/useExternalAnnotations';
import { useExternalAnnotationHighlights } from '@plannotator/ui/hooks/useExternalAnnotationHighlights';
import { useFileBrowser } from '@plannotator/ui/hooks/useFileBrowser';
import { isVaultBrowserEnabled } from '@plannotator/ui/utils/obsidian';
import { isFileBrowserEnabled, getFileBrowserSettings } from '@plannotator/ui/utils/fileBrowser';
import { SidebarTabs } from '@plannotator/ui/components/sidebar/SidebarTabs';
import { SidebarContainer } from '@plannotator/ui/components/sidebar/SidebarContainer';
import type { ArchivedPlan } from '@plannotator/ui/components/sidebar/ArchiveBrowser';
import { PlanDiffViewer } from '@plannotator/ui/components/plan-diff/PlanDiffViewer';
import type { PlanDiffMode } from '@plannotator/ui/components/plan-diff/PlanDiffModeSwitcher';
import { DEMO_PLAN_CONTENT } from './demoPlan';
import { useCheckboxOverrides } from './hooks/useCheckboxOverrides';
type NoteAutoSaveResults = {
obsidian?: boolean;
bear?: boolean;
octarine?: boolean;
};
const App: React.FC = () => {
const [markdown, setMarkdown] = useState(DEMO_PLAN_CONTENT);
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
const [blocks, setBlocks] = useState<Block[]>([]);
const [frontmatter, setFrontmatter] = useState<Frontmatter | null>(null);
const [showExport, setShowExport] = useState(false);
const [showImport, setShowImport] = useState(false);
const [showFeedbackPrompt, setShowFeedbackPrompt] = useState(false);
const [showClaudeCodeWarning, setShowClaudeCodeWarning] = useState(false);
const [showAgentWarning, setShowAgentWarning] = useState(false);
const [agentWarningMessage, setAgentWarningMessage] = useState('');
const [isPanelOpen, setIsPanelOpen] = useState(() => window.innerWidth >= 768);
const [mobileSettingsOpen, setMobileSettingsOpen] = useState(false);
const [editorMode, setEditorMode] = useState<EditorMode>(getEditorMode);
const [inputMethod, setInputMethod] = useState<InputMethod>(getInputMethod);
const [taterMode, setTaterMode] = useState(() => {
const stored = storage.getItem('plannotator-tater-mode');
return stored === 'true';
});
const [uiPrefs, setUiPrefs] = useState(() => getUIPreferences());
const [isApiMode, setIsApiMode] = useState(false);
const [origin, setOrigin] = useState<Origin | null>(null);
const [gitUser, setGitUser] = useState<string | undefined>();
const [isWSL, setIsWSL] = useState(false);
const [globalAttachments, setGlobalAttachments] = useState<ImageAttachment[]>([]);
const [annotateMode, setAnnotateMode] = useState(false);
const [annotateSource, setAnnotateSource] = useState<'file' | 'message' | 'folder' | null>(null);
const [imageBaseDir, setImageBaseDir] = useState<string | undefined>(undefined);
const [isLoading, setIsLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitted, setSubmitted] = useState<'approved' | 'denied' | null>(null);
const [pendingPasteImage, setPendingPasteImage] = useState<{ file: File; blobUrl: string; initialName: string } | null>(null);
const [showPermissionModeSetup, setShowPermissionModeSetup] = useState(false);
const [permissionMode, setPermissionMode] = useState<PermissionMode>('bypassPermissions');
const [sharingEnabled, setSharingEnabled] = useState(true);
const [shareBaseUrl, setShareBaseUrl] = useState<string | undefined>(undefined);
const [pasteApiUrl, setPasteApiUrl] = useState<string | undefined>(undefined);
const [repoInfo, setRepoInfo] = useState<{ display: string; branch?: string } | null>(null);
const [projectRoot, setProjectRoot] = useState<string | null>(null);
useEffect(() => {
document.title = repoInfo ? `${repoInfo.display} · Plannotator` : "Plannotator";
}, [repoInfo]);
const [showExportDropdown, setShowExportDropdown] = useState(false);
const [initialExportTab, setInitialExportTab] = useState<'share' | 'annotations' | 'notes'>();
const [noteSaveToast, setNoteSaveToast] = useState<ToastPayload>(null);
const [isPlanDiffActive, setIsPlanDiffActive] = useState(false);
const [planDiffMode, setPlanDiffMode] = useState<PlanDiffMode>('clean');
const [previousPlan, setPreviousPlan] = useState<string | null>(null);
const [versionInfo, setVersionInfo] = useState<VersionInfo | null>(null);
const viewerRef = useRef<ViewerHandle>(null);
const containerRef = useRef<HTMLElement>(null);
usePrintMode();
// Resizable panels
const panelResize = useResizablePanel({ storageKey: 'plannotator-panel-width' });
const tocResize = useResizablePanel({
storageKey: 'plannotator-toc-width',
defaultWidth: 240, minWidth: 160, maxWidth: 400, side: 'left',
});
const isResizing = panelResize.isDragging || tocResize.isDragging;
// Sidebar (shared TOC + Version Browser)
const sidebar = useSidebar(getUIPreferences().tocEnabled);
// Sync sidebar open state when preference changes in Settings
useEffect(() => {
if (uiPrefs.tocEnabled) {
sidebar.open('toc');
} else {
sidebar.close();
}
}, [uiPrefs.tocEnabled]);
// Clear diff view when switching away from versions tab
useEffect(() => {
if (sidebar.activeTab === 'toc' && isPlanDiffActive) {
setIsPlanDiffActive(false);
}
}, [sidebar.activeTab]);
// Clear diff view on Escape key
useEffect(() => {
if (!isPlanDiffActive) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setIsPlanDiffActive(false);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isPlanDiffActive]);
// Plan diff computation
const planDiff = usePlanDiff(markdown, previousPlan, versionInfo);
// Linked document navigation
const linkedDocHook = useLinkedDoc({
markdown, annotations, selectedAnnotationId, globalAttachments,
setMarkdown, setAnnotations, setSelectedAnnotationId, setGlobalAttachments,
viewerRef, sidebar,
});
// Archive browser
const archive = useArchive({
markdown, viewerRef, linkedDocHook,
setMarkdown, setAnnotations, setSelectedAnnotationId, setSubmitted,
});
// Obsidian vault browser
const vaultBrowser = useVaultBrowser();
const showVaultTab = useMemo(() => isVaultBrowserEnabled(), [uiPrefs]);
const vaultPath = useMemo(() => {
if (!showVaultTab) return '';
const settings = getObsidianSettings();
return getEffectiveVaultPath(settings);
}, [showVaultTab, uiPrefs]);
// Clear active file when vault browser is disabled
useEffect(() => {
if (!showVaultTab) vaultBrowser.setActiveFile(null);
}, [showVaultTab]);
// Auto-fetch vault tree when vault tab is first opened
useEffect(() => {
if (sidebar.activeTab === 'vault' && showVaultTab && vaultPath && vaultBrowser.tree.length === 0 && !vaultBrowser.isLoading) {
vaultBrowser.fetchTree(vaultPath);
}
}, [sidebar.activeTab, showVaultTab, vaultPath]);
const buildVaultDocUrl = React.useCallback(
(vp: string) => (path: string) =>
`/api/reference/obsidian/doc?vaultPath=${encodeURIComponent(vp)}&path=${encodeURIComponent(path)}`,
[]
);
// Vault file selection: open via linked doc system with vault endpoint
const handleVaultFileSelect = React.useCallback((relativePath: string) => {
linkedDocHook.open(relativePath, buildVaultDocUrl(vaultPath));
vaultBrowser.setActiveFile(relativePath);
}, [vaultPath, linkedDocHook, vaultBrowser, buildVaultDocUrl]);
// Markdown file browser
const fileBrowser = useFileBrowser();
const showFilesTab = useMemo(() => !!projectRoot || isFileBrowserEnabled(), [projectRoot, uiPrefs]);
const fileBrowserDirs = useMemo(() => {
const projectDirs = projectRoot ? [projectRoot] : [];
const userDirs = isFileBrowserEnabled()
? getFileBrowserSettings().directories
: [];
return [...new Set([...projectDirs, ...userDirs])];
}, [projectRoot, uiPrefs]);
// Clear active file when file browser is disabled
useEffect(() => {
if (!showFilesTab) fileBrowser.setActiveFile(null);
}, [showFilesTab]);
useEffect(() => {
if (sidebar.activeTab === 'files' && showFilesTab && fileBrowserDirs.length > 0) {
const loadedPaths = fileBrowser.dirs.map((d) => d.path);
const needsFetch = fileBrowserDirs.length !== loadedPaths.length
|| fileBrowserDirs.some((d) => !loadedPaths.includes(d));
if (needsFetch) {
fileBrowser.fetchAll(fileBrowserDirs);
}
}
}, [sidebar.activeTab, showFilesTab, fileBrowserDirs]);
// File browser file selection: open via linked doc system
const handleFileBrowserSelect = React.useCallback((absolutePath: string, dirPath: string) => {
const buildUrl = (path: string) =>
`/api/doc?path=${encodeURIComponent(path)}&base=${encodeURIComponent(dirPath)}`;
linkedDocHook.open(absolutePath, buildUrl, 'files');
fileBrowser.setActiveFile(absolutePath);
vaultBrowser.setActiveFile(null);
}, [linkedDocHook, fileBrowser]);
// Route linked doc opens through vault/file browser endpoint when viewing one of those files
const handleOpenLinkedDoc = React.useCallback((docPath: string) => {
if (vaultBrowser.activeFile && vaultPath) {
linkedDocHook.open(docPath, buildVaultDocUrl(vaultPath));
} else if (fileBrowser.activeFile && fileBrowser.activeDirPath) {
// When viewing a file browser doc, resolve links relative to current file's directory
const baseDir = linkedDocHook.filepath?.replace(/\/[^/]+$/, '') || fileBrowser.activeDirPath;
linkedDocHook.open(docPath, (path) =>
`/api/doc?path=${encodeURIComponent(path)}&base=${encodeURIComponent(baseDir)}`
);
} else {
// Pass the current file's directory as base for relative path resolution
const baseDir = linkedDocHook.filepath
? linkedDocHook.filepath.replace(/\/[^/]+$/, '')
: imageBaseDir;
if (baseDir) {
linkedDocHook.open(docPath, (path) =>
`/api/doc?path=${encodeURIComponent(path)}&base=${encodeURIComponent(baseDir)}`
);
} else {
linkedDocHook.open(docPath);
}
}
}, [vaultBrowser.activeFile, vaultPath, fileBrowser.activeFile, fileBrowser.activeDirPath, linkedDocHook, buildVaultDocUrl, imageBaseDir]);
// Wrap linked doc back to also clear vault/file browser active file
const handleLinkedDocBack = React.useCallback(() => {
linkedDocHook.back();
vaultBrowser.setActiveFile(null);
fileBrowser.setActiveFile(null);
archive.clearSelection();
}, [linkedDocHook, vaultBrowser, fileBrowser, archive]);
// Derive annotation counts per file from linked doc cache (includes active doc's live state)
const allAnnotationCounts = useMemo(() => {
const counts = new Map<string, number>();
for (const [fp, cached] of linkedDocHook.getDocAnnotations()) {
const count = cached.annotations.length + cached.globalAttachments.length;
if (count > 0) counts.set(fp, count);
}
return counts;
}, [linkedDocHook.getDocAnnotations, annotations, globalAttachments]);
// FileBrowser counts: only files under file browser directories
const fileAnnotationCounts = useMemo(() => {
if (fileBrowserDirs.length === 0) return allAnnotationCounts;
const counts = new Map<string, number>();
for (const [fp, count] of allAnnotationCounts) {
if (fileBrowserDirs.some(dir => fp.startsWith(dir + '/'))) {
counts.set(fp, count);
}
}
return counts;
}, [allAnnotationCounts, fileBrowserDirs]);
// VaultBrowser uses relative paths — strip vaultPath prefix for lookup
const vaultAnnotationCounts = useMemo(() => {
if (!vaultPath) return new Map<string, number>();
const prefix = vaultPath.endsWith('/') ? vaultPath : vaultPath + '/';
const counts = new Map<string, number>();
for (const [fp, count] of allAnnotationCounts) {
if (fp.startsWith(prefix)) {
counts.set(fp.slice(prefix.length), count);
}
}
return counts;
}, [allAnnotationCounts, vaultPath]);
const hasFileAnnotations = fileAnnotationCounts.size > 0;
const hasVaultAnnotations = vaultAnnotationCounts.size > 0;
// Annotations in other files (not the current view) — for the right panel "+N" indicator
const otherFileAnnotations = useMemo(() => {
const currentFile = linkedDocHook.filepath;
let count = 0;
let files = 0;
for (const [fp, n] of allAnnotationCounts) {
if (fp !== currentFile) {
count += n;
files++;
}
}
return count > 0 ? { count, files } : undefined;
}, [allAnnotationCounts, linkedDocHook.filepath]);
// Flash highlight for annotated files in the sidebar
const [highlightedFiles, setHighlightedFiles] = useState<Set<string> | undefined>();
const flashTimerRef = React.useRef<ReturnType<typeof setTimeout>>();
const handleFlashAnnotatedFiles = React.useCallback(() => {
const filePaths = new Set(allAnnotationCounts.keys());
if (filePaths.size === 0) return;
// Open sidebar to the relevant tab so the flash is visible
if (!sidebar.isOpen || (sidebar.activeTab !== 'files' && sidebar.activeTab !== 'vault')) {
sidebar.open(hasVaultAnnotations && !hasFileAnnotations ? 'vault' : 'files');
}
// Cancel any pending clear from a previous flash
if (flashTimerRef.current) clearTimeout(flashTimerRef.current);
// Clear first so re-triggering restarts the CSS animation
setHighlightedFiles(undefined);
requestAnimationFrame(() => {
setHighlightedFiles(filePaths);
flashTimerRef.current = setTimeout(() => setHighlightedFiles(undefined), 1200);
});
}, [allAnnotationCounts, sidebar, hasVaultAnnotations, hasFileAnnotations]);
// Derive vault-relative highlighted files for VaultBrowser
const vaultHighlightedFiles = useMemo(() => {
if (!highlightedFiles || !vaultPath) return undefined;
const prefix = vaultPath.endsWith('/') ? vaultPath : vaultPath + '/';
const relative = new Set<string>();
for (const fp of highlightedFiles) {
if (fp.startsWith(prefix)) relative.add(fp.slice(prefix.length));
}
return relative.size > 0 ? relative : undefined;
}, [highlightedFiles, vaultPath]);
// Context-aware back label for linked doc navigation
const backLabel = annotateSource === 'folder' ? 'file list'
: annotateSource === 'file' ? 'file'
: annotateSource === 'message' ? 'message'
: 'plan';
const handleVaultFetchTree = React.useCallback(() => {
vaultBrowser.fetchTree(vaultPath);
}, [vaultBrowser, vaultPath]);
// Track active section for TOC highlighting
const headingCount = useMemo(() => blocks.filter(b => b.type === 'heading').length, [blocks]);
const activeSection = useActiveSection(containerRef, headingCount);
const { editorAnnotations, deleteEditorAnnotation } = useEditorAnnotations();
const { externalAnnotations, updateExternalAnnotation, deleteExternalAnnotation } = useExternalAnnotations<Annotation>({ enabled: isApiMode });
// Drive DOM highlights for SSE-delivered external annotations. Disabled
// while a linked doc overlay is open (Viewer DOM is hidden) and while the
// plan diff view is active (diff view has its own annotation surface).
const { reset: resetExternalHighlights } = useExternalAnnotationHighlights({
viewerRef,
externalAnnotations,
enabled: isApiMode && !linkedDocHook.isActive && !isPlanDiffActive,
planKey: markdown,
});
// Merge local + SSE annotations, deduping draft-restored externals against
// live SSE versions. Prefer the SSE version when both exist (same source,
// type, and originalText). This avoids the timing issues of an effect-based
// cleanup — draft-restored externals persist until SSE actually re-delivers them.
const allAnnotations = useMemo(() => {
if (externalAnnotations.length === 0) return annotations;
const local = annotations.filter(a => {
if (!a.source) return true;
return !externalAnnotations.some(ext =>
ext.source === a.source &&
ext.type === a.type &&
ext.originalText === a.originalText
);
});
return [...local, ...externalAnnotations];
}, [annotations, externalAnnotations]);
// Plan diff state — memoize filtered annotation lists to avoid new references per render
const diffAnnotations = useMemo(() => allAnnotations.filter(a => !!a.diffContext), [allAnnotations]);
const viewerAnnotations = useMemo(() => allAnnotations.filter(a => !a.diffContext), [allAnnotations]);
// URL-based sharing
const {
isSharedSession,
isLoadingShared,
shareUrl,
shareUrlSize,
shortShareUrl,
isGeneratingShortUrl,
shortUrlError,
pendingSharedAnnotations,
sharedGlobalAttachments,
clearPendingSharedAnnotations,
generateShortUrl,
importFromShareUrl,
shareLoadError,
clearShareLoadError,
} = useSharing(
markdown,
allAnnotations,
globalAttachments,
setMarkdown,
setAnnotations,
setGlobalAttachments,
() => {
// When loaded from share, mark as loaded
setIsLoading(false);
},
shareBaseUrl,
pasteApiUrl
);
// Auto-save annotation drafts
const { draftBanner, restoreDraft, dismissDraft } = useAnnotationDraft({
annotations: allAnnotations,
globalAttachments,
isApiMode,
isSharedSession,
submitted: !!submitted,
});
const handleRestoreDraft = React.useCallback(() => {
const { annotations: restored, globalAttachments: restoredGlobal } = restoreDraft();
if (restored.length > 0) {
setAnnotations(restored);
if (restoredGlobal.length > 0) setGlobalAttachments(restoredGlobal);
// Apply highlights to DOM after a tick
setTimeout(() => {
viewerRef.current?.applySharedAnnotations(restored.filter(a => !a.diffContext));
}, 100);
}
}, [restoreDraft]);
// Fetch available agents for OpenCode (for validation on approve)
const { agents: availableAgents, validateAgent, getAgentWarning } = useAgents(origin);
// Apply shared annotations to DOM after they're loaded
useEffect(() => {
if (pendingSharedAnnotations && pendingSharedAnnotations.length > 0) {
// Small delay to ensure DOM is rendered
const timer = setTimeout(() => {
// Clear existing highlights first (important when loading new share URL)
viewerRef.current?.clearAllHighlights();
viewerRef.current?.applySharedAnnotations(pendingSharedAnnotations.filter(a => !a.diffContext));
clearPendingSharedAnnotations();
// `clearAllHighlights` wiped live external SSE highlights too;
// tell the external-highlight bookkeeper to re-apply them.
resetExternalHighlights();
}, 100);
return () => clearTimeout(timer);
}
}, [pendingSharedAnnotations, clearPendingSharedAnnotations, resetExternalHighlights]);
const handleTaterModeChange = (enabled: boolean) => {
setTaterMode(enabled);
storage.setItem('plannotator-tater-mode', String(enabled));
};
const handleEditorModeChange = (mode: EditorMode) => {
setEditorMode(mode);
saveEditorMode(mode);
};
const handleInputMethodChange = (method: InputMethod) => {
setInputMethod(method);
saveInputMethod(method);
};
// Alt/Option key: hold to temporarily switch, double-tap to toggle
useInputMethodSwitch(inputMethod, handleInputMethodChange);
// Check if we're in API mode (served from Bun hook server)
// Skip if we loaded from a shared URL
useEffect(() => {
if (isLoadingShared) return; // Wait for share check to complete
if (isSharedSession) return; // Already loaded from share
fetch('/api/plan')
.then(res => {
if (!res.ok) throw new Error('Not in API mode');
return res.json();
})
.then((data: { plan: string; origin?: Origin; mode?: 'annotate' | 'annotate-last' | 'annotate-folder' | 'archive'; filePath?: string; sharingEnabled?: boolean; shareBaseUrl?: string; pasteApiUrl?: string; repoInfo?: { display: string; branch?: string }; previousPlan?: string | null; versionInfo?: { version: number; totalVersions: number; project: string }; archivePlans?: ArchivedPlan[]; projectRoot?: string; isWSL?: boolean; serverConfig?: { displayName?: string; gitUser?: string } }) => {
// Initialize config store with server-provided values (config file > cookie > default)
configStore.init(data.serverConfig);
// gitUser drives the "Use git name" button in Settings; stays undefined (button hidden) when unavailable
setGitUser(data.serverConfig?.gitUser);
if (data.mode === 'archive') {
// Archive mode: show first archived plan or clear demo content
setMarkdown(data.plan || '');
if (data.archivePlans) archive.init(data.archivePlans);
archive.fetchPlans();
setSharingEnabled(false);
sidebar.open('archive');
} else if (data.mode === 'annotate-folder') {
// Folder annotation mode: clear demo content, let user pick a file
setMarkdown('');
} else if (data.plan) {
setMarkdown(data.plan);
}
setIsApiMode(true);
if (data.mode === 'annotate' || data.mode === 'annotate-last' || data.mode === 'annotate-folder') {
setAnnotateMode(true);
}
if (data.mode === 'annotate-folder') {
sidebar.open('files');
}
if (data.mode && data.mode !== 'archive') {
setAnnotateSource(data.mode === 'annotate-last' ? 'message' : data.mode === 'annotate-folder' ? 'folder' : 'file');
}
if (data.filePath) {
setImageBaseDir(data.mode === 'annotate-folder' ? data.filePath : data.filePath.replace(/\/[^/]+$/, ''));
}
if (data.sharingEnabled !== undefined) {
setSharingEnabled(data.sharingEnabled);
}
if (data.shareBaseUrl) {
setShareBaseUrl(data.shareBaseUrl);
}
if (data.pasteApiUrl) {
setPasteApiUrl(data.pasteApiUrl);
}
if (data.repoInfo) {
setRepoInfo(data.repoInfo);
}
if (data.projectRoot) {
setProjectRoot(data.projectRoot);
}
// Capture plan version history data
if (data.previousPlan !== undefined) {
setPreviousPlan(data.previousPlan);
}
if (data.versionInfo) {
setVersionInfo(data.versionInfo);
}
if (data.origin) {
setOrigin(data.origin);
// For Claude Code, check if user needs to configure permission mode
if (data.origin === 'claude-code' && needsPermissionModeSetup()) {
setShowPermissionModeSetup(true);
}
// Load saved permission mode preference
setPermissionMode(getPermissionModeSettings().mode);
}
if (data.isWSL) {
setIsWSL(true);
}
})
.catch(() => {
// Not in API mode - use default content
setIsApiMode(false);
})
.finally(() => setIsLoading(false));
}, [isLoadingShared, isSharedSession]);
useEffect(() => {
const { frontmatter: fm } = extractFrontmatter(markdown);
setFrontmatter(fm);
setBlocks(parseMarkdownToBlocks(markdown));
}, [markdown]);
// Auto-save to notes apps on plan arrival (each gated by its autoSave toggle)
const autoSaveAttempted = useRef(false);
const autoSaveResultsRef = useRef<NoteAutoSaveResults>({});
const autoSavePromiseRef = useRef<Promise<NoteAutoSaveResults> | null>(null);
useEffect(() => {
autoSaveAttempted.current = false;
autoSaveResultsRef.current = {};
autoSavePromiseRef.current = null;
}, [markdown]);
useEffect(() => {
if (!isApiMode || !markdown || isSharedSession || annotateMode || archive.archiveMode) return;
if (autoSaveAttempted.current) return;
const body: { obsidian?: object; bear?: object; octarine?: object } = {};
const targets: string[] = [];
const obsSettings = getObsidianSettings();
if (obsSettings.autoSave && obsSettings.enabled) {
const vaultPath = getEffectiveVaultPath(obsSettings);
if (vaultPath) {
body.obsidian = {
vaultPath,
folder: obsSettings.folder || 'plannotator',
plan: markdown,
...(obsSettings.filenameFormat && { filenameFormat: obsSettings.filenameFormat }),
...(obsSettings.filenameSeparator && obsSettings.filenameSeparator !== 'space' && { filenameSeparator: obsSettings.filenameSeparator }),
};
targets.push('Obsidian');
}
}
const bearSettings = getBearSettings();
if (bearSettings.autoSave && bearSettings.enabled) {
body.bear = {
plan: markdown,
customTags: bearSettings.customTags,
tagPosition: bearSettings.tagPosition,
};
targets.push('Bear');
}
const octSettings = getOctarineSettings();
if (octSettings.autoSave && isOctarineConfigured()) {
body.octarine = {
plan: markdown,
workspace: octSettings.workspace,
folder: octSettings.folder || 'plannotator',
};
targets.push('Octarine');
}
if (targets.length === 0) return;
autoSaveAttempted.current = true;
const autoSavePromise = fetch('/api/save-notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
.then(res => res.json())
.then(data => {
const results: NoteAutoSaveResults = {
...(body.obsidian ? { obsidian: Boolean(data.results?.obsidian?.success) } : {}),
...(body.bear ? { bear: Boolean(data.results?.bear?.success) } : {}),
...(body.octarine ? { octarine: Boolean(data.results?.octarine?.success) } : {}),
};
autoSaveResultsRef.current = results;
const failed = targets.filter(t => !data.results?.[t.toLowerCase()]?.success);
if (failed.length === 0) {
setNoteSaveToast({ type: 'success', message: `Auto-saved to ${targets.join(' & ')}` });
} else {
setNoteSaveToast({ type: 'error', message: `Auto-save failed for ${failed.join(' & ')}` });
}
return results;
})
.catch(() => {
autoSaveResultsRef.current = {};
setNoteSaveToast({ type: 'error', message: 'Auto-save failed' });
return {};
})
.finally(() => setTimeout(() => setNoteSaveToast(null), 3000));
autoSavePromiseRef.current = autoSavePromise;
}, [isApiMode, markdown, isSharedSession, annotateMode]);
// Global paste listener for image attachments
useEffect(() => {
const handlePaste = (e: ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (const item of items) {
if (item.type.startsWith('image/')) {
e.preventDefault();
const file = item.getAsFile();
if (file) {
// Derive name before showing annotator so user sees it immediately
const initialName = deriveImageName(file.name, globalAttachments.map(g => g.name));
const blobUrl = URL.createObjectURL(file);
setPendingPasteImage({ file, blobUrl, initialName });
}
break;
}
}
};
document.addEventListener('paste', handlePaste);
return () => document.removeEventListener('paste', handlePaste);
}, [globalAttachments]);
// Handle paste annotator accept — name comes from ImageAnnotator
const handlePasteAnnotatorAccept = async (blob: Blob, hasDrawings: boolean, name: string) => {
if (!pendingPasteImage) return;
try {
const formData = new FormData();
const fileToUpload = hasDrawings
? new File([blob], 'annotated.png', { type: 'image/png' })
: pendingPasteImage.file;
formData.append('file', fileToUpload);
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (res.ok) {
const data = await res.json();
setGlobalAttachments(prev => [...prev, { path: data.path, name }]);
}
} catch {
// Upload failed silently
} finally {
URL.revokeObjectURL(pendingPasteImage.blobUrl);
setPendingPasteImage(null);
}
};
const handlePasteAnnotatorClose = () => {
if (pendingPasteImage) {
URL.revokeObjectURL(pendingPasteImage.blobUrl);
setPendingPasteImage(null);
}
};
// API mode handlers
const handleApprove = async () => {
setIsSubmitting(true);
try {
const obsidianSettings = getObsidianSettings();
const bearSettings = getBearSettings();
const octarineSettings = getOctarineSettings();
const agentSwitchSettings = getAgentSwitchSettings();
const planSaveSettings = getPlanSaveSettings();
const autoSaveResults = bearSettings.autoSave && autoSavePromiseRef.current
? await autoSavePromiseRef.current
: autoSaveResultsRef.current;
// Build request body - include integrations if enabled
const body: { obsidian?: object; bear?: object; octarine?: object; feedback?: string; agentSwitch?: string; planSave?: { enabled: boolean; customPath?: string }; permissionMode?: string } = {};
// Include permission mode for Claude Code
if (origin === 'claude-code') {
body.permissionMode = permissionMode;
}
// Include agent switch setting for OpenCode (effective name handles custom agents)
const effectiveAgent = getEffectiveAgentName(agentSwitchSettings);
if (effectiveAgent) {
body.agentSwitch = effectiveAgent;
}
// Include plan save settings
body.planSave = {
enabled: planSaveSettings.enabled,
...(planSaveSettings.customPath && { customPath: planSaveSettings.customPath }),
};
const effectiveVaultPath = getEffectiveVaultPath(obsidianSettings);
if (obsidianSettings.enabled && effectiveVaultPath) {
body.obsidian = {
vaultPath: effectiveVaultPath,
folder: obsidianSettings.folder || 'plannotator',
plan: markdown,
...(obsidianSettings.filenameFormat && { filenameFormat: obsidianSettings.filenameFormat }),
...(obsidianSettings.filenameSeparator && obsidianSettings.filenameSeparator !== 'space' && { filenameSeparator: obsidianSettings.filenameSeparator }),
};
}
// Bear creates a new note each time, so don't send it again on approve
// if the arrival auto-save already succeeded.
if (bearSettings.enabled && !(bearSettings.autoSave && autoSaveResults.bear)) {
body.bear = {
plan: markdown,
customTags: bearSettings.customTags,
tagPosition: bearSettings.tagPosition,
};
}
if (isOctarineConfigured()) {
body.octarine = {
plan: markdown,
workspace: octarineSettings.workspace,
folder: octarineSettings.folder || 'plannotator',
};
}
// Include annotations as feedback if any exist (for OpenCode "approve with notes")
const hasDocAnnotations = Array.from(linkedDocHook.getDocAnnotations().values()).some(
(d) => d.annotations.length > 0 || d.globalAttachments.length > 0
);
if (allAnnotations.length > 0 || globalAttachments.length > 0 || hasDocAnnotations || editorAnnotations.length > 0) {
body.feedback = annotationsOutput;
}
await fetch('/api/approve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
setSubmitted('approved');
} catch {
setIsSubmitting(false);
}
};
const handleDeny = async () => {
setIsSubmitting(true);
try {
const planSaveSettings = getPlanSaveSettings();
await fetch('/api/deny', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
feedback: annotationsOutput,
planSave: {
enabled: planSaveSettings.enabled,
...(planSaveSettings.customPath && { customPath: planSaveSettings.customPath }),
},
})
});
setSubmitted('denied');
} catch {
setIsSubmitting(false);
}
};
// Annotate mode handler — sends feedback via /api/feedback
const handleAnnotateFeedback = async () => {
setIsSubmitting(true);
try {
await fetch('/api/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
feedback: annotationsOutput,
annotations: allAnnotations,
}),
});
setSubmitted('denied'); // reuse 'denied' state for "feedback sent" overlay
} catch {
setIsSubmitting(false);
}
};
// Global keyboard shortcuts (Cmd/Ctrl+Enter to submit)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Only handle Cmd/Ctrl+Enter
if (e.key !== 'Enter' || !(e.metaKey || e.ctrlKey)) return;
// Don't intercept if typing in an input/textarea
const tag = (e.target as HTMLElement)?.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') return;
// Don't intercept if any modal is open
if (showExport || showImport || showFeedbackPrompt || showClaudeCodeWarning ||
showAgentWarning || showPermissionModeSetup || pendingPasteImage) return;
// Don't intercept if already submitted or submitting
if (submitted || isSubmitting) return;
// Don't intercept in demo/share mode (no API)
if (!isApiMode) return;
// Don't submit while viewing a linked doc
if (linkedDocHook.isActive) return;
e.preventDefault();
// Annotate mode: always send feedback (empty = "no feedback" message)
if (annotateMode) {
handleAnnotateFeedback();
return;
}
// No annotations → Approve, otherwise → Send Feedback
const docAnnotations = linkedDocHook.getDocAnnotations();
const hasDocAnnotations = Array.from(docAnnotations.values()).some(
(d) => d.annotations.length > 0 || d.globalAttachments.length > 0
);
if (allAnnotations.length === 0 && editorAnnotations.length === 0 && !hasDocAnnotations) {
// Check if agent exists for OpenCode users
if (origin === 'opencode') {
const warning = getAgentWarning();
if (warning) {
setAgentWarningMessage(warning);
setShowAgentWarning(true);
return;
}
}
handleApprove();
} else {
handleDeny();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [
showExport, showImport, showFeedbackPrompt, showClaudeCodeWarning, showAgentWarning,
showPermissionModeSetup, pendingPasteImage,
submitted, isSubmitting, isApiMode, linkedDocHook.isActive, annotations.length, externalAnnotations.length, annotateMode,
origin, getAgentWarning,
]);
const handleAddAnnotation = (ann: Annotation) => {
setAnnotations(prev => [...prev, ann]);
setSelectedAnnotationId(ann.id);
setIsPanelOpen(true);
};
// Stable reference — the Viewer's highlighter useEffect depends on this
const handleSelectAnnotation = React.useCallback((id: string | null) => {
setSelectedAnnotationId(id);
if (id && window.innerWidth < 768) setIsPanelOpen(true);
}, []);
// Core annotation removal — highlight cleanup + state filter + selection clear
const removeAnnotation = (id: string) => {
viewerRef.current?.removeHighlight(id);
setAnnotations(prev => prev.filter(a => a.id !== id));
if (selectedAnnotationId === id) setSelectedAnnotationId(null);
};
// Interactive checkbox toggling with annotation tracking
const checkbox = useCheckboxOverrides({
blocks,
annotations,
addAnnotation: handleAddAnnotation,
removeAnnotation,
});
const handleDeleteAnnotation = (id: string) => {
const ann = allAnnotations.find(a => a.id === id);
// External annotations (live in SSE hook) route to the SSE hook, not local state.
// Check membership by ID — source alone is insufficient because share-imported
// and draft-restored annotations also carry source but live in local state.
if (ann?.source && externalAnnotations.some(e => e.id === id)) {
deleteExternalAnnotation(id);
if (selectedAnnotationId === id) setSelectedAnnotationId(null);
return;
}
// If this is a checkbox annotation, revert the visual override
if (id.startsWith('ann-checkbox-')) {
if (ann) {
checkbox.revertOverride(ann.blockId);
}
}
removeAnnotation(id);
};
const handleEditAnnotation = (id: string, updates: Partial<Annotation>) => {
const ann = allAnnotations.find(a => a.id === id);
if (ann?.source && externalAnnotations.some(e => e.id === id)) {
updateExternalAnnotation(id, updates);
return;
}
setAnnotations(prev => prev.map(a =>
a.id === id ? { ...a, ...updates } : a
));
};
const handleIdentityChange = (oldIdentity: string, newIdentity: string) => {
setAnnotations(prev => prev.map(ann =>
ann.author === oldIdentity ? { ...ann, author: newIdentity } : ann
));
};
const handleAddGlobalAttachment = (image: ImageAttachment) => {
setGlobalAttachments(prev => [...prev, image]);
};
const handleRemoveGlobalAttachment = (path: string) => {
setGlobalAttachments(prev => prev.filter(p => p.path !== path));
};
const handleTocNavigate = (blockId: string) => {