web-annotation-renderer 0.6.3 → 0.7.0

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 (112) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +62 -61
  5. package/dist/index.js.map +1 -1
  6. package/dist/index10.cjs +1 -1
  7. package/dist/index10.cjs.map +1 -1
  8. package/dist/index10.js +160 -13
  9. package/dist/index10.js.map +1 -1
  10. package/dist/index11.cjs +1 -1
  11. package/dist/index11.cjs.map +1 -1
  12. package/dist/index11.js +13 -50
  13. package/dist/index11.js.map +1 -1
  14. package/dist/index12.cjs +1 -1
  15. package/dist/index12.cjs.map +1 -1
  16. package/dist/index12.js +48 -155
  17. package/dist/index12.js.map +1 -1
  18. package/dist/index13.cjs +1 -1
  19. package/dist/index13.cjs.map +1 -1
  20. package/dist/index13.js +150 -34
  21. package/dist/index13.js.map +1 -1
  22. package/dist/index14.cjs +1 -1
  23. package/dist/index14.cjs.map +1 -1
  24. package/dist/index14.js +32 -65
  25. package/dist/index14.js.map +1 -1
  26. package/dist/index15.cjs +1 -1
  27. package/dist/index15.cjs.map +1 -1
  28. package/dist/index15.js +66 -33
  29. package/dist/index15.js.map +1 -1
  30. package/dist/index16.cjs +1 -1
  31. package/dist/index16.cjs.map +1 -1
  32. package/dist/index16.js +35 -77
  33. package/dist/index16.js.map +1 -1
  34. package/dist/index17.cjs +1 -1
  35. package/dist/index17.cjs.map +1 -1
  36. package/dist/index17.js +53 -28
  37. package/dist/index17.js.map +1 -1
  38. package/dist/index18.cjs +1 -1
  39. package/dist/index18.cjs.map +1 -1
  40. package/dist/index18.js +28 -22
  41. package/dist/index18.js.map +1 -1
  42. package/dist/index19.cjs +1 -1
  43. package/dist/index19.cjs.map +1 -1
  44. package/dist/index19.js +22 -117
  45. package/dist/index19.js.map +1 -1
  46. package/dist/index2.cjs +1 -1
  47. package/dist/index2.cjs.map +1 -1
  48. package/dist/index2.js +94 -98
  49. package/dist/index2.js.map +1 -1
  50. package/dist/index20.cjs +1 -1
  51. package/dist/index20.cjs.map +1 -1
  52. package/dist/index20.js +137 -100
  53. package/dist/index20.js.map +1 -1
  54. package/dist/index21.cjs +1 -1
  55. package/dist/index21.cjs.map +1 -1
  56. package/dist/index21.js +34 -76
  57. package/dist/index21.js.map +1 -1
  58. package/dist/index22.cjs +1 -1
  59. package/dist/index22.cjs.map +1 -1
  60. package/dist/index22.js +35 -139
  61. package/dist/index22.js.map +1 -1
  62. package/dist/index23.cjs +1 -1
  63. package/dist/index23.cjs.map +1 -1
  64. package/dist/index23.js +37 -37
  65. package/dist/index23.js.map +1 -1
  66. package/dist/index24.cjs +1 -1
  67. package/dist/index24.cjs.map +1 -1
  68. package/dist/index24.js +69 -37
  69. package/dist/index24.js.map +1 -1
  70. package/dist/index25.cjs +1 -1
  71. package/dist/index25.cjs.map +1 -1
  72. package/dist/index25.js +40 -38
  73. package/dist/index25.js.map +1 -1
  74. package/dist/index26.cjs +1 -1
  75. package/dist/index26.cjs.map +1 -1
  76. package/dist/index26.js +4 -39
  77. package/dist/index26.js.map +1 -1
  78. package/dist/index27.cjs +1 -1
  79. package/dist/index27.js +4 -4
  80. package/dist/index28.cjs +1 -1
  81. package/dist/index28.cjs.map +1 -1
  82. package/dist/index28.js +71 -5
  83. package/dist/index28.js.map +1 -1
  84. package/dist/index29.cjs +1 -1
  85. package/dist/index29.cjs.map +1 -1
  86. package/dist/index29.js +24 -69
  87. package/dist/index29.js.map +1 -1
  88. package/dist/index3.cjs +1 -1
  89. package/dist/index3.cjs.map +1 -1
  90. package/dist/index3.js +31 -31
  91. package/dist/index3.js.map +1 -1
  92. package/dist/index5.cjs +1 -1
  93. package/dist/index5.cjs.map +1 -1
  94. package/dist/index5.js +237 -190
  95. package/dist/index5.js.map +1 -1
  96. package/dist/index6.cjs +1 -1
  97. package/dist/index6.cjs.map +1 -1
  98. package/dist/index6.js +37 -19
  99. package/dist/index6.js.map +1 -1
  100. package/dist/index7.cjs +1 -1
  101. package/dist/index7.cjs.map +1 -1
  102. package/dist/index7.js +11 -17
  103. package/dist/index7.js.map +1 -1
  104. package/dist/index8.cjs +1 -1
  105. package/dist/index8.cjs.map +1 -1
  106. package/dist/index8.js +16 -125
  107. package/dist/index8.js.map +1 -1
  108. package/dist/index9.cjs +1 -1
  109. package/dist/index9.cjs.map +1 -1
  110. package/dist/index9.js +118 -201
  111. package/dist/index9.js.map +1 -1
  112. package/package.json +6 -3
