@e-llm-studio/citation 0.0.253 → 0.0.254

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/cjs/features/ChatDrawer/ChatDrawer.js +1 -1
  2. package/dist/cjs/features/ChatDrawer/ChatDrawer.js.map +1 -1
  3. package/dist/cjs/features/IngestionStatus/IngestionStatusComponent.js +1 -1
  4. package/dist/cjs/features/IngestionStatus/IngestionStatusComponent.js.map +1 -1
  5. package/dist/cjs/features/IngestionStatus/useIngestionStatus.js +1 -1
  6. package/dist/cjs/features/IngestionStatus/useIngestionStatus.js.map +1 -1
  7. package/dist/cjs/features/PdfViewer/PdfViewer.js +1 -1
  8. package/dist/cjs/features/PdfViewer/PdfViewer.js.map +1 -1
  9. package/dist/cjs/features/PdfViewer/usePdfHighlight.js +1 -1
  10. package/dist/cjs/features/PdfViewer/usePdfHighlight.js.map +1 -1
  11. package/dist/cjs/features/SegmentReviewComponents/CognitiveIntegrity.js +1 -1
  12. package/dist/cjs/features/SegmentReviewComponents/CognitiveIntegrity.js.map +1 -1
  13. package/dist/cjs/features/SegmentReviewComponents/SaveAsLearningCard.js +1 -1
  14. package/dist/cjs/features/SegmentReviewComponents/SaveAsLearningCard.js.map +1 -1
  15. package/dist/cjs/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js +1 -1
  16. package/dist/cjs/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js.map +1 -1
  17. package/dist/features/ChatDrawer/ChatDrawer.js +1 -1
  18. package/dist/features/ChatDrawer/ChatDrawer.js.map +1 -1
  19. package/dist/features/IngestionStatus/IngestionStatusComponent.js +1 -1
  20. package/dist/features/IngestionStatus/IngestionStatusComponent.js.map +1 -1
  21. package/dist/features/IngestionStatus/useIngestionStatus.js +1 -1
  22. package/dist/features/IngestionStatus/useIngestionStatus.js.map +1 -1
  23. package/dist/features/PdfViewer/PdfViewer.js +1 -1
  24. package/dist/features/PdfViewer/PdfViewer.js.map +1 -1
  25. package/dist/features/PdfViewer/usePdfHighlight.js +1 -1
  26. package/dist/features/PdfViewer/usePdfHighlight.js.map +1 -1
  27. package/dist/features/SegmentReviewComponents/CognitiveIntegrity.js +1 -1
  28. package/dist/features/SegmentReviewComponents/CognitiveIntegrity.js.map +1 -1
  29. package/dist/features/SegmentReviewComponents/SaveAsLearningCard.js +1 -1
  30. package/dist/features/SegmentReviewComponents/SaveAsLearningCard.js.map +1 -1
  31. package/dist/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js +1 -1
  32. package/dist/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js.map +1 -1
  33. package/dist/types/features/ChatDrawer/ChatDrawer.d.ts.map +1 -1
  34. package/dist/types/features/IngestionStatus/IngestionStatusComponent.d.ts +1 -0
  35. package/dist/types/features/IngestionStatus/IngestionStatusComponent.d.ts.map +1 -1
  36. package/dist/types/features/IngestionStatus/useIngestionStatus.d.ts +1 -1
  37. package/dist/types/features/IngestionStatus/useIngestionStatus.d.ts.map +1 -1
  38. package/dist/types/features/PdfViewer/PdfViewer.d.ts.map +1 -1
  39. package/dist/types/features/PdfViewer/usePdfHighlight.d.ts +1 -0
  40. package/dist/types/features/PdfViewer/usePdfHighlight.d.ts.map +1 -1
  41. package/dist/types/features/SegmentReviewComponents/CognitiveIntegrity.d.ts +6 -1
  42. package/dist/types/features/SegmentReviewComponents/CognitiveIntegrity.d.ts.map +1 -1
  43. package/dist/types/features/SegmentReviewComponents/SaveAsLearningCard.d.ts +2 -1
  44. package/dist/types/features/SegmentReviewComponents/SaveAsLearningCard.d.ts.map +1 -1
  45. package/dist/types/features/SegmentReviewComponents/SegmentReviewPdfWrapper.d.ts +8 -1
  46. package/dist/types/features/SegmentReviewComponents/SegmentReviewPdfWrapper.d.ts.map +1 -1
  47. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),o=require("lucide-react");exports.default=({children:n,uploadListTopContent:r,defaultHeight:i=300,minHeight:s=150,maxHeight:d,isExpanded:l=!1,onToggle:a,onHeightChange:u,styles:p={},drawerSummaryComponent:c,totalCountsBadge:x,headerComponent:f})=>{const[h,g]=t.useState(!1),[m,b]=t.useState(i),y=t.useRef(0),v=t.useRef(i),w=t.useRef(null),C=t.useRef(0),j="string"==typeof d?parseFloat(d)/100*window.innerHeight:d??.4*window.innerHeight;t.useEffect(()=>{!l&&w.current&&(C.current=w.current.getBoundingClientRect().height)},[l]);return t.useEffect(()=>{if(!h)return;const e=e=>{e.preventDefault();const t=e.clientY-y.current,o=Math.max(s,Math.min(j,v.current+t));b(o),u?.(o)},t=()=>{g(!1),document.body.style.userSelect=""};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[h]),e.jsxs("div",{ref:w,style:{position:"relative",width:"100%",minHeight:l?C.current:"auto"},children:[e.jsxs("div",{style:{position:l?"absolute":"relative",zIndex:l?10:"auto",left:0,right:0,top:0,display:"flex",flexDirection:"column",backgroundColor:"#fff",borderRadius:20,border:"1px solid #BDB4FE",boxShadow:"0 4px 8px -2px rgba(16, 24, 40, 0.05), 0 2px 4px -2px rgba(16, 24, 40, 0.06)",height:l?`${m}px`:"auto",minHeight:l?`${s}px`:"auto",maxHeight:l?`${m}px`:"auto",overflow:"hidden",width:"100%",...p.container},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",marginBottom:12,flexShrink:0,padding:"12px 20px 0 20px",gap:"16px",...p.header},children:[e.jsx("span",{style:{display:"inline-block",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:16,fontWeight:500,lineHeight:"24px",color:"#101828",fontFamily:"Inter, sans-serif",...p.title},children:f||(r?.trim()?r:"Data uploaded for your context")}),x]}),c,l&&e.jsx("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0,padding:"0 20px",paddingBottom:"36px",...p.body},children:n}),l&&e.jsx("div",{onMouseDown:e=>{e.preventDefault(),g(!0),y.current=e.clientY,v.current=m,document.body.style.userSelect="none"},style:{position:"absolute",bottom:0,left:0,right:0,backgroundColor:p.body?.backgroundColor??"#fff",display:"flex",justifyContent:"center",alignItems:"center",padding:"8px 20px",cursor:"ns-resize",userSelect:"none",flexShrink:0},children:e.jsx("div",{style:{width:48,height:4,borderRadius:4,background:h?p.dragPillActiveColor??"#a78bfa":"#d1d5db",...p.dragPill}})})]}),e.jsx("div",{style:{position:l?"absolute":"relative",top:l?`${m}px`:"auto",width:"100%",display:"flex",justifyContent:"center",height:18,zIndex:l?10:"auto"},children:e.jsx("button",{onClick:a,"aria-label":l?"Collapse":"Expand",style:{position:"absolute",width:"52px",height:"18px",borderBottomLeftRadius:"10px",borderBottomRightRadius:"10px",border:"1px solid rgb(189, 180, 254)",borderTop:"none",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,...p.notch},children:e.jsx(o.ChevronDown,{size:14,color:p.notchArrowColor??"#6d28d9",style:{transform:l?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"}})})})]})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=require("lucide-react");exports.default=({children:o,uploadListTopContent:r,defaultHeight:i=300,minHeight:s=150,maxHeight:d,isExpanded:l=!1,onToggle:a,onHeightChange:u,styles:c={},drawerSummaryComponent:p,totalCountsBadge:f,headerComponent:h})=>{const[x,g]=t.useState(!1),[m,v]=t.useState(i),w=t.useRef(0),b=t.useRef(i),y=t.useRef(null),C=t.useRef(0),j=()=>"string"==typeof d?parseFloat(d)/100*(window.visualViewport?.height??window.innerHeight):d??.4*window.innerHeight;t.useEffect(()=>{const e=()=>{const e=Math.max(s,Math.min(j(),m));e!==m&&(v(e),u?.(e))};window.addEventListener("resize",e),window.visualViewport?.addEventListener("resize",e);const t="undefined"!=typeof ResizeObserver?new ResizeObserver(e):null;return t?.observe(document.documentElement),()=>{window.removeEventListener("resize",e),window.visualViewport?.removeEventListener("resize",e),t?.disconnect()}},[m,d,s,u]),t.useEffect(()=>{!l&&y.current&&(C.current=y.current.getBoundingClientRect().height)},[l]);return t.useEffect(()=>{if(!x)return;const e=e=>{e.preventDefault();const t=e.clientY-w.current,n=Math.max(s,Math.min(j(),b.current+t));v(n),u?.(n)},t=()=>{g(!1),document.body.style.userSelect=""};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[x,d,s,u]),e.jsxs("div",{ref:y,style:{position:"relative",width:"100%",minHeight:l?C.current:"auto"},children:[e.jsxs("div",{style:{position:l?"absolute":"relative",zIndex:l?10:"auto",left:0,right:0,top:0,display:"flex",flexDirection:"column",backgroundColor:"#fff",borderRadius:20,border:"1px solid #BDB4FE",boxShadow:"0 4px 8px -2px rgba(16, 24, 40, 0.05), 0 2px 4px -2px rgba(16, 24, 40, 0.06)",height:l?`${m}px`:"auto",minHeight:l?`${s}px`:"auto",maxHeight:l?`${m}px`:"auto",overflow:"hidden",width:"100%",...c.container},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",marginBottom:12,flexShrink:0,padding:"12px 20px 0 20px",gap:"16px",...c.header},children:[e.jsx("span",{style:{display:"inline-block",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:16,fontWeight:500,lineHeight:"24px",color:"#101828",fontFamily:"Inter, sans-serif",...c.title},children:h||(r?.trim()?r:"Data uploaded for your context")}),f]}),p,l&&e.jsx("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0,padding:"0 20px",paddingBottom:"36px",...c.body},children:o}),l&&e.jsx("div",{onMouseDown:e=>{e.preventDefault(),g(!0),w.current=e.clientY,b.current=m,document.body.style.userSelect="none"},style:{position:"absolute",bottom:0,left:0,right:0,backgroundColor:c.body?.backgroundColor??"#fff",display:"flex",justifyContent:"center",alignItems:"center",padding:"8px 20px",cursor:"ns-resize",userSelect:"none",flexShrink:0},children:e.jsx("div",{style:{width:48,height:4,borderRadius:4,background:x?c.dragPillActiveColor??"#a78bfa":"#d1d5db",...c.dragPill}})})]}),e.jsx("div",{style:{position:l?"absolute":"relative",top:l?`${m}px`:"auto",width:"100%",display:"flex",justifyContent:"center",height:18,zIndex:l?10:"auto"},children:e.jsx("button",{onClick:a,"aria-label":l?"Collapse":"Expand",style:{position:"absolute",width:"52px",height:"18px",borderBottomLeftRadius:"10px",borderBottomRightRadius:"10px",border:"1px solid rgb(189, 180, 254)",borderTop:"none",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,...c.notch},children:e.jsx(n.ChevronDown,{size:14,color:c.notchArrowColor??"#6d28d9",style:{transform:l?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"}})})})]})};
2
2
  //# sourceMappingURL=ChatDrawer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ChatDrawer.js","sources":["../../../../src/features/ChatDrawer/ChatDrawer.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport { ChevronDown } from 'lucide-react';\nimport { ChatDrawerProps } from './types/ChatDrawer.types';\n\nconst ChatDrawer: React.FC<ChatDrawerProps> = ({\n children,\n uploadListTopContent,\n defaultHeight = 300,\n minHeight = 150,\n maxHeight,\n isExpanded = false,\n onToggle,\n onHeightChange,\n styles = {},\n drawerSummaryComponent,\n totalCountsBadge, \n headerComponent\n}) => {\n const [isDragging, setIsDragging] = useState(false);\n const [height, setHeight] = useState<number>(defaultHeight);\n\n const startYRef = useRef<number>(0);\n const startHeightRef = useRef<number>(defaultHeight);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const collapsedHeightRef = useRef<number>(0);\n\n const resolvedMaxHeight =\n typeof maxHeight === 'string'\n ? (parseFloat(maxHeight) / 100) * window.innerHeight\n : maxHeight ?? window.innerHeight * 0.4;\n\n useEffect(() => {\n if (!isExpanded && wrapperRef.current) {\n collapsedHeightRef.current = wrapperRef.current.getBoundingClientRect().height;\n }\n }, [isExpanded]);\n\n const handleDragStart = (e: React.MouseEvent) => {\n e.preventDefault();\n setIsDragging(true);\n startYRef.current = e.clientY;\n startHeightRef.current = height;\n document.body.style.userSelect = 'none';\n };\n\n useEffect(() => {\n if (!isDragging) return;\n\n const onMove = (e: MouseEvent) => {\n e.preventDefault();\n const deltaY = e.clientY - startYRef.current;\n const newHeight = Math.max(\n minHeight,\n Math.min(resolvedMaxHeight, startHeightRef.current + deltaY)\n );\n setHeight(newHeight);\n onHeightChange?.(newHeight);\n };\n\n const onUp = () => {\n setIsDragging(false);\n document.body.style.userSelect = '';\n };\n\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n return () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n };\n }, [isDragging]);\n\n return (\n <div\n ref={wrapperRef}\n style={{\n position: 'relative',\n width: '100%',\n minHeight: isExpanded ? collapsedHeightRef.current : 'auto',\n }}\n >\n {/* Main drawer container */}\n <div\n style={{\n position: isExpanded ? 'absolute' : 'relative',\n zIndex: isExpanded ? 10 : 'auto',\n left: 0,\n right: 0,\n top: 0,\n display: 'flex',\n flexDirection: 'column',\n backgroundColor: '#fff',\n borderRadius: 20,\n border: '1px solid #BDB4FE',\n boxShadow: '0 4px 8px -2px rgba(16, 24, 40, 0.05), 0 2px 4px -2px rgba(16, 24, 40, 0.06)',\n height: isExpanded ? `${height}px` : 'auto',\n minHeight: isExpanded ? `${minHeight}px` : 'auto',\n maxHeight: isExpanded ? `${height}px` : 'auto',\n overflow: 'hidden',\n width: '100%',\n ...styles.container,\n }}\n >\n {/* Header */}\n <div style={{ \n display: 'flex', \n alignItems: 'center', \n justifyContent: 'space-between', \n width: '100%', \n marginBottom: 12, \n flexShrink: 0, \n padding: '12px 20px 0 20px', \n gap: '16px',\n ...styles.header \n }}>\n <span\n style={{\n display: 'inline-block',\n flex: 1, \n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n fontSize: 16,\n fontWeight: 500,\n lineHeight: '24px',\n color: '#101828',\n fontFamily: 'Inter, sans-serif',\n ...styles.title,\n }}\n >\n {headerComponent ? headerComponent : (uploadListTopContent?.trim() ? uploadListTopContent : 'Data uploaded for your context')}\n </span>\n \n {totalCountsBadge}\n </div>\n {/* Summary of drawer */}\n {drawerSummaryComponent}\n\n {/* Body */}\n {isExpanded && (\n <div style={{ \n flex: 1, \n overflowY: 'auto', \n overflowX: 'hidden', \n minHeight: 0, \n padding: '0 20px', \n paddingBottom: '36px', // ADDED: Prevents content from hiding behind the floating drag handle\n ...styles.body \n }}>\n {children}\n </div>\n )}\n\n {/* Drag handle */}\n {isExpanded && (\n <div\n onMouseDown={handleDragStart}\n style={{ \n position: 'absolute', // Pin it to the bottom of the container\n bottom: 0, \n left: 0, \n right: 0,\n backgroundColor: styles.body?.backgroundColor ?? '#fff', // Use themed background\n display: 'flex', \n justifyContent: 'center', \n alignItems: 'center', \n padding: '8px 20px', \n cursor: 'ns-resize', \n userSelect: 'none', \n flexShrink: 0,\n }}\n >\n <div style={{ width: 48, height: 4, borderRadius: 4, background: isDragging ? (styles.dragPillActiveColor ?? '#a78bfa') : '#d1d5db', ...styles.dragPill }} />\n </div>\n )}\n </div>\n\n {/* Notch */}\n <div\n style={{\n position: isExpanded ? 'absolute' : 'relative',\n top: isExpanded ? `${height}px` : 'auto',\n width: '100%',\n display: 'flex',\n justifyContent: 'center',\n height: 18,\n zIndex: isExpanded ? 10 : 'auto',\n }}\n >\n <button\n onClick={onToggle}\n aria-label={isExpanded ? 'Collapse' : 'Expand'}\n style={{\n position: 'absolute',\n width: '52px',\n height: '18px',\n borderBottomLeftRadius: '10px',\n borderBottomRightRadius: '10px',\n border: '1px solid rgb(189, 180, 254)',\n borderTop: 'none',\n backgroundColor: '#fff',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n cursor: 'pointer',\n padding: 0,\n ...styles.notch,\n }}\n >\n <ChevronDown\n size={14}\n color={styles.notchArrowColor ?? \"#6d28d9\"}\n style={{\n transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',\n transition: 'transform 0.2s ease',\n }}\n />\n </button>\n </div>\n </div>\n );\n};\n\nexport default ChatDrawer;"],"names":["children","uploadListTopContent","defaultHeight","minHeight","maxHeight","isExpanded","onToggle","onHeightChange","styles","drawerSummaryComponent","totalCountsBadge","headerComponent","isDragging","setIsDragging","useState","height","setHeight","startYRef","useRef","startHeightRef","wrapperRef","collapsedHeightRef","resolvedMaxHeight","parseFloat","window","innerHeight","useEffect","current","getBoundingClientRect","onMove","e","preventDefault","deltaY","clientY","newHeight","Math","max","min","onUp","document","body","style","userSelect","addEventListener","removeEventListener","jsxs","ref","position","width","zIndex","left","right","top","display","flexDirection","backgroundColor","borderRadius","border","boxShadow","overflow","container","alignItems","justifyContent","marginBottom","flexShrink","padding","gap","header","jsx","flex","textOverflow","whiteSpace","fontSize","fontWeight","lineHeight","color","fontFamily","title","trim","overflowY","overflowX","paddingBottom","onMouseDown","bottom","cursor","background","dragPillActiveColor","dragPill","onClick","borderBottomLeftRadius","borderBottomRightRadius","borderTop","notch","ChevronDown","size","notchArrowColor","transform","transition"],"mappings":"oKAI8C,EAC5CA,WACAC,uBACAC,gBAAgB,IAChBC,YAAY,IACZC,YACAC,cAAa,EACbC,WACAC,iBACAC,SAAS,CAAC,EACVC,yBACAC,mBACAC,sBAEA,MAAOC,EAAYC,GAAiBC,YAAS,IACtCC,EAAQC,GAAaF,WAAiBZ,GAEvCe,EAAYC,SAAe,GAC3BC,EAAiBD,SAAehB,GAChCkB,EAAaF,SAAuB,MACpCG,EAAqBH,SAAe,GAEpCI,EACiB,iBAAdlB,EACFmB,WAAWnB,GAAa,IAAOoB,OAAOC,YACvCrB,GAAkC,GAArBoB,OAAOC,YAE1BC,EAAAA,UAAU,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AAQ,+BACRkC,UAAW,OACXpC,gBAAiB,OACjBF,QAAS,OACTQ,WAAY,SACZC,eAAgB,SAChBsB,OAAQ,UACRnB,QAAS,KACNzD,EAAOoF,OAGZ5F,SAAAoE,EAAAA,IAACyB,EAAAA,YAAA,CACCC,KAAM,GACNnB,MAAOnE,EAAOuF,iBAAmB,UACjCtD,MAAO,CACLuD,UAAW3F,EAAa,iBAAmB,eAC3C4F,WAAY"}
1
+ {"version":3,"file":"ChatDrawer.js","sources":["../../../../src/features/ChatDrawer/ChatDrawer.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport { ChevronDown } from 'lucide-react';\nimport { ChatDrawerProps } from './types/ChatDrawer.types';\n\nconst ChatDrawer: React.FC<ChatDrawerProps> = ({\n children,\n uploadListTopContent,\n defaultHeight = 300,\n minHeight = 150,\n maxHeight,\n isExpanded = false,\n onToggle,\n onHeightChange,\n styles = {},\n drawerSummaryComponent,\n totalCountsBadge, \n headerComponent\n}) => {\n const [isDragging, setIsDragging] = useState(false);\n const [height, setHeight] = useState<number>(defaultHeight);\n\n const startYRef = useRef<number>(0);\n const startHeightRef = useRef<number>(defaultHeight);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const collapsedHeightRef = useRef<number>(0);\n\n const getResolvedMaxHeight = () =>\n typeof maxHeight === 'string'\n ? (parseFloat(maxHeight) / 100) * (window.visualViewport?.height ?? window.innerHeight)\n : maxHeight ?? window.innerHeight * 0.4;\n\n useEffect(() => {\n const clampHeightToViewport = () => {\n const nextHeight = Math.max(minHeight, Math.min(getResolvedMaxHeight(), height));\n\n if (nextHeight !== height) {\n setHeight(nextHeight);\n onHeightChange?.(nextHeight);\n }\n };\n\n window.addEventListener('resize', clampHeightToViewport);\n window.visualViewport?.addEventListener('resize', clampHeightToViewport);\n\n const resizeObserver = typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(clampHeightToViewport)\n : null;\n resizeObserver?.observe(document.documentElement);\n\n return () => {\n window.removeEventListener('resize', clampHeightToViewport);\n window.visualViewport?.removeEventListener('resize', clampHeightToViewport);\n resizeObserver?.disconnect();\n };\n }, [height, maxHeight, minHeight, onHeightChange]);\n\n useEffect(() => {\n if (!isExpanded && wrapperRef.current) {\n collapsedHeightRef.current = wrapperRef.current.getBoundingClientRect().height;\n }\n }, [isExpanded]);\n\n const handleDragStart = (e: React.MouseEvent) => {\n e.preventDefault();\n setIsDragging(true);\n startYRef.current = e.clientY;\n startHeightRef.current = height;\n document.body.style.userSelect = 'none';\n };\n\n useEffect(() => {\n if (!isDragging) return;\n\n const onMove = (e: MouseEvent) => {\n e.preventDefault();\n const deltaY = e.clientY - startYRef.current;\n const newHeight = Math.max(\n minHeight,\n Math.min(getResolvedMaxHeight(), startHeightRef.current + deltaY)\n );\n setHeight(newHeight);\n onHeightChange?.(newHeight);\n };\n\n const onUp = () => {\n setIsDragging(false);\n document.body.style.userSelect = '';\n };\n\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n return () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n };\n }, [isDragging, maxHeight, minHeight, onHeightChange]);\n\n return (\n <div\n ref={wrapperRef}\n style={{\n position: 'relative',\n width: '100%',\n minHeight: isExpanded ? collapsedHeightRef.current : 'auto',\n }}\n >\n {/* Main drawer container */}\n <div\n style={{\n position: isExpanded ? 'absolute' : 'relative',\n zIndex: isExpanded ? 10 : 'auto',\n left: 0,\n right: 0,\n top: 0,\n display: 'flex',\n flexDirection: 'column',\n backgroundColor: '#fff',\n borderRadius: 20,\n border: '1px solid #BDB4FE',\n boxShadow: '0 4px 8px -2px rgba(16, 24, 40, 0.05), 0 2px 4px -2px rgba(16, 24, 40, 0.06)',\n height: isExpanded ? `${height}px` : 'auto',\n minHeight: isExpanded ? `${minHeight}px` : 'auto',\n maxHeight: isExpanded ? `${height}px` : 'auto',\n overflow: 'hidden',\n width: '100%',\n ...styles.container,\n }}\n >\n {/* Header */}\n <div style={{ \n display: 'flex', \n alignItems: 'center', \n justifyContent: 'space-between', \n width: '100%', \n marginBottom: 12, \n flexShrink: 0, \n padding: '12px 20px 0 20px', \n gap: '16px',\n ...styles.header \n }}>\n <span\n style={{\n display: 'inline-block',\n flex: 1, \n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n fontSize: 16,\n fontWeight: 500,\n lineHeight: '24px',\n color: '#101828',\n fontFamily: 'Inter, sans-serif',\n ...styles.title,\n }}\n >\n {headerComponent ? headerComponent : (uploadListTopContent?.trim() ? uploadListTopContent : 'Data uploaded for your context')}\n </span>\n \n {totalCountsBadge}\n </div>\n {/* Summary of drawer */}\n {drawerSummaryComponent}\n\n {/* Body */}\n {isExpanded && (\n <div style={{ \n flex: 1, \n overflowY: 'auto', \n overflowX: 'hidden', \n minHeight: 0, \n padding: '0 20px', \n paddingBottom: '36px', // ADDED: Prevents content from hiding behind the floating drag handle\n ...styles.body \n }}>\n {children}\n </div>\n )}\n\n {/* Drag handle */}\n {isExpanded && (\n <div\n onMouseDown={handleDragStart}\n style={{ \n position: 'absolute', // Pin it to the bottom of the container\n bottom: 0, \n left: 0, \n right: 0,\n backgroundColor: styles.body?.backgroundColor ?? '#fff', // Use themed background\n display: 'flex', \n justifyContent: 'center', \n alignItems: 'center', \n padding: '8px 20px', \n cursor: 'ns-resize', \n userSelect: 'none', \n flexShrink: 0,\n }}\n >\n <div style={{ width: 48, height: 4, borderRadius: 4, background: isDragging ? (styles.dragPillActiveColor ?? '#a78bfa') : '#d1d5db', ...styles.dragPill }} />\n </div>\n )}\n </div>\n\n {/* Notch */}\n <div\n style={{\n position: isExpanded ? 'absolute' : 'relative',\n top: isExpanded ? `${height}px` : 'auto',\n width: '100%',\n display: 'flex',\n justifyContent: 'center',\n height: 18,\n zIndex: isExpanded ? 10 : 'auto',\n }}\n >\n <button\n onClick={onToggle}\n aria-label={isExpanded ? 'Collapse' : 'Expand'}\n style={{\n position: 'absolute',\n width: '52px',\n height: '18px',\n borderBottomLeftRadius: '10px',\n borderBottomRightRadius: '10px',\n border: '1px solid rgb(189, 180, 254)',\n borderTop: 'none',\n backgroundColor: '#fff',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n cursor: 'pointer',\n padding: 0,\n ...styles.notch,\n }}\n >\n <ChevronDown\n size={14}\n color={styles.notchArrowColor ?? \"#6d28d9\"}\n style={{\n transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',\n transition: 'transform 0.2s ease',\n }}\n />\n </button>\n </div>\n </div>\n );\n};\n\nexport default ChatDrawer;"],"names":["children","uploadListTopContent","defaultHeight","minHeight","maxHeight","isExpanded","onToggle","onHeightChange","styles","drawerSummaryComponent","totalCountsBadge","headerComponent","isDragging","setIsDragging","useState","height","setHeight","startYRef","useRef","startHeightRef","wrapperRef","collapsedHeightRef","getResolvedMaxHeight","parseFloat","window","visualViewport","innerHeight","useEffect","clampHeightToViewport","nextHeight","Math","max","min","addEventListener","resizeObserver","ResizeObserver","observe","document","documentElement","removeEventListener","disconnect","current","getBoundingClientRect","onMove","e","preventDefault","deltaY","clientY","newHeight","onUp","body","style","userSelect","jsxs","ref","position","width","zIndex","left","right","top","display","flexDirection","backgroundColor","borderRadius","border","boxShadow","overflow","container","alignItems","justifyContent","marginBottom","flexShrink","padding","gap","header","jsx","flex","textOverflow","whiteSpace","fontSize","fontWeight","lineHeight","color","fontFamily","title","trim","overflowY","overflowX","paddingBottom","onMouseDown","bottom","cursor","background","dragPillActiveColor","dragPill","onClick","borderBottomLeftRadius","borderBottomRightRadius","borderTop","notch","ChevronDown","size","notchArrowColor","transform","transition"],"mappings":"oKAI8C,EAC5CA,WACAC,uBACAC,gBAAgB,IAChBC,YAAY,IACZC,YACAC,cAAa,EACbC,WACAC,iBACAC,SAAS,CAAC,EACVC,yBACAC,mBACAC,sBAEA,MAAOC,EAAYC,GAAiBC,YAAS,IACtCC,EAAQC,GAAaF,WAAiBZ,GAEvCe,EAAYC,SAAe,GAC3BC,EAAiBD,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SAAU,WACVoC,OAAQ,EACRjC,KAAM,EACNC,MAAO,EACNI,gBAAiBvD,EAAO0C,MAAMa,iBAAmB,OAClDF,QAAS,OACTS,eAAgB,SAChBD,WAAY,SACZI,QAAS,WACTmB,OAAQ,YACRxC,WAAY,OACZoB,WAAY,GAGdxE,eAAC,MAAI,CAAAmD,MAAO,CAAEK,MAAO,GAAIzC,OAAQ,EAAGiD,aAAc,EAAG6B,WAAYjF,EAAcJ,EAAOsF,qBAAuB,UAAa,aAActF,EAAOuF,iBAMrJnB,EAAAA,IAAC,MAAA,CACCzB,MAAO,CACLI,SAAUlD,EAAa,WAAa,WACpCuD,IAAKvD,EAAa,GAAGU,MAAa,OAClCyC,MAAO,OACPK,QAAS,OACTS,eAAgB,SAChBvD,OAAQ,GACR0C,OAAQpD,EAAa,GAAK,QAG5BL,SAAA4E,EAAAA,IAAC,SAAA,CACCoB,QAAS1F,EACT,aAAYD,EAAa,WAAa,SACtC8C,MAAO,CACLI,SAAU,WACVC,MAAO,OACPzC,OAAQ,OACRkF,uBAAwB,OACxBC,wBAAyB,OACzBjC,OAAQ,+BACRkC,UAAW,OACXpC,gBAAiB,OACjBF,QAAS,OACTQ,WAAY,SACZC,eAAgB,SAChBsB,OAAQ,UACRnB,QAAS,KACNjE,EAAO4F,OAGZpG,SAAA4E,EAAAA,IAACyB,EAAAA,YAAA,CACCC,KAAM,GACNnB,MAAO3E,EAAO+F,iBAAmB,UACjCpD,MAAO,CACLqD,UAAWnG,EAAa,iBAAmB,eAC3CoG,WAAY"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),s=require("./ingestion.module.css.js"),n=require("./useIngestionStatus.js"),t=require("lucide-react");const r={ingested:{label:"Ingested",className:s.default.ingested},failed:{label:"Ingestion Failed",className:s.default.failed},in_progress:{label:"Ingesting...",className:s.default.inProgress},pending:{label:"Pending",className:s.default.pending}};const o=({status:n,label:o,percentage:i,customConfig:a,redirectionLink:l})=>{if(a)return e.jsx("span",{className:s.default.chip,style:{border:`1px solid ${a.borderColor}`,background:a.background,color:a.color},children:o??a.label});if("custom"===n)return null;const u=r[n];if(!u)return null;const c="in_progress"===n&&void 0!==i;return e.jsxs("span",{className:`${s.default.chip} ${u.className}`,style:{display:"inline-flex",alignItems:"center",gap:6},children:[c?e.jsxs(e.Fragment,{children:[o??"Ingesting",e.jsx("span",{className:s.default.dot}),`${i}%`]}):o??u.label,l&&e.jsx(t.ExternalLink,{size:14,style:{cursor:"pointer",flexShrink:0},onClick:e=>{e.stopPropagation(),window.open(l,"_blank","noopener,noreferrer")}})]})},i=new Set(["DONE","COMPLETED","FAILED"]);exports.IngestionStatusChip=o,exports.IngestionStatusComponent=({ingestionId:s,status:t,wsBaseUrl:r,showPercentage:a=!0,statusMap:l,customStatusConfigs:u,redirectionLink:c})=>{console.log("Component:",c);const d=!!t&&i.has(t.toUpperCase()),{data:g}=n.useIngestionWebSocket(!d&&s?s:null,r),p=d?t:g?.ingestionStatus??t??"",f=p?function(e,s){if(!e)return"custom";if(s){if(void 0!==s[e])return s[e];const n=e.toUpperCase();if(void 0!==s[n])return s[n]}return"custom"}(p,l):"pending",m=u?u[f]??u[p]??u[p.toUpperCase()]:void 0,x=(()=>{if(!d&&a)return void 0!==g?.currentProgress?Math.max(5,g.currentProgress):"in_progress"===f?5:void 0})();return e.jsx(o,{status:f,percentage:x,customConfig:m,redirectionLink:c})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),s=require("./ingestion.module.css.js"),n=require("./useIngestionStatus.js"),t=require("lucide-react");const r={ingested:{label:"Ingested",className:s.default.ingested},failed:{label:"Ingestion Failed",className:s.default.failed},in_progress:{label:"Ingesting...",className:s.default.inProgress},pending:{label:"Pending",className:s.default.pending}};const o=({status:n,label:o,percentage:i,customConfig:a,redirectionLink:l})=>{if(a)return e.jsx("span",{className:s.default.chip,style:{border:`1px solid ${a.borderColor}`,background:a.background,color:a.color},children:o??a.label});if("custom"===n)return null;const u=r[n];if(!u)return null;const c="in_progress"===n&&void 0!==i;return e.jsxs("span",{className:`${s.default.chip} ${u.className}`,style:{display:"inline-flex",alignItems:"center",gap:6},children:[c?e.jsxs(e.Fragment,{children:[o??"Ingesting",e.jsx("span",{className:s.default.dot}),`${i}%`]}):o??u.label,l&&e.jsx(t.ExternalLink,{size:14,style:{cursor:"pointer",flexShrink:0},onClick:e=>{e.stopPropagation(),window.open(l,"_blank","noopener,noreferrer")}})]})},i=new Set(["DONE","COMPLETED","FAILED"]);exports.IngestionStatusChip=o,exports.IngestionStatusComponent=({ingestionId:s,status:t,wsBaseUrl:r,showPercentage:a=!0,statusMap:l,customStatusConfigs:u,redirectionLink:c,authToken:d})=>{console.log("Component:",c);const g=!!t&&i.has(t.toUpperCase()),{data:p}=n.useIngestionWebSocket(!g&&s?s:null,r,d),f=g?t:p?.ingestionStatus??t??"",m=f?function(e,s){if(!e)return"custom";if(s){if(void 0!==s[e])return s[e];const n=e.toUpperCase();if(void 0!==s[n])return s[n]}return"custom"}(f,l):"pending",x=u?u[m]??u[f]??u[f.toUpperCase()]:void 0,b=(()=>{if(!g&&a)return void 0!==p?.currentProgress?Math.max(5,p.currentProgress):"in_progress"===m?5:void 0})();return e.jsx(o,{status:m,percentage:b,customConfig:x,redirectionLink:c})};
2
2
  //# sourceMappingURL=IngestionStatusComponent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"IngestionStatusComponent.js","sources":["../../../../src/features/IngestionStatus/IngestionStatusComponent.tsx"],"sourcesContent":["import React from \"react\";\nimport styles from \"./ingestion.module.css\";\nimport { useIngestionWebSocket } from \"./useIngestionStatus\";\nimport { ExternalLink } from \"lucide-react\";\n\n\nconst STATUS_CONFIG: Record<\n Exclude<string, \"custom\">,\n { label: string; className: string }\n> = {\n ingested: { label: \"Ingested\", className: styles.ingested },\n failed: { label: \"Ingestion Failed\", className: styles.failed },\n in_progress: { label: \"Ingesting...\", className: styles.inProgress },\n pending: { label: \"Pending\", className: styles.pending },\n};\n\nexport interface CustomChipConfig {\n label: string;\n borderColor: string;\n background: string;\n color: string;\n dotColor?: string;\n}\n\nfunction mapStatus(rawStatus: string, statusMap?: Record<string, string>): string {\n if (!rawStatus) return \"custom\";\n if (statusMap) {\n if (statusMap[rawStatus] !== undefined) return statusMap[rawStatus];\n const upper = rawStatus.toUpperCase();\n if (statusMap[upper] !== undefined) return statusMap[upper];\n }\n return \"custom\";\n}\n\ninterface IngestionStatusChipProps {\n status: string;\n label?: string;\n percentage?: number;\n customConfig?: CustomChipConfig;\n redirectionLink?: string;\n\n}\n\nexport const IngestionStatusChip: React.FC<IngestionStatusChipProps> = ({\n status,\n label,\n percentage,\n customConfig,\n redirectionLink,\n}) => {\n if (customConfig) {\n return (\n <span\n className={styles.chip}\n style={{\n border: `1px solid ${customConfig.borderColor}`,\n background: customConfig.background,\n color: customConfig.color,\n }}\n >\n {label ?? customConfig.label}\n </span>\n );\n }\n\n if (status === \"custom\") return null;\n\n const config = STATUS_CONFIG[status];\n if (!config) return null;\n const showPercentage = status === \"in_progress\" && percentage !== undefined;\n\n return (\n <span className={`${styles.chip} ${config.className}`}\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n gap: 6,\n }}>\n {showPercentage ? (\n <>\n {label ?? \"Ingesting\"}\n <span className={styles.dot} />\n {`${percentage}%`}\n </>\n ) : (\n label ?? config.label\n )}\n \n {redirectionLink && (\n <ExternalLink\n size={14}\n style={{ cursor: \"pointer\", flexShrink: 0 }}\n onClick={(e) => {\n e.stopPropagation();\n window.open(redirectionLink, \"_blank\", \"noopener,noreferrer\");\n }}\n />\n )}\n </span>\n );\n};\n\nconst TERMINAL_STATUSES = new Set([\"DONE\", \"COMPLETED\", \"FAILED\"]);\n\n\ninterface IngestionStatusComponentProps {\n ingestionId?: string;\n status?: string;\n wsBaseUrl?: string;\n showPercentage?: boolean;\n statusMap?: Record<string, string>;\n customStatusConfigs?: Record<string, CustomChipConfig>;\n redirectionLink?: string;\n\n}\n\nexport const IngestionStatusComponent: React.FC<IngestionStatusComponentProps> = ({\n ingestionId,\n status,\n wsBaseUrl,\n showPercentage = true,\n statusMap,\n customStatusConfigs,\n redirectionLink\n}) => {\n console.log(\"Component:\", redirectionLink);\n\n const isTerminal = status ? TERMINAL_STATUSES.has(status.toUpperCase()) : false;\n\n const { data } = useIngestionWebSocket(\n !isTerminal && ingestionId ? ingestionId : null,\n wsBaseUrl\n );\n\n const rawForMapping: string = isTerminal\n ? status!\n : data?.ingestionStatus ?? status ?? \"\";\n\n const resolvedStatus: string = rawForMapping\n ? mapStatus(rawForMapping, statusMap)\n : \"pending\";\n\n const customConfig: CustomChipConfig | undefined = customStatusConfigs\n ? customStatusConfigs[resolvedStatus] ??\n customStatusConfigs[rawForMapping] ??\n customStatusConfigs[rawForMapping.toUpperCase()]\n : undefined;\n\n const percentage = (() => {\n if (isTerminal || !showPercentage) return undefined;\n if (data?.currentProgress !== undefined) return Math.max(5, data.currentProgress);\n if (resolvedStatus === \"in_progress\") return 5;\n return undefined;\n })();\n\n return <IngestionStatusChip status={resolvedStatus} percentage={percentage} customConfig={customConfig} redirectionLink={redirectionLink}\n />;\n};\n\n"],"names":["STATUS_CONFIG","ingested","label","className","styles","failed","in_progress","inProgress","pending","IngestionStatusChip","status","percentage","customConfig","redirectionLink","jsx","chip","style","border","borderColor","background","color","children","config","showPercentage","jsxs","display","alignItems","gap","Fragment","dot","ExternalLink","size","cursor","flexShrink","onClick","e","stopPropagation","window","open","TERMINAL_STATUSES","Set","ingestionId","wsBaseUrl","statusMap","customStatusConfigs","console","log","isTerminal","has","toUpperCase","data","useIngestionWebSocket","rawForMapping","ingestionStatus","resolvedStatus","rawStatus","upper","mapStatus","currentProgress","Math","max"],"mappings":"6MAMA,MAAMA,EAGF,CACFC,SAAU,CAAEC,MAAO,WAAYC,UAAWC,EAAAA,QAAOH,UACjDI,OAAQ,CAAEH,MAAO,mBAAoBC,UAAWC,EAAAA,QAAOC,QACvD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C,GAAMG,iBAAmB3C,GAAU,GAEjC4C,EAAyBF,EAlHjC,SAAmBG,EAAmBZ,GAChC,IAACY,EAAkB,MAAA,SACvB,GAAIZ,EAAW,CACb,QAAwC,IAApCA,EAAUY,GAA0B,OAAOZ,EAAUY,GACnD,MAAAC,EAAQD,EAAUN,cACxB,QAAoC,IAAhCN,EAAUa,GAAsB,OAAOb,EAAUa,EACvD,CACO,MAAA,QACT,CA2GMC,CAAUL,EAAeT,GACzB,UAEE/B,EAA6CgC,EAC/CA,EAAoBU,IACpBV,EAAoBQ,IACpBR,EAAoBQ,EAAcH,oBAClC,EAEEtC,QACA,IAAAoC,GAAexB,EACf,YAAqC,IAArC2B,GAAMQ,gBAAsCC,KAAKC,IAAI,EAAGV,EAAKQ,iBAC1C,gBAAnBJ,EAAyC,OAAzC,CAEH,KAEI,OAAAxC,EAAAA,IAACL,EAAA,CAAoBC,OAAQ4C,EAAgB3C,aAAwBC,eAA4BC"}
1
+ {"version":3,"file":"IngestionStatusComponent.js","sources":["../../../../src/features/IngestionStatus/IngestionStatusComponent.tsx"],"sourcesContent":["import React from \"react\";\nimport styles from \"./ingestion.module.css\";\nimport { useIngestionWebSocket } from \"./useIngestionStatus\";\nimport { ExternalLink } from \"lucide-react\";\n\n\nconst STATUS_CONFIG: Record<\n Exclude<string, \"custom\">,\n { label: string; className: string }\n> = {\n ingested: { label: \"Ingested\", className: styles.ingested },\n failed: { label: \"Ingestion Failed\", className: styles.failed },\n in_progress: { label: \"Ingesting...\", className: styles.inProgress },\n pending: { label: \"Pending\", className: styles.pending },\n};\n\nexport interface CustomChipConfig {\n label: string;\n borderColor: string;\n background: string;\n color: string;\n dotColor?: string;\n}\n\nfunction mapStatus(rawStatus: string, statusMap?: Record<string, string>): string {\n if (!rawStatus) return \"custom\";\n if (statusMap) {\n if (statusMap[rawStatus] !== undefined) return statusMap[rawStatus];\n const upper = rawStatus.toUpperCase();\n if (statusMap[upper] !== undefined) return statusMap[upper];\n }\n return \"custom\";\n}\n\ninterface IngestionStatusChipProps {\n status: string;\n label?: string;\n percentage?: number;\n customConfig?: CustomChipConfig;\n redirectionLink?: string;\n\n}\n\nexport const IngestionStatusChip: React.FC<IngestionStatusChipProps> = ({\n status,\n label,\n percentage,\n customConfig,\n redirectionLink,\n}) => {\n if (customConfig) {\n return (\n <span\n className={styles.chip}\n style={{\n border: `1px solid ${customConfig.borderColor}`,\n background: customConfig.background,\n color: customConfig.color,\n }}\n >\n {label ?? customConfig.label}\n </span>\n );\n }\n\n if (status === \"custom\") return null;\n\n const config = STATUS_CONFIG[status];\n if (!config) return null;\n const showPercentage = status === \"in_progress\" && percentage !== undefined;\n\n return (\n <span className={`${styles.chip} ${config.className}`}\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n gap: 6,\n }}>\n {showPercentage ? (\n <>\n {label ?? \"Ingesting\"}\n <span className={styles.dot} />\n {`${percentage}%`}\n </>\n ) : (\n label ?? config.label\n )}\n \n {redirectionLink && (\n <ExternalLink\n size={14}\n style={{ cursor: \"pointer\", flexShrink: 0 }}\n onClick={(e) => {\n e.stopPropagation();\n window.open(redirectionLink, \"_blank\", \"noopener,noreferrer\");\n }}\n />\n )}\n </span>\n );\n};\n\nconst TERMINAL_STATUSES = new Set([\"DONE\", \"COMPLETED\", \"FAILED\"]);\n\n\ninterface IngestionStatusComponentProps {\n ingestionId?: string;\n status?: string;\n wsBaseUrl?: string;\n showPercentage?: boolean;\n statusMap?: Record<string, string>;\n customStatusConfigs?: Record<string, CustomChipConfig>;\n redirectionLink?: string;\n authToken?: string;\n\n}\n\nexport const IngestionStatusComponent: React.FC<IngestionStatusComponentProps> = ({\n ingestionId,\n status,\n wsBaseUrl,\n showPercentage = true,\n statusMap,\n customStatusConfigs,\n redirectionLink,\n authToken\n}) => {\n console.log(\"Component:\", redirectionLink);\n\n const isTerminal = status ? TERMINAL_STATUSES.has(status.toUpperCase()) : false;\n\n const { data } = useIngestionWebSocket(\n !isTerminal && ingestionId ? ingestionId : null,\n wsBaseUrl,\n authToken\n );\n\n const rawForMapping: string = isTerminal\n ? status!\n : data?.ingestionStatus ?? status ?? \"\";\n\n const resolvedStatus: string = rawForMapping\n ? mapStatus(rawForMapping, statusMap)\n : \"pending\";\n\n const customConfig: CustomChipConfig | undefined = customStatusConfigs\n ? customStatusConfigs[resolvedStatus] ??\n customStatusConfigs[rawForMapping] ??\n customStatusConfigs[rawForMapping.toUpperCase()]\n : undefined;\n\n const percentage = (() => {\n if (isTerminal || !showPercentage) return undefined;\n if (data?.currentProgress !== undefined) return Math.max(5, data.currentProgress);\n if (resolvedStatus === \"in_progress\") return 5;\n return undefined;\n })();\n\n return <IngestionStatusChip status={resolvedStatus} percentage={percentage} customConfig={customConfig} redirectionLink={redirectionLink}\n />;\n};\n\n"],"names":["STATUS_CONFIG","ingested","label","className","styles","failed","in_progress","inProgress","pending","IngestionStatusChip","status","percentage","customConfig","redirectionLink","jsx","chip","style","border","borderColor","background","color","children","config","showPercentage","jsxs","display","alignItems","gap","Fragment","dot","ExternalLink","size","cursor","flexShrink","onClick","e","stopPropagation","window","open","TERMINAL_STATUSES","Set","ingestionId","wsBaseUrl","statusMap","customStatusConfigs","authToken","console","log","isTerminal","has","toUpperCase","data","useIngestionWebSocket","rawForMapping","ingestionStatus","resolvedStatus","rawStatus","upper","mapStatus","currentProgress","Math","max"],"mappings":"6MAMA,MAAMA,EAGF,CACFC,SAAU,CAAEC,MAAO,WAAYC,UAAWC,EAAAA,QAAOH,UACjDI,OAAQ,CAAEH,MAAO,mBAAoBC,UAAWC,EAAAA,QAAOC,QACvDC,YAAa,CAAEJ,MAAO,eAAgBC,UAAWC,EAAAA,QAAOG,YACxDC,QAAS,CAAEN,MAAO,UAAWC,UAAWC,EAAAA,QAAOI,UA8B1C,MAAMC,EAA0D,EACrEC,SACAR,QACAS,aACAC,eACAC,sBAEA,GAAID,EAEA,OAAAE,EAAAA,IAAC,OAAA,CACCX,UAAWC,EAAO,QAAAW,KAClBC,MAAO,CACLC,OAA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D,CACO,MAAA,QACT,CA8GMC,CAAUL,EAAeV,GACzB,UAEE/B,EAA6CgC,EAC/CA,EAAoBW,IACpBX,EAAoBS,IACpBT,EAAoBS,EAAcH,oBAClC,EAEEvC,QACA,IAAAqC,GAAezB,EACf,YAAqC,IAArC4B,GAAMQ,gBAAsCC,KAAKC,IAAI,EAAGV,EAAKQ,iBAC1C,gBAAnBJ,EAAyC,OAAzC,CAEH,KAEI,OAAAzC,EAAAA,IAACL,EAAA,CAAoBC,OAAQ6C,EAAgB5C,aAAwBC,eAA4BC"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t=new Set(["DONE","COMPLETED","FAILED"]);const n=new Map;function r(e,t,r){t.listeners.delete(r),0===t.listeners.size&&n.get(e)===t&&(clearInterval(t.keepAliveInterval),t.ws.readyState!==WebSocket.OPEN&&t.ws.readyState!==WebSocket.CONNECTING||t.ws.close(),n.delete(e))}exports.useIngestionWebSocket=function(s,o){const[l,c]=e.useState(null),[a,i]=e.useState(!1),[u,d]=e.useState(null),f=e.useRef(null),S=e.useRef(null),v=e.useRef(s);e.useEffect(()=>{v.current=s},[s]);const p=e.useCallback(()=>{const e=v.current;e&&f.current&&S.current&&r(e,f.current,S.current),f.current=null,S.current=null,i(!1)},[]);return e.useEffect(()=>{if(!s)return;d(null);const e=function(e,r){if(!r||"string"!=typeof r||!r.trim())return console.error("useIngestionWebSocket: wsBaseUrl is missing or invalid; skipping connection."),null;const s=n.get(e);if(s&&s.ws.readyState!==WebSocket.CLOSED)return s;const o=new WebSocket(`${r.trim()}/${e}`),l={ws:o,listeners:new Set,lastData:null,keepAliveInterval:setInterval(()=>{o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"ping"}))},5e3)};return o.onmessage=r=>{let s;try{s=JSON.parse(r.data)}catch{return void l.listeners.forEach(e=>e(null,"Failed to parse WebSocket message"))}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.ingestionStatus&&"string"==typeof t.ingestionId}(s))return void l.listeners.forEach(e=>e(null,"Received malformed WebSocket payload"));const c=s;l.lastData=c,l.listeners.forEach(e=>e(c,null)),t.has(c.ingestionStatus.toUpperCase())&&(clearInterval(l.keepAliveInterval),o.close(),n.delete(e))},o.onerror=()=>{l.listeners.forEach(e=>e(null,"WebSocket connection error"))},o.onclose=()=>{clearInterval(l.keepAliveInterval),n.get(e)===l&&n.delete(e)},n.set(e,l),l}(s,o);if(!e)return d("Missing or invalid WebSocket base URL"),void i(!1);e.lastData&&c(e.lastData),i(e.ws.readyState===WebSocket.OPEN);const l=(e,t)=>{t?d(t):c(e)};e.listeners.add(l),f.current=e,S.current=l;const a=()=>i(!0),u=()=>i(!1);return e.ws.addEventListener("open",a),e.ws.addEventListener("close",u),()=>{e.ws.removeEventListener("open",a),e.ws.removeEventListener("close",u),r(s,e,l),f.current=null,S.current=null}},[s,o]),{data:l,connected:a,error:u,disconnect:p}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t=new Set(["DONE","COMPLETED","FAILED"]);const n=new Map;function r(e,t,r){t.listeners.delete(r),0===t.listeners.size&&n.get(e)===t&&(clearInterval(t.keepAliveInterval),t.ws.readyState!==WebSocket.OPEN&&t.ws.readyState!==WebSocket.CONNECTING||t.ws.close(),n.delete(e))}exports.useIngestionWebSocket=function(s,o,l){const[c,a]=e.useState(null),[i,u]=e.useState(!1),[d,f]=e.useState(null),S=e.useRef(null),v=e.useRef(null),p=e.useRef(s);e.useEffect(()=>{p.current=s},[s]);const k=e.useCallback(()=>{const e=p.current;e&&S.current&&v.current&&r(e,S.current,v.current),S.current=null,v.current=null,u(!1)},[]);return e.useEffect(()=>{if(!s)return;f(null);const e=function(e,r,s){if(!r||"string"!=typeof r||!r.trim())return console.error("useIngestionWebSocket: wsBaseUrl is missing or invalid; skipping connection."),null;const o=n.get(e);if(o&&o.ws.readyState!==WebSocket.CLOSED)return o;let l=`${r.trim()}/${e}`;s&&(l+=`?token=${s}`);const c=new WebSocket(l),a={ws:c,listeners:new Set,lastData:null,keepAliveInterval:setInterval(()=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({type:"ping"}))},5e3)};return c.onmessage=r=>{let s;try{s=JSON.parse(r.data)}catch{return void a.listeners.forEach(e=>e(null,"Failed to parse WebSocket message"))}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.ingestionStatus&&"string"==typeof t.ingestionId}(s))return void a.listeners.forEach(e=>e(null,"Received malformed WebSocket payload"));const o=s;a.lastData=o,a.listeners.forEach(e=>e(o,null)),t.has(o.ingestionStatus.toUpperCase())&&(clearInterval(a.keepAliveInterval),c.close(),n.delete(e))},c.onerror=()=>{a.listeners.forEach(e=>e(null,"WebSocket connection error"))},c.onclose=()=>{clearInterval(a.keepAliveInterval),n.get(e)===a&&n.delete(e)},n.set(e,a),a}(s,o,l);if(!e)return f("Missing or invalid WebSocket base URL"),void u(!1);e.lastData&&a(e.lastData),u(e.ws.readyState===WebSocket.OPEN);const c=(e,t)=>{t?f(t):a(e)};e.listeners.add(c),S.current=e,v.current=c;const i=()=>u(!0),d=()=>u(!1);return e.ws.addEventListener("open",i),e.ws.addEventListener("close",d),()=>{e.ws.removeEventListener("open",i),e.ws.removeEventListener("close",d),r(s,e,c),S.current=null,v.current=null}},[s,o]),{data:c,connected:i,error:d,disconnect:k}};
2
2
  //# sourceMappingURL=useIngestionStatus.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useIngestionStatus.js","sources":["../../../../src/features/IngestionStatus/useIngestionStatus.tsx"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from \"react\";\n\nexport interface ArtifactLayer {\n label: string;\n layerStatus: string;\n currentProgress: number;\n chunks: { total: number; completed: number; failed: number };\n}\n\nexport interface Artifact {\n artifactId: string;\n name: string;\n status: string;\n artifactSize: string;\n layers: ArtifactLayer[];\n}\n\nexport interface WebSocketIngestionData {\n ingestionStatus: string;\n ingestionId: string;\n currentProgress: number;\n createdAt: string;\n completedAt?: string | null;\n eta?: string | null;\n artifacts: Artifact[];\n total_artifacts?: number;\n layer_orchestration_count?: number;\n artifactStatus?: {\n \"in-progress\": number;\n completed: number;\n queued: number;\n };\n}\n\nconst TERMINAL_STATUSES = new Set([\"DONE\", \"COMPLETED\", \"FAILED\"]);\n\n// Minimal runtime shape check for incoming WS payloads. We don't pull in a\n// full schema library for one message type — just guard the fields we\n// actually branch on (ingestionStatus) and require an object shape overall.\nfunction isValidIngestionPayload(value: unknown): value is WebSocketIngestionData {\n if (!value || typeof value !== \"object\") return false;\n const candidate = value as Record<string, unknown>;\n return typeof candidate.ingestionStatus === \"string\" && typeof candidate.ingestionId === \"string\";\n}\n\n// --- Shared connection registry -------------------------------------------\n// One real WebSocket per ingestionId, fanned out to any number of subscribers.\n// This lets multiple TimelineItem/IngestionStatusComponent instances that\n// happen to share the same ingestionId (e.g. a batched multi-file upload)\n// observe the same socket instead of each opening (and closing) their own.\ntype Listener = (data: WebSocketIngestionData | null, error: string | null) => void;\n\ninterface SharedConnection {\n ws: WebSocket;\n keepAliveInterval: ReturnType<typeof setInterval>;\n listeners: Set<Listener>;\n lastData: WebSocketIngestionData | null;\n}\n\nconst sharedConnections = new Map<string, SharedConnection>();\n\nfunction releaseListener(ingestionId: string, conn: SharedConnection, listener: Listener) {\n conn.listeners.delete(listener);\n\n // Last subscriber leaving → actually tear down the socket.\n if (conn.listeners.size === 0 && sharedConnections.get(ingestionId) === conn) {\n clearInterval(conn.keepAliveInterval);\n if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) {\n conn.ws.close();\n }\n sharedConnections.delete(ingestionId);\n }\n}\n\nfunction getOrCreateConnection(ingestionId: string, wsBaseUrl?: string): SharedConnection | null {\n if (!wsBaseUrl || typeof wsBaseUrl !== \"string\" || !wsBaseUrl.trim()) {\n console.error(\"useIngestionWebSocket: wsBaseUrl is missing or invalid; skipping connection.\");\n return null;\n }\n\n const existing = sharedConnections.get(ingestionId);\n if (existing && existing.ws.readyState !== WebSocket.CLOSED) {\n return existing;\n }\n\n const ws = new WebSocket(`${wsBaseUrl.trim()}/${ingestionId}`);\n const conn: SharedConnection = {\n ws,\n listeners: new Set(),\n lastData: null,\n keepAliveInterval: setInterval(() => {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: \"ping\" }));\n }\n }, 5000),\n };\n\n ws.onmessage = (event) => {\n let rawData: unknown;\n try {\n rawData = JSON.parse(event.data);\n } catch {\n conn.listeners.forEach((listener) => listener(null, \"Failed to parse WebSocket message\"));\n return;\n }\n\n if (!isValidIngestionPayload(rawData)) {\n conn.listeners.forEach((listener) => listener(null, \"Received malformed WebSocket payload\"));\n return;\n }\n\n // Bind to a const so the narrowed type survives inside the closures below —\n // `let` bindings get widened back to their declared type inside closures\n // since TS can't prove they won't be reassigned before the closure runs.\n const payload: WebSocketIngestionData = rawData;\n\n conn.lastData = payload;\n conn.listeners.forEach((listener) => listener(payload, null));\n\n if (TERMINAL_STATUSES.has(payload.ingestionStatus.toUpperCase())) {\n clearInterval(conn.keepAliveInterval);\n ws.close();\n sharedConnections.delete(ingestionId);\n }\n};\n\n ws.onerror = () => {\n conn.listeners.forEach((listener) => listener(null, \"WebSocket connection error\"));\n };\n\n ws.onclose = () => {\n clearInterval(conn.keepAliveInterval);\n // Only remove from the registry if this is still the active connection\n // for this id (avoids racing a newer reconnect attempt).\n if (sharedConnections.get(ingestionId) === conn) {\n sharedConnections.delete(ingestionId);\n }\n };\n\n sharedConnections.set(ingestionId, conn);\n return conn;\n}\n\nexport function useIngestionWebSocket(ingestionId: string | null, wsBaseUrl?: string) {\n const [data, setData] = useState<WebSocketIngestionData | null>(null);\n const [connected, setConnected] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Track the current connection + listener so the imperative disconnect()\n // below can unsubscribe/close outside of the effect's own cleanup.\n const connRef = useRef<SharedConnection | null>(null);\n const listenerRef = useRef<Listener | null>(null);\n const ingestionIdRef = useRef<string | null>(ingestionId);\n\n useEffect(() => {\n ingestionIdRef.current = ingestionId;\n }, [ingestionId]);\n\n const disconnect = useCallback(() => {\n const currentId = ingestionIdRef.current;\n if (currentId && connRef.current && listenerRef.current) {\n releaseListener(currentId, connRef.current, listenerRef.current);\n }\n connRef.current = null;\n listenerRef.current = null;\n setConnected(false);\n }, []);\n\n useEffect(() => {\n if (!ingestionId) return;\n\n setError(null);\n\n const conn = getOrCreateConnection(ingestionId, wsBaseUrl);\n if (!conn) {\n setError(\"Missing or invalid WebSocket base URL\");\n setConnected(false);\n return;\n }\n\n // Seed with whatever the shared connection already has, so a late\n // subscriber isn't stuck blank until the next message arrives.\n if (conn.lastData) setData(conn.lastData);\n setConnected(conn.ws.readyState === WebSocket.OPEN);\n\n const listener: Listener = (newData, newError) => {\n if (newError) {\n setError(newError);\n return;\n }\n setData(newData);\n };\n\n conn.listeners.add(listener);\n connRef.current = conn;\n listenerRef.current = listener;\n\n const handleOpen = () => setConnected(true);\n const handleClose = () => setConnected(false);\n conn.ws.addEventListener(\"open\", handleOpen);\n conn.ws.addEventListener(\"close\", handleClose);\n\n return () => {\n conn.ws.removeEventListener(\"open\", handleOpen);\n conn.ws.removeEventListener(\"close\", handleClose);\n releaseListener(ingestionId, conn, listener);\n connRef.current = null;\n listenerRef.current = null;\n };\n }, [ingestionId, wsBaseUrl]);\n\n return { data, connected, error, disconnect };\n}"],"names":["TERMINAL_STATUSES","Set","sharedConnections","Map","releaseListener","ingestionId","conn","listener","listeners","delete","size","get","clearInterval","keepAliveInterval","ws","readyState","WebSocket","OPEN","CONNECTING","close","wsBaseUrl","data","setData","useState","connected","setConnected","error","setError","connRef","useRef","listenerRef","ingestionIdRef","useEffect","current","disconnect","useCallback","currentId","trim","console","existing","CLOSED","lastData","setInterval","send","JSON","stringify","type","onmessage","event","rawData","parse","forEach","value","candidate","ingestionStatus","isValidIngestionPayload","payload","has","toUpperCase","onerror","onclose","set","getOrCreateConnection","newData","newError","add","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3B,EAClBwB,EAAYG,QAAU1B,EAEhB,MAAA2D,EAAa,IAAMzC,GAAa,GAChC0C,EAAc,IAAM1C,GAAa,GAIvC,OAHKnB,EAAAQ,GAAGsD,iBAAiB,OAAQF,GAC5B5D,EAAAQ,GAAGsD,iBAAiB,QAASD,GAE3B,KACA7D,EAAAQ,GAAGuD,oBAAoB,OAAQH,GAC/B5D,EAAAQ,GAAGuD,oBAAoB,QAASF,GACrB/D,EAAAC,EAAaC,EAAMC,GACnCqB,EAAQK,QAAU,KAClBH,EAAYG,QAAU,OAEvB,CAAC5B,EAAae,IAEV,CAAEC,OAAMG,YAAWE,QAAOQ,aACnC"}
