-
Notifications
You must be signed in to change notification settings - Fork 467
Expand file tree
/
Copy pathViewer.tsx
More file actions
1270 lines (1177 loc) · 48.5 KB
/
Copy pathViewer.tsx
File metadata and controls
1270 lines (1177 loc) · 48.5 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, { useRef, useState, useEffect, forwardRef, useImperativeHandle, useCallback } from 'react';
import { createPortal } from 'react-dom';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';
import { Block, Annotation, AnnotationType, EditorMode, type InputMethod, type ImageAttachment, type ActionsLabelMode } from '../types';
import { Frontmatter, computeListIndices } from '../utils/parser';
import { ListMarker } from './ListMarker';
import { AnnotationToolbar } from './AnnotationToolbar';
import { FloatingQuickLabelPicker } from './FloatingQuickLabelPicker';
// Debug error boundary to catch silent toolbar crashes
class ToolbarErrorBoundary extends React.Component<
{ children: React.ReactNode },
{ error: Error | null }
> {
state = { error: null as Error | null };
static getDerivedStateFromError(error: Error) { return { error }; }
componentDidCatch(error: Error) { console.error('AnnotationToolbar crashed:', error); }
render() {
if (this.state.error) {
return <div style={{ position: 'fixed', top: 10, left: 10, zIndex: 9999, background: 'red', color: 'white', padding: '8px 12px', borderRadius: 6, fontSize: 12 }}>
Toolbar error: {this.state.error.message}
</div>;
}
return this.props.children;
}
}
import { CommentPopover, type CommentDraftState } from './CommentPopover';
import { TaterSpriteSitting } from './TaterSpriteSitting';
import { AttachmentsButton } from './AttachmentsButton';
import { GraphvizBlock } from './GraphvizBlock';
import { MermaidBlock } from './MermaidBlock';
import { getImageSrc } from './ImageThumbnail';
import { isGraphvizLanguage, isMermaidLanguage } from './diagramLanguages';
import { getIdentity } from '../utils/identity';
import { type QuickLabel } from '../utils/quickLabels';
import { DocBadges } from './DocBadges';
import { PinpointOverlay } from './PinpointOverlay';
import { usePinpoint } from '../hooks/usePinpoint';
import { useAnnotationHighlighter } from '../hooks/useAnnotationHighlighter';
import { useScrollViewport } from '../hooks/useScrollViewport';
interface ViewerProps {
blocks: Block[];
markdown: string;
frontmatter?: Frontmatter | null;
annotations: Annotation[];
onAddAnnotation: (ann: Annotation) => void;
onSelectAnnotation: (id: string | null) => void;
selectedAnnotationId: string | null;
mode: EditorMode;
inputMethod?: InputMethod;
taterMode: boolean;
globalAttachments?: ImageAttachment[];
onAddGlobalAttachment?: (image: ImageAttachment) => void;
onRemoveGlobalAttachment?: (path: string) => void;
repoInfo?: { display: string; branch?: string } | null;
stickyActions?: boolean;
onOpenLinkedDoc?: (path: string) => void;
imageBaseDir?: string;
linkedDocInfo?: { filepath: string; onBack: () => void; label?: string; backLabel?: string } | null;
// Plan diff props
planDiffStats?: { additions: number; deletions: number; modifications: number } | null;
isPlanDiffActive?: boolean;
onPlanDiffToggle?: () => void;
hasPreviousVersion?: boolean;
/** Show amber "Demo" badge (portal mode, no shared content loaded) */
showDemoBadge?: boolean;
/** Max width in px for the plan card (from plan width setting) */
maxWidth?: number;
/** Label for the copy button (default: "Copy plan") */
copyLabel?: string;
/**
* Compactness of the action button labels. See ActionsLabelMode in
* types.ts. Defaults to 'full' to preserve the original look for
* callers that don't measure plan-area width.
*/
actionsLabelMode?: ActionsLabelMode;
archiveInfo?: { status: 'approved' | 'denied' | 'unknown'; timestamp: string; title: string } | null;
// Checkbox toggle props
onToggleCheckbox?: (blockId: string, checked: boolean) => void;
checkboxOverrides?: Map<string, boolean>;
}
export interface ViewerHandle {
removeHighlight: (id: string) => void;
clearAllHighlights: () => void;
applySharedAnnotations: (annotations: Annotation[]) => void;
dismissUndoableTransientState: () => boolean;
}
/**
* Renders YAML frontmatter as a styled metadata card.
*/
const FrontmatterCard: React.FC<{ frontmatter: Frontmatter }> = ({ frontmatter }) => {
const entries = Object.entries(frontmatter);
if (entries.length === 0) return null;
return (
<div className="mt-4 mb-6 p-4 bg-muted/30 border border-border/50 rounded-lg">
<div className="grid gap-2 text-sm">
{entries.map(([key, value]) => (
<div key={key} className="flex gap-2">
<span className="font-medium text-muted-foreground min-w-[80px]">{key}:</span>
<span className="text-foreground">
{Array.isArray(value) ? (
<span className="flex flex-wrap gap-1">
{value.map((v, i) => (
<span key={i} className="px-1.5 py-0.5 bg-primary/10 text-primary rounded text-xs">
{v}
</span>
))}
</span>
) : (
value
)}
</span>
</div>
))}
</div>
</div>
);
};
export const Viewer = forwardRef<ViewerHandle, ViewerProps>(({
blocks,
markdown,
frontmatter,
annotations,
onAddAnnotation,
onSelectAnnotation,
selectedAnnotationId,
mode,
inputMethod = 'drag',
taterMode,
globalAttachments = [],
onAddGlobalAttachment,
onRemoveGlobalAttachment,
repoInfo,
stickyActions = true,
planDiffStats,
isPlanDiffActive,
onPlanDiffToggle,
hasPreviousVersion,
showDemoBadge,
maxWidth,
onOpenLinkedDoc,
linkedDocInfo,
imageBaseDir,
copyLabel,
actionsLabelMode = 'full',
archiveInfo,
onToggleCheckbox,
checkboxOverrides,
}, ref) => {
const [copied, setCopied] = useState(false);
const [lightbox, setLightbox] = useState<{ src: string; alt: string } | null>(null);
const globalCommentButtonRef = useRef<HTMLButtonElement>(null);
const handleCopyPlan = async () => {
try {
await navigator.clipboard.writeText(markdown);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (e) {
console.error('Failed to copy:', e);
}
};
const containerRef = useRef<HTMLDivElement>(null);
const [hoveredCodeBlock, setHoveredCodeBlock] = useState<{ block: Block; element: HTMLElement } | null>(null);
const [isCodeBlockToolbarExiting, setIsCodeBlockToolbarExiting] = useState(false);
// Viewer-specific comment popover state (global comments + code blocks)
const [viewerCommentPopover, setViewerCommentPopover] = useState<{
anchorEl: HTMLElement;
contextText: string;
initialText?: string;
isGlobal: boolean;
codeBlock?: { block: Block; element: HTMLElement };
} | null>(null);
const [hookCommentDraftState, setHookCommentDraftState] = useState<CommentDraftState>({
hasContent: false,
hadContentEver: false,
});
const [viewerCommentDraftState, setViewerCommentDraftState] = useState<CommentDraftState>({
hasContent: false,
hadContentEver: false,
});
// Viewer-specific quick label state (code blocks)
const [codeBlockQuickLabelPicker, setCodeBlockQuickLabelPicker] = useState<{
anchorEl: HTMLElement;
codeBlock: { block: Block; element: HTMLElement };
} | null>(null);
const hoverTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const stickySentinelRef = useRef<HTMLDivElement>(null);
const [isStuck, setIsStuck] = useState(false);
const handleViewerCommentClose = useCallback(() => {
setViewerCommentPopover(null);
}, []);
// Shared annotation infrastructure via hook
const {
highlighterRef,
toolbarState,
commentPopover: hookCommentPopover,
quickLabelPicker: hookQuickLabelPicker,
handleAnnotate,
handleQuickLabel,
handleToolbarClose,
handleRequestComment,
handleCommentSubmit: hookCommentSubmit,
handleCommentClose: hookCommentClose,
handleFloatingQuickLabel: hookFloatingQuickLabel,
handleQuickLabelPickerDismiss: hookQuickLabelPickerDismiss,
removeHighlight: hookRemoveHighlight,
clearAllHighlights,
applyAnnotations,
} = useAnnotationHighlighter({
containerRef,
annotations,
onAddAnnotation,
onSelectAnnotation,
selectedAnnotationId,
mode,
});
useEffect(() => {
if (!hookCommentPopover) {
setHookCommentDraftState({ hasContent: false, hadContentEver: false });
}
}, [hookCommentPopover]);
useEffect(() => {
if (!viewerCommentPopover) {
setViewerCommentDraftState({ hasContent: false, hadContentEver: false });
}
}, [viewerCommentPopover]);
// Refs for code block annotation path
const onAddAnnotationRef = useRef(onAddAnnotation);
useEffect(() => { onAddAnnotationRef.current = onAddAnnotation; }, [onAddAnnotation]);
const modeRef = useRef<EditorMode>(mode);
useEffect(() => { modeRef.current = mode; }, [mode]);
// Pinpoint mode: hover + click to select elements
const handlePinpointCodeBlockClick = useCallback((blockId: string, element: HTMLElement) => {
const codeEl = element.querySelector('code');
if (!codeEl) return;
// In pinpoint mode, apply code block annotation based on current editor mode
if (modeRef.current === 'redline') {
applyCodeBlockAnnotation(blockId, codeEl, AnnotationType.DELETION);
} else if (modeRef.current === 'quickLabel') {
setCodeBlockQuickLabelPicker({
anchorEl: element,
codeBlock: { block: blocks.find(b => b.id === blockId)!, element },
});
} else {
// Show comment popover anchored to the code block
setViewerCommentPopover({
anchorEl: element,
contextText: (codeEl.textContent || '').slice(0, 80),
isGlobal: false,
codeBlock: { block: blocks.find(b => b.id === blockId)!, element },
});
}
}, [blocks]);
const { hoverTarget } = usePinpoint({
containerRef,
highlighterRef,
inputMethod,
enabled: !toolbarState && !hookCommentPopover && !viewerCommentPopover && !hookQuickLabelPicker && !codeBlockQuickLabelPicker && !(isPlanDiffActive ?? false),
onCodeBlockClick: handlePinpointCodeBlockClick,
});
// Suppress native context menu on touch devices (prevents cut/copy/paste overlay on mobile)
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const isTouchPrimary = window.matchMedia('(pointer: coarse)').matches;
if (!isTouchPrimary) return;
const handleContextMenu = (e: Event) => {
e.preventDefault();
};
container.addEventListener('contextmenu', handleContextMenu);
return () => container.removeEventListener('contextmenu', handleContextMenu);
}, []);
// Detect when sticky action bar is "stuck" to show card background.
// The IntersectionObserver root must be the actual scroll element — the
// OverlayScrollArea viewport — not the <main> host, which doesn't scroll.
const stickyScrollViewport = useScrollViewport();
useEffect(() => {
if (!stickyActions || !stickySentinelRef.current || !stickyScrollViewport) return;
const observer = new IntersectionObserver(
([entry]) => setIsStuck(!entry.isIntersecting),
{ root: stickyScrollViewport, threshold: 0 }
);
observer.observe(stickySentinelRef.current);
return () => observer.disconnect();
}, [stickyActions, stickyScrollViewport]);
// Cmd+C / Ctrl+C keyboard shortcut for copying selected text
useEffect(() => {
const handleKeyDown = async (e: KeyboardEvent) => {
// Check for Cmd+C (Mac) or Ctrl+C (Windows/Linux)
if ((e.metaKey || e.ctrlKey) && e.key === 'c') {
// Don't intercept if typing in an input/textarea
const tag = (e.target as HTMLElement)?.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') return;
// If we have an active selection with captured text, use that
if (toolbarState?.selectionText) {
e.preventDefault();
try {
await navigator.clipboard.writeText(toolbarState.selectionText);
} catch (err) {
console.error('Failed to copy:', err);
}
}
// Otherwise let the browser handle default copy behavior
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [toolbarState]);
// Imperative handle — delegates to hook, extends removeHighlight for code blocks
useImperativeHandle(ref, () => ({
removeHighlight: (id: string) => {
// Code block annotations need syntax re-highlighting after removal.
// Must run BEFORE hookRemoveHighlight, which removes the <mark> elements.
const manualHighlights = containerRef.current?.querySelectorAll(`[data-bind-id="${id}"]`);
manualHighlights?.forEach(el => {
const parent = el.parentNode;
if (parent && parent.nodeName === 'CODE') {
const codeEl = parent as HTMLElement;
const plainText = el.textContent || '';
el.remove();
codeEl.textContent = plainText;
const block = blocks.find(b => b.id === codeEl.closest('[data-block-id]')?.getAttribute('data-block-id'));
codeEl.removeAttribute('data-highlighted');
codeEl.className = `hljs font-mono${block?.language ? ` language-${block.language}` : ''}`;
hljs.highlightElement(codeEl);
}
});
hookRemoveHighlight(id);
},
clearAllHighlights,
applySharedAnnotations: applyAnnotations,
dismissUndoableTransientState: () => {
if (hookCommentPopover) {
if (hookCommentDraftState.hadContentEver) return false;
hookCommentClose();
return true;
}
if (viewerCommentPopover) {
if (viewerCommentDraftState.hadContentEver) return false;
handleViewerCommentClose();
return true;
}
if (hookQuickLabelPicker) {
hookQuickLabelPickerDismiss();
return true;
}
if (toolbarState) {
handleToolbarClose();
return true;
}
return false;
},
}), [
applyAnnotations,
blocks,
clearAllHighlights,
handleToolbarClose,
handleViewerCommentClose,
hookCommentClose,
hookCommentDraftState.hadContentEver,
hookCommentPopover,
hookQuickLabelPicker,
hookQuickLabelPickerDismiss,
hookRemoveHighlight,
toolbarState,
viewerCommentDraftState.hadContentEver,
viewerCommentPopover,
]);
// --- Viewer-specific: code block annotation ---
const applyCodeBlockAnnotation = (
blockId: string,
codeEl: Element,
type: AnnotationType,
text?: string,
images?: ImageAttachment[],
isQuickLabel?: boolean,
quickLabelTip?: string,
) => {
const id = `codeblock-${Date.now()}`;
const codeText = codeEl.textContent || '';
const wrapper = document.createElement('mark');
wrapper.className = `annotation-highlight ${type === AnnotationType.DELETION ? 'deletion' : type === AnnotationType.COMMENT ? 'comment' : ''}`.trim();
wrapper.dataset.bindId = id;
wrapper.textContent = codeText;
codeEl.innerHTML = '';
codeEl.appendChild(wrapper);
const newAnnotation: Annotation = {
id,
blockId,
startOffset: 0,
endOffset: codeText.length,
type,
text,
originalText: codeText,
createdA: Date.now(),
author: getIdentity(),
images,
...(isQuickLabel ? { isQuickLabel: true } : {}),
...(quickLabelTip ? { quickLabelTip } : {}),
};
onAddAnnotationRef.current(newAnnotation);
window.getSelection()?.removeAllRanges();
};
const handleCodeBlockAnnotate = (type: AnnotationType) => {
if (!hoveredCodeBlock) return;
const codeEl = hoveredCodeBlock.element.querySelector('code');
if (!codeEl) return;
applyCodeBlockAnnotation(hoveredCodeBlock.block.id, codeEl, type);
setHoveredCodeBlock(null);
};
const handleCodeBlockQuickLabel = (label: QuickLabel) => {
if (!hoveredCodeBlock) return;
const codeEl = hoveredCodeBlock.element.querySelector('code');
if (!codeEl) return;
applyCodeBlockAnnotation(
hoveredCodeBlock.block.id, codeEl, AnnotationType.COMMENT,
`${label.emoji} ${label.text}`, undefined, true, label.tip
);
setHoveredCodeBlock(null);
};
const handleCodeBlockToolbarClose = () => {
setHoveredCodeBlock(null);
};
// Viewer-specific comment popover handlers (code blocks + global comments)
const handleCodeBlockRequestComment = (initialChar?: string) => {
if (!hoveredCodeBlock) return;
const codeText = hoveredCodeBlock.element.querySelector('code')?.textContent || '';
setViewerCommentPopover({
anchorEl: hoveredCodeBlock.element,
contextText: codeText.slice(0, 80),
initialText: initialChar,
isGlobal: false,
codeBlock: hoveredCodeBlock,
});
setHoveredCodeBlock(null);
};
const handleViewerCommentSubmit = (text: string, images?: ImageAttachment[]) => {
if (!viewerCommentPopover) return;
if (viewerCommentPopover.isGlobal) {
const newAnnotation: Annotation = {
id: `global-${Date.now()}`,
blockId: '',
startOffset: 0,
endOffset: 0,
type: AnnotationType.GLOBAL_COMMENT,
text: text.trim(),
originalText: '',
createdA: Date.now(),
author: getIdentity(),
images,
};
onAddAnnotation(newAnnotation);
} else if (viewerCommentPopover.codeBlock) {
const codeEl = viewerCommentPopover.codeBlock.element.querySelector('code');
if (codeEl) {
applyCodeBlockAnnotation(viewerCommentPopover.codeBlock.block.id, codeEl, AnnotationType.COMMENT, text, images);
}
}
setViewerCommentPopover(null);
};
return (
<div className="relative z-50 w-full" style={maxWidth ? { maxWidth } : { maxWidth: 832 }}>
{taterMode && <TaterSpriteSitting />}
<article
ref={containerRef}
data-print-region="article"
className={`w-full bg-card rounded-xl shadow-xl p-5 md:p-8 lg:p-10 xl:p-12 relative border border-border/50 ${inputMethod === 'pinpoint' ? 'cursor-crosshair' : ''}`}
style={{ WebkitTouchCallout: 'none' } as React.CSSProperties}
>
{/* Repo info + plan diff badge + demo badge + linked doc badge + archive badge - top left */}
{(repoInfo || hasPreviousVersion || showDemoBadge || linkedDocInfo || archiveInfo) && (
<div data-print-hide className="absolute top-3 left-3 md:top-4 md:left-5">
<DocBadges
layout="column"
repoInfo={repoInfo}
planDiffStats={planDiffStats}
isPlanDiffActive={isPlanDiffActive}
hasPreviousVersion={hasPreviousVersion}
onPlanDiffToggle={onPlanDiffToggle}
showDemoBadge={showDemoBadge}
archiveInfo={archiveInfo}
linkedDocInfo={linkedDocInfo}
/>
</div>
)}
{/* Sentinel for sticky detection */}
{stickyActions && <div ref={stickySentinelRef} className="h-0 w-0 float-right" aria-hidden="true" />}
{/* Header buttons - top right */}
<div data-print-hide data-sticky-actions className={`${stickyActions ? 'sticky top-3' : ''} z-30 float-right flex items-start gap-1 md:gap-2 rounded-lg p-1 md:p-2 transition-colors duration-150 ${isStuck ? 'bg-card/95 backdrop-blur-sm shadow-sm' : ''} -mr-3 mt-6 md:-mr-5 md:-mt-5 lg:-mr-7 lg:-mt-7 xl:-mr-9 xl:-mt-9`}>
{/* Attachments button */}
{onAddGlobalAttachment && onRemoveGlobalAttachment && (
<AttachmentsButton
images={globalAttachments}
onAdd={onAddGlobalAttachment}
onRemove={onRemoveGlobalAttachment}
variant="toolbar"
hideLabel={actionsLabelMode === 'icon'}
/>
)}
{/* <span className="md:hidden">Comment</span><span className="hidden md:inline">Global comment</span> button */}
<button
ref={globalCommentButtonRef}
onClick={() => {
setViewerCommentPopover({
anchorEl: globalCommentButtonRef.current!,
contextText: '',
isGlobal: true,
});
}}
className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground bg-muted/50 hover:bg-muted rounded-md transition-colors"
title="Add global comment"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 21a9.004 9.004 0 008.716-6.747M12 21a9.004 9.004 0 01-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 017.843 4.582M12 3a8.997 8.997 0 00-7.843 4.582m15.686 0A11.953 11.953 0 0112 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0121 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0112 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 013 12c0-1.605.42-3.113 1.157-4.418" />
</svg>
{actionsLabelMode === 'full' && <span>Global comment</span>}
{actionsLabelMode === 'short' && <span>Comment</span>}
</button>
{/* Copy plan/file button */}
<button
onClick={handleCopyPlan}
className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground bg-muted/50 hover:bg-muted rounded-md transition-colors"
title={copied ? 'Copied!' : copyLabel || (linkedDocInfo ? 'Copy file' : 'Copy plan')}
>
{copied ? (
<>
<svg className="w-3.5 h-3.5 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
Copied!
</>
) : (
<>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
{actionsLabelMode === 'full' && <span>{copyLabel || (linkedDocInfo ? 'Copy file' : 'Copy plan')}</span>}
{actionsLabelMode === 'short' && <span>Copy</span>}
</>
)}
</button>
</div>
{frontmatter && <><div className="clear-right md:hidden" /><FrontmatterCard frontmatter={frontmatter} /></>}
{!frontmatter && blocks.length > 0 && blocks[0].type !== 'heading' && <div className="mt-4" />}
{groupBlocks(blocks).map(group =>
group.type === 'list-group' ? (
(() => {
const indices = computeListIndices(group.blocks);
return (
<div key={group.key} data-pinpoint-group="list" className="py-1 -mx-2 px-2">
{group.blocks.map((block, i) => (
<BlockRenderer
imageBaseDir={imageBaseDir}
onImageClick={(src, alt) => setLightbox({ src, alt })}
key={block.id}
block={block}
orderedIndex={indices[i]}
onOpenLinkedDoc={onOpenLinkedDoc}
onToggleCheckbox={onToggleCheckbox}
checkboxOverrides={checkboxOverrides}
/>
))}
</div>
);
})()
) : group.block.type === 'code' && isMermaidLanguage(group.block.language) ? (
<MermaidBlock key={group.block.id} block={group.block} />
) : group.block.type === 'code' && isGraphvizLanguage(group.block.language) ? (
<GraphvizBlock key={group.block.id} block={group.block} />
) : group.block.type === 'code' ? (
<CodeBlock
key={group.block.id}
block={group.block}
onHover={inputMethod === 'pinpoint' ? () => {} : (element) => {
// Clear any pending leave timeout
if (hoverTimeoutRef.current) {
clearTimeout(hoverTimeoutRef.current);
hoverTimeoutRef.current = null;
}
// Cancel exit animation if re-entering
setIsCodeBlockToolbarExiting(false);
// Only show hover toolbar if no selection toolbar is active
if (!toolbarState) {
setHoveredCodeBlock({ block: group.block, element });
}
}}
onLeave={inputMethod === 'pinpoint' ? () => {} : () => {
// Delay then start exit animation
hoverTimeoutRef.current = setTimeout(() => {
setIsCodeBlockToolbarExiting(true);
// After exit animation, unmount
setTimeout(() => {
setHoveredCodeBlock(null);
setIsCodeBlockToolbarExiting(false);
}, 150);
}, 100);
}}
isHovered={inputMethod !== 'pinpoint' && hoveredCodeBlock?.block.id === group.block.id}
/>
) : (
<BlockRenderer imageBaseDir={imageBaseDir} onImageClick={(src, alt) => setLightbox({ src, alt })} key={group.block.id} block={group.block} onOpenLinkedDoc={onOpenLinkedDoc} onToggleCheckbox={onToggleCheckbox} checkboxOverrides={checkboxOverrides} />
)
)}
{/* Text selection toolbar */}
{toolbarState && (
<ToolbarErrorBoundary>
<AnnotationToolbar
element={toolbarState.element}
positionMode="center-above"
onAnnotate={handleAnnotate}
onClose={handleToolbarClose}
onRequestComment={handleRequestComment}
onQuickLabel={handleQuickLabel}
copyText={toolbarState.selectionText}
closeOnScrollOut
/>
</ToolbarErrorBoundary>
)}
{/* Code block hover toolbar */}
{hoveredCodeBlock && !toolbarState && (
<ToolbarErrorBoundary>
<AnnotationToolbar
element={hoveredCodeBlock.element}
positionMode="top-right"
onAnnotate={handleCodeBlockAnnotate}
onClose={handleCodeBlockToolbarClose}
onRequestComment={handleCodeBlockRequestComment}
onQuickLabel={handleCodeBlockQuickLabel}
isExiting={isCodeBlockToolbarExiting}
onMouseEnter={() => {
if (hoverTimeoutRef.current) {
clearTimeout(hoverTimeoutRef.current);
hoverTimeoutRef.current = null;
}
setIsCodeBlockToolbarExiting(false);
}}
onMouseLeave={() => {
hoverTimeoutRef.current = setTimeout(() => {
setIsCodeBlockToolbarExiting(true);
setTimeout(() => {
setHoveredCodeBlock(null);
setIsCodeBlockToolbarExiting(false);
}, 150);
}, 100);
}}
/>
</ToolbarErrorBoundary>
)}
{/* Pinpoint hover overlay */}
{inputMethod === 'pinpoint' && (
<PinpointOverlay target={hoverTarget} containerRef={containerRef} />
)}
{/* Comment popover — hook handles text selection, Viewer handles global + code block */}
{hookCommentPopover && (
<CommentPopover
anchorEl={hookCommentPopover.anchorEl}
contextText={hookCommentPopover.contextText}
isGlobal={false}
initialText={hookCommentPopover.initialText}
onSubmit={hookCommentSubmit}
onClose={hookCommentClose}
onDraftStateChange={setHookCommentDraftState}
/>
)}
{viewerCommentPopover && (
<CommentPopover
anchorEl={viewerCommentPopover.anchorEl}
contextText={viewerCommentPopover.contextText}
isGlobal={viewerCommentPopover.isGlobal}
initialText={viewerCommentPopover.initialText}
onSubmit={handleViewerCommentSubmit}
onClose={handleViewerCommentClose}
onDraftStateChange={setViewerCommentDraftState}
/>
)}
{/* Quick Label floating picker — hook handles text selection, Viewer handles code blocks */}
{hookQuickLabelPicker && (
<FloatingQuickLabelPicker
anchorEl={hookQuickLabelPicker.anchorEl}
cursorHint={hookQuickLabelPicker.cursorHint}
onSelect={hookFloatingQuickLabel}
onDismiss={hookQuickLabelPickerDismiss}
/>
)}
{codeBlockQuickLabelPicker && (
<FloatingQuickLabelPicker
anchorEl={codeBlockQuickLabelPicker.anchorEl}
onSelect={(label: QuickLabel) => {
const codeEl = codeBlockQuickLabelPicker.codeBlock.element.querySelector('code');
if (codeEl) {
applyCodeBlockAnnotation(
codeBlockQuickLabelPicker.codeBlock.block.id, codeEl, AnnotationType.COMMENT,
`${label.emoji} ${label.text}`, undefined, true, label.tip
);
}
setCodeBlockQuickLabelPicker(null);
window.getSelection()?.removeAllRanges();
}}
onDismiss={() => {
setCodeBlockQuickLabelPicker(null);
window.getSelection()?.removeAllRanges();
}}
/>
)}
</article>
{/* Image lightbox */}
{lightbox && createPortal(
<ImageLightbox src={lightbox.src} alt={lightbox.alt} onClose={() => setLightbox(null)} />,
document.body
)}
</div>
);
});
/** Simple lightbox overlay for enlarged image viewing. */
const ImageLightbox: React.FC<{ src: string; alt: string; onClose: () => void }> = ({ src, alt, onClose }) => {
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [onClose]);
return (
<div
className="fixed inset-0 z-[200] flex flex-col items-center justify-center bg-black/80 backdrop-blur-sm cursor-zoom-out"
onClick={onClose}
>
<img
src={src}
alt={alt}
className="max-w-[90vw] max-h-[85vh] object-contain rounded-lg shadow-2xl"
onClick={(e) => e.stopPropagation()}
/>
{alt && (
<div className="mt-3 text-sm text-white/70 max-w-[90vw] text-center truncate">{alt}</div>
)}
</div>
);
};
/**
* Renders inline markdown: **bold**, *italic*, _italic_, `code`, [links](url)
*/
const InlineMarkdown: React.FC<{ text: string; onOpenLinkedDoc?: (path: string) => void; imageBaseDir?: string; onImageClick?: (src: string, alt: string) => void }> = ({ text, onOpenLinkedDoc, imageBaseDir, onImageClick }) => {
const parts: React.ReactNode[] = [];
let remaining = text;
let key = 0;
let previousChar = '';
while (remaining.length > 0) {
// Backslash escaping: \* \_ \` \[ \~ etc. — emit literal char, hide backslash
let match = remaining.match(/^\\([*_`\[\]~!\\])/);
if (match) {
parts.push(match[1]);
remaining = remaining.slice(2);
previousChar = match[1];
continue;
}
// Autolinks: <https://url> or <email@domain.com>
match = remaining.match(/^<(https?:\/\/[^>]+)>/);
if (match) {
const url = match[1];
parts.push(<a key={key++} href={url} target="_blank" rel="noopener noreferrer" className="text-primary underline underline-offset-2 hover:text-primary/80">{url}</a>);
remaining = remaining.slice(match[0].length);
previousChar = '>';
continue;
}
match = remaining.match(/^<([^@>\s]+@[^>\s]+)>/);
if (match) {
const email = match[1];
parts.push(<a key={key++} href={`mailto:${email}`} className="text-primary underline underline-offset-2 hover:text-primary/80">{email}</a>);
remaining = remaining.slice(match[0].length);
previousChar = '>';
continue;
}
// Strikethrough: ~~text~~
match = remaining.match(/^~~([\s\S]+?)~~/);
if (match) {
parts.push(<del key={key++}><InlineMarkdown imageBaseDir={imageBaseDir} onImageClick={onImageClick} text={match[1]} onOpenLinkedDoc={onOpenLinkedDoc} /></del>);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Bold + italic: ***text***
match = remaining.match(/^\*\*\*([\s\S]+?)\*\*\*/);
if (match) {
parts.push(<strong key={key++} className="font-semibold"><em><InlineMarkdown imageBaseDir={imageBaseDir} onImageClick={onImageClick} text={match[1]} onOpenLinkedDoc={onOpenLinkedDoc} /></em></strong>);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Bold: **text** ([\s\S]+? allows matching across hard line breaks)
match = remaining.match(/^\*\*([\s\S]+?)\*\*/);
if (match) {
parts.push(<strong key={key++} className="font-semibold"><InlineMarkdown imageBaseDir={imageBaseDir} onImageClick={onImageClick} text={match[1]} onOpenLinkedDoc={onOpenLinkedDoc} /></strong>);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Italic: *text* or _text_ (avoid intraword underscores)
match = remaining.match(/^\*([\s\S]+?)\*/);
if (match) {
parts.push(<em key={key++}><InlineMarkdown imageBaseDir={imageBaseDir} onImageClick={onImageClick} text={match[1]} onOpenLinkedDoc={onOpenLinkedDoc} /></em>);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
match = !/\w/.test(previousChar)
? remaining.match(/^_([^_\s](?:[\s\S]*?[^_\s])?)_(?!\w)/)
: null;
if (match) {
parts.push(<em key={key++}><InlineMarkdown imageBaseDir={imageBaseDir} onImageClick={onImageClick} text={match[1]} onOpenLinkedDoc={onOpenLinkedDoc} /></em>);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Inline code: `code`
match = remaining.match(/^`([^`]+)`/);
if (match) {
parts.push(
<code key={key++} className="px-1.5 py-0.5 rounded bg-muted text-sm font-mono">
{match[1]}
</code>
);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Wikilinks: [[filename]] or [[filename|display text]]
match = remaining.match(/^\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/);
if (match) {
const target = match[1].trim();
const display = match[2]?.trim() || target;
const targetPath = /\.mdx?$/i.test(target) ? target : `${target}.md`;
if (onOpenLinkedDoc) {
parts.push(
<a
key={key++}
href={targetPath}
onClick={(e) => {
e.preventDefault();
onOpenLinkedDoc(targetPath);
}}
className="text-primary underline underline-offset-2 hover:text-primary/80 inline-flex items-center gap-1 cursor-pointer"
title={`Open: ${target}`}
>
{display}
<svg className="w-3 h-3 opacity-50 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2} aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
</svg>
</a>
);
} else {
parts.push(
<span key={key++} className="text-primary">{display}</span>
);
}
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Images: 
match = remaining.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
if (match) {
const alt = match[1];
const src = match[2];
const imgSrc = /^https?:\/\//.test(src) ? src : getImageSrc(src, imageBaseDir);
parts.push(
<img
key={key++}
src={imgSrc}
alt={alt}
className="max-w-full rounded my-2 cursor-zoom-in"
loading="lazy"
onClick={(e) => { e.stopPropagation(); onImageClick?.(imgSrc, alt); }}
/>
);
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;
}
// Links: [text](url)
match = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
if (match) {
const linkText = match[1];
const linkUrl = match[2];
const isLocalMd = /\.md(x?)$/i.test(linkUrl) &&
!linkUrl.startsWith('http://') &&
!linkUrl.startsWith('https://');
if (isLocalMd && onOpenLinkedDoc) {
parts.push(
<a
key={key++}
href={linkUrl}
onClick={(e) => {
e.preventDefault();
onOpenLinkedDoc(linkUrl);
}}
className="text-primary underline underline-offset-2 hover:text-primary/80 inline-flex items-center gap-1 cursor-pointer"
title={`Open: ${linkUrl}`}
>
{linkText}
<svg className="w-3 h-3 opacity-50 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2} aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
</svg>
</a>
);
} else if (isLocalMd) {
// No handler — render as plain link (e.g., in shared/portal views)
parts.push(
<a
key={key++}
href={linkUrl}
className="text-primary underline underline-offset-2 hover:text-primary/80"
>
{linkText}
</a>
);
} else {
parts.push(
<a
key={key++}
href={linkUrl}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline underline-offset-2 hover:text-primary/80"
>
{linkText}
</a>
);
}
remaining = remaining.slice(match[0].length);
previousChar = match[0][match[0].length - 1] || previousChar;
continue;