@semiont/react-ui 0.5.11 → 0.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{PdfAnnotationCanvas.client-KWQ7XDWT.js → PdfAnnotationCanvas.client-75GY2EDR.js} +12 -6
  2. package/dist/PdfAnnotationCanvas.client-75GY2EDR.js.map +1 -0
  3. package/dist/{chunk-O2MD7TGE.js → chunk-VXASXU4K.js} +10 -2
  4. package/dist/chunk-VXASXU4K.js.map +1 -0
  5. package/dist/index.d.ts +54 -16
  6. package/dist/index.js +395 -343
  7. package/dist/index.js.map +1 -1
  8. package/dist/test-utils.d.ts +5 -1
  9. package/dist/test-utils.js +3 -2
  10. package/dist/test-utils.js.map +1 -1
  11. package/package.json +5 -5
  12. package/src/components/image-annotation/AnnotationOverlay.tsx +6 -6
  13. package/src/components/image-annotation/SvgDrawingCanvas.tsx +12 -4
  14. package/src/components/image-annotation/__tests__/AnnotationOverlay.click.test.tsx +137 -0
  15. package/src/components/image-annotation/__tests__/SvgDrawingCanvas.click.test.tsx +108 -0
  16. package/src/components/pdf-annotation/PdfAnnotationCanvas.tsx +12 -4
  17. package/src/components/pdf-annotation/__tests__/PdfAnnotationCanvas.test.tsx +137 -1
  18. package/src/components/resource/BrowseView.tsx +14 -6
  19. package/src/components/resource/ResourceViewer.tsx +6 -4
  20. package/src/components/resource/__tests__/BrowseView.test.tsx +98 -31
  21. package/src/components/resource/__tests__/ResourceViewer.embeddable.test.tsx +40 -1
  22. package/src/components/resource/__tests__/browse-renderers.dispatch.test.tsx +113 -0
  23. package/src/components/resource/browse-renderers.tsx +26 -4
  24. package/src/components/resource/panels/AssessmentEntry.tsx +5 -4
  25. package/src/components/resource/panels/AssessmentPanel.tsx +8 -5
  26. package/src/components/resource/panels/AssistSection.tsx +4 -3
  27. package/src/components/resource/panels/CommentEntry.tsx +5 -4
  28. package/src/components/resource/panels/CommentsPanel.tsx +8 -5
  29. package/src/components/resource/panels/HighlightEntry.tsx +5 -4
  30. package/src/components/resource/panels/HighlightPanel.tsx +8 -5
  31. package/src/components/resource/panels/ReferenceEntry.tsx +9 -10
  32. package/src/components/resource/panels/ReferencesPanel.tsx +11 -6
  33. package/src/components/resource/panels/ResourceInfoPanel.tsx +4 -3
  34. package/src/components/resource/panels/TagEntry.tsx +5 -3
  35. package/src/components/resource/panels/TaggingPanel.tsx +7 -4
  36. package/src/components/resource/panels/UnifiedAnnotationsPanel.tsx +10 -0
  37. package/src/components/resource/panels/__tests__/AssessmentEntry.test.tsx +28 -20
  38. package/src/components/resource/panels/__tests__/AssessmentPanel.test.tsx +38 -28
  39. package/src/components/resource/panels/__tests__/AssistSection.test.tsx +46 -17
  40. package/src/components/resource/panels/__tests__/CommentEntry.test.tsx +65 -57
  41. package/src/components/resource/panels/__tests__/CommentsPanel.test.tsx +53 -24
  42. package/src/components/resource/panels/__tests__/HighlightEntry.test.tsx +27 -17
  43. package/src/components/resource/panels/__tests__/HighlightPanel.annotationProgress.test.tsx +23 -17
  44. package/src/components/resource/panels/__tests__/ReferenceEntry.test.tsx +48 -77
  45. package/src/components/resource/panels/__tests__/ReferencesPanel.headless.test.tsx +87 -0
  46. package/src/components/resource/panels/__tests__/ReferencesPanel.observable-flow.test.tsx +15 -9
  47. package/src/components/resource/panels/__tests__/ReferencesPanel.test.tsx +77 -59
  48. package/src/components/resource/panels/__tests__/ResourceInfoPanel.test.tsx +11 -4
  49. package/src/components/resource/panels/__tests__/TagEntry.test.tsx +33 -19
  50. package/src/components/resource/panels/__tests__/TaggingPanel.test.tsx +15 -7
  51. package/src/features/resource-viewer/components/ResourceViewerPage.tsx +3 -0
  52. package/dist/PdfAnnotationCanvas.client-KWQ7XDWT.js.map +0 -1
  53. package/dist/chunk-O2MD7TGE.js.map +0 -1
@@ -1,8 +1,9 @@
1
1
  import { describe, it, expect, beforeEach, vi } from 'vitest';
2
+ import { cloneElement, type ReactElement } from 'react';
2
3
  import { render, screen } from '@testing-library/react';
3
4
  import '@testing-library/jest-dom';
4
5
  import { of } from 'rxjs';
5
- import { CacheObservable } from '@semiont/sdk';
6
+ import { CacheObservable, type SemiontSession } from '@semiont/sdk';
6
7
  import { renderWithProviders, createTestSemiontWrapper } from '../../../../test-utils';
7
8
  import userEvent from '@testing-library/user-event';
8
9
  import type { TagSchema } from '@semiont/core';