1
+ {"version":3,"file":"useIngestionStatus.js","sources":["../../../../src/features/IngestionStatus/useIngestionStatus.tsx"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from \"react\";\n\nexport interface ArtifactLayer {\n label: string;\n layerStatus: string;\n currentProgress: number;\n chunks: { total: number; completed: number; failed: number };\n}\n\nexport interface Artifact {\n artifactId: string;\n name: string;\n status: string;\n artifactSize: string;\n layers: ArtifactLayer[];\n}\n\nexport interface WebSocketIngestionData {\n ingestionStatus: string;\n ingestionId: string;\n currentProgress: number;\n createdAt: string;\n completedAt?: string | null;\n eta?: string | null;\n artifacts: Artifact[];\n total_artifacts?: number;\n layer_orchestration_count?: number;\n artifactStatus?: {\n \"in-progress\": number;\n completed: number;\n queued: number;\n };\n}\n\nconst TERMINAL_STATUSES = new Set([\"DONE\", \"COMPLETED\", \"FAILED\"]);\n\n// Minimal runtime shape check for incoming WS payloads. We don't pull in a\n// full schema library for one message type — just guard the fields we\n// actually branch on (ingestionStatus) and require an object shape overall.\nfunction isValidIngestionPayload(value: unknown): value is WebSocketIngestionData {\n if (!value || typeof value !== \"object\") return false;\n const candidate = value as Record<string, unknown>;\n return typeof candidate.ingestionStatus === \"string\" && typeof candidate.ingestionId === \"string\";\n}\n\n// --- Shared connection registry -------------------------------------------\n// One real WebSocket per ingestionId, fanned out to any number of subscribers.\n// This lets multiple TimelineItem/IngestionStatusComponent instances that\n// happen to share the same ingestionId (e.g. a batched multi-file upload)\n// observe the same socket instead of each opening (and closing) their own.\ntype Listener = (data: WebSocketIngestionData | null, error: string | null) => void;\n\ninterface SharedConnection {\n ws: WebSocket;\n keepAliveInterval: ReturnType<typeof setInterval>;\n listeners: Set<Listener>;\n lastData: WebSocketIngestionData | null;\n}\n\nconst sharedConnections = new Map<string, SharedConnection>();\n\nfunction releaseListener(ingestionId: string, conn: SharedConnection, listener: Listener) {\n conn.listeners.delete(listener);\n\n // Last subscriber leaving → actually tear down the socket.\n if (conn.listeners.size === 0 && sharedConnections.get(ingestionId) === conn) {\n clearInterval(conn.keepAliveInterval);\n if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) {\n conn.ws.close();\n }\n sharedConnections.delete(ingestionId);\n }\n}\n\nfunction getOrCreateConnection(ingestionId: string, wsBaseUrl?: string, authToken?: string): SharedConnection | null {\n if (!wsBaseUrl || typeof wsBaseUrl !== \"string\" || !wsBaseUrl.trim()) {\n console.error(\"useIngestionWebSocket: wsBaseUrl is missing or invalid; skipping connection.\");\n return null;\n }\n\n const existing = sharedConnections.get(ingestionId);\n if (existing && existing.ws.readyState !== WebSocket.CLOSED) {\n return existing;\n }\n let wsUrl = `${wsBaseUrl.trim()}/${ingestionId}`;\n if(authToken){\n wsUrl+=`?token=${authToken}`;\n }\n\n const ws = new WebSocket(wsUrl);\n const conn: SharedConnection = {\n ws,\n listeners: new Set(),\n lastData: null,\n keepAliveInterval: setInterval(() => {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: \"ping\" }));\n }\n }, 5000),\n };\n\n ws.onmessage = (event) => {\n let rawData: unknown;\n try {\n rawData = JSON.parse(event.data);\n } catch {\n conn.listeners.forEach((listener) => listener(null, \"Failed to parse WebSocket message\"));\n return;\n }\n\n if (!isValidIngestionPayload(rawData)) {\n conn.listeners.forEach((listener) => listener(null, \"Received malformed WebSocket payload\"));\n return;\n }\n\n // Bind to a const so the narrowed type survives inside the closures below —\n // `let` bindings get widened back to their declared type inside closures\n // since TS can't prove they won't be reassigned before the closure runs.\n const payload: WebSocketIngestionData = rawData;\n\n conn.lastData = payload;\n conn.listeners.forEach((listener) => listener(payload, null));\n\n if (TERMINAL_STATUSES.has(payload.ingestionStatus.toUpperCase())) {\n clearInterval(conn.keepAliveInterval);\n ws.close();\n sharedConnections.delete(ingestionId);\n }\n};\n\n ws.onerror = () => {\n conn.listeners.forEach((listener) => listener(null, \"WebSocket connection error\"));\n };\n\n ws.onclose = () => {\n clearInterval(conn.keepAliveInterval);\n // Only remove from the registry if this is still the active connection\n // for this id (avoids racing a newer reconnect attempt).\n if (sharedConnections.get(ingestionId) === conn) {\n sharedConnections.delete(ingestionId);\n }\n };\n\n sharedConnections.set(ingestionId, conn);\n return conn;\n}\n\nexport function useIngestionWebSocket(ingestionId: string | null, wsBaseUrl?: string, authToken?: string) {\n const [data, setData] = useState<WebSocketIngestionData | null>(null);\n const [connected, setConnected] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Track the current connection + listener so the imperative disconnect()\n // below can unsubscribe/close outside of the effect's own cleanup.\n const connRef = useRef<SharedConnection | null>(null);\n const listenerRef = useRef<Listener | null>(null);\n const ingestionIdRef = useRef<string | null>(ingestionId);\n\n useEffect(() => {\n ingestionIdRef.current = ingestionId;\n }, [ingestionId]);\n\n const disconnect = useCallback(() => {\n const currentId = ingestionIdRef.current;\n if (currentId && connRef.current && listenerRef.current) {\n releaseListener(currentId, connRef.current, listenerRef.current);\n }\n connRef.current = null;\n listenerRef.current = null;\n setConnected(false);\n }, []);\n\n useEffect(() => {\n if (!ingestionId) return;\n\n setError(null);\n\n const conn = getOrCreateConnection(ingestionId, wsBaseUrl, authToken);\n if (!conn) {\n setError(\"Missing or invalid WebSocket base URL\");\n setConnected(false);\n return;\n }\n\n // Seed with whatever the shared connection already has, so a late\n // subscriber isn't stuck blank until the next message arrives.\n if (conn.lastData) setData(conn.lastData);\n setConnected(conn.ws.readyState === WebSocket.OPEN);\n\n const listener: Listener = (newData, newError) => {\n if (newError) {\n setError(newError);\n return;\n }\n setData(newData);\n };\n\n conn.listeners.add(listener);\n connRef.current = conn;\n listenerRef.current = listener;\n\n const handleOpen = () => setConnected(true);\n const handleClose = () => setConnected(false);\n conn.ws.addEventListener(\"open\", handleOpen);\n conn.ws.addEventListener(\"close\", handleClose);\n\n return () => {\n conn.ws.removeEventListener(\"open\", handleOpen);\n conn.ws.removeEventListener(\"close\", handleClose);\n releaseListener(ingestionId, conn, listener);\n connRef.current = null;\n listenerRef.current = null;\n };\n }, [ingestionId, wsBaseUrl]);\n\n return { data, connected, error, disconnect };\n}"],"names":["TERMINAL_STATUSES","Set","sharedConnections","Map","releaseListener","ingestionId","conn","listener","listeners","delete","size","get","clearInterval","keepAliveInterval","ws","readyState","WebSocket","OPEN","CONNECTING","close","wsBaseUrl","authToken","data","setData","useState","connected","setConnected","error","setError","connRef","useRef","listenerRef","ingestionIdRef","useEffect","current","disconnect","useCallback","currentId","trim","console","existing","CLOSED","wsUrl","lastData","setInterval","send","JSON","stringify","type","onmessage","event","rawData","parse","forEach","value","candidate","ingestionStatus","isValidIngestionPayload","payload","has","toUpperCase","onerror","onclose","set","getOrCreateConnection","newData","newError","add","handleOpen","handleClose","addEventListener","removeEventListener"],"mappings":"2FAkCA,MAAMA,EAAwB,IAAAC,IAAI,CAAC,OAAQ,YAAa,WAyBxD,MAAMC,MAAwBC,IAE9B,SAASC,EAAgBC,EAAqBC,EAAwBC,GAC/DD,EAAAE,UAAUC,OAAOF,GAGM,IAAxBD,EAAKE,UAAUE,MAAcR,EAAkBS,IAAIN,KAAiBC,IACtEM,cAAcN,EAAKO,mBACfP,EAAKQ,GAAGC,aAAeC,UAAUC,MAAQX,EAAKQ,GAAGC,aAAeC,UAAUE,YAC5EZ,EAAKQ,GAAGK,QAEVjB,EAAkBO,OAAOJ,GAE7B,+BA2EgB,SAAsB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,QAAU,OAEvB,CAAC7B,EAAae,IAEV,CAAEE,OAAMG,YAAWE,QAAOQ,aACnC"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("@react-pdf-viewer/core"),r=require("./PdfContainer.js"),n=require("./PdfToolbar.js"),o=require("./PdfStyle.js"),i=require("./usePdfHighlight.js"),a=require("./rotationManager.js");require("@react-pdf-viewer/zoom/lib/styles/index.css"),require("@react-pdf-viewer/page-navigation/lib/styles/index.css"),require("@react-pdf-viewer/core/lib/styles/index.css"),require("@react-pdf-viewer/search/lib/styles/index.css");var s=require("react"),c=require("../ScannedDocCitation/ScannedDocCitation.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("./PdfViewer.css.js");var u=l(s);exports.default=({pdfUrl:l,highlightText:d,highlightPages:g,highlightCordinatePages:h,highlightColor:f="yellow",activeHighlightColor:p="#f7dc51",jumpToPageValue:m=0,pdfName:v,onClose:y,customStyles:w,customClasses:x,customIcons:P,useCoordinates:S,fallbackPages:T,activeCitationIndex:C,onActiveCitationChange:b,headerAction:q,isZoomEnabled:R=!0,showHighlightsAction:A=!0,defaultScale:_=t.SpecialZoomLevel.ActualSize,useRange:j=!1,rangeOfPages:I=null,showFullScreenAction:L=!0,showRotateButton:M=!1,segments:E=[{title:"Document 2",start_page:52,end_page:52,page_count:1}],segmentTooltipText:F,onCurrentPageChange:H,navigationRequest:N,onNavigationSettled:B,disablePdfAnnotations:Z=!1,disablePdfTextLayer:V=!1,renderPage:k,setRenderRange:z,onError:D})=>{const O=s.useRef(null),W=(e=>{switch(e){case"ActualSize":return t.SpecialZoomLevel.ActualSize;case"PageFit":return t.SpecialZoomLevel.PageFit;case"PageWidth":return t.SpecialZoomLevel.PageWidth;default:return e??t.SpecialZoomLevel.PageWidth}})(_),[U,$]=s.useState(0),[J,K]=s.useState(0),[G,Q]=s.useState(0),X=s.useRef(null),Y=s.useRef(null),ee=s.useRef(0),te=s.useRef(null),re=s.useMemo(()=>{if(!l)return"";try{return new URL(l,window.location.origin).pathname.split("/").pop()||"default"}catch{return"default"}},[l]);s.useEffect(()=>{re&&a.rotationManager.setPdfIdentifier(re)},[re]);s.useEffect(()=>a.rotationManager.onRotationChange((e,t)=>{e===U+1&&Q(t)}),[U]),s.useEffect(()=>{const e=new MutationObserver(()=>{const e=O.current?.querySelectorAll('[data-testid^="core__page-layer-"]'),t=new Set;e?.forEach(e=>{const r=e.getAttribute("data-testid")?.match(/core__page-layer-(\d+)/);if(r&&r.length>=2){const n=parseInt(r[1],10)+1;t.has(n)||(a.rotationManager.registerPageElement(n,e),t.add(n))}})});return O.current&&(e.observe(O.current,{childList:!0,subtree:!0,attributes:!1}),te.current=e),()=>{e.disconnect(),te.current=null}},[]),s.useEffect(()=>()=>{a.rotationManager.clearAll(),te.current&&te.current.disconnect()},[]),s.useEffect(()=>{const e=U+1;Q(a.rotationManager.getRotation(e))},[U]);const ne=s.useMemo(()=>Z||V?t=>{const r=V?e.jsx("div",{"aria-hidden":"true",style:{display:"none"},children:t.textLayer.children}):t.textLayer.children,n={...t,annotationLayer:{...t.annotationLayer,children:Z?null:t.annotationLayer.children},textLayer:{...t.textLayer,children:r}};return k?k(n):e.jsxs(e.Fragment,{children:[t.canvasLayer.children,r,!Z&&t.annotationLayer.children]})}:k,[Z,V,k]),oe=s.useMemo(()=>{if(S)return new Set(h.map(e=>e.pageIndex));{const e=new Set;return Object.values(g).forEach(t=>{t>0&&e.add(t-1)}),e}},[h,g,S]),ie=(ae=d)&&0!==ae.length?ae.filter(e=>!ae.some(t=>t!==e&&t.includes(e))):ae;var ae;const{highlightIndex:se,setHighlightIndex:ce,cursorIndex:le,setCursorIndex:ue,orderedKeys:de,totalHighlights:ge,getValidPosition:he,tryJump:fe,jumpToPage:pe,zoomTo:me,plugins:ve,controls:ye,hideNonTargetHighlights:we,deduplicateHighlights:xe,scrollToCoord:Pe}=i.PdfHighlightControls(ie,S?{}:g,O,oe,S,S?h:[],f,p),Se=he(le),Te=s.useMemo(()=>{const e=U+1;return E.find(t=>e>=t.start_page&&e<=t.end_page)},[U,E]);s.useEffect(()=>{void 0!==C&&C!==le&&ue(C)},[C]);const Ce={...ye,goToNext:()=>{le>=ge-1||(ye.goToNext(),b&&b(le+1))},goToPrevious:()=>{le<=0||(ye.goToPrevious(),b&&b(le-1))}},be=u.default.useCallback((e,t)=>{ee.current+=1;const r=ee.current;null!=Y.current&&window.clearTimeout(Y.current);let n=null,o=0,i=0;const a=()=>{if(ee.current!==r)return;i+=1;const s=O.current?.querySelector(".rpv-core__inner-pages"),c=O.current?.querySelector(`[data-testid="core__page-layer-${t-1}"]`);if(!s||!c)return i>=40?(Y.current=null,void B?.({pageNumber:t,requestId:e.requestId})):void(Y.current=window.setTimeout(a,50));n===s.scrollTop?o+=1:(n=s.scrollTop,o=0);const l=s.getBoundingClientRect(),u=c.getBoundingClientRect(),d=Boolean(l&&u&&u.bottom>l.top&&u.top<l.bottom);if(o>=2&&d||i>=40)return Y.current=null,void B?.({pageNumber:t,requestId:e.requestId});Y.current=window.setTimeout(a,50)};Y.current=window.setTimeout(a,50)},[B]);if(s.useEffect(()=>()=>{ee.current+=1,null!=Y.current&&window.clearTimeout(Y.current)},[]),s.useEffect(()=>{if(!N||J<=0)return;const e=Math.min(Math.max(Math.trunc(N.pageNumber),1),J),t=`${N.requestId??e}:${e}`;X.current!==t&&(X.current=t,$(e-1),pe(e-1),be(N,e))},[pe,N,J,be]),!l)return e.jsx(c.default,{pages:T,activeCitationIndex:C,onActiveCitationChange:b,headerAction:q});return e.jsxs("div",{ref:O,className:["citation-pdf-viewer",x?.pdfViewerWrapper].filter(Boolean).join(" "),"data-disable-pdf-annotations":Z?"true":void 0,"data-pdf-page-fit":W===t.SpecialZoomLevel.PageFit?"true":void 0,style:{height:"100%",minHeight:0,minWidth:0,overflow:"hidden",display:"flex",flexDirection:"column",...o.pdfStyles.pdfViewer,display:"flex",flexDirection:"column",height:"100%",width:"100%",backgroundColor:"#FAFAFA",...w?.pdfViewer,backgroundColor:"#F1F5F9"},children:[e.jsx(n.default,{highlightIndex:se,totalHighlights:ge,controls:Ce,currentPosition:Se,pdfName:v,onClose:y,pdfUrl:l,viewerRef:O,customStyles:w,customClasses:x,customIcons:P,headerAction:q,isZoomEnabled:R,showHighlightsAction:A,showFullScreenAction:L,currentSegment:Te,segmentTooltipText:F,currentPage:U+1,totalPages:J,onPageNavigate:e=>{const t=Math.min(Math.max(e,1),J||e);$(t-1),pe(t-1)},onRotatePage:()=>{const e=U+1;a.rotationManager.rotatePageBy90(e),Q(a.rotationManager.getRotation(e))},currentPageRotation:G,showRotateButton:M}),e.jsx(r.default,{defaultScale:W,pdfUrl:l,plugins:ve,customStyles:w,onError:D,onLoad:e=>{K(e.doc.numPages);const t=!S&&!j&&m<=0;if(m>0&&!j){const e=m-1,t=de[e],r=g[t],n=h[e];ue(e),console.log(n,"cordinateTargetHighlight"),S&&n.pageIndex>0&&pe(n.pageIndex),r>0&&(setTimeout(()=>{we(oe),xe(r-1)},1e3),S||pe(r-1))}else if(j&&I&&2===I.length){(async()=>{const[e,t]=I;for(let r=e;r<=t;r++){const e=r-1;pe(e),await new Promise(e=>setTimeout(e,1e3)),we(oe);const t=xe(e);if(t&&t>0)break}})()}else if(!S&&g){const e=de.find(e=>g[e]>0);if(void 0!==e){const t=g[e]-1;pe(t),setTimeout(()=>{we(oe),xe(t)},1e3)}}requestAnimationFrame(()=>{t&&fe(),!S&&m>0&&!j&&(()=>{if(!O.current)return;const e=m-1,t=de[e],r=g[t],n=r>0?r-1:0,o={};de.forEach((e,t)=>{const r=g[e];r>0&&(o[r]||(o[r]=[]),o[r].push(t))});const i=(o[r]||[]).indexOf(e);let a=0;const s=()=>{if(a++,a>40)return;const e=O.current?.querySelector(".rpv-core__inner-pages");if(!e)return void setTimeout(s,100);const t=O.current?.querySelector(`[data-testid="core__page-layer-${n}"]`);if(!t)return void setTimeout(s,100);const r=e.getBoundingClientRect(),o=t.getBoundingClientRect();if(!(o.top<r.bottom&&o.bottom>r.top))return void setTimeout(s,100);const c=t.querySelectorAll(".rpv-search__highlight")[i];if(!c)return void setTimeout(s,100);const l=c.getBoundingClientRect(),u=e.scrollTop+(l.top-r.top)-e.clientHeight/2+l.height/2;e.scrollTo({top:u,behavior:"smooth"})};setTimeout(s,500)})()})},onPageChange:e=>{const t=e.currentPage;$(t),H?.(t+1),oe.has(t)?(xe(t),we(oe)):we(oe)},renderPage:ne,setRenderRange:z})]})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("@react-pdf-viewer/core"),r=require("./PdfContainer.js"),n=require("./PdfToolbar.js"),o=require("./PdfStyle.js"),i=require("./usePdfHighlight.js"),a=require("./rotationManager.js");require("@react-pdf-viewer/zoom/lib/styles/index.css"),require("@react-pdf-viewer/page-navigation/lib/styles/index.css"),require("@react-pdf-viewer/core/lib/styles/index.css"),require("@react-pdf-viewer/search/lib/styles/index.css");var s=require("react"),u=require("../ScannedDocCitation/ScannedDocCitation.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("./PdfViewer.css.js");var l=c(s);exports.default=({pdfUrl:c,highlightText:d,highlightPages:g,highlightCordinatePages:h,highlightColor:f="yellow",activeHighlightColor:p="#f7dc51",jumpToPageValue:m,pdfName:v,onClose:x,customStyles:y,customClasses:w,customIcons:P,useCoordinates:b,fallbackPages:S,activeCitationIndex:T,onActiveCitationChange:C,headerAction:q,isZoomEnabled:I=!0,showHighlightsAction:R=!0,defaultScale:A=t.SpecialZoomLevel.ActualSize,useRange:j=!1,rangeOfPages:_=null,showFullScreenAction:L=!0,showRotateButton:M=!1,segments:E=[{title:"Document 2",start_page:52,end_page:52,page_count:1}],segmentTooltipText:F,onCurrentPageChange:N,navigationRequest:H,onNavigationSettled:B,disablePdfAnnotations:Z=!1,disablePdfTextLayer:V=!1,renderPage:k,setRenderRange:z,onError:D})=>{const O=s.useRef(null),W=(e=>{switch(e){case"ActualSize":return t.SpecialZoomLevel.ActualSize;case"PageFit":return t.SpecialZoomLevel.PageFit;case"PageWidth":return t.SpecialZoomLevel.PageWidth;default:return e??t.SpecialZoomLevel.PageWidth}})(A),U=m??(b&&h.length>0?1:0),[$,J]=s.useState(0),[K,G]=s.useState(0),[Q,X]=s.useState(null),[Y,ee]=s.useState(0),te=s.useRef(null),re=s.useRef(null),ne=s.useRef(0),oe=s.useRef(null),ie=s.useRef(null),ae=s.useMemo(()=>{if(!c)return"";try{return new URL(c,window.location.origin).pathname.split("/").pop()||"default"}catch{return"default"}},[c]);s.useEffect(()=>{ae&&a.rotationManager.setPdfIdentifier(ae)},[ae]);s.useEffect(()=>a.rotationManager.onRotationChange((e,t)=>{e===$+1&&ee(t)}),[$]),s.useEffect(()=>{const e=new MutationObserver(()=>{const e=O.current?.querySelectorAll('[data-testid^="core__page-layer-"]'),t=new Set;e?.forEach(e=>{const r=e.getAttribute("data-testid")?.match(/core__page-layer-(\d+)/);if(r&&r.length>=2){const n=parseInt(r[1],10)+1;t.has(n)||(a.rotationManager.registerPageElement(n,e),t.add(n))}})});return O.current&&(e.observe(O.current,{childList:!0,subtree:!0,attributes:!1}),oe.current=e),()=>{e.disconnect(),oe.current=null}},[]),s.useEffect(()=>()=>{a.rotationManager.clearAll(),oe.current&&oe.current.disconnect()},[]),s.useEffect(()=>{const e=$+1;ee(a.rotationManager.getRotation(e))},[$]);const se=s.useMemo(()=>Z||V?t=>{const r=V?e.jsx("div",{"aria-hidden":"true",style:{display:"none"},children:t.textLayer.children}):t.textLayer.children,n={...t,annotationLayer:{...t.annotationLayer,children:Z?null:t.annotationLayer.children},textLayer:{...t.textLayer,children:r}};return k?k(n):e.jsxs(e.Fragment,{children:[t.canvasLayer.children,r,!Z&&t.annotationLayer.children]})}:k,[Z,V,k]),ue=s.useMemo(()=>{if(b)return new Set(h.map(e=>e.pageIndex));{const e=new Set;return Object.values(g).forEach(t=>{t>0&&e.add(t-1)}),e}},[h,g,b]),ce=(le=d)&&0!==le.length?le.filter(e=>!le.some(t=>t!==e&&t.includes(e))):le;var le;const{highlightIndex:de,setHighlightIndex:ge,cursorIndex:he,setCursorIndex:fe,orderedKeys:pe,totalHighlights:me,getValidPosition:ve,tryJump:xe,jumpToPage:ye,zoomTo:we,plugins:Pe,controls:be,hideNonTargetHighlights:Se,deduplicateHighlights:Te,scrollToCoordAfterNav:Ce}=i.PdfHighlightControls(ce,b?{}:g,O,ue,b,b?h:[],f,p);s.useEffect(()=>{if(!b||j||K<=0||Q!==(c??null))return;const e=U-1,t=h[e];if(!t||t.pageIndex<0||t.pageIndex>=K)return;const r=[c,e,t.pageIndex,t.top,t.height].join(":");ie.current!==r&&(ie.current=r,fe(e),ye(t.pageIndex),Ce(t.pageIndex,t.top,t.height))},[h,ye,Q,c,U,Ce,fe,K,b,j]);const qe=ve(he),Ie=s.useMemo(()=>{const e=$+1;return E.find(t=>e>=t.start_page&&e<=t.end_page)},[$,E]);s.useEffect(()=>{void 0!==T&&T!==he&&fe(T)},[T]);const Re={...be,goToNext:()=>{if(he>=me-1)return;const e=he+1;if(b){const t=h[e];if(!t)return;fe(e),ye(t.pageIndex),Ce(t.pageIndex,Number.isFinite(t.top)?t.top:0,Number.isFinite(t.height)?t.height:0)}else be.goToNext();C?.(e)},goToPrevious:()=>{if(he<=0)return;const e=he-1;if(b){const t=h[e];if(!t)return;fe(e),ye(t.pageIndex),Ce(t.pageIndex,Number.isFinite(t.top)?t.top:0,Number.isFinite(t.height)?t.height:0)}else be.goToPrevious();C?.(e)}},Ae=l.default.useCallback((e,t)=>{ne.current+=1;const r=ne.current;null!=re.current&&window.clearTimeout(re.current);let n=null,o=0,i=0;const a=()=>{if(ne.current!==r)return;i+=1;const s=O.current?.querySelector(".rpv-core__inner-pages"),u=O.current?.querySelector(`[data-testid="core__page-layer-${t-1}"]`);if(!s||!u)return i>=40?(re.current=null,void B?.({pageNumber:t,requestId:e.requestId})):void(re.current=window.setTimeout(a,50));n===s.scrollTop?o+=1:(n=s.scrollTop,o=0);const c=s.getBoundingClientRect(),l=u.getBoundingClientRect(),d=Boolean(c&&l&&l.bottom>c.top&&l.top<c.bottom);if(o>=2&&d||i>=40)return re.current=null,void B?.({pageNumber:t,requestId:e.requestId});re.current=window.setTimeout(a,50)};re.current=window.setTimeout(a,50)},[B]);if(s.useEffect(()=>()=>{ne.current+=1,null!=re.current&&window.clearTimeout(re.current)},[]),s.useEffect(()=>{if(!H||K<=0)return;const e=Math.min(Math.max(Math.trunc(H.pageNumber),1),K),t=`${H.requestId??e}:${e}`;te.current!==t&&(te.current=t,J(e-1),ye(e-1),Ae(H,e))},[ye,H,K,Ae]),!c)return e.jsx(u.default,{pages:S,activeCitationIndex:T,onActiveCitationChange:C,headerAction:q});return e.jsxs("div",{ref:O,className:["citation-pdf-viewer",w?.pdfViewerWrapper].filter(Boolean).join(" "),"data-disable-pdf-annotations":Z?"true":void 0,"data-pdf-page-fit":W===t.SpecialZoomLevel.PageFit?"true":void 0,style:{height:"100%",minHeight:0,minWidth:0,overflow:"hidden",display:"flex",flexDirection:"column",...o.pdfStyles.pdfViewer,display:"flex",flexDirection:"column",height:"100%",width:"100%",backgroundColor:"#FAFAFA",...y?.pdfViewer,backgroundColor:"#F1F5F9"},children:[e.jsx(n.default,{highlightIndex:de,totalHighlights:me,controls:Re,currentPosition:qe,pdfName:v,onClose:x,pdfUrl:c,viewerRef:O,customStyles:y,customClasses:w,customIcons:P,headerAction:q,isZoomEnabled:I,showHighlightsAction:R,showFullScreenAction:L,currentSegment:Ie,segmentTooltipText:F,currentPage:$+1,totalPages:K,onPageNavigate:e=>{const t=Math.min(Math.max(e,1),K||e);J(t-1),ye(t-1)},onRotatePage:()=>{const e=$+1;a.rotationManager.rotatePageBy90(e),ee(a.rotationManager.getRotation(e))},currentPageRotation:Y,showRotateButton:M}),e.jsx(r.default,{defaultScale:W,pdfUrl:c,plugins:Pe,customStyles:y,onError:D,onLoad:e=>{G(e.doc.numPages),X(c??null);const t=!b&&!j&&U<=0;if(!b&&U>0&&!j){const e=U-1,t=pe[e],r=void 0!==t?g?.[t]:void 0;fe(e),r>0&&(setTimeout(()=>{Se(ue),Te(r-1)},1e3),ye(r-1))}else if(j&&_&&2===_.length){(async()=>{const[e,t]=_;for(let r=e;r<=t;r++){const e=r-1;ye(e),await new Promise(e=>setTimeout(e,1e3)),Se(ue);const t=Te(e);if(t&&t>0)break}})()}else if(!b&&g){const e=pe.find(e=>g[e]>0);if(void 0!==e){const t=g[e]-1;ye(t),setTimeout(()=>{Se(ue),Te(t)},1e3)}}requestAnimationFrame(()=>{t&&xe(),!b&&U>0&&!j&&(()=>{if(!O.current)return;const e=U-1,t=pe[e],r=g[t],n=r>0?r-1:0,o={};pe.forEach((e,t)=>{const r=g[e];r>0&&(o[r]||(o[r]=[]),o[r].push(t))});const i=(o[r]||[]).indexOf(e);let a=0;const s=()=>{if(a++,a>40)return;const e=O.current?.querySelector(".rpv-core__inner-pages");if(!e)return void setTimeout(s,100);const t=O.current?.querySelector(`[data-testid="core__page-layer-${n}"]`);if(!t)return void setTimeout(s,100);const r=e.getBoundingClientRect(),o=t.getBoundingClientRect();if(!(o.top<r.bottom&&o.bottom>r.top))return void setTimeout(s,100);const u=t.querySelectorAll(".rpv-search__highlight")[i];if(!u)return void setTimeout(s,100);const c=u.getBoundingClientRect(),l=e.scrollTop+(c.top-r.top)-e.clientHeight/2+c.height/2;e.scrollTo({top:l,behavior:"smooth"})};setTimeout(s,500)})()})},onPageChange:e=>{const t=e.currentPage;J(t),N?.(t+1),ue.has(t)?(Te(t),Se(ue)):Se(ue)},renderPage:se,setRenderRange:z})]})};
2
2
  //# sourceMappingURL=PdfViewer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PdfViewer.js","sources":["../../../../src/features/PdfViewer/PdfViewer.tsx"],"sourcesContent":["import { DocumentLoadEvent, PageChangeEvent, RenderPage, SetRenderRange, SpecialZoomLevel, type LoadError } from \"@react-pdf-viewer/core\";\nimport PdfContainer from \"./PdfContainer\";\nimport PdfToolbar from \"./PdfToolbar\";\nimport { pdfStyles } from \"./PdfStyle\";\nimport { PdfHighlightControls } from \"./usePdfHighlight\";\nimport { rotationManager } from \"./rotationManager\";\nimport \"@react-pdf-viewer/zoom/lib/styles/index.css\";\nimport \"@react-pdf-viewer/page-navigation/lib/styles/index.css\";\nimport \"@react-pdf-viewer/core/lib/styles/index.css\";\nimport \"@react-pdf-viewer/search/lib/styles/index.css\";\nimport React, { useMemo, useRef, useEffect, useState } from \"react\";\nimport ScannedDocCitation, { CitationPage } from \"../ScannedDocCitation/ScannedDocCitation\";\nimport \"./PdfViewer.css\";\n\nexport type CustomIconsType = {\n pdfIcon?: React.ReactNode;\n fullScreenIcon?: React.ReactNode;\n downloadIcon?: React.ReactNode;\n closeIcon?: React.ReactNode;\n};\n\nexport type CustomStylesType = {\n pdfViewer?: React.CSSProperties;\n header?: React.CSSProperties;\n pdfIconWrapper?: React.CSSProperties;\n pdfName?: React.CSSProperties;\n pdfContainer?: React.CSSProperties;\n emptyState?: React.CSSProperties;\n};\n\nexport type CustomClassesType = {\n header?: string;\n pdfName?: string;\n actionButton?: string;\n pdfViewerWrapper?: string;\n};\n\nexport type PdfSegment = {\n title: string;\n start_page: number;\n end_page: number;\n page_count: number;\n};\n\ntype PdfScaleOption =\n | \"ActualSize\"\n | \"PageFit\"\n | \"PageWidth\"\n | number;\nexport interface PdfNavigationRequest {\n pageNumber: number;\n /** Change this value to navigate to the same page more than once. */\n requestId?: string | number;\n}\n\nexport interface PdfNavigationSettledEvent extends PdfNavigationRequest {\n pageNumber: number;\n}\n\nexport interface PdfViewerProps {\n pdfUrl?: string;\n highlightText: string[];\n highlightPages?: any;\n highlightCordinatePages: HighlightArea[];\n highlightColor?: string;\n activeHighlightColor?: string;\n jumpToPageValue?: number;\n pdfName?: string;\n onClose?: () => void;\n item?: any;\n customStyles?: CustomStylesType;\n customClasses?: CustomClassesType;\n customIcons?: CustomIconsType;\n useCoordinates: boolean;\n fallbackPages?: CitationPage[];\n activeCitationIndex?: number;\n onActiveCitationChange?: (index: number) => void;\n headerAction?: {\n icon?: React.ReactNode;\n onClick?: () => void;\n tooltip?: string;\n };\n isZoomEnabled?: boolean;\n showHighlightsAction?: boolean;\n defaultScale?: PdfScaleOption;\n useRange?: boolean; //\n rangeOfPages?: number[] | null;\n showFullScreenAction?: boolean;\n showRotateButton?: boolean;\n segments?: PdfSegment[];\n segmentTooltipText?: string;\n onCurrentPageChange?: (pageNumber: number) => void;\n navigationRequest?: PdfNavigationRequest | null;\n onNavigationSettled?: (event: PdfNavigationSettledEvent) => void;\n disablePdfAnnotations?: boolean;\n disablePdfTextLayer?: boolean;\n renderPage?: RenderPage;\n setRenderRange?: SetRenderRange;\n onError?: (error: LoadError) => void;\n}\n\nconst getResolvedScale = (\n scale?: PdfScaleOption\n): SpecialZoomLevel | number => {\n switch (scale) {\n case \"ActualSize\":\n return SpecialZoomLevel.ActualSize;\n\n case \"PageFit\":\n return SpecialZoomLevel.PageFit;\n\n case \"PageWidth\":\n return SpecialZoomLevel.PageWidth;\n\n default:\n return scale ?? SpecialZoomLevel.PageWidth;\n }\n};\n\nexport type HighlightArea = {\n pageIndex: number;\n left: number;\n top: number;\n width: number;\n height: number;\n pageNumber?: number;\n};\n\nconst PdfViewer = ({\n pdfUrl,\n highlightText,\n highlightPages,\n highlightCordinatePages,\n highlightColor = \"yellow\",\n activeHighlightColor = \"#f7dc51\",\n jumpToPageValue = 0,\n pdfName,\n onClose,\n customStyles,\n customClasses,\n customIcons,\n useCoordinates,\n fallbackPages,\n activeCitationIndex,\n onActiveCitationChange,\n headerAction,\n isZoomEnabled = true,\n showHighlightsAction = true,\n defaultScale = SpecialZoomLevel.ActualSize,\n useRange = false,\n rangeOfPages = null,\n showFullScreenAction=true,\n showRotateButton = false,\n segments = [\n {\n title: \"Document 2\",\n start_page: 52,\n end_page: 52,\n page_count: 1,\n },\n ],\n segmentTooltipText,\n onCurrentPageChange,\n navigationRequest,\n onNavigationSettled,\n disablePdfAnnotations = false,\n disablePdfTextLayer = false,\n renderPage,\n setRenderRange,\n onError\n}: PdfViewerProps) => {\n\n const viewerRef = useRef<HTMLDivElement | null>(null);\n const resolvedDefaultScale = getResolvedScale(defaultScale);\n const [currentPage, setCurrentPage] = useState(0);\n const [totalPages, setTotalPages] = useState(0);\n const [currentPageRotation, setCurrentPageRotation] = useState(0);\n const lastNavigationRequestRef = useRef<string | null>(null);\n const navigationSettleTimerRef = useRef<number | null>(null);\n const navigationSettleSequenceRef = useRef(0);\n const mutationObserverRef = useRef<MutationObserver | null>(null);\n\n // Generate PDF identifier for localStorage from URL\n const pdfIdentifier = useMemo(() => {\n if (!pdfUrl) return '';\n // Use last part of URL or hash it\n try {\n const url = new URL(pdfUrl, window.location.origin);\n return url.pathname.split('/').pop() || 'default';\n } catch {\n return 'default';\n }\n }, [pdfUrl]);\n\n // Set up rotation manager with PDF identifier\n useEffect(() => {\n if (pdfIdentifier) {\n rotationManager.setPdfIdentifier(pdfIdentifier);\n }\n }, [pdfIdentifier]);\n\n // Handler for rotating current page (no state update)\n const handleRotatePage = () => {\n const pageNumber = currentPage + 1;\n rotationManager.rotatePageBy90(pageNumber);\n // Manually update state to reflect rotation in UI\n setCurrentPageRotation(rotationManager.getRotation(pageNumber));\n };\n\n // Subscribe to rotation changes to sync UI state\n useEffect(() => {\n const unsubscribe = rotationManager.onRotationChange((pageNum, angle) => {\n // Only update state if current page rotated\n if (pageNum === currentPage + 1) {\n setCurrentPageRotation(angle);\n }\n });\n\n return unsubscribe;\n }, [currentPage]);\n\n // Register page elements with rotation manager\n useEffect(() => {\n const observer = new MutationObserver(() => {\n // Find all newly rendered page elements\n const pageElements = viewerRef.current?.querySelectorAll(\n '[data-testid^=\"core__page-layer-\"]'\n );\n\n const registeredPages = new Set<number>();\n\n pageElements?.forEach((pageElement) => {\n const match = (pageElement as HTMLElement)\n .getAttribute('data-testid')\n ?.match(/core__page-layer-(\\d+)/);\n if (match && match.length >= 2) {\n const pageIndex = parseInt(match[1], 10);\n const pageNumber = pageIndex + 1;\n\n // Only register once per page\n if (!registeredPages.has(pageNumber)) {\n rotationManager.registerPageElement(pageNumber, pageElement as HTMLElement);\n registeredPages.add(pageNumber);\n }\n }\n });\n });\n\n if (viewerRef.current) {\n observer.observe(viewerRef.current, {\n childList: true,\n subtree: true,\n attributes: false,\n });\n mutationObserverRef.current = observer;\n }\n\n return () => {\n observer.disconnect();\n mutationObserverRef.current = null;\n };\n }, []);\n\n // Clean up when unmounting\n useEffect(() => {\n return () => {\n rotationManager.clearAll();\n if (mutationObserverRef.current) {\n mutationObserverRef.current.disconnect();\n }\n };\n }, []);\n\n // Update current page rotation when page changes\n useEffect(() => {\n const pageNumber = currentPage + 1;\n setCurrentPageRotation(rotationManager.getRotation(pageNumber));\n }, [currentPage]);\n const resolvedRenderPage = useMemo<RenderPage | undefined>(() => {\n if (!disablePdfAnnotations && !disablePdfTextLayer) return renderPage;\n\n return (props) => {\n const resolvedTextLayerChildren = disablePdfTextLayer ? (\n <div aria-hidden=\"true\" style={{ display: \"none\" }}>\n {props.textLayer.children}\n </div>\n ) : props.textLayer.children;\n const resolvedProps = {\n ...props,\n annotationLayer: {\n ...props.annotationLayer,\n children: disablePdfAnnotations ? null : props.annotationLayer.children,\n },\n textLayer: {\n ...props.textLayer,\n children: resolvedTextLayerChildren,\n },\n };\n\n const renderedPage = renderPage\n ? renderPage(resolvedProps)\n : (\n <>\n {props.canvasLayer.children}\n {resolvedTextLayerChildren}\n {!disablePdfAnnotations && props.annotationLayer.children}\n </>\n );\n\n return renderedPage;\n };\n }, [disablePdfAnnotations, disablePdfTextLayer, renderPage]);\n\n const cleanHighlightTexts = (texts: string[]): string[] => {\n if (!texts || texts.length === 0) return texts;\n return texts.filter((text) => {\n return !texts.some(\n (otherText) => otherText !== text && otherText.includes(text)\n );\n });\n };\n\n const highlightPageSet = useMemo(() => {\n if (useCoordinates) {\n return new Set(highlightCordinatePages.map((h: any) => h.pageIndex));\n } else {\n const set = new Set<number>();\n Object.values(highlightPages).forEach((p: any) => {\n if (p > 0) set.add(p - 1);\n });\n return set;\n }\n }, [highlightCordinatePages, highlightPages, useCoordinates]);\n\n const removeRedundantHighlightTexts = cleanHighlightTexts(highlightText);\n\n const {\n highlightIndex,\n setHighlightIndex,\n cursorIndex,\n setCursorIndex,\n orderedKeys,\n totalHighlights,\n getValidPosition,\n tryJump,\n jumpToPage,\n zoomTo,\n plugins,\n controls,\n hideNonTargetHighlights,\n deduplicateHighlights,\n scrollToCoord,\n } = PdfHighlightControls(\n removeRedundantHighlightTexts,\n !useCoordinates ? highlightPages : {},\n viewerRef,\n highlightPageSet,\n useCoordinates,\n useCoordinates ? highlightCordinatePages : [],\n highlightColor,\n activeHighlightColor\n );\n\n const currentPosition = getValidPosition(cursorIndex);\n const currentSegment = useMemo(() => {\n const pageNumber = currentPage + 1;\n return segments.find(\n (segment) =>\n pageNumber >= segment.start_page && pageNumber <= segment.end_page\n );\n }, [currentPage, segments]);\n\n // sync external activeCitationIndex → cursorIndex\n useEffect(() => {\n if (activeCitationIndex === undefined) return;\n if (activeCitationIndex === cursorIndex) return;\n setCursorIndex(activeCitationIndex);\n }, [activeCitationIndex]);\n\n // wrap controls to fire onActiveCitationChange\n const handleGoToNext = () => {\n if (cursorIndex >= totalHighlights - 1) return;\n controls.goToNext();\n if (onActiveCitationChange) onActiveCitationChange(cursorIndex + 1);\n };\n\n const handleGoToPrevious = () => {\n if (cursorIndex <= 0) return;\n controls.goToPrevious();\n if (onActiveCitationChange) onActiveCitationChange(cursorIndex - 1);\n };\n\n const modifiedControls = {\n ...controls,\n goToNext: handleGoToNext,\n goToPrevious: handleGoToPrevious,\n };\n\n const handlePageNavigate = (pageNumber: number) => {\n const nextPage = Math.min(Math.max(pageNumber, 1), totalPages || pageNumber);\n setCurrentPage(nextPage - 1);\n jumpToPage(nextPage - 1);\n };\n\n const waitForNavigationToSettle = React.useCallback((\n request: PdfNavigationRequest,\n pageNumber: number\n ) => {\n navigationSettleSequenceRef.current += 1;\n const settleSequence = navigationSettleSequenceRef.current;\n if (navigationSettleTimerRef.current != null) {\n window.clearTimeout(navigationSettleTimerRef.current);\n }\n\n let previousScrollTop: number | null = null;\n let stableChecks = 0;\n let attempts = 0;\n\n const checkScrollPosition = () => {\n if (navigationSettleSequenceRef.current !== settleSequence) return;\n\n attempts += 1;\n\n const scrollContainer = viewerRef.current?.querySelector(\n '.rpv-core__inner-pages'\n ) as HTMLElement | null;\n const targetPage = viewerRef.current?.querySelector(\n `[data-testid=\"core__page-layer-${pageNumber - 1}\"]`\n ) as HTMLElement | null;\n\n // Virtualized page layers are not guaranteed to be mounted on the first\n // check after jumpToPage. Keep polling so navigation completion is not\n // lost while React PDF Viewer is creating the target page DOM.\n if (!scrollContainer || !targetPage) {\n if (attempts >= 40) {\n navigationSettleTimerRef.current = null;\n onNavigationSettled?.({\n pageNumber,\n requestId: request.requestId,\n });\n return;\n }\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n return;\n }\n\n if (previousScrollTop === scrollContainer.scrollTop) {\n stableChecks += 1;\n } else {\n previousScrollTop = scrollContainer.scrollTop;\n stableChecks = 0;\n }\n\n const scrollRect = scrollContainer.getBoundingClientRect();\n const pageRect = targetPage.getBoundingClientRect();\n const isTargetVisible = Boolean(\n scrollRect &&\n pageRect &&\n pageRect.bottom > scrollRect.top &&\n pageRect.top < scrollRect.bottom\n );\n const hasSettled = stableChecks >= 2 && isTargetVisible;\n const reachedTimeout = attempts >= 40;\n\n if (hasSettled || reachedTimeout) {\n navigationSettleTimerRef.current = null;\n onNavigationSettled?.({\n pageNumber,\n requestId: request.requestId,\n });\n return;\n }\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n };\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n }, [onNavigationSettled]);\n\n useEffect(() => () => {\n navigationSettleSequenceRef.current += 1;\n if (navigationSettleTimerRef.current != null) {\n window.clearTimeout(navigationSettleTimerRef.current);\n }\n }, []);\n\n useEffect(() => {\n if (!navigationRequest || totalPages <= 0) return;\n\n const nextPage = Math.min(\n Math.max(Math.trunc(navigationRequest.pageNumber), 1),\n totalPages\n );\n const requestKey = `${navigationRequest.requestId ?? nextPage}:${nextPage}`;\n if (lastNavigationRequestRef.current === requestKey) return;\n\n lastNavigationRequestRef.current = requestKey;\n setCurrentPage(nextPage - 1);\n jumpToPage(nextPage - 1);\n waitForNavigationToSettle(navigationRequest, nextPage);\n }, [jumpToPage, navigationRequest, totalPages, waitForNavigationToSettle]);\n\n if (!pdfUrl) {\n return (\n <ScannedDocCitation\n pages={fallbackPages}\n activeCitationIndex={activeCitationIndex}\n onActiveCitationChange={onActiveCitationChange}\n headerAction={headerAction}\n />\n );\n }\n\n const defaultViewerStyles: React.CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n height: \"100%\",\n width: \"100%\",\n backgroundColor: \"#FAFAFA\",\n };\n\n const scrollToHighlight = () => {\n if (!viewerRef.current) return;\n\n const index = jumpToPageValue - 1;\n const key = orderedKeys[index];\n const page = highlightPages[key];\n const targetPage = page > 0 ? page - 1 : 0;\n\n const pageVisitMap: Record<number, number[]> = {};\n orderedKeys.forEach((k, i) => {\n const p = highlightPages[k];\n if (p > 0) {\n if (!pageVisitMap[p]) pageVisitMap[p] = [];\n pageVisitMap[p].push(i);\n }\n });\n const visits = pageVisitMap[page] || [];\n const occurrence = visits.indexOf(index);\n\n let attempts = 0;\n const maxAttempts = 40;\n\n const doScrollToHighlight = () => {\n attempts++;\n if (attempts > maxAttempts) return;\n\n const scrollContainer = viewerRef.current?.querySelector(\n \".rpv-core__inner-pages\"\n ) as HTMLElement;\n if (!scrollContainer) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const pageElement = viewerRef.current?.querySelector(\n `[data-testid=\"core__page-layer-${targetPage}\"]`\n );\n if (!pageElement) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const scrollContainerRect = scrollContainer.getBoundingClientRect();\n const pageRect = pageElement.getBoundingClientRect();\n const isPageVisible =\n pageRect.top < scrollContainerRect.bottom &&\n pageRect.bottom > scrollContainerRect.top;\n\n if (!isPageVisible) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const allHighlights = pageElement.querySelectorAll(\".rpv-search__highlight\");\n const target = allHighlights[occurrence] as HTMLElement;\n\n if (!target) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const highlightRect = target.getBoundingClientRect();\n const scrollTop =\n scrollContainer.scrollTop +\n (highlightRect.top - scrollContainerRect.top) -\n scrollContainer.clientHeight / 2 +\n highlightRect.height / 2;\n\n scrollContainer.scrollTo({ top: scrollTop, behavior: \"smooth\" });\n };\n\n setTimeout(doScrollToHighlight, 500);\n };\n\n return (\n <div\n ref={viewerRef}\n className={[\"citation-pdf-viewer\", customClasses?.pdfViewerWrapper]\n .filter(Boolean)\n .join(\" \")}\n data-disable-pdf-annotations={\n disablePdfAnnotations ? \"true\" : undefined\n }\n data-pdf-page-fit={\n resolvedDefaultScale === SpecialZoomLevel.PageFit ? \"true\" : undefined\n }\n style={{\n height: \"100%\",\n minHeight: 0,\n minWidth: 0,\n overflow: \"hidden\",\n display: \"flex\",\n flexDirection: \"column\",\n ...pdfStyles.pdfViewer,\n ...defaultViewerStyles,\n ...customStyles?.pdfViewer,\n backgroundColor: \"#F1F5F9\",\n }}\n >\n <PdfToolbar\n highlightIndex={highlightIndex}\n totalHighlights={totalHighlights}\n controls={modifiedControls}\n currentPosition={currentPosition}\n pdfName={pdfName}\n onClose={onClose}\n pdfUrl={pdfUrl}\n viewerRef={viewerRef}\n customStyles={customStyles}\n customClasses={customClasses}\n customIcons={customIcons}\n headerAction={headerAction}\n isZoomEnabled={isZoomEnabled}\n showHighlightsAction={showHighlightsAction}\n showFullScreenAction={showFullScreenAction} \n currentSegment={currentSegment}\n segmentTooltipText={segmentTooltipText}\n currentPage={currentPage + 1}\n totalPages={totalPages}\n onPageNavigate={handlePageNavigate}\n onRotatePage={handleRotatePage}\n currentPageRotation={currentPageRotation}\n showRotateButton={showRotateButton}\n />\n <PdfContainer\n defaultScale={resolvedDefaultScale}\n pdfUrl={pdfUrl}\n plugins={plugins}\n customStyles={customStyles}\n onError={onError}\n onLoad={(e: DocumentLoadEvent) => {\n setTotalPages(e.doc.numPages);\n\n const shouldAutoJumpToFirstMatch =\n !useCoordinates && !useRange && jumpToPageValue <= 0;\n\n if (jumpToPageValue > 0 && !useRange) {\n const index = jumpToPageValue - 1;\n const key = orderedKeys[index];\n const page = highlightPages[key];\n const cordinateTargetHighlight = highlightCordinatePages[index];\n setCursorIndex(index);\n\n console.log(cordinateTargetHighlight, \"cordinateTargetHighlight\");\n if (useCoordinates && cordinateTargetHighlight.pageIndex > 0)\n jumpToPage(cordinateTargetHighlight.pageIndex);\n\n if (page > 0) {\n setTimeout(() => {\n hideNonTargetHighlights(highlightPageSet);\n deduplicateHighlights(page - 1);\n }, 1000);\n if (!useCoordinates) {\n jumpToPage(page - 1);\n }\n }\n } else if (useRange && rangeOfPages && rangeOfPages.length === 2) {\n \n // Async function to handle sequential jumping and waiting\n const scanRangeSequence = async () => {\n const [startPage, endPage] = rangeOfPages;\n \n for (let p = startPage; p <= endPage; p++) {\n const targetPageIndex = p - 1;\n \n jumpToPage(targetPageIndex);\n \n // Pause execution for 1 second to let the DOM render the highlights\n await new Promise((resolve) => setTimeout(resolve, 1000));\n \n hideNonTargetHighlights(highlightPageSet);\n const matchSize = deduplicateHighlights(targetPageIndex);\n \n // If the returned size is greater than 0, a match was found. Stop the loop.\n if (matchSize && matchSize > 0) {\n break; \n }\n }\n };\n\n scanRangeSequence();\n\n } else if (!useCoordinates && highlightPages) {\n const firstKey = orderedKeys.find(k => highlightPages[k] > 0);\n if (firstKey !== undefined) {\n const firstPage = highlightPages[firstKey] - 1;\n jumpToPage(firstPage);\n setTimeout(() => {\n hideNonTargetHighlights(highlightPageSet);\n deduplicateHighlights(firstPage);\n }, 1000);\n }\n }\n\n requestAnimationFrame(() => {\n if (shouldAutoJumpToFirstMatch) {\n tryJump();\n }\n if (!useCoordinates && jumpToPageValue > 0 && !useRange) {\n scrollToHighlight();\n }\n });\n }}\n onPageChange={(e: PageChangeEvent) => {\n const currentPage = e.currentPage;\n setCurrentPage(currentPage);\n onCurrentPageChange?.(currentPage + 1);\n if (!highlightPageSet.has(currentPage)) {\n hideNonTargetHighlights(highlightPageSet);\n return;\n }\n deduplicateHighlights(currentPage);\n hideNonTargetHighlights(highlightPageSet);\n }}\n renderPage={resolvedRenderPage}\n setRenderRange={setRenderRange}\n />\n </div>\n );\n};\n\nexport default PdfViewer;\n"],"names":["pdfUrl","highlightText","highlightPages","highlightCordinatePages","highlightColor","activeHighlightColor","jumpToPageValue","pdfName","onClose","customStyles","customClasses","customIcons","useCoordinates","fallbackPages","activeCitationIndex","onActiveCitationChange","headerAction","isZoomEnabled","showHighlightsAction","defaultScale","SpecialZoomLevel","ActualSize","useRange","rangeOfPages","showFullScreenAction","showRotateButton","segments","title","start_page","end_page","page_count","segmentTooltipText","onCurrentPageChange","navigationRequest","onNavigationSettled","disablePdfAnnotations","disablePdfTextLayer","renderPage","setRenderRange","onError","viewerRef","useRef","resolvedDefaultScale","scale","PageFit","PageWidth","getResolvedScale","currentPage","setCurrentPage","useState","totalPages","setTotalPages","currentPageRotation","setCurrentPageRotation","lastNavigationRequestRef","navigationSettleTimerRef","navigationSettleSequenceRef","mutationObserverRef","pdfIdentifier","useMemo","URL","window","location","origin","pathname","split","pop","useEffect","rotationManager","setPdfIdentifier","onRotationChange","pageNum","angle","observer","MutationObserver","pageElements","current","querySelectorAll","registeredPages","Set","forEach","pageElement","match","getAttribute","length","pageNumber","parseInt","has","registerPageElement","add","observe","childList","subtree","attributes","disconnect","clearAll","getRotation","resolvedRenderPage","props","resolvedTextLayerChildren","jsx","style","display","children","textLayer","resolvedProps","annotationLayer","jsxs","Fragment","canvasLayer","highlightPageSet","map","h","pageIndex","set","Object","values","p","removeRedundantHighlightTexts","texts","filter","text","some","otherText","includes","highlightIndex","setHighlightIndex","cursorIndex","setCursorIndex","orderedKeys","totalHighlights","getValidPosition","tryJump","jumpToPage","zoomTo","plugins","controls","hideNonTargetHighlights","deduplicateHighlights","scrollToCoord","PdfHighlightControls","currentPosition","currentSegment","find","segment","modifiedControls","goToNext","goToPrevious","waitForNavigationToSettle","React","useCallback","request","settleSequence","clearTimeout","previousScrollTop","stableChecks","attempts","checkScrollPosition","scrollContainer","querySelector","targetPage","requestId","setTimeout","scrollTop","scrollRect","getBoundingClientRect","pageRect","isTargetVisible","Boolean","bottom","top","nextPage","Math","min","max","trunc","requestKey","ScannedDocCitation","pages","ref","className","pdfViewerWrapper","join","height","minHeight","minWidth","overflow","flexDirection","pdfStyles","pdfViewer","width","backgroundColor","PdfToolbar","onPageNavigate","onRotatePage","rotatePageBy90","PdfContainer","onLoad","e","doc","numPages","shouldAutoJumpToFirstMatch","index","key","page","cordinateTargetHighlight","console","log","async","startPage","endPage","targetPageIndex","Promise","resolve","matchSize","scanRangeSequence","firstKey","k","firstPage","requestAnimationFrame","pageVisitMap","i","push","occurrence","indexOf","doScrollToHighlight","scrollContainerRect","target","highlightRect","clientHeight","scrollTo","behavior","scrollToHighlight","onPageChange"],"mappings":"guBAgIkB,EAChBA,SACAC,gBACAC,iBACAC,0BACAC,iBAAiB,SACjBC,uBAAuB,UACvBC,kBAAkB,EAClBC,UACAC,UACAC,eACAC,gBACAC,cACAC,iBACAC,gBACAC,sBACAC,yBACAC,eACAC,iBAAgB,EAChBC,wBAAuB,EACvBC,eAAeC,EAAiBA,iBAAAC,WAChCC,YAAW,EACXC,eAAe,KACfC,wBAAqB,EACrBC,oBAAmB,EACnBC,WAAW,CACT,CACEC,MAAO,aACPC,WAAY,GACZC,SAAU,GACVC,WAAY,IAGhBC,qBACAC,sBACAC,oBACAC,sBACAC,yBAAwB,EACxBC,uBAAsB,EACtBC,aACAC,iBACAC,cAGM,MAAAC,EAAYC,SAA8B,MAC1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,KAI5B,MAAAhJ,EAAczC,EAAUoC,SAASmF,cACrC,kCAAkCC,OAEpC,IAAK/E,EAEH,YADAiF,WAAW+D,EAAqB,KAI5B,MAAAC,EAAsBpE,EAAgBO,wBACtCC,EAAWrF,EAAYoF,wBAK7B,KAHEC,EAASI,IAAMwD,EAAoBzD,QACnCH,EAASG,OAASyD,EAAoBxD,KAItC,YADAR,WAAW+D,EAAqB,KAI5B,MACAE,EADgBlJ,EAAYJ,iBAAiB,0BACtBkJ,GAE7B,IAAKI,EAEH,YADAjE,WAAW+D,EAAqB,KAI5B,MAAAG,EAAgBD,EAAO9D,wBACvBF,EACJL,EAAgBK,WACfiE,EAAc1D,IAAMwD,EAAoBxD,KACzCZ,EAAgBuE,aAAe,EAC/BD,EAAc7C,OAAS,EAEzBzB,EAAgBwE,SAAS,CAAE5D,IAAKP,EAAWoE,SAAU,YAGvDrE,WAAW+D,EAAqB,MAgIJO,MAIxBC,aAAenC,IACb,MAAMvJ,EAAcuJ,EAAEvJ,YACtBC,EAAeD,GACff,IAAsBe,EAAc,GAC/B+D,GAAiBvB,IAAIxC,IAI1B2F,GAAsB3F,GACtB0F,GAAwB3B,KAJtB2B,GAAwB3B,KAM5BzE,WAAY4D,GACZ3D"}
1
+ {"version":3,"file":"PdfViewer.js","sources":["../../../../src/features/PdfViewer/PdfViewer.tsx"],"sourcesContent":["import { DocumentLoadEvent, PageChangeEvent, RenderPage, SetRenderRange, SpecialZoomLevel, type LoadError } from \"@react-pdf-viewer/core\";\nimport PdfContainer from \"./PdfContainer\";\nimport PdfToolbar from \"./PdfToolbar\";\nimport { pdfStyles } from \"./PdfStyle\";\nimport { PdfHighlightControls } from \"./usePdfHighlight\";\nimport { rotationManager } from \"./rotationManager\";\nimport \"@react-pdf-viewer/zoom/lib/styles/index.css\";\nimport \"@react-pdf-viewer/page-navigation/lib/styles/index.css\";\nimport \"@react-pdf-viewer/core/lib/styles/index.css\";\nimport \"@react-pdf-viewer/search/lib/styles/index.css\";\nimport React, { useMemo, useRef, useEffect, useState } from \"react\";\nimport ScannedDocCitation, { CitationPage } from \"../ScannedDocCitation/ScannedDocCitation\";\nimport \"./PdfViewer.css\";\n\nexport type CustomIconsType = {\n pdfIcon?: React.ReactNode;\n fullScreenIcon?: React.ReactNode;\n downloadIcon?: React.ReactNode;\n closeIcon?: React.ReactNode;\n};\n\nexport type CustomStylesType = {\n pdfViewer?: React.CSSProperties;\n header?: React.CSSProperties;\n pdfIconWrapper?: React.CSSProperties;\n pdfName?: React.CSSProperties;\n pdfContainer?: React.CSSProperties;\n emptyState?: React.CSSProperties;\n};\n\nexport type CustomClassesType = {\n header?: string;\n pdfName?: string;\n actionButton?: string;\n pdfViewerWrapper?: string;\n};\n\nexport type PdfSegment = {\n title: string;\n start_page: number;\n end_page: number;\n page_count: number;\n};\n\ntype PdfScaleOption =\n | \"ActualSize\"\n | \"PageFit\"\n | \"PageWidth\"\n | number;\nexport interface PdfNavigationRequest {\n pageNumber: number;\n /** Change this value to navigate to the same page more than once. */\n requestId?: string | number;\n}\n\nexport interface PdfNavigationSettledEvent extends PdfNavigationRequest {\n pageNumber: number;\n}\n\nexport interface PdfViewerProps {\n pdfUrl?: string;\n highlightText: string[];\n highlightPages?: any;\n highlightCordinatePages: HighlightArea[];\n highlightColor?: string;\n activeHighlightColor?: string;\n jumpToPageValue?: number;\n pdfName?: string;\n onClose?: () => void;\n item?: any;\n customStyles?: CustomStylesType;\n customClasses?: CustomClassesType;\n customIcons?: CustomIconsType;\n useCoordinates: boolean;\n fallbackPages?: CitationPage[];\n activeCitationIndex?: number;\n onActiveCitationChange?: (index: number) => void;\n headerAction?: {\n icon?: React.ReactNode;\n onClick?: () => void;\n tooltip?: string;\n };\n isZoomEnabled?: boolean;\n showHighlightsAction?: boolean;\n defaultScale?: PdfScaleOption;\n useRange?: boolean; //\n rangeOfPages?: number[] | null;\n showFullScreenAction?: boolean;\n showRotateButton?: boolean;\n segments?: PdfSegment[];\n segmentTooltipText?: string;\n onCurrentPageChange?: (pageNumber: number) => void;\n navigationRequest?: PdfNavigationRequest | null;\n onNavigationSettled?: (event: PdfNavigationSettledEvent) => void;\n disablePdfAnnotations?: boolean;\n disablePdfTextLayer?: boolean;\n renderPage?: RenderPage;\n setRenderRange?: SetRenderRange;\n onError?: (error: LoadError) => void;\n}\n\nconst getResolvedScale = (\n scale?: PdfScaleOption\n): SpecialZoomLevel | number => {\n switch (scale) {\n case \"ActualSize\":\n return SpecialZoomLevel.ActualSize;\n\n case \"PageFit\":\n return SpecialZoomLevel.PageFit;\n\n case \"PageWidth\":\n return SpecialZoomLevel.PageWidth;\n\n default:\n return scale ?? SpecialZoomLevel.PageWidth;\n }\n};\n\nexport type HighlightArea = {\n pageIndex: number;\n left: number;\n top: number;\n width: number;\n height: number;\n pageNumber?: number;\n};\n\nconst PdfViewer = ({\n pdfUrl,\n highlightText,\n highlightPages,\n highlightCordinatePages,\n highlightColor = \"yellow\",\n activeHighlightColor = \"#f7dc51\",\n jumpToPageValue,\n pdfName,\n onClose,\n customStyles,\n customClasses,\n customIcons,\n useCoordinates,\n fallbackPages,\n activeCitationIndex,\n onActiveCitationChange,\n headerAction,\n isZoomEnabled = true,\n showHighlightsAction = true,\n defaultScale = SpecialZoomLevel.ActualSize,\n useRange = false,\n rangeOfPages = null,\n showFullScreenAction=true,\n showRotateButton = false,\n segments = [\n {\n title: \"Document 2\",\n start_page: 52,\n end_page: 52,\n page_count: 1,\n },\n ],\n segmentTooltipText,\n onCurrentPageChange,\n navigationRequest,\n onNavigationSettled,\n disablePdfAnnotations = false,\n disablePdfTextLayer = false,\n renderPage,\n setRenderRange,\n onError\n}: PdfViewerProps) => {\n\n const viewerRef = useRef<HTMLDivElement | null>(null);\n const resolvedDefaultScale = getResolvedScale(defaultScale);\n const resolvedJumpToPageValue =\n jumpToPageValue ??\n (useCoordinates && highlightCordinatePages.length > 0 ? 1 : 0);\n const [currentPage, setCurrentPage] = useState(0);\n const [totalPages, setTotalPages] = useState(0);\n const [loadedPdfUrl, setLoadedPdfUrl] = useState<string | null>(null);\n const [currentPageRotation, setCurrentPageRotation] = useState(0);\n const lastNavigationRequestRef = useRef<string | null>(null);\n const navigationSettleTimerRef = useRef<number | null>(null);\n const navigationSettleSequenceRef = useRef(0);\n const mutationObserverRef = useRef<MutationObserver | null>(null);\n const coordinateAutoJumpKeyRef = useRef<string | null>(null);\n\n // Generate PDF identifier for localStorage from URL\n const pdfIdentifier = useMemo(() => {\n if (!pdfUrl) return '';\n // Use last part of URL or hash it\n try {\n const url = new URL(pdfUrl, window.location.origin);\n return url.pathname.split('/').pop() || 'default';\n } catch {\n return 'default';\n }\n }, [pdfUrl]);\n\n // Set up rotation manager with PDF identifier\n useEffect(() => {\n if (pdfIdentifier) {\n rotationManager.setPdfIdentifier(pdfIdentifier);\n }\n }, [pdfIdentifier]);\n\n // Handler for rotating current page (no state update)\n const handleRotatePage = () => {\n const pageNumber = currentPage + 1;\n rotationManager.rotatePageBy90(pageNumber);\n // Manually update state to reflect rotation in UI\n setCurrentPageRotation(rotationManager.getRotation(pageNumber));\n };\n\n // Subscribe to rotation changes to sync UI state\n useEffect(() => {\n const unsubscribe = rotationManager.onRotationChange((pageNum, angle) => {\n // Only update state if current page rotated\n if (pageNum === currentPage + 1) {\n setCurrentPageRotation(angle);\n }\n });\n\n return unsubscribe;\n }, [currentPage]);\n\n // Register page elements with rotation manager\n useEffect(() => {\n const observer = new MutationObserver(() => {\n // Find all newly rendered page elements\n const pageElements = viewerRef.current?.querySelectorAll(\n '[data-testid^=\"core__page-layer-\"]'\n );\n\n const registeredPages = new Set<number>();\n\n pageElements?.forEach((pageElement) => {\n const match = (pageElement as HTMLElement)\n .getAttribute('data-testid')\n ?.match(/core__page-layer-(\\d+)/);\n if (match && match.length >= 2) {\n const pageIndex = parseInt(match[1], 10);\n const pageNumber = pageIndex + 1;\n\n // Only register once per page\n if (!registeredPages.has(pageNumber)) {\n rotationManager.registerPageElement(pageNumber, pageElement as HTMLElement);\n registeredPages.add(pageNumber);\n }\n }\n });\n });\n\n if (viewerRef.current) {\n observer.observe(viewerRef.current, {\n childList: true,\n subtree: true,\n attributes: false,\n });\n mutationObserverRef.current = observer;\n }\n\n return () => {\n observer.disconnect();\n mutationObserverRef.current = null;\n };\n }, []);\n\n // Clean up when unmounting\n useEffect(() => {\n return () => {\n rotationManager.clearAll();\n if (mutationObserverRef.current) {\n mutationObserverRef.current.disconnect();\n }\n };\n }, []);\n\n // Update current page rotation when page changes\n useEffect(() => {\n const pageNumber = currentPage + 1;\n setCurrentPageRotation(rotationManager.getRotation(pageNumber));\n }, [currentPage]);\n const resolvedRenderPage = useMemo<RenderPage | undefined>(() => {\n if (!disablePdfAnnotations && !disablePdfTextLayer) return renderPage;\n\n return (props) => {\n const resolvedTextLayerChildren = disablePdfTextLayer ? (\n <div aria-hidden=\"true\" style={{ display: \"none\" }}>\n {props.textLayer.children}\n </div>\n ) : props.textLayer.children;\n const resolvedProps = {\n ...props,\n annotationLayer: {\n ...props.annotationLayer,\n children: disablePdfAnnotations ? null : props.annotationLayer.children,\n },\n textLayer: {\n ...props.textLayer,\n children: resolvedTextLayerChildren,\n },\n };\n\n const renderedPage = renderPage\n ? renderPage(resolvedProps)\n : (\n <>\n {props.canvasLayer.children}\n {resolvedTextLayerChildren}\n {!disablePdfAnnotations && props.annotationLayer.children}\n </>\n );\n\n return renderedPage;\n };\n }, [disablePdfAnnotations, disablePdfTextLayer, renderPage]);\n\n const cleanHighlightTexts = (texts: string[]): string[] => {\n if (!texts || texts.length === 0) return texts;\n return texts.filter((text) => {\n return !texts.some(\n (otherText) => otherText !== text && otherText.includes(text)\n );\n });\n };\n\n const highlightPageSet = useMemo(() => {\n if (useCoordinates) {\n return new Set(highlightCordinatePages.map((h: any) => h.pageIndex));\n } else {\n const set = new Set<number>();\n Object.values(highlightPages).forEach((p: any) => {\n if (p > 0) set.add(p - 1);\n });\n return set;\n }\n }, [highlightCordinatePages, highlightPages, useCoordinates]);\n\n const removeRedundantHighlightTexts = cleanHighlightTexts(highlightText);\n\n const {\n highlightIndex,\n setHighlightIndex,\n cursorIndex,\n setCursorIndex,\n orderedKeys,\n totalHighlights,\n getValidPosition,\n tryJump,\n jumpToPage,\n zoomTo,\n plugins,\n controls,\n hideNonTargetHighlights,\n deduplicateHighlights,\n scrollToCoordAfterNav,\n } = PdfHighlightControls(\n removeRedundantHighlightTexts,\n !useCoordinates ? highlightPages : {},\n viewerRef,\n highlightPageSet,\n useCoordinates,\n useCoordinates ? highlightCordinatePages : [],\n highlightColor,\n activeHighlightColor\n );\n\n useEffect(() => {\n if (\n !useCoordinates ||\n useRange ||\n totalPages <= 0 ||\n loadedPdfUrl !== (pdfUrl ?? null)\n ) {\n return;\n }\n\n const index = resolvedJumpToPageValue - 1;\n const target = highlightCordinatePages[index];\n if (!target || target.pageIndex < 0 || target.pageIndex >= totalPages) return;\n\n const jumpKey = [\n pdfUrl,\n index,\n target.pageIndex,\n target.top,\n target.height,\n ].join(\":\");\n if (coordinateAutoJumpKeyRef.current === jumpKey) return;\n coordinateAutoJumpKeyRef.current = jumpKey;\n\n setCursorIndex(index);\n jumpToPage(target.pageIndex);\n scrollToCoordAfterNav(target.pageIndex, target.top, target.height);\n }, [\n highlightCordinatePages,\n jumpToPage,\n loadedPdfUrl,\n pdfUrl,\n resolvedJumpToPageValue,\n scrollToCoordAfterNav,\n setCursorIndex,\n totalPages,\n useCoordinates,\n useRange,\n ]);\n\n const currentPosition = getValidPosition(cursorIndex);\n const currentSegment = useMemo(() => {\n const pageNumber = currentPage + 1;\n return segments.find(\n (segment) =>\n pageNumber >= segment.start_page && pageNumber <= segment.end_page\n );\n }, [currentPage, segments]);\n\n // sync external activeCitationIndex → cursorIndex\n useEffect(() => {\n if (activeCitationIndex === undefined) return;\n if (activeCitationIndex === cursorIndex) return;\n setCursorIndex(activeCitationIndex);\n }, [activeCitationIndex]);\n\n // wrap controls to fire onActiveCitationChange\n const handleGoToNext = () => {\n if (cursorIndex >= totalHighlights - 1) return;\n const nextIndex = cursorIndex + 1;\n\n if (useCoordinates) {\n const target = highlightCordinatePages[nextIndex];\n\n if (!target) return;\n\n setCursorIndex(nextIndex);\n jumpToPage(target.pageIndex);\n scrollToCoordAfterNav(\n target.pageIndex,\n Number.isFinite(target.top) ? target.top : 0,\n Number.isFinite(target.height) ? target.height : 0\n );\n } else {\n controls.goToNext();\n }\n\n onActiveCitationChange?.(nextIndex);\n };\n\n const handleGoToPrevious = () => {\n if (cursorIndex <= 0) return;\n const previousIndex = cursorIndex - 1;\n\n if (useCoordinates) {\n const target = highlightCordinatePages[previousIndex];\n\n if (!target) return;\n\n setCursorIndex(previousIndex);\n jumpToPage(target.pageIndex);\n scrollToCoordAfterNav(\n target.pageIndex,\n Number.isFinite(target.top) ? target.top : 0,\n Number.isFinite(target.height) ? target.height : 0\n );\n } else {\n controls.goToPrevious();\n }\n\n onActiveCitationChange?.(previousIndex);\n };\n\n const modifiedControls = {\n ...controls,\n goToNext: handleGoToNext,\n goToPrevious: handleGoToPrevious,\n };\n\n const handlePageNavigate = (pageNumber: number) => {\n const nextPage = Math.min(Math.max(pageNumber, 1), totalPages || pageNumber);\n setCurrentPage(nextPage - 1);\n jumpToPage(nextPage - 1);\n };\n\n const waitForNavigationToSettle = React.useCallback((\n request: PdfNavigationRequest,\n pageNumber: number\n ) => {\n navigationSettleSequenceRef.current += 1;\n const settleSequence = navigationSettleSequenceRef.current;\n if (navigationSettleTimerRef.current != null) {\n window.clearTimeout(navigationSettleTimerRef.current);\n }\n\n let previousScrollTop: number | null = null;\n let stableChecks = 0;\n let attempts = 0;\n\n const checkScrollPosition = () => {\n if (navigationSettleSequenceRef.current !== settleSequence) return;\n\n attempts += 1;\n\n const scrollContainer = viewerRef.current?.querySelector(\n '.rpv-core__inner-pages'\n ) as HTMLElement | null;\n const targetPage = viewerRef.current?.querySelector(\n `[data-testid=\"core__page-layer-${pageNumber - 1}\"]`\n ) as HTMLElement | null;\n\n // Virtualized page layers are not guaranteed to be mounted on the first\n // check after jumpToPage. Keep polling so navigation completion is not\n // lost while React PDF Viewer is creating the target page DOM.\n if (!scrollContainer || !targetPage) {\n if (attempts >= 40) {\n navigationSettleTimerRef.current = null;\n onNavigationSettled?.({\n pageNumber,\n requestId: request.requestId,\n });\n return;\n }\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n return;\n }\n\n if (previousScrollTop === scrollContainer.scrollTop) {\n stableChecks += 1;\n } else {\n previousScrollTop = scrollContainer.scrollTop;\n stableChecks = 0;\n }\n\n const scrollRect = scrollContainer.getBoundingClientRect();\n const pageRect = targetPage.getBoundingClientRect();\n const isTargetVisible = Boolean(\n scrollRect &&\n pageRect &&\n pageRect.bottom > scrollRect.top &&\n pageRect.top < scrollRect.bottom\n );\n const hasSettled = stableChecks >= 2 && isTargetVisible;\n const reachedTimeout = attempts >= 40;\n\n if (hasSettled || reachedTimeout) {\n navigationSettleTimerRef.current = null;\n onNavigationSettled?.({\n pageNumber,\n requestId: request.requestId,\n });\n return;\n }\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n };\n\n navigationSettleTimerRef.current = window.setTimeout(checkScrollPosition, 50);\n }, [onNavigationSettled]);\n\n useEffect(() => () => {\n navigationSettleSequenceRef.current += 1;\n if (navigationSettleTimerRef.current != null) {\n window.clearTimeout(navigationSettleTimerRef.current);\n }\n }, []);\n\n useEffect(() => {\n if (!navigationRequest || totalPages <= 0) return;\n\n const nextPage = Math.min(\n Math.max(Math.trunc(navigationRequest.pageNumber), 1),\n totalPages\n );\n const requestKey = `${navigationRequest.requestId ?? nextPage}:${nextPage}`;\n if (lastNavigationRequestRef.current === requestKey) return;\n\n lastNavigationRequestRef.current = requestKey;\n setCurrentPage(nextPage - 1);\n jumpToPage(nextPage - 1);\n waitForNavigationToSettle(navigationRequest, nextPage);\n }, [jumpToPage, navigationRequest, totalPages, waitForNavigationToSettle]);\n\n if (!pdfUrl) {\n return (\n <ScannedDocCitation\n pages={fallbackPages}\n activeCitationIndex={activeCitationIndex}\n onActiveCitationChange={onActiveCitationChange}\n headerAction={headerAction}\n />\n );\n }\n\n const defaultViewerStyles: React.CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n height: \"100%\",\n width: \"100%\",\n backgroundColor: \"#FAFAFA\",\n };\n\n const scrollToHighlight = () => {\n if (!viewerRef.current) return;\n\n const index = resolvedJumpToPageValue - 1;\n const key = orderedKeys[index];\n const page = highlightPages[key];\n const targetPage = page > 0 ? page - 1 : 0;\n\n const pageVisitMap: Record<number, number[]> = {};\n orderedKeys.forEach((k, i) => {\n const p = highlightPages[k];\n if (p > 0) {\n if (!pageVisitMap[p]) pageVisitMap[p] = [];\n pageVisitMap[p].push(i);\n }\n });\n const visits = pageVisitMap[page] || [];\n const occurrence = visits.indexOf(index);\n\n let attempts = 0;\n const maxAttempts = 40;\n\n const doScrollToHighlight = () => {\n attempts++;\n if (attempts > maxAttempts) return;\n\n const scrollContainer = viewerRef.current?.querySelector(\n \".rpv-core__inner-pages\"\n ) as HTMLElement;\n if (!scrollContainer) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const pageElement = viewerRef.current?.querySelector(\n `[data-testid=\"core__page-layer-${targetPage}\"]`\n );\n if (!pageElement) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const scrollContainerRect = scrollContainer.getBoundingClientRect();\n const pageRect = pageElement.getBoundingClientRect();\n const isPageVisible =\n pageRect.top < scrollContainerRect.bottom &&\n pageRect.bottom > scrollContainerRect.top;\n\n if (!isPageVisible) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const allHighlights = pageElement.querySelectorAll(\".rpv-search__highlight\");\n const target = allHighlights[occurrence] as HTMLElement;\n\n if (!target) {\n setTimeout(doScrollToHighlight, 100);\n return;\n }\n\n const highlightRect = target.getBoundingClientRect();\n const scrollTop =\n scrollContainer.scrollTop +\n (highlightRect.top - scrollContainerRect.top) -\n scrollContainer.clientHeight / 2 +\n highlightRect.height / 2;\n\n scrollContainer.scrollTo({ top: scrollTop, behavior: \"smooth\" });\n };\n\n setTimeout(doScrollToHighlight, 500);\n };\n\n return (\n <div\n ref={viewerRef}\n className={[\"citation-pdf-viewer\", customClasses?.pdfViewerWrapper]\n .filter(Boolean)\n .join(\" \")}\n data-disable-pdf-annotations={\n disablePdfAnnotations ? \"true\" : undefined\n }\n data-pdf-page-fit={\n resolvedDefaultScale === SpecialZoomLevel.PageFit ? \"true\" : undefined\n }\n style={{\n height: \"100%\",\n minHeight: 0,\n minWidth: 0,\n overflow: \"hidden\",\n display: \"flex\",\n flexDirection: \"column\",\n ...pdfStyles.pdfViewer,\n ...defaultViewerStyles,\n ...customStyles?.pdfViewer,\n backgroundColor: \"#F1F5F9\",\n }}\n >\n <PdfToolbar\n highlightIndex={highlightIndex}\n totalHighlights={totalHighlights}\n controls={modifiedControls}\n currentPosition={currentPosition}\n pdfName={pdfName}\n onClose={onClose}\n pdfUrl={pdfUrl}\n viewerRef={viewerRef}\n customStyles={customStyles}\n customClasses={customClasses}\n customIcons={customIcons}\n headerAction={headerAction}\n isZoomEnabled={isZoomEnabled}\n showHighlightsAction={showHighlightsAction}\n showFullScreenAction={showFullScreenAction} \n currentSegment={currentSegment}\n segmentTooltipText={segmentTooltipText}\n currentPage={currentPage + 1}\n totalPages={totalPages}\n onPageNavigate={handlePageNavigate}\n onRotatePage={handleRotatePage}\n currentPageRotation={currentPageRotation}\n showRotateButton={showRotateButton}\n />\n <PdfContainer\n defaultScale={resolvedDefaultScale}\n pdfUrl={pdfUrl}\n plugins={plugins}\n customStyles={customStyles}\n onError={onError}\n onLoad={(e: DocumentLoadEvent) => {\n setTotalPages(e.doc.numPages);\n setLoadedPdfUrl(pdfUrl ?? null);\n\n const shouldAutoJumpToFirstMatch =\n !useCoordinates && !useRange && resolvedJumpToPageValue <= 0;\n\n if (\n !useCoordinates &&\n resolvedJumpToPageValue > 0 &&\n !useRange\n ) {\n const index = resolvedJumpToPageValue - 1;\n const key = orderedKeys[index];\n const page = key !== undefined ? highlightPages?.[key] : undefined;\n setCursorIndex(index);\n\n if (page > 0) {\n setTimeout(() => {\n hideNonTargetHighlights(highlightPageSet);\n deduplicateHighlights(page - 1);\n }, 1000);\n jumpToPage(page - 1);\n }\n } else if (useRange && rangeOfPages && rangeOfPages.length === 2) {\n \n // Async function to handle sequential jumping and waiting\n const scanRangeSequence = async () => {\n const [startPage, endPage] = rangeOfPages;\n \n for (let p = startPage; p <= endPage; p++) {\n const targetPageIndex = p - 1;\n \n jumpToPage(targetPageIndex);\n \n // Pause execution for 1 second to let the DOM render the highlights\n await new Promise((resolve) => setTimeout(resolve, 1000));\n \n hideNonTargetHighlights(highlightPageSet);\n const matchSize = deduplicateHighlights(targetPageIndex);\n \n // If the returned size is greater than 0, a match was found. Stop the loop.\n if (matchSize && matchSize > 0) {\n break; \n }\n }\n };\n\n scanRangeSequence();\n\n } else if (!useCoordinates && highlightPages) {\n const firstKey = orderedKeys.find(k => highlightPages[k] > 0);\n if (firstKey !== undefined) {\n const firstPage = highlightPages[firstKey] - 1;\n jumpToPage(firstPage);\n setTimeout(() => {\n hideNonTargetHighlights(highlightPageSet);\n deduplicateHighlights(firstPage);\n }, 1000);\n }\n }\n\n requestAnimationFrame(() => {\n if (shouldAutoJumpToFirstMatch) {\n tryJump();\n }\n if (!useCoordinates && resolvedJumpToPageValue > 0 && !useRange) {\n scrollToHighlight();\n }\n });\n }}\n onPageChange={(e: PageChangeEvent) => {\n const currentPage = e.currentPage;\n setCurrentPage(currentPage);\n onCurrentPageChange?.(currentPage + 1);\n if (!highlightPageSet.has(currentPage)) {\n hideNonTargetHighlights(highlightPageSet);\n return;\n }\n deduplicateHighlights(currentPage);\n hideNonTargetHighlights(highlightPageSet);\n }}\n renderPage={resolvedRenderPage}\n setRenderRange={setRenderRange}\n />\n </div>\n );\n};\n\nexport default PdfViewer;\n"],"names":["pdfUrl","highlightText","highlightPages","highlightCordinatePages","highlightColor","activeHighlightColor","jumpToPageValue","pdfName","onClose","customStyles","customClasses","customIcons","useCoordinates","fallbackPages","activeCitationIndex","onActiveCitationChange","headerAction","isZoomEnabled","showHighlightsAction","defaultScale","SpecialZoomLevel","ActualSize","useRange","rangeOfPages","showFullScreenAction","showRotateButton","segments","title","start_page","end_page","page_count","segmentTooltipText","onCurrentPageChange","navigationRequest","onNavigationSettled","disablePdfAnnotations","disablePdfTextLayer","renderPage","setRenderRange","onError","viewerRef","useRef","resolvedDefaultScale","scale","PageFit","PageWidth","getResolvedScale","resolvedJumpToPageValue","length","currentPage","setCurrentPage","useState","totalPages","setTotalPages","loadedPdfUrl","setLoadedPdfUrl","currentPageRotation","setCurrentPageRotation","lastNavigationRequestRef","navigationSettleTimerRef","navigationSettleSequenceRef","mutationObserverRef","coordinateAutoJumpKeyRef","pdfIdentifier","useMemo","URL","window","location","origin","pathname","split","pop","useEffect","rotationManager","setPdfIdentifier","onRotationChange","pageNum","angle","observer","MutationObserver","pageElements","current","querySelectorAll","registeredPages","Set","forEach","pageElement","match","getAttribute","pageNumber","parseInt","has","registerPageElement","add","observe","childList","subtree","attributes","disconnect","clearAll","getRotation","resolvedRenderPage","props","resolvedTextLayerChildren","jsx","style","display","children","textLayer","resolvedProps","annotationLayer","jsxs","Fragment","canvasLayer","highlightPageSet","map","h","pageIndex","set","Object","values","p","removeRedundantHighlightTexts","texts","filter","text","some","otherText","includes","highlightIndex","setHighlightIndex","cursorIndex","setCursorIndex","orderedKeys","totalHighlights","getValidPosition","tryJump","jumpToPage","zoomTo","plugins","controls","hideNonTargetHighlights","deduplicateHighlights","scrollToCoordAfterNav","PdfHighlightControls","index","target","jumpKey","top","height","join","currentPosition","currentSegment","find","segment","modifiedControls","goToNext","nextIndex","Number","isFinite","goToPrevious","previousIndex","waitForNavigationToSettle","React","useCallback","request","settleSequence","clearTimeout","previousScrollTop","stableChecks","attempts","checkScrollPosition","scrollContainer","querySelector","targetPage","requestId","setTimeout","scrollTop","scrollRect","getBoundingClientRect","pageRect","isTargetVisible","Boolean","bottom","nextPage","Math","min","max","trunc","requestKey","ScannedDocCitation","pages","ref","className","pdfViewerWrapper","minHeight","minWidth","overflow","flexDirection","pdfStyles","pdfViewer","width","backgroundColor","PdfToolbar","onPageNavigate","onRotatePage","rotatePageBy90","PdfContainer","onLoad","e","doc","numPages","shouldAutoJumpToFirstMatch","key","page","async","startPage","endPage","targetPageIndex","Promise","resolve","matchSize","scanRangeSequence","firstKey","k","firstPage","requestAnimationFrame","pageVisitMap","i","push","occurrence","indexOf","doScrollToHighlight","scrollContainerRect","highlightRect","clientHeight","scrollTo","behavior","scrollToHighlight","onPageChange"],"mappings":"guBAgIkB,EAChBA,SACAC,gBACAC,iBACAC,0BACAC,iBAAiB,SACjBC,uBAAuB,UACvBC,kBACAC,UACAC,UACAC,eACAC,gBACAC,cACAC,iBACAC,gBACAC,sBACAC,yBACAC,eACAC,iBAAgB,EAChBC,wBAAuB,EACvBC,eAAeC,EAAiBA,iBAAAC,WAChCC,YAAW,EACXC,eAAe,KACfC,wBAAqB,EACrBC,oBAAmB,EACnBC,WAAW,CACT,CACEC,MAAO,aACPC,WAAY,GACZC,SAAU,GACVC,WAAY,IAGhBC,qBACAC,sBACAC,oBACAC,sBACAC,yBAAwB,EACxBC,uBAAsB,EACtBC,aACAC,iBACAC,cAGM,MAAAC,EAAYC,SAA8B,MAC1CC,EAxEiB,CACvBC,IAEA,OAAQA,GACN,IAAK,aACH,OAAOvB,EAAAA,iBAAiBC,WAE1B,IAAK,UACH,OAAOD,EAAAA,iBAAiBwB,QAE1B,IAAK,YACH,OAAOxB,EAAAA,iBAAiByB,UAE1B,QACE,OAAOF,GAASvB,EAAiBA,iBAAAyB,YA0DRC,CAAiB3B,GACxC4B,EACJzC,IACCM,GAAkBT,EAAwB6C,OAAS,EAAI,EAAI,IACvDC,EAAaC,GAAkBC,WAAS,IACxCC,EAAYC,GAAiBF,WAAS,IACtCG,EAAcC,GAAmBJ,WAAwB,OACzDK,EAAqBC,IAA0BN,WAAS,GACzDO,GAA2BjB,S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gBgE,SAAS,CAAExF,IAAK6B,EAAW4D,SAAU,YAGvD7D,WAAWwD,EAAqB,MA8HJM,MAIxBC,aAAe9B,IACb,MAAMhK,EAAcgK,EAAEhK,YACtBC,EAAeD,GACfjB,IAAsBiB,EAAc,GAC/BiE,GAAiBvB,IAAI1C,IAI1B6F,GAAsB7F,GACtB4F,GAAwB3B,KAJtB2B,GAAwB3B,KAM5B7E,WAAYgE,GACZ/D"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),r=require("@react-pdf-viewer/search"),n=require("@react-pdf-viewer/page-navigation"),o=require("@react-pdf-viewer/zoom"),l=require("@react-pdf-viewer/highlight");exports.PdfHighlightControls=(i,s,a,c,h,g,u="yellow",p="#F6D739")=>{const[f,d]=t.useState(0),m=t.useRef(!1),[x,v]=t.useState(0);t.useRef([]);const T=e=>e.replace(/[^\S\n]+/g," ").trim(),y=e=>(e||"").toLowerCase().replace(/\u00ad/g,"").replace(/[""]/g,'"').replace(/['']/g,"'").replace(/[\u2013\u2014]/g,"-").replace(/-/g," ").replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim(),M=e=>{let t=e.trim();t=t.replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\u00A0\u2009\u202F]/g," "),t=t.replace(/^[-•]\s+/,"");const r=t.match(/^((\d+(?:\.\d+)*[.)]?)|[A-Za-z][.)]|\([A-Za-z0-9]+\)|(?:i|ii|iii|iv|v|vi|vii|viii|ix|x)[.)])\s*/i);return r?t.slice(r[0].length).trim():t},w=e=>{const t=y(e),r=t.replace(/\s+/g,""),n=new Set;return t&&n.add(t),r&&n.add(r),n},b=e=>e.replace(/\\([''])/g,"$1").replace(/\]\s*\n\s*\(/g,"](").replace(/&[#\w]+;/g,e=>(e=>{const t=document.createElement("textarea");return t.innerHTML=e,t.value})(e)).replace(/<br\s*\/?>/gi,"\n").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1"),_=e=>{if(!e)return[];return b(e).split(/\n+/).map(M).flatMap(e=>{const t=e.match(/^\s*\|(.+)\|\s*$/);return t?t[1].split("|").map(e=>e.trim()).filter(Boolean):[e]}).map(e=>T((e=>e.replace(/(^|\W)[*_]{1,3}([^*_]+)[*_]{1,3}(?=\W|$)/g,"$1$2"))(e))).filter(Boolean)},S=Object.keys(s).map(Number).sort((e,t)=>e-t),I=t.useMemo(()=>h?g.length:h?0:Object.values(s).filter(e=>e>0).length,[g,s]),$=e=>{if(!a.current)return;const t=a.current.querySelector(`[data-testid="search__highlights-${e}"]`);if(!t)return;const r=Array.from(t.querySelectorAll(".rpv-search__highlight"));if(0===r.length)return;const n=j.map(w),o=k.map(w);if(0===n.length&&0===o.length)return;const l=r.map(e=>{const t=(e=>{const t=e.getBoundingClientRect();if(t.height>0||t.width>0)return{top:t.top,left:t.left,right:t.right};const r=e.offsetTop,n=e.offsetLeft;return{top:r,left:n,right:n+e.offsetWidth}})(e),r=(e.textContent||"").trim(),n=(e.getAttribute("title")||"").trim();return{el:e,text:r||n,...t}}).filter(e=>e.text.length>0).sort((e,t)=>e.top-t.top||e.left-t.left);if(0===l.length)return;const s=[];let c=null,h=[];const g=()=>{if(!c)return;const e=h.join(" ");c.title=y(e),c.title&&s.push(c),c=null,h=[]};if(l.forEach(e=>{if(!c)return c={title:"",elements:[e.el],lastTop:e.top,lastRight:e.right},void(h=[e.text]);const t=Math.abs(e.top-c.lastTop)<=5,r=e.left<=c.lastRight+28;t&&r?(c.elements.push(e.el),c.lastTop=e.top,c.lastRight=Math.max(c.lastRight,e.right),h.push(e.text)):(g(),c={title:"",elements:[e.el],lastTop:e.top,lastRight:e.right},h=[e.text])}),g(),0===s.length)return;const u=(e,t)=>{if(!e)return!1;if(t.has(e))return!0;const r=e.replace(/\s+/g,"");for(const n of Array.from(t)){if(!n)continue;const t=n.replace(/\s+/g,"");if(t===r)return!0;if(n.length>=8&&e.length>=5&&n.includes(e))return!0;if(t.length>=8&&r.length>=5&&t.includes(r))return!0;if(e.length>=10&&n.length>=8&&e.includes(n))return!0;if(r.length>=10&&t.length>=8&&r.includes(t))return!0}return!1};let p=0,f=new Set;const d=Array.from(new Set([...j,...k].map(y).filter(e=>e.length>=8))).sort((e,t)=>t.length-e.length),m=e=>{if(!e||e.length<8)return null;const t=e.replace(/\s+/g,"");for(let r=0;r<s.length;r++){let n="",o="";const l=new Set;for(let i=r;i<s.length&&i<r+20;i++){const r=s[i].title;if(n=n?`${n} ${r}`:r,o=o?`${o}${r.replace(/\s+/g,"")}`:r.replace(/\s+/g,""),l.add(i),n.includes(e)||o.includes(t))return l;if(n.length>=15&&(e.includes(n)||t.includes(o)))return l;if(n.length>e.length+150)break}}return null};for(const e of d){const t=m(e);t&&t.size>0&&(t.forEach(e=>f.add(e)),p=f.size)}if(0===p){const e=(e=>{if(0===e.length)return null;let t=null;for(const r of e)for(const e of Array.from(r)){if(!e||e.length<5)continue;const r=e.replace(/\s+/g,"");for(let n=0;n<s.length;n++){let o="",l="";const i=new Set;for(let a=n;a<s.length&&a<n+15;a++){const n=s[a].title;if(o=o?`${o} ${n}`:n,l=l?`${l}${n.replace(/\s+/g,"")}`:n.replace(/\s+/g,""),i.add(a),o.includes(e)||l.includes(r)){const r=Math.max(0,o.length-e.length);(!t||r<t.extra)&&(t={blocks:new Set(i),extra:r});break}if(o.length>e.length+120)break}}}return t?t.blocks:null})(n);e&&e.size>0&&(e.forEach(e=>f.add(e)),p=f.size)}const x=(e=>{if(e.length<2)return 40;const t=[];for(let r=1;r<e.length;r++){const n=Math.abs(e[r].lastTop-e[r-1].lastTop);n>0&&t.push(n)}if(0===t.length)return 40;t.sort((e,t)=>e-t);const r=t[Math.floor(t.length/2)],n=Math.round(2.25*r);return Math.min(60,Math.max(24,n))})(s),v=k.map(y).filter(e=>e.length>=8),T=v.map(e=>e.split(/\s+/).filter(e=>e.length>=2));if(0===p){const e=o;for(let t=0;t<s.length;t++){const r=s[t].title;for(let n=0;n<e.length;n++){if(!u(r,e[n]))continue;let o=0;const l=new Set;let i=n,a=t-1;for(let r=t;r<s.length&&i<e.length;r++){if(u(s[r].title,e[i])){if(a>=0){const e=s[a].lastTop,t=s[r].lastTop;if(Math.abs(t-e)>x)break}o++,l.add(r),a=r,i++}else if(i>0&&u(s[r].title,e[i-1])){const e=s[a].lastTop,t=s[r].lastTop;Math.abs(t-e)<=3&&(l.add(r),a=r)}if(r-a>6)break}o>p&&(p=o,f=l)}}}if(p<Math.min(3,v.length)&&v.length>0){const e=new Set;s.forEach((t,r)=>{const n=t.title.split(/\s+/).filter(e=>e.length>=2);if(n.length<2)return;const o=new Set(n);for(const t of T){if(t.length<2)continue;let n=0;for(const e of t)o.has(e)&&n++;const l=n/t.length;if(n>=3||l>=.5){e.add(r);break}}}),e.size>0&&(f=e,p=Math.max(p,e.size))}const M=new Set;if(B.forEach(e=>{const t=y(e);t&&(M.add(t),M.add(t.replace(/\s+/g,"")))}),0===p){const e=new Set;if(s.forEach((t,r)=>{const n=t.title.replace(/\s+/g,"");if(M.has(t.title)||M.has(n))return void e.add(r);const o=Array.from(M);for(let n=0;n<o.length;n++){const l=o[n];if(l.length>=10&&l.includes(t.title)&&t.title.length>=5){e.add(r);break}}}),0===e.size)return 0;f=e}s.forEach((e,t)=>{const r=f.has(t);e.elements.forEach(e=>{r?(e.classList.add("verified-match"),e.style.display=""):(e.style.display="none",e.classList.remove("verified-match"))})});const b=[];return s.forEach((e,t)=>{f.has(t)&&e.elements.forEach(e=>b.push(e))}),requestAnimationFrame(()=>{const e=b.map(e=>({el:e,rect:e.getBoundingClientRect()})).filter(e=>e.rect.width>0&&e.rect.height>0).sort((e,t)=>t.rect.width*t.rect.height-e.rect.width*e.rect.height),t=[];e.forEach(({el:e,rect:r})=>{t.some(e=>((e,t)=>{const r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),n=Math.min(e.width*e.height,t.width*t.height);return n>0?r/n:0})(e.rect,r)>.5)?(e.style.display="none",e.classList.remove("verified-match")):t.push({el:e,rect:r})})}),console.groupCollapsed(`[debug: PDF ordered matching - Page ${e}]`),console.log("input->",i),console.log("processed sentences->",j),console.log("processed lines->",k),console.log("Expected sentence count:",n.length),console.log("Expected line count:",o.length),console.log("Matched sequence length:",p),console.log("blocksToKeep",f,"size",f.size),console.groupEnd(),f.size},q=e=>{if(!a.current)return;a.current.querySelectorAll(".rpv-search__highlights").forEach(t=>{const r=t.getAttribute("data-testid"),n=parseInt(r?.replace(/search__highlights-/g,"")||"-1"),o=t.querySelectorAll(".rpv-search__highlight");e.has(n)||o.forEach(e=>{e.style.display="none"})})},E=i.map(e=>(e=>e?b(e).split(/\n{2,}/).map(e=>_(e).join(" ")).map(e=>T(e)).filter(Boolean):[])(e)).flat(),A=i.map(e=>_(e)).flat(),z=E.some(e=>e.length>=3)?3:1,j=E.filter(e=>e.length>=z),k=A.filter(e=>e.length>=z),C=k.flatMap(e=>((e,t=6,r=4)=>{const n=e.split(/\s+/).filter(Boolean);if(n.length<=t)return[];const o=[];for(let e=0;e+t<=n.length;e+=r)o.push(n.slice(e,e+t).join(" "));return n.length>t&&(n.length-t)%r!==0&&o.push(n.slice(n.length-t).join(" ")),o})(e)),B=Array.from(new Set([...j,...k,...C].flatMap(e=>{const t=T(e.replace(/[\u00A0\u2009\u202F]/g," ").replace(/\u00ad/g,"").replace(/[""]/g,'"').replace(/['']/g,"'"));if(!t)return[];const r=t.replace(/[\u2013\u2014]/g,"-"),n=T(r.replace(/(\w)-\s+(\w)/g,"$1$2")),o=T(r.replace(/-/g," ")),l=T(r.replace(/-/g,"")),i=T(t.replace(/[^\w\s]/g,"")),s=new Set([t,r,n,o,l,i]);return Array.from(s).filter(Boolean)}))).filter(e=>{const t=e.split(/\s+/).filter(Boolean);return!(e.length<z)&&(t.length>=3||e.length>=12)}),R=r.searchPlugin({keyword:B}),P=n.pageNavigationPlugin(),H=o.zoomPlugin(),{jumpToMatch:F}=R,{jumpToPage:N}=P,{zoomTo:L,CurrentScale:O,ZoomPopover:Z}=H,D=t.useMemo(()=>(e=>{if(0===e.length)return[];const t=new Map;e.forEach((e,r)=>{const n=null!=e.pageNumber?e.pageNumber-1:e.pageIndex;t.has(n)||t.set(n,[]),t.get(n).push({...e,originalIndex:r})});const r=[];return t.forEach(e=>{const t=[...e].sort((e,t)=>e.top!==t.top?e.top-t.top:e.left-t.left),n=new Array(t.length).fill(!1);for(let e=0;e<t.length;e++){if(n[e])continue;let{left:o,top:l,width:i,height:s,pageIndex:a,pageNumber:c}=t[e],h=o+i,g=l+s;const u=[t[e].originalIndex];n[e]=!0;let p=!0;for(;p;){p=!1;for(let r=e+1;r<t.length;r++){if(n[r])continue;const e=t[r],a=e.left+e.width,c=e.top+e.height,f=Math.max(0,Math.min(h,a)-Math.max(o,e.left))*Math.max(0,Math.min(g,c)-Math.max(l,e.top)),d=Math.max(i*s,1e-4),m=Math.max(e.width*e.height,1e-4),x=Math.min(d,m);(x>0?f/x:0)>=.8&&(o=Math.min(o,e.left),l=Math.min(l,e.top),h=Math.max(h,a),g=Math.max(g,c),i=h-o,s=g-l,u.push(e.originalIndex),n[r]=!0,p=!0)}}r.push({pageIndex:a,pageNumber:c,left:o,top:l,width:i,height:s,originalIndexes:u})}}),r})(g),[g]),W=l.highlightPlugin({renderHighlights:t=>e.jsx(e.Fragment,{children:D.filter(e=>null!=e.pageNumber?e.pageNumber-1===t.pageIndex:e.pageIndex===t.pageIndex).map(t=>{const r=t.originalIndexes.includes(x);return e.jsx("div",{style:{position:"absolute",left:`${t.left}%`,top:`${t.top+.08*t.height}%`,width:`${t.width}%`,height:.95*t.height+"%",background:r?p:u,opacity:r?.7:.4,transition:"background 0.2s, opacity 0.2s",border:r?"1px solid red":"1px solid transparent"}},t.originalIndexes.join("-"))})})}),K=()=>{if(!m.current)try{F(0),m.current=!0;const e=g[0];e&&h&&V(e.pageIndex,e.top)}catch{requestAnimationFrame(K)}},J=(e,t)=>{if(!a.current)return;if(!a.current.querySelector(".rpv-core__viewer"))return;let r=-1;const n=()=>{const o=a.current?.querySelector(".rpv-core__inner-pages");if(!o)return;if(o.scrollTop!==r)return r=o.scrollTop,void setTimeout(n,100);const l=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!l)return;const i=l.querySelectorAll(".rpv-search__highlight")[t];if(!i)return;const s=o.getBoundingClientRect(),c=i.getBoundingClientRect(),h=o.scrollTop+(c.top-s.top)-o.clientHeight/2+c.height/2;o.scrollTo({top:h,behavior:"smooth"})};setTimeout(n,300)},V=(e,t,r=0)=>{if(!a.current)return;let n=0;const o=()=>{if(++n>60)return;const l=a.current?.querySelector(".rpv-core__inner-pages");if(!l)return void setTimeout(o,100);const i=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!i)return void setTimeout(o,100);const s=i.getBoundingClientRect();if(0===s.height)return void setTimeout(o,100);const c=l.getBoundingClientRect(),h=t/100*s.height,g=r/100*s.height,u=s.top-c.top+h,p=u+g;if(u>=80&&p<=l.clientHeight-80)return;const f=u<80?l.scrollTop+u-80:l.scrollTop+p-l.clientHeight+80;l.scrollTo({top:f,behavior:"smooth"})};setTimeout(o,100)},G=t.useMemo(()=>{const e={};return S.forEach((t,r)=>{const n=s[t];n>0&&(e[n]||(e[n]=[]),e[n].push(r))}),e},[S,s]),Q=e=>{const t=s[S[e]];return(G[t]||[]).indexOf(e)},U=(e,t,r=0)=>{if(!a.current)return;let n=-1,o=0;const l=()=>{if(++o>60)return;const i=a.current?.querySelector(".rpv-core__inner-pages");if(!i)return void setTimeout(l,100);if(i.scrollTop!==n)return n=i.scrollTop,void setTimeout(l,100);const s=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!s)return void setTimeout(l,100);const c=s.getBoundingClientRect();if(0===c.height)return void setTimeout(l,100);const h=i.getBoundingClientRect(),g=t/100*c.height,u=r/100*c.height,p=c.top-h.top+g,f=p+u;if(p>=80&&f<=i.clientHeight-80)return;const d=p<80?i.scrollTop+p-80:i.scrollTop+f-i.clientHeight+80;i.scrollTo({top:d,behavior:"instant"})};setTimeout(l,100)};return{setHighlightIndex:d,highlightIndex:f,cursorIndex:x,setCursorIndex:v,orderedKeys:S,totalHighlights:I,getValidPosition:e=>{if(h)return e+1;if(!s)return 0;let t=0;for(let r=0;r<=e;r++)s[S[r]]>0&&t++;return t},tryJump:K,jumpToPage:N,zoomTo:L,hideNonTargetHighlights:q,deduplicateHighlights:$,scrollToCoord:V,plugins:[h?W:R,P,H],controls:{CurrentScale:O,ZoomPopover:Z,zoomTo:L,goToNext:()=>{if(h&&g)for(let e=x+1;e<g.length;e++){const t=g[e],r=g[x];return v(e),void(t.pageIndex!==r.pageIndex?(N(t.pageIndex),U(t.pageIndex,t.top,t.height)):V(t.pageIndex,t.top,t.height))}else{for(let e=x+1;e<S.length;e++){const t=S[e];if(s[t]>0){const r=s[t]-1,n=Q(e);return v(e),N(s[t]-1),J(r,n),setTimeout(()=>{$(r)},500),void(1===Object.keys(s).length&&q(c))}}}},goToPrevious:()=>{if(h&&g)for(let e=x-1;e>=0;e--){const t=g[e],r=g[x];return v(e),void(t.pageIndex!==r.pageIndex?(N(t.pageIndex),U(t.pageIndex,t.top,t.height)):V(t.pageIndex,t.top,t.height))}else{for(let e=x-1;e>=0;e--){const t=S[e];if(s[t]>0){const r=s[t]-1,n=Q(e);return v(e),N(s[t]-1),J(r,n),setTimeout(()=>{$(r)},500),void(1===Object.keys(s).length&&q(c))}}}}}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),r=require("@react-pdf-viewer/search"),n=require("@react-pdf-viewer/page-navigation"),o=require("@react-pdf-viewer/zoom"),l=require("@react-pdf-viewer/highlight");exports.PdfHighlightControls=(i,s,a,c,h,g,u="yellow",p="#F6D739")=>{const[f,d]=t.useState(0),m=t.useRef(!1),[x,v]=t.useState(0);t.useRef([]);const T=t.useRef(0),y=e=>e.replace(/[^\S\n]+/g," ").trim(),M=e=>(e||"").toLowerCase().replace(/\u00ad/g,"").replace(/[""]/g,'"').replace(/['']/g,"'").replace(/[\u2013\u2014]/g,"-").replace(/-/g," ").replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim(),b=e=>{let t=e.trim();t=t.replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\u00A0\u2009\u202F]/g," "),t=t.replace(/^[-•]\s+/,"");const r=t.match(/^((\d+(?:\.\d+)*[.)]?)|[A-Za-z][.)]|\([A-Za-z0-9]+\)|(?:i|ii|iii|iv|v|vi|vii|viii|ix|x)[.)])\s*/i);return r?t.slice(r[0].length).trim():t},w=e=>{const t=M(e),r=t.replace(/\s+/g,""),n=new Set;return t&&n.add(t),r&&n.add(r),n},_=e=>e.replace(/\\([''])/g,"$1").replace(/\]\s*\n\s*\(/g,"](").replace(/&[#\w]+;/g,e=>(e=>{const t=document.createElement("textarea");return t.innerHTML=e,t.value})(e)).replace(/<br\s*\/?>/gi,"\n").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1"),S=e=>{if(!e)return[];return _(e).split(/\n+/).map(b).flatMap(e=>{const t=e.match(/^\s*\|(.+)\|\s*$/);return t?t[1].split("|").map(e=>e.trim()).filter(Boolean):[e]}).map(e=>y((e=>e.replace(/(^|\W)[*_]{1,3}([^*_]+)[*_]{1,3}(?=\W|$)/g,"$1$2"))(e))).filter(Boolean)},I=Object.keys(s).map(Number).sort((e,t)=>e-t),$=t.useMemo(()=>h?g.length:h?0:Object.values(s).filter(e=>e>0).length,[g,s]),q=e=>{if(!a.current)return;const t=a.current.querySelector(`[data-testid="search__highlights-${e}"]`);if(!t)return;const r=Array.from(t.querySelectorAll(".rpv-search__highlight"));if(0===r.length)return;const n=j.map(w),o=k.map(w);if(0===n.length&&0===o.length)return;const l=r.map(e=>{const t=(e=>{const t=e.getBoundingClientRect();if(t.height>0||t.width>0)return{top:t.top,left:t.left,right:t.right};const r=e.offsetTop,n=e.offsetLeft;return{top:r,left:n,right:n+e.offsetWidth}})(e),r=(e.textContent||"").trim(),n=(e.getAttribute("title")||"").trim();return{el:e,text:r||n,...t}}).filter(e=>e.text.length>0).sort((e,t)=>e.top-t.top||e.left-t.left);if(0===l.length)return;const s=[];let c=null,h=[];const g=()=>{if(!c)return;const e=h.join(" ");c.title=M(e),c.title&&s.push(c),c=null,h=[]};if(l.forEach(e=>{if(!c)return c={title:"",elements:[e.el],lastTop:e.top,lastRight:e.right},void(h=[e.text]);const t=Math.abs(e.top-c.lastTop)<=5,r=e.left<=c.lastRight+28;t&&r?(c.elements.push(e.el),c.lastTop=e.top,c.lastRight=Math.max(c.lastRight,e.right),h.push(e.text)):(g(),c={title:"",elements:[e.el],lastTop:e.top,lastRight:e.right},h=[e.text])}),g(),0===s.length)return;const u=(e,t)=>{if(!e)return!1;if(t.has(e))return!0;const r=e.replace(/\s+/g,"");for(const n of Array.from(t)){if(!n)continue;const t=n.replace(/\s+/g,"");if(t===r)return!0;if(n.length>=8&&e.length>=5&&n.includes(e))return!0;if(t.length>=8&&r.length>=5&&t.includes(r))return!0;if(e.length>=10&&n.length>=8&&e.includes(n))return!0;if(r.length>=10&&t.length>=8&&r.includes(t))return!0}return!1};let p=0,f=new Set;const d=Array.from(new Set([...j,...k].map(M).filter(e=>e.length>=8))).sort((e,t)=>t.length-e.length),m=e=>{if(!e||e.length<8)return null;const t=e.replace(/\s+/g,"");for(let r=0;r<s.length;r++){let n="",o="";const l=new Set;for(let i=r;i<s.length&&i<r+20;i++){const r=s[i].title;if(n=n?`${n} ${r}`:r,o=o?`${o}${r.replace(/\s+/g,"")}`:r.replace(/\s+/g,""),l.add(i),n.includes(e)||o.includes(t))return l;if(n.length>=15&&(e.includes(n)||t.includes(o)))return l;if(n.length>e.length+150)break}}return null};for(const e of d){const t=m(e);t&&t.size>0&&(t.forEach(e=>f.add(e)),p=f.size)}if(0===p){const e=(e=>{if(0===e.length)return null;let t=null;for(const r of e)for(const e of Array.from(r)){if(!e||e.length<5)continue;const r=e.replace(/\s+/g,"");for(let n=0;n<s.length;n++){let o="",l="";const i=new Set;for(let a=n;a<s.length&&a<n+15;a++){const n=s[a].title;if(o=o?`${o} ${n}`:n,l=l?`${l}${n.replace(/\s+/g,"")}`:n.replace(/\s+/g,""),i.add(a),o.includes(e)||l.includes(r)){const r=Math.max(0,o.length-e.length);(!t||r<t.extra)&&(t={blocks:new Set(i),extra:r});break}if(o.length>e.length+120)break}}}return t?t.blocks:null})(n);e&&e.size>0&&(e.forEach(e=>f.add(e)),p=f.size)}const x=(e=>{if(e.length<2)return 40;const t=[];for(let r=1;r<e.length;r++){const n=Math.abs(e[r].lastTop-e[r-1].lastTop);n>0&&t.push(n)}if(0===t.length)return 40;t.sort((e,t)=>e-t);const r=t[Math.floor(t.length/2)],n=Math.round(2.25*r);return Math.min(60,Math.max(24,n))})(s),v=k.map(M).filter(e=>e.length>=8),T=v.map(e=>e.split(/\s+/).filter(e=>e.length>=2));if(0===p){const e=o;for(let t=0;t<s.length;t++){const r=s[t].title;for(let n=0;n<e.length;n++){if(!u(r,e[n]))continue;let o=0;const l=new Set;let i=n,a=t-1;for(let r=t;r<s.length&&i<e.length;r++){if(u(s[r].title,e[i])){if(a>=0){const e=s[a].lastTop,t=s[r].lastTop;if(Math.abs(t-e)>x)break}o++,l.add(r),a=r,i++}else if(i>0&&u(s[r].title,e[i-1])){const e=s[a].lastTop,t=s[r].lastTop;Math.abs(t-e)<=3&&(l.add(r),a=r)}if(r-a>6)break}o>p&&(p=o,f=l)}}}if(p<Math.min(3,v.length)&&v.length>0){const e=new Set;s.forEach((t,r)=>{const n=t.title.split(/\s+/).filter(e=>e.length>=2);if(n.length<2)return;const o=new Set(n);for(const t of T){if(t.length<2)continue;let n=0;for(const e of t)o.has(e)&&n++;const l=n/t.length;if(n>=3||l>=.5){e.add(r);break}}}),e.size>0&&(f=e,p=Math.max(p,e.size))}const y=new Set;if(B.forEach(e=>{const t=M(e);t&&(y.add(t),y.add(t.replace(/\s+/g,"")))}),0===p){const e=new Set;if(s.forEach((t,r)=>{const n=t.title.replace(/\s+/g,"");if(y.has(t.title)||y.has(n))return void e.add(r);const o=Array.from(y);for(let n=0;n<o.length;n++){const l=o[n];if(l.length>=10&&l.includes(t.title)&&t.title.length>=5){e.add(r);break}}}),0===e.size)return 0;f=e}s.forEach((e,t)=>{const r=f.has(t);e.elements.forEach(e=>{r?(e.classList.add("verified-match"),e.style.display=""):(e.style.display="none",e.classList.remove("verified-match"))})});const b=[];return s.forEach((e,t)=>{f.has(t)&&e.elements.forEach(e=>b.push(e))}),requestAnimationFrame(()=>{const e=b.map(e=>({el:e,rect:e.getBoundingClientRect()})).filter(e=>e.rect.width>0&&e.rect.height>0).sort((e,t)=>t.rect.width*t.rect.height-e.rect.width*e.rect.height),t=[];e.forEach(({el:e,rect:r})=>{t.some(e=>((e,t)=>{const r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),n=Math.min(e.width*e.height,t.width*t.height);return n>0?r/n:0})(e.rect,r)>.5)?(e.style.display="none",e.classList.remove("verified-match")):t.push({el:e,rect:r})})}),console.groupCollapsed(`[debug: PDF ordered matching - Page ${e}]`),console.log("input->",i),console.log("processed sentences->",j),console.log("processed lines->",k),console.log("Expected sentence count:",n.length),console.log("Expected line count:",o.length),console.log("Matched sequence length:",p),console.log("blocksToKeep",f,"size",f.size),console.groupEnd(),f.size},A=e=>{if(!a.current)return;a.current.querySelectorAll(".rpv-search__highlights").forEach(t=>{const r=t.getAttribute("data-testid"),n=parseInt(r?.replace(/search__highlights-/g,"")||"-1"),o=t.querySelectorAll(".rpv-search__highlight");e.has(n)||o.forEach(e=>{e.style.display="none"})})},E=i.map(e=>(e=>e?_(e).split(/\n{2,}/).map(e=>S(e).join(" ")).map(e=>y(e)).filter(Boolean):[])(e)).flat(),z=i.map(e=>S(e)).flat(),C=E.some(e=>e.length>=3)?3:1,j=E.filter(e=>e.length>=C),k=z.filter(e=>e.length>=C),R=k.flatMap(e=>((e,t=6,r=4)=>{const n=e.split(/\s+/).filter(Boolean);if(n.length<=t)return[];const o=[];for(let e=0;e+t<=n.length;e+=r)o.push(n.slice(e,e+t).join(" "));return n.length>t&&(n.length-t)%r!==0&&o.push(n.slice(n.length-t).join(" ")),o})(e)),B=Array.from(new Set([...j,...k,...R].flatMap(e=>{const t=y(e.replace(/[\u00A0\u2009\u202F]/g," ").replace(/\u00ad/g,"").replace(/[""]/g,'"').replace(/['']/g,"'"));if(!t)return[];const r=t.replace(/[\u2013\u2014]/g,"-"),n=y(r.replace(/(\w)-\s+(\w)/g,"$1$2")),o=y(r.replace(/-/g," ")),l=y(r.replace(/-/g,"")),i=y(t.replace(/[^\w\s]/g,"")),s=new Set([t,r,n,o,l,i]);return Array.from(s).filter(Boolean)}))).filter(e=>{const t=e.split(/\s+/).filter(Boolean);return!(e.length<C)&&(t.length>=3||e.length>=12)}),P=r.searchPlugin({keyword:B}),H=n.pageNavigationPlugin(),N=o.zoomPlugin(),{jumpToMatch:F}=P,{jumpToPage:L}=H,{zoomTo:O,CurrentScale:Z,ZoomPopover:D}=N,W=t.useMemo(()=>(e=>{if(0===e.length)return[];const t=new Map;e.forEach((e,r)=>{const n=null!=e.pageNumber?e.pageNumber-1:e.pageIndex;t.has(n)||t.set(n,[]),t.get(n).push({...e,originalIndex:r})});const r=[];return t.forEach(e=>{const t=[...e].sort((e,t)=>e.top!==t.top?e.top-t.top:e.left-t.left),n=new Array(t.length).fill(!1);for(let e=0;e<t.length;e++){if(n[e])continue;let{left:o,top:l,width:i,height:s,pageIndex:a,pageNumber:c}=t[e],h=o+i,g=l+s;const u=[t[e].originalIndex];n[e]=!0;let p=!0;for(;p;){p=!1;for(let r=e+1;r<t.length;r++){if(n[r])continue;const e=t[r],a=e.left+e.width,c=e.top+e.height,f=Math.max(0,Math.min(h,a)-Math.max(o,e.left))*Math.max(0,Math.min(g,c)-Math.max(l,e.top)),d=Math.max(i*s,1e-4),m=Math.max(e.width*e.height,1e-4),x=Math.min(d,m);(x>0?f/x:0)>=.8&&(o=Math.min(o,e.left),l=Math.min(l,e.top),h=Math.max(h,a),g=Math.max(g,c),i=h-o,s=g-l,u.push(e.originalIndex),n[r]=!0,p=!0)}}r.push({pageIndex:a,pageNumber:c,left:o,top:l,width:i,height:s,originalIndexes:u})}}),r})(g),[g]),K=l.highlightPlugin({renderHighlights:t=>e.jsx(e.Fragment,{children:W.filter(e=>null!=e.pageNumber?e.pageNumber-1===t.pageIndex:e.pageIndex===t.pageIndex).map(t=>{const r=t.originalIndexes.includes(x);return e.jsx("div",{style:{position:"absolute",left:`${t.left}%`,top:`${t.top+.08*t.height}%`,width:`${t.width}%`,height:.95*t.height+"%",background:r?p:u,opacity:r?.7:.4,transition:"background 0.2s, opacity 0.2s",border:r?"1px solid red":"1px solid transparent"}},t.originalIndexes.join("-"))})})}),J=()=>{if(!m.current)try{F(0),m.current=!0;const e=g[0];e&&h&&G(e.pageIndex,e.top)}catch{requestAnimationFrame(J)}},V=(e,t)=>{if(!a.current)return;if(!a.current.querySelector(".rpv-core__viewer"))return;let r=-1;const n=()=>{const o=a.current?.querySelector(".rpv-core__inner-pages");if(!o)return;if(o.scrollTop!==r)return r=o.scrollTop,void setTimeout(n,100);const l=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!l)return;const i=l.querySelectorAll(".rpv-search__highlight")[t];if(!i)return;const s=o.getBoundingClientRect(),c=i.getBoundingClientRect(),h=o.scrollTop+(c.top-s.top)-o.clientHeight/2+c.height/2;o.scrollTo({top:h,behavior:"smooth"})};setTimeout(n,300)},G=(e,t,r=0)=>{if(!a.current)return;T.current+=1;let n=0;const o=()=>{if(++n>60)return;const l=a.current?.querySelector(".rpv-core__inner-pages");if(!l)return void setTimeout(o,100);const i=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!i)return void setTimeout(o,100);const s=i.getBoundingClientRect();if(0===s.height)return void setTimeout(o,100);const c=l.getBoundingClientRect(),h=t/100*s.height,g=r/100*s.height,u=s.top-c.top+h,p=u+g;if(u>=80&&p<=l.clientHeight-80)return;const f=u<80?l.scrollTop+u-80:l.scrollTop+p-l.clientHeight+80;l.scrollTo({top:f,behavior:"smooth"})};setTimeout(o,100)},Q=t.useMemo(()=>{const e={};return I.forEach((t,r)=>{const n=s[t];n>0&&(e[n]||(e[n]=[]),e[n].push(r))}),e},[I,s]),U=e=>{const t=s[I[e]];return(Q[t]||[]).indexOf(e)},X=(e,t,r=0)=>{if(!a.current)return;const n=++T.current;let o=null,l=0,i=0;const s=()=>{if(T.current!==n)return;if(++i>60)return;const c=a.current?.querySelector(".rpv-core__inner-pages");if(!c)return void setTimeout(s,100);const h=a.current?.querySelector(`[data-testid="core__page-layer-${e}"]`);if(!h)return void setTimeout(s,100);const g=h.getBoundingClientRect();if(0===g.height)return void setTimeout(s,100);const u=c.getBoundingClientRect(),p=g.bottom>u.top&&g.top<u.bottom;if(o===c.scrollTop?l+=1:(o=c.scrollTop,l=0),!p||l<2)return void setTimeout(s,100);const f=t/100*g.height,d=r/100*g.height,m=g.top-u.top+f+d/2,x=c.scrollTop+m-c.clientHeight/2;c.scrollTo({top:x,behavior:"smooth"})};setTimeout(s,100)};return{setHighlightIndex:d,highlightIndex:f,cursorIndex:x,setCursorIndex:v,orderedKeys:I,totalHighlights:$,getValidPosition:e=>{if(h)return e+1;if(!s)return 0;let t=0;for(let r=0;r<=e;r++)s[I[r]]>0&&t++;return t},tryJump:J,jumpToPage:L,zoomTo:O,hideNonTargetHighlights:A,deduplicateHighlights:q,scrollToCoord:G,scrollToCoordAfterNav:X,plugins:[h?K:P,H,N],controls:{CurrentScale:Z,ZoomPopover:D,zoomTo:O,goToNext:()=>{if(h&&g)for(let e=x+1;e<g.length;e++){const t=g[e],r=g[x];return v(e),void(t.pageIndex!==r.pageIndex?(L(t.pageIndex),X(t.pageIndex,t.top,t.height)):G(t.pageIndex,t.top,t.height))}else{for(let e=x+1;e<I.length;e++){const t=I[e];if(s[t]>0){const r=s[t]-1,n=U(e);return v(e),L(s[t]-1),V(r,n),setTimeout(()=>{q(r)},500),void(1===Object.keys(s).length&&A(c))}}}},goToPrevious:()=>{if(h&&g)for(let e=x-1;e>=0;e--){const t=g[e],r=g[x];return v(e),void(t.pageIndex!==r.pageIndex?(L(t.pageIndex),X(t.pageIndex,t.top,t.height)):G(t.pageIndex,t.top,t.height))}else{for(let e=x-1;e>=0;e--){const t=I[e];if(s[t]>0){const r=s[t]-1,n=U(e);return v(e),L(s[t]-1),V(r,n),setTimeout(()=>{q(r)},500),void(1===Object.keys(s).length&&A(c))}}}}}}};
2
2
  //# sourceMappingURL=usePdfHighlight.js.map