web-annotation-renderer 0.2.0 → 0.4.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.
- package/ai-tools.js +11 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +49 -30
- package/dist/index.js.map +1 -1
- package/dist/index10.cjs +1 -1
- package/dist/index10.cjs.map +1 -1
- package/dist/index10.js +172 -17
- package/dist/index10.js.map +1 -1
- package/dist/index11.cjs +1 -1
- package/dist/index11.cjs.map +1 -1
- package/dist/index11.js +13 -20
- package/dist/index11.js.map +1 -1
- package/dist/index12.cjs +1 -1
- package/dist/index12.cjs.map +1 -1
- package/dist/index12.js +148 -123
- package/dist/index12.js.map +1 -1
- package/dist/index13.cjs +1 -1
- package/dist/index13.cjs.map +1 -1
- package/dist/index13.js +29 -198
- package/dist/index13.js.map +1 -1
- package/dist/index14.cjs +1 -1
- package/dist/index14.cjs.map +1 -1
- package/dist/index14.js +56 -15
- package/dist/index14.js.map +1 -1
- package/dist/index15.cjs +1 -1
- package/dist/index15.cjs.map +1 -1
- package/dist/index15.js +115 -120
- package/dist/index15.js.map +1 -1
- package/dist/index16.cjs +1 -1
- package/dist/index16.cjs.map +1 -1
- package/dist/index16.js +104 -32
- package/dist/index16.js.map +1 -1
- package/dist/index17.cjs +2 -0
- package/dist/index17.cjs.map +1 -0
- package/dist/index17.js +62 -0
- package/dist/index17.js.map +1 -0
- package/dist/index18.cjs +2 -0
- package/dist/index18.cjs.map +1 -0
- package/dist/index18.js +144 -0
- package/dist/index18.js.map +1 -0
- package/dist/index19.cjs +2 -0
- package/dist/index19.cjs.map +1 -0
- package/dist/index19.js +41 -0
- package/dist/index19.js.map +1 -0
- package/dist/index2.cjs +1 -1
- package/dist/index2.cjs.map +1 -1
- package/dist/index2.js +65 -73
- package/dist/index2.js.map +1 -1
- package/dist/index20.cjs +2 -0
- package/dist/index20.cjs.map +1 -0
- package/dist/index20.js +40 -0
- package/dist/index20.js.map +1 -0
- package/dist/index21.cjs +2 -0
- package/dist/index21.cjs.map +1 -0
- package/dist/index21.js +41 -0
- package/dist/index21.js.map +1 -0
- package/dist/index22.cjs +2 -0
- package/dist/index22.cjs.map +1 -0
- package/dist/index22.js +25 -0
- package/dist/index22.js.map +1 -0
- package/dist/index23.cjs +2 -0
- package/dist/index23.cjs.map +1 -0
- package/dist/index23.js +8 -0
- package/dist/index23.js.map +1 -0
- package/dist/index24.cjs +2 -0
- package/dist/index24.cjs.map +1 -0
- package/dist/index24.js +8 -0
- package/dist/index24.js.map +1 -0
- package/dist/index3.cjs +1 -1
- package/dist/index3.cjs.map +1 -1
- package/dist/index3.js +1 -1
- package/dist/index4.cjs +1 -1
- package/dist/index4.cjs.map +1 -1
- package/dist/index4.js +72 -71
- package/dist/index4.js.map +1 -1
- package/dist/index5.cjs +1 -1
- package/dist/index5.cjs.map +1 -1
- package/dist/index5.js +153 -65
- package/dist/index5.js.map +1 -1
- package/dist/index6.cjs +1 -1
- package/dist/index6.cjs.map +1 -1
- package/dist/index6.js +60 -114
- package/dist/index6.js.map +1 -1
- package/dist/index7.cjs +1 -1
- package/dist/index7.cjs.map +1 -1
- package/dist/index7.js +19 -91
- package/dist/index7.js.map +1 -1
- package/dist/index8.cjs +1 -1
- package/dist/index8.cjs.map +1 -1
- package/dist/index8.js +19 -105
- package/dist/index8.js.map +1 -1
- package/dist/index9.cjs +1 -1
- package/dist/index9.cjs.map +1 -1
- package/dist/index9.js +123 -98
- package/dist/index9.js.map +1 -1
- package/package.json +9 -3
package/dist/index12.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const P=require("react/jsx-runtime"),n=require("react"),j=require("./index2.cjs"),q=require("./index17.cjs");function C({pdfUrl:d,page:s=1,scale:l=1.5,annotations:g=[],currentTime:f=0,strokeConfig:u,onLoad:p,onError:t,onPageChange:w,className:F,style:R,canvasStyle:b}){const h=n.useRef(null),y=n.useRef(null),r=n.useRef(null),A=n.useRef(Promise.resolve()),i=n.useCallback(e=>{A.current=A.current.then(e).catch(c=>{console.error("AnnotPdf: Queued operation failed:",c)})},[]),a=n.useMemo(()=>{if(!u)return;const e=u.preset||"default",c=q.getPreset(e);return{highlight:{color:c.highlight.color,width:u.highlight?.width??c.highlight.width},text:{color:c.handText.color,width:u.text?.width??c.handText.width}}},[u]);n.useEffect(()=>{if(!(!h.current||!y.current)){try{r.current=new j.AnnotationRenderer({canvasElement:h.current,container:y.current,strokeConfig:a})}catch(e){console.error("AnnotPdf: Failed to initialize renderer:",e),t&&t(e)}return()=>{r.current&&(r.current.destroy(),r.current=null)}}},[]),n.useEffect(()=>{if(!r.current||!d)return;let e=!1;return i(async()=>{try{const o=await r.current.loadPDF(d);if(e)return;if(!o.success){console.error("AnnotPdf: Failed to load PDF:",o.error),t&&t(new Error(o.error));return}p&&p({pageCount:o.pageCount})}catch(o){if(e)return;console.error("AnnotPdf: Failed to load PDF:",o),t&&t(o)}}),()=>{e=!0}},[d,i]),n.useEffect(()=>{!r.current||!s||typeof s!="number"||i(async()=>{try{const e=await r.current.setPage(s);if(!e.success){console.error("AnnotPdf: Failed to set page:",e.error),t&&t(new Error(e.error));return}w&&w(s)}catch(e){console.error("AnnotPdf: Failed to set page:",e),t&&t(e)}})},[s,i]),n.useEffect(()=>{!r.current||!l||typeof l!="number"||i(async()=>{try{const e=await r.current.setScale(l);e.success||(console.error("AnnotPdf: Failed to set scale:",e.error),t&&t(new Error(e.error)))}catch(e){console.error("AnnotPdf: Failed to set scale:",e),t&&t(e)}})},[l,i]),n.useEffect(()=>{if(r.current)try{r.current.setAnnotations(g||[])}catch(e){console.error("AnnotPdf: Failed to set annotations:",e),t&&t(e)}},[g]),n.useEffect(()=>{if(!(!r.current||f===void 0||f===null))try{r.current.setTime(f)}catch(e){console.error("AnnotPdf: Failed to set time:",e),t&&t(e)}},[f]);const v=n.useRef(!0);n.useEffect(()=>{if(v.current){v.current=!1;return}if(r.current&&a)try{r.current.updateStrokeConfig(a)}catch(e){console.error("AnnotPdf: Failed to update stroke config:",e),t&&t(e)}},[a]);const m={position:"relative",display:"inline-block",lineHeight:0,...R},x={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"hidden"},S={display:"block",...b};return P.jsxs("div",{className:F,style:m,children:[P.jsx("canvas",{ref:h,style:S}),P.jsx("div",{ref:y,style:x})]})}exports.default=C;
|
|
2
2
|
//# sourceMappingURL=index12.cjs.map
|
package/dist/index12.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index12.cjs","sources":["../src/utils/pdfExtractor.js"],"sourcesContent":["/**\n * PDF Data Extractor - Extract text and image blocks from PDF\n *\n * Uses PDF.js getOperatorList() for efficient metadata extraction without rendering.\n *\n * @module utils/pdfExtractor\n */\n\nimport * as pdfjsLib from \"pdfjs-dist\";\n\n/**\n * Extract text blocks from a PDF page with normalized coordinates\n *\n * @param {PDFPageProxy} page - PDF.js page object\n * @returns {Promise<Array>} Array of text blocks with normalized bounding boxes (0-1 range)\n */\nasync function extractTextBlocks(page) {\n try {\n const textContent = await page.getTextContent();\n const viewport = page.getViewport({ scale: 1.0 });\n\n const pageWidth = viewport.width;\n const pageHeight = viewport.height;\n\n const textBlocks = [];\n\n for (const item of textContent.items) {\n // Skip empty text\n if (!item.str || !item.str.trim()) {\n continue;\n }\n\n // Get transform matrix [a, b, c, d, e, f]\n const transform = item.transform;\n const fontSize = Math.sqrt(transform[2] * transform[2] + transform[3] * transform[3]);\n\n // Calculate bounding box (absolute coordinates)\n const x = transform[4];\n const y = viewport.height - transform[5]; // Convert to top-left origin\n const width = item.width;\n const height = item.height || fontSize;\n\n const x1 = x;\n const y1 = y - height;\n const x2 = x + width;\n const y2 = y;\n\n // Normalize coordinates to 0-1 range\n const bbox_norm = [\n Math.max(0.0, Math.min(1.0, x1 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y1 / pageHeight)),\n Math.max(0.0, Math.min(1.0, x2 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y2 / pageHeight))\n ];\n\n textBlocks.push({\n type: \"text\",\n text: item.str,\n bbox_norm: bbox_norm,\n font: item.fontName || \"unknown\",\n fontSize: fontSize,\n source: \"pdfjs\"\n });\n }\n\n return textBlocks;\n } catch (error) {\n console.error(\"Error extracting text blocks:\", error);\n return [];\n }\n}\n\n/**\n * Extract normalized bounding box from PDF transformation matrix\n *\n * @param {Array} transform - PDF transformation matrix [a, b, c, d, e, f]\n * @param {number} pageWidth - Page width for normalization\n * @param {number} pageHeight - Page height for coordinate conversion and normalization\n * @returns {Array} Normalized bounding box [x1, y1, x2, y2] in 0-1 range\n */\nfunction extractBBoxFromTransform(transform, pageWidth, pageHeight) {\n const x = transform[4];\n const y = transform[5];\n const scaleX = transform[0];\n const scaleY = transform[3];\n\n // Scale factors represent image dimensions\n const width = Math.abs(scaleX);\n const height = Math.abs(scaleY);\n\n // Convert from PDF bottom-left to image top-left origin\n const y1 = pageHeight - y - height;\n const y2 = pageHeight - y;\n const x1 = x;\n const x2 = x + width;\n\n // Normalize to 0-1 range\n return [\n Math.max(0.0, Math.min(1.0, x1 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y1 / pageHeight)),\n Math.max(0.0, Math.min(1.0, x2 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y2 / pageHeight))\n ];\n}\n\n/**\n * Multiply two transformation matrices\n *\n * @param {Array} m1 - First matrix [a, b, c, d, e, f]\n * @param {Array} m2 - Second matrix [a, b, c, d, e, f]\n * @returns {Array} Result matrix [a, b, c, d, e, f]\n */\nfunction multiplyTransforms(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5]\n ];\n}\n\n/**\n * Get human-readable operator name\n *\n * @param {number} op - Operator code\n * @param {Object} OPS - PDF.js OPS constants\n * @returns {string} Operator name\n */\nfunction getOperatorName(op, OPS) {\n const opNames = {\n [OPS.paintImageXObject]: \"paintImageXObject\",\n [OPS.paintInlineImageXObject]: \"paintInlineImageXObject\",\n [OPS.paintImageMaskXObject]: \"paintImageMaskXObject\",\n [OPS.paintJpegXObject]: \"paintJpegXObject\"\n };\n return opNames[op] || \"unknown\";\n}\n\n/**\n * Extract image blocks from a PDF page using getOperatorList with normalized coordinates\n *\n * @param {PDFPageProxy} page - PDF.js page object\n * @returns {Promise<Array>} Array of image blocks with normalized bounding boxes (0-1 range)\n */\nasync function extractImageBlocks(page) {\n try {\n const operatorList = await page.getOperatorList();\n const viewport = page.getViewport({ scale: 1.0 });\n\n const pageWidth = viewport.width;\n const pageHeight = viewport.height;\n\n const imageBlocks = [];\n const graphicsStateStack = []; // Track graphics state transformations\n let currentTransform = [1, 0, 0, 1, 0, 0]; // Identity matrix\n\n const ops = operatorList.fnArray;\n const args = operatorList.argsArray;\n\n // Image paint operator constants from PDF.js\n const OPS = pdfjsLib.OPS;\n const IMAGE_OPS = [\n OPS.paintImageXObject,\n OPS.paintInlineImageXObject,\n OPS.paintImageMaskXObject,\n OPS.paintJpegXObject\n ];\n\n for (let i = 0; i < ops.length; i++) {\n const op = ops[i];\n const arg = args[i];\n\n // Track graphics state stack\n if (op === OPS.save) {\n graphicsStateStack.push([...currentTransform]);\n } else if (op === OPS.restore) {\n if (graphicsStateStack.length > 0) {\n currentTransform = graphicsStateStack.pop();\n }\n } else if (op === OPS.transform) {\n // Update current transformation matrix\n const [a, b, c, d, e, f] = arg;\n currentTransform = multiplyTransforms(currentTransform, [a, b, c, d, e, f]);\n } else if (IMAGE_OPS.includes(op)) {\n // Extract image bounding box (normalized)\n const bbox_norm = extractBBoxFromTransform(currentTransform, pageWidth, pageHeight);\n\n imageBlocks.push({\n type: \"image\",\n bbox_norm: bbox_norm,\n source: \"pdfjs\",\n operator: getOperatorName(op, OPS)\n });\n }\n }\n\n return imageBlocks;\n } catch (error) {\n console.error(\"Error extracting image blocks:\", error);\n return [];\n }\n}\n\n/**\n * Extract all blocks (text and images) from a PDF page\n *\n * @param {string} pdfPath - Path to PDF file\n * @param {number} pageNumber - Page number (1-indexed)\n * @returns {Promise<Object>} Object with textBlocks and imageBlocks arrays\n */\nexport async function extractAllBlocks(pdfPath, pageNumber) {\n try {\n // Load PDF document\n const loadingTask = pdfjsLib.getDocument(pdfPath);\n const pdfDoc = await loadingTask.promise;\n\n // Validate page number\n if (pageNumber < 1 || pageNumber > pdfDoc.numPages) {\n throw new Error(`Invalid page number: ${pageNumber}. Document has ${pdfDoc.numPages} pages.`);\n }\n\n // Get page\n const page = await pdfDoc.getPage(pageNumber);\n const viewport = page.getViewport({ scale: 1.0 });\n\n // Extract text and image blocks in parallel\n const [textBlocks, imageBlocks] = await Promise.all([\n extractTextBlocks(page),\n extractImageBlocks(page)\n ]);\n\n return {\n textBlocks,\n imageBlocks,\n pageDimensions: {\n width: viewport.width,\n height: viewport.height\n },\n pageNumber: pageNumber\n };\n } catch (error) {\n console.error(`Error extracting blocks from page ${pageNumber}:`, error);\n throw error;\n }\n}\n\n/**\n * Extract blocks from multiple pages\n *\n * @param {string} pdfPath - Path to PDF file\n * @param {Array<number>} pageNumbers - Array of page numbers (1-indexed)\n * @returns {Promise<Array>} Array of extraction results, one per page\n */\nexport async function extractMultiplePages(pdfPath, pageNumbers) {\n const results = [];\n\n for (const pageNum of pageNumbers) {\n try {\n const pageData = await extractAllBlocks(pdfPath, pageNum);\n results.push(pageData);\n } catch (error) {\n console.error(`Failed to extract page ${pageNum}:`, error);\n results.push({\n textBlocks: [],\n imageBlocks: [],\n pageDimensions: null,\n pageNumber: pageNum,\n error: error.message\n });\n }\n }\n\n return results;\n}\n"],"names":["extractTextBlocks","page","textContent","viewport","pageWidth","pageHeight","textBlocks","item","transform","fontSize","x","y","width","height","x1","y1","x2","y2","bbox_norm","error","extractBBoxFromTransform","scaleX","scaleY","multiplyTransforms","m1","m2","getOperatorName","op","OPS","extractImageBlocks","operatorList","imageBlocks","graphicsStateStack","currentTransform","ops","args","pdfjsLib","IMAGE_OPS","i","arg","a","b","c","d","e","f","extractAllBlocks","pdfPath","pageNumber","pdfDoc","extractMultiplePages","pageNumbers","results","pageNum","pageData"],"mappings":"wYAgBA,eAAeA,EAAkBC,EAAM,CACrC,GAAI,CACF,MAAMC,EAAc,MAAMD,EAAK,eAAc,EACvCE,EAAWF,EAAK,YAAY,CAAE,MAAO,CAAG,CAAE,EAE1CG,EAAYD,EAAS,MACrBE,EAAaF,EAAS,OAEtBG,EAAa,CAAA,EAEnB,UAAWC,KAAQL,EAAY,MAAO,CAEpC,GAAI,CAACK,EAAK,KAAO,CAACA,EAAK,IAAI,OACzB,SAIF,MAAMC,EAAYD,EAAK,UACjBE,EAAW,KAAK,KAAKD,EAAU,CAAC,EAAIA,EAAU,CAAC,EAAIA,EAAU,CAAC,EAAIA,EAAU,CAAC,CAAC,EAG9EE,EAAIF,EAAU,CAAC,EACfG,EAAIR,EAAS,OAASK,EAAU,CAAC,EACjCI,EAAQL,EAAK,MACbM,EAASN,EAAK,QAAUE,EAExBK,EAAKJ,EACLK,EAAKJ,EAAIE,EACTG,EAAKN,EAAIE,EACTK,EAAKN,EAGLO,EAAY,CAChB,KAAK,IAAI,EAAK,KAAK,IAAI,EAAKJ,EAAKV,CAAS,CAAC,EAC3C,KAAK,IAAI,EAAK,KAAK,IAAI,EAAKW,EAAKV,CAAU,CAAC,EAC5C,KAAK,IAAI,EAAK,KAAK,IAAI,EAAKW,EAAKZ,CAAS,CAAC,EAC3C,KAAK,IAAI,EAAK,KAAK,IAAI,EAAKa,EAAKZ,CAAU,CAAC,CACpD,EAEMC,EAAW,KAAK,CACd,KAAM,OACN,KAAMC,EAAK,IACX,UAAWW,EACX,K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df.jsx"],"sourcesContent":["// ============================================================================\n// SECTION 1: IMPORTS\n// ============================================================================\n\nimport { useRef, useEffect, useCallback, useMemo } from 'react';\nimport { AnnotationRenderer } from '../core/AnnotationRenderer.js';\nimport { getPreset } from '../pen/presets.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\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 * @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\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\n * @param {string} [props.strokeConfig.preset] - Preset name: 'default', 'blue', 'minimal'\n * @param {Object} [props.strokeConfig.highlight] - Highlight style overrides\n * @param {number} [props.strokeConfig.highlight.width] - Highlight stroke width (16-32)\n * @param {Object} [props.strokeConfig.text] - Text style overrides\n * @param {number} [props.strokeConfig.text.width] - Text stroke width (1-4)\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 // 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 // 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 4.6: STROKE CONFIG BUILDER\n // ==========================================================================\n\n /**\n * Build merged stroke config from preset and overrides\n *\n * If strokeConfig.preset is provided, loads base config from presets.\n * Then merges any override values (highlight.width, text.width).\n */\n const mergedStrokeConfig = useMemo(() => {\n if (!strokeConfig) {\n return undefined;\n }\n\n // Start with preset or empty object\n const presetName = strokeConfig.preset || 'default';\n const presetConfig = getPreset(presetName);\n\n // Build config object matching StrokeRenderer format\n const config = {\n highlight: {\n color: presetConfig.highlight.color,\n width: strokeConfig.highlight?.width ?? presetConfig.highlight.width\n },\n text: {\n color: presetConfig.handText.color,\n width: strokeConfig.text?.width ?? presetConfig.handText.width\n }\n };\n\n return config;\n }, [strokeConfig]);\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: mergedStrokeConfig\n });\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 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: Engine must exist and pdfUrl must be valid\n if (!engineRef.current || !pdfUrl) {\n return;\n }\n\n let cancelled = false;\n\n const loadPdf = async () => {\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, 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: Engine must exist and page must be valid\n if (!engineRef.current || !page || typeof page !== 'number') {\n return;\n }\n\n // Queue the page change operation to prevent race conditions\n queueOperation(async () => {\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 // 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, 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: Engine must exist and scale must be valid\n if (!engineRef.current || !scale || typeof scale !== 'number') {\n return;\n }\n\n // Queue the scale change operation to prevent race conditions\n queueOperation(async () => {\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, queueOperation]);\n\n // ==========================================================================\n // SECTION 9: ANNOTATIONS SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync annotations prop to engine.setAnnotations() method\n */\n useEffect(() => {\n // Guard: Engine must exist\n if (!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]);\n\n // ==========================================================================\n // SECTION 10: TIMELINE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync currentTime prop to engine.setTime() method\n */\n useEffect(() => {\n // Guard: Engine must exist and currentTime must be defined\n if (!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]);\n\n // ==========================================================================\n // SECTION 10.5: STROKE CONFIG SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync strokeConfig prop to engine at runtime for live preview\n * Skips initial render (handled by initialization)\n */\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n // Skip first render - config is passed during initialization\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n // Guard: Engine must exist\n if (!engineRef.current) {\n return;\n }\n\n // Update stroke config if provided\n if (mergedStrokeConfig) {\n try {\n engineRef.current.updateStrokeConfig(mergedStrokeConfig);\n } catch (error) {\n console.error('AnnotPdf: Failed to update stroke config:', error);\n if (onError) {\n onError(error);\n }\n }\n }\n }, [mergedStrokeConfig]);\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","strokeConfig","onLoad","onError","onPageChange","className","style","canvasStyle","canvasRef","useRef","layerContainerRef","engineRef","renderQueue","queueOperation","useCallback","operation","error","mergedStrokeConfig","useMemo","presetName","presetConfig","getPreset","useEffect","AnnotationRenderer","cancelled","result","isFirstRender","defaultContainerStyle","defaultLayerStyle","defaultCanvasStyle","jsxs","jsx"],"mappings":"yNAmFA,SAASA,EAAS,CAEhB,OAAAC,EAGA,KAAAC,EAAO,EACP,MAAAC,EAAQ,IACR,YAAAC,EAAc,CAAA,EACd,YAAAC,EAAc,EAGd,aAAAC,EAGA,OAAAC,EACA,QAAAC,EACA,aAAAC,EAGA,UAAAC,EACA,MAAAC,EACA,YAAAC,CACF,EAAG,CAUD,MAAMC,EAAYC,EAAAA,OAAO,IAAI,EAMvBC,EAAoBD,EAAAA,OAAO,IAAI,EAO/B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,132 +1,157 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
[t.paintInlineImageXObject]: "paintInlineImageXObject",
|
|
51
|
-
[t.paintImageMaskXObject]: "paintImageMaskXObject",
|
|
52
|
-
[t.paintJpegXObject]: "paintJpegXObject"
|
|
53
|
-
}[e] || "unknown";
|
|
54
|
-
}
|
|
55
|
-
async function X(e) {
|
|
56
|
-
try {
|
|
57
|
-
const t = await e.getOperatorList(), o = e.getViewport({ scale: 1 }), s = o.width, n = o.height, i = [], r = [];
|
|
58
|
-
let a = [1, 0, 0, 1, 0, 0];
|
|
59
|
-
const g = t.fnArray, l = t.argsArray, c = w.OPS, x = [
|
|
60
|
-
c.paintImageXObject,
|
|
61
|
-
c.paintInlineImageXObject,
|
|
62
|
-
c.paintImageMaskXObject,
|
|
63
|
-
c.paintJpegXObject
|
|
64
|
-
];
|
|
65
|
-
for (let h = 0; h < g.length; h++) {
|
|
66
|
-
const p = g[h], f = l[h];
|
|
67
|
-
if (p === c.save)
|
|
68
|
-
r.push([...a]);
|
|
69
|
-
else if (p === c.restore)
|
|
70
|
-
r.length > 0 && (a = r.pop());
|
|
71
|
-
else if (p === c.transform) {
|
|
72
|
-
const [u, m, b, M, k, y] = f;
|
|
73
|
-
a = I(a, [u, m, b, M, k, y]);
|
|
74
|
-
} else if (x.includes(p)) {
|
|
75
|
-
const u = j(a, s, n);
|
|
76
|
-
i.push({
|
|
77
|
-
type: "image",
|
|
78
|
-
bbox_norm: u,
|
|
79
|
-
source: "pdfjs",
|
|
80
|
-
operator: O(p, c)
|
|
1
|
+
import { jsxs as k, jsx as F } from "react/jsx-runtime";
|
|
2
|
+
import { useRef as u, useCallback as D, useMemo as j, useEffect as i } from "react";
|
|
3
|
+
import { AnnotationRenderer as Q } from "./index2.js";
|
|
4
|
+
import { getPreset as q } from "./index17.js";
|
|
5
|
+
function O({
|
|
6
|
+
// Required props
|
|
7
|
+
pdfUrl: h,
|
|
8
|
+
// Optional props with defaults
|
|
9
|
+
page: s = 1,
|
|
10
|
+
scale: a = 1.5,
|
|
11
|
+
annotations: p = [],
|
|
12
|
+
currentTime: f = 0,
|
|
13
|
+
// Stroke configuration
|
|
14
|
+
strokeConfig: l,
|
|
15
|
+
// Callbacks
|
|
16
|
+
onLoad: g,
|
|
17
|
+
onError: t,
|
|
18
|
+
onPageChange: w,
|
|
19
|
+
// Styling
|
|
20
|
+
className: v,
|
|
21
|
+
style: x,
|
|
22
|
+
canvasStyle: b
|
|
23
|
+
}) {
|
|
24
|
+
const y = u(null), P = u(null), r = u(null), m = u(Promise.resolve()), c = D((e) => {
|
|
25
|
+
m.current = m.current.then(e).catch((o) => {
|
|
26
|
+
console.error("AnnotPdf: Queued operation failed:", o);
|
|
27
|
+
});
|
|
28
|
+
}, []), d = j(() => {
|
|
29
|
+
if (!l)
|
|
30
|
+
return;
|
|
31
|
+
const e = l.preset || "default", o = q(e);
|
|
32
|
+
return {
|
|
33
|
+
highlight: {
|
|
34
|
+
color: o.highlight.color,
|
|
35
|
+
width: l.highlight?.width ?? o.highlight.width
|
|
36
|
+
},
|
|
37
|
+
text: {
|
|
38
|
+
color: o.handText.color,
|
|
39
|
+
width: l.text?.width ?? o.handText.width
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}, [l]);
|
|
43
|
+
i(() => {
|
|
44
|
+
if (!(!y.current || !P.current)) {
|
|
45
|
+
try {
|
|
46
|
+
r.current = new Q({
|
|
47
|
+
canvasElement: y.current,
|
|
48
|
+
container: P.current,
|
|
49
|
+
strokeConfig: d
|
|
81
50
|
});
|
|
51
|
+
} catch (e) {
|
|
52
|
+
console.error("AnnotPdf: Failed to initialize renderer:", e), t && t(e);
|
|
82
53
|
}
|
|
54
|
+
return () => {
|
|
55
|
+
r.current && (r.current.destroy(), r.current = null);
|
|
56
|
+
};
|
|
83
57
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
height: i.height
|
|
104
|
-
},
|
|
105
|
-
pageNumber: t
|
|
58
|
+
}, []), i(() => {
|
|
59
|
+
if (!r.current || !h)
|
|
60
|
+
return;
|
|
61
|
+
let e = !1;
|
|
62
|
+
return c(async () => {
|
|
63
|
+
try {
|
|
64
|
+
const n = await r.current.loadPDF(h);
|
|
65
|
+
if (e) return;
|
|
66
|
+
if (!n.success) {
|
|
67
|
+
console.error("AnnotPdf: Failed to load PDF:", n.error), t && t(new Error(n.error));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
g && g({ pageCount: n.pageCount });
|
|
71
|
+
} catch (n) {
|
|
72
|
+
if (e) return;
|
|
73
|
+
console.error("AnnotPdf: Failed to load PDF:", n), t && t(n);
|
|
74
|
+
}
|
|
75
|
+
}), () => {
|
|
76
|
+
e = !0;
|
|
106
77
|
};
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
78
|
+
}, [h, c]), i(() => {
|
|
79
|
+
!r.current || !s || typeof s != "number" || c(async () => {
|
|
80
|
+
try {
|
|
81
|
+
const e = await r.current.setPage(s);
|
|
82
|
+
if (!e.success) {
|
|
83
|
+
console.error("AnnotPdf: Failed to set page:", e.error), t && t(new Error(e.error));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
w && w(s);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
console.error("AnnotPdf: Failed to set page:", e), t && t(e);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}, [s, c]), i(() => {
|
|
92
|
+
!r.current || !a || typeof a != "number" || c(async () => {
|
|
93
|
+
try {
|
|
94
|
+
const e = await r.current.setScale(a);
|
|
95
|
+
e.success || (console.error("AnnotPdf: Failed to set scale:", e.error), t && t(new Error(e.error)));
|
|
96
|
+
} catch (e) {
|
|
97
|
+
console.error("AnnotPdf: Failed to set scale:", e), t && t(e);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}, [a, c]), i(() => {
|
|
101
|
+
if (r.current)
|
|
102
|
+
try {
|
|
103
|
+
r.current.setAnnotations(p || []);
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.error("AnnotPdf: Failed to set annotations:", e), t && t(e);
|
|
106
|
+
}
|
|
107
|
+
}, [p]), i(() => {
|
|
108
|
+
if (!(!r.current || f === void 0 || f === null))
|
|
109
|
+
try {
|
|
110
|
+
r.current.setTime(f);
|
|
111
|
+
} catch (e) {
|
|
112
|
+
console.error("AnnotPdf: Failed to set time:", e), t && t(e);
|
|
113
|
+
}
|
|
114
|
+
}, [f]);
|
|
115
|
+
const A = u(!0);
|
|
116
|
+
i(() => {
|
|
117
|
+
if (A.current) {
|
|
118
|
+
A.current = !1;
|
|
119
|
+
return;
|
|
125
120
|
}
|
|
126
|
-
|
|
121
|
+
if (r.current && d)
|
|
122
|
+
try {
|
|
123
|
+
r.current.updateStrokeConfig(d);
|
|
124
|
+
} catch (e) {
|
|
125
|
+
console.error("AnnotPdf: Failed to update stroke config:", e), t && t(e);
|
|
126
|
+
}
|
|
127
|
+
}, [d]);
|
|
128
|
+
const R = {
|
|
129
|
+
position: "relative",
|
|
130
|
+
display: "inline-block",
|
|
131
|
+
lineHeight: 0,
|
|
132
|
+
// Remove extra space below canvas
|
|
133
|
+
...x
|
|
134
|
+
// User styles override defaults
|
|
135
|
+
}, S = {
|
|
136
|
+
position: "absolute",
|
|
137
|
+
top: 0,
|
|
138
|
+
left: 0,
|
|
139
|
+
width: "100%",
|
|
140
|
+
height: "100%",
|
|
141
|
+
pointerEvents: "none",
|
|
142
|
+
// Allow clicks to pass through to canvas
|
|
143
|
+
overflow: "hidden"
|
|
144
|
+
}, C = {
|
|
145
|
+
display: "block",
|
|
146
|
+
...b
|
|
147
|
+
// User styles override defaults
|
|
148
|
+
};
|
|
149
|
+
return /* @__PURE__ */ k("div", { className: v, style: R, children: [
|
|
150
|
+
/* @__PURE__ */ F("canvas", { ref: y, style: C }),
|
|
151
|
+
/* @__PURE__ */ F("div", { ref: P, style: S })
|
|
152
|
+
] });
|
|
127
153
|
}
|
|
128
154
|
export {
|
|
129
|
-
|
|
130
|
-
T as extractMultiplePages
|
|
155
|
+
O as default
|
|
131
156
|
};
|
|
132
157
|
//# sourceMappingURL=index12.js.map
|
package/dist/index12.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index12.js","sources":["../src/utils/pdfExtractor.js"],"sourcesContent":["/**\n * PDF Data Extractor - Extract text and image blocks from PDF\n *\n * Uses PDF.js getOperatorList() for efficient metadata extraction without rendering.\n *\n * @module utils/pdfExtractor\n */\n\nimport * as pdfjsLib from \"pdfjs-dist\";\n\n/**\n * Extract text blocks from a PDF page with normalized coordinates\n *\n * @param {PDFPageProxy} page - PDF.js page object\n * @returns {Promise<Array>} Array of text blocks with normalized bounding boxes (0-1 range)\n */\nasync function extractTextBlocks(page) {\n try {\n const textContent = await page.getTextContent();\n const viewport = page.getViewport({ scale: 1.0 });\n\n const pageWidth = viewport.width;\n const pageHeight = viewport.height;\n\n const textBlocks = [];\n\n for (const item of textContent.items) {\n // Skip empty text\n if (!item.str || !item.str.trim()) {\n continue;\n }\n\n // Get transform matrix [a, b, c, d, e, f]\n const transform = item.transform;\n const fontSize = Math.sqrt(transform[2] * transform[2] + transform[3] * transform[3]);\n\n // Calculate bounding box (absolute coordinates)\n const x = transform[4];\n const y = viewport.height - transform[5]; // Convert to top-left origin\n const width = item.width;\n const height = item.height || fontSize;\n\n const x1 = x;\n const y1 = y - height;\n const x2 = x + width;\n const y2 = y;\n\n // Normalize coordinates to 0-1 range\n const bbox_norm = [\n Math.max(0.0, Math.min(1.0, x1 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y1 / pageHeight)),\n Math.max(0.0, Math.min(1.0, x2 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y2 / pageHeight))\n ];\n\n textBlocks.push({\n type: \"text\",\n text: item.str,\n bbox_norm: bbox_norm,\n font: item.fontName || \"unknown\",\n fontSize: fontSize,\n source: \"pdfjs\"\n });\n }\n\n return textBlocks;\n } catch (error) {\n console.error(\"Error extracting text blocks:\", error);\n return [];\n }\n}\n\n/**\n * Extract normalized bounding box from PDF transformation matrix\n *\n * @param {Array} transform - PDF transformation matrix [a, b, c, d, e, f]\n * @param {number} pageWidth - Page width for normalization\n * @param {number} pageHeight - Page height for coordinate conversion and normalization\n * @returns {Array} Normalized bounding box [x1, y1, x2, y2] in 0-1 range\n */\nfunction extractBBoxFromTransform(transform, pageWidth, pageHeight) {\n const x = transform[4];\n const y = transform[5];\n const scaleX = transform[0];\n const scaleY = transform[3];\n\n // Scale factors represent image dimensions\n const width = Math.abs(scaleX);\n const height = Math.abs(scaleY);\n\n // Convert from PDF bottom-left to image top-left origin\n const y1 = pageHeight - y - height;\n const y2 = pageHeight - y;\n const x1 = x;\n const x2 = x + width;\n\n // Normalize to 0-1 range\n return [\n Math.max(0.0, Math.min(1.0, x1 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y1 / pageHeight)),\n Math.max(0.0, Math.min(1.0, x2 / pageWidth)),\n Math.max(0.0, Math.min(1.0, y2 / pageHeight))\n ];\n}\n\n/**\n * Multiply two transformation matrices\n *\n * @param {Array} m1 - First matrix [a, b, c, d, e, f]\n * @param {Array} m2 - Second matrix [a, b, c, d, e, f]\n * @returns {Array} Result matrix [a, b, c, d, e, f]\n */\nfunction multiplyTransforms(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5]\n ];\n}\n\n/**\n * Get human-readable operator name\n *\n * @param {number} op - Operator code\n * @param {Object} OPS - PDF.js OPS constants\n * @returns {string} Operator name\n */\nfunction getOperatorName(op, OPS) {\n const opNames = {\n [OPS.paintImageXObject]: \"paintImageXObject\",\n [OPS.paintInlineImageXObject]: \"paintInlineImageXObject\",\n [OPS.paintImageMaskXObject]: \"paintImageMaskXObject\",\n [OPS.paintJpegXObject]: \"paintJpegXObject\"\n };\n return opNames[op] || \"unknown\";\n}\n\n/**\n * Extract image blocks from a PDF page using getOperatorList with normalized coordinates\n *\n * @param {PDFPageProxy} page - PDF.js page object\n * @returns {Promise<Array>} Array of image blocks with normalized bounding boxes (0-1 range)\n */\nasync function extractImageBlocks(page) {\n try {\n const operatorList = await page.getOperatorList();\n const viewport = page.getViewport({ scale: 1.0 });\n\n const pageWidth = viewport.width;\n const pageHeight = viewport.height;\n\n const imageBlocks = [];\n const graphicsStateStack = []; // Track graphics state transformations\n let currentTransform = [1, 0, 0, 1, 0, 0]; // Identity matrix\n\n const ops = operatorList.fnArray;\n const args = operatorList.argsArray;\n\n // Image paint operator constants from PDF.js\n const OPS = pdfjsLib.OPS;\n const IMAGE_OPS = [\n OPS.paintImageXObject,\n OPS.paintInlineImageXObject,\n OPS.paintImageMaskXObject,\n OPS.paintJpegXObject\n ];\n\n for (let i = 0; i < ops.length; i++) {\n const op = ops[i];\n const arg = args[i];\n\n // Track graphics state stack\n if (op === OPS.save) {\n graphicsStateStack.push([...currentTransform]);\n } else if (op === OPS.restore) {\n if (graphicsStateStack.length > 0) {\n currentTransform = graphicsStateStack.pop();\n }\n } else if (op === OPS.transform) {\n // Update current transformation matrix\n const [a, b, c, d, e, f] = arg;\n currentTransform = multiplyTransforms(currentTransform, [a, b, c, d, e, f]);\n } else if (IMAGE_OPS.includes(op)) {\n // Extract image bounding box (normalized)\n const bbox_norm = extractBBoxFromTransform(currentTransform, pageWidth, pageHeight);\n\n imageBlocks.push({\n type: \"image\",\n bbox_norm: bbox_norm,\n source: \"pdfjs\",\n operator: getOperatorName(op, OPS)\n });\n }\n }\n\n return imageBlocks;\n } catch (error) {\n console.error(\"Error extracting image blocks:\", error);\n return [];\n }\n}\n\n/**\n * Extract all blocks (text and images) from a PDF page\n *\n * @param {string} pdfPath - Path to PDF file\n * @param {number} pageNumber - Page number (1-indexed)\n * @returns {Promise<Object>} Object with textBlocks and imageBlocks arrays\n */\nexport async function extractAllBlocks(pdfPath, pageNumber) {\n try {\n // Load PDF document\n const loadingTask = pdfjsLib.getDocument(pdfPath);\n const pdfDoc = await loadingTask.promise;\n\n // Validate page number\n if (pageNumber < 1 || pageNumber > pdfDoc.numPages) {\n throw new Error(`Invalid page number: ${pageNumber}. Document has ${pdfDoc.numPages} pages.`);\n }\n\n // Get page\n const page = await pdfDoc.getPage(pageNumber);\n const viewport = page.getViewport({ scale: 1.0 });\n\n // Extract text and image blocks in parallel\n const [textBlocks, imageBlocks] = await Promise.all([\n extractTextBlocks(page),\n extractImageBlocks(page)\n ]);\n\n return {\n textBlocks,\n imageBlocks,\n pageDimensions: {\n width: viewport.width,\n height: viewport.height\n },\n pageNumber: pageNumber\n };\n } catch (error) {\n console.error(`Error extracting blocks from page ${pageNumber}:`, error);\n throw error;\n }\n}\n\n/**\n * Extract blocks from multiple pages\n *\n * @param {string} pdfPath - Path to PDF file\n * @param {Array<number>} pageNumbers - Array of page numbers (1-indexed)\n * @returns {Promise<Array>} Array of extraction results, one per page\n */\nexport async function extractMultiplePages(pdfPath, pageNumbers) {\n const results = [];\n\n for (const pageNum of pageNumbers) {\n try {\n const pageData = await extractAllBlocks(pdfPath, pageNum);\n results.push(pageData);\n } catch (error) {\n console.error(`Failed to extract page ${pageNum}:`, error);\n results.push({\n textBlocks: [],\n imageBlocks: [],\n pageDimensions: null,\n pageNumber: pageNum,\n error: error.message\n });\n }\n }\n\n return results;\n}\n"],"names":["extractTextBlocks","page","textContent","viewport","pageWidth","pageHeight","textBlocks","item","transform","fontSize","x","y","width","height","x1","y1","x2","y2","bbox_norm","error","extractBBoxFromTransform","scaleX","scaleY","multiplyTransforms","m1","m2","getOperatorName","op","OPS","extractImageBlocks","operatorList","imageBlocks","graphicsStateStack","currentTransform","ops","args","pdfjsLib","IMAGE_OPS","i","arg","a","b","c","d","e","f","extractAllBlocks","pdfPath","pageNumber","pdfDoc","extractMultiplePages","pageNumbers","results","pageNum","pageData"],"mappings":";AAgBA,eAAeA,EAAkBC,GAAM;AACrC,MAAI;AACF,UAAMC,IAAc,MAAMD,EAAK,eAAc,GACvCE,IAAWF,EAAK,YAAY,EAAE,OAAO,EAAG,CAAE,GAE1CG,IAAYD,EAAS,OACrBE,IAAaF,EAAS,QAEtBG,IAAa,CAAA;AAEnB,eAAWC,KAAQL,EAAY,OAAO;AAEpC,UAAI,CAACK,EAAK,OAAO,CAACA,EAAK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S,MADKb,EAAS,YAAYW,CAAO,EACf;AAGjC,QAAIC,IAAa,KAAKA,IAAaC,EAAO;AACxC,YAAM,IAAI,MAAM,wBAAwBD,CAAU,kBAAkBC,EAAO,QAAQ,SAAS;AAI9F,UAAMhD,IAAO,MAAMgD,EAAO,QAAQD,CAAU,GACtC7C,IAAWF,EAAK,YAAY,EAAE,OAAO,EAAG,CAAE,GAG1C,CAACK,GAAYyB,CAAW,IAAI,MAAM,QAAQ,IAAI;AAAA,MAClD/B,EAAkBC,CAAI;AAAA,MACtB4B,EAAmB5B,CAAI;AAAA,IAC7B,CAAK;AAED,WAAO;AAAA,MACL,YAAAK;AAAA,MACA,aAAAyB;AAAA,MACA,gBAAgB;AAAA,QACd,OAAO5B,EAAS;AAAA,QAChB,QAAQA,EAAS;AAAA,MACzB;AAAA,MACM,YAAY6C;AAAA,IAClB;AAAA,EACE,SAAS7B,GAAO;AACd,kBAAQ,MAAM,qCAAqC6B,CAAU,KAAK7B,CAAK,GACjEA;AAAA,EACR;AACF;AASO,eAAe+B,EAAqBH,GAASI,GAAa;AAC/D,QAAMC,IAAU,CAAA;AAEhB,aAAWC,KAAWF;AACpB,QAAI;AACF,YAAMG,IAAW,MAAMR,EAAiBC,GAASM,CAAO;AACxD,MAAAD,EAAQ,KAAKE,CAAQ;AAAA,IACvB,SAASnC,GAAO;AACd,cAAQ,MAAM,0BAA0BkC,CAAO,KAAKlC,CAAK,GACzDiC,EAAQ,KAAK;AAAA,QACX,YAAY,CAAA;AAAA,QACZ,aAAa,CAAA;AAAA,QACb,gBAAgB;AAAA,QAChB,YAAYC;AAAA,QACZ,OAAOlC,EAAM;AAAA,MACrB,CAAO;AAAA,IACH;AAGF,SAAOiC;AACT;"}
|
|
1
|
+
{"version":3,"file":"index12.js","sources":["../src/adapters/AnnotPdf.jsx"],"sourcesContent":["// ============================================================================\n// SECTION 1: IMPORTS\n// ============================================================================\n\nimport { useRef, useEffect, useCallback, useMemo } from 'react';\nimport { AnnotationRenderer } from '../core/AnnotationRenderer.js';\nimport { getPreset } from '../pen/presets.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\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 * @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\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\n * @param {string} [props.strokeConfig.preset] - Preset name: 'default', 'blue', 'minimal'\n * @param {Object} [props.strokeConfig.highlight] - Highlight style overrides\n * @param {number} [props.strokeConfig.highlight.width] - Highlight stroke width (16-32)\n * @param {Object} [props.strokeConfig.text] - Text style overrides\n * @param {number} [props.strokeConfig.text.width] - Text stroke width (1-4)\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 // 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 // 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 4.6: STROKE CONFIG BUILDER\n // ==========================================================================\n\n /**\n * Build merged stroke config from preset and overrides\n *\n * If strokeConfig.preset is provided, loads base config from presets.\n * Then merges any override values (highlight.width, text.width).\n */\n const mergedStrokeConfig = useMemo(() => {\n if (!strokeConfig) {\n return undefined;\n }\n\n // Start with preset or empty object\n const presetName = strokeConfig.preset || 'default';\n const presetConfig = getPreset(presetName);\n\n // Build config object matching StrokeRenderer format\n const config = {\n highlight: {\n color: presetConfig.highlight.color,\n width: strokeConfig.highlight?.width ?? presetConfig.highlight.width\n },\n text: {\n color: presetConfig.handText.color,\n width: strokeConfig.text?.width ?? presetConfig.handText.width\n }\n };\n\n return config;\n }, [strokeConfig]);\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: mergedStrokeConfig\n });\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 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: Engine must exist and pdfUrl must be valid\n if (!engineRef.current || !pdfUrl) {\n return;\n }\n\n let cancelled = false;\n\n const loadPdf = async () => {\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, 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: Engine must exist and page must be valid\n if (!engineRef.current || !page || typeof page !== 'number') {\n return;\n }\n\n // Queue the page change operation to prevent race conditions\n queueOperation(async () => {\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 // 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, 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: Engine must exist and scale must be valid\n if (!engineRef.current || !scale || typeof scale !== 'number') {\n return;\n }\n\n // Queue the scale change operation to prevent race conditions\n queueOperation(async () => {\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, queueOperation]);\n\n // ==========================================================================\n // SECTION 9: ANNOTATIONS SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync annotations prop to engine.setAnnotations() method\n */\n useEffect(() => {\n // Guard: Engine must exist\n if (!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]);\n\n // ==========================================================================\n // SECTION 10: TIMELINE SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync currentTime prop to engine.setTime() method\n */\n useEffect(() => {\n // Guard: Engine must exist and currentTime must be defined\n if (!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]);\n\n // ==========================================================================\n // SECTION 10.5: STROKE CONFIG SYNCHRONIZATION\n // ==========================================================================\n\n /**\n * Sync strokeConfig prop to engine at runtime for live preview\n * Skips initial render (handled by initialization)\n */\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n // Skip first render - config is passed during initialization\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n // Guard: Engine must exist\n if (!engineRef.current) {\n return;\n }\n\n // Update stroke config if provided\n if (mergedStrokeConfig) {\n try {\n engineRef.current.updateStrokeConfig(mergedStrokeConfig);\n } catch (error) {\n console.error('AnnotPdf: Failed to update stroke config:', error);\n if (onError) {\n onError(error);\n }\n }\n }\n }, [mergedStrokeConfig]);\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","strokeConfig","onLoad","onError","onPageChange","className","style","canvasStyle","canvasRef","useRef","layerContainerRef","engineRef","renderQueue","queueOperation","useCallback","operation","error","mergedStrokeConfig","useMemo","presetName","presetConfig","getPreset","useEffect","AnnotationRenderer","cancelled","result","isFirstRender","defaultContainerStyle","defaultLayerStyle","defaultCanvasStyle","jsxs","jsx"],"mappings":";;;;AAmFA,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,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,GA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OAAO;AAAA,IACP,QAAQ;AAAA,IACR,eAAe;AAAA;AAAA,IACf,UAAU;AAAA,EAAA,GAONC,IAAqB;AAAA,IACzB,SAAS;AAAA,IACT,GAAGtB;AAAA;AAAA,EAAA;AAOL,SACE,gBAAAuB,EAAC,OAAA,EAAI,WAAAzB,GAAsB,OAAOsB,GAChC,UAAA;AAAA,IAAA,gBAAAI,EAAC,UAAA,EAAO,KAAKvB,GAAW,OAAOqB,GAAoB;AAAA,IACnD,gBAAAE,EAAC,OAAA,EAAI,KAAKrB,GAAmB,OAAOkB,EAAA,CAAmB;AAAA,EAAA,GACzD;AAEJ;"}
|
package/dist/index13.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("./index6.cjs");function h(g,t){const{id:o,start:u,end:f,quads:r}=g;if(!r||r.length===0)return[];const s=[],q=f-u,S=r.length,i=q/S;for(let e=0;e<r.length;e++){const b=r[e],{x:a,y:C,w:$,h:j}=b,d=C+j/2;let n=[[a,d],[a+$,d]];t.jitter?.amplitude>0&&(n=p.applyJitter(n,t.jitter,`${o}-${e}`));let c=null;(t.pressure?.taperIn>0||t.pressure?.taperOut>0)&&(c=p.applyPressure(n,t.pressure));const l=u+e*i,k=l+i;s.push({id:`${o}-${e}`,points:n,start:l,end:k,color:t.color||"rgba(255, 255, 0, 0.3)",width:t.width||24,lineCap:t.lineCap||"butt",pressures:c})}return s}exports.default=h;exports.highlightToStrokes=h;
|
|
2
2
|
//# sourceMappingURL=index13.cjs.map
|
package/dist/index13.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index13.cjs","sources":["../src/types/validators.js"],"sourcesContent":["/**\n * Annotation Data Normalization Utilities\n *\n * This module provides defensive normalization functions that validate and fix\n * annotation data. Invalid values are replaced with safe defaults and warnings\n * are collected for user feedback.\n *\n * @module types/validators\n */\n\nimport {\n BASE_DEFAULTS,\n HIGHLIGHT_DEFAULTS,\n TEXT_DEFAULTS,\n INK_DEFAULTS\n} from './defaults.js';\n\n// ============================================================================\n// FIELD-LEVEL NORMALIZERS\n// ============================================================================\n\n/**\n * Normalize coordinate value to 0-1 range\n *\n * Validates that a value is a number in the 0-1 range. Out-of-range values\n * are clamped. Invalid values use the provided default.\n *\n * @param {*} value - Value to normalize\n * @param {number} defaultValue - Fallback value if invalid\n * @param {string} id - Annotation ID for warning messages\n * @param {string} fieldName - Field name for warning messages\n * @param {Array<string>} warnings - Array to collect warning messages\n * @returns {number} Normalized coordinate value in range [0, 1]\n *\n * @example\n * normalizeCoordinate(0.5, 0.1, 'txt-1', 'x', warnings) // Returns: 0.5\n * normalizeCoordinate(5, 0.1, 'txt-1', 'x', warnings) // Returns: 1, adds warning\n * normalizeCoordinate('abc', 0.1, 'txt-1', 'x', warnings) // Returns: 0.1, adds warning\n */\nexport function normalizeCoordinate(value, defaultValue, id, fieldName, warnings) {\n // Type coercion: parse string to number if needed\n let numValue = value;\n if (typeof value === 'string') {\n numValue = parseFloat(value);\n if (!isNaN(numValue) && numValue === value) {\n // Successfully parsed - no warning needed\n }\n }\n\n // Validate is valid number\n if (typeof numValue !== 'number' || isNaN(numValue)) {\n warnings.push(\n `[${id}]: Field \"${fieldName}\" invalid value \"${value}\", using default ${defaultValue}`\n );\n return defaultValue;\n }\n\n // Range check: clamp to [0, 1]\n if (numValue < 0) {\n warnings.push(\n `[${id}]: Field \"${fieldName}\" value ${numValue} below range [0,1], clamping to 0`\n );\n return 0;\n }\n\n if (numValue > 1) {\n warnings.push(\n `[${id}]: Field \"${fieldName}\" value ${numValue} exceeds range [0,1], clamping to 1`\n );\n return 1;\n }\n\n // Valid value\n return numValue;\n}\n\n/**\n * Normalize color string\n *\n * Validates that a value is a valid color string. Supports hex, rgb/rgba,\n * and named colors. Invalid colors use the provided default.\n *\n * @param {*} value - Color value to normalize\n * @param {string} defaultValue - Fallback color if invalid\n * @param {string} id - Annotation ID for warning messages\n * @param {Array<string>} warnings - Array to collect warning messages\n * @returns {string} Valid color string\n *\n * @example\n * normalizeColor('#fff', '#000', 'txt-1', warnings) // Returns: '#fff'\n * normalizeColor('rgba(255,0,0,0.5)', '#000', 'txt-1', warnings) // Returns: 'rgba(255,0,0,0.5)'\n * normalizeColor('notacolor', '#000', 'txt-1', warnings) // Returns: '#000', adds warning\n */\nexport function normalizeColor(value, defaultValue, id, warnings) {\n // Type check: must be non-empty string\n if (typeof value !== 'string' || value.trim().length === 0) {\n warnings.push(\n `[${id}]: Invalid color format \"${value}\", using default ${defaultValue}`\n );\n return defaultValue;\n }\n\n const trimmed = value.trim();\n\n // Regex patterns for color validation (cached at module level)\n const hexPattern = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;\n const rgbPattern = /^rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+\\s*(,\\s*[\\d.]+\\s*)?\\)$/;\n\n // Named colors (basic set)\n const namedColors = [\n 'red', 'blue', 'green', 'yellow', 'black', 'white', 'gray',\n 'grey', 'orange', 'purple', 'pink', 'brown', 'transparent'\n ];\n\n // Validate format\n const isHex = hexPattern.test(trimmed);\n const isRgb = rgbPattern.test(trimmed);\n const isNamed = namedColors.includes(trimmed.toLowerCase());\n\n if (isHex || isRgb || isNamed) {\n return trimmed;\n }\n\n // Invalid format\n warnings.push(\n `[${id}]: Invalid color format \"${value}\", using default ${defaultValue}`\n );\n return defaultValue;\n}\n\n/**\n * Normalize positive number\n *\n * Validates that a value is a positive number. Invalid values use the\n * provided default.\n *\n * @param {*} value - Value to normalize\n * @param {number} defaultValue - Fallback value if invalid\n * @param {string} id - Annotation ID for warning messages\n * @param {string} fieldName - Field name for warning messages\n * @param {Array<string>} warnings - Array to collect warning messages\n * @returns {number} Positive number\n *\n * @example\n * normalizePositiveNumber(5, 3, 'ink-1', 'size', warnings) // Returns: 5\n * normalizePositiveNumber(-1, 3, 'ink-1', 'size', warnings) // Returns: 3, adds warning\n * normalizePositiveNumber('abc', 3, 'ink-1', 'size', warnings) // Returns: 3, adds warning\n */\nexport function normalizePositiveNumber(value, defaultValue, id, fieldName, warnings) {\n // Type coercion: parse string to number if needed\n let numValue = value;\n if (typeof value === 'string') {\n numValue = parseFloat(value);\n }\n\n // Validate is valid number and positive\n if (typeof numValue !== 'number' || isNaN(numValue) || numValue <= 0) {\n warnings.push(\n `[${id}]: Field \"${fieldName}\" invalid value \"${value}\", using default ${defaultValue}`\n );\n return defaultValue;\n }\n\n return numValue;\n}\n\n// ============================================================================\n// BASE FIELDS NORMALIZER\n// ============================================================================\n\n/**\n * Normalize common base annotation fields\n *\n * Validates and normalizes fields common to all annotation types: id, type,\n * page, start, and end. Auto-generates ID if missing. Applies safe defaults\n * for invalid values.\n *\n * @param {Object} raw - Raw annotation object\n * @param {Array<string>} warnings - Array to collect warning messages\n * @param {Array<string>} info - Array to collect info messages\n * @returns {Object} Object with normalized base fields\n *\n * @example\n * normalizeBaseFields({ type: 'text', page: 2 }, warnings, info)\n * // Returns: { id: 'anno-1234...', type: 'text', page: 2, start: 0, end: 0 }\n */\nexport function normalizeBaseFields(raw, warnings, info) {\n const base = {};\n\n // ===== ID Field =====\n // Check: non-empty string\n // Invalid: auto-generate unique ID\n if (typeof raw.id !== 'string' || raw.id.trim().length === 0) {\n const timestamp = Date.now();\n const random = Math.random().toString(36).substr(2, 9);\n base.id = `anno-${timestamp}-${random}`;\n info.push(`[${base.id}]: Auto-generated ID (original was missing or invalid)`);\n } else {\n base.id = raw.id.trim();\n }\n\n // ===== Type Field =====\n // Pass through as-is (validated in parent function)\n base.type = raw.type;\n\n // ===== Page Field =====\n // Check: positive integer\n // Invalid: default to 1\n if (typeof raw.page !== 'number' || raw.page < 1) {\n warnings.push(\n `[${base.id}]: Field \"page\" invalid value \"${raw.page}\", using default ${BASE_DEFAULTS.page}`\n );\n base.page = BASE_DEFAULTS.page;\n } else {\n // Floor to ensure integer\n base.page = Math.floor(raw.page);\n }\n\n // ===== Start Field =====\n // Check: non-negative number\n // Invalid: default to 0\n if (typeof raw.start !== 'number' || raw.start < 0) {\n warnings.push(\n `[${base.id}]: Field \"start\" invalid value \"${raw.start}\", using default ${BASE_DEFAULTS.start}`\n );\n base.start = BASE_DEFAULTS.start;\n } else {\n base.start = raw.start;\n }\n\n // ===== End Field =====\n // Check: non-negative number >= start\n // Invalid: clamp to start value\n if (typeof raw.end !== 'number' || raw.end < 0) {\n warnings.push(\n `[${base.id}]: Field \"end\" invalid value \"${raw.end}\", using start value ${base.start}`\n );\n base.end = base.start;\n } else if (raw.end < base.start) {\n warnings.push(\n `[${base.id}]: Field \"end\" (${raw.end}) less than start (${base.start}), clamping to start`\n );\n base.end = base.start;\n } else {\n base.end = raw.end;\n }\n\n return base;\n}\n\n// ============================================================================\n// TYPE-SPECIFIC NORMALIZERS\n// ============================================================================\n\n/**\n * Normalize a single quad (rectangular region)\n *\n * @private\n * @param {Object} quad - Quad object with x, y, w, h\n * @param {string} id - Annotation ID\n * @param {Array<string>} warnings - Warnings array\n * @returns {Object} Normalized quad\n */\nfunction normalizeQuad(quad, id, warnings) {\n if (!quad || typeof quad !== 'object') {\n warnings.push(`[${id}]: Invalid quad object, using default`);\n return { x: 0.1, y: 0.1, w: 0.8, h: 0.05 };\n }\n\n return {\n x: normalizeCoordinate(quad.x, 0.1, id, 'quad.x', warnings),\n y: normalizeCoordinate(quad.y, 0.1, id, 'quad.y', warnings),\n w: normalizeCoordinate(quad.w, 0.8, id, 'quad.w', warnings),\n h: normalizeCoordinate(quad.h, 0.05, id, 'quad.h', warnings)\n };\n}\n\n/**\n * Normalize highlight annotation\n *\n * Validates and normalizes highlight-specific fields: mode, quads array,\n * and style.color. Applies defaults for invalid fields.\n *\n * @param {Object} base - Object with normalized base fields\n * @param {Object} raw - Raw annotation object\n * @param {Array<string>} warnings - Warnings array\n * @param {Array<string>} info - Info array\n * @returns {Object} Fully normalized highlight annotation\n *\n * @example\n * normalizeHighlight(base, raw, warnings, info)\n * // Returns: { ...base, mode: 'quads', quads: [...], style: {...} }\n */\nexport function normalizeHighlight(base, raw, warnings, info) {\n const annotation = { ...base };\n\n // ===== Mode Field =====\n // Check: value equals \"quads\"\n // Invalid: default to \"quads\"\n if (raw.mode !== 'quads') {\n warnings.push(\n `[${base.id}]: Field \"mode\" invalid value \"${raw.mode}\", using default \"${HIGHLIGHT_DEFAULTS.mode}\"`\n );\n annotation.mode = HIGHLIGHT_DEFAULTS.mode;\n } else {\n annotation.mode = raw.mode;\n }\n\n // ===== Quads Array =====\n // Check: non-empty array\n // Invalid: use default quads\n if (!Array.isArray(raw.quads) || raw.quads.length === 0) {\n warnings.push(\n `[${base.id}]: Field \"quads\" missing or empty, using default`\n );\n annotation.quads = HIGHLIGHT_DEFAULTS.quads;\n } else {\n // Normalize each quad\n annotation.quads = raw.quads.map((quad, idx) => normalizeQuad(quad, base.id, warnings));\n }\n\n // ===== Style Object =====\n // Check: object with color property\n const defaultColor = HIGHLIGHT_DEFAULTS.style.color;\n if (!raw.style || typeof raw.style !== 'object') {\n warnings.push(\n `[${base.id}]: Field \"style\" missing or invalid, using default`\n );\n annotation.style = { color: defaultColor };\n } else {\n annotation.style = {\n color: normalizeColor(raw.style.color, defaultColor, base.id, warnings)\n };\n }\n\n return annotation;\n}\n\n/**\n * Normalize text annotation\n *\n * Validates and normalizes text-specific fields: content, position (x, y),\n * dimensions (w, h), and style (bg, color). Applies defaults for invalid fields.\n *\n * @param {Object} base - Object with normalized base fields\n * @param {Object} raw - Raw annotation object\n * @param {Array<string>} warnings - Warnings array\n * @param {Array<string>} info - Info array\n * @returns {Object} Fully normalized text annotation\n *\n * @example\n * normalizeText(base, raw, warnings, info)\n * // Returns: { ...base, content: '...', x: 0.1, y: 0.1, w: 0.3, h: 0.1, style: {...} }\n */\nexport function normalizeText(base, raw, warnings, info) {\n const annotation = { ...base };\n\n // ===== Content Field =====\n // Check: non-empty string\n // Invalid: default to placeholder\n if (typeof raw.content !== 'string' || raw.content.trim().length === 0) {\n warnings.push(\n `[${base.id}]: Field \"content\" missing or empty, using default \"${TEXT_DEFAULTS.content}\"`\n );\n annotation.content = TEXT_DEFAULTS.content;\n } else {\n annotation.content = raw.content;\n }\n\n // ===== Position Fields (x, y) =====\n annotation.x = normalizeCoordinate(raw.x, TEXT_DEFAULTS.x, base.id, 'x', warnings);\n annotation.y = normalizeCoordinate(raw.y, TEXT_DEFAULTS.y, base.id, 'y', warnings);\n\n // ===== Dimension Fields (w, h) =====\n annotation.w = normalizeCoordinate(raw.w, TEXT_DEFAULTS.w, base.id, 'w', warnings);\n annotation.h = normalizeCoordinate(raw.h, TEXT_DEFAULTS.h, base.id, 'h', warnings);\n\n // ===== Style Object =====\n const defaultBg = TEXT_DEFAULTS.style.bg;\n const defaultColor = TEXT_DEFAULTS.style.color;\n\n if (!raw.style || typeof raw.style !== 'object') {\n warnings.push(\n `[${base.id}]: Field \"style\" missing or invalid, using defaults`\n );\n annotation.style = {\n bg: defaultBg,\n color: defaultColor\n };\n } else {\n annotation.style = {\n bg: normalizeColor(raw.style.bg, defaultBg, base.id, warnings),\n color: normalizeColor(raw.style.color, defaultColor, base.id, warnings)\n };\n }\n\n return annotation;\n}\n\n/**\n * Normalize a single ink point\n *\n * @private\n * @param {Object} point - Point object with t, x, y\n * @param {string} id - Annotation ID\n * @param {Array<string>} warnings - Warnings array\n * @returns {Object} Normalized point\n */\nfunction normalizePoint(point, id, warnings) {\n if (!point || typeof point !== 'object') {\n warnings.push(`[${id}]: Invalid point object, using default`);\n return { t: 0, x: 0.1, y: 0.1 };\n }\n\n return {\n t: normalizeCoordinate(point.t, 0, id, 'point.t', warnings),\n x: normalizeCoordinate(point.x, 0.1, id, 'point.x', warnings),\n y: normalizeCoordinate(point.y, 0.1, id, 'point.y', warnings)\n };\n}\n\n/**\n * Normalize a single ink stroke\n *\n * @private\n * @param {Object} stroke - Stroke object with color, size, points\n * @param {string} id - Annotation ID\n * @param {Array<string>} warnings - Warnings array\n * @returns {Object} Normalized stroke\n */\nfunction normalizeStroke(stroke, id, warnings) {\n if (!stroke || typeof stroke !== 'object') {\n warnings.push(`[${id}]: Invalid stroke object, using default`);\n return INK_DEFAULTS.strokes[0];\n }\n\n const normalized = {\n color: normalizeColor(stroke.color, INK_DEFAULTS.strokes[0].color, id, warnings),\n size: normalizePositiveNumber(stroke.size, INK_DEFAULTS.strokes[0].size, id, 'stroke.size', warnings)\n };\n\n // ===== Points Array =====\n if (!Array.isArray(stroke.points) || stroke.points.length === 0) {\n warnings.push(`[${id}]: Stroke missing points array, using default`);\n normalized.points = INK_DEFAULTS.strokes[0].points;\n } else {\n normalized.points = stroke.points.map(point => normalizePoint(point, id, warnings));\n }\n\n return normalized;\n}\n\n/**\n * Normalize ink annotation\n *\n * Validates and normalizes ink-specific fields: strokes array with color,\n * size, and points. Applies defaults for invalid fields.\n *\n * @param {Object} base - Object with normalized base fields\n * @param {Object} raw - Raw annotation object\n * @param {Array<string>} warnings - Warnings array\n * @param {Array<string>} info - Info array\n * @returns {Object} Fully normalized ink annotation\n *\n * @example\n * normalizeInk(base, raw, warnings, info)\n * // Returns: { ...base, strokes: [{ color: '...', size: 3, points: [...] }] }\n */\nexport function normalizeInk(base, raw, warnings, info) {\n const annotation = { ...base };\n\n // ===== Strokes Array =====\n // Check: non-empty array\n // Invalid: use default single stroke\n if (!Array.isArray(raw.strokes) || raw.strokes.length === 0) {\n warnings.push(\n `[${base.id}]: Field \"strokes\" missing or empty, using default`\n );\n annotation.strokes = INK_DEFAULTS.strokes;\n } else {\n // Normalize each stroke\n annotation.strokes = raw.strokes.map(stroke => normalizeStroke(stroke, base.id, warnings));\n }\n\n return annotation;\n}\n\n// ============================================================================\n// ORCHESTRATION - SINGLE ANNOTATION & ARRAY\n// ============================================================================\n\n/**\n * Normalize a single annotation\n *\n * Routes annotation to appropriate type-specific normalizer based on type field.\n * Handles critical validation errors (missing/invalid type).\n *\n * @param {Object} raw - Raw annotation object\n * @param {number} index - Position in original array (for error context)\n * @returns {Object} Result object with annotation, warnings, info, and critical error\n * @returns {Object|null} return.annotation - Normalized annotation or null if critical error\n * @returns {Array<string>} return.warnings - Warning messages\n * @returns {Array<string>} return.info - Info messages\n * @returns {string|null} return.critical - Critical error message or null\n *\n * @example\n * normalizeAnnotation({ type: 'text', content: 'Hello' }, 0)\n * // Returns: { annotation: {...}, warnings: [], info: [], critical: null }\n */\nexport function normalizeAnnotation(raw, index) {\n const warnings = [];\n const info = [];\n\n // Validate input is object\n if (!raw || typeof raw !== 'object') {\n return {\n annotation: null,\n warnings: [],\n info: [],\n critical: `Annotation at index ${index}: Not a valid object`\n };\n }\n\n // Check type field (critical - cannot route without type)\n if (typeof raw.type !== 'string' || raw.type.trim().length === 0) {\n return {\n annotation: null,\n warnings: [],\n info: [],\n critical: `Annotation at index ${index}: Missing or invalid type field`\n };\n }\n\n const type = raw.type.trim();\n\n // Normalize base fields first\n const base = normalizeBaseFields(raw, warnings, info);\n\n // Route to type-specific normalizer\n let annotation;\n\n if (type === 'highlight') {\n annotation = normalizeHighlight(base, raw, warnings, info);\n } else if (type === 'text') {\n annotation = normalizeText(base, raw, warnings, info);\n } else if (type === 'ink') {\n annotation = normalizeInk(base, raw, warnings, info);\n } else {\n return {\n annotation: null,\n warnings: [],\n info: [],\n critical: `Annotation at index ${index}: Unsupported type \"${type}\"`\n };\n }\n\n return {\n annotation,\n warnings,\n info,\n critical: null\n };\n}\n\n/**\n * Normalize array of annotations\n *\n * MAIN ENTRY POINT for annotation normalization. Processes each annotation,\n * collects warnings, and returns normalized data ready for rendering.\n *\n * @param {Array} rawAnnotations - Array of raw annotation objects\n * @param {Object} [options] - Configuration options\n * @param {boolean} [options.skipInvalid=true] - Skip critically invalid annotations\n * @param {boolean} [options.warnInConsole=true] - Log warnings to console\n * @param {Function} [options.onWarning] - Custom warning callback\n * @returns {Object} ValidationResult with normalized annotations and messages\n * @returns {Array} return.normalized - Successfully normalized annotations\n * @returns {Array<string>} return.warnings - Warning messages\n * @returns {Array<string>} return.info - Informational messages\n * @returns {Array<Object>} return.skipped - Skipped annotations with reasons\n *\n * @example\n * const result = normalizeAnnotationArray(rawAnnotations, {\n * skipInvalid: true,\n * warnInConsole: true\n * });\n *\n * renderer.setAnnotations(result.normalized);\n */\nexport function normalizeAnnotationArray(rawAnnotations, options = {}) {\n // Default options\n const skipInvalid = options.skipInvalid !== false; // Default: true\n const warnInConsole = options.warnInConsole !== false; // Default: true\n const onWarning = options.onWarning || null;\n\n // Initialize result structure\n const result = {\n normalized: [],\n warnings: [],\n info: [],\n skipped: []\n };\n\n // Validate input is array\n if (!Array.isArray(rawAnnotations)) {\n const warning = 'normalizeAnnotationArray: Input is not an array, returning empty result';\n result.warnings.push(warning);\n\n if (warnInConsole) {\n console.warn(`[Annotation Normalizer] ${warning}`);\n }\n\n return result;\n }\n\n // Process each annotation\n rawAnnotations.forEach((raw, index) => {\n // Skip null/undefined\n if (raw == null) {\n result.skipped.push({\n index,\n annotation: raw,\n reason: 'Annotation is null or undefined'\n });\n return;\n }\n\n // Normalize annotation\n const normalized = normalizeAnnotation(raw, index);\n\n // Check for critical error\n if (normalized.critical) {\n result.skipped.push({\n index,\n annotation: raw,\n reason: normalized.critical\n });\n\n if (warnInConsole) {\n console.error(`[Annotation Normalizer] ${normalized.critical}`);\n }\n\n return;\n }\n\n // Add to normalized array\n result.normalized.push(normalized.annotation);\n\n // Collect warnings and info\n result.warnings.push(...normalized.warnings);\n result.info.push(...normalized.info);\n });\n\n // Console output\n if (warnInConsole) {\n if (result.warnings.length > 0 || result.info.length > 0 || result.skipped.length > 0) {\n console.group('[Annotation Normalizer] Validation Summary');\n\n if (result.normalized.length > 0) {\n console.info(`✓ Normalized ${result.normalized.length} annotation(s)`);\n }\n\n if (result.skipped.length > 0) {\n console.error(`✗ Skipped ${result.skipped.length} annotation(s)`);\n result.skipped.forEach(s => {\n console.error(` Index ${s.index}: ${s.reason}`);\n });\n }\n\n if (result.warnings.length > 0) {\n console.warn(`⚠ ${result.warnings.length} warning(s):`);\n result.warnings.forEach(w => console.warn(` ${w}`));\n }\n\n if (result.info.length > 0) {\n console.info(`ℹ ${result.info.length} info message(s):`);\n result.info.forEach(i => console.info(` ${i}`));\n }\n\n console.groupEnd();\n }\n }\n\n // Call custom warning handler\n if (onWarning && typeof onWarning === 'function') {\n onWarning(result);\n }\n\n return result;\n}\n"],"names":["normalizeCoordinate","value","defaultValue","id","fieldName","warnings","numValue","normalizeColor","trimmed","hexPattern","rgbPattern","namedColors","isHex","isRgb","isNamed","normalizePositiveNumber","normalizeBaseFields","raw","info","base","timestamp","random","BASE_DEFAULTS","normalizeQuad","quad","normalizeHighlight","annotation","HIGHLIGHT_DEFAULTS","idx","defaultColor","normalizeText","TEXT_DEFAULTS","defaultBg","normalizePoint","point","normalizeStroke","stroke","INK_DEFAULTS","normalized","normalizeInk","normalizeAnnotation","index","type","normalizeAnnotationArray","rawAnnotations","options","warnInConsole","onWarning","result","warning","s","w"],"mappings":"iHAuCO,SAASA,EAAoBC,EAAOC,EAAcC,EAAIC,EAAWC,EAAU,CAEhF,IAAIC,EAAWL,EASf,OARI,OAAOA,GAAU,WACnBK,EAAW,WAAWL,CAAK,GAOzB,OAAOK,GAAa,UAAY,MAAMA,CAAQ,GAChDD,EAAS,KACP,IAAIF,CAAE,aAAaC,CAAS,oBAAoBH,CAAK,oBAAoBC,CAAY,EAC3F,EACWA,GAILI,EAAW,GACbD,EAAS,KACP,IAAIF,CAAE,aAAaC,CAAS,WAAWE,CAAQ,mCACrD,EACW,GAGLA,EAAW,GACbD,EAAS,KACP,IAAIF,CAAE,aAAaC,CAAS,WAAWE,CAAQ,qCACrD,EACW,GAIFA,CACT,CAmBO,SAASC,EAAeN,EAAOC,EAAcC,EAAIE,EAAU,CAEhE,GAAI,OAAOJ,GAAU,UAAYA,EAAM,KAAI,EAAG,SAAW,EACvD,OAAAI,EAAS,KACP,IAAIF,CAAE,4BAA4BF,CAAK,oBAAoBC,CAAY,EAC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,OAAS,GAC7B,QAAQ,KAAK,gBAAgBA,EAAO,WAAW,MAAM,gBAAgB,EAGnEA,EAAO,QAAQ,OAAS,IAC1B,QAAQ,MAAM,aAAaA,EAAO,QAAQ,MAAM,gBAAgB,EAChEA,EAAO,QAAQ,QAAQE,GAAK,CAC1B,QAAQ,MAAM,WAAWA,EAAE,KAAK,KAAKA,EAAE,MAAM,EAAE,CACjD,CAAC,GAGCF,EAAO,SAAS,OAAS,IAC3B,QAAQ,KAAK,KAAKA,EAAO,SAAS,MAAM,cAAc,EACtDA,EAAO,SAAS,QAAQG,GAAK,QAAQ,KAAK,KAAKA,CAAC,EAAE,CAAC,GAGjDH,EAAO,KAAK,OAAS,IACvB,QAAQ,KAAK,KAAKA,EAAO,KAAK,MAAM,mBAAmB,EACvDA,EAAO,KAAK,QAAQ,GAAK,QAAQ,KAAK,KAAK,CAAC,EAAE,CAAC,GAGjD,QAAQ,SAAQ,GAKhBD,GAAa,OAAOA,GAAc,YACpCA,EAAUC,CAAM,EAGXA,CACT"}
|
|
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.\n *\n * @module converters/highlight\n */\n\nimport { applyJitter, applyPressure } from '../pen/effects.js';\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 *\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 {Object} [style.jitter] - Jitter configuration\n * @param {Object} [style.pressure] - Pressure configuration\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\n // Calculate timing for each quad (staggered)\n const quadDuration = totalDuration / quadCount;\n\n for (let i = 0; i < quads.length; i++) {\n const quad = quads[i];\n const { x, y, w, h } = quad;\n\n // Calculate center-line Y position\n const yCenter = y + h / 2;\n\n // Create stroke points (left to right horizontal line)\n let points = [\n [x, yCenter],\n [x + w, yCenter]\n ];\n\n // Apply jitter if configured\n if (style.jitter?.amplitude > 0) {\n points = applyJitter(points, style.jitter, `${id}-${i}`);\n }\n\n // Calculate pressure values if configured\n let pressures = null;\n if (style.pressure?.taperIn > 0 || style.pressure?.taperOut > 0) {\n pressures = applyPressure(points, style.pressure);\n }\n\n // Calculate timing for this quad\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 pressures\n });\n }\n\n return strokes;\n}\n\nexport default highlightToStrokes;\n"],"names":["highlightToStrokes","annotation","style","id","start","end","quads","strokes","totalDuration","quadCount","quadDuration","i","quad","x","y","w","h","yCenter","points","applyJitter","pressures","applyPressure","quadStart","quadEnd"],"mappings":"4IA+BO,SAASA,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,OAGlBI,EAAeF,EAAgBC,EAErC,QAASE,EAAI,EAAGA,EAAIL,EAAM,OAAQK,IAAK,CACrC,MAAMC,EAAON,EAAMK,CAAC,EACd,CAAE,EAAAE,EAAG,EAAAC,EAAG,EAAAC,EAAG,EAAAC,CAAC,EAAKJ,EAGjBK,EAAUH,EAAIE,EAAI,EAGxB,IAAIE,EAAS,CACX,CAACL,EAAGI,CAAO,EACX,CAACJ,EAAIE,EAAGE,CAAO,CACrB,EAGQf,EAAM,QAAQ,UAAY,IAC5BgB,EAASC,EAAAA,YAAYD,EAAQhB,EAAM,OAAQ,GAAGC,CAAE,IAAIQ,CAAC,EAAE,GAIzD,IAAIS,EAAY,MACZlB,EAAM,UAAU,QAAU,GAAKA,EAAM,UAAU,SAAW,KAC5DkB,EAAYC,EAAAA,cAAcH,EAAQhB,EAAM,QAAQ,GAIlD,MAAMoB,EAAYlB,EAAQO,EAAID,EACxBa,EAAUD,EAAYZ,EAE5BH,EAAQ,KAAK,CACX,GAAI,GAAGJ,CAAE,IAAIQ,CAAC,GACd,OAAAO,EACA,MAAOI,EACP,IAAKC,EACL,MAAOrB,EAAM,OAAS,yBACtB,MAAOA,EAAM,OAAS,GACtB,QAASA,EAAM,SAAW,OAC1B,UAAAkB,CACN,CAAK,CACH,CAEA,OAAOb,CACT"}
|