@viswa-test/test-citation 0.0.390 → 0.0.391
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/features/CognitiveCompare/CitationAnchor.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CitationAnchor.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CitationRenderer.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CitationRenderer.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveCompare.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveCompare.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveCompareConstants.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveCompareConstants.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveComparehelpers.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitiveComparehelpers.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitivePopup.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CognitivePopup.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/CompareContext.js +1 -1
- package/dist/cjs/features/CognitiveCompare/CompareContext.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/components/WebGptPanel.js +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/components/WebGptPanel.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js +1 -1
- package/dist/cjs/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/components/LHSSectionRow.js +1 -1
- package/dist/cjs/features/CognitiveCompare/components/LHSSectionRow.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/components/RHSSectionRow.js +1 -1
- package/dist/cjs/features/CognitiveCompare/components/RHSSectionRow.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SectionAccordion.js +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SectionAccordion.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SubSectionAccordion.js +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SubSectionAccordion.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SvgConnectors.js +1 -1
- package/dist/cjs/features/CognitiveCompare/components/SvgConnectors.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/memoizedMarkdown.js +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/memoizedMarkdown.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useCompareData.js +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useCompareData.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useLinesCalculator.js +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useLinesCalculator.js.map +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useSideBySide.js +1 -1
- package/dist/cjs/features/CognitiveCompare/hooks/useSideBySide.js.map +1 -1
- package/dist/cjs/features/PdfViewer/PdfToolbar.js +1 -1
- package/dist/cjs/features/PdfViewer/PdfToolbar.js.map +1 -1
- package/dist/cjs/features/PdfViewer/PdfViewer.css.js +1 -1
- package/dist/cjs/features/PdfViewer/PdfViewer.js +1 -1
- package/dist/cjs/features/PdfViewer/PdfViewer.js.map +1 -1
- package/dist/cjs/features/PdfViewer/rotationManager.js +1 -1
- package/dist/cjs/features/PdfViewer/rotationManager.js.map +1 -1
- package/dist/cjs/features/PdfViewer/usePdfHighlight.js +1 -1
- package/dist/cjs/features/PdfViewer/usePdfHighlight.js.map +1 -1
- package/dist/cjs/features/PdfViewer/zoomStateManager.js +2 -0
- package/dist/cjs/features/PdfViewer/zoomStateManager.js.map +1 -0
- package/dist/cjs/features/SegmentReviewComponents/CognitiveScoreBadge.js +1 -1
- package/dist/cjs/features/SegmentReviewComponents/CognitiveScoreBadge.js.map +1 -1
- package/dist/cjs/features/SegmentReviewComponents/reviewStepAdapters.js +1 -1
- package/dist/cjs/features/SegmentReviewComponents/reviewStepAdapters.js.map +1 -1
- package/dist/features/CognitiveCompare/CitationAnchor.js +1 -1
- package/dist/features/CognitiveCompare/CitationAnchor.js.map +1 -1
- package/dist/features/CognitiveCompare/CitationRenderer.js +1 -1
- package/dist/features/CognitiveCompare/CitationRenderer.js.map +1 -1
- package/dist/features/CognitiveCompare/CognitiveCompare.js +1 -1
- package/dist/features/CognitiveCompare/CognitiveCompare.js.map +1 -1
- package/dist/features/CognitiveCompare/CognitiveCompareConstants.js +1 -1
- package/dist/features/CognitiveCompare/CognitiveCompareConstants.js.map +1 -1
- package/dist/features/CognitiveCompare/CognitiveComparehelpers.js +1 -1
- package/dist/features/CognitiveCompare/CognitiveComparehelpers.js.map +1 -1
- package/dist/features/CognitiveCompare/CognitivePopup.js +1 -1
- package/dist/features/CognitiveCompare/CognitivePopup.js.map +1 -1
- package/dist/features/CognitiveCompare/CompareContext.js +1 -1
- package/dist/features/CognitiveCompare/CompareContext.js.map +1 -1
- package/dist/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js +1 -1
- package/dist/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js.map +1 -1
- package/dist/features/CognitiveCompare/Guidelines/components/WebGptPanel.js +1 -1
- package/dist/features/CognitiveCompare/Guidelines/components/WebGptPanel.js.map +1 -1
- package/dist/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js +1 -1
- package/dist/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js.map +1 -1
- package/dist/features/CognitiveCompare/components/LHSSectionRow.js +1 -1
- package/dist/features/CognitiveCompare/components/LHSSectionRow.js.map +1 -1
- package/dist/features/CognitiveCompare/components/RHSSectionRow.js +1 -1
- package/dist/features/CognitiveCompare/components/RHSSectionRow.js.map +1 -1
- package/dist/features/CognitiveCompare/components/SectionAccordion.js +1 -1
- package/dist/features/CognitiveCompare/components/SectionAccordion.js.map +1 -1
- package/dist/features/CognitiveCompare/components/SubSectionAccordion.js +1 -1
- package/dist/features/CognitiveCompare/components/SubSectionAccordion.js.map +1 -1
- package/dist/features/CognitiveCompare/components/SvgConnectors.js +1 -1
- package/dist/features/CognitiveCompare/components/SvgConnectors.js.map +1 -1
- package/dist/features/CognitiveCompare/hooks/memoizedMarkdown.js +1 -1
- package/dist/features/CognitiveCompare/hooks/memoizedMarkdown.js.map +1 -1
- package/dist/features/CognitiveCompare/hooks/useCompareData.js +1 -1
- package/dist/features/CognitiveCompare/hooks/useCompareData.js.map +1 -1
- package/dist/features/CognitiveCompare/hooks/useLinesCalculator.js +1 -1
- package/dist/features/CognitiveCompare/hooks/useLinesCalculator.js.map +1 -1
- package/dist/features/CognitiveCompare/hooks/useSideBySide.js +1 -1
- package/dist/features/CognitiveCompare/hooks/useSideBySide.js.map +1 -1
- package/dist/features/PdfViewer/PdfToolbar.js +1 -1
- package/dist/features/PdfViewer/PdfToolbar.js.map +1 -1
- package/dist/features/PdfViewer/PdfViewer.css.js +1 -1
- package/dist/features/PdfViewer/PdfViewer.js +1 -1
- package/dist/features/PdfViewer/PdfViewer.js.map +1 -1
- package/dist/features/PdfViewer/rotationManager.js +1 -1
- package/dist/features/PdfViewer/rotationManager.js.map +1 -1
- package/dist/features/PdfViewer/usePdfHighlight.js +1 -1
- package/dist/features/PdfViewer/usePdfHighlight.js.map +1 -1
- package/dist/features/PdfViewer/zoomStateManager.js +2 -0
- package/dist/features/PdfViewer/zoomStateManager.js.map +1 -0
- package/dist/features/SegmentReviewComponents/CognitiveScoreBadge.js +1 -1
- package/dist/features/SegmentReviewComponents/CognitiveScoreBadge.js.map +1 -1
- package/dist/features/SegmentReviewComponents/reviewStepAdapters.js +1 -1
- package/dist/features/SegmentReviewComponents/reviewStepAdapters.js.map +1 -1
- package/dist/types/features/CognitiveCompare/CitationAnchor.d.ts +0 -2
- package/dist/types/features/CognitiveCompare/CitationAnchor.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CitationRenderer.d.ts +1 -8
- package/dist/types/features/CognitiveCompare/CitationRenderer.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveCompare.d.ts +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveCompare.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveCompareConstants.d.ts +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveCompareConstants.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveCompareTypes.d.ts +3 -12
- package/dist/types/features/CognitiveCompare/CognitiveCompareTypes.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CognitiveComparehelpers.d.ts +0 -12
- package/dist/types/features/CognitiveCompare/CognitiveComparehelpers.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CognitivePopup.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/CompareContext.d.ts +2 -9
- package/dist/types/features/CognitiveCompare/CompareContext.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/Guidelines/components/GuidelinePanel.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/Guidelines/components/WebGptPanel.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.d.ts +1 -14
- package/dist/types/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/components/LHSSectionRow.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/components/RHSSectionRow.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/components/SectionAccordion.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/components/SubSectionAccordion.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/components/SvgConnectors.d.ts +3 -2
- package/dist/types/features/CognitiveCompare/components/SvgConnectors.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/hooks/memoizedMarkdown.d.ts +1 -2
- package/dist/types/features/CognitiveCompare/hooks/memoizedMarkdown.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/hooks/useCompareData.d.ts +1 -1
- package/dist/types/features/CognitiveCompare/hooks/useCompareData.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/hooks/useLinesCalculator.d.ts.map +1 -1
- package/dist/types/features/CognitiveCompare/hooks/useSideBySide.d.ts.map +1 -1
- package/dist/types/features/PdfViewer/PdfToolbar.d.ts.map +1 -1
- package/dist/types/features/PdfViewer/PdfViewer.d.ts.map +1 -1
- package/dist/types/features/PdfViewer/rotationManager.d.ts.map +1 -1
- package/dist/types/features/PdfViewer/usePdfHighlight.d.ts +1 -2
- package/dist/types/features/PdfViewer/usePdfHighlight.d.ts.map +1 -1
- package/dist/types/features/PdfViewer/zoomStateManager.d.ts +21 -0
- package/dist/types/features/PdfViewer/zoomStateManager.d.ts.map +1 -0
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t}from"react/jsx-runtime";import{Dialog as o}from"@mui/material";import{Globe as i,ChevronUp as n,ChevronDown as r}from"lucide-react";import{useState as a,useEffect as l,useMemo as d,useCallback as s}from"react";import{DefaultFullScreenCloseIcon as p,DefaultFullScreenIcon as c}from"../../assests/svg/PdfViewerIcons.js";import{useOptionalCompareContext as g}from"./CompareContext.js";import h from"./CitationRendererInner.js";const x="90vh",m={border:"1px solid #D0D5DD",borderRadius:"6px",background:"#FFFFFF",color:"#344054",cursor:"pointer",fontSize:"12px",fontWeight:600,padding:"3px 8px"},f=({href:f,children:u,citationType:b,citationReason:y,metaData:C,chevronUpComponent:v=null,chevronDownComponent:w=null,customStyle:F={},defaultState:D=!1,onFullscreenChange:k,onDemandCitationContext:S})=>{const z=g(),R=z?.onDemandCitationConfig,A=z?.getOnDemandCitationCacheEntry,j=z?.fetchOnDemandCitationContext,B=z?.onDemandCitationCacheVersion,[G,W]=a(D),[E,I]=a(!1),P="string"==typeof u&&u?.split("\n")?.length>1?u.split("\n").join(" "):u,T="string"==typeof u?u:u[0];l(()=>{if(k?.(E),E)return()=>{k?.(!1)}},[E,k]);const O=d(()=>S&&A?A(S):void 0,[A,B,S]),H=!!R?.enabled&&!!S,L="success"===O?.status&&O.data&&"object"==typeof O.data&&Object.keys(O.data).length>0,U=d(()=>({...C,citations:H?L?O?.data:{}:C?.citations}),[L,H,C,O?.data]),V=H&&(!O||"loading"===O.status)&&!L,q=H&&"error"===O?.status&&!L,J=H&&"success"===O?.status&&!L,K=!H||L,M=s(()=>{R?.enabled&&S&&j&&("loading"===O?.status||"success"===O?.status&&L||j(S).catch(e=>{R.debug&&console.error("[CognitiveCompare:onDemandCitations] citation fetch failed",e)}))},[j,L,O?.status,R,S]),N=v??(Q=F?.arrow??{},t(n,{size:Q?.fontSize??16,color:Q?.color??"rgb(214, 51, 132)"}));var Q;const X=w??(e=>t(r,{size:e?.fontSize??16,color:e?.color??"rgb(214, 51, 132)"}))(F?.arrow??{}),Y=e=>t("button",{type:"button",onClick:e=>{e.stopPropagation(),M()},style:{...m,...e},children:"Retry"}),Z=e("div",{style:{boxSizing:"border-box",border:E?"none":"1px solid #E4E7EC",borderRadius:E?0:"8px",overflow:"hidden",marginTop:E?0:"8px",display:"flex",flexDirection:"column",width:"100%",height:E?"100%":void 0,backgroundColor:"#FAFAFA"},children:[t("div",{style:{display:"flex",justifyContent:"flex-end",padding:"6px 10px",borderBottom:"1px solid #E4E7EC",backgroundColor:"#FFFFFF",flexShrink:0},children:t("button",{onClick:()=>{I(e=>!e)},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px",color:"#475467",marginRight:"9px"},children:t(E?p:c,{})})}),e("div",{style:{flex:1,minHeight:0,height:"100%",overflow:"hidden"},children:[V&&t("div",{style:{padding:"12px",fontSize:"13px",color:"#475467"},children:"Loading citation details..."}),q&&e("div",{style:{padding:"12px",fontSize:"13px",color:"#B42318",display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[t("span",{children:"Unable to load citation details. Please try again later."}),Y({border:"1px solid #FDA29B",color:"#B42318"})]}),J&&e("div",{style:{padding:"12px",fontSize:"13px",color:"#475467",display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[t("span",{children:"Citation details are not available for this source."}),Y()]}),K&&t(h,{href:f,children:u,metaData:U,citationTitle:T,citationType:b,citationReason:y,isFullscreen:E})]})]});return e("span",{style:{display:"inline",...F.relativeWrapper||{}},children:[t("div",{style:{display:"inline",marginTop:0,...F.citationButtonWrapper||{}},children:e("button",{type:"button",onClick:()=>{W(e=>{const t=!e;return t&&M(),t})},style:{display:C?.webGpt?"inline":"inline-flex",alignItems:C?.webGpt?void 0:"center",gap:C?.webGpt?void 0:"3px",fontFamily:'"Inter", sans-serif',backgroundColor:"transparent",padding:0,margin:0,fontSize:"13px",borderRadius:9999,cursor:"pointer",fontWeight:C?.webGpt?600:700,color:C?.webGpt?"#6D28D9":"rgb(214, 51, 132)",border:"none",textDecoration:"none",wordBreak:"break-word",whiteSpace:"normal",...F.citationButton||{}},children:[C?.webGpt&&t(i,{size:F.arrow?.fontSize??"1em",color:F.arrow?.color??"#6D28D9",style:{display:"inline-block",width:"1em",height:"1em",marginRight:"3px",verticalAlign:"-0.125em",flexShrink:0}}),t("span",{children:P}),t("span",{style:{display:"inline-flex",alignItems:"center",marginLeft:C?.webGpt?"3px":void 0,verticalAlign:C?.webGpt?"-0.125em":void 0},children:G?N:X})]})}),G&&(E?t(o,{open:E,onClose:()=>{I(!1),k?.(!1)},maxWidth:!1,BackdropProps:{sx:{backgroundColor:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"}},PaperProps:{sx:{backgroundColor:"#FAFAFA",borderRadius:"16px",height:x,m:0,maxHeight:x,maxWidth:"95vw",overflow:"hidden",width:"95vw"}},children:Z}):Z)]})};export{f as default};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as i}from"react/jsx-runtime";import{Globe as a,ChevronUp as o,ChevronDown as n,Maximize2 as r,X as l,ExternalLink as s}from"lucide-react";import{useState as c,useEffect as d,useMemo as p,useRef as u}from"react";import m from"./ResizableSplitPane.js";import h from"../PdfViewer/PdfViewer.js";import{DefaultFullScreenCloseIcon as g,DefaultFullScreenIcon as x}from"../../assests/svg/PdfViewerIcons.js";import f from"react-markdown";import b from"rehype-raw";import{Dialog as _,Box as y}from"@mui/material";import{SHARED_MARKDOWN_STYLES as w}from"./CognitiveCompareConfig.js";import"react-dom";import{useCompareContext as C}from"./CompareContext.js";import{processGuidelinesMarkdown as F}from"./Guidelines/utils/processGuidelinesMarkdown.js";import D from"../GptWebCitation/GptWebCitation.js";import{CitationType as v}from"../GptWebCitation/types.js";import"./components/SubSectionAccordion.js";import"./components/LHSSectionRow.js";import"./components/RHSSectionRow.js";const P=e=>(e?.extraMetaData||e)?.aiReasoningCitation?.gpt_citation?.[0]||null,T="https://dev-proposals-ai.techo.camp/utility/ca-workflow-composer-agent/get_citation",S="sai.siddhartha@techolution.com",k="672e32f7a0e8fe2e8e50bcba",N="TNV Sai Siddhartha",I="90vh",j=`calc(${I} - 120px)`,R=()=>"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)}),G=(e,t)=>{const i=(e=>e?.payloadCitationId||e?.extraMetaData?.payloadCitationId||"")(e)||t||R();return((e,t)=>{e&&"object"==typeof e&&(e.payloadCitationId=t,e.extraMetaData&&"object"==typeof e.extraMetaData&&(e.extraMetaData.payloadCitationId=t))})(e,i),i},U=({metaData:e,isFullscreen:i=!1})=>{const{gptWebCitationConfig:a}=C(),m=p(()=>(e=>({endpoint:e?.endpoint||T,userEmail:e?.userEmail||S,userId:e?.userId||k,userName:e?.userName||N,headers:e?.headers}))(a),[a]),h=e?.webGpt,g=u(null);g.current||(g.current=R());const x=p(()=>((e,t,i)=>{const a=P(e),o=a?.customMetaData||{},n=o?.value||{},r=e?.webSearchAnswer||{},l=e?.extraMetaData||e||{};return{userEmail:e?.userEmail||r?.userEmail||t?.userEmail||"",userId:e?.userId||r?.userId||t?.userId||"",userName:e?.userName||r?.userName||t?.userName||"",citationId:G(e,i),citationUrl:n?.citationUrl||r?.citationUrl||"",content:l?.Reasoning||r?.enhanced_content||"",citationType:n?.citationType||"web",citatioNumber:o?.citation_number??a?.citation_number??Number(e?.reasoningId||0)}})(h,m,g.current||void 0),[h,m]),f=p(()=>P(h),[h]),b=f?.customMetaData?.value||{},_=h?.extraMetaData||h||{},[y,w]=c(),[F,I]=c("pending"),[U,E]=c(!0);d(()=>{let e=!0;return(async()=>{if(m.endpoint&&x?.citationUrl&&x?.content){I("pending");try{const t=await fetch(m.endpoint,{method:"POST",headers:{"actor-id":x.userEmail,Accept:"application/json, text/plain, */*","Content-Type":"application/json",...m.headers||{}},body:JSON.stringify(x)});if(!t.ok)throw new Error(`Failed to fetch GPT web citation (${t.status})`);const i=await t.json();if(!e)return;w(i?.responseData||i?.result||i?.data||i),I("success")}catch(t){if(!e)return;console.error("Failed to load GPT web citation",t),I("error")}}else I("error")})(),()=>{e=!1}},[x,m]);const A=p(()=>({item:{confidence_score:Number(_?.Confidence_score||0),text:b?.paraphrase||"Web citation reasoning",dataSource:b?.text||_?.Reasoning||"",paraphrase:b?.paraphrase||""},headerTitle:"GPT Web Citation",index:Number(x?.citatioNumber||1)-1,iconsConfig:{ChevronDownIcon:n,ChevronUpIcon:o,MaximizeIcon:r,CloseIcon:l}}),[b,x?.citatioNumber,_]),H=p(()=>({...A,...i?{bodyHeight:j}:{}}),[A,i]);return t(D,{gptCitation:H,defaultCitationUrl:x?.citationUrl||"",citationType:v.GPT_WEB,webCitationData:y,webCitationStatus:F,showWebCitation:U,onToggleCitationView:()=>E(e=>!e),iconsConfig:{MaximizeIcon:r,ExternalLinkIcon:s},isFixedHeight:!0})},E=({href:e,metaData:a,citationTitle:o,citationType:n,citationReason:r,isFullscreen:l})=>{const{guidelinesData:s}=C(),{citationNumber:c,phraseToHighlight:d,citationTypeFromHref:u}=(e=>{try{const{citationNumber:t,parsedUrl:i}=(e=>{const t=e.match(/^(?:pdf_citation|deviation_summary)\$(\d+)/);if(t)try{const i=e.indexOf("?"),a=i>=0?e.slice(i):"";return{citationNumber:t[1],parsedUrl:new URL(a||"./",window.location.origin)}}catch{return{citationNumber:t[1],parsedUrl:null}}try{const t=new URL(e,window.location.origin);return{citationNumber:t.searchParams.get("citationNumber")||t.searchParams.get("citation_number"),parsedUrl:t}}catch{return{citationNumber:null,parsedUrl:null}}})(e),a=i?.searchParams.get("phrase_to_highlight")||null;return{citationNumber:t,phraseToHighlight:a,citationTypeFromHref:i?.searchParams.get("citation_type")||null}}catch{return{citationNumber:null,phraseToHighlight:null,citationTypeFromHref:null}}})(e),g=n||u||void 0,x="il_rulebook_citation"===g?"rulebook_citation":g,_=c&&a?.citations?.[c]||{},D=a?.docData?.documents||{},v=a?.docData?.input_index_map||{},P=Object.keys(a?.citations||{}).length>0||Object.keys(a?.docData||{}).length>0,T=v?.[0],S=v?.[1],k=T?D[T]:null,N=S?D[S]:null,I=T?_[T]:null,j=S?_[S]:null,R=p(()=>I&&k?t(h,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:k?.title,pdfUrl:k?.signed_url,highlightText:[I?.highlighted_text??""],highlightPages:{1:I?.custom_metadata?.pdf_start_page_number},jumpToPageValue:1,highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[I?.custom_metadata?.pdf_start_page_number,I?.custom_metadata?.pdf_end_page_number]}):null,[k?.title,k?.signed_url,I?.highlighted_text,I?.custom_metadata?.pdf_start_page_number,I?.custom_metadata?.pdf_end_page_number]),G=p(()=>j&&N?t(h,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:N?.title,pdfUrl:N?.signed_url,jumpToPageValue:1,highlightText:[j?.highlighted_text??""],highlightPages:{1:j?.custom_metadata?.pdf_start_page_number},highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[j?.custom_metadata?.pdf_start_page_number,j?.custom_metadata?.pdf_end_page_number]}):null,[N?.title,N?.signed_url,j?.highlighted_text,j?.custom_metadata?.pdf_start_page_number,j?.custom_metadata?.pdf_end_page_number]),E="dual_citation"===x,A=E&&!!a?.webGpt,H=p(()=>{if(!R)return null;const e=A?t(U,{metaData:a,isFullscreen:l}):"rulebook_citation"===x?t(i,{children:t(y,{sx:{padding:"0px 20px",backgroundColor:"#FFFFFF",borderRadius:"8px",...w,overflow:"auto"},children:t(f,{rehypePlugins:[b],children:F({guidelinesData:s,targetHighlights:[d],labelColor:"#FEF08A"})})})}):G;return e?t(m,{leftComponent:R,rightComponent:e,isFullscreen:l}):R},[R,G,x,A,a,l,s,d]);return a?.webGpt&&!P?t(U,{metaData:a,isFullscreen:l}):c?"rulebook_citation"===x?t("div",I?{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}:{style:{padding:"12px",fontSize:"13px",color:"#344054",lineHeight:1.5},children:r||"Rulebook citation selected."}):E?I||j?t("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}):a?.webGpt?t(U,{metaData:a,isFullscreen:l}):t("div",{children:"Missing PDF Citation. Please try again later"}):["contract","clause"].includes(o)?t("div",I||j?{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}:{children:"Missing PDF Citation. Please try again later"}):t("div",{children:"No Citation Found. Please try again later"}):null},A=({href:i,children:r,citationType:l,citationReason:s,metaData:p,chevronUpComponent:u=null,chevronDownComponent:m=null,customStyle:h={},defaultState:f=!1,onFullscreenChange:b})=>{const[y,w]=c(f),[C,F]=c(!1),D="string"==typeof r&&r?.split("\n")?.length>1?r.split("\n").join(" "):r;d(()=>{if(b?.(C),C)return()=>{b?.(!1)}},[C,b]);const v="string"==typeof r?r:r[0],P=u??(T=h?.arrow??{},t(o,{size:T?.fontSize??16,color:T?.color??"rgb(214, 51, 132)"}));var T;const S=m??(e=>t(n,{size:e?.fontSize??16,color:e?.color??"rgb(214, 51, 132)"}))(h?.arrow??{}),k=e("div",{style:{boxSizing:"border-box",border:C?"none":"1px solid #E4E7EC",borderRadius:C?0:"8px",overflow:"hidden",marginTop:C?0:"8px",display:"flex",flexDirection:"column",width:"100%",height:C?"100%":void 0,backgroundColor:"#FAFAFA"},children:[t("div",{style:{display:"flex",justifyContent:"flex-end",padding:"6px 10px",borderBottom:"1px solid #E4E7EC",backgroundColor:"#FFFFFF",flexShrink:0},children:t("button",{onClick:()=>{F(e=>!e)},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px",color:"#475467",marginRight:"9px"},children:t(C?g:x,{})})}),t("div",{style:{flex:1,minHeight:0,height:"100%",overflow:"hidden"},children:t(E,{href:i,children:r,metaData:p,citationTitle:v,citationType:l,citationReason:s,isFullscreen:C})})]});return e("span",{style:{display:"inline",...h.relativeWrapper||{}},children:[t("div",{style:{display:"inline",marginTop:0,...h.citationButtonWrapper||{}},children:e("button",{type:"button",onClick:()=>w(e=>!e),style:{display:p?.webGpt?"inline":"inline-flex",alignItems:p?.webGpt?void 0:"center",gap:p?.webGpt?void 0:"3px",fontFamily:'"Inter", sans-serif',backgroundColor:"transparent",padding:0,margin:0,fontSize:"13px",borderRadius:9999,cursor:"pointer",fontWeight:p?.webGpt?600:700,color:p?.webGpt?"#6D28D9":"rgb(214, 51, 132)",border:"none",textDecoration:"none",wordBreak:"break-word",whiteSpace:"normal",...h.citationButton||{}},children:[p?.webGpt&&t(a,{size:h.arrow?.fontSize??"1em",color:h.arrow?.color??"#6D28D9",style:{display:"inline-block",width:"1em",height:"1em",marginRight:"3px",verticalAlign:"-0.125em",flexShrink:0}}),t("span",{children:D}),t("span",{style:{display:"inline-flex",alignItems:"center",marginLeft:p?.webGpt?"3px":void 0,verticalAlign:p?.webGpt?"-0.125em":void 0},children:y?P:S})]})}),y&&(C?t(_,{open:C,onClose:()=>F(!1),maxWidth:!1,BackdropProps:{sx:{backgroundColor:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"}},PaperProps:{sx:{backgroundColor:"#FAFAFA",borderRadius:"16px",height:I,m:0,maxHeight:I,maxWidth:"95vw",overflow:"hidden",width:"95vw"}},children:k}):k)]})};export{A as default};
|
|
2
2
|
//# sourceMappingURL=CitationAnchor.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CitationAnchor.js","sources":["../../../src/features/CognitiveCompare/CitationAnchor.tsx"],"sourcesContent":["import { Dialog } from \"@mui/material\";\nimport { ChevronDown, ChevronUp, Globe } from \"lucide-react\";\nimport React, {\n CSSProperties,\n useCallback,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { DefaultFullScreenIcon, DefaultFullScreenCloseIcon } from \"../../assests/svg/PdfViewerIcons\";\nimport type { OnDemandCitationContext } from \"./CognitiveCompareTypes\";\nimport { useOptionalCompareContext } from \"./CompareContext\";\nimport CitationRendererInner from \"./CitationRendererInner\";\n\ninterface CitationAnchorProps {\n href: string;\n children: any;\n citationType?: string;\n citationReason?: string;\n chevronUpComponent?: React.ReactNode;\n chevronDownComponent?: React.ReactNode;\n customStyle?: {\n citationButtonWrapper?: CSSProperties;\n arrow?: CSSProperties;\n citationButton?: CSSProperties;\n expandableContent?: CSSProperties;\n bookHeader?: CSSProperties;\n relative?: CSSProperties;\n pageColor?: CSSProperties;\n highlightedText?: CSSProperties;\n expandedWrapper?: CSSProperties;\n expandableContainer?: CSSProperties;\n bookBodyContent?: CSSProperties;\n customScrollbarClass?: CSSProperties;\n relativeWrapper?: CSSProperties;\n };\n defaultState?: boolean;\n metaData?: any;\n onFullscreenChange?: (isFullscreen: boolean) => void;\n onDemandCitationContext?: OnDemandCitationContext;\n}\n\nconst CITATION_FULLSCREEN_DIALOG_HEIGHT = \"90vh\";\n\nconst retryButtonStyle: React.CSSProperties = {\n border: \"1px solid #D0D5DD\",\n borderRadius: \"6px\",\n background: \"#FFFFFF\",\n color: \"#344054\",\n cursor: \"pointer\",\n fontSize: \"12px\",\n fontWeight: 600,\n padding: \"3px 8px\",\n};\n\nconst CitationAnchor: React.FC<CitationAnchorProps> = ({\n href,\n children,\n citationType,\n citationReason,\n metaData,\n chevronUpComponent = null,\n chevronDownComponent = null,\n customStyle = {},\n defaultState = false,\n onFullscreenChange,\n onDemandCitationContext,\n}) => {\n const compareContext = useOptionalCompareContext();\n const onDemandCitationConfig = compareContext?.onDemandCitationConfig;\n const getOnDemandCitationCacheEntry = compareContext?.getOnDemandCitationCacheEntry;\n const fetchOnDemandCitationContext = compareContext?.fetchOnDemandCitationContext;\n const onDemandCitationCacheVersion = compareContext?.onDemandCitationCacheVersion;\n const [isExpanded, setIsExpanded] = useState(defaultState);\n const [isFullscreen, setIsFullscreen] = useState(false);\n\n const ChevronUpComponentDefault = (arrow: CSSProperties) => (\n <ChevronUp\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n\n const ChevronDownComponentDefault = (arrow: CSSProperties) => (\n <ChevronDown\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n\n const citationDisplayTitle =\n typeof children === \"string\" && children?.split(\"\\n\")?.length > 1\n ? children.split(\"\\n\").join(\" \")\n : children;\n const citationTitle = typeof children === \"string\" ? children : children[0];\n\n useEffect(() => {\n onFullscreenChange?.(isFullscreen);\n\n if (!isFullscreen) return;\n\n return () => {\n onFullscreenChange?.(false);\n };\n }, [isFullscreen, onFullscreenChange]);\n\n const onDemandCacheEntry = useMemo(\n () => onDemandCitationContext && getOnDemandCitationCacheEntry\n ? getOnDemandCitationCacheEntry(onDemandCitationContext)\n : undefined,\n [\n getOnDemandCitationCacheEntry,\n onDemandCitationCacheVersion,\n onDemandCitationContext,\n ],\n );\n const isOnDemandCitationEnabled =\n !!onDemandCitationConfig?.enabled &&\n !!onDemandCitationContext;\n const hasOnDemandCitationData =\n onDemandCacheEntry?.status === \"success\" &&\n onDemandCacheEntry.data &&\n typeof onDemandCacheEntry.data === \"object\" &&\n Object.keys(onDemandCacheEntry.data).length > 0;\n const effectiveMetaData = useMemo(\n () => ({\n ...metaData,\n citations: isOnDemandCitationEnabled\n ? (hasOnDemandCitationData ? onDemandCacheEntry?.data : {})\n : metaData?.citations,\n }),\n [\n hasOnDemandCitationData,\n isOnDemandCitationEnabled,\n metaData,\n onDemandCacheEntry?.data,\n ],\n );\n const shouldShowLoading =\n isOnDemandCitationEnabled &&\n (!onDemandCacheEntry || onDemandCacheEntry.status === \"loading\") &&\n !hasOnDemandCitationData;\n const shouldShowError =\n isOnDemandCitationEnabled &&\n onDemandCacheEntry?.status === \"error\" &&\n !hasOnDemandCitationData;\n const shouldShowMissing =\n isOnDemandCitationEnabled &&\n onDemandCacheEntry?.status === \"success\" &&\n !hasOnDemandCitationData;\n const shouldRenderCitationContent =\n !isOnDemandCitationEnabled || hasOnDemandCitationData;\n\n const requestOnDemandCitation = useCallback(() => {\n if (\n !onDemandCitationConfig?.enabled ||\n !onDemandCitationContext ||\n !fetchOnDemandCitationContext\n ) {\n return;\n }\n\n if (\n onDemandCacheEntry?.status === \"loading\" ||\n (onDemandCacheEntry?.status === \"success\" && hasOnDemandCitationData)\n ) {\n return;\n }\n\n fetchOnDemandCitationContext(onDemandCitationContext).catch((error) => {\n if (onDemandCitationConfig.debug) {\n console.error(\"[CognitiveCompare:onDemandCitations] citation fetch failed\", error);\n }\n });\n }, [\n fetchOnDemandCitationContext,\n hasOnDemandCitationData,\n onDemandCacheEntry?.status,\n onDemandCitationConfig,\n onDemandCitationContext,\n ]);\n\n const toggleCitation = () => {\n setIsExpanded((prev) => {\n const next = !prev;\n if (next) {\n requestOnDemandCitation();\n }\n return next;\n });\n };\n const chevronUpComponentResolved =\n chevronUpComponent ??\n ChevronUpComponentDefault(customStyle?.arrow ?? {});\n const chevronDownComponentResolved =\n chevronDownComponent ??\n ChevronDownComponentDefault(customStyle?.arrow ?? {});\n\n const handleFullscreen = () => {\n setIsFullscreen((prev) => !prev);\n };\n\n const renderRetryButton = (style?: React.CSSProperties) => (\n <button\n type=\"button\"\n onClick={(event) => {\n event.stopPropagation();\n requestOnDemandCitation();\n }}\n style={{ ...retryButtonStyle, ...style }}\n >\n Retry\n </button>\n );\n\n const citationPanel = (\n <div\n style={{\n boxSizing: \"border-box\",\n border: isFullscreen ? \"none\" : \"1px solid #E4E7EC\",\n borderRadius: isFullscreen ? 0 : \"8px\",\n overflow: \"hidden\",\n marginTop: isFullscreen ? 0 : \"8px\",\n display: \"flex\",\n flexDirection: \"column\",\n width: \"100%\",\n height: isFullscreen ? \"100%\" : undefined,\n backgroundColor: \"#FAFAFA\",\n }}\n >\n <div style={{\n display: \"flex\",\n justifyContent: \"flex-end\",\n padding: \"6px 10px\",\n borderBottom: \"1px solid #E4E7EC\",\n backgroundColor: \"#FFFFFF\",\n flexShrink: 0,\n }}>\n <button onClick={handleFullscreen}\n style={{ background: \"none\", border: \"none\", cursor: \"pointer\", padding: \"4px\", borderRadius: \"6px\", color: \"#475467\", marginRight: \"9px\" }}>\n {isFullscreen ? <DefaultFullScreenCloseIcon /> : <DefaultFullScreenIcon />}\n </button>\n </div>\n <div style={{ flex: 1, minHeight: 0, height: \"100%\", overflow: \"hidden\" }}>\n {shouldShowLoading && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#475467\" }}>\n Loading citation details...\n </div>\n )}\n {shouldShowError && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#B42318\", display: \"flex\", alignItems: \"center\", gap: \"8px\", flexWrap: \"wrap\" }}>\n <span>\n Unable to load citation details. Please try again later.\n </span>\n {renderRetryButton({\n border: \"1px solid #FDA29B\",\n color: \"#B42318\",\n })}\n </div>\n )}\n {shouldShowMissing && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#475467\", display: \"flex\", alignItems: \"center\", gap: \"8px\", flexWrap: \"wrap\" }}>\n <span>Citation details are not available for this source.</span>\n {renderRetryButton()}\n </div>\n )}\n {shouldRenderCitationContent && (\n <CitationRendererInner\n href={href}\n children={children}\n metaData={effectiveMetaData}\n citationTitle={citationTitle}\n citationType={citationType}\n citationReason={citationReason}\n isFullscreen={isFullscreen}\n />\n )}\n </div>\n </div>\n );\n\n return (\n <span\n style={{\n display: \"inline\",\n ...(customStyle.relativeWrapper || {}),\n }}\n >\n <div\n style={{\n display: \"inline\",\n marginTop: 0,\n ...(customStyle.citationButtonWrapper || {}),\n }}\n >\n <button\n type=\"button\"\n onClick={toggleCitation}\n style={{\n display: metaData?.webGpt ? \"inline\" : \"inline-flex\",\n alignItems: metaData?.webGpt ? undefined : \"center\",\n gap: metaData?.webGpt ? undefined : \"3px\",\n fontFamily: '\"Inter\", sans-serif',\n backgroundColor: \"transparent\",\n padding: 0,\n margin: 0,\n fontSize: \"13px\",\n borderRadius: 9999,\n cursor: \"pointer\",\n fontWeight: (metaData?.webGpt) ? 600 : 700,\n color: (metaData?.webGpt) ? \"#6D28D9\" : \"rgb(214, 51, 132)\",\n border: \"none\",\n textDecoration: \"none\",\n wordBreak: \"break-word\",\n whiteSpace: \"normal\",\n ...(customStyle.citationButton || {}),\n }}\n >\n {metaData?.webGpt && (\n <Globe\n size={customStyle.arrow?.fontSize ?? \"1em\"}\n color={customStyle.arrow?.color ?? \"#6D28D9\"}\n style={{\n display: \"inline-block\",\n width: \"1em\",\n height: \"1em\",\n marginRight: \"3px\",\n verticalAlign: \"-0.125em\",\n flexShrink: 0,\n }}\n />\n )}\n <span>{citationDisplayTitle}</span>\n\n <span\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n marginLeft: metaData?.webGpt ? \"3px\" : undefined,\n verticalAlign: metaData?.webGpt ? \"-0.125em\" : undefined,\n }}\n >\n {isExpanded\n ? chevronUpComponentResolved\n : chevronDownComponentResolved}\n </span>\n </button>\n </div>\n {isExpanded && (\n isFullscreen ? (\n <Dialog\n open={isFullscreen}\n onClose={() => {\n setIsFullscreen(false);\n onFullscreenChange?.(false);\n }}\n maxWidth={false}\n BackdropProps={{\n sx: {\n backgroundColor: \"rgba(0, 0, 0, 0.6)\",\n backdropFilter: \"blur(4px)\",\n },\n }}\n PaperProps={{\n sx: {\n backgroundColor: \"#FAFAFA\",\n borderRadius: \"16px\",\n height: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n m: 0,\n maxHeight: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n maxWidth: \"95vw\",\n overflow: \"hidden\",\n width: \"95vw\",\n },\n }}\n >\n {citationPanel}\n </Dialog>\n ) : (\n citationPanel\n )\n )}\n </span>\n );\n};\n\nexport default CitationAnchor;\n"],"names":["CITATION_FULLSCREEN_DIALOG_HEIGHT","retryButtonStyle","border","borderRadius","background","color","cursor","fontSize","fontWeight","padding","CitationAnchor","href","children","citationType","citationReason","metaData","chevronUpComponent","chevronDownComponent","customStyle","defaultState","onFullscreenChange","onDemandCitationContext","compareContext","useOptionalCompareContext","onDemandCitationConfig","getOnDemandCitationCacheEntry","fetchOnDemandCitationContext","onDemandCitationCacheVersion","isExpanded","setIsExpanded","useState","isFullscreen","setIsFullscreen","citationDisplayTitle","split","length","join","citationTitle","useEffect","onDemandCacheEntry","useMemo","isOnDemandCitationEnabled","enabled","hasOnDemandCitationData","status","data","Object","keys","effectiveMetaData","citations","shouldShowLoading","shouldShowError","shouldShowMissing","shouldRenderCitationContent","requestOnDemandCitation","useCallback","catch","error","debug","console","chevronUpComponentResolved","arrow","jsx","ChevronUp","size","chevronDownComponentResolved","ChevronDown","ChevronDownComponentDefault","renderRetryButton","style","type","onClick","event","stopPropagation","citationPanel","jsxs","boxSizing","overflow","marginTop","display","flexDirection","width","height","backgroundColor","justifyContent","borderBottom","flexShrink","prev","marginRight","DefaultFullScreenCloseIcon","DefaultFullScreenIcon","flex","minHeight","alignItems","gap","flexWrap","CitationRendererInner","relativeWrapper","citationButtonWrapper","next","webGpt","fontFamily","margin","textDecoration","wordBreak","whiteSpace","citationButton","Globe","verticalAlign","marginLeft","Dialog","open","onClose","maxWidth","BackdropProps","sx","backdropFilter","PaperProps","m","maxHeight"],"mappings":"kcA0CA,MAAMA,EAAoC,OAEpCC,EAAwC,CAC1CC,OAAQ,oBACRC,aAAc,MACdC,WAAY,UACZC,MAAO,UACPC,OAAQ,UACRC,SAAU,OACVC,WAAY,IACZC,QAAS,WAGPC,EAAgD,EAClDC,OACAC,WACAC,eACAC,iBACAC,WACAC,qBAAqB,KACrBC,uBAAuB,KACvBC,cAAc,CAAC,EACfC,gBAAe,EACfC,qBACAC,8BAEA,MAAMC,EAAiBC,IACjBC,EAAyBF,GAAgBE,uBACzCC,EAAgCH,GAAgBG,8BAChDC,EAA+BJ,GAAgBI,6BAC/CC,EAA+BL,GAAgBK,8BAC9CC,EAAYC,GAAiBC,EAASX,IACtCY,EAAcC,GAAmBF,GAAS,GAgB3CG,EACkB,iBAAbrB,GAAyBA,GAAUsB,MAAM,OAAOC,OAAS,EAC1DvB,EAASsB,MAAM,MAAME,KAAK,KAC1BxB,EACJyB,EAAoC,iBAAbzB,EAAwBA,EAAWA,EAAS,GAEzE0B,EAAU,KAGN,GAFAlB,IAAqBW,GAEhBA,EAEL,MAAO,KACHX,KAAqB,KAE1B,CAACW,EAAcX,IAElB,MAAMmB,EAAqBC,EACvB,IAAMnB,GAA2BI,EAC3BA,EAA8BJ,QAC9B,EACN,CACII,EACAE,EACAN,IAGFoB,IACAjB,GAAwBkB,WACxBrB,EACAsB,EAC6B,YAA/BJ,GAAoBK,QACpBL,EAAmBM,MACgB,iBAA5BN,EAAmBM,MAC1BC,OAAOC,KAAKR,EAAmBM,MAAMV,OAAS,EAC5Ca,EAAoBR,EACtB,KAAO,IACAzB,EACHkC,UAAWR,EACJE,EAA0BJ,GAAoBM,KAAO,CAAA,EACtD9B,GAAUkC,YAEpB,CACIN,EACAF,EACA1B,EACAwB,GAAoBM,OAGtBK,EACFT,KACEF,GAAoD,YAA9BA,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AY9E,GAAUqF,YAAqB,EAAA,SAC3CN,IAAK/E,GAAUqF,YAAqB,EAAA,MACpCC,WAAY,sBACZlB,gBAAiB,cACjB1E,QAAS,EACT6F,OAAQ,EACR/F,SAAU,OACVJ,aAAc,KACdG,OAAQ,UACRE,WAAaO,GAAUqF,OAAU,IAAM,IACvC/F,MAAQU,GAAUqF,OAAU,UAAY,oBACxClG,OAAQ,OACRqG,eAAgB,OAChBC,UAAW,aACXC,WAAY,YACRvF,EAAYwF,gBAAkB,CAAC,GAGtC9F,SAAA,CAAAG,GAAUqF,QACPtC,EAAC6C,EAAA,CACG3C,KAAM9C,EAAY2C,OAAOtD,UAAY,MACrCF,MAAOa,EAAY2C,OAAOxD,OAAS,UACnCgE,MAAO,CACHU,QAAS,eACTE,MAAO,MACPC,OAAQ,MACRM,YAAa,MACboB,cAAe,WACftB,WAAY,KAIxBxB,EAAC,QAAMlD,SAAqBqB,IAE5B6B,EAAC,OAAA,CACGO,MAAO,CACHU,QAAS,cACTc,WAAY,SACZgB,WAAY9F,GAAUqF,OAAS,WAAQ,EACvCQ,cAAe7F,GAAUqF,OAAS,gBAAa,GAGlDxF,WACKgD,EACAK,SAIjBrC,IACGG,EACI+B,EAACgD,EAAA,CACGC,KAAMhF,EACNiF,QAAS,KACLhF,GAAgB,GAChBZ,KAAqB,IAEzB6F,UAAU,EACVC,cAAe,CACXC,GAAI,CACAhC,gBAAiB,qBACjBiC,eAAgB,cAGxBC,WAAY,CACRF,GAAI,CACAhC,gBAAiB,UACjBhF,aAAc,OACd+E,OAAQlF,EACRsH,EAAG,EACHC,UAAWvH,EACXiH,SAAU,OACVpC,SAAU,SACVI,MAAO,SAIdrE,SAAA8D,IAGLA"}
|
|
1
|
+
{"version":3,"file":"CitationAnchor.js","sources":["../../../src/features/CognitiveCompare/CitationAnchor.tsx"],"sourcesContent":["// import PdfViewer from \"@e-llm-studio/citation/PdfViewer\";\nimport DOMPurify from \"dompurify\";\nimport { ChevronDown, ChevronUp, ExternalLink, Globe, Maximize2, X } from \"lucide-react\";\nimport React, {\n CSSProperties,\n useState,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport ResizableSplitPane from \"./ResizableSplitPane\";\nimport PdfViewer from \"../PdfViewer/PdfViewer\";\nimport { DefaultFullScreenIcon, DefaultFullScreenCloseIcon } from \"../../assests/svg/PdfViewerIcons\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport { Box, Dialog } from '@mui/material';\nimport { SHARED_MARKDOWN_STYLES } from \"./CognitiveCompare\";\nimport { useCompareContext } from \"./CompareContext\";\nimport { processGuidelinesMarkdown } from \"./Guidelines/utils/processGuidelinesMarkdown\";\nimport GptWebCitation from \"../GptWebCitation/GptWebCitation\";\nimport { CitationType, GptWebCitationStatus, IWebCitationApiResponse } from \"../GptWebCitation/types\";\nimport { GptWebCitationConfig } from \"./CognitiveCompareTypes\";\n\ninterface CitationAnchorProps {\n href: string;\n children: any;\n citationType?: string;\n citationReason?: string;\n chevronUpComponent?: React.ReactNode;\n chevronDownComponent?: React.ReactNode;\n customStyle?: {\n citationButtonWrapper?: CSSProperties;\n arrow?: CSSProperties;\n citationButton?: CSSProperties;\n expandableContent?: CSSProperties;\n bookHeader?: CSSProperties;\n relative?: CSSProperties;\n pageColor?: CSSProperties;\n highlightedText?: CSSProperties;\n expandedWrapper?: CSSProperties;\n expandableContainer?: CSSProperties;\n bookBodyContent?: CSSProperties;\n customScrollbarClass?: CSSProperties;\n relativeWrapper?: CSSProperties;\n };\n defaultState?: boolean;\n metaData?: any;\n onFullscreenChange?: (isFullscreen: boolean) => void;\n}\ninterface CitationRendererInnerProps {\n href: string;\n children: any;\n metaData: any;\n citationTitle: string;\n citationType?: string;\n citationReason?: string;\n isFullscreen: boolean\n}\n\nconst getFirstGptCitation = (webGptMeta: any) =>\n (webGptMeta?.extraMetaData || webGptMeta)?.aiReasoningCitation?.gpt_citation?.[0] || null;\n\nconst DEFAULT_GPT_WEB_CITATION_CONFIG: GptWebCitationConfig = {\n endpoint: \"https://dev-proposals-ai.techo.camp/utility/ca-workflow-composer-agent/get_citation\",\n userEmail: \"sai.siddhartha@techolution.com\",\n userId: \"672e32f7a0e8fe2e8e50bcba\",\n userName: \"TNV Sai Siddhartha\",\n};\n\nconst CITATION_FULLSCREEN_DIALOG_HEIGHT = \"90vh\";\nconst CITATION_FULLSCREEN_GPT_BODY_HEIGHT = `calc(${CITATION_FULLSCREEN_DIALOG_HEIGHT} - 120px)`;\n\nconst resolveGptWebCitationConfig = (\n gptWebCitationConfig?: GptWebCitationConfig,\n): GptWebCitationConfig => ({\n endpoint: gptWebCitationConfig?.endpoint || DEFAULT_GPT_WEB_CITATION_CONFIG.endpoint,\n userEmail: gptWebCitationConfig?.userEmail || DEFAULT_GPT_WEB_CITATION_CONFIG.userEmail,\n userId: gptWebCitationConfig?.userId || DEFAULT_GPT_WEB_CITATION_CONFIG.userId,\n userName: gptWebCitationConfig?.userName || DEFAULT_GPT_WEB_CITATION_CONFIG.userName,\n headers: gptWebCitationConfig?.headers,\n});\n\nconst createCitationUuid = () => {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (char) => {\n const random = Math.floor(Math.random() * 16);\n const value = char === \"x\" ? random : (random % 4) + 8;\n return value.toString(16);\n });\n};\n\nconst getStoredPayloadCitationId = (webGptMeta: any) =>\n webGptMeta?.payloadCitationId ||\n webGptMeta?.extraMetaData?.payloadCitationId ||\n \"\";\n\nconst attachPayloadCitationId = (webGptMeta: any, payloadCitationId: string) => {\n if (!webGptMeta || typeof webGptMeta !== \"object\") return;\n\n webGptMeta.payloadCitationId = payloadCitationId;\n\n if (webGptMeta.extraMetaData && typeof webGptMeta.extraMetaData === \"object\") {\n webGptMeta.extraMetaData.payloadCitationId = payloadCitationId;\n }\n};\n\nconst getOrCreatePayloadCitationId = (webGptMeta: any, generatedCitationId?: string) => {\n const payloadCitationId =\n getStoredPayloadCitationId(webGptMeta) ||\n generatedCitationId ||\n createCitationUuid();\n\n attachPayloadCitationId(webGptMeta, payloadCitationId);\n return payloadCitationId;\n};\n\nconst buildGptWebCitationPayload = (\n webGptMeta: any,\n gptWebCitationConfig?: GptWebCitationConfig,\n generatedCitationId?: string,\n) => {\n const gptCitation = getFirstGptCitation(webGptMeta);\n const customMetaData = gptCitation?.customMetaData || {};\n const citationValue = customMetaData?.value || {};\n const webSearchAnswer = webGptMeta?.webSearchAnswer || {};\n const extraMetaData = webGptMeta?.extraMetaData || webGptMeta || {};\n\n return {\n userEmail:\n webGptMeta?.userEmail ||\n webSearchAnswer?.userEmail ||\n gptWebCitationConfig?.userEmail ||\n \"\",\n userId:\n webGptMeta?.userId ||\n webSearchAnswer?.userId ||\n gptWebCitationConfig?.userId ||\n \"\",\n userName:\n webGptMeta?.userName ||\n webSearchAnswer?.userName ||\n gptWebCitationConfig?.userName ||\n \"\",\n citationId:\n getOrCreatePayloadCitationId(webGptMeta, generatedCitationId),\n citationUrl: citationValue?.citationUrl || webSearchAnswer?.citationUrl || \"\",\n content: extraMetaData?.Reasoning || webSearchAnswer?.enhanced_content || \"\",\n citationType: citationValue?.citationType || \"web\",\n citatioNumber:\n customMetaData?.citation_number ??\n gptCitation?.citation_number ??\n Number(webGptMeta?.reasoningId || 0),\n };\n};\n\nconst GptWebCitationPanel = ({\n metaData,\n isFullscreen = false,\n}: {\n metaData: any;\n isFullscreen?: boolean;\n}) => {\n const { gptWebCitationConfig } = useCompareContext();\n const resolvedGptWebCitationConfig = useMemo(\n () => resolveGptWebCitationConfig(gptWebCitationConfig),\n [gptWebCitationConfig],\n );\n const webGptMeta = metaData?.webGpt;\n const generatedCitationIdRef = useRef<string | null>(null);\n if (!generatedCitationIdRef.current) {\n generatedCitationIdRef.current = createCitationUuid();\n }\n\n const payload = useMemo(\n () => buildGptWebCitationPayload(\n webGptMeta,\n resolvedGptWebCitationConfig,\n generatedCitationIdRef.current || undefined,\n ),\n [webGptMeta, resolvedGptWebCitationConfig],\n );\n const firstGptCitation = useMemo(() => getFirstGptCitation(webGptMeta), [webGptMeta]);\n const citationValue = firstGptCitation?.customMetaData?.value || {};\n const extraMetaData = webGptMeta?.extraMetaData || webGptMeta || {};\n const [webCitationData, setWebCitationData] = useState<IWebCitationApiResponse | undefined>();\n const [webCitationStatus, setWebCitationStatus] = useState<GptWebCitationStatus>(\"pending\");\n const [showWebCitation, setShowWebCitation] = useState(true);\n\n useEffect(() => {\n let isMounted = true;\n\n const fetchGptWebCitation = async () => {\n if (!resolvedGptWebCitationConfig.endpoint || !payload?.citationUrl || !payload?.content) {\n setWebCitationStatus(\"error\");\n return;\n }\n\n setWebCitationStatus(\"pending\");\n\n try {\n const response = await fetch(resolvedGptWebCitationConfig.endpoint, {\n method: \"POST\",\n headers: {\n \"actor-id\": payload.userEmail,\n \"Accept\": \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\",\n ...(resolvedGptWebCitationConfig.headers || {}),\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch GPT web citation (${response.status})`);\n }\n\n const rawData = await response.json();\n const data =\n rawData?.responseData ||\n rawData?.result ||\n rawData?.data ||\n rawData;\n if (!isMounted) return;\n\n setWebCitationData(data);\n setWebCitationStatus(\"success\");\n } catch (error) {\n if (!isMounted) return;\n console.error(\"Failed to load GPT web citation\", error);\n setWebCitationStatus(\"error\");\n }\n };\n\n fetchGptWebCitation();\n\n return () => {\n isMounted = false;\n };\n }, [payload, resolvedGptWebCitationConfig]);\n\n const gptCitation = useMemo(\n () => ({\n item: {\n confidence_score: Number(extraMetaData?.Confidence_score || 0),\n text: citationValue?.paraphrase || \"Web citation reasoning\",\n dataSource: citationValue?.text || extraMetaData?.Reasoning || \"\",\n paraphrase: citationValue?.paraphrase || \"\",\n },\n headerTitle: \"GPT Web Citation\",\n index: Number(payload?.citatioNumber || 1) - 1,\n iconsConfig: {\n ChevronDownIcon: ChevronDown,\n ChevronUpIcon: ChevronUp,\n MaximizeIcon: Maximize2,\n CloseIcon: X,\n },\n }),\n [citationValue, payload?.citatioNumber, extraMetaData],\n );\n\n const resolvedGptCitation = useMemo(\n () => ({\n ...gptCitation,\n ...(isFullscreen ? { bodyHeight: CITATION_FULLSCREEN_GPT_BODY_HEIGHT } : {}),\n }),\n [gptCitation, isFullscreen],\n );\n\n return (\n <GptWebCitation\n gptCitation={resolvedGptCitation}\n defaultCitationUrl={payload?.citationUrl || \"\"}\n citationType={CitationType.GPT_WEB}\n webCitationData={webCitationData}\n webCitationStatus={webCitationStatus}\n showWebCitation={showWebCitation}\n onToggleCitationView={() => setShowWebCitation((current) => !current)}\n iconsConfig={{\n MaximizeIcon: Maximize2,\n ExternalLinkIcon: ExternalLink,\n }}\n isFixedHeight\n />\n );\n};\n\nconst CitationRendererInner: React.FC<CitationRendererInnerProps> = ({\n href,\n metaData,\n citationTitle,\n citationType,\n citationReason,\n isFullscreen\n}) => {\n const { guidelinesData } = useCompareContext();\n const pdfCitationTypes = [\"contract\", \"clause\"];\n\n const getCitationUrl = (url: string) => {\n const prefixedCitationMatch = url.match(/^(?:pdf_citation|deviation_summary)\\$(\\d+)/);\n if (prefixedCitationMatch) {\n try {\n const queryStartIndex = url.indexOf(\"?\");\n const search = queryStartIndex >= 0 ? url.slice(queryStartIndex) : \"\";\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: new URL(search || \"./\", window.location.origin),\n };\n } catch {\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: null,\n };\n }\n }\n\n try {\n const parsedUrl = new URL(url, window.location.origin);\n const citationNumber =\n parsedUrl.searchParams.get(\"citationNumber\") ||\n parsedUrl.searchParams.get(\"citation_number\");\n return {citationNumber, parsedUrl};\n } catch {\n return {citationNumber: null, parsedUrl: null};\n }\n };\n\n const getCitationDetailsFromHref = (url: string): { citationNumber: string | null; phraseToHighlight: string | null; citationTypeFromHref: string | null } => {\n try {\n const { citationNumber, parsedUrl } = getCitationUrl(url);\n const phraseToHighlight = parsedUrl?.searchParams.get(\"phrase_to_highlight\") || null;\n const citationTypeFromHref = parsedUrl?.searchParams.get(\"citation_type\") || null;\n return {citationNumber, phraseToHighlight, citationTypeFromHref};\n } catch {\n return {citationNumber: null, phraseToHighlight: null, citationTypeFromHref: null};\n }\n };\n\n const {citationNumber, phraseToHighlight, citationTypeFromHref} = getCitationDetailsFromHref(href);\n const resolvedCitationType = citationType || citationTypeFromHref || undefined;\n const normalizedCitationType =\n resolvedCitationType === \"il_rulebook_citation\" ? \"rulebook_citation\" : resolvedCitationType;\n const citationGroup = citationNumber ? (metaData?.citations?.[citationNumber] || {}) : {};\n const documents = metaData?.docData?.documents || {};\n const inputIndexMap = metaData?.docData?.input_index_map || {};\n const hasRegularCitationData =\n Object.keys(metaData?.citations || {}).length > 0 ||\n Object.keys(metaData?.docData || {}).length > 0;\n\n const leftUuid = inputIndexMap?.[\"0\"];\n const rightUuid = inputIndexMap?.[\"1\"];\n\n const leftDocument = leftUuid ? documents[leftUuid] : null;\n const rightDocument = rightUuid ? documents[rightUuid] : null;\n const leftCitation = leftUuid ? citationGroup[leftUuid] : null;\n const rightCitation = rightUuid ? citationGroup[rightUuid] : null;\n\n const leftComponent = useMemo(() => {\n if (!leftCitation || !leftDocument) return null;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={leftDocument?.title}\n pdfUrl={leftDocument?.signed_url}\n highlightText={[leftCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: leftCitation?.custom_metadata?.pdf_start_page_number }}\n jumpToPageValue={1}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[leftCitation?.custom_metadata?.pdf_start_page_number, leftCitation?.custom_metadata?.pdf_end_page_number]}\n />\n );\n }, [\n leftDocument?.title,\n leftDocument?.signed_url,\n leftCitation?.highlighted_text,\n leftCitation?.custom_metadata?.pdf_start_page_number,\n leftCitation?.custom_metadata?.pdf_end_page_number\n ]);\n\n const rightComponent = useMemo(() => {\n if (!rightCitation || !rightDocument) return null;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={rightDocument?.title}\n pdfUrl={rightDocument?.signed_url}\n jumpToPageValue={1}\n highlightText={[rightCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: rightCitation?.custom_metadata?.pdf_start_page_number }}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[rightCitation?.custom_metadata?.pdf_start_page_number, rightCitation?.custom_metadata?.pdf_end_page_number]}\n />\n );\n }, [\n rightDocument?.title,\n rightDocument?.signed_url,\n rightCitation?.highlighted_text,\n rightCitation?.custom_metadata?.pdf_start_page_number,\n rightCitation?.custom_metadata?.pdf_end_page_number\n ]);\n\n const isDualCitationType = normalizedCitationType === \"dual_citation\";\n const isDualWebGptCitation = isDualCitationType && !!metaData?.webGpt;\n\n const splitPaneComponent = useMemo(() => {\n if (!leftComponent) return null;\n\n const rightPane =\n isDualWebGptCitation ? (\n <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />\n ) : normalizedCitationType === \"rulebook_citation\" ? (\n <>\n <Box sx={{\n padding: '0px 20px',\n backgroundColor: '#FFFFFF',\n borderRadius: '8px',\n ...SHARED_MARKDOWN_STYLES,\n overflow: 'auto'\n }}>\n <ReactMarkdown rehypePlugins={[rehypeRaw as any]}>\n {processGuidelinesMarkdown({\n guidelinesData, targetHighlights: [phraseToHighlight!], labelColor: \"#FEF08A\"})}\n </ReactMarkdown>\n </Box>\n </>\n ) : (\n rightComponent\n );\n\n if (!rightPane) return leftComponent;\n\n return (\n <ResizableSplitPane\n leftComponent={leftComponent}\n rightComponent={rightPane}\n isFullscreen={isFullscreen}\n />\n );\n}, [leftComponent, rightComponent, normalizedCitationType, isDualWebGptCitation, metaData, isFullscreen, guidelinesData, phraseToHighlight]);\n\n if (metaData?.webGpt && !hasRegularCitationData) {\n return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n }\n\n if (!citationNumber) return null;\n\n if (normalizedCitationType === \"rulebook_citation\") {\n if (leftCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n return (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#344054\", lineHeight: 1.5 }}>\n {citationReason || \"Rulebook citation selected.\"}\n </div>\n );\n }\n\n if (isDualCitationType) {\n if (leftCitation || rightCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n if (metaData?.webGpt) {\n return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n }\n\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n if (pdfCitationTypes.includes(citationTitle)) {\n if (leftCitation || rightCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n return <div>No Citation Found. Please try again later</div>;\n};\n\n\nconst CitationAnchor: React.FC<CitationAnchorProps> = ({\n href,\n children,\n citationType,\n citationReason,\n metaData,\n chevronUpComponent = null,\n chevronDownComponent = null,\n customStyle = {},\n defaultState = false,\n onFullscreenChange,\n}) => {\n const ChevronUpComponentDefault = (arrow: CSSProperties) => {\n return (\n <ChevronUp\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n };\n\n const ChevronDownComponentDefault = (arrow: CSSProperties) => {\n return (\n <ChevronDown\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n };\n const [isExpanded, setIsExpanded] = useState(defaultState);\n const [isFullscreen, setIsFullscreen] = useState(false);\n const citationDisplayTitle =\n typeof children === \"string\" && children?.split(\"\\n\")?.length > 1\n ? children.split(\"\\n\").join(\" \")\n : children;\n\n useEffect(() => {\n onFullscreenChange?.(isFullscreen);\n\n if (!isFullscreen) return;\n\n return () => {\n onFullscreenChange?.(false);\n };\n }, [isFullscreen, onFullscreenChange]);\n \n const citationTitle = typeof children === \"string\" ? children : children[0]\n\n const toggleCitation = () => setIsExpanded((prev) => !prev);\n const chevronUpComponentResolved =\n chevronUpComponent ??\n ChevronUpComponentDefault(customStyle?.arrow ?? {});\n const chevronDownComponentResolved =\n chevronDownComponent ??\n ChevronDownComponentDefault(customStyle?.arrow ?? {});\n\n const pdfCitationTypes = [\"contract\", \"clause\"];\n \nconst handleFullscreen = () => {\n setIsFullscreen((prev) => !prev);\n};\n // const jumpToPageRef = useRef<number>(item.pdf_highlight_details.pdf_page_number);\n // const highlightPagesIndexArray = {1: citationMetaData.pdf_highlight_details.pdf_page_number}\n // // const highlightTextArray = citationMetaData.pdf_highlight_details.pdf_highlight_text?.split('\\n')\n // const highlightTextArray = (() => {\n // const text = [citationMetaData.pdf_highlight_details.pdf_highlight_text ?? ''];\n // // console.log('textchecking old', text, processPdfHighlightText_Old(text[0]))\n // // console.log('textchecking new', text, processPdfHighlightText(\"payment in full for undisputed invoices shall be due within\\n**fourty-five (45) days** from invoice date unless stated otherwise in the respective SOW\"))\n // return text\n // })();\n\n const citationPanel = (\n <div\n style={{\n boxSizing: \"border-box\",\n border: isFullscreen ? \"none\" : \"1px solid #E4E7EC\",\n borderRadius: isFullscreen ? 0 : \"8px\",\n overflow: \"hidden\",\n marginTop: isFullscreen ? 0 : \"8px\",\n display: \"flex\",\n flexDirection: \"column\",\n width: \"100%\",\n height: isFullscreen ? \"100%\" : undefined,\n backgroundColor: \"#FAFAFA\",\n }}\n >\n <div style={{\n display: \"flex\",\n justifyContent: \"flex-end\",\n padding: \"6px 10px\",\n borderBottom: \"1px solid #E4E7EC\",\n backgroundColor: \"#FFFFFF\",\n flexShrink: 0,\n }}>\n <button onClick={handleFullscreen}\n style={{ background: \"none\", border: \"none\", cursor: \"pointer\", padding: \"4px\", borderRadius: \"6px\", color: \"#475467\", marginRight: \"9px\" }}>\n {isFullscreen ? <DefaultFullScreenCloseIcon /> : <DefaultFullScreenIcon />}\n </button>\n </div>\n <div style={{ flex: 1, minHeight: 0, height: \"100%\", overflow: \"hidden\" }}>\n <CitationRendererInner\n href={href}\n children={children}\n metaData={metaData}\n citationTitle={citationTitle}\n citationType={citationType}\n citationReason={citationReason}\n isFullscreen={isFullscreen}\n />\n </div>\n </div>\n );\n\n return (\n <span\n style={{\n display: \"inline\",\n ...(customStyle.relativeWrapper || {}),\n }}\n >\n <div\n style={{\n display: \"inline\",\n marginTop: 0,\n ...(customStyle.citationButtonWrapper || {}),\n }}\n >\n <button\n type=\"button\"\n onClick={toggleCitation}\n style={{\n display: metaData?.webGpt ? \"inline\" : \"inline-flex\",\n alignItems: metaData?.webGpt ? undefined : \"center\",\n gap: metaData?.webGpt ? undefined : \"3px\",\n fontFamily: '\"Inter\", sans-serif',\n backgroundColor: \"transparent\",\n padding: 0,\n margin: 0,\n fontSize: \"13px\",\n borderRadius: 9999,\n cursor: \"pointer\",\n fontWeight: (metaData?.webGpt) ? 600 : 700,\n color: (metaData?.webGpt) ? \"#6D28D9\" : \"rgb(214, 51, 132)\",\n border: \"none\",\n textDecoration: \"none\",\n wordBreak: \"break-word\",\n whiteSpace: \"normal\",\n ...(customStyle.citationButton || {}),\n }}\n >\n {metaData?.webGpt && (\n <Globe\n size={customStyle.arrow?.fontSize ?? \"1em\"}\n color={customStyle.arrow?.color ?? \"#6D28D9\"}\n style={{\n display: \"inline-block\",\n width: \"1em\",\n height: \"1em\",\n marginRight: \"3px\",\n verticalAlign: \"-0.125em\",\n flexShrink: 0,\n }}\n />\n )}\n <span>{citationDisplayTitle}</span>\n\n <span\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n marginLeft: metaData?.webGpt ? \"3px\" : undefined,\n verticalAlign: metaData?.webGpt ? \"-0.125em\" : undefined,\n }}\n >\n {isExpanded\n ? chevronUpComponentResolved\n : chevronDownComponentResolved}\n </span>\n {/* <span>\n <ChevronDownComponentDefault />\n </span> */}\n </button>\n </div>\n {isExpanded && (\n isFullscreen ? (\n <Dialog\n open={isFullscreen}\n onClose={() => setIsFullscreen(false)}\n maxWidth={false}\n BackdropProps={{\n sx: {\n backgroundColor: \"rgba(0, 0, 0, 0.6)\",\n backdropFilter: \"blur(4px)\",\n },\n }}\n PaperProps={{\n sx: {\n backgroundColor: \"#FAFAFA\",\n borderRadius: \"16px\",\n height: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n m: 0,\n maxHeight: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n maxWidth: \"95vw\",\n overflow: \"hidden\",\n width: \"95vw\",\n },\n }}\n >\n {citationPanel}\n </Dialog>\n ) : (\n citationPanel\n )\n )}\n </span>\n );\n};\n\nexport default CitationAnchor;\n"],"names":["getFirstGptCitation","webGptMeta","extraMetaData","aiReasoningCitation","gpt_citation","DEFAULT_GPT_WEB_CITATION_CONFIG","CITATION_FULLSCREEN_DIALOG_HEIGHT","CITATION_FULLSCREEN_GPT_BODY_HEIGHT","createCitationUuid","globalThis","crypto","randomUUID","replace","char","random","Math","floor","toString","getOrCreatePayloadCitationId","generatedCitationId","payloadCitationId","getStoredPayloadCitationId","attachPayloadCitationId","GptWebCitationPanel","metaData","isFullscreen","gptWebCitationConfig","useCompareContext","resolvedGptWebCitationConfig","useMemo","endpoint","userEmail","userId","userName","headers","resolveGptWebCitationConfig","webGpt","generatedCitationIdRef","useRef","current","payload","gptCitation","customMetaData","citationValue","value","webSearchAnswer","citationId","citationUrl","content","Reasoning","enhanced_content","citationType","citatioNumber","citation_number","Number","reasoningId","buildGptWebCitationPayload","firstGptCitation","webCitationData","setWebCitationData","useState","webCitationStatus","setWebCitationStatus","showWebCitation","setShowWebCitation","useEffect","isMounted","async","response","fetch","method","Accept","body","JSON","stringify","ok","Error","status","rawData","json","responseData","result","data","error","console","fetchGptWebCitation","item","confidence_score","Confidence_score","text","paraphrase","dataSource","headerTitle","index","iconsConfig","ChevronDownIcon","ChevronDown","ChevronUpIcon","ChevronUp","MaximizeIcon","Maximize2","CloseIcon","X","resolvedGptCitation","bodyHeight","jsx","GptWebCitation","defaultCitationUrl","CitationType","GPT_WEB","onToggleCitationView","ExternalLinkIcon","ExternalLink","isFixedHeight","CitationRendererInner","href","citationTitle","citationReason","guidelinesData","citationNumber","phraseToHighlight","citationTypeFromHref","url","parsedUrl","prefixedCitationMatch","match","queryStartIndex","indexOf","search","slice","URL","window","location","origin","searchParams","get","getCitationUrl","getCitationDetailsFromHref","resolvedCitationType","normalizedCitationType","citationGroup","citations","documents","docData","inputIndexMap","input_index_map","hasRegularCitationData","Object","keys","length","leftUuid","rightUuid","leftDocument","rightDocument","leftCitation","rightCitation","leftComponent","PdfViewer","defaultScale","showFullScreenAction","showHighlightsAction","pdfName","title","pdfUrl","signed_url","highlightText","highlighted_text","highlightPages","custom_metadata","pdf_start_page_number","jumpToPageValue","highlightCordinatePages","useCoordinates","useRange","rangeOfPages","pdf_end_page_number","rightComponent","isDualCitationType","isDualWebGptCitation","splitPaneComponent","rightPane","Fragment","children","Box","sx","padding","backgroundColor","borderRadius","SHARED_MARKDOWN_STYLES","overflow","ReactMarkdown","rehypePlugins","rehypeRaw","processGuidelinesMarkdown","targetHighlights","labelColor","ResizableSplitPane","style","height","display","flexDirection","fontSize","color","lineHeight","includes","CitationAnchor","chevronUpComponent","chevronDownComponent","customStyle","defaultState","onFullscreenChange","isExpanded","setIsExpanded","setIsFullscreen","citationDisplayTitle","split","join","chevronUpComponentResolved","arrow","size","chevronDownComponentResolved","ChevronDownComponentDefault","citationPanel","jsxs","boxSizing","border","marginTop","width","justifyContent","borderBottom","flexShrink","onClick","prev","background","cursor","marginRight","DefaultFullScreenCloseIcon","DefaultFullScreenIcon","flex","minHeight","relativeWrapper","citationButtonWrapper","type","alignItems","gap","fontFamily","margin","fontWeight","textDecoration","wordBreak","whiteSpace","citationButton","Globe","verticalAlign","marginLeft","Dialog","open","onClose","maxWidth","BackdropProps","backdropFilter","PaperProps","m","maxHeight"],"mappings":"0+BA2DA,MAAMA,EAAuBC,IACxBA,GAAYC,eAAiBD,IAAaE,qBAAqBC,eAAe,IAAM,KAEnFC,EACQ,sFADRA,EAES,iCAFTA,EAGM,2BAHNA,EAIQ,qBAGRC,EAAoC,OACpCC,EAAsC,QAAQD,aAY9CE,EAAqB,IACsB,mBAAlCC,WAAWC,QAAQC,WACnBF,WAAWC,OAAOC,aAGtB,uCAAuCC,QAAQ,QAAUC,IAC5D,MAAMC,EAASC,KAAKC,MAAsB,GAAhBD,KAAKD,UAExB,OADgB,MAATD,EAAeC,EAAUA,EAAS,EAAK,GACxCG,SAAS,MAmBxBC,EAA+B,CAACjB,EAAiBkB,KACnD,MAAMC,EAhByB,CAACnB,GAChCA,GAAYmB,mBACZnB,GAAYC,eAAekB,mBAC3B,GAcIC,CAA2BpB,IAC3BkB,GACAX,IAGG,MAjBqB,EAACP,EAAiBmB,KACzCnB,GAAoC,iBAAfA,IAE1BA,EAAWmB,kBAAoBA,EAE3BnB,EAAWC,eAAqD,iBAA7BD,EAAWC,gBAC9CD,EAAWC,cAAckB,kBAAoBA,KAUjDE,CAAwBrB,EAAYmB,GAC7BA,GA0CLG,EAAsB,EACxBC,WACAC,gBAAe,MAKT,MAAAC,qBAAEA,GAAyBC,IAC3BC,EAA+BC,EACjC,IA/F4B,CAChCH,IACwB,CACxBI,SAAUJ,GAAsBI,UAAYzB,EAC5C0B,UAAWL,GAAsBK,WAAa1B,EAC9C2B,OAAQN,GAAsBM,QAAU3B,EACxC4B,SAAUP,GAAsBO,UAAY5B,EAC5C6B,QAASR,GAAsBQ,UAwFrBC,CAA4BT,GAClC,CAACA,IAECzB,EAAauB,GAAUY,OACvBC,EAAyBC,EAAsB,MAChDD,EAAuBE,UACxBF,EAAuBE,QAAU/B,KAGrC,MAA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wO,QAAS,IAAM5C,GAAgB,GAC/B6C,UAAU,EACVC,cAAe,CACX3E,GAAI,CACAE,gBAAiB,qBACjB0E,eAAgB,cAGxBC,WAAY,CACR7E,GAAI,CACAE,gBAAiB,UACjBC,aAAc,OACdW,OAAQhM,EACRgQ,EAAG,EACHC,UAAWjQ,EACX4P,SAAU,OACVrE,SAAU,SACVsC,MAAO,SAId7C,SAAAwC,IAGLA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useMemo as
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useMemo as r}from"react";import{Box as n,Typography as o}from"@mui/material";import i from"react-markdown";import a from"rehype-raw";import c from"./CitationAnchor.js";import{mergeRulebookCitationsIntoMatchingLinks as l}from"./Guidelines/utils/helper.js";const s=e=>e?`./dual-citation?citationNumber=${encodeURIComponent(e)}`:"";function d({content:d="",title:u="",citations:p={},styles:m={},docData:h={},deviationData:x=null,open:f,onCitationFullscreenChange:g}){const y=r(()=>JSON.stringify(p||{}),[p]),D=r(()=>p,[y]),b=r(()=>JSON.stringify(h||{}),[h]),w=r(()=>h,[b]),C=r(()=>({citations:D,docData:w}),[D,w]),S=r(()=>{const e=x?.web_search_answer,t=e?.extraMetaData||{};return Object.keys(t).reduce((e,t)=>{const r=((e,t)=>{if(!e||!t)return null;const r=e?.web_search_answer,n=r?.extraMetaData?.[t];return r&&n?{reasoningId:t,evaluation:e,webSearchAnswer:r,extraMetaData:n}:null})(x,t);return r&&(e[t]=r),e},{})},[x]),F=r(()=>l(d),[d]),v=r(()=>({a:({href:t="",children:r,type:n,reason:o,...i})=>{const a=i?.["data-cognitive-reasoning"],l=(d=i?.["dual-citation"],!0===d||"true"===d);var d;const u=l&&a?S[String(a)]:null;return e(c,{href:l?s(String(a||"")):t,children:r,citationType:l?"dual_citation":n,citationReason:o,metaData:{...C,...u?{webGpt:u}:{}},customStyle:u?{arrow:{color:"#6D28D9"}}:{},onFullscreenChange:g})}}),[C,S,g]);return t(n,{sx:{borderRadius:"8px",border:"1px solid #E4E7EC",bgcolor:"#FCFCFD"},children:[e(n,{sx:{px:1.5,py:.75,borderBottom:"1px solid #EAECF0"},children:e(o,{sx:{fontSize:"15px",fontWeight:600,color:"#344054",lineHeight:1.25},children:u})}),e(n,{sx:{px:1.5,py:1.1,display:"flex",flexDirection:"column",gap:.95},children:e(n,{sx:{display:"flex",flexDirection:"column"},children:e(o,{component:"div",sx:{...m},children:e(i,{components:v,rehypePlugins:[a],children:F})})})})]})}export{d as default};
|
|
2
2
|
//# sourceMappingURL=CitationRenderer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CitationRenderer.js","sources":["../../../src/features/CognitiveCompare/CitationRenderer.tsx"],"sourcesContent":["import React, { useMemo } from 'react'\nimport { Box, Typography, IconButton } from \"@mui/material\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport CitationAnchor from './CitationAnchor';\nimport { mergeRulebookCitationsIntoMatchingLinks } from './Guidelines/utils/helper';\nimport { useOptionalCompareContext } from './CompareContext';\nimport {\n buildOnDemandCitationContexts,\n getOnDemandCitationLinkKey,\n} from './onDemandCitations';\n\ntype Props = {\n title?: string,\n content?: string,\n citations?: Record<string, any>,\n styles?: Record<string, any>\n docData?: Record<string, any> | null,\n deviationData?: Record<string, any> | null,\n open: boolean,\n onCitationFullscreenChange?: (isFullscreen: boolean) => void,\n tabKey?: \"deviation\" | \"association\",\n sectionTitle?: string,\n referenceSectionTitle?: string,\n sourceNodeId?: string,\n deviationKey?: string,\n baseContentId?: string,\n compareContentIds?: string[],\n}\n\nconst parseHref = (href: string) => {\n try {\n const baseUrl = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n return new URL(href, baseUrl);\n } catch {\n return null;\n }\n};\n\nconst isDualCitation = (value: unknown) => value === true || value === \"true\";\n\nconst buildDualCitationHref = (reasoningId: string) =>\n reasoningId ? `./dual-citation?citationNumber=${encodeURIComponent(reasoningId)}` : \"\";\n\nconst buildWebGptMetaForReasoning = (\n deviationData: Record<string, any> | null | undefined,\n reasoningId: string,\n) => {\n if (!deviationData || !reasoningId) return null;\n\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData?.[reasoningId];\n if (!webSearchAnswer || !extraMetaData) return null;\n\n return {\n reasoningId,\n evaluation: deviationData,\n webSearchAnswer,\n extraMetaData,\n };\n};\n\nfunction CitationRenderer({\n content = \"\",\n title = \"\",\n citations = {},\n styles = {},\n docData = {} as Record<string, any>,\n deviationData = null,\n open,\n onCitationFullscreenChange,\n tabKey,\n sectionTitle,\n referenceSectionTitle,\n sourceNodeId,\n deviationKey,\n baseContentId,\n compareContentIds,\n}: Props) {\n const compareContext = useOptionalCompareContext();\n const treeData = compareContext?.treeData;\n const onDemandCitationConfig = compareContext?.onDemandCitationConfig;\n // Stabilize citations and docData — they arrive as new object references\n // on every stream tick even when content hasn't changed, which would\n // remount CitationAnchor and reset its expanded state.\n const stableCitationsStr = useMemo(() => JSON.stringify(citations || {}), [citations]);\n const stableCitations = useMemo(\n () => citations,\n [stableCitationsStr]\n );\n\n const stableDocDataStr = useMemo(() => JSON.stringify(docData || {}), [docData]);\n const stableDocData = useMemo(\n () => docData,\n [stableDocDataStr]\n );\n\n const stableMetaData = useMemo(\n () => ({ citations: stableCitations, docData: stableDocData }),\n [stableCitations, stableDocData]\n );\n\n const onDemandContextByLinkKey = useMemo(() => {\n if (!onDemandCitationConfig?.enabled) return new Map<string, any>();\n\n const contexts = buildOnDemandCitationContexts({\n treeData,\n content,\n requestId: onDemandCitationConfig.requestId,\n tabKey,\n popupNodeId: sourceNodeId || (deviationData as any)?.nodeId,\n deviationKey,\n sectionTitle,\n referenceSectionTitle,\n docData: stableDocData,\n staticCitations: stableCitations,\n deviationData,\n cognitiveData: null,\n baseContentId,\n compareContentIds,\n });\n\n return contexts.reduce((acc, context) => {\n acc.set(getOnDemandCitationLinkKey(context.href), context);\n return acc;\n }, new Map<string, any>());\n }, [\n baseContentId,\n compareContentIds,\n content,\n deviationData,\n deviationKey,\n onDemandCitationConfig,\n referenceSectionTitle,\n sectionTitle,\n sourceNodeId,\n stableCitations,\n stableDocData,\n tabKey,\n treeData,\n ]);\n\n const webGptMetaByReasoningId = useMemo(() => {\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData || {};\n\n return Object.keys(extraMetaData).reduce((acc: Record<string, any>, reasoningId) => {\n const matchedExtraMetaData = buildWebGptMetaForReasoning(deviationData, reasoningId);\n if (matchedExtraMetaData) acc[reasoningId] = matchedExtraMetaData;\n return acc;\n }, {});\n }, [deviationData]);\n\n const processedContent = useMemo(\n () => mergeRulebookCitationsIntoMatchingLinks(content),\n [content]\n );\n\n const components = useMemo(() => {\n return {\n a: ({ href = \"\", children, type, reason, ...props }: any) => {\n const reasoningId = props?.[\"data-cognitive-reasoning\"];\n const shouldUseDualCitation = isDualCitation(props?.[\"dual-citation\"]);\n const matchedExtraMetaData =\n shouldUseDualCitation && reasoningId\n ? webGptMetaByReasoningId[String(reasoningId)]\n : null;\n return (\n <CitationAnchor\n href={shouldUseDualCitation ? buildDualCitationHref(String(reasoningId || \"\")) : href}\n children={children}\n citationType={shouldUseDualCitation ? \"dual_citation\" : type}\n citationReason={reason}\n onDemandCitationContext={\n shouldUseDualCitation\n ? undefined\n : onDemandContextByLinkKey.get(getOnDemandCitationLinkKey(href))\n }\n metaData={{\n ...stableMetaData,\n ...(matchedExtraMetaData ? { webGpt: matchedExtraMetaData } : {}),\n }}\n customStyle={\n matchedExtraMetaData ? \n {\n arrow: {\n color: \"#6D28D9\"\n }\n } : {}\n }\n onFullscreenChange={onCitationFullscreenChange}\n />\n );\n },\n };\n }, [onDemandContextByLinkKey, stableMetaData, webGptMetaByReasoningId, onCitationFullscreenChange]);\n\n return (\n <Box\n sx={{\n borderRadius: \"8px\",\n border: \"1px solid #E4E7EC\",\n bgcolor: \"#FCFCFD\",\n }}\n >\n <Box\n sx={{ px: 1.5, py: 0.75, borderBottom: \"1px solid #EAECF0\" }}\n >\n <Typography\n sx={{\n fontSize: \"15px\",\n fontWeight: 600,\n color: \"#344054\",\n lineHeight: 1.25,\n }}\n >\n {title}\n </Typography>\n </Box>\n <Box\n sx={{\n px: 1.5,\n py: 1.1,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 0.95,\n }}\n >\n <Box sx={{ display: \"flex\", flexDirection: \"column\" }}>\n <Typography\n component=\"div\"\n sx={{ ...styles }}\n >\n <ReactMarkdown components={components} rehypePlugins={[rehypeRaw as any]}>\n {processedContent}\n </ReactMarkdown>\n </Typography>\n </Box>\n </Box>\n </Box>\n )\n}\n\nexport default CitationRenderer\n"],"names":["buildDualCitationHref","reasoningId","encodeURIComponent","CitationRenderer","content","title","citations","styles","docData","deviationData","open","onCitationFullscreenChange","tabKey","sectionTitle","referenceSectionTitle","sourceNodeId","deviationKey","baseContentId","compareContentIds","compareContext","useOptionalCompareContext","treeData","onDemandCitationConfig","stableCitationsStr","useMemo","JSON","stringify","stableCitations","stableDocDataStr","stableDocData","stableMetaData","onDemandContextByLinkKey","enabled","Map","buildOnDemandCitationContexts","requestId","popupNodeId","nodeId","staticCitations","cognitiveData","reduce","acc","context","set","getOnDemandCitationLinkKey","href","webGptMetaByReasoningId","webSearchAnswer","web_search_answer","extraMetaData","Object","keys","matchedExtraMetaData","evaluation","buildWebGptMetaForReasoning","processedContent","mergeRulebookCitationsIntoMatchingLinks","components","a","children","type","reason","props","shouldUseDualCitation","value","String","jsx","CitationAnchor","citationType","citationReason","onDemandCitationContext","get","metaData","webGpt","customStyle","arrow","color","onFullscreenChange","jsxs","Box","sx","borderRadius","border","bgcolor","px","py","borderBottom","Typography","fontSize","fontWeight","lineHeight","display","flexDirection","gap","component","ReactMarkdown","rehypePlugins","rehypeRaw"],"mappings":"uhBAuCA,MAEMA,EAAyBC,GAC3BA,EAAc,kCAAk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ACVC,WAAY,IACZb,MAAO,UACPc,WAAY,MAGf/B,SAAAtD,MAGT6D,EAACa,EAAA,CACGC,GAAI,CACAI,GAAI,IACJC,GAAI,IACJM,QAAS,OACTC,cAAe,SACfC,IAAK,KAGTlC,SAAAO,EAACa,GAAIC,GAAI,CAAEW,QAAS,OAAQC,cAAe,UACvCjC,SAAAO,EAACqB,EAAA,CACGO,UAAU,MACVd,GAAI,IAAKzE,GAEToD,WAACoC,EAAc,CAAAtC,aAAwBuC,cAAe,CAACC,GAClDtC,SACLJ,YAMxB"}
|
|
1
|
+
{"version":3,"file":"CitationRenderer.js","sources":["../../../src/features/CognitiveCompare/CitationRenderer.tsx"],"sourcesContent":["import React, { useMemo } from 'react'\nimport { Box, Typography, IconButton } from \"@mui/material\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport CitationAnchor from './CitationAnchor';\nimport { mergeRulebookCitationsIntoMatchingLinks } from './Guidelines/utils/helper';\n\ntype Props = {\n title?: string,\n content?: string,\n citations?: Record<string, any>,\n styles?: Record<string, any>\n docData?: Record<string, any> | null,\n deviationData?: Record<string, any> | null,\n open: boolean,\n onCitationFullscreenChange?: (isFullscreen: boolean) => void,\n}\n\nconst parseHref = (href: string) => {\n try {\n const baseUrl = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n return new URL(href, baseUrl);\n } catch {\n return null;\n }\n};\n\nconst isDualCitation = (value: unknown) => value === true || value === \"true\";\n\nconst buildDualCitationHref = (reasoningId: string) =>\n reasoningId ? `./dual-citation?citationNumber=${encodeURIComponent(reasoningId)}` : \"\";\n\nconst buildWebGptMetaForReasoning = (\n deviationData: Record<string, any> | null | undefined,\n reasoningId: string,\n) => {\n if (!deviationData || !reasoningId) return null;\n\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData?.[reasoningId];\n if (!webSearchAnswer || !extraMetaData) return null;\n\n return {\n reasoningId,\n evaluation: deviationData,\n webSearchAnswer,\n extraMetaData,\n };\n};\n\nfunction CitationRenderer({\n content = \"\",\n title = \"\",\n citations = {},\n styles = {},\n docData = {} as Record<string, any>,\n deviationData = null,\n open,\n onCitationFullscreenChange,\n}: Props) {\n // Stabilize citations and docData — they arrive as new object references\n // on every stream tick even when content hasn't changed, which would\n // remount CitationAnchor and reset its expanded state.\n const stableCitationsStr = useMemo(() => JSON.stringify(citations || {}), [citations]);\n const stableCitations = useMemo(\n () => citations,\n [stableCitationsStr]\n );\n\n const stableDocDataStr = useMemo(() => JSON.stringify(docData || {}), [docData]);\n const stableDocData = useMemo(\n () => docData,\n [stableDocDataStr]\n );\n\n const stableMetaData = useMemo(\n () => ({ citations: stableCitations, docData: stableDocData }),\n [stableCitations, stableDocData]\n );\n\n const webGptMetaByReasoningId = useMemo(() => {\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData || {};\n\n return Object.keys(extraMetaData).reduce((acc: Record<string, any>, reasoningId) => {\n const matchedExtraMetaData = buildWebGptMetaForReasoning(deviationData, reasoningId);\n if (matchedExtraMetaData) acc[reasoningId] = matchedExtraMetaData;\n return acc;\n }, {});\n }, [deviationData]);\n\n const processedContent = useMemo(\n () => mergeRulebookCitationsIntoMatchingLinks(content),\n [content]\n );\n\n const components = useMemo(() => {\n return {\n a: ({ href = \"\", children, type, reason, ...props }: any) => {\n const reasoningId = props?.[\"data-cognitive-reasoning\"];\n const shouldUseDualCitation = isDualCitation(props?.[\"dual-citation\"]);\n const matchedExtraMetaData =\n shouldUseDualCitation && reasoningId\n ? webGptMetaByReasoningId[String(reasoningId)]\n : null;\n return (\n <CitationAnchor\n href={shouldUseDualCitation ? buildDualCitationHref(String(reasoningId || \"\")) : href}\n children={children}\n citationType={shouldUseDualCitation ? \"dual_citation\" : type}\n citationReason={reason}\n metaData={{\n ...stableMetaData,\n ...(matchedExtraMetaData ? { webGpt: matchedExtraMetaData } : {}),\n }}\n customStyle={\n matchedExtraMetaData ? \n {\n arrow: {\n color: \"#6D28D9\"\n }\n } : {}\n }\n onFullscreenChange={onCitationFullscreenChange}\n />\n );\n },\n };\n }, [stableMetaData, webGptMetaByReasoningId, onCitationFullscreenChange]);\n\n return (\n <Box\n sx={{\n borderRadius: \"8px\",\n border: \"1px solid #E4E7EC\",\n bgcolor: \"#FCFCFD\",\n }}\n >\n <Box\n sx={{ px: 1.5, py: 0.75, borderBottom: \"1px solid #EAECF0\" }}\n >\n <Typography\n sx={{\n fontSize: \"15px\",\n fontWeight: 600,\n color: \"#344054\",\n lineHeight: 1.25,\n }}\n >\n {title}\n </Typography>\n </Box>\n <Box\n sx={{\n px: 1.5,\n py: 1.1,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 0.95,\n }}\n >\n <Box sx={{ display: \"flex\", flexDirection: \"column\" }}>\n <Typography\n component=\"div\"\n sx={{ ...styles }}\n >\n <ReactMarkdown components={components} rehypePlugins={[rehypeRaw as any]}>\n {processedContent}\n </ReactMarkdown>\n </Typography>\n </Box>\n </Box>\n </Box>\n )\n}\n\nexport default CitationRenderer\n"],"names":["buildDualCitationHref","reasoningId","encodeURIComponent","CitationRenderer","content","title","citations","styles","docData","deviationData","open","onCitationFullscreenChange","stableCitationsStr","useMemo","JSON","stringify","stableCitations","stableDocDataStr","stableDocData","stableMetaData","webGptMetaByReasoningId","webSearchAnswer","web_search_answer","extraMetaData","Object","keys","reduce","acc","matchedExtraMetaData","evaluation","buildWebGptMetaForReasoning","processedContent","mergeRulebookCitationsIntoMatchingLinks","components","a","href","children","type","reason","props","shouldUseDualCitation","value","String","jsx","CitationAnchor","citationType","citationReason","metaData","webGpt","customStyle","arrow","color","onFullscreenChange","jsxs","Box","sx","borderRadius","border","bgcolor","px","py","borderBottom","Typography","fontSize","fontWeight","lineHeight","display","flexDirection","gap","component","ReactMarkdown","rehypePlugins","rehypeRaw"],"mappings":"wTA2BA,MAEMA,EAAyBC,GAC3BA,EAAc,kCAAkCC,mBAAmBD,KAAiB,GAoBxF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OAAA0C,EAACC,EAAA,CACGT,KAAMK,EAAwBxC,EAAsB0C,OAAOzC,GAAe,KAAOkC,EACjFC,WACAS,aAAcL,EAAwB,gBAAkBH,EACxDS,eAAgBR,EAChBS,SAAU,IACH5B,KACCS,EAAuB,CAAEoB,OAAQpB,GAAyB,CAAC,GAEnEqB,YACIrB,EACA,CACIsB,MAAO,CACHC,MAAO,YAEX,CAAC,EAETC,mBAAoBzC,OAKrC,CAACQ,EAAgBC,EAAyBT,IAGzC,OAAA0C,EAACC,EAAA,CACGC,GAAI,CACAC,aAAc,MACdC,OAAQ,oBACRC,QAAS,WAGbtB,SAAA,CAAAO,EAACW,EAAA,CACGC,GAAI,CAAEI,GAAI,IAAKC,GAAI,IAAMC,aAAc,qBAEvCzB,SAAAO,EAACmB,EAAA,CACGP,GAAI,CACAQ,SAAU,OACVC,WAAY,IACZb,MAAO,UACPc,WAAY,MAGf7B,SAAA/B,MAGTsC,EAACW,EAAA,CACGC,GAAI,CACAI,GAAI,IACJC,GAAI,IACJM,QAAS,OACTC,cAAe,SACfC,IAAK,KAGThC,SAAAO,EAACW,GAAIC,GAAI,CAAEW,QAAS,OAAQC,cAAe,UACvC/B,SAAAO,EAACmB,EAAA,CACGO,UAAU,MACVd,GAAI,IAAKhD,GAET6B,WAACkC,EAAc,CAAArC,aAAwBsC,cAAe,CAACC,GAClDpC,SACLL,YAMxB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useState as n,useRef as i,useMemo as o,useEffect as r,useCallback as s}from"react";import{Box as l,Snackbar as c,Alert as a,Tooltip as u,Typography as d,Tabs as p,Tab as f}from"@mui/material";import{ChevronDown as g}from"lucide-react";import{ButtonCognitiveIcon as h}from"../../assests/svg/ButtonCognitiveIcon.js";import m from"./OverlayComponent.js";import{safeStringify as S,extractDeviationScore as v,generateColorPalette as x,DEVIATION_BADGE_SEPARATOR as R,findKeyPathByNodeId as y,hasMeaningfulRedlineTags as b,scrollAndHighlightClause as C,scrollAndWait as w,waitForScrollIdle as I}from"./CognitiveComparehelpers.js";import{SHARED_MARKDOWN_STYLES as B,DEFAULT_FIELD_CONFIG as _,DEFAULT_COMPARISON_CONFIG as F}from"./CognitiveCompareConfig.js";export{SHARED_MARKDOWN_STYLES}from"./CognitiveCompareConfig.js";import{DEFAULT_DEVIAION_COLOR as T,EMPTY_SUMMARY_POPUP_STATE as E,DEFAULT_COMPONENT_HEADER_TEXT as A}from"./CognitiveCompareConstants.js";import D from"./CognitivePopup.js";import O from"./MoreFunctionsPopup.js";import k from"./LoaderComponent.js";import P from"./components/ThreeDotsLoader.js";import{useCognitiveTreeData as j}from"./hooks/useCompareData.js";import{useComparePopups as L}from"./hooks/useComparePopups.js";import{useSectionRefs as $}from"./hooks/useSectionRefs.js";import{useAccordionState as N}from"./hooks/useAccordionState.js";import{useDeviationNavigation as M}from"./hooks/useDeviationNavigation.js";import{useOnDemandCitationCache as H}from"./hooks/useOnDemandCitationCache.js";import z from"./components/CompareHeader.js";import G from"./components/SubSectionAccordion.js";import W from"./components/LHSSectionRow.js";import q from"./components/RHSSectionRow.js";import V from"./components/CognitiveSummaryPopup.js";import{CompareContextProvider as K}from"./CompareContext.js";import{useStyleHelpers as J}from"./hooks/useStyles.js";import{useResizeHandler as Y}from"./hooks/useResizeHandler.js";import{useLinesCalculator as X}from"./hooks/useLinesCalculator.js";import{useSideBySide as U}from"./hooks/useSideBySide.js";import Q from"./components/SvgConnectors.js";import Z from"./Guidelines/components/GuidelinePanel.js";import ee from"./Guidelines/components/WebGptPanel.js";import{GuidelineSkeleton as te}from"./components/GuidelineSkeletonLoader.js";import{getVisibleGuidelineTargets as ne}from"./Guidelines/utils/guidelineTargets.js";import{hasGptCitationObjects as ie}from"./Guidelines/utils/hasGptCitationObjects.js";const oe=({componentHeaderText:oe=A,treeData:re,comparisonConfig:se,leftColumnTitleText:le,rightColumnTitleText:ce,markdownStyles:ae,resetTrigger:ue,displayConfig:de={isHeaderVisible:!0,isToggleVisible:!0,maintainRelativeOrder:!1,isLoading:!0,showDeviationBadges:!1,enableDeviationSchemaBackwardCompatibility:!1,displayEmailNotifier:!0,isStreamingEnabled:!1},onMaintainRelativeOrderChange:pe,popupConfig:fe,deviationData:ge={},deviationNodeIdToView:he,resetDeviationNodeId:me,isProposingFix:Se=!1,proposingFixNodeId:ve,isRedlineFlow:xe,badgeStyleOverride:Re,guidelinesData:ye,isGuidelineMode:be,gptWebCitationConfig:Ce,onDemandCitationConfig:we})=>{const[Ie,Be]=n(de.maintainRelativeOrder),_e=de?.expandLevels??0,Fe=!!de?.expandAllSections,Te=!!Ie||!!de?.showDeviationBadges,[Ee,Ae]=n(!1),[De,Oe]=n(null),[ke]=n(re?.newEvaluationResult??de?.enableDeviationSchemaBackwardCompatibility??!0),[Pe,je]=n(new Set),[Le,$e]=n([]),[Ne,Me]=n(!1),[He,ze]=n(0),Ge=i(null),We=i(null),qe=i(null),Ve=i(null),Ke=i(null),Je=i(!1),Ye=i(null),Xe=i({}),Ue=i([]),Qe=i(()=>{}),Ze=i(null),et=i(()=>{}),tt=o(()=>JSON.stringify(ge||{}),[JSON.stringify(ge)]),nt=o(()=>ge||{},[tt]),it=o(()=>ie(nt),[nt]),ot=o(()=>re?.cognitive_decisioning||{},[re]),rt=o(()=>({...B,...ae}),[ae]),st=i(null),lt=i(null),ct=i(null),at=i(null),ut=i(null),dt=i(null),pt=i(null),ft=i(null),gt=i(null),ht=i(null),{cognitivePopup:mt,setCognitivePopup:St,moreFunctions:vt,setMoreFunctions:xt,position:Rt,setPosition:yt,activeBadgeId:bt,summaryPopup:Ct,setSummaryPopup:wt,closeSummaryPopup:It,setActiveBadgeId:Bt,popupRef:_t,handleOpenCognitiveCompare:Ft,openCognitivePopupFromState:Tt,closeCognitivePopup:Et,closeMoreFunctionsPopup:At}=L(st),Dt=o(()=>({fields:se?.fields??_,thresholds:{high:se?.thresholds?.high??F.thresholds.high,medium:se?.thresholds?.medium??F.thresholds.medium,exact:se?.thresholds?.exact??F.thresholds.exact}}),[se]),[Ot,kt]=n(null),Pt=re?.documents?.[re?.input_index_map?.[0]]?.title,jt=re?.documents?.[re?.input_index_map?.[1]]?.title,Lt=S(le||Pt||"Uploaded Contract"),$t=re?.documents?.[re?.input_index_map?.[0]]?.metadata?.file_name,Nt=S($t),Mt=re?.documents?.[re?.input_index_map?.[1]]?.metadata?.file_name,Ht=S(Mt),zt=S(ce||jt||"Reference Template"),{isGuidelineMode:Gt,activeProposed:Wt,existingRule:qt,proposedSections:Vt,existingSections:Kt,visibleFields:Jt,parentDeviationRecord:Yt,deviationNumberRegistry:Xt,deviationParentRegistry:Ut,parseError:Qt}=j(re,Ie,nt,Dt,ke,ye,be);r(()=>{Qt&&Oe(`Failed to load comparison: ${Qt}`)},[Qt]);const Zt=Vt.length>0||Kt.length>0,en=o(()=>{if(!xe)return"off";let e=0,t=0;const n=i=>{Array.isArray(i)&&i.forEach(i=>{const o=i?.content||"";b(o)&&(e+=1,t+=String(o).length),i?.subsections?.length&&n(i.subsections)})};return n(Vt),n(Kt),`${e}:${t}`},[xe,Vt,Kt]);r(()=>{if(Vt.length||Kt.length)if(Fe){const e={},t={},n=(n,i)=>{n.forEach((n,o)=>{const r=Ie?`${i}-${o}`:String(o);e[r]=!0;const s=(e,n)=>{e?.forEach((e,i)=>{const o=`${n}-${i}`;t[o]=!0,e.subsections?.length&&s(e.subsections,o)})};n.subsections?.length&&s(n.subsections,String(o))})};n(Vt,"left"),n(Kt,"right"),$n(e),Mn(t)}else if(_e>0){const e={},t={},n=(n,i,o)=>{n.forEach((n,r)=>{if(o>=1){const t=Ie?`${i}-${r}`:String(r);e[t]=!0}const s=(e,n,i)=>{i>o||e?.forEach((e,o)=>{const r=`${n}-${o}`;t[r]=!0,e.subsections?.length&&s(e.subsections,r,i+1)})};n.subsections?.length&&o>=2&&s(n.subsections,String(r),2)})};n(Vt,"left",_e),n(Kt,"right",_e),$n(e),Mn(t)}},[Fe,_e,Vt,Kt,Ie]);const{leftRefs:tn,rightRefs:nn,sectionLeftRefs:on,sectionRightRefs:rn,lhsBadgeRefs:sn,rhsBadgeRefs:ln,sectionRightRowRefs:cn,subSectionLeftRefs:an,subSectionRightRefs:un,sectionRowRefs:dn,getSectionRowRef:pn,getSubSectionRef:fn,getBadgeRef:gn}=$(Jt.map(({key:e})=>e),Math.max(Vt.length,Kt.length)),{isSideBySide:hn,isArrowVisible:mn,setIsSideBySide:Sn,setIsArrowVisible:vn,isResizing:xn,setIsResizing:Rn,isSideBySideLoading:yn,setIsSideBySideLoading:bn,activeSideBySideSection:Cn,setActiveSideBySideSection:wn,scrollLock:In,sideBySideCacheRef:Bn,isSideBySideRef:_n,activeSideBySideRightSectionRef:Fn,activeSideBySideSectionRef:Tn,sideBySideLineRef:En,highlightedClauseRefs:An,clearClauseHighlight:Dn,applyAlignmentPadding:On,resetSideBySide:kn,activateSideBySide:Pn}=U({isGuidelineMode:Gt,maintainRelativeOrder:Ie,proposedSections:Vt,existingSections:Kt,leftContainerRef:ft,rightContainerRef:ct,scrollContainerRef:st,sectionLeftRefs:on,sectionRightRefs:rn,subSectionLeftRefs:an,subSectionRightRefs:un,lhsBadgeRefs:sn,rhsBadgeRefs:ln,sectionRowRefs:dn,sectionRightRowRefs:cn,rhsTopSpacerRef:at,rhsBottomSpacerRef:ut,lhsTopSpacerRef:dt,lhsBottomSpacerRef:pt,calculateLinesRef:Qe,setConnectedSections:je,setConnectedLines:$e,cachedConnectedPositions:Ue,closeMoreFunctionsPopup:At,setErrorToast:Oe,moreFunctions:vt,closeSummaryPopup:It}),jn=i(Pn);r(()=>{jn.current=Pn},[Pn]);const{expandedSections:Ln,setExpandedSections:$n,expandedSubSections:Nn,setExpandedSubSections:Mn,handleSubSectionToggle:Hn,toggleSection:zn,forceExpandCrossWiredSections:Gn}=N({maintainRelativeOrder:!!Ie,proposedSections:Vt,existingSections:Kt,activeSideBySideSection:Cn,connectedSections:Pe,resetSideBySide:kn,setConnectedSections:je,setConnectedLines:$e,cachedConnectedPositions:Ue,svgContainerRef:Ge,isAnimatingRef:Je,animationTimerRef:Ye,calculateLinesRef:Qe,sectionLeftRefs:on,sectionRightRefs:rn,subSectionLeftRefs:an,subSectionRightRefs:un}),Wn=()=>{if(null==Cn)return;const e=on.current[Cn]?.current,t=rn.current[Cn]?.current,n=ct.current;if(!e||!t||!n)return;const i=e.getBoundingClientRect(),o=t.getBoundingClientRect(),r=n.getBoundingClientRect(),s=i.top-r.top,l=o.top-r.top-s;n.scrollBy({top:l,behavior:"smooth"})},qn=s(e=>{e?.stopPropagation(),Me(e=>{const t=!e;return t&&requestAnimationFrame(()=>{Wn()}),t})},[Wn]);r(()=>{xe&&"off"!==en&&"0:0"!==en&&(Bn.current=null,Ue.current=[],requestAnimationFrame(()=>{Qe.current?.()}))},[xe,en]);const Vn=o(()=>{const e=new Map,t=new Map;let n=1;if(Ie)Vt.forEach(t=>{!t.title&&!t.content||t.id&&e.set(t.id,n++)}),Kt.forEach(i=>{if(!i.id)return;if(!i.title&&!i.content)return;const o=Vt.filter(e=>e.refIndexes?.includes(i.selfIndex));if(o.length>0){const n=o.map(t=>e.get(t.id)).filter(Boolean);t.set(i.id,n.join(", "))}else t.set(i.id,String(n++))});else{const i=Math.max(Vt.length,Kt.length);for(let o=0;o<i;o++){const i=Vt[o],r=Kt[o];i?(e.set(i.id,n),r&&t.set(r.id,String(n)),n++):r&&t.set(r.id,String(n++))}}return{leftNums:e,rightNums:t}},[Vt,Kt,Ie]),Kn=qt.analysis,Jn=S(Kn?.rule_difference_comparison?.summary?.overall_summary),Yn=!!Jn.match(/<ai_reasoning>([\s\S]*?)<\/ai_reasoning>/i),Xn=re?.base_root_id??"-1",Un=ke?(ge&&ge?.[Xn]?.evaluation_result)??re?.nodes?.[Xn]?.evaluation_result??null:(ge&&ge?.[Xn]?.evaluation_result?.[0])??re?.nodes?.[Xn]?.evaluation_result?.[0]??null,Qn=v(Un);let Zn=x(Un?.evaluation_outputs?.metadata?.label_color??T);if(Re){const e=Re(Qn);e&&(Zn={...Zn,badgeBg:e.bg,badgeText:e.text,badgeBorder:e.border})}const ei=i(kn);r(()=>{ei.current=kn},[kn]);const ti=i(Et);r(()=>{ti.current=Et},[Et]);const ni=s((e,t,n,i,o,r)=>fo.current(e,t,n,i,o,r),[]),ii=s((e,t,n,i,o)=>ho.current(e,t,n,i,o),[]),oi=s(()=>mo.current(),[]),ri=s((e,t)=>So.current(e,t),[]),si=s(e=>vo.current(e),[]),li=s(e=>xo.current(e),[]),ci=s(()=>Ro.current(),[]),ai=s(()=>{Dn(),ei.current?.(),Me(!1),je(new Set),$e([]),Ue.current=[],Ti([]),Ai(null),wt(E),ti.current?.(),requestAnimationFrame(()=>{Qe.current?.()})},[]),ui=i(ai);r(()=>{ui.current=ai},[ai]),r(()=>{ue&&ui.current()},[ue]);const di=o(()=>({documents:re?.documents,input_index_map:re?.input_index_map}),[JSON.stringify(re?.documents),JSON.stringify(re?.input_index_map)]),[pi,fi]=n(""),gi=S(jt),hi=i(re);r(()=>{hi.current=re;const e=re?.input_index_map?.[0],t=re?.documents?.[e]?.title;fi(t)},[re]);const mi=i(ot);r(()=>{mi.current=ot},[ot]);const Si=s((e,t,n,i,o,r,s)=>{const l=S(t?.id)||S(n?.id)||"",c="string"==typeof i?i.split(R):[],a=c[0]||S(t?.nodeId)||S(n?.nodeId)||S(t?.id).split(R)[0]||S(n?.id).split(R)[0]||void 0,u=c.length>1&&void 0!==c[1]?c[1]:void 0,d=(l?mi.current?.[l]:null)||t?.cognitiveData||n?.cognitiveData||{section_id:l,decisioning:[],gap:[],relevance_score:0},p=dn.current[i]?.current??null,f=(()=>{const e=t?.evaluationResult||n?.evaluationResult||null,o=e=>{const t=(e=>{if(!e||"object"!=typeof e)return null;const t=e?.deviation_entries;if(t&&"object"==typeof t){const e=Object.keys(t).sort((e,t)=>Number(e)-Number(t))[0];if(e&&t[e])return t[e]}const n=Object.keys(e).filter(e=>/^\d+$/.test(e)).sort((e,t)=>Number(e)-Number(t));if(n.length&&e[n[0]])return e[n[0]];const i=e?.deviations;if(i&&"object"==typeof i){const e=Object.keys(i).sort((e,t)=>Number(e)-Number(t))[0];if(e&&i[e])return i[e]}return null})(e);return t?{...e,deviation_summary:e?.deviation_summary||t?.deviation_summary,deviation_title:e?.deviation_title||t?.deviation_title,deviation_impact:e?.deviation_impact||t?.deviation_impact,deviation_explanation:e?.deviation_explanation||t?.deviation_explanation,evaluation_outputs:e?.evaluation_outputs||t?.evaluation_outputs,cognitive_decisioning:e?.cognitive_decisioning||t?.cognitive_decisioning}:e};if(!("string"==typeof i&&i.includes(R)))return o(e);const r=i.split(R)[1];if(!r)return e;const s=t?.evaluationResult||n?.evaluationResult||{},l=s?.deviation_entries?.[r]||s?.deviations?.[r]||null;return l?{...s,...l,deviation_summary:l?.deviation_summary||s?.deviation_summary,deviation_title:l?.deviation_title||s?.deviation_title,deviation_impact:l?.deviation_impact||s?.deviation_impact,deviation_explanation:l?.deviation_explanation||s?.deviation_explanation,evaluation_outputs:l?.evaluation_outputs||s?.evaluation_outputs,cognitive_decisioning:l?.cognitive_decisioning||s?.cognitive_decisioning}:o(e)})(),g=(f?.cognitive_decisioning?.decisioning_factors?.length??0)>0||(f?.cognitive_decisioning?.gaps_in_decision?.length??0)>0,h=de?.isLoading??!1;let m=!0;if(Gt){const e=f?.deviation_highlights;if(e&&"object"==typeof e){m=Object.values(e).some(e=>Array.isArray(e)&&e.length>0)}else m=!1}return{isLoading:h&&!g,open:!0,sectionTitle:t?.title?t?.title:"No Counterpart",refSectionTitle:n?.title?n?.title:"No Counterpart",cognitiveData:d,anchorEl:e,sectionAnchorEl:p,badgeStyle:r||null,sectionIdx:i,docData:di,deviationData:f,isOrphan:!!o,hasGuidelineMatches:m,sourceNodeId:a,deviationKey:u,baseContentId:t?.contentId,compareContentIds:[...n?.contentId?[n.contentId]:[],...t?.refContentIds||[],...n?.refContentIds||[]].filter(Boolean)}},[di,de?.isLoading,Gt]),vi=s((e,t,n,i,o,r)=>{if(e.stopPropagation(),vt.open&&vt.sectionIdx===o)return void At();const s=e.currentTarget;let l="left";ct.current?.contains(s)&&(l="right");Dn(),_n.current&&kn(),je(new Set),$e([]),Ue.current=[],Et(),Ct.open?Ji():It(),requestAnimationFrame(()=>{const e=(()=>{if("string"==typeof o&&o.includes(R)){const e=o.split(R),t=`${e[0]}${R}${e[1]}`;return"right"===l?ln.current[t]?.current:sn.current[t]?.current}return"right"===l?ln.current[o]?.current:sn.current[o]?.current})()||s;xt(Si(e,t,i,o,n,r))})},[vt.open,vt.sectionIdx,At,It,Si]),xi=s(()=>{const e=vt.sectionIdx;vt.isOrphan,At(),It(),null!==e&&(Gn(e),Dn(),_n.current&&kn(),$e([]),Ue.current=[],Gt&&null!==e&&ze(Gi(e)),je(t=>t.has(e)?new Set:new Set([e])),setTimeout(()=>{Qe.current&&Qe.current()},50))},[vt.sectionIdx,vt.isOrphan,At,It,kn]),Ri=s(()=>{const e=Ke.current;if(!e)return;Ke.current=null;const t=Vt.findIndex(t=>t.id===e),n=Kt.findIndex(t=>t.id===e),i=-1===t?y(Vt,e):null,o=-1===n?y(Kt,e):null,r=-1!==t?t:i?Number(i.split("-")[0]):-1,s=-1!==n?n:o?Number(o.split("-")[0]):-1,l=(e,t,n,i)=>-1!==e?n.current[e]?.current??null:t?i.current[t]?.current??null:null,c=(e,t,n=30)=>{let i=0;const o=()=>{const r=e();r&&0!==r.getBoundingClientRect().height?(An.current.add(r),C(r,t)):i++<n&&requestAnimationFrame(o)};requestAnimationFrame(o)};if(Ie)-1!==r&&ft.current&&c(()=>l(t,i,on,an),ft.current),-1!==s&&ct.current&&c(()=>l(n,o,rn,un),ct.current);else{const e=st.current;if(!e)return;c(()=>-1!==r?l(t,i,on,an):l(n,o,rn,un),e)}},[Vt,Kt,Ie,on,rn,an,un,ft,ct,st]),yi=s(e=>{if(!e)return;Dn(),kn(),je(new Set),$e([]),Ue.current=[],It(),Et();const t=Vt.findIndex(t=>t.id===e),n=Kt.findIndex(t=>t.id===e),i=-1===t?y(Vt,e):null,o=-1===n?y(Kt,e):null;if(-1===t&&!i&&-1===n&&!o)return void console.warn(`scrollToAndHighlightClause: nodeId "${e}" not found`);const r=-1!==t?t:i?Number(i.split("-")[0]):-1,s=-1!==n?n:o?Number(o.split("-")[0]):-1;Ke.current=e,$n(e=>{const t={...e};let n=!1;if(-1!==r){const e=Ie?`left-${r}`:String(r);t[e]||(t[e]=!0,n=!0)}if(-1!==s){const e=Ie?`right-${s}`:String(s);t[e]||(t[e]=!0,n=!0)}return n?t:e}),Mn(e=>{const t={...e};let n=!1;const r=e=>{const i=e.split("-");let o=i[0];for(let e=1;e<i.length;e++)o+=`-${i[e]}`,t[o]||(t[o]=!0,n=!0)};return i&&r(i),o&&r(o),n?t:e}),setTimeout(()=>{requestAnimationFrame(()=>{Ke.current===e&&bi.current()})},50)},[Vt,Kt,Ie,$n,Mn,kn,It,Et]),bi=i(Ri);r(()=>{bi.current=Ri},[Ri]);const Ci=i(null);r(()=>{if(Ot){const e=Dt.fields.find(e=>e.analysisKey===Ot||e.key===Ot);if(e){const t=tn.current[e.key]||nn.current[e.key];t?.current&&setTimeout(()=>t.current.scrollIntoView({behavior:"smooth",block:"center"}),150)}}},[Ot,Dt.fields]);const wi=s(e=>{const t=Kn?.rule_difference_comparison?.fields;if(!t||!t[e])return{score:0,relation:"",highlightsA:[],highlightsB:[],hasContent:!1};const n=t[e],i=n?.relation||n?.highlights?.ruleA_spans?.length||n?.highlights?.ruleB_spans?.length||n?.mappings&&n.mappings.length>0;if(n.mappings){const e=n.mappings[0]||{};return{score:n.score,relation:e.relation||"",highlightsA:e.highlights?.ruleA_spans||[],highlightsB:e.highlights?.ruleB_spans||[],hasContent:!!i}}return{score:n.score,relation:n.relation||"",highlightsA:n.highlights?.ruleA_spans||[],highlightsB:n.highlights?.ruleB_spans||[],hasContent:!!i}},[Kn]),{getSectionCompareStyle:Ii,getSubSectionCompareStyle:Bi,getDeviationStyleByKey:_i}=J({proposedSections:Vt,existingSections:Kt,maintainRelativeOrder:Ie,cognitiveMap:ot,deviationData:nt,treeData:re,resolvedComparisonConfig:Dt,badgeStyleOverride:Re}),{lines:Fi,setLines:Ti,overallConnector:Ei,setOverallConnector:Ai,svgDimensions:Di,calculateLines:Oi,calculateLinesDebounced:ki,handleColumnScroll:Pi}=X({containerRef:We,leftContainerRef:ft,rightContainerRef:ct,svgContainerRef:Ge,pathRefs:Xe,leftHeaderRef:qe,rightHeaderRef:Ve,proposedSections:Vt,existingSections:Kt,visibleFields:Jt,leftRefs:tn,rightRefs:nn,sectionLeftRefs:on,sectionRightRefs:rn,subSectionLeftRefs:an,subSectionRightRefs:un,lhsBadgeRefs:sn,rhsBadgeRefs:ln,sectionRowRefs:dn,expandedSections:Ln,expandedSubSections:Nn,connectedSections:Pe,isSideBySide:hn,activeSideBySideSection:Cn,maintainRelativeOrder:Ie,isGuidelineMode:Gt,cognitiveMap:ot,getSectionCompareStyle:Ii,getSubSectionCompareStyle:Bi,getDeviationStyleByKey:_i,isArrowVisible:mn,isAnimatingRef:Je,isSideBySideRef:_n,sideBySideCacheRef:Bn,sideBySideLineRef:En,activeSideBySideSectionRef:Tn,activeSideBySideRightSectionRef:Fn,connectedLines:Le,setConnectedLines:$e,cachedConnectedPositions:Ue,calculateLinesRef:Qe,resizeTimerRef:Ze,scrollLock:In,scrollSyncLocked:Ne,handleResizeRef:et,activeProposed:Wt,existingRule:qt,analysisData:Kn,pendingScrollTargetRef:gt,pendingScrollCallbackRef:ht,resolvedComparisonConfig:Dt,getFieldData:wi});r(()=>{Ct.anchorEl&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Qe.current?.()})})},[Ct.anchorEl,Ne]);const ji=s(()=>{Dn(),Me(!1),$n({}),Mn({}),kn(),je(new Set),$e([]),Ue.current=[],It(),Et(),At(),requestAnimationFrame(()=>{Qe.current&&Qe.current()})},[$n,Mn,kn,It,Et,At]);r(()=>{hn||0!==Pe.size||Me(!1)},[hn,Pe]);const Li=o(()=>Object.values(Ln).some(Boolean)||Object.values(Nn).some(Boolean),[Ln,Nn]),$i=i(null),Ni=i(0),Mi=i(0),Hi=i(0),{handleResize:zi}=Y({timerRef:$i,ruleComponentRef:lt,scrollContainerRef:st,containerRef:We,maintainRelativeOrder:Ie,proposedSections:Vt,existingSections:Kt,isSideBySideRef:_n,activeSideBySideSectionRef:Tn,activeSideBySideRightSectionRef:Fn,sectionRowRefs:dn,sectionRightRowRefs:cn,sectionLeftRefs:on,sectionRightRefs:rn,subSectionLeftRefs:an,subSectionRightRefs:un,lhsBadgeRefs:sn,rhsBadgeRefs:ln,leftContainerRef:ft,rightContainerRef:ct,calculateLinesRef:Qe,handleResizeRef:et,setIsResizing:Rn,setIsArrowVisible:vn,sideBySideCacheRef:Bn,cachedConnectedPositions:Ue});r(()=>{et.current=zi},[zi,et]),r(()=>{const e=(e,t,n,i,o)=>{t.current=e.getBoundingClientRect().width;const r=new ResizeObserver(e=>{null!==n.current&&cancelAnimationFrame(n.current),n.current=requestAnimationFrame(()=>{n.current=null;const r=e[e.length-1];if(!r)return;const s=r.borderBoxSize?.[0]?.inlineSize??r.contentRect.width;Math.abs(s-t.current)<1?o():(t.current=s,i())})});return r.observe(e),r},t={current:null},n={current:null},i={current:null},o=[],r=[t,n,i];return lt.current&&o.push(e(lt.current,Ni,t,()=>et.current(),()=>{})),st.current&&o.push(e(st.current,Mi,n,()=>et.current(),()=>Qe.current())),We.current&&o.push(e(We.current,Hi,i,()=>et.current(),()=>Qe.current())),()=>{o.forEach(e=>e.disconnect()),r.forEach(e=>{null!==e.current&&(cancelAnimationFrame(e.current),e.current=null)})}},[]),r(()=>{_n.current=hn},[hn]),r(()=>{Tn.current=Cn},[Cn]);const Gi=s(e=>{let t="",n="0";if("number"==typeof e)t=Vt[e]?.nodeId||Vt[e]?.id||"";else{const i=String(e).split(R);t=i[0],n=i[1]||"0"}const i=nt?.[t]?.evaluation_result,o=Array.isArray(i)?i[parseInt(n,10)]:i?.[n];return!1===o?.evaluation_outputs?.guideline_flag?.rulebook_used&&ie(o)?1:0},[Vt,nt]),Wi=s(()=>{kn(),je(new Set),$e([]),Ue.current=[]},[kn]),qi=s((e,t)=>{t!==He&&(Wi(),ze(t))},[He,Wi]);r(()=>{it||0===He||(Wi(),ze(0))},[He,it,Wi]);const Vi=s(e=>{const t=ft.current,n=ct.current,i=ne(n);if(!n)return;const o="string"==typeof e&&e.includes(R);let r=e;if(o){const t=e.split(R);t.length>=2&&(r=`${t[0]}${R}${t[1]}`)}const s=sn.current[r]?.current||sn.current[e]?.current;if(i.length>0&&s&&t&&n){const e=i[0];dt.current&&(dt.current.style.height="0px"),at.current&&(at.current.style.height="0px"),pt.current&&(pt.current.style.height="0px"),ut.current&&(ut.current.style.height="0px"),requestAnimationFrame(()=>{const i=s.getBoundingClientRect(),o=e.getBoundingClientRect(),r=t.getBoundingClientRect(),l=n.getBoundingClientRect(),c=t.scrollTop+(i.top-r.top)+i.height/2,a=n.scrollTop+(o.top-l.top)+o.height/2,u=c-r.height/2,d=Math.max(0,u),p=t.scrollHeight-t.clientHeight,f=d>p?d-p:0,g=r.top+c-d;let h=l.top+a-g,m=0;h<0&&(m=Math.abs(h),h=0);const S=n.scrollHeight-n.clientHeight+m,v=h>S?h-S:0;pt.current&&(pt.current.style.height=`${f}px`),at.current&&(at.current.style.height=`${m}px`),ut.current&&(ut.current.style.height=`${v}px`),requestAnimationFrame(()=>{t.scrollTo({top:d,behavior:"smooth"}),n.scrollTo({top:h,behavior:"smooth"}),Qe.current&&setTimeout(()=>Qe.current(),50)})})}},[R]),Ki=s(()=>{const e=vt.sectionIdx,t=vt.isOrphan;if(It(),null==e)return;let n="left";vt.anchorEl&&ct.current?.contains(vt.anchorEl)&&(n="right"),Gn(e),Gt&&(ze(Gi(e)),je(new Set([e]))),Pn(e,t,{sourceSide:n,onReady:()=>{Gt&&setTimeout(()=>Vi(String(e)),150)}})},[Pn,vt.isOrphan,vt.sectionIdx,vt.anchorEl,It,Gn,Gt,Vi,Gi]),Ji=s(()=>{It(),kn(),je(new Set),$e([]),Ue.current=[]},[It,kn]),Yi=null!==vt.sectionIdx&&Pe.has(vt.sectionIdx),{showDeviationNavigation:Xi,showOpenNodeRef:Ui,adjustScrollForPopup:Qi}=M({proposedSections:Vt,existingSections:Kt,parentDeviationRecord:Yt,expandedSections:Ln,maintainRelativeOrder:!!Ie,scrollContainerRef:st,leftContainerRef:ft,rightContainerRef:ct,lhsBadgeRefs:sn,rhsBadgeRefs:ln}),Zi=s((e,t,n,i,o)=>{const r="string"==typeof i?S(i).trim():S(i?.deviation_summary).trim(),s=e.currentTarget;Et();let l="left";ct.current?.contains(s)&&(l="right");const c=()=>{if("string"==typeof t&&t.includes(R)){const e=t.split(R),n=`${e[0]}${R}${e[1]}`;return"right"===l?ln.current[n]?.current:sn.current[n]?.current}return"right"===l?ln.current[t]?.current:sn.current[t]?.current};if(n&&!Gt)return kn(),je(new Set),$e([]),Ue.current=[],void(r&&(Gn(t),requestAnimationFrame(()=>{const e=c()||s;if(e){e.getBoundingClientRect().top>.8*window.innerHeight&&e.scrollIntoView({behavior:"smooth",block:"center"})}wt({open:!0,anchorEl:e,summary:i,displayImpact:o})})));Gn(t),Gt&&(ze(Gi(t)),je(new Set([t]))),r?setTimeout(()=>{Pn(t,n,{toggleIfSame:!1,sourceSide:l,onReady:()=>{const e=c()||s;if(Gt)setTimeout(()=>Vi(t),150);else if(e){const t=e.getBoundingClientRect();if(t.top>.8*window.innerHeight||t.top<100){const e=t.top-window.innerHeight/2;Ie?(ft.current?.scrollBy({top:e,behavior:"smooth"}),ct.current?.scrollBy({top:e,behavior:"smooth"})):st.current?.scrollBy({top:e,behavior:"smooth"})}}wt({open:!0,anchorEl:e,summary:i,displayImpact:o})}})},350):setTimeout(()=>{Pn(t,n,{toggleIfSame:!1,sourceSide:l}),Gt&&setTimeout(()=>Vi(t),150)},350)},[Pn,Et,wt,kn,Gn,Gt,Ie,Vi,nt]),eo=o(()=>{if(!he)return null;const e=he?.id?.split(":")[0];for(const t in Yt){if((Yt[t]||[]).some(t=>t.id===e))return t}return null},[he,Yt]),to=i({id:null,triggerMs:null}),no=i(null);r(()=>{if(!he?.id)return;const e=Number(he.trigger),t=to.current;if(t?.id===he.id&&t?.triggerMs===e)return;if(!(he.id.includes(":")&&/:\d+$/.test(he.id))){to.current={id:he.id,triggerMs:e},yi(he.id);const t=Vt.findIndex(e=>e.id===he.id),n=Kt.findIndex(e=>e.id===he.id);return void(-1===t&&-1===n||setTimeout(()=>{const e=-1!==t?t:n,i=-1===t;Gt&&ze(Gi(e)),je(new Set([e])),jn.current(e,i,{sourceSide:i?"right":"left",onReady:()=>{Gt&&setTimeout(()=>Vi(String(e)),150)}})},400))}const[n,i]=he.id.split(":"),o=i??"0",r=`${he.id}:${e}`;no.current!==r&&(It(),Et(),kn(),je(new Set),$e([]),Ue.current=[],no.current=r);let s=!1,l=0;let c=null,a=null,u=!1;const d=(e,t)=>{const n=(e,i)=>{if(!e)return null;if(t.includes(e.id)||t.includes(e.nodeId)||t.includes(e.contentId))return i;if(!Array.isArray(e.subsections))return null;for(let t=0;t<e.subsections.length;t++){const o=n(e.subsections[t],`${i}-${t}`);if(o)return o}return null};for(let t=0;t<e.length;t++){const i=n(e[t],String(t));if(i)return i}return null},p=()=>{if(s)return;const t=()=>{to.current={id:he.id,triggerMs:e}};let i=null,r=null;for(const e in Yt){const t=Yt[e].find(e=>e.id===n||e.nodeId===n||e.contentId===n||e.evaluationResult?.nodeId===n);if(t){i=e,r=t;break}}if(!r||!i)return l++,void(l<30&&(c=setTimeout(p,100)));const f=Array.from(new Set([n,r.id,r.nodeId,r.contentId,r.evaluationResult?.nodeId].filter(Boolean))),g=Vt.findIndex(e=>e.id===i),h=Kt.findIndex(e=>e.id===i),m=-1===g&&-1!==h,S=d(Vt,f);let v=d(Kt,f);if(S&&!v&&!m){const e=S.split("-");let t=Number(e[0]);if(Ie){const e=Vt[t]?.refIndexes?.[0],n=Kt.findIndex(t=>t.selfIndex===e);-1!==n&&(t=n)}v=[t,...e.slice(1)].join("-")}if(!S&&!v)return l++,void(l<30&&(c=setTimeout(p,100)));const x=S?Number(S.split("-")[0]):g,y=v?Number(v.split("-")[0]):h,b=y>=0?y:v?Number(v.split("-")[0]):-1,C=Vt[x],B=Kt[b],_=C&&!C.title&&!C.content,F=B&&!B.title&&!B.content,T=m||(!S&&!!v||_&&!F);if(T){if(!(Ie?!!go.current[`right-${y}`]:!!go.current[String(y)])&&y>=0)return zn(y,"right"),void(c=setTimeout(p,200))}else{if(!(Ie?!!go.current[`left-${x}`]:!!go.current[String(x)])&&x>=0)return zn(x,"left"),void(c=setTimeout(p,200))}const E=S||"",A=v||"",D=f.map(e=>`${e}${R}${o}`),O=D[0],k=()=>{for(const e of D){const t=sn.current[e]?.current||null,n=ln.current[e]?.current||null;if(t||n)return{refId:e,left:t,right:n}}return{refId:O,left:null,right:null}},P=e=>`${e}${R}${E}${R}${A}`;if(!u){Gn(P(O)),u=!0,l=0;const e=()=>{const{left:e,right:t}=k();return T||!e&&!!t?t:e};return a?.(),void(c=setTimeout(()=>{s||(a=((e,t)=>{let n,i=0,o=null,r=null;const l=performance.now(),c=()=>{if(s)return;if(performance.now()-l>3e3)return void t();const a=e();if(!a||0===a.getBoundingClientRect().height)return void(n=requestAnimationFrame(c));const u=a.getBoundingClientRect(),d=u.top,p=u.height,f=null!==o&&Math.abs(d-o)<.5,g=null!==r&&Math.abs(p-r)<.5;if(f&&g){if(i++,i>=5)return void t()}else i=0;o=d,r=p,n=requestAnimationFrame(c)};return n=requestAnimationFrame(c),()=>cancelAnimationFrame(n)})(e,()=>{s||(a=null,p())}))},300))}const{refId:j,left:L,right:$}=k(),N=P(j);if(!L&&!$)return l++,void(l<30&&(c=setTimeout(p,100)));const M=T||!L&&!!$,H=M?$:L,z=Ie?M?ct.current:ft.current:st.current;if(!H||!z)return l++,void(l<30&&(c=setTimeout(p,100)));const G=H.getBoundingClientRect();if(0===G.height)return l++,void(l<30&&(c=setTimeout(p,100)));const W=z.getBoundingClientRect(),q=G.top-W.top+z.scrollTop-W.height/2+G.height/2,V=S?.includes("-")||v?.includes("-"),K=async()=>{if(s)return;t();const e=H instanceof Element?window.getComputedStyle(H).color:"";[L,$].forEach(t=>{t&&(t.style.transition="box-shadow 300ms ease-in-out",t.style.boxShadow=`0 0 10px ${e}`)}),setTimeout(()=>{[L,$].forEach(e=>{e&&(e.style.boxShadow="")})},2e3);const n=r.evaluationResult?.deviations?.[o]||r,i=r.evaluationResult?.evaluation_outputs||r.evaluation_outputs;if(!(!!L&&!!$)&&!Gt){const e=M?ln.current[V?j:y]?.current||$:sn.current[V?j:x]?.current||L;return Qi(e,()=>{wt({open:!0,anchorEl:e,displayImpact:he.displayImpact,summary:{...n,evaluation_outputs:i}})},{skipScroll:!0}),void me?.()}const l=(e,t)=>Promise.race([e,new Promise(e=>setTimeout(e,t))]);Ie&&await Promise.all([ft.current?l(I(ft.current),600):Promise.resolve(),ct.current?l(I(ct.current),600):Promise.resolve()]),Gt&&(ze(Gi(N)),je(new Set([N]))),jn.current(N,!1,{toggleIfSame:!1,sourceSide:m?"right":"left",onReady:()=>{t();const e=M?ln.current[j]?.current||$:sn.current[j]?.current||L;if(Gt)setTimeout(()=>Vi(N),150);else{const e=sn.current[j]?.current||L,t=ln.current[j]?.current||$;e&&(e.style.scrollMarginTop="150px",e.scrollIntoView({behavior:"smooth",block:"start"})),t&&(t.style.scrollMarginTop="150px",t.scrollIntoView({behavior:"smooth",block:"start"}))}wt({open:!0,anchorEl:e,displayImpact:he.displayImpact,summary:{...n}}),me?.()}})};Math.abs(z.scrollTop-q)<=2?K():w(z,q,K)};return c=setTimeout(p,100),()=>{s=!0,c&&clearTimeout(c),a?.()}},[he?.id,he?.trigger,he?.displayImpact,Yt,Vt,Kt,Ie,wt,yi,Gt,Gi,Vi]),r(()=>{if(!Ct.open)return;const e=Ct.anchorEl;if(!e)return;if(e.isConnected)return;const t=t=>{for(const[n,i]of Object.entries(t))if(i.current?.textContent===e.textContent)return n;return null},n=e.dataset?.deviationRefId||t(sn.current)||t(ln.current);if(!n)return;const i=ln.current[n]?.current||sn.current[n]?.current;i&&i.isConnected&&wt(e=>({...e,anchorEl:i}))},[Ct.open,Ct.anchorEl,Ne,Pe,Ln]);const{open:io,sectionIdx:oo,isOrphan:ro,badgeStyle:so,anchorEl:lo,sectionAnchorEl:co}=mt;r(()=>{if(!de.isStreamingEnabled)return;if(!io||null==oo)return;if(oo===Xn)return;const e="string"==typeof oo?oo.split(R)[0]:null,t=(e,n)=>{if(!e||!Array.isArray(e))return null;for(const i of e){if(i.id===n)return i;if(i.subsections?.length){const e=t(i.subsections,n);if(e)return e}}return null},n=e&&"string"==typeof e?t(Vt,e):null,i=e&&"string"==typeof e?t(Kt,e):null,o="number"==typeof oo?Vt[oo]||null:n||e&&(re?.nodes?.[e]||re?.[e])||null,r="number"==typeof oo?Kt[oo]||null:i,s=Si(lo,o,r,oo,ro,so);St(e=>{if(!e.open)return e;return S(e.cognitiveData)===S(s.cognitiveData)&&S(e.deviationData)===S(s.deviationData)&&e.sectionTitle===s.sectionTitle&&e.refSectionTitle===s.refSectionTitle?e:{...e,...s,open:!0,anchorEl:e.anchorEl,sectionAnchorEl:e.sectionAnchorEl}})},[io,oo,ro,so,lo,co,Vt,Kt,Si]);const ao=s(({section:t,keyPath:n,depth:i=0,columnKey:o="left",parentNodeId:r="",sectionOffset:s,rhsOrphanVisualIndexes:l})=>e(G,{section:t,keyPath:n,depth:i,columnKey:o,parentNodeId:r,sectionOffset:s,rhsOrphanVisualIndexes:l}),[]),uo=o(()=>Vt.map((t,n)=>{const i=!t?.title&&!t?.content,o=!t?.refIndexes||0===t.refIndexes.length;return i&&o&&Ie?null:e(W,{section:t,idx:n},t?.layoutKey??t?.id??`left-row-${n}`)}),[Vt,Ie]),po=o(()=>Kt.map((t,n)=>{const i=!t?.title&&!t?.content,o=!t?.refIndexes||0===t.refIndexes.length;return i&&o&&Ie?null:e(q,{section:t,idx:n},t?.layoutKey??t?.id??`right-row-${n}`)}),[Kt,Ie]),fo=i(vi);r(()=>{fo.current=vi},[vi]);const go=i(Ln);r(()=>{go.current=Ln},[Ln]);const ho=i(Zi);r(()=>{ho.current=Zi},[Zi]);const mo=i(Ji);r(()=>{mo.current=Ji},[Ji]);const So=i(zn);r(()=>{So.current=zn},[zn]);const vo=i(Hn);r(()=>{vo.current=Hn},[Hn]);const xo=i(ao);r(()=>{xo.current=ao},[ao]);const Ro=i(kn);r(()=>{Ro.current=kn},[kn]);const{cacheVersion:yo,getCacheKey:bo,getCacheEntry:Co,fetchCitationContext:wo,prefetchCitationContexts:Io,abortCitationContexts:Bo}=H(we),_o=o(()=>({isGuidelineMode:Gt,maintainRelativeOrder:!!Ie,showDeviationBadges:Te,isProposingFix:Se,proposingFixNodeId:ve,isRedlineFlow:xe,isSideBySide:hn,activeSideBySideSection:Cn,scrollSyncLocked:Ne,toggleScrollSyncLocked:qn,summaryPopupAnchorEl:Ct.anchorEl,connectedSections:Pe,proposedSections:Vt,existingSections:Kt,deviationNumberRegistry:Xt,deviationParentRegistry:Ut,treeData:re,displayConfig:de,resolvedMarkdownStyles:rt,unifiedNumbering:Vn,expandedSections:Ln,expandedSubSections:Nn,setExpandedSubSections:Mn,getSectionCompareStyle:Ii,getSubSectionCompareStyle:Bi,getBadgeRef:gn,getSectionRowRef:pn,getSubSectionRef:fn,sectionLeftRefs:on,sectionRightRefs:rn,sectionRowRefs:dn,sectionRightRowRefs:cn,subSectionLeftRefs:an,subSectionRightRefs:un,lhsBadgeRefs:sn,rhsBadgeRefs:ln,openMoreFunctionsPopup:ni,handleOpenSummaryPopup:ii,openSummaryPopup:ii,handleCloseSummaryPopup:oi,toggleSection:ri,handleSubSectionToggle:si,renderSubSectionAccordion:li,resetSideBySide:ci,setConnectedSections:je,setConnectedLines:$e,cachedConnectedPositions:Ue,showDeviationNavigation:Xi,showOpenNodeRef:Ui,deviationNodeIdToView:he?.id,deviationTargetParentId:eo,guidelinesData:ye,gptWebCitationConfig:Ce,onDemandCitationConfig:we,onDemandCitationCacheVersion:yo,getOnDemandCitationCacheKey:bo,getOnDemandCitationCacheEntry:Co,fetchOnDemandCitationContext:wo,prefetchOnDemandCitationContexts:Io,abortOnDemandCitationContexts:Bo}),[Gt,Ie,Te,Se,ve,xe,hn,Cn,Ne,qn,Ct.anchorEl,Pe,Vt,Kt,Xt,de,rt,Vn,Ln,Nn,Mn,Ii,Bi,gn,pn,fn,Xi,Ui,he,eo,ye,Ce,we,yo,bo,Co,wo,Io,Bo]),Fo=S(mt.sectionTitle||Nt||Lt),To=S(Gt?Ht||zt||mt.refSectionTitle:mt.refSectionTitle||Ht||zt);return e(K,{value:_o,children:t(l,{ref:lt,sx:{display:"flex",flexDirection:"column",height:"100%",bgcolor:"#F6F7F9B2",fontFamily:'"Plus Jakarta Sans", sans-serif',overflow:"visible",position:"relative"},children:[Ee&&e(l,{sx:{position:"absolute",inset:0,bgcolor:"rgba(255, 255, 255, 0.6)",backdropFilter:"blur(10px)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"8px"},children:e(k,{})}),Ct.open&&e(V,{open:Ct.open,anchorEl:Ct.anchorEl,containerEl:Ci.current,clipTopEl:qe.current,scrollContainerEl:st.current,onClose:Ji,summary:Ct.summary,displayImpact:Ct.displayImpact,isScrollLocked:Ne}),e(O,{open:vt.open,anchorEl:vt.anchorEl,maintainRelativeOrder:!!Ie,sectionTitle:vt.sectionTitle,referenceSectionTitle:vt.refSectionTitle,onClose:At,onOpenCognitiveCompare:Ft,onOpenSideBySide:Ki,onConnect:xi,isConnected:Yi,isOrphan:!Gt&&!!vt.isOrphan,isGuidelineMode:Gt,hasGuidelineMatches:vt.hasGuidelineMatches}),mt.open&&e(D,{open:mt.open,popupRef:_t,position:Rt,popupConfig:fe,onClose:()=>{yt(null),St(e=>({...e,open:!1})),Bt(null)},markdownStyles:ae,sectionTitle:Fo,referenceSectionTitle:To,cognitiveData:mt.cognitiveData,anchorEl:mt.anchorEl,sectionAnchorEl:mt.sectionAnchorEl,scrollContainerEl:st.current,badgeStyle:mt.badgeStyle,docData:mt.docData,deviationData:mt.deviationData,isLoading:mt.isLoading,sourceNodeId:mt.sourceNodeId,deviationKey:mt.deviationKey,baseContentId:mt.baseContentId,compareContentIds:mt.compareContentIds}),e(c,{open:!!De,autoHideDuration:8e3,onClose:()=>Oe(null),anchorOrigin:{vertical:"top",horizontal:"center"},children:e(a,{onClose:()=>Oe(null),severity:"error",sx:{width:"100%",whiteSpace:"pre-line"},children:De})}),e(z,{componentHeaderText:oe,displayConfig:de,maintainRelativeOrder:Ie,onCollapseAll:ji,showCollapseAll:Li,onToggleView:e=>{Ae(!0),setTimeout(()=>{Be(!e),pe?.(!e),Me(!1),kn(),It(),je(new Set),$e([]),Ue.current=[],requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{Ae(!1)},600)})})},50)}}),e(l,{ref:st,onScroll:Pi,sx:{flex:1,minHeight:0,pt:1.5,pb:1,px:3,display:"flex",justifyContent:"center",alignItems:Ie?"stretch":"flex-start",bgcolor:"#FFFFFF",overflowY:Ie?"visible":"auto",borderTop:Jn&&Yn?"none":"1.5px solid #EEF0F4"},children:e(l,{sx:{display:"flex",flexDirection:"column",width:"100%",maxWidth:"1200px",minHeight:0,...Ie?{flex:1}:{}},children:t(l,{ref:We,sx:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) 180px minmax(0, 1fr)",gap:"100px",maxWidth:"1200px",width:"100%",position:"relative",minHeight:0,...Ie?{flex:1,overflow:"visible"}:{}},children:[e(Q,{svgContainerRef:Ge,svgDimensions:Di,isResizing:xn,overallConnector:Ei,rootDeviationStyle:Zn,lines:Fi,isSideBySide:hn,activeSideBySideSection:Cn,isArrowVisible:mn,maintainRelativeOrder:Ie,proposedSections:Vt,existingSections:Kt,cognitivePopup:mt,activeBadgeId:bt,closeCognitivePopup:Et,setActiveBadgeId:Bt,openCognitivePopupFromState:Tt,buildSectionPopupState:Si,connectedLines:Le,isGuidelineMode:Gt,pathRefs:Xe}),t(l,{sx:{border:"1px solid #E7E7E9",borderRadius:"8px",bgcolor:"#FFFFFF",display:"flex",flexDirection:"column",position:"relative",zIndex:2,filter:"drop-shadow(0px 2px 4px #F2F2F2)",...Ie?{flex:1,overflow:"visible",minHeight:0}:{}},children:[e(l,{ref:qe,sx:{p:"8px",bgcolor:"#F7F8FA",borderBottom:"1px solid #E7E7E9",borderRadius:"8px 8px 0 0",display:"flex",alignItems:"center",minHeight:"40px",overflow:"hidden",minWidth:0},children:e(u,{title:Lt,placement:"top",children:e(d,{sx:{fontSize:"16px",fontWeight:500,color:"#19213D",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%",minWidth:0,textAlign:"center",display:"block"},children:Lt})})}),t(l,{ref:ft,onScroll:Pi,sx:{p:"12px",display:"flex",flexDirection:"column",...Ie?{flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0,mr:"-180px",pr:"192px","&::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"}:{}},children:[e("div",{ref:dt,style:{width:"100%",height:"0px",flexShrink:0}}),Zt&&uo,e("div",{ref:pt,style:{width:"100%",height:"0px",flexShrink:0}})]})]}),e(l,{ref:Ci,sx:{width:"180px",display:"flex",flexDirection:"column",alignItems:"center",pt:"15px",gap:0,zIndex:20,pointerEvents:"none"},children:e(l,{sx:{display:"flex",justifyContent:"center",alignItems:"center",mt:0},children:t(l,{onClick:e=>{e.stopPropagation(),mt.open&&bt===Xn?Et():(Bt(Xn),Tt(Si(e.currentTarget,{title:pi,content:"",evaluationResult:Un,cognitiveData:{section_id:"",decisioning:[],gap:[],relevance_score:0,isMissingRationale:!0}},{title:gi,content:""},Xn,!0,{...Zn,label:""})))},sx:{display:"inline-flex",alignItems:"center",gap:"5px",px:1.5,py:"5px",top:"-8px",borderRadius:"20px",bgcolor:Zn.badgeBg,color:Zn.badgeText,border:`1px solid ${Zn.badgeBorder}`,fontSize:"12px",fontWeight:600,whiteSpace:"nowrap",position:"relative",zIndex:1,pointerEvents:"auto",cursor:"pointer"},children:[Qn??e(P,{}),e(l,{component:"span",sx:{width:14,height:14,display:"flex",alignItems:"center","& svg":{width:"14px",height:"14px"}},children:e(h,{})}),e(g,{size:11,style:{transform:mt.open&&bt===Xn?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.25s ease"}})]})})}),t(l,{sx:{border:"1px solid #E3E6EA",borderRadius:"8px",bgcolor:"#FFFFFF",boxShadow:"0px 1px 4px #F7F4FE",position:"relative",zIndex:2,display:"flex",flexDirection:"column",minWidth:0,...Ie?{flex:1,overflow:"visible",minHeight:0}:{}},children:[yn&&e(m,{sections:11}),e(l,{ref:Ve,sx:{p:"8px",bgcolor:Gt?"#F1F3F5":"#F7F8FA",borderBottom:"1px solid #D7DCE2",borderRadius:"8px 8px 0 0",display:"flex",alignItems:"center",flexShrink:0},children:Gt?t(p,{value:He,onChange:qi,variant:"fullWidth",TabIndicatorProps:{sx:{display:"none"}},sx:{width:"100%",minHeight:"36px","& .MuiTab-root":{minHeight:"36px",px:1,py:0,borderRadius:"8px",fontSize:"14px",lineHeight:1,fontWeight:500,textTransform:"none",color:"#374151",minWidth:0,transition:"background-color 160ms ease, box-shadow 160ms ease"},"& .Mui-selected":{color:"#374151",bgcolor:"#FFFFFF"}},children:[e(f,{label:e(u,{title:zt,placement:"top",children:e(l,{component:"span",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",width:"100%"},children:"Redline Guidelines"})})}),it&&e(f,{label:e(u,{title:"Web & GPT Sources",placement:"top",children:e(l,{component:"span",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",width:"100%"},children:"Web & GPT Sources"})})})]}):e(u,{title:zt,placement:"top",children:e(d,{sx:{fontSize:"16px",fontWeight:500,color:"#5928ED",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%",minWidth:0,textAlign:"center",display:"block"},children:zt})})}),t(l,{ref:ct,onScroll:Pi,sx:{p:Gt?"0px":"12px",display:"flex",flexDirection:"column",...Ie?{flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0,ml:"-150px",pl:"165px","&::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"}:{}},children:[e("div",{ref:at,style:{width:"100%",height:"0px",flexShrink:0}}),Gt?ye?0!==He&&it?e(ee,{deviationData:ge,connectedSections:Pe,proposedSections:Vt}):e(Z,{guidelinesData:ye,deviationData:ge,connectedSections:Pe,proposedSections:Vt}):e(te,{}):Zt&&po,e("div",{ref:ut,style:{width:"100%",height:"0px",flexShrink:0}})]})]})]})})})]})})};export{oe as default};
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useState as n,useRef as i,useMemo as o,useEffect as r,useCallback as s}from"react";import{Box as l,Snackbar as c,Alert as a,Tooltip as u,Typography as d,Tabs as p,Tab as g}from"@mui/material";import{ChevronDown as f}from"lucide-react";import{ButtonCognitiveIcon as h}from"../../assests/svg/ButtonCognitiveIcon.js";import m from"./OverlayComponent.js";import{safeStringify as S,extractDeviationScore as v,generateColorPalette as x,findKeyPathByNodeId as R,DEVIATION_BADGE_SEPARATOR as y,hasMeaningfulRedlineTags as b,scrollAndHighlightClause as C,scrollAndWait as w,waitForScrollIdle as B}from"./CognitiveComparehelpers.js";import{SHARED_MARKDOWN_STYLES as _,DEFAULT_FIELD_CONFIG as I,DEFAULT_COMPARISON_CONFIG as F}from"./CognitiveCompareConfig.js";export{SHARED_MARKDOWN_STYLES}from"./CognitiveCompareConfig.js";import{DEFAULT_DEVIAION_COLOR as T,EMPTY_SUMMARY_POPUP_STATE as E,DEFAULT_COMPONENT_HEADER_TEXT as A}from"./CognitiveCompareConstants.js";import D from"./CognitivePopup.js";import k from"./MoreFunctionsPopup.js";import P from"./LoaderComponent.js";import O from"./components/ThreeDotsLoader.js";import{useCognitiveTreeData as $}from"./hooks/useCompareData.js";import{useComparePopups as j}from"./hooks/useComparePopups.js";import{useSectionRefs as L}from"./hooks/useSectionRefs.js";import{useAccordionState as N}from"./hooks/useAccordionState.js";import{useDeviationNavigation as M}from"./hooks/useDeviationNavigation.js";import H from"./components/CompareHeader.js";import z from"./components/SubSectionAccordion.js";import W from"./components/LHSSectionRow.js";import q from"./components/RHSSectionRow.js";import G from"./components/CognitiveSummaryPopup.js";import{CompareContextProvider as V}from"./CompareContext.js";import{useStyleHelpers as K}from"./hooks/useStyles.js";import{useResizeHandler as J}from"./hooks/useResizeHandler.js";import{useLinesCalculator as Y}from"./hooks/useLinesCalculator.js";import{useSideBySide as X}from"./hooks/useSideBySide.js";import U from"./components/SvgConnectors.js";import Q from"./Guidelines/components/GuidelinePanel.js";import Z from"./Guidelines/components/WebGptPanel.js";const ee=({componentHeaderText:ee=A,treeData:te,comparisonConfig:ne,leftColumnTitleText:ie,rightColumnTitleText:oe,markdownStyles:re,resetTrigger:se,displayConfig:le={isHeaderVisible:!0,isToggleVisible:!0,maintainRelativeOrder:!1,isLoading:!0,showDeviationBadges:!1,enableDeviationSchemaBackwardCompatibility:!1,displayEmailNotifier:!0,isStreamingEnabled:!1},deviationAnalysisStatus:ce,onMaintainRelativeOrderChange:ae,popupConfig:ue,deviationData:de={},deviationNodeIdToView:pe,resetDeviationNodeId:ge,isProposingFix:fe=!1,proposingFixNodeId:he,isRedlineFlow:me,badgeStyleOverride:Se,guidelinesData:ve,gptWebCitationConfig:xe})=>{const[Re,ye]=n(le.maintainRelativeOrder),be=le?.expandLevels??0,Ce=!!le?.expandAllSections,we=!!Re||!!le?.showDeviationBadges,[Be,_e]=n(!1),[Ie,Fe]=n(null),[Te]=n(te?.newEvaluationResult??le?.enableDeviationSchemaBackwardCompatibility??!0),[Ee,Ae]=n(new Set),[De,ke]=n([]),[Pe,Oe]=n(!1),[$e,je]=n(0),Le=ce??(le?.isLoading?"deviations_streaming":"complete"),Ne="mapping_ready"===Le||"deviations_streaming"===Le,Me=i(null),He=i(null),ze=i(null),We=i(null),qe=i(null),Ge=i(!1),Ve=i(null),Ke=i({}),Je=i([]),Ye=i(()=>{}),Xe=i(null),Ue=i(()=>{}),Qe=o(()=>JSON.stringify(de||{}),[JSON.stringify(de)]),Ze=o(()=>de||{},[Qe]),et=o(()=>te?.cognitive_decisioning||{},[te]),tt=o(()=>({..._,...re}),[re]),nt=i(null),it=i(null),ot=i(null),rt=i(null),st=i(null),lt=i(null),ct=i(null),at=i(null),ut=i(null),dt=i(null),{cognitivePopup:pt,setCognitivePopup:gt,moreFunctions:ft,setMoreFunctions:ht,position:mt,setPosition:St,activeBadgeId:vt,summaryPopup:xt,setSummaryPopup:Rt,closeSummaryPopup:yt,setActiveBadgeId:bt,popupRef:Ct,handleOpenCognitiveCompare:wt,openCognitivePopupFromState:Bt,closeCognitivePopup:_t,closeMoreFunctionsPopup:It}=j(nt),Ft=o(()=>({fields:ne?.fields??I,thresholds:{high:ne?.thresholds?.high??F.thresholds.high,medium:ne?.thresholds?.medium??F.thresholds.medium,exact:ne?.thresholds?.exact??F.thresholds.exact}}),[ne]),[Tt,Et]=n(null),At=te?.documents?.[te?.input_index_map?.[0]]?.title,Dt=te?.documents?.[te?.input_index_map?.[1]]?.title,kt=S(ie||At||"Uploaded Contract"),Pt=te?.documents?.[te?.input_index_map?.[0]]?.metadata?.file_name,Ot=S(Pt),$t=te?.documents?.[te?.input_index_map?.[1]]?.metadata?.file_name,jt=S($t),Lt=S(oe||Dt||"Reference Template"),{isGuidelineMode:Nt,activeProposed:Mt,existingRule:Ht,proposedSections:zt,existingSections:Wt,visibleFields:qt,parentDeviationRecord:Gt,deviationNumberRegistry:Vt,deviationParentRegistry:Kt,parseError:Jt}=$(te,Re,Ze,Ft,Te,ve);r(()=>{Jt&&Fe(`Failed to load comparison: ${Jt}`)},[Jt]);const Yt=zt.length>0||Wt.length>0,Xt=o(()=>{if(!me)return"off";let e=0,t=0;const n=i=>{Array.isArray(i)&&i.forEach(i=>{const o=i?.content||"";b(o)&&(e+=1,t+=String(o).length),i?.subsections?.length&&n(i.subsections)})};return n(zt),n(Wt),`${e}:${t}`},[me,zt,Wt]);r(()=>{if(zt.length||Wt.length)if(Ce){const e={},t={},n=(n,i)=>{n.forEach((n,o)=>{const r=Re?`${i}-${o}`:String(o);e[r]=!0;const s=(e,n)=>{e?.forEach((e,i)=>{const o=`${n}-${i}`;t[o]=!0,e.subsections?.length&&s(e.subsections,o)})};n.subsections?.length&&s(n.subsections,String(o))})};n(zt,"left"),n(Wt,"right"),Pn(e),$n(t)}else if(be>0){const e={},t={},n=(n,i,o)=>{n.forEach((n,r)=>{if(o>=1){const t=Re?`${i}-${r}`:String(r);e[t]=!0}const s=(e,n,i)=>{i>o||e?.forEach((e,o)=>{const r=`${n}-${o}`;t[r]=!0,e.subsections?.length&&s(e.subsections,r,i+1)})};n.subsections?.length&&o>=2&&s(n.subsections,String(r),2)})};n(zt,"left",be),n(Wt,"right",be),Pn(e),$n(t)}},[Ce,be,zt,Wt,Re]);const{leftRefs:Ut,rightRefs:Qt,sectionLeftRefs:Zt,sectionRightRefs:en,lhsBadgeRefs:tn,rhsBadgeRefs:nn,sectionRightRowRefs:on,subSectionLeftRefs:rn,subSectionRightRefs:sn,sectionRowRefs:ln,getSectionRowRef:cn,getSubSectionRef:an,getBadgeRef:un}=L(qt.map(({key:e})=>e),Math.max(zt.length,Wt.length)),{isSideBySide:dn,isArrowVisible:pn,setIsSideBySide:gn,setIsArrowVisible:fn,isResizing:hn,setIsResizing:mn,isSideBySideLoading:Sn,setIsSideBySideLoading:vn,activeSideBySideSection:xn,setActiveSideBySideSection:Rn,scrollLock:yn,sideBySideCacheRef:bn,isSideBySideRef:Cn,activeSideBySideRightSectionRef:wn,activeSideBySideSectionRef:Bn,sideBySideLineRef:_n,highlightedClauseRefs:In,clearClauseHighlight:Fn,applyAlignmentPadding:Tn,resetSideBySide:En,activateSideBySide:An}=X({isGuidelineMode:Nt,maintainRelativeOrder:Re,proposedSections:zt,existingSections:Wt,leftContainerRef:at,rightContainerRef:ot,scrollContainerRef:nt,sectionLeftRefs:Zt,sectionRightRefs:en,subSectionLeftRefs:rn,subSectionRightRefs:sn,lhsBadgeRefs:tn,rhsBadgeRefs:nn,sectionRowRefs:ln,sectionRightRowRefs:on,rhsTopSpacerRef:rt,rhsBottomSpacerRef:st,lhsTopSpacerRef:lt,lhsBottomSpacerRef:ct,calculateLinesRef:Ye,setConnectedSections:Ae,setConnectedLines:ke,cachedConnectedPositions:Je,closeMoreFunctionsPopup:It,setErrorToast:Fe,moreFunctions:ft,closeSummaryPopup:yt}),Dn=i(An);r(()=>{Dn.current=An},[An]);const{expandedSections:kn,setExpandedSections:Pn,expandedSubSections:On,setExpandedSubSections:$n,handleSubSectionToggle:jn,toggleSection:Ln,forceExpandCrossWiredSections:Nn}=N({maintainRelativeOrder:!!Re,proposedSections:zt,existingSections:Wt,activeSideBySideSection:xn,connectedSections:Ee,resetSideBySide:En,setConnectedSections:Ae,setConnectedLines:ke,cachedConnectedPositions:Je,svgContainerRef:Me,isAnimatingRef:Ge,animationTimerRef:Ve,calculateLinesRef:Ye,sectionLeftRefs:Zt,sectionRightRefs:en,subSectionLeftRefs:rn,subSectionRightRefs:sn}),Mn=()=>{if(null==xn)return;const e=Zt.current[xn]?.current,t=en.current[xn]?.current,n=ot.current;if(!e||!t||!n)return;const i=e.getBoundingClientRect(),o=t.getBoundingClientRect(),r=n.getBoundingClientRect(),s=i.top-r.top,l=o.top-r.top-s;n.scrollBy({top:l,behavior:"smooth"})},Hn=s(e=>{e?.stopPropagation(),Oe(e=>{const t=!e;return t&&requestAnimationFrame(()=>{Mn()}),t})},[Mn]);r(()=>{me&&"off"!==Xt&&"0:0"!==Xt&&(bn.current=null,Je.current=[],requestAnimationFrame(()=>{Ye.current?.()}))},[me,Xt]);const zn=o(()=>{const e=new Map,t=new Map;let n=1;if(Re)zt.forEach(t=>{!t.title&&!t.content||t.id&&e.set(t.id,n++)}),Wt.forEach(i=>{if(!i.id)return;if(!i.title&&!i.content)return;const o=zt.filter(e=>e.refIndexes?.includes(i.selfIndex));if(o.length>0){const n=o.map(t=>e.get(t.id)).filter(Boolean);t.set(i.id,n.join(", "))}else t.set(i.id,String(n++))});else{const i=Math.max(zt.length,Wt.length);for(let o=0;o<i;o++){const i=zt[o],r=Wt[o];i?(e.set(i.id,n),r&&t.set(r.id,String(n)),n++):r&&t.set(r.id,String(n++))}}return{leftNums:e,rightNums:t}},[zt,Wt,Re]),Wn=Ht.analysis,qn=S(Wn?.rule_difference_comparison?.summary?.overall_summary),Gn=!!qn.match(/<ai_reasoning>([\s\S]*?)<\/ai_reasoning>/i),Vn=te?.base_root_id??"-1",Kn=Te?(de&&de?.[Vn]?.evaluation_result)??te?.nodes?.[Vn]?.evaluation_result??null:(de&&de?.[Vn]?.evaluation_result?.[0])??te?.nodes?.[Vn]?.evaluation_result?.[0]??null,Jn=v(Kn),Yn=Ne&&null==Kn,Xn=Yn?null:Jn??("complete"===Le&&null==Kn?"Same":null);let Un=x(Kn?.evaluation_outputs?.metadata?.label_color??T);if(Se){const e=Se(Jn);e&&(Un={...Un,badgeBg:e.bg,badgeText:e.text,badgeBorder:e.border})}const Qn=i(En);r(()=>{Qn.current=En},[En]);const Zn=i(_t);r(()=>{Zn.current=_t},[_t]);const ei=s((e,t,n,i,o,r)=>lo.current(e,t,n,i,o,r),[]),ti=s((e,t,n,i,o)=>ao.current(e,t,n,i,o),[]),ni=s(()=>uo.current(),[]),ii=s((e,t)=>po.current(e,t),[]),oi=s(e=>go.current(e),[]),ri=s(e=>fo.current(e),[]),si=s(()=>ho.current(),[]),li=s(()=>{Fn(),Qn.current?.(),Oe(!1),Ae(new Set),ke([]),Je.current=[],_i([]),Fi(null),Rt(E),Zn.current?.(),requestAnimationFrame(()=>{Ye.current?.()})},[]),ci=i(li);r(()=>{ci.current=li},[li]),r(()=>{se&&ci.current()},[se]);const ai=o(()=>({documents:te?.documents,input_index_map:te?.input_index_map}),[JSON.stringify(te?.documents),JSON.stringify(te?.input_index_map)]),[ui,di]=n(""),pi=i(te);r(()=>{pi.current=te;const e=te?.input_index_map?.[0],t=te?.documents?.[e]?.title;di(t)},[te]);const gi=i(et);r(()=>{gi.current=et},[et]);const fi=s((e,t,n,i,o,r,s)=>{const l=S(t?.id)||S(n?.id)||"",c=(l?gi.current?.[l]:null)||t?.cognitiveData||n?.cognitiveData||{section_id:l,decisioning:[],gap:[],relevance_score:0},a=ln.current[i]?.current??null,u=(()=>{const e=t?.evaluationResult||n?.evaluationResult||null,o=e=>{const t=(e=>{if(!e||"object"!=typeof e)return null;const t=e?.deviation_entries;if(t&&"object"==typeof t){const e=Object.keys(t).sort((e,t)=>Number(e)-Number(t))[0];if(e&&t[e])return t[e]}const n=Object.keys(e).filter(e=>/^\d+$/.test(e)).sort((e,t)=>Number(e)-Number(t));if(n.length&&e[n[0]])return e[n[0]];const i=e?.deviations;if(i&&"object"==typeof i){const e=Object.keys(i).sort((e,t)=>Number(e)-Number(t))[0];if(e&&i[e])return i[e]}return null})(e);return t?{...e,deviation_summary:e?.deviation_summary||t?.deviation_summary,deviation_title:e?.deviation_title||t?.deviation_title,deviation_impact:e?.deviation_impact||t?.deviation_impact,deviation_explanation:e?.deviation_explanation||t?.deviation_explanation,evaluation_outputs:e?.evaluation_outputs||t?.evaluation_outputs,cognitive_decisioning:e?.cognitive_decisioning||t?.cognitive_decisioning}:e};if(!("string"==typeof i&&i.includes(y)))return o(e);const r=i.split(y)[1];if(!r)return e;const s=t?.evaluationResult||n?.evaluationResult||{},l=s?.deviation_entries?.[r]||s?.deviations?.[r]||null;return l?{...s,...l,deviation_summary:l?.deviation_summary||s?.deviation_summary,deviation_title:l?.deviation_title||s?.deviation_title,deviation_impact:l?.deviation_impact||s?.deviation_impact,deviation_explanation:l?.deviation_explanation||s?.deviation_explanation,evaluation_outputs:l?.evaluation_outputs||s?.evaluation_outputs,cognitive_decisioning:l?.cognitive_decisioning||s?.cognitive_decisioning}:o(e)})(),d=(u?.cognitive_decisioning?.decisioning_factors?.length??0)>0||(u?.cognitive_decisioning?.gaps_in_decision?.length??0)>0,p=Ne;let g=!0;if(Nt){const e=u?.deviation_highlights;if(e&&"object"==typeof e){g=Object.values(e).some(e=>Array.isArray(e)&&e.length>0)}else g=!1}return{isLoading:p&&!d,open:!0,sectionTitle:t?.title?t?.title:"No Counterpart",refSectionTitle:n?.title?n?.title:"No Counterpart",cognitiveData:c,anchorEl:e,sectionAnchorEl:a,badgeStyle:r||null,sectionIdx:i,docData:ai,deviationData:u,isOrphan:!!o,hasGuidelineMatches:g}},[ai,Ne,Nt]),hi=s((e,t,n,i,o,r)=>{if(e.stopPropagation(),ft.open&&ft.sectionIdx===o)return void It();const s=e.currentTarget;let l="left";ot.current?.contains(s)&&(l="right");Fn(),Cn.current&&En(),Ae(new Set),ke([]),Je.current=[],_t(),xt.open?Wi():yt(),requestAnimationFrame(()=>{const e=(()=>{if("string"==typeof o&&o.includes(y)){const e=o.split(y),t=`${e[0]}${y}${e[1]}`;return"right"===l?nn.current[t]?.current:tn.current[t]?.current}return"right"===l?nn.current[o]?.current:tn.current[o]?.current})()||s;ht(fi(e,t,i,o,n,r))})},[ft.open,ft.sectionIdx,It,yt,fi]),mi=s(()=>{const e=ft.sectionIdx;ft.isOrphan,It(),yt(),null!==e&&(Nn(e),Fn(),Cn.current&&En(),ke([]),Je.current=[],Nt&&null!==e&&je(Mi(e)),Ae(t=>t.has(e)?new Set:new Set([e])),setTimeout(()=>{Ye.current&&Ye.current()},50))},[ft.sectionIdx,ft.isOrphan,It,yt,En]),Si=s(()=>{const e=qe.current;if(!e)return;qe.current=null;const t=zt.findIndex(t=>t.id===e),n=Wt.findIndex(t=>t.id===e),i=-1===t?R(zt,e):null,o=-1===n?R(Wt,e):null,r=-1!==t?t:i?Number(i.split("-")[0]):-1,s=-1!==n?n:o?Number(o.split("-")[0]):-1,l=(e,t,n,i)=>-1!==e?n.current[e]?.current??null:t?i.current[t]?.current??null:null,c=(e,t,n=30)=>{let i=0;const o=()=>{const r=e();r&&0!==r.getBoundingClientRect().height?(In.current.add(r),C(r,t)):i++<n&&requestAnimationFrame(o)};requestAnimationFrame(o)};if(Re)-1!==r&&at.current&&c(()=>l(t,i,Zt,rn),at.current),-1!==s&&ot.current&&c(()=>l(n,o,en,sn),ot.current);else{const e=nt.current;if(!e)return;c(()=>-1!==r?l(t,i,Zt,rn):l(n,o,en,sn),e)}},[zt,Wt,Re,Zt,en,rn,sn,at,ot,nt]),vi=s(e=>{if(!e)return;Fn(),En(),Ae(new Set),ke([]),Je.current=[],yt(),_t();const t=zt.findIndex(t=>t.id===e),n=Wt.findIndex(t=>t.id===e),i=-1===t?R(zt,e):null,o=-1===n?R(Wt,e):null;if(-1===t&&!i&&-1===n&&!o)return void console.warn(`scrollToAndHighlightClause: nodeId "${e}" not found`);const r=-1!==t?t:i?Number(i.split("-")[0]):-1,s=-1!==n?n:o?Number(o.split("-")[0]):-1;qe.current=e,Pn(e=>{const t={...e};let n=!1;if(-1!==r){const e=Re?`left-${r}`:String(r);t[e]||(t[e]=!0,n=!0)}if(-1!==s){const e=Re?`right-${s}`:String(s);t[e]||(t[e]=!0,n=!0)}return n?t:e}),$n(e=>{const t={...e};let n=!1;const r=e=>{const i=e.split("-");let o=i[0];for(let e=1;e<i.length;e++)o+=`-${i[e]}`,t[o]||(t[o]=!0,n=!0)};return i&&r(i),o&&r(o),n?t:e}),setTimeout(()=>{requestAnimationFrame(()=>{qe.current===e&&xi.current()})},50)},[zt,Wt,Re,Pn,$n,En,yt,_t]),xi=i(Si);r(()=>{xi.current=Si},[Si]);const Ri=i(null);r(()=>{if(Tt){const e=Ft.fields.find(e=>e.analysisKey===Tt||e.key===Tt);if(e){const t=Ut.current[e.key]||Qt.current[e.key];t?.current&&setTimeout(()=>t.current.scrollIntoView({behavior:"smooth",block:"center"}),150)}}},[Tt,Ft.fields]);const yi=s(e=>{const t=Wn?.rule_difference_comparison?.fields;if(!t||!t[e])return{score:0,relation:"",highlightsA:[],highlightsB:[],hasContent:!1};const n=t[e],i=n?.relation||n?.highlights?.ruleA_spans?.length||n?.highlights?.ruleB_spans?.length||n?.mappings&&n.mappings.length>0;if(n.mappings){const e=n.mappings[0]||{};return{score:n.score,relation:e.relation||"",highlightsA:e.highlights?.ruleA_spans||[],highlightsB:e.highlights?.ruleB_spans||[],hasContent:!!i}}return{score:n.score,relation:n.relation||"",highlightsA:n.highlights?.ruleA_spans||[],highlightsB:n.highlights?.ruleB_spans||[],hasContent:!!i}},[Wn]),{getSectionCompareStyle:bi,getSubSectionCompareStyle:Ci,getDeviationStyleByKey:wi}=K({proposedSections:zt,existingSections:Wt,maintainRelativeOrder:Re,cognitiveMap:et,deviationData:Ze,treeData:te,resolvedComparisonConfig:Ft,badgeStyleOverride:Se}),{lines:Bi,setLines:_i,overallConnector:Ii,setOverallConnector:Fi,svgDimensions:Ti,calculateLines:Ei,calculateLinesDebounced:Ai,handleColumnScroll:Di}=Y({containerRef:He,leftContainerRef:at,rightContainerRef:ot,svgContainerRef:Me,pathRefs:Ke,leftHeaderRef:ze,rightHeaderRef:We,proposedSections:zt,existingSections:Wt,visibleFields:qt,leftRefs:Ut,rightRefs:Qt,sectionLeftRefs:Zt,sectionRightRefs:en,subSectionLeftRefs:rn,subSectionRightRefs:sn,lhsBadgeRefs:tn,rhsBadgeRefs:nn,sectionRowRefs:ln,expandedSections:kn,expandedSubSections:On,connectedSections:Ee,isSideBySide:dn,activeSideBySideSection:xn,maintainRelativeOrder:Re,isGuidelineMode:Nt,cognitiveMap:et,getSectionCompareStyle:bi,getSubSectionCompareStyle:Ci,getDeviationStyleByKey:wi,isArrowVisible:pn,isAnimatingRef:Ge,isSideBySideRef:Cn,sideBySideCacheRef:bn,sideBySideLineRef:_n,activeSideBySideSectionRef:Bn,activeSideBySideRightSectionRef:wn,connectedLines:De,setConnectedLines:ke,cachedConnectedPositions:Je,calculateLinesRef:Ye,resizeTimerRef:Xe,scrollLock:yn,scrollSyncLocked:Pe,handleResizeRef:Ue,activeProposed:Mt,existingRule:Ht,analysisData:Wn,pendingScrollTargetRef:ut,pendingScrollCallbackRef:dt,resolvedComparisonConfig:Ft,getFieldData:yi});r(()=>{xt.anchorEl&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ye.current?.()})})},[xt.anchorEl,Pe]);const ki=s(()=>{Fn(),Oe(!1),Pn({}),$n({}),En(),Ae(new Set),ke([]),Je.current=[],yt(),_t(),It(),requestAnimationFrame(()=>{Ye.current&&Ye.current()})},[Pn,$n,En,yt,_t,It]);r(()=>{dn||0!==Ee.size||Oe(!1)},[dn,Ee]);const Pi=o(()=>Object.values(kn).some(Boolean)||Object.values(On).some(Boolean),[kn,On]),Oi=i(null),$i=i(0),ji=i(0),Li=i(0),{handleResize:Ni}=J({timerRef:Oi,ruleComponentRef:it,scrollContainerRef:nt,containerRef:He,maintainRelativeOrder:Re,proposedSections:zt,existingSections:Wt,isSideBySideRef:Cn,activeSideBySideSectionRef:Bn,activeSideBySideRightSectionRef:wn,sectionRowRefs:ln,sectionRightRowRefs:on,sectionLeftRefs:Zt,sectionRightRefs:en,subSectionLeftRefs:rn,subSectionRightRefs:sn,lhsBadgeRefs:tn,rhsBadgeRefs:nn,leftContainerRef:at,rightContainerRef:ot,calculateLinesRef:Ye,handleResizeRef:Ue,setIsResizing:mn,setIsArrowVisible:fn,sideBySideCacheRef:bn,cachedConnectedPositions:Je});r(()=>{Ue.current=Ni},[Ni,Ue]),r(()=>{const e=(e,t,n,i,o)=>{t.current=e.getBoundingClientRect().width;const r=new ResizeObserver(e=>{null!==n.current&&cancelAnimationFrame(n.current),n.current=requestAnimationFrame(()=>{n.current=null;const r=e[e.length-1];if(!r)return;const s=r.borderBoxSize?.[0]?.inlineSize??r.contentRect.width;Math.abs(s-t.current)<1?o():(t.current=s,i())})});return r.observe(e),r},t={current:null},n={current:null},i={current:null},o=[],r=[t,n,i];return it.current&&o.push(e(it.current,$i,t,()=>Ue.current(),()=>{})),nt.current&&o.push(e(nt.current,ji,n,()=>Ue.current(),()=>Ye.current())),He.current&&o.push(e(He.current,Li,i,()=>Ue.current(),()=>Ye.current())),()=>{o.forEach(e=>e.disconnect()),r.forEach(e=>{null!==e.current&&(cancelAnimationFrame(e.current),e.current=null)})}},[]),r(()=>{Cn.current=dn},[dn]),r(()=>{Bn.current=xn},[xn]);const Mi=s(e=>{let t="",n="0";if("number"==typeof e)t=zt[e]?.nodeId||zt[e]?.id||"";else{const i=String(e).split(y);t=i[0],n=i[1]||"0"}const i=Ze?.[t]?.evaluation_result,o=Array.isArray(i)?i[parseInt(n,10)]:i?.[n];return!1===o?.evaluation_outputs?.guideline_flag?.rulebook_used?1:0},[zt,Ze]),Hi=s(e=>{const t=document.querySelectorAll('[id^="guideline-target-"], [data-web-gpt-active="true"]'),n=at.current,i=ot.current,o="string"==typeof e&&e.includes(y);let r=e;if(o){const t=e.split(y);t.length>=2&&(r=`${t[0]}${y}${t[1]}`)}const s=tn.current[r]?.current||tn.current[e]?.current;if(t.length>0&&s&&n&&i){const e=t[0];lt.current&&(lt.current.style.height="0px"),rt.current&&(rt.current.style.height="0px"),ct.current&&(ct.current.style.height="0px"),st.current&&(st.current.style.height="0px"),requestAnimationFrame(()=>{const t=s.getBoundingClientRect(),o=e.getBoundingClientRect(),r=n.getBoundingClientRect(),l=i.getBoundingClientRect(),c=n.scrollTop+(t.top-r.top)+t.height/2,a=i.scrollTop+(o.top-l.top)+o.height/2,u=c-r.height/2,d=Math.max(0,u),p=n.scrollHeight-n.clientHeight,g=d>p?d-p:0,f=r.top+c-d;let h=l.top+a-f,m=0;h<0&&(m=Math.abs(h),h=0);const S=i.scrollHeight-i.clientHeight+m,v=h>S?h-S:0;ct.current&&(ct.current.style.height=`${g}px`),rt.current&&(rt.current.style.height=`${m}px`),st.current&&(st.current.style.height=`${v}px`),requestAnimationFrame(()=>{n.scrollTo({top:d,behavior:"smooth"}),i.scrollTo({top:h,behavior:"smooth"}),Ye.current&&setTimeout(()=>Ye.current(),50)})})}},[y]),zi=s(()=>{const e=ft.sectionIdx,t=ft.isOrphan;if(yt(),null==e)return;let n="left";ft.anchorEl&&ot.current?.contains(ft.anchorEl)&&(n="right"),Nn(e),Nt&&(je(Mi(e)),Ae(new Set([e]))),An(e,t,{sourceSide:n,onReady:()=>{Nt&&setTimeout(()=>Hi(String(e)),150)}})},[An,ft.isOrphan,ft.sectionIdx,ft.anchorEl,yt,Nn,Nt,Hi,Mi]),Wi=s(()=>{yt(),En(),Ae(new Set),ke([]),Je.current=[]},[yt,En]),qi=null!==ft.sectionIdx&&Ee.has(ft.sectionIdx),{showDeviationNavigation:Gi,showOpenNodeRef:Vi,adjustScrollForPopup:Ki}=M({proposedSections:zt,existingSections:Wt,parentDeviationRecord:Gt,expandedSections:kn,maintainRelativeOrder:!!Re,scrollContainerRef:nt,leftContainerRef:at,rightContainerRef:ot,lhsBadgeRefs:tn,rhsBadgeRefs:nn}),Ji=s((e,t,n,i,o)=>{const r="string"==typeof i?S(i).trim():S(i?.deviation_summary).trim(),s=e.currentTarget;_t();let l="left";ot.current?.contains(s)&&(l="right");const c=()=>{if("string"==typeof t&&t.includes(y)){const e=t.split(y),n=`${e[0]}${y}${e[1]}`;return"right"===l?nn.current[n]?.current:tn.current[n]?.current}return"right"===l?nn.current[t]?.current:tn.current[t]?.current};if(n&&!Nt)return En(),Ae(new Set),ke([]),Je.current=[],void(r&&(Nn(t),requestAnimationFrame(()=>{const e=c()||s;if(e){e.getBoundingClientRect().top>.8*window.innerHeight&&e.scrollIntoView({behavior:"smooth",block:"center"})}Rt({open:!0,anchorEl:e,summary:i,displayImpact:o})})));Nn(t),Nt&&(je(Mi(t)),Ae(new Set([t]))),r?setTimeout(()=>{An(t,n,{toggleIfSame:!1,sourceSide:l,onReady:()=>{const e=c()||s;if(Nt)setTimeout(()=>Hi(t),150);else if(e){const t=e.getBoundingClientRect();if(t.top>.8*window.innerHeight||t.top<100){const e=t.top-window.innerHeight/2;Re?(at.current?.scrollBy({top:e,behavior:"smooth"}),ot.current?.scrollBy({top:e,behavior:"smooth"})):nt.current?.scrollBy({top:e,behavior:"smooth"})}}Rt({open:!0,anchorEl:e,summary:i,displayImpact:o})}})},350):setTimeout(()=>{An(t,n,{toggleIfSame:!1,sourceSide:l}),Nt&&setTimeout(()=>Hi(t),150)},350)},[An,_t,Rt,En,Nn,Nt,Re,Hi,Ze]),Yi=o(()=>{if(!pe)return null;const e=pe?.id?.split(":")[0];for(const t in Gt){if((Gt[t]||[]).some(t=>t.id===e))return t}return null},[pe,Gt]),Xi=i({id:null,triggerMs:null}),Ui=i(null);r(()=>{if(!pe?.id)return;const e=Number(pe.trigger),t=Xi.current;if(t?.id===pe.id&&t?.triggerMs===e)return;if(!(pe.id.includes(":")&&/:\d+$/.test(pe.id))){Xi.current={id:pe.id,triggerMs:e},vi(pe.id);const t=zt.findIndex(e=>e.id===pe.id),n=Wt.findIndex(e=>e.id===pe.id);return void(-1===t&&-1===n||setTimeout(()=>{const e=-1!==t?t:n,i=-1===t;Nt&&je(Mi(e)),Ae(new Set([e])),Dn.current(e,i,{sourceSide:i?"right":"left",onReady:()=>{Nt&&setTimeout(()=>Hi(String(e)),150)}})},400))}const[n,i]=pe.id.split(":"),o=i??"0",r=`${pe.id}:${e}`;Ui.current!==r&&(yt(),_t(),En(),Ae(new Set),ke([]),Je.current=[],Ui.current=r);let s=!1,l=0;let c=null,a=null,u=!1;const d=(e,t)=>{const n=(e,i)=>{if(!e)return null;if(t.includes(e.id)||t.includes(e.nodeId)||t.includes(e.contentId))return i;if(!Array.isArray(e.subsections))return null;for(let t=0;t<e.subsections.length;t++){const o=n(e.subsections[t],`${i}-${t}`);if(o)return o}return null};for(let t=0;t<e.length;t++){const i=n(e[t],String(t));if(i)return i}return null},p=()=>{if(s)return;const t=()=>{Xi.current={id:pe.id,triggerMs:e}};let i=null,r=null;for(const e in Gt){const t=Gt[e].find(e=>e.id===n||e.nodeId===n||e.contentId===n||e.evaluationResult?.nodeId===n);if(t){i=e,r=t;break}}if(!r||!i)return l++,void(l<30&&(c=setTimeout(p,100)));const g=Array.from(new Set([n,r.id,r.nodeId,r.contentId,r.evaluationResult?.nodeId].filter(Boolean))),f=zt.findIndex(e=>e.id===i),h=Wt.findIndex(e=>e.id===i),m=-1===f&&-1!==h,S=d(zt,g);let v=d(Wt,g);if(S&&!v&&!m){const e=S.split("-");let t=Number(e[0]);if(Re){const e=zt[t]?.refIndexes?.[0],n=Wt.findIndex(t=>t.selfIndex===e);-1!==n&&(t=n)}v=[t,...e.slice(1)].join("-")}if(!S&&!v)return l++,void(l<30&&(c=setTimeout(p,100)));const x=S?Number(S.split("-")[0]):f,R=v?Number(v.split("-")[0]):h,b=R>=0?R:v?Number(v.split("-")[0]):-1,C=zt[x],_=Wt[b],I=C&&!C.title&&!C.content,F=_&&!_.title&&!_.content,T=m||(!S&&!!v||I&&!F);if(T){if(!(Re?!!co.current[`right-${R}`]:!!co.current[String(R)])&&R>=0)return Ln(R,"right"),void(c=setTimeout(p,200))}else{if(!(Re?!!co.current[`left-${x}`]:!!co.current[String(x)])&&x>=0)return Ln(x,"left"),void(c=setTimeout(p,200))}const E=S||"",A=v||"",D=g.map(e=>`${e}${y}${o}`),k=D[0],P=()=>{for(const e of D){const t=tn.current[e]?.current||null,n=nn.current[e]?.current||null;if(t||n)return{refId:e,left:t,right:n}}return{refId:k,left:null,right:null}},O=e=>`${e}${y}${E}${y}${A}`;if(!u){Nn(O(k)),u=!0,l=0;const e=()=>{const{left:e,right:t}=P();return T||!e&&!!t?t:e};return a?.(),void(c=setTimeout(()=>{s||(a=((e,t)=>{let n,i=0,o=null,r=null;const l=performance.now(),c=()=>{if(s)return;if(performance.now()-l>3e3)return void t();const a=e();if(!a||0===a.getBoundingClientRect().height)return void(n=requestAnimationFrame(c));const u=a.getBoundingClientRect(),d=u.top,p=u.height,g=null!==o&&Math.abs(d-o)<.5,f=null!==r&&Math.abs(p-r)<.5;if(g&&f){if(i++,i>=5)return void t()}else i=0;o=d,r=p,n=requestAnimationFrame(c)};return n=requestAnimationFrame(c),()=>cancelAnimationFrame(n)})(e,()=>{s||(a=null,p())}))},300))}const{refId:$,left:j,right:L}=P(),N=O($);if(!j&&!L)return l++,void(l<30&&(c=setTimeout(p,100)));const M=T||!j&&!!L,H=M?L:j,z=Re?M?ot.current:at.current:nt.current;if(!H||!z)return l++,void(l<30&&(c=setTimeout(p,100)));const W=H.getBoundingClientRect();if(0===W.height)return l++,void(l<30&&(c=setTimeout(p,100)));const q=z.getBoundingClientRect(),G=W.top-q.top+z.scrollTop-q.height/2+W.height/2,V=S?.includes("-")||v?.includes("-"),K=async()=>{if(s)return;t();const e=H instanceof Element?window.getComputedStyle(H).color:"";[j,L].forEach(t=>{t&&(t.style.transition="box-shadow 300ms ease-in-out",t.style.boxShadow=`0 0 10px ${e}`)}),setTimeout(()=>{[j,L].forEach(e=>{e&&(e.style.boxShadow="")})},2e3);const n=r.evaluationResult?.deviations?.[o]||r,i=r.evaluationResult?.evaluation_outputs||r.evaluation_outputs;if(!(!!j&&!!L)&&!Nt){const e=M?nn.current[V?$:R]?.current||L:tn.current[V?$:x]?.current||j;return Ki(e,()=>{Rt({open:!0,anchorEl:e,displayImpact:pe.displayImpact,summary:{...n,evaluation_outputs:i}})},{skipScroll:!0}),void ge?.()}const l=(e,t)=>Promise.race([e,new Promise(e=>setTimeout(e,t))]);Re&&await Promise.all([at.current?l(B(at.current),600):Promise.resolve(),ot.current?l(B(ot.current),600):Promise.resolve()]),Nt&&(je(Mi(N)),Ae(new Set([N]))),Dn.current(N,!1,{toggleIfSame:!1,sourceSide:m?"right":"left",onReady:()=>{t();const e=M?nn.current[$]?.current||L:tn.current[$]?.current||j;if(Nt)setTimeout(()=>Hi(N),150);else{const e=tn.current[$]?.current||j,t=nn.current[$]?.current||L;e&&(e.style.scrollMarginTop="150px",e.scrollIntoView({behavior:"smooth",block:"start"})),t&&(t.style.scrollMarginTop="150px",t.scrollIntoView({behavior:"smooth",block:"start"}))}Rt({open:!0,anchorEl:e,displayImpact:pe.displayImpact,summary:{...n}}),ge?.()}})};Math.abs(z.scrollTop-G)<=2?K():w(z,G,K)};return c=setTimeout(p,100),()=>{s=!0,c&&clearTimeout(c),a?.()}},[pe?.id,pe?.trigger,pe?.displayImpact,Gt,zt,Wt,Re,Rt,vi,Nt,Mi,Hi]),r(()=>{if(!xt.open)return;const e=xt.anchorEl;if(!e)return;if(e.isConnected)return;const t=t=>{for(const[n,i]of Object.entries(t))if(i.current?.textContent===e.textContent)return n;return null},n=e.dataset?.deviationRefId||t(tn.current)||t(nn.current);if(!n)return;const i=nn.current[n]?.current||tn.current[n]?.current;i&&i.isConnected&&Rt(e=>({...e,anchorEl:i}))},[xt.open,xt.anchorEl,Pe,Ee,kn]);const{open:Qi,sectionIdx:Zi,isOrphan:eo,badgeStyle:to,anchorEl:no,sectionAnchorEl:io}=pt;r(()=>{if(!le.isStreamingEnabled)return;if(!Qi||null==Zi)return;if(Zi===Vn)return;const e="string"==typeof Zi?Zi.split(y)[0]:null,t=(e,n)=>{if(!e||!Array.isArray(e))return null;for(const i of e){if(i.id===n)return i;if(i.subsections?.length){const e=t(i.subsections,n);if(e)return e}}return null},n=e&&"string"==typeof e?t(zt,e):null,i=e&&"string"==typeof e?t(Wt,e):null,o="number"==typeof Zi?zt[Zi]||null:n||e&&(te?.nodes?.[e]||te?.[e])||null,r="number"==typeof Zi?Wt[Zi]||null:i,s=fi(no,o,r,Zi,eo,to);gt(e=>{if(!e.open)return e;return S(e.cognitiveData)===S(s.cognitiveData)&&S(e.deviationData)===S(s.deviationData)&&e.sectionTitle===s.sectionTitle&&e.refSectionTitle===s.refSectionTitle?e:{...e,...s,open:!0,anchorEl:e.anchorEl,sectionAnchorEl:e.sectionAnchorEl}})},[Qi,Zi,eo,to,no,io,zt,Wt,fi]);const oo=s(({section:t,keyPath:n,depth:i=0,columnKey:o="left",parentNodeId:r="",sectionOffset:s,rhsOrphanVisualIndexes:l})=>e(z,{section:t,keyPath:n,depth:i,columnKey:o,parentNodeId:r,sectionOffset:s,rhsOrphanVisualIndexes:l}),[]),ro=o(()=>zt.map((t,n)=>{const i=!t?.title&&!t?.content,o=!t?.refIndexes||0===t.refIndexes.length;return i&&o&&Re?null:e(W,{section:t,idx:n},t?.layoutKey??t?.id??`left-row-${n}`)}),[zt,Re]),so=o(()=>Wt.map((t,n)=>{const i=!t?.title&&!t?.content,o=!t?.refIndexes||0===t.refIndexes.length;return i&&o&&Re?null:e(q,{section:t,idx:n},t?.layoutKey??t?.id??`right-row-${n}`)}),[Wt,Re]),lo=i(hi);r(()=>{lo.current=hi},[hi]);const co=i(kn);r(()=>{co.current=kn},[kn]);const ao=i(Ji);r(()=>{ao.current=Ji},[Ji]);const uo=i(Wi);r(()=>{uo.current=Wi},[Wi]);const po=i(Ln);r(()=>{po.current=Ln},[Ln]);const go=i(jn);r(()=>{go.current=jn},[jn]);const fo=i(oo);r(()=>{fo.current=oo},[oo]);const ho=i(En);r(()=>{ho.current=En},[En]);const mo=o(()=>({isGuidelineMode:Nt,maintainRelativeOrder:!!Re,showDeviationBadges:we,isProposingFix:fe,proposingFixNodeId:he,isRedlineFlow:me,isSideBySide:dn,activeSideBySideSection:xn,scrollSyncLocked:Pe,toggleScrollSyncLocked:Hn,summaryPopupAnchorEl:xt.anchorEl,connectedSections:Ee,proposedSections:zt,existingSections:Wt,deviationNumberRegistry:Vt,deviationParentRegistry:Kt,treeData:te,displayConfig:le,deviationAnalysisStatus:Le,resolvedMarkdownStyles:tt,unifiedNumbering:zn,expandedSections:kn,expandedSubSections:On,setExpandedSubSections:$n,getSectionCompareStyle:bi,getSubSectionCompareStyle:Ci,getBadgeRef:un,getSectionRowRef:cn,getSubSectionRef:an,sectionLeftRefs:Zt,sectionRightRefs:en,sectionRowRefs:ln,sectionRightRowRefs:on,subSectionLeftRefs:rn,subSectionRightRefs:sn,lhsBadgeRefs:tn,rhsBadgeRefs:nn,openMoreFunctionsPopup:ei,handleOpenSummaryPopup:ti,openSummaryPopup:ti,handleCloseSummaryPopup:ni,toggleSection:ii,handleSubSectionToggle:oi,renderSubSectionAccordion:ri,resetSideBySide:si,setConnectedSections:Ae,setConnectedLines:ke,cachedConnectedPositions:Je,showDeviationNavigation:Gi,showOpenNodeRef:Vi,deviationNodeIdToView:pe?.id,deviationTargetParentId:Yi,guidelinesData:ve,gptWebCitationConfig:xe}),[Nt,Re,we,fe,he,me,dn,xn,Pe,Hn,xt.anchorEl,Ee,zt,Wt,Vt,le,Le,tt,zn,kn,On,$n,bi,Ci,un,cn,an,Gi,Vi,pe,Yi,ve,xe]),So=S(pt.sectionTitle||Ot||kt),vo=S(Nt?jt||Lt||pt.refSectionTitle:pt.refSectionTitle||jt||Lt);return e(V,{value:mo,children:t(l,{ref:it,sx:{display:"flex",flexDirection:"column",height:"100%",bgcolor:"#F6F7F9B2",fontFamily:'"Plus Jakarta Sans", sans-serif',overflow:"visible",position:"relative"},children:[Be&&e(l,{sx:{position:"absolute",inset:0,bgcolor:"rgba(255, 255, 255, 0.6)",backdropFilter:"blur(10px)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"8px"},children:e(P,{})}),xt.open&&e(G,{open:xt.open,anchorEl:xt.anchorEl,containerEl:Ri.current,clipTopEl:ze.current,scrollContainerEl:nt.current,onClose:Wi,summary:xt.summary,displayImpact:xt.displayImpact,isScrollLocked:Pe}),e(k,{open:ft.open,anchorEl:ft.anchorEl,maintainRelativeOrder:!!Re,sectionTitle:ft.sectionTitle,referenceSectionTitle:ft.refSectionTitle,onClose:It,onOpenCognitiveCompare:wt,onOpenSideBySide:zi,onConnect:mi,isConnected:qi,isOrphan:!Nt&&!!ft.isOrphan,isGuidelineMode:Nt,hasGuidelineMatches:ft.hasGuidelineMatches}),pt.open&&e(D,{open:pt.open,popupRef:Ct,position:mt,popupConfig:ue,onClose:()=>{St(null),gt(e=>({...e,open:!1})),bt(null)},markdownStyles:re,sectionTitle:So,referenceSectionTitle:vo,cognitiveData:pt.cognitiveData,anchorEl:pt.anchorEl,sectionAnchorEl:pt.sectionAnchorEl,scrollContainerEl:nt.current,badgeStyle:pt.badgeStyle,docData:pt.docData,deviationData:pt.deviationData,isLoading:pt.isLoading}),e(c,{open:!!Ie,autoHideDuration:8e3,onClose:()=>Fe(null),anchorOrigin:{vertical:"top",horizontal:"center"},children:e(a,{onClose:()=>Fe(null),severity:"error",sx:{width:"100%",whiteSpace:"pre-line"},children:Ie})}),e(H,{componentHeaderText:ee,displayConfig:le,maintainRelativeOrder:Re,onCollapseAll:ki,showCollapseAll:Pi,onToggleView:e=>{_e(!0),setTimeout(()=>{ye(!e),ae?.(!e),Oe(!1),En(),yt(),Ae(new Set),ke([]),Je.current=[],requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(()=>{_e(!1)},600)})})},50)}}),e(l,{ref:nt,onScroll:Di,sx:{flex:1,minHeight:0,pt:1.5,pb:1,px:3,display:"flex",justifyContent:"center",alignItems:"flex-start",bgcolor:"#FFFFFF",overflowY:Re?"visible":"auto",borderTop:qn&&Gn?"none":"1.5px solid #EEF0F4"},children:e(l,{sx:{display:"flex",flexDirection:"column",width:"100%",maxWidth:"1200px",...Re?{flex:1}:{}},children:t(l,{ref:He,sx:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) 180px minmax(0, 1fr)",gap:"100px",maxWidth:"1200px",width:"100%",position:"relative",minHeight:0,...Re?{flex:1,overflow:"visible"}:{}},children:[e(U,{svgContainerRef:Me,svgDimensions:Ti,isResizing:hn,overallConnector:Ii,rootDeviationStyle:Un,lines:Bi,isSideBySide:dn,activeSideBySideSection:xn,isArrowVisible:pn,maintainRelativeOrder:Re,proposedSections:zt,existingSections:Wt,cognitivePopup:pt,activeBadgeId:vt,closeCognitivePopup:_t,setActiveBadgeId:bt,openCognitivePopupFromState:Bt,buildSectionPopupState:fi,connectedLines:De,isGuidelineMode:Nt,deviationAnalysisStatus:Le,pathRefs:Ke}),t(l,{sx:{border:"1px solid #E7E7E9",borderRadius:"8px",bgcolor:"#FFFFFF",display:"flex",flexDirection:"column",position:"relative",zIndex:2,filter:"drop-shadow(0px 2px 4px #F2F2F2)",...Re?{flex:1,overflow:"visible"}:{}},children:[e(l,{ref:ze,sx:{p:"8px",bgcolor:"#F7F8FA",borderBottom:"1px solid #E7E7E9",borderRadius:"8px 8px 0 0",display:"flex",alignItems:"center",minHeight:"40px",overflow:"hidden",minWidth:0},children:e(u,{title:kt,placement:"top",children:e(d,{sx:{fontSize:"16px",fontWeight:500,color:"#19213D",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%",minWidth:0,textAlign:"center",display:"block"},children:kt})})}),t(l,{ref:at,onScroll:Di,sx:{p:"12px",display:"flex",flexDirection:"column",...Re?{maxHeight:"calc(100vh - 250px)",flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0,mr:"-180px",pr:"192px","&::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"}:{}},children:[e("div",{ref:lt,style:{width:"100%",height:"0px",flexShrink:0}}),Yt&&ro,e("div",{ref:ct,style:{width:"100%",height:"0px",flexShrink:0}})]})]}),e(l,{ref:Ri,sx:{width:"180px",display:"flex",flexDirection:"column",alignItems:"center",pt:"15px",gap:0,zIndex:20,pointerEvents:"none"},children:e(l,{sx:{display:"flex",justifyContent:"center",alignItems:"center",mt:0},children:t(l,{onClick:e=>{e.stopPropagation(),pt.open&&vt===Vn?_t():(bt(Vn),Bt(fi(e.currentTarget,{title:ui,content:"",evaluationResult:Kn,cognitiveData:{section_id:"",decisioning:[],gap:[],relevance_score:0,isMissingRationale:!0}},null,Vn,!0,{...Un,label:""})))},sx:{display:"inline-flex",alignItems:"center",gap:"5px",px:1.5,py:"5px",top:"-8px",borderRadius:"20px",bgcolor:Un.badgeBg,color:Un.badgeText,border:`1px solid ${Un.badgeBorder}`,fontSize:"12px",fontWeight:600,whiteSpace:"nowrap",position:"relative",zIndex:1,pointerEvents:"auto",cursor:"pointer"},children:[Yn?e(u,{title:"Deviation data generation in progress",placement:"top",arrow:!0,children:e(l,{component:"span",sx:{display:"inline-flex",alignItems:"center"},children:e(O,{color:Un.badgeText})})}):Xn??e(O,{color:Un.badgeText}),e(l,{component:"span",sx:{width:14,height:14,display:"flex",alignItems:"center","& svg":{width:"14px",height:"14px"}},children:e(h,{})}),e(f,{size:11,style:{transform:pt.open&&vt===Vn?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.25s ease"}})]})})}),t(l,{sx:{border:"1px solid #E3E6EA",borderRadius:"8px",bgcolor:"#FFFFFF",boxShadow:"0px 1px 4px #F7F4FE",position:"relative",zIndex:2,display:"flex",flexDirection:"column",minWidth:0,...Re?{flex:1,overflow:"visible",minHeight:0}:{}},children:[Sn&&e(m,{sections:11}),e(l,{ref:We,sx:{p:"8px",bgcolor:Nt?"#F1F3F5":"#F7F8FA",borderBottom:"1px solid #D7DCE2",borderRadius:"8px 8px 0 0",display:"flex",alignItems:"center",...Re?{maxHeight:"calc(100vh - 250px)",overflowY:"auto",overflowX:"hidden",minHeight:0,...Nt?{"&::-webkit-scrollbar":{width:"6px",display:"block"},"&::-webkit-scrollbar-track":{background:"transparent"},"&::-webkit-scrollbar-thumb":{background:"#CBD5E1",borderRadius:"10px"},"&::-webkit-scrollbar-thumb:hover":{background:"#94A3B8"},scrollbarWidth:"thin",scrollbarColor:"#CBD5E1 transparent"}:{"&::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"}}:{}},children:Nt?t(p,{value:$e,onChange:(e,t)=>je(t),variant:"fullWidth",TabIndicatorProps:{sx:{display:"none"}},sx:{width:"100%",minHeight:"36px","& .MuiTab-root":{minHeight:"36px",px:1,py:0,borderRadius:"8px",fontSize:"14px",lineHeight:1,fontWeight:500,textTransform:"none",color:"#374151",minWidth:0,transition:"background-color 160ms ease, box-shadow 160ms ease"},"& .Mui-selected":{color:"#374151",bgcolor:"#FFFFFF"}},children:[e(g,{label:e(u,{title:Lt,placement:"top",children:e(l,{component:"span",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",width:"100%"},children:"Redline Guidelines"})})}),e(g,{label:e(u,{title:"Web & GPT Sources",placement:"top",children:e(l,{component:"span",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",width:"100%"},children:"Web & GPT Sources"})})})]}):e(u,{title:Lt,placement:"top",children:e(d,{sx:{fontSize:"16px",fontWeight:500,color:"#5928ED",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",width:"100%",minWidth:0,textAlign:"center",display:"block"},children:Lt})})}),t(l,{ref:ot,onScroll:Di,sx:{p:Nt?"0px":"12px",display:"flex",flexDirection:"column",...Re?{maxHeight:"calc(100vh - 250px)",...!Nt&&{flex:1},overflowY:"auto",overflowX:"hidden",minHeight:0,ml:"-150px",pl:"165px","&::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"}:{}},children:[e("div",{ref:rt,style:{width:"100%",height:"0px",flexShrink:0}}),Nt?0===$e?e(Q,{guidelinesData:ve,deviationData:de,connectedSections:Ee,proposedSections:zt}):e(Z,{deviationData:de,connectedSections:Ee,proposedSections:zt}):Yt&&so,e("div",{ref:st,style:{width:"100%",height:"0px",flexShrink:0}})]})]})]})})})]})})};export{ee as default};
|
|
2
2
|
//# sourceMappingURL=CognitiveCompare.js.map
|