@@ -65,6 +66,17 @@ describe('TagEntry', () => {
65
66
  const defaultProps = {
66
67
  tag: createMockTag(),
67
68
  isFocused: false,
69
+ // Satisfies JSX at element construction only; render helpers/tests pass
70
+ // the real per-test factory session explicitly. Never put a live session
71
+ // here — module-scope clients get disposed after the first test.
72
+ session: null,
73
+ };
74
+
75
+ // The component is provider-free: hand it a fresh per-test fake session as
76
+ // the `session` prop. renderWithProviders still supplies translations/toasts.
77
+ const renderTagEntry = (element: ReactElement<{ session: SemiontSession | null }>) => {
78
+ const { session } = createTestSemiontWrapper();
79
+ return renderWithProviders(cloneElement(element, { session }));
68
80
  };
69
81
 
70
82
  beforeEach(() => {
@@ -76,13 +88,13 @@ describe('TagEntry', () => {
76
88
 
77
89
  describe('Rendering', () => {
78
90
  it('should render the category badge', () => {
79
- renderWithProviders(<TagEntry {...defaultProps} />);
91
+ renderTagEntry(<TagEntry {...defaultProps} />);
80
92
 
81
93
  expect(screen.getByText('Entity')).toBeInTheDocument();
82
94
  });
83
95
 
84
96
  it('should render the selected text in quotes', () => {
85
- renderWithProviders(<TagEntry {...defaultProps} />);
97
+ renderTagEntry(<TagEntry {...defaultProps} />);
86
98
 
87
99
  expect(screen.getByText(/Tagged text content/)).toBeInTheDocument();
88
100
  });
@@ -91,7 +103,7 @@ describe('TagEntry', () => {
91
103
  const longText = 'C'.repeat(200);
92
104
  mockGetAnnotationExactText.mockReturnValue(longText);
93
105
 
94
- renderWithProviders(<TagEntry {...defaultProps} />);
106
+ renderTagEntry(<TagEntry {...defaultProps} />);
95
107
 
96
108
  expect(screen.getByText(new RegExp(`"${'C'.repeat(150)}`))).toBeInTheDocument();
97
109
  expect(screen.getByText(/\.\.\./)).toBeInTheDocument();
@@ -101,7 +113,7 @@ describe('TagEntry', () => {
101
113
  const exactText = 'D'.repeat(150);
102
114
  mockGetAnnotationExactText.mockReturnValue(exactText);
103
115
 
104
- const { container } = renderWithProviders(<TagEntry {...defaultProps} />);
116
+ const { container } = renderTagEntry(<TagEntry {...defaultProps} />);
105
117
 
106
118
  const quote = container.querySelector('.semiont-annotation-entry__quote');
107
119
  expect(quote).toBeInTheDocument();
@@ -121,11 +133,11 @@ describe('TagEntry', () => {
121
133
  // Stub the cache to resolve immediately with the test schema —
122
134
  // exercises the rendering path without round-tripping through the
123
135
  // transport's HTTP plumbing.
124
- const { SemiontWrapper, client } = createTestSemiontWrapper();
136
+ const { SemiontWrapper, client, session } = createTestSemiontWrapper();
125
137
  vi.spyOn(client.browse, 'tagSchemas').mockReturnValue(
126
138
  CacheObservable.from(of([NER_SCHEMA]))
127
139
  );
128
- render(<TagEntry {...defaultProps} />, { wrapper: SemiontWrapper });
140
+ render(<TagEntry {...defaultProps} session={session} />, { wrapper: SemiontWrapper });
129
141
 
130
142
  expect(screen.getByText('Named Entity Recognition')).toBeInTheDocument();
131
143
  });
@@ -135,17 +147,17 @@ describe('TagEntry', () => {
135
147
 
136
148
  // Stub the cache to resolve to an empty list — the schema lookup
137
149
  // misses, the schema-name `<span>` is not rendered.
138
- const { SemiontWrapper, client } = createTestSemiontWrapper();
150
+ const { SemiontWrapper, client, session } = createTestSemiontWrapper();
139
151
  vi.spyOn(client.browse, 'tagSchemas').mockReturnValue(
140
152
  CacheObservable.from(of([]))
141
153
  );
142
- const { container } = render(<TagEntry {...defaultProps} />, { wrapper: SemiontWrapper });
154
+ const { container } = render(<TagEntry {...defaultProps} session={session} />, { wrapper: SemiontWrapper });
143
155
 
144
156
  expect(container.querySelector('.semiont-annotation-entry__meta')).not.toBeInTheDocument();
145
157
  });
146
158
 
147
159
  it('should render category badge with correct data-variant', () => {
148
- const { container } = renderWithProviders(<TagEntry {...defaultProps} />);
160
+ const { container } = renderTagEntry(<TagEntry {...defaultProps} />);
149
161
 
150
162
  const badge = container.querySelector('.semiont-tag-badge');
151
163
  expect(badge).toBeInTheDocument();
@@ -157,12 +169,14 @@ describe('TagEntry', () => {
157
169
  it('should emit browse:click on click', async () => {
158
170
  const clickHandler = vi.fn();
159
171
 
160
- const { container, eventBus } = renderWithProviders(
161
- <TagEntry {...defaultProps} />,
162
- { returnEventBus: true }
163
- );
172
+ // The session prop is the only session the provider-free component
173
+ // sees — subscribe on the SAME factory's bus that backs it.
174
+ const { session, eventBus } = createTestSemiontWrapper();
175
+ const subscription = eventBus.get('browse:click').subscribe(clickHandler);
164
176
 
165
- const subscription = eventBus!.get('browse:click').subscribe(clickHandler);
177
+ const { container } = renderWithProviders(
178
+ <TagEntry {...defaultProps} session={session} />
179
+ );
166
180
 
167
181
  const entry = container.firstChild as HTMLElement;
168
182
  await userEvent.click(entry);
@@ -178,7 +192,7 @@ describe('TagEntry', () => {
178
192
 
179
193
  describe('Hover state', () => {
180
194
  it('should apply pulse class when isHovered is true', () => {
181
- const { container } = renderWithProviders(
195
+ const { container } = renderTagEntry(
182
196
  <TagEntry {...defaultProps} isHovered={true} />
183
197
  );
184
198
 
@@ -187,7 +201,7 @@ describe('TagEntry', () => {
187
201
  });
188
202
 
189
203
  it('should not apply pulse class when isHovered is false', () => {
190
- const { container } = renderWithProviders(
204
+ const { container } = renderTagEntry(
191
205
  <TagEntry {...defaultProps} isHovered={false} />
192
206
  );
193
207
 
@@ -198,7 +212,7 @@ describe('TagEntry', () => {
198
212
 
199
213
  describe('Focus state', () => {
200
214
  it('should set data-focused to true when focused', () => {
201
- const { container } = renderWithProviders(
215
+ const { container } = renderTagEntry(
202
216
  <TagEntry {...defaultProps} isFocused={true} />
203
217
  );
204
218
 
@@ -207,7 +221,7 @@ describe('TagEntry', () => {
207
221
  });
208
222
 
209
223
  it('should set data-type to tag', () => {
210
- const { container } = renderWithProviders(<TagEntry {...defaultProps} />);
224
+ const { container } = renderTagEntry(<TagEntry {...defaultProps} />);
211
225
 
212
226
  const entry = container.firstChild as HTMLElement;
213
227
  expect(entry).toHaveAttribute('data-type', 'tag');
@@ -5,7 +5,7 @@ import { render, screen, waitFor } from '@testing-library/react';
5
5
  import userEvent from '@testing-library/user-event';
6
6
  import '@testing-library/jest-dom';
7
7
  import { of } from 'rxjs';
8
- import { CacheObservable } from '@semiont/sdk';
8
+ import { CacheObservable, type SemiontSession } from '@semiont/sdk';
9
9
  import { TaggingPanel } from '../TaggingPanel';
10
10
  import type { EventBus, TagSchema } from '@semiont/core';
11
11
  import { createTestSemiontWrapper } from '../../../../test-utils';
@@ -53,8 +53,8 @@ const TEST_TAG_SCHEMAS: TagSchema[] = [
53
53
  },
54
54
  ];
55
55
 
56
- const renderWithEventBus = (component: React.ReactElement, tracker?: ReturnType<typeof createEventTracker>) => {
57
- const { SemiontWrapper, eventBus, client } = createTestSemiontWrapper();
56
+ const renderWithEventBus = (component: React.ReactElement<{ session: SemiontSession | null }>, tracker?: ReturnType<typeof createEventTracker>) => {
57
+ const { SemiontWrapper, eventBus, client, session } = createTestSemiontWrapper();
58
58
  vi.spyOn(client.browse, 'tagSchemas').mockReturnValue(
59
59
  CacheObservable.from(of(TEST_TAG_SCHEMAS))
60
60
  );
@@ -62,21 +62,24 @@ const renderWithEventBus = (component: React.ReactElement, tracker?: ReturnType<
62
62
  const Wrapper = ({ children }: { children: React.ReactNode }) => (
63
63
  <SemiontWrapper>{children}</SemiontWrapper>
64
64
  );
65
- return render(component, { wrapper: Wrapper });
65
+ // The component is provider-free: the `session` prop is the only session it
66
+ // sees. Inject the factory session here so it is the SAME session whose
67
+ // client backs `eventBus` (trackers subscribe there).
68
+ return render(React.cloneElement(component, { session }), { wrapper: Wrapper });
66
69
  };
67
70
 
68
71
  // Variant for the empty-registry case: the cache resolves to `[]`
69
72
  // (post-bootstrap, no schemas registered). Distinct from the still-
70
73
  // loading case where the observable yields `undefined`.
71
- const renderWithEmptyRegistry = (component: React.ReactElement) => {
72
- const { SemiontWrapper, client } = createTestSemiontWrapper();
74
+ const renderWithEmptyRegistry = (component: React.ReactElement<{ session: SemiontSession | null }>) => {
75
+ const { SemiontWrapper, client, session } = createTestSemiontWrapper();
73
76
  vi.spyOn(client.browse, 'tagSchemas').mockReturnValue(
74
77
  CacheObservable.from(of([]))
75
78
  );
76
79
  const Wrapper = ({ children }: { children: React.ReactNode }) => (
77
80
  <SemiontWrapper>{children}</SemiontWrapper>
78
81
  );
79
- return render(component, { wrapper: Wrapper });
82
+ return render(React.cloneElement(component, { session }), { wrapper: Wrapper });
80
83
  };
81
84
 
82
85
  // Mock TranslationContext. The component now uses `schema.name` /
@@ -188,6 +191,11 @@ describe('TaggingPanel Component', () => {
188
191
  resourceId: 'res-1',
189
192
  annotations: mockTags.empty,
190
193
  pendingAnnotation: null,
194
+ // Satisfies JSX at element construction only; the render helpers always
195
+ // replace it (via cloneElement) with the per-test factory session. Never
196
+ // put a live session here — module-scope clients get disposed after the
197
+ // first test.
198
+ session: null,
191
199
  };
192
200
 
193
201
  beforeEach(() => {
@@ -574,6 +574,8 @@ export function ResourceViewerPage({
574
574
  {/* Unified Annotations Panel */}
575
575
  {activePanel === 'annotations' && !resource.archived && (
576
576
  <UnifiedAnnotationsPanel
577
+ session={session ?? null}
578
+ onOpenResource={handleViewerOpenResource}
577
579
  annotations={annotations}
578
580
  annotators={ANNOTATORS}
579
581
  annotateMode={annotateMode}
@@ -612,6 +614,7 @@ export function ResourceViewerPage({
612
614
  {/* Document Info Panel */}
613
615
  {activePanel === 'info' && (
614
616
  <ResourceInfoPanel
617
+ session={session ?? null}
615
618
  resourceId={rUri}
616
619
  documentEntityTypes={documentEntityTypes}
617
620
  documentLocale={getLanguage(resource)}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/pdf-annotation/PdfAnnotationCanvas.tsx","../src/lib/pdf-coordinates.ts"],"sourcesContent":["'use client';\n\nimport React, { useRef, useState, useCallback, useEffect, useMemo } from 'react';\nimport type { Annotation } from '@semiont/core';\nimport { resourceId as toResourceId } from '@semiont/core';\nimport {\n getTargetSelector,\n createFragmentSelector,\n parseFragmentSelector,\n getPageFromFragment,\n} from '@semiont/core';\nimport { createHoverHandlers, type SemiontSession } from '@semiont/sdk';\nimport type { SelectionMotivation } from '../annotation/AnnotateToolbar';\nimport {\n canvasToPdfCoordinates,\n pdfToCanvasCoordinates,\n type CanvasRectangle\n} from '../../lib/pdf-coordinates';\nimport {\n loadPdfDocument,\n renderPdfPageToDataUrl,\n type PDFDocumentProxy\n} from '../../lib/browser-pdfjs';\nimport './PdfAnnotationCanvas.css';\n\nexport type DrawingMode = 'rectangle' | 'circle' | 'polygon' | null;\n\n/**\n * Get color for annotation based on motivation\n */\nfunction getMotivationColor(motivation: SelectionMotivation | null): { stroke: string; fill: string } {\n if (!motivation) {\n return { stroke: 'rgb(156, 163, 175)', fill: 'rgba(156, 163, 175, 0.2)' };\n }\n\n switch (motivation) {\n case 'highlighting':\n return { stroke: 'rgb(250, 204, 21)', fill: 'rgba(250, 204, 21, 0.3)' };\n case 'linking':\n return { stroke: 'rgb(59, 130, 246)', fill: 'rgba(59, 130, 246, 0.2)' };\n case 'assessing':\n return { stroke: 'rgb(239, 68, 68)', fill: 'rgba(239, 68, 68, 0.2)' };\n case 'commenting':\n return { stroke: 'rgb(255, 255, 255)', fill: 'rgba(255, 255, 255, 0.2)' };\n default:\n return { stroke: 'rgb(156, 163, 175)', fill: 'rgba(156, 163, 175, 0.2)' };\n }\n}\n\ninterface PdfAnnotationCanvasProps {\n pdfUrl: string;\n /** The '@id' of the annotated resource — stamped as `source` on mark:requested (multi-viewer routing). */\n resourceUri: string;\n existingAnnotations?: Annotation[];\n drawingMode: DrawingMode;\n selectedMotivation?: SelectionMotivation | null;\n session?: SemiontSession | null | undefined;\n hoveredAnnotationId?: string | null;\n selectedAnnotationId?: string | null;\n hoverDelayMs?: number;\n}\n\n/**\n * PDF annotation canvas with page navigation and rectangle drawing\n *\n * @emits browse:click - Annotation clicked on PDF. Payload: { annotationId: string, motivation: Motivation }\n * @emits mark:requested - New annotation drawn on PDF. Payload: { selector: FragmentSelector, motivation: SelectionMotivation }\n * @emits beckon:hover - Annotation hovered or unhovered. Payload: { annotationId: string | null }\n */\nexport function PdfAnnotationCanvas({\n pdfUrl,\n resourceUri,\n existingAnnotations = [],\n drawingMode,\n selectedMotivation,\n session,\n hoveredAnnotationId,\n selectedAnnotationId,\n hoverDelayMs = 150\n}: PdfAnnotationCanvasProps) {\n // PDF state\n const [pdfDoc, setPdfDoc] = useState<PDFDocumentProxy | null>(null);\n const [numPages, setNumPages] = useState<number>(0);\n const [pageNumber, setPageNumber] = useState(1);\n const [pageImageUrl, setPageImageUrl] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n const [pageDimensions, setPageDimensions] = useState<{ width: number; height: number } | null>(null);\n const [displayDimensions, setDisplayDimensions] = useState<{ width: number; height: number } | null>(null);\n const [scale] = useState(1.5); // Fixed scale for better quality\n\n // Drawing state\n const [isDrawing, setIsDrawing] = useState(false);\n const [selection, setSelection] = useState<CanvasRectangle | null>(null);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const imageRef = useRef<HTMLImageElement>(null);\n\n // Load PDF document on mount\n useEffect(() => {\n let cancelled = false;\n\n async function loadPdf() {\n try {\n setIsLoading(true);\n setError(null);\n\n const doc = await loadPdfDocument(pdfUrl);\n\n if (cancelled) return;\n\n setPdfDoc(doc);\n setNumPages(doc.numPages);\n setIsLoading(false);\n } catch (err) {\n if (cancelled) return;\n\n console.error('Error loading PDF:', err);\n setError('Failed to load PDF');\n setIsLoading(false);\n }\n }\n\n loadPdf();\n\n return () => {\n cancelled = true;\n };\n }, [pdfUrl]);\n\n // Load current page when page number changes\n useEffect(() => {\n if (!pdfDoc) return;\n\n let cancelled = false;\n const doc = pdfDoc;\n\n async function loadPage() {\n try {\n const page = await doc.getPage(pageNumber);\n\n if (cancelled) return;\n\n // Get page dimensions (at scale 1.0)\n const viewport = page.getViewport({ scale: 1.0 });\n setPageDimensions({\n width: viewport.width,\n height: viewport.height\n });\n\n // Render page to image\n const { dataUrl } = await renderPdfPageToDataUrl(page, scale);\n\n if (cancelled) return;\n\n setPageImageUrl(dataUrl);\n } catch (err) {\n if (cancelled) return;\n\n console.error('Error loading page:', err);\n setError('Failed to load page');\n }\n }\n\n loadPage();\n\n return () => {\n cancelled = true;\n };\n }, [pdfDoc, pageNumber, scale]);\n\n // Update display dimensions on resize\n useEffect(() => {\n const updateDisplayDimensions = () => {\n if (imageRef.current) {\n setDisplayDimensions({\n width: imageRef.current.clientWidth,\n height: imageRef.current.clientHeight\n });\n }\n };\n\n updateDisplayDimensions();\n\n // Use ResizeObserver to detect image element size changes\n // This catches: sidebar open/close, window resize, font size changes, etc.\n let resizeObserver: ResizeObserver | null = null;\n\n try {\n resizeObserver = new ResizeObserver(updateDisplayDimensions);\n if (imageRef.current) {\n resizeObserver.observe(imageRef.current);\n }\n } catch (error) {\n // Fallback for browsers without ResizeObserver support\n console.warn('ResizeObserver not supported, falling back to window resize listener');\n window.addEventListener('resize', updateDisplayDimensions);\n }\n\n return () => {\n if (resizeObserver) {\n resizeObserver.disconnect();\n } else {\n window.removeEventListener('resize', updateDisplayDimensions);\n }\n };\n }, [pageImageUrl]);\n\n // Mouse event handlers for drawing\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (!drawingMode) return;\n if (!imageRef.current) return;\n\n const rect = imageRef.current.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n\n // Clear any previous selection when starting new drawing\n setIsDrawing(true);\n setSelection({\n startX: x,\n startY: y,\n endX: x,\n endY: y\n });\n }, [drawingMode]);\n\n const handleMouseMove = useCallback((e: React.MouseEvent) => {\n if (!isDrawing || !selection || !imageRef.current) return;\n\n const rect = imageRef.current.getBoundingClientRect();\n\n setSelection({\n ...selection,\n endX: e.clientX - rect.left,\n endY: e.clientY - rect.top\n });\n }, [isDrawing, selection]);\n\n const handleMouseUp = useCallback(() => {\n if (!isDrawing || !selection || !pageDimensions || !displayDimensions || !session) {\n setIsDrawing(false);\n setSelection(null);\n return;\n }\n\n // Calculate drag distance\n const dragDistance = Math.sqrt(\n Math.pow(selection.endX - selection.startX, 2) +\n Math.pow(selection.endY - selection.startY, 2)\n );\n\n // Minimum drag threshold in pixels (10px)\n const MIN_DRAG_DISTANCE = 10;\n\n if (dragDistance < MIN_DRAG_DISTANCE) {\n // This was a click, not a drag - check if we clicked an existing annotation\n if (existingAnnotations.length > 0) {\n const clickedAnnotation = pageAnnotations.find(ann => {\n const fragmentSel = getFragmentSelector(ann.target);\n if (!fragmentSel) return false;\n\n const pdfCoord = parseFragmentSelector(fragmentSel.value);\n if (!pdfCoord) return false;\n\n const rect = pdfToCanvasCoordinates(pdfCoord, pageDimensions.height, 1.0);\n\n // Scale to display coordinates\n const scaleX = displayDimensions.width / pageDimensions.width;\n const scaleY = displayDimensions.height / pageDimensions.height;\n\n const displayX = rect.x * scaleX;\n const displayY = rect.y * scaleY;\n const displayWidth = rect.width * scaleX;\n const displayHeight = rect.height * scaleY;\n\n return (\n selection.endX >= displayX &&\n selection.endX <= displayX + displayWidth &&\n selection.endY >= displayY &&\n selection.endY <= displayY + displayHeight\n );\n });\n\n if (clickedAnnotation) {\n session?.client.browse.click(clickedAnnotation.id, clickedAnnotation.motivation);\n setIsDrawing(false);\n setSelection(null);\n return;\n }\n }\n\n // Click on empty space - do nothing\n setIsDrawing(false);\n setSelection(null);\n return;\n }\n\n // This was a drag - create new annotation\n // Scale selection from display coordinates to native page coordinates\n const scaleX = pageDimensions.width / displayDimensions.width;\n const scaleY = pageDimensions.height / displayDimensions.height;\n\n const nativeSelection: CanvasRectangle = {\n startX: selection.startX * scaleX,\n startY: selection.startY * scaleY,\n endX: selection.endX * scaleX,\n endY: selection.endY * scaleY\n };\n\n // Convert canvas coordinates to PDF coordinates\n const pdfCoord = canvasToPdfCoordinates(\n nativeSelection,\n pageNumber,\n pageDimensions.width,\n pageDimensions.height,\n 1.0 // Use scale 1.0 since we already scaled to native coords\n );\n\n // Create FragmentSelector\n const fragmentSelector = createFragmentSelector(pdfCoord);\n\n // Emit annotation:requested event with FragmentSelector\n if (selectedMotivation) {\n session.client.mark.request(\n toResourceId(resourceUri),\n {\n type: 'FragmentSelector',\n conformsTo: 'http://tools.ietf.org/rfc/rfc3778',\n value: fragmentSelector,\n },\n selectedMotivation,\n );\n }\n\n // Keep drawing state active to show preview until annotation is persisted\n // The parent component should clear this by changing drawingMode after save\n setIsDrawing(false);\n // Note: We keep selection so the preview remains visible\n // It will be cleared when drawingMode changes or user starts new selection\n }, [isDrawing, selection, pageNumber, pageDimensions, displayDimensions, selectedMotivation, existingAnnotations]);\n\n // Helper to get FragmentSelector from annotation target\n const getFragmentSelector = (target: Annotation['target']) => {\n const selector = getTargetSelector(target);\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n\n const found = selectors.find(s => s.type === 'FragmentSelector');\n if (!found || found.type !== 'FragmentSelector') return null;\n return found as { type: 'FragmentSelector'; value: string; conformsTo?: string };\n };\n\n // Filter annotations for current page\n const pageAnnotations = existingAnnotations.filter(ann => {\n const fragmentSel = getFragmentSelector(ann.target);\n if (!fragmentSel) return false;\n const page = getPageFromFragment(fragmentSel.value);\n return page === pageNumber;\n });\n\n // Hover handlers with currentHover guard and dwell delay\n const { handleMouseEnter, handleMouseLeave } = useMemo(\n () => createHoverHandlers((id) => session?.client.beckon.hover(id), hoverDelayMs),\n [session, hoverDelayMs]\n );\n\n // Calculate motivation color\n const { stroke, fill } = getMotivationColor(selectedMotivation ?? null);\n\n if (error) {\n return <div className=\"semiont-pdf-annotation-canvas__error\">{error}</div>;\n }\n\n return (\n <div className=\"semiont-pdf-annotation-canvas\">\n {isLoading && <div className=\"semiont-pdf-annotation-canvas__loading\">Loading PDF...</div>}\n\n <div\n ref={containerRef}\n className=\"semiont-pdf-annotation-canvas__container\"\n style={{ display: isLoading ? 'none' : undefined }}\n onMouseDown={handleMouseDown}\n onMouseMove={handleMouseMove}\n onMouseUp={handleMouseUp}\n onMouseLeave={() => {\n if (isDrawing) {\n setIsDrawing(false);\n setSelection(null);\n }\n }}\n data-drawing-mode={drawingMode || 'none'}\n >\n {/* PDF page rendered as image */}\n {pageImageUrl && (\n <img\n ref={imageRef}\n src={pageImageUrl}\n alt={`PDF page ${pageNumber}`}\n className=\"semiont-pdf-annotation-canvas__image\"\n draggable={false}\n style={{ pointerEvents: 'none' }}\n onLoad={() => {\n // Use double RAF to ensure layout is complete even in onLoad\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (imageRef.current) {\n setDisplayDimensions({\n width: imageRef.current.clientWidth,\n height: imageRef.current.clientHeight\n });\n }\n });\n });\n }}\n />\n )}\n\n {/* SVG overlay for annotations */}\n {displayDimensions && pageDimensions && (\n <div className=\"semiont-pdf-annotation-canvas__overlay-container\">\n <div className=\"semiont-pdf-annotation-canvas__overlay\">\n <svg\n className=\"semiont-pdf-annotation-canvas__svg\"\n width={displayDimensions.width}\n height={displayDimensions.height}\n >\n {/* Render existing annotations for this page */}\n {pageAnnotations.map(ann => {\n const fragmentSel = getFragmentSelector(ann.target);\n if (!fragmentSel) return null;\n\n const pdfCoord = parseFragmentSelector(fragmentSel.value);\n if (!pdfCoord) return null;\n\n const rect = pdfToCanvasCoordinates(pdfCoord, pageDimensions.height, 1.0);\n\n // Scale to display coordinates\n const scaleX = displayDimensions.width / pageDimensions.width;\n const scaleY = displayDimensions.height / pageDimensions.height;\n\n const isHovered = ann.id === hoveredAnnotationId;\n const isSelected = ann.id === selectedAnnotationId;\n\n // Get color for this annotation's motivation (not the selected motivation)\n const annMotivation = ann.motivation as SelectionMotivation | null;\n const { stroke: annStroke, fill: annFill } = getMotivationColor(annMotivation);\n\n return (\n <rect\n key={ann.id}\n x={rect.x * scaleX}\n y={rect.y * scaleY}\n width={rect.width * scaleX}\n height={rect.height * scaleY}\n stroke={annStroke}\n strokeWidth={isSelected ? 4 : isHovered ? 3 : 2}\n fill={annFill}\n style={{\n pointerEvents: 'auto',\n cursor: 'pointer',\n opacity: isSelected ? 1 : isHovered ? 0.9 : 0.7\n }}\n onClick={() => session?.client.browse.click(ann.id, ann.motivation)}\n onMouseEnter={() => handleMouseEnter(ann.id)}\n onMouseLeave={handleMouseLeave}\n />\n );\n })}\n\n {/* Render current selection while drawing or awaiting save */}\n {selection && (() => {\n const rectX = Math.min(selection.startX, selection.endX);\n const rectY = Math.min(selection.startY, selection.endY);\n const rectWidth = Math.abs(selection.endX - selection.startX);\n const rectHeight = Math.abs(selection.endY - selection.startY);\n\n // PDF only supports rectangle shapes (FragmentSelector with viewrect)\n // Circle/polygon are disabled in the UI for PDF media types\n return (\n <rect\n x={rectX}\n y={rectY}\n width={rectWidth}\n height={rectHeight}\n stroke={stroke}\n strokeWidth={2}\n strokeDasharray=\"5,5\"\n fill={fill}\n pointerEvents=\"none\"\n />\n );\n })()}\n </svg>\n </div>\n </div>\n )}\n </div>\n\n {/* Page navigation controls */}\n {numPages > 0 && (\n <div className=\"semiont-pdf-annotation-canvas__controls\">\n <button\n disabled={pageNumber <= 1}\n onClick={() => setPageNumber(pageNumber - 1)}\n className=\"semiont-pdf-annotation-canvas__button\"\n >\n Previous\n </button>\n <span className=\"semiont-pdf-annotation-canvas__page-info\">\n Page {pageNumber} of {numPages}\n </span>\n <button\n disabled={pageNumber >= numPages}\n onClick={() => setPageNumber(pageNumber + 1)}\n className=\"semiont-pdf-annotation-canvas__button\"\n >\n Next\n </button>\n </div>\n )}\n </div>\n );\n}\n","/**\n * PDF Canvas Coordinate Transforms\n *\n * Converts between canvas space (pixels, top-left origin, Y increases downward)\n * and PDF space (points, bottom-left origin, Y increases upward) — the Y-flip and\n * scale. UI-only: the server has no canvas.\n *\n * `PdfCoordinate` and the viewrect FragmentSelector codec live in `@semiont/core`.\n *\n * Based on RFC 3778 PDF Fragment Identifiers:\n * https://tools.ietf.org/html/rfc3778\n */\n\nimport type { PdfCoordinate } from '@semiont/core';\n\nexport interface Rectangle {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface CanvasRectangle {\n startX: number;\n startY: number;\n endX: number;\n endY: number;\n}\n\n/**\n * Convert canvas coordinates to PDF coordinates\n *\n * Canvas: Origin at top-left, Y increases downward\n * PDF: Origin at bottom-left, Y increases upward\n *\n * @param canvasRect - Rectangle in canvas pixel coordinates\n * @param page - PDF page number (1-indexed)\n * @param pageWidth - PDF page width in points\n * @param pageHeight - PDF page height in points\n * @param scale - Current canvas scale factor\n */\nexport function canvasToPdfCoordinates(\n canvasRect: CanvasRectangle,\n page: number,\n _pageWidth: number,\n pageHeight: number,\n scale: number = 1\n): PdfCoordinate {\n // Normalize rectangle (handle drag in any direction)\n const x1 = Math.min(canvasRect.startX, canvasRect.endX);\n const y1 = Math.min(canvasRect.startY, canvasRect.endY);\n const x2 = Math.max(canvasRect.startX, canvasRect.endX);\n const y2 = Math.max(canvasRect.startY, canvasRect.endY);\n\n // Convert from canvas pixels to PDF points\n const pdfX = x1 / scale;\n const pdfWidth = (x2 - x1) / scale;\n\n // Flip Y coordinate (canvas top-left to PDF bottom-left)\n const pdfY = pageHeight - (y2 / scale);\n const pdfHeight = (y2 - y1) / scale;\n\n return {\n page,\n x: Math.round(pdfX),\n y: Math.round(pdfY),\n width: Math.round(pdfWidth),\n height: Math.round(pdfHeight)\n };\n}\n\n/**\n * Convert PDF coordinates to canvas coordinates\n *\n * @param pdfCoord - Coordinates in PDF space\n * @param pageHeight - PDF page height in points\n * @param scale - Current canvas scale factor\n */\nexport function pdfToCanvasCoordinates(\n pdfCoord: PdfCoordinate,\n pageHeight: number,\n scale: number = 1\n): Rectangle {\n // Convert from PDF points to canvas pixels\n const canvasX = pdfCoord.x * scale;\n const canvasWidth = pdfCoord.width * scale;\n\n // Flip Y coordinate (PDF bottom-left to canvas top-left)\n const canvasY = (pageHeight - pdfCoord.y - pdfCoord.height) * scale;\n const canvasHeight = pdfCoord.height * scale;\n\n return {\n x: canvasX,\n y: canvasY,\n width: canvasWidth,\n height: canvasHeight\n };\n}\n"],"mappings":";;;;;;;;;AAEA,SAAgB,QAAQ,UAAU,aAAa,WAAW,eAAe;AAEzE,SAAS,cAAc,oBAAoB;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAAgD;;;AC8BlD,SAAS,uBACd,YACA,MACA,YACA,YACA,QAAgB,GACD;AAEf,QAAM,KAAK,KAAK,IAAI,WAAW,QAAQ,WAAW,IAAI;AACtD,QAAM,KAAK,KAAK,IAAI,WAAW,QAAQ,WAAW,IAAI;AACtD,QAAM,KAAK,KAAK,IAAI,WAAW,QAAQ,WAAW,IAAI;AACtD,QAAM,KAAK,KAAK,IAAI,WAAW,QAAQ,WAAW,IAAI;AAGtD,QAAM,OAAO,KAAK;AAClB,QAAM,YAAY,KAAK,MAAM;AAG7B,QAAM,OAAO,aAAc,KAAK;AAChC,QAAM,aAAa,KAAK,MAAM;AAE9B,SAAO;AAAA,IACL;AAAA,IACA,GAAG,KAAK,MAAM,IAAI;AAAA,IAClB,GAAG,KAAK,MAAM,IAAI;AAAA,IAClB,OAAO,KAAK,MAAM,QAAQ;AAAA,IAC1B,QAAQ,KAAK,MAAM,SAAS;AAAA,EAC9B;AACF;AASO,SAAS,uBACd,UACA,YACA,QAAgB,GACL;AAEX,QAAM,UAAU,SAAS,IAAI;AAC7B,QAAM,cAAc,SAAS,QAAQ;AAGrC,QAAM,WAAW,aAAa,SAAS,IAAI,SAAS,UAAU;AAC9D,QAAM,eAAe,SAAS,SAAS;AAEvC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;;;ADkRW,cAmDG,YAnDH;AArVX,SAAS,mBAAmB,YAA0E;AACpG,MAAI,CAAC,YAAY;AACf,WAAO,EAAE,QAAQ,s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AAA;AAAA;AAAA,UACL,GACF,GACF;AAAA;AAAA;AAAA,IAEJ;AAAA,IAGC,WAAW,KACV,qBAAC,SAAI,WAAU,2CACb;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,UAAU,cAAc;AAAA,UACxB,SAAS,MAAM,cAAc,aAAa,CAAC;AAAA,UAC3C,WAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,MACA,qBAAC,UAAK,WAAU,4CAA2C;AAAA;AAAA,QACnD;AAAA,QAAW;AAAA,QAAK;AAAA,SACxB;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,UAAU,cAAc;AAAA,UACxB,SAAS,MAAM,cAAc,aAAa,CAAC;AAAA,UAC3C,WAAU;AAAA,UACX;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KAEJ;AAEJ;","names":["error","pdfCoord","scaleX","scaleY"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/browser-pdfjs.ts"],"sourcesContent":["/**\n * Browser PDF.js — bundled from the npm `pdfjs-dist` (v6) package, loaded\n * lazily.\n *\n * pdf.js (the ~300 kB display layer) is pulled in via a dynamic `import()` the\n * first time a PDF is actually opened, so it is code-split out of the main app\n * bundle — restoring the lazy-load behaviour the old CDN loader had. Only the\n * pdf.js *types* are imported statically (erased at build time, zero runtime\n * cost).\n *\n * The worker can't be resolved inside this tsup-built library (Vite's `?url`\n * lives in the app), so the host hands us the worker URL via `setPdfWorkerSrc`\n * once at startup; it is applied to `GlobalWorkerOptions` when pdf.js loads.\n * See `apps/frontend/src/main.tsx`.\n */\nimport type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist';\n\nexport type { PDFDocumentProxy };\n\nlet workerSrc: string | undefined;\n\n/**\n * Supply the (Vite-resolved) pdf.js worker URL. Call once at app startup,\n * before any PDF is opened.\n */\nexport function setPdfWorkerSrc(src: string): void {\n workerSrc = src;\n}\n\nlet pdfjsPromise: Promise<typeof import('pdfjs-dist')> | undefined;\n\n/** Lazy-load pdf.js once, applying the worker URL on first load. */\nasync function getPdfjs(): Promise<typeof import('pdfjs-dist')> {\n if (!pdfjsPromise) {\n pdfjsPromise = import('pdfjs-dist').then((pdfjsLib) => {\n if (workerSrc) {\n pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;\n }\n return pdfjsLib;\n });\n }\n return pdfjsPromise;\n}\n\n/**\n * Load a PDF document from a URL. The URL must carry auth (e.g. `?token=…`);\n * pdf.js streams the document directly.\n */\nexport async function loadPdfDocument(url: string): Promise<PDFDocumentProxy> {\n const pdfjsLib = await getPdfjs();\n return pdfjsLib.getDocument({ url }).promise;\n}\n\n/**\n * Render a PDF page to a PNG data URL. The `page` is already loaded (its owning\n * document came from `loadPdfDocument`), so no pdf.js import is needed here.\n */\nexport async function renderPdfPageToDataUrl(\n page: PDFPageProxy,\n scale = 1.0,\n): Promise<{ dataUrl: string; width: number; height: number }> {\n const viewport = page.getViewport({ scale });\n\n const canvas = document.createElement('canvas');\n canvas.width = viewport.width;\n canvas.height = viewport.height;\n\n // pdf.js 6 requires the `canvas` parameter; `canvasContext` is deprecated.\n await page.render({ canvas, viewport }).promise;\n\n return {\n dataUrl: canvas.toDataURL('image/png'),\n width: viewport.width,\n height: viewport.height,\n };\n}\n"],"mappings":";;;AAmBA,IAAI;AAMG,SAAS,gBAAgB,KAAmB;AACjD,cAAY;AACd;AAEA,IAAI;AAGJ,eAAe,WAAiD;AAC9D,MAAI,CAAC,cAAc;AACjB,mBAAe,OAAO,YAAY,EAAE,KAAK,CAAC,aAAa;AACrD,UAAI,WAAW;AACb,iBAAS,oBAAoB,YAAY;AAAA,MAC3C;AACA,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAMA,eAAsB,gBAAgB,KAAwC;AAC5E,QAAM,WAAW,MAAM,SAAS;AAChC,SAAO,SAAS,YAAY,EAAE,IAAI,CAAC,EAAE;AACvC;AAMA,eAAsB,uBACpB,MACA,QAAQ,GACqD;AAC7D,QAAM,WAAW,KAAK,YAAY,EAAE,MAAM,CAAC;AAE3C,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,QAAQ,SAAS;AACxB,SAAO,SAAS,SAAS;AAGzB,QAAM,KAAK,OAAO,EAAE,QAAQ,SAAS,CAAC,EAAE;AAExC,SAAO;AAAA,IACL,SAAS,OAAO,UAAU,WAAW;AAAA,IACrC,OAAO,SAAS;AAAA,IAChB,QAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}