@@ -1 +1 @@
1
- {"version":3,"file":"index13.cjs","sources":["../src/converters/highlight.js"],"sourcesContent":["/**\n * Highlight Converter - Converts highlight annotations to stroke commands\n *\n * Transforms rectangular quads into horizontal stroke paths that can be\n * rendered progressively on canvas with hand-drawn highlighter style.\n *\n * @module converters/highlight\n */\n\nimport { roughLine, hashSeed } from '../rough/roughPathExtractor.js';\n\nconst SCALE = 1000;\n\n/**\n * Converts a highlight annotation to stroke commands\n *\n * Each quad in the annotation becomes a horizontal stroke at the\n * vertical center of the quad. Multiple quads are staggered in timing.\n * Uses RoughJS for hand-drawn highlighter style.\n *\n * @param {Object} annotation - Highlight annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {Array<{x: number, y: number, w: number, h: number}>} annotation.quads - Array of quads\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} style.color - Stroke color\n * @param {number} style.width - Stroke width in pixels\n * @param {string} [style.lineCap='butt'] - Line cap style\n * @param {number} [style.roughness=0.5] - Hand-drawn roughness (lower for highlighter)\n * @param {number} [style.bowing=0.5] - Line curvature\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function highlightToStrokes(annotation, style) {\n const { id, start, end, quads } = annotation;\n\n if (!quads || quads.length === 0) {\n return [];\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const quadCount = quads.length;\n const quadDuration = totalDuration / quadCount;\n\n const roughness = style.roughness ?? 0.5;\n const bowing = style.bowing ?? 0.5;\n const curveFitting = style.curveFitting ?? 0.95;\n const curveStepCount = style.curveStepCount ?? 9;\n const maxRandomnessOffset = style.maxRandomnessOffset ?? 2;\n const disableMultiStroke = style.disableMultiStroke ?? false;\n\n for (let i = 0; i < quads.length; i++) {\n const quad = quads[i];\n const { x, y, w, h } = quad;\n\n const yCenter = y + h / 2;\n\n const roughPoints = roughLine(\n x * SCALE,\n yCenter * SCALE,\n (x + w) * SCALE,\n yCenter * SCALE,\n {\n roughness,\n bowing,\n seed: hashSeed(`${id}-${i}`),\n curveFitting,\n curveStepCount,\n maxRandomnessOffset,\n disableMultiStroke\n }\n );\n\n const points = roughPoints.map(([px, py]) => [px / SCALE, py / SCALE]);\n\n const quadStart = start + i * quadDuration;\n const quadEnd = quadStart + quadDuration;\n\n strokes.push({\n id: `${id}-${i}`,\n points,\n start: quadStart,\n end: quadEnd,\n color: style.color || 'rgba(255, 255, 0, 0.3)',\n width: style.width || 24,\n lineCap: style.lineCap || 'butt'\n });\n }\n\n return strokes;\n}\n\nexport default highlightToStrokes;\n"],"names":["SCALE","highlightToStrokes","annotation","style","id","start","end","quads","strokes","totalDuration","quadCount","quadDuration","roughness","bowing","curveFitting","curveStepCount","maxRandomnessOffset","disableMultiStroke","i","quad","x","y","w","h","yCenter","points","roughLine","hashSeed","px","py","quadStart","quadEnd"],"mappings":"6IAWMA,EAAQ,IAuBP,SAASC,EAAmBC,EAAYC,EAAO,CACpD,KAAM,CAAE,GAAAC,EAAI,MAAAC,EAAO,IAAAC,EAAK,MAAAC,CAAK,EAAKL,EAElC,GAAI,CAACK,GAASA,EAAM,SAAW,EAC7B,MAAO,CAAA,EAGT,MAAMC,EAAU,CAAA,EACVC,EAAgBH,EAAMD,EACtBK,EAAYH,EAAM,OAClBI,EAAeF,EAAgBC,EAE/BE,EAAYT,EAAM,WAAa,GAC/BU,EAASV,EAAM,QAAU,GACzBW,EAAeX,EAAM,cAAgB,IACrCY,EAAiBZ,EAAM,gBAAkB,EACzCa,EAAsBb,EAAM,qBAAuB,EACnDc,EAAqBd,EAAM,oBAAsB,GAEvD,QAASe,EAAI,EAAGA,EAAIX,EAAM,OAAQW,IAAK,CACrC,MAAMC,EAAOZ,EAAMW,CAAC,EACd,CAAE,EAAAE,EAAG,EAAAC,EAAG,EAAAC,EAAG,EAAAC,CAAC,EAAKJ,EAEjBK,EAAUH,EAAIE,EAAI,EAkBlBE,EAhBcC,EAAAA,UAClBN,EAAIpB,EACJwB,EAAUxB,GACToB,EAAIE,GAAKtB,EACVwB,EAAUxB,EACV,CACE,UAAAY,EACA,OAAAC,EACA,KAAMc,EAAAA,SAAS,GAAGvB,CAAE,IAAIc,CAAC,EAAE,EAC3B,aAAAJ,EACA,eAAAC,EACA,oBAAAC,EACA,mBAAAC,CACR,CACA,EAE+B,IAAI,CAAC,CAACW,EAAIC,CAAE,IAAM,CAACD,EAAK5B,EAAO6B,EAAK7B,CAAK,CAAC,EAE/D8B,EAAYzB,EAAQa,EAAIP,EACxBoB,EAAUD,EAAYnB,EAE5BH,EAAQ,KAAK,CACX,GAAI,GAAGJ,CAAE,IAAIc,CAAC,GACd,OAAAO,EACA,MAAOK,EACP,IAAKC,EACL,MAAO5B,EAAM,OAAS,yBACtB,MAAOA,EAAM,OAAS,GACtB,QAASA,EAAM,SAAW,MAChC,CAAK,CACH,CAEA,OAAOK,CACT"}
1
+ {"version":3,"file":"index13.cjs","sources":["../src/adapters/AnnotPdf.jsx"],"sourcesContent":["// ============================================================================\n// SECTION 1: IMPORTS\n// ============================================================================\n\nimport { useRef, useEffect, useCallback, useState } from 'react';\nimport { AnnotationRenderer } from '../core/AnnotationRenderer.js';\n\n// ============================================================================\n// SECTION 2: JSDOC DOCUMENTATION\n// ============================================================================\n\n/**\n * AnnotPdf - Declarative React component for PDF annotation rendering\n *\n * A React wrapper around the AnnotationRenderer core engine that provides\n * a declarative, props-based API for rendering PDF documents with\n * timeline-synchronized annotations.\n *\n * Features:\n * - Automatic lifecycle management (initialization and cleanup)\n * - Declarative prop-to-method synchronization\n * - PDF rendering with pdf.js\n * - Timeline-synchronized annotation display\n * - Support for highlight, text, and ink annotations\n * - Page navigation and zoom control\n *\n * @component\n * @example\n * // Basic usage\n * <AnnotPdf\n * pdfUrl=\"/document.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={[]}\n * currentTime={0}\n * />\n *\n * @example\n * // With audio synchronization (discrete mode - ~4fps)\n * const [currentTime, setCurrentTime] = useState(0);\n *\n * <div>\n * <AnnotPdf\n * pdfUrl=\"/lecture.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={annotations}\n * currentTime={currentTime}\n * onLoad={({ pageCount }) => console.log('Loaded:', pageCount)}\n * />\n * <audio\n * src=\"/lecture.mp3\"\n * onTimeUpdate={(e) => setCurrentTime(e.target.currentTime)}\n * controls\n * />\n * </div>\n *\n * @example\n * // With audio synchronization (continuous mode - 60fps, smoother)\n * const audioRef = useRef(null);\n *\n * <div>\n * <AnnotPdf\n * pdfUrl=\"/lecture.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={annotations}\n * audioRef={audioRef}\n * onLoad={({ pageCount }) => console.log('Loaded:', pageCount)}\n * />\n * <audio ref={audioRef} src=\"/lecture.mp3\" controls />\n * </div>\n *\n * @param {Object} props - Component props\n * @param {string} props.pdfUrl - PDF document URL (required)\n * @param {number} [props.page=1] - Current page number (1-indexed)\n * @param {number} [props.scale=1.5] - Zoom scale factor\n * @param {Array} [props.annotations=[]] - Array of annotation objects\n * @param {number} [props.currentTime=0] - Timeline position in seconds (discrete mode)\n * @param {React.RefObject<HTMLAudioElement>} [props.audioRef] - Audio element ref for continuous sync (60fps)\n * @param {Function} [props.onLoad] - Callback when PDF loads: ({pageCount}) => void\n * @param {Function} [props.onError] - Callback on error: (error) => void\n * @param {Function} [props.onPageChange] - Callback when page changes: (page) => void\n * @param {Object} [props.strokeConfig] - Stroke rendering configuration (setConfig format)\n * @param {number} [props.strokeConfig.roughness] - Global roughness for all types\n * @param {number} [props.strokeConfig.bowing] - Global bowing for all types\n * @param {Object} [props.strokeConfig.highlight] - Highlight-specific options\n * @param {Object} [props.strokeConfig.text] - Text-specific options\n * @param {Object} [props.strokeConfig.underline] - Underline-specific options\n * @param {Object} [props.strokeConfig.arrow] - Arrow-specific options\n * @param {Object} [props.strokeConfig.circle] - Circle-specific options\n * @param {string} [props.className] - CSS class for container div\n * @param {Object} [props.style] - Inline styles for container div\n * @param {Object} [props.canvasStyle] - Inline styles for canvas element\n * @returns {JSX.Element} PDF viewer component with annotation layers\n */\n\n// ============================================================================\n// SECTION 3: COMPONENT DEFINITION\n// ============================================================================\n\nfunction AnnotPdf({\n // Required props\n pdfUrl,\n\n // Optional props with defaults\n page = 1,\n scale = 1.5,\n annotations = [],\n currentTime = 0,\n\n // Continuous sync mode (use instead of currentTime for smoother animation)\n audioRef,\n\n // Stroke configuration\n strokeConfig,\n\n // Callbacks\n onLoad,\n onError,\n onPageChange,\n\n // Styling\n className,\n style,\n canvasStyle\n}) {\n\n // ==========================================================================\n // SECTION 4: REFS INITIALIZATION\n // ==========================================================================\n\n /**\n * Reference to the canvas element for PDF rendering\n * @type {React.RefObject<HTMLCanvasElement>}\n */\n const canvasRef = useRef(null);\n\n /**\n * Reference to the layer container div for annotation layers\n * @type {React.RefObject<HTMLDivElement>}\n */\n const layerContainerRef = useRef(null);\n\n /**\n * Reference to the AnnotationRenderer engine instance\n * Stored in ref to avoid triggering re-renders\n * @type {React.RefObject<AnnotationRenderer|null>}\n */\n const engineRef = useRef(null);\n\n /**\n * Reference to the render operation queue\n * Ensures sequential execution of async canvas operations\n * Prevents PDF.js race condition: \"Cannot use the same canvas during multiple render() operations\"\n * @type {React.RefObject<Promise<void>>}\n */\n const renderQueue = useRef(Promise.resolve());\n\n /**\n * State to track engine initialization\n * Used to trigger dependent effects after engine is ready\n */\n const [isEngineReady, setEngineReady] = useState(false);\n\n /**\n * Latest annotations prop, exposed via ref so the page-change effect can\n * read it without re-running whenever annotations change. AnnotationRenderer\n * v0.7.0 no longer applies annotations from setPage (R18) so the adapter\n * is responsible for re-binding them after a page transition.\n * @type {React.MutableRefObject<Array>}\n */\n const annotationsRef = useRef(annotations);\n useEffect(() => {\n annotationsRef.current = annotations;\n }, [annotations]);\n\n // ==========================================================================\n // SECTION 4.5: RENDER QUEUE HELPER\n // ==========================================================================\n\n /**\n * Queue a render operation to execute sequentially\n *\n * This helper ensures that async canvas operations (loadPDF, setPage, setScale)\n * execute one at a time, preventing concurrent access to the PDF.js canvas.\n * Uses Promise chaining to maintain operation order.\n *\n * @param {Function} operation - Async function returning a Promise\n * @returns {void}\n */\n const queueOperation = useCallback((operation) => {\n renderQueue.current = renderQueue.current\n .then(operation)\n .catch(error => {\n // Log errors but don't break the queue\n console.error('AnnotPdf: Queued operation failed:', error);\n });\n }, []);\n\n // ==========================================================================\n // SECTION 5: ENGINE INITIALIZATION AND CLEANUP\n // ==========================================================================\n\n /**\n * Initialize AnnotationRenderer on component mount\n * Cleanup on component unmount\n */\n useEffect(() => {\n // Guard: Wait for DOM elements to be ready\n if (!canvasRef.current || !layerContainerRef.current) {\n return;\n }\n\n // Initialize engine with stroke config if provided\n try {\n engineRef.current = new AnnotationRenderer({\n canvasElement: canvasRef.current,\n container: layerContainerRef.current,\n strokeConfig: strokeConfig\n });\n // Signal that engine is ready for dependent effects\n setEngineReady(true);\n } catch (error) {\n console.error('AnnotPdf: Failed to initialize renderer:', error);\n if (onError) {\n onError(error);\n }\n }\n\n // Cleanup on unmount\n return () => {\n setEngineReady(false);\n if (engineRef.current) {\n engineRef.current.destroy();\n engineRef.current = null;\n }\n };\n }, []); // Empty deps - run once on mount\n\n // ==========================================================================\n // SECTION 6: PDF LOADING SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Load PDF document when pdfUrl prop changes\n * Handles async operation with cancellation support\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid pdfUrl\n if (!isEngineReady || !pdfUrl) {\n return;\n }\n\n let cancelled = false;\n\n const loadPdf = async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.loadPDF(pdfUrl);\n\n // Check if component unmounted during async operation\n if (cancelled) return;\n\n // Check if load was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to load PDF:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n return;\n }\n\n // Call onLoad callback with pageCount from result\n if (onLoad) {\n onLoad({ pageCount: result.pageCount });\n }\n } catch (error) {\n if (cancelled) return;\n\n console.error('AnnotPdf: Failed to load PDF:', error);\n if (onError) {\n onError(error);\n }\n }\n };\n\n // Queue the PDF loading operation to prevent race conditions\n queueOperation(loadPdf);\n\n // Cleanup: Prevent state updates if component unmounts during load\n return () => {\n cancelled = true;\n };\n }, [pdfUrl, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 7: PAGE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync page prop to engine.setPage() method\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid page\n if (!isEngineReady || !page || typeof page !== 'number') {\n return;\n }\n\n // Queue the page change operation to prevent race conditions\n queueOperation(async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.setPage(page);\n\n // Check if page change was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to set page:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n return;\n }\n\n // R18: setPage no longer rebinds annotations — do it here using the\n // latest annotations snapshot from `annotationsRef`.\n engineRef.current.setAnnotations(annotationsRef.current || []);\n\n // Optional: Notify parent of successful page change\n if (onPageChange) {\n onPageChange(page);\n }\n } catch (error) {\n console.error('AnnotPdf: Failed to set page:', error);\n if (onError) {\n onError(error);\n }\n }\n });\n }, [page, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 8: SCALE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync scale prop to engine.setScale() method\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid scale\n if (!isEngineReady || !scale || typeof scale !== 'number') {\n return;\n }\n\n // Queue the scale change operation to prevent race conditions\n queueOperation(async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.setScale(scale);\n\n // Check if scale change was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to set scale:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n }\n } catch (error) {\n console.error('AnnotPdf: Failed to set scale:', error);\n if (onError) {\n onError(error);\n }\n }\n });\n }, [scale, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 9: ANNOTATIONS SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync annotations prop to engine.setAnnotations() method\n */\n useEffect(() => {\n // Guard: Wait for engine\n if (!isEngineReady || !engineRef.current) {\n return;\n }\n\n // Sync annotations to engine (default to empty array)\n try {\n engineRef.current.setAnnotations(annotations || []);\n } catch (error) {\n console.error('AnnotPdf: Failed to set annotations:', error);\n if (onError) {\n onError(error);\n }\n }\n }, [annotations, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10: TIMELINE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync currentTime prop to engine.setTime() method\n * Only used when audioRef is NOT provided (discrete mode)\n */\n useEffect(() => {\n // Skip if using continuous sync mode\n if (audioRef) {\n return;\n }\n\n // Guard: Wait for engine and valid currentTime\n if (!isEngineReady || !engineRef.current || currentTime === undefined || currentTime === null) {\n return;\n }\n\n // Sync timeline to engine\n try {\n engineRef.current.setTime(currentTime);\n } catch (error) {\n console.error('AnnotPdf: Failed to set time:', error);\n if (onError) {\n onError(error);\n }\n }\n }, [currentTime, audioRef, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10.1: CONTINUOUS SYNC MODE (audioRef)\n // ==========================================================================\n\n /**\n * Manage continuous sync mode when audioRef is provided\n *\n * Uses requestAnimationFrame for 60fps smooth animation instead of\n * discrete currentTime updates (~4fps from audio timeupdate events).\n */\n useEffect(() => {\n // Guard: Skip if not using continuous sync mode\n if (!audioRef?.current) {\n return;\n }\n\n // Guard: Wait for engine\n if (!isEngineReady || !engineRef.current) {\n return;\n }\n\n const audio = audioRef.current;\n /**\n * Start continuous sync when audio plays\n */\n const handlePlay = () => {\n if (!engineRef.current) return;\n engineRef.current.startContinuousSync(() => audio.currentTime);\n };\n\n /**\n * Stop continuous sync when audio pauses\n */\n const handlePause = () => {\n if (!engineRef.current) return;\n engineRef.current.stopContinuousSync();\n engineRef.current.setTime(audio.currentTime);\n };\n\n /**\n * Handle seeking - update time immediately\n */\n const handleSeeked = () => {\n if (!engineRef.current) return;\n engineRef.current.setTime(audio.currentTime);\n };\n\n // Add event listeners\n audio.addEventListener('play', handlePlay);\n audio.addEventListener('pause', handlePause);\n audio.addEventListener('ended', handlePause);\n audio.addEventListener('seeked', handleSeeked);\n\n // If audio is already playing, start sync immediately\n if (!audio.paused) {\n handlePlay();\n }\n\n // Cleanup on unmount or audioRef change\n return () => {\n audio.removeEventListener('play', handlePlay);\n audio.removeEventListener('pause', handlePause);\n audio.removeEventListener('ended', handlePause);\n audio.removeEventListener('seeked', handleSeeked);\n // Guard: engine may have been destroyed by initialization effect cleanup\n if (engineRef.current) {\n engineRef.current.stopContinuousSync();\n }\n };\n }, [audioRef, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10.5: STROKE CONFIG SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync strokeConfig prop changes to the engine at runtime. The engine is\n * created with the initial config in the mount effect, so the first\n * invocation here is a no-op against an identical reference; subsequent\n * runs (live preview, theme switches) call `updateStrokeConfig`.\n */\n useEffect(() => {\n if (!isEngineReady || !engineRef.current || !strokeConfig) {\n return;\n }\n const result = engineRef.current.updateStrokeConfig(strokeConfig);\n if (result && !result.success && onError) {\n onError(new Error(result.error));\n }\n }, [strokeConfig, isEngineReady]);\n\n // ==========================================================================\n // SECTION 11: STYLING DEFINITIONS\n // ==========================================================================\n\n /**\n * Default container styles\n * Merged with user-provided styles (user styles override defaults)\n */\n const defaultContainerStyle = {\n position: 'relative',\n display: 'inline-block',\n lineHeight: 0, // Remove extra space below canvas\n ...style // User styles override defaults\n };\n\n /**\n * Default layer container styles\n * Positions layer div absolutely over canvas\n */\n const defaultLayerStyle = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n pointerEvents: 'none', // Allow clicks to pass through to canvas\n overflow: 'hidden'\n };\n\n /**\n * Default canvas styles\n * Merged with user-provided canvasStyle\n */\n const defaultCanvasStyle = {\n display: 'block',\n ...canvasStyle // User styles override defaults\n };\n\n // ==========================================================================\n // SECTION 12: JSX RETURN\n // ==========================================================================\n\n return (\n <div className={className} style={defaultContainerStyle}>\n <canvas ref={canvasRef} style={defaultCanvasStyle} />\n <div ref={layerContainerRef} style={defaultLayerStyle} />\n </div>\n );\n}\n\n// ============================================================================\n// SECTION 13: EXPORT\n// ============================================================================\n\nexport default AnnotPdf;\n"],"names":["AnnotPdf","pdfUrl","page","scale","annotations","currentTime","audioRef","strokeConfig","onLoad","onError","onPageChange","className","style","canvasStyle","canvasRef","useRef","layerContainerRef","engineRef","renderQueue","isEngineReady","setEngineReady","useState","annotationsRef","useEffect","queueOperation","useCallback","operation","error","AnnotationRenderer","cancelled","result","audio","handlePlay","handlePause","handleSeeked","defaultContainerStyle","defaultLayerStyle","defaultCanvasStyle","jsxs","jsx"],"mappings":"8LAqGA,SAASA,EAAS,CAEhB,OAAAC,EAGA,KAAAC,EAAO,EACP,MAAAC,EAAQ,IACR,YAAAC,EAAc,CAAA,EACd,YAAAC,EAAc,EAGd,SAAAC,EAGA,aAAAC,EAGA,OAAAC,EACA,QAAAC,EACA,aAAAC,EAGA,UAAAC,EACA,MAAAC,EACA,YAAAC,CACF,EAAG,CAUD,MAAMC,EAAY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,CAAW,EAC9CF,EAAM,oBAAoB,SAAUG,CAAY,EAE5CjB,EAAU,SACZA,EAAU,QAAQ,mBAAA,CAEtB,CACF,EAAG,CAACX,EAAUa,CAAa,CAAC,EAY5BI,EAAAA,UAAU,IAAM,CACd,GAAI,CAACJ,GAAiB,CAACF,EAAU,SAAW,CAACV,EAC3C,OAEF,MAAMuB,EAASb,EAAU,QAAQ,mBAAmBV,CAAY,EAC5DuB,GAAU,CAACA,EAAO,SAAWrB,GAC/BA,EAAQ,IAAI,MAAMqB,EAAO,KAAK,CAAC,CAEnC,EAAG,CAACvB,EAAcY,CAAa,CAAC,EAUhC,MAAMgB,EAAwB,CAC5B,SAAU,WACV,QAAS,eACT,WAAY,EACZ,GAAGvB,CAAA,EAOCwB,EAAoB,CACxB,SAAU,WACV,IAAK,EACL,KAAM,EACN,MAAO,OACP,OAAQ,OACR,cAAe,OACf,SAAU,QAAA,EAONC,EAAqB,CACzB,QAAS,QACT,GAAGxB,CAAA,EAOL,OACEyB,EAAAA,KAAC,MAAA,CAAI,UAAA3B,EAAsB,MAAOwB,EAChC,SAAA,CAAAI,EAAAA,IAAC,SAAA,CAAO,IAAKzB,EAAW,MAAOuB,EAAoB,EACnDE,EAAAA,IAAC,MAAA,CAAI,IAAKvB,EAAmB,MAAOoB,CAAA,CAAmB,CAAA,EACzD,CAEJ"}
package/dist/index13.js CHANGED
@@ -1,40 +1,156 @@
1
- import { roughLine as L, hashSeed as M } from "./index29.js";
2
- const o = 1e3;
3
- function R(h, t) {
4
- const { id: e, start: r, end: g, quads: s } = h;
5
- if (!s || s.length === 0)
6
- return [];
7
- const i = [], f = g - r, p = s.length, u = f / p, l = t.roughness ?? 0.5, S = t.bowing ?? 0.5, m = t.curveFitting ?? 0.95, C = t.curveStepCount ?? 9, b = t.maxRandomnessOffset ?? 2, q = t.disableMultiStroke ?? !1;
8
- for (let n = 0; n < s.length; n++) {
9
- const w = s[n], { x: a, y: k, w: v, h: x } = w, c = k + x / 2, $ = L(
10
- a * o,
11
- c * o,
12
- (a + v) * o,
13
- c * o,
14
- {
15
- roughness: l,
16
- bowing: S,
17
- seed: M(`${e}-${n}`),
18
- curveFitting: m,
19
- curveStepCount: C,
20
- maxRandomnessOffset: b,
21
- disableMultiStroke: q
1
+ import { jsxs as g, jsx as b } from "react/jsx-runtime";
2
+ import { useRef as f, useState as j, useEffect as s, useCallback as Q } from "react";
3
+ import { AnnotationRenderer as q } from "./index2.js";
4
+ function B({
5
+ // Required props
6
+ pdfUrl: p,
7
+ // Optional props with defaults
8
+ page: o = 1,
9
+ scale: d = 1.5,
10
+ annotations: l = [],
11
+ currentTime: y = 0,
12
+ // Continuous sync mode (use instead of currentTime for smoother animation)
13
+ audioRef: a,
14
+ // Stroke configuration
15
+ strokeConfig: v,
16
+ // Callbacks
17
+ onLoad: h,
18
+ onError: r,
19
+ onPageChange: A,
20
+ // Styling
21
+ className: C,
22
+ style: k,
23
+ canvasStyle: R
24
+ }) {
25
+ const P = f(null), m = f(null), t = f(null), F = f(Promise.resolve()), [n, w] = j(!1), S = f(l);
26
+ s(() => {
27
+ S.current = l;
28
+ }, [l]);
29
+ const u = Q((e) => {
30
+ F.current = F.current.then(e).catch((i) => {
31
+ console.error("AnnotPdf: Queued operation failed:", i);
32
+ });
33
+ }, []);
34
+ s(() => {
35
+ if (!(!P.current || !m.current)) {
36
+ try {
37
+ t.current = new q({
38
+ canvasElement: P.current,
39
+ container: m.current,
40
+ strokeConfig: v
41
+ }), w(!0);
42
+ } catch (e) {
43
+ console.error("AnnotPdf: Failed to initialize renderer:", e), r && r(e);
22
44
  }
23
- ).map(([E, F]) => [E / o, F / o]), d = r + n * u, D = d + u;
24
- i.push({
25
- id: `${e}-${n}`,
26
- points: $,
27
- start: d,
28
- end: D,
29
- color: t.color || "rgba(255, 255, 0, 0.3)",
30
- width: t.width || 24,
31
- lineCap: t.lineCap || "butt"
45
+ return () => {
46
+ w(!1), t.current && (t.current.destroy(), t.current = null);
47
+ };
48
+ }
49
+ }, []), s(() => {
50
+ if (!n || !p)
51
+ return;
52
+ let e = !1;
53
+ return u(async () => {
54
+ if (t.current)
55
+ try {
56
+ const c = await t.current.loadPDF(p);
57
+ if (e) return;
58
+ if (!c.success) {
59
+ console.error("AnnotPdf: Failed to load PDF:", c.error), r && r(new Error(c.error));
60
+ return;
61
+ }
62
+ h && h({ pageCount: c.pageCount });
63
+ } catch (c) {
64
+ if (e) return;
65
+ console.error("AnnotPdf: Failed to load PDF:", c), r && r(c);
66
+ }
67
+ }), () => {
68
+ e = !0;
69
+ };
70
+ }, [p, n, u]), s(() => {
71
+ !n || !o || typeof o != "number" || u(async () => {
72
+ if (t.current)
73
+ try {
74
+ const e = await t.current.setPage(o);
75
+ if (!e.success) {
76
+ console.error("AnnotPdf: Failed to set page:", e.error), r && r(new Error(e.error));
77
+ return;
78
+ }
79
+ t.current.setAnnotations(S.current || []), A && A(o);
80
+ } catch (e) {
81
+ console.error("AnnotPdf: Failed to set page:", e), r && r(e);
82
+ }
83
+ });
84
+ }, [o, n, u]), s(() => {
85
+ !n || !d || typeof d != "number" || u(async () => {
86
+ if (t.current)
87
+ try {
88
+ const e = await t.current.setScale(d);
89
+ e.success || (console.error("AnnotPdf: Failed to set scale:", e.error), r && r(new Error(e.error)));
90
+ } catch (e) {
91
+ console.error("AnnotPdf: Failed to set scale:", e), r && r(e);
92
+ }
32
93
  });
33
- }
34
- return i;
94
+ }, [d, n, u]), s(() => {
95
+ if (!(!n || !t.current))
96
+ try {
97
+ t.current.setAnnotations(l || []);
98
+ } catch (e) {
99
+ console.error("AnnotPdf: Failed to set annotations:", e), r && r(e);
100
+ }
101
+ }, [l, n]), s(() => {
102
+ if (!a && !(!n || !t.current || y === void 0 || y === null))
103
+ try {
104
+ t.current.setTime(y);
105
+ } catch (e) {
106
+ console.error("AnnotPdf: Failed to set time:", e), r && r(e);
107
+ }
108
+ }, [y, a, n]), s(() => {
109
+ if (!a?.current || !n || !t.current)
110
+ return;
111
+ const e = a.current, i = () => {
112
+ t.current && t.current.startContinuousSync(() => e.currentTime);
113
+ }, c = () => {
114
+ t.current && (t.current.stopContinuousSync(), t.current.setTime(e.currentTime));
115
+ }, L = () => {
116
+ t.current && t.current.setTime(e.currentTime);
117
+ };
118
+ return e.addEventListener("play", i), e.addEventListener("pause", c), e.addEventListener("ended", c), e.addEventListener("seeked", L), e.paused || i(), () => {
119
+ e.removeEventListener("play", i), e.removeEventListener("pause", c), e.removeEventListener("ended", c), e.removeEventListener("seeked", L), t.current && t.current.stopContinuousSync();
120
+ };
121
+ }, [a, n]), s(() => {
122
+ if (!n || !t.current || !v)
123
+ return;
124
+ const e = t.current.updateStrokeConfig(v);
125
+ e && !e.success && r && r(new Error(e.error));
126
+ }, [v, n]);
127
+ const x = {
128
+ position: "relative",
129
+ display: "inline-block",
130
+ lineHeight: 0,
131
+ // Remove extra space below canvas
132
+ ...k
133
+ // User styles override defaults
134
+ }, D = {
135
+ position: "absolute",
136
+ top: 0,
137
+ left: 0,
138
+ width: "100%",
139
+ height: "100%",
140
+ pointerEvents: "none",
141
+ // Allow clicks to pass through to canvas
142
+ overflow: "hidden"
143
+ }, T = {
144
+ display: "block",
145
+ ...R
146
+ // User styles override defaults
147
+ };
148
+ return /* @__PURE__ */ g("div", { className: C, style: x, children: [
149
+ /* @__PURE__ */ b("canvas", { ref: P, style: T }),
150
+ /* @__PURE__ */ b("div", { ref: m, style: D })
151
+ ] });
35
152
  }
36
153
  export {
37
- R as default,
38
- R as highlightToStrokes
154
+ B as default
39
155
  };
40
156
  //# sourceMappingURL=index13.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index13.js","sources":["../src/converters/highlight.js"],"sourcesContent":["/**\n * Highlight Converter - Converts highlight annotations to stroke commands\n *\n * Transforms rectangular quads into horizontal stroke paths that can be\n * rendered progressively on canvas with hand-drawn highlighter style.\n *\n * @module converters/highlight\n */\n\nimport { roughLine, hashSeed } from '../rough/roughPathExtractor.js';\n\nconst SCALE = 1000;\n\n/**\n * Converts a highlight annotation to stroke commands\n *\n * Each quad in the annotation becomes a horizontal stroke at the\n * vertical center of the quad. Multiple quads are staggered in timing.\n * Uses RoughJS for hand-drawn highlighter style.\n *\n * @param {Object} annotation - Highlight annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {Array<{x: number, y: number, w: number, h: number}>} annotation.quads - Array of quads\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} style.color - Stroke color\n * @param {number} style.width - Stroke width in pixels\n * @param {string} [style.lineCap='butt'] - Line cap style\n * @param {number} [style.roughness=0.5] - Hand-drawn roughness (lower for highlighter)\n * @param {number} [style.bowing=0.5] - Line curvature\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function highlightToStrokes(annotation, style) {\n const { id, start, end, quads } = annotation;\n\n if (!quads || quads.length === 0) {\n return [];\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const quadCount = quads.length;\n const quadDuration = totalDuration / quadCount;\n\n const roughness = style.roughness ?? 0.5;\n const bowing = style.bowing ?? 0.5;\n const curveFitting = style.curveFitting ?? 0.95;\n const curveStepCount = style.curveStepCount ?? 9;\n const maxRandomnessOffset = style.maxRandomnessOffset ?? 2;\n const disableMultiStroke = style.disableMultiStroke ?? false;\n\n for (let i = 0; i < quads.length; i++) {\n const quad = quads[i];\n const { x, y, w, h } = quad;\n\n const yCenter = y + h / 2;\n\n const roughPoints = roughLine(\n x * SCALE,\n yCenter * SCALE,\n (x + w) * SCALE,\n yCenter * SCALE,\n {\n roughness,\n bowing,\n seed: hashSeed(`${id}-${i}`),\n curveFitting,\n curveStepCount,\n maxRandomnessOffset,\n disableMultiStroke\n }\n );\n\n const points = roughPoints.map(([px, py]) => [px / SCALE, py / SCALE]);\n\n const quadStart = start + i * quadDuration;\n const quadEnd = quadStart + quadDuration;\n\n strokes.push({\n id: `${id}-${i}`,\n points,\n start: quadStart,\n end: quadEnd,\n color: style.color || 'rgba(255, 255, 0, 0.3)',\n width: style.width || 24,\n lineCap: style.lineCap || 'butt'\n });\n }\n\n return strokes;\n}\n\nexport default highlightToStrokes;\n"],"names":["SCALE","highlightToStrokes","annotation","style","id","start","end","quads","strokes","totalDuration","quadCount","quadDuration","roughness","bowing","curveFitting","curveStepCount","maxRandomnessOffset","disableMultiStroke","i","quad","x","y","w","h","yCenter","points","roughLine","hashSeed","px","py","quadStart","quadEnd"],"mappings":";AAWA,MAAMA,IAAQ;AAuBP,SAASC,EAAmBC,GAAYC,GAAO;AACpD,QAAM,EAAE,IAAAC,GAAI,OAAAC,GAAO,KAAAC,GAAK,OAAAC,EAAK,IAAKL;AAElC,MAAI,CAACK,KAASA,EAAM,WAAW;AAC7B,WAAO,CAAA;AAGT,QAAMC,IAAU,CAAA,GACVC,IAAgBH,IAAMD,GACtBK,IAAYH,EAAM,QAClBI,IAAeF,IAAgBC,GAE/BE,IAAYT,EAAM,aAAa,KAC/BU,IAASV,EAAM,UAAU,KACzBW,IAAeX,EAAM,gBAAgB,MACrCY,IAAiBZ,EAAM,kBAAkB,GACzCa,IAAsBb,EAAM,uBAAuB,GACnDc,IAAqBd,EAAM,sBAAsB;AAEvD,WAASe,IAAI,GAAGA,IAAIX,EAAM,QAAQW,KAAK;AACrC,UAAMC,IAAOZ,EAAMW,CAAC,GACd,EAAE,GAAAE,GAAG,GAAAC,GAAG,GAAAC,GAAG,GAAAC,EAAC,IAAKJ,GAEjBK,IAAUH,IAAIE,IAAI,GAkBlBE,IAhBcC;AAAA,MAClBN,IAAIpB;AAAA,MACJwB,IAAUxB;AAAA,OACToB,IAAIE,KAAKtB;AAAA,MACVwB,IAAUxB;AAAA,MACV;AAAA,QACE,WAAAY;AAAA,QACA,QAAAC;AAAA,QACA,MAAMc,EAAS,GAAGvB,CAAE,IAAIc,CAAC,EAAE;AAAA,QAC3B,cAAAJ;AAAA,QACA,gBAAAC;AAAA,QACA,qBAAAC;AAAA,QACA,oBAAAC;AAAA,MACR;AAAA,IACA,EAE+B,IAAI,CAAC,CAACW,GAAIC,CAAE,MAAM,CAACD,IAAK5B,GAAO6B,IAAK7B,CAAK,CAAC,GAE/D8B,IAAYzB,IAAQa,IAAIP,GACxBoB,IAAUD,IAAYnB;AAE5B,IAAAH,EAAQ,KAAK;AAAA,MACX,IAAI,GAAGJ,CAAE,IAAIc,CAAC;AAAA,MACd,QAAAO;AAAA,MACA,OAAOK;AAAA,MACP,KAAKC;AAAA,MACL,OAAO5B,EAAM,SAAS;AAAA,MACtB,OAAOA,EAAM,SAAS;AAAA,MACtB,SAASA,EAAM,WAAW;AAAA,IAChC,CAAK;AAAA,EACH;AAEA,SAAOK;AACT;"}
1
+ {"version":3,"file":"index13.js","sources":["../src/adapters/AnnotPdf.jsx"],"sourcesContent":["// ============================================================================\n// SECTION 1: IMPORTS\n// ============================================================================\n\nimport { useRef, useEffect, useCallback, useState } from 'react';\nimport { AnnotationRenderer } from '../core/AnnotationRenderer.js';\n\n// ============================================================================\n// SECTION 2: JSDOC DOCUMENTATION\n// ============================================================================\n\n/**\n * AnnotPdf - Declarative React component for PDF annotation rendering\n *\n * A React wrapper around the AnnotationRenderer core engine that provides\n * a declarative, props-based API for rendering PDF documents with\n * timeline-synchronized annotations.\n *\n * Features:\n * - Automatic lifecycle management (initialization and cleanup)\n * - Declarative prop-to-method synchronization\n * - PDF rendering with pdf.js\n * - Timeline-synchronized annotation display\n * - Support for highlight, text, and ink annotations\n * - Page navigation and zoom control\n *\n * @component\n * @example\n * // Basic usage\n * <AnnotPdf\n * pdfUrl=\"/document.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={[]}\n * currentTime={0}\n * />\n *\n * @example\n * // With audio synchronization (discrete mode - ~4fps)\n * const [currentTime, setCurrentTime] = useState(0);\n *\n * <div>\n * <AnnotPdf\n * pdfUrl=\"/lecture.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={annotations}\n * currentTime={currentTime}\n * onLoad={({ pageCount }) => console.log('Loaded:', pageCount)}\n * />\n * <audio\n * src=\"/lecture.mp3\"\n * onTimeUpdate={(e) => setCurrentTime(e.target.currentTime)}\n * controls\n * />\n * </div>\n *\n * @example\n * // With audio synchronization (continuous mode - 60fps, smoother)\n * const audioRef = useRef(null);\n *\n * <div>\n * <AnnotPdf\n * pdfUrl=\"/lecture.pdf\"\n * page={1}\n * scale={1.5}\n * annotations={annotations}\n * audioRef={audioRef}\n * onLoad={({ pageCount }) => console.log('Loaded:', pageCount)}\n * />\n * <audio ref={audioRef} src=\"/lecture.mp3\" controls />\n * </div>\n *\n * @param {Object} props - Component props\n * @param {string} props.pdfUrl - PDF document URL (required)\n * @param {number} [props.page=1] - Current page number (1-indexed)\n * @param {number} [props.scale=1.5] - Zoom scale factor\n * @param {Array} [props.annotations=[]] - Array of annotation objects\n * @param {number} [props.currentTime=0] - Timeline position in seconds (discrete mode)\n * @param {React.RefObject<HTMLAudioElement>} [props.audioRef] - Audio element ref for continuous sync (60fps)\n * @param {Function} [props.onLoad] - Callback when PDF loads: ({pageCount}) => void\n * @param {Function} [props.onError] - Callback on error: (error) => void\n * @param {Function} [props.onPageChange] - Callback when page changes: (page) => void\n * @param {Object} [props.strokeConfig] - Stroke rendering configuration (setConfig format)\n * @param {number} [props.strokeConfig.roughness] - Global roughness for all types\n * @param {number} [props.strokeConfig.bowing] - Global bowing for all types\n * @param {Object} [props.strokeConfig.highlight] - Highlight-specific options\n * @param {Object} [props.strokeConfig.text] - Text-specific options\n * @param {Object} [props.strokeConfig.underline] - Underline-specific options\n * @param {Object} [props.strokeConfig.arrow] - Arrow-specific options\n * @param {Object} [props.strokeConfig.circle] - Circle-specific options\n * @param {string} [props.className] - CSS class for container div\n * @param {Object} [props.style] - Inline styles for container div\n * @param {Object} [props.canvasStyle] - Inline styles for canvas element\n * @returns {JSX.Element} PDF viewer component with annotation layers\n */\n\n// ============================================================================\n// SECTION 3: COMPONENT DEFINITION\n// ============================================================================\n\nfunction AnnotPdf({\n // Required props\n pdfUrl,\n\n // Optional props with defaults\n page = 1,\n scale = 1.5,\n annotations = [],\n currentTime = 0,\n\n // Continuous sync mode (use instead of currentTime for smoother animation)\n audioRef,\n\n // Stroke configuration\n strokeConfig,\n\n // Callbacks\n onLoad,\n onError,\n onPageChange,\n\n // Styling\n className,\n style,\n canvasStyle\n}) {\n\n // ==========================================================================\n // SECTION 4: REFS INITIALIZATION\n // ==========================================================================\n\n /**\n * Reference to the canvas element for PDF rendering\n * @type {React.RefObject<HTMLCanvasElement>}\n */\n const canvasRef = useRef(null);\n\n /**\n * Reference to the layer container div for annotation layers\n * @type {React.RefObject<HTMLDivElement>}\n */\n const layerContainerRef = useRef(null);\n\n /**\n * Reference to the AnnotationRenderer engine instance\n * Stored in ref to avoid triggering re-renders\n * @type {React.RefObject<AnnotationRenderer|null>}\n */\n const engineRef = useRef(null);\n\n /**\n * Reference to the render operation queue\n * Ensures sequential execution of async canvas operations\n * Prevents PDF.js race condition: \"Cannot use the same canvas during multiple render() operations\"\n * @type {React.RefObject<Promise<void>>}\n */\n const renderQueue = useRef(Promise.resolve());\n\n /**\n * State to track engine initialization\n * Used to trigger dependent effects after engine is ready\n */\n const [isEngineReady, setEngineReady] = useState(false);\n\n /**\n * Latest annotations prop, exposed via ref so the page-change effect can\n * read it without re-running whenever annotations change. AnnotationRenderer\n * v0.7.0 no longer applies annotations from setPage (R18) so the adapter\n * is responsible for re-binding them after a page transition.\n * @type {React.MutableRefObject<Array>}\n */\n const annotationsRef = useRef(annotations);\n useEffect(() => {\n annotationsRef.current = annotations;\n }, [annotations]);\n\n // ==========================================================================\n // SECTION 4.5: RENDER QUEUE HELPER\n // ==========================================================================\n\n /**\n * Queue a render operation to execute sequentially\n *\n * This helper ensures that async canvas operations (loadPDF, setPage, setScale)\n * execute one at a time, preventing concurrent access to the PDF.js canvas.\n * Uses Promise chaining to maintain operation order.\n *\n * @param {Function} operation - Async function returning a Promise\n * @returns {void}\n */\n const queueOperation = useCallback((operation) => {\n renderQueue.current = renderQueue.current\n .then(operation)\n .catch(error => {\n // Log errors but don't break the queue\n console.error('AnnotPdf: Queued operation failed:', error);\n });\n }, []);\n\n // ==========================================================================\n // SECTION 5: ENGINE INITIALIZATION AND CLEANUP\n // ==========================================================================\n\n /**\n * Initialize AnnotationRenderer on component mount\n * Cleanup on component unmount\n */\n useEffect(() => {\n // Guard: Wait for DOM elements to be ready\n if (!canvasRef.current || !layerContainerRef.current) {\n return;\n }\n\n // Initialize engine with stroke config if provided\n try {\n engineRef.current = new AnnotationRenderer({\n canvasElement: canvasRef.current,\n container: layerContainerRef.current,\n strokeConfig: strokeConfig\n });\n // Signal that engine is ready for dependent effects\n setEngineReady(true);\n } catch (error) {\n console.error('AnnotPdf: Failed to initialize renderer:', error);\n if (onError) {\n onError(error);\n }\n }\n\n // Cleanup on unmount\n return () => {\n setEngineReady(false);\n if (engineRef.current) {\n engineRef.current.destroy();\n engineRef.current = null;\n }\n };\n }, []); // Empty deps - run once on mount\n\n // ==========================================================================\n // SECTION 6: PDF LOADING SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Load PDF document when pdfUrl prop changes\n * Handles async operation with cancellation support\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid pdfUrl\n if (!isEngineReady || !pdfUrl) {\n return;\n }\n\n let cancelled = false;\n\n const loadPdf = async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.loadPDF(pdfUrl);\n\n // Check if component unmounted during async operation\n if (cancelled) return;\n\n // Check if load was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to load PDF:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n return;\n }\n\n // Call onLoad callback with pageCount from result\n if (onLoad) {\n onLoad({ pageCount: result.pageCount });\n }\n } catch (error) {\n if (cancelled) return;\n\n console.error('AnnotPdf: Failed to load PDF:', error);\n if (onError) {\n onError(error);\n }\n }\n };\n\n // Queue the PDF loading operation to prevent race conditions\n queueOperation(loadPdf);\n\n // Cleanup: Prevent state updates if component unmounts during load\n return () => {\n cancelled = true;\n };\n }, [pdfUrl, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 7: PAGE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync page prop to engine.setPage() method\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid page\n if (!isEngineReady || !page || typeof page !== 'number') {\n return;\n }\n\n // Queue the page change operation to prevent race conditions\n queueOperation(async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.setPage(page);\n\n // Check if page change was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to set page:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n return;\n }\n\n // R18: setPage no longer rebinds annotations — do it here using the\n // latest annotations snapshot from `annotationsRef`.\n engineRef.current.setAnnotations(annotationsRef.current || []);\n\n // Optional: Notify parent of successful page change\n if (onPageChange) {\n onPageChange(page);\n }\n } catch (error) {\n console.error('AnnotPdf: Failed to set page:', error);\n if (onError) {\n onError(error);\n }\n }\n });\n }, [page, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 8: SCALE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync scale prop to engine.setScale() method\n * Uses render queue to prevent concurrent canvas operations\n */\n useEffect(() => {\n // Guard: Wait for engine and valid scale\n if (!isEngineReady || !scale || typeof scale !== 'number') {\n return;\n }\n\n // Queue the scale change operation to prevent race conditions\n queueOperation(async () => {\n // Check engine exists at execution time (not queue time)\n if (!engineRef.current) {\n return;\n }\n\n try {\n const result = await engineRef.current.setScale(scale);\n\n // Check if scale change was successful\n if (!result.success) {\n console.error('AnnotPdf: Failed to set scale:', result.error);\n if (onError) {\n onError(new Error(result.error));\n }\n }\n } catch (error) {\n console.error('AnnotPdf: Failed to set scale:', error);\n if (onError) {\n onError(error);\n }\n }\n });\n }, [scale, isEngineReady, queueOperation]);\n\n // ==========================================================================\n // SECTION 9: ANNOTATIONS SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync annotations prop to engine.setAnnotations() method\n */\n useEffect(() => {\n // Guard: Wait for engine\n if (!isEngineReady || !engineRef.current) {\n return;\n }\n\n // Sync annotations to engine (default to empty array)\n try {\n engineRef.current.setAnnotations(annotations || []);\n } catch (error) {\n console.error('AnnotPdf: Failed to set annotations:', error);\n if (onError) {\n onError(error);\n }\n }\n }, [annotations, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10: TIMELINE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync currentTime prop to engine.setTime() method\n * Only used when audioRef is NOT provided (discrete mode)\n */\n useEffect(() => {\n // Skip if using continuous sync mode\n if (audioRef) {\n return;\n }\n\n // Guard: Wait for engine and valid currentTime\n if (!isEngineReady || !engineRef.current || currentTime === undefined || currentTime === null) {\n return;\n }\n\n // Sync timeline to engine\n try {\n engineRef.current.setTime(currentTime);\n } catch (error) {\n console.error('AnnotPdf: Failed to set time:', error);\n if (onError) {\n onError(error);\n }\n }\n }, [currentTime, audioRef, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10.1: CONTINUOUS SYNC MODE (audioRef)\n // ==========================================================================\n\n /**\n * Manage continuous sync mode when audioRef is provided\n *\n * Uses requestAnimationFrame for 60fps smooth animation instead of\n * discrete currentTime updates (~4fps from audio timeupdate events).\n */\n useEffect(() => {\n // Guard: Skip if not using continuous sync mode\n if (!audioRef?.current) {\n return;\n }\n\n // Guard: Wait for engine\n if (!isEngineReady || !engineRef.current) {\n return;\n }\n\n const audio = audioRef.current;\n /**\n * Start continuous sync when audio plays\n */\n const handlePlay = () => {\n if (!engineRef.current) return;\n engineRef.current.startContinuousSync(() => audio.currentTime);\n };\n\n /**\n * Stop continuous sync when audio pauses\n */\n const handlePause = () => {\n if (!engineRef.current) return;\n engineRef.current.stopContinuousSync();\n engineRef.current.setTime(audio.currentTime);\n };\n\n /**\n * Handle seeking - update time immediately\n */\n const handleSeeked = () => {\n if (!engineRef.current) return;\n engineRef.current.setTime(audio.currentTime);\n };\n\n // Add event listeners\n audio.addEventListener('play', handlePlay);\n audio.addEventListener('pause', handlePause);\n audio.addEventListener('ended', handlePause);\n audio.addEventListener('seeked', handleSeeked);\n\n // If audio is already playing, start sync immediately\n if (!audio.paused) {\n handlePlay();\n }\n\n // Cleanup on unmount or audioRef change\n return () => {\n audio.removeEventListener('play', handlePlay);\n audio.removeEventListener('pause', handlePause);\n audio.removeEventListener('ended', handlePause);\n audio.removeEventListener('seeked', handleSeeked);\n // Guard: engine may have been destroyed by initialization effect cleanup\n if (engineRef.current) {\n engineRef.current.stopContinuousSync();\n }\n };\n }, [audioRef, isEngineReady]);\n\n // ==========================================================================\n // SECTION 10.5: STROKE CONFIG SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync strokeConfig prop changes to the engine at runtime. The engine is\n * created with the initial config in the mount effect, so the first\n * invocation here is a no-op against an identical reference; subsequent\n * runs (live preview, theme switches) call `updateStrokeConfig`.\n */\n useEffect(() => {\n if (!isEngineReady || !engineRef.current || !strokeConfig) {\n return;\n }\n const result = engineRef.current.updateStrokeConfig(strokeConfig);\n if (result && !result.success && onError) {\n onError(new Error(result.error));\n }\n }, [strokeConfig, isEngineReady]);\n\n // ==========================================================================\n // SECTION 11: STYLING DEFINITIONS\n // ==========================================================================\n\n /**\n * Default container styles\n * Merged with user-provided styles (user styles override defaults)\n */\n const defaultContainerStyle = {\n position: 'relative',\n display: 'inline-block',\n lineHeight: 0, // Remove extra space below canvas\n ...style // User styles override defaults\n };\n\n /**\n * Default layer container styles\n * Positions layer div absolutely over canvas\n */\n const defaultLayerStyle = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n pointerEvents: 'none', // Allow clicks to pass through to canvas\n overflow: 'hidden'\n };\n\n /**\n * Default canvas styles\n * Merged with user-provided canvasStyle\n */\n const defaultCanvasStyle = {\n display: 'block',\n ...canvasStyle // User styles override defaults\n };\n\n // ==========================================================================\n // SECTION 12: JSX RETURN\n // ==========================================================================\n\n return (\n <div className={className} style={defaultContainerStyle}>\n <canvas ref={canvasRef} style={defaultCanvasStyle} />\n <div ref={layerContainerRef} style={defaultLayerStyle} />\n </div>\n );\n}\n\n// ============================================================================\n// SECTION 13: EXPORT\n// ============================================================================\n\nexport default AnnotPdf;\n"],"names":["AnnotPdf","pdfUrl","page","scale","annotations","currentTime","audioRef","strokeConfig","onLoad","onError","onPageChange","className","style","canvasStyle","canvasRef","useRef","layerContainerRef","engineRef","renderQueue","isEngineReady","setEngineReady","useState","annotationsRef","useEffect","queueOperation","useCallback","operation","error","AnnotationRenderer","cancelled","result","audio","handlePlay","handlePause","handleSeeked","defaultContainerStyle","defaultLayerStyle","defaultCanvasStyle","jsxs","jsx"],"mappings":";;;AAqGA,SAASA,EAAS;AAAA;AAAA,EAEhB,QAAAC;AAAA;AAAA,EAGA,MAAAC,IAAO;AAAA,EACP,OAAAC,IAAQ;AAAA,EACR,aAAAC,IAAc,CAAA;AAAA,EACd,aAAAC,IAAc;AAAA;AAAA,EAGd,UAAAC;AAAA;AAAA,EAGA,cAAAC;AAAA;AAAA,EAGA,QAAAC;AAAA,EACA,SAAAC;AAAA,EACA,cAAAC;AAAA;AAAA,EAGA,WAAAC;AAAA,EACA,OAAAC;AAAA,EACA,aAAAC;AACF,GAAG;AAUD,QAAMC,IAAYC,EAAO,IAAI,GAMvBC,IAAoBD,EAAO,IAAI,GAO/BE,IAAYF,EAAO,IAAI,GAQvBG,IAAcH,EAAO,QAAQ,QAAA,CAAS,GAMtC,CAACI,GAAeC,CAAc,IAAIC,EAAS,EAAK,GAShDC,IAAiBP,EAAOX,CAAW;AACzC,EAAAmB,EAAU,MAAM;AACd,IAAAD,EAAe,UAAUlB;AAAA,EAC3B,GAAG,CAACA,CAAW,CAAC;AAgBhB,QAAMoB,IAAiBC,EAAY,CAACC,MAAc;AAChD,IAAAR,EAAY,UAAUA,EAAY,QAC/B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EACF,GAAG,CAACX,GAAUa,CAAa,CAAC,GAY5BI,EAAU,MAAM;AACd,QAAI,CAACJ,KAAiB,CAACF,EAAU,WAAW,CAACV;AAC3C;AAEF,UAAMuB,IAASb,EAAU,QAAQ,mBAAmBV,CAAY;AAChE,IAAIuB,KAAU,CAACA,EAAO,WAAWrB,KAC/BA,EAAQ,IAAI,MAAMqB,EAAO,KAAK,CAAC;AAAA,EAEnC,GAAG,CAACvB,GAAcY,CAAa,CAAC;AAUhC,QAAMgB,IAAwB;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,YAAY;AAAA;AAAA,IACZ,GAAGvB;AAAA;AAAA,EAAA,GAOCwB,IAAoB;AAAA,IACxB,UAAU;AAAA,IACV,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,eAAe;AAAA;AAAA,IACf,UAAU;AAAA,EAAA,GAONC,IAAqB;AAAA,IACzB,SAAS;AAAA,IACT,GAAGxB;AAAA;AAAA,EAAA;AAOL,SACE,gBAAAyB,EAAC,OAAA,EAAI,WAAA3B,GAAsB,OAAOwB,GAChC,UAAA;AAAA,IAAA,gBAAAI,EAAC,UAAA,EAAO,KAAKzB,GAAW,OAAOuB,GAAoB;AAAA,IACnD,gBAAAE,EAAC,OAAA,EAAI,KAAKvB,GAAmB,OAAOoB,EAAA,CAAmB;AAAA,EAAA,GACzD;AAEJ;"}
package/dist/index14.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const R=require("./index11.cjs"),X=require("./index29.cjs");function P(e){const t=Math.sin(e)*1e4;return(t-Math.floor(t))*2-1}function _(e,t,n){return e.map(([r,c],o)=>[r+P(n+o*2)*t,c+P(n+o*2+1)*t])}function A(e,t,n){return e.map(([r,c])=>[(t+r)*n,c*n])}function $(e,t){const{id:n,start:r,end:c,content:o,x:b,y:D,fontSize:T}=e;if(!o||o.length===0)return[];const g=[],v=c-r,w=T||t.fontSize||16,z=t.roughness??1.5,C=w/1e3;let i=0;const M=o.length,p=v/M;for(let a=0;a<o.length;a++){const k=o[a],h=R.resolveGlyph(k);if(!h){i+=.5+.18;continue}const S=h.width||.5,l=h.paths||[],q=h.pathTiming||"sequential";if(l.length===0){i+=S+.18;continue}const d=r+a*p,y=d+p,E=l.length;for(let s=0;s<l.length;s++){const m=l[s].points||[];if(m.length<2)continue;const j=A(m,i,C),G=z*7e-4,I=X.hashSeed(`${n}-${a}-${s}`),O=_(j,G,I);let u,f;if(q==="parallel")u=d,f=y;else{const x=p/E;u=d+s*x,f=u+x}g.push({id:`${n}-${a}-${s}`,points:O,baseX:b,baseY:D,start:u,end:f,color:t.color||"rgba(220, 20, 60, 1.0)",width:t.width||2,lineCap:t.lineCap||"round",uniformScale:!0})}i+=S+.18}return g}exports.default=$;exports.textToStrokes=$;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("./index28.cjs"),R=require("./index24.cjs"),l=require("./index29.cjs"),e=1e3;let g=!1;function f(w,t){const{id:i,start:r,end:p,quads:n}=w;if(!n||n.length===0)return[];t&&t.width!==void 0&&!g&&(g=!0,console.warn("highlight: 'width' option is deprecated; use 'widthScale' instead. The 'width' value is ignored."));const s=[],q=p-r,S=n.length,a=q/S,E=t.widthScale??1;for(let o=0;o<n.length;o++){const C=n[o],{x:d,y:b,w:T,h:u}=C,h=b+u/2,W=u*R.REFERENCE_HEIGHT*E,_=k.roughLine(d*e,h*e,(d+T)*e,h*e,l.buildRoughOptions(t,`${i}-${o}`,{roughness:.5,bowing:.5})).map(([P,$])=>[P/e,$/e]),c=r+o*a,v=c+a;s.push({id:`${i}-${o}`,points:_,start:c,end:v,color:l.resolveColor(t,"rgba(255, 255, 0, 0.3)"),width:W,lineCap:t.lineCap||"butt"})}return s}exports.default=f;exports.highlightToStrokes=f;
2
2
  //# sourceMappingURL=index14.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index14.cjs","sources":["../src/converters/text.js"],"sourcesContent":["/**\n * Text Converter - Converts text annotations to stroke commands\n *\n * Transforms text content into stroke paths for each character,\n * using single-stroke font glyphs for smooth writing animation\n * with hand-drawn style.\n *\n * @module converters/text\n */\n\nimport { resolveGlyph } from \"./glyphResolver.js\";\nimport { hashSeed } from \"../rough/roughPathExtractor.js\";\n\n/**\n * Simple seeded random number generator\n * Returns value between -1 and 1\n */\nfunction seededRandom(seed) {\n const x = Math.sin(seed) * 10000;\n return (x - Math.floor(x)) * 2 - 1;\n}\n\n/**\n * Apply hand-drawn jitter to points\n * Each point gets a random offset based on seed for reproducibility\n */\nfunction applyJitter(points, amplitude, seed) {\n return points.map(([x, y], i) => [\n x + seededRandom(seed + i * 2) * amplitude,\n y + seededRandom(seed + i * 2 + 1) * amplitude\n ]);\n}\n\n/**\n * Scales glyph points by fontSize scale factor\n *\n * Glyph points are in normalized space where:\n * - X is 0 to charWidth (already scaled within the glyph)\n * - Y is 0 to ~1.0 (baseline at 0.8, cap height at 0)\n *\n * This scales them to the target size, but does NOT add the base position.\n * The base position is stored separately to allow correct rendering with\n * mixed coordinate systems (position in page coords, offsets in uniform space).\n *\n * @param {Array<[number, number]>} points - Glyph points in normalized space\n * @param {number} offsetX - X offset from base position (character offset within text)\n * @param {number} scale - Scale factor based on fontSize\n * @returns {Array<[number, number]>} Scaled offset points (not absolute positions)\n */\nfunction scaleGlyphPoints(points, offsetX, scale) {\n // Scale points and add character offset (in uniform space)\n return points.map(([px, py]) => [(offsetX + px) * scale, py * scale]);\n}\n\n/**\n * Converts a text annotation to stroke commands\n *\n * Each character in the content becomes one or more strokes.\n * Characters are staggered in timing to create a writing effect.\n * Multi-path characters (like 'i', 'j', '!') use pathTiming to\n * control whether paths are drawn sequentially or in parallel.\n *\n * @param {Object} annotation - Text annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {string} annotation.content - Text content to render\n * @param {number} annotation.x - X position (normalized 0-1)\n * @param {number} annotation.y - Y position (normalized 0-1)\n * @param {number} [annotation.fontSize=16] - Font size in pixels\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} style.color - Stroke color\n * @param {number} style.width - Stroke width in pixels\n * @param {number} [style.fontSize=16] - Default font size\n * @param {string} [style.lineCap='round'] - Line cap style\n * @param {number} [style.roughness=1.5] - Hand-drawn jitter amplitude\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function textToStrokes(annotation, style) {\n const { id, start, end, content, x, y, fontSize: annotFontSize } = annotation;\n\n if (!content || content.length === 0) {\n return [];\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const fontSize = annotFontSize || style.fontSize || 16;\n\n const roughness = style.roughness ?? 1.5;\n\n // Scale factor: convert fontSize (pixels) to normalized coordinates\n // Assuming a reference viewport of ~1000px\n const fontScale = fontSize / 1000;\n\n // Track character offset from base position (in glyph units, not page coords)\n let charOffsetX = 0;\n\n // Calculate timing per character\n const charCount = content.length;\n const charDuration = totalDuration / charCount;\n\n for (let charIndex = 0; charIndex < content.length; charIndex++) {\n const char = content[charIndex];\n const glyph = resolveGlyph(char);\n\n if (!glyph) {\n // Skip unknown characters, but advance position with default width\n charOffsetX += 0.5 + 0.18; // default width + spacing (in glyph units)\n continue;\n }\n\n const charWidth = glyph.width || 0.5;\n const charPaths = glyph.paths || [];\n const pathTiming = glyph.pathTiming || \"sequential\";\n\n // Skip if no paths (e.g., space character)\n if (charPaths.length === 0) {\n charOffsetX += charWidth + 0.18;\n continue;\n }\n\n // Calculate timing for this character's paths\n const charStart = start + charIndex * charDuration;\n const charEnd = charStart + charDuration;\n\n // Determine path timing based on pathTiming mode\n const pathCount = charPaths.length;\n\n for (let pathIndex = 0; pathIndex < charPaths.length; pathIndex++) {\n const pathData = charPaths[pathIndex];\n const rawPoints = pathData.points || [];\n\n if (rawPoints.length < 2) continue;\n\n // Scale glyph points to offset coordinates\n const scaledPoints = scaleGlyphPoints(rawPoints, charOffsetX, fontScale);\n\n // Apply hand-drawn jitter effect\n // Amplitude is in offset coordinates (scaled by viewport.height when rendered)\n // 0.0007 = ~0.4 pixels at 600px viewport, subtle hand-drawn effect\n const jitterAmplitude = roughness * 0.0007;\n const seed = hashSeed(`${id}-${charIndex}-${pathIndex}`);\n const points = applyJitter(scaledPoints, jitterAmplitude, seed);\n\n // Calculate path timing based on pathTiming mode\n let pathStart, pathEnd;\n\n if (pathTiming === \"parallel\") {\n // All paths drawn simultaneously during character duration\n pathStart = charStart;\n pathEnd = charEnd;\n } else {\n // Sequential: each path gets a portion of character duration\n const pathDuration = charDuration / pathCount;\n pathStart = charStart + pathIndex * pathDuration;\n pathEnd = pathStart + pathDuration;\n }\n\n strokes.push({\n id: `${id}-${charIndex}-${pathIndex}`,\n points, // Offset coordinates from baseX/baseY (uniform space)\n baseX: x, // Base X position (width-normalized page coords)\n baseY: y, // Base Y position (height-normalized page coords)\n start: pathStart,\n end: pathEnd,\n color: style.color || \"rgba(220, 20, 60, 1.0)\",\n width: style.width || 2,\n lineCap: style.lineCap || \"round\",\n uniformScale: true, // Preserve aspect ratio when rendering\n });\n }\n\n // Advance offset for next character (in glyph units)\n charOffsetX += charWidth + 0.18; // Add small spacing\n }\n\n return strokes;\n}\n\nexport default textToStrokes;\n"],"names":["seededRandom","seed","x","applyJitter","points","amplitude","y","i","scaleGlyphPoints","offsetX","scale","px","py","textToStrokes","annotation","style","id","start","end","content","annotFontSize","strokes","totalDuration","fontSize","roughness","fontScale","charOffsetX","charCount","charDuration","charIndex","char","glyph","resolveGlyph","charWidth","charPaths","pathTiming","charStart","charEnd","pathCount","pathIndex","rawPoints","scaledPoints","jitterAmplitude","hashSeed","pathStart","pathEnd","pathDuration"],"mappings":"wKAiBA,SAASA,EAAaC,EAAM,CAC1B,MAAMC,EAAI,KAAK,IAAID,CAAI,EAAI,IAC3B,OAAQC,EAAI,KAAK,MAA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J,EAAU,OAE5B,QAASK,EAAY,EAAGA,EAAYL,EAAU,OAAQK,IAAa,CAEjE,MAAMC,EADWN,EAAUK,CAAS,EACT,QAAU,CAAA,EAErC,GAAIC,EAAU,OAAS,EAAG,SAG1B,MAAMC,EAAejC,EAAiBgC,EAAWd,EAAaD,CAAS,EAKjEiB,EAAkBlB,EAAY,KAC9BvB,EAAO0C,WAAS,GAAG3B,CAAE,IAAIa,CAAS,IAAIU,CAAS,EAAE,EACjDnC,EAASD,EAAYsC,EAAcC,EAAiBzC,CAAI,EAG9D,IAAI2C,EAAWC,EAEf,GAAIV,IAAe,WAEjBS,EAAYR,EACZS,EAAUR,MACL,CAEL,MAAMS,EAAelB,EAAeU,EACpCM,EAAYR,EAAYG,EAAYO,EACpCD,EAAUD,EAAYE,CACxB,CAEAzB,EAAQ,KAAK,CACX,GAAI,GAAGL,CAAE,IAAIa,CAAS,IAAIU,CAAS,GACnC,OAAAnC,EACA,MAAOF,EACP,MAAOI,EACP,MAAOsC,EACP,IAAKC,EACL,MAAO9B,EAAM,OAAS,yBACtB,MAAOA,EAAM,OAAS,EACtB,QAASA,EAAM,SAAW,QAC1B,aAAc,EACtB,CAAO,CACH,CAGAW,GAAeO,EAAY,GAC7B,CAEA,OAAOZ,CACT"}
1
+ {"version":3,"file":"index14.cjs","sources":["../src/converters/highlight.js"],"sourcesContent":["/**\n * Highlight Converter - Converts highlight annotations to stroke commands\n *\n * Transforms rectangular quads into horizontal stroke paths that can be\n * rendered progressively on canvas with hand-drawn highlighter style.\n *\n * @module converters/highlight\n */\n\nimport { roughLine } from '../rough/roughPathExtractor.js';\nimport { REFERENCE_HEIGHT } from '../config/defaults.js';\nimport { buildRoughOptions, resolveColor } from './_shared.js';\n\nconst SCALE = 1000;\n\n// One-time module-load deprecation warning for the legacy `width` field.\n// Highlight thickness in v0.7+ is data-derived (quad.h * REFERENCE_HEIGHT)\n// and scaled by `widthScale`. The old `width` field is silently ignored.\nlet _legacyWidthWarned = false;\n\n/**\n * Converts a highlight annotation to stroke commands\n *\n * Each quad in the annotation becomes a horizontal stroke at the\n * vertical center of the quad. Multiple quads are staggered in timing.\n * Uses RoughJS for hand-drawn highlighter style.\n *\n * Stroke width is derived from the quad height (`quad.h`, normalized 0-1)\n * scaled to the renderer's reference viewport height. `style.widthScale`\n * acts as a multiplier (default 1.0) so that the highlighter's thickness\n * tracks the underlying text size automatically.\n *\n * @param {Object} annotation - Highlight annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {Array<{x: number, y: number, w: number, h: number}>} annotation.quads - Array of quads\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} [style.color] - Stroke color\n * @param {number} [style.widthScale=1.0] - Multiplier applied to the quad-derived width\n * @param {string} [style.lineCap='butt'] - Line cap style\n * @param {number} [style.roughness=0.5] - Hand-drawn roughness (lower for highlighter)\n * @param {number} [style.bowing=0.5] - Line curvature\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function highlightToStrokes(annotation, style) {\n const { id, start, end, quads } = annotation;\n\n if (!quads || quads.length === 0) {\n return [];\n }\n\n // Detect legacy `width` usage and warn once per module load. The field is\n // ignored width is data-derived; consumers should use `widthScale`.\n if (style && style.width !== undefined && !_legacyWidthWarned) {\n _legacyWidthWarned = true;\n console.warn(\n \"highlight: 'width' option is deprecated; use 'widthScale' instead. The 'width' value is ignored.\",\n );\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const quadCount = quads.length;\n const quadDuration = totalDuration / quadCount;\n\n const widthScale = style.widthScale ?? 1.0;\n\n for (let i = 0; i < quads.length; i++) {\n const quad = quads[i];\n const { x, y, w, h } = quad;\n\n const yCenter = y + h / 2;\n\n // quad.h is normalized (0-1); scale to the renderer's reference viewport\n // so the highlighter thickness tracks the underlying text height.\n const dataWidth = h * REFERENCE_HEIGHT;\n const finalWidth = dataWidth * widthScale;\n\n const roughPoints = roughLine(\n x * SCALE,\n yCenter * SCALE,\n (x + w) * SCALE,\n yCenter * SCALE,\n buildRoughOptions(style, `${id}-${i}`, { roughness: 0.5, bowing: 0.5 })\n );\n\n const points = roughPoints.map(([px, py]) => [px / SCALE, py / SCALE]);\n\n const quadStart = start + i * quadDuration;\n const quadEnd = quadStart + quadDuration;\n\n strokes.push({\n id: `${id}-${i}`,\n points,\n start: quadStart,\n end: quadEnd,\n color: resolveColor(style, 'rgba(255, 255, 0, 0.3)'),\n width: finalWidth,\n lineCap: style.lineCap || 'butt'\n });\n }\n\n return strokes;\n}\n\nexport default highlightToStrokes;\n"],"names":["SCALE","_legacyWidthWarned","highlightToStrokes","annotation","style","id","start","end","quads","strokes","totalDuration","quadCount","quadDuration","widthScale","i","quad","x","y","w","h","yCenter","finalWidth","REFERENCE_HEIGHT","points","roughLine","buildRoughOptions","px","py","quadStart","quadEnd","resolveColor"],"mappings":"mMAaMA,EAAQ,IAKd,IAAIC,EAAqB,GA4BlB,SAASC,EAAmBC,EAAYC,EAAO,CACpD,KAAM,CAAE,GAAAC,EAAI,MAAAC,EAAO,IAAAC,EAAK,MAAAC,CAAK,EAAKL,EAElC,GAAI,CAACK,GAASA,EAAM,SAAW,EAC7B,MAAO,CAAA,EAKLJ,GAASA,EAAM,QAAU,QAAa,CAACH,IACzCA,EAAqB,GACrB,QAAQ,KACN,kGACN,GAGE,MAAMQ,EAAU,CAAA,EACVC,EAAgBH,EAAMD,EACtBK,EAAYH,EAAM,OAClBI,EAAeF,EAAgBC,EAE/BE,EAAaT,EAAM,YAAc,EAEvC,QAASU,EAAI,EAAGA,EAAIN,EAAM,OAAQM,IAAK,CACrC,MAAMC,EAAOP,EAAMM,CAAC,EACd,CAAE,EAAAE,EAAG,EAAAC,EAAG,EAAAC,EAAG,EAAAC,CAAC,EAAKJ,EAEjBK,EAAUH,EAAIE,EAAI,EAKlBE,EADYF,EAAIG,EAAAA,iBACST,EAUzBU,EARcC,EAAAA,UAClBR,EAAIhB,EACJoB,EAAUpB,GACTgB,EAAIE,GAAKlB,EACVoB,EAAUpB,EACVyB,EAAAA,kBAAkBrB,EAAO,GAAGC,CAAE,IAAIS,CAAC,GAAI,CAAE,UAAW,GAAK,OAAQ,EAAG,CAAE,CAC5E,EAE+B,IAAI,CAAC,CAACY,EAAIC,CAAE,IAAM,CAACD,EAAK1B,EAAO2B,EAAK3B,CAAK,CAAC,EAE/D4B,EAAYtB,EAAQQ,EAAIF,EACxBiB,EAAUD,EAAYhB,EAE5BH,EAAQ,KAAK,CACX,GAAI,GAAGJ,CAAE,IAAIS,CAAC,GACd,OAAAS,EACA,MAAOK,EACP,IAAKC,EACL,MAAOC,EAAAA,aAAa1B,EAAO,wBAAwB,EACnD,MAAOiB,EACP,QAASjB,EAAM,SAAW,MAChC,CAAK,CACH,CAEA,OAAOK,CACT"}
package/dist/index14.js CHANGED
@@ -1,71 +1,38 @@
1
- import { resolveGlyph as y } from "./index11.js";
2
- import { hashSeed as A } from "./index29.js";
3
- function $(e) {
4
- const t = Math.sin(e) * 1e4;
5
- return (t - Math.floor(t)) * 2 - 1;
6
- }
7
- function F(e, t, n) {
8
- return e.map(([a, c], o) => [
9
- a + $(n + o * 2) * t,
10
- c + $(n + o * 2 + 1) * t
11
- ]);
12
- }
13
- function J(e, t, n) {
14
- return e.map(([a, c]) => [(t + a) * n, c * n]);
15
- }
16
- function Y(e, t) {
17
- const { id: n, start: a, end: c, content: o, x: D, y: w, fontSize: z } = e;
18
- if (!o || o.length === 0)
1
+ import { roughLine as T } from "./index28.js";
2
+ import { REFERENCE_HEIGHT as k } from "./index24.js";
3
+ import { buildRoughOptions as v, resolveColor as x } from "./index29.js";
4
+ const n = 1e3;
5
+ let l = !1;
6
+ function A(g, t) {
7
+ const { id: e, start: a, end: p, quads: i } = g;
8
+ if (!i || i.length === 0)
19
9
  return [];
20
- const g = [], C = c - a, P = z || t.fontSize || 16, b = t.roughness ?? 1.5, T = P / 1e3;
21
- let i = 0;
22
- const k = o.length, u = C / k;
23
- for (let r = 0; r < o.length; r++) {
24
- const E = o[r], h = y(E);
25
- if (!h) {
26
- i += 0.5 + 0.18;
27
- continue;
28
- }
29
- const m = h.width || 0.5, l = h.paths || [], G = h.pathTiming || "sequential";
30
- if (l.length === 0) {
31
- i += m + 0.18;
32
- continue;
33
- }
34
- const f = a + r * u, I = f + u, M = l.length;
35
- for (let s = 0; s < l.length; s++) {
36
- const S = l[s].points || [];
37
- if (S.length < 2) continue;
38
- const X = J(S, i, T), j = b * 7e-4, q = A(`${n}-${r}-${s}`), v = F(X, j, q);
39
- let p, d;
40
- if (G === "parallel")
41
- p = f, d = I;
42
- else {
43
- const x = u / M;
44
- p = f + s * x, d = p + x;
45
- }
46
- g.push({
47
- id: `${n}-${r}-${s}`,
48
- points: v,
49
- // Offset coordinates from baseX/baseY (uniform space)
50
- baseX: D,
51
- // Base X position (width-normalized page coords)
52
- baseY: w,
53
- // Base Y position (height-normalized page coords)
54
- start: p,
55
- end: d,
56
- color: t.color || "rgba(220, 20, 60, 1.0)",
57
- width: t.width || 2,
58
- lineCap: t.lineCap || "round",
59
- uniformScale: !0
60
- // Preserve aspect ratio when rendering
61
- });
62
- }
63
- i += m + 0.18;
10
+ t && t.width !== void 0 && !l && (l = !0, console.warn(
11
+ "highlight: 'width' option is deprecated; use 'widthScale' instead. The 'width' value is ignored."
12
+ ));
13
+ const d = [], f = p - a, w = i.length, r = f / w, m = t.widthScale ?? 1;
14
+ for (let o = 0; o < i.length; o++) {
15
+ const C = i[o], { x: s, y: E, w: q, h } = C, u = E + h / 2, S = h * k * m, W = T(
16
+ s * n,
17
+ u * n,
18
+ (s + q) * n,
19
+ u * n,
20
+ v(t, `${e}-${o}`, { roughness: 0.5, bowing: 0.5 })
21
+ ).map(([$, R]) => [$ / n, R / n]), c = a + o * r, b = c + r;
22
+ d.push({
23
+ id: `${e}-${o}`,
24
+ points: W,
25
+ start: c,
26
+ end: b,
27
+ color: x(t, "rgba(255, 255, 0, 0.3)"),
28
+ width: S,
29
+ lineCap: t.lineCap || "butt"
30
+ });
64
31
  }
65
- return g;
32
+ return d;
66
33
  }
67
34
  export {
68
- Y as default,
69
- Y as textToStrokes
35
+ A as default,
36
+ A as highlightToStrokes
70
37
  };
71
38
  //# sourceMappingURL=index14.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index14.js","sources":["../src/converters/text.js"],"sourcesContent":["/**\n * Text Converter - Converts text annotations to stroke commands\n *\n * Transforms text content into stroke paths for each character,\n * using single-stroke font glyphs for smooth writing animation\n * with hand-drawn style.\n *\n * @module converters/text\n */\n\nimport { resolveGlyph } from \"./glyphResolver.js\";\nimport { hashSeed } from \"../rough/roughPathExtractor.js\";\n\n/**\n * Simple seeded random number generator\n * Returns value between -1 and 1\n */\nfunction seededRandom(seed) {\n const x = Math.sin(seed) * 10000;\n return (x - Math.floor(x)) * 2 - 1;\n}\n\n/**\n * Apply hand-drawn jitter to points\n * Each point gets a random offset based on seed for reproducibility\n */\nfunction applyJitter(points, amplitude, seed) {\n return points.map(([x, y], i) => [\n x + seededRandom(seed + i * 2) * amplitude,\n y + seededRandom(seed + i * 2 + 1) * amplitude\n ]);\n}\n\n/**\n * Scales glyph points by fontSize scale factor\n *\n * Glyph points are in normalized space where:\n * - X is 0 to charWidth (already scaled within the glyph)\n * - Y is 0 to ~1.0 (baseline at 0.8, cap height at 0)\n *\n * This scales them to the target size, but does NOT add the base position.\n * The base position is stored separately to allow correct rendering with\n * mixed coordinate systems (position in page coords, offsets in uniform space).\n *\n * @param {Array<[number, number]>} points - Glyph points in normalized space\n * @param {number} offsetX - X offset from base position (character offset within text)\n * @param {number} scale - Scale factor based on fontSize\n * @returns {Array<[number, number]>} Scaled offset points (not absolute positions)\n */\nfunction scaleGlyphPoints(points, offsetX, scale) {\n // Scale points and add character offset (in uniform space)\n return points.map(([px, py]) => [(offsetX + px) * scale, py * scale]);\n}\n\n/**\n * Converts a text annotation to stroke commands\n *\n * Each character in the content becomes one or more strokes.\n * Characters are staggered in timing to create a writing effect.\n * Multi-path characters (like 'i', 'j', '!') use pathTiming to\n * control whether paths are drawn sequentially or in parallel.\n *\n * @param {Object} annotation - Text annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {string} annotation.content - Text content to render\n * @param {number} annotation.x - X position (normalized 0-1)\n * @param {number} annotation.y - Y position (normalized 0-1)\n * @param {number} [annotation.fontSize=16] - Font size in pixels\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} style.color - Stroke color\n * @param {number} style.width - Stroke width in pixels\n * @param {number} [style.fontSize=16] - Default font size\n * @param {string} [style.lineCap='round'] - Line cap style\n * @param {number} [style.roughness=1.5] - Hand-drawn jitter amplitude\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function textToStrokes(annotation, style) {\n const { id, start, end, content, x, y, fontSize: annotFontSize } = annotation;\n\n if (!content || content.length === 0) {\n return [];\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const fontSize = annotFontSize || style.fontSize || 16;\n\n const roughness = style.roughness ?? 1.5;\n\n // Scale factor: convert fontSize (pixels) to normalized coordinates\n // Assuming a reference viewport of ~1000px\n const fontScale = fontSize / 1000;\n\n // Track character offset from base position (in glyph units, not page coords)\n let charOffsetX = 0;\n\n // Calculate timing per character\n const charCount = content.length;\n const charDuration = totalDuration / charCount;\n\n for (let charIndex = 0; charIndex < content.length; charIndex++) {\n const char = content[charIndex];\n const glyph = resolveGlyph(char);\n\n if (!glyph) {\n // Skip unknown characters, but advance position with default width\n charOffsetX += 0.5 + 0.18; // default width + spacing (in glyph units)\n continue;\n }\n\n const charWidth = glyph.width || 0.5;\n const charPaths = glyph.paths || [];\n const pathTiming = glyph.pathTiming || \"sequential\";\n\n // Skip if no paths (e.g., space character)\n if (charPaths.length === 0) {\n charOffsetX += charWidth + 0.18;\n continue;\n }\n\n // Calculate timing for this character's paths\n const charStart = start + charIndex * charDuration;\n const charEnd = charStart + charDuration;\n\n // Determine path timing based on pathTiming mode\n const pathCount = charPaths.length;\n\n for (let pathIndex = 0; pathIndex < charPaths.length; pathIndex++) {\n const pathData = charPaths[pathIndex];\n const rawPoints = pathData.points || [];\n\n if (rawPoints.length < 2) continue;\n\n // Scale glyph points to offset coordinates\n const scaledPoints = scaleGlyphPoints(rawPoints, charOffsetX, fontScale);\n\n // Apply hand-drawn jitter effect\n // Amplitude is in offset coordinates (scaled by viewport.height when rendered)\n // 0.0007 = ~0.4 pixels at 600px viewport, subtle hand-drawn effect\n const jitterAmplitude = roughness * 0.0007;\n const seed = hashSeed(`${id}-${charIndex}-${pathIndex}`);\n const points = applyJitter(scaledPoints, jitterAmplitude, seed);\n\n // Calculate path timing based on pathTiming mode\n let pathStart, pathEnd;\n\n if (pathTiming === \"parallel\") {\n // All paths drawn simultaneously during character duration\n pathStart = charStart;\n pathEnd = charEnd;\n } else {\n // Sequential: each path gets a portion of character duration\n const pathDuration = charDuration / pathCount;\n pathStart = charStart + pathIndex * pathDuration;\n pathEnd = pathStart + pathDuration;\n }\n\n strokes.push({\n id: `${id}-${charIndex}-${pathIndex}`,\n points, // Offset coordinates from baseX/baseY (uniform space)\n baseX: x, // Base X position (width-normalized page coords)\n baseY: y, // Base Y position (height-normalized page coords)\n start: pathStart,\n end: pathEnd,\n color: style.color || \"rgba(220, 20, 60, 1.0)\",\n width: style.width || 2,\n lineCap: style.lineCap || \"round\",\n uniformScale: true, // Preserve aspect ratio when rendering\n });\n }\n\n // Advance offset for next character (in glyph units)\n charOffsetX += charWidth + 0.18; // Add small spacing\n }\n\n return strokes;\n}\n\nexport default textToStrokes;\n"],"names":["seededRandom","seed","x","applyJitter","points","amplitude","y","i","scaleGlyphPoints","offsetX","scale","px","py","textToStrokes","annotation","style","id","start","end","content","annotFontSize","strokes","totalDuration","fontSize","roughness","fontScale","charOffsetX","charCount","charDuration","charIndex","char","glyph","resolveGlyph","charWidth","charPaths","pathTiming","charStart","charEnd","pathCount","pathIndex","raw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,EAAM,SAAS,CAAA,GAC3BI,IAAaJ,EAAM,cAAc;AAGvC,QAAIG,EAAU,WAAW,GAAG;AAC1B,MAAAR,KAAeO,IAAY;AAC3B;AAAA,IACF;AAGA,UAAMG,IAAYnB,IAAQY,IAAYD,GAChCS,IAAUD,IAAYR,GAGtBU,IAAYJ,EAAU;AAE5B,aAASK,IAAY,GAAGA,IAAYL,EAAU,QAAQK,KAAa;AAEjE,YAAMC,IADWN,EAAUK,CAAS,EACT,UAAU,CAAA;AAErC,UAAIC,EAAU,SAAS,EAAG;AAG1B,YAAMC,IAAejC,EAAiBgC,GAAWd,GAAaD,CAAS,GAKjEiB,IAAkBlB,IAAY,MAC9BvB,IAAO0C,EAAS,GAAG3B,CAAE,IAAIa,CAAS,IAAIU,CAAS,EAAE,GACjDnC,IAASD,EAAYsC,GAAcC,GAAiBzC,CAAI;AAG9D,UAAI2C,GAAWC;AAEf,UAAIV,MAAe;AAEjB,QAAAS,IAAYR,GACZS,IAAUR;AAAA,WACL;AAEL,cAAMS,IAAelB,IAAeU;AACpC,QAAAM,IAAYR,IAAYG,IAAYO,GACpCD,IAAUD,IAAYE;AAAA,MACxB;AAEA,MAAAzB,EAAQ,KAAK;AAAA,QACX,IAAI,GAAGL,CAAE,IAAIa,CAAS,IAAIU,CAAS;AAAA,QACnC,QAAAnC;AAAA;AAAA,QACA,OAAOF;AAAA;AAAA,QACP,OAAOI;AAAA;AAAA,QACP,OAAOsC;AAAA,QACP,KAAKC;AAAA,QACL,OAAO9B,EAAM,SAAS;AAAA,QACtB,OAAOA,EAAM,SAAS;AAAA,QACtB,SAASA,EAAM,WAAW;AAAA,QAC1B,cAAc;AAAA;AAAA,MACtB,CAAO;AAAA,IACH;AAGA,IAAAW,KAAeO,IAAY;AAAA,EAC7B;AAEA,SAAOZ;AACT;"}
1
+ {"version":3,"file":"index14.js","sources":["../src/converters/highlight.js"],"sourcesContent":["/**\n * Highlight Converter - Converts highlight annotations to stroke commands\n *\n * Transforms rectangular quads into horizontal stroke paths that can be\n * rendered progressively on canvas with hand-drawn highlighter style.\n *\n * @module converters/highlight\n */\n\nimport { roughLine } from '../rough/roughPathExtractor.js';\nimport { REFERENCE_HEIGHT } from '../config/defaults.js';\nimport { buildRoughOptions, resolveColor } from './_shared.js';\n\nconst SCALE = 1000;\n\n// One-time module-load deprecation warning for the legacy `width` field.\n// Highlight thickness in v0.7+ is data-derived (quad.h * REFERENCE_HEIGHT)\n// and scaled by `widthScale`. The old `width` field is silently ignored.\nlet _legacyWidthWarned = false;\n\n/**\n * Converts a highlight annotation to stroke commands\n *\n * Each quad in the annotation becomes a horizontal stroke at the\n * vertical center of the quad. Multiple quads are staggered in timing.\n * Uses RoughJS for hand-drawn highlighter style.\n *\n * Stroke width is derived from the quad height (`quad.h`, normalized 0-1)\n * scaled to the renderer's reference viewport height. `style.widthScale`\n * acts as a multiplier (default 1.0) so that the highlighter's thickness\n * tracks the underlying text size automatically.\n *\n * @param {Object} annotation - Highlight annotation object\n * @param {string} annotation.id - Unique identifier\n * @param {number} annotation.start - Start time in seconds\n * @param {number} annotation.end - End time in seconds\n * @param {Array<{x: number, y: number, w: number, h: number}>} annotation.quads - Array of quads\n * @param {Object} [annotation.style] - Optional style overrides\n * @param {Object} style - Resolved style configuration\n * @param {string} [style.color] - Stroke color\n * @param {number} [style.widthScale=1.0] - Multiplier applied to the quad-derived width\n * @param {string} [style.lineCap='butt'] - Line cap style\n * @param {number} [style.roughness=0.5] - Hand-drawn roughness (lower for highlighter)\n * @param {number} [style.bowing=0.5] - Line curvature\n * @returns {Array<Object>} Array of stroke commands\n */\nexport function highlightToStrokes(annotation, style) {\n const { id, start, end, quads } = annotation;\n\n if (!quads || quads.length === 0) {\n return [];\n }\n\n // Detect legacy `width` usage and warn once per module load. The field is\n // ignored width is data-derived; consumers should use `widthScale`.\n if (style && style.width !== undefined && !_legacyWidthWarned) {\n _legacyWidthWarned = true;\n console.warn(\n \"highlight: 'width' option is deprecated; use 'widthScale' instead. The 'width' value is ignored.\",\n );\n }\n\n const strokes = [];\n const totalDuration = end - start;\n const quadCount = quads.length;\n const quadDuration = totalDuration / quadCount;\n\n const widthScale = style.widthScale ?? 1.0;\n\n for (let i = 0; i < quads.length; i++) {\n const quad = quads[i];\n const { x, y, w, h } = quad;\n\n const yCenter = y + h / 2;\n\n // quad.h is normalized (0-1); scale to the renderer's reference viewport\n // so the highlighter thickness tracks the underlying text height.\n const dataWidth = h * REFERENCE_HEIGHT;\n const finalWidth = dataWidth * widthScale;\n\n const roughPoints = roughLine(\n x * SCALE,\n yCenter * SCALE,\n (x + w) * SCALE,\n yCenter * SCALE,\n buildRoughOptions(style, `${id}-${i}`, { roughness: 0.5, bowing: 0.5 })\n );\n\n const points = roughPoints.map(([px, py]) => [px / SCALE, py / SCALE]);\n\n const quadStart = start + i * quadDuration;\n const quadEnd = quadStart + quadDuration;\n\n strokes.push({\n id: `${id}-${i}`,\n points,\n start: quadStart,\n end: quadEnd,\n color: resolveColor(style, 'rgba(255, 255, 0, 0.3)'),\n width: finalWidth,\n lineCap: style.lineCap || 'butt'\n });\n }\n\n return strokes;\n}\n\nexport default highlightToStrokes;\n"],"names":["SCALE","_legacyWidthWarned","highlightToStrokes","annotation","style","id","start","end","quads","strokes","totalDuration","quadCount","quadDuration","widthScale","i","quad","x","y","w","yCenter","finalWidth","REFERENCE_HEIGHT","points","roughLine","buildRoughOptions","px","py","quadStart","quadEnd","resolveColor"],"mappings":";;;AAaA,MAAMA,IAAQ;AAKd,IAAIC,IAAqB;AA4BlB,SAASC,EAAmBC,GAAYC,GAAO;AACpD,QAAM,EAAE,IAAAC,GAAI,OAAAC,GAAO,KAAAC,GAAK,OAAAC,EAAK,IAAKL;AAElC,MAAI,CAACK,KAASA,EAAM,WAAW;AAC7B,WAAO,CAAA;AAKT,EAAIJ,KAASA,EAAM,UAAU,UAAa,CAACH,MACzCA,IAAqB,IACrB,QAAQ;AAAA,IACN;AAAA,EACN;AAGE,QAAMQ,IAAU,CAAA,GACVC,IAAgBH,IAAMD,GACtBK,IAAYH,EAAM,QAClBI,IAAeF,IAAgBC,GAE/BE,IAAaT,EAAM,cAAc;AAEvC,WAASU,IAAI,GAAGA,IAAIN,EAAM,QAAQM,KAAK;AACrC,UAAMC,IAAOP,EAAMM,CAAC,GACd,EAAE,GAAAE,GAAG,GAAAC,GAAG,GAAAC,GAAG,EAAC,IAAKH,GAEjBI,IAAUF,IAAI,IAAI,GAKlBG,IADY,IAAIC,IACSR,GAUzBS,IARcC;AAAA,MAClBP,IAAIhB;AAAA,MACJmB,IAAUnB;AAAA,OACTgB,IAAIE,KAAKlB;AAAA,MACVmB,IAAUnB;AAAA,MACVwB,EAAkBpB,GAAO,GAAGC,CAAE,IAAIS,CAAC,IAAI,EAAE,WAAW,KAAK,QAAQ,IAAG,CAAE;AAAA,IAC5E,EAE+B,IAAI,CAAC,CAACW,GAAIC,CAAE,MAAM,CAACD,IAAKzB,GAAO0B,IAAK1B,CAAK,CAAC,GAE/D2B,IAAYrB,IAAQQ,IAAIF,GACxBgB,IAAUD,IAAYf;AAE5B,IAAAH,EAAQ,KAAK;AAAA,MACX,IAAI,GAAGJ,CAAE,IAAIS,CAAC;AAAA,MACd,QAAAQ;AAAA,MACA,OAAOK;AAAA,MACP,KAAKC;AAAA,MACL,OAAOC,EAAazB,GAAO,wBAAwB;AAAA,MACnD,OAAOgB;AAAA,MACP,SAAShB,EAAM,WAAW;AAAA,IAChC,CAAK;AAAA,EACH;AAEA,SAAOK;AACT;"}
package/dist/index15.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("./index29.cjs"),o=1e3;function h(l,t){const{id:s,start:r,end:S,quads:e}=l;if(!e||e.length===0)return[];const u=[],f=S-r,p=e.length,i=f/p,b=t.roughness??1,q=t.bowing??1,m=t.curveFitting??.95,v=t.curveStepCount??9,C=t.maxRandomnessOffset??2,k=t.disableMultiStroke??!1;for(let n=0;n<e.length;n++){const w=e[n],{x:a,y:x,w:M,h:P}=w,c=x+P,$=g.roughLine(a*o,c*o,(a+M)*o,c*o,{roughness:b,bowing:q,seed:g.hashSeed(`${s}-${n}`),curveFitting:m,curveStepCount:v,maxRandomnessOffset:C,disableMultiStroke:k}).map(([O,T])=>[O/o,T/o]),d=r+n*i,E=d+i;u.push({id:`${s}-${n}`,points:$,start:d,end:E,color:t.color||"rgba(0, 0, 255, 0.8)",width:t.width||2,lineCap:t.lineCap||"round"})}return u}exports.default=h;exports.underlineToStrokes=h;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const j=require("./index12.cjs"),F=require("./index28.cjs"),H=require("./index29.cjs"),O=require("./index24.cjs");function x(o){const t=Math.sin(o)*1e4;return(t-Math.floor(t))*2-1}function X(o,t,n){return o.map(([r,c],e)=>[r+x(n+e*2)*t,c+x(n+e*2+1)*t])}function A(o,t,n){return o.map(([r,c])=>[(t+r)*n,c*n])}function C(o,t){const{id:n,start:r,end:c,content:e,x:P,y:T,fontSize:$}=o;if(!e||e.length===0)return[];const g=[],b=c-r,q=$||t.fontSize||16,v=t.roughness??1.5,D=q/O.REFERENCE_HEIGHT;let i=0;const w=e.length,p=b/w;for(let s=0;s<e.length;s++){const z=e[s],h=j.resolveGlyph(z);if(!h){i+=.5+.18;continue}const S=h.width||.5,u=h.paths||[],M=h.pathTiming||"sequential";if(u.length===0){i+=S+.18;continue}const d=r+s*p,R=d+p,_=u.length;for(let a=0;a<u.length;a++){const E=u[a].points||[];if(E.length<2)continue;const k=A(E,i,D),y=v*7e-4,G=F.hashSeed(`${n}-${s}-${a}`),I=X(k,y,G);let l,f;if(M==="parallel")l=d,f=R;else{const m=p/_;l=d+a*m,f=l+m}g.push({id:`${n}-${s}-${a}`,points:I,baseX:P,baseY:T,start:l,end:f,color:H.resolveColor(t,"rgba(220, 20, 60, 1.0)"),width:t.width||2,lineCap:t.lineCap||"round",uniformScale:!0})}i+=S+.18}return g}exports.default=C;exports.textToStrokes=C;
2
2
  //# sourceMappingURL=index15.cjs.map