@veltdev/sdk-dev 6.0.50-beta.4 → 6.0.50-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/app/models/data/custom-css.data.model.d.ts +3 -2
  2. package/{chunk-TBXKEMWQ.js → chunk-22I4DH53.js} +1 -1
  3. package/{chunk-Z5HOZ663.js → chunk-2UZN24LU.js} +1 -1
  4. package/{chunk-LTJOCETF.js → chunk-4F4E7EFW.js} +1 -1
  5. package/{chunk-NZHMGDTH.js → chunk-5GGSP4VM.js} +1 -1
  6. package/{chunk-T6V4S7QH.js → chunk-6YADUX5R.js} +1 -1
  7. package/{chunk-ZLYWK2VG.js → chunk-77YRJB6U.js} +1 -1
  8. package/{chunk-BV4TNIOZ.js → chunk-7XUMHBJU.js} +1 -1
  9. package/{chunk-FXWWWEBW.js → chunk-A3NJZPJU.js} +1 -1
  10. package/{chunk-AB2WGHOS.js → chunk-AF2PV57S.js} +1 -1
  11. package/{chunk-IVZUDPN3.js → chunk-AZPZ6YNE.js} +1 -1
  12. package/{chunk-HLC2AZHF.js → chunk-DQRA6TYX.js} +1 -1
  13. package/{chunk-FCOBFDQS.js → chunk-IWNLZTY7.js} +1 -1
  14. package/{chunk-4IBV5UCY.js → chunk-JNWDY6EC.js} +1 -1
  15. package/{chunk-2X43K3RH.js → chunk-MQWR574P.js} +1 -1
  16. package/{chunk-DRRKYAJ2.js → chunk-NPHXJUYD.js} +1 -1
  17. package/{chunk-FQ4KYGRK.js → chunk-NTUJPDO3.js} +1 -1
  18. package/{chunk-YPU2HZ7F.js → chunk-OC27IKXX.js} +1 -1
  19. package/{chunk-HVVSOIIK.js → chunk-PNGL2BK2.js} +1 -1
  20. package/{chunk-CKTADJ5E.js → chunk-RQ7JAEYC.js} +1 -1
  21. package/{chunk-JW6XN3VT.js → chunk-RSU53L4Z.js} +1 -1
  22. package/{chunk-YJ72I5DT.js → chunk-S7GV42W6.js} +1 -1
  23. package/{chunk-L7CPPZOT.js → chunk-TIAQKD26.js} +1 -1
  24. package/{chunk-GQQEMXF4.js → chunk-TV5RRJEX.js} +1 -1
  25. package/{chunk-FNNVYVET.js → chunk-U5WQDAMR.js} +1 -1
  26. package/{chunk-PTU55FCA.js → chunk-U65L5XOP.js} +1 -1
  27. package/{chunk-3EEXUWWU.js → chunk-V5JKL7XI.js} +1 -1
  28. package/{chunk-LC6FO2ZL.js → chunk-VJ47SA66.js} +20 -20
  29. package/{chunk-6YAIJWR5.js → chunk-WIO7FLS6.js} +1 -1
  30. package/{chunk-B7AYR5M5.js → chunk-XBR7WTYL.js} +1 -1
  31. package/{chunk-RAZFUE7H.js → chunk-Y2R3M2JH.js} +1 -1
  32. package/{chunk-FFATDE7D.js → chunk-YOXKQAJM.js} +1 -1
  33. package/{chunk-NJ4DESBW.js → chunk-ZB27UMZA.js} +1 -1
  34. package/{chunk-KC7IFS73.js → chunk-ZGDIZTBA.js} +1 -1
  35. package/chunk-ZHFA5BHC.js +6 -0
  36. package/{chunk-B7VI7OAD.js → chunk-ZJ2MICFG.js} +1 -1
  37. package/{chunk-LUEDRA66.js → chunk-ZZE4KN4N.js} +1 -1
  38. package/package.json +1 -1
  39. package/velt-activity-log.js +1 -1
  40. package/velt-area.js +1 -1
  41. package/velt-arrow.js +1 -1
  42. package/velt-comment.js +1 -1
  43. package/velt-crdt.js +1 -1
  44. package/velt-cursor.js +1 -1
  45. package/velt-huddle.js +1 -1
  46. package/velt-live-state-sync.js +1 -1
  47. package/velt-notification.js +1 -1
  48. package/velt-portable.js +1 -1
  49. package/velt-presence.js +1 -1
  50. package/velt-reaction.js +1 -1
  51. package/velt-recorder.js +1 -1
  52. package/velt-rewriter.js +1 -1
  53. package/velt-selection.js +1 -1
  54. package/velt-tag.js +1 -1
  55. package/velt-user-invite.js +1 -1
  56. package/velt-user-request.js +1 -1
  57. package/velt-video-player.js +1 -1
  58. package/velt-views.js +1 -1
  59. package/velt.js +5 -5
  60. package/chunk-A5Z4DFLZ.js +0 -6
package/velt-comment.js CHANGED
@@ -1,4 +1,4 @@
1
- import{C as Nh}from"./chunk-FNNVYVET.js";import{a as ep,b as E0}from"./chunk-4IBV5UCY.js";import{a as F0,b as Ph}from"./chunk-TBXKEMWQ.js";import{a as D0,b as T0}from"./chunk-NZHMGDTH.js";import{a as jb,b as Gb,c as M0,d as A0,e as P0,f as _c,g as Sc}from"./chunk-AB2WGHOS.js";import{a as ap}from"./chunk-T6V4S7QH.js";import"./chunk-FQ4KYGRK.js";import{a as WC,b as So,c as f0,d as qu,e as b0,f as C0,g as Tr,h as Zu,i as k0,j as Qu,k as Mn,n as Xu,o as x0,p as _0,q as yo,r as S0,s as y0,t as I0}from"./chunk-NJ4DESBW.js";import"./chunk-CKTADJ5E.js";import"./chunk-6YAIJWR5.js";import{b as yu,c as Iu,g as wu,l as Xb,m as eC,r as tC,s as iC,w as lC,x as Ft}from"./chunk-ZLYWK2VG.js";import{b as Nb,c as Rb,d as Ub}from"./chunk-FFATDE7D.js";import{a as dn}from"./chunk-B7VI7OAD.js";import{b as O0}from"./chunk-DRRKYAJ2.js";import{a as Du,c as rC,d as nC}from"./chunk-Z5HOZ663.js";import{a as tp}from"./chunk-FCOBFDQS.js";import{a as Yt}from"./chunk-PTU55FCA.js";import{a as pt,b as tr}from"./chunk-BV4TNIOZ.js";import{a as An}from"./chunk-B7AYR5M5.js";import{a as Io}from"./chunk-YPU2HZ7F.js";import{a as rp,b as np,c as N0,d as Fh,e as op}from"./chunk-S6JZ7XRE.js";import{A as p0,E as h0,F as Ku,G as P,H as N,a as Wu,c as Ju,d as yr,e as g0,f as Ir,i as Yu}from"./chunk-LUEDRA66.js";import{a as Be,b as Rm}from"./chunk-L7CPPZOT.js";import{a as u0,b as J,c as ln,d as Ut}from"./chunk-LTJOCETF.js";import{a as wr}from"./chunk-KC7IFS73.js";import{a as qb}from"./chunk-RAZFUE7H.js";import{A as bn,Ea as aC,F as Vb,Fa as zt,G as ft,Ga as D,H as kt,Ha as Dt,I as $b,Ia as Se,J as zb,Ja as Pt,K as Hb,M as on,N as Wb,O as fu,P as Jb,Q as bu,R as Cu,T as Yb,U as Kb,V as sc,X as Vt,Y as Zo,da as ku,ea as xu,f as gu,ga as _u,j as Pb,m as mc,n as uu,p as Fb,r as pu,s as Lb,t as hu,v as Bb,za as oC}from"./chunk-A5Z4DFLZ.js";import{a as w0}from"./chunk-2X43K3RH.js";import{D as s0,G as _o,H as ut,e as Hu,l as o0,n as a0,p as i0,q as l0,r as d0,x as v0,y as c0,z as m0}from"./chunk-JW6XN3VT.js";import{$b as mu,$h as Ie,$i as UC,$j as XC,A as cb,Ae as uc,Ag as pC,Ah as qr,Bb as l,Bc as su,Be as dC,Bg as hC,Bh as Zr,C as mb,Ca as Cr,Cb as kr,Ce as bo,Cg as fC,Ch as Pm,Ck as t0,D as Ko,Db as xr,Df as mC,Dg as bC,Dh as Bu,E as qt,Ea as sr,Eh as Fm,Fb as ot,Fe as Kr,Fk as r0,G as Wr,Ga as ou,Gb as at,Gc as nn,Gd as Zb,Ge as st,Gk as Ah,Ha as v,Hb as it,Hc as wt,He as Z,Hg as Mm,Hk as n0,Ia as Le,Ib as Hn,Ic as ue,Ig as Nu,Ii as oe,Ij as Xn,Ik as Re,J as po,Ja as au,Jb as dc,Jg as kn,Ji as Oh,Jj as JC,Jk as vt,K as qo,Ka as iu,Kb as we,Kg as xn,Lb as mt,Lg as Ih,Lj as xc,M as Gt,Mb as pe,Mf as Em,Mg as CC,Mj as YC,N as sb,Nc as tt,Nj as Et,O as zn,Oa as lu,Ob as vc,Og as kC,P as gb,Pb as ie,Pc as cc,Pg as Ru,Q as ub,Qa as lc,Qb as Ge,Qc as Tn,Qd as Qb,Qf as Mu,Qj as KC,R as pb,Ra as G,Rb as Ce,Rc as Mb,Re as vC,Rg as wh,S as Dn,Sb as cu,Sg as Uu,T as hb,Ta as xb,Tb as Db,Tg as Dh,Th as EC,U as Ch,Ug as Am,Uh as OC,V as Fe,Va as _b,Vd as ho,Ve as Zt,Vg as Dr,Vi as _n,Vj as qC,Wa as T,Wd as fo,We as Kn,Wg as xC,Wh as Vu,Wi as Mh,Wj as Gu,Xa as Sb,Xe as At,Xg as Lu,Xh as hc,Xj as ZC,Y as Tm,Ya as yb,Yd as kh,Ye as cC,Yj as QC,Zc as Ab,Zd as qe,Ze as Co,Zf as Qo,_ as ic,_a as M,_b as Tb,_f as fr,_g as _C,_i as $u,a as g,aa as ru,ab as s,ac as U,ae as ct,ag as Au,aj as LC,b,ba as et,bc as Jr,bi as fc,bj as BC,c as ib,ca as fb,cc as gt,cg as pc,ci as MC,cj as VC,da as bb,db as du,dc as se,de as Tu,dg as ur,di as Qn,dj as $C,ea as be,ec as k,eg as xo,eh as SC,ej as jC,fa as ge,fb as x,fc as _e,fg as br,fi as bc,fj as GC,g as Pe,gb as rn,gc as Ye,gg as qn,gj as ju,h as lb,ha as Cb,hb as I,hc as E,hg as Zn,hh as yC,hj as Cc,i as ac,ia as kb,ib as w,ic as It,ig as _h,ik as e0,ja as B,jb as Ib,jc as fn,jg as Pu,ji as Nm,jj as zC,k as Lt,ka as V,kb as vu,l as De,la as de,lb as rt,lc as Wn,lg as Om,lh as IC,lj as Xo,m as db,ma as _t,mb as nt,mc as F,mg as Sh,mh as wC,mk as zu,na as nu,nb as c,nc as R,ng as Fu,nh as DC,ni as AC,o as vb,ob as C,oc as Rr,oi as Eh,oj as Sr,p as Hr,pb as _,pc as Eb,pd as Su,pi as PC,pj as pr,q as jn,qb as O,qc as Ob,qg as sC,qj as A,r as ye,rc as $e,rd as _r,re as ke,rf as ko,rg as gC,rj as kc,sa as Ae,se as Eu,sh as TC,tc as Yr,te as Yn,tg as En,th as Lr,ub as p,uc as L,ug as uC,uh as Th,ui as FC,v as Ee,vb as h,vc as Ct,ve as an,vg as Jt,vi as NC,w as Bt,wa as dt,wb as je,wc as dr,we as gc,wj as HC,x as tu,xa as K,xb as Y,xc as te,ya as me,yb as wb,yc as Jn,ye as xh,yg as yh,yi as RC,z as Gn,zb as z,zc as vr,ze as gr,zf as Ou,zg as Cn,zh as On}from"./chunk-LC6FO2ZL.js";function cr(r){try{if(typeof r!="string")return null;let o=r.trim();return o||null}catch{return null}}function eo(r,o){try{return typeof r!="string"||!r?o:b(g({},o),{sidebarId:r})}catch{return o}}var R0="velt-comments-sidebar-v2",xD="__veltSidebarV2Instance";function U0(r){try{let o=r;return o?cr(o.sidebarId)||typeof o.getAttribute=="function"&&cr(o.getAttribute("sidebar-id"))?!0:!!cr(o[xD]?.id):!1}catch{return!1}}function ip(){try{let r=document.querySelector(R0);return!r||!U0(r)?r:Array.from(document.querySelectorAll(R0)).find(n=>!U0(n))??null}catch{return null}}function L0(r){try{return!r||typeof r!="object"||!Object.prototype.hasOwnProperty.call(r,"sidebarId")?!1:!cr(r.sidebarId)}catch{return!1}}function B0(r,o){let n=[],e=(a,i,d,m)=>{n.push({key:a,field:i,op:d,value:m})},t=r?.order==="asc";if(r?.folderId&&e("folderId","metadata.veltFolderId","==",r.folderId),r?.locationId&&e("locationId","location.id","==",r.locationId),o?.length&&e("documentIds","metadata.documentId","in",o),r?.resolvedBy){if(t)throw new Error("Order by resolvedBy is not supported in ascending order.");e("resolvedBy","resolvedByUserId","==",r.resolvedBy)}if(r?.mentionedUserIds?.length){if(t)throw new Error("Order by mentionedUserIds is not supported in ascending order.");e("mentionedUserIds","mentionedUserIds","array-contains-any",r.mentionedUserIds)}if(r?.userIds?.length){if(t)throw new Error("Order by userIds is not supported in ascending order.");e("userIds","from.userId","in",r.userIds)}if(r?.statusIds?.length){if(t)throw new Error("Order by status id is not supported in ascending order.");e("statusIds","status.id","in",r.statusIds)}return r?.createdAfter&&e("createdAfter","createdAt",">=",r.createdAfter),r?.createdBefore&&e("createdBefore","createdAt","<=",r.createdBefore),r?.updatedAfter&&e("updatedAfter","lastUpdated",">=",r.updatedAfter),r?.updatedBefore&&e("updatedBefore","lastUpdated","<=",r.updatedBefore),b(g({clauses:n,direction:r?.order??"desc"},r?.order?{requestedOrder:r.order}:{}),{pageSize:r?.pageSize??100})}function V0(r,o){let n={organizationId:o.organizationId};for(let e of r.clauses)n[e.key]=e.value;return r.requestedOrder&&(n.order=r.requestedOrder),n.pageSize=r.pageSize,o.pageToken!==void 0&&(n.pageToken=o.pageToken),n}function Rh(r,o,n=!1){return{data:r.slice(0,o),hasMore:n||r.length>o}}var j0=["lastUpdated","createdAt"];function yc(r,o="desc"){return j0.map(n=>r(n,o))}function $0(r){if(typeof r=="number")return Number.isFinite(r)?r:0;if(typeof r=="string"){let o=Date.parse(r);return Number.isFinite(o)?o:0}return r&&typeof r=="object"&&typeof r.seconds=="number"?r.seconds*1e3:0}function G0(r,o){for(let n of j0){let e=$0(o?.[n])-$0(r?.[n]);if(e!==0)return e}return 0}var z0=new WeakSet;function H0(r){r&&typeof r=="object"&&z0.add(r)}function W0(r){return!!r&&typeof r=="object"&&z0.has(r)}function Um(r){try{let o=r?.organizationId,n=r?.documentId;return!o||!n?null:`${o}::${n}`}catch{return null}}function J0(r){try{if(!r)return{excludeResolved:!1,unlockedDocumentKey:null};let{lazyLoadResolvedComments:o,hasResolvedIntent:n,currentDocumentKey:e}=r;if(!e)return{excludeResolved:!1,unlockedDocumentKey:r.unlockedDocumentKey??null};let t=r.unlockedDocumentKey??null,a=n?e:t===e?t:null;return{excludeResolved:!!o&&!(a===e),unlockedDocumentKey:a}}catch{return{excludeResolved:!1,unlockedDocumentKey:null}}}function Y0(r,o){if(r==null&&o==null)return!0;if(r==null||o==null)return!1;let n=new Set(r),e=new Set(o);if(n.size!==e.size)return!1;for(let t of n)if(!e.has(t))return!1;return!0}function K0(r){try{return r?Object.entries(r).filter(([,o])=>o?.type!=="terminal").map(([o,n])=>n?.id??o).filter(o=>!!o):[]}catch{return[]}}function q0(r){try{return r?Object.entries(r).filter(([,o])=>o?.type==="terminal").map(([o,n])=>n?.id??o).filter(o=>!!o):[]}catch{return[]}}function _D(r){try{if(!r)return 0;let o=0;return r.hasApiKeyClause&&o++,r.hasOrganizationIdClause&&o++,(r.documentIdCount??0)>0&&o++,(r.accessFieldCount??0)>0&&o++,(r.locationIdCount??0)>0&&o++,r.hasFolderClause&&o++,(r.nonTerminalStatusCount??0)>0&&o++,o}catch{return 0}}function Z0(r){return{documentIdCount:r?.documentIdCount??0,accessFieldCount:r?.accessFieldCount??0,locationIdCount:r?.locationIdCount??0,nonTerminalStatusCount:r?.nonTerminalStatusCount??0,terminalStatusCount:r?.terminalStatusCount??0,hasApiKeyClause:!0,hasOrganizationIdClause:!0,hasFolderClause:!!r?.hasFolderClause,orderByCount:r?.orderByCount??0}}function Q0(r){let o=r?.maxDocumentBatchSize??0,n=(e,t=0,a=0,i="none")=>({applyStatusClause:!1,documentBatchSize:o,projectedDisjunctions:t,projectedFilterSum:a,boundBy:i,reason:e});try{if(o<1)return n("dropped-no-non-terminal-statuses");let e=r?.clauses;if(!e)return n("dropped-no-non-terminal-statuses");let t=e.nonTerminalStatusCount??0;if(t<=0)return n("dropped-no-non-terminal-statuses");if((e.terminalStatusCount??0)<=0)return n("dropped-no-terminal-statuses");let a=(e.documentIdCount??0)>0?e:b(g({},e),{documentIdCount:o}),i=_D(a),d=Math.max(1,e.accessFieldCount??0),m=Math.max(1,e.locationIdCount??0),u=e.orderByCount??0,f=a.documentIdCount,y=le=>Math.min(le,f),S=le=>y(le)*d*m*t,j=le=>le*i+u+1,W=S(o),$=j(W),H=W>30,q=$>100,ce=H&&q?"both":H?"disjunctions":q?"filter-sum":"none",fe=r?.minDocumentBatchSize??o;for(let le=o;le>=fe;le--){let he=S(le),xe=j(he);if(he<=30&&xe<=100)return{applyStatusClause:!0,documentBatchSize:le,projectedDisjunctions:he,projectedFilterSum:xe,boundBy:ce,reason:le===o?"fits":"fits-after-shrink"}}return n("dropped-over-budget",W,$,ce)}catch{return n("dropped-over-budget")}}var X0="Processing\u2026";function Lh(r){try{return r?!!(typeof r.commentText=="string"&&r.commentText.trim().length>0||typeof r.commentHtml=="string"&&r.commentHtml.trim().length>0||typeof r.commentVoiceUrl=="string"&&r.commentVoiceUrl.trim().length>0||Array.isArray(r.attachments)&&r.attachments.length>0||Array.isArray(r.recorders)&&r.recorders.length>0):!1}catch{return!1}}function Bh(r){try{return!!r?.progress}catch{return!1}}function Vh(r){try{return Bh(r)&&!Lh(r)}catch{return!1}}function $h(r){try{let o=r?.comments;if(!Array.isArray(o))return{comments:[],progress:[]};let n=[],e=[];return o.forEach(t=>(Vh(t)?e:n).push(t)),{comments:n,progress:e}}catch{return{comments:r?.comments??[],progress:[]}}}function SD(r){try{let o=Number(r);return!Number.isFinite(o)||o<=0?6e5:o}catch{return 6e5}}function Uh(r){try{if(r==null)return null;if(typeof r=="number")return Number.isFinite(r)?r:null;if(r instanceof Date)return r.getTime();if(typeof r?.toMillis=="function")return r.toMillis();if(typeof r?.seconds=="number")return r.seconds*1e3;let o=new Date(r).getTime();return Number.isNaN(o)?null:o}catch{return null}}function yD(r,o,n){try{let e=Uh(r?.lastUpdated);return e==null?!1:n-e>SD(o)}catch{return!1}}function lp(r,o,n){try{return r?.progress?.state!=="active"?!1:!yD(r,o,n)}catch{return!1}}function ek(r){try{let o=r?.progress?.steps;if(Array.isArray(o)&&o.length>0){let n=o[o.length-1];for(let t=o.length-1;t>=0;t--)if(o[t]?.state==="active"){n=o[t];break}let e=n?.label;if(typeof e=="string"&&e.trim().length>0)return{kind:"literal",text:e}}return{kind:"i18nKey",key:X0}}catch{return{kind:"i18nKey",key:X0}}}function tk(r){try{return Array.isArray(r)?r.slice().sort((o,n)=>(Uh(o?.createdAt)??0)-(Uh(n?.createdAt)??0)):[]}catch{return Array.isArray(r)?r.slice():[]}}var rk=r=>!!(r?.userId||r?.email),ID=(r,o)=>r?.userId&&o?.userId?r.userId===o.userId:r?.email&&o?.email?r.email===o.email:!1;function to(r,o,n){try{return o==null?rk(r):rk(o)&&!ID(r,o)}catch(e){try{n?.(e)}catch{}return!1}}function rr(r){return r?.isDocumentLevel===!0&&!r?.targetTextRange}function ro(r,o){return r?o?.length?r.filter(n=>rr(n)||!n?.location?.id?!0:!o.includes(n.location.id)):r:[]}function Lm(r,o){return r?.location?.id===o||rr(r)}var wD=new Set(["cfXPath","fXPath","parent+tag","contentHash"]);function dp(r){return r?wD.has(r.replace(/\+position$/,"")):!1}var St=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new De(Z.CommentAnnotationStatusMap),this._customPriorityMap=new De(Z.CommentAnnotationPriorityMap),this._customCategoryMap=new De(Z.CommentCategoryMap),this.isLazyLoadResolvedCommentsEnabled=null;try{let t=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let a=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);a&&this._customStatusMap.next(JSON.parse(a));let i=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);i&&this._customCategoryMap.next(JSON.parse(i))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(Z.CommentAnnotationStatusMap),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(Z.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(a=>{t[a.id]=a,a.type||(a.type="ongoing")}),this.warnOnDroppedStatusIds(t),this._customStatusMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}warnOnDroppedStatusIds(e){try{let t=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);if(!t)return;let a=JSON.parse(t),i=Object.keys(a??{});if(!i.length)return;let d=new Set(Object.keys(e??{})),m=i.filter(u=>!d.has(u));if(!m.length||!this.isLazyLoadResolvedCommentsEnabled?.())return;this.loggingService.catch(`[lazyLoadResolvedComments] status catalog dropped ${m.length} id(s): ${m.join(", ")}. Comments still carrying them will NOT be fetched while lazyLoadResolvedComments is enabled \u2014 migrate those annotations to the new ids, or keep the retired ids in the catalog.`,void 0,void 0,!0)}catch(t){this.loggingService.catch("Error in CustomFilterService warnOnDroppedStatusIds: ",t)}}setLazyLoadResolvedCommentsProvider(e){this.isLazyLoadResolvedCommentsEnabled=e}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(Z.CommentAnnotationPriorityMap),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(Z.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(a=>{t[a.id]=a}),this._customPriorityMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(a=>{t[a.id]=a}),this._customCategoryMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([a,i])=>i.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return Z.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([a,i])=>i.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return Z.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([a,i])=>i.type==="ongoing");if(t)return t.map(a=>a[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[Z.CommentAnnotationStatusMap.IN_PROGRESS]}get terminalStatuses(){try{return Object.entries(this._customStatusMap.value).filter(([t,a])=>a.type==="terminal").map(t=>t[1])}catch(e){this.loggingService.catch("Error in CustomFilterService terminalStatuses: ",e)}return[]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),a=t.find(([i,d])=>d.type==="default");switch(e.status){case"open":a&&(e.status=a[1]);break;case"inProgress":let i=t.find(([m,u])=>u.type==="ongoing");i&&(e.status=i[1]);break;case"resolved":let d=t.find(([m,u])=>u.type==="terminal");d&&(e.status=d[1]);break;default:a&&(e.status=a[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=Z.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(t=>Z.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var nk=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new Lt;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(ub()),this.domService.onWindowKeydown$().subscribe(a=>{this.keyEventSubject$.next(a)})}catch(a){this.loggingService.catch("Error in HotkeyService constructor: ",a)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe(qt(a=>a?.key===e),qt(a=>!(!!t?.includeCtrl!==a.ctrlKey||!!t?.includeAlt!==a.altKey||!!t?.includeShift!==a.shiftKey||!!t?.includeMeta!==a.metaKey)),qt(()=>this.isNoInputFocused()))}catch(a){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",a),new ac}}isNoInputFocused(){try{let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e.parentElement??e.getRootNode()?.host??null}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(be(Re),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var OD=["access","accessFields"];function MD(r,o){return!o||!r?.data||typeof r.data!="object"?r:b(g({},r),{data:Object.fromEntries(Object.entries(r.data).filter(([,n])=>n?.metadata?.veltFolderId===o))})}function AD(r){try{let o=Object.entries(r?.data??{});if(o.length<2)return r;o.sort(([,e],[,t])=>G0(e,t));let n={};for(let[e,t]of o)n[e]=t;return b(g({},r),{data:n})}catch{return r}}function PD(r){return r?Object.keys(r).length>0:!1}var FD=[Z.TAGS.VELT_COMMENT_THREAD,Z.TAGS.VELT_COMMENTS_SIDEBAR_V2,Z.TAGS.VELT_COMMENTS_SIDEBAR,Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR,Z.TAGS.VELT_INLINE_COMMENTS_SECTION,Z.TAGS.VELT_COMMENT_COMPOSER,Z.TAGS.VELT_MULTI_THREAD_COMMENT_DIALOG];function ND(r){try{let o=(r||[]).map(e=>String(e?.tagName||"").toLowerCase());return o.some(e=>e===Z.TAGS.VELT_COMMENT_DIALOG||e===Z.TAGS.SNIPPYLY_COMMENT_DIALOG)?!o.some(e=>FD.includes(e)):!1}catch{return!1}}function RD(r){try{if(!ND(r))return null;let o=r||[];if(o.some(e=>{let t=String(e?.tagName||"").toLowerCase();return t==="textarea"||t==="input"?!!String(e.value??"").trim():e?.isContentEditable===!0&&!!String(e.textContent??"").trim()}))return null;for(let e of o){let t=String(e?.tagName||"").toLowerCase();if(t!==Z.TAGS.VELT_COMMENT_DIALOG&&t!==Z.TAGS.SNIPPYLY_COMMENT_DIALOG)continue;let a=e.getAttribute?.("data-velt-dialog-annotation-id");if(a)return a}return null}catch{return null}}function UD(r){return r.insideManualCommentContainer?!1:r.commentPlaced?!0:!(r.clickConsumedByVeltSurface||r.draftDialogOpen)}var LD=new Set(["position","ghostComment","targetElement"]);function jh(r){if(r?.annotationId)return`pin:${r.annotationId}:${r.metadata?.documentId??""}`}var ae=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y,S,j,W,$,H,q,ce,fe,le,he,xe,ze,Ze,He,Xe){this.analyticsService=e,this.commonDbService=t,this.configService=a,this.docService=i,this.databaseService=d,this.authService=m,this.domService=u,this.afAuth=f,this.avatarService=y,this.contactService=S,this.storageService=j,this.functions=W,this.dialog=$,this.iamService=H,this.loggingService=q,this.notificationService=ce,this.customFilterService=fe,this.hotkeyService=le,this.serviceBook=he,this.buttonService=xe,this.metadataService=ze,this.commonDbUtilsService=Ze,this.attachmentResolverService=He,this.userPermissionService=Xe,this.endpointsService=ge(HC),this.customPinsById=new Map,this.commentAdded$=new Lt,this.commentUpdated$=new Lt,this.commentAccepted$=new Lt,this.commentRejected$=new Lt,this.commentAnnotationDeleted$=new Lt,this.multiThreadCommentAnnotationDeleted$=new Lt,this.commentAnnotationById$=new De(null),this.multiThreadCommentAnnotationById$=new De(null),this.lastRichTextEditorBlockLogKey=null,this.ghostCommentAnnotationMap$=new De({}),this.unreadCommentsMap$=new De(null),this.documentPaths=null,this.user=null,this.customCategoryMap=Z.CommentCategoryMap,this.allowedElementIds$=new De([]),this.allowedElementClassNames$=new De([]),this.allowedElementQuerySelectors$=new De([]),this.addCommentMode$=new De(!1),this.persistentCommentMode$=new De(!1),this.seenByUsers$=new De(!0),this.deleteReplyConfirmation$=new De(!1),this.persistentModeBanner$=new De(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new De(!0),this.sidebarVisible$=new De(!1),this.sidebarFocusRequest$=new De(null),this.sidebarOpenedByCustomTrigger$=new De(!1),this.floatingCommentsEnabled$=new De(!0),this.moderatorMode$=new De(!1),this.streamMode$=new De(!1),this.enableSignInButton$=new De(!1),this.enableUpgradeButton$=new De(!1),this.onSignInClick$=new Lt,this.onUpgradeClick$=new Lt,this.enableAttachment$=new De(!0),this.enableAttachmentDownload$=new De(!0),this.enableReactions$=new De(!0),this.enableAnonymousEmail$=new De(!0),this.enableFormatOptions$=new De(!1),this.formatConfig$=new De({bold:{enable:!0},italic:{enable:!0},underline:{enable:!0},strikethrough:{enable:!0}}),this.allowedRecordings$=new De(["audio","video","screen"]),this.openSidebar$=new Lt,this.showScreenSizeInfo$=new De(!1),this.showCommentIndex$=new De(!1),this.popoverMode$=new De(!1),this.popoverTriangleComponent$=new De(!0),this.draftMode$=new De(!0),this.draftConfirmation$=new De(!1),this.idScopedAnchoring$=new De(!1),this.idScopedAnchoringConfig$=new De({enabled:!1,documentIds:null}),this.idScopedAnchoringScope=null,this.loggedHiddenDocumentLevelPins=null,this.idScopedAnchoringVersion=0,this.draftConfirmationPendingAnnotationIds=new Set,this.enableDialogOnHover$=new De(!0),this.enableDialogOnTargetElementClick$=new De(!1),this.enablePriority$=new De(!1),this.enableStatus$=new De(!0),this.visibilityOptions$=new De(!1),this.enableResolve$=new De(!0),this.enableGhostComments$=new De(!1),this.enableGhostCommentsMessage$=new De(!0),this.inboxMode$=new De(!1),this.enableAutoCategorize$=new De(!1),this.commentContainerDarkMode$=new De(!1),this.suggestionMode$=new De(!1),this.mobileMode$=new De(!0),this.inlineCommentMode$=new De(!1),this.minimap$=new De(!1),this.commentsOnDom$=new De(!0),this.commentToolEnabled$=new De(!0),this.totalMediaLength$=new De(0),this.sidebarUrlNavigationEnabled$=new De(!1),this.detectionStrategy$=new De(xh.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new De(!1),this.sidebarButtonOnCommentDialogClick$=new Lt,this.commentNavigationButtonClick$=new Lt,this.deviceIndicatorOnCommentPins$=new De(!1),this.sidebarCommentClick$=new Lt,this.privateCommentMode$=new De(!1),this.privateCommentAllowed$=new De(!1),this.privateCommentModeRequested=!1,this.privateModeConfig$=new De(null),this.scrollToComment$=new De(!0),this.userMentions$=new De(!0),this.paginatedContactList$=new De(Z.PAGINATED_CONTACT_LIST_DEFAULT),this.deleteOnBackspace$=new De(!0),this.hotkeyEnabled$=new De(!1),this.recordingSummaryEnabled$=new De(!0),this.unreadIndicatorMode$=new De(uc.MINIMAL),this.composerMode$=new De(dC.DEFAULT),this.enterKeyToSubmit$=new De(!1),this.resolvedCommentsOnDom$=new De(!1),this.lazyLoadResolvedComments$=new De(!1),this.resolvedIntentFromSidebar$=new De(!1),this.resolvedUnlockedDocumentKey=null,this.lastQueryClauseDescriptor=null,this.bubbleOnPinEnabled$=new De(!1),this.bubbleOnPinHoverEnabled$=new De(!0),this.pinDragEnabled$=new De(!0),this.excludeLocationIdsFromSidebar$=new De([]),this.multiThread$=new De(!1),this.groupMatchedComments$=new De(!1),this.restrictTextSearchToAnchor$=new De(!1),this.shortUserName$=new De(!0),this.collapsedComments$=new De(!1),this.collapsedRepliesPreview$=new De(!1),this.fullExpanded$=new De(!1),this.queryParamsComments$=new De(!1),this.resolveStatusAccessAdminOnly$=new De(!1),this.linkCallback$=new De(!1),this.svgAsImg$=new De(!1),this.commentToNearestAllowedElement$=new De(!1),this.filterCommentsOnDom$=new De(!1),this.maxReplyAvatars$=new De(3),this.commentProgressStaleAfter$=new De(6e5),this.progressCommentsByAnnotationId=new Map,this.progressOnlyAnnotationsLogged=new Set,this.progressCommentsVersion$=new De(0),this.replyAvatars$=new De(!1),this.commentplaceholder$=new De(void 0),this.replyplaceholder$=new De(void 0),this.editplaceholder$=new De(void 0),this.editcommentplaceholder$=new De(void 0),this.editreplyplaceholder$=new De(void 0),this.screenshotEnabled$=new De(!1),this.pinShadowDOM$=new De(!0),this.dialogShadowDOM$=new De(!0),this.dialogShadowDOMExplicit$=new De(void 0),this.textCommentToolShadowDOM$=new De(!0),this.pinDarkMode$=new De(null),this.textCommentToolDarkMode$=new De(null),this.textCommentToolbarDarkMode$=new De(null),this.textCommentToolbarShadowDOM$=new De(!0),this.sidebarShadowDOM$=new De(!0),this.changeDetectionInCommentMode$=new De(!1),this.commentSelectionChange$=new Lt,this.visibilityOptionClicked$=new Lt,this.submitComment$=new Lt,this.clearComposer$=new Lt,this.composerDataMap=new Map,this.commentsFromSidebarMap$=new De(null),this.sidebarButtonCountType$=new De("default"),this.filterGhostCommentsInSidebar$=new De(!1),this.commentSidebarFilters$=new De(null),this.effectiveSidebarFilters$=new De({}),this.customSidebarDataAnnotationIds$=new De(null),this.commentSidebarSystemFiltersOperator$=new De(Kr.AND),this.bubbleCommentAnnotationIds$=new De([]),this.updateCommentDialogPositionTriggerSubject$=new De(void 0),this.areaCommentEnabled$=new De(!0),this.commentPinCursorImage$=new De(""),this.commentAnnotationsFromCommentsContainer$=new De([]),this.customChipDropdownData$=new De(null),this.originalCommentAnnotationsByDocumentId$=new De({}),this.draftCommentAnnotationsByAnnotationId$=new De(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new De({}),this.pendingAddCommentAnnotationData=new Map,this.copyLink$=new De(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new De(null),this.sidebarCustomActionEventData$=new De(null),this.sidebarCustomActionEventDataAllChanges$=new De(null),this.sidebarCustomActionEventDataOnInit$=new De(null),this.customActions$=new De(!1),this.focusedThreadMode$=new De(!1),this.openAnnotationInFocusMode$=new De(!1),this.customStatusesShown$=new De(!1),this.readOnly$=new De(!1),this.customAutocompleteSearch$=new De(!1),this.deleteThreadWithFirstComment$=new De(!0),this.assignToType$=new De("dropdown"),this.pageModeComposerContext$=new De(null),this.contextInPageModeComposer$=new De(!1),this.focusPageModeComposer$=new Lt,this.transformContext$=new De(null),this.expandMentionGroups$=new De(!1),this.showMentionGroupsFirst$=new De(!1),this.showMentionGroupsOnly$=new De(!1),this.fullScreenInSidebar$=new De(!1),this.composerFileAttachments$=new De(null),this.attachmentNameInMessage$=new De(!1),this.allowedFileTypes$=new De([]),this.forceCloseAllOnEsc$=new De(!1),this.autoCompleteScrollConfig$=new De({itemSize:55,minBufferPx:350,maxBufferPx:600,templateCacheSize:350}),this.commentAnnotationContextDraft=null,this.reactionService=null,this.areaService=null,this.viewsService=null,this.sharedCommentData=new Map,this.unreadMapComputedFor=new WeakMap,this.defaultSidebarResolvedIntent=!1,this.namedSidebarResolvedIntents=new Map,this.multiThreadReadUnansweredLogged=!1,this.multiThreadUnservedLogged=!1,this.getCommentAnnotationForClient=Oe=>{try{let Qe=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource","involvedUserIds","mentionedUserIds","viewedByUserIds","views"],Ke=JSON.parse(JSON.stringify(Oe)),xt={};Object.keys(Ke).forEach(Ot=>{Qe.includes(Ot)||(xt[Ot]=Ke[Ot])}),xt?.comments?.forEach(Ot=>{let Je=[];Ot?.reactionAnnotationIds&&Ot?.reactionAnnotationIds?.forEach(wm=>{let eu=this.reactionService?.getAnnotationById(wm);if(eu){let Dm=this.reactionService.getReactionAnnotationForClient(eu);Je.push(Dm)}}),Ot.reactionAnnotations=Je}),Ke?.viewedByUserIds?.forEach(Ot=>{let Je=this.contactService.getUserBySnippylyId(Ot);Je&&(xt.viewedBy||(xt.viewedBy=[]),xt.viewedBy.push(Je))}),this.user?.userSnippylyId&&(xt.unread=!Ke?.viewedByUserIds?.includes(this.user.userSnippylyId));let Ue=Ke?.targetElement?.anchor?.fXPath||Ke?.targetElement?.fXpath;return Ue&&(xt.basicAnchorData={xpath:Ue,topPercentage:Ke?.targetElement?.topPercentage||0,leftPercentage:Ke?.targetElement?.leftPercentage||0}),JSON.parse(JSON.stringify(xt))}catch{return null}},this.loggingService.log("%c[WB] Creating CLASS: CommentService","color: blue;"),this.serviceBook.set($u,this),this.serviceBook.observe(ju).subscribe(Oe=>{this.reactionService=Oe}),this.serviceBook.observe(zC).subscribe(Oe=>{this.areaService=Oe}),this.serviceBook.observe(Xo).subscribe(Oe=>{this.viewsService=Oe}),this.domService.getSelectedAnnotationsMap$().pipe(po(100),zn()).subscribe(([Oe,Qe])=>{try{if(this.draftCommentAnnotationsByAnnotationId$.value){let Ke=Object.keys(this.draftCommentAnnotationsByAnnotationId$.value||{}),xt=[];Object.keys(Oe||{}).forEach(Ot=>{if(!Qe?.[Ot]&&Ke.includes(Ot)){if(this.draftConfirmationPendingAnnotationIds?.has(Ot))return;xt.push(Ot)}});let Ue=JSON.parse(JSON.stringify(this.draftCommentAnnotationsByAnnotationId$.value||{}));xt.forEach(Ot=>{delete Ue[Ot]}),xn(Ue,this.draftCommentAnnotationsByAnnotationId$.value)||this.draftCommentAnnotationsByAnnotationId$.next(Ue)}}catch{}}),this.docService.getDocumentPaths$().pipe(zn()).subscribe(([Oe,Qe])=>{Oe?.documentId!==Qe?.documentId&&this.unreadCommentsMap$.next(null),Qe&&this.shouldEnableReadOnly()},Oe=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",Oe)}),this.draftCommentAnnotationsByAnnotationId$.pipe(zn()).subscribe(([Oe,Qe])=>{try{if(this.pendingAddCommentAnnotationData.size===0)return;let Ke=Object.keys(Oe||{});if(Ke.length===0)return;let xt=new Set(Object.keys(Qe||{}));Ke.forEach(Ue=>{!xt.has(Ue)&&this.pendingAddCommentAnnotationData.has(Ue)&&this.pendingAddCommentAnnotationData.delete(Ue)})}catch(Ke){this.loggingService.catch("Error in CommentService pendingAddCommentAnnotationData reconcile: ",Ke)}}),this.authService.getUser$().subscribe(Oe=>{Oe||this.resetCacheData()},Oe=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",Oe)}),this.authService.getUser$().pipe(Fe(Oe=>Oe?Bt([this.iamService.isUserAdmin$(),this.contactService.getUserOrganizationContacts$()]).pipe(Ee(([Qe,Ke])=>{let xt=!1;return Ke?.find(Ue=>Ue.userId===Oe?.userId)&&(xt=!0),{isUserAdmin:Qe,isOrgUser:xt}})):ye({isUserAdmin:!1,isOrgUser:!1}))).subscribe(({isUserAdmin:Oe,isOrgUser:Qe})=>{let Ke=Oe||Qe;Ke!==this.privateCommentAllowed$.value&&this.privateCommentAllowed$.next(Ke),Ke&&this.applyRequestedPrivateCommentMode()}),this.commentDbReadyGate$().pipe(qo(1)).subscribe(()=>{this.getDocumentPaths()},Oe=>{this.loggingService.catch("Error in CommentService getDb subscription: ",Oe)}),this.domService.onWindowPointerMove$().subscribe(Oe=>{if(this.addCommentMode$.value){let Qe=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let Ke=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY,!0,!0);if(Ke&&PC(Ke,{x:Oe.clientX,y:Oe.clientY})&&(Ke=Ke?.parentElement),Ke)if(this.isElementInsideAllowedElements(Ke))if(!this.isCommentBlockedOnElement(Oe.target)&&!Dr(Ke)){this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==Ke&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=Ke;let xt=this.domService.getSelectedAnnotationsMap("comment")||{},Ue=this.commentPinCursorImage$.value||Z.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,Ue,!!Object.keys(xt)?.length),Qe=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor");else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&Qe&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},Oe=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",Oe)}),this.domService.onWindowKeyupEsc$().subscribe(Oe=>{if(this.addCommentMode$.value){let Qe=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(Qe)?.length&&this.domService.resetSelectedAnnotationsMap(),this.disableAddCommentMode()}},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",Oe)}),this.domService.onDocumentClick$().subscribe(Oe=>{if(Oe&&!Nu(Oe)){let Qe=this.domService.getSelectedAnnotationsMap("comment")||{};if(Qe=g(g({},Qe),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Qe=g(g({},Qe),this.domService.getSelectedAnnotationsMap("suggestion")||{}),Object.keys(Qe)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),Oe.preventDefault(),Oe.stopPropagation();return}}if(Oe&&this.addCommentMode$.value){let Qe=!this.addCommentDragMode&&this.isCommentModeClickInsideRichTextEditor(Oe);if(Qe&&!Am(Oe.target)&&this.detectToAddAreaComment(),!Am(Oe.target)&&!Qe){let Ke=!1,xt=!1,Ue=!1,Ot=!1;if(this.addCommentDragMode)Oe.preventDefault(),Oe.stopPropagation(),this.addCommentDragMode=!1,xt=!0;else if(Ot=!!this.domService.getDraftCommentAnnotationDialogs()?.length,!Ot){let Je=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);if(this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(Oe.clientX,Oe.clientY)?Je=null:Oe&&Nu(Oe)&&(Je=null,Ue=!0),Je&&(this.isElementInsideAllowedElements(Je)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(Je))&&(Ke=this.isElementInsideManualCommentContainer(Je),!Ke)){Oe.preventDefault(),Oe.stopPropagation();let wm=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(Oe,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,wm),xt=!0}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():UD({insideManualCommentContainer:Ke,commentPlaced:xt,clickConsumedByVeltSurface:Ue,draftDialogOpen:Ot})&&this.disableAddCommentMode()}}},Oe=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",Oe)}),this.watchDocumentChangesForSidebarFocus(this.docService.getDocumentIds$()),this.domService.onWindowKeydown$().subscribe(Oe=>{try{if(Oe?.key!=="Escape"||Oe?.isComposing===!0)return;if(this.forceCloseAllOnEsc$.value!==!0){if(Oe?.defaultPrevented&&!W0(Oe))return;let Qe=RD(Oe?.composedPath?.());if(!Qe||this.getProgressComments(Qe)?.length)return;this.domService.discardEmptyDraftAnnotation(Qe)&&this.addCommentMode$.value&&this.disableAddCommentMode();return}if(Oe?.defaultPrevented)return;this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(Qe){this.loggingService.catch("Error in CommentService forceCloseAllOnEsc subscription: ",Qe)}},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeydown$ subscription: ",Oe)}),this.addCommentMode$.subscribe(Oe=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),Oe?(this.domService.addClassToElement(document.body,"snippyly-add-comment-mode"),this.detectToAddAreaComment(),this.addIframeContainerStaticAttribute()):(this.removeIframeContainerStaticAttribute(),this.domService.removeClassFromElement(document.body,"snippyly-add-comment-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"),this.dragSubscriptions.forEach(Qe=>Qe.unsubscribe()),this.clearFreeStyleCommentContext())},Oe=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",Oe)}),this.domService.onWindowKeyupBackspace$().subscribe(Oe=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",Oe)}),this.domService.onWindowKeyupDelete$().subscribe(Oe=>{this.deleteCommentPinAnnotations("keyupDelete")},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Oe)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Oe=>{Oe?.length&&(Oe?.filter(Ke=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(Ke.type))?.filter(Ke=>!this.getProgressComments(Ke?.annotationId).length)).forEach(Ke=>Pe(this,null,function*(){yield this.deleteCommentPinAnnotation(Ke)}))},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Oe)}),this.getPopoverMode$().subscribe(Oe=>{Oe?document?.body?.setAttribute(Z.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(Z.ATTRIBUTES.VELT_POPOVER_MODE)},Oe=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",Oe)}),this.customFilterService.customCategoryMap$.subscribe(Oe=>{this.customCategoryMap=Oe},Oe=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",Oe)}),this.hotkeyEnabled$.subscribe(Oe=>{Oe?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},Oe=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",Oe)}),this.domService.getSelectedAnnotationsMap$().pipe(zn()).subscribe(([Oe,Qe])=>{try{let Ke=Object.values(Oe||{}).filter(Ue=>!["tag","recorder","rewriter","arrow","area"].includes(Ue.type)),xt=Object.values(Qe||{}).filter(Ue=>!["tag","recorder","rewriter","arrow","area"].includes(Ue.type));Ke?.forEach(Ue=>{xt?.find(Ot=>Ot.annotationId===Ue.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(Ue),selected:!1})}),xt?.forEach(Ue=>{Ke?.find(Ot=>Ot.annotationId===Ue.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(Ue),selected:!0})})}catch(Ke){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",Ke)}},Oe=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",Oe)})}clearCache(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in CommentService","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear(),this.customAutocompleteSearch$.next(!1),this.hightlightElement=null,this.addCommentMode$.next(!1),this.unreadCommentsMap$.next(null),this.documentPaths=null,this.commentsFromSidebarMap$.next(null),this.customSidebarDataAnnotationIds$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService?.getAreaEnabled()??!1,t=this.getAreaCommentEnabled();if(e&&t){let a,i,d,m=null,u=null;this.dragSubscriptions.forEach(f=>f.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(qt(f=>!(f&&Nu(f))),qo(1)).subscribe(f=>{m=null,u=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(y=>{if(m===null){let S=y?.startPoint?.event?.target,j=Mm(S),W=this.isCommentBlockedOnElement(S),$=this.isElementInsideAllowedElements(S);m=!j&&!W&&$}if(m){this.addCommentDragMode=!0,a=y.startPoint,i=y.curPoint;let S=y?.curPoint?.event?.target,j=Mm(S),W=this.isCommentBlockedOnElement(S),$=this.isElementInsideAllowedElements(S);u=!j&&!W&&$,u?d=this.domService.drawRectangle(a,i):d?.remove()}})),this.domService.onWindowPointerUp$().pipe(Dn(1),qo(1)).subscribe(y=>{if(i={x:y.clientX,y:y.clientY},a&&i&&(d?.remove(),m&&u)){let S=[{x:a.x-window.scrollX,y:a.y-window.scrollY},{x:i.x,y:i.y}],j=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(y,void 0,S,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,j)}this.dragSubscriptions.forEach(S=>S.unsubscribe())})}))}}catch(e){this.loggingService.catch("Error in CommentService detectToAddAreaComment: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: resetCacheData","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear()}catch(e){this.loggingService.catch("Error in CommentService resetCacheData: ",e)}}addAreaContainerTag(){try{if(!(document.querySelector(Z.TAGS.VELT_AREAS)||document.querySelector(Z.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(Z.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${Z.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC)})}catch(e){this.loggingService.catch("Error in CommentService removeIframeContainerStaticAttribute: ",e)}}subscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: subscribeHotkeyEvents","color: green;"),this.unsubscribeHotkeyEvents(),this.hotkeySubscriptions.push(this.hotkeyService.getKeyPressEvent("c").subscribe(e=>{e&&!this.addCommentMode$.value&&this.enableAddCommentMode()},e=>{this.loggingService.catch("Error in CommentService hotkeyService.getKeyPressEvent subscription: ",e)}))}catch(e){this.loggingService.catch("Error in CommentService subscribeHotkeyEvents: ",e)}}unsubscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeHotkeyEvents","color: green;"),this.hotkeySubscriptions.forEach(e=>e?.unsubscribe())}catch(e){this.loggingService.catch("Error in CommentService unsubscribeHotkeyEvents: ",e)}}setCommentAddedEmitter(e){try{this.commentAddedEmitter=e}catch(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}commentDbReadyGate$(){return QC({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(Hu),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in CommentService commentDbReadyGate$ ${e}: `,t)})}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementIds:e}}),this.allowedElementIds$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:a,detectGhostComments:i,skipPositionCalculation:d,query:m,fromCommentSidebar:u,analytics:f,addFilterCommentsOnDomCheck:y}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let S,j,W;f?.enabled&&this.analyticsService.trackEvent(f?.eventName||oe.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,f?.properties);try{if(e&&(W=`${Qo(e)}`),t&&typeof t=="object"){let $=yh(t);j=$?.id,S=Qo(JSON.stringify($))}}catch($){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",$)}return Ko(ye(null),new ac($=>Gu(()=>$.next(null)))).pipe(Fe(()=>this.authService.getAuthState$()),qt($=>!!$),Fe($=>this.isFeatureAllowed({firebaseUser:$,annotations:[],filteredAnnotations:[]})),Fe($=>$.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(H=>($.featureAllowed=H,$))):ye($)),Fe($=>$.featureAllowed?ye($).pipe(Fe(H=>this.docService.getDocumentPaths$().pipe(Ee(q=>(this.documentPaths=q,H.documentPaths=q,H)))),Fe(H=>m?.documentIds?.length||W?this.getDataFromDocumentIds({documentIds:W?[W]:m?.documentIds?.map(q=>`${Qo(q)}`),organizationId:this.documentPaths?.organizationId,query:m}).pipe(Ee(q=>({res:H,data:q}))):this.docService.getDocumentIds$().pipe(Fe(q=>{let ce=q?.length>0?q.map(fe=>fe.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ce.length>0?ce:[W??""],organizationId:this.documentPaths?.organizationId,query:m}).pipe(Ee(fe=>({res:H,data:fe})))}))),Fe(H=>H?.data?(H.res.annotations=H.data||[],ye(H.res).pipe(Fe(q=>this.docService.getLocation$().pipe(Ee(ce=>(q.location=ce,q)))),Fe(q=>this.docService.getLocations$().pipe(Ee(ce=>(q.customLocations=ce,q)))),Fe(q=>this.docService.getExcludedLocationIds$().pipe(Ee(ce=>(q.excludedLocationIds=ce,q)))),Ee(q=>this.applyPageLocationFilters(q,{query:m,customInternalDocumentId:W,customLocationId:S,customClientLocationId:j,fromCommentSidebar:u})),Fe(q=>this.isPrivateCommentAllowed$().pipe(Ee(ce=>(ce||(q.filteredAnnotations=q.filteredAnnotations?.filter(fe=>!br(fe))),q)))),Fe(q=>this.draftCommentAnnotationsByAnnotationId$.pipe(Ee(ce=>(q.dataGeneration=(q.dataGeneration??0)+1,q.filteredAnnotations=q.filteredAnnotations?.filter(fe=>!fe.isDraft),ce&&q.filteredAnnotations.push(...Object.values(ce)),q)))),Fe(q=>{if(a)return ye(q);{let ce=q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$():null;return this.withIdScopedAnchoringChanges(ce,d).pipe(Ee(()=>q))}}),Fe(q=>a?ye(q):this.addCommentMode$.pipe(Fe(ce=>ce&&!this.getChangeDetectionInCommentMode()?ye(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(Ee(()=>q)):ye(q)))),Ee(q=>(d||this.domService.runPositionPass(()=>{(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(q.filteredAnnotations=q.filteredAnnotations?.map(fe=>{let le=Object.assign({},fe);return this.calculateCommentAnnotationPosition(le,i),le}));let ce={};q.filteredAnnotations?.forEach(fe=>{if(fe?.targetTextRange){let le=this.domService.getElementFromTargetTextRange(fe?.targetTextRange);ce[fe.annotationId]=!!le}}),q.textAnnotationsElementMap=ce}),q)),Fe(q=>q?.annotations?.length?this.serviceBook.observe(Xo).pipe(Fe(ce=>ce?ce.getCommentFeatureViews$():ye({})),Ee(ce=>(this.unreadMapComputedFor.get(q.annotations)!==ce&&(this.unreadMapComputedFor.set(q.annotations,ce),this.updateUnreadAnnotationsMap(q?.annotations,ce)),q))):(PD(this.unreadCommentsMap$.value)&&this.unreadCommentsMap$.next({}),ye(q))))):ye(null))):ye(null)),this.jsonSnapshotUnlessIdScopedAnchoringChanged($=>typeof $=="object"&&$?{filteredAnnotations:$.filteredAnnotations,textAnnotationsElementMap:$.textAnnotationsElementMap}:$),Fe($=>$?$?.filteredAnnotations?ye($?.filteredAnnotations||[]):ye([]):ye(null)),Fe($=>y?this.filterCommentsUsingSidebarSettings($):ye($)))}getAllMultiThreadCommentAnnotations(e,t,a,i,d,m){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let u,f;try{if(e&&(f=Qo(e)),t&&typeof t=="object"){let y=yh(t);u=Qo(JSON.stringify(y))}}catch(y){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",y)}return this.authService.getAuthState$().pipe(qt(y=>!!y),Fe(y=>this.isFeatureAllowed({firebaseUser:y,annotations:[],filteredAnnotations:[]})),Fe(y=>y.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(S=>(y.featureAllowed=S,y))):ye(y)),Fe(y=>y.featureAllowed?ye(y).pipe(Fe(S=>this.docService.getDocumentPaths$().pipe(Ee(j=>(this.documentPaths=j,S.documentPaths=j,S)))),Fe(S=>f?this.getMultiThreadDataFromDocumentIds([f]).pipe(Ee(j=>({res:S,data:j}))):this.docService.getDocumentIds$().pipe(Fe(j=>{let W=j?.length>0?j.map($=>$.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(W.length>0?W:[`${f}`]).pipe(Ee($=>({res:S,data:$})))}))),Fe(({res:S,data:j})=>j?(S.annotations=j||[],ye(S).pipe(Fe(W=>this.docService.getLocation$().pipe(Ee($=>(W.location=$,W)))),Fe(W=>this.docService.getLocations$().pipe(Ee($=>(W.customLocations=$,W)))),Fe(W=>this.docService.getExcludedLocationIds$().pipe(Ee($=>(W.excludedLocationIds=$,W)))),Ee(W=>{if(W.filteredAnnotations=[],f&&!u)return W.filteredAnnotations=W.annotations?.slice(),W?.excludedLocationIds?.length&&(W.filteredAnnotations=W.filteredAnnotations?.filter($=>$?.location?.id?!W.excludedLocationIds.includes($.location.id):!0)),W;{let $=[],H=[];return u?$.push(u):($.push(W?.location?.locationId),$.push(...Object.values(W?.customLocations||[]).map(q=>q.locationId)),W?.location?.location?.id&&H.push(W?.location?.location?.id),H.push(...Object.values(W?.customLocations||{}).map(q=>q.location?.id).filter(q=>!!q))),W.filteredAnnotations=this.filterAnnotationsByLocationIds(W?.annotations,$,H),W?.excludedLocationIds?.length&&(W.filteredAnnotations=W.filteredAnnotations?.filter(q=>q?.location?.id?!W.excludedLocationIds.includes(q.location.id):!0)),W}}),Fe(W=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(Ee($=>(W.filteredAnnotations=W.filteredAnnotations?.filter(H=>!H.isDraft),$&&W.filteredAnnotations.push(...Object.values($)),W)))),Fe(W=>{if(a)return ye(W);{let $=W?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$():null;return this.withIdScopedAnchoringChanges($,d).pipe(Ee(()=>W))}}),Fe(W=>a?ye(W):this.addCommentMode$.pipe(Fe($=>$&&!this.getChangeDetectionInCommentMode()?ye(W):W?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(Ee(()=>W)):ye(W)))),Ee(W=>(d||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(W.filteredAnnotations=W.filteredAnnotations?.map($=>{let H=Object.assign({},$);return this.calculateCommentAnnotationPosition(H,i),H})),W)),Fe(W=>W?.filteredAnnotations?ye(W?.filteredAnnotations||[]):ye([])))):ye(null))):ye(null)),this.distinctUnlessIdScopedAnchoringChanged(Qn),Fe(y=>m?this.filterCommentsUsingSidebarSettings(y):ye(y)))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(qt(t=>!!t),Ee(t=>b(g({},e),{config:t})),Fe(t=>this.authService.getUser$().pipe(Ee(a=>(this.user=a,b(g({},t),{user:a}))))),Fe(t=>uC(t.config,t.user,ke.COMMENT)?ye(b(g({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),ye(b(g({},t),{featureAllowed:!1})))),Gt((t,a)=>t?.featureAllowed===a?.featureAllowed))}buildVisibilityTokens(e){return Pe(this,null,function*(){try{let a=this.authService.getUser()?.clientOrganizationId,i=a?yield this.isViewerOrgMembershipConfirmed(e,a):!1;return _h({userId:e,clientOrganizationId:i?a:void 0,fallbackServerOrganizationId:a?void 0:this.documentPaths?.organizationId})}catch(t){this.loggingService.catch("Error in CommentService buildVisibilityTokens: ",t);try{return[Z.DEFAULT_VELT_CONTEXT,`${Z.VISIBILITY_SELF_PREFIX}${fr(e)}`]}catch{return[Z.DEFAULT_VELT_CONTEXT]}}})}isViewerOrgMembershipConfirmed(e,t){return Pe(this,null,function*(){try{let i=(yield this.userPermissionService.getUserPermissionsFromCacheOrFetch({organizationId:t}))?.[e]?.organization?.[t];return!!i&&i.errorCode!==Mu.PERMISSION_DENIED}catch(a){return this.loggingService.catch("Error in CommentService isViewerOrgMembershipConfirmed: ",a),!1}})}applyPortableVisibilityFilter(e,t,a){try{if(!e?.data)return e;let i=Object.values(e.data).filter(u=>typeof u=="object"),d=Pu(i,t);if(d.length===i.length)return e;if(a?.resultSet){let u=new Set(d);this.evictResultSetDepartures(a.resultSet.leave(i.filter(f=>!u.has(f))))}let m={};return d.forEach(u=>{u?.annotationId&&(m[u.annotationId]=u)}),b(g({},e),{data:m})}catch(i){return this.loggingService.catch("Error in CommentService applyPortableVisibilityFilter: ",i),e}}buildAllCommentsRawListener$(e){let{isContextEnabled:t,documentIds:a,organizationId:i,accessFields:d,isPrivateCommentsEnabled:m,veltFolderId:u,locationIds:f,statusIds:y,commonProperties:S,includeStatusIds:j,documentBatchSize:W}=e,$=y?.length?[Et("status.id","in",y)]:j?.length?[Et("status.id","in",j)]:[],H;if(t){let q=[];for(let ce=0;ce<d.length;ce+=Z.LISTENER_CONTEXT_BATCH_SIZE)q.push(d.slice(ce,ce+Z.LISTENER_CONTEXT_BATCH_SIZE));this.loggingService.logContext("[CONTEXT] getDataFromDocuments called with accessFields:",JSON.parse(JSON.stringify(d??"nil"))),H=Bt(q.map(ce=>this.commonDbService.dbListener({feature:"allComments",properties:b(g({},S),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",i??this.documentPaths?.organizationId),Et("metadata.documentId","in",a),...$,...u?[Et("metadata.veltFolderId","==",u)]:[],...f?.length?[Et("location.id","in",f)]:[],...ce?.length?[Et("context.accessFields","array-contains-any",ce)]:[]),...yc(xc)]})}).pipe(ic()))).pipe(Ee(ce=>bc(JSON.parse(JSON.stringify(ce)))))}else{let q=[];for(let ce=0;ce<(a?.length??0);ce+=W)q.push(a?.slice(ce,ce+W)??[]);H=Bt(q.map(ce=>this.commonDbService.dbListener({feature:"allComments",properties:b(g({},S),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",i??this.documentPaths?.organizationId),Et("metadata.documentId","in",ce),...$,...u?[Et("metadata.veltFolderId","==",u)]:[],...f?.length?[Et("location.id","in",f)]:[],...d?.length&&m?[Et("context.accessFields","array-contains-any",d)]:[]),...yc(xc)]})}).pipe(ic()))).pipe(Ee(ce=>bc(JSON.parse(JSON.stringify(ce)))))}return H}resolvedStatusExclusion$(e){let t=this.customFilterService.customStatusMap$,a=(typeof this.docService?.getDocumentPaths$=="function"?this.docService.getDocumentPaths$():ye(null)).pipe(Ee(i=>Um(i)),Gt());return Bt([this.lazyLoadResolvedComments$,this.resolvedIntentFromSidebar$,t,a]).pipe(Ee(([i,d,m,u])=>{let f=Z.LISTENER_BATCH_SIZE;if(e.hasExplicitStatusIds)return{includeStatusIds:null,documentBatchSize:f};let y=u??Um(this.documentPaths),S=J0({lazyLoadResolvedComments:!!i,hasResolvedIntent:!!d,currentDocumentKey:y,unlockedDocumentKey:this.resolvedUnlockedDocumentKey});if(this.resolvedUnlockedDocumentKey=S.unlockedDocumentKey,!S.excludeResolved)return{includeStatusIds:null,documentBatchSize:f};let j=K0(m),W=q0(m);if(e.clientSideOnly)return{includeStatusIds:j,documentBatchSize:f};let $=Z0({branch:e.isContextEnabled?"context":"default",documentIdCount:e.documentIdCount,accessFieldCount:e.isContextEnabled?Math.min(e.accessFieldCount,Z.LISTENER_CONTEXT_BATCH_SIZE):e.accessFieldCount,locationIdCount:e.locationIdCount,nonTerminalStatusCount:j.length,terminalStatusCount:W.length,hasFolderClause:e.hasFolderClause,orderByCount:2});this.lastQueryClauseDescriptor=$;let H=e.documentIdCount,q=Q0({branch:e.isContextEnabled?"context":"default",clauses:$,maxDocumentBatchSize:e.isContextEnabled?H:f,minDocumentBatchSize:e.isContextEnabled?H:2});return q.applyStatusClause?{includeStatusIds:j,documentBatchSize:q.documentBatchSize}:(this.loggingService.catch(`[lazyLoadResolvedComments] status clause dropped \u2014 branch=${e.isContextEnabled?"context":"default"} disjunctions=${q.projectedDisjunctions} filterSum=${q.projectedFilterSum} boundBy=${q.boundBy} reason=${q.reason}`,null,void 0,!0),{includeStatusIds:null,documentBatchSize:f})}),Gt((i,d)=>i.documentBatchSize===d.documentBatchSize&&Y0(i.includeStatusIds,d.includeStatusIds)),Wr(i=>(this.loggingService.catch("[lazyLoadResolvedComments] status-exclusion stream failed; falling back to today's query: ",i),ye({includeStatusIds:null,documentBatchSize:Z.LISTENER_BATCH_SIZE}))))}getDataFromDocuments(e){let{documentIds:t,organizationId:a,query:i}=e;if(!this.configService?.getApiKey())return ye(null);if(t?.some(j=>!j)||!this.documentPaths)return ye(null);let d,m,u=[];if(i)i?.folderId&&(d=ur(i?.folderId)),i?.locationId&&(u=[...u,i?.locationId]),i?.locationIds?.length&&(u=[...u,...i?.locationIds]),m=i?.statusIds;else{d=this.docService.getDocumentPaths()?.veltFolderId;let j=this.docService.getDocumentPaths()?.locationId;j&&(u=[...u,j])}let f={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(f.documentId=t?.length?t[0]:void 0,f.organizationId=this.documentPaths?.organizationId);let y=this.authService.getUser()?.userId;if(!y)return ye(null);let S=this.authService.getIsPrivateCommentsEnabled();return this.queryDocContextChanges$().pipe(Fe(()=>tu(()=>jn(this.buildVisibilityTokens(y)).pipe(Fe(W=>{let $=S?W:[Z.DEFAULT_VELT_CONTEXT],{isContextEnabled:H,contextFields:q}=this.getQueryDocContext(),ce=[...$,...q],fe,le=this.commonDbService.usesPortableChannelFeed(Hu),he=!m,xe=le&&he?D0():null,ze=null;return le?fe=this.resolvedStatusExclusion$({isContextEnabled:!!H,documentIdCount:t?.length??0,accessFieldCount:ce?.length&&(H||S)?ce.length:0,locationIdCount:u?.length??0,hasFolderClause:!!d,hasExplicitStatusIds:!!m,clientSideOnly:!0}).pipe(Fe(Ze=>(ze=Ze.includeStatusIds,this.commonDbService.dbListener({feature:"allComments",properties:b(g({},f),{organizationId:a??this.documentPaths?.organizationId,documentIds:t})}).pipe(ic(),Ee(He=>bc(JSON.parse(JSON.stringify([He])))),Ee(He=>S?this.applyPortableVisibilityFilter(He,{userId:y,tokens:W},{resultSet:xe}):He),Ee(He=>AD(He)))))):fe=this.resolvedStatusExclusion$({isContextEnabled:!!H,documentIdCount:t?.length??0,accessFieldCount:ce?.length&&(H||S)?ce.length:0,locationIdCount:u?.length??0,hasFolderClause:!!d,hasExplicitStatusIds:!!m}).pipe(Fe(Ze=>this.buildAllCommentsRawListener$({isContextEnabled:!!H,documentIds:t,organizationId:a,accessFields:ce,isPrivateCommentsEnabled:S,veltFolderId:d,locationIds:u,statusIds:m,commonProperties:f,includeStatusIds:Ze.includeStatusIds,documentBatchSize:Ze.documentBatchSize}))),fe.pipe(Fe(Ze=>Ze?.data?ye(Ze).pipe(Fe(He=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:He,feature:"allComments"}).pipe(Ee(Xe=>{let Oe=Object.values(Xe?.data||{}).filter(Ke=>typeof Ke=="object"),Qe=this.applyPortableQueryScopeFilter(Oe,{isPortableFeed:le,scope:{statusIds:m??ze,veltFolderId:d,locationIds:u},evictDropped:he,resultSet:xe});return{data:this.applyListenerVisibilityPostFilter(Qe,W,y,H?q:null),operation:Xe?.operation}}))),Ee(({data:He,operation:Xe})=>{let Oe=He.reduce((Qe,Ke)=>{let xt=Ke.metadata?.documentId;return xt&&(Qe[xt]||(Qe[xt]=[]),Qe[xt].push(Ke)),Qe},{});return{data:He,documentMap:Oe,operation:Xe}}),Ee(({data:He,documentMap:Xe,operation:Oe})=>m?{data:He,documentMap:Xe,operation:Oe}:(He?.length&&(He?.forEach(Qe=>{this.sanitizeCommentAnnotation(Qe)}),this.setAnnotationIndex(He),this.updateAnnotationsForSelectAllContentMode(He),He.forEach(Qe=>{this.customFilterService.convertLegacyAnnotationStatus(Qe),this.customFilterService.convertLegacyPriority(Qe),this.customFilterService.convertLegacyCategory(Qe)})),{data:He,documentMap:Xe,operation:Oe})),Wr(He=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",He),ye([]))),Tm(({documentMap:He})=>{m||Object.entries(He??{}).forEach(([Xe,Oe])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(Oe)))})}),Ee(({data:He,documentMap:Xe,operation:Oe})=>({data:this.filterUserDraftComments(He),documentMap:Xe,operation:Oe})),Ee(({data:He,documentMap:Xe,operation:Oe})=>({data:this.splitProgressCommentsStage(this.removeDraftFlags(He)),documentMap:Xe,operation:Oe})),Fe(({data:He,documentMap:Xe,operation:Oe})=>m?ye({data:He,documentMap:Xe,operation:Oe}):this.mergeDraftAnnotations(He).pipe(Ee(Qe=>({data:Qe,documentMap:Xe,operation:Oe})))),Ee(({data:He,documentMap:Xe,operation:Oe})=>{if(!m)if(Oe?.type==="removed"){if(Oe?.ids?.length){let Qe=this.commentAnnotationById$.value??{};Oe?.ids?.forEach(Ke=>{delete Qe?.[Ke]}),this.evictProgressComments(Oe?.ids??[]),this.commentAnnotationById$.next(Qe)}}else Object.entries(Xe??{}).length?Object.entries(Xe??{}).forEach(([Ke,xt])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:Ke,annotations:xt})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return He})):ye(null)))})))))}fetchCommentAnnotations(e){return Pe(this,null,function*(){try{let t=this.authService.getUser();if(!t)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{data:[],hasMore:!1};let a=this.commonDbService?.isPortableCommentQueryCandidate?.()===!0,i=this.configService?.getApiKey(),d=e?.organizationId??t?.clientOrganizationId,m=pc(d??""),u=[];e?.allDocuments||(u=e?.documentIds?.map(ce=>Au(ce??""))??this.docService.getDocumentIds()?.map(ce=>ce.documentId));let f=B0(e,u),y;e?.pageToken&&(y=yield fC(e?.pageToken??"","veltencrypttoken","veltencrypttoken"));let S,j;a?{data:S,hasMore:j}=yield this.fetchPortableCommentAnnotationPage(t.userId,V0(f,{organizationId:d??"",pageToken:y}),f.pageSize):(S=yield this.commonDbService.queryData({feature:"allComments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:this.buildFirestoreCommentAnnotationQuery(f,{serverOrganizationId:m,apiKey:i,hasPageToken:!!e?.pageToken,decryptedPageToken:y}),apiKey:i??"",organizationId:m}}),{data:S,hasMore:j}=Rh(S,f.pageSize));let W=S?.reduce((ce,fe)=>(ce[fe?.annotationId]=fe,ce),{});W=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:W,shouldAwait:!0}),W=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:W});let $=t.clientOrganizationId?yield this.isViewerOrgMembershipConfirmed(t.userId,t.clientOrganizationId):!1,H=_h({userId:t.userId,clientOrganizationId:$?t.clientOrganizationId:void 0,fallbackServerOrganizationId:t.clientOrganizationId?void 0:m});return{data:Pu(Object.values(W??{}),{userId:t.userId,tokens:H}),hasMore:j}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}fetchPortableCommentAnnotationPage(e,t,a){return Pe(this,null,function*(){try{let i=yield this.commonDbService.runPortableCommentQuery("fetchCommentAnnotations",t,e);if(!i?.ok)return{data:[],hasMore:!1};let d=i.data;return Array.isArray(d?.data)?Rh(d.data,a,d.hasMore===!0):(this.loggingService.log("Tier B fetchCommentAnnotations answered ok without a `data` array; treated as no rows."),{data:[],hasMore:!1})}catch(i){return this.loggingService.catch("Error in CommentService fetchPortableCommentAnnotationPage: ",i),{data:[],hasMore:!1}}})}buildFirestoreCommentAnnotationQuery(e,t){return[Et("metadata.organizationId","==",t.serverOrganizationId),Et("metadata.apiKey","==",t.apiKey),...e.clauses.map(a=>Et(a.field,a.op,a.key==="folderId"?ur(a.value):a.value)),...yc(xc,e.direction),...t.hasPageToken?[YC(parseInt(t.decryptedPageToken,10),"lastUpdated")]:[],JC(e.pageSize+1)]}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(a=>(a.comments=a?.comments?.filter(i=>i?.from?.userId===t?.userId||!i?.isDraft),!!a?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(Ee(t=>{let a=t||{};return e?.filter(i=>{a?.[i?.annotationId]&&delete a[i?.annotationId]}),a}),Ee(t=>{if(t){let a=e.slice();return a.push(...Object.values(t)),a}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:a}){try{let i=this.getSharedCommentDataKey({documentIds:e,organizationId:t,query:a});if(i===null)return this.getDataFromDocuments({documentIds:e,organizationId:t,query:a});let d=this.sharedCommentData.get(i);return d||(d=this.getDataFromDocuments({documentIds:e,organizationId:t,query:a}).pipe(sb(()=>{try{this.sharedCommentData.get(i)===d&&this.sharedCommentData.delete(i)}catch(m){this.loggingService.catch("Error in CommentService getDataFromDocumentIds finalize: ",m)}}),pb({bufferSize:1,refCount:!0})),this.sharedCommentData.set(i,d)),d}catch(i){return this.loggingService.catch("Error in CommentService getDataFromDocumentIds: ",i),this.getDataFromDocuments({documentIds:e,organizationId:t,query:a})}}getSharedCommentDataKey({documentIds:e,organizationId:t,query:a}){try{let i=this.docService.getDocumentPaths();return JSON.stringify([e??null,t??null,a??null,this.configService?.getApiKey()??null,this.authService.getUser()?.userId??null,this.authService.getIsPrivateCommentsEnabled()??null,this.commonDbService.shouldUseFirestore(),this.commonDbService.usesPortableChannelFeed(Hu),this.commonDbService.isPortableSession?.()??null,!!this.documentPaths,this.documentPaths?.organizationId??null,i?.veltFolderId??null,i?.locationId??null,this.getQueryDocContext()])}catch(i){return this.loggingService.catch("Error in CommentService getSharedCommentDataKey: ",i),null}}queryDocContextChanges$(){return(this.docService?.getDocContext$?.()??ye(null)).pipe(Ee(()=>this.getQueryDocContext()),Gt((t,a)=>t.isContextEnabled===a.isContextEnabled&&JSON.stringify(t.contextFields)===JSON.stringify(a.contextFields)),Wr(t=>(this.loggingService.catch("Error in CommentService queryDocContextChanges$: ",t),ye(this.getQueryDocContext()))))}getQueryDocContext(){try{let e=!!this.userPermissionService?.getIsContextEnabled();return{isContextEnabled:e,contextFields:e?this.docService.getProcessedDocContext():[]}}catch(e){return this.loggingService.catch("Error in CommentService getQueryDocContext: ",e),{isContextEnabled:!0,contextFields:[]}}}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(m=>!m)||!this.documentPaths)return ye(null);let a=this.docService.getDocumentPaths()?.veltFolderId,i=ye([]),d={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(d.documentId=t?.length?t[0]:void 0,d.organizationId=this.documentPaths?.organizationId),this.commonDbService?.isPortableSession?.()===!0&&a0(o0)&&typeof this.commonDbService?.portableCapability$=="function")i=qC(this.commonDbService,zu,{feature:"allMultiThreads",properties:b(g({},d),{organizationId:this.documentPaths?.organizationId,documentIds:t})}).pipe(Ee(m=>this.applyMultiThreadFolderClause(m,a)));else if(this.userPermissionService?.getIsContextEnabled()){let m=[Z.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],u=[];for(let f=0;f<(m?.length??0);f+=Z.LISTENER_CONTEXT_BATCH_SIZE)u.push(m?.slice(f,f+Z.LISTENER_CONTEXT_BATCH_SIZE)??[]);i=Bt(u.map(f=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:b(g({},d),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",this.documentPaths?.organizationId),Et("metadata.documentId","in",t),...a?[Et("metadata.veltFolderId","==",a)]:[],...f?.length?[Et("context.accessFields","array-contains-any",f)]:[])]})}).pipe(ic()))).pipe(Ee(f=>bc(f)))}else{let m=[];for(let u=0;u<(t?.length??0);u+=Z.LISTENER_BATCH_SIZE)m.push(t?.slice(u,u+Z.LISTENER_BATCH_SIZE)??[]);i=Bt(m.map(u=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:b(g({},d),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",this.documentPaths?.organizationId),Et("metadata.documentId","in",u),...a?[Et("metadata.veltFolderId","==",a)]:[])]})}).pipe(ic()))).pipe(Ee(u=>bc(u)))}return i.pipe(Fe(m=>m?.data?ye(m).pipe(Ee(u=>({data:u?.data,operation:u?.operation})),Ee(({data:u,operation:f})=>{let y=[];return u&&(y=Object.values(u??{}).filter(S=>typeof S=="object")),{data:y,operation:f}}),Wr(u=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",u),ye({data:[],operation:null}))),Ee(({data:u,operation:f})=>{u.forEach(S=>{delete S.isDraft});let y=u.reduce((S,j)=>{let W=j.metadata?.documentId;return W&&(S[W]||(S[W]=[]),S[W].push(j)),S},{});return{data:u,documentMap:y,operation:f}}),Fe(({data:u,documentMap:f,operation:y})=>{let S=[];return this.commentAnnotationById$.pipe(Fe(()=>this.domService.getSelectedAnnotationsMap$().pipe(Ee(j=>({selectedAnnotationsMap:j})))),Ee(({selectedAnnotationsMap:j})=>{let W={};return Object.keys(f??{}).forEach($=>{let H=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:$});H&&H?.forEach(q=>{W[q?.annotationId]=q})}),S=u.filter($=>{let H=!1;if($?.commentAnnotations){for(let q in $?.commentAnnotations)if(W?.[q]&&W?.[q]?.status?.id!==this.customFilterService.resolvedStatus.id){H=!0;break}}return H}),S.forEach($=>{Object.keys($?.commentAnnotations||{}).forEach(H=>{$.commentAnnotationsMap||($.commentAnnotationsMap={}),$.commentAnnotationsMap[H]=W?.[H]})}),{data:S,operation:y}}))}),Fe(({data:u,operation:f})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(Ee(y=>{let S=y||{};return u?.filter(j=>{S?.[j?.annotationId]&&delete S[j?.annotationId]}),S}),Ee(y=>{if(y){let S=u.slice();return S.push(...Object.values(y)),{data:S,operation:f}}return{data:u,operation:f}}))),Ee(({data:u,operation:f})=>{let y=u.reduce((S,j)=>{let W=j.metadata?.documentId;return W&&(S[W]||(S[W]=[]),S[W].push(j)),S},{});if(f?.type==="removed"){if(f?.ids?.length){let S=this.multiThreadCommentAnnotationById$.value;f?.ids?.forEach(j=>{delete S?.[j]}),this.multiThreadCommentAnnotationById$.next(S)}}else Object.keys(y??{}).forEach(S=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:S,annotations:y[S]})});return u})):ye(null)))}else return ye(null)}updateUnreadAnnotationsMap(e,t){try{let a=new Date(Z.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),i=e.filter(d=>d?.lastUpdated>a);if(t){let d={},m=!1;i.forEach(u=>{let f=0,y=t?.[u?.annotationId];if(y){let S=y?.comments;S&&u?.comments?.forEach(j=>{S?.[j?.commentId]?.views?.[this.user?.userSnippylyId]||f++})}f?f!==d?.[u?.annotationId]&&(d[u?.annotationId]=f,m=!0):d?.[u?.annotationId]&&(delete d[u?.annotationId],m=!0)}),this.unreadCommentsMap$.next(d)}}catch(a){this.loggingService.catch("Error in CommentService updateUnreadAnnotationsMap:",a)}}updateAnnotationsForSelectAllContentMode(e){try{e.forEach(t=>{if(t?.selectAllContent&&t?.targetElementId){let a=Lr(t.targetElementId,["id","data-id"]);if(a){let i=a.textContent;i&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(a),text:i,occurrence:1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(a)??void 0},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:a,queryHash:i}){try{if(t){e||(e=Z.NO_ORGANIZATION_ID),i||(i=Z.DEFAULT_QUERY_HASH);let d={};a?.forEach(u=>{u?.annotationId&&(d[u?.annotationId]=u)});let m=g(g({},this.commentAnnotationById$.value??{}),d);this.commentAnnotationById$.next(m)}}catch(d){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",d)}}getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Ee(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",a),ye([])}}getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:e,documentIds:t}){try{let a=new Set((t||[]).map(f=>String(f))),i=this.commentAnnotationById$.value,d=this.draftCommentAnnotationsByAnnotationId$.value;if(!i&&!d)return null;if(!a.size)return[];let m=f=>f?.metadata?.documentId!=null&&a.has(String(f.metadata.documentId))&&f?.metadata?.organizationId==e,u={};return Object.values(i||{}).forEach(f=>{m(f)&&(u[f.annotationId]=f)}),Object.values(d||{}).forEach(f=>{m(f)&&!u[f.annotationId]&&(u[f.annotationId]=f)}),Object.values(u)}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentIds:",a),[]}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let a=null;this.commentAnnotationById$.value&&(a={},Object.values(this.commentAnnotationById$.value).forEach(d=>{d?.metadata?.documentId==t&&d?.metadata?.organizationId==e&&(a[d?.annotationId]=d)}));let i=this.draftCommentAnnotationsByAnnotationId$.value;return i&&(a===null&&(a={}),Object.values(i).forEach(d=>{d?.metadata?.documentId===t&&d?.metadata?.organizationId===e&&!a[d?.annotationId]&&(a[d?.annotationId]=d)})),a?Object.values(a):null}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId:",a),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(Fe(a=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:a?.organizationId,documentId:t}))):ye(null)}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",a),ye(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Fe(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ye([])))}getCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId}):[]}catch(e){return this.loggingService.catch("Error in CommentService getCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}setOriginalCommentAnnotationsByAnnotationId(e){try{let t={};e?.forEach(a=>{a?.annotationId&&(t[a?.annotationId]=a)}),this.originalCommentAnnotationsByDocumentId$.next(g(g({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:a,queryHash:i}){try{if(t){e||(e=Z.NO_ORGANIZATION_ID),i||(i=Z.DEFAULT_QUERY_HASH);let d={};a.forEach(u=>{u?.annotationId&&(d[u?.annotationId]=u)});let m=g(g({},this.multiThreadCommentAnnotationById$.value),d);this.multiThreadCommentAnnotationById$.next(m)}}catch(d){this.loggingService.catch("Error in CommentService setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",d)}}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){return this.multiThreadCommentAnnotationById$.pipe(Ee(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let a={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(d=>{d?.metadata?.documentId==t&&d?.metadata?.organizationId==e&&(a[d?.annotationId]=d)});let i=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return i&&Object.values(i??{}).forEach(d=>{d?.metadata?.documentId===t&&d?.metadata?.organizationId===e&&!a[d?.annotationId]&&(a[d?.annotationId]=d)}),Object.values(a)}catch(a){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",a),[]}}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Fe(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ye([])))}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId})}catch(e){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}getLocations$(){return this.docService.getLocation$().pipe(Fe(e=>this.docService.getLocations$().pipe(Ee(t=>({location:e,locations:t})))),Ee(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(a=>a.locationId)),t||[]}))}applyPageLocationFilters(e,{query:t,customInternalDocumentId:a,customLocationId:i,customClientLocationId:d,fromCommentSidebar:m}){let u=e;try{if(u.filteredAnnotations=[],t)return u.filteredAnnotations=u.annotations?.slice(),u;if(a&&!i||m)return u.filteredAnnotations=ro(u.annotations?.slice(),u?.excludedLocationIds),u;let f=[],y=[];return i?(f.push(i),d&&y.push(d)):(f.push(u?.location?.locationId),f.push(...Object.values(u?.customLocations||[]).map(S=>S.locationId)),u?.location?.location?.id&&y.push(u?.location?.location?.id),y.push(...Object.values(u?.customLocations||{}).map(S=>S.location?.id).filter(S=>!!S))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,f,y),u.filteredAnnotations=ro(u.filteredAnnotations,u?.excludedLocationIds),u}catch(f){return this.loggingService.catch("Error in CommentService applyPageLocationFilters: ",f),u}}filterAnnotationsByLocationIds(e,t,a){try{return e.filter(i=>rr(i)||t.includes(i.locationId)||a?.includes(i?.location?.id)||t?.find(d=>d==i?.location?.id)||a?.find(d=>d==i?.locationId+""))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByLocations:",i),[]}}setAnnotationIndex(e){try{e.forEach((t,a)=>{t?.annotationId&&(t.annotationIndex=a+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}acceptsInOwnDocumentArea(e){return t=>this.docService.isAnnotationAllowedInArea(e?.metadata,t)!==!1}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;let a=rr(e);if(e.targetElementId){let d=a?this.findDocumentLevelTargetById(e):Lr(e.targetElementId,["id","data-id"]);if(d&&this.domService.isElementVisible(d)){let m=d.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_TYPE),u=!0;if(m)m==="popover"?u=!0:u=!1;else{let f=document.querySelector(`${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_ELEMENT_ID}="${e.targetElementId}"]`);f&&d?.contains(f)&&(u=!1)}u?e.targetElement={xpath:this.domService.getXPath(d),fXpath:this.domService.getXPath(d,!0),cfXpath:this.domService.getXPath(d,!0,!0),topPercentage:e.targetElement?.topPercentage||50,leftPercentage:e.targetElement?.leftPercentage||90}:e.targetElement=null}else e.targetElement=null,a&&this.logHiddenDocumentLevelPin(e)}if(e.targetElement){e.position=null,e.ghostComment=null;let d=e.targetElement?.xpath,m=this.acceptsInOwnDocumentArea(e),u=null,f=e?.targetElement?.anchor,y=this.resolveIdScopedPinElement(e);if(y!==void 0)u=y;else if(f){let W=this.domService.resolveAnchorRecord(f,{accept:m,cacheKey:jh(e)});W?.element&&this.domService.isElementVisible(W.element)&&kn(W.element)&&!(a&&dp(W.matchedBy))&&(u=W.element)}else d&&(u=this.domService.getElementFromXPathAccepted(d,m),!this.domService.isXpathWithId(d)&&!a&&((!u||!this.domService.isElementVisible(u)||!m(u))&&e.targetElement?.cfXpath&&(d=e.targetElement?.cfXpath,u=this.domService.getElementFromXPathAccepted(d,m)),this.getDetectionStrategy()===xh.DYNAMIC_ID&&(!u||!this.domService.isElementVisible(u)||!m(u))&&(d=e.targetElement?.fXpath,d&&(u=this.domService.getElementFromXPathAccepted(d,m)))));let S=!!u&&this.domService.isElementVisible(u);a&&!S&&(u=null,this.logHiddenDocumentLevelPin(e)),S||t&&y===void 0&&!a&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=this.getGhostCommentTargetElement(e),e?.ghostComment?.targetElement?.xpath&&(u=this.domService.getElementFromXPath(e?.ghostComment?.targetElement?.xpath)));let j=!1;if(e?.locationId&&!a){let W=this.docService.getLocation();if(!fc({location:W?.location,locationId:W?.locationId},{location:e?.location,locationId:e?.locationId})){let $=this.docService.getAdditionLocationFromElement(u),H=$?this.docService.genarateLocationId($):void 0;e?.location?.id&&e?.location?.id===$?.id||H&&H===e?.locationId?j=!1:j=!0}}if(u&&this.docService.isAnnotationAllowedInArea(e?.metadata,u)===!1&&(j=!0,this.docService.logHiddenByArea("comment pin",e,u)),j&&(e.ghostComment=null),!j&&u&&kn(u)&&!u?.closest(".cdk-overlay-container")&&u?.getBoundingClientRect()){let $=this.popoverMode$?.value?0:e.targetElement?.topPercentage,H=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:q,width:ce}=EC(u);e.position={top:q*($||0)/100,left:ce*(H||0)/100};let fe=window.getComputedStyle(u).transform;if(fe&&fe!=="none")try{let le=new DOMMatrixReadOnly(fe),he=Math.sqrt(le.a*le.a+le.b*le.b)||1,xe=Math.sqrt(le.c*le.c+le.d*le.d)||1;(Math.abs(he-1)>.01||Math.abs(xe-1)>.01)&&(e.position.parentScaleX=he,e.position.parentScaleY=xe)}catch{}if(this.transformContext$.value){let{containerSelector:le,transforms:he}=this.transformContext$.value,xe=document.querySelector(le);xe&&xe.contains(u)&&(e.position.transformContext=he)}}!j&&t&&!e?.position&&!e?.ghostComment&&y===void 0&&!a&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}let i=!!e?.targetTextRange&&!e?.targetElement;t&&!i&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(a){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",a)}}addComment(Oe,Qe,Ke,xt,Ue){return Pe(this,arguments,function*(e,t,a,i,d,m=[],u,f,y,S,j,W,$,H,q,ce,fe,le,he,xe,ze,Ze,He,Xe){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let Ot=this.authService.getUser();if(Ot)if(Ot.isReadOnly||Ot.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{yield this.triggerAddCommentAnnotationDraftEvent();let Je=new At;fe&&(Je=g(g({},Je),fe)),Je.comments=[],fe?.comments?.length&&(Je.comments=fe.comments.map(Mt=>{let er=new Co;return er=g(g({},er),Mt),er.from=Ot,er.lastUpdated=new Date,er.createdAt=this.timestamp,er})),Je.from=Ot,Je.color=Je?.color||Z.DEFAULT_ANNOTATION_COLOR,Je.lastUpdated=this.timestamp,Je.createdAt=this.timestamp,Je.sourceId=q,Je.assignedTo=fe?.assignedTo||ce,Je.customList=fe?.customList||[],Ze&&(Je.targetElementId=Ze);let{topPositionX:wm,topPositionY:eu}=this.domService.getTopLeftPosition();Je.positionX=wm,Je.positionY=eu;let Dm=this.domService.getCurrentWindowSizeValue();if(Je.screenWidth=Dm.screenWidth,Je.screenHeight=Dm.screenHeight,Je.screenScrollHeight=Dm.screenScrollHeight,Je.taggedElementPath="",e){let{targetElement:Mt,skip:er}=this.buildNewPinTargetElement(e);if(er)return;Je.targetElement=Mt}if(t&&(Je.targetTextRange=t),Je?.targetElement?.xpath){let Mt=this.domService.getXPath(Je.targetElement.xpath);if(Mt){let er=Mt.iterateNext();er&&(kn(er)||(Je.targetElement=null))}}this.customFilterService.defaultStatus&&!fe?.status&&(Je.status=this.customFilterService.defaultStatus),Je.pageInfo=Dh(),Je.pageInfo&&(Je.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let fD=this.docService.getClientDocumentId(),bD=this.docService.getLocation()?.location;if(he&&(Je.context=this.preserveAccessSentinels(Je.context,he&&Cn(he)),Je.contextId=this.generateContextId(Je.context)),this.commentContextProvider!==null){let Mt=this.commentContextProvider(fD,bD),er=Mt instanceof Promise?yield Mt:Mt;er&&(Je.context=this.preserveAccessSentinels(Je.context,er&&Cn(er)),Je.contextId=this.generateContextId(Je.context),er?.commentType==="manual"&&(Je.commentType="manual",delete Je.targetElement))}if(i){Je.sourceId=i?.sourceId;let Mt=i?.targetElement,er=i?.commentData;if(Mt?.targetText)Je.targetTextRange={commonAncestorContainer:"/html/body",text:Mt.targetText,occurrence:Mt?.occurrence||1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(document.body)??void 0};else if(Mt?.elementId)if(Je.targetElementId=Mt.elementId,Mt?.selectAllContent)Je.selectAllContent=!!Mt?.selectAllContent;else{let zr=Lr(Mt.elementId,["id","data-id"]);zr?Je.targetElement={xpath:this.domService.getXPath(zr),fXpath:this.domService.getXPath(zr,!0),cfXpath:this.domService.getXPath(zr,!0,!0),anchor:this.domService.generateAnchorRecord(zr),topPercentage:50,leftPercentage:90}:Je.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",anchor:this.domService.generateAnchorRecord(document.body),topPercentage:50,leftPercentage:90}}i?.status&&(Je.status=i.status),i?.context&&(Je.context=this.preserveAccessSentinels(Je.context,i.context?Cn(i.context):i.context),Je.contextId=this.generateContextId(Je.context)),Je.comments||(Je.comments=[]);let bh=this.authService.getUser();er?.forEach(zr=>{let oc=new Co;oc.commentText=zr.commentText,oc.commentHtml=zr.commentHtml,oc.replaceContentHtml=zr.replaceContentHtml,oc.replaceContentText=zr.replaceContentText,oc.from=bh,Je.comments.push(oc)})}if(d&&(Je.isPageAnnotation=!0),m?.length&&(Je.comments=m),u&&(Je.commentType="chart",Je.metadata=u),y?.sourceId&&(Je.sourceId=y.sourceId),Je?.targetElement?.xpath&&!y){let Mt=this.domService.getElementFromXPath(Je.targetElement.xpath);Mt&&(y=this.getInlineCommentSectionConfig(Mt))}y?.targetInlineCommentElementId&&(Je.targetInlineCommentElementId=y?.targetInlineCommentElementId,Je.targetElementId=y.targetInlineCommentElementId,y?.config?.id&&(Je.inlineCommentSectionConfig=y?.config));let CD=!Je?.comments?.length,kD=!!(i?.openComment===!1||xe);this.getPrivateCommentMode()&&(Je?.iam||(Je.iam=new cC),Je.iam.accessMode=gr.PRIVATE),S&&(S.isDocumentLevel===!0&&(Je.isDocumentLevel=!0),Je.context=this.preserveAccessSentinels(Je.context,S.context?Cn(S.context):S.context),Je.commentType="manual",delete Je.targetElement,Je.contextId=this.generateContextId(Je.context)),j&&(Je.targetElementId=j.targetElementId,Je.targetElement=j.targetElement);let ab=this.getPrivateModeConfig();if(ab)try{let Mt=g({},ab),er=this.authService.getUser();if(Mt.type==="restricted"&&er?.userId&&(Mt=xo(Mt,er.userId)),Mt.type==="organizationPrivate"&&!Mt.organizationId&&!Mt.organizationIds?.length){let zr=this.docService.getOrganizationConfig();zr?.clientOrganizationId&&(Mt.organizationId=zr.clientOrganizationId)}let bh=qn(Mt,er?.userId);Je.context||(Je.context={}),Je.context._setAccessFields=bh,Je.visibilityConfig=Zn(Mt,er?.userId)}catch(Mt){this.loggingService.catch("Error building accessFields from privateModeConfig: ",Mt)}this.saveCommentToDb(Je,a,CD,kD,f,W,$,le,H,ze,He,Xe)}}catch(Ot){this.loggingService.catch("Error in CommentService addComment: ",Ot)}})}triggerAddCommentAnnotationDraftEvent(){return Pe(this,null,function*(){try{this.commentAnnotationContextDraft=null;let e={addContext:a=>{this.commentAnnotationContextDraft=a}},t=yield this.commentActionsService?.getAddCommentAnnotationDraftEventFromCommentAddEventData(e);t&&this.commentActionsService?.triggerAddCommentAnnotationDraftEvent(t)}catch(e){this.loggingService.catch("Error in CommentService triggerAddCommentAnnotationDraftEvent: ",e)}})}triggerAddCommentDraftEventOnAbandon(e,t){return Pe(this,null,function*(){try{if(!e||!t)return;let a=this.getAnnotationById(e),i=!!this.getFullComments(a).some(d=>d&&!d.isDraft);a&&i&&(yield this.commentActionsService?.triggerAddCommentDraftEventForAnnotation(a,t))}catch(a){this.loggingService.catch("Error in CommentService triggerAddCommentDraftEventOnAbandon: ",a)}})}willDeleteWholeAnnotation(e,t){try{let a=this.getFullComments(e);if(!a.length)return!1;let i=a.findIndex(d=>d?.commentId===t);return i<0?!1:i===0&&this.deleteThreadWithFirstComment$.value!==!1||a.length===1}catch(a){return this.loggingService.catch("Error in CommentService willDeleteWholeAnnotation: ",a),!1}}confirmDeleteCommentIfRequired(e,t){return Pe(this,null,function*(){try{let a=this.getFullComments(e);if(!a.length||!t)return!0;let i=a.findIndex(f=>f?.commentId===t?.commentId);if(i<0||!(i===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value))return!0;let m;return this.deleteReplyConfirmation$.value&&(i!==0||this.deleteThreadWithFirstComment$.value===!1)?m={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:m={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:m}).afterClosed().toPromise())}catch(a){return this.loggingService.catch("Error in CommentService confirmDeleteCommentIfRequired: ",a),!1}})}releaseDraftConfirmationRetention(e){try{if(!e||!this.draftConfirmationPendingAnnotationIds?.delete(e))return;let t=this.draftCommentAnnotationsByAnnotationId$?.value;if(!t||!(e in t))return;let a=JSON.parse(JSON.stringify(t));delete a[e],this.draftCommentAnnotationsByAnnotationId$.next(a)}catch(t){try{this.loggingService?.catch("Error in CommentService releaseDraftConfirmationRetention: ",t)}catch{}}}confirmDraftIfRequired(e,t){return Pe(this,null,function*(){try{if(!e?.isDraft||!this.draftConfirmation$?.value)return!0;t&&this.draftConfirmationPendingAnnotationIds?.add(t);let a=BD({composerContent:e?.commentText??"",attachmentCount:e?.attachments?.length??0,recordingCount:e?.recorders?.length??0});return!(yield this.confirmDraftDecision?.(a))}catch(a){try{this.loggingService?.catch("Error in CommentService confirmDraftIfRequired: ",a)}catch{}return!0}finally{this.releaseDraftConfirmationRetention(t)}})}confirmDraftDecision(e){return Pe(this,null,function*(){try{let t={title:"Delete Draft?",message:"Your comment will be permanently removed",previewText:e,yesButton:"Delete Draft",noButton:"Keep Draft",darkMode:this.commentContainerDarkMode$.value,variant:"draft",type:"draft"};return!!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],role:"alertdialog",ariaDescribedBy:"velt-confirm-dialog-message",data:t}).afterClosed().toPromise())}catch(t){return this.loggingService.catch("Error in CommentService confirmDraftDecision: ",t),!1}})}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let a;e.targetElement?a=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?a=Lr(e.targetElementId,["id","data-id"]):e.targetTextRange&&(a=this.domService.getElementFromTargetTextRange(e.targetTextRange));let i=this.docService.getAdditionLocationFromElement(a);if(i){let d=this.docService.addLocation({location:i,source:"internal"});d?.[0]&&(e.locationId=d[0].locationId,e.location=d[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?t=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?t=Lr(e.targetElementId,["id","data-id"]):e.targetTextRange&&(t=this.domService.getElementFromTargetTextRange(e.targetTextRange)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,a=!1,i=!1,d,m,u,f,y,S,j,W){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(ke.COMMENT)&&this.docService.getDocumentPaths$().pipe(qt($=>!!$),qo(1),Fe($=>(this.documentPaths=$,this.loggingService.log(this.documentPaths),this.commentDbReadyGate$().pipe(qo(1),Fe(H=>Pe(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let q=this.docService.getClientDocumentId(),ce=this.docService.getLocation()?.location;if(u)e.multiThreadAnnotationId=u;else if(this.getMultiThread()){let He=En();e.targetElementId&&(He=En(e.targetElementId),e?.location?.id?He=En([e?.location?.id,e.targetElementId]):e?.locationId&&(He=En([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=He}let fe={addContext:He=>{He.access&&(He.accessFields=Nm(He)),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_CONTEXT_TRIGGERED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode(),context:He}),e.context=He&&Cn(He),e.contextId=this.generateContextId(e.context),He?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&setTimeout(()=>{this.updateCommentAnnotationContext(e.annotationId,He)},200)},documentId:q,location:ce,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?fe.elementRef={xpath:e.targetElement.xpath}:fe.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(fe),this.commentAdded$.next(fe),y&&y(fe),fe?.annotation?.annotationId&&this.pendingAddCommentAnnotationData.set(fe.annotation.annotationId,fe),this.setLocationToCommentAnnotation(e);let le=this.getElementForCommentAnnotation(e),he=this.docService.getBaseMetadata("comment",{element:le,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!he?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=g(g({},e.metadata),he),S&&(e.metadata=g(g({},e.metadata),S)),d&&typeof d=="object"&&(e.locationId=f||this.docService.genarateLocationId(d),e.location=d,W||this.docService.addLocation({location:d})),a)window.localStorage.setItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let He=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);He&&JSON.parse(He).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let xe=e.comments,ze=JSON.parse(JSON.stringify(e));if(this.commentAnnotationContextDraft){let He=this.commentAnnotationContextDraft;this.commentAnnotationContextDraft=null,He.access&&(He.accessFields=Nm(He)),ze.context=this.preserveAccessSentinels(ze.context,He&&Cn(He))}if(this.applyContextAccessDefaults(ze),ze.visibilityConfig||Om(ze?.context?.accessFields).length===0&&(ze.visibilityConfig={type:"public"}),ze.position=null,t){ze.targetElement=null,ze.targetTextRange=null;let He={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?ke.MULTI_THREAD:ke.COMMENT},Xe=yield this.areaService?.generateAreaAnnotationId();ze.areaAnnotationId=Xe;let Oe=this.areaService?.addArea(void 0,t,He,Xe,{locationId:ze.locationId,location:ze.location},ze.context);Oe&&(ze.metadata=g(g({},ze.metadata),Oe?.metadata||{}))}!i&&!ze?.targetInlineCommentElementId&&!ze?.isPageAnnotation&&this.domService.toggleAnnotationSelection(ze,void 0,void 0,!1,void 0,m),e.targetTextRange&&sessionStorage.setItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),ze?.comments?.length?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:ze?.comments[0]?.commentId,commentThreadIndex:0,commentType:this.getCommentType(ze),commentMode:this.getCommentMode(),source:j??"internal",commentAnnotationCreatedAt:e.createdAt,taggedClientUserIds:ze?.comments[0]?.taggedUserContacts?.map(He=>He.contact?.userId).filter(He=>!!He),taggedSnippylyUserIds:ze?.comments[0]?.taggedUserContacts?.filter(He=>!!ze?.metadata?.apiKey&&!!He.contact?.userId).map(He=>Uu(ze.metadata.apiKey,He.contact.userId))}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(ze),commentMode:this.getCommentMode()});let Ze=this.getAnnotationNumber(e);Ze&&(ze.annotationNumber=Ze),ze?.comments?.length?ze.comments=[]:ze.isDraft=!0,ze?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(ze),ze?.context&&(ze.contextId=this.generateContextId(ze.context),ze.context?.commentType==="manual"&&(ze.commentType="manual",delete ze.targetElement)),xe?.length?this.saveComment(ze,{type:qe.NEWLY_ADDED,updatedComment:xe[0]}):this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:ze}))}})))))).subscribe(()=>{},$=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",$)})}catch($){this.loggingService.catch("Error in CommentService saveCommentToDb: ",$)}}saveMultiThreadCommentAnnotation(e){return Pe(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if((this.databaseService.getDbValue()||this.commonDbService?.isPortableBackendActive?.()===!0&&this.commonDbService?.portableCapabilityState?.(zu)!=="absent")&&t?.multiThread){let i={annotationId:e.multiThreadAnnotationId,targetElement:e.targetElement,targetElementId:e.targetElementId,targetInlineCommentElementId:e.targetInlineCommentElementId,inlineCommentSectionConfig:e.inlineCommentSectionConfig,areaAnnotationId:e.areaAnnotationId,targetTextRange:e.targetTextRange,from:e.from,locationId:e.locationId,location:e.location,sourceId:e.sourceId,type:"multiThread",metadata:e.metadata,context:e.context};delete e?.targetElement,delete e?.areaAnnotationId,delete e?.targetTextRange;let d=e?.metadata?.documentId||t?.documentId,m=e?.metadata?.organizationId||t?.organizationId,u=this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:m,documentId:d})?.find(f=>f.annotationId===e.multiThreadAnnotationId);if(!u){let f=yield this.readMultiThreadRow({documentId:d??"",organizationId:m??"",id:e.multiThreadAnnotationId});if(f.answered)u=f.data;else if(f.unserved)u=void 0;else{if(!e?.isDraft)return null;u=void 0}}if(u&&(u=JSON.parse(JSON.stringify(u)),delete u.from,i=g(g({},u),i)),i?.commentAnnotations||(i.commentAnnotations={}),i.commentAnnotations[e.annotationId]=!0,e?.isDraft)this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(b(g({},this.draftMultiThreadCommentAnnotationsByAnnotationId$.value),{[i.annotationId]:b(g({},i),{isDraft:!0})}));else{let f=this.getDraftMultiThreadAnnotationOfDocument(i.annotationId,d);if(f&&(i=g(g({},i),f)),delete i.isDraft,i.commentAnnotationsMap={},!i?.metadata?.documentId){i?.metadata||(i.metadata={});let j=this.docService.getBaseMetadata("multiThread");i.metadata=g(g({},i?.metadata),j)}let{documentId:y,organizationId:S}=i?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:i.annotationId,documentId:y,organizationId:S},data:JSON.parse(JSON.stringify(i)),callback:()=>{let j=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;j[e.annotationId]&&(delete j[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(j))}})}return i}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return Pe(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let a=yield this.getCommentCategory(t).toPromise();if(a){let i=this.docService.getDocumentPaths();if(i?.comment&&e?.annotationId){let d=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(m=>m.annotationId===e.annotationId);if(d||(d=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e.annotationId}})),d?.annotationId){let m=d;m.commentCategories=[a];let{documentId:u,organizationId:f}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(m);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:u,organizationId:f,metadata:{apiKey:this.configService.getApiKey(),organizationId:f,veltFolderId:m?.metadata?.veltFolderId,documentId:u}},data:JSON.parse(JSON.stringify(m))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=Oh(this.functions,Eh({url:this.endpointsService.getCloudFunctionUrl("chatgptCompletion"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return jn(t({messages:i,apiKey:this.configService.getApiKey(),sdkVersion:SC(),sdkType:this.configService.getSdkType(),numResponse:1})).pipe(Ee(d=>{if(d?.data){let m=d.data,u=m?.length?m[0]?.content?.trim():void 0;return u&&Object.keys(this.customCategoryMap).includes(u)?this.customCategoryMap[u]:void 0}else return}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),ye(void 0)}}applyListenerVisibilityPostFilter(e,t,a,i){try{let d=Pu(e,{userId:a,tokens:t});i&&(d=sC(d,i));let m=(e||[]).filter(u=>!d.includes(u));return m.length&&this.evictAnnotationsFromLocalCache(m.map(u=>u?.annotationId).filter(u=>!!u)),d}catch(d){return this.loggingService.catch("Error in CommentService applyListenerVisibilityPostFilter: ",d),e}}applyPortableQueryScopeFilter(e,t){try{let{kept:a,departed:i}=T0(e,t,d=>gC(d,t.scope));return i.length&&this.evictResultSetDepartures(i),a}catch(a){return this.loggingService.catch("Error in CommentService applyPortableQueryScopeFilter: ",a),e}}evictResultSetDepartures(e){try{if(!e?.length)return;this.evictAnnotationsFromLocalCache(e),this.evictProgressComments(e)}catch(t){this.loggingService.catch("Error in CommentService evictResultSetDepartures: ",t)}}evictAnnotationsFromLocalCache(e){try{if(!e?.length)return;let t=this.commentAnnotationById$?.value;if(t&&e.some(a=>a in t)){let a=g({},t);e.forEach(i=>{delete a[i]}),this.commentAnnotationById$.next(a)}}catch(t){this.loggingService.catch("Error in CommentService evictAnnotationsFromLocalCache: ",t)}}preserveAccessSentinels(e,t){try{return e&&typeof e=="object"&&t&&typeof t=="object"&&("_setAccessFields"in e&&!("_setAccessFields"in t)&&(t._setAccessFields=e._setAccessFields),"_replaceAccessFields"in e&&!("_replaceAccessFields"in t)&&(t._replaceAccessFields=e._replaceAccessFields)),t}catch(a){return this.loggingService.catch("Error in CommentService preserveAccessSentinels: ",a),t}}applyContextAccessDefaults(e){try{this.handleDirectAccessFieldsAssignment(e?.context)||(e?.context?.access?e.context.accessFields?.length||(e.context.accessFields=Nm(e.context)):Om(e?.context?.accessFields).length>0||(e?.context||(e.context={}),e.context.access={default:"velt"},e.context.accessFields=[...new Set([...e.context.accessFields||[],Z.DEFAULT_VELT_CONTEXT])]))}catch(t){this.loggingService.catch("Error in CommentService applyContextAccessDefaults: ",t)}}buildContextAccessFieldsPreservingVisibility(e,t){try{return Fu(e,Om(t))}catch(a){return this.loggingService.catch("Error in CommentService buildContextAccessFieldsPreservingVisibility: ",a),[...t||[]]}}handleDirectAccessFieldsAssignment(e){try{if(!e||typeof e!="object"||!("_setAccessFields"in e)&&!("_replaceAccessFields"in e))return!1;let t=!("_setAccessFields"in e),a=t?e._replaceAccessFields:e._setAccessFields;delete e._setAccessFields,delete e._replaceAccessFields;let i=Array.isArray(a)?a:[];if(!(!t&&Sh(e.access)))return delete e.access,delete e.accessFields,i.length>0&&(e.accessFields=i),!0;let m=i.length>0&&!i.includes(Z.DEFAULT_VELT_CONTEXT),u;return m?u=Fu(e,i):this.userPermissionService?.getIsContextEnabled()?u=Fu(e,i):u=[...new Set([...i,...Nm(e)])],u.length>0?e.accessFields=u:delete e.accessFields,!0}catch(t){return this.loggingService.catch("Error in CommentService handleDirectAccessFieldsAssignment: ",t),!1}}updateCommentAnnotationContext(e,t,a){return Pe(this,null,function*(){try{this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:a?.merge});let i=this.authService.getUser(),d=this.docService.getDocumentPaths();if(i&&d?.comment&&e){let m=this.getAnnotationById(e);if(typeof m=="object"&&(m=JSON.parse(JSON.stringify(m))),m||(m=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:d?.documentId??"",organizationId:d?.organizationId??"",id:e}})),m?.annotationId){let u=t,f=JSON.parse(JSON.stringify(m.context||{}));if(a?.merge&&(u=g(g({},f),t),Sh(f?.access)&&t?.access&&typeof t.access=="object"&&!Array.isArray(t.access))){let W=g(g({},f.access),t.access);Object.keys(W).forEach($=>{(W[$]===null||W[$]===void 0)&&delete W[$]}),u.access=Object.keys(W).length?W:{default:"velt"}}let y=this.handleDirectAccessFieldsAssignment(u);if(u&&"_setVisibilityConfig"in u&&(m.visibilityConfig=u._setVisibilityConfig,delete u._setVisibilityConfig),u&&typeof u=="object"&&!y)if("access"in t)if(t.access!==null&&t.access!==void 0)u.accessFields=this.buildContextAccessFieldsPreservingVisibility(u,f?.accessFields);else{delete u.access;let W=Om(f?.accessFields);W.length?u.accessFields=W:delete u.accessFields}else{if(!a?.merge)for(let W of OD)!(W in t)&&f?.[W]!==void 0&&(u[W]=f[W]);u.access!==null&&u.access!==void 0&&(u.accessFields=this.buildContextAccessFieldsPreservingVisibility(u,f?.accessFields))}let S={context:JSON.parse(JSON.stringify(u||{}))},j=!1;if(S?.context?.commentType==="manual"&&(S.commentType="manual",S.targetElement=null,m?.targetElement&&(m.targetElement=null,j=!0)),m.context=S.context?Cn(S.context):S.context,m.contextId=this.generateContextId(m.context),xn(f,u)&&!j)return Promise.resolve("Comment annotation context is already updated.");if(m?.comments?.length){m.lastUpdated=this.timestamp;let W=this.commentAnnotationById$?.value?.[e]?JSON.parse(JSON.stringify({context:this.commentAnnotationById$.value[e].context??null,contextId:this.commentAnnotationById$.value[e].contextId??null,visibilityConfig:this.commentAnnotationById$.value[e].visibilityConfig})):null;this.patchLocalAnnotationContext(e,m);let $=JSON.stringify({context:m.context??null,visibilityConfig:m.visibilityConfig}),{documentId:H,organizationId:q}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(m);return this.commonDbService.setData({feature:"comment",properties:{id:e,documentId:H,organizationId:q,metadata:{apiKey:this.configService.getApiKey(),organizationId:q,veltFolderId:m?.metadata?.veltFolderId,documentId:H}},data:JSON.parse(JSON.stringify(m)),callback:()=>{this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:S?.context,merge:a?.merge})},errorCallback:()=>{try{let ce=this.commentAnnotationById$?.value,fe=ce?.[e];if(!ce||!fe||!W||JSON.stringify({context:fe.context??null,visibilityConfig:fe.visibilityConfig})!==$)return;let he=b(g({},fe),{context:W.context,contextId:W.contextId});W.visibilityConfig===void 0?delete he.visibilityConfig:he.visibilityConfig=W.visibilityConfig,this.commentAnnotationById$.next(b(g({},ce),{[e]:he}))}catch(ce){this.loggingService.catch("Error reverting optimistic context patch: ",ce)}}})}else return this.draftCommentAnnotationsByAnnotationId$.value?.[e]?(this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e]:m})),Promise.resolve("Draft comment annotation context updated.")):(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:a?.merge,error:"Draft comment annotation not found."}),Promise.resolve("Draft comment annotation not found."))}else return this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:a?.merge,error:"Comment annotation not found in database."}),Promise.resolve("Comment annotation not found in database.")}}catch(i){return this.loggingService.catch("Error in CommentService updateCommentAnnotationContext: ",i),Promise.resolve("Error in CommentService updateCommentAnnotationContext.")}})}patchLocalAnnotationContext(e,t){try{let a=this.commentAnnotationById$?.value,i=a?.[e];if(!a||!i)return;let d=g(b(g({},i),{context:t?.context?JSON.parse(JSON.stringify(t.context)):i.context,contextId:t?.contextId??i.contextId}),t?.visibilityConfig!==void 0?{visibilityConfig:JSON.parse(JSON.stringify(t.visibilityConfig))}:{});this.commentAnnotationById$.next(b(g({},a),{[e]:d}))}catch(a){this.loggingService.catch("Error in CommentService patchLocalAnnotationContext: ",a)}}updateComment(e,t,a,i,d,m){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(ke.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let u=this.domService.getXPath(e.targetElement.xpath);if(u){let f=u.iterateNext();f&&(kn(f)||(e.targetElement=null))}}if(e?.type==="multiThread"){let u=JSON.parse(JSON.stringify(e));if(u.position=null,u.ghostComment=null,u?.context&&this.handleDirectAccessFieldsAssignment(u.context),!u?.metadata?.documentId){u?.metadata||(u.metadata={});let S=this.docService.getBaseMetadata("multiThread");u.metadata=g(g({},u?.metadata),S)}let{documentId:f,organizationId:y}=u?.metadata||{};a?this.commonDbService.updateData({feature:"multiThread",properties:{id:u.annotationId,documentId:f,organizationId:y},data:JSON.parse(JSON.stringify(u))}):this.commonDbService.setData({feature:"multiThread",properties:{id:u.annotationId,documentId:f,organizationId:y},data:JSON.parse(JSON.stringify(u))})}else{this.setSubscribedUsersDataInCommentAnnotation(e);let u=JSON.parse(JSON.stringify(e));if(u.position=null,u.ghostComment=null,u.lastUpdated=this.timestamp,u.status||(u.status=this.customFilterService.defaultStatus),delete u.resolved,delete u.inProgress,this.setLocationFromDocumentParams(u),u?.context&&this.handleDirectAccessFieldsAssignment(u.context),u?.annotationId?.startsWith("TEMP_COMPOSER_"))return;let f=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(f&&JSON.parse(f).annotationId===u.annotationId&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),u?.multiThreadAnnotationId&&!d&&this.saveMultiThreadCommentAnnotation(u).then(y=>{}),u?.comments?.length){if(delete u?.isDraft,u?.multiThreadAnnotationId&&this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[u?.multiThreadAnnotationId]&&this.saveMultiThreadCommentAnnotation(u),!u?.metadata?.documentId){u?.metadata||(u.metadata={});let W=this.docService.getBaseMetadata("comment");u.metadata=g(g({},u?.metadata),W)}let{documentId:y,organizationId:S}=u?.metadata||{},j=i?g({annotationData:i?.commentAnnotation,targetAnnotationData:i?.targetComment,actionType:i?.actionType,notificationSource:"comment"},i?.otherFields||{}):null;this.viewsService?.updateCommentAnnotationViews(u),this.commonDbService.setData({feature:"comment",properties:{id:u.annotationId,documentId:y,targetCommentId:m?.commentId,organizationId:S,metadata:{apiKey:this.configService.getApiKey(),organizationId:S,veltFolderId:u?.metadata?.veltFolderId,documentId:y}},extraData:j,data:JSON.parse(JSON.stringify(u)),callback:W=>Pe(this,null,function*(){if(i&&!W?.firestoreAvailable&&this.updateNotificationsDatabase(i.commentAnnotation,i.targetComment,i.actionType,i.otherFields||{}),this.getScreenshotEnabled()&&i?.actionType===qe.NEWLY_ADDED&&this.captureScreenshot(e),i?.actionType===qe.NEWLY_ADDED||i?.actionType===qe.ADDED)try{let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:u.annotationId,commentAnnotation:this.getCommentAnnotationForClient(u),metadata:$};this.commentActionsService?.triggerAction(ct.COMMENT_SAVED,H)}catch($){this.loggingService.catch("Error triggering commentSaved event: ",$)}})})}else this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:u}))}}}catch(u){this.loggingService.catch("Error in CommentService updateComment: ",u)}}captureScreenshot(e){return Pe(this,null,function*(){try{if(this.getScreenshotEnabled()){let a=Oh(this.functions,Eh({url:this.endpointsService.getCloudFunctionUrl("screenshot"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i,d={source:"velt",sourceData:{commentAnnotation:e},eventType:"screenshot"};e?.areaAnnotationId&&(i=this.areaService?.getAnnotationById(e?.areaAnnotationId),i&&(d.sourceData||(d.sourceData={}),d.sourceData.areaAnnotation=i));let m=yield bC(d,this.authService.getUser()?.userId??"");yield a({veltData:m})}}catch(t){this.loggingService.catch("Error in CommentService captureScreenshot: ",t)}})}getDocumentIdAndOrganizationIdFromCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}setLocationFromDocumentParams(e){e?.documentParams&&(e.location=e.documentParams,delete e.documentParams),e?.documentParamsId&&(e.locationId=e.documentParamsId,delete e.documentParamsId)}deleteCommentPinAnnotations(e){return new Promise((t,a)=>Pe(this,null,function*(){try{let i=this.domService.getSelectedAnnotationsMap(),d=this.authService.getUser(),m=[];Object.keys(i).forEach(u=>{let f=i[u];["tag","recorder","rewriter","arrow","area","multiThread"].includes(f.type)||d&&f.from&&(d?.isAdmin||f.from.userId===d.userId)&&m.push(f)}),m?.length?(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DELETE_TRIGGERED,{triggerType:e,annotationId:m.map(u=>u.annotationId).join(),commentMode:this.getCommentMode()}),this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:{title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"}}).afterClosed().pipe(qo(1)).subscribe(u=>{try{u?(m.forEach(f=>Pe(this,null,function*(){yield this.deleteCommentPinAnnotation(f)})),setTimeout(()=>{document.querySelectorAll(`[${Z.SNIPPYLY_HIGHLIGHT}]`).forEach(y=>{this.domService.removeHighlightFromElement(y)}),t()},100)):t()}catch(f){a(f)}},u=>{a(u)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(i){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",i),a(i)}}))}deleteCommentPinAnnotation(e,t){return Pe(this,null,function*(){try{if(setTimeout(()=>{if(!this.draftConfirmationPendingAnnotationIds?.has(e?.annotationId)&&this.draftCommentAnnotationsByAnnotationId$?.value?.[e.annotationId]){let a=this.draftCommentAnnotationsByAnnotationId$.value;delete a[e.annotationId],this.draftCommentAnnotationsByAnnotationId$.next(a)}},50),e?.annotationId&&this.pendingAddCommentAnnotationData.delete(e.annotationId),this.authService.isFeatureAllowed(ke.COMMENT)){let a=!!(t||e.comments?.length);if(a&&this.updateNotificationsDatabase(e,null,qe.DELETED),e.comments?.forEach(i=>{i.reactionAnnotationIds&&i.reactionAnnotationIds.forEach(d=>{this.deleteReaction(d)})}),e?.annotationId){this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DELETED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode()});let i=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);i&&JSON.parse(i).annotationId===e.annotationId&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),this.areaService?.onDeleteTargetAnnotation(e?.annotationId,e?.areaAnnotationId);let d={type:"delete",annotation:null,targetAnnotationId:e.annotationId};this.commentUpdated$.next(d),e?.multiThreadAnnotationId&&(yield this.removeCommentAnnotationFromMultiThread(e)),this.commentAnnotationDeleted$.next(e);let{documentId:m,organizationId:u}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(e);if(e?.isDraft)return Promise.resolve();{let f={annotationData:e,targetAnnotationData:null,actionType:qe.DELETED,notificationSource:"comment",isAnnotationDelete:!0};return this.commonDbService.deleteData(g({feature:"comment",properties:{id:e.annotationId,documentId:m,organizationId:u,metadata:{apiKey:this.configService.getApiKey(),organizationId:u,veltFolderId:e?.metadata?.veltFolderId,documentId:m}},extraData:f},a?{hubNotification:this.buildCommentNotificationRawData(e,null,qe.DELETED)}:{}))}}else return Promise.resolve()}return Promise.resolve()}catch(a){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",a),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return Pe(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let a=this.docService.getDocumentPaths(),i=e?.metadata?.documentId,d=this.getMultiThreadAnnotationById(t,i?{documentId:i}:void 0);if(!d){let y=e?.metadata?.documentId||a?.documentId,S=e?.metadata?.organizationId||a?.organizationId,j=yield this.readMultiThreadRow({documentId:y,organizationId:S,id:t});if(!j.answered)return;d=j.data}let m=this.getDraftMultiThreadAnnotationOfDocument(t,i);if(d&&delete d?.commentAnnotations?.[e.annotationId],m&&(delete m?.commentAnnotations?.[e.annotationId],Object.keys(m?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(this.draftMultiThreadCommentAnnotationsByAnnotationId$.value))),!d)return;delete d.commentAnnotationsMap;let{documentId:u,organizationId:f}=this.getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(d);return Object.keys(d?.commentAnnotations||{}).length===0?(this.areaService?.onDeleteTargetAnnotation(d?.annotationId,d?.areaAnnotationId),this.multiThreadCommentAnnotationDeleted$.next(d),this.commonDbService.deleteData({feature:"multiThread",properties:{id:d?.annotationId,documentId:u,organizationId:f}})):this.commonDbService.setData({feature:"multiThread",properties:{id:d?.annotationId,documentId:u,organizationId:f},data:JSON.parse(JSON.stringify(d))})}}catch(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let a=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(a){let{documentId:i,organizationId:d}=t||{};if(i&&a.metadata?.documentId!==i||d&&a.metadata?.organizationId!==d)return}return a}catch(a){this.loggingService.catch("Error in CommentService getAnnotationById: ",a);return}}getBaseMetadataFromCommentAnnotationId(e){try{let t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}isCommentAnnotationCacheLoaded(){try{return this.commentAnnotationById$.value!=null}catch(e){return this.loggingService.catch("Error in CommentService isCommentAnnotationCacheLoaded: ",e),!1}}getDraftMultiThreadAnnotationOfDocument(e,t){let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[e];if(!(a&&t&&a.metadata?.documentId&&String(a.metadata.documentId)!==String(t)))return a}getMultiThreadAnnotationById(e,t){try{let a=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(a){let{documentId:i,organizationId:d}=t||{};if(i&&a.metadata?.documentId!==i||d&&a.metadata?.organizationId!==d)return}return a}catch(a){this.loggingService.catch("Error in CommentService getAnnotationById: ",a);return}}getBaseMetadataFromMultiThreadCommentAnnotationId(e){try{let t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let a=t?.targetElement?.xpath;if(a)return{xpath:a}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),a=document.getElementById(`comment-pin-container-${e}`);a||(a=document.querySelector(`[data-velt-id='${e}']`)),a||(a=document.querySelector(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),a&&(a.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");let a=e?this.getAnnotationById(e):void 0;a?this.domService.toggleAnnotationSelection(a,void 0,void 0,!0):this.domService.resetSelectedAnnotationsMap()}catch(a){this.loggingService.catch("Error in CommentService selectCommentByAnnotationId: ",a)}}enableAddCommentMode(){try{this.authService.isFeatureAllowed(ke.COMMENT)?!this.authService.isPlanExpired()&&this.iamService.hasRoleAny([gc.ADMIN,gc.COMMENTER])?(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!0)):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","User is not allowed to add comment."):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","Comment feature is not enabled.")}catch(e){this.loggingService.catch("Error in CommentService enableAddCommentMode: ",e)}}disableAddCommentMode(){this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!1)}addCommentModeChange(){return this.addCommentMode$.asObservable()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}enablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{persistentCommentMode:!0}}),this.persistentCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePersistentCommentMode: ",e)}}enableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteReplyConfirmation:!0}}),this.deleteReplyConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteReplyConfirmation: ",e)}}enableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{seenByUsers:!0}}),this.seenByUsers$.value===!0)return;this.seenByUsers$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSeenByUsers: ",e)}}disableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{seenByUsers:!1}}),this.seenByUsers$.value===!1)return;this.seenByUsers$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSeenByUsers: ",e)}}getSeenByUsers$(){return this.seenByUsers$.asObservable()}disableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteReplyConfirmation:!1}}),this.deleteReplyConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteReplyConfirmation: ",e)}}disablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{persistentCommentMode:!1}}),this.persistentCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePersistentCommentMode: ",e)}}persistentCommentModeChange(){return this.persistentCommentMode$.asObservable()}enablePersistentModeBanner(){this.persistentModeBanner$.next(!0)}disablePersistentModeBanner(){this.persistentModeBanner$.next(!1)}persistentModeBannerChange(){return this.persistentModeBanner$.asObservable()}setAssignToType(e){try{this.assignToType$.next(e.type)}catch(t){this.loggingService.catch("Error in CommentService setAssignToType: ",t)}}getAssignToType$(){return this.assignToType$.asObservable()}getAssignToType(){return this.assignToType$.value}setPageModeComposerContext(e){try{this.pageModeComposerContext$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPageModeComposerContext: ",t)}}clearPageModeComposerContext(){try{this.pageModeComposerContext$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearPageModeComposerContext: ",e)}}getPageModeComposerContext$(){return this.pageModeComposerContext$.asObservable()}getPageModeComposerContext(){return this.pageModeComposerContext$.value}enableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableContextInPageModeComposer: ",e)}}disableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableContextInPageModeComposer: ",e)}}getContextInPageModeComposer$(){return this.contextInPageModeComposer$.asObservable()}getContextInPageModeComposer(){return this.contextInPageModeComposer$.value}focusPageModeComposer(){try{this.focusPageModeComposer$.next()}catch(e){this.loggingService.catch("Error in CommentService focusPageModeComposer: ",e)}}getFocusPageModeComposer$(){return this.focusPageModeComposer$.asObservable()}showCommentIndex(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentIndex:e}}),this.showCommentIndex$.value===e)return;this.showCommentIndex$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}getShowCommentIndex(){return this.showCommentIndex$.asObservable()}enablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverMode:!0}}),this.popoverMode$.value===!0)return;this.popoverMode$.next(!0),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_POPOVER_MODE_ENABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService enablePopoverMode: ",e)}}disablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverMode:!1}}),this.popoverMode$.value===!1)return;this.popoverMode$.next(!1),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_POPOVER_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService disablePopoverMode: ",e)}}getPopoverMode(){try{return this.popoverMode$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverMode: ",e),!1}}getPopoverMode$(){return this.popoverMode$.asObservable()}enablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverTriangleComponent:!0}}),this.popoverTriangleComponent$.value===!0)return;this.popoverTriangleComponent$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePopoverTriangleComponent: ",e)}}disablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverTriangleComponent:!1}}),this.popoverTriangleComponent$.value===!1)return;this.popoverTriangleComponent$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePopoverTriangleComponent: ",e)}}getPopoverTriangleComponent(){try{return this.popoverTriangleComponent$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverTriangleComponent: ",e),!1}}getPopoverTriangleComponent$(){return this.popoverTriangleComponent$.asObservable()}enableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftMode:!0}}),this.draftMode$.value===!0)return;this.draftMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftMode: ",e)}}disableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftMode:!1}}),this.draftMode$.value===!1)return;this.draftMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftMode: ",e)}}getDraftMode$(){return this.draftMode$.asObservable()}getDraftMode(){return this.draftMode$.value}enableDraftConfirmation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftConfirmation:!0}}),this.draftConfirmation$.value===!0)return;this.draftConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftConfirmation: ",e)}}disableDraftConfirmation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftConfirmation:!1}}),this.draftConfirmation$.value===!1)return;this.draftConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftConfirmation: ",e)}}getDraftConfirmation$(){return this.draftConfirmation$.asObservable()}getDraftConfirmation(){return this.draftConfirmation$.value}enableIdScopedAnchoring(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{idScopedAnchoring:!0}});let{documentIds:t,problem:a}=r0(e);a==="not-an-array"?console.warn("[Velt] enableIdScopedAnchoring: `documentIds` must be an array of document ids; id-scoped anchoring now applies to no document."):a==="dropped-entries"&&console.warn("[Velt] enableIdScopedAnchoring: `documentIds` entries that are not non-empty strings were ignored.");let i=this.idScopedAnchoringConfig$.value;if(i.enabled&&Ah(i.documentIds,t))return;Ah(i.documentIds,t)||(this.idScopedAnchoringScope=t?{clientIds:new Set(t),serverIds:new Set(t.map(d=>this.docService.generateDocumentId(d)))}:null),this.idScopedAnchoring$.value!==!0&&this.idScopedAnchoring$.next(!0),this.idScopedAnchoringVersion++,this.idScopedAnchoringConfig$.next({enabled:!0,documentIds:t})}catch(t){this.loggingService.catch("Error in CommentService enableIdScopedAnchoring: ",t)}}disableIdScopedAnchoring(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{idScopedAnchoring:!1}}),this.idScopedAnchoring$.value===!1)return;this.idScopedAnchoring$.next(!1),this.idScopedAnchoringVersion++,this.idScopedAnchoringConfig$.next(b(g({},this.idScopedAnchoringConfig$.value),{enabled:!1}))}catch(e){this.loggingService.catch("Error in CommentService disableIdScopedAnchoring: ",e)}}getIdScopedAnchoring$(){return this.idScopedAnchoring$.asObservable()}getIdScopedAnchoring(){return this.idScopedAnchoring$.value}getIdScopedAnchoringVersion(){return this.idScopedAnchoringVersion}getIdScopedAnchoringDocumentIds(){let e=this.idScopedAnchoringConfig$.value.documentIds;return e?[...e]:null}getIdScopedAnchoringConfig$(){return this.idScopedAnchoringConfig$.asObservable()}sameUnlessIdScopedAnchoringChanged(e){let t=this.idScopedAnchoringVersion;return(a,i)=>{let d=this.idScopedAnchoringVersion,m=d!==t;return t=d,!m&&e(a,i)}}distinctUnlessIdScopedAnchoringChanged(e){return t=>tu(()=>t.pipe(Gt(this.sameUnlessIdScopedAnchoringChanged(e))))}jsonSnapshotUnlessIdScopedAnchoringChanged(e){return t=>tu(()=>{let a=this.idScopedAnchoringVersion,i=null,d=m=>{try{let u=m;if(!u||typeof u!="object")return i=null,!1;let f={generation:u.dataGeneration,filtered:u.filteredAnnotations,textMap:u.textAnnotationsElementMap},y=!!i&&f.generation!==void 0&&i.generation===f.generation&&m0(i.filtered,f.filtered,LD)&&c0(i.textMap??null,f.textMap??null);return i=f,y}catch(u){return this.loggingService.catch("Error in CommentService jsonSnapshotUnlessIdScopedAnchoringChanged: ",u),i=null,!1}};return t.pipe(v0({select:e,knownUnchanged:d,forceEmit:()=>{try{let m=this.idScopedAnchoringVersion,u=m!==a;return a=m,u}catch(m){return this.loggingService.catch("Error in CommentService jsonSnapshotUnlessIdScopedAnchoringChanged forceEmit: ",m),!1}}}))})}withIdScopedAnchoringChanges(e,t){return e?t?e:Bt([e,this.getIdScopedAnchoringConfig$()]):t?ye(null):this.getIdScopedAnchoringConfig$()}buildNewPinTargetElement(e){let t=u=>{let f=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,y=>this.applyCommentPinTargetModifier(y),!0,void 0,u);if(this.getCommentToNearestAllowedElement()&&f?.xpath){let y=this.domService.getElementFromXPath(f.xpath);if(y&&!this.isElementInsideAllowedElements(y)){let S=this.getNearestAllowedElement(y);if(!S)return{targetElement:null,skip:!0};f.xpath=this.domService.getXPath(S,!1,!1,void 0,u),f.fXpath=this.domService.getXPath(S,!0),f.cfXpath=this.domService.getXPath(S,!0,!0),f.anchor=this.domService.generateAnchorRecord(S,u)}}return{targetElement:f,skip:!1}},a=this.getPinXPathOptions({element:e?.target}),i=t(a);if(i.skip||!i.targetElement?.xpath||!this.idScopedAnchoringScope)return i;let d=this.domService.getElementFromXPath(i.targetElement.xpath),m=d?this.getPinXPathOptions({element:d}):a;return!!m==!!a?i:t(m)}getPinXPathOptions(e){if(this.idScopedAnchoring$?.value){if(!this.idScopedAnchoringScope)return{ignoreGeneratedIds:!0};try{if(e?.annotation)return this.isIdScopedAnchoringForAnnotation(e.annotation)?{ignoreGeneratedIds:!0}:void 0;let t=e?.element instanceof Element?e.element:null,a=this.docService.getAdditionalDocumentIdFromElement(t)||this.docService.getDocumentPaths()?.clientDocumentId;return a&&this.idScopedAnchoringScope.clientIds.has(String(a))?{ignoreGeneratedIds:!0}:void 0}catch(t){this.loggingService.catch("Error in CommentService getPinXPathOptions: ",t);return}}}isIdScopedAnchoringForAnnotation(e){if(!this.idScopedAnchoring$?.value)return!1;let t=this.idScopedAnchoringScope;if(!t)return!0;let a=e?.metadata,i=a?.clientDocumentId;return i!=null&&i!==""?t.clientIds.has(String(i)):!!a?.documentId&&t.serverIds.has(String(a.documentId))}resolveIdScopedPinElement(e){try{let t=e?.targetElement;if(!t||!this.isIdScopedAnchoringForAnnotation(e))return;let a=this.domService.resolveIdScopedTarget(t);return a?.applicable?a.element&&kn(a.element)?a.element:null:void 0}catch(t){this.loggingService.catch("Error in CommentService resolveIdScopedPinElement: ",t);return}}enableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textMode:!0}}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_TEXT_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!0)return;this.textCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextComments: ",e)}}disableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textMode:!1}}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_TEXT_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!1)return;this.textCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextComments: ",e)}}getTextCommentMode$(){return this.textCommentMode$.asObservable()}isUserGlobalContact$(){return this.contactService.isUserGlobalContact$()}isSidebarOpenedByCustomTrigger(){try{return this.sidebarOpenedByCustomTrigger$.value}catch(e){return this.loggingService.catch("Error in CommentService isSidebarOpenedByCustomTrigger: ",e),!1}}requestSidebarFocus(e){let t=typeof e=="string"?e.trim():"";t&&ip()&&this.sidebarFocusRequest$.next({annotationId:t})}watchDocumentChangesForSidebarFocus(e){let t=null;e.subscribe(a=>{try{let i=(a||[]).map(m=>m?.documentId).filter(Boolean).sort(),d=i.length?JSON.stringify(i):null;d&&t&&d!==t&&this.consumeSidebarFocus(),d&&(t=d)}catch(i){this.loggingService.catch("Error in CommentService watchDocumentChangesForSidebarFocus: ",i)}})}consumeSidebarFocus(){this.sidebarFocusRequest$.value&&this.sidebarFocusRequest$.next(null)}getSidebarFocusRequest$(){return this.sidebarFocusRequest$.asObservable()}setSidebarVisibility(e,t=!1,a=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(ip()||document.querySelector(Z.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):(this.consumeSidebarFocus(),this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> or <${Z.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`)),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||a)&&(this.sidebarVisible$.next(e),this.consumeSidebarFocus(),this.sidebarOpenedByCustomTrigger$.next(!1),this.clearPageModeComposerContext()),e?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_OPENED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_CLOSED,{commentMode:this.getCommentMode()})}catch{this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1),this.sidebarVisible$.value||this.clearPageModeComposerContext()):(ip()||document.querySelector(Z.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarVisible$.value?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"closed"}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"opened"})):this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> or <${Z.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}getSidebarVisibility$(){return this.sidebarVisible$.asObservable()}disableFloatingComments(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{floatingCommentDialog:!e}}),this.floatingCommentsEnabled$.value===!e)return;this.floatingCommentsEnabled$.next(!e)}catch(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}showFloatingComments$(){return this.floatingCommentsEnabled$.asObservable()}showFloatingComments(){return this.floatingCommentsEnabled$.value}setModeratorMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{moderatorMode:e}}),this.moderatorMode$.value===e)return;this.moderatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}getModeratorMode(){return this.moderatorMode$.value}getModeratorMode$(){return this.moderatorMode$.asObservable()}setStreamMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{streamMode:e}}),this.streamMode$.value===e)return;this.streamMode$.next(e),e?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STREAM_MODE_ENABLED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STREAM_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}getStreamMode(){return this.streamMode$.value}getStreamMode$(){return this.streamMode$.asObservable()}getEnableDialogOnHover(){return this.enableDialogOnHover$.value}getEnableDialogOnHover$(){return this.enableDialogOnHover$.asObservable()}setEnableDialogOnHover(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogOnHover:e}}),this.enableDialogOnHover$.value===e)return;this.enableDialogOnHover$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}getEnableDialogOnTargetElementClick(){return this.enableDialogOnTargetElementClick$.value}getEnableDialogOnTargetElementClick$(){return this.enableDialogOnTargetElementClick$.asObservable()}setEnableDialogOnTargetElementClick(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogOnTargetElementClick:e}}),this.enableDialogOnTargetElementClick$.value===e)return;this.enableDialogOnTargetElementClick$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}getEnablePriority(){return this.enablePriority$.value}getEnablePriority$(){return this.enablePriority$.asObservable()}setEnablePriority(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{priority:e}}),this.enablePriority$.value===e)return;this.enablePriority$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}getEnableStatus(){return this.enableStatus$.value}getEnableStatus$(){return this.enableStatus$.asObservable()}setEnableStatus(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{status:e}}),this.getEnableStatus()===e)return;this.enableStatus$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}getEnableVisibilityOptions(){return this.visibilityOptions$.value}getEnableVisibilityOptions$(){return this.visibilityOptions$.asObservable()}setEnableVisibilityOptions(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{visibilityOptions:e}}),this.visibilityOptions$.value===e)return;this.visibilityOptions$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableVisibilityOptions: ",t)}}getEnableResolve(){return this.enableResolve$.value}getEnableResolve$(){return this.enableResolve$.asObservable()}setEnableResolve(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveButton:e}}),this.getEnableResolve()===e)return;this.enableResolve$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}getEnableGhostComments(){return this.enableGhostComments$.value}getEnableGhostComments$(){return this.enableGhostComments$.asObservable()}enableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostComments:!0}}),this.enableGhostComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGhostComments: ",e)}}disableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostComments:!1}}),this.enableGhostComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGhostComments: ",e)}}getEnableGhostCommentsMessage(){return this.enableGhostCommentsMessage$.value}getEnableGhostCommentsMessage$(){return this.enableGhostCommentsMessage$.asObservable()}enableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostCommentsIndicator:!0}}),this.enableGhostCommentsMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowGhostCommentsMessage: ",e)}}disableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostCommentsIndicator:!1}}),this.enableGhostCommentsMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowGhostCommentsMessage: ",e)}}enableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inboxMode:!0}}),this.inboxMode$.value===!0)return;this.inboxMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInboxMode: ",e)}}disableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inboxMode:!1}}),this.inboxMode$.value===!1)return;this.inboxMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInboxMode: ",e)}}getInboxMode(){return this.inboxMode$.value}getInboxMode$(){return this.inboxMode$.asObservable()}setEnableAutoCategorize(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{autoCategorize:e}}),this.enableAutoCategorize$.value===e)return;this.enableAutoCategorize$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}getEnableAutoCategorize(){return this.enableAutoCategorize$.value}getEnableAutoCategorize$(){return this.enableAutoCategorize$.asObservable()}setCommentContainerDarkMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{darkMode:e}}),this.commentContainerDarkMode$.value===e)return;this.commentContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}getCommentContainerDarkMode(){return this.commentContainerDarkMode$.asObservable()}getSuggestionMode(){return this.suggestionMode$.value}getSuggestionMode$(){return this.suggestionMode$.asObservable()}setSuggestionMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{suggestionMode:e}}),this.getSuggestionMode()===e)return;this.suggestionMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}getMobileMode(){return this.mobileMode$.value}getMobileMode$(){return this.mobileMode$.asObservable()}setMobileMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{mobileMode:e}}),this.getMobileMode()===e)return;this.mobileMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}enableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inlineCommentMode:!0}}),this.inlineCommentMode$.value===!0)return;this.inlineCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInlineCommentMode: ",e)}}disableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inlineCommentMode:!1}}),this.inlineCommentMode$.value===!1)return;this.inlineCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInlineCommentMode: ",e)}}getInlineCommentMode(){return this.inlineCommentMode$.value}getInlineCommentMode$(){return this.inlineCommentMode$.asObservable()}enableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{minimap:!0}}),this.minimap$.value===!0)return;this.minimap$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMinimap: ",e)}}disableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{minimap:!1}}),this.minimap$.value===!1)return;this.minimap$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMinimap: ",e)}}getMinimap(){return this.minimap$.value}getMinimap$(){return this.minimap$.asObservable()}showCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentsOnDom:!0}}),this.commentsOnDom$.value===!0)return;this.commentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showCommentsOnDom: ",e)}}hideCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentsOnDom:!1}}),this.commentsOnDom$.value===!1)return;this.commentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideCommentsOnDom: ",e)}}getCommentsOnDom(){return this.commentsOnDom$.value}getCommentsOnDom$(){return this.commentsOnDom$.asObservable()}enableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentTool:!0}}),this.commentToolEnabled$.value===!0)return;this.commentToolEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentTool: ",e)}}disableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentTool:!1}}),this.commentToolEnabled$.value===!1)return;this.commentToolEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentTool: ",e)}}getCommentTool(){return this.commentToolEnabled$.value}getCommentTool$(){return this.commentToolEnabled$.asObservable()}setTotalMediaLength(e){try{if(this.totalMediaLength$.value===e)return;this.totalMediaLength$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}getTotalMediaLength(){return this.totalMediaLength$.value}getTotalMediaLength$(){return this.totalMediaLength$.asObservable()}enableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarUrlNavigation:!0}}),this.sidebarUrlNavigationEnabled$.value===!0)return;this.sidebarUrlNavigationEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarUrlNavigation: ",e)}}disableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarUrlNavigation:!1}}),this.sidebarUrlNavigationEnabled$.value===!1)return;this.sidebarUrlNavigationEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarUrlNavigation: ",e)}}getSidebarUrlNavigation(){return this.sidebarUrlNavigationEnabled$.value}getSidebarUrlNavigation$(){return this.sidebarUrlNavigationEnabled$.asObservable()}setDetectionStrategy(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{detectionStrategy:e}}),this.detectionStrategy$.value===e)return;this.detectionStrategy$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}getDetectionStrategy(){return this.detectionStrategy$.value}getDetectionStrategy$(){return this.detectionStrategy$.asObservable()}enableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonOnCommentDialog:!0}}),this.sidebarButtonOnCommentDialogVisible$.value===!0)return;this.sidebarButtonOnCommentDialogVisible$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarButtonOnCommentDialog: ",e)}}disableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonOnCommentDialog:!1}}),this.sidebarButtonOnCommentDialogVisible$.value===!1)return;this.sidebarButtonOnCommentDialogVisible$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarButtonOnCommentDialog: ",e)}}getSidebarButtonOnCommentDialogVisibility(){return this.sidebarButtonOnCommentDialogVisible$.value}getSidebarButtonOnCommentDialogVisibility$(){return this.sidebarButtonOnCommentDialogVisible$.asObservable()}onSidebarButtonOnCommentDialogClick(){this.sidebarButtonOnCommentDialogClick$.next()}getSidebarButtonOnCommentDialogClick$(){return this.sidebarButtonOnCommentDialogClick$.asObservable()}enableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceIndicatorOnCommentPins:!0}}),this.deviceIndicatorOnCommentPins$.value===!0)return;this.deviceIndicatorOnCommentPins$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeviceIndicatorOnCommentPins: ",e)}}disableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceIndicatorOnCommentPins:!1}}),this.deviceIndicatorOnCommentPins$.value===!1)return;this.deviceIndicatorOnCommentPins$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeviceIndicatorOnCommentPins: ",e)}}getDeviceIndicatorOnCommentPins(){return this.deviceIndicatorOnCommentPins$.value}getDeviceIndicatorOnCommentPins$(){return this.deviceIndicatorOnCommentPins$.asObservable()}onSidebarCommentClick(e){this.sidebarCommentClick$.next(e)}getSidebarCommentClick$(){return this.sidebarCommentClick$.asObservable()}onCommentNavigationButtonClick(e){this.commentNavigationButtonClick$.next(e)}getCommentNavigationButtonClick$(){return this.commentNavigationButtonClick$.asObservable()}addBubbleCommentAnnotationIds(e){try{let a=[...this.bubbleCommentAnnotationIds$.value||[],...e],i=[...new Set(a)];this.bubbleCommentAnnotationIds$.next(i)}catch(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}getBubbleCommentAnnotationIds(){return this.bubbleCommentAnnotationIds$.value}getBubbleCommentAnnotationIds$(){return this.bubbleCommentAnnotationIds$.asObservable()}removeBubbleCommentAnnotationIds(e){try{let a=(this.bubbleCommentAnnotationIds$.value||[]).filter(i=>!e.includes(i));this.bubbleCommentAnnotationIds$.next(a)}catch(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}getSignInButton(){return this.enableSignInButton$.value}getSignInButton$(){return this.enableSignInButton$.asObservable()}onSignInClick(){this.onSignInClick$.next()}getSignInButtonClick$(){return this.onSignInClick$.asObservable()}enableUpgradeButton(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{upgradeButton:e}}),this.enableUpgradeButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}getUpgradeButton(){return this.enableUpgradeButton$.value}getUpgradeButton$(){return this.enableUpgradeButton$.asObservable()}onUpgradeClick(){this.onUpgradeClick$.next()}getUpgradeButtonClick$(){return this.onUpgradeClick$.asObservable()}openSidebar(){this.openSidebar$.next()}getOpenSidebar$(){return this.openSidebar$.asObservable()}enableAttachment(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachments:e}}),this.enableAttachment$.value===e)return;this.enableAttachment$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}getEnableAttachment$(){return this.enableAttachment$.asObservable()}enableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentDownload:!0}}),this.enableAttachmentDownload$.value===!0)return;this.enableAttachmentDownload$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentDownload: ",e)}}disableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentDownload:!1}}),this.enableAttachmentDownload$.value===!1)return;this.enableAttachmentDownload$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentDownload: ",e)}}getEnableAttachmentDownload$(){return this.enableAttachmentDownload$.asObservable()}getEnableAttachmentDownload(){return this.enableAttachmentDownload$.value}enableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatOptions:!0}}),this.enableFormatOptions$.value===!0)return;this.enableFormatOptions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFormatOptions: ",e)}}disableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatOptions:!1}}),this.enableFormatOptions$.value===!1)return;this.enableFormatOptions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFormatOptions: ",e)}}getEnableFormatOptions$(){return this.enableFormatOptions$.asObservable()}setFormatConfig(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatConfig:e}}),this.formatConfig$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setFormatConfig: ",t)}}getFormatConfig$(){return this.formatConfig$.asObservable()}setAllowedRecordings(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordings:e}}),e?.includes("all")?this.allowedRecordings$.next(["audio","video","screen"]):e?.includes("none")?this.allowedRecordings$.next([]):this.allowedRecordings$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}getAllowedRecordings(){return this.allowedRecordings$.value}getAllowedRecordings$(){return this.allowedRecordings$.asObservable()}enableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{reactions:!0}}),this.enableReactions$.value===!0)return;this.enableReactions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReactions: ",e)}}disableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{reactions:!1}}),this.enableReactions$.value===!1)return;this.enableReactions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReactions: ",e)}}getEnableReactions(){return this.enableReactions$.value}getEnableReactions$(){return this.enableReactions$.asObservable()}enableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!0)return;this.enableAnonymousEmail$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAnonymousEmail: ",e)}}disableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!1)return;this.enableAnonymousEmail$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAnonymousEmail: ",e)}}getEnableAnonymousEmail(){return this.enableAnonymousEmail$.value}getEnableAnonymousEmail$(){return this.enableAnonymousEmail$.asObservable()}addCommentOnElement(e){this.addComment(void 0,void 0,void 0,e)}enablePrivateCommentMode(){return Pe(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.privateCommentModeRequested=!0,this.privateCommentAllowed$.value?this.applyRequestedPrivateCommentMode():this.loggingService.logsEnabled&&console.warn("You are not allowed to enable private comment mode yet. It turns on once you are an admin or a member of the organization.")}catch(e){this.loggingService.catch("Error in CommentService enablePrivateCommentMode: ",e)}})}disablePrivateCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateCommentMode:!1}}),this.privateCommentModeRequested=!1,this.privateCommentMode$.value===!1)return;this.privateCommentMode$.next(!1),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_DISABLED)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateCommentMode: ",e)}}applyRequestedPrivateCommentMode(){try{if(!this.privateCommentModeRequested||(this.privateCommentModeRequested=!1,this.privateCommentMode$.value===!0))return;this.privateCommentMode$.next(!0),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_ENABLED)}catch(e){this.loggingService.catch("Error in CommentService applyRequestedPrivateCommentMode: ",e)}}getPrivateCommentMode(){return this.privateCommentMode$.value}getPrivateCommentMode$(){return this.privateCommentMode$.asObservable()}isPrivateCommentAllowed(){return this.privateCommentAllowed$.value}isPrivateCommentAllowed$(){return this.privateCommentAllowed$.asObservable()}enablePrivateMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateModeConfig:e}}),!e?.type){this.loggingService.catch("enablePrivateMode: type is required in config");return}this.privateModeConfig$.next(g({},e))}catch(t){this.loggingService.catch("Error in CommentService enablePrivateMode: ",t)}}disablePrivateMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateModeConfig:null}}),this.privateModeConfig$.value===null)return;this.privateModeConfig$.next(null)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateMode: ",e)}}getPrivateModeConfig(){return this.privateModeConfig$.value}getPrivateModeConfig$(){return this.privateModeConfig$.asObservable()}enableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{scrollToComment:!0}}),this.scrollToComment$.value===!0)return;this.scrollToComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScrollToComment: ",e)}}disableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{scrollToComment:!1}}),this.scrollToComment$.value===!1)return;this.scrollToComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScrollToComment: ",e)}}getScrollToComment(){return this.scrollToComment$.value}getScrollToComment$(){return this.scrollToComment$.asObservable()}showScreenSizeInfo(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceInfo:e}}),this.showScreenSizeInfo$.value===e)return;this.showScreenSizeInfo$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}getShowScreenSizeInfo$(){return this.showScreenSizeInfo$.asObservable()}enableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{userMentions:!0}}),this.userMentions$.value===!0)return;this.userMentions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableUserMentions: ",e)}}disableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{userMentions:!1}}),this.userMentions$.value===!1)return;this.userMentions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableUserMentions: ",e)}}getUserMentions(){return this.userMentions$.value}getUserMentions$(){return this.userMentions$.asObservable()}enablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!0)return;this.paginatedContactList$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePaginatedContactList: ",e)}}disablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!1)return;this.paginatedContactList$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePaginatedContactList: ",e)}}getPaginatedContactList(){return this.paginatedContactList$.value}getPaginatedContactList$(){return this.paginatedContactList$.asObservable()}enableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteOnBackspace:!0}}),this.deleteOnBackspace$.value===!0)return;this.deleteOnBackspace$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteOnBackspace: ",e)}}disableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteOnBackspace:!1}}),this.deleteOnBackspace$.value===!1)return;this.deleteOnBackspace$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteOnBackspace: ",e)}}getDeleteOnBackspace(){return this.deleteOnBackspace$.value}getDeleteOnBackspace$(){return this.deleteOnBackspace$.asObservable()}enableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{hotkey:!0}}),this.hotkeyEnabled$.value===!0)return;this.hotkeyEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableHotkey: ",e)}}disableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{hotkey:!1}}),this.hotkeyEnabled$.value===!1)return;this.hotkeyEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableHotkey: ",e)}}enableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingSummary:!0}}),this.recordingSummaryEnabled$.value===!0)return;this.recordingSummaryEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRecordingSummary: ",e)}}disableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingSummary:!1}}),this.recordingSummaryEnabled$.value===!1)return;this.recordingSummaryEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRecordingSummary: ",e)}}getRecordingSummaryEnabled(){return this.recordingSummaryEnabled$.value}getRecordingSummaryEnabled$(){return this.recordingSummaryEnabled$.asObservable()}setUnreadIndicatorMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{unreadIndicatorMode:e}}),this.unreadIndicatorMode$.value===e)return;this.unreadIndicatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}getUnreadIndicatorMode(){return this.unreadIndicatorMode$.value}getUnreadIndicatorMode$(){return this.unreadIndicatorMode$.asObservable()}setComposerMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setComposerMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{composerMode:e}}),this.composerMode$.value===e)return;this.composerMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}getComposerMode(){return this.composerMode$.value}getComposerMode$(){return this.composerMode$.asObservable()}enableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{enterKeyToSubmit:!0}}),this.enterKeyToSubmit$.value===!0)return;this.enterKeyToSubmit$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableEnterKeyToSubmit: ",e)}}disableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{enterKeyToSubmit:!1}}),this.enterKeyToSubmit$.value===!1)return;this.enterKeyToSubmit$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableEnterKeyToSubmit: ",e)}}getEnterKeyToSubmit(){return this.enterKeyToSubmit$.value}getEnterKeyToSubmit$(){return this.enterKeyToSubmit$.asObservable()}enablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinShadowDom:!0}}),this.pinShadowDOM$.value===!0)return;this.pinShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinShadowDOM: ",e)}}disablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinShadowDom:!1}}),this.pinShadowDOM$.value===!1)return;this.pinShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinShadowDOM: ",e)}}getPinShadowDOM(){return this.pinShadowDOM$.value}getPinDarkMode(){return this.pinDarkMode$.value}getPinDarkMode$(){return this.pinDarkMode$.asObservable()}getTextCommentToolDarkMode(){return this.textCommentToolDarkMode$.value}getTextCommentToolDarkMode$(){return this.textCommentToolDarkMode$.asObservable()}getTextCommentToolbarDarkMode(){return this.textCommentToolbarDarkMode$.value}getTextCommentToolbarDarkMode$(){return this.textCommentToolbarDarkMode$.asObservable()}getPinShadowDOM$(){return this.pinShadowDOM$.asObservable()}getTextCommentToolShadowDOM$(){return this.textCommentToolShadowDOM$.asObservable()}getTextCommentToolbarShadowDOM$(){return this.textCommentToolbarShadowDOM$.asObservable()}enableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogShadowDom:!0}}),this.dialogShadowDOM$.value===!0)return;this.dialogShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDialogShadowDOM: ",e)}}enableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarShadowDom:!0}}),this.textCommentToolbarShadowDOM$.value===!0)return;this.textCommentToolbarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarShadowDOM: ",e)}}disableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarShadowDom:!1}}),this.textCommentToolbarShadowDOM$.value===!1)return;this.textCommentToolbarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarShadowDOM: ",e)}}enableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolShadowDom:!0}}),this.textCommentToolShadowDOM$.value===!0)return;this.textCommentToolShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolShadowDOM: ",e)}}disableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolShadowDom:!1}}),this.textCommentToolShadowDOM$.value===!1)return;this.textCommentToolShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolShadowDOM: ",e)}}enableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolDarkMode:!0}}),this.textCommentToolDarkMode$.value===!0)return;this.textCommentToolDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolDarkMode: ",e)}}disableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolDarkMode:!1}}),this.textCommentToolDarkMode$.value===!1)return;this.textCommentToolDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolDarkMode: ",e)}}enableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarDarkMode:!0}}),this.textCommentToolbarDarkMode$.value===!0)return;this.textCommentToolbarDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarDarkMode: ",e)}}disableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarDarkMode:!1}}),this.textCommentToolbarDarkMode$.value===!1)return;this.textCommentToolbarDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarDarkMode: ",e)}}enablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDarkMode:!0}}),this.pinDarkMode$.value===!0)return;this.pinDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDarkMode: ",e)}}disablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDarkMode:!1}}),this.pinDarkMode$.value===!1)return;this.pinDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDarkMode: ",e)}}disableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogShadowDom:!1}}),this.dialogShadowDOM$.value===!1)return;this.dialogShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDialogShadowDOM: ",e)}}getDialogShadowDOM(){return this.dialogShadowDOM$.value}getDialogShadowDOM$(){return this.dialogShadowDOM$.asObservable()}setDialogShadowDOMExplicit(e){this.dialogShadowDOMExplicit$.next(e)}getDialogShadowDOMExplicit$(){return this.dialogShadowDOMExplicit$.asObservable()}enableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarShadowDOM:!0}}),this.sidebarShadowDOM$.value===!0)return;this.sidebarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarShadowDOM: ",e)}}disableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarShadowDOM:!1}}),this.sidebarShadowDOM$.value===!1)return;this.sidebarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarShadowDOM: ",e)}}getSidebarShadowDOM(){return this.sidebarShadowDOM$.value}getSidebarShadowDOM$(){return this.sidebarShadowDOM$.asObservable()}enableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{changeDetectionInCommentMode:!0}}),this.changeDetectionInCommentMode$.value===!0)return;this.changeDetectionInCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableChangeDetectionInCommentMode: ",e)}}disableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{changeDetectionInCommentMode:!1}}),this.changeDetectionInCommentMode$.value===!1)return;this.changeDetectionInCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableChangeDetectionInCommentMode: ",e)}}getChangeDetectionInCommentMode(){return this.changeDetectionInCommentMode$.value}getChangeDetectionInCommentMode$(){return this.changeDetectionInCommentMode$.asObservable()}showResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolvedCommentsOnDom:!0}}),this.resolvedCommentsOnDom$.value===!0)return;this.resolvedCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showResolvedCommentsOnDom: ",e)}}hideResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolvedCommentsOnDom:!1}}),this.resolvedCommentsOnDom$.value===!1)return;this.resolvedCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideResolvedCommentsOnDom: ",e)}}getResolvedCommentsOnDom(){return this.resolvedCommentsOnDom$.value}enableLazyLoadResolvedComments(){try{this.installLazyLoadResolvedCommentsProvider();let e=Um(this.documentPaths);if(e&&this.resolvedUnlockedDocumentKey===e){this.loggingService.catch("[lazyLoadResolvedComments] enabled, but resolved comments were already unlocked this session; takes effect on the next page load.",null,void 0,!0),this.lazyLoadResolvedComments$.next(!0);return}if(this.lazyLoadResolvedComments$.value===!0)return;this.lazyLoadResolvedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLazyLoadResolvedComments: ",e)}}disableLazyLoadResolvedComments(){try{if(this.lazyLoadResolvedComments$.value===!1)return;this.lazyLoadResolvedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLazyLoadResolvedComments: ",e)}}isResolvedUnlockedForCurrentDocument(){try{let e=Um(this.documentPaths);return!!e&&this.resolvedUnlockedDocumentKey===e}catch(e){return this.loggingService.catch("Error in CommentService isResolvedUnlockedForCurrentDocument: ",e),!0}}getLazyLoadResolvedComments(){return this.lazyLoadResolvedComments$.value}installLazyLoadResolvedCommentsProvider(){try{this.customFilterService?.setLazyLoadResolvedCommentsProvider?.(()=>this.lazyLoadResolvedComments$.value)}catch(e){this.loggingService.catch("Error in CommentService installLazyLoadResolvedCommentsProvider: ",e)}}publishResolvedIntent(e){try{this.defaultSidebarResolvedIntent=!!e,this.resolvedIntentFromSidebar$.next(!!e||this.anyNamedSidebarResolvedIntent())}catch(t){this.loggingService.catch("Error in CommentService publishResolvedIntent: ",t)}}anyNamedSidebarResolvedIntent(){if(!this.namedSidebarResolvedIntents?.size)return!1;for(let e of this.namedSidebarResolvedIntents.values())if(e)return!0;return!1}publishNamedSidebarResolvedIntent(e,t){try{if(typeof e!="string"||!e)return;t?this.namedSidebarResolvedIntents.set(e,!0):this.namedSidebarResolvedIntents.delete(e);let a=this.defaultSidebarResolvedIntent||this.anyNamedSidebarResolvedIntent();this.resolvedIntentFromSidebar$.value!==a&&this.resolvedIntentFromSidebar$.next(a)}catch(a){this.loggingService.catch("Error in CommentService publishNamedSidebarResolvedIntent: ",a)}}getResolvedCommentsOnDom$(){return this.resolvedCommentsOnDom$.asObservable()}enableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPin:!0}}),this.bubbleOnPinEnabled$.value===!0)return;this.bubbleOnPinEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPin: ",e)}}disableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPin:!1}}),this.bubbleOnPinEnabled$.value===!1)return;this.bubbleOnPinEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPin: ",e)}}getBubbleOnPin(){return this.bubbleOnPinEnabled$.value}getBubbleOnPin$(){return this.bubbleOnPinEnabled$.asObservable()}enableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPinHover:!0}}),this.bubbleOnPinHoverEnabled$.value===!0)return;this.bubbleOnPinHoverEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPinHover: ",e)}}disableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPinHover:!1}}),this.bubbleOnPinHoverEnabled$.value===!1)return;this.bubbleOnPinHoverEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPinHover: ",e)}}getBubbleOnPinHover(){return this.bubbleOnPinHoverEnabled$.value}getBubbleOnPinHover$(){return this.bubbleOnPinHoverEnabled$.asObservable()}enablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDrag:!0}}),this.pinDragEnabled$.value===!0)return;this.pinDragEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDrag: ",e)}}disablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDrag:!1}}),this.pinDragEnabled$.value===!1)return;this.pinDragEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDrag: ",e)}}getPinDrag(){return this.pinDragEnabled$.value}getPinDrag$(){return this.pinDragEnabled$.asObservable()}setExcludeLocationIdsFromSidebar(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{excludeLocationIdsFromSidebar:e}}),this.excludeLocationIdsFromSidebar$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}getExcludeLocationIdsFromSidebar(){return this.excludeLocationIdsFromSidebar$.value}getExcludeLocationIdsFromSidebar$(){return this.excludeLocationIdsFromSidebar$.asObservable()}enableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{multiThread:!0}}),this.multiThread$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMultiThread: ",e)}}disableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{multiThread:!1}}),this.multiThread$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMultiThread: ",e)}}getMultiThread(){return this.multiThread$.value&&!this.isMultiThreadUnservedOnPortable()}getMultiThread$(){let e=this.commonDbService?.portableConnectionChanges$?.()??ye(void 0);return Bt([this.multiThread$,e]).pipe(Ee(([t])=>t&&!this.isMultiThreadUnservedOnPortable()),Gt())}readMultiThreadRow(e){return Pe(this,null,function*(){try{if(this.commonDbService?.isPortableSession?.()!==!0)return{answered:!0,data:yield this.commonDbService?.getData({feature:"multiThread",properties:e})};this.commonDbService?.isPortableBackendActive?.()!==!0&&(yield ZC(o.PORTABLE_ACTIVATION_WAIT_MS));let t=(yield this.commonDbService?.readPortableDoc?.("multiThread",e))??{answered:!1};return!t.answered&&!this.multiThreadReadUnansweredLogged&&(this.multiThreadReadUnansweredLogged=!0,this.loggingService.catch("Velt [portable backend]: the multi-thread row could not be read. If the gateway does not serve the multiThread read (an older image \u2014 Part 116 S1), a new comment writes its container fresh; on a transient read failure the write is HELD (the stored row is not overwritten) and a removal keeps the stored row.",void 0,void 0,!0)),t}catch(t){return this.loggingService.catch("Error in CommentService readMultiThreadRow: ",t),{answered:!1}}})}applyMultiThreadFolderClause(e,t){return MD(e,t)}isMultiThreadUnservedOnPortable(){try{return!this.multiThread$.value||this.commonDbService?.isPortableBackendActive?.()!==!0||this.commonDbService.portableCapabilityState?.(zu)!=="absent"?!1:(this.multiThreadUnservedLogged||(this.multiThreadUnservedLogged=!0,this.loggingService.catch("Velt [portable backend]: multiThread is not served by this gateway",void 0,void 0,!0)),!0)}catch(e){return this.loggingService.catch("Error in CommentService isMultiThreadUnservedOnPortable: ",e),!1}}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.asObservable()}enableRestrictTextSearchToAnchor(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{restrictTextSearchToAnchor:!0}}),this.restrictTextSearchToAnchor$.value===!0)return;this.restrictTextSearchToAnchor$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRestrictTextSearchToAnchor: ",e)}}disableRestrictTextSearchToAnchor(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{restrictTextSearchToAnchor:!1}}),this.restrictTextSearchToAnchor$.value===!1)return;this.restrictTextSearchToAnchor$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRestrictTextSearchToAnchor: ",e)}}getRestrictTextSearchToAnchor(){return this.restrictTextSearchToAnchor$.value}getRestrictTextSearchToAnchor$(){return this.restrictTextSearchToAnchor$.asObservable()}enableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{shortUserName:!0}}),this.shortUserName$.value===!0)return;this.shortUserName$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShortUserName: ",e)}}disableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{shortUserName:!1}}),this.shortUserName$.value===!1)return;this.shortUserName$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShortUserName: ",e)}}getShortUserName(){return this.shortUserName$.value}getShortUserName$(){return this.shortUserName$.asObservable()}enableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingCountdown:!0}}),this.serviceBook.get(_n)?.enableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingCountdown:!1}}),this.serviceBook.get(_n)?.disableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService disableRecordingCountdown: ",e)}}setCommentSidebarFilters(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;"),this.commentSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value??{}}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setEffectiveSidebarFilters(e){try{this.effectiveSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEffectiveSidebarFilters: ",t)}}getEffectiveSidebarFilters$(){return this.effectiveSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.asObservable()}enableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentPinHighlighter:!0}}),this.domService.enableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService enableCommentPinHighlighter: ",e)}}disableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentPinHighlighter:!1}}),this.domService.disableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService disableCommentPinHighlighter: ",e)}}setCustomReactions(e){try{this.reactionService?.setCustomReactions(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}onCommentSelectionChange$(){return this.commentSelectionChange$.asObservable()}onVisibilityOptionClicked$(){return this.visibilityOptionClicked$.asObservable()}emitVisibilityOptionClicked(e){this.visibilityOptionClicked$.next(e)}onCommentAdd$(){return this.commentAdded$.asObservable()}onCommentUpdate$(){return this.commentUpdated$.asObservable()}onCommentAnnotationDelete$(){return this.commentAnnotationDeleted$.asObservable()}onMultiThreadCommentAnnotationDelete$(){return this.multiThreadCommentAnnotationDeleted$.asObservable()}getCommentMode(){try{let e="freestyle";return this.getStreamMode()?e="stream":this.getPopoverMode()&&(e="popover"),e}catch(e){return this.loggingService.catch("Error in CommentService getCommentMode: ",e),"freestyle"}}getCommentType(e){try{return e.targetElement?"element":e.targetTextRange?"text":e.areaAnnotationId?"area":""}catch(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,a,i){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(d=>this.docService.getAreaChanges$().pipe(Ee(()=>d))),Fe(d=>(!a&&t&&(a=Lr(t,["id","data-id"])),ye(b(g({},d),{element:a})))),Fe(d=>this.getLocations$().pipe(Ee(m=>b(g({},d),{locationIds:m})))),Ee(({locationIds:d,element:m})=>{let u=[],f=this.docService.getDocumentPaths();if(f?.documentId){let y=i?[i]:this.docService.getAreaDocumentIds(m),S=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:f?.organizationId,documentIds:y});if(S)for(let j of S)(t&&j?.targetElementId===t||j?.targetElement?.xpath===e)&&(d?.includes(j?.locationId)||rr(j))&&u.push(j)}return u.length?u:null}))}catch(d){return this.loggingService.catch("Error in CommentService isCommentAnnotationAvailableOnXPath: ",d),ye(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:a,clientDocumentId:i}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$()),Fe(()=>this.docService.getAreaChanges$()),Ee(()=>{let d=null,m=this.docService.getDocumentPaths(),u=Cn(e),f=this.generateContextId(u);if(m?.documentId){let y=i?[this.docService.generateDocumentId(i)]:this.docService.getAreaDocumentIds(a??null),S=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:m?.organizationId,documentIds:y});if(S){d=[];for(let j of S)t?.partialMatch?pC(j?.context,u)&&d.push(j):f&&j?.contextId===f&&d.push(j)}}return d}))}catch(d){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",d),ye(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(Ee(()=>this.getAnnotationById(e)),Fe(t=>t?t?.iam?.accessMode===gr.PRIVATE?this.isPrivateCommentAllowed$().pipe(Ee(a=>{if(a)return t})):ye(t):ye(t)),Fe(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(Ee(a=>{if(a)return a})):ye(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),ye(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(Ee(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${Z.TAGS.VELT_COMMENT_BUBBLE}[${Z.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${Z.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${Z.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e,t){try{return this.commentAnnotationById$.pipe(Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(a=>({documentPaths:a,sectionId:e})))),Fe(a=>this.docService.getAreaChanges$().pipe(Ee(()=>a))),Fe(a=>{let i=Lr(e,["id","data-id"]);if(i){let d=this.docService.getAdditionLocationFromElement(i);if(d){let m=this.docService.genarateLocationId(d);return this.docService.getLocations$().pipe(Ee(u=>{let y=Object.values(u||{}).find(S=>S.locationId===m||d?.id&&S.location.id===d.id);return b(g({},a),{additionalLocation:y,locationOnElement:!!d,element:i})}))}}return ye(b(g({},a),{additionalLocation:null,element:i}))}),Fe(a=>a?.locationOnElement?ye(a):this.docService.getLocation$().pipe(Ee(i=>b(g({},a),{location:i})))),Ee(({documentPaths:a,location:i,additionalLocation:d,locationOnElement:m,element:u})=>{let f=null;if(this.authService.getUser()&&a?.documentId){let S=t?[t]:this.docService.getAreaDocumentIds(u),j=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:a?.organizationId,documentIds:S});if(j){f=[];let W=En(e);m?d?.location?.id?W=En([d?.location?.id,e]):d?.locationId&&(W=En([d?.locationId+"",e])):i&&(i?.location?.id?W=En([i?.location?.id,e]):i?.locationId&&(W=En([i?.locationId+"",e])));for(let $ of j)$?.multiThreadAnnotationId===W?f.push($):($?.targetInlineCommentElementId===e||$?.targetElementId===e)&&(m?d&&fc({location:d?.location,locationId:d?.locationId},{location:$.location,locationId:$.locationId})&&f.push($):i?fc({location:i?.location,locationId:i?.locationId},{location:$.location,locationId:$.locationId})&&f.push($):$?.locationId||f.push($))}}return f}))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",a),ye(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(Fe(()=>this.multiThreadCommentAnnotationById$),Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(t=>({documentPaths:t,multiThreadAnnotationId:e})))),Ee(({documentPaths:t,location:a,additionalLocation:i,locationOnElement:d})=>{let m=null;if(t?.documentId){let u=this.getMultiThreadAnnotationById(e),{documentId:f,organizationId:y}=u?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},S=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:y,documentId:f||""});if(S){m=[];for(let j of S)j?.multiThreadAnnotationId===e&&u?.commentAnnotations?.[j?.annotationId]&&m.push(j)}}return m}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ye(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(t=>({documentPaths:t,annotationIds:e})))),Ee(({documentPaths:t})=>{let a=null;if(t?.documentId){let i=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],d=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(i=[...i,...d],i){a=[];for(let m of i)e.includes(m?.annotationId)&&a.push(m)}}return a}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),ye(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$()),Ee(()=>{e&&!t&&(t=ur(e));let a=this.authService.getUser(),i=this.docService.getDocumentPaths(),d=null;if(a&&i?.documentId){this.commentAnnotationById$.value&&(d={},Object.values(this.commentAnnotationById$.value).forEach(u=>{u?.metadata?.folderId==e&&u?.metadata?.veltFolderId==t&&(d[u?.annotationId]=u)}));let m=this.draftCommentAnnotationsByAnnotationId$.value;m&&(d===null&&(d={}),Object.values(m).forEach(u=>{u?.metadata?.folderId==e&&u?.metadata?.veltFolderId==t&&!d[u?.annotationId]&&(d[u?.annotationId]=u)}))}return d?Object.values(d):null}))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",a),ye(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:a,veltFolderId:i,targetElementId:d,clientDocumentId:m,documentId:u,context:f,contextOptions:y,element:S,type:j,sectionId:W,locationId:$}=e||{};if(m&&!u&&(u=this.docService.generateDocumentId(m)),a&&!i&&(i=ur(a)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(Ee(ce=>ce?[ce]:null));let H=[],q=S;if(d&&(j==="pin"||j==="tool"||j==="bubble")){let ce=Lr(d,["id","data-id"]);if(ce){let fe=ce;q=fe;let le=this.domService.getXPath(ce);H.push(this.getCommentAnnotationAvailableOnXPath(le,d,fe,u))}}return W&&H.push(this.getCommentAnnotationsBySectionId(W,u)),f&&H.push(this.getCommentAnnotationsByContext({context:f,contextOptions:y,element:q,clientDocumentId:m})),u&&H.push(this.getCommentAnnotationsByDocumentId$({documentId:u})),a&&H.push(this.getCommentAnnotationsByFolderId({folderId:a,veltFolderId:i})),H.length===0?ye(null):Bt(H).pipe(Ee(ce=>{let fe=ce.filter(he=>he!==null&&Array.isArray(he));if(fe.length===0)return null;if(fe.length===1){let he=fe[0];return $&&he?.length?he.filter(ze=>Lm(ze,$)):he}let le=fe[0];for(let he=1;he<fe.length;he++){let xe=fe[he];le=le.filter(ze=>xe.some(He=>He.annotationId===ze.annotationId))}return $&&le?.length&&(le=le.filter(he=>Lm(he,$))),le}),Gt(Qn))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),ye(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.allowedElementIds$.value?.length||this.allowedElementClassNames$.value?.length||this.allowedElementQuerySelectors$.value?.length?!!(this.allowedElementIds$.value?.length&&this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)||this.allowedElementClassNames$.value?.length&&this.domService.isElementInsideListedElementClassNames(e,this.allowedElementClassNames$.value)||this.allowedElementQuerySelectors$.value?.length&&this.domService.isElementInsideListedElementQuerySelectors(e,this.allowedElementQuerySelectors$.value)):!0}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}canCommentOnTextRange(e){try{let t=e?.commonAncestorContainer;return!e||!t?!1:Lu(e)?(this.logRichTextEditorBlock("text selection","range"),!1):this.isElementInsideAllowedElements(t)&&!Am(t)}catch(t){return this.loggingService.catch("Error in CommentService canCommentOnTextRange: ",t),!1}}isCommentBlockedOnElement(e){try{return Am(e)||Dr(e)}catch(t){return this.loggingService.catch("Error in CommentService isCommentBlockedOnElement: ",t),!1}}applyCommentPinTargetModifier(e){if(this.getSvgAsImg()){let t=e?.closest(`[${Z.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);t&&t instanceof HTMLElement&&(e=t)}if(this.getPopoverMode()){let t=e?.closest(`[${Z.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(t&&t instanceof HTMLElement)return t}return e}isCommentModeClickInsideRichTextEditor(e){try{let t=this.domService.getBackgroundElement(e?.clientX,e?.clientY,!0,!0);return t?(t=this.applyCommentPinTargetModifier(t),t&&this.getCommentToNearestAllowedElement()&&!this.isElementInsideAllowedElements(t)&&(t=this.getNearestAllowedElement(t)),Dr(t)?(this.logRichTextEditorBlock("comment-mode click","final-target"),!0):!1):!1}catch(t){return this.loggingService.catch("Error in CommentService isCommentModeClickInsideRichTextEditor: ",t),!1}}logRichTextEditorBlock(e,t){try{let a=`${e}|${t}`;if(this.lastRichTextEditorBlockLogKey===a)return;this.lastRichTextEditorBlockLogKey=a,this.loggingService.log(`[Velt] ${e} skipped: it touches a ProseMirror/TipTap editor.`)}catch{}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let a=0;a<t.length;a++){let i=t[a];if(e.contains(i)&&!Dr(i))return i}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,Z.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return Pe(this,null,function*(){try{if(t?.updatedComment?.isDraft&&this.draftConfirmation$?.value&&!(yield this.confirmDraftIfRequired(t.updatedComment,e?.annotationId)))return;t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let a=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(a?.comments?.length){let y=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],a.comments?.forEach(S=>{let j=y.find(W=>W.commentId===S.commentId);j?e.comments.push(j):e.comments.push(S)})}e.comments||(e.comments=[]);let i=!1,d=!1,m;switch(t.type){case qe.NEWLY_ADDED:case qe.ADDED:if(!t.updatedComment)break;e?.comments?.length||(d=!0),e.comments.push(t.updatedComment);let y=t?.assigned||void 0;m={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:y}};break;case qe.APPROVED:e.approved=!0,m={commentAnnotation:e,targetComment:null,actionType:qe.APPROVED};break;case qe.ASSIGNED:{let ce=a?.assignedTo;e.assignedTo=t.assignedTo,m={commentAnnotation:e,targetComment:null,actionType:qe.ASSIGNED,otherFields:{oldAssignedTo:ce,newAssignedTo:t.assignedTo}};break}case qe.UPDATED:if(!t.updatedComment)break;let S=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);if(S>=0){let ce=e.comments[S]?.commentText;e.comments[S]=t.updatedComment,e.comments[S].status=qe.UPDATED;let fe=t?.assigned||void 0;m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.UPDATED,otherFields:{assigned:fe,oldCommentText:ce}}}break;case qe.REACTION_ADDED:if(!t.updatedComment)break;let j=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);j>=0&&(e.comments[j]=t.updatedComment,e.comments[j].status=qe.UPDATED,m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.REACTION_ADDED});break;case qe.REACTION_DELETED:if(!t.updatedComment)break;let W=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);W>=0&&(e.comments[W]=t.updatedComment,e.comments[W].status=qe.UPDATED,m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.REACTION_DELETED});break;case qe.STATUS_CHANGED:if(e.status.type==="terminal"){this.domService.resetSelectedAnnotationsMap(!1,"comment");let ce=this.authService.getUser();e.resolvedByUserId=ce?.userId,e.resolvedByUser=ce}m={commentAnnotation:e,targetComment:null,actionType:qe.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case qe.PRIORITY_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case qe.ACCESS_MODE_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case qe.CUSTOM_LIST_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case qe.SUBSCRIBED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUBSCRIBED};break;case qe.UNSUBSCRIBED:m={commentAnnotation:e,targetComment:null,actionType:qe.UNSUBSCRIBED};break;case qe.DELETED:if(!t.updatedComment)break;let $=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);if($>=0){if(($===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let fe={};if(this.deleteReplyConfirmation$.value&&($!==0||this.deleteThreadWithFirstComment$.value===!1)?fe={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:fe={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:fe}).afterClosed().toPromise()))return}let ce=e.comments.splice($,1);ce?.length&&ce.forEach(fe=>{fe?.attachments&&this.deleteCommentAttachmentsForCascade(e,fe),fe?.reactionAnnotationIds&&fe.reactionAnnotationIds.forEach(le=>{this.deleteReaction(le)})})}e?.status?.type==="terminal"&&(e.status=this.customFilterService.defaultStatus),$===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?i=!0:(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.DELETED});break;case qe.ACCEPTED:let H={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:qe.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentAccepted$.next(H),m={commentAnnotation:e,targetComment:null,actionType:qe.ACCEPTED};break;case qe.REJECTED:let q={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:qe.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentRejected$.next(q),this.domService.resetSelectedAnnotationsMap(),m={commentAnnotation:e,targetComment:null,actionType:qe.REJECTED};break;case qe.SUGGESTION_ACCEPTED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUGGESTION_ACCEPTED,otherFields:{resolvedBy:e?.suggestion?.resolvedBy,resolvedAt:e?.suggestion?.resolvedAt}};break;case qe.SUGGESTION_REJECTED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUGGESTION_REJECTED,otherFields:{rejectReason:e?.suggestion?.rejectReason,resolvedBy:e?.suggestion?.resolvedBy,resolvedAt:e?.suggestion?.resolvedAt}};break;default:break}if(e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null,e.resolvedByUser=null),t.visibility)try{let y=g({},t.visibility);if(y.type==="organizationPrivate"&&!y.organizationId&&!y.organizationIds?.length){let W=this.docService.getOrganizationConfig();W?.clientOrganizationId&&(y.organizationId=W.clientOrganizationId)}let S=e.from?.userId||this.authService.getUser()?.userId,j=qn(y,S);j.length>0&&(e.context||(e.context={}),e.context._setAccessFields=j,e.visibilityConfig=Zn(y,S))}catch(y){this.loggingService.catch("Error building accessFields from visibility in saveComment:",y)}if(t?.updatedComment?.isDraft&&(m=void 0),i)this.deleteCommentPinAnnotation(e,!0),this.domService.resetSelectedAnnotationsMap(!1,"comment");else{d&&e.comments?.length&&this.enableAutoCategorize$?.value&&this.setCommentCategory(e);let y=this.authService.getUser()?.userId;if(!this.iamService.isUserAdmin()&&e.context?.access&&e.context?.accessFields&&t.updatedComment?.from?.userId&&y&&!this.userPermissionService?.hasUserContextAccess({userId:y,accessFields:e.context.accessFields})){this.loggingService.catch("User does not have context access to update comment annotation.",void 0,void 0,!0);return}this.updateComment(e,!1,!1,m,!0,t.updatedComment),e?.multiThreadAnnotationId&&(t.type===qe.ADDED||t.type===qe.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e])}let u=this.getCustomPinById(e.annotationId),f={type:t.type,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(y,S)=>{this.updateCommentAnnotationContext(e.annotationId,y,S)}};if(u!==void 0&&(f.element=u),delete f?.annotation?.pageInfo,delete f?.annotation?.targetElement,delete f?.annotation?.targetTextRange,f?.type===qe.DELETED&&(e.comments?.length||(f.annotation=null)),i||this.commentUpdated$.next(f),t.type===qe.NEWLY_ADDED&&!i&&e?.annotationId){let y=this.pendingAddCommentAnnotationData.get(e.annotationId);if(y){this.pendingAddCommentAnnotationData.delete(e.annotationId);let S=to(void 0,e.assignedTo,$=>this.loggingService.catch("Error resolving isAssigneeChanged: ",$)),j=b(g({},y),{annotation:this.getCommentAnnotationForClient(e),targetCommentId:t.updatedComment?.commentId}),W=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(j,S);W&&this.commentActionsService?.triggerAddCommentAnnotationEvent(W),t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment,isAssigneeChanged:S}))}}t.type===qe.ADDED&&t._dispatchAddCommentEvent&&!i&&e?.annotationId&&t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment,isAssigneeChanged:t._isAssigneeChanged}))}catch(a){this.loggingService.catch("Error in CommentService saveComment: ",a)}})}attachComment(e,t=[],a,i,d,m,u,f){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let y;if(e){let S=Lr(e,t);S&&(y={targetElement:{xpath:this.domService.getXPath(S),topPercentage:50,leftPercentage:90},targetElementId:e})}(y||a||d)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,m,void 0,void 0,y,f,void 0,void 0,i,void 0,void 0,void 0,a,void 0,d,void 0,void 0,u)}catch(y){this.loggingService.catch("Error in CommentService attachComment: ",y)}}generateComponentIdFromObject(e){try{let t=Cn(e||{});return fr(JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CommentService generateComponentIdFromObject: ",t);return}}updateNotificationsDatabase(e,t,a,i={}){try{let d=this.buildCommentNotificationRawData(e,t,a,i);this.notificationService.updateNotificationDatabase(d)}catch(d){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",d)}}buildCommentNotificationRawData(e,t,a,i={}){return g({annotationData:e,targetAnnotationData:t,actionType:a,notificationSource:"comment"},i)}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getCustomUserContacts(){try{return this.contactService.getCustomUserContacts()}catch(e){return this.loggingService.catch("Error in CommentService getCustomUserContacts:",e),null}}getCustomUserContactsConfig(){try{return this.contactService.getCustomUserContactsConfig()}catch(e){this.loggingService.catch("Error in CommentService getCustomUserContactsConfig:",e);return}}getElementFromComment(e){try{let t=null,a;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else if((a=this.resolveIdScopedPinElement(e))!==void 0)t=a;else{let i=!1,d=e?.targetElement?.anchor,m=this.acceptsInOwnDocumentArea(e);if(!t&&d){let u=this.domService.resolveAnchorRecord(d,{accept:m,cacheKey:jh(e)});u?.element&&this.domService.isElementVisible(u.element)&&kn(u.element)&&!(rr(e)&&dp(u.matchedBy))&&(t=u.element)}!t&&e?.targetElement?.xpath&&(i=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPathAccepted(e?.targetElement?.xpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)),!i&&!rr(e)&&(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPathAccepted(e?.targetElement?.cfXpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPathAccepted(e?.targetElement?.fXpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)))}return t&&!kn(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],a=null,i;if(e?.ghostComment)!a&&e.ghostComment?.targetElement?.fXpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),a&&!this.domService.isElementVisible(a)&&(a=null)),!a&&e.ghostComment?.targetElement?.cfXpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),a&&!this.domService.isElementVisible(a)&&(a=null)),!a&&e.ghostComment?.targetElement?.xpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),a&&!this.domService.isElementVisible(a)&&(a=null));else if((i=this.resolveIdScopedPinElement(e))!==void 0)a=i;else{let d=!1,m=e?.targetElement?.anchor,u=this.acceptsInOwnDocumentArea(e);if(!a&&m){let f=this.domService.resolveAnchorRecord(m,{accept:u,cacheKey:jh(e)});f?.element&&this.domService.isElementVisible(f.element)&&kn(f.element)&&!(rr(e)&&dp(f.matchedBy))&&(a=f.element)}!a&&e?.targetElement?.xpath&&(d=this.domService.isXpathWithId(e?.targetElement?.xpath),a=this.domService.getElementFromXPathAccepted(e?.targetElement?.xpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)),!d&&!rr(e)&&(!a&&e?.targetElement?.cfXpath&&(a=this.domService.getElementFromXPathAccepted(e?.targetElement?.cfXpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)),!a&&e?.targetElement?.fXpath&&(a=this.domService.getElementFromXPathAccepted(e?.targetElement?.fXpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)))}return a&&!kn(a)&&(a=null),e?.targetElementId&&(t=Array.from(Th(e.targetElementId,["id","data-id"]))),a&&!t.includes(a)&&t.push(a),rr(e)&&(t=t.filter(d=>this.domService.isElementVisible(d)&&this.docService.isAnnotationAllowedInArea(e?.metadata,d)!==!1)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,a=null;if(t)for(;!a&&t;)a=this.domService.getElementFromXPath(t),a&&(!this.domService.isElementVisible(a)||!kn(a))&&(a=null),a||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}findDocumentLevelTargetById(e){try{return Array.from(Th(e.targetElementId,["id","data-id"])).find(t=>this.domService.isElementVisible(t)&&this.docService.isAnnotationAllowedInArea(e?.metadata,t)!==!1)??null}catch(t){return this.loggingService.catch("Error in CommentService findDocumentLevelTargetById: ",t),null}}isAnnotationPinDrawnOnPage(e){try{return e?!!document.getElementById(`comment-pin-container-${e}`)?.isConnected:!1}catch(t){return this.loggingService.catch("Error in CommentService isAnnotationPinDrawnOnPage: ",t),!1}}logHiddenDocumentLevelPin(e){try{if(this.loggingService?.debugMode===!1)return;let t=`${e?.annotationId}|${window.location.href}`;if(this.loggedHiddenDocumentLevelPins||(this.loggedHiddenDocumentLevelPins=new Set),this.loggedHiddenDocumentLevelPins.has(t))return;this.loggedHiddenDocumentLevelPins.add(t),this.loggingService.log(`[Velt] document-level comment pin not drawn: target not found on this page. annotationId="${e?.annotationId}"`)}catch(t){this.loggingService.catch("Error in CommentService logHiddenDocumentLevelPin: ",t)}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=an.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,a=new vC().getDeviceType();t&&t!==a&&(e.ghostComment.type=an.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[Yn.MOBILE,Yn.TABLET].includes(t)&&[Yn.MOBILE,Yn.TABLET].includes(a)||[Yn.DESKTOP,Yn.MONITOR].includes(t)&&[Yn.DESKTOP,Yn.MONITOR].includes(a)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},a=t[e?.annotationId]||{};xn(e.ghostComment,a)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(Gt(Qn))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>t?{count:t[e]||0}:null))}getUnreadCommentAnnotationCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(Ee(e=>e?{count:Object.keys(e??{}).length||0}:null))}getUnreadCommentCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(Ee(e=>e?{count:Object.values(e).reduce((a,i)=>a+i,0)}:null))}getUnreadCommentCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>{if(t){let a=this.docService.getDocumentPaths(),i=[],d=0;return a?.documentId&&(i=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId}),i&&Object.keys(t).forEach(m=>{let u=i?.find(f=>f.annotationId===m);Lm(u,e)&&(d+=t[m])})),{count:d}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>{if(t){let a=this.docService.getDocumentPaths(),i=[],d=0;return a?.documentId&&(i=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId}),Object.keys(t).forEach(m=>{if(t[m]){let u=i?.find(f=>f.annotationId===m);Lm(u,e)&&(d+=1)}})),{count:d}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsRead(t))}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus,a=this.authService.getUser();if(t){for(let i of e)if(t?.id!==i?.status?.id){let d=JSON.parse(JSON.stringify(i||{}));i.status=this.customFilterService.resolvedStatus,i.statusUpdatedByUserId=a?.userId;let m={annotation:i,type:qe.STATUS_CHANGED,oldStatus:d.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(i,m)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}isCommentAnnotationUnread(e){try{let t=this.authService.getUser();return!(t?.userSnippylyId&&e?.viewedByUserIds?.length&&e?.viewedByUserIds?.includes(t?.userSnippylyId))}catch(t){return this.loggingService.catch("Error in CommentService isCommentAnnotationUnread: ",t),!1}}updateCommentDialogPosition(){try{this.updateCommentDialogPositionTriggerSubject$.next()}catch(e){this.loggingService.catch("Error in CommentService updateCommentDialogPosition: ",e)}}updateCommentDialogPositionTrigger$(){return this.updateCommentDialogPositionTriggerSubject$.asObservable()}enableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{areaComment:!0}}),this.areaCommentEnabled$.value===!0)return;this.areaCommentEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAreaComment: ",e)}}disableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{areaComment:!1}}),this.areaCommentEnabled$.value===!1)return;this.areaCommentEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAreaComment: ",e)}}getAreaCommentEnabled$(){return this.areaCommentEnabled$.asObservable()}getAreaCommentEnabled(){return this.areaCommentEnabled$.value}setPinCursorImage(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;"),e&&(e=`url(${e}) 0 31, auto`),this.commentPinCursorImage$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return Pe(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,a)=>{let i=this.domService.getLastDocumentClickTarget(),d=e?.location||this.docService.getAdditionLocationFromElement(i);if(d?.id){let m=this.docService.getLocationByClientLocationId(d.id);m&&(d=m)}this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,d,void 0,e,void 0,void 0,void 0,m=>{t(m)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=Dh(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let a=`${Z.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${Z.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(a=`${Z.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${Z.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${Z.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let i=this.getPortableAttachmentScope(t),d={organizationId:i.organizationId??null,documentId:i.documentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??this.configService?.getApiKey()??null,folderId:t.metadata?.folderId??this.documentPaths?.folderId??null,attachmentId:null};return this.storageService.uploadFile({path:a,file:e,metadata:d,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable(),portableScope:i})}downloadAttachment(e,t){this.storageService.downloadAttachment(e,this.getPortableAttachmentScope(t))}deleteAttachment({attachment:e,metadata:t,annotation:a}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable(),portableScope:this.getPortableAttachmentScope(a)})}deleteCommentAttachmentsForCascade(e,t){let a=e.metadata;t.attachments?.forEach(i=>{let d={attachmentId:i.attachmentId,organizationId:a?.clientOrganizationId??a?.organizationId??null,documentId:a?.clientDocumentId??a?.documentId??null,folderId:a?.folderId??null,commentAnnotationId:e.annotationId,apiKey:a?.apiKey??null};this.deleteAttachment({attachment:i,metadata:d,annotation:e})})}getPortableAttachmentScope(e){return{organizationId:e?.metadata?.clientOrganizationId??this.documentPaths?.clientOrganizationId??null,documentId:e?.metadata?.clientDocumentId??this.documentPaths?.clientDocumentId??null}}getAttachmentDisplayUrl(e,t){return this.storageService.getAttachmentDisplayUrl(e,this.getPortableAttachmentScope(t))}isPortableAttachment(e){return this.storageService.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.storageService.resolveAttachmentUrl(e,this.getPortableAttachmentScope(t))}isAttachmentDisplayPending(e,t){return this.storageService.isAttachmentDisplayPending(e,this.getPortableAttachmentScope(t))}reportAttachmentLoadError(e,t,a){this.storageService.reportAttachmentLoadError(e,this.getPortableAttachmentScope(t),a)}deleteReaction(e){try{this.reactionService?.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t;try{t=new URL(e?.pageInfo?.url||window.location.href)}catch(a){this.loggingService.catch("Error in CommentService generateCommentUrl: ",a),t=new URL(window.location.href)}return t.searchParams.delete(Z.URL_PARAMS.COMMENT_ID),t.searchParams.append(Z.URL_PARAMS.COMMENT_ID,e.annotationId),t.href}getCustomPinById(e){if(this.customPinsById.has(e))return this.customPinsById.get(e)}setCustomStatuses(e){try{if(e===void 0)return;this.customStatusesShown$.next(!0),this.customFilterService.setCustomStatusFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(ke.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!Fm()&&t?.commonAncestorContainer&&this.canCommentOnTextRange(t)){let a=t?this.domService.getTargetTextRangeFromSelectionRange(t):void 0;this.domService.clearTextSelection(),setTimeout(()=>{this.addComment(void 0,a)},100)}}}catch(e){this.loggingService.catch("Error in CommentService addCommentOnSelectedText: ",e)}}getInlineCommentSectionConfig(e){try{let t;if(e){let a=e?.closest(`[${Z.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(a){let i=a.getAttribute(Z.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);i&&(t={},t.targetInlineCommentElementId=i,a.getAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(a.getAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},a=e?.unsubscribedUsers||{},i={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(d=>{let m=e.subscribedUsers?.[d];m?.type==="manual"&&(t[d]=m)}),e?.assignedTo?.userId){let d=fr(e?.assignedTo?.userId);a[d]||t[d]?.type!=="manual"&&(t[d]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(d=>!d?.isDraft)?.forEach(d=>{if(d?.from?.userId){let m=fr(d?.from?.userId);a[m]||t[m]?.type!=="manual"&&(t[m]={user:d?.from,type:"auto"})}d?.to?.forEach(m=>{if(m?.userId){let u=fr(m.userId);a[u]||t[u]?.type!=="manual"&&(t[u]={user:m,type:"auto"})}}),d?.toOrganizationUserGroup?.forEach(m=>{if(m?.groupId)i[m?.groupId]={type:"auto"};else if(m?.clientGroupId){let u=fr(m.clientGroupId);i[u]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=a,e.subscribedGroups=i}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(Fe(()=>{let{annotationId:t,documentId:a}=e;if(a){let i=Qo(a).toString();return this.getDataCommentAnnotationsFromDocumentId(i).pipe(Ee(d=>d.find(u=>u.annotationId===t)||null))}else{let i=this.docService.getDocumentPaths();if(i?.documentId){let d=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId});if(d){let m=d.find(u=>u.annotationId===t);return ye(m||null)}}}return ye(null)}),Wr(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),ye(null))))}getCommentAnnotationByIdSync(e){try{return this.commentAnnotationById$.value?.[e]}catch(t){this.loggingService.catch("Error in CommentService getCommentAnnotationByIdSync: ",t);return}}getDataCommentAnnotationsFromDocumentId(e){return this.configService?.getApiKey()?this.commonDbService.dbListener({feature:"allComments",properties:{documentId:e||this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,isCollection:!0}}).pipe(Ee(t=>t?.data),Ee(t=>{let a=[];return t&&(a=Object.values(t??{}).filter(i=>typeof i=="object")),a})):ye([])}enableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedComments:!0}}),this.collapsedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedComments: ",e)}}disableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedComments:!1}}),this.collapsedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedComments: ",e)}}getCollapsedComments$(){return this.collapsedComments$.asObservable()}enableCollapsedRepliesPreview(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedRepliesPreview:!0}}),this.collapsedRepliesPreview$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedRepliesPreview: ",e)}}disableCollapsedRepliesPreview(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedRepliesPreview:!1}}),this.collapsedRepliesPreview$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedRepliesPreview: ",e)}}getCollapsedRepliesPreview$(){return this.collapsedRepliesPreview$.asObservable()}enableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullExpanded:!0}}),this.fullExpanded$.value===!0)return;this.fullExpanded$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullExpanded: ",e)}}disableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullExpanded:!1}}),this.fullExpanded$.value===!1)return;this.fullExpanded$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullExpanded: ",e)}}getFullExpanded$(){return this.fullExpanded$.asObservable()}getFullExpanded(){return this.fullExpanded$.value}setSidebarCustomActionEventData(e,t,a,i,d){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d})}catch(m){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",m)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{let a=new Set;(e||[]).forEach(d=>{(d?.annotations||[]).forEach(m=>{m?.annotationId&&a.add(m.annotationId)})});let i=this.customSidebarDataAnnotationIds$.value;this.areAnnotationIdSetsEqual(i,a)||this.customSidebarDataAnnotationIds$.next(a),this.sidebarData$.next({data:e,options:t})}catch(a){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",a)}}areAnnotationIdSetsEqual(e,t){if(e===t)return!0;if(e===null||t===null||e.size!==t.size)return!1;for(let a of e)if(!t.has(a))return!1;return!0}getSidebarCustomData(){return this.sidebarData$.asObservable()}getCustomSidebarDataAnnotationIds$(){return this.customSidebarDataAnnotationIds$.asObservable()}getCustomSidebarDataAnnotationIds(){return this.customSidebarDataAnnotationIds$.value}setSidebarCustomActionEventDataAllChanges(e,t,a,i,d){return Pe(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d});let m=yield this.metadataService.getGlobalMetadata(),u={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:a,commentAnnotations:t,systemFilteredAnnotations:i,metadata:m,customFilters:d};this.commentActionsService?.triggerAction(ct.COMMENT_SIDEBAR_DATA_UPDATE,u)}catch(m){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",m)}})}setSidebarCustomActionEventDataOnInit(e,t,a,i,d){return Pe(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d});let u={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:a,commentAnnotations:t,systemFilteredAnnotations:i,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:d};this.commentActionsService?.triggerAction(ct.COMMENT_SIDEBAR_DATA_INIT,u)}catch(m){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",m)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?xn(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}getTransformContext$(){return this.transformContext$.asObservable()}getTransformContext(){return this.transformContext$.value}enableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customActions:!0}}),this.customActions$.value===!0)return;this.customActions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarCustomActions: ",e)}}disableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customActions:!1}}),this.customActions$.value===!1)return;this.customActions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarCustomActions: ",e)}}getSidebarCustomActionsValue(){return this.customActions$.getValue()}enableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{queryParamsComments:!0}}),this.queryParamsComments$.value===!0)return;this.queryParamsComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableQueryParamsComments: ",e)}}disableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{queryParamsComments:!1}}),this.queryParamsComments$.value===!1)return;this.queryParamsComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableQueryParamsComments: ",e)}}getQueryParamsComments$(){return this.queryParamsComments$.asObservable()}getQueryParamsComments(){return this.queryParamsComments$.value}enableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveStatusAccessAdminOnly:!0}}),this.resolveStatusAccessAdminOnly$.value===!0)return;this.resolveStatusAccessAdminOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableResolveStatusAccessAdminOnly: ",e)}}disableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveStatusAccessAdminOnly:!1}}),this.resolveStatusAccessAdminOnly$.value===!1)return;this.resolveStatusAccessAdminOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableResolveStatusAccessAdminOnly: ",e)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.value}enableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{svgAsImg:!0}}),this.svgAsImg$.value===!0)return;this.svgAsImg$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSvgAsImg: ",e)}}disableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{svgAsImg:!1}}),this.svgAsImg$.value===!1)return;this.svgAsImg$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSvgAsImg: ",e)}}getSvgAsImg$(){return this.svgAsImg$.asObservable()}getSvgAsImg(){return this.svgAsImg$.value}enableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentToNearestAllowedElement:!0}}),this.commentToNearestAllowedElement$.value===!0)return;this.commentToNearestAllowedElement$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentToNearestAllowedElement: ",e)}}disableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentToNearestAllowedElement:!1}}),this.commentToNearestAllowedElement$.value===!1)return;this.commentToNearestAllowedElement$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentToNearestAllowedElement: ",e)}}getCommentToNearestAllowedElement$(){return this.commentToNearestAllowedElement$.asObservable()}getCommentToNearestAllowedElement(){return this.commentToNearestAllowedElement$.value}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:a}=e||{},i=null;t&&(i={},t.forEach(m=>{m?.annotationId&&i&&(i[m.annotationId]=m)}));let d={};t===void 0?d.data=this.commentsFromSidebarMap$.value?.data:d.data=i,a===void 0?d.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:d.sidebarVisible=a,xn(this.commentsFromSidebarMap$.value,d)||this.commentsFromSidebarMap$.next(d)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}hasActiveFilters(e){try{return e?!!(e.people?.length||e.assigned?.length||e.tagged?.length||e.involved?.length||e.priority?.length||e.status?.length||e.category?.length||e.location?.length||e.document?.length||e.version?.length||e.accessModes?.length||this.hasCustomContextFilters(e)):!1}catch(t){return this.loggingService.catch("Error in CommentService hasActiveFilters: ",t),!1}}hasCustomContextFilters(e){try{if(!e)return!1;let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]);return Object.keys(e).some(a=>!t.has(a)&&Array.isArray(e[a])&&e[a]?.length>0)}catch(t){return this.loggingService.catch("Error in CommentService hasCustomContextFilters: ",t),!1}}applyDirectFilters(e,t){try{let a=this.commentSidebarSystemFiltersOperator$.value,i,d=!1,m=new Set;a===Kr.AND?i=e.slice():i=[];let u=f=>{a===Kr.AND?i=i.filter(y=>f.some(S=>S.annotationId===y.annotationId)):f.forEach(y=>m.add(y.annotationId)),d=!0};if(t.people?.length){let f=[];t.people.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByPeople({id:S,name:y.name},e)])}),u(f)}if(t.assigned?.length){let f=[];t.assigned.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByAssigned({id:S,name:y.name},e)])}),u(f)}if(t.tagged?.length){let f=[];t.tagged.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByTagged({id:S,name:y.name},e)])}),u(f)}if(t.involved?.length){let f=[];t.involved.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByInvolved({id:S,name:y.name},e)])}),u(f)}if(t.priority?.length){let f=[];t.priority.forEach(y=>f=[...f,...this.filterAnnotationsByPriority({id:y},e)]),u(f)}if(t.status?.length){let f=[];t.status.forEach(y=>f=[...f,...this.filterAnnotationsByStatus({id:y},e)]),u(f)}if(t.category?.length){let f=[];t.category.forEach(y=>f=[...f,...this.filterAnnotationsByCommentCategory({id:y},e)]),u(f)}if(t.version?.length){let f=[];t.version.forEach(y=>f=[...f,...this.filterAnnotationsByVersion(y,e)]),u(f)}if(t.document?.length){let f=[];t.document.forEach(y=>f=[...f,...this.filterAnnotationsByDocument(y,e)]),u(f)}if(t.location?.length){let f=[];t.location.forEach(y=>{y.id&&(f=[...f,...e.filter(S=>S.location?.id===y.id||S.documentParams?.id===y.id)])}),f=[...f,...e.filter(y=>rr(y)&&!f.includes(y))],u(f)}if(t.accessModes?.length){let f=[];t.accessModes.forEach(y=>{y===gr.PRIVATE?f=[...f,...e.filter(S=>br(S))]:y===gr.PUBLIC&&(f=[...f,...e.filter(S=>!br(S))])}),u(f)}return this.getCustomContextFilterEntries(t).forEach(({key:f,values:y})=>{let S=this.matchAnnotationsByContext(e,f,y);u(S)}),a!==Kr.AND&&(d?i=e.filter(f=>m.has(f.annotationId)):i=e),i}catch(a){return this.loggingService.catch("Error in CommentService applyDirectFilters: ",a),e}}applyCommentSidebarClientFilters(e,t){return this.applyDirectFilters(e,t)}getCustomContextFilterEntries(e){try{if(!e)return[];let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]),a=[];return Object.keys(e).forEach(i=>{if(t.has(i))return;let d=e[i];!Array.isArray(d)||!d.length||a.push({key:i,values:d})}),a}catch(t){return this.loggingService.catch("Error in CommentService getCustomContextFilterEntries: ",t),[]}}matchAnnotationsByContext(e,t,a){try{return e.filter(i=>{let d=i.context?.[t];return d==null?!1:a.some(m=>{let u=typeof m=="string"?m:m?.id;return d===u||d?.toString()===u})})}catch(i){return this.loggingService.catch("Error in CommentService matchAnnotationsByContext: ",i),[]}}filterAnnotationsByPeople(e,t){try{return e.id?t.filter(a=>a?.from?.userId===e.id||a?.from?.email===e.id):t}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByPeople: ",a),[]}}filterAnnotationsByTagged(e,t){try{return t.filter(a=>a?.comments?.some(i=>i.taggedUserContacts?.some(d=>d?.contact?.userId===e.id)))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByTagged: ",a),[]}}filterAnnotationsByAssigned(e,t){try{return t.filter(a=>a?.assignedTo?.userId===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByAssigned: ",a),[]}}filterAnnotationsByInvolved(e,t){try{return t.filter(a=>{let i=a?.from?.userId===e.id||a?.from?.email===e.id,d=a?.assignedTo?.userId===e.id,m=a?.comments?.some(u=>u.taggedUserContacts?.some(f=>f?.contact?.userId===e.id));return i||d||m})}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByInvolved: ",a),[]}}filterAnnotationsByPriority(e,t){try{return e.id==="unset"?t.filter(a=>!a?.priority):t.filter(a=>a?.priority?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByPriority: ",a),[]}}filterAnnotationsByStatus(e,t){try{return t.filter(a=>a?.status?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByStatus: ",a),[]}}filterAnnotationsByCommentCategory(e,t){try{return e.id==="other"?t.filter(a=>!a?.commentCategories?.length||a?.commentCategories?.some(i=>i.id===e.id)):t.filter(a=>(a?.commentCategories||[]).some(i=>i.id===e.id))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByCommentCategory: ",a),[]}}filterAnnotationsByVersion(e,t){try{return e.id==="unset"?t.filter(a=>!a?.location?.version):t.filter(a=>a?.location?.version?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByVersion: ",a),[]}}filterAnnotationsByDocument(e,t){try{return e?.id&&e.id!=="other"?t.filter(a=>a?.metadata?.clientDocumentId?.toString()===e.id):t.filter(a=>!a?.metadata?.clientDocumentId)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByDocument: ",a),[]}}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),a;return t?a=e||[]:e?a=[e]:a=[],this.getFilterCommentsOnDom$().pipe(Fe(i=>i?a.length===0?ye(e):Bt([this.effectiveSidebarFilters$,this.customSidebarDataAnnotationIds$]).pipe(Ee(([d,m])=>{let u=a,f=!1;if(this.hasActiveFilters(d)){let y=this.applyDirectFilters(a,d),S=new Set(y.map(j=>j.annotationId));u=u.filter(j=>j?.isDraft||S.has(j.annotationId)),f=!0}return m&&(u=u.filter(y=>y?.isDraft||y?.annotationId&&m.has(y.annotationId)),f=!0),f?t?u:u.length>0?u[0]:null:e})):ye(e)))}catch{return ye(e)}}enableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!0)return;this.focusedThreadMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFocusedThreadMode: ",e)}}disableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!1)return;this.focusedThreadMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFocusedThreadMode: ",e)}}getFocusedThreadMode$(){return this.focusedThreadMode$.asObservable()}enableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{openAnnotationInFocusMode:!0}}),this.openAnnotationInFocusMode$.value===!0)return;this.openAnnotationInFocusMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableOpenAnnotationInFocusMode: ",e)}}disableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{openAnnotationInFocusMode:!1}}),this.openAnnotationInFocusMode$.value===!1)return;this.openAnnotationInFocusMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableOpenAnnotationInFocusMode: ",e)}}getOpenAnnotationInFocusMode$(){return this.openAnnotationInFocusMode$.asObservable()}getOpenAnnotationInFocusMode(){return this.openAnnotationInFocusMode$.value}enableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{readOnly:!0}}),this.readOnly$.value===!0)return;this.readOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReadOnly: ",e)}}disableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{readOnly:!1}}),this.readOnly$.value===!1)return;this.readOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReadOnly: ",e)}}getReadOnly$(){return this.readOnly$.asObservable()}getReadOnly(){return this.readOnly$.value}shouldEnableReadOnly(){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,a=this.docService.getDocumentIds().map(i=>i.clientDocumentId);if(e){let i=this.userPermissionService.getCurrentUserPermissions();i?.[e.userId]?t&&i[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():a.forEach(d=>{i[e.userId]?.documents?.[d]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),e}}enableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customAutocompleteSearch:!0}}),this.customAutocompleteSearch$.value===!0)return;this.customAutocompleteSearch$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCustomAutocompleteSearch: ",e)}}disableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customAutocompleteSearch:!1}}),this.customAutocompleteSearch$.value===!1)return;this.customAutocompleteSearch$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCustomAutocompleteSearch: ",e)}}getCustomAutocompleteSearch$(){return this.customAutocompleteSearch$.asObservable()}getCustomAutocompleteSearch(){return this.customAutocompleteSearch$.value}enableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteThreadWithFirstComment:!0}}),this.deleteThreadWithFirstComment$.value===!0)return;this.deleteThreadWithFirstComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteThreadWithFirstComment: ",e)}}disableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteThreadWithFirstComment:!1}}),this.deleteThreadWithFirstComment$.value===!1)return;this.deleteThreadWithFirstComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteThreadWithFirstComment: ",e)}}getDeleteThreadWithFirstComment$(){return this.deleteThreadWithFirstComment$.asObservable()}enableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{expandMentionGroups:!0}}),this.expandMentionGroups$.value===!0)return;this.expandMentionGroups$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableExpandMentionGroups: ",e)}}disableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{expandMentionGroups:!1}}),this.expandMentionGroups$.value===!1)return;this.expandMentionGroups$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableExpandMentionGroups: ",e)}}getExpandMentionGroups$(){return this.expandMentionGroups$.asObservable()}getExpandMentionGroups(){return this.expandMentionGroups$.value}enableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsFirst:!0}}),this.showMentionGroupsFirst$.value===!0)return;this.showMentionGroupsFirst$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsFirst: ",e)}}disableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsFirst:!1}}),this.showMentionGroupsFirst$.value===!1)return;this.showMentionGroupsFirst$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsFirst: ",e)}}getShowMentionGroupsFirst$(){return this.showMentionGroupsFirst$.asObservable()}getShowMentionGroupsFirst(){return this.showMentionGroupsFirst$.value}enableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsOnly:!0}}),this.showMentionGroupsOnly$.value===!0)return;this.showMentionGroupsOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsOnly: ",e)}}disableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsOnly:!1}}),this.showMentionGroupsOnly$.value===!1)return;this.showMentionGroupsOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsOnly: ",e)}}getShowMentionGroupsOnly$(){return this.showMentionGroupsOnly$.asObservable()}getShowMentionGroupsOnly(){return this.showMentionGroupsOnly$.value}setAnalyticsFeatureConfig({config:e,feature:t}){try{this.analyticsService.setFeatureConfig({feature:t||ke.COMMENT,config:e})}catch(a){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",a)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let a=JSON.parse(JSON.stringify(e));if(delete a.accessFields,delete a.access,Object.keys(a).length){let i=Cn(a),d=JSON.stringify(i);t=fr(d)}}return t}catch{return}}splitProgressCommentsStage(e){try{if(!Array.isArray(e))return e;let t=!1;return e.forEach(a=>{let i=a?.annotationId;if(typeof i!="string"||!i)return;let{comments:d,progress:m}=$h(a);!m.length&&!this.progressCommentsByAnnotationId.has(i)||(a.comments=d,m.length?(this.progressCommentsByAnnotationId.set(i,m),t=!0):(this.progressCommentsByAnnotationId.delete(i)&&(t=!0),this.progressOnlyAnnotationsLogged.delete(i)),!d.length&&m.length&&!this.progressOnlyAnnotationsLogged.has(i)&&(this.progressOnlyAnnotationsLogged.add(i),this.loggingService.log("[velt] progress: annotation currently has only content-less progress comments: "+i)))}),t&&this.progressCommentsVersion$.next(this.progressCommentsVersion$.value+1),e}catch(t){return this.loggingService.catch("Error in CommentService splitProgressCommentsStage:",t),e}}getProgressCommentsVersion$(){return this.progressCommentsVersion$.asObservable()}getFullComments(e){try{let t=Array.isArray(e?.comments)?e.comments:[],a=this.getProgressComments(e?.annotationId);return a.length?[...t,...a].sort((i,d)=>{let m=i?.createdAt instanceof Date?i.createdAt.getTime():Number(i?.createdAt??0),u=d?.createdAt instanceof Date?d.createdAt.getTime():Number(d?.createdAt??0);return m-u}):t}catch{return e?.comments??[]}}spliceProgressCommentsIn(e){try{if(!e?.annotationId||!this.getProgressComments(e.annotationId).length)return;e.comments=this.getFullComments(e)}catch(t){this.loggingService.catch("Error in CommentService spliceProgressCommentsIn:",t)}}withProgressCommentsSpliced(e,t){return Pe(this,null,function*(){try{this.spliceProgressCommentsIn(e);try{return yield t()}finally{this.restoreProgressCommentSplit(e)}}catch(a){this.loggingService.catch("Error in CommentService withProgressCommentsSpliced:",a);return}})}restoreProgressCommentSplit(e){try{if(!e?.annotationId||!this.getProgressComments(e.annotationId).length)return;let{comments:t}=$h(e);e.comments=t}catch(t){this.loggingService.catch("Error in CommentService restoreProgressCommentSplit:",t)}}hasRenderableContent(e){try{if(!e)return!1;if(e.comments?.length)return!0;let t=e.annotationId;if(typeof t!="string"||!t)return!1;let a=Date.now(),i=this.getCommentProgressStaleAfter();return this.getProgressComments(t).some(d=>lp(d,i,a))}catch{return!!e?.comments?.length}}getProgressComments(e){try{return this.progressCommentsByAnnotationId.get(e)??[]}catch{return[]}}evictProgressComments(e){try{e?.forEach(t=>{this.progressCommentsByAnnotationId.delete(t),this.progressOnlyAnnotationsLogged.delete(t)})}catch(t){this.loggingService.catch("Error in CommentService evictProgressComments:",t)}}setCommentProgressStaleAfter(e){try{let t=Number(e);if(!Number.isFinite(t)||t<=0||this.commentProgressStaleAfter$.value===t)return;this.commentProgressStaleAfter$.next(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentProgressStaleAfter:",t)}}getCommentProgressStaleAfter$(){return this.commentProgressStaleAfter$.asObservable()}getCommentProgressStaleAfter(){return this.commentProgressStaleAfter$.value}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}setEditplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editplaceholder:e}}),this.editplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditplaceholder: ",t)}}getEditplaceholder$(){return this.editplaceholder$.asObservable()}getEditplaceholder(){return this.editplaceholder$.value}setEditcommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editcommentplaceholder:e}}),this.editcommentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditcommentplaceholder: ",t)}}getEditcommentplaceholder$(){return this.editcommentplaceholder$.asObservable()}getEditcommentplaceholder(){return this.editcommentplaceholder$.value}setEditreplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editreplyplaceholder:e}}),this.editreplyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditreplyplaceholder: ",t)}}getEditreplyplaceholder$(){return this.editreplyplaceholder$.asObservable()}getEditreplyplaceholder(){return this.editreplyplaceholder$.value}enableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{screenshotEnabled:!0}}),this.screenshotEnabled$.value===!0)return;this.screenshotEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScreenshot: ",e)}}disableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{screenshotEnabled:!1}}),this.screenshotEnabled$.value===!1)return;this.screenshotEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScreenshot: ",e)}}getScreenshotEnabled$(){return this.screenshotEnabled$.asObservable()}getScreenshotEnabled(){return this.screenshotEnabled$.value}getAnnotationNumber(e){try{let t=this.commentAnnotationById$.value||{},a=-1,i=Object.values(t).filter(d=>{let m=d.metadata?.documentId===e.metadata?.documentId;return m&&d.annotationNumber&&(a=Math.max(a,d.annotationNumber)),m});return a===-1?i.length+1:a+1}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationNumber: ",t),null}}enableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullScreen:!0}}),this.fullScreenInSidebar$.value===!0)return;this.fullScreenInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullScreenInSidebar: ",e)}}disableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullScreen:!1}}),this.fullScreenInSidebar$.value===!1)return;this.fullScreenInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullScreenInSidebar: ",e)}}getFullScreenInSidebar$(){return this.fullScreenInSidebar$.asObservable()}getFullScreenInSidebar(){return this.fullScreenInSidebar$.value}setComposerFileAttachments(e){try{this.composerFileAttachments$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerFileAttachments: ",t)}}getComposerFileAttachments$(){return this.composerFileAttachments$.asObservable()}getComposerFileAttachments(){return this.composerFileAttachments$.value}clearComposerFileAttachments(){try{this.composerFileAttachments$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearComposerFileAttachments: ",e)}}enableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!0)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentNameInMessage:!0}}),this.attachmentNameInMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentNameInMessage: ",e)}}disableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!1)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentNameInMessage:!1}}),this.attachmentNameInMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentNameInMessage: ",e)}}getAttachmentNameInMessage$(){return this.attachmentNameInMessage$.asObservable()}getAttachmentNameInMessage(){return this.attachmentNameInMessage$.value}setAllowedFileTypes(e){try{this.allowedFileTypes$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedFileTypes: ",t)}}getAllowedFileTypes$(){return this.allowedFileTypes$.asObservable()}getAllowedFileTypes(){return this.allowedFileTypes$.value}enableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!0)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{forceCloseAllOnEsc:!0}}),this.forceCloseAllOnEsc$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableForceCloseAllOnEsc: ",e)}}disableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!1)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{forceCloseAllOnEsc:!1}}),this.forceCloseAllOnEsc$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableForceCloseAllOnEsc: ",e)}}getForceCloseAllOnEsc$(){return this.forceCloseAllOnEsc$.asObservable()}getForceCloseAllOnEsc(){return this.forceCloseAllOnEsc$.value}markAsRead(e){return Pe(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsRead(t)))}catch(t){this.loggingService.catch("Error in ViewsService markAsRead:",t)}})}markAsUnread(e){return Pe(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsUnread(t)))}catch(t){this.loggingService.catch("Error in ViewsService markAsUnread:",t)}})}setAutoCompleteScrollConfig(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{autoCompleteScrollConfig:e}});let t=this.autoCompleteScrollConfig$.value,a={itemSize:e.itemSize??t.itemSize,minBufferPx:e.minBufferPx??t.minBufferPx,maxBufferPx:e.maxBufferPx??t.maxBufferPx,templateCacheSize:e.templateCacheSize??t.templateCacheSize};this.autoCompleteScrollConfig$.next(a)}catch(t){this.loggingService.catch("Error in CommentService setAutoCompleteScrollConfig: ",t)}}getAutoCompleteScrollConfig(){return this.autoCompleteScrollConfig$.value}getAutoCompleteScrollConfig$(){return this.autoCompleteScrollConfig$.asObservable()}submitComment(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: submitComment","color: green;"),this.submitComment$.next(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService submitComment: ",t)}}onSubmitComment$(){return this.submitComment$.asObservable()}clearComposer(e){try{this.clearComposer$.next(e.targetComposerElementId),this.composerDataMap.delete(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService clearComposer: ",t)}}onClearComposer$(){return this.clearComposer$.asObservable()}emitComposerTextChange(e,t,a){try{this.commentActionsService?.onComposerTextChange({text:e,annotation:t,targetComposerElementId:a})}catch(i){this.loggingService.catch("Error in CommentService emitComposerTextChange: ",i)}}setComposerData(e,t){try{this.composerDataMap.set(e,t)}catch(a){this.loggingService.catch("Error in CommentService setComposerData: ",a)}}clearComposerData(e){try{this.composerDataMap.delete(e)}catch(t){this.loggingService.catch("Error in CommentService clearComposerData: ",t)}}getComposerData(e){try{return this.composerDataMap.get(e.targetComposerElementId)||null}catch(t){return this.loggingService.catch("Error in CommentService getComposerData: ",t),null}}};o.PORTABLE_ACTIVATION_WAIT_MS=1e4,o.\u0275fac=function(t){return new(t||o)(be(pr),be(_o),be(kc),be(ut),be(KC),be(vt),be(Re),be(Zb),be(t0),be(zt),be(E0),be(Qb),be(oC),be(wr),be(A),be(O0),be(St),be(nk),be(Sr),be(p0),be(Ju),be(s0),be(d0),be(tp))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function BD(r){try{let o=(r?.composerContent??"").replace(/\s+/g," ").trim();if(o)return o;let n=r?.recordingCount??0;if(n>0)return`${n} ${n===1?"recording":"recordings"}`;let e=r?.attachmentCount??0;return e>0?`${e} ${e===1?"attachment":"attachments"}`:""}catch{return""}}function ik(r,o){let n=[];if(!o)return n;let e=0;for(;;){let t=r.indexOf(o,e);if(t<0)return n;n.push(t),e=t+1}}function ak(r,o,n,e){let t=ik(r,o.contextBefore+n+o.contextAfter),a=t.length>=o.occurrence?t[o.occurrence-1]:t.length===1?t[0]:void 0;if(a===void 0)return null;let i=a+o.contextBefore.length;return{form:e,start:i,end:i+n.length}}function cp(r,o,n,e){let t=o.contextBefore,a=o.contextAfter;if(!t&&!a)return null;for(let i=t.length,d=a.length,m=!0;Math.max(i,d)>=4;i=Math.floor(i/2),d=Math.floor(d/2),m=!1){let u=m?[[i,0],[0,d]]:[[i,d],[i,0],[0,d]];for(let[f,y]of u){if(Math.max(f,y)<4)continue;let S=t.slice(t.length-f),j=a.slice(0,y),W=ik(r,S+n+j);if(W.length===1){let $=W[0]+S.length;return{form:e,start:$,end:$+n.length}}}}return null}var Bm=r=>r.replace(/\u00a0/g," ");function mp(r,o){if(!r||!o||!o.removed&&!o.added&&!o.contextBefore&&!o.contextAfter)return null;let n=Bm(r),e={removed:Bm(o.removed),added:Bm(o.added),contextBefore:Bm(o.contextBefore),contextAfter:Bm(o.contextAfter),occurrence:o.occurrence},t=ak(n,e,e.removed,"original")??ak(n,e,e.added,"edited");return t||(!e.removed&&e.added?cp(n,e,e.added,"edited")??cp(n,e,e.removed,"original"):cp(n,e,e.removed,"original")??cp(n,e,e.added,"edited"))}function wc(r){let o=r.documentIds?[{key:"documentIds",field:"metadata.documentId",op:"in",value:r.documentIds}]:[],n=r.folder?[{key:"folderId",field:"metadata.veltFolderId",op:"=="}]:[],e=[...r.filters?.statusIds?.length?[{key:"statusIds",field:"status.id",op:"in",value:r.filters.statusIds}]:[],...r.filters?.locationIds?.length?[{key:"locationIds",field:"location.id",op:"in",value:r.filters.locationIds}]:[],...r.filters?.agentFields?.length?[{key:"agentFields",field:"agent.agentFields",op:"array-contains-any",value:r.filters.agentFields}]:[]];return{clauses:r.layout==="perDocument"?[...o,...n,...e]:[...e,...o,...n],countsRead:!r.filters?.agentFields?.length}}function lk(r){if(r.mode.isFolderMode)return{key:r.folderId??"",queries:[wc({layout:"aggregate",folder:!0,filters:r.filters})]};if(r.mode.isOrgMode)return{key:r.clientOrganizationId??"",queries:[wc({layout:"aggregate",folder:!1,filters:r.filters})]};let o=[];for(let n=0;n<r.serverDocumentIds.length;n+=r.batchSize)o.push(wc({layout:"aggregate",documentIds:r.serverDocumentIds.slice(n,n+r.batchSize),folder:r.hasFolder,filters:r.filters}));return{key:"result",queries:o}}function sp(r,o){let n={organizationId:o.organizationId};for(let e of r.clauses)n[e.key]=e.key==="folderId"?o.folderId:e.value;return n}var Dc={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0};function dk(r){return r.sort().join(",")}function vk(r){let o=r,n=typeof o?.total=="number"&&Number.isFinite(o.total)?o.total:0,e=typeof o?.unread=="number"&&Number.isFinite(o.unread)?o.unread:0;return{total:n,unread:e}}var gp=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y){this.authService=e,this.iamService=t,this.docService=a,this.configService=i,this.commonDbService=d,this.loggingService=m,this.commentService=u,this.userPermissionService=f,this.adapterSelectorService=y,this.documentPaths=null,this.LISTENER_BATCH_SIZE=5}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(qt(t=>!!t),Fe(t=>this.docService.getOrganizationConfig$().pipe(qt(a=>!!a),Ee(()=>t))),Fe(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),Fe(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(a=>(t.featureAllowed=a,t))):ye(t)),Fe(t=>t.featureAllowed?this.processRequest(t,e):ye(null)),Ee(t=>t??{data:null}),Gt(Qn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),ye({data:null})}}processRequest(e,t){try{return ye(e).pipe(Fe(()=>this.initializeDocumentPaths(t,e)),Fe(()=>this.getDocumentIds$(t)),Fe(a=>{let i=this.authService.getUser()?.userSnippylyId,d=this.buildRequestContext(t,a);if(!this.validateRequestContext(d,t))return ye({data:null,mode:d.mode,serverDocumentIds:d.serverDocumentIds});if(!d.organizationId)return ye({data:null,mode:d.mode,serverDocumentIds:d.serverDocumentIds});let m=this.setupTriggers$(d.mode,d.organizationId,d.clientOrganizationId,d.veltFolderId,d.serverDocumentIds);if(this.shouldUseAggregateMode(d.mode))return this.handleAggregateCounts$({triggers$:m,serverDocumentIds:d.serverDocumentIds,request:t,userId:i,organizationId:d.organizationId,clientOrganizationId:d.clientOrganizationId,veltFolderId:d.veltFolderId,folderId:d.folderId,mode:d.mode}).pipe(Ee(u=>({data:u,mode:d.mode,serverDocumentIds:d.serverDocumentIds})));if(d.mode.isBatchedGroupedMode){let u=t?.debounceMs??5e3;return this.handleBatchedGroupedCounts$({triggers$:m,documentIds:a,request:t,userId:i,organizationId:d.organizationId,veltFolderId:d.veltFolderId,debounceMs:u,portableIds:{clientOrganizationId:d.clientOrganizationId??"",folderId:d.folderId}}).pipe(Ee(f=>({data:f,mode:d.mode,serverDocumentIds:d.serverDocumentIds})))}else return this.handleGroupedCounts$(m,a,t,i,d.organizationId,d.veltFolderId,{clientOrganizationId:d.clientOrganizationId??"",folderId:d.folderId}).pipe(Ee(u=>({data:u,mode:d.mode,serverDocumentIds:d.serverDocumentIds})))}),Fe(a=>{if(!a?.data)return ye(null);let{data:i,mode:d,serverDocumentIds:m}=a;return t?.filterGhostComments?this.filterGhostComments$(i,d,m):ye(i)}),Wr(a=>(this.loggingService.catch("Error processing request: ",a),ye(null))))}catch(a){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",a),ye(null)}}initializeDocumentPaths(e,t){try{return e?ye(t):this.docService.getDocumentPaths$().pipe(qt(a=>!!a),Tm(a=>{this.documentPaths=a,t.documentPaths=a}),Ee(()=>{}))}catch(a){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",a),ye(t)}}buildRequestContext(e,t){try{let a=this.docService.getOrganizationConfig(),i=this.documentPaths?.organizationId??a?.organizationId,d=this.documentPaths?.clientOrganizationId??a?.clientOrganizationId,m,u,f;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(i=pc(e.organizationId),d=e.organizationId),!i)throw new Error("organizationId is required for this request type");e.folderId&&(m=ur(e.folderId),u=e.folderId),e.allDocuments&&(f=!0)}else m=this.documentPaths?.veltFolderId,u=this.documentPaths?.folderId,f=this.documentPaths?.allDocuments;let y=this.determineMode(e,m,f,t),S=y.isOrgMode?[]:t.length>0?t.map(j=>j.documentId):[this.documentPaths?.documentId??""];return{organizationId:i,clientOrganizationId:d,veltFolderId:m,folderId:u,allDocuments:f,mode:y,serverDocumentIds:S}}catch(a){return this.loggingService.catch("Error in CommentService buildRequestContext: ",a),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(a=>!a))}catch(a){return this.loggingService.catch("Error in CommentService validateRequestContext: ",a),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?ye(e.documentIds.map(t=>({clientDocumentId:t,documentId:Au(t)}))):this.docService.getDocumentIds$().pipe(Ee(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),ye([])}}determineMode(e,t,a,i){try{let d=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!a,m=!!t&&!!a,u=!!e?.aggregateDocuments&&!a&&!!i?.length,f=(!!e?.batchedPerDocument||i.length>1)&&!!i?.length&&!e?.aggregateDocuments&&!a;return{isOrgMode:d,isFolderMode:m,isBatchMode:u,isBatchedGroupedMode:f}}catch(d){return this.loggingService.catch("Error in CommentService determineMode: ",d),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1}}}setupTriggers$(e,t,a,i,d){try{return this.adapterSelectorService?.isPortableSession?.()===!0?this.setupPortableTriggers$(e,t,a,i,d):this.setupHostedTriggers$(e,t,a,i,d)}catch(m){return this.loggingService.catch("Error in CommentService setupTriggers: ",m),[]}}setupHostedTriggers$(e,t,a,i,d){if(e.isOrgMode){let m=this.gateOnOrganizationAccess$(a,()=>this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}));return[this.commentViewsTimestampTrigger$(m)]}else if(e.isFolderMode){let m=this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:i,organizationId:t}});return[this.commentViewsTimestampTrigger$(m)]}else return e.isBatchMode||e.isBatchedGroupedMode?this.batchDocumentIds(d).map(u=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",t),Et("metadata.documentId","in",u))]}}).pipe(Ee(y=>dk(Object.values(y?.data||{}).map(S=>S?.commentViewsUpdatedAt??null))),Gt(Qn))):d.map(m=>{let u=this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:m,organizationId:t}});return this.commentViewsTimestampTrigger$(u)})}batchDocumentIds(e){let t=[];for(let a=0;a<e.length;a+=this.LISTENER_BATCH_SIZE)t.push(e.slice(a,a+this.LISTENER_BATCH_SIZE));return t}gateOnOrganizationAccess$(e,t){let a=this.authService.getUser()?.userId??"";return jn(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:e})??Promise.resolve({})).pipe(Fe(i=>a&&i?.[a]?.organization?.[e]?.errorCode===Mu.PERMISSION_DENIED?(this.loggingService.log(`%c[WB] commentViews org listener skipped \u2014 user does not have access to organization: ${e}`,"color: orange;"),Hr):t()))}commentViewsTimestampTrigger$(e){return e.pipe(Ee(t=>t?.data?.commentViewsUpdatedAt??null),qt(t=>!!t),Gt(Qn))}setupPortableTriggers$(e,t,a,i,d){let m=this.batchDocumentIds(d),u=e.isOrgMode||e.isFolderMode?1:e.isBatchMode||e.isBatchedGroupedMode?m.length:d.length,f=null,y=S=>(f=f??this.setupHostedTriggers$(e,t,a,i,d),f[S]??Hr);return Array.from({length:u},(S,j)=>this.rebuiltOnPortableRegistration$(()=>this.liveCommentViewsAvailable(),W=>W?e.isOrgMode?this.portableOrganizationTrigger$(t,a):e.isFolderMode?this.portableFolderTrigger$(t,i):e.isBatchMode||e.isBatchedGroupedMode?this.portableBatchTrigger$(t,m[j]??[]):this.commentViewsTimestampTrigger$(this.portableDocumentListener$(t,d[j])):y(j)))}liveCommentViewsAvailable(){try{return this.adapterSelectorService?.isPortableBackendActive?.()===!0&&this.adapterSelectorService.portableConnectionAnnounces(e0)===!0}catch(e){return this.loggingService.catch("Error in CommentViewsService liveCommentViewsAvailable: ",e),!1}}rebuiltOnPortableRegistration$(e,t){return new ac(a=>{a.next();let i=Gu(()=>a.next()),d;try{d=this.adapterSelectorService?.portableConnectionChanges$?.().pipe(Dn(1)).subscribe(()=>a.next())}catch(m){this.loggingService.catch("Error binding the comment-views trigger connection listener: ",m)}return()=>{try{i(),d?.unsubscribe()}catch(m){this.loggingService.catch("Error disposing the comment-views trigger registration listener: ",m)}}}).pipe(Ee(()=>e()),Gt(),Fe(a=>t(a)))}portableOrganizationTrigger$(e,t){return this.commentViewsTimestampTrigger$(this.gateOnOrganizationAccess$(t,()=>this.commonDbService.dbListener({feature:"organizationCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:e}})))}portableFolderTrigger$(e,t){return this.commentViewsTimestampTrigger$(this.commonDbService.dbListener({feature:"folderCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:e,folderId:t,id:t}}))}portableDocumentListener$(e,t){return this.commonDbService.dbListener({feature:"documentCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t,organizationId:e}})}portableBatchTrigger$(e,t){return t.length?Bt(t.map(a=>this.portableDocumentListener$(e,a).pipe(Ee(i=>i?.data?.commentViewsUpdatedAt??null)))).pipe(Ee(a=>dk([...a])),Gt(Qn)):Hr}handleGroupedCounts$(e,t,a,i,d,m,u){try{let f=t.map((y,S)=>e[S].pipe(Ch(void 0),Fe(()=>jn(this.getCountsForDocument$(y.documentId,y.clientDocumentId,a,i,d,m,u)))));return Bt(f).pipe(Ee(y=>{let S={};return y.forEach(j=>{j&&(S[j.clientDocumentId]={total:j.total,unread:j.unread})}),{data:S}}),Wr(y=>(this.loggingService.catch("Error in grouped counts: ",y),ye(null))))}catch(f){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",f),ye(null)}}handleBatchedGroupedCounts$(e){try{let{triggers$:t,documentIds:a,request:i,userId:d,organizationId:m,veltFolderId:u,debounceMs:f,portableIds:y}=e,S=this.LISTENER_BATCH_SIZE,j=new db(1),W=t.map((ce,fe)=>ce.pipe(hb(j),Ee(()=>fe))),$=Ko(...W).pipe(po(f)),H=ye(-1).pipe(Fe(()=>jn(this.fetchAllDocumentCounts$(a,i,d,m,u,y))),Ee(ce=>({batchIndex:-1,data:ce?.data||{}})),Tm(()=>{j.next()})),q=$.pipe(Fe(ce=>{let fe=ce*S,le=Math.min(fe+S,a.length),he=a.slice(fe,le);return jn(this.fetchAllDocumentCounts$(he,i,d,m,u,y)).pipe(Ee(xe=>({batchIndex:ce,data:xe?.data||{}})))}));return Ko(H,q).pipe(gb((ce,fe)=>({data:g(g({},ce.data),fe.data)}),{data:{}}),Wr(ce=>(this.loggingService.catch("Error in batched grouped counts: ",ce),ye(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleBatchedGroupedCounts: ",t),ye(null)}}fetchAllDocumentCounts$(e,t,a,i,d,m){return Pe(this,null,function*(){try{if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0)return yield this.fetchPortablePerDocumentCounts(e,t,d,m);let u=e.map(S=>this.getCountsForDocument$(S.documentId,S.clientDocumentId,t,a,i,d)),f=yield Promise.allSettled(u),y={};return f.forEach(S=>{if(S.status==="fulfilled"&&S.value){let{clientDocumentId:j,total:W,unread:$}=S.value;y[j]={total:W,unread:$}}}),{data:y}}catch(u){return this.loggingService.catch("Error in CommentService fetchAllDocumentCounts: ",u),null}})}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:a,request:i,userId:d,organizationId:m,clientOrganizationId:u,veltFolderId:f,folderId:y,mode:S}=e;return Bt(t).pipe(Ee(()=>{})).pipe(Ch(void 0),Fe(()=>jn(this.getAggregateCounts({serverDocumentIds:a,request:i,userId:d,organizationId:m,clientOrganizationId:u,veltFolderId:f,folderId:y,mode:S}))),Wr(W=>(this.loggingService.catch("Error in aggregate counts: ",W),ye(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),ye(null)}}getCountsForDocument$(e,t,a,i,d,m,u){return Pe(this,null,function*(){try{let f=wc({layout:"perDocument",documentIds:[e],folder:!!m,filters:a});if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0){let W=yield this.countCommentsOnPortable(sp(f,{organizationId:u?.clientOrganizationId??"",folderId:u?.folderId}));return g({clientDocumentId:t},W)}let y=this.toFirestoreCountQueries(f,{apiKey:this.configService?.getApiKey(),organizationId:d,veltFolderId:m,userId:i}),S=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:y.total})}),j=0;return y.read&&(j=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:y.read})})),{clientDocumentId:t,total:S,unread:S-j}}catch(f){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",f),null}})}getAggregateCounts(e){return Pe(this,null,function*(){try{let{serverDocumentIds:t,request:a,userId:i,organizationId:d,clientOrganizationId:m,veltFolderId:u,folderId:f,mode:y}=e,S=lk({mode:y,serverDocumentIds:t,hasFolder:!!u,filters:a,batchSize:this.LISTENER_BATCH_SIZE,folderId:f,clientOrganizationId:m});if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0)return yield this.getPortableAggregateCounts(S,{clientOrganizationId:m,folderId:f});let j=S.key,W={apiKey:this.configService?.getApiKey(),organizationId:d,veltFolderId:u,userId:i},$,H=0;if(y.isFolderMode||y.isOrgMode){let q=this.toFirestoreCountQueries(S.queries[0],W);$=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:q.total})}),q.read&&(H=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:q.read})}))}else{let q=S.queries.map(le=>this.toFirestoreCountQueries(le,W));$=(yield Promise.allSettled(q.map(le=>Pe(this,null,function*(){return this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:le.total})})})))).reduce((le,he)=>le+(he.status==="fulfilled"&&he.value||0),0);let fe=q.filter(le=>le.read);fe.length&&(H=(yield Promise.allSettled(fe.map(he=>Pe(this,null,function*(){return this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:he.read})})})))).reduce((he,xe)=>he+(xe.status==="fulfilled"&&xe.value||0),0))}return{data:{[j]:{total:$,unread:$-H}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}countCommentsOnPortable(e){return Pe(this,null,function*(){try{let t=yield this.commonDbService.runPortableCommentQuery("getCommentAnnotationsCount",e);return t?.ok?vk(t.data):{total:0,unread:0}}catch(t){return this.loggingService.catch("Error in CommentViewsService countCommentsOnPortable: ",t),{total:0,unread:0}}})}fetchPortablePerDocumentCounts(e,t,a,i){return Pe(this,null,function*(){try{let d={},m=[];for(let u=0;u<e.length;u+=Z.FIRESTORE_IN_QUERY_LIMIT)m.push(e.slice(u,u+Z.FIRESTORE_IN_QUERY_LIMIT));return yield Promise.all(m.map(u=>Pe(this,null,function*(){let f=wc({layout:"perDocument",documentIds:u.map(j=>j.documentId),folder:!!a,filters:t}),y=yield this.commonDbService.runPortableCommentQuery("getCommentAnnotationsCount",b(g({},sp(f,{organizationId:i?.clientOrganizationId??"",folderId:i?.folderId})),{perDocument:!0})),S=y?.ok?y.data?.counts:void 0;for(let j of u)d[j.clientDocumentId]=vk(S?.[j.documentId])}))),{data:d}}catch(d){return this.loggingService.catch("Error in CommentViewsService fetchPortablePerDocumentCounts: ",d),null}})}getPortableAggregateCounts(e,t){return Pe(this,null,function*(){try{let a=yield Promise.all(e.queries.map(m=>this.countCommentsOnPortable(sp(m,{organizationId:t.clientOrganizationId??"",folderId:t.folderId})))),i=a.reduce((m,u)=>m+u.total,0),d=a.reduce((m,u)=>m+u.unread,0);return{data:{[e.key]:{total:i,unread:d}}}}catch(a){return this.loggingService.catch("Error in CommentViewsService getPortableAggregateCounts: ",a),null}})}toFirestoreCountQueries(e,t){let a=[Et("metadata.apiKey","==",t.apiKey),Et("metadata.organizationId","==",t.organizationId),...e.clauses.map(d=>Et(d.field,d.op,d.key==="folderId"?t.veltFolderId:d.value))],i=yc(xc);return g({total:[Xn(...a),...i]},e.countsRead?{read:[Xn(...a,Et("viewedByUserIds","array-contains",t.userId)),...i]}:{})}filterGhostComments$(e,t,a){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(Ee(i=>{if(!i)return e;let d=this.buildGhostCommentAnnotationMap(i),m=this.groupGhostCommentsByModeId(d,t,a);return this.adjustCountsForGhostComments(e,m),e})):ye(null)}catch(i){return this.loggingService.catch("Error in CommentService filterGhostComments: ",i),ye(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(a=>{let i=this.commentService.getAnnotationById(a);i&&(t[a]=i)}),t}groupGhostCommentsByModeId(e,t,a){try{let i={};return Object.values(e).forEach(d=>{let m=this.getModeIdForAnnotation(d,t,a);m&&(i[m]||(i[m]=[]),i[m].push(d))}),i}catch(i){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",i),{}}}getModeIdForAnnotation(e,t,a){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?a.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(i){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",i),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let i=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(d=>{let m=t[d];if(!(!m||!e?.data?.[d]?.total)&&(e.data[d].total=Math.max(0,e.data[d].total-m.length),i)){let u=m.filter(f=>f?.viewedByUserIds&&!f?.viewedByUserIds?.includes(i));u.length>0&&(e.data[d].unread=Math.max(0,e.data[d].unread-u.length))}})}catch(a){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",a)}}};o.\u0275fac=function(t){return new(t||o)(be(vt),be(wr),be(ut),be(kc),be(_o),be(A),be(ae),be(tp),be(XC))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var $D=1e4,lt=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y,S,j,W,$,H,q){this.analyticsService=e,this.authService=t,this.commentService=a,this.commentViewsService=i,this.contactService=d,this.customFilterService=m,this.docService=u,this.iamService=f,this.loggingService=y,this.metadataService=S,this.commonDbService=j,this.serviceBook=W,this.suggestionActions=$,this.targetRegistry=H,this.commentAnnotationsResolverService=q,this.recentAccepts=new Map,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.reactionService=null,this.inFlightSuggestionTransitions=new Set,this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;");try{this.commentService.setCommentActionsService(this),this.iamService.isUserAdmin$().subscribe(ce=>{this.isUserAdmin=ce}),this.serviceBook.observe(ju).subscribe(ce=>{this.reactionService=ce})}catch(ce){this.loggingService.catch("Error in CommentActionsService constructor: ",ce)}}addCommentAnnotation(d,m){return Pe(this,arguments,function*({annotation:e,options:t,visibility:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addCommentAnnotation","color: green;"),a){if(a.type==="restricted"){let y=this.authService.getUser();y?.userId&&(a=xo(a,y.userId))}if(a.type==="organizationPrivate"&&!a.organizationId&&!a.organizationIds?.length){let y=this.authService.getUser()?.clientOrganizationId;y&&(a=b(g({},a),{organizationId:y}))}let u=this.authService.getUser()?.userId,f=qn(a,u);f.length>0&&(e.context||(e.context={}),e.context._setAccessFields=f,e.visibilityConfig=Zn(a,u))}return new Promise(u=>{this.commentService.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,f=>Pe(this,null,function*(){let y=to(void 0,f?.annotation?.assignedTo,this.onIsAssigneeChangedError),S=yield this.getAddCommentAnnotationEventFromCommentAddEventData(f,y);u(S)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,i)})}catch(u){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",u),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e,t){return Pe(this,null,function*(){try{let a=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:this.commentService.getCommentAnnotationForClient(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:a,addContext:e?.addContext,elementRef:e?.elementRef,isAssigneeChanged:t??!1}}catch(a){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",a),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ct.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}getAddCommentAnnotationDraftEventFromCommentAddEventData(e){return Pe(this,null,function*(){try{return{metadata:yield this.metadataService.getGlobalMetadata(),addContext:e?.addContext}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationDraftEvent(e){try{this.triggerAction(ct.ADD_COMMENT_ANNOTATION_DRAFT,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationDraftEvent: ",t)}}triggerAddCommentDraftEventForAnnotation(e,t){return Pe(this,null,function*(){try{if(!e?.annotationId||!t)return;let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),comment:t,metadata:a};this.triggerAction(ct.ADD_COMMENT_DRAFT,i)}catch(a){this.loggingService.catch("Error in CommentActionsService triggerAddCommentDraftEventForAnnotation: ",a)}})}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let u=this.commentService.getAnnotationById(e,t);if(u){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===u?.from?.userId){this.commentService.deleteCommentPinAnnotation(u);let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:u.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(u),metadata:y};return this.triggerAction(ct.DELETE_COMMENT_ANNOTATION,S),S}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteCommentAnnotation: ",m),null}})}updatePriority(d,m){return Pe(this,arguments,function*({annotationId:e,priority:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updatePriority","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f=JSON.parse(JSON.stringify(f));let y=f.priority?JSON.parse(JSON.stringify(f.priority)):null;y&&t&&y?.id===t?.id?f.priority=void 0:f.priority=t,this.commentService.saveComment(f,{type:qe.PRIORITY_CHANGED,newPriority:t,oldPriority:y});let S=yield this.metadataService.getGlobalMetadata(),j={newPriority:t,oldPriority:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};return this.triggerAction(ct.UPDATE_PRIORITY,j),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(f),oldPriority:f.priority,newPriority:t,commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),j}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updatePriority: ",u),null}})}updateStatus(d,m){return Pe(this,arguments,function*({annotationId:e,status:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateStatus","color: green;");let u=this.authService.getUser();if(!u)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f=JSON.parse(JSON.stringify(f));let y=f.status?JSON.parse(JSON.stringify(f.status)):null;f.status=t,f.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(f,{type:qe.STATUS_CHANGED,newStatus:t,oldStatus:y});let S=yield this.metadataService.getGlobalMetadata(),j={newStatus:t,oldStatus:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};return this.triggerAction(ct.UPDATE_STATUS,j),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(f),oldStatus:y,newStatus:t,commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,commentAnnotationCreatedAt:f.createdAt}),j}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateStatus: ",u),null}})}updateAccess(d,m){return Pe(this,arguments,function*({annotationId:e,accessMode:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateAccess","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f)if(this.commentService.isPrivateCommentAllowed()){f=JSON.parse(JSON.stringify(f));let y=f.iam?.accessMode;f.iam.accessMode=t,this.commentService.saveComment(f,{type:qe.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:y});let S=yield this.metadataService.getGlobalMetadata(),j={newAccessMode:t,oldAccessMode:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};switch(this.triggerAction(ct.UPDATE_ACCESS,j),t){case gr.PRIVATE:this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:gr.PRIVATE,source:i??this.defaultSource});break;case gr.PUBLIC:this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:gr.PUBLIC,source:i??this.defaultSource});break;default:break}return j}else this.loggingService.catch("Access Denied","You must be an admin to update the access mode of the comment.");else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateAccess: ",u),null}})}resolveCommentAnnotation(a){return Pe(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: resolveCommentAnnotation","color: green;");let i=this.authService.getUser();if(!i)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let d=this.commentService.getAnnotationById(e,t);if(d){d=JSON.parse(JSON.stringify(d));let m=this.customFilterService.resolvedStatus,u=d.status?JSON.parse(JSON.stringify(d.status)):null;m&&(d.status=m,d.statusUpdatedByUserId=i?.userId,this.commentService.saveComment(d,{type:qe.STATUS_CHANGED,newStatus:m,oldStatus:u}));let f=yield this.metadataService.getGlobalMetadata(),y={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:f};return this.triggerAction(ct.RESOLVE_COMMENT,y),y}else this.triggerAnnotationNotFoundError(e);return null}catch(i){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",i),null}})}getLink(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let m=this.commentService.getAnnotationById(e,t);if(m){let u=this.commentService.getCommentUrl(m)??null,f=yield this.metadataService.getGlobalMetadata();return{link:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:f}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService getLink: ",m),null}})}copyLink(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let m=yield this.getLink({annotationId:e,options:t},a);if(m?.link){yC(m.link),this.commentService.setCopyLink(m.link),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_LINK_COPIED,{annotationId:e,commentType:this.commentService.getCommentType(m.commentAnnotation),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,link:m.link});let u=yield this.metadataService.getGlobalMetadata(),f={link:m.link,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m.commentAnnotation),metadata:u};return this.triggerAction(ct.COPY_LINK,f),f}return null}catch(m){return this.loggingService.catch("Error in CommentActionsService copyLink: ",m),null}})}addComment(f,y){return Pe(this,arguments,function*({annotationId:e,comment:t,assignedTo:a,assigned:i,options:d,visibility:m},u){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let S=this.authService.getUser();if(!S)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(S){let j=this.commentService.getAnnotationById(e,d),W=j?.comments?.length?qe.ADDED:qe.NEWLY_ADDED;if(j){let $=j.assignedTo;j.status.type==="terminal"&&(j.status=this.customFilterService.defaultStatus);let H=new Co;H=g(g({},H),t),H.lastUpdated=new Date,H.attachments||(H.attachments=[]),H.attachments=H.attachments.filter(xe=>xe?.attachmentId),H.createdAt=this.timestamp,H.from=S,a&&(j.assignedTo=a);let q=to(W===qe.NEWLY_ADDED?void 0:$,j.assignedTo,this.onIsAssigneeChangedError);this.commentService.saveComment(j,b(g({type:W,updatedComment:H,assigned:i,visibility:m},W===qe.ADDED?{_isAssigneeChanged:q}:{}),{_dispatchAddCommentEvent:!0}));let ce=b(g({},j),{comments:[...j.comments||[],H]}),fe=yield this.buildAddCommentEvent({annotation:ce,newComment:H,isAssigneeChanged:q});if(!fe)return null;let le=t?.commentId,he=this.calculateCommentThreadIndex(t,j);return this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:le,commentThreadIndex:he,commentType:this.commentService.getCommentType(j),commentMode:this.commentService.getCommentMode(),source:u??this.defaultSource,commentAnnotationCreatedAt:j.createdAt,taggedClientUserIds:H.taggedUserContacts?.map(xe=>xe.contact?.userId).filter(xe=>!!xe),taggedSnippylyUserIds:H.taggedUserContacts?.filter(xe=>!!j?.metadata?.apiKey&&!!xe.contact?.userId).map(xe=>Uu(j.metadata.apiKey,xe.contact.userId))}),fe}else this.triggerAnnotationNotFoundError(e)}return null}catch(S){return this.loggingService.catch("Error in CommentActionsService addComment: ",S),null}})}buildAddCommentEvent(i){return Pe(this,arguments,function*({annotation:e,newComment:t,isAssigneeChanged:a}){try{let d=yield this.metadataService.getGlobalMetadata();return{annotationId:e.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:d,isAssigneeChanged:a??!1}}catch(d){return this.loggingService.catch("Error in CommentActionsService buildAddCommentEvent: ",d),null}})}triggerAddCommentEvent(i){return Pe(this,arguments,function*({annotation:e,newComment:t,isAssigneeChanged:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: triggerAddCommentEvent","color: green;");let d=yield this.buildAddCommentEvent({annotation:e,newComment:t,isAssigneeChanged:a});return d&&this.triggerAction(ct.ADD_COMMENT,d),d}catch(d){return this.loggingService.catch("Error in CommentActionsService triggerAddCommentEvent: ",d),null}})}approveCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t);if(m){m.approved=!0,this.commentService.saveComment(m,{type:qe.APPROVED}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_APPROVED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource});let u=yield this.metadataService.getGlobalMetadata(),f={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:u};return this.triggerAction(ct.APPROVE_COMMENT_ANNOTATION,f),f}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService approveComment: ",m),null}})}acceptCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=Z.CommentAcceptStatus,m.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(m,{type:qe.ACCEPTED,oldStatus:f,newStatus:Z.CommentAcceptStatus});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:y,actionUser:u,replaceContentHtml:m?.comments?.length?m?.comments[0]?.replaceContentHtml:void 0,replaceContentText:m?.comments?.length?m?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ct.ACCEPT_COMMENT_ANNOTATION,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPTED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService acceptCommentAnnotation: ",m),null}})}rejectCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=Z.CommentRejectStatus,m.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(m,{type:qe.REJECTED,oldStatus:f,newStatus:Z.CommentRejectStatus});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:y,actionUser:u,replaceContentHtml:m?.comments?.length?m?.comments[0]?.replaceContentHtml:void 0,replaceContentText:m?.comments?.length?m?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ct.REJECT_COMMENT_ANNOTATION,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_REJECTED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService rejectCommentAnnotation: ",m),null}})}ensureSuggestionObject(e){try{return!e||e?.suggestion||!(e?.type==="suggestion"||e?.commentType==="suggestion")?"noop":this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.getFieldsToRemove()?.includes("suggestion")&&!this.commentAnnotationsResolverService.getCommentAnnotationById(e.annotationId)?(this.loggingService.catch(`CommentActionsService: suggestion transition refused for ${e.annotationId} \u2014 its suggestion has not loaded from the comment resolver`),"refused"):(e.suggestion={status:"pending",targetId:"",targetType:"custom",oldValue:null,newValue:null,summary:null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},"seeded")}catch(t){return this.loggingService.catch("Error in CommentActionsService ensureSuggestionObject: ",t),"noop"}}runSuggestionTransition(e,t){return Pe(this,null,function*(){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t();if(this.inFlightSuggestionTransitions.has(e))return this.loggingService.catch(`CommentActionsService: a suggestion transition is already in flight for ${e}`),null;this.inFlightSuggestionTransitions.add(e);try{return yield t()}finally{this.inFlightSuggestionTransitions.delete(e)}})}loadForSuggestionTransition(e,t,a){return Pe(this,null,function*(){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;if(!this.commentAnnotationsResolverService.getCommentAnnotationById(t)){let m=this.docService.getDocumentPaths()?.clientOrganizationId??this.authService.getUser()?.clientOrganizationId??"";if((yield this.commentAnnotationsResolverService.fetchForTransition(t,m))!=="ok")return this.loggingService.catch(`CommentActionsService: suggestion transition refused for ${t} \u2014 the comment resolver could not be reached`),null}let i=this.commentService.getAnnotationById(t,a);if(!i)return this.triggerAnnotationNotFoundError(t),null;let d=this.commentAnnotationsResolverService.getCommentAnnotationById(t)?.suggestion;return!i.suggestion&&d&&typeof d=="object"&&!Array.isArray(d)&&(i.suggestion=FC(d)),RC(i,d),i})}refusesContentlessAccept(e,t){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||t==="seeded")return!1;let a=e?.suggestion;return NC(a)&&Object.prototype.hasOwnProperty.call(a,"newValue")?!1:(this.loggingService.catch(`CommentActionsService: accept refused for ${e?.annotationId} \u2014 its suggestion content is not available from the comment resolver`),!0)}acceptSuggestion(e,t){return Pe(this,null,function*(){return this.runSuggestionTransition(e?.annotationId,()=>this.acceptSuggestionTransition(e,t))})}applyOnCurrentText(e,t,a){try{if(typeof a!="string"||typeof t.oldValue!="string")return;let i=S=>S.replace(/\u00a0/g," "),d=t.targetId,m=d?this.recentAccepts.get(d):void 0,f=m&&Date.now()-m.at<$D&&i(a)===i(m.oldValue)&&i(m.newValue)!==i(a)?m.newValue:a,y=null;if(i(f)!==i(t.oldValue)){let S=M0(t.textChange).value,j=S?mp(f,S):null;if(!S||!j||j.form!=="original")return;y={oldValue:f,newValue:f.slice(0,j.start)+S.added+f.slice(j.end)},this.suggestionActions.setAppliedValues(e,y)}d&&typeof t.newValue=="string"&&this.recentAccepts.set(d,b(g({},y??{oldValue:t.oldValue,newValue:t.newValue}),{at:Date.now()}))}catch(i){this.loggingService.catch("Error in CommentActionsService applyOnCurrentText: ",i)}}applyThroughSetter(e){try{let t=e.suggestion,a=t?.targetId;if(!t||!a||!this.targetRegistry.getSetter(a))return;let i=this.suggestionActions.projectAnnotationToSuggestion(e);this.targetRegistry.callSetter(a,i?i.newValue:t.newValue,{reason:"accept",suggestion:i})}catch(t){this.loggingService.catch("Error in CommentActionsService applyThroughSetter: ",t)}}acceptSuggestionTransition(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptSuggestion","color: green;");let m=this.authService.getUser();if(!m)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let u=this.commentService.getAnnotationById(e,t);if(!u)return this.triggerAnnotationNotFoundError(e),null;let f=yield this.loadForSuggestionTransition(u,e,t);if(!f)return null;let y=this.ensureSuggestionObject(f);if(y==="refused"||!(f.type==="suggestion"||f.commentType==="suggestion")||!f.suggestion||f.suggestion.status!=="pending")return null;let S=f.suggestion.targetId;if(S){let $=this.targetRegistry.getNode(S),H=this.targetRegistry.getGetter(S);if(!$&&!H){f.suggestion.status="stale",f.suggestion.resolvedBy=m,f.suggestion.resolvedAt=this.timestamp,f.statusUpdatedByUserId=m?.userId,this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"stale",targetId:S}),this.commentService.updateComment(f),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_STALE,f);let fe=yield this.metadataService.getGlobalMetadata(),le={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:fe,actionUser:m};return this.triggerAction(ct.SUGGESTION_ACCEPTED,le),le}if(this.refusesContentlessAccept(f,y))return null;let q=!1,ce;if(H)try{ce=H(),q=!xn(ce,f.suggestion.oldValue)}catch(fe){if(!$)return this.loggingService.catch("Error in acceptSuggestion: registered getter threw",fe,{targetId:S,annotationId:e}),null;q=!1}else $ instanceof HTMLElement&&$.isContentEditable&&(ce=$.textContent??"");f.suggestion.driftDetected=q,this.applyOnCurrentText(e,f.suggestion,ce)}else if(this.refusesContentlessAccept(f,y))return null;f.suggestion.status="accepted",f.suggestion.resolvedBy=m,f.suggestion.resolvedAt=this.timestamp,f.statusUpdatedByUserId=m?.userId,f.type="comment",f?.agent?.agentFields&&typeof f.agent.agentFields=="object"&&Array.isArray(f.agent.agentFields)&&(f.agent.agentFields=f.agent.agentFields.filter($=>$!=="status:suggestion"),f.agent.agentFields.includes("status:accepted")||f.agent.agentFields.push("status:accepted")),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"accepted",targetId:S,driftDetected:f.suggestion?.driftDetected}),this.commentService.saveComment(f,{type:qe.SUGGESTION_ACCEPTED}),this.applyThroughSetter(f),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_APPROVED,f),this.analyticsService.trackEvent(oe.Events.Comments.SUGGESTION_ACCEPTED,{annotationId:e});let j=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:j,actionUser:m};return this.triggerAction(ct.SUGGESTION_ACCEPTED,W),W}catch(m){return this.loggingService.catch("Error in CommentActionsService acceptSuggestion: ",m),null}})}getRejectSuggestionAnalyticsRequest(e){if(!e||!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=e,{reason:t}=i;return ib(i,["reason"])}rejectSuggestion(e,t){return Pe(this,null,function*(){return this.runSuggestionTransition(e?.annotationId,()=>this.rejectSuggestionTransition(e,t))})}rejectSuggestionTransition(d,m){return Pe(this,arguments,function*({annotationId:e,reason:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectSuggestion","color: green;");let u=this.authService.getUser();if(!u)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(!f)return this.triggerAnnotationNotFoundError(e),null;let y=yield this.loadForSuggestionTransition(f,e,a);if(!y||this.ensureSuggestionObject(y)==="refused"||!(y.type==="suggestion"||y.commentType==="suggestion")||!y.suggestion||y.suggestion.status!=="pending")return null;y.suggestion.status="rejected",y.suggestion.rejectReason=t??null,y.suggestion.resolvedBy=u,y.suggestion.resolvedAt=this.timestamp,y.statusUpdatedByUserId=u?.userId,y.type="comment",y?.agent?.agentFields&&typeof y.agent.agentFields=="object"&&Array.isArray(y.agent.agentFields)&&(y.agent.agentFields=y.agent.agentFields.filter(W=>W!=="status:suggestion"),y.agent.agentFields.includes("status:rejected")||y.agent.agentFields.push("status:rejected")),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_REJECT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"rejected",targetId:y.suggestion.targetId}),this.commentService.saveComment(y,{type:qe.SUGGESTION_REJECTED}),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_REJECTED,y),this.analyticsService.trackEvent(oe.Events.Comments.SUGGESTION_REJECTED,{annotationId:e});let S=yield this.metadataService.getGlobalMetadata(),j={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(y),metadata:S,actionUser:u,rejectReason:t??null};return this.triggerAction(ct.SUGGESTION_REJECTED,j),j}catch(u){return this.loggingService.catch("Error in CommentActionsService rejectSuggestion: ",u),null}})}toggleNotificationSubscription(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=fr(u.userId);if(f){m.subscribedUsers||(m.subscribedUsers={}),m.unsubscribedUsers||(m.unsubscribedUsers={});let y,S=!1;if(m?.unsubscribedUsers?.[f])S=!1;else if(m?.subscribedUsers?.[f])S=!0;else{let $=this.contactService.getCurrentOrganizationUserIAM();if($){let H=$.groups||{};Object.keys(H).forEach(q=>{m?.subscribedGroups?.[q]&&(S=!0)})}}if(a==="subscribe"||!a&&!S)delete m.unsubscribedUsers[f],m.subscribedUsers[f]={user:u,type:"manual"},y=qe.SUBSCRIBED;else if(a==="unsubscribe"||!a&&S)delete m.subscribedUsers[f],m.unsubscribedUsers[f]={user:u,type:"manual"},y=qe.UNSUBSCRIBED;else return null;this.commentService.saveComment(m,{type:y});let j=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:j};return y===qe.SUBSCRIBED?this.triggerAction(ct.SUBSCRIBE_COMMENT_ANNOTATION,W):this.triggerAction(ct.UNSUBSCRIBE_COMMENT_ANNOTATION,W),W}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",m),null}})}assignUser(d,m){return Pe(this,arguments,function*({annotationId:e,assignedTo:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: assignUser","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f.assignedTo=t,this.commentService.saveComment(f,{type:qe.ASSIGNED,assignedTo:t});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,assignedTo:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:y};return this.triggerAction(ct.ASSIGN_USER,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(f),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,assignedToUserId:t?.userId}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService assignUser: ",u),null}})}getComment(a){return Pe(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let i=this.commentService.getAnnotationById(e,t);return i?i.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(i){return this.loggingService.catch("Error in CommentActionsService getComment: ",i),[]}})}updateOrDeleteComment(e,t,a,i,d,m,u){return Pe(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length||Bh(t)){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=qe.UPDATED,!t.isEdited&&Lh(m)&&(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:qe.UPDATED,updatedComment:t});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:y,isAssigneeChanged:u??!1};return this.triggerAction(ct.UPDATE_COMMENT,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:d??this.defaultSource}),S}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}else yield this.deleteComment({annotationId:e?.annotationId,commentId:t.commentId,skipDeleteThreadConfirmation:a,options:i});return null}catch(f){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",f),null}})}updateComment(f,y,S){return Pe(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:a,merge:i,options:d},m,u){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let j=this.commentService.getAnnotationById(e,d),W=this.authService.getUser();if(!W)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(j&&W){this.commentService.spliceProgressCommentsIn(j);try{let $=t,H=j.comments?.find(q=>q.commentId===t.commentId);if(H){if(this.isUserAdmin||W?.userId===H?.from?.userId)return j?.status.type==="terminal"&&(j.status=this.customFilterService.defaultStatus),i&&($=g(g({},H),t)),$.from=H.from,$.createdAt=H.createdAt,$.lastUpdated=new Date,yield this.updateOrDeleteComment(j,$,a,d,m,H,u);this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}}finally{this.commentService.restoreProgressCommentSplit(j)}}else this.triggerAnnotationNotFoundError(e);return null}catch(j){return this.loggingService.catch("Error in CommentActionsService updateComment: ",j),null}})}deleteComment(m,u){return Pe(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:a,options:i},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let f=this.commentService.getAnnotationById(e,i),y=this.authService.getUser();if(!f)return this.triggerAnnotationNotFoundError(e),null;this.commentService.spliceProgressCommentsIn(f);try{let S=f.comments?.find(q=>q?.commentId===t);if(!S)return null;if(!(this.isUserAdmin||y?.userId===S?.from?.userId))return this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it."),null;let j=this.commentService.willDeleteWholeAnnotation(f,t),W=this.commentService.getCommentAnnotationForClient(f);if(!a&&!(yield this.commentService.confirmDeleteCommentIfRequired(f,S)))return null;this.commentService.saveComment(f,{type:qe.DELETED,updatedComment:S,skipDeleteThreadConfirmation:!0});let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:e,commentId:t,commentAnnotation:W,comment:S,metadata:$};if(j){let q={annotationId:e,commentAnnotation:W,metadata:$};this.triggerAction(ct.DELETE_COMMENT_ANNOTATION,q)}else this.triggerAction(ct.DELETE_COMMENT,H);return H}finally{this.commentService.restoreProgressCommentSplit(f)}}catch(f){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",f),null}})}addAttachment(d,m){return Pe(this,arguments,function*({annotationId:e,files:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let u=[],f=this.commentService.getAnnotationById(e,a);if(f||i==="internal"){let j=[];t.forEach(W=>{let{valid:$,file:H,maxAllowedSize:q,error:ce}=this.validateFile(W);$&&H?j.push(this.uploadFile(H,f||{}).then(fe=>({valid:$,file:H,maxAllowedSize:q,error:ce,attachment:fe||void 0}))):j.push(Promise.resolve({valid:$,file:H,maxAllowedSize:q,error:ce,attachment:void 0}))}),u=yield Promise.all(j)}else this.triggerAnnotationNotFoundError(e);let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:f?this.commentService.getCommentAnnotationForClient(f):void 0,attachments:u,metadata:y};return this.triggerAction(ct.ADD_ATTACHMENT,S),u}catch(u){return this.loggingService.catch("Error in CommentActionsService addAttachment: ",u),[]}})}validateFile(e){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: validateFile","color: green;");let t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let a=e.size<=t;return{valid:a,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:a?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(d){return Pe(this,arguments,function*({annotationId:e,commentId:t,attachmentId:a,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteAttachment","color: green;");let m=this.commentService.getAnnotationById(e,i);if(m){let u=m.comments?.find(y=>y?.commentId===t),f=m.metadata;if(u){let y=this.authService.getUser();if(this.isUserAdmin||y?.userId===u?.from?.userId){let S=u.attachments?.find(j=>j?.attachmentId===a);if(S){u.attachments=u.attachments?.filter(H=>H?.attachmentId!==a);let j={attachmentId:S.attachmentId,organizationId:f?.clientOrganizationId??f?.organizationId??null,documentId:f?.clientDocumentId??f?.documentId??null,folderId:f?.folderId??null,commentAnnotationId:m.annotationId,apiKey:f?.apiKey??null};yield this.commentService.deleteAttachment({attachment:S,metadata:j,annotation:m});let W=yield this.metadataService.getGlobalMetadata(),$={attachment:S,annotationId:e,commentId:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:W};return this.triggerAction(ct.DELETE_ATTACHMENT,$),this.updateComment({annotationId:e,comment:u,options:i}),$}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the attachment.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteAttachment: ",m),null}})}getAttachment(i){return Pe(this,arguments,function*({annotationId:e,commentId:t,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getAttachment","color: green;");let d=this.commentService.getAnnotationById(e,a);return d?d.comments?.find(u=>u?.commentId===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(d){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",d),[]}})}uploadFile(e,t){return Pe(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(a){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",a),null}})}getRecording(i){return Pe(this,arguments,function*({annotationId:e,commentId:t,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getRecording","color: green;");let d=this.commentService.getAnnotationById(e,a);return d?d.comments?.find(u=>u?.commentId===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(d){return this.loggingService.catch("Error in CommentActionsService getRecording: ",d),[]}})}deleteRecording(d){return Pe(this,arguments,function*({annotationId:e,commentId:t,recorderId:a,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteRecording","color: green;");let m=this.commentService.getAnnotationById(e,i);if(m){let u=m.comments?.find(f=>f?.commentId===t);if(u){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===u?.from?.userId){let y=u.recorders?.find(S=>S?.id===a);if(y){u.recorders=u.recorders?.filter(W=>W?.id!==a);let S=yield this.metadataService.getGlobalMetadata(),j={annotationId:e,commentId:t,recording:y,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:S};return this.triggerAction(ct.DELETE_RECORDING,j),this.updateComment({annotationId:e,comment:u,skipDeleteThreadConfirmation:!0,options:i}),j}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the recording.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteRecording: ",m),null}})}fetchCommentAnnotations(e){return Pe(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),a;if(t?.hasMore){let d=t?.data[t?.data?.length-1];a=yield hC(d?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let i=t?.data?.reduce((d,m)=>(d[m.metadata.clientDocumentId??m.metadata.documentId]=d[m.metadata.clientDocumentId??m.metadata.documentId]||[],d[m.metadata.clientDocumentId??m.metadata.documentId].push(this.commentService.getCommentAnnotationForClient(m)),d),{});return g({data:i},t?.hasMore?{nextPageToken:a}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(m,u){return Pe(this,arguments,function*({annotationId:e,commentId:t,reaction:a,options:i},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let f=this.commentService.getAnnotationById(e,i),y=this.authService.getUser();if(f&&y){this.commentService.spliceProgressCommentsIn(f);try{let S=f.comments?.find(j=>j?.commentId===t);if(S){let j=yield this.reactionService?.addOrUpdateReaction(a.reactionId,S?.reactionAnnotationIds||[],void 0,void 0,f?.annotationId,a.customReaction,d),W=qe.REACTION_ADDED;if(j){j?.reactions?.find(q=>q.from?.userId===y?.userId)||(W=qe.REACTION_DELETED),S.reactionAnnotationIds||(S.reactionAnnotationIds=[]),S.reactionAnnotationIds.includes(j.annotationId)||S.reactionAnnotationIds.push(j.annotationId),j?.reactions?.length||(S.reactionAnnotationIds=S.reactionAnnotationIds.filter(q=>q!==j.annotationId)),this.pruneDanglingReactionIds(S,j.annotationId),this.commentService.saveComment(f,{type:W,updatedComment:S});let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:e,commentId:t,reaction:j,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:$};return d==="add"?this.triggerAction(ct.ADD_REACTION,H):d==="delete"?this.triggerAction(ct.DELETE_REACTION,H):this.triggerAction(ct.TOGGLE_REACTION,H),W===qe.REACTION_ADDED?this.analyticsService.trackEvent(oe.Events.Comments.REACTION_ADDED,{annotationId:e,commentId:t,reactionId:a.reactionId,commentMode:this.commentService.getCommentMode()}):W===qe.REACTION_DELETED&&this.analyticsService.trackEvent(oe.Events.Comments.REACTION_DELETED,{annotationId:e,commentId:t,reactionId:a.reactionId,commentMode:this.commentService.getCommentMode()}),H}this.pruneDanglingReactionIds(S)&&this.commentService.saveComment(f,{type:qe.REACTION_DELETED,updatedComment:S})}}finally{this.commentService.restoreProgressCommentSplit(f)}}else this.triggerAnnotationNotFoundError(e);return null}catch(f){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",f),null}})}pruneDanglingReactionIds(e,t){try{let a=e?.reactionAnnotationIds;if(!Array.isArray(a)||!a.length)return!1;let i=a.filter(d=>d===t||!!this.reactionService?.getAnnotationById(d));return i.length===a.length?!1:(e.reactionAnnotationIds=i,!0)}catch(a){return this.loggingService.catch("Error in CommentActionsService pruneDanglingReactionIds: ",a),!1}}onComposerClick(t){return Pe(this,arguments,function*({commentAnnotation:e}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onComposerClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={commentAnnotation:e?.annotationId?this.commentService.getCommentAnnotationForClient(e):void 0,metadata:a};this.triggerAction(ct.COMPOSER_CLICKED,i)}catch(a){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",a)}})}onComposerTextChange(e){return Pe(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),a={text:e.text,annotation:e.annotation,targetComposerElementId:e.targetComposerElementId,metadata:t};this.commentService.setComposerData(e.targetComposerElementId,a),this.triggerAction(ct.COMPOSER_TEXT_CHANGE,a)}catch(t){this.loggingService.catch("Error in CommentActionsService onComposerTextChange: ",t)}})}autocompleteSearch(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ct.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}onCommentPinClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentPinClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ct.COMMENT_PIN_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentPinClick: ",t),null}})}onCommentBubbleClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentBubbleClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ct.COMMENT_BUBBLE_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentBubbleClick: ",t),null}})}onCommentToolClick(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentToolClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={context:e,targetElementId:t,metadata:a},d={context:e,targetElementId:t,metadata:a};return this.triggerAction(ct.COMMENT_TOOL_CLICK,i),this.triggerAction(ct.COMMENT_TOOL_CLICKED,d),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onCommentToolClick: ",a),null}})}onSidebarButtonClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onSidebarButtonClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a=eo(e,{metadata:t}),i=eo(e,{metadata:t});return this.triggerAction(ct.SIDEBAR_BUTTON_CLICK,a),this.triggerAction(ct.SIDEBAR_BUTTON_CLICKED,i),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onSidebarButtonClick: ",t),null}})}onAttachmentDownloadClick(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onAttachmentDownloadClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),attachment:t,metadata:a};return this.triggerAction(ct.ATTACHMENT_DOWNLOAD_CLICKED,i),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onAttachmentDownloadClick: ",a),null}})}onCommentSaveTriggered(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentSaveTriggered","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(t),metadata:a};return this.triggerAction(ct.COMMENT_SAVE_TRIGGERED,i),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onCommentSaveTriggered: ",a),null}})}onVisibilityOptionClick(e,t,a){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onVisibilityOptionClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),d={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),visibility:t,users:a?.map(m=>AC(m)).filter(Boolean),metadata:i};return this.triggerAction(ct.VISIBILITY_OPTION_CLICKED,d),d}catch(i){return this.loggingService.catch("Error in CommentActionsService onVisibilityOptionClick: ",i),null}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:a}=this.docService.getServerId(e?.options);e.options=b(g({},e?.options),{documentId:t,organizationId:a})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}emitCommentActionClicked(e){return Pe(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),a=b(g(g({action:e.action,actionId:e.action?.id,scope:e.scope,annotationId:e.annotationId},e.commentId!==void 0?{commentId:e.commentId}:{}),e.comment!==void 0?{comment:e.comment}:{}),{commentAnnotation:this.commentService.getCommentAnnotationForClient(e.annotation),actionUser:this.authService.getUser(),metadata:t});return this.triggerAction(ct.COMMENT_ACTION_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService emitCommentActionClicked: ",t),null}})}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new Lt),this.actionSubjects.get(e)?.next(t)}catch(a){this.loggingService.catch("Error in CommentActionsService triggerAction: ",a)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new Lt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),ye(null)}}get onIsAssigneeChangedError(){return e=>this.loggingService.catch("Error resolving isAssigneeChanged: ",e)}get timestamp(){return this.commonDbService.getServerTimestamp()}getCommentAnnotations(e){try{if(e){if(e?.allDocuments&&!e?.folderId)return this.loggingService.catch("folderId is required when allDocuments is true."),ye({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),ye({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(Ee(t=>t?t.reduce((a,i)=>{let d=i.metadata?.clientDocumentId;return!d||e?.documentIds&&!e?.documentIds?.includes(d)||(a[d]||(a[d]=[]),a[d].push(i)),a},{}):null),Ee(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ye({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(Ee(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ye({data:null})}}updateVisibility(e){this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateVisibility","color: green;");try{let t=e.annotationId;if(!t)throw new Error("annotationId is required in visibility config");if(e.type==="restricted"){let u=this.authService.getUser();if(!u?.userId)throw new Error("Current user not found. Cannot set restricted visibility without userIds.");e=xo(e,u.userId)}if(e.type==="organizationPrivate"&&!e.organizationId&&!e.organizationIds?.length){let u=this.authService.getUser()?.clientOrganizationId;if(!u)throw new Error("No organizationId found. Cannot set organizationPrivate visibility without organizationId.");e=b(g({},e),{organizationId:u})}this.analyticsService.trackEvent(oe.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{annotationId:t,visibility:e}});let a=this.commentService.getCommentAnnotationByIdSync(t)?.from?.userId,i=a??this.authService.getUser()?.userId;a||this.loggingService.warn(`updateVisibility: annotation ${t} not in local cache \u2014 falling back to current user for the author access token`);let d=qn(e,i),m=Zn(e,i);return this.commentService.updateCommentAnnotationContext(t,{_setAccessFields:d,_setVisibilityConfig:m},{merge:!0})}catch(t){return this.loggingService.catch("Error in updateVisibility: ",t),Promise.resolve()}}calculateCommentThreadIndex(e,t){try{let a=e?.commentId,i;return a&&(i=t?.comments?.findIndex(d=>d.commentId===a)),i===-1&&(i=t?.comments?.length),i}catch(a){this.loggingService.catch("Error in calculateCommentThreadIndex: ",a);return}}};o.\u0275fac=function(t){return new(t||o)(be(pr),be(vt),be(ae),be(gp),be(zt),be(St),be(ut),be(wr),be(A),be(Ju),be(_o),be(Sr),be(Sc),be(_c),be(l0))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var up=(()=>{let o=class o{constructor(e){this.loggingService=e,this.commentTextData$=new De({});try{this.loggingService.log("%c[WB] Creating CLASS: CommentTextService","color: blue;")}catch(t){this.loggingService.catch("Error in CommentTextService constructor: ",t)}}setCommentTextData(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: setCommentTextData","color: green;");let t=e.annotationId||e.multiThreadAnnotationId;if(t){let a=e.componentId,i=this.commentTextData$.getValue();i[t]||(i[t]={}),i[t][a]=e,this.commentTextData$.next(i),this.updateLastPositionInDataByAnnotationId(t)}}catch(t){this.loggingService.catch("Error in CommentTextService setCommentTextData: ",t)}}removeCommentTextData(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: removeCommentTextData","color: green;");let t=e.annotationId||e.multiThreadAnnotationId;if(t){let a=e.componentId,i=this.commentTextData$.getValue();delete i[t][a],this.commentTextData$.next(i),this.updateLastPositionInDataByAnnotationId(t)}}catch(t){this.loggingService.catch("Error in CommentTextService removeCommentTextData: ",t)}}updateLastPositionInDataByAnnotationId(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: updateLastPositionInDataByAnnotationId","color: green;");let t=this.commentTextData$.getValue();Object.values(t[e]).forEach(a=>{a.last=this.checkIfLast(a)}),this.commentTextData$.next(t)}catch(t){this.loggingService.catch("Error in CommentTextService updateLastPositionInDataByAnnotationId: ",t)}}checkIfLast(e){try{if(this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: checkIfLast","color: green;"),e?.elementRef?.nativeElement){let t=e.elementRef.nativeElement.getRootNode(),a=t instanceof Document||t instanceof ShadowRoot?t:document,i=[];if(e.annotationId?i=Array.from(a.querySelectorAll(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.ANNOTATION_ID}="${e.annotationId}"]`)):e.multiThreadAnnotationId&&(i=Array.from(a.querySelectorAll(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.MULTI_THREAD_ANNOTATION_ID}="${e.multiThreadAnnotationId}"]`))),i.length&&i[i.length-1]===e.elementRef.nativeElement)return!0}return!1}catch(t){return this.loggingService.catch("Error in CommentTextService checkIfLast: ",t),!1}}getCommentTextDataByAnnotationIdAndComponentId(e,t){try{return this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: getCommentTextDataByAnnotationIdAndComponentId","color: green;"),this.commentTextData$.pipe(Ee(a=>a&&e&&t&&a[e]?a[e][t]:null))}catch(a){return this.loggingService.catch("Error in CommentTextService getCommentTextDataByAnnotationIdAndComponentId: ",a),ye(null)}}};o.\u0275fac=function(t){return new(t||o)(be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function pp(r,o){return r?{commentPinSelected:!0,textClicked:!!o}:{commentPinSelected:!1,textClicked:!1}}function hp(r,o,n){return r!=null&&r===o&&!!n}function sk(r){return r instanceof Document||r instanceof ShadowRoot?r:document}function gk(r,o){let n=e=>{if(!e)return null;let t=null;return(e instanceof Document||e instanceof DocumentFragment)&&(t=e.getElementById(`comment-pin-container-${o}`)),t||e.querySelector(`[data-velt-id='${o}']`)||null};return n(r)||(r!==document?n(document):null)}var GD=["overlay"],zD=()=>["snippyly-overlay-panel","velt-overlay-panel"];function HD(r,o){if(r&1&&O(0,"span",8),r&2){let n,e=l().ngIf;pe("index-3-digit",(e.commentPinAnnotation==null||e.commentPinAnnotation.annotationNumber==null||(n=e.commentPinAnnotation.annotationNumber.toString())==null?null:n.length)===3),x("data-comment-annotation-number","#"+(e.commentPinAnnotation==null?null:e.commentPinAnnotation.annotationNumber))}}function WD(r,o){if(r&1){let n=Y();p(0),C(1,"velt-multi-thread-comment-dialog-internal",10),z("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))})("pointerUp",function(t){B(n);let a=l(3);return V(a.togglePinSelection(t))}),_(),h()}if(r&2){let n=l(2).ngIf;v(),c("multiThreadAnnotationId",n.commentPinAnnotation.annotationId)("annotation",n.commentPinAnnotation)("user",n.user)("commentPinSelected",n.commentPinSelected)}}function JD(r,o){if(r&1){let n=Y();C(0,"velt-comment-dialog-internal",11),z("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))}),_()}if(r&2){let n=l(2).ngIf;c("annotation",n.commentPinAnnotation)("user",n.user)("commentPinSelected",n.commentPinSelected)("inlineCommentMode",n.inlineCommentMode)("isInsidePdfViewer",n.isInsidePdfViewer)}}function YD(r,o){if(r&1&&s(0,WD,2,4,"ng-container",9)(1,JD,1,5,"ng-template",null,2,$e),r&2){let n=we(2),e=l().ngIf;c("ngIf",(e==null||e.commentPinAnnotation==null?null:e.commentPinAnnotation.type)==="multiThread")("ngIfElse",n)}}function KD(r,o){if(r&1){let n=Y();C(0,"snippyly-comment-bottom-sheet",12),z("saveComment",function(t){B(n);let a=l(2);return V(a.saveComment(t))}),_()}if(r&2){let n=l().ngIf;c("annotation",n.commentPinAnnotation)("user",n.user)("isInsidePdfViewer",n.isInsidePdfViewer)}}function qD(r,o){if(r&1){let n=Y();p(0),C(1,"snippyly-comment-text",4,0),z("pointerover",function(t){return B(n),l().onPointerOver(t),V(t.stopPropagation())})("pointerout",function(){B(n);let t=l();return V(t.onPointerOut())})("pointerdown",function(t){return B(n),V(t.stopPropagation())})("pointerup",function(t){return B(n),l().togglePinSelection(),V(t.stopPropagation())})("touchend",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())})("click",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())}),_(),s(3,HD,1,3,"span",5)(4,YD,3,2,"ng-template",6,1,$e)(6,KD,1,3,"snippyly-comment-bottom-sheet",7),h()}if(r&2){let n=o.ngIf,e=we(2),t=l();v(),pe("inline-comment-mode",n.inlineCommentMode&&!n.isInsidePdfViewer)("agent-comment",(n.commentPinAnnotation==null?null:n.commentPinAnnotation.sourceType)==="agent")("selected",n.commentPinHover||n.commentPinSelected),v(2),c("ngIf",n.last&&n.showCommentIndex&&(n.commentPinAnnotation==null?null:n.commentPinAnnotation.annotationNumber)),v(),c("cdkConnectedOverlayOrigin",e)("cdkConnectedOverlayOpen",(!n.mobileMode||!n.isPhone)&&!n.inboxMode&&!n.streamMode&&(!n.inlineCommentMode||n.isInsidePdfViewer)&&n.floatingCommentsEnabled&&(n.textClicked&&n.commentPinSelected||n.commentPinHover&&!n.commentPinSelected))("cdkConnectedOverlayOffsetY",n.overlayOriginY==="top"?-8:2)("cdkConnectedOverlayPanelClass",gt(17,zD))("cdkConnectedOverlayBackdropClass","snippyly-overlay-backdrop")("cdkConnectedOverlayLockPosition",!1)("cdkConnectedOverlayPositions",t.positions)("cdkConnectedOverlayGrowAfterOpen",!0)("cdkConnectedOverlayDisableClose",!0),v(2),c("ngIf",(n==null?null:n.user)&&n.mobileMode&&n.isPhone&&!n.sidebarVisible&&(!n.inlineCommentMode||n.isInsidePdfViewer)&&!n.inboxMode&&!n.streamMode&&n.floatingCommentsEnabled&&n.textClicked&&n.commentPinSelected)}}var fp=(()=>{let o=class o{onEnter(e){this.onKeyupEnter&&this.onKeyupEnter()}constructor(e,t,a,i,d,m,u,f){this.analyticsService=e,this.authService=t,this.breakpointObserver=a,this.domService=i,this.commentService=d,this.loggingService=m,this.serviceBook=u,this.elementRef=f,this.subscriptions=[],this.selectedAnnotationsMap={},this.customScrollableParentEventsListenersSubscriptions=[],this.isDialogOnHoverEnabled=!1,this.componentConfigSignal=Ae({inlineCommentMode:!1,isInsidePdfViewer:!1,commentPinHover:!1,commentPinSelected:!1,first:!1,last:!1,showCommentIndex:!1,commentPinAnnotation:null,isPhone:!1,mobileMode:!1,streamMode:!1,inboxMode:!1,textClicked:!1,floatingCommentsEnabled:!0,sidebarVisible:!1,user:null,overlayOriginX:"start",overlayOriginY:"top"}),this.positions=Z.OVERLAY_POSITIONS.map(y=>new bn({originX:y.originX,originY:y.originY},{overlayX:y.overlayX,overlayY:y.overlayY})),this.veltElement=!0,this.componentId="velt-comment-text-portal",this.subscriptions.push(this.authService.getUser$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{user:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getUser$ subscription: ",y)})),this.subscriptions.push(this.commentService.getSidebarVisibility$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{sidebarVisible:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getSidebarVisibility$ subscription: ",y)})),this.subscriptions.push(this.commentService.showFloatingComments$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{floatingCommentsEnabled:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent showFloatingComments$ subscription: ",y)})),this.subscriptions.push(this.commentService.getShowCommentIndex().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{showCommentIndex:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getShowCommentIndex subscription: ",y)})),this.subscriptions.push(this.commentService.getEnableDialogOnHover$().subscribe(y=>{this.isDialogOnHoverEnabled=y},y=>{this.catchError("Error in CommentPinComponent getEnableDialogOnHover subscription: ",y)})),this.subscriptions.push(this.breakpointObserver.observe(fo.XSmall).subscribe(y=>{let S=!1;y.matches?S=!0:S=!1,this.componentConfigSignal.update(j=>(j=b(g({},j),{isPhone:S}),j))},y=>{this.catchError("Error in CommentTextPortalComponent breakpointObserver subscription: ",y)}))}ngOnInit(){try{this.setupA11yAttributes()}catch(e){this.loggingService.catch("Error in CommentTextPortalComponent ngOnInit:",e)}}setupA11yAttributes(){try{this.elementRef.nativeElement.setAttribute("data-testid",this.componentId+"-container")}catch(e){this.loggingService.catch("Error in CommentTextPortalComponent setupA11yAttributes:",e)}}ngAfterViewInit(){try{let e=this.element.childNodes[0];this.element.childNodes[1].childNodes[0].appendChild(e),this.componentConfigSignal.update(a=>{let i=hc(this.element,Z.ATTRIBUTES.VELT_PDF_VIEWER);return a=b(g({},a),{isInsidePdfViewer:i}),a}),this.subscriptions.push(this.overlay?.positionChange?.subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{overlayOriginX:a.connectionPair.originX,overlayOriginY:a.connectionPair.originY}),i))},a=>{this.catchError("Error in CommentTextPortalComponent positionChange subscription: ",a)})),this.subscriptions.push(this.domService.getSelectedAnnotationsMap$().subscribe(a=>{this.selectedAnnotationsMap=a,this.checkPinSelection()},a=>{this.catchError("Error in CommentTextPortalComponent getSelectedAnnotationsMap$ subscription: ",a)})),this.subscriptions.push(this.commentService.getStreamMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{streamMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getStreamMode$ subscription: ",a)})),this.subscriptions.push(this.commentService.getInboxMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{inboxMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getInboxMode subscription: ",a)})),this.subscriptions.push(this.commentService.getMobileMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{mobileMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getMobileMode$ subscription: ",a)})),this.subscriptions.push(this.commentService.getInlineCommentMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{inlineCommentMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getInlineCommentMode$ subscription: ",a)})),this.subscriptions.push(this.serviceBook.observe(_n).pipe(Fe(a=>a?.onInitRecording()??Hr)).subscribe(a=>{this.recorderInitConfig=a},a=>{this.catchError("Error in CommentTextPortalComponent onInitRecording subscription: ",a)}))}catch(e){this.catchError("Error in CommentTextPortalComponent AfterViewInit: ",e)}}setFirst(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{first:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setFirst: ",t)}}setLast(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{last:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setLast: ",t)}}setCommentPinAnnotation(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinAnnotation:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setCommentPinAnnotation: ",t)}}setElement(e){try{this.element=e,this.element?this.customScrollableParents=Ru(this.element):this.customScrollableParents=[],this.addCustomScrollableParentsEventListeners()}catch(t){this.catchError("Error in CommentTextPortalComponent setElement: ",t)}}checkPinSelection(){try{let e=!!this.selectedAnnotationsMap[this.componentConfigSignal().commentPinAnnotation?.annotationId];this.componentConfigSignal.update(t=>{let a=pp(e,t.last);return g(g({},t),a)}),hp(sessionStorage.getItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID),this.componentConfigSignal().commentPinAnnotation.annotationId,this.componentConfigSignal().last)&&(this.componentConfigSignal.update(t=>(t=b(g({},t),{textClicked:!0}),t)),sessionStorage.removeItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID))}catch(e){this.catchError("Error in CommentTextPortalComponent checkPinSelection: ",e)}}onPointerOver(e){try{if(this.componentConfigSignal().commentPinHover)return;e.buttons?this.componentConfigSignal().commentPinHover&&this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinHover:!1}),t)):!this.componentConfigSignal().commentPinHover&&this.isDialogOnHoverEnabled&&this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinHover:!0}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent onPointerOver: ",t)}}onPointerOut(){this.componentConfigSignal.update(e=>(e=b(g({},e),{commentPinHover:!1}),e))}togglePinSelection(e){try{if(this.recorderInitConfig?.isCommentRecording||this.componentConfigSignal().textClicked&&!e)return;let t=e||this.componentConfigSignal().commentPinAnnotation;if(this.selectedAnnotationsMap[t.annotationId])e||(document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}="${t?.annotationId}"]`)?this.domService.resetSelectedAnnotationsMap(!0,"comments"):(this.componentConfigSignal.update(i=>(i=b(g({},i),{textClicked:!0}),i)),this.domService.toggleAnnotationSelection(t)));else{let a=document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);if(a||(a=(this.domService.getDraftCommentAnnotationDialogs()||[])[0]),a){let i=a.getAttribute(Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT);if(i){let d=document.getElementById(`comment-pin-container-${i}`)||document.querySelector(`[data-velt-id='${i}']`);d&&(d.scrollIntoView({behavior:"auto",block:"center",inline:"center"}),this.domService.resetSelectedAnnotationsMap(!0,"comments"))}}else this.domService.resetSelectedAnnotationsMap(!0,"comments"),this.componentConfigSignal.update(i=>(i=b(g({},i),{textClicked:!0}),i)),this.domService.toggleAnnotationSelection(t)}}catch(t){this.catchError("Error in CommentTextPortalComponent togglePinSelection: ",t)}}saveComment(e){try{this.commentService.saveComment(this.componentConfigSignal().commentPinAnnotation,e)}catch(t){this.catchError("Error in CommentTextPortalComponent saveComment: ",t)}}updateOverlayPosition(){try{this.loggingService.log("updateOverlayPosition",this.componentConfigSignal().commentPinAnnotation?.annotationId),this.overlay&&this.overlay?.overlayRef?.updatePosition()}catch(e){this.catchError("Error in CommentTextPortalComponent updateOverlayPosition: ",e)}}addCustomScrollableParentsEventListeners(){try{this.removeCustomScrollableParentsEventListeners(),this.customScrollableParents?.length&&this.customScrollableParents?.forEach(e=>{this.customScrollableParentEventsListenersSubscriptions.push(Gn(e,"scroll").subscribe(t=>{this.updateOverlayPosition()},t=>{this.catchError("Error in CommentTextPortalComponent addCustomScrollableParentsEventListeners scroll subscription: ",t)}))})}catch(e){this.catchError("Error in CommentTextPortalComponent addCustomScrollableParentsEventListeners: ",e)}}removeCustomScrollableParentsEventListeners(){try{this.customScrollableParentEventsListenersSubscriptions.map(e=>{e.unsubscribe()}),this.customScrollableParentEventsListenersSubscriptions=[]}catch(e){this.catchError("Error in CommentTextPortalComponent removeCustomScrollableParentsEventListeners: ",e)}}ngOnDestroy(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.removeCustomScrollableParentsEventListeners(),this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[]}catch(e){this.catchError("Error in CommentTextPortalComponent unsubscribe: ",e)}}catchError(e,t,a){try{this.loggingService.catch(e,t,b(g({},a||{}),{annotationId:this.componentConfigSignal()?.commentPinAnnotation?.annotationId}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(G(pr),G(vt),G(ho),G(Re),G(ae),G(A),G(Sr),G(me))},o.\u0275cmp=T({type:o,selectors:[["snippyly-comment-text-portal"]],viewQuery:function(t,a){if(t&1&&ot(GD,5),t&2){let i;at(i=it())&&(a.overlay=i.first)}},hostVars:1,hostBindings:function(t,a){t&1&&z("keyup.enter",function(d){return a.onEnter(d)},ou),t&2&&x("data-velt-element",a.veltElement)},standalone:!1,decls:1,vars:1,consts:[["trigger","cdkOverlayOrigin"],["overlay","cdkConnectedOverlay"],["commentDialogRef",""],[4,"ngIf"],["cdkOverlayOrigin","","data-velt-comment-disabled","true",1,"comment-text-highlight",3,"pointerover","pointerout","pointerdown","pointerup","touchend","click"],["class","comment-annotation-number",3,"index-3-digit",4,"ngIf"],["cdkConnectedOverlay","",3,"cdkConnectedOverlayOrigin","cdkConnectedOverlayOpen","cdkConnectedOverlayOffsetY","cdkConnectedOverlayPanelClass","cdkConnectedOverlayBackdropClass","cdkConnectedOverlayLockPosition","cdkConnectedOverlayPositions","cdkConnectedOverlayGrowAfterOpen","cdkConnectedOverlayDisableClose"],[3,"annotation","user","isInsidePdfViewer","saveComment",4,"ngIf"],[1,"comment-annotation-number"],[4,"ngIf","ngIfElse"],[3,"saveComment","pointerUp","multiThreadAnnotationId","annotation","user","commentPinSelected"],[3,"saveComment","annotation","user","commentPinSelected","inlineCommentMode","isInsidePdfViewer"],[3,"saveComment","annotation","user","isInsidePdfViewer"]],template:function(t,a){t&1&&s(0,qD,7,18,"ng-container",3),t&2&&c("ngIf",a.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}*[_ngcontent-%COMP%]{box-sizing:border-box;margin:0;padding:0;height:inherit;width:inherit;text-align:inherit;line-height:inherit;font-size:inherit;text-transform:inherit;float:inherit;-webkit-text-fill-color:initial}*[_ngcontent-%COMP%]:empty{display:revert}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-agent-accent: #4495ff;--velt-agent-accent-transparent: rgba(68, 149, 255, .2);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent);font-family:inherit}.comment-text-highlight[_ngcontent-%COMP%]{cursor:pointer} snippyly-text-highlight.snippyly-text-highlight{color:var(--velt-black)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight{color:var(--velt-warning-hover);background-color:var(--velt-warning-transparent);border-bottom:1px solid var(--velt-warning-hover)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.selected{color:var(--velt-black);background-color:var(--velt-warning)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.agent-comment{color:var(--velt-agent-accent);background-color:var(--velt-agent-accent-transparent);border-bottom-color:var(--velt-agent-accent)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.agent-comment.selected{color:var(--velt-agent-accent);background-color:var(--velt-agent-accent-transparent)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.inline-comment-mode{background-color:inherit} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.inline-comment-mode.selected{background-color:inherit}.comment-annotation-number[_ngcontent-%COMP%]{border-radius:50%;border:1px solid var(--velt-gray);width:20px;height:20px;font-size:calc((.7rem + 0px) * var(--velt-base-rem-unit));display:inline-flex;justify-content:center;align-items:center;box-sizing:content-box;background:var(--velt-white);color:var(--velt-black);position:relative}.comment-annotation-number.index-3-digit[_ngcontent-%COMP%]{width:32px;height:32px}.comment-annotation-number[_ngcontent-%COMP%]:after{content:attr(data-comment-annotation-number);position:absolute;font-weight:400;letter-spacing:normal;word-spacing:normal}"],changeDetection:0});let r=o;return r})();var ZD=`[${Z.ATTRIBUTES.VELT_LOCATION}], [${Z.ATTRIBUTES.VELT_LOCATION_ID}]`,Tc=(()=>{let o=class o{constructor(e,t,a,i,d,m,u){this.docService=e,this.domService=t,this.commentService=a,this.componentFactoryResolver=i,this.injector=d,this.appRef=m,this.loggingService=u,this.commentsTextById={},this.lastTextCommentAnnotations=[],this.commonAncestorElementObservers=new Map,this.commonAncestorElementObserverCounts=new Map,this.inlineCommentMode=!1,this.restrictTextSearchToAnchor=!1;try{this.commentService.getInlineCommentMode$().subscribe(f=>{this.inlineCommentMode=f}),this.commentService.getRestrictTextSearchToAnchor$().subscribe(f=>{this.restrictTextSearchToAnchor=f})}catch(f){this.loggingService.catch("Error in CommentPinPortalService constructor: ",f)}}updateTextCommentAnnotations(e,t){try{t&&(this.textCommentAnnotationsOwner=t),this.lastTextCommentAnnotations=e||[],this.checkToRemoveTextCommentAnnotations(e),e.forEach(a=>{this.updateTextCommentAnnotation(a)})}catch(a){this.loggingService.catch("Error in CommentPinPortalService updateTextCommentAnnotations: ",a)}this.watchAreaChanges()}stopWatchingAreaChanges(e){try{if(e&&e!==this.textCommentAnnotationsOwner)return;this.textCommentAnnotationsOwner=void 0,this.areaChangesSubscription?.unsubscribe(),this.areaChangesSubscription=void 0,this.lastTextCommentAnnotations=[]}catch(t){this.loggingService.catch("Error in CommentTextPortalService stopWatchingAreaChanges: ",t)}}watchAreaChanges(){try{if(this.areaChangesSubscription)return;this.areaChangesSubscription=this.docService.getAreaChanges$().pipe(Dn(1)).subscribe(()=>{this.updateTextCommentAnnotations(this.lastTextCommentAnnotations||[])})}catch(e){this.loggingService.catch("Error in CommentTextPortalService watchAreaChanges: ",e)}}refreshTextCommentAnnotations(){try{this.lastTextCommentAnnotations.forEach(e=>{let t=this.commentsTextById[e?.annotationId];t?.texts?.length&&t.texts.every(i=>document.body.contains(i?.textNode))||this.updateTextCommentAnnotation(t?.annotation||e)})}catch(e){this.loggingService.catch("Error in CommentPinPortalService refreshTextCommentAnnotations: ",e)}}updateTextCommentAnnotation(e){let t=this.commentsTextById[e.annotationId];if(t)if(xn(t?.annotation?.targetTextRange,e?.targetTextRange)){let a=!1;if(!t?.texts?.length)a=!0;else{let i=t.areaElement;i&&this.docService.isAnnotationAllowedInArea(e?.metadata,i)===!1&&(a=!0),t.texts.forEach(d=>{(!document.body.contains(d?.textNode)||Dr(d?.element))&&(a=!0),!i&&this.docService.isAnnotationAllowedInArea(e?.metadata,d?.element)===!1&&(a=!0)})}a?(this.removeTextCommentAnnotation(e),this.getCommonAncestorContainer(e)):(t.texts.forEach(i=>{i.portalRef&&i.portalRef.instance.setCommentPinAnnotation(e)}),t.annotation=e)}else this.removeTextCommentAnnotation(e),this.getCommonAncestorContainer(e);else this.getCommonAncestorContainer(e)}setGhostUnlessHiddenByArea(e,t){try{let a=t?.nodeType===Node.ELEMENT_NODE?t:t?.parentElement??null;if(a&&this.docService.isAnnotationAllowedInArea(e?.metadata,a)===!1){this.docService.logHiddenByArea("text comment",e,a),this.removeGhostComment(e);return}this.setGhostComment(e)}catch(a){this.loggingService.catch("Error in CommentTextPortalService setGhostUnlessHiddenByArea: ",a),this.setGhostComment(e)}}getCommonAncestorContainer(e){try{let t=this.resolveTextSearchScope(e);if(t.notOnPage){this.removeGhostComment(e);return}let a=t.anchor;if(a&&this.domService.isElementVisible(a)){let i=a?.nodeType===Node.ELEMENT_NODE?a:a?.parentElement;this.commentsTextById[e.annotationId]={texts:[],annotation:e,commonAncestorContainer:a,commonAncestorElement:i,commonAncestorText:i?.textContent},this.setTextCommentPortal(e),this.observeCommonAncestorElementChanges(e)}else this.setGhostUnlessHiddenByArea(e,a)}catch(t){this.loggingService.catch("Error in CommentPinPortalService getCommonAncestorContainer: ",t)}}setTextCommentPortal(e){try{let t=this.commentsTextById[e.annotationId];if(t){let{anchor:a,fallbackRoot:i,notOnPage:d}=this.resolveTextSearchScope(e);if(d)return;let m=this.resolveHighlightRange(e,a,i);if(m&&Lu(m)){this.loggingService.log("[Velt] text comment shown as ghost: its text now resolves inside a ProseMirror/TipTap editor."),this.setGhostComment(e);return}if(m){let u=m.commonAncestorContainer?.nodeType===Node.ELEMENT_NODE?m.commonAncestorContainer:m.commonAncestorContainer?.parentElement??null;if(this.docService.isAnnotationAllowedInArea(e?.metadata,u)===!1){this.docService.logHiddenByArea("text comment",e,u),this.removeGhostComment(e);return}t.areaElement=u}if(m){let u=m.commonAncestorContainer?.nodeType===Node.ELEMENT_NODE?m.commonAncestorContainer:m.commonAncestorContainer?.parentElement??null;u&&t.commonAncestorElement&&!t.commonAncestorElement.contains(u)&&(t.commonAncestorElement=u,t.commonAncestorContainer=u,t.commonAncestorText=u.textContent);let f=F0(m),y=[],S=f?.find(j=>!j?.textContent);if(S&&S?.remove(),f=f?.filter(j=>j?.textContent),f&&f.length){let j=-1,W=-1;if(f.forEach(($,H)=>{this.textHighlighterClass?this.domService.addClassToElement($,this.textHighlighterClass):this.domService.addClassToElement($,$.tagName?.toLowerCase()),$.setAttribute(Z.ATTRIBUTES.VELT_ID,e.annotationId);let q=$.childNodes[0],ce=new pu(fp),fe=new hu($,this.appRef,this.injector),le=fe.attach(ce);le.instance.setCommentPinAnnotation(e),le.instance.setElement($),le.instance.onKeyupEnter=()=>{this.onCommonAncestorElementChange(e)},j<0&&(j=H),W=H,y.push({host:fe,portal:ce,portalRef:le,element:$,textNode:q})}),j>=0&&y[j]?.portalRef&&y[j].portalRef.instance.setFirst(!0),W>=0&&y[W]?.portalRef&&y[W].portalRef.instance.setLast(!0),t.texts=y,this.inlineCommentMode&&!document.querySelector(`${Z.TAGS.VELT_INLINE_COMMENT}[${Z.ATTRIBUTES.VELT_INLINE_COMMENT_ID}="${e.annotationId}"]`)){let H=t.texts?.filter(ce=>!!ce?.element)?.map(ce=>ce?.element),q=H?.length?H[H.length-1]:null;if(q&&!hc(q,Z.ATTRIBUTES.VELT_PDF_VIEWER)){let fe=q?.parentElement;if(fe){let le=document.createElement(Z.TAGS.VELT_INLINE_COMMENT);le.setAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_ID,e.annotationId),fe.insertAdjacentElement("afterend",le),t.inlineCommentElement=le}}}}this.removeGhostComment(e)}else this.setGhostUnlessHiddenByArea(e,a)}else this.setGhostComment(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService setTextCommentPortal: ",t)}}resolveTextSearchScope(e){try{let t=this.docService.getElementMapWithLocation()||{},a=this.getAnnotationLocationElement(e,t),i=Object.keys(t).length>0;if(!a&&i&&this.isAdditionalLocationAnnotation(e))return{anchor:null,fallbackRoot:null,notOnPage:!0};let d=this.domService.getElementFromTargetTextRange(e?.targetTextRange);return a?d&&(d===a||a.contains(d))?{anchor:d,fallbackRoot:a}:d&&!this.domService.getAdditionalLocationContainer(d)&&!d.querySelector(ZD)?{anchor:d,fallbackRoot:a}:{anchor:a,fallbackRoot:a}:{anchor:d,fallbackRoot:document.body}}catch(t){return this.loggingService.catch("Error in CommentPinPortalService resolveTextSearchScope: ",t),{anchor:null,fallbackRoot:null}}}isAdditionalLocationAnnotation(e){try{if(!e?.locationId&&!e?.location?.id)return!1;let t=this.docService.getLocation();return t?!fc({location:t.location,locationId:t.locationId},{location:e.location,locationId:e.locationId}):!1}catch(t){return this.loggingService.catch("Error in CommentPinPortalService isAdditionalLocationAnnotation: ",t),!1}}getAnnotationLocationElement(e,t){try{let a=e?.locationId,i=e?.location?.id;if(!a&&!i)return null;let d=t??this.docService.getElementMapWithLocation()??{};return(a?d[a]?.element:null)||(i?d[i]?.element:null)||null}catch(a){return this.loggingService.catch("Error in CommentPinPortalService getAnnotationLocationElement: ",a),null}}resolveHighlightRange(e,t,a=document.body){try{let i=e.targetTextRange?.text,d=e.targetTextRange?.occurrence,m=t?this.buildValidRange(Ih(i,t,d),i):null;return!m&&!this.restrictTextSearchToAnchor&&a&&t!==a&&(m=this.buildValidRange(Ih(i,a,d),i)),m}catch(i){return this.loggingService.catch("Error in CommentPinPortalService resolveHighlightRange: ",i),null}}buildValidRange(e,t){try{if(!e?.length||e.some(d=>d?.textNode?.parentElement?.closest("script")))return null;let i=new Range;try{i.setStart(e[0].textNode,e[0].startOffset||0),i.setEnd(e[e.length-1].textNode,e[e.length-1].endOffset||0)}catch{return null}return i.toString()===t?i:null}catch(a){return this.loggingService.catch("Error in CommentPinPortalService buildValidRange: ",a),null}}checkToRemoveTextCommentAnnotations(e){try{let t=new Set(e.map(i=>i.annotationId)),a=!1;if(Object.keys(this.commentsTextById).forEach(i=>{t.has(i)||(this.commentsTextById[i]?.annotation?.targetTextRange&&(a=!0),this.removeTextCommentAnnotation(this.commentsTextById[i].annotation))}),a){let i=[];Object.keys(this.commentsTextById).forEach(d=>{this.commentsTextById[d]?.annotation?.targetTextRange&&(i.push(this.commentsTextById[d]?.annotation),this.removeTextCommentAnnotation(this.commentsTextById[d]?.annotation))}),i?.length&&i.forEach(d=>{this.updateTextCommentAnnotation(d)})}}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkToRemoveTextCommentAnnotations: ",t)}}removeTextCommentAnnotation(e){try{let t=this.commentsTextById[e.annotationId],a=new Set;if(t.texts.forEach(i=>{i?.host&&i.host.detach();let d=i?.element?.parentNode??i?.textNode?.parentNode;i?.element&&i?.textNode&&Ph(i.element,i.textNode),i.textNode&&d&&a.add(d)}),t.texts?.length){let i=document.querySelectorAll(`${Z.TAGS.SNIPPYLY_TEXT_HIGHLIGHT}[data-velt-id="${e?.annotationId}"]`);i?.length&&i.forEach(d=>{let m=d?.parentNode;d?.textContent&&Ph(d),m&&a.add(m)})}a.forEach(i=>_C(i)),t?.inlineCommentElement&&t?.inlineCommentElement?.remove(),this.checkToUnsubscribeCommonAncestorElementChanges(e),delete this.commentsTextById[e.annotationId]}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeTextCommentAnnotation: ",t)}}observeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];if(Dr(t?.commonAncestorElement))return;if(t.commonAncestorElement){let a=this.commonAncestorElementObservers.get(t.commonAncestorElement);if(a)a.annotations.find(i=>i.annotationId===e.annotationId)||a.annotations.push(e);else{let i=new MutationObserver(d=>{let m="";if(IC(t?.commonAncestorElement).forEach(f=>{f?.parentElement?.closest(".comment-annotation-number")||(m+=f.textContent)}),t?.commonAncestorText!==m&&d.filter(f=>[Node.ELEMENT_NODE,Node.TEXT_NODE].includes(f.target.nodeType)).filter(f=>f.target?.parentElement&&(f?.target?.parentElement?.classList?.contains("comment-text-highlight")||!Mm(f.target?.parentElement))).length){this.commonAncestorElementObservers.get(t.commonAncestorElement)?.annotations?.forEach(W=>{this.onCommonAncestorElementChange(W)});let{count:y,lastUpdated:S}=this.commonAncestorElementObserverCounts.get(t.commonAncestorElement)||{count:0,lastUpdated:0},j=Date.now();this.commonAncestorElementObserverCounts.set(t.commonAncestorElement,{count:j-S<100?y+1:1,lastUpdated:Date.now()}),y>5&&(i.disconnect(),this.loggingService.catch("Failed to detect text changes."))}});i.observe(t.commonAncestorElement,{characterData:!0,subtree:!0}),a={observer:i,annotations:[e]}}this.commonAncestorElementObservers.set(t.commonAncestorElement,a)}}catch(t){this.loggingService.catch("Error in CommentPinPortalService observeCommonAncestorElementChanges: ",t)}}onCommonAncestorElementChange(e){try{let t=this.commentsTextById[e.annotationId];if(t?.texts?.some(a=>Dr(a?.element)))return;if(t.texts?.length){let a="";t.texts.forEach(y=>a+=y.textNode?.textContent);let i=t.texts[0].textNode,d=[];document.querySelectorAll(`${Z.TAGS.SNIPPYLY_TEXT_HIGHLIGHT}[data-velt-id="${e?.annotationId}"]`)?.forEach(y=>{d.push(y)});let m=!1;if(d?.length!==t?.texts?.length&&(m=!0),d?.length){let y="";d.forEach(S=>{y+=S?.textContent||""}),y&&(a=y,m&&this.removeTextCommentAnnotation(e))}let u=CC(t.commonAncestorContainer,0,i,0,a)+1,f={};f.commonAncestorContainer=e.targetTextRange?.commonAncestorContainer,f.text=a,f.occurrence=u,xn(e.targetTextRange,f)||(t.annotation.targetTextRange=f,this.updateAnnotationToFirebase(t.annotation))}else this.setTextCommentPortal(t.annotation)}catch(t){this.loggingService.catch("Error in CommentPinPortalService onCommonAncestorElementChange: ",t)}}updateAnnotationToFirebase(e){try{this.commentService.updateComment(e,!1,!0)}catch(t){this.loggingService.catch("Error in CommentPinPortalService updateAnnotationToFirebase: ",t)}}checkToUnsubscribeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];if(t.commonAncestorElement){let a=this.commonAncestorElementObservers.get(t.commonAncestorElement);a&&(a.annotations=a?.annotations.filter(i=>i.annotationId!==e.annotationId),a.annotations.length||this.unsubscribeCommonAncestorElementChanges(e))}}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkToUnsubscribeCommonAncestorElementChanges: ",t)}}setGhostComment(e){try{e.ghostComment={},this.commentService.setGhostCommentMessage(e),this.commentService.addAnnotationToGhostCommentAnnotationMap(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService setGhostComment: ",t)}}removeGhostComment(e){try{delete e.ghostComment,this.commentService.removeAnnotationFromGhostCommentAnnotationMap(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeGhostComment: ",t)}}onAcceptComment(e){try{let t=this.commentsTextById[e.annotationId];if(t?.texts?.length){let a=t.texts.length-1,i=t.texts[a].textNode;if(i&&i.parentNode){let d=e.comments?.length?e.comments[0]:null,m=Vu(d?.replaceContentHtml)?null:d?.replaceContentHtml,u=d?.replaceContentText||d?.commentText||"";if(Vu(m)&&!d?.replaceContentText&&(m=d?.commentHtml||""),e?.selectAllContent&&e?.targetElementId){let f=Lr(e.targetElementId,["id","data-id"]);if(f&&(Dr(f)||xC(f))){this.loggingService.log("[Velt] accept skipped: the target element contains a ProseMirror/TipTap editor.");return}else f&&(f.innerHTML=this.domService.sanitizeHtml(Vu(m)?u||"":m||""))}else{if(m&&m!==u){let f=document.createElement("span");f.innerHTML=this.domService.sanitizeHtml(m||u||""),i.parentNode.replaceChild(f,i),t.texts[a].textNode=f}else t.texts[a].textNode.textContent=u||"";for(let f=0;f<a;f++){let y=t.texts[f].textNode;y&&(y.textContent="")}}this.removeTextCommentAnnotation(e),this.domService.resetSelectedAnnotationsMap()}}}catch(t){this.loggingService.catch("Error in CommentPinPortalService onAcceptComment: ",t)}}unsubscribeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];this.commonAncestorElementObservers.get(t.commonAncestorElement)?.observer?.disconnect(),this.commonAncestorElementObservers.delete(t.commonAncestorElement)}catch(t){this.loggingService.catch("Error in CommentPinPortalService unsubscribeCommonAncestorElementChanges: ",t)}}};o.\u0275fac=function(t){return new(t||o)(be(ut),be(Re),be(ae),be(lu),be(nu),be(du),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function QD(r,o){if(r&1){let n=Y();C(0,"div",4),z("pointerup",function(t){return B(n),l(2).togglePinSelection(void 0,t),V(t.stopPropagation())})("click",function(t){return B(n),V(t.stopPropagation())})("cdkDragStarted",function(){B(n);let t=l(2);return V(t.onPinDragStart())}),C(1,"snippyly-comment-pin",5),z("saveComment",function(t){B(n);let a=l(2);return V(a.saveComment(t))})("commentTargetElementClicked",function(){B(n);let t=l(2);return V(t.togglePinSelection())})("togglePinSelection",function(t){B(n);let a=l(2);return V(a.togglePinSelection(t))}),_()()}if(r&2){let n=l().ngIf,e=l();mt("top",(n.commentPinAnnotation==null||n.commentPinAnnotation.position==null?null:n.commentPinAnnotation.position.top)-0+n.offsetTop,"px")("left",(n.commentPinAnnotation==null||n.commentPinAnnotation.position==null?null:n.commentPinAnnotation.position.left)-10+n.offsetLeft,"px"),c("id","comment-pin-container-"+(n.commentPinAnnotation==null?null:n.commentPinAnnotation.annotationId)),x("data-testid",e.componentId+"-popover")("role","button")("aria-expanded",n.commentPinSelected),v(),c("annotation",n.commentPinAnnotation)("containerComponentId",n.componentId)("commentPinSelected",n.commentPinSelected&&!n.annotationDragging)("multipleCommentPinSelected",n.commentPinSelected&&e.objectKeys(n.selectedAnnotationsMap).length>1)("targetElement",n.targetElement)("user",n.user)}}function XD(r,o){if(r&1){let n=Y();C(0,"div",7),z("pointerup",function(t){return B(n),l(3).togglePinSelection(void 0,t),V(t.stopPropagation())})("touchend",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())})("mousedown",function(t){return B(n),V(t.stopPropagation())})("touchstart",function(t){return B(n),V(t.stopPropagation())})("pointerdown",function(t){return B(n),V(t.stopPropagation())})("click",function(t){return B(n),V(t.stopPropagation())})("cdkDragStarted",function(){B(n);let t=l(3);return V(t.onPinDragStart())})("cdkDragMoved",function(t){B(n);let a=l(3);return V(a.onPinMove(t))})("cdkDragReleased",function(){B(n);let t=l(3);return V(t.onPinRelease())}),C(1,"snippyly-comment-pin",8,1),z("togglePinSelection",function(t){B(n);let a=l(3);return V(a.togglePinSelection(t))})("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))}),_()()}if(r&2){let n=we(2),e=l(2).ngIf,t=l();mt("top",e.annotationDragging?(e.dragPosition==null?null:e.dragPosition.top)-((n==null?null:n.COMMENT_PIN_SIZE)||40):(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.top)-((n==null?null:n.COMMENT_PIN_SIZE)||40)+e.offsetTop,"px")("left",e.annotationDragging?e.dragPosition==null?null:e.dragPosition.left:(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.left)+e.offsetLeft,"px")("--velt-comment-pin-transform",e.annotationDragging?"none":e.pinTransform??"none")("transform",!e.annotationDragging&&(!(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null)&&e.commentPinAnnotation.position.parentScaleX)?"scale("+1/((e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.parentScaleX)||1)+", "+1/((e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.parentScaleY)||1)+")":""),pe("pin-dragging",e.annotationDragging),c("id","comment-pin-container-"+(e.commentPinAnnotation==null?null:e.commentPinAnnotation.annotationId))("cdkDragDisabled",!e.pinDragEnabled||(e.commentPinAnnotation==null||e.commentPinAnnotation.from==null?null:e.commentPinAnnotation.from.userId)!==(e.user==null?null:e.user.userId)),x("data-testid",t.componentId+"-default")("role","button")("aria-expanded",e.commentPinSelected)("aria-grabbed",e.annotationDragging)("data-transform-inside",e.transformContext?"true":"false"),v(),c("annotation",e.commentPinAnnotation)("annotationDragging",e.annotationDragging)("containerComponentId",e.componentId)("commentPinSelected",e.commentPinSelected&&!e.annotationDragging)("multipleCommentPinSelected",e.commentPinSelected&&t.objectKeys(e.selectedAnnotationsMap).length>1)("targetElement",e.targetElement)("user",e.user)}}function e3(r,o){if(r&1&&s(0,XD,3,24,"div",6),r&2){let n=l().ngIf;c("ngIf",n.commentPinAnnotation==null?null:n.commentPinAnnotation.position)}}function t3(r,o){if(r&1&&(p(0),s(1,QD,2,14,"div",3)(2,e3,1,1,"ng-template",null,0,$e),h()),r&2){let n=o.ngIf,e=we(3);v(),c("ngIf",n.popoverMode)("ngIfElse",e)}}var bp=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f){this.analyticsService=e,this.authService=t,this.docService=a,this.domService=i,this.commentService=d,this.commentActionsService=m,this.loggingService=u,this.elementRef=f,this.multipleCommentPinsSelected=!1,this.avatarErrorImage="",this.objectKeys=Object.keys,this.selectedAnnotationsLocationMap={},this.subscriptions=[],this.componentConfigSignal=Ae({popoverMode:!1,commentPinAnnotation:void 0,commentPinSelected:!1,offsetLeft:0,offsetTop:0,selectedAnnotationsMap:{},annotationDragging:!1,dragPosition:null,targetElement:void 0,user:void 0,componentId:`comment-pin-portal-${Jt()}`,pinDragEnabled:!0}),this.veltElement=!0,this.componentId="velt-comment-pin-portal",this.subscriptions.push(this.authService.getUser$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{user:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getUser$ subscription: ",y)})),this.subscriptions.push(this.domService.getSelectedAnnotationsMap$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{selectedAnnotationsMap:y}),S)),this.checkCommentPinSelected()},y=>{this.catchError("Error in CommentPinPortalComponent getSelectedAnnotationsMap$ subscription: ",y)})),this.subscriptions.push(this.domService.getSelectedAnnotationsLocationMap$().subscribe(y=>{this.selectedAnnotationsLocationMap=y||{},this.checkCommentPinSelected()},y=>{this.catchError("Error in CommentPinPortalComponent getSelectedAnnotationsLocationMap$ subscription: ",y)})),this.subscriptions.push(this.commentService.getPinDrag$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{pinDragEnabled:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getPinDrag$ subscription: ",y)})),this.subscriptions.push(this.commentService.getPopoverMode$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{popoverMode:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getPopoverMode subscription: ",y)}))}ngOnInit(){try{this.setupA11yAttributes(),this.subscriptions.push(this.commentService.getTransformContext$().subscribe(e=>{this.componentConfigSignal.update(t=>{if(t=b(g({},t),{transformContext:e}),e&&this.isElementInsideTransformContainer(this.elementRef?.nativeElement,e.containerSelector)){let a=e.transforms.scale?1/e.transforms.scale:1;t.pinTransform=`scale(${a})`}else t.pinTransform=void 0;return t})}))}catch(e){this.loggingService.catch("Error in CommentPinPortalComponent ngOnInit:",e)}}isElementInsideTransformContainer(e,t){try{return document.querySelector(t)?.contains(e)??!1}catch(a){return this.loggingService.catch("Error in CommentPinPortalComponent isElementInsideTransformContainer:",a),!1}}setupA11yAttributes(){try{this.elementRef.nativeElement.setAttribute("data-testid",this.componentId+"-container")}catch(e){this.loggingService.catch("Error in CommentPinPortalComponent setupA11yAttributes:",e)}}setCommentPinAnnotation(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinAnnotation:e}),t)),this.id=this.componentConfigSignal().commentPinAnnotation?.annotationId,this.checkCommentPinSelected()}catch(t){this.catchError("Error in CommentPinPortalComponent setCommentPinAnnotation: ",t)}}setSourceId(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{sourceId:e}),t)),this.checkCommentPinSelected()}catch(t){this.catchError("Error in CommentPinPortalComponent setSourceId: ",t)}}getMultiThreadCommentAnnotations(){}checkCommentPinSelected(){try{let e=this.componentConfigSignal().selectedAnnotationsMap,t=this.componentConfigSignal().commentPinAnnotation,a=this.componentConfigSignal().sourceId;if(t){let i=!!e[t.annotationId];if(i)if(t?.isDraft)t?.sourceId&&(i=t?.sourceId===a,i&&this.domService.setSelectedAnnotationLocation(t.annotationId,this.componentConfigSignal().componentId));else{let d=this.selectedAnnotationsLocationMap?.[t.annotationId];d&&(i=d===this.componentConfigSignal().componentId)}i!==this.componentConfigSignal().commentPinSelected&&this.componentConfigSignal.update(d=>(d=b(g({},d),{commentPinSelected:i}),d))}}catch(e){this.catchError("Error in CommentPinPortalComponent checkCommentPinSelected: ",e)}}setTargetElement(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{targetElement:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setTargetElement: ",t)}}setOffsetLeft(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{offsetLeft:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setOffsetLeft: ",t)}}setOffsetTop(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{offsetTop:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setOffsetTop: ",t)}}togglePinSelection(e,t){try{if(Zo(t))return;let a=e||this.componentConfigSignal().commentPinAnnotation;if(a&&this.commentActionsService.onCommentPinClick(a).catch(d=>{this.catchError("Error in CommentPinPortalComponent togglePinSelection onCommentPinClick: ",d)}),this.componentConfigSignal().selectedAnnotationsMap[a?.annotationId]&&this.selectedAnnotationsLocationMap?.[a?.annotationId]===this.componentConfigSignal().componentId)a?.ghostComment?.type!==an.DIFFERENT_DEVICE&&document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}="${a?.annotationId}"]`)&&this.domService.resetSelectedAnnotationsMap(!0,"comments");else{let d=document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);if(d||(d=(this.domService.getDraftCommentAnnotationDialogs()||[])[0]),d){let m=d.getAttribute(Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT);if(m){let u=document.getElementById(`comment-pin-container-${m}`)||document.querySelector(`[data-velt-id='${m}']`);u&&(u.scrollIntoView({behavior:"auto",block:"center",inline:"center"}),this.domService.resetSelectedAnnotationsMap(!0,"comments"))}}else this.domService.resetSelectedAnnotationsMap(!0,"comments"),this.componentConfigSignal().targetElement&&this.domService.isElementVisibleOnScreen(this.componentConfigSignal().targetElement)&&(this.componentConfigSignal().annotationDragging||this.domService.toggleAnnotationSelection(a,this.componentConfigSignal().componentId,void 0,!0))}}catch(a){this.catchError("Error in CommentPinPortalComponent togglePinSelection: ",a)}}onPinDragStart(){try{this.componentConfigSignal().selectedAnnotationsMap[this.componentConfigSignal().commentPinAnnotation.annotationId]&&this.componentConfigSignal().commentPinAnnotation?.ghostComment?.type!==an.DIFFERENT_DEVICE&&this.domService.toggleAnnotationSelection(this.componentConfigSignal().commentPinAnnotation,this.componentConfigSignal().componentId);let e=document.getElementById(this.componentConfigSignal().commentPinAnnotation.annotationId);if(!e)return;this.parentElement=e.parentElement;let t=this.componentConfigSignal().commentPinAnnotation.position,a=this.componentConfigSignal().transformContext,i=this.parentElement.getBoundingClientRect(),d=i.left+t.left,m=i.top+t.top,u=a&&this.isElementInsideTransformContainer(e,a.containerSelector);this.componentConfigSignal.update(f=>(f=b(g({},f),{elementInTransformedContainer:u}),f)),e.style.width="20px",e.style.height="20px",e.style.margin="0",e.style.padding="0",e.style.display="block",e.style.visibility="visible",e.style.opacity="1",e.style.backgroundColor="var(--velt-comment-pin-background-color, #2d62ff)",e.style.borderRadius="50%",e.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.2)",e.style.pointerEvents="auto",e.offsetWidth,document.body.appendChild(e),e.style.position="fixed",e.style.top=`${m}px`,e.style.left=`${d}px`,e.style.zIndex="10000",e.style.transform="none",e.offsetWidth,document.body.classList.add(Z.BODY_CLASSES.VELT_PIN_DRAGGING),this.componentConfigSignal.update(f=>(f=b(g({},f),{annotationDragging:!0}),f))}catch(e){this.catchError("Error in CommentPinPortalComponent onPinDragStart: ",e)}}onPinMove(e){try{this.updateCurrentPinPosition(e)}catch(t){this.catchError("Error in CommentPinPortalComponent onPinMove: ",t)}}updateCurrentPinPosition(e){try{this.domService.removeHighlightFromElement(this.componentConfigSignal().targetElement);let t=e.event,a=t?.touches?.length?t.touches[0]?.clientX:t.clientX,i=t?.touches?.length?t.touches[0]?.clientY:t.clientY,d=this.componentConfigSignal().transformContext,m=this.domService.getBackgroundElement(a,i);m&&this.commentService.isElementInsideAllowedElements(m)&&!Dr(m)&&(this.componentConfigSignal.update(u=>(u=b(g({},u),{targetElement:m}),u)),this.domService.highlightElement(this.componentConfigSignal().targetElement),this.pointerMoveEvent=e.event,this.componentConfigSignal.update(u=>(u=b(g({},u),{dragPosition:{top:i,left:a}}),u)))}catch(t){this.catchError("Error in CommentPinPortalComponent updateCurrentPinPosition: ",t)}}onPinRelease(){try{document.body.classList.remove(Z.BODY_CLASSES.VELT_PIN_DRAGGING);let e=document.getElementById(this.componentConfigSignal().commentPinAnnotation.annotationId);if(!e||!this.parentElement)return;this.domService.removeHighlightFromElement(this.componentConfigSignal().targetElement);let t=this.domService.getElementFromXPath(this.componentConfigSignal().commentPinAnnotation.targetElement?.xpath),a=this.componentConfigSignal().commentPinAnnotation?.targetElement;if(this.pointerMoveEvent){let q=this.domService.getTargetElementForCursorPosition(this.pointerMoveEvent,!0,!0,!0,ce=>{if(this.commentService.getSvgAsImg()){let fe=ce?.closest(`[${Z.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);fe&&fe instanceof HTMLElement&&(ce=fe)}if(Dr(ce)){let fe=this.componentConfigSignal().targetElement;return fe&&!Dr(fe)?fe:null}return ce},!0,void 0,this.commentService.getPinXPathOptions?.({annotation:this.componentConfigSignal().commentPinAnnotation}));q&&(a=q)}let i=this.domService.getElementFromXPath(a?.xpath),d=this.componentConfigSignal().commentPinAnnotation.targetElement?.xpath,m=a?.xpath,u=d===m;if(!i)return;let f=this.componentConfigSignal().dragPosition,y=i.getBoundingClientRect(),S=50,j=50;if(f){let q=f.left-y.left,ce=f.top-y.top;S=q/y.width*100,j=ce/y.height*100,S=Math.max(0,Math.min(100,S)),j=Math.max(0,Math.min(100,j))}let W=g({},this.componentConfigSignal().commentPinAnnotation);W.targetElement=g({},a),W.targetElement.leftPercentage=S,W.targetElement.topPercentage=j,this.commentService.calculateCommentAnnotationPosition(W),this.componentConfigSignal.update(q=>(q=b(g({},q),{commentPinAnnotation:W,targetElement:i}),q));let $=this.domService.isElementInsideAdditionalLocationContainer(t)||this.domService.isElementInsideAdditionalLocationContainer(i),H=this.docService.getAdditionalDocumentIdFromElement(i)||this.docService.getDocumentPaths()?.clientDocumentId;if(!this.componentConfigSignal().commentPinAnnotation?.metadata?.clientDocumentId||this.componentConfigSignal().commentPinAnnotation?.metadata?.clientDocumentId==H?(this.componentConfigSignal.update(q=>(q=b(g({},q),{commentPinAnnotation:b(g({},q.commentPinAnnotation),{targetElement:a})}),q)),this.commentService.updateComment(this.componentConfigSignal().commentPinAnnotation,$)):this.componentConfigSignal.update(q=>(q=b(g({},q),{targetElement:t}),q)),u){let q=this.componentConfigSignal().transformContext,ce=this.componentConfigSignal().elementInTransformedContainer,fe=q&&this.isElementInsideTransformContainer(i,q.containerSelector);this.componentConfigSignal.update(he=>(he=b(g({},he),{elementInTransformedContainer:fe}),he));let le=e.getBoundingClientRect();if(!ce&&fe){e.style.transition="none";let he=le.top,xe=le.left;this.parentElement.appendChild(e),e.style.position="fixed",e.style.top=`${he}px`,e.style.left=`${xe}px`,e.offsetWidth,requestAnimationFrame(()=>{e.style.position="absolute",fe&&W.position.transformContext?(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`,W.position.transformContext.scale!==1&&(e.style.transform=`scale(${1/W.position.transformContext.scale})`)):(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`)})}else e.style.transition="none",this.parentElement.appendChild(e),e.style.position="absolute",e.style.width="20px",e.style.height="20px",e.style.backgroundColor="var(--velt-comment-pin-background-color, #2d62ff)",e.style.borderRadius="50%",e.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.2)",e.style.visibility="visible",e.style.display="block",e.offsetWidth,fe&&W.position.transformContext?(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`):(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`);e.offsetWidth,this.componentConfigSignal.update(he=>(he=b(g({},he),{annotationDragging:!1,dragPosition:null}),he))}this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PIN_DRAGGED,{annotationId:this.componentConfigSignal().commentPinAnnotation.annotationId,commentMode:this.commentService.getCommentMode()})}catch(e){this.catchError("Error in CommentPinPortalComponent onPinRelease: ",e)}}saveComment(e){try{this.commentService.saveComment(this.componentConfigSignal().commentPinAnnotation,e)}catch(t){this.catchError("Error in CommentPinPortalComponent saveComment: ",t)}}ngOnDestroy(){this.loggingService.log("%c[WB] Calling FUNCTION: ngOnDestroy","color: green;");try{this.unsubscribe(),this.componentConfigSignal()?.annotationDragging&&document.body.classList.remove(Z.BODY_CLASSES.VELT_PIN_DRAGGING)}catch(e){this.catchError("Error in CommentPinPortalComponent ondestroy: ",e)}}unsubscribe(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[]}catch(e){this.catchError("Error in CommentPinPortalComponent unsubscribe: ",e)}}catchError(e,t,a){try{this.loggingService.catch(e,t,b(g({},a||{}),{annotationId:this.componentConfigSignal()?.commentPinAnnotation?.annotationId}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(G(pr),G(vt),G(ut),G(Re),G(ae),G(lt),G(A),G(me))},o.\u0275cmp=T({type:o,selectors:[["snippyly-comment-pin-portal"]],hostVars:2,hostBindings:function(t,a){t&2&&(wb("id",a.id),x("data-velt-element",a.veltElement))},inputs:{multipleCommentPinsSelected:"multipleCommentPinsSelected",avatarErrorImage:"avatarErrorImage"},standalone:!1,decls:1,vars:1,consts:[["defaultPinPortalRef",""],["commentPinRef",""],[4,"ngIf"],["class","comment-pin-portal",3,"id","top","left","pointerup","click","cdkDragStarted",4,"ngIf","ngIfElse"],[1,"comment-pin-portal",3,"pointerup","click","cdkDragStarted","id"],[3,"saveComment","commentTargetElementClicked","togglePinSelection","annotation","containerComponentId","commentPinSelected","multipleCommentPinSelected","targetElement","user"],["class","comment-pin-portal","cdkDrag","","cdkDragHandle","",3,"id","pin-dragging","top","left","--velt-comment-pin-transform","transform","cdkDragDisabled","pointerup","touchend","mousedown","touchstart","pointerdown","click","cdkDragStarted","cdkDragMoved","cdkDragReleased",4,"ngIf"],["cdkDrag","","cdkDragHandle","",1,"comment-pin-portal",3,"pointerup","touchend","mousedown","touchstart","pointerdown","click","cdkDragStarted","cdkDragMoved","cdkDragReleased","id","cdkDragDisabled"],[3,"togglePinSelection","saveComment","annotation","annotationDragging","containerComponentId","commentPinSelected","multipleCommentPinSelected","targetElement","user"]],template:function(t,a){t&1&&s(0,t3,4,2,"ng-container",2),t&2&&c("ngIf",a.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{position:absolute!important;top:0!important;left:0!important;box-sizing:border-box!important;-webkit-tap-highlight-color:rgba(255,255,255,0)!important;outline:none!important;margin:0!important;padding:0!important;height:unset!important;width:unset!important;text-align:left!important;z-index:var(--velt-comment-pin-z-index)!important}*[_ngcontent-%COMP%]{box-sizing:border-box;-webkit-tap-highlight-color:rgba(255,255,255,0)!important;outline:none!important;margin:0!important;padding:0!important;height:unset;width:unset;text-align:left!important;line-height:1.5!important;color:#000!important;font-size:calc((1rem + 0px) * var(--velt-base-rem-unit));-webkit-text-fill-color:initial!important}*[_ngcontent-%COMP%]:empty{display:revert!important}.comment-pin-portal[_ngcontent-%COMP%]{position:absolute;transform:var(--velt-comment-pin-transform, none)!important;transform-origin:0 100%!important;transform-box:fill-box!important;top:0;left:0}.comment-pin-portal.pin-dragging[_ngcontent-%COMP%]{position:fixed;z-index:var(--velt-comment-pin-z-index)!important}"],changeDetection:0});let r=o;return r})();var To=(()=>{let o=class o{constructor(e,t,a,i,d,m){this.commentService=e,this.domService=t,this.componentFactoryResolver=a,this.injector=i,this.appRef=d,this.loggingService=m,this.commentsPinById={},this.commentPinTemplate$=new De(null),this.reattachTimes=new Map,this.reattachStopped=new Set,this.customPinEvents$=new Lt}setCommentPin(e){try{if(!this.commentsPinById[e.annotationId])this.setPinPortal(e);else{let t=!1;if(e?.ghostComment?t=e?.ghostComment?.targetElement?.xpath!==this.commentsPinById[e.annotationId]?.[0]?.annotation?.ghostComment?.targetElement?.xpath:this.commentsPinById[e.annotationId]?.[0]?.annotation?.ghostComment?t=!0:t=e.targetElement?.xpath!==this.commentsPinById[e.annotationId]?.[0]?.annotation?.targetElement?.xpath,!t&&this.isPinTargetChangedByIdScopedAnchoring(e)&&(t=!0),!t)this.commentsPinById[e.annotationId]?.forEach(a=>{let i=a.portalRef,d=a.userTargetElement,m=a.pinHostElement;if(document.body.contains(d)&&document.body.contains(m))i&&(i.instance.setCommentPinAnnotation(e),this.updateElementOffset(e));else{let u=a.pinHostDomPortalOutlet;u&&(this.removeCommentPinHostAttributes(e.annotationId,a.pinHostElement),this.removeCommentDisabledAttribute(m),u.detach(),delete this.commentsPinById[e.annotationId],e.ghostComment&&this.unselectCommentAnnotation(e),this.setPinPortal(e))}});else{let a=this.commentsPinById[e.annotationId]??[];a.some(i=>i.pinHostDomPortalOutlet)&&(a.forEach(i=>{this.removeCommentPinHostAttributes(e.annotationId,i.pinHostElement),this.removeCommentDisabledAttribute(i.pinHostElement),i.pinHostDomPortalOutlet?.detach()}),delete this.commentsPinById[e.annotationId],e.ghostComment&&this.unselectCommentAnnotation(e),this.setPinPortal(e))}}}catch(t){this.loggingService.catch("Error in CommentPinPortalService setCommentPin: ",t)}}reattachDetachedPins(e){try{e?.forEach(t=>{let a=t?.annotationId,i=this.commentsPinById[a];!i?.some(m=>!document.body.contains(m.userTargetElement)||!document.body.contains(m.pinHostElement)||!m.pinHostElement.contains(m.portalRef?.location?.nativeElement))||this.reattachStopped.has(a)||i.some(m=>Dr(m.pinHostElement)||Dr(m.userTargetElement))||this.allowReattach(a)&&(i.forEach(m=>{this.removeCommentPinHostAttributes(a,m.pinHostElement),this.removeCommentDisabledAttribute(m.pinHostElement),m.pinHostDomPortalOutlet?.detach()}),delete this.commentsPinById[a],t.ghostComment&&this.unselectCommentAnnotation(t),this.setPinPortal(t))})}catch(t){this.loggingService.catch("Error in CommentPinPortalService reattachDetachedPins: ",t)}}allowReattach(e){try{let t=Date.now(),a=(this.reattachTimes.get(e)||[]).filter(i=>t-i<o.REATTACH_WINDOW_MS);return a.length>=o.REATTACH_LIMIT?(this.reattachStopped.add(e),this.reattachTimes.delete(e),this.loggingService.log(`[Velt] Comment pin ${e}: its element keeps removing the pin; not re-attaching it again.`),!1):(a.push(t),this.reattachTimes.set(e,a),!0)}catch(t){return this.loggingService.catch("Error in CommentPinPortalService allowReattach: ",t),!1}}unselectCommentAnnotation(e){try{this.loggingService.log("%c[WB] Calling CommentPinPortalService FUNCTION: unselectCommentAnnotation","color: green;"),this.domService.getSelectedAnnotationsMap()?.[e?.annotationId]&&this.domService.toggleAnnotationSelection(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService unselectCommentAnnotation: ",t)}}isPinTargetChangedByIdScopedAnchoring(e){let t=this.commentsPinById[e.annotationId],a=this.commentService.getIdScopedAnchoringVersion?.()??0;if(!t?.length||t.every(m=>(m.idScopedAnchoringVersion??0)===a))return!1;let i=this.commentService.getElementFromComments(e)??[],d=i.length!==t.length||i.some((m,u)=>m!==t[u].userTargetElement);return d||t.forEach(m=>{m.idScopedAnchoringVersion=a}),d}setPinPortal(e){try{let t=this.commentService.getElementFromComments(e);t.length>0&&(this.commentsPinById[e.annotationId]=[],t.forEach(a=>{if(a){let i=this.domService.getHostElement(a),d=new pu(bp),m=new hu(i,this.appRef,this.injector),u=m.attach(d);u.instance.setCommentPinAnnotation(e),u.instance.setTargetElement(a);let f=a?.getAttribute(Z.ATTRIBUTES.VELT_SOURCE_ID);f&&u.instance.setSourceId(f),this.commentsPinById[e.annotationId].push({pinHostDomPortalOutlet:m,pinPortal:d,portalRef:u,annotation:JSON.parse(JSON.stringify(e)),userTargetElement:a,pinHostElement:i,idScopedAnchoringVersion:this.commentService.getIdScopedAnchoringVersion?.()??0}),this.setCommentPinHostAttributes(e.annotationId,i),this.setCommentDisabledAttribute(i),this.updateElementOffset(e)}}))}catch(t){this.loggingService.catch("Error in CommentPinPortalService setPinPortal: ",t)}}setCommentPinHostAttributes(e,t){try{let a=t.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST);if(a){let i=a.split(",");i.includes(e)||(i.push(e),t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,i.join(",")))}else t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,e);this.domService.isElementOriginallyStatic(t)&&t.offsetHeight>0&&(OC(t)||t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC,"true"))}catch(a){this.loggingService.catch("Error in CommentPinPortalService setCommentPinHostAttributes: ",a)}}removeCommentPinHostAttributes(e,t){try{let a=t.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST);if(a){let i=a.split(","),d=i.indexOf(e);d>-1&&(i.splice(d,1),i.length>0?t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,i.join(",")):t.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST))}t?.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST)||t.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)}catch(a){this.loggingService.catch("Error in CommentPinPortalService removeCommentPinHostAttributes: ",a)}}setCommentDisabledAttribute(e){try{this.commentService.getPopoverMode()&&e.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED,"auto")}catch(t){this.loggingService.catch("Error in CommentPinPortalService setCommentDisabledAttribute: ",t)}}removeCommentDisabledAttribute(e){try{e?.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED)==="auto"&&e.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED)}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeCommentDisabledAttribute: ",t)}}updateElementOffset(e){try{for(let t of this.commentsPinById[e.annotationId]){let{portalRef:a,userTargetElement:i,pinHostElement:d}=t,m=this.domService.getElementOffset(i,d);a.instance.setOffsetLeft(m.offsetLeft),a.instance.setOffsetTop(m.offsetTop)}}catch(t){this.loggingService.catch("Error in CommentPinPortalService updateElementOffset: ",t)}}checkPinsToRemove(e){try{let t=new Set(e.map(a=>a.annotationId));Object.keys(this.commentsPinById).forEach(a=>{t.has(a)||(this.commentService.customPinsById.has(a)&&this.commentService.customPinsById.delete(a),this.commentsPinById[a].forEach(d=>{d.pinHostDomPortalOutlet.detach(),this.removeCommentPinHostAttributes(a,d.pinHostElement),this.removeCommentDisabledAttribute(d.pinHostElement),this.domService.removeHighlightFromElement(d.pinHostElement),d.userTargetElement&&this.domService.removeHighlightFromElement(d.userTargetElement)}),delete this.commentsPinById[a])})}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkPinsToRemove: ",t)}}getAnnotationIdsByUserTargetElement(e){try{let t=[];return Object.keys(this.commentsPinById||{}).forEach(a=>{this.commentsPinById[a]?.forEach(d=>{d.userTargetElement===e&&t.push(a)})}),t?.length>0?Array.from(new Set(t)):[]}catch(t){return this.loggingService.catch("Error in CommentPinPortalService getAnnotationIdsByUserTargetElement: ",t),[]}}setCommentPinOverrideTemplate(e){this.commentPinTemplate$.next(e)}getCommentPinTemplate$(){return this.commentPinTemplate$}emitCustomPinEvent(e){try{let{element:t,annotation:a}=e;a&&this.commentService.customPinsById.set(a.annotationId,t),this.customPinEvents$.next(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService emitCustomPinEvent",t)}}getCustomPinEvents$(){return this.customPinEvents$}};o.REATTACH_LIMIT=20,o.REATTACH_WINDOW_MS=1e3,o.\u0275fac=function(t){return new(t||o)(be(ae),be(Re),be(lu),be(nu),be(du),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var Br="data-velt-suggestion-inline",Vm="data-velt-mark",Wh="data-velt-before",Jh="data-velt-after",Hh="typing",Cp="velt-comment-text",Yh="velt-suggestion-inline-removed",Kh="velt-suggestion-inline-added",hk="velt-suggestion-inline-style",r3=5e3,n3=1e3,o3=100,a3=`
1
+ import{C as Nh}from"./chunk-U5WQDAMR.js";import{a as ep,b as E0}from"./chunk-JNWDY6EC.js";import{a as F0,b as Ph}from"./chunk-22I4DH53.js";import{a as D0,b as T0}from"./chunk-5GGSP4VM.js";import{a as jb,b as Gb,c as M0,d as A0,e as P0,f as _c,g as Sc}from"./chunk-AF2PV57S.js";import{a as ap}from"./chunk-6YADUX5R.js";import"./chunk-NTUJPDO3.js";import{a as WC,b as So,c as f0,d as qu,e as b0,f as C0,g as Tr,h as Zu,i as k0,j as Qu,k as Mn,n as Xu,o as x0,p as _0,q as yo,r as S0,s as y0,t as I0}from"./chunk-ZB27UMZA.js";import"./chunk-RQ7JAEYC.js";import"./chunk-WIO7FLS6.js";import{b as yu,c as Iu,g as wu,l as Xb,m as eC,r as tC,s as iC,w as lC,x as Ft}from"./chunk-77YRJB6U.js";import{b as Nb,c as Rb,d as Ub}from"./chunk-YOXKQAJM.js";import{a as dn}from"./chunk-ZJ2MICFG.js";import{b as O0}from"./chunk-NPHXJUYD.js";import{a as Du,c as rC,d as nC}from"./chunk-2UZN24LU.js";import{a as tp}from"./chunk-IWNLZTY7.js";import{a as Yt}from"./chunk-U65L5XOP.js";import{a as pt,b as tr}from"./chunk-7XUMHBJU.js";import{a as An}from"./chunk-XBR7WTYL.js";import{a as Io}from"./chunk-OC27IKXX.js";import{a as rp,b as np,c as N0,d as Fh,e as op}from"./chunk-S6JZ7XRE.js";import{A as p0,E as h0,F as Ku,G as P,H as N,a as Wu,c as Ju,d as yr,e as g0,f as Ir,i as Yu}from"./chunk-ZZE4KN4N.js";import{a as Be,b as Rm}from"./chunk-TIAQKD26.js";import{a as u0,b as J,c as ln,d as Ut}from"./chunk-4F4E7EFW.js";import{a as wr}from"./chunk-ZGDIZTBA.js";import{a as qb}from"./chunk-Y2R3M2JH.js";import{A as bn,Ea as aC,F as Vb,Fa as zt,G as ft,H as kt,Ha as D,I as $b,Ia as Dt,J as zb,Ja as Se,K as Hb,Ka as Pt,M as on,N as Wb,O as fu,P as Jb,Q as bu,R as Cu,T as Yb,U as Kb,V as sc,X as Vt,Y as Zo,da as ku,ea as xu,f as gu,ga as _u,j as Pb,m as mc,n as uu,p as Fb,r as pu,s as Lb,t as hu,v as Bb,za as oC}from"./chunk-ZHFA5BHC.js";import{a as w0}from"./chunk-MQWR574P.js";import{D as s0,G as _o,H as ut,e as Hu,l as o0,n as a0,p as i0,q as l0,r as d0,x as v0,y as c0,z as m0}from"./chunk-RSU53L4Z.js";import{$b as mu,$h as Ie,$i as UC,$j as XC,A as cb,Ae as uc,Ag as pC,Ah as qr,Bb as l,Bc as su,Be as dC,Bg as hC,Bh as Zr,C as mb,Ca as Cr,Cb as kr,Ce as bo,Cg as fC,Ch as Pm,Ck as t0,D as Ko,Db as xr,Df as mC,Dg as bC,Dh as Bu,E as qt,Ea as sr,Eh as Fm,Fb as ot,Fe as Kr,Fk as r0,G as Wr,Ga as ou,Gb as at,Gc as nn,Gd as Zb,Ge as st,Gk as Ah,Ha as v,Hb as it,Hc as wt,He as Z,Hg as Mm,Hk as n0,Ia as Le,Ib as Hn,Ic as ue,Ig as Nu,Ii as oe,Ij as Xn,Ik as Re,J as po,Ja as au,Jb as dc,Jg as kn,Ji as Oh,Jj as JC,Jk as vt,K as qo,Ka as iu,Kb as we,Kg as xn,Lb as mt,Lg as Ih,Lj as xc,M as Gt,Mb as pe,Mf as Em,Mg as CC,Mj as YC,N as sb,Nc as tt,Nj as Et,O as zn,Oa as lu,Ob as vc,Og as kC,P as gb,Pb as ie,Pc as cc,Pg as Ru,Q as ub,Qa as lc,Qb as Ge,Qc as Tn,Qd as Qb,Qf as Mu,Qj as KC,R as pb,Ra as G,Rb as Ce,Rc as Mb,Re as vC,Rg as wh,S as Dn,Sb as cu,Sg as Uu,T as hb,Ta as xb,Tb as Db,Tg as Dh,Th as EC,U as Ch,Ug as Am,Uh as OC,V as Fe,Va as _b,Vd as ho,Ve as Zt,Vg as Dr,Vi as _n,Vj as qC,Wa as T,Wd as fo,We as Kn,Wg as xC,Wh as Vu,Wi as Mh,Wj as Gu,Xa as Sb,Xe as At,Xg as Lu,Xh as hc,Xj as ZC,Y as Tm,Ya as yb,Yd as kh,Ye as cC,Yj as QC,Zc as Ab,Zd as qe,Ze as Co,Zf as Qo,_ as ic,_a as M,_b as Tb,_f as fr,_g as _C,_i as $u,a as g,aa as ru,ab as s,ac as U,ae as ct,ag as Au,aj as LC,b,ba as et,bc as Jr,bi as fc,bj as BC,c as ib,ca as fb,cc as gt,cg as pc,ci as MC,cj as VC,da as bb,db as du,dc as se,de as Tu,dg as ur,di as Qn,dj as $C,ea as be,ec as k,eg as xo,eh as SC,ej as jC,fa as ge,fb as x,fc as _e,fg as br,fi as bc,fj as GC,g as Pe,gb as rn,gc as Ye,gg as qn,gj as ju,h as lb,ha as Cb,hb as I,hc as E,hg as Zn,hh as yC,hj as Cc,i as ac,ia as kb,ib as w,ic as It,ig as _h,ik as e0,ja as B,jb as Ib,jc as fn,jg as Pu,ji as Nm,jj as zC,k as Lt,ka as V,kb as vu,l as De,la as de,lb as rt,lc as Wn,lg as Om,lh as IC,lj as Xo,m as db,ma as _t,mb as nt,mc as F,mg as Sh,mh as wC,mk as zu,na as nu,nb as c,nc as R,ng as Fu,nh as DC,ni as AC,o as vb,ob as C,oc as Rr,oi as Eh,oj as Sr,p as Hr,pb as _,pc as Eb,pd as Su,pi as PC,pj as pr,q as jn,qb as O,qc as Ob,qg as sC,qj as A,r as ye,rc as $e,rd as _r,re as ke,rf as ko,rg as gC,rj as kc,sa as Ae,se as Eu,sh as TC,tc as Yr,te as Yn,tg as En,th as Lr,ub as p,uc as L,ug as uC,uh as Th,ui as FC,v as Ee,vb as h,vc as Ct,ve as an,vg as Jt,vi as NC,w as Bt,wa as dt,wb as je,wc as dr,we as gc,wj as HC,x as tu,xa as K,xb as Y,xc as te,ya as me,yb as wb,yc as Jn,ye as xh,yg as yh,yi as RC,z as Gn,zb as z,zc as vr,ze as gr,zf as Ou,zg as Cn,zh as On}from"./chunk-VJ47SA66.js";function cr(r){try{if(typeof r!="string")return null;let o=r.trim();return o||null}catch{return null}}function eo(r,o){try{return typeof r!="string"||!r?o:b(g({},o),{sidebarId:r})}catch{return o}}var R0="velt-comments-sidebar-v2",xD="__veltSidebarV2Instance";function U0(r){try{let o=r;return o?cr(o.sidebarId)||typeof o.getAttribute=="function"&&cr(o.getAttribute("sidebar-id"))?!0:!!cr(o[xD]?.id):!1}catch{return!1}}function ip(){try{let r=document.querySelector(R0);return!r||!U0(r)?r:Array.from(document.querySelectorAll(R0)).find(n=>!U0(n))??null}catch{return null}}function L0(r){try{return!r||typeof r!="object"||!Object.prototype.hasOwnProperty.call(r,"sidebarId")?!1:!cr(r.sidebarId)}catch{return!1}}function B0(r,o){let n=[],e=(a,i,d,m)=>{n.push({key:a,field:i,op:d,value:m})},t=r?.order==="asc";if(r?.folderId&&e("folderId","metadata.veltFolderId","==",r.folderId),r?.locationId&&e("locationId","location.id","==",r.locationId),o?.length&&e("documentIds","metadata.documentId","in",o),r?.resolvedBy){if(t)throw new Error("Order by resolvedBy is not supported in ascending order.");e("resolvedBy","resolvedByUserId","==",r.resolvedBy)}if(r?.mentionedUserIds?.length){if(t)throw new Error("Order by mentionedUserIds is not supported in ascending order.");e("mentionedUserIds","mentionedUserIds","array-contains-any",r.mentionedUserIds)}if(r?.userIds?.length){if(t)throw new Error("Order by userIds is not supported in ascending order.");e("userIds","from.userId","in",r.userIds)}if(r?.statusIds?.length){if(t)throw new Error("Order by status id is not supported in ascending order.");e("statusIds","status.id","in",r.statusIds)}return r?.createdAfter&&e("createdAfter","createdAt",">=",r.createdAfter),r?.createdBefore&&e("createdBefore","createdAt","<=",r.createdBefore),r?.updatedAfter&&e("updatedAfter","lastUpdated",">=",r.updatedAfter),r?.updatedBefore&&e("updatedBefore","lastUpdated","<=",r.updatedBefore),b(g({clauses:n,direction:r?.order??"desc"},r?.order?{requestedOrder:r.order}:{}),{pageSize:r?.pageSize??100})}function V0(r,o){let n={organizationId:o.organizationId};for(let e of r.clauses)n[e.key]=e.value;return r.requestedOrder&&(n.order=r.requestedOrder),n.pageSize=r.pageSize,o.pageToken!==void 0&&(n.pageToken=o.pageToken),n}function Rh(r,o,n=!1){return{data:r.slice(0,o),hasMore:n||r.length>o}}var j0=["lastUpdated","createdAt"];function yc(r,o="desc"){return j0.map(n=>r(n,o))}function $0(r){if(typeof r=="number")return Number.isFinite(r)?r:0;if(typeof r=="string"){let o=Date.parse(r);return Number.isFinite(o)?o:0}return r&&typeof r=="object"&&typeof r.seconds=="number"?r.seconds*1e3:0}function G0(r,o){for(let n of j0){let e=$0(o?.[n])-$0(r?.[n]);if(e!==0)return e}return 0}var z0=new WeakSet;function H0(r){r&&typeof r=="object"&&z0.add(r)}function W0(r){return!!r&&typeof r=="object"&&z0.has(r)}function Um(r){try{let o=r?.organizationId,n=r?.documentId;return!o||!n?null:`${o}::${n}`}catch{return null}}function J0(r){try{if(!r)return{excludeResolved:!1,unlockedDocumentKey:null};let{lazyLoadResolvedComments:o,hasResolvedIntent:n,currentDocumentKey:e}=r;if(!e)return{excludeResolved:!1,unlockedDocumentKey:r.unlockedDocumentKey??null};let t=r.unlockedDocumentKey??null,a=n?e:t===e?t:null;return{excludeResolved:!!o&&!(a===e),unlockedDocumentKey:a}}catch{return{excludeResolved:!1,unlockedDocumentKey:null}}}function Y0(r,o){if(r==null&&o==null)return!0;if(r==null||o==null)return!1;let n=new Set(r),e=new Set(o);if(n.size!==e.size)return!1;for(let t of n)if(!e.has(t))return!1;return!0}function K0(r){try{return r?Object.entries(r).filter(([,o])=>o?.type!=="terminal").map(([o,n])=>n?.id??o).filter(o=>!!o):[]}catch{return[]}}function q0(r){try{return r?Object.entries(r).filter(([,o])=>o?.type==="terminal").map(([o,n])=>n?.id??o).filter(o=>!!o):[]}catch{return[]}}function _D(r){try{if(!r)return 0;let o=0;return r.hasApiKeyClause&&o++,r.hasOrganizationIdClause&&o++,(r.documentIdCount??0)>0&&o++,(r.accessFieldCount??0)>0&&o++,(r.locationIdCount??0)>0&&o++,r.hasFolderClause&&o++,(r.nonTerminalStatusCount??0)>0&&o++,o}catch{return 0}}function Z0(r){return{documentIdCount:r?.documentIdCount??0,accessFieldCount:r?.accessFieldCount??0,locationIdCount:r?.locationIdCount??0,nonTerminalStatusCount:r?.nonTerminalStatusCount??0,terminalStatusCount:r?.terminalStatusCount??0,hasApiKeyClause:!0,hasOrganizationIdClause:!0,hasFolderClause:!!r?.hasFolderClause,orderByCount:r?.orderByCount??0}}function Q0(r){let o=r?.maxDocumentBatchSize??0,n=(e,t=0,a=0,i="none")=>({applyStatusClause:!1,documentBatchSize:o,projectedDisjunctions:t,projectedFilterSum:a,boundBy:i,reason:e});try{if(o<1)return n("dropped-no-non-terminal-statuses");let e=r?.clauses;if(!e)return n("dropped-no-non-terminal-statuses");let t=e.nonTerminalStatusCount??0;if(t<=0)return n("dropped-no-non-terminal-statuses");if((e.terminalStatusCount??0)<=0)return n("dropped-no-terminal-statuses");let a=(e.documentIdCount??0)>0?e:b(g({},e),{documentIdCount:o}),i=_D(a),d=Math.max(1,e.accessFieldCount??0),m=Math.max(1,e.locationIdCount??0),u=e.orderByCount??0,f=a.documentIdCount,y=le=>Math.min(le,f),S=le=>y(le)*d*m*t,j=le=>le*i+u+1,W=S(o),$=j(W),H=W>30,q=$>100,ce=H&&q?"both":H?"disjunctions":q?"filter-sum":"none",fe=r?.minDocumentBatchSize??o;for(let le=o;le>=fe;le--){let he=S(le),xe=j(he);if(he<=30&&xe<=100)return{applyStatusClause:!0,documentBatchSize:le,projectedDisjunctions:he,projectedFilterSum:xe,boundBy:ce,reason:le===o?"fits":"fits-after-shrink"}}return n("dropped-over-budget",W,$,ce)}catch{return n("dropped-over-budget")}}var X0="Processing\u2026";function Lh(r){try{return r?!!(typeof r.commentText=="string"&&r.commentText.trim().length>0||typeof r.commentHtml=="string"&&r.commentHtml.trim().length>0||typeof r.commentVoiceUrl=="string"&&r.commentVoiceUrl.trim().length>0||Array.isArray(r.attachments)&&r.attachments.length>0||Array.isArray(r.recorders)&&r.recorders.length>0):!1}catch{return!1}}function Bh(r){try{return!!r?.progress}catch{return!1}}function Vh(r){try{return Bh(r)&&!Lh(r)}catch{return!1}}function $h(r){try{let o=r?.comments;if(!Array.isArray(o))return{comments:[],progress:[]};let n=[],e=[];return o.forEach(t=>(Vh(t)?e:n).push(t)),{comments:n,progress:e}}catch{return{comments:r?.comments??[],progress:[]}}}function SD(r){try{let o=Number(r);return!Number.isFinite(o)||o<=0?6e5:o}catch{return 6e5}}function Uh(r){try{if(r==null)return null;if(typeof r=="number")return Number.isFinite(r)?r:null;if(r instanceof Date)return r.getTime();if(typeof r?.toMillis=="function")return r.toMillis();if(typeof r?.seconds=="number")return r.seconds*1e3;let o=new Date(r).getTime();return Number.isNaN(o)?null:o}catch{return null}}function yD(r,o,n){try{let e=Uh(r?.lastUpdated);return e==null?!1:n-e>SD(o)}catch{return!1}}function lp(r,o,n){try{return r?.progress?.state!=="active"?!1:!yD(r,o,n)}catch{return!1}}function ek(r){try{let o=r?.progress?.steps;if(Array.isArray(o)&&o.length>0){let n=o[o.length-1];for(let t=o.length-1;t>=0;t--)if(o[t]?.state==="active"){n=o[t];break}let e=n?.label;if(typeof e=="string"&&e.trim().length>0)return{kind:"literal",text:e}}return{kind:"i18nKey",key:X0}}catch{return{kind:"i18nKey",key:X0}}}function tk(r){try{return Array.isArray(r)?r.slice().sort((o,n)=>(Uh(o?.createdAt)??0)-(Uh(n?.createdAt)??0)):[]}catch{return Array.isArray(r)?r.slice():[]}}var rk=r=>!!(r?.userId||r?.email),ID=(r,o)=>r?.userId&&o?.userId?r.userId===o.userId:r?.email&&o?.email?r.email===o.email:!1;function to(r,o,n){try{return o==null?rk(r):rk(o)&&!ID(r,o)}catch(e){try{n?.(e)}catch{}return!1}}function rr(r){return r?.isDocumentLevel===!0&&!r?.targetTextRange}function ro(r,o){return r?o?.length?r.filter(n=>rr(n)||!n?.location?.id?!0:!o.includes(n.location.id)):r:[]}function Lm(r,o){return r?.location?.id===o||rr(r)}var wD=new Set(["cfXPath","fXPath","parent+tag","contentHash"]);function dp(r){return r?wD.has(r.replace(/\+position$/,"")):!1}var St=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new De(Z.CommentAnnotationStatusMap),this._customPriorityMap=new De(Z.CommentAnnotationPriorityMap),this._customCategoryMap=new De(Z.CommentCategoryMap),this.isLazyLoadResolvedCommentsEnabled=null;try{let t=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let a=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);a&&this._customStatusMap.next(JSON.parse(a));let i=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);i&&this._customCategoryMap.next(JSON.parse(i))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(Z.CommentAnnotationStatusMap),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(Z.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(a=>{t[a.id]=a,a.type||(a.type="ongoing")}),this.warnOnDroppedStatusIds(t),this._customStatusMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}warnOnDroppedStatusIds(e){try{let t=sessionStorage.getItem(Z.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);if(!t)return;let a=JSON.parse(t),i=Object.keys(a??{});if(!i.length)return;let d=new Set(Object.keys(e??{})),m=i.filter(u=>!d.has(u));if(!m.length||!this.isLazyLoadResolvedCommentsEnabled?.())return;this.loggingService.catch(`[lazyLoadResolvedComments] status catalog dropped ${m.length} id(s): ${m.join(", ")}. Comments still carrying them will NOT be fetched while lazyLoadResolvedComments is enabled \u2014 migrate those annotations to the new ids, or keep the retired ids in the catalog.`,void 0,void 0,!0)}catch(t){this.loggingService.catch("Error in CustomFilterService warnOnDroppedStatusIds: ",t)}}setLazyLoadResolvedCommentsProvider(e){this.isLazyLoadResolvedCommentsEnabled=e}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(Z.CommentAnnotationPriorityMap),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(Z.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(a=>{t[a.id]=a}),this._customPriorityMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(a=>{t[a.id]=a}),this._customCategoryMap.next(t),sessionStorage.setItem(Z.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([a,i])=>i.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return Z.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([a,i])=>i.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return Z.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([a,i])=>i.type==="ongoing");if(t)return t.map(a=>a[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[Z.CommentAnnotationStatusMap.IN_PROGRESS]}get terminalStatuses(){try{return Object.entries(this._customStatusMap.value).filter(([t,a])=>a.type==="terminal").map(t=>t[1])}catch(e){this.loggingService.catch("Error in CustomFilterService terminalStatuses: ",e)}return[]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),a=t.find(([i,d])=>d.type==="default");switch(e.status){case"open":a&&(e.status=a[1]);break;case"inProgress":let i=t.find(([m,u])=>u.type==="ongoing");i&&(e.status=i[1]);break;case"resolved":let d=t.find(([m,u])=>u.type==="terminal");d&&(e.status=d[1]);break;default:a&&(e.status=a[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=Z.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(t=>Z.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var nk=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new Lt;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(ub()),this.domService.onWindowKeydown$().subscribe(a=>{this.keyEventSubject$.next(a)})}catch(a){this.loggingService.catch("Error in HotkeyService constructor: ",a)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe(qt(a=>a?.key===e),qt(a=>!(!!t?.includeCtrl!==a.ctrlKey||!!t?.includeAlt!==a.altKey||!!t?.includeShift!==a.shiftKey||!!t?.includeMeta!==a.metaKey)),qt(()=>this.isNoInputFocused()))}catch(a){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",a),new ac}}isNoInputFocused(){try{let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e.parentElement??e.getRootNode()?.host??null}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(be(Re),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var OD=["access","accessFields"];function MD(r,o){return!o||!r?.data||typeof r.data!="object"?r:b(g({},r),{data:Object.fromEntries(Object.entries(r.data).filter(([,n])=>n?.metadata?.veltFolderId===o))})}function AD(r){try{let o=Object.entries(r?.data??{});if(o.length<2)return r;o.sort(([,e],[,t])=>G0(e,t));let n={};for(let[e,t]of o)n[e]=t;return b(g({},r),{data:n})}catch{return r}}function PD(r){return r?Object.keys(r).length>0:!1}var FD=[Z.TAGS.VELT_COMMENT_THREAD,Z.TAGS.VELT_COMMENTS_SIDEBAR_V2,Z.TAGS.VELT_COMMENTS_SIDEBAR,Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR,Z.TAGS.VELT_INLINE_COMMENTS_SECTION,Z.TAGS.VELT_COMMENT_COMPOSER,Z.TAGS.VELT_MULTI_THREAD_COMMENT_DIALOG];function ND(r){try{let o=(r||[]).map(e=>String(e?.tagName||"").toLowerCase());return o.some(e=>e===Z.TAGS.VELT_COMMENT_DIALOG||e===Z.TAGS.SNIPPYLY_COMMENT_DIALOG)?!o.some(e=>FD.includes(e)):!1}catch{return!1}}function RD(r){try{if(!ND(r))return null;let o=r||[];if(o.some(e=>{let t=String(e?.tagName||"").toLowerCase();return t==="textarea"||t==="input"?!!String(e.value??"").trim():e?.isContentEditable===!0&&!!String(e.textContent??"").trim()}))return null;for(let e of o){let t=String(e?.tagName||"").toLowerCase();if(t!==Z.TAGS.VELT_COMMENT_DIALOG&&t!==Z.TAGS.SNIPPYLY_COMMENT_DIALOG)continue;let a=e.getAttribute?.("data-velt-dialog-annotation-id");if(a)return a}return null}catch{return null}}function UD(r){return r.insideManualCommentContainer?!1:r.commentPlaced?!0:!(r.clickConsumedByVeltSurface||r.draftDialogOpen)}var LD=new Set(["position","ghostComment","targetElement"]);function jh(r){if(r?.annotationId)return`pin:${r.annotationId}:${r.metadata?.documentId??""}`}var ae=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y,S,j,W,$,H,q,ce,fe,le,he,xe,ze,Ze,He,Xe){this.analyticsService=e,this.commonDbService=t,this.configService=a,this.docService=i,this.databaseService=d,this.authService=m,this.domService=u,this.afAuth=f,this.avatarService=y,this.contactService=S,this.storageService=j,this.functions=W,this.dialog=$,this.iamService=H,this.loggingService=q,this.notificationService=ce,this.customFilterService=fe,this.hotkeyService=le,this.serviceBook=he,this.buttonService=xe,this.metadataService=ze,this.commonDbUtilsService=Ze,this.attachmentResolverService=He,this.userPermissionService=Xe,this.endpointsService=ge(HC),this.customPinsById=new Map,this.commentAdded$=new Lt,this.commentUpdated$=new Lt,this.commentAccepted$=new Lt,this.commentRejected$=new Lt,this.commentAnnotationDeleted$=new Lt,this.multiThreadCommentAnnotationDeleted$=new Lt,this.commentAnnotationById$=new De(null),this.multiThreadCommentAnnotationById$=new De(null),this.lastRichTextEditorBlockLogKey=null,this.ghostCommentAnnotationMap$=new De({}),this.unreadCommentsMap$=new De(null),this.documentPaths=null,this.user=null,this.customCategoryMap=Z.CommentCategoryMap,this.allowedElementIds$=new De([]),this.allowedElementClassNames$=new De([]),this.allowedElementQuerySelectors$=new De([]),this.addCommentMode$=new De(!1),this.persistentCommentMode$=new De(!1),this.seenByUsers$=new De(!0),this.deleteReplyConfirmation$=new De(!1),this.persistentModeBanner$=new De(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new De(!0),this.sidebarVisible$=new De(!1),this.sidebarFocusRequest$=new De(null),this.sidebarOpenedByCustomTrigger$=new De(!1),this.floatingCommentsEnabled$=new De(!0),this.moderatorMode$=new De(!1),this.streamMode$=new De(!1),this.enableSignInButton$=new De(!1),this.enableUpgradeButton$=new De(!1),this.onSignInClick$=new Lt,this.onUpgradeClick$=new Lt,this.enableAttachment$=new De(!0),this.enableAttachmentDownload$=new De(!0),this.enableReactions$=new De(!0),this.enableAnonymousEmail$=new De(!0),this.enableFormatOptions$=new De(!1),this.formatConfig$=new De({bold:{enable:!0},italic:{enable:!0},underline:{enable:!0},strikethrough:{enable:!0}}),this.allowedRecordings$=new De(["audio","video","screen"]),this.openSidebar$=new Lt,this.showScreenSizeInfo$=new De(!1),this.showCommentIndex$=new De(!1),this.popoverMode$=new De(!1),this.popoverTriangleComponent$=new De(!0),this.draftMode$=new De(!0),this.draftConfirmation$=new De(!1),this.idScopedAnchoring$=new De(!1),this.idScopedAnchoringConfig$=new De({enabled:!1,documentIds:null}),this.idScopedAnchoringScope=null,this.loggedHiddenDocumentLevelPins=null,this.idScopedAnchoringVersion=0,this.draftConfirmationPendingAnnotationIds=new Set,this.enableDialogOnHover$=new De(!0),this.enableDialogOnTargetElementClick$=new De(!1),this.enablePriority$=new De(!1),this.enableStatus$=new De(!0),this.visibilityOptions$=new De(!1),this.enableResolve$=new De(!0),this.enableGhostComments$=new De(!1),this.enableGhostCommentsMessage$=new De(!0),this.inboxMode$=new De(!1),this.enableAutoCategorize$=new De(!1),this.commentContainerDarkMode$=new De(!1),this.suggestionMode$=new De(!1),this.mobileMode$=new De(!0),this.inlineCommentMode$=new De(!1),this.minimap$=new De(!1),this.commentsOnDom$=new De(!0),this.commentToolEnabled$=new De(!0),this.totalMediaLength$=new De(0),this.sidebarUrlNavigationEnabled$=new De(!1),this.detectionStrategy$=new De(xh.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new De(!1),this.sidebarButtonOnCommentDialogClick$=new Lt,this.commentNavigationButtonClick$=new Lt,this.deviceIndicatorOnCommentPins$=new De(!1),this.sidebarCommentClick$=new Lt,this.privateCommentMode$=new De(!1),this.privateCommentAllowed$=new De(!1),this.privateCommentModeRequested=!1,this.privateModeConfig$=new De(null),this.scrollToComment$=new De(!0),this.userMentions$=new De(!0),this.paginatedContactList$=new De(Z.PAGINATED_CONTACT_LIST_DEFAULT),this.deleteOnBackspace$=new De(!0),this.hotkeyEnabled$=new De(!1),this.recordingSummaryEnabled$=new De(!0),this.unreadIndicatorMode$=new De(uc.MINIMAL),this.composerMode$=new De(dC.DEFAULT),this.enterKeyToSubmit$=new De(!1),this.resolvedCommentsOnDom$=new De(!1),this.lazyLoadResolvedComments$=new De(!1),this.resolvedIntentFromSidebar$=new De(!1),this.resolvedUnlockedDocumentKey=null,this.lastQueryClauseDescriptor=null,this.bubbleOnPinEnabled$=new De(!1),this.bubbleOnPinHoverEnabled$=new De(!0),this.pinDragEnabled$=new De(!0),this.excludeLocationIdsFromSidebar$=new De([]),this.multiThread$=new De(!1),this.groupMatchedComments$=new De(!1),this.restrictTextSearchToAnchor$=new De(!1),this.shortUserName$=new De(!0),this.collapsedComments$=new De(!1),this.collapsedRepliesPreview$=new De(!1),this.fullExpanded$=new De(!1),this.queryParamsComments$=new De(!1),this.resolveStatusAccessAdminOnly$=new De(!1),this.linkCallback$=new De(!1),this.svgAsImg$=new De(!1),this.commentToNearestAllowedElement$=new De(!1),this.filterCommentsOnDom$=new De(!1),this.maxReplyAvatars$=new De(3),this.commentProgressStaleAfter$=new De(6e5),this.progressCommentsByAnnotationId=new Map,this.progressOnlyAnnotationsLogged=new Set,this.progressCommentsVersion$=new De(0),this.replyAvatars$=new De(!1),this.commentplaceholder$=new De(void 0),this.replyplaceholder$=new De(void 0),this.editplaceholder$=new De(void 0),this.editcommentplaceholder$=new De(void 0),this.editreplyplaceholder$=new De(void 0),this.screenshotEnabled$=new De(!1),this.pinShadowDOM$=new De(!0),this.dialogShadowDOM$=new De(!0),this.dialogShadowDOMExplicit$=new De(void 0),this.textCommentToolShadowDOM$=new De(!0),this.pinDarkMode$=new De(null),this.textCommentToolDarkMode$=new De(null),this.textCommentToolbarDarkMode$=new De(null),this.textCommentToolbarShadowDOM$=new De(!0),this.sidebarShadowDOM$=new De(!0),this.changeDetectionInCommentMode$=new De(!1),this.commentSelectionChange$=new Lt,this.visibilityOptionClicked$=new Lt,this.submitComment$=new Lt,this.clearComposer$=new Lt,this.composerDataMap=new Map,this.commentsFromSidebarMap$=new De(null),this.sidebarButtonCountType$=new De("default"),this.filterGhostCommentsInSidebar$=new De(!1),this.commentSidebarFilters$=new De(null),this.effectiveSidebarFilters$=new De({}),this.customSidebarDataAnnotationIds$=new De(null),this.commentSidebarSystemFiltersOperator$=new De(Kr.AND),this.bubbleCommentAnnotationIds$=new De([]),this.updateCommentDialogPositionTriggerSubject$=new De(void 0),this.areaCommentEnabled$=new De(!0),this.commentPinCursorImage$=new De(""),this.commentAnnotationsFromCommentsContainer$=new De([]),this.customChipDropdownData$=new De(null),this.originalCommentAnnotationsByDocumentId$=new De({}),this.draftCommentAnnotationsByAnnotationId$=new De(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new De({}),this.pendingAddCommentAnnotationData=new Map,this.copyLink$=new De(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new De(null),this.sidebarCustomActionEventData$=new De(null),this.sidebarCustomActionEventDataAllChanges$=new De(null),this.sidebarCustomActionEventDataOnInit$=new De(null),this.customActions$=new De(!1),this.focusedThreadMode$=new De(!1),this.openAnnotationInFocusMode$=new De(!1),this.customStatusesShown$=new De(!1),this.readOnly$=new De(!1),this.customAutocompleteSearch$=new De(!1),this.deleteThreadWithFirstComment$=new De(!0),this.assignToType$=new De("dropdown"),this.pageModeComposerContext$=new De(null),this.contextInPageModeComposer$=new De(!1),this.focusPageModeComposer$=new Lt,this.transformContext$=new De(null),this.expandMentionGroups$=new De(!1),this.showMentionGroupsFirst$=new De(!1),this.showMentionGroupsOnly$=new De(!1),this.fullScreenInSidebar$=new De(!1),this.composerFileAttachments$=new De(null),this.attachmentNameInMessage$=new De(!1),this.allowedFileTypes$=new De([]),this.forceCloseAllOnEsc$=new De(!1),this.autoCompleteScrollConfig$=new De({itemSize:55,minBufferPx:350,maxBufferPx:600,templateCacheSize:350}),this.commentAnnotationContextDraft=null,this.reactionService=null,this.areaService=null,this.viewsService=null,this.sharedCommentData=new Map,this.unreadMapComputedFor=new WeakMap,this.defaultSidebarResolvedIntent=!1,this.namedSidebarResolvedIntents=new Map,this.multiThreadReadUnansweredLogged=!1,this.multiThreadUnservedLogged=!1,this.getCommentAnnotationForClient=Oe=>{try{let Qe=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource","involvedUserIds","mentionedUserIds","viewedByUserIds","views"],Ke=JSON.parse(JSON.stringify(Oe)),xt={};Object.keys(Ke).forEach(Ot=>{Qe.includes(Ot)||(xt[Ot]=Ke[Ot])}),xt?.comments?.forEach(Ot=>{let Je=[];Ot?.reactionAnnotationIds&&Ot?.reactionAnnotationIds?.forEach(wm=>{let eu=this.reactionService?.getAnnotationById(wm);if(eu){let Dm=this.reactionService.getReactionAnnotationForClient(eu);Je.push(Dm)}}),Ot.reactionAnnotations=Je}),Ke?.viewedByUserIds?.forEach(Ot=>{let Je=this.contactService.getUserBySnippylyId(Ot);Je&&(xt.viewedBy||(xt.viewedBy=[]),xt.viewedBy.push(Je))}),this.user?.userSnippylyId&&(xt.unread=!Ke?.viewedByUserIds?.includes(this.user.userSnippylyId));let Ue=Ke?.targetElement?.anchor?.fXPath||Ke?.targetElement?.fXpath;return Ue&&(xt.basicAnchorData={xpath:Ue,topPercentage:Ke?.targetElement?.topPercentage||0,leftPercentage:Ke?.targetElement?.leftPercentage||0}),JSON.parse(JSON.stringify(xt))}catch{return null}},this.loggingService.log("%c[WB] Creating CLASS: CommentService","color: blue;"),this.serviceBook.set($u,this),this.serviceBook.observe(ju).subscribe(Oe=>{this.reactionService=Oe}),this.serviceBook.observe(zC).subscribe(Oe=>{this.areaService=Oe}),this.serviceBook.observe(Xo).subscribe(Oe=>{this.viewsService=Oe}),this.domService.getSelectedAnnotationsMap$().pipe(po(100),zn()).subscribe(([Oe,Qe])=>{try{if(this.draftCommentAnnotationsByAnnotationId$.value){let Ke=Object.keys(this.draftCommentAnnotationsByAnnotationId$.value||{}),xt=[];Object.keys(Oe||{}).forEach(Ot=>{if(!Qe?.[Ot]&&Ke.includes(Ot)){if(this.draftConfirmationPendingAnnotationIds?.has(Ot))return;xt.push(Ot)}});let Ue=JSON.parse(JSON.stringify(this.draftCommentAnnotationsByAnnotationId$.value||{}));xt.forEach(Ot=>{delete Ue[Ot]}),xn(Ue,this.draftCommentAnnotationsByAnnotationId$.value)||this.draftCommentAnnotationsByAnnotationId$.next(Ue)}}catch{}}),this.docService.getDocumentPaths$().pipe(zn()).subscribe(([Oe,Qe])=>{Oe?.documentId!==Qe?.documentId&&this.unreadCommentsMap$.next(null),Qe&&this.shouldEnableReadOnly()},Oe=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",Oe)}),this.draftCommentAnnotationsByAnnotationId$.pipe(zn()).subscribe(([Oe,Qe])=>{try{if(this.pendingAddCommentAnnotationData.size===0)return;let Ke=Object.keys(Oe||{});if(Ke.length===0)return;let xt=new Set(Object.keys(Qe||{}));Ke.forEach(Ue=>{!xt.has(Ue)&&this.pendingAddCommentAnnotationData.has(Ue)&&this.pendingAddCommentAnnotationData.delete(Ue)})}catch(Ke){this.loggingService.catch("Error in CommentService pendingAddCommentAnnotationData reconcile: ",Ke)}}),this.authService.getUser$().subscribe(Oe=>{Oe||this.resetCacheData()},Oe=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",Oe)}),this.authService.getUser$().pipe(Fe(Oe=>Oe?Bt([this.iamService.isUserAdmin$(),this.contactService.getUserOrganizationContacts$()]).pipe(Ee(([Qe,Ke])=>{let xt=!1;return Ke?.find(Ue=>Ue.userId===Oe?.userId)&&(xt=!0),{isUserAdmin:Qe,isOrgUser:xt}})):ye({isUserAdmin:!1,isOrgUser:!1}))).subscribe(({isUserAdmin:Oe,isOrgUser:Qe})=>{let Ke=Oe||Qe;Ke!==this.privateCommentAllowed$.value&&this.privateCommentAllowed$.next(Ke),Ke&&this.applyRequestedPrivateCommentMode()}),this.commentDbReadyGate$().pipe(qo(1)).subscribe(()=>{this.getDocumentPaths()},Oe=>{this.loggingService.catch("Error in CommentService getDb subscription: ",Oe)}),this.domService.onWindowPointerMove$().subscribe(Oe=>{if(this.addCommentMode$.value){let Qe=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let Ke=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY,!0,!0);if(Ke&&PC(Ke,{x:Oe.clientX,y:Oe.clientY})&&(Ke=Ke?.parentElement),Ke)if(this.isElementInsideAllowedElements(Ke))if(!this.isCommentBlockedOnElement(Oe.target)&&!Dr(Ke)){this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==Ke&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=Ke;let xt=this.domService.getSelectedAnnotationsMap("comment")||{},Ue=this.commentPinCursorImage$.value||Z.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,Ue,!!Object.keys(xt)?.length),Qe=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor");else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&Qe&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},Oe=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",Oe)}),this.domService.onWindowKeyupEsc$().subscribe(Oe=>{if(this.addCommentMode$.value){let Qe=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(Qe)?.length&&this.domService.resetSelectedAnnotationsMap(),this.disableAddCommentMode()}},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",Oe)}),this.domService.onDocumentClick$().subscribe(Oe=>{if(Oe&&!Nu(Oe)){let Qe=this.domService.getSelectedAnnotationsMap("comment")||{};if(Qe=g(g({},Qe),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Qe=g(g({},Qe),this.domService.getSelectedAnnotationsMap("suggestion")||{}),Object.keys(Qe)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),Oe.preventDefault(),Oe.stopPropagation();return}}if(Oe&&this.addCommentMode$.value){let Qe=!this.addCommentDragMode&&this.isCommentModeClickInsideRichTextEditor(Oe);if(Qe&&!Am(Oe.target)&&this.detectToAddAreaComment(),!Am(Oe.target)&&!Qe){let Ke=!1,xt=!1,Ue=!1,Ot=!1;if(this.addCommentDragMode)Oe.preventDefault(),Oe.stopPropagation(),this.addCommentDragMode=!1,xt=!0;else if(Ot=!!this.domService.getDraftCommentAnnotationDialogs()?.length,!Ot){let Je=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);if(this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(Oe.clientX,Oe.clientY)?Je=null:Oe&&Nu(Oe)&&(Je=null,Ue=!0),Je&&(this.isElementInsideAllowedElements(Je)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(Je))&&(Ke=this.isElementInsideManualCommentContainer(Je),!Ke)){Oe.preventDefault(),Oe.stopPropagation();let wm=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(Oe,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,wm),xt=!0}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():UD({insideManualCommentContainer:Ke,commentPlaced:xt,clickConsumedByVeltSurface:Ue,draftDialogOpen:Ot})&&this.disableAddCommentMode()}}},Oe=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",Oe)}),this.watchDocumentChangesForSidebarFocus(this.docService.getDocumentIds$()),this.domService.onWindowKeydown$().subscribe(Oe=>{try{if(Oe?.key!=="Escape"||Oe?.isComposing===!0)return;if(this.forceCloseAllOnEsc$.value!==!0){if(Oe?.defaultPrevented&&!W0(Oe))return;let Qe=RD(Oe?.composedPath?.());if(!Qe||this.getProgressComments(Qe)?.length)return;this.domService.discardEmptyDraftAnnotation(Qe)&&this.addCommentMode$.value&&this.disableAddCommentMode();return}if(Oe?.defaultPrevented)return;this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(Qe){this.loggingService.catch("Error in CommentService forceCloseAllOnEsc subscription: ",Qe)}},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeydown$ subscription: ",Oe)}),this.addCommentMode$.subscribe(Oe=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),Oe?(this.domService.addClassToElement(document.body,"snippyly-add-comment-mode"),this.detectToAddAreaComment(),this.addIframeContainerStaticAttribute()):(this.removeIframeContainerStaticAttribute(),this.domService.removeClassFromElement(document.body,"snippyly-add-comment-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"),this.dragSubscriptions.forEach(Qe=>Qe.unsubscribe()),this.clearFreeStyleCommentContext())},Oe=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",Oe)}),this.domService.onWindowKeyupBackspace$().subscribe(Oe=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",Oe)}),this.domService.onWindowKeyupDelete$().subscribe(Oe=>{this.deleteCommentPinAnnotations("keyupDelete")},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Oe)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Oe=>{Oe?.length&&(Oe?.filter(Ke=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(Ke.type))?.filter(Ke=>!this.getProgressComments(Ke?.annotationId).length)).forEach(Ke=>Pe(this,null,function*(){yield this.deleteCommentPinAnnotation(Ke)}))},Oe=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",Oe)}),this.getPopoverMode$().subscribe(Oe=>{Oe?document?.body?.setAttribute(Z.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(Z.ATTRIBUTES.VELT_POPOVER_MODE)},Oe=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",Oe)}),this.customFilterService.customCategoryMap$.subscribe(Oe=>{this.customCategoryMap=Oe},Oe=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",Oe)}),this.hotkeyEnabled$.subscribe(Oe=>{Oe?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},Oe=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",Oe)}),this.domService.getSelectedAnnotationsMap$().pipe(zn()).subscribe(([Oe,Qe])=>{try{let Ke=Object.values(Oe||{}).filter(Ue=>!["tag","recorder","rewriter","arrow","area"].includes(Ue.type)),xt=Object.values(Qe||{}).filter(Ue=>!["tag","recorder","rewriter","arrow","area"].includes(Ue.type));Ke?.forEach(Ue=>{xt?.find(Ot=>Ot.annotationId===Ue.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(Ue),selected:!1})}),xt?.forEach(Ue=>{Ke?.find(Ot=>Ot.annotationId===Ue.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(Ue),selected:!0})})}catch(Ke){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",Ke)}},Oe=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",Oe)})}clearCache(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in CommentService","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear(),this.customAutocompleteSearch$.next(!1),this.hightlightElement=null,this.addCommentMode$.next(!1),this.unreadCommentsMap$.next(null),this.documentPaths=null,this.commentsFromSidebarMap$.next(null),this.customSidebarDataAnnotationIds$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService?.getAreaEnabled()??!1,t=this.getAreaCommentEnabled();if(e&&t){let a,i,d,m=null,u=null;this.dragSubscriptions.forEach(f=>f.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(qt(f=>!(f&&Nu(f))),qo(1)).subscribe(f=>{m=null,u=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(y=>{if(m===null){let S=y?.startPoint?.event?.target,j=Mm(S),W=this.isCommentBlockedOnElement(S),$=this.isElementInsideAllowedElements(S);m=!j&&!W&&$}if(m){this.addCommentDragMode=!0,a=y.startPoint,i=y.curPoint;let S=y?.curPoint?.event?.target,j=Mm(S),W=this.isCommentBlockedOnElement(S),$=this.isElementInsideAllowedElements(S);u=!j&&!W&&$,u?d=this.domService.drawRectangle(a,i):d?.remove()}})),this.domService.onWindowPointerUp$().pipe(Dn(1),qo(1)).subscribe(y=>{if(i={x:y.clientX,y:y.clientY},a&&i&&(d?.remove(),m&&u)){let S=[{x:a.x-window.scrollX,y:a.y-window.scrollY},{x:i.x,y:i.y}],j=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(y,void 0,S,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,j)}this.dragSubscriptions.forEach(S=>S.unsubscribe())})}))}}catch(e){this.loggingService.catch("Error in CommentService detectToAddAreaComment: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: resetCacheData","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear()}catch(e){this.loggingService.catch("Error in CommentService resetCacheData: ",e)}}addAreaContainerTag(){try{if(!(document.querySelector(Z.TAGS.VELT_AREAS)||document.querySelector(Z.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(Z.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${Z.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(Z.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC)})}catch(e){this.loggingService.catch("Error in CommentService removeIframeContainerStaticAttribute: ",e)}}subscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: subscribeHotkeyEvents","color: green;"),this.unsubscribeHotkeyEvents(),this.hotkeySubscriptions.push(this.hotkeyService.getKeyPressEvent("c").subscribe(e=>{e&&!this.addCommentMode$.value&&this.enableAddCommentMode()},e=>{this.loggingService.catch("Error in CommentService hotkeyService.getKeyPressEvent subscription: ",e)}))}catch(e){this.loggingService.catch("Error in CommentService subscribeHotkeyEvents: ",e)}}unsubscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeHotkeyEvents","color: green;"),this.hotkeySubscriptions.forEach(e=>e?.unsubscribe())}catch(e){this.loggingService.catch("Error in CommentService unsubscribeHotkeyEvents: ",e)}}setCommentAddedEmitter(e){try{this.commentAddedEmitter=e}catch(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}commentDbReadyGate$(){return QC({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(Hu),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in CommentService commentDbReadyGate$ ${e}: `,t)})}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementIds:e}}),this.allowedElementIds$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:a,detectGhostComments:i,skipPositionCalculation:d,query:m,fromCommentSidebar:u,analytics:f,addFilterCommentsOnDomCheck:y}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let S,j,W;f?.enabled&&this.analyticsService.trackEvent(f?.eventName||oe.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,f?.properties);try{if(e&&(W=`${Qo(e)}`),t&&typeof t=="object"){let $=yh(t);j=$?.id,S=Qo(JSON.stringify($))}}catch($){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",$)}return Ko(ye(null),new ac($=>Gu(()=>$.next(null)))).pipe(Fe(()=>this.authService.getAuthState$()),qt($=>!!$),Fe($=>this.isFeatureAllowed({firebaseUser:$,annotations:[],filteredAnnotations:[]})),Fe($=>$.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(H=>($.featureAllowed=H,$))):ye($)),Fe($=>$.featureAllowed?ye($).pipe(Fe(H=>this.docService.getDocumentPaths$().pipe(Ee(q=>(this.documentPaths=q,H.documentPaths=q,H)))),Fe(H=>m?.documentIds?.length||W?this.getDataFromDocumentIds({documentIds:W?[W]:m?.documentIds?.map(q=>`${Qo(q)}`),organizationId:this.documentPaths?.organizationId,query:m}).pipe(Ee(q=>({res:H,data:q}))):this.docService.getDocumentIds$().pipe(Fe(q=>{let ce=q?.length>0?q.map(fe=>fe.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ce.length>0?ce:[W??""],organizationId:this.documentPaths?.organizationId,query:m}).pipe(Ee(fe=>({res:H,data:fe})))}))),Fe(H=>H?.data?(H.res.annotations=H.data||[],ye(H.res).pipe(Fe(q=>this.docService.getLocation$().pipe(Ee(ce=>(q.location=ce,q)))),Fe(q=>this.docService.getLocations$().pipe(Ee(ce=>(q.customLocations=ce,q)))),Fe(q=>this.docService.getExcludedLocationIds$().pipe(Ee(ce=>(q.excludedLocationIds=ce,q)))),Ee(q=>this.applyPageLocationFilters(q,{query:m,customInternalDocumentId:W,customLocationId:S,customClientLocationId:j,fromCommentSidebar:u})),Fe(q=>this.isPrivateCommentAllowed$().pipe(Ee(ce=>(ce||(q.filteredAnnotations=q.filteredAnnotations?.filter(fe=>!br(fe))),q)))),Fe(q=>this.draftCommentAnnotationsByAnnotationId$.pipe(Ee(ce=>(q.dataGeneration=(q.dataGeneration??0)+1,q.filteredAnnotations=q.filteredAnnotations?.filter(fe=>!fe.isDraft),ce&&q.filteredAnnotations.push(...Object.values(ce)),q)))),Fe(q=>{if(a)return ye(q);{let ce=q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$():null;return this.withIdScopedAnchoringChanges(ce,d).pipe(Ee(()=>q))}}),Fe(q=>a?ye(q):this.addCommentMode$.pipe(Fe(ce=>ce&&!this.getChangeDetectionInCommentMode()?ye(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(Ee(()=>q)):ye(q)))),Ee(q=>(d||this.domService.runPositionPass(()=>{(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(q.filteredAnnotations=q.filteredAnnotations?.map(fe=>{let le=Object.assign({},fe);return this.calculateCommentAnnotationPosition(le,i),le}));let ce={};q.filteredAnnotations?.forEach(fe=>{if(fe?.targetTextRange){let le=this.domService.getElementFromTargetTextRange(fe?.targetTextRange);ce[fe.annotationId]=!!le}}),q.textAnnotationsElementMap=ce}),q)),Fe(q=>q?.annotations?.length?this.serviceBook.observe(Xo).pipe(Fe(ce=>ce?ce.getCommentFeatureViews$():ye({})),Ee(ce=>(this.unreadMapComputedFor.get(q.annotations)!==ce&&(this.unreadMapComputedFor.set(q.annotations,ce),this.updateUnreadAnnotationsMap(q?.annotations,ce)),q))):(PD(this.unreadCommentsMap$.value)&&this.unreadCommentsMap$.next({}),ye(q))))):ye(null))):ye(null)),this.jsonSnapshotUnlessIdScopedAnchoringChanged($=>typeof $=="object"&&$?{filteredAnnotations:$.filteredAnnotations,textAnnotationsElementMap:$.textAnnotationsElementMap}:$),Fe($=>$?$?.filteredAnnotations?ye($?.filteredAnnotations||[]):ye([]):ye(null)),Fe($=>y?this.filterCommentsUsingSidebarSettings($):ye($)))}getAllMultiThreadCommentAnnotations(e,t,a,i,d,m){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let u,f;try{if(e&&(f=Qo(e)),t&&typeof t=="object"){let y=yh(t);u=Qo(JSON.stringify(y))}}catch(y){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",y)}return this.authService.getAuthState$().pipe(qt(y=>!!y),Fe(y=>this.isFeatureAllowed({firebaseUser:y,annotations:[],filteredAnnotations:[]})),Fe(y=>y.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(S=>(y.featureAllowed=S,y))):ye(y)),Fe(y=>y.featureAllowed?ye(y).pipe(Fe(S=>this.docService.getDocumentPaths$().pipe(Ee(j=>(this.documentPaths=j,S.documentPaths=j,S)))),Fe(S=>f?this.getMultiThreadDataFromDocumentIds([f]).pipe(Ee(j=>({res:S,data:j}))):this.docService.getDocumentIds$().pipe(Fe(j=>{let W=j?.length>0?j.map($=>$.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(W.length>0?W:[`${f}`]).pipe(Ee($=>({res:S,data:$})))}))),Fe(({res:S,data:j})=>j?(S.annotations=j||[],ye(S).pipe(Fe(W=>this.docService.getLocation$().pipe(Ee($=>(W.location=$,W)))),Fe(W=>this.docService.getLocations$().pipe(Ee($=>(W.customLocations=$,W)))),Fe(W=>this.docService.getExcludedLocationIds$().pipe(Ee($=>(W.excludedLocationIds=$,W)))),Ee(W=>{if(W.filteredAnnotations=[],f&&!u)return W.filteredAnnotations=W.annotations?.slice(),W?.excludedLocationIds?.length&&(W.filteredAnnotations=W.filteredAnnotations?.filter($=>$?.location?.id?!W.excludedLocationIds.includes($.location.id):!0)),W;{let $=[],H=[];return u?$.push(u):($.push(W?.location?.locationId),$.push(...Object.values(W?.customLocations||[]).map(q=>q.locationId)),W?.location?.location?.id&&H.push(W?.location?.location?.id),H.push(...Object.values(W?.customLocations||{}).map(q=>q.location?.id).filter(q=>!!q))),W.filteredAnnotations=this.filterAnnotationsByLocationIds(W?.annotations,$,H),W?.excludedLocationIds?.length&&(W.filteredAnnotations=W.filteredAnnotations?.filter(q=>q?.location?.id?!W.excludedLocationIds.includes(q.location.id):!0)),W}}),Fe(W=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(Ee($=>(W.filteredAnnotations=W.filteredAnnotations?.filter(H=>!H.isDraft),$&&W.filteredAnnotations.push(...Object.values($)),W)))),Fe(W=>{if(a)return ye(W);{let $=W?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$():null;return this.withIdScopedAnchoringChanges($,d).pipe(Ee(()=>W))}}),Fe(W=>a?ye(W):this.addCommentMode$.pipe(Fe($=>$&&!this.getChangeDetectionInCommentMode()?ye(W):W?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(Ee(()=>W)):ye(W)))),Ee(W=>(d||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(W.filteredAnnotations=W.filteredAnnotations?.map($=>{let H=Object.assign({},$);return this.calculateCommentAnnotationPosition(H,i),H})),W)),Fe(W=>W?.filteredAnnotations?ye(W?.filteredAnnotations||[]):ye([])))):ye(null))):ye(null)),this.distinctUnlessIdScopedAnchoringChanged(Qn),Fe(y=>m?this.filterCommentsUsingSidebarSettings(y):ye(y)))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(qt(t=>!!t),Ee(t=>b(g({},e),{config:t})),Fe(t=>this.authService.getUser$().pipe(Ee(a=>(this.user=a,b(g({},t),{user:a}))))),Fe(t=>uC(t.config,t.user,ke.COMMENT)?ye(b(g({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),ye(b(g({},t),{featureAllowed:!1})))),Gt((t,a)=>t?.featureAllowed===a?.featureAllowed))}buildVisibilityTokens(e){return Pe(this,null,function*(){try{let a=this.authService.getUser()?.clientOrganizationId,i=a?yield this.isViewerOrgMembershipConfirmed(e,a):!1;return _h({userId:e,clientOrganizationId:i?a:void 0,fallbackServerOrganizationId:a?void 0:this.documentPaths?.organizationId})}catch(t){this.loggingService.catch("Error in CommentService buildVisibilityTokens: ",t);try{return[Z.DEFAULT_VELT_CONTEXT,`${Z.VISIBILITY_SELF_PREFIX}${fr(e)}`]}catch{return[Z.DEFAULT_VELT_CONTEXT]}}})}isViewerOrgMembershipConfirmed(e,t){return Pe(this,null,function*(){try{let i=(yield this.userPermissionService.getUserPermissionsFromCacheOrFetch({organizationId:t}))?.[e]?.organization?.[t];return!!i&&i.errorCode!==Mu.PERMISSION_DENIED}catch(a){return this.loggingService.catch("Error in CommentService isViewerOrgMembershipConfirmed: ",a),!1}})}applyPortableVisibilityFilter(e,t,a){try{if(!e?.data)return e;let i=Object.values(e.data).filter(u=>typeof u=="object"),d=Pu(i,t);if(d.length===i.length)return e;if(a?.resultSet){let u=new Set(d);this.evictResultSetDepartures(a.resultSet.leave(i.filter(f=>!u.has(f))))}let m={};return d.forEach(u=>{u?.annotationId&&(m[u.annotationId]=u)}),b(g({},e),{data:m})}catch(i){return this.loggingService.catch("Error in CommentService applyPortableVisibilityFilter: ",i),e}}buildAllCommentsRawListener$(e){let{isContextEnabled:t,documentIds:a,organizationId:i,accessFields:d,isPrivateCommentsEnabled:m,veltFolderId:u,locationIds:f,statusIds:y,commonProperties:S,includeStatusIds:j,documentBatchSize:W}=e,$=y?.length?[Et("status.id","in",y)]:j?.length?[Et("status.id","in",j)]:[],H;if(t){let q=[];for(let ce=0;ce<d.length;ce+=Z.LISTENER_CONTEXT_BATCH_SIZE)q.push(d.slice(ce,ce+Z.LISTENER_CONTEXT_BATCH_SIZE));this.loggingService.logContext("[CONTEXT] getDataFromDocuments called with accessFields:",JSON.parse(JSON.stringify(d??"nil"))),H=Bt(q.map(ce=>this.commonDbService.dbListener({feature:"allComments",properties:b(g({},S),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",i??this.documentPaths?.organizationId),Et("metadata.documentId","in",a),...$,...u?[Et("metadata.veltFolderId","==",u)]:[],...f?.length?[Et("location.id","in",f)]:[],...ce?.length?[Et("context.accessFields","array-contains-any",ce)]:[]),...yc(xc)]})}).pipe(ic()))).pipe(Ee(ce=>bc(JSON.parse(JSON.stringify(ce)))))}else{let q=[];for(let ce=0;ce<(a?.length??0);ce+=W)q.push(a?.slice(ce,ce+W)??[]);H=Bt(q.map(ce=>this.commonDbService.dbListener({feature:"allComments",properties:b(g({},S),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",i??this.documentPaths?.organizationId),Et("metadata.documentId","in",ce),...$,...u?[Et("metadata.veltFolderId","==",u)]:[],...f?.length?[Et("location.id","in",f)]:[],...d?.length&&m?[Et("context.accessFields","array-contains-any",d)]:[]),...yc(xc)]})}).pipe(ic()))).pipe(Ee(ce=>bc(JSON.parse(JSON.stringify(ce)))))}return H}resolvedStatusExclusion$(e){let t=this.customFilterService.customStatusMap$,a=(typeof this.docService?.getDocumentPaths$=="function"?this.docService.getDocumentPaths$():ye(null)).pipe(Ee(i=>Um(i)),Gt());return Bt([this.lazyLoadResolvedComments$,this.resolvedIntentFromSidebar$,t,a]).pipe(Ee(([i,d,m,u])=>{let f=Z.LISTENER_BATCH_SIZE;if(e.hasExplicitStatusIds)return{includeStatusIds:null,documentBatchSize:f};let y=u??Um(this.documentPaths),S=J0({lazyLoadResolvedComments:!!i,hasResolvedIntent:!!d,currentDocumentKey:y,unlockedDocumentKey:this.resolvedUnlockedDocumentKey});if(this.resolvedUnlockedDocumentKey=S.unlockedDocumentKey,!S.excludeResolved)return{includeStatusIds:null,documentBatchSize:f};let j=K0(m),W=q0(m);if(e.clientSideOnly)return{includeStatusIds:j,documentBatchSize:f};let $=Z0({branch:e.isContextEnabled?"context":"default",documentIdCount:e.documentIdCount,accessFieldCount:e.isContextEnabled?Math.min(e.accessFieldCount,Z.LISTENER_CONTEXT_BATCH_SIZE):e.accessFieldCount,locationIdCount:e.locationIdCount,nonTerminalStatusCount:j.length,terminalStatusCount:W.length,hasFolderClause:e.hasFolderClause,orderByCount:2});this.lastQueryClauseDescriptor=$;let H=e.documentIdCount,q=Q0({branch:e.isContextEnabled?"context":"default",clauses:$,maxDocumentBatchSize:e.isContextEnabled?H:f,minDocumentBatchSize:e.isContextEnabled?H:2});return q.applyStatusClause?{includeStatusIds:j,documentBatchSize:q.documentBatchSize}:(this.loggingService.catch(`[lazyLoadResolvedComments] status clause dropped \u2014 branch=${e.isContextEnabled?"context":"default"} disjunctions=${q.projectedDisjunctions} filterSum=${q.projectedFilterSum} boundBy=${q.boundBy} reason=${q.reason}`,null,void 0,!0),{includeStatusIds:null,documentBatchSize:f})}),Gt((i,d)=>i.documentBatchSize===d.documentBatchSize&&Y0(i.includeStatusIds,d.includeStatusIds)),Wr(i=>(this.loggingService.catch("[lazyLoadResolvedComments] status-exclusion stream failed; falling back to today's query: ",i),ye({includeStatusIds:null,documentBatchSize:Z.LISTENER_BATCH_SIZE}))))}getDataFromDocuments(e){let{documentIds:t,organizationId:a,query:i}=e;if(!this.configService?.getApiKey())return ye(null);if(t?.some(j=>!j)||!this.documentPaths)return ye(null);let d,m,u=[];if(i)i?.folderId&&(d=ur(i?.folderId)),i?.locationId&&(u=[...u,i?.locationId]),i?.locationIds?.length&&(u=[...u,...i?.locationIds]),m=i?.statusIds;else{d=this.docService.getDocumentPaths()?.veltFolderId;let j=this.docService.getDocumentPaths()?.locationId;j&&(u=[...u,j])}let f={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(f.documentId=t?.length?t[0]:void 0,f.organizationId=this.documentPaths?.organizationId);let y=this.authService.getUser()?.userId;if(!y)return ye(null);let S=this.authService.getIsPrivateCommentsEnabled();return this.queryDocContextChanges$().pipe(Fe(()=>tu(()=>jn(this.buildVisibilityTokens(y)).pipe(Fe(W=>{let $=S?W:[Z.DEFAULT_VELT_CONTEXT],{isContextEnabled:H,contextFields:q}=this.getQueryDocContext(),ce=[...$,...q],fe,le=this.commonDbService.usesPortableChannelFeed(Hu),he=!m,xe=le&&he?D0():null,ze=null;return le?fe=this.resolvedStatusExclusion$({isContextEnabled:!!H,documentIdCount:t?.length??0,accessFieldCount:ce?.length&&(H||S)?ce.length:0,locationIdCount:u?.length??0,hasFolderClause:!!d,hasExplicitStatusIds:!!m,clientSideOnly:!0}).pipe(Fe(Ze=>(ze=Ze.includeStatusIds,this.commonDbService.dbListener({feature:"allComments",properties:b(g({},f),{organizationId:a??this.documentPaths?.organizationId,documentIds:t})}).pipe(ic(),Ee(He=>bc(JSON.parse(JSON.stringify([He])))),Ee(He=>S?this.applyPortableVisibilityFilter(He,{userId:y,tokens:W},{resultSet:xe}):He),Ee(He=>AD(He)))))):fe=this.resolvedStatusExclusion$({isContextEnabled:!!H,documentIdCount:t?.length??0,accessFieldCount:ce?.length&&(H||S)?ce.length:0,locationIdCount:u?.length??0,hasFolderClause:!!d,hasExplicitStatusIds:!!m}).pipe(Fe(Ze=>this.buildAllCommentsRawListener$({isContextEnabled:!!H,documentIds:t,organizationId:a,accessFields:ce,isPrivateCommentsEnabled:S,veltFolderId:d,locationIds:u,statusIds:m,commonProperties:f,includeStatusIds:Ze.includeStatusIds,documentBatchSize:Ze.documentBatchSize}))),fe.pipe(Fe(Ze=>Ze?.data?ye(Ze).pipe(Fe(He=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:He,feature:"allComments"}).pipe(Ee(Xe=>{let Oe=Object.values(Xe?.data||{}).filter(Ke=>typeof Ke=="object"),Qe=this.applyPortableQueryScopeFilter(Oe,{isPortableFeed:le,scope:{statusIds:m??ze,veltFolderId:d,locationIds:u},evictDropped:he,resultSet:xe});return{data:this.applyListenerVisibilityPostFilter(Qe,W,y,H?q:null),operation:Xe?.operation}}))),Ee(({data:He,operation:Xe})=>{let Oe=He.reduce((Qe,Ke)=>{let xt=Ke.metadata?.documentId;return xt&&(Qe[xt]||(Qe[xt]=[]),Qe[xt].push(Ke)),Qe},{});return{data:He,documentMap:Oe,operation:Xe}}),Ee(({data:He,documentMap:Xe,operation:Oe})=>m?{data:He,documentMap:Xe,operation:Oe}:(He?.length&&(He?.forEach(Qe=>{this.sanitizeCommentAnnotation(Qe)}),this.setAnnotationIndex(He),this.updateAnnotationsForSelectAllContentMode(He),He.forEach(Qe=>{this.customFilterService.convertLegacyAnnotationStatus(Qe),this.customFilterService.convertLegacyPriority(Qe),this.customFilterService.convertLegacyCategory(Qe)})),{data:He,documentMap:Xe,operation:Oe})),Wr(He=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",He),ye([]))),Tm(({documentMap:He})=>{m||Object.entries(He??{}).forEach(([Xe,Oe])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(Oe)))})}),Ee(({data:He,documentMap:Xe,operation:Oe})=>({data:this.filterUserDraftComments(He),documentMap:Xe,operation:Oe})),Ee(({data:He,documentMap:Xe,operation:Oe})=>({data:this.splitProgressCommentsStage(this.removeDraftFlags(He)),documentMap:Xe,operation:Oe})),Fe(({data:He,documentMap:Xe,operation:Oe})=>m?ye({data:He,documentMap:Xe,operation:Oe}):this.mergeDraftAnnotations(He).pipe(Ee(Qe=>({data:Qe,documentMap:Xe,operation:Oe})))),Ee(({data:He,documentMap:Xe,operation:Oe})=>{if(!m)if(Oe?.type==="removed"){if(Oe?.ids?.length){let Qe=this.commentAnnotationById$.value??{};Oe?.ids?.forEach(Ke=>{delete Qe?.[Ke]}),this.evictProgressComments(Oe?.ids??[]),this.commentAnnotationById$.next(Qe)}}else Object.entries(Xe??{}).length?Object.entries(Xe??{}).forEach(([Ke,xt])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:Ke,annotations:xt})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return He})):ye(null)))})))))}fetchCommentAnnotations(e){return Pe(this,null,function*(){try{let t=this.authService.getUser();if(!t)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{data:[],hasMore:!1};let a=this.commonDbService?.isPortableCommentQueryCandidate?.()===!0,i=this.configService?.getApiKey(),d=e?.organizationId??t?.clientOrganizationId,m=pc(d??""),u=[];e?.allDocuments||(u=e?.documentIds?.map(ce=>Au(ce??""))??this.docService.getDocumentIds()?.map(ce=>ce.documentId));let f=B0(e,u),y;e?.pageToken&&(y=yield fC(e?.pageToken??"","veltencrypttoken","veltencrypttoken"));let S,j;a?{data:S,hasMore:j}=yield this.fetchPortableCommentAnnotationPage(t.userId,V0(f,{organizationId:d??"",pageToken:y}),f.pageSize):(S=yield this.commonDbService.queryData({feature:"allComments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:this.buildFirestoreCommentAnnotationQuery(f,{serverOrganizationId:m,apiKey:i,hasPageToken:!!e?.pageToken,decryptedPageToken:y}),apiKey:i??"",organizationId:m}}),{data:S,hasMore:j}=Rh(S,f.pageSize));let W=S?.reduce((ce,fe)=>(ce[fe?.annotationId]=fe,ce),{});W=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:W,shouldAwait:!0}),W=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:W});let $=t.clientOrganizationId?yield this.isViewerOrgMembershipConfirmed(t.userId,t.clientOrganizationId):!1,H=_h({userId:t.userId,clientOrganizationId:$?t.clientOrganizationId:void 0,fallbackServerOrganizationId:t.clientOrganizationId?void 0:m});return{data:Pu(Object.values(W??{}),{userId:t.userId,tokens:H}),hasMore:j}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}fetchPortableCommentAnnotationPage(e,t,a){return Pe(this,null,function*(){try{let i=yield this.commonDbService.runPortableCommentQuery("fetchCommentAnnotations",t,e);if(!i?.ok)return{data:[],hasMore:!1};let d=i.data;return Array.isArray(d?.data)?Rh(d.data,a,d.hasMore===!0):(this.loggingService.log("Tier B fetchCommentAnnotations answered ok without a `data` array; treated as no rows."),{data:[],hasMore:!1})}catch(i){return this.loggingService.catch("Error in CommentService fetchPortableCommentAnnotationPage: ",i),{data:[],hasMore:!1}}})}buildFirestoreCommentAnnotationQuery(e,t){return[Et("metadata.organizationId","==",t.serverOrganizationId),Et("metadata.apiKey","==",t.apiKey),...e.clauses.map(a=>Et(a.field,a.op,a.key==="folderId"?ur(a.value):a.value)),...yc(xc,e.direction),...t.hasPageToken?[YC(parseInt(t.decryptedPageToken,10),"lastUpdated")]:[],JC(e.pageSize+1)]}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(a=>(a.comments=a?.comments?.filter(i=>i?.from?.userId===t?.userId||!i?.isDraft),!!a?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(Ee(t=>{let a=t||{};return e?.filter(i=>{a?.[i?.annotationId]&&delete a[i?.annotationId]}),a}),Ee(t=>{if(t){let a=e.slice();return a.push(...Object.values(t)),a}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:a}){try{let i=this.getSharedCommentDataKey({documentIds:e,organizationId:t,query:a});if(i===null)return this.getDataFromDocuments({documentIds:e,organizationId:t,query:a});let d=this.sharedCommentData.get(i);return d||(d=this.getDataFromDocuments({documentIds:e,organizationId:t,query:a}).pipe(sb(()=>{try{this.sharedCommentData.get(i)===d&&this.sharedCommentData.delete(i)}catch(m){this.loggingService.catch("Error in CommentService getDataFromDocumentIds finalize: ",m)}}),pb({bufferSize:1,refCount:!0})),this.sharedCommentData.set(i,d)),d}catch(i){return this.loggingService.catch("Error in CommentService getDataFromDocumentIds: ",i),this.getDataFromDocuments({documentIds:e,organizationId:t,query:a})}}getSharedCommentDataKey({documentIds:e,organizationId:t,query:a}){try{let i=this.docService.getDocumentPaths();return JSON.stringify([e??null,t??null,a??null,this.configService?.getApiKey()??null,this.authService.getUser()?.userId??null,this.authService.getIsPrivateCommentsEnabled()??null,this.commonDbService.shouldUseFirestore(),this.commonDbService.usesPortableChannelFeed(Hu),this.commonDbService.isPortableSession?.()??null,!!this.documentPaths,this.documentPaths?.organizationId??null,i?.veltFolderId??null,i?.locationId??null,this.getQueryDocContext()])}catch(i){return this.loggingService.catch("Error in CommentService getSharedCommentDataKey: ",i),null}}queryDocContextChanges$(){return(this.docService?.getDocContext$?.()??ye(null)).pipe(Ee(()=>this.getQueryDocContext()),Gt((t,a)=>t.isContextEnabled===a.isContextEnabled&&JSON.stringify(t.contextFields)===JSON.stringify(a.contextFields)),Wr(t=>(this.loggingService.catch("Error in CommentService queryDocContextChanges$: ",t),ye(this.getQueryDocContext()))))}getQueryDocContext(){try{let e=!!this.userPermissionService?.getIsContextEnabled();return{isContextEnabled:e,contextFields:e?this.docService.getProcessedDocContext():[]}}catch(e){return this.loggingService.catch("Error in CommentService getQueryDocContext: ",e),{isContextEnabled:!0,contextFields:[]}}}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(m=>!m)||!this.documentPaths)return ye(null);let a=this.docService.getDocumentPaths()?.veltFolderId,i=ye([]),d={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(d.documentId=t?.length?t[0]:void 0,d.organizationId=this.documentPaths?.organizationId),this.commonDbService?.isPortableSession?.()===!0&&a0(o0)&&typeof this.commonDbService?.portableCapability$=="function")i=qC(this.commonDbService,zu,{feature:"allMultiThreads",properties:b(g({},d),{organizationId:this.documentPaths?.organizationId,documentIds:t})}).pipe(Ee(m=>this.applyMultiThreadFolderClause(m,a)));else if(this.userPermissionService?.getIsContextEnabled()){let m=[Z.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],u=[];for(let f=0;f<(m?.length??0);f+=Z.LISTENER_CONTEXT_BATCH_SIZE)u.push(m?.slice(f,f+Z.LISTENER_CONTEXT_BATCH_SIZE)??[]);i=Bt(u.map(f=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:b(g({},d),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",this.documentPaths?.organizationId),Et("metadata.documentId","in",t),...a?[Et("metadata.veltFolderId","==",a)]:[],...f?.length?[Et("context.accessFields","array-contains-any",f)]:[])]})}).pipe(ic()))).pipe(Ee(f=>bc(f)))}else{let m=[];for(let u=0;u<(t?.length??0);u+=Z.LISTENER_BATCH_SIZE)m.push(t?.slice(u,u+Z.LISTENER_BATCH_SIZE)??[]);i=Bt(m.map(u=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:b(g({},d),{firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",this.documentPaths?.organizationId),Et("metadata.documentId","in",u),...a?[Et("metadata.veltFolderId","==",a)]:[])]})}).pipe(ic()))).pipe(Ee(u=>bc(u)))}return i.pipe(Fe(m=>m?.data?ye(m).pipe(Ee(u=>({data:u?.data,operation:u?.operation})),Ee(({data:u,operation:f})=>{let y=[];return u&&(y=Object.values(u??{}).filter(S=>typeof S=="object")),{data:y,operation:f}}),Wr(u=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",u),ye({data:[],operation:null}))),Ee(({data:u,operation:f})=>{u.forEach(S=>{delete S.isDraft});let y=u.reduce((S,j)=>{let W=j.metadata?.documentId;return W&&(S[W]||(S[W]=[]),S[W].push(j)),S},{});return{data:u,documentMap:y,operation:f}}),Fe(({data:u,documentMap:f,operation:y})=>{let S=[];return this.commentAnnotationById$.pipe(Fe(()=>this.domService.getSelectedAnnotationsMap$().pipe(Ee(j=>({selectedAnnotationsMap:j})))),Ee(({selectedAnnotationsMap:j})=>{let W={};return Object.keys(f??{}).forEach($=>{let H=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:$});H&&H?.forEach(q=>{W[q?.annotationId]=q})}),S=u.filter($=>{let H=!1;if($?.commentAnnotations){for(let q in $?.commentAnnotations)if(W?.[q]&&W?.[q]?.status?.id!==this.customFilterService.resolvedStatus.id){H=!0;break}}return H}),S.forEach($=>{Object.keys($?.commentAnnotations||{}).forEach(H=>{$.commentAnnotationsMap||($.commentAnnotationsMap={}),$.commentAnnotationsMap[H]=W?.[H]})}),{data:S,operation:y}}))}),Fe(({data:u,operation:f})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(Ee(y=>{let S=y||{};return u?.filter(j=>{S?.[j?.annotationId]&&delete S[j?.annotationId]}),S}),Ee(y=>{if(y){let S=u.slice();return S.push(...Object.values(y)),{data:S,operation:f}}return{data:u,operation:f}}))),Ee(({data:u,operation:f})=>{let y=u.reduce((S,j)=>{let W=j.metadata?.documentId;return W&&(S[W]||(S[W]=[]),S[W].push(j)),S},{});if(f?.type==="removed"){if(f?.ids?.length){let S=this.multiThreadCommentAnnotationById$.value;f?.ids?.forEach(j=>{delete S?.[j]}),this.multiThreadCommentAnnotationById$.next(S)}}else Object.keys(y??{}).forEach(S=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:S,annotations:y[S]})});return u})):ye(null)))}else return ye(null)}updateUnreadAnnotationsMap(e,t){try{let a=new Date(Z.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),i=e.filter(d=>d?.lastUpdated>a);if(t){let d={},m=!1;i.forEach(u=>{let f=0,y=t?.[u?.annotationId];if(y){let S=y?.comments;S&&u?.comments?.forEach(j=>{S?.[j?.commentId]?.views?.[this.user?.userSnippylyId]||f++})}f?f!==d?.[u?.annotationId]&&(d[u?.annotationId]=f,m=!0):d?.[u?.annotationId]&&(delete d[u?.annotationId],m=!0)}),this.unreadCommentsMap$.next(d)}}catch(a){this.loggingService.catch("Error in CommentService updateUnreadAnnotationsMap:",a)}}updateAnnotationsForSelectAllContentMode(e){try{e.forEach(t=>{if(t?.selectAllContent&&t?.targetElementId){let a=Lr(t.targetElementId,["id","data-id"]);if(a){let i=a.textContent;i&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(a),text:i,occurrence:1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(a)??void 0},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:a,queryHash:i}){try{if(t){e||(e=Z.NO_ORGANIZATION_ID),i||(i=Z.DEFAULT_QUERY_HASH);let d={};a?.forEach(u=>{u?.annotationId&&(d[u?.annotationId]=u)});let m=g(g({},this.commentAnnotationById$.value??{}),d);this.commentAnnotationById$.next(m)}}catch(d){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",d)}}getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Ee(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",a),ye([])}}getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:e,documentIds:t}){try{let a=new Set((t||[]).map(f=>String(f))),i=this.commentAnnotationById$.value,d=this.draftCommentAnnotationsByAnnotationId$.value;if(!i&&!d)return null;if(!a.size)return[];let m=f=>f?.metadata?.documentId!=null&&a.has(String(f.metadata.documentId))&&f?.metadata?.organizationId==e,u={};return Object.values(i||{}).forEach(f=>{m(f)&&(u[f.annotationId]=f)}),Object.values(d||{}).forEach(f=>{m(f)&&!u[f.annotationId]&&(u[f.annotationId]=f)}),Object.values(u)}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentIds:",a),[]}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let a=null;this.commentAnnotationById$.value&&(a={},Object.values(this.commentAnnotationById$.value).forEach(d=>{d?.metadata?.documentId==t&&d?.metadata?.organizationId==e&&(a[d?.annotationId]=d)}));let i=this.draftCommentAnnotationsByAnnotationId$.value;return i&&(a===null&&(a={}),Object.values(i).forEach(d=>{d?.metadata?.documentId===t&&d?.metadata?.organizationId===e&&!a[d?.annotationId]&&(a[d?.annotationId]=d)})),a?Object.values(a):null}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId:",a),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(Fe(a=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:a?.organizationId,documentId:t}))):ye(null)}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",a),ye(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Fe(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ye([])))}getCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId}):[]}catch(e){return this.loggingService.catch("Error in CommentService getCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}setOriginalCommentAnnotationsByAnnotationId(e){try{let t={};e?.forEach(a=>{a?.annotationId&&(t[a?.annotationId]=a)}),this.originalCommentAnnotationsByDocumentId$.next(g(g({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:a,queryHash:i}){try{if(t){e||(e=Z.NO_ORGANIZATION_ID),i||(i=Z.DEFAULT_QUERY_HASH);let d={};a.forEach(u=>{u?.annotationId&&(d[u?.annotationId]=u)});let m=g(g({},this.multiThreadCommentAnnotationById$.value),d);this.multiThreadCommentAnnotationById$.next(m)}}catch(d){this.loggingService.catch("Error in CommentService setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",d)}}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){return this.multiThreadCommentAnnotationById$.pipe(Ee(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let a={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(d=>{d?.metadata?.documentId==t&&d?.metadata?.organizationId==e&&(a[d?.annotationId]=d)});let i=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return i&&Object.values(i??{}).forEach(d=>{d?.metadata?.documentId===t&&d?.metadata?.organizationId===e&&!a[d?.annotationId]&&(a[d?.annotationId]=d)}),Object.values(a)}catch(a){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",a),[]}}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Fe(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ye([])))}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId})}catch(e){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}getLocations$(){return this.docService.getLocation$().pipe(Fe(e=>this.docService.getLocations$().pipe(Ee(t=>({location:e,locations:t})))),Ee(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(a=>a.locationId)),t||[]}))}applyPageLocationFilters(e,{query:t,customInternalDocumentId:a,customLocationId:i,customClientLocationId:d,fromCommentSidebar:m}){let u=e;try{if(u.filteredAnnotations=[],t)return u.filteredAnnotations=u.annotations?.slice(),u;if(a&&!i||m)return u.filteredAnnotations=ro(u.annotations?.slice(),u?.excludedLocationIds),u;let f=[],y=[];return i?(f.push(i),d&&y.push(d)):(f.push(u?.location?.locationId),f.push(...Object.values(u?.customLocations||[]).map(S=>S.locationId)),u?.location?.location?.id&&y.push(u?.location?.location?.id),y.push(...Object.values(u?.customLocations||{}).map(S=>S.location?.id).filter(S=>!!S))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,f,y),u.filteredAnnotations=ro(u.filteredAnnotations,u?.excludedLocationIds),u}catch(f){return this.loggingService.catch("Error in CommentService applyPageLocationFilters: ",f),u}}filterAnnotationsByLocationIds(e,t,a){try{return e.filter(i=>rr(i)||t.includes(i.locationId)||a?.includes(i?.location?.id)||t?.find(d=>d==i?.location?.id)||a?.find(d=>d==i?.locationId+""))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByLocations:",i),[]}}setAnnotationIndex(e){try{e.forEach((t,a)=>{t?.annotationId&&(t.annotationIndex=a+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}acceptsInOwnDocumentArea(e){return t=>this.docService.isAnnotationAllowedInArea(e?.metadata,t)!==!1}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;let a=rr(e);if(e.targetElementId){let d=a?this.findDocumentLevelTargetById(e):Lr(e.targetElementId,["id","data-id"]);if(d&&this.domService.isElementVisible(d)){let m=d.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_TYPE),u=!0;if(m)m==="popover"?u=!0:u=!1;else{let f=document.querySelector(`${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${Z.TAGS.VELT_INLINE_COMMENTS_SECTION}[${Z.ATTRIBUTES.TARGET_ELEMENT_ID}="${e.targetElementId}"]`);f&&d?.contains(f)&&(u=!1)}u?e.targetElement={xpath:this.domService.getXPath(d),fXpath:this.domService.getXPath(d,!0),cfXpath:this.domService.getXPath(d,!0,!0),topPercentage:e.targetElement?.topPercentage||50,leftPercentage:e.targetElement?.leftPercentage||90}:e.targetElement=null}else e.targetElement=null,a&&this.logHiddenDocumentLevelPin(e)}if(e.targetElement){e.position=null,e.ghostComment=null;let d=e.targetElement?.xpath,m=this.acceptsInOwnDocumentArea(e),u=null,f=e?.targetElement?.anchor,y=this.resolveIdScopedPinElement(e);if(y!==void 0)u=y;else if(f){let W=this.domService.resolveAnchorRecord(f,{accept:m,cacheKey:jh(e)});W?.element&&this.domService.isElementVisible(W.element)&&kn(W.element)&&!(a&&dp(W.matchedBy))&&(u=W.element)}else d&&(u=this.domService.getElementFromXPathAccepted(d,m),!this.domService.isXpathWithId(d)&&!a&&((!u||!this.domService.isElementVisible(u)||!m(u))&&e.targetElement?.cfXpath&&(d=e.targetElement?.cfXpath,u=this.domService.getElementFromXPathAccepted(d,m)),this.getDetectionStrategy()===xh.DYNAMIC_ID&&(!u||!this.domService.isElementVisible(u)||!m(u))&&(d=e.targetElement?.fXpath,d&&(u=this.domService.getElementFromXPathAccepted(d,m)))));let S=!!u&&this.domService.isElementVisible(u);a&&!S&&(u=null,this.logHiddenDocumentLevelPin(e)),S||t&&y===void 0&&!a&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=this.getGhostCommentTargetElement(e),e?.ghostComment?.targetElement?.xpath&&(u=this.domService.getElementFromXPath(e?.ghostComment?.targetElement?.xpath)));let j=!1;if(e?.locationId&&!a){let W=this.docService.getLocation();if(!fc({location:W?.location,locationId:W?.locationId},{location:e?.location,locationId:e?.locationId})){let $=this.docService.getAdditionLocationFromElement(u),H=$?this.docService.genarateLocationId($):void 0;e?.location?.id&&e?.location?.id===$?.id||H&&H===e?.locationId?j=!1:j=!0}}if(u&&this.docService.isAnnotationAllowedInArea(e?.metadata,u)===!1&&(j=!0,this.docService.logHiddenByArea("comment pin",e,u)),j&&(e.ghostComment=null),!j&&u&&kn(u)&&!u?.closest(".cdk-overlay-container")&&u?.getBoundingClientRect()){let $=this.popoverMode$?.value?0:e.targetElement?.topPercentage,H=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:q,width:ce}=EC(u);e.position={top:q*($||0)/100,left:ce*(H||0)/100};let fe=window.getComputedStyle(u).transform;if(fe&&fe!=="none")try{let le=new DOMMatrixReadOnly(fe),he=Math.sqrt(le.a*le.a+le.b*le.b)||1,xe=Math.sqrt(le.c*le.c+le.d*le.d)||1;(Math.abs(he-1)>.01||Math.abs(xe-1)>.01)&&(e.position.parentScaleX=he,e.position.parentScaleY=xe)}catch{}if(this.transformContext$.value){let{containerSelector:le,transforms:he}=this.transformContext$.value,xe=document.querySelector(le);xe&&xe.contains(u)&&(e.position.transformContext=he)}}!j&&t&&!e?.position&&!e?.ghostComment&&y===void 0&&!a&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}let i=!!e?.targetTextRange&&!e?.targetElement;t&&!i&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(a){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",a)}}addComment(Oe,Qe,Ke,xt,Ue){return Pe(this,arguments,function*(e,t,a,i,d,m=[],u,f,y,S,j,W,$,H,q,ce,fe,le,he,xe,ze,Ze,He,Xe){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let Ot=this.authService.getUser();if(Ot)if(Ot.isReadOnly||Ot.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{yield this.triggerAddCommentAnnotationDraftEvent();let Je=new At;fe&&(Je=g(g({},Je),fe)),Je.comments=[],fe?.comments?.length&&(Je.comments=fe.comments.map(Mt=>{let er=new Co;return er=g(g({},er),Mt),er.from=Ot,er.lastUpdated=new Date,er.createdAt=this.timestamp,er})),Je.from=Ot,Je.color=Je?.color||Z.DEFAULT_ANNOTATION_COLOR,Je.lastUpdated=this.timestamp,Je.createdAt=this.timestamp,Je.sourceId=q,Je.assignedTo=fe?.assignedTo||ce,Je.customList=fe?.customList||[],Ze&&(Je.targetElementId=Ze);let{topPositionX:wm,topPositionY:eu}=this.domService.getTopLeftPosition();Je.positionX=wm,Je.positionY=eu;let Dm=this.domService.getCurrentWindowSizeValue();if(Je.screenWidth=Dm.screenWidth,Je.screenHeight=Dm.screenHeight,Je.screenScrollHeight=Dm.screenScrollHeight,Je.taggedElementPath="",e){let{targetElement:Mt,skip:er}=this.buildNewPinTargetElement(e);if(er)return;Je.targetElement=Mt}if(t&&(Je.targetTextRange=t),Je?.targetElement?.xpath){let Mt=this.domService.getXPath(Je.targetElement.xpath);if(Mt){let er=Mt.iterateNext();er&&(kn(er)||(Je.targetElement=null))}}this.customFilterService.defaultStatus&&!fe?.status&&(Je.status=this.customFilterService.defaultStatus),Je.pageInfo=Dh(),Je.pageInfo&&(Je.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let fD=this.docService.getClientDocumentId(),bD=this.docService.getLocation()?.location;if(he&&(Je.context=this.preserveAccessSentinels(Je.context,he&&Cn(he)),Je.contextId=this.generateContextId(Je.context)),this.commentContextProvider!==null){let Mt=this.commentContextProvider(fD,bD),er=Mt instanceof Promise?yield Mt:Mt;er&&(Je.context=this.preserveAccessSentinels(Je.context,er&&Cn(er)),Je.contextId=this.generateContextId(Je.context),er?.commentType==="manual"&&(Je.commentType="manual",delete Je.targetElement))}if(i){Je.sourceId=i?.sourceId;let Mt=i?.targetElement,er=i?.commentData;if(Mt?.targetText)Je.targetTextRange={commonAncestorContainer:"/html/body",text:Mt.targetText,occurrence:Mt?.occurrence||1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(document.body)??void 0};else if(Mt?.elementId)if(Je.targetElementId=Mt.elementId,Mt?.selectAllContent)Je.selectAllContent=!!Mt?.selectAllContent;else{let zr=Lr(Mt.elementId,["id","data-id"]);zr?Je.targetElement={xpath:this.domService.getXPath(zr),fXpath:this.domService.getXPath(zr,!0),cfXpath:this.domService.getXPath(zr,!0,!0),anchor:this.domService.generateAnchorRecord(zr),topPercentage:50,leftPercentage:90}:Je.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",anchor:this.domService.generateAnchorRecord(document.body),topPercentage:50,leftPercentage:90}}i?.status&&(Je.status=i.status),i?.context&&(Je.context=this.preserveAccessSentinels(Je.context,i.context?Cn(i.context):i.context),Je.contextId=this.generateContextId(Je.context)),Je.comments||(Je.comments=[]);let bh=this.authService.getUser();er?.forEach(zr=>{let oc=new Co;oc.commentText=zr.commentText,oc.commentHtml=zr.commentHtml,oc.replaceContentHtml=zr.replaceContentHtml,oc.replaceContentText=zr.replaceContentText,oc.from=bh,Je.comments.push(oc)})}if(d&&(Je.isPageAnnotation=!0),m?.length&&(Je.comments=m),u&&(Je.commentType="chart",Je.metadata=u),y?.sourceId&&(Je.sourceId=y.sourceId),Je?.targetElement?.xpath&&!y){let Mt=this.domService.getElementFromXPath(Je.targetElement.xpath);Mt&&(y=this.getInlineCommentSectionConfig(Mt))}y?.targetInlineCommentElementId&&(Je.targetInlineCommentElementId=y?.targetInlineCommentElementId,Je.targetElementId=y.targetInlineCommentElementId,y?.config?.id&&(Je.inlineCommentSectionConfig=y?.config));let CD=!Je?.comments?.length,kD=!!(i?.openComment===!1||xe);this.getPrivateCommentMode()&&(Je?.iam||(Je.iam=new cC),Je.iam.accessMode=gr.PRIVATE),S&&(S.isDocumentLevel===!0&&(Je.isDocumentLevel=!0),Je.context=this.preserveAccessSentinels(Je.context,S.context?Cn(S.context):S.context),Je.commentType="manual",delete Je.targetElement,Je.contextId=this.generateContextId(Je.context)),j&&(Je.targetElementId=j.targetElementId,Je.targetElement=j.targetElement);let ab=this.getPrivateModeConfig();if(ab)try{let Mt=g({},ab),er=this.authService.getUser();if(Mt.type==="restricted"&&er?.userId&&(Mt=xo(Mt,er.userId)),Mt.type==="organizationPrivate"&&!Mt.organizationId&&!Mt.organizationIds?.length){let zr=this.docService.getOrganizationConfig();zr?.clientOrganizationId&&(Mt.organizationId=zr.clientOrganizationId)}let bh=qn(Mt,er?.userId);Je.context||(Je.context={}),Je.context._setAccessFields=bh,Je.visibilityConfig=Zn(Mt,er?.userId)}catch(Mt){this.loggingService.catch("Error building accessFields from privateModeConfig: ",Mt)}this.saveCommentToDb(Je,a,CD,kD,f,W,$,le,H,ze,He,Xe)}}catch(Ot){this.loggingService.catch("Error in CommentService addComment: ",Ot)}})}triggerAddCommentAnnotationDraftEvent(){return Pe(this,null,function*(){try{this.commentAnnotationContextDraft=null;let e={addContext:a=>{this.commentAnnotationContextDraft=a}},t=yield this.commentActionsService?.getAddCommentAnnotationDraftEventFromCommentAddEventData(e);t&&this.commentActionsService?.triggerAddCommentAnnotationDraftEvent(t)}catch(e){this.loggingService.catch("Error in CommentService triggerAddCommentAnnotationDraftEvent: ",e)}})}triggerAddCommentDraftEventOnAbandon(e,t){return Pe(this,null,function*(){try{if(!e||!t)return;let a=this.getAnnotationById(e),i=!!this.getFullComments(a).some(d=>d&&!d.isDraft);a&&i&&(yield this.commentActionsService?.triggerAddCommentDraftEventForAnnotation(a,t))}catch(a){this.loggingService.catch("Error in CommentService triggerAddCommentDraftEventOnAbandon: ",a)}})}willDeleteWholeAnnotation(e,t){try{let a=this.getFullComments(e);if(!a.length)return!1;let i=a.findIndex(d=>d?.commentId===t);return i<0?!1:i===0&&this.deleteThreadWithFirstComment$.value!==!1||a.length===1}catch(a){return this.loggingService.catch("Error in CommentService willDeleteWholeAnnotation: ",a),!1}}confirmDeleteCommentIfRequired(e,t){return Pe(this,null,function*(){try{let a=this.getFullComments(e);if(!a.length||!t)return!0;let i=a.findIndex(f=>f?.commentId===t?.commentId);if(i<0||!(i===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value))return!0;let m;return this.deleteReplyConfirmation$.value&&(i!==0||this.deleteThreadWithFirstComment$.value===!1)?m={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:m={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:m}).afterClosed().toPromise())}catch(a){return this.loggingService.catch("Error in CommentService confirmDeleteCommentIfRequired: ",a),!1}})}releaseDraftConfirmationRetention(e){try{if(!e||!this.draftConfirmationPendingAnnotationIds?.delete(e))return;let t=this.draftCommentAnnotationsByAnnotationId$?.value;if(!t||!(e in t))return;let a=JSON.parse(JSON.stringify(t));delete a[e],this.draftCommentAnnotationsByAnnotationId$.next(a)}catch(t){try{this.loggingService?.catch("Error in CommentService releaseDraftConfirmationRetention: ",t)}catch{}}}confirmDraftIfRequired(e,t){return Pe(this,null,function*(){try{if(!e?.isDraft||!this.draftConfirmation$?.value)return!0;t&&this.draftConfirmationPendingAnnotationIds?.add(t);let a=BD({composerContent:e?.commentText??"",attachmentCount:e?.attachments?.length??0,recordingCount:e?.recorders?.length??0});return!(yield this.confirmDraftDecision?.(a))}catch(a){try{this.loggingService?.catch("Error in CommentService confirmDraftIfRequired: ",a)}catch{}return!0}finally{this.releaseDraftConfirmationRetention(t)}})}confirmDraftDecision(e){return Pe(this,null,function*(){try{let t={title:"Delete Draft?",message:"Your comment will be permanently removed",previewText:e,yesButton:"Delete Draft",noButton:"Keep Draft",darkMode:this.commentContainerDarkMode$.value,variant:"draft",type:"draft"};return!!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],role:"alertdialog",ariaDescribedBy:"velt-confirm-dialog-message",data:t}).afterClosed().toPromise())}catch(t){return this.loggingService.catch("Error in CommentService confirmDraftDecision: ",t),!1}})}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let a;e.targetElement?a=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?a=Lr(e.targetElementId,["id","data-id"]):e.targetTextRange&&(a=this.domService.getElementFromTargetTextRange(e.targetTextRange));let i=this.docService.getAdditionLocationFromElement(a);if(i){let d=this.docService.addLocation({location:i,source:"internal"});d?.[0]&&(e.locationId=d[0].locationId,e.location=d[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?t=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?t=Lr(e.targetElementId,["id","data-id"]):e.targetTextRange&&(t=this.domService.getElementFromTargetTextRange(e.targetTextRange)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,a=!1,i=!1,d,m,u,f,y,S,j,W){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(ke.COMMENT)&&this.docService.getDocumentPaths$().pipe(qt($=>!!$),qo(1),Fe($=>(this.documentPaths=$,this.loggingService.log(this.documentPaths),this.commentDbReadyGate$().pipe(qo(1),Fe(H=>Pe(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let q=this.docService.getClientDocumentId(),ce=this.docService.getLocation()?.location;if(u)e.multiThreadAnnotationId=u;else if(this.getMultiThread()){let He=En();e.targetElementId&&(He=En(e.targetElementId),e?.location?.id?He=En([e?.location?.id,e.targetElementId]):e?.locationId&&(He=En([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=He}let fe={addContext:He=>{He.access&&(He.accessFields=Nm(He)),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_CONTEXT_TRIGGERED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode(),context:He}),e.context=He&&Cn(He),e.contextId=this.generateContextId(e.context),He?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&setTimeout(()=>{this.updateCommentAnnotationContext(e.annotationId,He)},200)},documentId:q,location:ce,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?fe.elementRef={xpath:e.targetElement.xpath}:fe.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(fe),this.commentAdded$.next(fe),y&&y(fe),fe?.annotation?.annotationId&&this.pendingAddCommentAnnotationData.set(fe.annotation.annotationId,fe),this.setLocationToCommentAnnotation(e);let le=this.getElementForCommentAnnotation(e),he=this.docService.getBaseMetadata("comment",{element:le,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!he?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=g(g({},e.metadata),he),S&&(e.metadata=g(g({},e.metadata),S)),d&&typeof d=="object"&&(e.locationId=f||this.docService.genarateLocationId(d),e.location=d,W||this.docService.addLocation({location:d})),a)window.localStorage.setItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let He=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);He&&JSON.parse(He).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let xe=e.comments,ze=JSON.parse(JSON.stringify(e));if(this.commentAnnotationContextDraft){let He=this.commentAnnotationContextDraft;this.commentAnnotationContextDraft=null,He.access&&(He.accessFields=Nm(He)),ze.context=this.preserveAccessSentinels(ze.context,He&&Cn(He))}if(this.applyContextAccessDefaults(ze),ze.visibilityConfig||Om(ze?.context?.accessFields).length===0&&(ze.visibilityConfig={type:"public"}),ze.position=null,t){ze.targetElement=null,ze.targetTextRange=null;let He={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?ke.MULTI_THREAD:ke.COMMENT},Xe=yield this.areaService?.generateAreaAnnotationId();ze.areaAnnotationId=Xe;let Oe=this.areaService?.addArea(void 0,t,He,Xe,{locationId:ze.locationId,location:ze.location},ze.context);Oe&&(ze.metadata=g(g({},ze.metadata),Oe?.metadata||{}))}!i&&!ze?.targetInlineCommentElementId&&!ze?.isPageAnnotation&&this.domService.toggleAnnotationSelection(ze,void 0,void 0,!1,void 0,m),e.targetTextRange&&sessionStorage.setItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),ze?.comments?.length?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:ze?.comments[0]?.commentId,commentThreadIndex:0,commentType:this.getCommentType(ze),commentMode:this.getCommentMode(),source:j??"internal",commentAnnotationCreatedAt:e.createdAt,taggedClientUserIds:ze?.comments[0]?.taggedUserContacts?.map(He=>He.contact?.userId).filter(He=>!!He),taggedSnippylyUserIds:ze?.comments[0]?.taggedUserContacts?.filter(He=>!!ze?.metadata?.apiKey&&!!He.contact?.userId).map(He=>Uu(ze.metadata.apiKey,He.contact.userId))}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(ze),commentMode:this.getCommentMode()});let Ze=this.getAnnotationNumber(e);Ze&&(ze.annotationNumber=Ze),ze?.comments?.length?ze.comments=[]:ze.isDraft=!0,ze?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(ze),ze?.context&&(ze.contextId=this.generateContextId(ze.context),ze.context?.commentType==="manual"&&(ze.commentType="manual",delete ze.targetElement)),xe?.length?this.saveComment(ze,{type:qe.NEWLY_ADDED,updatedComment:xe[0]}):this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:ze}))}})))))).subscribe(()=>{},$=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",$)})}catch($){this.loggingService.catch("Error in CommentService saveCommentToDb: ",$)}}saveMultiThreadCommentAnnotation(e){return Pe(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if((this.databaseService.getDbValue()||this.commonDbService?.isPortableBackendActive?.()===!0&&this.commonDbService?.portableCapabilityState?.(zu)!=="absent")&&t?.multiThread){let i={annotationId:e.multiThreadAnnotationId,targetElement:e.targetElement,targetElementId:e.targetElementId,targetInlineCommentElementId:e.targetInlineCommentElementId,inlineCommentSectionConfig:e.inlineCommentSectionConfig,areaAnnotationId:e.areaAnnotationId,targetTextRange:e.targetTextRange,from:e.from,locationId:e.locationId,location:e.location,sourceId:e.sourceId,type:"multiThread",metadata:e.metadata,context:e.context};delete e?.targetElement,delete e?.areaAnnotationId,delete e?.targetTextRange;let d=e?.metadata?.documentId||t?.documentId,m=e?.metadata?.organizationId||t?.organizationId,u=this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:m,documentId:d})?.find(f=>f.annotationId===e.multiThreadAnnotationId);if(!u){let f=yield this.readMultiThreadRow({documentId:d??"",organizationId:m??"",id:e.multiThreadAnnotationId});if(f.answered)u=f.data;else if(f.unserved)u=void 0;else{if(!e?.isDraft)return null;u=void 0}}if(u&&(u=JSON.parse(JSON.stringify(u)),delete u.from,i=g(g({},u),i)),i?.commentAnnotations||(i.commentAnnotations={}),i.commentAnnotations[e.annotationId]=!0,e?.isDraft)this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(b(g({},this.draftMultiThreadCommentAnnotationsByAnnotationId$.value),{[i.annotationId]:b(g({},i),{isDraft:!0})}));else{let f=this.getDraftMultiThreadAnnotationOfDocument(i.annotationId,d);if(f&&(i=g(g({},i),f)),delete i.isDraft,i.commentAnnotationsMap={},!i?.metadata?.documentId){i?.metadata||(i.metadata={});let j=this.docService.getBaseMetadata("multiThread");i.metadata=g(g({},i?.metadata),j)}let{documentId:y,organizationId:S}=i?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:i.annotationId,documentId:y,organizationId:S},data:JSON.parse(JSON.stringify(i)),callback:()=>{let j=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;j[e.annotationId]&&(delete j[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(j))}})}return i}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return Pe(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let a=yield this.getCommentCategory(t).toPromise();if(a){let i=this.docService.getDocumentPaths();if(i?.comment&&e?.annotationId){let d=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(m=>m.annotationId===e.annotationId);if(d||(d=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e.annotationId}})),d?.annotationId){let m=d;m.commentCategories=[a];let{documentId:u,organizationId:f}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(m);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:u,organizationId:f,metadata:{apiKey:this.configService.getApiKey(),organizationId:f,veltFolderId:m?.metadata?.veltFolderId,documentId:u}},data:JSON.parse(JSON.stringify(m))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=Oh(this.functions,Eh({url:this.endpointsService.getCloudFunctionUrl("chatgptCompletion"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return jn(t({messages:i,apiKey:this.configService.getApiKey(),sdkVersion:SC(),sdkType:this.configService.getSdkType(),numResponse:1})).pipe(Ee(d=>{if(d?.data){let m=d.data,u=m?.length?m[0]?.content?.trim():void 0;return u&&Object.keys(this.customCategoryMap).includes(u)?this.customCategoryMap[u]:void 0}else return}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),ye(void 0)}}applyListenerVisibilityPostFilter(e,t,a,i){try{let d=Pu(e,{userId:a,tokens:t});i&&(d=sC(d,i));let m=(e||[]).filter(u=>!d.includes(u));return m.length&&this.evictAnnotationsFromLocalCache(m.map(u=>u?.annotationId).filter(u=>!!u)),d}catch(d){return this.loggingService.catch("Error in CommentService applyListenerVisibilityPostFilter: ",d),e}}applyPortableQueryScopeFilter(e,t){try{let{kept:a,departed:i}=T0(e,t,d=>gC(d,t.scope));return i.length&&this.evictResultSetDepartures(i),a}catch(a){return this.loggingService.catch("Error in CommentService applyPortableQueryScopeFilter: ",a),e}}evictResultSetDepartures(e){try{if(!e?.length)return;this.evictAnnotationsFromLocalCache(e),this.evictProgressComments(e)}catch(t){this.loggingService.catch("Error in CommentService evictResultSetDepartures: ",t)}}evictAnnotationsFromLocalCache(e){try{if(!e?.length)return;let t=this.commentAnnotationById$?.value;if(t&&e.some(a=>a in t)){let a=g({},t);e.forEach(i=>{delete a[i]}),this.commentAnnotationById$.next(a)}}catch(t){this.loggingService.catch("Error in CommentService evictAnnotationsFromLocalCache: ",t)}}preserveAccessSentinels(e,t){try{return e&&typeof e=="object"&&t&&typeof t=="object"&&("_setAccessFields"in e&&!("_setAccessFields"in t)&&(t._setAccessFields=e._setAccessFields),"_replaceAccessFields"in e&&!("_replaceAccessFields"in t)&&(t._replaceAccessFields=e._replaceAccessFields)),t}catch(a){return this.loggingService.catch("Error in CommentService preserveAccessSentinels: ",a),t}}applyContextAccessDefaults(e){try{this.handleDirectAccessFieldsAssignment(e?.context)||(e?.context?.access?e.context.accessFields?.length||(e.context.accessFields=Nm(e.context)):Om(e?.context?.accessFields).length>0||(e?.context||(e.context={}),e.context.access={default:"velt"},e.context.accessFields=[...new Set([...e.context.accessFields||[],Z.DEFAULT_VELT_CONTEXT])]))}catch(t){this.loggingService.catch("Error in CommentService applyContextAccessDefaults: ",t)}}buildContextAccessFieldsPreservingVisibility(e,t){try{return Fu(e,Om(t))}catch(a){return this.loggingService.catch("Error in CommentService buildContextAccessFieldsPreservingVisibility: ",a),[...t||[]]}}handleDirectAccessFieldsAssignment(e){try{if(!e||typeof e!="object"||!("_setAccessFields"in e)&&!("_replaceAccessFields"in e))return!1;let t=!("_setAccessFields"in e),a=t?e._replaceAccessFields:e._setAccessFields;delete e._setAccessFields,delete e._replaceAccessFields;let i=Array.isArray(a)?a:[];if(!(!t&&Sh(e.access)))return delete e.access,delete e.accessFields,i.length>0&&(e.accessFields=i),!0;let m=i.length>0&&!i.includes(Z.DEFAULT_VELT_CONTEXT),u;return m?u=Fu(e,i):this.userPermissionService?.getIsContextEnabled()?u=Fu(e,i):u=[...new Set([...i,...Nm(e)])],u.length>0?e.accessFields=u:delete e.accessFields,!0}catch(t){return this.loggingService.catch("Error in CommentService handleDirectAccessFieldsAssignment: ",t),!1}}updateCommentAnnotationContext(e,t,a){return Pe(this,null,function*(){try{this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:a?.merge});let i=this.authService.getUser(),d=this.docService.getDocumentPaths();if(i&&d?.comment&&e){let m=this.getAnnotationById(e);if(typeof m=="object"&&(m=JSON.parse(JSON.stringify(m))),m||(m=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:d?.documentId??"",organizationId:d?.organizationId??"",id:e}})),m?.annotationId){let u=t,f=JSON.parse(JSON.stringify(m.context||{}));if(a?.merge&&(u=g(g({},f),t),Sh(f?.access)&&t?.access&&typeof t.access=="object"&&!Array.isArray(t.access))){let W=g(g({},f.access),t.access);Object.keys(W).forEach($=>{(W[$]===null||W[$]===void 0)&&delete W[$]}),u.access=Object.keys(W).length?W:{default:"velt"}}let y=this.handleDirectAccessFieldsAssignment(u);if(u&&"_setVisibilityConfig"in u&&(m.visibilityConfig=u._setVisibilityConfig,delete u._setVisibilityConfig),u&&typeof u=="object"&&!y)if("access"in t)if(t.access!==null&&t.access!==void 0)u.accessFields=this.buildContextAccessFieldsPreservingVisibility(u,f?.accessFields);else{delete u.access;let W=Om(f?.accessFields);W.length?u.accessFields=W:delete u.accessFields}else{if(!a?.merge)for(let W of OD)!(W in t)&&f?.[W]!==void 0&&(u[W]=f[W]);u.access!==null&&u.access!==void 0&&(u.accessFields=this.buildContextAccessFieldsPreservingVisibility(u,f?.accessFields))}let S={context:JSON.parse(JSON.stringify(u||{}))},j=!1;if(S?.context?.commentType==="manual"&&(S.commentType="manual",S.targetElement=null,m?.targetElement&&(m.targetElement=null,j=!0)),m.context=S.context?Cn(S.context):S.context,m.contextId=this.generateContextId(m.context),xn(f,u)&&!j)return Promise.resolve("Comment annotation context is already updated.");if(m?.comments?.length){m.lastUpdated=this.timestamp;let W=this.commentAnnotationById$?.value?.[e]?JSON.parse(JSON.stringify({context:this.commentAnnotationById$.value[e].context??null,contextId:this.commentAnnotationById$.value[e].contextId??null,visibilityConfig:this.commentAnnotationById$.value[e].visibilityConfig})):null;this.patchLocalAnnotationContext(e,m);let $=JSON.stringify({context:m.context??null,visibilityConfig:m.visibilityConfig}),{documentId:H,organizationId:q}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(m);return this.commonDbService.setData({feature:"comment",properties:{id:e,documentId:H,organizationId:q,metadata:{apiKey:this.configService.getApiKey(),organizationId:q,veltFolderId:m?.metadata?.veltFolderId,documentId:H}},data:JSON.parse(JSON.stringify(m)),callback:()=>{this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:S?.context,merge:a?.merge})},errorCallback:()=>{try{let ce=this.commentAnnotationById$?.value,fe=ce?.[e];if(!ce||!fe||!W||JSON.stringify({context:fe.context??null,visibilityConfig:fe.visibilityConfig})!==$)return;let he=b(g({},fe),{context:W.context,contextId:W.contextId});W.visibilityConfig===void 0?delete he.visibilityConfig:he.visibilityConfig=W.visibilityConfig,this.commentAnnotationById$.next(b(g({},ce),{[e]:he}))}catch(ce){this.loggingService.catch("Error reverting optimistic context patch: ",ce)}}})}else return this.draftCommentAnnotationsByAnnotationId$.value?.[e]?(this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e]:m})),Promise.resolve("Draft comment annotation context updated.")):(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:a?.merge,error:"Draft comment annotation not found."}),Promise.resolve("Draft comment annotation not found."))}else return this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:a?.merge,error:"Comment annotation not found in database."}),Promise.resolve("Comment annotation not found in database.")}}catch(i){return this.loggingService.catch("Error in CommentService updateCommentAnnotationContext: ",i),Promise.resolve("Error in CommentService updateCommentAnnotationContext.")}})}patchLocalAnnotationContext(e,t){try{let a=this.commentAnnotationById$?.value,i=a?.[e];if(!a||!i)return;let d=g(b(g({},i),{context:t?.context?JSON.parse(JSON.stringify(t.context)):i.context,contextId:t?.contextId??i.contextId}),t?.visibilityConfig!==void 0?{visibilityConfig:JSON.parse(JSON.stringify(t.visibilityConfig))}:{});this.commentAnnotationById$.next(b(g({},a),{[e]:d}))}catch(a){this.loggingService.catch("Error in CommentService patchLocalAnnotationContext: ",a)}}updateComment(e,t,a,i,d,m){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(ke.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let u=this.domService.getXPath(e.targetElement.xpath);if(u){let f=u.iterateNext();f&&(kn(f)||(e.targetElement=null))}}if(e?.type==="multiThread"){let u=JSON.parse(JSON.stringify(e));if(u.position=null,u.ghostComment=null,u?.context&&this.handleDirectAccessFieldsAssignment(u.context),!u?.metadata?.documentId){u?.metadata||(u.metadata={});let S=this.docService.getBaseMetadata("multiThread");u.metadata=g(g({},u?.metadata),S)}let{documentId:f,organizationId:y}=u?.metadata||{};a?this.commonDbService.updateData({feature:"multiThread",properties:{id:u.annotationId,documentId:f,organizationId:y},data:JSON.parse(JSON.stringify(u))}):this.commonDbService.setData({feature:"multiThread",properties:{id:u.annotationId,documentId:f,organizationId:y},data:JSON.parse(JSON.stringify(u))})}else{this.setSubscribedUsersDataInCommentAnnotation(e);let u=JSON.parse(JSON.stringify(e));if(u.position=null,u.ghostComment=null,u.lastUpdated=this.timestamp,u.status||(u.status=this.customFilterService.defaultStatus),delete u.resolved,delete u.inProgress,this.setLocationFromDocumentParams(u),u?.context&&this.handleDirectAccessFieldsAssignment(u.context),u?.annotationId?.startsWith("TEMP_COMPOSER_"))return;let f=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(f&&JSON.parse(f).annotationId===u.annotationId&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),u?.multiThreadAnnotationId&&!d&&this.saveMultiThreadCommentAnnotation(u).then(y=>{}),u?.comments?.length){if(delete u?.isDraft,u?.multiThreadAnnotationId&&this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[u?.multiThreadAnnotationId]&&this.saveMultiThreadCommentAnnotation(u),!u?.metadata?.documentId){u?.metadata||(u.metadata={});let W=this.docService.getBaseMetadata("comment");u.metadata=g(g({},u?.metadata),W)}let{documentId:y,organizationId:S}=u?.metadata||{},j=i?g({annotationData:i?.commentAnnotation,targetAnnotationData:i?.targetComment,actionType:i?.actionType,notificationSource:"comment"},i?.otherFields||{}):null;this.viewsService?.updateCommentAnnotationViews(u),this.commonDbService.setData({feature:"comment",properties:{id:u.annotationId,documentId:y,targetCommentId:m?.commentId,organizationId:S,metadata:{apiKey:this.configService.getApiKey(),organizationId:S,veltFolderId:u?.metadata?.veltFolderId,documentId:y}},extraData:j,data:JSON.parse(JSON.stringify(u)),callback:W=>Pe(this,null,function*(){if(i&&!W?.firestoreAvailable&&this.updateNotificationsDatabase(i.commentAnnotation,i.targetComment,i.actionType,i.otherFields||{}),this.getScreenshotEnabled()&&i?.actionType===qe.NEWLY_ADDED&&this.captureScreenshot(e),i?.actionType===qe.NEWLY_ADDED||i?.actionType===qe.ADDED)try{let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:u.annotationId,commentAnnotation:this.getCommentAnnotationForClient(u),metadata:$};this.commentActionsService?.triggerAction(ct.COMMENT_SAVED,H)}catch($){this.loggingService.catch("Error triggering commentSaved event: ",$)}})})}else this.draftCommentAnnotationsByAnnotationId$.next(b(g({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:u}))}}}catch(u){this.loggingService.catch("Error in CommentService updateComment: ",u)}}captureScreenshot(e){return Pe(this,null,function*(){try{if(this.getScreenshotEnabled()){let a=Oh(this.functions,Eh({url:this.endpointsService.getCloudFunctionUrl("screenshot"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i,d={source:"velt",sourceData:{commentAnnotation:e},eventType:"screenshot"};e?.areaAnnotationId&&(i=this.areaService?.getAnnotationById(e?.areaAnnotationId),i&&(d.sourceData||(d.sourceData={}),d.sourceData.areaAnnotation=i));let m=yield bC(d,this.authService.getUser()?.userId??"");yield a({veltData:m})}}catch(t){this.loggingService.catch("Error in CommentService captureScreenshot: ",t)}})}getDocumentIdAndOrganizationIdFromCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}setLocationFromDocumentParams(e){e?.documentParams&&(e.location=e.documentParams,delete e.documentParams),e?.documentParamsId&&(e.locationId=e.documentParamsId,delete e.documentParamsId)}deleteCommentPinAnnotations(e){return new Promise((t,a)=>Pe(this,null,function*(){try{let i=this.domService.getSelectedAnnotationsMap(),d=this.authService.getUser(),m=[];Object.keys(i).forEach(u=>{let f=i[u];["tag","recorder","rewriter","arrow","area","multiThread"].includes(f.type)||d&&f.from&&(d?.isAdmin||f.from.userId===d.userId)&&m.push(f)}),m?.length?(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DELETE_TRIGGERED,{triggerType:e,annotationId:m.map(u=>u.annotationId).join(),commentMode:this.getCommentMode()}),this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:{title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"}}).afterClosed().pipe(qo(1)).subscribe(u=>{try{u?(m.forEach(f=>Pe(this,null,function*(){yield this.deleteCommentPinAnnotation(f)})),setTimeout(()=>{document.querySelectorAll(`[${Z.SNIPPYLY_HIGHLIGHT}]`).forEach(y=>{this.domService.removeHighlightFromElement(y)}),t()},100)):t()}catch(f){a(f)}},u=>{a(u)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(i){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",i),a(i)}}))}deleteCommentPinAnnotation(e,t){return Pe(this,null,function*(){try{if(setTimeout(()=>{if(!this.draftConfirmationPendingAnnotationIds?.has(e?.annotationId)&&this.draftCommentAnnotationsByAnnotationId$?.value?.[e.annotationId]){let a=this.draftCommentAnnotationsByAnnotationId$.value;delete a[e.annotationId],this.draftCommentAnnotationsByAnnotationId$.next(a)}},50),e?.annotationId&&this.pendingAddCommentAnnotationData.delete(e.annotationId),this.authService.isFeatureAllowed(ke.COMMENT)){let a=!!(t||e.comments?.length);if(a&&this.updateNotificationsDatabase(e,null,qe.DELETED),e.comments?.forEach(i=>{i.reactionAnnotationIds&&i.reactionAnnotationIds.forEach(d=>{this.deleteReaction(d)})}),e?.annotationId){this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_DELETED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode()});let i=window.localStorage.getItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);i&&JSON.parse(i).annotationId===e.annotationId&&window.localStorage.removeItem(Z.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),this.areaService?.onDeleteTargetAnnotation(e?.annotationId,e?.areaAnnotationId);let d={type:"delete",annotation:null,targetAnnotationId:e.annotationId};this.commentUpdated$.next(d),e?.multiThreadAnnotationId&&(yield this.removeCommentAnnotationFromMultiThread(e)),this.commentAnnotationDeleted$.next(e);let{documentId:m,organizationId:u}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(e);if(e?.isDraft)return Promise.resolve();{let f={annotationData:e,targetAnnotationData:null,actionType:qe.DELETED,notificationSource:"comment",isAnnotationDelete:!0};return this.commonDbService.deleteData(g({feature:"comment",properties:{id:e.annotationId,documentId:m,organizationId:u,metadata:{apiKey:this.configService.getApiKey(),organizationId:u,veltFolderId:e?.metadata?.veltFolderId,documentId:m}},extraData:f},a?{hubNotification:this.buildCommentNotificationRawData(e,null,qe.DELETED)}:{}))}}else return Promise.resolve()}return Promise.resolve()}catch(a){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",a),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return Pe(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let a=this.docService.getDocumentPaths(),i=e?.metadata?.documentId,d=this.getMultiThreadAnnotationById(t,i?{documentId:i}:void 0);if(!d){let y=e?.metadata?.documentId||a?.documentId,S=e?.metadata?.organizationId||a?.organizationId,j=yield this.readMultiThreadRow({documentId:y,organizationId:S,id:t});if(!j.answered)return;d=j.data}let m=this.getDraftMultiThreadAnnotationOfDocument(t,i);if(d&&delete d?.commentAnnotations?.[e.annotationId],m&&(delete m?.commentAnnotations?.[e.annotationId],Object.keys(m?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(this.draftMultiThreadCommentAnnotationsByAnnotationId$.value))),!d)return;delete d.commentAnnotationsMap;let{documentId:u,organizationId:f}=this.getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(d);return Object.keys(d?.commentAnnotations||{}).length===0?(this.areaService?.onDeleteTargetAnnotation(d?.annotationId,d?.areaAnnotationId),this.multiThreadCommentAnnotationDeleted$.next(d),this.commonDbService.deleteData({feature:"multiThread",properties:{id:d?.annotationId,documentId:u,organizationId:f}})):this.commonDbService.setData({feature:"multiThread",properties:{id:d?.annotationId,documentId:u,organizationId:f},data:JSON.parse(JSON.stringify(d))})}}catch(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let a=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(a){let{documentId:i,organizationId:d}=t||{};if(i&&a.metadata?.documentId!==i||d&&a.metadata?.organizationId!==d)return}return a}catch(a){this.loggingService.catch("Error in CommentService getAnnotationById: ",a);return}}getBaseMetadataFromCommentAnnotationId(e){try{let t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}isCommentAnnotationCacheLoaded(){try{return this.commentAnnotationById$.value!=null}catch(e){return this.loggingService.catch("Error in CommentService isCommentAnnotationCacheLoaded: ",e),!1}}getDraftMultiThreadAnnotationOfDocument(e,t){let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[e];if(!(a&&t&&a.metadata?.documentId&&String(a.metadata.documentId)!==String(t)))return a}getMultiThreadAnnotationById(e,t){try{let a=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(a){let{documentId:i,organizationId:d}=t||{};if(i&&a.metadata?.documentId!==i||d&&a.metadata?.organizationId!==d)return}return a}catch(a){this.loggingService.catch("Error in CommentService getAnnotationById: ",a);return}}getBaseMetadataFromMultiThreadCommentAnnotationId(e){try{let t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let a=t?.targetElement?.xpath;if(a)return{xpath:a}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),a=document.getElementById(`comment-pin-container-${e}`);a||(a=document.querySelector(`[data-velt-id='${e}']`)),a||(a=document.querySelector(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),a&&(a.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");let a=e?this.getAnnotationById(e):void 0;a?this.domService.toggleAnnotationSelection(a,void 0,void 0,!0):this.domService.resetSelectedAnnotationsMap()}catch(a){this.loggingService.catch("Error in CommentService selectCommentByAnnotationId: ",a)}}enableAddCommentMode(){try{this.authService.isFeatureAllowed(ke.COMMENT)?!this.authService.isPlanExpired()&&this.iamService.hasRoleAny([gc.ADMIN,gc.COMMENTER])?(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!0)):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","User is not allowed to add comment."):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","Comment feature is not enabled.")}catch(e){this.loggingService.catch("Error in CommentService enableAddCommentMode: ",e)}}disableAddCommentMode(){this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADD_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!1)}addCommentModeChange(){return this.addCommentMode$.asObservable()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}enablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{persistentCommentMode:!0}}),this.persistentCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePersistentCommentMode: ",e)}}enableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteReplyConfirmation:!0}}),this.deleteReplyConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteReplyConfirmation: ",e)}}enableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{seenByUsers:!0}}),this.seenByUsers$.value===!0)return;this.seenByUsers$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSeenByUsers: ",e)}}disableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{seenByUsers:!1}}),this.seenByUsers$.value===!1)return;this.seenByUsers$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSeenByUsers: ",e)}}getSeenByUsers$(){return this.seenByUsers$.asObservable()}disableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteReplyConfirmation:!1}}),this.deleteReplyConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteReplyConfirmation: ",e)}}disablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{persistentCommentMode:!1}}),this.persistentCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePersistentCommentMode: ",e)}}persistentCommentModeChange(){return this.persistentCommentMode$.asObservable()}enablePersistentModeBanner(){this.persistentModeBanner$.next(!0)}disablePersistentModeBanner(){this.persistentModeBanner$.next(!1)}persistentModeBannerChange(){return this.persistentModeBanner$.asObservable()}setAssignToType(e){try{this.assignToType$.next(e.type)}catch(t){this.loggingService.catch("Error in CommentService setAssignToType: ",t)}}getAssignToType$(){return this.assignToType$.asObservable()}getAssignToType(){return this.assignToType$.value}setPageModeComposerContext(e){try{this.pageModeComposerContext$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPageModeComposerContext: ",t)}}clearPageModeComposerContext(){try{this.pageModeComposerContext$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearPageModeComposerContext: ",e)}}getPageModeComposerContext$(){return this.pageModeComposerContext$.asObservable()}getPageModeComposerContext(){return this.pageModeComposerContext$.value}enableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableContextInPageModeComposer: ",e)}}disableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableContextInPageModeComposer: ",e)}}getContextInPageModeComposer$(){return this.contextInPageModeComposer$.asObservable()}getContextInPageModeComposer(){return this.contextInPageModeComposer$.value}focusPageModeComposer(){try{this.focusPageModeComposer$.next()}catch(e){this.loggingService.catch("Error in CommentService focusPageModeComposer: ",e)}}getFocusPageModeComposer$(){return this.focusPageModeComposer$.asObservable()}showCommentIndex(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentIndex:e}}),this.showCommentIndex$.value===e)return;this.showCommentIndex$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}getShowCommentIndex(){return this.showCommentIndex$.asObservable()}enablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverMode:!0}}),this.popoverMode$.value===!0)return;this.popoverMode$.next(!0),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_POPOVER_MODE_ENABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService enablePopoverMode: ",e)}}disablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverMode:!1}}),this.popoverMode$.value===!1)return;this.popoverMode$.next(!1),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_POPOVER_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService disablePopoverMode: ",e)}}getPopoverMode(){try{return this.popoverMode$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverMode: ",e),!1}}getPopoverMode$(){return this.popoverMode$.asObservable()}enablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverTriangleComponent:!0}}),this.popoverTriangleComponent$.value===!0)return;this.popoverTriangleComponent$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePopoverTriangleComponent: ",e)}}disablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{popoverTriangleComponent:!1}}),this.popoverTriangleComponent$.value===!1)return;this.popoverTriangleComponent$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePopoverTriangleComponent: ",e)}}getPopoverTriangleComponent(){try{return this.popoverTriangleComponent$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverTriangleComponent: ",e),!1}}getPopoverTriangleComponent$(){return this.popoverTriangleComponent$.asObservable()}enableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftMode:!0}}),this.draftMode$.value===!0)return;this.draftMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftMode: ",e)}}disableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftMode:!1}}),this.draftMode$.value===!1)return;this.draftMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftMode: ",e)}}getDraftMode$(){return this.draftMode$.asObservable()}getDraftMode(){return this.draftMode$.value}enableDraftConfirmation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftConfirmation:!0}}),this.draftConfirmation$.value===!0)return;this.draftConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftConfirmation: ",e)}}disableDraftConfirmation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{draftConfirmation:!1}}),this.draftConfirmation$.value===!1)return;this.draftConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftConfirmation: ",e)}}getDraftConfirmation$(){return this.draftConfirmation$.asObservable()}getDraftConfirmation(){return this.draftConfirmation$.value}enableIdScopedAnchoring(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{idScopedAnchoring:!0}});let{documentIds:t,problem:a}=r0(e);a==="not-an-array"?console.warn("[Velt] enableIdScopedAnchoring: `documentIds` must be an array of document ids; id-scoped anchoring now applies to no document."):a==="dropped-entries"&&console.warn("[Velt] enableIdScopedAnchoring: `documentIds` entries that are not non-empty strings were ignored.");let i=this.idScopedAnchoringConfig$.value;if(i.enabled&&Ah(i.documentIds,t))return;Ah(i.documentIds,t)||(this.idScopedAnchoringScope=t?{clientIds:new Set(t),serverIds:new Set(t.map(d=>this.docService.generateDocumentId(d)))}:null),this.idScopedAnchoring$.value!==!0&&this.idScopedAnchoring$.next(!0),this.idScopedAnchoringVersion++,this.idScopedAnchoringConfig$.next({enabled:!0,documentIds:t})}catch(t){this.loggingService.catch("Error in CommentService enableIdScopedAnchoring: ",t)}}disableIdScopedAnchoring(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{idScopedAnchoring:!1}}),this.idScopedAnchoring$.value===!1)return;this.idScopedAnchoring$.next(!1),this.idScopedAnchoringVersion++,this.idScopedAnchoringConfig$.next(b(g({},this.idScopedAnchoringConfig$.value),{enabled:!1}))}catch(e){this.loggingService.catch("Error in CommentService disableIdScopedAnchoring: ",e)}}getIdScopedAnchoring$(){return this.idScopedAnchoring$.asObservable()}getIdScopedAnchoring(){return this.idScopedAnchoring$.value}getIdScopedAnchoringVersion(){return this.idScopedAnchoringVersion}getIdScopedAnchoringDocumentIds(){let e=this.idScopedAnchoringConfig$.value.documentIds;return e?[...e]:null}getIdScopedAnchoringConfig$(){return this.idScopedAnchoringConfig$.asObservable()}sameUnlessIdScopedAnchoringChanged(e){let t=this.idScopedAnchoringVersion;return(a,i)=>{let d=this.idScopedAnchoringVersion,m=d!==t;return t=d,!m&&e(a,i)}}distinctUnlessIdScopedAnchoringChanged(e){return t=>tu(()=>t.pipe(Gt(this.sameUnlessIdScopedAnchoringChanged(e))))}jsonSnapshotUnlessIdScopedAnchoringChanged(e){return t=>tu(()=>{let a=this.idScopedAnchoringVersion,i=null,d=m=>{try{let u=m;if(!u||typeof u!="object")return i=null,!1;let f={generation:u.dataGeneration,filtered:u.filteredAnnotations,textMap:u.textAnnotationsElementMap},y=!!i&&f.generation!==void 0&&i.generation===f.generation&&m0(i.filtered,f.filtered,LD)&&c0(i.textMap??null,f.textMap??null);return i=f,y}catch(u){return this.loggingService.catch("Error in CommentService jsonSnapshotUnlessIdScopedAnchoringChanged: ",u),i=null,!1}};return t.pipe(v0({select:e,knownUnchanged:d,forceEmit:()=>{try{let m=this.idScopedAnchoringVersion,u=m!==a;return a=m,u}catch(m){return this.loggingService.catch("Error in CommentService jsonSnapshotUnlessIdScopedAnchoringChanged forceEmit: ",m),!1}}}))})}withIdScopedAnchoringChanges(e,t){return e?t?e:Bt([e,this.getIdScopedAnchoringConfig$()]):t?ye(null):this.getIdScopedAnchoringConfig$()}buildNewPinTargetElement(e){let t=u=>{let f=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,y=>this.applyCommentPinTargetModifier(y),!0,void 0,u);if(this.getCommentToNearestAllowedElement()&&f?.xpath){let y=this.domService.getElementFromXPath(f.xpath);if(y&&!this.isElementInsideAllowedElements(y)){let S=this.getNearestAllowedElement(y);if(!S)return{targetElement:null,skip:!0};f.xpath=this.domService.getXPath(S,!1,!1,void 0,u),f.fXpath=this.domService.getXPath(S,!0),f.cfXpath=this.domService.getXPath(S,!0,!0),f.anchor=this.domService.generateAnchorRecord(S,u)}}return{targetElement:f,skip:!1}},a=this.getPinXPathOptions({element:e?.target}),i=t(a);if(i.skip||!i.targetElement?.xpath||!this.idScopedAnchoringScope)return i;let d=this.domService.getElementFromXPath(i.targetElement.xpath),m=d?this.getPinXPathOptions({element:d}):a;return!!m==!!a?i:t(m)}getPinXPathOptions(e){if(this.idScopedAnchoring$?.value){if(!this.idScopedAnchoringScope)return{ignoreGeneratedIds:!0};try{if(e?.annotation)return this.isIdScopedAnchoringForAnnotation(e.annotation)?{ignoreGeneratedIds:!0}:void 0;let t=e?.element instanceof Element?e.element:null,a=this.docService.getAdditionalDocumentIdFromElement(t)||this.docService.getDocumentPaths()?.clientDocumentId;return a&&this.idScopedAnchoringScope.clientIds.has(String(a))?{ignoreGeneratedIds:!0}:void 0}catch(t){this.loggingService.catch("Error in CommentService getPinXPathOptions: ",t);return}}}isIdScopedAnchoringForAnnotation(e){if(!this.idScopedAnchoring$?.value)return!1;let t=this.idScopedAnchoringScope;if(!t)return!0;let a=e?.metadata,i=a?.clientDocumentId;return i!=null&&i!==""?t.clientIds.has(String(i)):!!a?.documentId&&t.serverIds.has(String(a.documentId))}resolveIdScopedPinElement(e){try{let t=e?.targetElement;if(!t||!this.isIdScopedAnchoringForAnnotation(e))return;let a=this.domService.resolveIdScopedTarget(t);return a?.applicable?a.element&&kn(a.element)?a.element:null:void 0}catch(t){this.loggingService.catch("Error in CommentService resolveIdScopedPinElement: ",t);return}}enableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textMode:!0}}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_TEXT_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!0)return;this.textCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextComments: ",e)}}disableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textMode:!1}}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_TEXT_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!1)return;this.textCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextComments: ",e)}}getTextCommentMode$(){return this.textCommentMode$.asObservable()}isUserGlobalContact$(){return this.contactService.isUserGlobalContact$()}isSidebarOpenedByCustomTrigger(){try{return this.sidebarOpenedByCustomTrigger$.value}catch(e){return this.loggingService.catch("Error in CommentService isSidebarOpenedByCustomTrigger: ",e),!1}}requestSidebarFocus(e){let t=typeof e=="string"?e.trim():"";t&&ip()&&this.sidebarFocusRequest$.next({annotationId:t})}watchDocumentChangesForSidebarFocus(e){let t=null;e.subscribe(a=>{try{let i=(a||[]).map(m=>m?.documentId).filter(Boolean).sort(),d=i.length?JSON.stringify(i):null;d&&t&&d!==t&&this.consumeSidebarFocus(),d&&(t=d)}catch(i){this.loggingService.catch("Error in CommentService watchDocumentChangesForSidebarFocus: ",i)}})}consumeSidebarFocus(){this.sidebarFocusRequest$.value&&this.sidebarFocusRequest$.next(null)}getSidebarFocusRequest$(){return this.sidebarFocusRequest$.asObservable()}setSidebarVisibility(e,t=!1,a=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(ip()||document.querySelector(Z.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):(this.consumeSidebarFocus(),this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> or <${Z.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`)),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||a)&&(this.sidebarVisible$.next(e),this.consumeSidebarFocus(),this.sidebarOpenedByCustomTrigger$.next(!1),this.clearPageModeComposerContext()),e?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_OPENED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_CLOSED,{commentMode:this.getCommentMode()})}catch{this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1),this.sidebarVisible$.value||this.clearPageModeComposerContext()):(ip()||document.querySelector(Z.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(Z.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarVisible$.value?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"closed"}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"opened"})):this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> or <${Z.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${Z.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}getSidebarVisibility$(){return this.sidebarVisible$.asObservable()}disableFloatingComments(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{floatingCommentDialog:!e}}),this.floatingCommentsEnabled$.value===!e)return;this.floatingCommentsEnabled$.next(!e)}catch(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}showFloatingComments$(){return this.floatingCommentsEnabled$.asObservable()}showFloatingComments(){return this.floatingCommentsEnabled$.value}setModeratorMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{moderatorMode:e}}),this.moderatorMode$.value===e)return;this.moderatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}getModeratorMode(){return this.moderatorMode$.value}getModeratorMode$(){return this.moderatorMode$.asObservable()}setStreamMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{streamMode:e}}),this.streamMode$.value===e)return;this.streamMode$.next(e),e?this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STREAM_MODE_ENABLED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STREAM_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}getStreamMode(){return this.streamMode$.value}getStreamMode$(){return this.streamMode$.asObservable()}getEnableDialogOnHover(){return this.enableDialogOnHover$.value}getEnableDialogOnHover$(){return this.enableDialogOnHover$.asObservable()}setEnableDialogOnHover(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogOnHover:e}}),this.enableDialogOnHover$.value===e)return;this.enableDialogOnHover$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}getEnableDialogOnTargetElementClick(){return this.enableDialogOnTargetElementClick$.value}getEnableDialogOnTargetElementClick$(){return this.enableDialogOnTargetElementClick$.asObservable()}setEnableDialogOnTargetElementClick(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogOnTargetElementClick:e}}),this.enableDialogOnTargetElementClick$.value===e)return;this.enableDialogOnTargetElementClick$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}getEnablePriority(){return this.enablePriority$.value}getEnablePriority$(){return this.enablePriority$.asObservable()}setEnablePriority(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{priority:e}}),this.enablePriority$.value===e)return;this.enablePriority$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}getEnableStatus(){return this.enableStatus$.value}getEnableStatus$(){return this.enableStatus$.asObservable()}setEnableStatus(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{status:e}}),this.getEnableStatus()===e)return;this.enableStatus$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}getEnableVisibilityOptions(){return this.visibilityOptions$.value}getEnableVisibilityOptions$(){return this.visibilityOptions$.asObservable()}setEnableVisibilityOptions(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{visibilityOptions:e}}),this.visibilityOptions$.value===e)return;this.visibilityOptions$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableVisibilityOptions: ",t)}}getEnableResolve(){return this.enableResolve$.value}getEnableResolve$(){return this.enableResolve$.asObservable()}setEnableResolve(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveButton:e}}),this.getEnableResolve()===e)return;this.enableResolve$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}getEnableGhostComments(){return this.enableGhostComments$.value}getEnableGhostComments$(){return this.enableGhostComments$.asObservable()}enableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostComments:!0}}),this.enableGhostComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGhostComments: ",e)}}disableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostComments:!1}}),this.enableGhostComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGhostComments: ",e)}}getEnableGhostCommentsMessage(){return this.enableGhostCommentsMessage$.value}getEnableGhostCommentsMessage$(){return this.enableGhostCommentsMessage$.asObservable()}enableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostCommentsIndicator:!0}}),this.enableGhostCommentsMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowGhostCommentsMessage: ",e)}}disableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{ghostCommentsIndicator:!1}}),this.enableGhostCommentsMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowGhostCommentsMessage: ",e)}}enableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inboxMode:!0}}),this.inboxMode$.value===!0)return;this.inboxMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInboxMode: ",e)}}disableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inboxMode:!1}}),this.inboxMode$.value===!1)return;this.inboxMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInboxMode: ",e)}}getInboxMode(){return this.inboxMode$.value}getInboxMode$(){return this.inboxMode$.asObservable()}setEnableAutoCategorize(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{autoCategorize:e}}),this.enableAutoCategorize$.value===e)return;this.enableAutoCategorize$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}getEnableAutoCategorize(){return this.enableAutoCategorize$.value}getEnableAutoCategorize$(){return this.enableAutoCategorize$.asObservable()}setCommentContainerDarkMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{darkMode:e}}),this.commentContainerDarkMode$.value===e)return;this.commentContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}getCommentContainerDarkMode(){return this.commentContainerDarkMode$.asObservable()}getSuggestionMode(){return this.suggestionMode$.value}getSuggestionMode$(){return this.suggestionMode$.asObservable()}setSuggestionMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{suggestionMode:e}}),this.getSuggestionMode()===e)return;this.suggestionMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}getMobileMode(){return this.mobileMode$.value}getMobileMode$(){return this.mobileMode$.asObservable()}setMobileMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{mobileMode:e}}),this.getMobileMode()===e)return;this.mobileMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}enableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inlineCommentMode:!0}}),this.inlineCommentMode$.value===!0)return;this.inlineCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInlineCommentMode: ",e)}}disableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{inlineCommentMode:!1}}),this.inlineCommentMode$.value===!1)return;this.inlineCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInlineCommentMode: ",e)}}getInlineCommentMode(){return this.inlineCommentMode$.value}getInlineCommentMode$(){return this.inlineCommentMode$.asObservable()}enableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{minimap:!0}}),this.minimap$.value===!0)return;this.minimap$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMinimap: ",e)}}disableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{minimap:!1}}),this.minimap$.value===!1)return;this.minimap$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMinimap: ",e)}}getMinimap(){return this.minimap$.value}getMinimap$(){return this.minimap$.asObservable()}showCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentsOnDom:!0}}),this.commentsOnDom$.value===!0)return;this.commentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showCommentsOnDom: ",e)}}hideCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentsOnDom:!1}}),this.commentsOnDom$.value===!1)return;this.commentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideCommentsOnDom: ",e)}}getCommentsOnDom(){return this.commentsOnDom$.value}getCommentsOnDom$(){return this.commentsOnDom$.asObservable()}enableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentTool:!0}}),this.commentToolEnabled$.value===!0)return;this.commentToolEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentTool: ",e)}}disableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentTool:!1}}),this.commentToolEnabled$.value===!1)return;this.commentToolEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentTool: ",e)}}getCommentTool(){return this.commentToolEnabled$.value}getCommentTool$(){return this.commentToolEnabled$.asObservable()}setTotalMediaLength(e){try{if(this.totalMediaLength$.value===e)return;this.totalMediaLength$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}getTotalMediaLength(){return this.totalMediaLength$.value}getTotalMediaLength$(){return this.totalMediaLength$.asObservable()}enableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarUrlNavigation:!0}}),this.sidebarUrlNavigationEnabled$.value===!0)return;this.sidebarUrlNavigationEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarUrlNavigation: ",e)}}disableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarUrlNavigation:!1}}),this.sidebarUrlNavigationEnabled$.value===!1)return;this.sidebarUrlNavigationEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarUrlNavigation: ",e)}}getSidebarUrlNavigation(){return this.sidebarUrlNavigationEnabled$.value}getSidebarUrlNavigation$(){return this.sidebarUrlNavigationEnabled$.asObservable()}setDetectionStrategy(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{detectionStrategy:e}}),this.detectionStrategy$.value===e)return;this.detectionStrategy$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}getDetectionStrategy(){return this.detectionStrategy$.value}getDetectionStrategy$(){return this.detectionStrategy$.asObservable()}enableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonOnCommentDialog:!0}}),this.sidebarButtonOnCommentDialogVisible$.value===!0)return;this.sidebarButtonOnCommentDialogVisible$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarButtonOnCommentDialog: ",e)}}disableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonOnCommentDialog:!1}}),this.sidebarButtonOnCommentDialogVisible$.value===!1)return;this.sidebarButtonOnCommentDialogVisible$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarButtonOnCommentDialog: ",e)}}getSidebarButtonOnCommentDialogVisibility(){return this.sidebarButtonOnCommentDialogVisible$.value}getSidebarButtonOnCommentDialogVisibility$(){return this.sidebarButtonOnCommentDialogVisible$.asObservable()}onSidebarButtonOnCommentDialogClick(){this.sidebarButtonOnCommentDialogClick$.next()}getSidebarButtonOnCommentDialogClick$(){return this.sidebarButtonOnCommentDialogClick$.asObservable()}enableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceIndicatorOnCommentPins:!0}}),this.deviceIndicatorOnCommentPins$.value===!0)return;this.deviceIndicatorOnCommentPins$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeviceIndicatorOnCommentPins: ",e)}}disableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceIndicatorOnCommentPins:!1}}),this.deviceIndicatorOnCommentPins$.value===!1)return;this.deviceIndicatorOnCommentPins$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeviceIndicatorOnCommentPins: ",e)}}getDeviceIndicatorOnCommentPins(){return this.deviceIndicatorOnCommentPins$.value}getDeviceIndicatorOnCommentPins$(){return this.deviceIndicatorOnCommentPins$.asObservable()}onSidebarCommentClick(e){this.sidebarCommentClick$.next(e)}getSidebarCommentClick$(){return this.sidebarCommentClick$.asObservable()}onCommentNavigationButtonClick(e){this.commentNavigationButtonClick$.next(e)}getCommentNavigationButtonClick$(){return this.commentNavigationButtonClick$.asObservable()}addBubbleCommentAnnotationIds(e){try{let a=[...this.bubbleCommentAnnotationIds$.value||[],...e],i=[...new Set(a)];this.bubbleCommentAnnotationIds$.next(i)}catch(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}getBubbleCommentAnnotationIds(){return this.bubbleCommentAnnotationIds$.value}getBubbleCommentAnnotationIds$(){return this.bubbleCommentAnnotationIds$.asObservable()}removeBubbleCommentAnnotationIds(e){try{let a=(this.bubbleCommentAnnotationIds$.value||[]).filter(i=>!e.includes(i));this.bubbleCommentAnnotationIds$.next(a)}catch(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}getSignInButton(){return this.enableSignInButton$.value}getSignInButton$(){return this.enableSignInButton$.asObservable()}onSignInClick(){this.onSignInClick$.next()}getSignInButtonClick$(){return this.onSignInClick$.asObservable()}enableUpgradeButton(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{upgradeButton:e}}),this.enableUpgradeButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}getUpgradeButton(){return this.enableUpgradeButton$.value}getUpgradeButton$(){return this.enableUpgradeButton$.asObservable()}onUpgradeClick(){this.onUpgradeClick$.next()}getUpgradeButtonClick$(){return this.onUpgradeClick$.asObservable()}openSidebar(){this.openSidebar$.next()}getOpenSidebar$(){return this.openSidebar$.asObservable()}enableAttachment(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachments:e}}),this.enableAttachment$.value===e)return;this.enableAttachment$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}getEnableAttachment$(){return this.enableAttachment$.asObservable()}enableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentDownload:!0}}),this.enableAttachmentDownload$.value===!0)return;this.enableAttachmentDownload$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentDownload: ",e)}}disableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentDownload:!1}}),this.enableAttachmentDownload$.value===!1)return;this.enableAttachmentDownload$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentDownload: ",e)}}getEnableAttachmentDownload$(){return this.enableAttachmentDownload$.asObservable()}getEnableAttachmentDownload(){return this.enableAttachmentDownload$.value}enableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatOptions:!0}}),this.enableFormatOptions$.value===!0)return;this.enableFormatOptions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFormatOptions: ",e)}}disableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatOptions:!1}}),this.enableFormatOptions$.value===!1)return;this.enableFormatOptions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFormatOptions: ",e)}}getEnableFormatOptions$(){return this.enableFormatOptions$.asObservable()}setFormatConfig(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{formatConfig:e}}),this.formatConfig$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setFormatConfig: ",t)}}getFormatConfig$(){return this.formatConfig$.asObservable()}setAllowedRecordings(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordings:e}}),e?.includes("all")?this.allowedRecordings$.next(["audio","video","screen"]):e?.includes("none")?this.allowedRecordings$.next([]):this.allowedRecordings$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}getAllowedRecordings(){return this.allowedRecordings$.value}getAllowedRecordings$(){return this.allowedRecordings$.asObservable()}enableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{reactions:!0}}),this.enableReactions$.value===!0)return;this.enableReactions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReactions: ",e)}}disableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{reactions:!1}}),this.enableReactions$.value===!1)return;this.enableReactions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReactions: ",e)}}getEnableReactions(){return this.enableReactions$.value}getEnableReactions$(){return this.enableReactions$.asObservable()}enableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!0)return;this.enableAnonymousEmail$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAnonymousEmail: ",e)}}disableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!1)return;this.enableAnonymousEmail$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAnonymousEmail: ",e)}}getEnableAnonymousEmail(){return this.enableAnonymousEmail$.value}getEnableAnonymousEmail$(){return this.enableAnonymousEmail$.asObservable()}addCommentOnElement(e){this.addComment(void 0,void 0,void 0,e)}enablePrivateCommentMode(){return Pe(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.privateCommentModeRequested=!0,this.privateCommentAllowed$.value?this.applyRequestedPrivateCommentMode():this.loggingService.logsEnabled&&console.warn("You are not allowed to enable private comment mode yet. It turns on once you are an admin or a member of the organization.")}catch(e){this.loggingService.catch("Error in CommentService enablePrivateCommentMode: ",e)}})}disablePrivateCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateCommentMode:!1}}),this.privateCommentModeRequested=!1,this.privateCommentMode$.value===!1)return;this.privateCommentMode$.next(!1),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_DISABLED)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateCommentMode: ",e)}}applyRequestedPrivateCommentMode(){try{if(!this.privateCommentModeRequested||(this.privateCommentModeRequested=!1,this.privateCommentMode$.value===!0))return;this.privateCommentMode$.next(!0),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_ENABLED)}catch(e){this.loggingService.catch("Error in CommentService applyRequestedPrivateCommentMode: ",e)}}getPrivateCommentMode(){return this.privateCommentMode$.value}getPrivateCommentMode$(){return this.privateCommentMode$.asObservable()}isPrivateCommentAllowed(){return this.privateCommentAllowed$.value}isPrivateCommentAllowed$(){return this.privateCommentAllowed$.asObservable()}enablePrivateMode(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateModeConfig:e}}),!e?.type){this.loggingService.catch("enablePrivateMode: type is required in config");return}this.privateModeConfig$.next(g({},e))}catch(t){this.loggingService.catch("Error in CommentService enablePrivateMode: ",t)}}disablePrivateMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{privateModeConfig:null}}),this.privateModeConfig$.value===null)return;this.privateModeConfig$.next(null)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateMode: ",e)}}getPrivateModeConfig(){return this.privateModeConfig$.value}getPrivateModeConfig$(){return this.privateModeConfig$.asObservable()}enableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{scrollToComment:!0}}),this.scrollToComment$.value===!0)return;this.scrollToComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScrollToComment: ",e)}}disableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{scrollToComment:!1}}),this.scrollToComment$.value===!1)return;this.scrollToComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScrollToComment: ",e)}}getScrollToComment(){return this.scrollToComment$.value}getScrollToComment$(){return this.scrollToComment$.asObservable()}showScreenSizeInfo(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deviceInfo:e}}),this.showScreenSizeInfo$.value===e)return;this.showScreenSizeInfo$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}getShowScreenSizeInfo$(){return this.showScreenSizeInfo$.asObservable()}enableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{userMentions:!0}}),this.userMentions$.value===!0)return;this.userMentions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableUserMentions: ",e)}}disableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{userMentions:!1}}),this.userMentions$.value===!1)return;this.userMentions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableUserMentions: ",e)}}getUserMentions(){return this.userMentions$.value}getUserMentions$(){return this.userMentions$.asObservable()}enablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!0)return;this.paginatedContactList$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePaginatedContactList: ",e)}}disablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!1)return;this.paginatedContactList$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePaginatedContactList: ",e)}}getPaginatedContactList(){return this.paginatedContactList$.value}getPaginatedContactList$(){return this.paginatedContactList$.asObservable()}enableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteOnBackspace:!0}}),this.deleteOnBackspace$.value===!0)return;this.deleteOnBackspace$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteOnBackspace: ",e)}}disableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteOnBackspace:!1}}),this.deleteOnBackspace$.value===!1)return;this.deleteOnBackspace$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteOnBackspace: ",e)}}getDeleteOnBackspace(){return this.deleteOnBackspace$.value}getDeleteOnBackspace$(){return this.deleteOnBackspace$.asObservable()}enableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{hotkey:!0}}),this.hotkeyEnabled$.value===!0)return;this.hotkeyEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableHotkey: ",e)}}disableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{hotkey:!1}}),this.hotkeyEnabled$.value===!1)return;this.hotkeyEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableHotkey: ",e)}}enableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingSummary:!0}}),this.recordingSummaryEnabled$.value===!0)return;this.recordingSummaryEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRecordingSummary: ",e)}}disableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingSummary:!1}}),this.recordingSummaryEnabled$.value===!1)return;this.recordingSummaryEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRecordingSummary: ",e)}}getRecordingSummaryEnabled(){return this.recordingSummaryEnabled$.value}getRecordingSummaryEnabled$(){return this.recordingSummaryEnabled$.asObservable()}setUnreadIndicatorMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{unreadIndicatorMode:e}}),this.unreadIndicatorMode$.value===e)return;this.unreadIndicatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}getUnreadIndicatorMode(){return this.unreadIndicatorMode$.value}getUnreadIndicatorMode$(){return this.unreadIndicatorMode$.asObservable()}setComposerMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setComposerMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{composerMode:e}}),this.composerMode$.value===e)return;this.composerMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}getComposerMode(){return this.composerMode$.value}getComposerMode$(){return this.composerMode$.asObservable()}enableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{enterKeyToSubmit:!0}}),this.enterKeyToSubmit$.value===!0)return;this.enterKeyToSubmit$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableEnterKeyToSubmit: ",e)}}disableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{enterKeyToSubmit:!1}}),this.enterKeyToSubmit$.value===!1)return;this.enterKeyToSubmit$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableEnterKeyToSubmit: ",e)}}getEnterKeyToSubmit(){return this.enterKeyToSubmit$.value}getEnterKeyToSubmit$(){return this.enterKeyToSubmit$.asObservable()}enablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinShadowDom:!0}}),this.pinShadowDOM$.value===!0)return;this.pinShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinShadowDOM: ",e)}}disablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinShadowDom:!1}}),this.pinShadowDOM$.value===!1)return;this.pinShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinShadowDOM: ",e)}}getPinShadowDOM(){return this.pinShadowDOM$.value}getPinDarkMode(){return this.pinDarkMode$.value}getPinDarkMode$(){return this.pinDarkMode$.asObservable()}getTextCommentToolDarkMode(){return this.textCommentToolDarkMode$.value}getTextCommentToolDarkMode$(){return this.textCommentToolDarkMode$.asObservable()}getTextCommentToolbarDarkMode(){return this.textCommentToolbarDarkMode$.value}getTextCommentToolbarDarkMode$(){return this.textCommentToolbarDarkMode$.asObservable()}getPinShadowDOM$(){return this.pinShadowDOM$.asObservable()}getTextCommentToolShadowDOM$(){return this.textCommentToolShadowDOM$.asObservable()}getTextCommentToolbarShadowDOM$(){return this.textCommentToolbarShadowDOM$.asObservable()}enableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogShadowDom:!0}}),this.dialogShadowDOM$.value===!0)return;this.dialogShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDialogShadowDOM: ",e)}}enableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarShadowDom:!0}}),this.textCommentToolbarShadowDOM$.value===!0)return;this.textCommentToolbarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarShadowDOM: ",e)}}disableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarShadowDom:!1}}),this.textCommentToolbarShadowDOM$.value===!1)return;this.textCommentToolbarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarShadowDOM: ",e)}}enableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolShadowDom:!0}}),this.textCommentToolShadowDOM$.value===!0)return;this.textCommentToolShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolShadowDOM: ",e)}}disableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolShadowDom:!1}}),this.textCommentToolShadowDOM$.value===!1)return;this.textCommentToolShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolShadowDOM: ",e)}}enableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolDarkMode:!0}}),this.textCommentToolDarkMode$.value===!0)return;this.textCommentToolDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolDarkMode: ",e)}}disableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolDarkMode:!1}}),this.textCommentToolDarkMode$.value===!1)return;this.textCommentToolDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolDarkMode: ",e)}}enableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarDarkMode:!0}}),this.textCommentToolbarDarkMode$.value===!0)return;this.textCommentToolbarDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarDarkMode: ",e)}}disableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{textCommentToolbarDarkMode:!1}}),this.textCommentToolbarDarkMode$.value===!1)return;this.textCommentToolbarDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarDarkMode: ",e)}}enablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDarkMode:!0}}),this.pinDarkMode$.value===!0)return;this.pinDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDarkMode: ",e)}}disablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDarkMode:!1}}),this.pinDarkMode$.value===!1)return;this.pinDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDarkMode: ",e)}}disableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{dialogShadowDom:!1}}),this.dialogShadowDOM$.value===!1)return;this.dialogShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDialogShadowDOM: ",e)}}getDialogShadowDOM(){return this.dialogShadowDOM$.value}getDialogShadowDOM$(){return this.dialogShadowDOM$.asObservable()}setDialogShadowDOMExplicit(e){this.dialogShadowDOMExplicit$.next(e)}getDialogShadowDOMExplicit$(){return this.dialogShadowDOMExplicit$.asObservable()}enableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarShadowDOM:!0}}),this.sidebarShadowDOM$.value===!0)return;this.sidebarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarShadowDOM: ",e)}}disableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarShadowDOM:!1}}),this.sidebarShadowDOM$.value===!1)return;this.sidebarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarShadowDOM: ",e)}}getSidebarShadowDOM(){return this.sidebarShadowDOM$.value}getSidebarShadowDOM$(){return this.sidebarShadowDOM$.asObservable()}enableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{changeDetectionInCommentMode:!0}}),this.changeDetectionInCommentMode$.value===!0)return;this.changeDetectionInCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableChangeDetectionInCommentMode: ",e)}}disableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{changeDetectionInCommentMode:!1}}),this.changeDetectionInCommentMode$.value===!1)return;this.changeDetectionInCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableChangeDetectionInCommentMode: ",e)}}getChangeDetectionInCommentMode(){return this.changeDetectionInCommentMode$.value}getChangeDetectionInCommentMode$(){return this.changeDetectionInCommentMode$.asObservable()}showResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolvedCommentsOnDom:!0}}),this.resolvedCommentsOnDom$.value===!0)return;this.resolvedCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showResolvedCommentsOnDom: ",e)}}hideResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolvedCommentsOnDom:!1}}),this.resolvedCommentsOnDom$.value===!1)return;this.resolvedCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideResolvedCommentsOnDom: ",e)}}getResolvedCommentsOnDom(){return this.resolvedCommentsOnDom$.value}enableLazyLoadResolvedComments(){try{this.installLazyLoadResolvedCommentsProvider();let e=Um(this.documentPaths);if(e&&this.resolvedUnlockedDocumentKey===e){this.loggingService.catch("[lazyLoadResolvedComments] enabled, but resolved comments were already unlocked this session; takes effect on the next page load.",null,void 0,!0),this.lazyLoadResolvedComments$.next(!0);return}if(this.lazyLoadResolvedComments$.value===!0)return;this.lazyLoadResolvedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLazyLoadResolvedComments: ",e)}}disableLazyLoadResolvedComments(){try{if(this.lazyLoadResolvedComments$.value===!1)return;this.lazyLoadResolvedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLazyLoadResolvedComments: ",e)}}isResolvedUnlockedForCurrentDocument(){try{let e=Um(this.documentPaths);return!!e&&this.resolvedUnlockedDocumentKey===e}catch(e){return this.loggingService.catch("Error in CommentService isResolvedUnlockedForCurrentDocument: ",e),!0}}getLazyLoadResolvedComments(){return this.lazyLoadResolvedComments$.value}installLazyLoadResolvedCommentsProvider(){try{this.customFilterService?.setLazyLoadResolvedCommentsProvider?.(()=>this.lazyLoadResolvedComments$.value)}catch(e){this.loggingService.catch("Error in CommentService installLazyLoadResolvedCommentsProvider: ",e)}}publishResolvedIntent(e){try{this.defaultSidebarResolvedIntent=!!e,this.resolvedIntentFromSidebar$.next(!!e||this.anyNamedSidebarResolvedIntent())}catch(t){this.loggingService.catch("Error in CommentService publishResolvedIntent: ",t)}}anyNamedSidebarResolvedIntent(){if(!this.namedSidebarResolvedIntents?.size)return!1;for(let e of this.namedSidebarResolvedIntents.values())if(e)return!0;return!1}publishNamedSidebarResolvedIntent(e,t){try{if(typeof e!="string"||!e)return;t?this.namedSidebarResolvedIntents.set(e,!0):this.namedSidebarResolvedIntents.delete(e);let a=this.defaultSidebarResolvedIntent||this.anyNamedSidebarResolvedIntent();this.resolvedIntentFromSidebar$.value!==a&&this.resolvedIntentFromSidebar$.next(a)}catch(a){this.loggingService.catch("Error in CommentService publishNamedSidebarResolvedIntent: ",a)}}getResolvedCommentsOnDom$(){return this.resolvedCommentsOnDom$.asObservable()}enableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPin:!0}}),this.bubbleOnPinEnabled$.value===!0)return;this.bubbleOnPinEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPin: ",e)}}disableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPin:!1}}),this.bubbleOnPinEnabled$.value===!1)return;this.bubbleOnPinEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPin: ",e)}}getBubbleOnPin(){return this.bubbleOnPinEnabled$.value}getBubbleOnPin$(){return this.bubbleOnPinEnabled$.asObservable()}enableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPinHover:!0}}),this.bubbleOnPinHoverEnabled$.value===!0)return;this.bubbleOnPinHoverEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPinHover: ",e)}}disableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{bubbleOnPinHover:!1}}),this.bubbleOnPinHoverEnabled$.value===!1)return;this.bubbleOnPinHoverEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPinHover: ",e)}}getBubbleOnPinHover(){return this.bubbleOnPinHoverEnabled$.value}getBubbleOnPinHover$(){return this.bubbleOnPinHoverEnabled$.asObservable()}enablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDrag:!0}}),this.pinDragEnabled$.value===!0)return;this.pinDragEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDrag: ",e)}}disablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{pinDrag:!1}}),this.pinDragEnabled$.value===!1)return;this.pinDragEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDrag: ",e)}}getPinDrag(){return this.pinDragEnabled$.value}getPinDrag$(){return this.pinDragEnabled$.asObservable()}setExcludeLocationIdsFromSidebar(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{excludeLocationIdsFromSidebar:e}}),this.excludeLocationIdsFromSidebar$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}getExcludeLocationIdsFromSidebar(){return this.excludeLocationIdsFromSidebar$.value}getExcludeLocationIdsFromSidebar$(){return this.excludeLocationIdsFromSidebar$.asObservable()}enableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{multiThread:!0}}),this.multiThread$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMultiThread: ",e)}}disableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{multiThread:!1}}),this.multiThread$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMultiThread: ",e)}}getMultiThread(){return this.multiThread$.value&&!this.isMultiThreadUnservedOnPortable()}getMultiThread$(){let e=this.commonDbService?.portableConnectionChanges$?.()??ye(void 0);return Bt([this.multiThread$,e]).pipe(Ee(([t])=>t&&!this.isMultiThreadUnservedOnPortable()),Gt())}readMultiThreadRow(e){return Pe(this,null,function*(){try{if(this.commonDbService?.isPortableSession?.()!==!0)return{answered:!0,data:yield this.commonDbService?.getData({feature:"multiThread",properties:e})};this.commonDbService?.isPortableBackendActive?.()!==!0&&(yield ZC(o.PORTABLE_ACTIVATION_WAIT_MS));let t=(yield this.commonDbService?.readPortableDoc?.("multiThread",e))??{answered:!1};return!t.answered&&!this.multiThreadReadUnansweredLogged&&(this.multiThreadReadUnansweredLogged=!0,this.loggingService.catch("Velt [portable backend]: the multi-thread row could not be read. If the gateway does not serve the multiThread read (an older image \u2014 Part 116 S1), a new comment writes its container fresh; on a transient read failure the write is HELD (the stored row is not overwritten) and a removal keeps the stored row.",void 0,void 0,!0)),t}catch(t){return this.loggingService.catch("Error in CommentService readMultiThreadRow: ",t),{answered:!1}}})}applyMultiThreadFolderClause(e,t){return MD(e,t)}isMultiThreadUnservedOnPortable(){try{return!this.multiThread$.value||this.commonDbService?.isPortableBackendActive?.()!==!0||this.commonDbService.portableCapabilityState?.(zu)!=="absent"?!1:(this.multiThreadUnservedLogged||(this.multiThreadUnservedLogged=!0,this.loggingService.catch("Velt [portable backend]: multiThread is not served by this gateway",void 0,void 0,!0)),!0)}catch(e){return this.loggingService.catch("Error in CommentService isMultiThreadUnservedOnPortable: ",e),!1}}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.asObservable()}enableRestrictTextSearchToAnchor(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{restrictTextSearchToAnchor:!0}}),this.restrictTextSearchToAnchor$.value===!0)return;this.restrictTextSearchToAnchor$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRestrictTextSearchToAnchor: ",e)}}disableRestrictTextSearchToAnchor(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{restrictTextSearchToAnchor:!1}}),this.restrictTextSearchToAnchor$.value===!1)return;this.restrictTextSearchToAnchor$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRestrictTextSearchToAnchor: ",e)}}getRestrictTextSearchToAnchor(){return this.restrictTextSearchToAnchor$.value}getRestrictTextSearchToAnchor$(){return this.restrictTextSearchToAnchor$.asObservable()}enableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{shortUserName:!0}}),this.shortUserName$.value===!0)return;this.shortUserName$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShortUserName: ",e)}}disableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{shortUserName:!1}}),this.shortUserName$.value===!1)return;this.shortUserName$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShortUserName: ",e)}}getShortUserName(){return this.shortUserName$.value}getShortUserName$(){return this.shortUserName$.asObservable()}enableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingCountdown:!0}}),this.serviceBook.get(_n)?.enableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{recordingCountdown:!1}}),this.serviceBook.get(_n)?.disableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService disableRecordingCountdown: ",e)}}setCommentSidebarFilters(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;"),this.commentSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value??{}}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setEffectiveSidebarFilters(e){try{this.effectiveSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEffectiveSidebarFilters: ",t)}}getEffectiveSidebarFilters$(){return this.effectiveSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.asObservable()}enableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentPinHighlighter:!0}}),this.domService.enableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService enableCommentPinHighlighter: ",e)}}disableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentPinHighlighter:!1}}),this.domService.disableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService disableCommentPinHighlighter: ",e)}}setCustomReactions(e){try{this.reactionService?.setCustomReactions(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}onCommentSelectionChange$(){return this.commentSelectionChange$.asObservable()}onVisibilityOptionClicked$(){return this.visibilityOptionClicked$.asObservable()}emitVisibilityOptionClicked(e){this.visibilityOptionClicked$.next(e)}onCommentAdd$(){return this.commentAdded$.asObservable()}onCommentUpdate$(){return this.commentUpdated$.asObservable()}onCommentAnnotationDelete$(){return this.commentAnnotationDeleted$.asObservable()}onMultiThreadCommentAnnotationDelete$(){return this.multiThreadCommentAnnotationDeleted$.asObservable()}getCommentMode(){try{let e="freestyle";return this.getStreamMode()?e="stream":this.getPopoverMode()&&(e="popover"),e}catch(e){return this.loggingService.catch("Error in CommentService getCommentMode: ",e),"freestyle"}}getCommentType(e){try{return e.targetElement?"element":e.targetTextRange?"text":e.areaAnnotationId?"area":""}catch(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,a,i){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(d=>this.docService.getAreaChanges$().pipe(Ee(()=>d))),Fe(d=>(!a&&t&&(a=Lr(t,["id","data-id"])),ye(b(g({},d),{element:a})))),Fe(d=>this.getLocations$().pipe(Ee(m=>b(g({},d),{locationIds:m})))),Ee(({locationIds:d,element:m})=>{let u=[],f=this.docService.getDocumentPaths();if(f?.documentId){let y=i?[i]:this.docService.getAreaDocumentIds(m),S=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:f?.organizationId,documentIds:y});if(S)for(let j of S)(t&&j?.targetElementId===t||j?.targetElement?.xpath===e)&&(d?.includes(j?.locationId)||rr(j))&&u.push(j)}return u.length?u:null}))}catch(d){return this.loggingService.catch("Error in CommentService isCommentAnnotationAvailableOnXPath: ",d),ye(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:a,clientDocumentId:i}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$()),Fe(()=>this.docService.getAreaChanges$()),Ee(()=>{let d=null,m=this.docService.getDocumentPaths(),u=Cn(e),f=this.generateContextId(u);if(m?.documentId){let y=i?[this.docService.generateDocumentId(i)]:this.docService.getAreaDocumentIds(a??null),S=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:m?.organizationId,documentIds:y});if(S){d=[];for(let j of S)t?.partialMatch?pC(j?.context,u)&&d.push(j):f&&j?.contextId===f&&d.push(j)}}return d}))}catch(d){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",d),ye(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(Ee(()=>this.getAnnotationById(e)),Fe(t=>t?t?.iam?.accessMode===gr.PRIVATE?this.isPrivateCommentAllowed$().pipe(Ee(a=>{if(a)return t})):ye(t):ye(t)),Fe(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(Ee(a=>{if(a)return a})):ye(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),ye(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(Ee(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${Z.TAGS.VELT_COMMENT_BUBBLE}[${Z.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${Z.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${Z.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e,t){try{return this.commentAnnotationById$.pipe(Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(a=>({documentPaths:a,sectionId:e})))),Fe(a=>this.docService.getAreaChanges$().pipe(Ee(()=>a))),Fe(a=>{let i=Lr(e,["id","data-id"]);if(i){let d=this.docService.getAdditionLocationFromElement(i);if(d){let m=this.docService.genarateLocationId(d);return this.docService.getLocations$().pipe(Ee(u=>{let y=Object.values(u||{}).find(S=>S.locationId===m||d?.id&&S.location.id===d.id);return b(g({},a),{additionalLocation:y,locationOnElement:!!d,element:i})}))}}return ye(b(g({},a),{additionalLocation:null,element:i}))}),Fe(a=>a?.locationOnElement?ye(a):this.docService.getLocation$().pipe(Ee(i=>b(g({},a),{location:i})))),Ee(({documentPaths:a,location:i,additionalLocation:d,locationOnElement:m,element:u})=>{let f=null;if(this.authService.getUser()&&a?.documentId){let S=t?[t]:this.docService.getAreaDocumentIds(u),j=this.getCommentAnnotationsByOrganizationIdAndDocumentIds({organizationId:a?.organizationId,documentIds:S});if(j){f=[];let W=En(e);m?d?.location?.id?W=En([d?.location?.id,e]):d?.locationId&&(W=En([d?.locationId+"",e])):i&&(i?.location?.id?W=En([i?.location?.id,e]):i?.locationId&&(W=En([i?.locationId+"",e])));for(let $ of j)$?.multiThreadAnnotationId===W?f.push($):($?.targetInlineCommentElementId===e||$?.targetElementId===e)&&(m?d&&fc({location:d?.location,locationId:d?.locationId},{location:$.location,locationId:$.locationId})&&f.push($):i?fc({location:i?.location,locationId:i?.locationId},{location:$.location,locationId:$.locationId})&&f.push($):$?.locationId||f.push($))}}return f}))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",a),ye(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(Fe(()=>this.multiThreadCommentAnnotationById$),Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(t=>({documentPaths:t,multiThreadAnnotationId:e})))),Ee(({documentPaths:t,location:a,additionalLocation:i,locationOnElement:d})=>{let m=null;if(t?.documentId){let u=this.getMultiThreadAnnotationById(e),{documentId:f,organizationId:y}=u?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},S=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:y,documentId:f||""});if(S){m=[];for(let j of S)j?.multiThreadAnnotationId===e&&u?.commentAnnotations?.[j?.annotationId]&&m.push(j)}}return m}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ye(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$().pipe(Ee(t=>({documentPaths:t,annotationIds:e})))),Ee(({documentPaths:t})=>{let a=null;if(t?.documentId){let i=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],d=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(i=[...i,...d],i){a=[];for(let m of i)e.includes(m?.annotationId)&&a.push(m)}}return a}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),ye(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(Fe(()=>this.draftCommentAnnotationsByAnnotationId$),Fe(()=>this.docService.getDocumentPaths$()),Ee(()=>{e&&!t&&(t=ur(e));let a=this.authService.getUser(),i=this.docService.getDocumentPaths(),d=null;if(a&&i?.documentId){this.commentAnnotationById$.value&&(d={},Object.values(this.commentAnnotationById$.value).forEach(u=>{u?.metadata?.folderId==e&&u?.metadata?.veltFolderId==t&&(d[u?.annotationId]=u)}));let m=this.draftCommentAnnotationsByAnnotationId$.value;m&&(d===null&&(d={}),Object.values(m).forEach(u=>{u?.metadata?.folderId==e&&u?.metadata?.veltFolderId==t&&!d[u?.annotationId]&&(d[u?.annotationId]=u)}))}return d?Object.values(d):null}))}catch(a){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",a),ye(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:a,veltFolderId:i,targetElementId:d,clientDocumentId:m,documentId:u,context:f,contextOptions:y,element:S,type:j,sectionId:W,locationId:$}=e||{};if(m&&!u&&(u=this.docService.generateDocumentId(m)),a&&!i&&(i=ur(a)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(Ee(ce=>ce?[ce]:null));let H=[],q=S;if(d&&(j==="pin"||j==="tool"||j==="bubble")){let ce=Lr(d,["id","data-id"]);if(ce){let fe=ce;q=fe;let le=this.domService.getXPath(ce);H.push(this.getCommentAnnotationAvailableOnXPath(le,d,fe,u))}}return W&&H.push(this.getCommentAnnotationsBySectionId(W,u)),f&&H.push(this.getCommentAnnotationsByContext({context:f,contextOptions:y,element:q,clientDocumentId:m})),u&&H.push(this.getCommentAnnotationsByDocumentId$({documentId:u})),a&&H.push(this.getCommentAnnotationsByFolderId({folderId:a,veltFolderId:i})),H.length===0?ye(null):Bt(H).pipe(Ee(ce=>{let fe=ce.filter(he=>he!==null&&Array.isArray(he));if(fe.length===0)return null;if(fe.length===1){let he=fe[0];return $&&he?.length?he.filter(ze=>Lm(ze,$)):he}let le=fe[0];for(let he=1;he<fe.length;he++){let xe=fe[he];le=le.filter(ze=>xe.some(He=>He.annotationId===ze.annotationId))}return $&&le?.length&&(le=le.filter(he=>Lm(he,$))),le}),Gt(Qn))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),ye(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.allowedElementIds$.value?.length||this.allowedElementClassNames$.value?.length||this.allowedElementQuerySelectors$.value?.length?!!(this.allowedElementIds$.value?.length&&this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)||this.allowedElementClassNames$.value?.length&&this.domService.isElementInsideListedElementClassNames(e,this.allowedElementClassNames$.value)||this.allowedElementQuerySelectors$.value?.length&&this.domService.isElementInsideListedElementQuerySelectors(e,this.allowedElementQuerySelectors$.value)):!0}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}canCommentOnTextRange(e){try{let t=e?.commonAncestorContainer;return!e||!t?!1:Lu(e)?(this.logRichTextEditorBlock("text selection","range"),!1):this.isElementInsideAllowedElements(t)&&!Am(t)}catch(t){return this.loggingService.catch("Error in CommentService canCommentOnTextRange: ",t),!1}}isCommentBlockedOnElement(e){try{return Am(e)||Dr(e)}catch(t){return this.loggingService.catch("Error in CommentService isCommentBlockedOnElement: ",t),!1}}applyCommentPinTargetModifier(e){if(this.getSvgAsImg()){let t=e?.closest(`[${Z.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);t&&t instanceof HTMLElement&&(e=t)}if(this.getPopoverMode()){let t=e?.closest(`[${Z.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(t&&t instanceof HTMLElement)return t}return e}isCommentModeClickInsideRichTextEditor(e){try{let t=this.domService.getBackgroundElement(e?.clientX,e?.clientY,!0,!0);return t?(t=this.applyCommentPinTargetModifier(t),t&&this.getCommentToNearestAllowedElement()&&!this.isElementInsideAllowedElements(t)&&(t=this.getNearestAllowedElement(t)),Dr(t)?(this.logRichTextEditorBlock("comment-mode click","final-target"),!0):!1):!1}catch(t){return this.loggingService.catch("Error in CommentService isCommentModeClickInsideRichTextEditor: ",t),!1}}logRichTextEditorBlock(e,t){try{let a=`${e}|${t}`;if(this.lastRichTextEditorBlockLogKey===a)return;this.lastRichTextEditorBlockLogKey=a,this.loggingService.log(`[Velt] ${e} skipped: it touches a ProseMirror/TipTap editor.`)}catch{}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let a=0;a<t.length;a++){let i=t[a];if(e.contains(i)&&!Dr(i))return i}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,Z.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return Pe(this,null,function*(){try{if(t?.updatedComment?.isDraft&&this.draftConfirmation$?.value&&!(yield this.confirmDraftIfRequired(t.updatedComment,e?.annotationId)))return;t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let a=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(a?.comments?.length){let y=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],a.comments?.forEach(S=>{let j=y.find(W=>W.commentId===S.commentId);j?e.comments.push(j):e.comments.push(S)})}e.comments||(e.comments=[]);let i=!1,d=!1,m;switch(t.type){case qe.NEWLY_ADDED:case qe.ADDED:if(!t.updatedComment)break;e?.comments?.length||(d=!0),e.comments.push(t.updatedComment);let y=t?.assigned||void 0;m={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:y}};break;case qe.APPROVED:e.approved=!0,m={commentAnnotation:e,targetComment:null,actionType:qe.APPROVED};break;case qe.ASSIGNED:{let ce=a?.assignedTo;e.assignedTo=t.assignedTo,m={commentAnnotation:e,targetComment:null,actionType:qe.ASSIGNED,otherFields:{oldAssignedTo:ce,newAssignedTo:t.assignedTo}};break}case qe.UPDATED:if(!t.updatedComment)break;let S=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);if(S>=0){let ce=e.comments[S]?.commentText;e.comments[S]=t.updatedComment,e.comments[S].status=qe.UPDATED;let fe=t?.assigned||void 0;m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.UPDATED,otherFields:{assigned:fe,oldCommentText:ce}}}break;case qe.REACTION_ADDED:if(!t.updatedComment)break;let j=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);j>=0&&(e.comments[j]=t.updatedComment,e.comments[j].status=qe.UPDATED,m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.REACTION_ADDED});break;case qe.REACTION_DELETED:if(!t.updatedComment)break;let W=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);W>=0&&(e.comments[W]=t.updatedComment,e.comments[W].status=qe.UPDATED,m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.REACTION_DELETED});break;case qe.STATUS_CHANGED:if(e.status.type==="terminal"){this.domService.resetSelectedAnnotationsMap(!1,"comment");let ce=this.authService.getUser();e.resolvedByUserId=ce?.userId,e.resolvedByUser=ce}m={commentAnnotation:e,targetComment:null,actionType:qe.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case qe.PRIORITY_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case qe.ACCESS_MODE_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case qe.CUSTOM_LIST_CHANGED:m={commentAnnotation:e,targetComment:null,actionType:qe.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case qe.SUBSCRIBED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUBSCRIBED};break;case qe.UNSUBSCRIBED:m={commentAnnotation:e,targetComment:null,actionType:qe.UNSUBSCRIBED};break;case qe.DELETED:if(!t.updatedComment)break;let $=e.comments.findIndex(ce=>ce.commentId===t.updatedComment.commentId);if($>=0){if(($===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let fe={};if(this.deleteReplyConfirmation$.value&&($!==0||this.deleteThreadWithFirstComment$.value===!1)?fe={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:fe={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!(yield this.dialog.open(Rm,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:fe}).afterClosed().toPromise()))return}let ce=e.comments.splice($,1);ce?.length&&ce.forEach(fe=>{fe?.attachments&&this.deleteCommentAttachmentsForCascade(e,fe),fe?.reactionAnnotationIds&&fe.reactionAnnotationIds.forEach(le=>{this.deleteReaction(le)})})}e?.status?.type==="terminal"&&(e.status=this.customFilterService.defaultStatus),$===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?i=!0:(this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),m={commentAnnotation:e,targetComment:t.updatedComment,actionType:qe.DELETED});break;case qe.ACCEPTED:let H={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:qe.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentAccepted$.next(H),m={commentAnnotation:e,targetComment:null,actionType:qe.ACCEPTED};break;case qe.REJECTED:let q={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:qe.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentRejected$.next(q),this.domService.resetSelectedAnnotationsMap(),m={commentAnnotation:e,targetComment:null,actionType:qe.REJECTED};break;case qe.SUGGESTION_ACCEPTED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUGGESTION_ACCEPTED,otherFields:{resolvedBy:e?.suggestion?.resolvedBy,resolvedAt:e?.suggestion?.resolvedAt}};break;case qe.SUGGESTION_REJECTED:m={commentAnnotation:e,targetComment:null,actionType:qe.SUGGESTION_REJECTED,otherFields:{rejectReason:e?.suggestion?.rejectReason,resolvedBy:e?.suggestion?.resolvedBy,resolvedAt:e?.suggestion?.resolvedAt}};break;default:break}if(e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null,e.resolvedByUser=null),t.visibility)try{let y=g({},t.visibility);if(y.type==="organizationPrivate"&&!y.organizationId&&!y.organizationIds?.length){let W=this.docService.getOrganizationConfig();W?.clientOrganizationId&&(y.organizationId=W.clientOrganizationId)}let S=e.from?.userId||this.authService.getUser()?.userId,j=qn(y,S);j.length>0&&(e.context||(e.context={}),e.context._setAccessFields=j,e.visibilityConfig=Zn(y,S))}catch(y){this.loggingService.catch("Error building accessFields from visibility in saveComment:",y)}if(t?.updatedComment?.isDraft&&(m=void 0),i)this.deleteCommentPinAnnotation(e,!0),this.domService.resetSelectedAnnotationsMap(!1,"comment");else{d&&e.comments?.length&&this.enableAutoCategorize$?.value&&this.setCommentCategory(e);let y=this.authService.getUser()?.userId;if(!this.iamService.isUserAdmin()&&e.context?.access&&e.context?.accessFields&&t.updatedComment?.from?.userId&&y&&!this.userPermissionService?.hasUserContextAccess({userId:y,accessFields:e.context.accessFields})){this.loggingService.catch("User does not have context access to update comment annotation.",void 0,void 0,!0);return}this.updateComment(e,!1,!1,m,!0,t.updatedComment),e?.multiThreadAnnotationId&&(t.type===qe.ADDED||t.type===qe.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e])}let u=this.getCustomPinById(e.annotationId),f={type:t.type,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(y,S)=>{this.updateCommentAnnotationContext(e.annotationId,y,S)}};if(u!==void 0&&(f.element=u),delete f?.annotation?.pageInfo,delete f?.annotation?.targetElement,delete f?.annotation?.targetTextRange,f?.type===qe.DELETED&&(e.comments?.length||(f.annotation=null)),i||this.commentUpdated$.next(f),t.type===qe.NEWLY_ADDED&&!i&&e?.annotationId){let y=this.pendingAddCommentAnnotationData.get(e.annotationId);if(y){this.pendingAddCommentAnnotationData.delete(e.annotationId);let S=to(void 0,e.assignedTo,$=>this.loggingService.catch("Error resolving isAssigneeChanged: ",$)),j=b(g({},y),{annotation:this.getCommentAnnotationForClient(e),targetCommentId:t.updatedComment?.commentId}),W=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(j,S);W&&this.commentActionsService?.triggerAddCommentAnnotationEvent(W),t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment,isAssigneeChanged:S}))}}t.type===qe.ADDED&&t._dispatchAddCommentEvent&&!i&&e?.annotationId&&t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment,isAssigneeChanged:t._isAssigneeChanged}))}catch(a){this.loggingService.catch("Error in CommentService saveComment: ",a)}})}attachComment(e,t=[],a,i,d,m,u,f){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let y;if(e){let S=Lr(e,t);S&&(y={targetElement:{xpath:this.domService.getXPath(S),topPercentage:50,leftPercentage:90},targetElementId:e})}(y||a||d)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,m,void 0,void 0,y,f,void 0,void 0,i,void 0,void 0,void 0,a,void 0,d,void 0,void 0,u)}catch(y){this.loggingService.catch("Error in CommentService attachComment: ",y)}}generateComponentIdFromObject(e){try{let t=Cn(e||{});return fr(JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CommentService generateComponentIdFromObject: ",t);return}}updateNotificationsDatabase(e,t,a,i={}){try{let d=this.buildCommentNotificationRawData(e,t,a,i);this.notificationService.updateNotificationDatabase(d)}catch(d){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",d)}}buildCommentNotificationRawData(e,t,a,i={}){return g({annotationData:e,targetAnnotationData:t,actionType:a,notificationSource:"comment"},i)}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getCustomUserContacts(){try{return this.contactService.getCustomUserContacts()}catch(e){return this.loggingService.catch("Error in CommentService getCustomUserContacts:",e),null}}getCustomUserContactsConfig(){try{return this.contactService.getCustomUserContactsConfig()}catch(e){this.loggingService.catch("Error in CommentService getCustomUserContactsConfig:",e);return}}getElementFromComment(e){try{let t=null,a;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else if((a=this.resolveIdScopedPinElement(e))!==void 0)t=a;else{let i=!1,d=e?.targetElement?.anchor,m=this.acceptsInOwnDocumentArea(e);if(!t&&d){let u=this.domService.resolveAnchorRecord(d,{accept:m,cacheKey:jh(e)});u?.element&&this.domService.isElementVisible(u.element)&&kn(u.element)&&!(rr(e)&&dp(u.matchedBy))&&(t=u.element)}!t&&e?.targetElement?.xpath&&(i=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPathAccepted(e?.targetElement?.xpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)),!i&&!rr(e)&&(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPathAccepted(e?.targetElement?.cfXpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPathAccepted(e?.targetElement?.fXpath,m),t&&(!this.domService.isElementVisible(t)||!m(t))&&(t=null)))}return t&&!kn(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],a=null,i;if(e?.ghostComment)!a&&e.ghostComment?.targetElement?.fXpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),a&&!this.domService.isElementVisible(a)&&(a=null)),!a&&e.ghostComment?.targetElement?.cfXpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),a&&!this.domService.isElementVisible(a)&&(a=null)),!a&&e.ghostComment?.targetElement?.xpath&&(a=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),a&&!this.domService.isElementVisible(a)&&(a=null));else if((i=this.resolveIdScopedPinElement(e))!==void 0)a=i;else{let d=!1,m=e?.targetElement?.anchor,u=this.acceptsInOwnDocumentArea(e);if(!a&&m){let f=this.domService.resolveAnchorRecord(m,{accept:u,cacheKey:jh(e)});f?.element&&this.domService.isElementVisible(f.element)&&kn(f.element)&&!(rr(e)&&dp(f.matchedBy))&&(a=f.element)}!a&&e?.targetElement?.xpath&&(d=this.domService.isXpathWithId(e?.targetElement?.xpath),a=this.domService.getElementFromXPathAccepted(e?.targetElement?.xpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)),!d&&!rr(e)&&(!a&&e?.targetElement?.cfXpath&&(a=this.domService.getElementFromXPathAccepted(e?.targetElement?.cfXpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)),!a&&e?.targetElement?.fXpath&&(a=this.domService.getElementFromXPathAccepted(e?.targetElement?.fXpath,u),a&&(!this.domService.isElementVisible(a)||!u(a))&&(a=null)))}return a&&!kn(a)&&(a=null),e?.targetElementId&&(t=Array.from(Th(e.targetElementId,["id","data-id"]))),a&&!t.includes(a)&&t.push(a),rr(e)&&(t=t.filter(d=>this.domService.isElementVisible(d)&&this.docService.isAnnotationAllowedInArea(e?.metadata,d)!==!1)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,a=null;if(t)for(;!a&&t;)a=this.domService.getElementFromXPath(t),a&&(!this.domService.isElementVisible(a)||!kn(a))&&(a=null),a||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}findDocumentLevelTargetById(e){try{return Array.from(Th(e.targetElementId,["id","data-id"])).find(t=>this.domService.isElementVisible(t)&&this.docService.isAnnotationAllowedInArea(e?.metadata,t)!==!1)??null}catch(t){return this.loggingService.catch("Error in CommentService findDocumentLevelTargetById: ",t),null}}isAnnotationPinDrawnOnPage(e){try{return e?!!document.getElementById(`comment-pin-container-${e}`)?.isConnected:!1}catch(t){return this.loggingService.catch("Error in CommentService isAnnotationPinDrawnOnPage: ",t),!1}}logHiddenDocumentLevelPin(e){try{if(this.loggingService?.debugMode===!1)return;let t=`${e?.annotationId}|${window.location.href}`;if(this.loggedHiddenDocumentLevelPins||(this.loggedHiddenDocumentLevelPins=new Set),this.loggedHiddenDocumentLevelPins.has(t))return;this.loggedHiddenDocumentLevelPins.add(t),this.loggingService.log(`[Velt] document-level comment pin not drawn: target not found on this page. annotationId="${e?.annotationId}"`)}catch(t){this.loggingService.catch("Error in CommentService logHiddenDocumentLevelPin: ",t)}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=an.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,a=new vC().getDeviceType();t&&t!==a&&(e.ghostComment.type=an.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[Yn.MOBILE,Yn.TABLET].includes(t)&&[Yn.MOBILE,Yn.TABLET].includes(a)||[Yn.DESKTOP,Yn.MONITOR].includes(t)&&[Yn.DESKTOP,Yn.MONITOR].includes(a)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},a=t[e?.annotationId]||{};xn(e.ghostComment,a)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(Gt(Qn))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>t?{count:t[e]||0}:null))}getUnreadCommentAnnotationCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(Ee(e=>e?{count:Object.keys(e??{}).length||0}:null))}getUnreadCommentCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(Ee(e=>e?{count:Object.values(e).reduce((a,i)=>a+i,0)}:null))}getUnreadCommentCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>{if(t){let a=this.docService.getDocumentPaths(),i=[],d=0;return a?.documentId&&(i=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId}),i&&Object.keys(t).forEach(m=>{let u=i?.find(f=>f.annotationId===m);Lm(u,e)&&(d+=t[m])})),{count:d}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(Ee(t=>{if(t){let a=this.docService.getDocumentPaths(),i=[],d=0;return a?.documentId&&(i=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId}),Object.keys(t).forEach(m=>{if(t[m]){let u=i?.find(f=>f.annotationId===m);Lm(u,e)&&(d+=1)}})),{count:d}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsRead(t))}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus,a=this.authService.getUser();if(t){for(let i of e)if(t?.id!==i?.status?.id){let d=JSON.parse(JSON.stringify(i||{}));i.status=this.customFilterService.resolvedStatus,i.statusUpdatedByUserId=a?.userId;let m={annotation:i,type:qe.STATUS_CHANGED,oldStatus:d.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(i,m)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}isCommentAnnotationUnread(e){try{let t=this.authService.getUser();return!(t?.userSnippylyId&&e?.viewedByUserIds?.length&&e?.viewedByUserIds?.includes(t?.userSnippylyId))}catch(t){return this.loggingService.catch("Error in CommentService isCommentAnnotationUnread: ",t),!1}}updateCommentDialogPosition(){try{this.updateCommentDialogPositionTriggerSubject$.next()}catch(e){this.loggingService.catch("Error in CommentService updateCommentDialogPosition: ",e)}}updateCommentDialogPositionTrigger$(){return this.updateCommentDialogPositionTriggerSubject$.asObservable()}enableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{areaComment:!0}}),this.areaCommentEnabled$.value===!0)return;this.areaCommentEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAreaComment: ",e)}}disableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{areaComment:!1}}),this.areaCommentEnabled$.value===!1)return;this.areaCommentEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAreaComment: ",e)}}getAreaCommentEnabled$(){return this.areaCommentEnabled$.asObservable()}getAreaCommentEnabled(){return this.areaCommentEnabled$.value}setPinCursorImage(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;"),e&&(e=`url(${e}) 0 31, auto`),this.commentPinCursorImage$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return Pe(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,a)=>{let i=this.domService.getLastDocumentClickTarget(),d=e?.location||this.docService.getAdditionLocationFromElement(i);if(d?.id){let m=this.docService.getLocationByClientLocationId(d.id);m&&(d=m)}this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,d,void 0,e,void 0,void 0,void 0,m=>{t(m)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=Dh(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let a=`${Z.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${Z.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(a=`${Z.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${Z.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${Z.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let i=this.getPortableAttachmentScope(t),d={organizationId:i.organizationId??null,documentId:i.documentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??this.configService?.getApiKey()??null,folderId:t.metadata?.folderId??this.documentPaths?.folderId??null,attachmentId:null};return this.storageService.uploadFile({path:a,file:e,metadata:d,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable(),portableScope:i})}downloadAttachment(e,t){this.storageService.downloadAttachment(e,this.getPortableAttachmentScope(t))}deleteAttachment({attachment:e,metadata:t,annotation:a}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable(),portableScope:this.getPortableAttachmentScope(a)})}deleteCommentAttachmentsForCascade(e,t){let a=e.metadata;t.attachments?.forEach(i=>{let d={attachmentId:i.attachmentId,organizationId:a?.clientOrganizationId??a?.organizationId??null,documentId:a?.clientDocumentId??a?.documentId??null,folderId:a?.folderId??null,commentAnnotationId:e.annotationId,apiKey:a?.apiKey??null};this.deleteAttachment({attachment:i,metadata:d,annotation:e})})}getPortableAttachmentScope(e){return{organizationId:e?.metadata?.clientOrganizationId??this.documentPaths?.clientOrganizationId??null,documentId:e?.metadata?.clientDocumentId??this.documentPaths?.clientDocumentId??null}}getAttachmentDisplayUrl(e,t){return this.storageService.getAttachmentDisplayUrl(e,this.getPortableAttachmentScope(t))}isPortableAttachment(e){return this.storageService.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.storageService.resolveAttachmentUrl(e,this.getPortableAttachmentScope(t))}isAttachmentDisplayPending(e,t){return this.storageService.isAttachmentDisplayPending(e,this.getPortableAttachmentScope(t))}reportAttachmentLoadError(e,t,a){this.storageService.reportAttachmentLoadError(e,this.getPortableAttachmentScope(t),a)}deleteReaction(e){try{this.reactionService?.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t;try{t=new URL(e?.pageInfo?.url||window.location.href)}catch(a){this.loggingService.catch("Error in CommentService generateCommentUrl: ",a),t=new URL(window.location.href)}return t.searchParams.delete(Z.URL_PARAMS.COMMENT_ID),t.searchParams.append(Z.URL_PARAMS.COMMENT_ID,e.annotationId),t.href}getCustomPinById(e){if(this.customPinsById.has(e))return this.customPinsById.get(e)}setCustomStatuses(e){try{if(e===void 0)return;this.customStatusesShown$.next(!0),this.customFilterService.setCustomStatusFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(ke.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!Fm()&&t?.commonAncestorContainer&&this.canCommentOnTextRange(t)){let a=t?this.domService.getTargetTextRangeFromSelectionRange(t):void 0;this.domService.clearTextSelection(),setTimeout(()=>{this.addComment(void 0,a)},100)}}}catch(e){this.loggingService.catch("Error in CommentService addCommentOnSelectedText: ",e)}}getInlineCommentSectionConfig(e){try{let t;if(e){let a=e?.closest(`[${Z.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(a){let i=a.getAttribute(Z.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);i&&(t={},t.targetInlineCommentElementId=i,a.getAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(a.getAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},a=e?.unsubscribedUsers||{},i={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(d=>{let m=e.subscribedUsers?.[d];m?.type==="manual"&&(t[d]=m)}),e?.assignedTo?.userId){let d=fr(e?.assignedTo?.userId);a[d]||t[d]?.type!=="manual"&&(t[d]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(d=>!d?.isDraft)?.forEach(d=>{if(d?.from?.userId){let m=fr(d?.from?.userId);a[m]||t[m]?.type!=="manual"&&(t[m]={user:d?.from,type:"auto"})}d?.to?.forEach(m=>{if(m?.userId){let u=fr(m.userId);a[u]||t[u]?.type!=="manual"&&(t[u]={user:m,type:"auto"})}}),d?.toOrganizationUserGroup?.forEach(m=>{if(m?.groupId)i[m?.groupId]={type:"auto"};else if(m?.clientGroupId){let u=fr(m.clientGroupId);i[u]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=a,e.subscribedGroups=i}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(Fe(()=>{let{annotationId:t,documentId:a}=e;if(a){let i=Qo(a).toString();return this.getDataCommentAnnotationsFromDocumentId(i).pipe(Ee(d=>d.find(u=>u.annotationId===t)||null))}else{let i=this.docService.getDocumentPaths();if(i?.documentId){let d=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId});if(d){let m=d.find(u=>u.annotationId===t);return ye(m||null)}}}return ye(null)}),Wr(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),ye(null))))}getCommentAnnotationByIdSync(e){try{return this.commentAnnotationById$.value?.[e]}catch(t){this.loggingService.catch("Error in CommentService getCommentAnnotationByIdSync: ",t);return}}getDataCommentAnnotationsFromDocumentId(e){return this.configService?.getApiKey()?this.commonDbService.dbListener({feature:"allComments",properties:{documentId:e||this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,isCollection:!0}}).pipe(Ee(t=>t?.data),Ee(t=>{let a=[];return t&&(a=Object.values(t??{}).filter(i=>typeof i=="object")),a})):ye([])}enableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedComments:!0}}),this.collapsedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedComments: ",e)}}disableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedComments:!1}}),this.collapsedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedComments: ",e)}}getCollapsedComments$(){return this.collapsedComments$.asObservable()}enableCollapsedRepliesPreview(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedRepliesPreview:!0}}),this.collapsedRepliesPreview$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedRepliesPreview: ",e)}}disableCollapsedRepliesPreview(){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{collapsedRepliesPreview:!1}}),this.collapsedRepliesPreview$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedRepliesPreview: ",e)}}getCollapsedRepliesPreview$(){return this.collapsedRepliesPreview$.asObservable()}enableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullExpanded:!0}}),this.fullExpanded$.value===!0)return;this.fullExpanded$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullExpanded: ",e)}}disableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullExpanded:!1}}),this.fullExpanded$.value===!1)return;this.fullExpanded$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullExpanded: ",e)}}getFullExpanded$(){return this.fullExpanded$.asObservable()}getFullExpanded(){return this.fullExpanded$.value}setSidebarCustomActionEventData(e,t,a,i,d){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d})}catch(m){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",m)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{let a=new Set;(e||[]).forEach(d=>{(d?.annotations||[]).forEach(m=>{m?.annotationId&&a.add(m.annotationId)})});let i=this.customSidebarDataAnnotationIds$.value;this.areAnnotationIdSetsEqual(i,a)||this.customSidebarDataAnnotationIds$.next(a),this.sidebarData$.next({data:e,options:t})}catch(a){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",a)}}areAnnotationIdSetsEqual(e,t){if(e===t)return!0;if(e===null||t===null||e.size!==t.size)return!1;for(let a of e)if(!t.has(a))return!1;return!0}getSidebarCustomData(){return this.sidebarData$.asObservable()}getCustomSidebarDataAnnotationIds$(){return this.customSidebarDataAnnotationIds$.asObservable()}getCustomSidebarDataAnnotationIds(){return this.customSidebarDataAnnotationIds$.value}setSidebarCustomActionEventDataAllChanges(e,t,a,i,d){return Pe(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d});let m=yield this.metadataService.getGlobalMetadata(),u={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:a,commentAnnotations:t,systemFilteredAnnotations:i,metadata:m,customFilters:d};this.commentActionsService?.triggerAction(ct.COMMENT_SIDEBAR_DATA_UPDATE,u)}catch(m){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",m)}})}setSidebarCustomActionEventDataOnInit(e,t,a,i,d){return Pe(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:a,systemFilteredData:i,customFilters:d});let u={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:a,commentAnnotations:t,systemFilteredAnnotations:i,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:d};this.commentActionsService?.triggerAction(ct.COMMENT_SIDEBAR_DATA_INIT,u)}catch(m){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",m)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?xn(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}getTransformContext$(){return this.transformContext$.asObservable()}getTransformContext(){return this.transformContext$.value}enableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customActions:!0}}),this.customActions$.value===!0)return;this.customActions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarCustomActions: ",e)}}disableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customActions:!1}}),this.customActions$.value===!1)return;this.customActions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarCustomActions: ",e)}}getSidebarCustomActionsValue(){return this.customActions$.getValue()}enableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{queryParamsComments:!0}}),this.queryParamsComments$.value===!0)return;this.queryParamsComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableQueryParamsComments: ",e)}}disableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{queryParamsComments:!1}}),this.queryParamsComments$.value===!1)return;this.queryParamsComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableQueryParamsComments: ",e)}}getQueryParamsComments$(){return this.queryParamsComments$.asObservable()}getQueryParamsComments(){return this.queryParamsComments$.value}enableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveStatusAccessAdminOnly:!0}}),this.resolveStatusAccessAdminOnly$.value===!0)return;this.resolveStatusAccessAdminOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableResolveStatusAccessAdminOnly: ",e)}}disableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{resolveStatusAccessAdminOnly:!1}}),this.resolveStatusAccessAdminOnly$.value===!1)return;this.resolveStatusAccessAdminOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableResolveStatusAccessAdminOnly: ",e)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.value}enableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{svgAsImg:!0}}),this.svgAsImg$.value===!0)return;this.svgAsImg$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSvgAsImg: ",e)}}disableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{svgAsImg:!1}}),this.svgAsImg$.value===!1)return;this.svgAsImg$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSvgAsImg: ",e)}}getSvgAsImg$(){return this.svgAsImg$.asObservable()}getSvgAsImg(){return this.svgAsImg$.value}enableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentToNearestAllowedElement:!0}}),this.commentToNearestAllowedElement$.value===!0)return;this.commentToNearestAllowedElement$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentToNearestAllowedElement: ",e)}}disableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentToNearestAllowedElement:!1}}),this.commentToNearestAllowedElement$.value===!1)return;this.commentToNearestAllowedElement$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentToNearestAllowedElement: ",e)}}getCommentToNearestAllowedElement$(){return this.commentToNearestAllowedElement$.asObservable()}getCommentToNearestAllowedElement(){return this.commentToNearestAllowedElement$.value}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:a}=e||{},i=null;t&&(i={},t.forEach(m=>{m?.annotationId&&i&&(i[m.annotationId]=m)}));let d={};t===void 0?d.data=this.commentsFromSidebarMap$.value?.data:d.data=i,a===void 0?d.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:d.sidebarVisible=a,xn(this.commentsFromSidebarMap$.value,d)||this.commentsFromSidebarMap$.next(d)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}hasActiveFilters(e){try{return e?!!(e.people?.length||e.assigned?.length||e.tagged?.length||e.involved?.length||e.priority?.length||e.status?.length||e.category?.length||e.location?.length||e.document?.length||e.version?.length||e.accessModes?.length||this.hasCustomContextFilters(e)):!1}catch(t){return this.loggingService.catch("Error in CommentService hasActiveFilters: ",t),!1}}hasCustomContextFilters(e){try{if(!e)return!1;let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]);return Object.keys(e).some(a=>!t.has(a)&&Array.isArray(e[a])&&e[a]?.length>0)}catch(t){return this.loggingService.catch("Error in CommentService hasCustomContextFilters: ",t),!1}}applyDirectFilters(e,t){try{let a=this.commentSidebarSystemFiltersOperator$.value,i,d=!1,m=new Set;a===Kr.AND?i=e.slice():i=[];let u=f=>{a===Kr.AND?i=i.filter(y=>f.some(S=>S.annotationId===y.annotationId)):f.forEach(y=>m.add(y.annotationId)),d=!0};if(t.people?.length){let f=[];t.people.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByPeople({id:S,name:y.name},e)])}),u(f)}if(t.assigned?.length){let f=[];t.assigned.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByAssigned({id:S,name:y.name},e)])}),u(f)}if(t.tagged?.length){let f=[];t.tagged.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByTagged({id:S,name:y.name},e)])}),u(f)}if(t.involved?.length){let f=[];t.involved.forEach(y=>{let S=y.userId||y.email;S&&(f=[...f,...this.filterAnnotationsByInvolved({id:S,name:y.name},e)])}),u(f)}if(t.priority?.length){let f=[];t.priority.forEach(y=>f=[...f,...this.filterAnnotationsByPriority({id:y},e)]),u(f)}if(t.status?.length){let f=[];t.status.forEach(y=>f=[...f,...this.filterAnnotationsByStatus({id:y},e)]),u(f)}if(t.category?.length){let f=[];t.category.forEach(y=>f=[...f,...this.filterAnnotationsByCommentCategory({id:y},e)]),u(f)}if(t.version?.length){let f=[];t.version.forEach(y=>f=[...f,...this.filterAnnotationsByVersion(y,e)]),u(f)}if(t.document?.length){let f=[];t.document.forEach(y=>f=[...f,...this.filterAnnotationsByDocument(y,e)]),u(f)}if(t.location?.length){let f=[];t.location.forEach(y=>{y.id&&(f=[...f,...e.filter(S=>S.location?.id===y.id||S.documentParams?.id===y.id)])}),f=[...f,...e.filter(y=>rr(y)&&!f.includes(y))],u(f)}if(t.accessModes?.length){let f=[];t.accessModes.forEach(y=>{y===gr.PRIVATE?f=[...f,...e.filter(S=>br(S))]:y===gr.PUBLIC&&(f=[...f,...e.filter(S=>!br(S))])}),u(f)}return this.getCustomContextFilterEntries(t).forEach(({key:f,values:y})=>{let S=this.matchAnnotationsByContext(e,f,y);u(S)}),a!==Kr.AND&&(d?i=e.filter(f=>m.has(f.annotationId)):i=e),i}catch(a){return this.loggingService.catch("Error in CommentService applyDirectFilters: ",a),e}}applyCommentSidebarClientFilters(e,t){return this.applyDirectFilters(e,t)}getCustomContextFilterEntries(e){try{if(!e)return[];let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]),a=[];return Object.keys(e).forEach(i=>{if(t.has(i))return;let d=e[i];!Array.isArray(d)||!d.length||a.push({key:i,values:d})}),a}catch(t){return this.loggingService.catch("Error in CommentService getCustomContextFilterEntries: ",t),[]}}matchAnnotationsByContext(e,t,a){try{return e.filter(i=>{let d=i.context?.[t];return d==null?!1:a.some(m=>{let u=typeof m=="string"?m:m?.id;return d===u||d?.toString()===u})})}catch(i){return this.loggingService.catch("Error in CommentService matchAnnotationsByContext: ",i),[]}}filterAnnotationsByPeople(e,t){try{return e.id?t.filter(a=>a?.from?.userId===e.id||a?.from?.email===e.id):t}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByPeople: ",a),[]}}filterAnnotationsByTagged(e,t){try{return t.filter(a=>a?.comments?.some(i=>i.taggedUserContacts?.some(d=>d?.contact?.userId===e.id)))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByTagged: ",a),[]}}filterAnnotationsByAssigned(e,t){try{return t.filter(a=>a?.assignedTo?.userId===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByAssigned: ",a),[]}}filterAnnotationsByInvolved(e,t){try{return t.filter(a=>{let i=a?.from?.userId===e.id||a?.from?.email===e.id,d=a?.assignedTo?.userId===e.id,m=a?.comments?.some(u=>u.taggedUserContacts?.some(f=>f?.contact?.userId===e.id));return i||d||m})}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByInvolved: ",a),[]}}filterAnnotationsByPriority(e,t){try{return e.id==="unset"?t.filter(a=>!a?.priority):t.filter(a=>a?.priority?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByPriority: ",a),[]}}filterAnnotationsByStatus(e,t){try{return t.filter(a=>a?.status?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByStatus: ",a),[]}}filterAnnotationsByCommentCategory(e,t){try{return e.id==="other"?t.filter(a=>!a?.commentCategories?.length||a?.commentCategories?.some(i=>i.id===e.id)):t.filter(a=>(a?.commentCategories||[]).some(i=>i.id===e.id))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByCommentCategory: ",a),[]}}filterAnnotationsByVersion(e,t){try{return e.id==="unset"?t.filter(a=>!a?.location?.version):t.filter(a=>a?.location?.version?.id===e.id)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByVersion: ",a),[]}}filterAnnotationsByDocument(e,t){try{return e?.id&&e.id!=="other"?t.filter(a=>a?.metadata?.clientDocumentId?.toString()===e.id):t.filter(a=>!a?.metadata?.clientDocumentId)}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByDocument: ",a),[]}}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),a;return t?a=e||[]:e?a=[e]:a=[],this.getFilterCommentsOnDom$().pipe(Fe(i=>i?a.length===0?ye(e):Bt([this.effectiveSidebarFilters$,this.customSidebarDataAnnotationIds$]).pipe(Ee(([d,m])=>{let u=a,f=!1;if(this.hasActiveFilters(d)){let y=this.applyDirectFilters(a,d),S=new Set(y.map(j=>j.annotationId));u=u.filter(j=>j?.isDraft||S.has(j.annotationId)),f=!0}return m&&(u=u.filter(y=>y?.isDraft||y?.annotationId&&m.has(y.annotationId)),f=!0),f?t?u:u.length>0?u[0]:null:e})):ye(e)))}catch{return ye(e)}}enableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!0)return;this.focusedThreadMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFocusedThreadMode: ",e)}}disableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!1)return;this.focusedThreadMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFocusedThreadMode: ",e)}}getFocusedThreadMode$(){return this.focusedThreadMode$.asObservable()}enableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{openAnnotationInFocusMode:!0}}),this.openAnnotationInFocusMode$.value===!0)return;this.openAnnotationInFocusMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableOpenAnnotationInFocusMode: ",e)}}disableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{openAnnotationInFocusMode:!1}}),this.openAnnotationInFocusMode$.value===!1)return;this.openAnnotationInFocusMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableOpenAnnotationInFocusMode: ",e)}}getOpenAnnotationInFocusMode$(){return this.openAnnotationInFocusMode$.asObservable()}getOpenAnnotationInFocusMode(){return this.openAnnotationInFocusMode$.value}enableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{readOnly:!0}}),this.readOnly$.value===!0)return;this.readOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReadOnly: ",e)}}disableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{readOnly:!1}}),this.readOnly$.value===!1)return;this.readOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReadOnly: ",e)}}getReadOnly$(){return this.readOnly$.asObservable()}getReadOnly(){return this.readOnly$.value}shouldEnableReadOnly(){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,a=this.docService.getDocumentIds().map(i=>i.clientDocumentId);if(e){let i=this.userPermissionService.getCurrentUserPermissions();i?.[e.userId]?t&&i[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():a.forEach(d=>{i[e.userId]?.documents?.[d]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),e}}enableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customAutocompleteSearch:!0}}),this.customAutocompleteSearch$.value===!0)return;this.customAutocompleteSearch$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCustomAutocompleteSearch: ",e)}}disableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{customAutocompleteSearch:!1}}),this.customAutocompleteSearch$.value===!1)return;this.customAutocompleteSearch$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCustomAutocompleteSearch: ",e)}}getCustomAutocompleteSearch$(){return this.customAutocompleteSearch$.asObservable()}getCustomAutocompleteSearch(){return this.customAutocompleteSearch$.value}enableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteThreadWithFirstComment:!0}}),this.deleteThreadWithFirstComment$.value===!0)return;this.deleteThreadWithFirstComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteThreadWithFirstComment: ",e)}}disableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{deleteThreadWithFirstComment:!1}}),this.deleteThreadWithFirstComment$.value===!1)return;this.deleteThreadWithFirstComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteThreadWithFirstComment: ",e)}}getDeleteThreadWithFirstComment$(){return this.deleteThreadWithFirstComment$.asObservable()}enableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{expandMentionGroups:!0}}),this.expandMentionGroups$.value===!0)return;this.expandMentionGroups$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableExpandMentionGroups: ",e)}}disableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{expandMentionGroups:!1}}),this.expandMentionGroups$.value===!1)return;this.expandMentionGroups$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableExpandMentionGroups: ",e)}}getExpandMentionGroups$(){return this.expandMentionGroups$.asObservable()}getExpandMentionGroups(){return this.expandMentionGroups$.value}enableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsFirst:!0}}),this.showMentionGroupsFirst$.value===!0)return;this.showMentionGroupsFirst$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsFirst: ",e)}}disableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsFirst:!1}}),this.showMentionGroupsFirst$.value===!1)return;this.showMentionGroupsFirst$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsFirst: ",e)}}getShowMentionGroupsFirst$(){return this.showMentionGroupsFirst$.asObservable()}getShowMentionGroupsFirst(){return this.showMentionGroupsFirst$.value}enableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsOnly:!0}}),this.showMentionGroupsOnly$.value===!0)return;this.showMentionGroupsOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsOnly: ",e)}}disableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{showMentionGroupsOnly:!1}}),this.showMentionGroupsOnly$.value===!1)return;this.showMentionGroupsOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsOnly: ",e)}}getShowMentionGroupsOnly$(){return this.showMentionGroupsOnly$.asObservable()}getShowMentionGroupsOnly(){return this.showMentionGroupsOnly$.value}setAnalyticsFeatureConfig({config:e,feature:t}){try{this.analyticsService.setFeatureConfig({feature:t||ke.COMMENT,config:e})}catch(a){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",a)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let a=JSON.parse(JSON.stringify(e));if(delete a.accessFields,delete a.access,Object.keys(a).length){let i=Cn(a),d=JSON.stringify(i);t=fr(d)}}return t}catch{return}}splitProgressCommentsStage(e){try{if(!Array.isArray(e))return e;let t=!1;return e.forEach(a=>{let i=a?.annotationId;if(typeof i!="string"||!i)return;let{comments:d,progress:m}=$h(a);!m.length&&!this.progressCommentsByAnnotationId.has(i)||(a.comments=d,m.length?(this.progressCommentsByAnnotationId.set(i,m),t=!0):(this.progressCommentsByAnnotationId.delete(i)&&(t=!0),this.progressOnlyAnnotationsLogged.delete(i)),!d.length&&m.length&&!this.progressOnlyAnnotationsLogged.has(i)&&(this.progressOnlyAnnotationsLogged.add(i),this.loggingService.log("[velt] progress: annotation currently has only content-less progress comments: "+i)))}),t&&this.progressCommentsVersion$.next(this.progressCommentsVersion$.value+1),e}catch(t){return this.loggingService.catch("Error in CommentService splitProgressCommentsStage:",t),e}}getProgressCommentsVersion$(){return this.progressCommentsVersion$.asObservable()}getFullComments(e){try{let t=Array.isArray(e?.comments)?e.comments:[],a=this.getProgressComments(e?.annotationId);return a.length?[...t,...a].sort((i,d)=>{let m=i?.createdAt instanceof Date?i.createdAt.getTime():Number(i?.createdAt??0),u=d?.createdAt instanceof Date?d.createdAt.getTime():Number(d?.createdAt??0);return m-u}):t}catch{return e?.comments??[]}}spliceProgressCommentsIn(e){try{if(!e?.annotationId||!this.getProgressComments(e.annotationId).length)return;e.comments=this.getFullComments(e)}catch(t){this.loggingService.catch("Error in CommentService spliceProgressCommentsIn:",t)}}withProgressCommentsSpliced(e,t){return Pe(this,null,function*(){try{this.spliceProgressCommentsIn(e);try{return yield t()}finally{this.restoreProgressCommentSplit(e)}}catch(a){this.loggingService.catch("Error in CommentService withProgressCommentsSpliced:",a);return}})}restoreProgressCommentSplit(e){try{if(!e?.annotationId||!this.getProgressComments(e.annotationId).length)return;let{comments:t}=$h(e);e.comments=t}catch(t){this.loggingService.catch("Error in CommentService restoreProgressCommentSplit:",t)}}hasRenderableContent(e){try{if(!e)return!1;if(e.comments?.length)return!0;let t=e.annotationId;if(typeof t!="string"||!t)return!1;let a=Date.now(),i=this.getCommentProgressStaleAfter();return this.getProgressComments(t).some(d=>lp(d,i,a))}catch{return!!e?.comments?.length}}getProgressComments(e){try{return this.progressCommentsByAnnotationId.get(e)??[]}catch{return[]}}evictProgressComments(e){try{e?.forEach(t=>{this.progressCommentsByAnnotationId.delete(t),this.progressOnlyAnnotationsLogged.delete(t)})}catch(t){this.loggingService.catch("Error in CommentService evictProgressComments:",t)}}setCommentProgressStaleAfter(e){try{let t=Number(e);if(!Number.isFinite(t)||t<=0||this.commentProgressStaleAfter$.value===t)return;this.commentProgressStaleAfter$.next(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentProgressStaleAfter:",t)}}getCommentProgressStaleAfter$(){return this.commentProgressStaleAfter$.asObservable()}getCommentProgressStaleAfter(){return this.commentProgressStaleAfter$.value}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}setEditplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editplaceholder:e}}),this.editplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditplaceholder: ",t)}}getEditplaceholder$(){return this.editplaceholder$.asObservable()}getEditplaceholder(){return this.editplaceholder$.value}setEditcommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editcommentplaceholder:e}}),this.editcommentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditcommentplaceholder: ",t)}}getEditcommentplaceholder$(){return this.editcommentplaceholder$.asObservable()}getEditcommentplaceholder(){return this.editcommentplaceholder$.value}setEditreplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{editreplyplaceholder:e}}),this.editreplyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditreplyplaceholder: ",t)}}getEditreplyplaceholder$(){return this.editreplyplaceholder$.asObservable()}getEditreplyplaceholder(){return this.editreplyplaceholder$.value}enableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{screenshotEnabled:!0}}),this.screenshotEnabled$.value===!0)return;this.screenshotEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScreenshot: ",e)}}disableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{screenshotEnabled:!1}}),this.screenshotEnabled$.value===!1)return;this.screenshotEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScreenshot: ",e)}}getScreenshotEnabled$(){return this.screenshotEnabled$.asObservable()}getScreenshotEnabled(){return this.screenshotEnabled$.value}getAnnotationNumber(e){try{let t=this.commentAnnotationById$.value||{},a=-1,i=Object.values(t).filter(d=>{let m=d.metadata?.documentId===e.metadata?.documentId;return m&&d.annotationNumber&&(a=Math.max(a,d.annotationNumber)),m});return a===-1?i.length+1:a+1}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationNumber: ",t),null}}enableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullScreen:!0}}),this.fullScreenInSidebar$.value===!0)return;this.fullScreenInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullScreenInSidebar: ",e)}}disableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{fullScreen:!1}}),this.fullScreenInSidebar$.value===!1)return;this.fullScreenInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullScreenInSidebar: ",e)}}getFullScreenInSidebar$(){return this.fullScreenInSidebar$.asObservable()}getFullScreenInSidebar(){return this.fullScreenInSidebar$.value}setComposerFileAttachments(e){try{this.composerFileAttachments$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerFileAttachments: ",t)}}getComposerFileAttachments$(){return this.composerFileAttachments$.asObservable()}getComposerFileAttachments(){return this.composerFileAttachments$.value}clearComposerFileAttachments(){try{this.composerFileAttachments$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearComposerFileAttachments: ",e)}}enableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!0)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentNameInMessage:!0}}),this.attachmentNameInMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentNameInMessage: ",e)}}disableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!1)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{attachmentNameInMessage:!1}}),this.attachmentNameInMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentNameInMessage: ",e)}}getAttachmentNameInMessage$(){return this.attachmentNameInMessage$.asObservable()}getAttachmentNameInMessage(){return this.attachmentNameInMessage$.value}setAllowedFileTypes(e){try{this.allowedFileTypes$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedFileTypes: ",t)}}getAllowedFileTypes$(){return this.allowedFileTypes$.asObservable()}getAllowedFileTypes(){return this.allowedFileTypes$.value}enableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!0)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{forceCloseAllOnEsc:!0}}),this.forceCloseAllOnEsc$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableForceCloseAllOnEsc: ",e)}}disableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!1)return;this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{forceCloseAllOnEsc:!1}}),this.forceCloseAllOnEsc$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableForceCloseAllOnEsc: ",e)}}getForceCloseAllOnEsc$(){return this.forceCloseAllOnEsc$.asObservable()}getForceCloseAllOnEsc(){return this.forceCloseAllOnEsc$.value}markAsRead(e){return Pe(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsRead(t)))}catch(t){this.loggingService.catch("Error in ViewsService markAsRead:",t)}})}markAsUnread(e){return Pe(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.withProgressCommentsSpliced(t,()=>this.viewsService?.setCommentAnnotationAsUnread(t)))}catch(t){this.loggingService.catch("Error in ViewsService markAsUnread:",t)}})}setAutoCompleteScrollConfig(e){try{this.analyticsService.setFeatureConfig({feature:ke.COMMENT,config:{autoCompleteScrollConfig:e}});let t=this.autoCompleteScrollConfig$.value,a={itemSize:e.itemSize??t.itemSize,minBufferPx:e.minBufferPx??t.minBufferPx,maxBufferPx:e.maxBufferPx??t.maxBufferPx,templateCacheSize:e.templateCacheSize??t.templateCacheSize};this.autoCompleteScrollConfig$.next(a)}catch(t){this.loggingService.catch("Error in CommentService setAutoCompleteScrollConfig: ",t)}}getAutoCompleteScrollConfig(){return this.autoCompleteScrollConfig$.value}getAutoCompleteScrollConfig$(){return this.autoCompleteScrollConfig$.asObservable()}submitComment(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: submitComment","color: green;"),this.submitComment$.next(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService submitComment: ",t)}}onSubmitComment$(){return this.submitComment$.asObservable()}clearComposer(e){try{this.clearComposer$.next(e.targetComposerElementId),this.composerDataMap.delete(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService clearComposer: ",t)}}onClearComposer$(){return this.clearComposer$.asObservable()}emitComposerTextChange(e,t,a){try{this.commentActionsService?.onComposerTextChange({text:e,annotation:t,targetComposerElementId:a})}catch(i){this.loggingService.catch("Error in CommentService emitComposerTextChange: ",i)}}setComposerData(e,t){try{this.composerDataMap.set(e,t)}catch(a){this.loggingService.catch("Error in CommentService setComposerData: ",a)}}clearComposerData(e){try{this.composerDataMap.delete(e)}catch(t){this.loggingService.catch("Error in CommentService clearComposerData: ",t)}}getComposerData(e){try{return this.composerDataMap.get(e.targetComposerElementId)||null}catch(t){return this.loggingService.catch("Error in CommentService getComposerData: ",t),null}}};o.PORTABLE_ACTIVATION_WAIT_MS=1e4,o.\u0275fac=function(t){return new(t||o)(be(pr),be(_o),be(kc),be(ut),be(KC),be(vt),be(Re),be(Zb),be(t0),be(zt),be(E0),be(Qb),be(oC),be(wr),be(A),be(O0),be(St),be(nk),be(Sr),be(p0),be(Ju),be(s0),be(d0),be(tp))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function BD(r){try{let o=(r?.composerContent??"").replace(/\s+/g," ").trim();if(o)return o;let n=r?.recordingCount??0;if(n>0)return`${n} ${n===1?"recording":"recordings"}`;let e=r?.attachmentCount??0;return e>0?`${e} ${e===1?"attachment":"attachments"}`:""}catch{return""}}function ik(r,o){let n=[];if(!o)return n;let e=0;for(;;){let t=r.indexOf(o,e);if(t<0)return n;n.push(t),e=t+1}}function ak(r,o,n,e){let t=ik(r,o.contextBefore+n+o.contextAfter),a=t.length>=o.occurrence?t[o.occurrence-1]:t.length===1?t[0]:void 0;if(a===void 0)return null;let i=a+o.contextBefore.length;return{form:e,start:i,end:i+n.length}}function cp(r,o,n,e){let t=o.contextBefore,a=o.contextAfter;if(!t&&!a)return null;for(let i=t.length,d=a.length,m=!0;Math.max(i,d)>=4;i=Math.floor(i/2),d=Math.floor(d/2),m=!1){let u=m?[[i,0],[0,d]]:[[i,d],[i,0],[0,d]];for(let[f,y]of u){if(Math.max(f,y)<4)continue;let S=t.slice(t.length-f),j=a.slice(0,y),W=ik(r,S+n+j);if(W.length===1){let $=W[0]+S.length;return{form:e,start:$,end:$+n.length}}}}return null}var Bm=r=>r.replace(/\u00a0/g," ");function mp(r,o){if(!r||!o||!o.removed&&!o.added&&!o.contextBefore&&!o.contextAfter)return null;let n=Bm(r),e={removed:Bm(o.removed),added:Bm(o.added),contextBefore:Bm(o.contextBefore),contextAfter:Bm(o.contextAfter),occurrence:o.occurrence},t=ak(n,e,e.removed,"original")??ak(n,e,e.added,"edited");return t||(!e.removed&&e.added?cp(n,e,e.added,"edited")??cp(n,e,e.removed,"original"):cp(n,e,e.removed,"original")??cp(n,e,e.added,"edited"))}function wc(r){let o=r.documentIds?[{key:"documentIds",field:"metadata.documentId",op:"in",value:r.documentIds}]:[],n=r.folder?[{key:"folderId",field:"metadata.veltFolderId",op:"=="}]:[],e=[...r.filters?.statusIds?.length?[{key:"statusIds",field:"status.id",op:"in",value:r.filters.statusIds}]:[],...r.filters?.locationIds?.length?[{key:"locationIds",field:"location.id",op:"in",value:r.filters.locationIds}]:[],...r.filters?.agentFields?.length?[{key:"agentFields",field:"agent.agentFields",op:"array-contains-any",value:r.filters.agentFields}]:[]];return{clauses:r.layout==="perDocument"?[...o,...n,...e]:[...e,...o,...n],countsRead:!r.filters?.agentFields?.length}}function lk(r){if(r.mode.isFolderMode)return{key:r.folderId??"",queries:[wc({layout:"aggregate",folder:!0,filters:r.filters})]};if(r.mode.isOrgMode)return{key:r.clientOrganizationId??"",queries:[wc({layout:"aggregate",folder:!1,filters:r.filters})]};let o=[];for(let n=0;n<r.serverDocumentIds.length;n+=r.batchSize)o.push(wc({layout:"aggregate",documentIds:r.serverDocumentIds.slice(n,n+r.batchSize),folder:r.hasFolder,filters:r.filters}));return{key:"result",queries:o}}function sp(r,o){let n={organizationId:o.organizationId};for(let e of r.clauses)n[e.key]=e.key==="folderId"?o.folderId:e.value;return n}var Dc={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0};function dk(r){return r.sort().join(",")}function vk(r){let o=r,n=typeof o?.total=="number"&&Number.isFinite(o.total)?o.total:0,e=typeof o?.unread=="number"&&Number.isFinite(o.unread)?o.unread:0;return{total:n,unread:e}}var gp=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y){this.authService=e,this.iamService=t,this.docService=a,this.configService=i,this.commonDbService=d,this.loggingService=m,this.commentService=u,this.userPermissionService=f,this.adapterSelectorService=y,this.documentPaths=null,this.LISTENER_BATCH_SIZE=5}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(qt(t=>!!t),Fe(t=>this.docService.getOrganizationConfig$().pipe(qt(a=>!!a),Ee(()=>t))),Fe(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),Fe(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(Ee(a=>(t.featureAllowed=a,t))):ye(t)),Fe(t=>t.featureAllowed?this.processRequest(t,e):ye(null)),Ee(t=>t??{data:null}),Gt(Qn))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),ye({data:null})}}processRequest(e,t){try{return ye(e).pipe(Fe(()=>this.initializeDocumentPaths(t,e)),Fe(()=>this.getDocumentIds$(t)),Fe(a=>{let i=this.authService.getUser()?.userSnippylyId,d=this.buildRequestContext(t,a);if(!this.validateRequestContext(d,t))return ye({data:null,mode:d.mode,serverDocumentIds:d.serverDocumentIds});if(!d.organizationId)return ye({data:null,mode:d.mode,serverDocumentIds:d.serverDocumentIds});let m=this.setupTriggers$(d.mode,d.organizationId,d.clientOrganizationId,d.veltFolderId,d.serverDocumentIds);if(this.shouldUseAggregateMode(d.mode))return this.handleAggregateCounts$({triggers$:m,serverDocumentIds:d.serverDocumentIds,request:t,userId:i,organizationId:d.organizationId,clientOrganizationId:d.clientOrganizationId,veltFolderId:d.veltFolderId,folderId:d.folderId,mode:d.mode}).pipe(Ee(u=>({data:u,mode:d.mode,serverDocumentIds:d.serverDocumentIds})));if(d.mode.isBatchedGroupedMode){let u=t?.debounceMs??5e3;return this.handleBatchedGroupedCounts$({triggers$:m,documentIds:a,request:t,userId:i,organizationId:d.organizationId,veltFolderId:d.veltFolderId,debounceMs:u,portableIds:{clientOrganizationId:d.clientOrganizationId??"",folderId:d.folderId}}).pipe(Ee(f=>({data:f,mode:d.mode,serverDocumentIds:d.serverDocumentIds})))}else return this.handleGroupedCounts$(m,a,t,i,d.organizationId,d.veltFolderId,{clientOrganizationId:d.clientOrganizationId??"",folderId:d.folderId}).pipe(Ee(u=>({data:u,mode:d.mode,serverDocumentIds:d.serverDocumentIds})))}),Fe(a=>{if(!a?.data)return ye(null);let{data:i,mode:d,serverDocumentIds:m}=a;return t?.filterGhostComments?this.filterGhostComments$(i,d,m):ye(i)}),Wr(a=>(this.loggingService.catch("Error processing request: ",a),ye(null))))}catch(a){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",a),ye(null)}}initializeDocumentPaths(e,t){try{return e?ye(t):this.docService.getDocumentPaths$().pipe(qt(a=>!!a),Tm(a=>{this.documentPaths=a,t.documentPaths=a}),Ee(()=>{}))}catch(a){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",a),ye(t)}}buildRequestContext(e,t){try{let a=this.docService.getOrganizationConfig(),i=this.documentPaths?.organizationId??a?.organizationId,d=this.documentPaths?.clientOrganizationId??a?.clientOrganizationId,m,u,f;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(i=pc(e.organizationId),d=e.organizationId),!i)throw new Error("organizationId is required for this request type");e.folderId&&(m=ur(e.folderId),u=e.folderId),e.allDocuments&&(f=!0)}else m=this.documentPaths?.veltFolderId,u=this.documentPaths?.folderId,f=this.documentPaths?.allDocuments;let y=this.determineMode(e,m,f,t),S=y.isOrgMode?[]:t.length>0?t.map(j=>j.documentId):[this.documentPaths?.documentId??""];return{organizationId:i,clientOrganizationId:d,veltFolderId:m,folderId:u,allDocuments:f,mode:y,serverDocumentIds:S}}catch(a){return this.loggingService.catch("Error in CommentService buildRequestContext: ",a),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(a=>!a))}catch(a){return this.loggingService.catch("Error in CommentService validateRequestContext: ",a),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?ye(e.documentIds.map(t=>({clientDocumentId:t,documentId:Au(t)}))):this.docService.getDocumentIds$().pipe(Ee(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),ye([])}}determineMode(e,t,a,i){try{let d=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!a,m=!!t&&!!a,u=!!e?.aggregateDocuments&&!a&&!!i?.length,f=(!!e?.batchedPerDocument||i.length>1)&&!!i?.length&&!e?.aggregateDocuments&&!a;return{isOrgMode:d,isFolderMode:m,isBatchMode:u,isBatchedGroupedMode:f}}catch(d){return this.loggingService.catch("Error in CommentService determineMode: ",d),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1}}}setupTriggers$(e,t,a,i,d){try{return this.adapterSelectorService?.isPortableSession?.()===!0?this.setupPortableTriggers$(e,t,a,i,d):this.setupHostedTriggers$(e,t,a,i,d)}catch(m){return this.loggingService.catch("Error in CommentService setupTriggers: ",m),[]}}setupHostedTriggers$(e,t,a,i,d){if(e.isOrgMode){let m=this.gateOnOrganizationAccess$(a,()=>this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}));return[this.commentViewsTimestampTrigger$(m)]}else if(e.isFolderMode){let m=this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:i,organizationId:t}});return[this.commentViewsTimestampTrigger$(m)]}else return e.isBatchMode||e.isBatchedGroupedMode?this.batchDocumentIds(d).map(u=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[Xn(Et("metadata.apiKey","==",this.configService?.getApiKey()),Et("metadata.organizationId","==",t),Et("metadata.documentId","in",u))]}}).pipe(Ee(y=>dk(Object.values(y?.data||{}).map(S=>S?.commentViewsUpdatedAt??null))),Gt(Qn))):d.map(m=>{let u=this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:m,organizationId:t}});return this.commentViewsTimestampTrigger$(u)})}batchDocumentIds(e){let t=[];for(let a=0;a<e.length;a+=this.LISTENER_BATCH_SIZE)t.push(e.slice(a,a+this.LISTENER_BATCH_SIZE));return t}gateOnOrganizationAccess$(e,t){let a=this.authService.getUser()?.userId??"";return jn(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:e})??Promise.resolve({})).pipe(Fe(i=>a&&i?.[a]?.organization?.[e]?.errorCode===Mu.PERMISSION_DENIED?(this.loggingService.log(`%c[WB] commentViews org listener skipped \u2014 user does not have access to organization: ${e}`,"color: orange;"),Hr):t()))}commentViewsTimestampTrigger$(e){return e.pipe(Ee(t=>t?.data?.commentViewsUpdatedAt??null),qt(t=>!!t),Gt(Qn))}setupPortableTriggers$(e,t,a,i,d){let m=this.batchDocumentIds(d),u=e.isOrgMode||e.isFolderMode?1:e.isBatchMode||e.isBatchedGroupedMode?m.length:d.length,f=null,y=S=>(f=f??this.setupHostedTriggers$(e,t,a,i,d),f[S]??Hr);return Array.from({length:u},(S,j)=>this.rebuiltOnPortableRegistration$(()=>this.liveCommentViewsAvailable(),W=>W?e.isOrgMode?this.portableOrganizationTrigger$(t,a):e.isFolderMode?this.portableFolderTrigger$(t,i):e.isBatchMode||e.isBatchedGroupedMode?this.portableBatchTrigger$(t,m[j]??[]):this.commentViewsTimestampTrigger$(this.portableDocumentListener$(t,d[j])):y(j)))}liveCommentViewsAvailable(){try{return this.adapterSelectorService?.isPortableBackendActive?.()===!0&&this.adapterSelectorService.portableConnectionAnnounces(e0)===!0}catch(e){return this.loggingService.catch("Error in CommentViewsService liveCommentViewsAvailable: ",e),!1}}rebuiltOnPortableRegistration$(e,t){return new ac(a=>{a.next();let i=Gu(()=>a.next()),d;try{d=this.adapterSelectorService?.portableConnectionChanges$?.().pipe(Dn(1)).subscribe(()=>a.next())}catch(m){this.loggingService.catch("Error binding the comment-views trigger connection listener: ",m)}return()=>{try{i(),d?.unsubscribe()}catch(m){this.loggingService.catch("Error disposing the comment-views trigger registration listener: ",m)}}}).pipe(Ee(()=>e()),Gt(),Fe(a=>t(a)))}portableOrganizationTrigger$(e,t){return this.commentViewsTimestampTrigger$(this.gateOnOrganizationAccess$(t,()=>this.commonDbService.dbListener({feature:"organizationCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:e}})))}portableFolderTrigger$(e,t){return this.commentViewsTimestampTrigger$(this.commonDbService.dbListener({feature:"folderCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:e,folderId:t,id:t}}))}portableDocumentListener$(e,t){return this.commonDbService.dbListener({feature:"documentCommentViews",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t,organizationId:e}})}portableBatchTrigger$(e,t){return t.length?Bt(t.map(a=>this.portableDocumentListener$(e,a).pipe(Ee(i=>i?.data?.commentViewsUpdatedAt??null)))).pipe(Ee(a=>dk([...a])),Gt(Qn)):Hr}handleGroupedCounts$(e,t,a,i,d,m,u){try{let f=t.map((y,S)=>e[S].pipe(Ch(void 0),Fe(()=>jn(this.getCountsForDocument$(y.documentId,y.clientDocumentId,a,i,d,m,u)))));return Bt(f).pipe(Ee(y=>{let S={};return y.forEach(j=>{j&&(S[j.clientDocumentId]={total:j.total,unread:j.unread})}),{data:S}}),Wr(y=>(this.loggingService.catch("Error in grouped counts: ",y),ye(null))))}catch(f){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",f),ye(null)}}handleBatchedGroupedCounts$(e){try{let{triggers$:t,documentIds:a,request:i,userId:d,organizationId:m,veltFolderId:u,debounceMs:f,portableIds:y}=e,S=this.LISTENER_BATCH_SIZE,j=new db(1),W=t.map((ce,fe)=>ce.pipe(hb(j),Ee(()=>fe))),$=Ko(...W).pipe(po(f)),H=ye(-1).pipe(Fe(()=>jn(this.fetchAllDocumentCounts$(a,i,d,m,u,y))),Ee(ce=>({batchIndex:-1,data:ce?.data||{}})),Tm(()=>{j.next()})),q=$.pipe(Fe(ce=>{let fe=ce*S,le=Math.min(fe+S,a.length),he=a.slice(fe,le);return jn(this.fetchAllDocumentCounts$(he,i,d,m,u,y)).pipe(Ee(xe=>({batchIndex:ce,data:xe?.data||{}})))}));return Ko(H,q).pipe(gb((ce,fe)=>({data:g(g({},ce.data),fe.data)}),{data:{}}),Wr(ce=>(this.loggingService.catch("Error in batched grouped counts: ",ce),ye(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleBatchedGroupedCounts: ",t),ye(null)}}fetchAllDocumentCounts$(e,t,a,i,d,m){return Pe(this,null,function*(){try{if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0)return yield this.fetchPortablePerDocumentCounts(e,t,d,m);let u=e.map(S=>this.getCountsForDocument$(S.documentId,S.clientDocumentId,t,a,i,d)),f=yield Promise.allSettled(u),y={};return f.forEach(S=>{if(S.status==="fulfilled"&&S.value){let{clientDocumentId:j,total:W,unread:$}=S.value;y[j]={total:W,unread:$}}}),{data:y}}catch(u){return this.loggingService.catch("Error in CommentService fetchAllDocumentCounts: ",u),null}})}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:a,request:i,userId:d,organizationId:m,clientOrganizationId:u,veltFolderId:f,folderId:y,mode:S}=e;return Bt(t).pipe(Ee(()=>{})).pipe(Ch(void 0),Fe(()=>jn(this.getAggregateCounts({serverDocumentIds:a,request:i,userId:d,organizationId:m,clientOrganizationId:u,veltFolderId:f,folderId:y,mode:S}))),Wr(W=>(this.loggingService.catch("Error in aggregate counts: ",W),ye(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),ye(null)}}getCountsForDocument$(e,t,a,i,d,m,u){return Pe(this,null,function*(){try{let f=wc({layout:"perDocument",documentIds:[e],folder:!!m,filters:a});if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0){let W=yield this.countCommentsOnPortable(sp(f,{organizationId:u?.clientOrganizationId??"",folderId:u?.folderId}));return g({clientDocumentId:t},W)}let y=this.toFirestoreCountQueries(f,{apiKey:this.configService?.getApiKey(),organizationId:d,veltFolderId:m,userId:i}),S=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:y.total})}),j=0;return y.read&&(j=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:y.read})})),{clientDocumentId:t,total:S,unread:S-j}}catch(f){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",f),null}})}getAggregateCounts(e){return Pe(this,null,function*(){try{let{serverDocumentIds:t,request:a,userId:i,organizationId:d,clientOrganizationId:m,veltFolderId:u,folderId:f,mode:y}=e,S=lk({mode:y,serverDocumentIds:t,hasFolder:!!u,filters:a,batchSize:this.LISTENER_BATCH_SIZE,folderId:f,clientOrganizationId:m});if(this.commonDbService?.isPortableCommentQueryCandidate?.()===!0)return yield this.getPortableAggregateCounts(S,{clientOrganizationId:m,folderId:f});let j=S.key,W={apiKey:this.configService?.getApiKey(),organizationId:d,veltFolderId:u,userId:i},$,H=0;if(y.isFolderMode||y.isOrgMode){let q=this.toFirestoreCountQueries(S.queries[0],W);$=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:q.total})}),q.read&&(H=yield this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:q.read})}))}else{let q=S.queries.map(le=>this.toFirestoreCountQueries(le,W));$=(yield Promise.allSettled(q.map(le=>Pe(this,null,function*(){return this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:le.total})})})))).reduce((le,he)=>le+(he.status==="fulfilled"&&he.value||0),0);let fe=q.filter(le=>le.read);fe.length&&(H=(yield Promise.allSettled(fe.map(he=>Pe(this,null,function*(){return this.commonDbService.queryData({feature:"allComments",properties:b(g({},Dc),{firestoreQuery:he.read})})})))).reduce((he,xe)=>he+(xe.status==="fulfilled"&&xe.value||0),0))}return{data:{[j]:{total:$,unread:$-H}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}countCommentsOnPortable(e){return Pe(this,null,function*(){try{let t=yield this.commonDbService.runPortableCommentQuery("getCommentAnnotationsCount",e);return t?.ok?vk(t.data):{total:0,unread:0}}catch(t){return this.loggingService.catch("Error in CommentViewsService countCommentsOnPortable: ",t),{total:0,unread:0}}})}fetchPortablePerDocumentCounts(e,t,a,i){return Pe(this,null,function*(){try{let d={},m=[];for(let u=0;u<e.length;u+=Z.FIRESTORE_IN_QUERY_LIMIT)m.push(e.slice(u,u+Z.FIRESTORE_IN_QUERY_LIMIT));return yield Promise.all(m.map(u=>Pe(this,null,function*(){let f=wc({layout:"perDocument",documentIds:u.map(j=>j.documentId),folder:!!a,filters:t}),y=yield this.commonDbService.runPortableCommentQuery("getCommentAnnotationsCount",b(g({},sp(f,{organizationId:i?.clientOrganizationId??"",folderId:i?.folderId})),{perDocument:!0})),S=y?.ok?y.data?.counts:void 0;for(let j of u)d[j.clientDocumentId]=vk(S?.[j.documentId])}))),{data:d}}catch(d){return this.loggingService.catch("Error in CommentViewsService fetchPortablePerDocumentCounts: ",d),null}})}getPortableAggregateCounts(e,t){return Pe(this,null,function*(){try{let a=yield Promise.all(e.queries.map(m=>this.countCommentsOnPortable(sp(m,{organizationId:t.clientOrganizationId??"",folderId:t.folderId})))),i=a.reduce((m,u)=>m+u.total,0),d=a.reduce((m,u)=>m+u.unread,0);return{data:{[e.key]:{total:i,unread:d}}}}catch(a){return this.loggingService.catch("Error in CommentViewsService getPortableAggregateCounts: ",a),null}})}toFirestoreCountQueries(e,t){let a=[Et("metadata.apiKey","==",t.apiKey),Et("metadata.organizationId","==",t.organizationId),...e.clauses.map(d=>Et(d.field,d.op,d.key==="folderId"?t.veltFolderId:d.value))],i=yc(xc);return g({total:[Xn(...a),...i]},e.countsRead?{read:[Xn(...a,Et("viewedByUserIds","array-contains",t.userId)),...i]}:{})}filterGhostComments$(e,t,a){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(Ee(i=>{if(!i)return e;let d=this.buildGhostCommentAnnotationMap(i),m=this.groupGhostCommentsByModeId(d,t,a);return this.adjustCountsForGhostComments(e,m),e})):ye(null)}catch(i){return this.loggingService.catch("Error in CommentService filterGhostComments: ",i),ye(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(a=>{let i=this.commentService.getAnnotationById(a);i&&(t[a]=i)}),t}groupGhostCommentsByModeId(e,t,a){try{let i={};return Object.values(e).forEach(d=>{let m=this.getModeIdForAnnotation(d,t,a);m&&(i[m]||(i[m]=[]),i[m].push(d))}),i}catch(i){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",i),{}}}getModeIdForAnnotation(e,t,a){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?a.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(i){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",i),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let i=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(d=>{let m=t[d];if(!(!m||!e?.data?.[d]?.total)&&(e.data[d].total=Math.max(0,e.data[d].total-m.length),i)){let u=m.filter(f=>f?.viewedByUserIds&&!f?.viewedByUserIds?.includes(i));u.length>0&&(e.data[d].unread=Math.max(0,e.data[d].unread-u.length))}})}catch(a){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",a)}}};o.\u0275fac=function(t){return new(t||o)(be(vt),be(wr),be(ut),be(kc),be(_o),be(A),be(ae),be(tp),be(XC))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var $D=1e4,lt=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f,y,S,j,W,$,H,q){this.analyticsService=e,this.authService=t,this.commentService=a,this.commentViewsService=i,this.contactService=d,this.customFilterService=m,this.docService=u,this.iamService=f,this.loggingService=y,this.metadataService=S,this.commonDbService=j,this.serviceBook=W,this.suggestionActions=$,this.targetRegistry=H,this.commentAnnotationsResolverService=q,this.recentAccepts=new Map,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.reactionService=null,this.inFlightSuggestionTransitions=new Set,this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;");try{this.commentService.setCommentActionsService(this),this.iamService.isUserAdmin$().subscribe(ce=>{this.isUserAdmin=ce}),this.serviceBook.observe(ju).subscribe(ce=>{this.reactionService=ce})}catch(ce){this.loggingService.catch("Error in CommentActionsService constructor: ",ce)}}addCommentAnnotation(d,m){return Pe(this,arguments,function*({annotation:e,options:t,visibility:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addCommentAnnotation","color: green;"),a){if(a.type==="restricted"){let y=this.authService.getUser();y?.userId&&(a=xo(a,y.userId))}if(a.type==="organizationPrivate"&&!a.organizationId&&!a.organizationIds?.length){let y=this.authService.getUser()?.clientOrganizationId;y&&(a=b(g({},a),{organizationId:y}))}let u=this.authService.getUser()?.userId,f=qn(a,u);f.length>0&&(e.context||(e.context={}),e.context._setAccessFields=f,e.visibilityConfig=Zn(a,u))}return new Promise(u=>{this.commentService.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,f=>Pe(this,null,function*(){let y=to(void 0,f?.annotation?.assignedTo,this.onIsAssigneeChangedError),S=yield this.getAddCommentAnnotationEventFromCommentAddEventData(f,y);u(S)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,i)})}catch(u){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",u),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e,t){return Pe(this,null,function*(){try{let a=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:this.commentService.getCommentAnnotationForClient(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:a,addContext:e?.addContext,elementRef:e?.elementRef,isAssigneeChanged:t??!1}}catch(a){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",a),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ct.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}getAddCommentAnnotationDraftEventFromCommentAddEventData(e){return Pe(this,null,function*(){try{return{metadata:yield this.metadataService.getGlobalMetadata(),addContext:e?.addContext}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationDraftEvent(e){try{this.triggerAction(ct.ADD_COMMENT_ANNOTATION_DRAFT,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationDraftEvent: ",t)}}triggerAddCommentDraftEventForAnnotation(e,t){return Pe(this,null,function*(){try{if(!e?.annotationId||!t)return;let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),comment:t,metadata:a};this.triggerAction(ct.ADD_COMMENT_DRAFT,i)}catch(a){this.loggingService.catch("Error in CommentActionsService triggerAddCommentDraftEventForAnnotation: ",a)}})}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let u=this.commentService.getAnnotationById(e,t);if(u){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===u?.from?.userId){this.commentService.deleteCommentPinAnnotation(u);let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:u.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(u),metadata:y};return this.triggerAction(ct.DELETE_COMMENT_ANNOTATION,S),S}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteCommentAnnotation: ",m),null}})}updatePriority(d,m){return Pe(this,arguments,function*({annotationId:e,priority:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updatePriority","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f=JSON.parse(JSON.stringify(f));let y=f.priority?JSON.parse(JSON.stringify(f.priority)):null;y&&t&&y?.id===t?.id?f.priority=void 0:f.priority=t,this.commentService.saveComment(f,{type:qe.PRIORITY_CHANGED,newPriority:t,oldPriority:y});let S=yield this.metadataService.getGlobalMetadata(),j={newPriority:t,oldPriority:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};return this.triggerAction(ct.UPDATE_PRIORITY,j),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(f),oldPriority:f.priority,newPriority:t,commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),j}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updatePriority: ",u),null}})}updateStatus(d,m){return Pe(this,arguments,function*({annotationId:e,status:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateStatus","color: green;");let u=this.authService.getUser();if(!u)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f=JSON.parse(JSON.stringify(f));let y=f.status?JSON.parse(JSON.stringify(f.status)):null;f.status=t,f.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(f,{type:qe.STATUS_CHANGED,newStatus:t,oldStatus:y});let S=yield this.metadataService.getGlobalMetadata(),j={newStatus:t,oldStatus:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};return this.triggerAction(ct.UPDATE_STATUS,j),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(f),oldStatus:y,newStatus:t,commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,commentAnnotationCreatedAt:f.createdAt}),j}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateStatus: ",u),null}})}updateAccess(d,m){return Pe(this,arguments,function*({annotationId:e,accessMode:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateAccess","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f)if(this.commentService.isPrivateCommentAllowed()){f=JSON.parse(JSON.stringify(f));let y=f.iam?.accessMode;f.iam.accessMode=t,this.commentService.saveComment(f,{type:qe.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:y});let S=yield this.metadataService.getGlobalMetadata(),j={newAccessMode:t,oldAccessMode:y,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:S};switch(this.triggerAction(ct.UPDATE_ACCESS,j),t){case gr.PRIVATE:this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:gr.PRIVATE,source:i??this.defaultSource});break;case gr.PUBLIC:this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:gr.PUBLIC,source:i??this.defaultSource});break;default:break}return j}else this.loggingService.catch("Access Denied","You must be an admin to update the access mode of the comment.");else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateAccess: ",u),null}})}resolveCommentAnnotation(a){return Pe(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: resolveCommentAnnotation","color: green;");let i=this.authService.getUser();if(!i)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let d=this.commentService.getAnnotationById(e,t);if(d){d=JSON.parse(JSON.stringify(d));let m=this.customFilterService.resolvedStatus,u=d.status?JSON.parse(JSON.stringify(d.status)):null;m&&(d.status=m,d.statusUpdatedByUserId=i?.userId,this.commentService.saveComment(d,{type:qe.STATUS_CHANGED,newStatus:m,oldStatus:u}));let f=yield this.metadataService.getGlobalMetadata(),y={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:f};return this.triggerAction(ct.RESOLVE_COMMENT,y),y}else this.triggerAnnotationNotFoundError(e);return null}catch(i){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",i),null}})}getLink(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let m=this.commentService.getAnnotationById(e,t);if(m){let u=this.commentService.getCommentUrl(m)??null,f=yield this.metadataService.getGlobalMetadata();return{link:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:f}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService getLink: ",m),null}})}copyLink(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let m=yield this.getLink({annotationId:e,options:t},a);if(m?.link){yC(m.link),this.commentService.setCopyLink(m.link),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_LINK_COPIED,{annotationId:e,commentType:this.commentService.getCommentType(m.commentAnnotation),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,link:m.link});let u=yield this.metadataService.getGlobalMetadata(),f={link:m.link,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m.commentAnnotation),metadata:u};return this.triggerAction(ct.COPY_LINK,f),f}return null}catch(m){return this.loggingService.catch("Error in CommentActionsService copyLink: ",m),null}})}addComment(f,y){return Pe(this,arguments,function*({annotationId:e,comment:t,assignedTo:a,assigned:i,options:d,visibility:m},u){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let S=this.authService.getUser();if(!S)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(S){let j=this.commentService.getAnnotationById(e,d),W=j?.comments?.length?qe.ADDED:qe.NEWLY_ADDED;if(j){let $=j.assignedTo;j.status.type==="terminal"&&(j.status=this.customFilterService.defaultStatus);let H=new Co;H=g(g({},H),t),H.lastUpdated=new Date,H.attachments||(H.attachments=[]),H.attachments=H.attachments.filter(xe=>xe?.attachmentId),H.createdAt=this.timestamp,H.from=S,a&&(j.assignedTo=a);let q=to(W===qe.NEWLY_ADDED?void 0:$,j.assignedTo,this.onIsAssigneeChangedError);this.commentService.saveComment(j,b(g({type:W,updatedComment:H,assigned:i,visibility:m},W===qe.ADDED?{_isAssigneeChanged:q}:{}),{_dispatchAddCommentEvent:!0}));let ce=b(g({},j),{comments:[...j.comments||[],H]}),fe=yield this.buildAddCommentEvent({annotation:ce,newComment:H,isAssigneeChanged:q});if(!fe)return null;let le=t?.commentId,he=this.calculateCommentThreadIndex(t,j);return this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:le,commentThreadIndex:he,commentType:this.commentService.getCommentType(j),commentMode:this.commentService.getCommentMode(),source:u??this.defaultSource,commentAnnotationCreatedAt:j.createdAt,taggedClientUserIds:H.taggedUserContacts?.map(xe=>xe.contact?.userId).filter(xe=>!!xe),taggedSnippylyUserIds:H.taggedUserContacts?.filter(xe=>!!j?.metadata?.apiKey&&!!xe.contact?.userId).map(xe=>Uu(j.metadata.apiKey,xe.contact.userId))}),fe}else this.triggerAnnotationNotFoundError(e)}return null}catch(S){return this.loggingService.catch("Error in CommentActionsService addComment: ",S),null}})}buildAddCommentEvent(i){return Pe(this,arguments,function*({annotation:e,newComment:t,isAssigneeChanged:a}){try{let d=yield this.metadataService.getGlobalMetadata();return{annotationId:e.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:d,isAssigneeChanged:a??!1}}catch(d){return this.loggingService.catch("Error in CommentActionsService buildAddCommentEvent: ",d),null}})}triggerAddCommentEvent(i){return Pe(this,arguments,function*({annotation:e,newComment:t,isAssigneeChanged:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: triggerAddCommentEvent","color: green;");let d=yield this.buildAddCommentEvent({annotation:e,newComment:t,isAssigneeChanged:a});return d&&this.triggerAction(ct.ADD_COMMENT,d),d}catch(d){return this.loggingService.catch("Error in CommentActionsService triggerAddCommentEvent: ",d),null}})}approveCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t);if(m){m.approved=!0,this.commentService.saveComment(m,{type:qe.APPROVED}),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_APPROVED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource});let u=yield this.metadataService.getGlobalMetadata(),f={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:u};return this.triggerAction(ct.APPROVE_COMMENT_ANNOTATION,f),f}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService approveComment: ",m),null}})}acceptCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=Z.CommentAcceptStatus,m.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(m,{type:qe.ACCEPTED,oldStatus:f,newStatus:Z.CommentAcceptStatus});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:y,actionUser:u,replaceContentHtml:m?.comments?.length?m?.comments[0]?.replaceContentHtml:void 0,replaceContentText:m?.comments?.length?m?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ct.ACCEPT_COMMENT_ANNOTATION,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPTED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService acceptCommentAnnotation: ",m),null}})}rejectCommentAnnotation(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=Z.CommentRejectStatus,m.statusUpdatedByUserId=u?.userId,this.commentService.saveComment(m,{type:qe.REJECTED,oldStatus:f,newStatus:Z.CommentRejectStatus});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:y,actionUser:u,replaceContentHtml:m?.comments?.length?m?.comments[0]?.replaceContentHtml:void 0,replaceContentText:m?.comments?.length?m?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ct.REJECT_COMMENT_ANNOTATION,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_REJECTED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService rejectCommentAnnotation: ",m),null}})}ensureSuggestionObject(e){try{return!e||e?.suggestion||!(e?.type==="suggestion"||e?.commentType==="suggestion")?"noop":this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.getFieldsToRemove()?.includes("suggestion")&&!this.commentAnnotationsResolverService.getCommentAnnotationById(e.annotationId)?(this.loggingService.catch(`CommentActionsService: suggestion transition refused for ${e.annotationId} \u2014 its suggestion has not loaded from the comment resolver`),"refused"):(e.suggestion={status:"pending",targetId:"",targetType:"custom",oldValue:null,newValue:null,summary:null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},"seeded")}catch(t){return this.loggingService.catch("Error in CommentActionsService ensureSuggestionObject: ",t),"noop"}}runSuggestionTransition(e,t){return Pe(this,null,function*(){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t();if(this.inFlightSuggestionTransitions.has(e))return this.loggingService.catch(`CommentActionsService: a suggestion transition is already in flight for ${e}`),null;this.inFlightSuggestionTransitions.add(e);try{return yield t()}finally{this.inFlightSuggestionTransitions.delete(e)}})}loadForSuggestionTransition(e,t,a){return Pe(this,null,function*(){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;if(!this.commentAnnotationsResolverService.getCommentAnnotationById(t)){let m=this.docService.getDocumentPaths()?.clientOrganizationId??this.authService.getUser()?.clientOrganizationId??"";if((yield this.commentAnnotationsResolverService.fetchForTransition(t,m))!=="ok")return this.loggingService.catch(`CommentActionsService: suggestion transition refused for ${t} \u2014 the comment resolver could not be reached`),null}let i=this.commentService.getAnnotationById(t,a);if(!i)return this.triggerAnnotationNotFoundError(t),null;let d=this.commentAnnotationsResolverService.getCommentAnnotationById(t)?.suggestion;return!i.suggestion&&d&&typeof d=="object"&&!Array.isArray(d)&&(i.suggestion=FC(d)),RC(i,d),i})}refusesContentlessAccept(e,t){if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()||t==="seeded")return!1;let a=e?.suggestion;return NC(a)&&Object.prototype.hasOwnProperty.call(a,"newValue")?!1:(this.loggingService.catch(`CommentActionsService: accept refused for ${e?.annotationId} \u2014 its suggestion content is not available from the comment resolver`),!0)}acceptSuggestion(e,t){return Pe(this,null,function*(){return this.runSuggestionTransition(e?.annotationId,()=>this.acceptSuggestionTransition(e,t))})}applyOnCurrentText(e,t,a){try{if(typeof a!="string"||typeof t.oldValue!="string")return;let i=S=>S.replace(/\u00a0/g," "),d=t.targetId,m=d?this.recentAccepts.get(d):void 0,f=m&&Date.now()-m.at<$D&&i(a)===i(m.oldValue)&&i(m.newValue)!==i(a)?m.newValue:a,y=null;if(i(f)!==i(t.oldValue)){let S=M0(t.textChange).value,j=S?mp(f,S):null;if(!S||!j||j.form!=="original")return;y={oldValue:f,newValue:f.slice(0,j.start)+S.added+f.slice(j.end)},this.suggestionActions.setAppliedValues(e,y)}d&&typeof t.newValue=="string"&&this.recentAccepts.set(d,b(g({},y??{oldValue:t.oldValue,newValue:t.newValue}),{at:Date.now()}))}catch(i){this.loggingService.catch("Error in CommentActionsService applyOnCurrentText: ",i)}}applyThroughSetter(e){try{let t=e.suggestion,a=t?.targetId;if(!t||!a||!this.targetRegistry.getSetter(a))return;let i=this.suggestionActions.projectAnnotationToSuggestion(e);this.targetRegistry.callSetter(a,i?i.newValue:t.newValue,{reason:"accept",suggestion:i})}catch(t){this.loggingService.catch("Error in CommentActionsService applyThroughSetter: ",t)}}acceptSuggestionTransition(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptSuggestion","color: green;");let m=this.authService.getUser();if(!m)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let u=this.commentService.getAnnotationById(e,t);if(!u)return this.triggerAnnotationNotFoundError(e),null;let f=yield this.loadForSuggestionTransition(u,e,t);if(!f)return null;let y=this.ensureSuggestionObject(f);if(y==="refused"||!(f.type==="suggestion"||f.commentType==="suggestion")||!f.suggestion||f.suggestion.status!=="pending")return null;let S=f.suggestion.targetId;if(S){let $=this.targetRegistry.getNode(S),H=this.targetRegistry.getGetter(S);if(!$&&!H){f.suggestion.status="stale",f.suggestion.resolvedBy=m,f.suggestion.resolvedAt=this.timestamp,f.statusUpdatedByUserId=m?.userId,this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"stale",targetId:S}),this.commentService.updateComment(f),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_STALE,f);let fe=yield this.metadataService.getGlobalMetadata(),le={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:fe,actionUser:m};return this.triggerAction(ct.SUGGESTION_ACCEPTED,le),le}if(this.refusesContentlessAccept(f,y))return null;let q=!1,ce;if(H)try{ce=H(),q=!xn(ce,f.suggestion.oldValue)}catch(fe){if(!$)return this.loggingService.catch("Error in acceptSuggestion: registered getter threw",fe,{targetId:S,annotationId:e}),null;q=!1}else $ instanceof HTMLElement&&$.isContentEditable&&(ce=$.textContent??"");f.suggestion.driftDetected=q,this.applyOnCurrentText(e,f.suggestion,ce)}else if(this.refusesContentlessAccept(f,y))return null;f.suggestion.status="accepted",f.suggestion.resolvedBy=m,f.suggestion.resolvedAt=this.timestamp,f.statusUpdatedByUserId=m?.userId,f.type="comment",f?.agent?.agentFields&&typeof f.agent.agentFields=="object"&&Array.isArray(f.agent.agentFields)&&(f.agent.agentFields=f.agent.agentFields.filter($=>$!=="status:suggestion"),f.agent.agentFields.includes("status:accepted")||f.agent.agentFields.push("status:accepted")),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ACCEPT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"accepted",targetId:S,driftDetected:f.suggestion?.driftDetected}),this.commentService.saveComment(f,{type:qe.SUGGESTION_ACCEPTED}),this.applyThroughSetter(f),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_APPROVED,f),this.analyticsService.trackEvent(oe.Events.Comments.SUGGESTION_ACCEPTED,{annotationId:e});let j=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:j,actionUser:m};return this.triggerAction(ct.SUGGESTION_ACCEPTED,W),W}catch(m){return this.loggingService.catch("Error in CommentActionsService acceptSuggestion: ",m),null}})}getRejectSuggestionAnalyticsRequest(e){if(!e||!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let i=e,{reason:t}=i;return ib(i,["reason"])}rejectSuggestion(e,t){return Pe(this,null,function*(){return this.runSuggestionTransition(e?.annotationId,()=>this.rejectSuggestionTransition(e,t))})}rejectSuggestionTransition(d,m){return Pe(this,arguments,function*({annotationId:e,reason:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectSuggestion","color: green;");let u=this.authService.getUser();if(!u)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(!f)return this.triggerAnnotationNotFoundError(e),null;let y=yield this.loadForSuggestionTransition(f,e,a);if(!y||this.ensureSuggestionObject(y)==="refused"||!(y.type==="suggestion"||y.commentType==="suggestion")||!y.suggestion||y.suggestion.status!=="pending")return null;y.suggestion.status="rejected",y.suggestion.rejectReason=t??null,y.suggestion.resolvedBy=u,y.suggestion.resolvedAt=this.timestamp,y.statusUpdatedByUserId=u?.userId,y.type="comment",y?.agent?.agentFields&&typeof y.agent.agentFields=="object"&&Array.isArray(y.agent.agentFields)&&(y.agent.agentFields=y.agent.agentFields.filter(W=>W!=="status:suggestion"),y.agent.agentFields.includes("status:rejected")||y.agent.agentFields.push("status:rejected")),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_REJECT_BUTTON_CLICKED,{annotationId:e,commentType:"suggestion",suggestionOutcome:"rejected",targetId:y.suggestion.targetId}),this.commentService.saveComment(y,{type:qe.SUGGESTION_REJECTED}),this.suggestionActions.projectAndTrigger(Tu.SUGGESTION_REJECTED,y),this.analyticsService.trackEvent(oe.Events.Comments.SUGGESTION_REJECTED,{annotationId:e});let S=yield this.metadataService.getGlobalMetadata(),j={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(y),metadata:S,actionUser:u,rejectReason:t??null};return this.triggerAction(ct.SUGGESTION_REJECTED,j),j}catch(u){return this.loggingService.catch("Error in CommentActionsService rejectSuggestion: ",u),null}})}toggleNotificationSubscription(i,d){return Pe(this,arguments,function*({annotationId:e,options:t},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let m=this.commentService.getAnnotationById(e,t),u=this.authService.getUser();if(m&&u){let f=fr(u.userId);if(f){m.subscribedUsers||(m.subscribedUsers={}),m.unsubscribedUsers||(m.unsubscribedUsers={});let y,S=!1;if(m?.unsubscribedUsers?.[f])S=!1;else if(m?.subscribedUsers?.[f])S=!0;else{let $=this.contactService.getCurrentOrganizationUserIAM();if($){let H=$.groups||{};Object.keys(H).forEach(q=>{m?.subscribedGroups?.[q]&&(S=!0)})}}if(a==="subscribe"||!a&&!S)delete m.unsubscribedUsers[f],m.subscribedUsers[f]={user:u,type:"manual"},y=qe.SUBSCRIBED;else if(a==="unsubscribe"||!a&&S)delete m.subscribedUsers[f],m.unsubscribedUsers[f]={user:u,type:"manual"},y=qe.UNSUBSCRIBED;else return null;this.commentService.saveComment(m,{type:y});let j=yield this.metadataService.getGlobalMetadata(),W={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:j};return y===qe.SUBSCRIBED?this.triggerAction(ct.SUBSCRIBE_COMMENT_ANNOTATION,W):this.triggerAction(ct.UNSUBSCRIBE_COMMENT_ANNOTATION,W),W}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",m),null}})}assignUser(d,m){return Pe(this,arguments,function*({annotationId:e,assignedTo:t,options:a},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: assignUser","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let f=this.commentService.getAnnotationById(e,a);if(f){f.assignedTo=t,this.commentService.saveComment(f,{type:qe.ASSIGNED,assignedTo:t});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,assignedTo:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:y};return this.triggerAction(ct.ASSIGN_USER,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(f),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,assignedToUserId:t?.userId}),S}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService assignUser: ",u),null}})}getComment(a){return Pe(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let i=this.commentService.getAnnotationById(e,t);return i?i.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(i){return this.loggingService.catch("Error in CommentActionsService getComment: ",i),[]}})}updateOrDeleteComment(e,t,a,i,d,m,u){return Pe(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length||Bh(t)){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=qe.UPDATED,!t.isEdited&&Lh(m)&&(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:qe.UPDATED,updatedComment:t});let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:y,isAssigneeChanged:u??!1};return this.triggerAction(ct.UPDATE_COMMENT,S),this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:d??this.defaultSource}),S}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}else yield this.deleteComment({annotationId:e?.annotationId,commentId:t.commentId,skipDeleteThreadConfirmation:a,options:i});return null}catch(f){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",f),null}})}updateComment(f,y,S){return Pe(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:a,merge:i,options:d},m,u){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let j=this.commentService.getAnnotationById(e,d),W=this.authService.getUser();if(!W)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(j&&W){this.commentService.spliceProgressCommentsIn(j);try{let $=t,H=j.comments?.find(q=>q.commentId===t.commentId);if(H){if(this.isUserAdmin||W?.userId===H?.from?.userId)return j?.status.type==="terminal"&&(j.status=this.customFilterService.defaultStatus),i&&($=g(g({},H),t)),$.from=H.from,$.createdAt=H.createdAt,$.lastUpdated=new Date,yield this.updateOrDeleteComment(j,$,a,d,m,H,u);this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}}finally{this.commentService.restoreProgressCommentSplit(j)}}else this.triggerAnnotationNotFoundError(e);return null}catch(j){return this.loggingService.catch("Error in CommentActionsService updateComment: ",j),null}})}deleteComment(m,u){return Pe(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:a,options:i},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let f=this.commentService.getAnnotationById(e,i),y=this.authService.getUser();if(!f)return this.triggerAnnotationNotFoundError(e),null;this.commentService.spliceProgressCommentsIn(f);try{let S=f.comments?.find(q=>q?.commentId===t);if(!S)return null;if(!(this.isUserAdmin||y?.userId===S?.from?.userId))return this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it."),null;let j=this.commentService.willDeleteWholeAnnotation(f,t),W=this.commentService.getCommentAnnotationForClient(f);if(!a&&!(yield this.commentService.confirmDeleteCommentIfRequired(f,S)))return null;this.commentService.saveComment(f,{type:qe.DELETED,updatedComment:S,skipDeleteThreadConfirmation:!0});let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:e,commentId:t,commentAnnotation:W,comment:S,metadata:$};if(j){let q={annotationId:e,commentAnnotation:W,metadata:$};this.triggerAction(ct.DELETE_COMMENT_ANNOTATION,q)}else this.triggerAction(ct.DELETE_COMMENT,H);return H}finally{this.commentService.restoreProgressCommentSplit(f)}}catch(f){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",f),null}})}addAttachment(d,m){return Pe(this,arguments,function*({annotationId:e,files:t,options:a},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let u=[],f=this.commentService.getAnnotationById(e,a);if(f||i==="internal"){let j=[];t.forEach(W=>{let{valid:$,file:H,maxAllowedSize:q,error:ce}=this.validateFile(W);$&&H?j.push(this.uploadFile(H,f||{}).then(fe=>({valid:$,file:H,maxAllowedSize:q,error:ce,attachment:fe||void 0}))):j.push(Promise.resolve({valid:$,file:H,maxAllowedSize:q,error:ce,attachment:void 0}))}),u=yield Promise.all(j)}else this.triggerAnnotationNotFoundError(e);let y=yield this.metadataService.getGlobalMetadata(),S={annotationId:e,commentAnnotation:f?this.commentService.getCommentAnnotationForClient(f):void 0,attachments:u,metadata:y};return this.triggerAction(ct.ADD_ATTACHMENT,S),u}catch(u){return this.loggingService.catch("Error in CommentActionsService addAttachment: ",u),[]}})}validateFile(e){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: validateFile","color: green;");let t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let a=e.size<=t;return{valid:a,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:a?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(d){return Pe(this,arguments,function*({annotationId:e,commentId:t,attachmentId:a,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteAttachment","color: green;");let m=this.commentService.getAnnotationById(e,i);if(m){let u=m.comments?.find(y=>y?.commentId===t),f=m.metadata;if(u){let y=this.authService.getUser();if(this.isUserAdmin||y?.userId===u?.from?.userId){let S=u.attachments?.find(j=>j?.attachmentId===a);if(S){u.attachments=u.attachments?.filter(H=>H?.attachmentId!==a);let j={attachmentId:S.attachmentId,organizationId:f?.clientOrganizationId??f?.organizationId??null,documentId:f?.clientDocumentId??f?.documentId??null,folderId:f?.folderId??null,commentAnnotationId:m.annotationId,apiKey:f?.apiKey??null};yield this.commentService.deleteAttachment({attachment:S,metadata:j,annotation:m});let W=yield this.metadataService.getGlobalMetadata(),$={attachment:S,annotationId:e,commentId:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:W};return this.triggerAction(ct.DELETE_ATTACHMENT,$),this.updateComment({annotationId:e,comment:u,options:i}),$}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the attachment.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteAttachment: ",m),null}})}getAttachment(i){return Pe(this,arguments,function*({annotationId:e,commentId:t,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getAttachment","color: green;");let d=this.commentService.getAnnotationById(e,a);return d?d.comments?.find(u=>u?.commentId===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(d){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",d),[]}})}uploadFile(e,t){return Pe(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(a){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",a),null}})}getRecording(i){return Pe(this,arguments,function*({annotationId:e,commentId:t,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getRecording","color: green;");let d=this.commentService.getAnnotationById(e,a);return d?d.comments?.find(u=>u?.commentId===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(d){return this.loggingService.catch("Error in CommentActionsService getRecording: ",d),[]}})}deleteRecording(d){return Pe(this,arguments,function*({annotationId:e,commentId:t,recorderId:a,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteRecording","color: green;");let m=this.commentService.getAnnotationById(e,i);if(m){let u=m.comments?.find(f=>f?.commentId===t);if(u){let f=this.authService.getUser();if(this.isUserAdmin||f?.userId===u?.from?.userId){let y=u.recorders?.find(S=>S?.id===a);if(y){u.recorders=u.recorders?.filter(W=>W?.id!==a);let S=yield this.metadataService.getGlobalMetadata(),j={annotationId:e,commentId:t,recording:y,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:S};return this.triggerAction(ct.DELETE_RECORDING,j),this.updateComment({annotationId:e,comment:u,skipDeleteThreadConfirmation:!0,options:i}),j}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the recording.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteRecording: ",m),null}})}fetchCommentAnnotations(e){return Pe(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),a;if(t?.hasMore){let d=t?.data[t?.data?.length-1];a=yield hC(d?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let i=t?.data?.reduce((d,m)=>(d[m.metadata.clientDocumentId??m.metadata.documentId]=d[m.metadata.clientDocumentId??m.metadata.documentId]||[],d[m.metadata.clientDocumentId??m.metadata.documentId].push(this.commentService.getCommentAnnotationForClient(m)),d),{});return g({data:i},t?.hasMore?{nextPageToken:a}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(m,u){return Pe(this,arguments,function*({annotationId:e,commentId:t,reaction:a,options:i},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let f=this.commentService.getAnnotationById(e,i),y=this.authService.getUser();if(f&&y){this.commentService.spliceProgressCommentsIn(f);try{let S=f.comments?.find(j=>j?.commentId===t);if(S){let j=yield this.reactionService?.addOrUpdateReaction(a.reactionId,S?.reactionAnnotationIds||[],void 0,void 0,f?.annotationId,a.customReaction,d),W=qe.REACTION_ADDED;if(j){j?.reactions?.find(q=>q.from?.userId===y?.userId)||(W=qe.REACTION_DELETED),S.reactionAnnotationIds||(S.reactionAnnotationIds=[]),S.reactionAnnotationIds.includes(j.annotationId)||S.reactionAnnotationIds.push(j.annotationId),j?.reactions?.length||(S.reactionAnnotationIds=S.reactionAnnotationIds.filter(q=>q!==j.annotationId)),this.pruneDanglingReactionIds(S,j.annotationId),this.commentService.saveComment(f,{type:W,updatedComment:S});let $=yield this.metadataService.getGlobalMetadata(),H={annotationId:e,commentId:t,reaction:j,commentAnnotation:this.commentService.getCommentAnnotationForClient(f),metadata:$};return d==="add"?this.triggerAction(ct.ADD_REACTION,H):d==="delete"?this.triggerAction(ct.DELETE_REACTION,H):this.triggerAction(ct.TOGGLE_REACTION,H),W===qe.REACTION_ADDED?this.analyticsService.trackEvent(oe.Events.Comments.REACTION_ADDED,{annotationId:e,commentId:t,reactionId:a.reactionId,commentMode:this.commentService.getCommentMode()}):W===qe.REACTION_DELETED&&this.analyticsService.trackEvent(oe.Events.Comments.REACTION_DELETED,{annotationId:e,commentId:t,reactionId:a.reactionId,commentMode:this.commentService.getCommentMode()}),H}this.pruneDanglingReactionIds(S)&&this.commentService.saveComment(f,{type:qe.REACTION_DELETED,updatedComment:S})}}finally{this.commentService.restoreProgressCommentSplit(f)}}else this.triggerAnnotationNotFoundError(e);return null}catch(f){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",f),null}})}pruneDanglingReactionIds(e,t){try{let a=e?.reactionAnnotationIds;if(!Array.isArray(a)||!a.length)return!1;let i=a.filter(d=>d===t||!!this.reactionService?.getAnnotationById(d));return i.length===a.length?!1:(e.reactionAnnotationIds=i,!0)}catch(a){return this.loggingService.catch("Error in CommentActionsService pruneDanglingReactionIds: ",a),!1}}onComposerClick(t){return Pe(this,arguments,function*({commentAnnotation:e}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onComposerClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={commentAnnotation:e?.annotationId?this.commentService.getCommentAnnotationForClient(e):void 0,metadata:a};this.triggerAction(ct.COMPOSER_CLICKED,i)}catch(a){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",a)}})}onComposerTextChange(e){return Pe(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),a={text:e.text,annotation:e.annotation,targetComposerElementId:e.targetComposerElementId,metadata:t};this.commentService.setComposerData(e.targetComposerElementId,a),this.triggerAction(ct.COMPOSER_TEXT_CHANGE,a)}catch(t){this.loggingService.catch("Error in CommentActionsService onComposerTextChange: ",t)}})}autocompleteSearch(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ct.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}onCommentPinClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentPinClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ct.COMMENT_PIN_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentPinClick: ",t),null}})}onCommentBubbleClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentBubbleClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ct.COMMENT_BUBBLE_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentBubbleClick: ",t),null}})}onCommentToolClick(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentToolClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={context:e,targetElementId:t,metadata:a},d={context:e,targetElementId:t,metadata:a};return this.triggerAction(ct.COMMENT_TOOL_CLICK,i),this.triggerAction(ct.COMMENT_TOOL_CLICKED,d),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onCommentToolClick: ",a),null}})}onSidebarButtonClick(e){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onSidebarButtonClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),a=eo(e,{metadata:t}),i=eo(e,{metadata:t});return this.triggerAction(ct.SIDEBAR_BUTTON_CLICK,a),this.triggerAction(ct.SIDEBAR_BUTTON_CLICKED,i),a}catch(t){return this.loggingService.catch("Error in CommentActionsService onSidebarButtonClick: ",t),null}})}onAttachmentDownloadClick(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onAttachmentDownloadClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),attachment:t,metadata:a};return this.triggerAction(ct.ATTACHMENT_DOWNLOAD_CLICKED,i),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onAttachmentDownloadClick: ",a),null}})}onCommentSaveTriggered(e,t){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentSaveTriggered","color: green;");let a=yield this.metadataService.getGlobalMetadata(),i={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(t),metadata:a};return this.triggerAction(ct.COMMENT_SAVE_TRIGGERED,i),i}catch(a){return this.loggingService.catch("Error in CommentActionsService onCommentSaveTriggered: ",a),null}})}onVisibilityOptionClick(e,t,a){return Pe(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onVisibilityOptionClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),d={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),visibility:t,users:a?.map(m=>AC(m)).filter(Boolean),metadata:i};return this.triggerAction(ct.VISIBILITY_OPTION_CLICKED,d),d}catch(i){return this.loggingService.catch("Error in CommentActionsService onVisibilityOptionClick: ",i),null}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:a}=this.docService.getServerId(e?.options);e.options=b(g({},e?.options),{documentId:t,organizationId:a})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}emitCommentActionClicked(e){return Pe(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),a=b(g(g({action:e.action,actionId:e.action?.id,scope:e.scope,annotationId:e.annotationId},e.commentId!==void 0?{commentId:e.commentId}:{}),e.comment!==void 0?{comment:e.comment}:{}),{commentAnnotation:this.commentService.getCommentAnnotationForClient(e.annotation),actionUser:this.authService.getUser(),metadata:t});return this.triggerAction(ct.COMMENT_ACTION_CLICKED,a),a}catch(t){return this.loggingService.catch("Error in CommentActionsService emitCommentActionClicked: ",t),null}})}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new Lt),this.actionSubjects.get(e)?.next(t)}catch(a){this.loggingService.catch("Error in CommentActionsService triggerAction: ",a)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new Lt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),ye(null)}}get onIsAssigneeChangedError(){return e=>this.loggingService.catch("Error resolving isAssigneeChanged: ",e)}get timestamp(){return this.commonDbService.getServerTimestamp()}getCommentAnnotations(e){try{if(e){if(e?.allDocuments&&!e?.folderId)return this.loggingService.catch("folderId is required when allDocuments is true."),ye({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),ye({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(Ee(t=>t?t.reduce((a,i)=>{let d=i.metadata?.clientDocumentId;return!d||e?.documentIds&&!e?.documentIds?.includes(d)||(a[d]||(a[d]=[]),a[d].push(i)),a},{}):null),Ee(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ye({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(Ee(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ye({data:null})}}updateVisibility(e){this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateVisibility","color: green;");try{let t=e.annotationId;if(!t)throw new Error("annotationId is required in visibility config");if(e.type==="restricted"){let u=this.authService.getUser();if(!u?.userId)throw new Error("Current user not found. Cannot set restricted visibility without userIds.");e=xo(e,u.userId)}if(e.type==="organizationPrivate"&&!e.organizationId&&!e.organizationIds?.length){let u=this.authService.getUser()?.clientOrganizationId;if(!u)throw new Error("No organizationId found. Cannot set organizationPrivate visibility without organizationId.");e=b(g({},e),{organizationId:u})}this.analyticsService.trackEvent(oe.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{annotationId:t,visibility:e}});let a=this.commentService.getCommentAnnotationByIdSync(t)?.from?.userId,i=a??this.authService.getUser()?.userId;a||this.loggingService.warn(`updateVisibility: annotation ${t} not in local cache \u2014 falling back to current user for the author access token`);let d=qn(e,i),m=Zn(e,i);return this.commentService.updateCommentAnnotationContext(t,{_setAccessFields:d,_setVisibilityConfig:m},{merge:!0})}catch(t){return this.loggingService.catch("Error in updateVisibility: ",t),Promise.resolve()}}calculateCommentThreadIndex(e,t){try{let a=e?.commentId,i;return a&&(i=t?.comments?.findIndex(d=>d.commentId===a)),i===-1&&(i=t?.comments?.length),i}catch(a){this.loggingService.catch("Error in calculateCommentThreadIndex: ",a);return}}};o.\u0275fac=function(t){return new(t||o)(be(pr),be(vt),be(ae),be(gp),be(zt),be(St),be(ut),be(wr),be(A),be(Ju),be(_o),be(Sr),be(Sc),be(_c),be(l0))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var up=(()=>{let o=class o{constructor(e){this.loggingService=e,this.commentTextData$=new De({});try{this.loggingService.log("%c[WB] Creating CLASS: CommentTextService","color: blue;")}catch(t){this.loggingService.catch("Error in CommentTextService constructor: ",t)}}setCommentTextData(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: setCommentTextData","color: green;");let t=e.annotationId||e.multiThreadAnnotationId;if(t){let a=e.componentId,i=this.commentTextData$.getValue();i[t]||(i[t]={}),i[t][a]=e,this.commentTextData$.next(i),this.updateLastPositionInDataByAnnotationId(t)}}catch(t){this.loggingService.catch("Error in CommentTextService setCommentTextData: ",t)}}removeCommentTextData(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: removeCommentTextData","color: green;");let t=e.annotationId||e.multiThreadAnnotationId;if(t){let a=e.componentId,i=this.commentTextData$.getValue();delete i[t][a],this.commentTextData$.next(i),this.updateLastPositionInDataByAnnotationId(t)}}catch(t){this.loggingService.catch("Error in CommentTextService removeCommentTextData: ",t)}}updateLastPositionInDataByAnnotationId(e){try{this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: updateLastPositionInDataByAnnotationId","color: green;");let t=this.commentTextData$.getValue();Object.values(t[e]).forEach(a=>{a.last=this.checkIfLast(a)}),this.commentTextData$.next(t)}catch(t){this.loggingService.catch("Error in CommentTextService updateLastPositionInDataByAnnotationId: ",t)}}checkIfLast(e){try{if(this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: checkIfLast","color: green;"),e?.elementRef?.nativeElement){let t=e.elementRef.nativeElement.getRootNode(),a=t instanceof Document||t instanceof ShadowRoot?t:document,i=[];if(e.annotationId?i=Array.from(a.querySelectorAll(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.ANNOTATION_ID}="${e.annotationId}"]`)):e.multiThreadAnnotationId&&(i=Array.from(a.querySelectorAll(`${Z.TAGS.VELT_COMMENT_TEXT}[${Z.ATTRIBUTES.MULTI_THREAD_ANNOTATION_ID}="${e.multiThreadAnnotationId}"]`))),i.length&&i[i.length-1]===e.elementRef.nativeElement)return!0}return!1}catch(t){return this.loggingService.catch("Error in CommentTextService checkIfLast: ",t),!1}}getCommentTextDataByAnnotationIdAndComponentId(e,t){try{return this.loggingService.log("%c[WB] Calling CommentTextService FUNCTION: getCommentTextDataByAnnotationIdAndComponentId","color: green;"),this.commentTextData$.pipe(Ee(a=>a&&e&&t&&a[e]?a[e][t]:null))}catch(a){return this.loggingService.catch("Error in CommentTextService getCommentTextDataByAnnotationIdAndComponentId: ",a),ye(null)}}};o.\u0275fac=function(t){return new(t||o)(be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function pp(r,o){return r?{commentPinSelected:!0,textClicked:!!o}:{commentPinSelected:!1,textClicked:!1}}function hp(r,o,n){return r!=null&&r===o&&!!n}function sk(r){return r instanceof Document||r instanceof ShadowRoot?r:document}function gk(r,o){let n=e=>{if(!e)return null;let t=null;return(e instanceof Document||e instanceof DocumentFragment)&&(t=e.getElementById(`comment-pin-container-${o}`)),t||e.querySelector(`[data-velt-id='${o}']`)||null};return n(r)||(r!==document?n(document):null)}var GD=["overlay"],zD=()=>["snippyly-overlay-panel","velt-overlay-panel"];function HD(r,o){if(r&1&&O(0,"span",8),r&2){let n,e=l().ngIf;pe("index-3-digit",(e.commentPinAnnotation==null||e.commentPinAnnotation.annotationNumber==null||(n=e.commentPinAnnotation.annotationNumber.toString())==null?null:n.length)===3),x("data-comment-annotation-number","#"+(e.commentPinAnnotation==null?null:e.commentPinAnnotation.annotationNumber))}}function WD(r,o){if(r&1){let n=Y();p(0),C(1,"velt-multi-thread-comment-dialog-internal",10),z("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))})("pointerUp",function(t){B(n);let a=l(3);return V(a.togglePinSelection(t))}),_(),h()}if(r&2){let n=l(2).ngIf;v(),c("multiThreadAnnotationId",n.commentPinAnnotation.annotationId)("annotation",n.commentPinAnnotation)("user",n.user)("commentPinSelected",n.commentPinSelected)}}function JD(r,o){if(r&1){let n=Y();C(0,"velt-comment-dialog-internal",11),z("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))}),_()}if(r&2){let n=l(2).ngIf;c("annotation",n.commentPinAnnotation)("user",n.user)("commentPinSelected",n.commentPinSelected)("inlineCommentMode",n.inlineCommentMode)("isInsidePdfViewer",n.isInsidePdfViewer)}}function YD(r,o){if(r&1&&s(0,WD,2,4,"ng-container",9)(1,JD,1,5,"ng-template",null,2,$e),r&2){let n=we(2),e=l().ngIf;c("ngIf",(e==null||e.commentPinAnnotation==null?null:e.commentPinAnnotation.type)==="multiThread")("ngIfElse",n)}}function KD(r,o){if(r&1){let n=Y();C(0,"snippyly-comment-bottom-sheet",12),z("saveComment",function(t){B(n);let a=l(2);return V(a.saveComment(t))}),_()}if(r&2){let n=l().ngIf;c("annotation",n.commentPinAnnotation)("user",n.user)("isInsidePdfViewer",n.isInsidePdfViewer)}}function qD(r,o){if(r&1){let n=Y();p(0),C(1,"snippyly-comment-text",4,0),z("pointerover",function(t){return B(n),l().onPointerOver(t),V(t.stopPropagation())})("pointerout",function(){B(n);let t=l();return V(t.onPointerOut())})("pointerdown",function(t){return B(n),V(t.stopPropagation())})("pointerup",function(t){return B(n),l().togglePinSelection(),V(t.stopPropagation())})("touchend",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())})("click",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())}),_(),s(3,HD,1,3,"span",5)(4,YD,3,2,"ng-template",6,1,$e)(6,KD,1,3,"snippyly-comment-bottom-sheet",7),h()}if(r&2){let n=o.ngIf,e=we(2),t=l();v(),pe("inline-comment-mode",n.inlineCommentMode&&!n.isInsidePdfViewer)("agent-comment",(n.commentPinAnnotation==null?null:n.commentPinAnnotation.sourceType)==="agent")("selected",n.commentPinHover||n.commentPinSelected),v(2),c("ngIf",n.last&&n.showCommentIndex&&(n.commentPinAnnotation==null?null:n.commentPinAnnotation.annotationNumber)),v(),c("cdkConnectedOverlayOrigin",e)("cdkConnectedOverlayOpen",(!n.mobileMode||!n.isPhone)&&!n.inboxMode&&!n.streamMode&&(!n.inlineCommentMode||n.isInsidePdfViewer)&&n.floatingCommentsEnabled&&(n.textClicked&&n.commentPinSelected||n.commentPinHover&&!n.commentPinSelected))("cdkConnectedOverlayOffsetY",n.overlayOriginY==="top"?-8:2)("cdkConnectedOverlayPanelClass",gt(17,zD))("cdkConnectedOverlayBackdropClass","snippyly-overlay-backdrop")("cdkConnectedOverlayLockPosition",!1)("cdkConnectedOverlayPositions",t.positions)("cdkConnectedOverlayGrowAfterOpen",!0)("cdkConnectedOverlayDisableClose",!0),v(2),c("ngIf",(n==null?null:n.user)&&n.mobileMode&&n.isPhone&&!n.sidebarVisible&&(!n.inlineCommentMode||n.isInsidePdfViewer)&&!n.inboxMode&&!n.streamMode&&n.floatingCommentsEnabled&&n.textClicked&&n.commentPinSelected)}}var fp=(()=>{let o=class o{onEnter(e){this.onKeyupEnter&&this.onKeyupEnter()}constructor(e,t,a,i,d,m,u,f){this.analyticsService=e,this.authService=t,this.breakpointObserver=a,this.domService=i,this.commentService=d,this.loggingService=m,this.serviceBook=u,this.elementRef=f,this.subscriptions=[],this.selectedAnnotationsMap={},this.customScrollableParentEventsListenersSubscriptions=[],this.isDialogOnHoverEnabled=!1,this.componentConfigSignal=Ae({inlineCommentMode:!1,isInsidePdfViewer:!1,commentPinHover:!1,commentPinSelected:!1,first:!1,last:!1,showCommentIndex:!1,commentPinAnnotation:null,isPhone:!1,mobileMode:!1,streamMode:!1,inboxMode:!1,textClicked:!1,floatingCommentsEnabled:!0,sidebarVisible:!1,user:null,overlayOriginX:"start",overlayOriginY:"top"}),this.positions=Z.OVERLAY_POSITIONS.map(y=>new bn({originX:y.originX,originY:y.originY},{overlayX:y.overlayX,overlayY:y.overlayY})),this.veltElement=!0,this.componentId="velt-comment-text-portal",this.subscriptions.push(this.authService.getUser$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{user:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getUser$ subscription: ",y)})),this.subscriptions.push(this.commentService.getSidebarVisibility$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{sidebarVisible:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getSidebarVisibility$ subscription: ",y)})),this.subscriptions.push(this.commentService.showFloatingComments$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{floatingCommentsEnabled:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent showFloatingComments$ subscription: ",y)})),this.subscriptions.push(this.commentService.getShowCommentIndex().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{showCommentIndex:y}),S))},y=>{this.catchError("Error in CommentTextPortalComponent getShowCommentIndex subscription: ",y)})),this.subscriptions.push(this.commentService.getEnableDialogOnHover$().subscribe(y=>{this.isDialogOnHoverEnabled=y},y=>{this.catchError("Error in CommentPinComponent getEnableDialogOnHover subscription: ",y)})),this.subscriptions.push(this.breakpointObserver.observe(fo.XSmall).subscribe(y=>{let S=!1;y.matches?S=!0:S=!1,this.componentConfigSignal.update(j=>(j=b(g({},j),{isPhone:S}),j))},y=>{this.catchError("Error in CommentTextPortalComponent breakpointObserver subscription: ",y)}))}ngOnInit(){try{this.setupA11yAttributes()}catch(e){this.loggingService.catch("Error in CommentTextPortalComponent ngOnInit:",e)}}setupA11yAttributes(){try{this.elementRef.nativeElement.setAttribute("data-testid",this.componentId+"-container")}catch(e){this.loggingService.catch("Error in CommentTextPortalComponent setupA11yAttributes:",e)}}ngAfterViewInit(){try{let e=this.element.childNodes[0];this.element.childNodes[1].childNodes[0].appendChild(e),this.componentConfigSignal.update(a=>{let i=hc(this.element,Z.ATTRIBUTES.VELT_PDF_VIEWER);return a=b(g({},a),{isInsidePdfViewer:i}),a}),this.subscriptions.push(this.overlay?.positionChange?.subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{overlayOriginX:a.connectionPair.originX,overlayOriginY:a.connectionPair.originY}),i))},a=>{this.catchError("Error in CommentTextPortalComponent positionChange subscription: ",a)})),this.subscriptions.push(this.domService.getSelectedAnnotationsMap$().subscribe(a=>{this.selectedAnnotationsMap=a,this.checkPinSelection()},a=>{this.catchError("Error in CommentTextPortalComponent getSelectedAnnotationsMap$ subscription: ",a)})),this.subscriptions.push(this.commentService.getStreamMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{streamMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getStreamMode$ subscription: ",a)})),this.subscriptions.push(this.commentService.getInboxMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{inboxMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getInboxMode subscription: ",a)})),this.subscriptions.push(this.commentService.getMobileMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{mobileMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getMobileMode$ subscription: ",a)})),this.subscriptions.push(this.commentService.getInlineCommentMode$().subscribe(a=>{this.componentConfigSignal.update(i=>(i=b(g({},i),{inlineCommentMode:a}),i))},a=>{this.catchError("Error in CommentTextPortalComponent getInlineCommentMode$ subscription: ",a)})),this.subscriptions.push(this.serviceBook.observe(_n).pipe(Fe(a=>a?.onInitRecording()??Hr)).subscribe(a=>{this.recorderInitConfig=a},a=>{this.catchError("Error in CommentTextPortalComponent onInitRecording subscription: ",a)}))}catch(e){this.catchError("Error in CommentTextPortalComponent AfterViewInit: ",e)}}setFirst(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{first:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setFirst: ",t)}}setLast(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{last:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setLast: ",t)}}setCommentPinAnnotation(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinAnnotation:e}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent setCommentPinAnnotation: ",t)}}setElement(e){try{this.element=e,this.element?this.customScrollableParents=Ru(this.element):this.customScrollableParents=[],this.addCustomScrollableParentsEventListeners()}catch(t){this.catchError("Error in CommentTextPortalComponent setElement: ",t)}}checkPinSelection(){try{let e=!!this.selectedAnnotationsMap[this.componentConfigSignal().commentPinAnnotation?.annotationId];this.componentConfigSignal.update(t=>{let a=pp(e,t.last);return g(g({},t),a)}),hp(sessionStorage.getItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID),this.componentConfigSignal().commentPinAnnotation.annotationId,this.componentConfigSignal().last)&&(this.componentConfigSignal.update(t=>(t=b(g({},t),{textClicked:!0}),t)),sessionStorage.removeItem(Z.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID))}catch(e){this.catchError("Error in CommentTextPortalComponent checkPinSelection: ",e)}}onPointerOver(e){try{if(this.componentConfigSignal().commentPinHover)return;e.buttons?this.componentConfigSignal().commentPinHover&&this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinHover:!1}),t)):!this.componentConfigSignal().commentPinHover&&this.isDialogOnHoverEnabled&&this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinHover:!0}),t))}catch(t){this.catchError("Error in CommentTextPortalComponent onPointerOver: ",t)}}onPointerOut(){this.componentConfigSignal.update(e=>(e=b(g({},e),{commentPinHover:!1}),e))}togglePinSelection(e){try{if(this.recorderInitConfig?.isCommentRecording||this.componentConfigSignal().textClicked&&!e)return;let t=e||this.componentConfigSignal().commentPinAnnotation;if(this.selectedAnnotationsMap[t.annotationId])e||(document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}="${t?.annotationId}"]`)?this.domService.resetSelectedAnnotationsMap(!0,"comments"):(this.componentConfigSignal.update(i=>(i=b(g({},i),{textClicked:!0}),i)),this.domService.toggleAnnotationSelection(t)));else{let a=document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);if(a||(a=(this.domService.getDraftCommentAnnotationDialogs()||[])[0]),a){let i=a.getAttribute(Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT);if(i){let d=document.getElementById(`comment-pin-container-${i}`)||document.querySelector(`[data-velt-id='${i}']`);d&&(d.scrollIntoView({behavior:"auto",block:"center",inline:"center"}),this.domService.resetSelectedAnnotationsMap(!0,"comments"))}}else this.domService.resetSelectedAnnotationsMap(!0,"comments"),this.componentConfigSignal.update(i=>(i=b(g({},i),{textClicked:!0}),i)),this.domService.toggleAnnotationSelection(t)}}catch(t){this.catchError("Error in CommentTextPortalComponent togglePinSelection: ",t)}}saveComment(e){try{this.commentService.saveComment(this.componentConfigSignal().commentPinAnnotation,e)}catch(t){this.catchError("Error in CommentTextPortalComponent saveComment: ",t)}}updateOverlayPosition(){try{this.loggingService.log("updateOverlayPosition",this.componentConfigSignal().commentPinAnnotation?.annotationId),this.overlay&&this.overlay?.overlayRef?.updatePosition()}catch(e){this.catchError("Error in CommentTextPortalComponent updateOverlayPosition: ",e)}}addCustomScrollableParentsEventListeners(){try{this.removeCustomScrollableParentsEventListeners(),this.customScrollableParents?.length&&this.customScrollableParents?.forEach(e=>{this.customScrollableParentEventsListenersSubscriptions.push(Gn(e,"scroll").subscribe(t=>{this.updateOverlayPosition()},t=>{this.catchError("Error in CommentTextPortalComponent addCustomScrollableParentsEventListeners scroll subscription: ",t)}))})}catch(e){this.catchError("Error in CommentTextPortalComponent addCustomScrollableParentsEventListeners: ",e)}}removeCustomScrollableParentsEventListeners(){try{this.customScrollableParentEventsListenersSubscriptions.map(e=>{e.unsubscribe()}),this.customScrollableParentEventsListenersSubscriptions=[]}catch(e){this.catchError("Error in CommentTextPortalComponent removeCustomScrollableParentsEventListeners: ",e)}}ngOnDestroy(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.removeCustomScrollableParentsEventListeners(),this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[]}catch(e){this.catchError("Error in CommentTextPortalComponent unsubscribe: ",e)}}catchError(e,t,a){try{this.loggingService.catch(e,t,b(g({},a||{}),{annotationId:this.componentConfigSignal()?.commentPinAnnotation?.annotationId}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(G(pr),G(vt),G(ho),G(Re),G(ae),G(A),G(Sr),G(me))},o.\u0275cmp=T({type:o,selectors:[["snippyly-comment-text-portal"]],viewQuery:function(t,a){if(t&1&&ot(GD,5),t&2){let i;at(i=it())&&(a.overlay=i.first)}},hostVars:1,hostBindings:function(t,a){t&1&&z("keyup.enter",function(d){return a.onEnter(d)},ou),t&2&&x("data-velt-element",a.veltElement)},standalone:!1,decls:1,vars:1,consts:[["trigger","cdkOverlayOrigin"],["overlay","cdkConnectedOverlay"],["commentDialogRef",""],[4,"ngIf"],["cdkOverlayOrigin","","data-velt-comment-disabled","true",1,"comment-text-highlight",3,"pointerover","pointerout","pointerdown","pointerup","touchend","click"],["class","comment-annotation-number",3,"index-3-digit",4,"ngIf"],["cdkConnectedOverlay","",3,"cdkConnectedOverlayOrigin","cdkConnectedOverlayOpen","cdkConnectedOverlayOffsetY","cdkConnectedOverlayPanelClass","cdkConnectedOverlayBackdropClass","cdkConnectedOverlayLockPosition","cdkConnectedOverlayPositions","cdkConnectedOverlayGrowAfterOpen","cdkConnectedOverlayDisableClose"],[3,"annotation","user","isInsidePdfViewer","saveComment",4,"ngIf"],[1,"comment-annotation-number"],[4,"ngIf","ngIfElse"],[3,"saveComment","pointerUp","multiThreadAnnotationId","annotation","user","commentPinSelected"],[3,"saveComment","annotation","user","commentPinSelected","inlineCommentMode","isInsidePdfViewer"],[3,"saveComment","annotation","user","isInsidePdfViewer"]],template:function(t,a){t&1&&s(0,qD,7,18,"ng-container",3),t&2&&c("ngIf",a.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}*[_ngcontent-%COMP%]{box-sizing:border-box;margin:0;padding:0;height:inherit;width:inherit;text-align:inherit;line-height:inherit;font-size:inherit;text-transform:inherit;float:inherit;-webkit-text-fill-color:initial}*[_ngcontent-%COMP%]:empty{display:revert}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-agent-accent: #4495ff;--velt-agent-accent-transparent: rgba(68, 149, 255, .2);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent);font-family:inherit}.comment-text-highlight[_ngcontent-%COMP%]{cursor:pointer} snippyly-text-highlight.snippyly-text-highlight{color:var(--velt-black)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight{color:var(--velt-warning-hover);background-color:var(--velt-warning-transparent);border-bottom:1px solid var(--velt-warning-hover)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.selected{color:var(--velt-black);background-color:var(--velt-warning)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.agent-comment{color:var(--velt-agent-accent);background-color:var(--velt-agent-accent-transparent);border-bottom-color:var(--velt-agent-accent)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.agent-comment.selected{color:var(--velt-agent-accent);background-color:var(--velt-agent-accent-transparent)} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.inline-comment-mode{background-color:inherit} snippyly-text-highlight.snippyly-text-highlight .comment-text-highlight.inline-comment-mode.selected{background-color:inherit}.comment-annotation-number[_ngcontent-%COMP%]{border-radius:50%;border:1px solid var(--velt-gray);width:20px;height:20px;font-size:calc((.7rem + 0px) * var(--velt-base-rem-unit));display:inline-flex;justify-content:center;align-items:center;box-sizing:content-box;background:var(--velt-white);color:var(--velt-black);position:relative}.comment-annotation-number.index-3-digit[_ngcontent-%COMP%]{width:32px;height:32px}.comment-annotation-number[_ngcontent-%COMP%]:after{content:attr(data-comment-annotation-number);position:absolute;font-weight:400;letter-spacing:normal;word-spacing:normal}"],changeDetection:0});let r=o;return r})();var ZD=`[${Z.ATTRIBUTES.VELT_LOCATION}], [${Z.ATTRIBUTES.VELT_LOCATION_ID}]`,Tc=(()=>{let o=class o{constructor(e,t,a,i,d,m,u){this.docService=e,this.domService=t,this.commentService=a,this.componentFactoryResolver=i,this.injector=d,this.appRef=m,this.loggingService=u,this.commentsTextById={},this.lastTextCommentAnnotations=[],this.commonAncestorElementObservers=new Map,this.commonAncestorElementObserverCounts=new Map,this.inlineCommentMode=!1,this.restrictTextSearchToAnchor=!1;try{this.commentService.getInlineCommentMode$().subscribe(f=>{this.inlineCommentMode=f}),this.commentService.getRestrictTextSearchToAnchor$().subscribe(f=>{this.restrictTextSearchToAnchor=f})}catch(f){this.loggingService.catch("Error in CommentPinPortalService constructor: ",f)}}updateTextCommentAnnotations(e,t){try{t&&(this.textCommentAnnotationsOwner=t),this.lastTextCommentAnnotations=e||[],this.checkToRemoveTextCommentAnnotations(e),e.forEach(a=>{this.updateTextCommentAnnotation(a)})}catch(a){this.loggingService.catch("Error in CommentPinPortalService updateTextCommentAnnotations: ",a)}this.watchAreaChanges()}stopWatchingAreaChanges(e){try{if(e&&e!==this.textCommentAnnotationsOwner)return;this.textCommentAnnotationsOwner=void 0,this.areaChangesSubscription?.unsubscribe(),this.areaChangesSubscription=void 0,this.lastTextCommentAnnotations=[]}catch(t){this.loggingService.catch("Error in CommentTextPortalService stopWatchingAreaChanges: ",t)}}watchAreaChanges(){try{if(this.areaChangesSubscription)return;this.areaChangesSubscription=this.docService.getAreaChanges$().pipe(Dn(1)).subscribe(()=>{this.updateTextCommentAnnotations(this.lastTextCommentAnnotations||[])})}catch(e){this.loggingService.catch("Error in CommentTextPortalService watchAreaChanges: ",e)}}refreshTextCommentAnnotations(){try{this.lastTextCommentAnnotations.forEach(e=>{let t=this.commentsTextById[e?.annotationId];t?.texts?.length&&t.texts.every(i=>document.body.contains(i?.textNode))||this.updateTextCommentAnnotation(t?.annotation||e)})}catch(e){this.loggingService.catch("Error in CommentPinPortalService refreshTextCommentAnnotations: ",e)}}updateTextCommentAnnotation(e){let t=this.commentsTextById[e.annotationId];if(t)if(xn(t?.annotation?.targetTextRange,e?.targetTextRange)){let a=!1;if(!t?.texts?.length)a=!0;else{let i=t.areaElement;i&&this.docService.isAnnotationAllowedInArea(e?.metadata,i)===!1&&(a=!0),t.texts.forEach(d=>{(!document.body.contains(d?.textNode)||Dr(d?.element))&&(a=!0),!i&&this.docService.isAnnotationAllowedInArea(e?.metadata,d?.element)===!1&&(a=!0)})}a?(this.removeTextCommentAnnotation(e),this.getCommonAncestorContainer(e)):(t.texts.forEach(i=>{i.portalRef&&i.portalRef.instance.setCommentPinAnnotation(e)}),t.annotation=e)}else this.removeTextCommentAnnotation(e),this.getCommonAncestorContainer(e);else this.getCommonAncestorContainer(e)}setGhostUnlessHiddenByArea(e,t){try{let a=t?.nodeType===Node.ELEMENT_NODE?t:t?.parentElement??null;if(a&&this.docService.isAnnotationAllowedInArea(e?.metadata,a)===!1){this.docService.logHiddenByArea("text comment",e,a),this.removeGhostComment(e);return}this.setGhostComment(e)}catch(a){this.loggingService.catch("Error in CommentTextPortalService setGhostUnlessHiddenByArea: ",a),this.setGhostComment(e)}}getCommonAncestorContainer(e){try{let t=this.resolveTextSearchScope(e);if(t.notOnPage){this.removeGhostComment(e);return}let a=t.anchor;if(a&&this.domService.isElementVisible(a)){let i=a?.nodeType===Node.ELEMENT_NODE?a:a?.parentElement;this.commentsTextById[e.annotationId]={texts:[],annotation:e,commonAncestorContainer:a,commonAncestorElement:i,commonAncestorText:i?.textContent},this.setTextCommentPortal(e),this.observeCommonAncestorElementChanges(e)}else this.setGhostUnlessHiddenByArea(e,a)}catch(t){this.loggingService.catch("Error in CommentPinPortalService getCommonAncestorContainer: ",t)}}setTextCommentPortal(e){try{let t=this.commentsTextById[e.annotationId];if(t){let{anchor:a,fallbackRoot:i,notOnPage:d}=this.resolveTextSearchScope(e);if(d)return;let m=this.resolveHighlightRange(e,a,i);if(m&&Lu(m)){this.loggingService.log("[Velt] text comment shown as ghost: its text now resolves inside a ProseMirror/TipTap editor."),this.setGhostComment(e);return}if(m){let u=m.commonAncestorContainer?.nodeType===Node.ELEMENT_NODE?m.commonAncestorContainer:m.commonAncestorContainer?.parentElement??null;if(this.docService.isAnnotationAllowedInArea(e?.metadata,u)===!1){this.docService.logHiddenByArea("text comment",e,u),this.removeGhostComment(e);return}t.areaElement=u}if(m){let u=m.commonAncestorContainer?.nodeType===Node.ELEMENT_NODE?m.commonAncestorContainer:m.commonAncestorContainer?.parentElement??null;u&&t.commonAncestorElement&&!t.commonAncestorElement.contains(u)&&(t.commonAncestorElement=u,t.commonAncestorContainer=u,t.commonAncestorText=u.textContent);let f=F0(m),y=[],S=f?.find(j=>!j?.textContent);if(S&&S?.remove(),f=f?.filter(j=>j?.textContent),f&&f.length){let j=-1,W=-1;if(f.forEach(($,H)=>{this.textHighlighterClass?this.domService.addClassToElement($,this.textHighlighterClass):this.domService.addClassToElement($,$.tagName?.toLowerCase()),$.setAttribute(Z.ATTRIBUTES.VELT_ID,e.annotationId);let q=$.childNodes[0],ce=new pu(fp),fe=new hu($,this.appRef,this.injector),le=fe.attach(ce);le.instance.setCommentPinAnnotation(e),le.instance.setElement($),le.instance.onKeyupEnter=()=>{this.onCommonAncestorElementChange(e)},j<0&&(j=H),W=H,y.push({host:fe,portal:ce,portalRef:le,element:$,textNode:q})}),j>=0&&y[j]?.portalRef&&y[j].portalRef.instance.setFirst(!0),W>=0&&y[W]?.portalRef&&y[W].portalRef.instance.setLast(!0),t.texts=y,this.inlineCommentMode&&!document.querySelector(`${Z.TAGS.VELT_INLINE_COMMENT}[${Z.ATTRIBUTES.VELT_INLINE_COMMENT_ID}="${e.annotationId}"]`)){let H=t.texts?.filter(ce=>!!ce?.element)?.map(ce=>ce?.element),q=H?.length?H[H.length-1]:null;if(q&&!hc(q,Z.ATTRIBUTES.VELT_PDF_VIEWER)){let fe=q?.parentElement;if(fe){let le=document.createElement(Z.TAGS.VELT_INLINE_COMMENT);le.setAttribute(Z.ATTRIBUTES.VELT_INLINE_COMMENT_ID,e.annotationId),fe.insertAdjacentElement("afterend",le),t.inlineCommentElement=le}}}}this.removeGhostComment(e)}else this.setGhostUnlessHiddenByArea(e,a)}else this.setGhostComment(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService setTextCommentPortal: ",t)}}resolveTextSearchScope(e){try{let t=this.docService.getElementMapWithLocation()||{},a=this.getAnnotationLocationElement(e,t),i=Object.keys(t).length>0;if(!a&&i&&this.isAdditionalLocationAnnotation(e))return{anchor:null,fallbackRoot:null,notOnPage:!0};let d=this.domService.getElementFromTargetTextRange(e?.targetTextRange);return a?d&&(d===a||a.contains(d))?{anchor:d,fallbackRoot:a}:d&&!this.domService.getAdditionalLocationContainer(d)&&!d.querySelector(ZD)?{anchor:d,fallbackRoot:a}:{anchor:a,fallbackRoot:a}:{anchor:d,fallbackRoot:document.body}}catch(t){return this.loggingService.catch("Error in CommentPinPortalService resolveTextSearchScope: ",t),{anchor:null,fallbackRoot:null}}}isAdditionalLocationAnnotation(e){try{if(!e?.locationId&&!e?.location?.id)return!1;let t=this.docService.getLocation();return t?!fc({location:t.location,locationId:t.locationId},{location:e.location,locationId:e.locationId}):!1}catch(t){return this.loggingService.catch("Error in CommentPinPortalService isAdditionalLocationAnnotation: ",t),!1}}getAnnotationLocationElement(e,t){try{let a=e?.locationId,i=e?.location?.id;if(!a&&!i)return null;let d=t??this.docService.getElementMapWithLocation()??{};return(a?d[a]?.element:null)||(i?d[i]?.element:null)||null}catch(a){return this.loggingService.catch("Error in CommentPinPortalService getAnnotationLocationElement: ",a),null}}resolveHighlightRange(e,t,a=document.body){try{let i=e.targetTextRange?.text,d=e.targetTextRange?.occurrence,m=t?this.buildValidRange(Ih(i,t,d),i):null;return!m&&!this.restrictTextSearchToAnchor&&a&&t!==a&&(m=this.buildValidRange(Ih(i,a,d),i)),m}catch(i){return this.loggingService.catch("Error in CommentPinPortalService resolveHighlightRange: ",i),null}}buildValidRange(e,t){try{if(!e?.length||e.some(d=>d?.textNode?.parentElement?.closest("script")))return null;let i=new Range;try{i.setStart(e[0].textNode,e[0].startOffset||0),i.setEnd(e[e.length-1].textNode,e[e.length-1].endOffset||0)}catch{return null}return i.toString()===t?i:null}catch(a){return this.loggingService.catch("Error in CommentPinPortalService buildValidRange: ",a),null}}checkToRemoveTextCommentAnnotations(e){try{let t=new Set(e.map(i=>i.annotationId)),a=!1;if(Object.keys(this.commentsTextById).forEach(i=>{t.has(i)||(this.commentsTextById[i]?.annotation?.targetTextRange&&(a=!0),this.removeTextCommentAnnotation(this.commentsTextById[i].annotation))}),a){let i=[];Object.keys(this.commentsTextById).forEach(d=>{this.commentsTextById[d]?.annotation?.targetTextRange&&(i.push(this.commentsTextById[d]?.annotation),this.removeTextCommentAnnotation(this.commentsTextById[d]?.annotation))}),i?.length&&i.forEach(d=>{this.updateTextCommentAnnotation(d)})}}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkToRemoveTextCommentAnnotations: ",t)}}removeTextCommentAnnotation(e){try{let t=this.commentsTextById[e.annotationId],a=new Set;if(t.texts.forEach(i=>{i?.host&&i.host.detach();let d=i?.element?.parentNode??i?.textNode?.parentNode;i?.element&&i?.textNode&&Ph(i.element,i.textNode),i.textNode&&d&&a.add(d)}),t.texts?.length){let i=document.querySelectorAll(`${Z.TAGS.SNIPPYLY_TEXT_HIGHLIGHT}[data-velt-id="${e?.annotationId}"]`);i?.length&&i.forEach(d=>{let m=d?.parentNode;d?.textContent&&Ph(d),m&&a.add(m)})}a.forEach(i=>_C(i)),t?.inlineCommentElement&&t?.inlineCommentElement?.remove(),this.checkToUnsubscribeCommonAncestorElementChanges(e),delete this.commentsTextById[e.annotationId]}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeTextCommentAnnotation: ",t)}}observeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];if(Dr(t?.commonAncestorElement))return;if(t.commonAncestorElement){let a=this.commonAncestorElementObservers.get(t.commonAncestorElement);if(a)a.annotations.find(i=>i.annotationId===e.annotationId)||a.annotations.push(e);else{let i=new MutationObserver(d=>{let m="";if(IC(t?.commonAncestorElement).forEach(f=>{f?.parentElement?.closest(".comment-annotation-number")||(m+=f.textContent)}),t?.commonAncestorText!==m&&d.filter(f=>[Node.ELEMENT_NODE,Node.TEXT_NODE].includes(f.target.nodeType)).filter(f=>f.target?.parentElement&&(f?.target?.parentElement?.classList?.contains("comment-text-highlight")||!Mm(f.target?.parentElement))).length){this.commonAncestorElementObservers.get(t.commonAncestorElement)?.annotations?.forEach(W=>{this.onCommonAncestorElementChange(W)});let{count:y,lastUpdated:S}=this.commonAncestorElementObserverCounts.get(t.commonAncestorElement)||{count:0,lastUpdated:0},j=Date.now();this.commonAncestorElementObserverCounts.set(t.commonAncestorElement,{count:j-S<100?y+1:1,lastUpdated:Date.now()}),y>5&&(i.disconnect(),this.loggingService.catch("Failed to detect text changes."))}});i.observe(t.commonAncestorElement,{characterData:!0,subtree:!0}),a={observer:i,annotations:[e]}}this.commonAncestorElementObservers.set(t.commonAncestorElement,a)}}catch(t){this.loggingService.catch("Error in CommentPinPortalService observeCommonAncestorElementChanges: ",t)}}onCommonAncestorElementChange(e){try{let t=this.commentsTextById[e.annotationId];if(t?.texts?.some(a=>Dr(a?.element)))return;if(t.texts?.length){let a="";t.texts.forEach(y=>a+=y.textNode?.textContent);let i=t.texts[0].textNode,d=[];document.querySelectorAll(`${Z.TAGS.SNIPPYLY_TEXT_HIGHLIGHT}[data-velt-id="${e?.annotationId}"]`)?.forEach(y=>{d.push(y)});let m=!1;if(d?.length!==t?.texts?.length&&(m=!0),d?.length){let y="";d.forEach(S=>{y+=S?.textContent||""}),y&&(a=y,m&&this.removeTextCommentAnnotation(e))}let u=CC(t.commonAncestorContainer,0,i,0,a)+1,f={};f.commonAncestorContainer=e.targetTextRange?.commonAncestorContainer,f.text=a,f.occurrence=u,xn(e.targetTextRange,f)||(t.annotation.targetTextRange=f,this.updateAnnotationToFirebase(t.annotation))}else this.setTextCommentPortal(t.annotation)}catch(t){this.loggingService.catch("Error in CommentPinPortalService onCommonAncestorElementChange: ",t)}}updateAnnotationToFirebase(e){try{this.commentService.updateComment(e,!1,!0)}catch(t){this.loggingService.catch("Error in CommentPinPortalService updateAnnotationToFirebase: ",t)}}checkToUnsubscribeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];if(t.commonAncestorElement){let a=this.commonAncestorElementObservers.get(t.commonAncestorElement);a&&(a.annotations=a?.annotations.filter(i=>i.annotationId!==e.annotationId),a.annotations.length||this.unsubscribeCommonAncestorElementChanges(e))}}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkToUnsubscribeCommonAncestorElementChanges: ",t)}}setGhostComment(e){try{e.ghostComment={},this.commentService.setGhostCommentMessage(e),this.commentService.addAnnotationToGhostCommentAnnotationMap(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService setGhostComment: ",t)}}removeGhostComment(e){try{delete e.ghostComment,this.commentService.removeAnnotationFromGhostCommentAnnotationMap(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeGhostComment: ",t)}}onAcceptComment(e){try{let t=this.commentsTextById[e.annotationId];if(t?.texts?.length){let a=t.texts.length-1,i=t.texts[a].textNode;if(i&&i.parentNode){let d=e.comments?.length?e.comments[0]:null,m=Vu(d?.replaceContentHtml)?null:d?.replaceContentHtml,u=d?.replaceContentText||d?.commentText||"";if(Vu(m)&&!d?.replaceContentText&&(m=d?.commentHtml||""),e?.selectAllContent&&e?.targetElementId){let f=Lr(e.targetElementId,["id","data-id"]);if(f&&(Dr(f)||xC(f))){this.loggingService.log("[Velt] accept skipped: the target element contains a ProseMirror/TipTap editor.");return}else f&&(f.innerHTML=this.domService.sanitizeHtml(Vu(m)?u||"":m||""))}else{if(m&&m!==u){let f=document.createElement("span");f.innerHTML=this.domService.sanitizeHtml(m||u||""),i.parentNode.replaceChild(f,i),t.texts[a].textNode=f}else t.texts[a].textNode.textContent=u||"";for(let f=0;f<a;f++){let y=t.texts[f].textNode;y&&(y.textContent="")}}this.removeTextCommentAnnotation(e),this.domService.resetSelectedAnnotationsMap()}}}catch(t){this.loggingService.catch("Error in CommentPinPortalService onAcceptComment: ",t)}}unsubscribeCommonAncestorElementChanges(e){try{let t=this.commentsTextById[e.annotationId];this.commonAncestorElementObservers.get(t.commonAncestorElement)?.observer?.disconnect(),this.commonAncestorElementObservers.delete(t.commonAncestorElement)}catch(t){this.loggingService.catch("Error in CommentPinPortalService unsubscribeCommonAncestorElementChanges: ",t)}}};o.\u0275fac=function(t){return new(t||o)(be(ut),be(Re),be(ae),be(lu),be(nu),be(du),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();function QD(r,o){if(r&1){let n=Y();C(0,"div",4),z("pointerup",function(t){return B(n),l(2).togglePinSelection(void 0,t),V(t.stopPropagation())})("click",function(t){return B(n),V(t.stopPropagation())})("cdkDragStarted",function(){B(n);let t=l(2);return V(t.onPinDragStart())}),C(1,"snippyly-comment-pin",5),z("saveComment",function(t){B(n);let a=l(2);return V(a.saveComment(t))})("commentTargetElementClicked",function(){B(n);let t=l(2);return V(t.togglePinSelection())})("togglePinSelection",function(t){B(n);let a=l(2);return V(a.togglePinSelection(t))}),_()()}if(r&2){let n=l().ngIf,e=l();mt("top",(n.commentPinAnnotation==null||n.commentPinAnnotation.position==null?null:n.commentPinAnnotation.position.top)-0+n.offsetTop,"px")("left",(n.commentPinAnnotation==null||n.commentPinAnnotation.position==null?null:n.commentPinAnnotation.position.left)-10+n.offsetLeft,"px"),c("id","comment-pin-container-"+(n.commentPinAnnotation==null?null:n.commentPinAnnotation.annotationId)),x("data-testid",e.componentId+"-popover")("role","button")("aria-expanded",n.commentPinSelected),v(),c("annotation",n.commentPinAnnotation)("containerComponentId",n.componentId)("commentPinSelected",n.commentPinSelected&&!n.annotationDragging)("multipleCommentPinSelected",n.commentPinSelected&&e.objectKeys(n.selectedAnnotationsMap).length>1)("targetElement",n.targetElement)("user",n.user)}}function XD(r,o){if(r&1){let n=Y();C(0,"div",7),z("pointerup",function(t){return B(n),l(3).togglePinSelection(void 0,t),V(t.stopPropagation())})("touchend",function(t){return B(n),t.stopPropagation(),V(t.preventDefault())})("mousedown",function(t){return B(n),V(t.stopPropagation())})("touchstart",function(t){return B(n),V(t.stopPropagation())})("pointerdown",function(t){return B(n),V(t.stopPropagation())})("click",function(t){return B(n),V(t.stopPropagation())})("cdkDragStarted",function(){B(n);let t=l(3);return V(t.onPinDragStart())})("cdkDragMoved",function(t){B(n);let a=l(3);return V(a.onPinMove(t))})("cdkDragReleased",function(){B(n);let t=l(3);return V(t.onPinRelease())}),C(1,"snippyly-comment-pin",8,1),z("togglePinSelection",function(t){B(n);let a=l(3);return V(a.togglePinSelection(t))})("saveComment",function(t){B(n);let a=l(3);return V(a.saveComment(t))}),_()()}if(r&2){let n=we(2),e=l(2).ngIf,t=l();mt("top",e.annotationDragging?(e.dragPosition==null?null:e.dragPosition.top)-((n==null?null:n.COMMENT_PIN_SIZE)||40):(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.top)-((n==null?null:n.COMMENT_PIN_SIZE)||40)+e.offsetTop,"px")("left",e.annotationDragging?e.dragPosition==null?null:e.dragPosition.left:(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.left)+e.offsetLeft,"px")("--velt-comment-pin-transform",e.annotationDragging?"none":e.pinTransform??"none")("transform",!e.annotationDragging&&(!(e.commentPinAnnotation==null||e.commentPinAnnotation.position==null)&&e.commentPinAnnotation.position.parentScaleX)?"scale("+1/((e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.parentScaleX)||1)+", "+1/((e.commentPinAnnotation==null||e.commentPinAnnotation.position==null?null:e.commentPinAnnotation.position.parentScaleY)||1)+")":""),pe("pin-dragging",e.annotationDragging),c("id","comment-pin-container-"+(e.commentPinAnnotation==null?null:e.commentPinAnnotation.annotationId))("cdkDragDisabled",!e.pinDragEnabled||(e.commentPinAnnotation==null||e.commentPinAnnotation.from==null?null:e.commentPinAnnotation.from.userId)!==(e.user==null?null:e.user.userId)),x("data-testid",t.componentId+"-default")("role","button")("aria-expanded",e.commentPinSelected)("aria-grabbed",e.annotationDragging)("data-transform-inside",e.transformContext?"true":"false"),v(),c("annotation",e.commentPinAnnotation)("annotationDragging",e.annotationDragging)("containerComponentId",e.componentId)("commentPinSelected",e.commentPinSelected&&!e.annotationDragging)("multipleCommentPinSelected",e.commentPinSelected&&t.objectKeys(e.selectedAnnotationsMap).length>1)("targetElement",e.targetElement)("user",e.user)}}function e3(r,o){if(r&1&&s(0,XD,3,24,"div",6),r&2){let n=l().ngIf;c("ngIf",n.commentPinAnnotation==null?null:n.commentPinAnnotation.position)}}function t3(r,o){if(r&1&&(p(0),s(1,QD,2,14,"div",3)(2,e3,1,1,"ng-template",null,0,$e),h()),r&2){let n=o.ngIf,e=we(3);v(),c("ngIf",n.popoverMode)("ngIfElse",e)}}var bp=(()=>{let o=class o{constructor(e,t,a,i,d,m,u,f){this.analyticsService=e,this.authService=t,this.docService=a,this.domService=i,this.commentService=d,this.commentActionsService=m,this.loggingService=u,this.elementRef=f,this.multipleCommentPinsSelected=!1,this.avatarErrorImage="",this.objectKeys=Object.keys,this.selectedAnnotationsLocationMap={},this.subscriptions=[],this.componentConfigSignal=Ae({popoverMode:!1,commentPinAnnotation:void 0,commentPinSelected:!1,offsetLeft:0,offsetTop:0,selectedAnnotationsMap:{},annotationDragging:!1,dragPosition:null,targetElement:void 0,user:void 0,componentId:`comment-pin-portal-${Jt()}`,pinDragEnabled:!0}),this.veltElement=!0,this.componentId="velt-comment-pin-portal",this.subscriptions.push(this.authService.getUser$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{user:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getUser$ subscription: ",y)})),this.subscriptions.push(this.domService.getSelectedAnnotationsMap$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{selectedAnnotationsMap:y}),S)),this.checkCommentPinSelected()},y=>{this.catchError("Error in CommentPinPortalComponent getSelectedAnnotationsMap$ subscription: ",y)})),this.subscriptions.push(this.domService.getSelectedAnnotationsLocationMap$().subscribe(y=>{this.selectedAnnotationsLocationMap=y||{},this.checkCommentPinSelected()},y=>{this.catchError("Error in CommentPinPortalComponent getSelectedAnnotationsLocationMap$ subscription: ",y)})),this.subscriptions.push(this.commentService.getPinDrag$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{pinDragEnabled:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getPinDrag$ subscription: ",y)})),this.subscriptions.push(this.commentService.getPopoverMode$().subscribe(y=>{this.componentConfigSignal.update(S=>(S=b(g({},S),{popoverMode:y}),S))},y=>{this.catchError("Error in CommentPinPortalComponent getPopoverMode subscription: ",y)}))}ngOnInit(){try{this.setupA11yAttributes(),this.subscriptions.push(this.commentService.getTransformContext$().subscribe(e=>{this.componentConfigSignal.update(t=>{if(t=b(g({},t),{transformContext:e}),e&&this.isElementInsideTransformContainer(this.elementRef?.nativeElement,e.containerSelector)){let a=e.transforms.scale?1/e.transforms.scale:1;t.pinTransform=`scale(${a})`}else t.pinTransform=void 0;return t})}))}catch(e){this.loggingService.catch("Error in CommentPinPortalComponent ngOnInit:",e)}}isElementInsideTransformContainer(e,t){try{return document.querySelector(t)?.contains(e)??!1}catch(a){return this.loggingService.catch("Error in CommentPinPortalComponent isElementInsideTransformContainer:",a),!1}}setupA11yAttributes(){try{this.elementRef.nativeElement.setAttribute("data-testid",this.componentId+"-container")}catch(e){this.loggingService.catch("Error in CommentPinPortalComponent setupA11yAttributes:",e)}}setCommentPinAnnotation(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{commentPinAnnotation:e}),t)),this.id=this.componentConfigSignal().commentPinAnnotation?.annotationId,this.checkCommentPinSelected()}catch(t){this.catchError("Error in CommentPinPortalComponent setCommentPinAnnotation: ",t)}}setSourceId(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{sourceId:e}),t)),this.checkCommentPinSelected()}catch(t){this.catchError("Error in CommentPinPortalComponent setSourceId: ",t)}}getMultiThreadCommentAnnotations(){}checkCommentPinSelected(){try{let e=this.componentConfigSignal().selectedAnnotationsMap,t=this.componentConfigSignal().commentPinAnnotation,a=this.componentConfigSignal().sourceId;if(t){let i=!!e[t.annotationId];if(i)if(t?.isDraft)t?.sourceId&&(i=t?.sourceId===a,i&&this.domService.setSelectedAnnotationLocation(t.annotationId,this.componentConfigSignal().componentId));else{let d=this.selectedAnnotationsLocationMap?.[t.annotationId];d&&(i=d===this.componentConfigSignal().componentId)}i!==this.componentConfigSignal().commentPinSelected&&this.componentConfigSignal.update(d=>(d=b(g({},d),{commentPinSelected:i}),d))}}catch(e){this.catchError("Error in CommentPinPortalComponent checkCommentPinSelected: ",e)}}setTargetElement(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{targetElement:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setTargetElement: ",t)}}setOffsetLeft(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{offsetLeft:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setOffsetLeft: ",t)}}setOffsetTop(e){try{this.componentConfigSignal.update(t=>(t=b(g({},t),{offsetTop:e}),t))}catch(t){this.catchError("Error in CommentPinPortalComponent setOffsetTop: ",t)}}togglePinSelection(e,t){try{if(Zo(t))return;let a=e||this.componentConfigSignal().commentPinAnnotation;if(a&&this.commentActionsService.onCommentPinClick(a).catch(d=>{this.catchError("Error in CommentPinPortalComponent togglePinSelection onCommentPinClick: ",d)}),this.componentConfigSignal().selectedAnnotationsMap[a?.annotationId]&&this.selectedAnnotationsLocationMap?.[a?.annotationId]===this.componentConfigSignal().componentId)a?.ghostComment?.type!==an.DIFFERENT_DEVICE&&document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}="${a?.annotationId}"]`)&&this.domService.resetSelectedAnnotationsMap(!0,"comments");else{let d=document.querySelector(`[${Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);if(d||(d=(this.domService.getDraftCommentAnnotationDialogs()||[])[0]),d){let m=d.getAttribute(Z.ATTRIBUTES.VELT_ANNOTATION_DRAFT);if(m){let u=document.getElementById(`comment-pin-container-${m}`)||document.querySelector(`[data-velt-id='${m}']`);u&&(u.scrollIntoView({behavior:"auto",block:"center",inline:"center"}),this.domService.resetSelectedAnnotationsMap(!0,"comments"))}}else this.domService.resetSelectedAnnotationsMap(!0,"comments"),this.componentConfigSignal().targetElement&&this.domService.isElementVisibleOnScreen(this.componentConfigSignal().targetElement)&&(this.componentConfigSignal().annotationDragging||this.domService.toggleAnnotationSelection(a,this.componentConfigSignal().componentId,void 0,!0))}}catch(a){this.catchError("Error in CommentPinPortalComponent togglePinSelection: ",a)}}onPinDragStart(){try{this.componentConfigSignal().selectedAnnotationsMap[this.componentConfigSignal().commentPinAnnotation.annotationId]&&this.componentConfigSignal().commentPinAnnotation?.ghostComment?.type!==an.DIFFERENT_DEVICE&&this.domService.toggleAnnotationSelection(this.componentConfigSignal().commentPinAnnotation,this.componentConfigSignal().componentId);let e=document.getElementById(this.componentConfigSignal().commentPinAnnotation.annotationId);if(!e)return;this.parentElement=e.parentElement;let t=this.componentConfigSignal().commentPinAnnotation.position,a=this.componentConfigSignal().transformContext,i=this.parentElement.getBoundingClientRect(),d=i.left+t.left,m=i.top+t.top,u=a&&this.isElementInsideTransformContainer(e,a.containerSelector);this.componentConfigSignal.update(f=>(f=b(g({},f),{elementInTransformedContainer:u}),f)),e.style.width="20px",e.style.height="20px",e.style.margin="0",e.style.padding="0",e.style.display="block",e.style.visibility="visible",e.style.opacity="1",e.style.backgroundColor="var(--velt-comment-pin-background-color, #2d62ff)",e.style.borderRadius="50%",e.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.2)",e.style.pointerEvents="auto",e.offsetWidth,document.body.appendChild(e),e.style.position="fixed",e.style.top=`${m}px`,e.style.left=`${d}px`,e.style.zIndex="10000",e.style.transform="none",e.offsetWidth,document.body.classList.add(Z.BODY_CLASSES.VELT_PIN_DRAGGING),this.componentConfigSignal.update(f=>(f=b(g({},f),{annotationDragging:!0}),f))}catch(e){this.catchError("Error in CommentPinPortalComponent onPinDragStart: ",e)}}onPinMove(e){try{this.updateCurrentPinPosition(e)}catch(t){this.catchError("Error in CommentPinPortalComponent onPinMove: ",t)}}updateCurrentPinPosition(e){try{this.domService.removeHighlightFromElement(this.componentConfigSignal().targetElement);let t=e.event,a=t?.touches?.length?t.touches[0]?.clientX:t.clientX,i=t?.touches?.length?t.touches[0]?.clientY:t.clientY,d=this.componentConfigSignal().transformContext,m=this.domService.getBackgroundElement(a,i);m&&this.commentService.isElementInsideAllowedElements(m)&&!Dr(m)&&(this.componentConfigSignal.update(u=>(u=b(g({},u),{targetElement:m}),u)),this.domService.highlightElement(this.componentConfigSignal().targetElement),this.pointerMoveEvent=e.event,this.componentConfigSignal.update(u=>(u=b(g({},u),{dragPosition:{top:i,left:a}}),u)))}catch(t){this.catchError("Error in CommentPinPortalComponent updateCurrentPinPosition: ",t)}}onPinRelease(){try{document.body.classList.remove(Z.BODY_CLASSES.VELT_PIN_DRAGGING);let e=document.getElementById(this.componentConfigSignal().commentPinAnnotation.annotationId);if(!e||!this.parentElement)return;this.domService.removeHighlightFromElement(this.componentConfigSignal().targetElement);let t=this.domService.getElementFromXPath(this.componentConfigSignal().commentPinAnnotation.targetElement?.xpath),a=this.componentConfigSignal().commentPinAnnotation?.targetElement;if(this.pointerMoveEvent){let q=this.domService.getTargetElementForCursorPosition(this.pointerMoveEvent,!0,!0,!0,ce=>{if(this.commentService.getSvgAsImg()){let fe=ce?.closest(`[${Z.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);fe&&fe instanceof HTMLElement&&(ce=fe)}if(Dr(ce)){let fe=this.componentConfigSignal().targetElement;return fe&&!Dr(fe)?fe:null}return ce},!0,void 0,this.commentService.getPinXPathOptions?.({annotation:this.componentConfigSignal().commentPinAnnotation}));q&&(a=q)}let i=this.domService.getElementFromXPath(a?.xpath),d=this.componentConfigSignal().commentPinAnnotation.targetElement?.xpath,m=a?.xpath,u=d===m;if(!i)return;let f=this.componentConfigSignal().dragPosition,y=i.getBoundingClientRect(),S=50,j=50;if(f){let q=f.left-y.left,ce=f.top-y.top;S=q/y.width*100,j=ce/y.height*100,S=Math.max(0,Math.min(100,S)),j=Math.max(0,Math.min(100,j))}let W=g({},this.componentConfigSignal().commentPinAnnotation);W.targetElement=g({},a),W.targetElement.leftPercentage=S,W.targetElement.topPercentage=j,this.commentService.calculateCommentAnnotationPosition(W),this.componentConfigSignal.update(q=>(q=b(g({},q),{commentPinAnnotation:W,targetElement:i}),q));let $=this.domService.isElementInsideAdditionalLocationContainer(t)||this.domService.isElementInsideAdditionalLocationContainer(i),H=this.docService.getAdditionalDocumentIdFromElement(i)||this.docService.getDocumentPaths()?.clientDocumentId;if(!this.componentConfigSignal().commentPinAnnotation?.metadata?.clientDocumentId||this.componentConfigSignal().commentPinAnnotation?.metadata?.clientDocumentId==H?(this.componentConfigSignal.update(q=>(q=b(g({},q),{commentPinAnnotation:b(g({},q.commentPinAnnotation),{targetElement:a})}),q)),this.commentService.updateComment(this.componentConfigSignal().commentPinAnnotation,$)):this.componentConfigSignal.update(q=>(q=b(g({},q),{targetElement:t}),q)),u){let q=this.componentConfigSignal().transformContext,ce=this.componentConfigSignal().elementInTransformedContainer,fe=q&&this.isElementInsideTransformContainer(i,q.containerSelector);this.componentConfigSignal.update(he=>(he=b(g({},he),{elementInTransformedContainer:fe}),he));let le=e.getBoundingClientRect();if(!ce&&fe){e.style.transition="none";let he=le.top,xe=le.left;this.parentElement.appendChild(e),e.style.position="fixed",e.style.top=`${he}px`,e.style.left=`${xe}px`,e.offsetWidth,requestAnimationFrame(()=>{e.style.position="absolute",fe&&W.position.transformContext?(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`,W.position.transformContext.scale!==1&&(e.style.transform=`scale(${1/W.position.transformContext.scale})`)):(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`)})}else e.style.transition="none",this.parentElement.appendChild(e),e.style.position="absolute",e.style.width="20px",e.style.height="20px",e.style.backgroundColor="var(--velt-comment-pin-background-color, #2d62ff)",e.style.borderRadius="50%",e.style.boxShadow="0 2px 4px rgba(0, 0, 0, 0.2)",e.style.visibility="visible",e.style.display="block",e.offsetWidth,fe&&W.position.transformContext?(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`):(e.style.top=`${W.position.top}px`,e.style.left=`${W.position.left}px`);e.offsetWidth,this.componentConfigSignal.update(he=>(he=b(g({},he),{annotationDragging:!1,dragPosition:null}),he))}this.analyticsService.trackEvent(oe.Events.Comments.COMMENT_PIN_DRAGGED,{annotationId:this.componentConfigSignal().commentPinAnnotation.annotationId,commentMode:this.commentService.getCommentMode()})}catch(e){this.catchError("Error in CommentPinPortalComponent onPinRelease: ",e)}}saveComment(e){try{this.commentService.saveComment(this.componentConfigSignal().commentPinAnnotation,e)}catch(t){this.catchError("Error in CommentPinPortalComponent saveComment: ",t)}}ngOnDestroy(){this.loggingService.log("%c[WB] Calling FUNCTION: ngOnDestroy","color: green;");try{this.unsubscribe(),this.componentConfigSignal()?.annotationDragging&&document.body.classList.remove(Z.BODY_CLASSES.VELT_PIN_DRAGGING)}catch(e){this.catchError("Error in CommentPinPortalComponent ondestroy: ",e)}}unsubscribe(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[]}catch(e){this.catchError("Error in CommentPinPortalComponent unsubscribe: ",e)}}catchError(e,t,a){try{this.loggingService.catch(e,t,b(g({},a||{}),{annotationId:this.componentConfigSignal()?.commentPinAnnotation?.annotationId}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(G(pr),G(vt),G(ut),G(Re),G(ae),G(lt),G(A),G(me))},o.\u0275cmp=T({type:o,selectors:[["snippyly-comment-pin-portal"]],hostVars:2,hostBindings:function(t,a){t&2&&(wb("id",a.id),x("data-velt-element",a.veltElement))},inputs:{multipleCommentPinsSelected:"multipleCommentPinsSelected",avatarErrorImage:"avatarErrorImage"},standalone:!1,decls:1,vars:1,consts:[["defaultPinPortalRef",""],["commentPinRef",""],[4,"ngIf"],["class","comment-pin-portal",3,"id","top","left","pointerup","click","cdkDragStarted",4,"ngIf","ngIfElse"],[1,"comment-pin-portal",3,"pointerup","click","cdkDragStarted","id"],[3,"saveComment","commentTargetElementClicked","togglePinSelection","annotation","containerComponentId","commentPinSelected","multipleCommentPinSelected","targetElement","user"],["class","comment-pin-portal","cdkDrag","","cdkDragHandle","",3,"id","pin-dragging","top","left","--velt-comment-pin-transform","transform","cdkDragDisabled","pointerup","touchend","mousedown","touchstart","pointerdown","click","cdkDragStarted","cdkDragMoved","cdkDragReleased",4,"ngIf"],["cdkDrag","","cdkDragHandle","",1,"comment-pin-portal",3,"pointerup","touchend","mousedown","touchstart","pointerdown","click","cdkDragStarted","cdkDragMoved","cdkDragReleased","id","cdkDragDisabled"],[3,"togglePinSelection","saveComment","annotation","annotationDragging","containerComponentId","commentPinSelected","multipleCommentPinSelected","targetElement","user"]],template:function(t,a){t&1&&s(0,t3,4,2,"ng-container",2),t&2&&c("ngIf",a.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{position:absolute!important;top:0!important;left:0!important;box-sizing:border-box!important;-webkit-tap-highlight-color:rgba(255,255,255,0)!important;outline:none!important;margin:0!important;padding:0!important;height:unset!important;width:unset!important;text-align:left!important;z-index:var(--velt-comment-pin-z-index)!important}*[_ngcontent-%COMP%]{box-sizing:border-box;-webkit-tap-highlight-color:rgba(255,255,255,0)!important;outline:none!important;margin:0!important;padding:0!important;height:unset;width:unset;text-align:left!important;line-height:1.5!important;color:#000!important;font-size:calc((1rem + 0px) * var(--velt-base-rem-unit));-webkit-text-fill-color:initial!important}*[_ngcontent-%COMP%]:empty{display:revert!important}.comment-pin-portal[_ngcontent-%COMP%]{position:absolute;transform:var(--velt-comment-pin-transform, none)!important;transform-origin:0 100%!important;transform-box:fill-box!important;top:0;left:0}.comment-pin-portal.pin-dragging[_ngcontent-%COMP%]{position:fixed;z-index:var(--velt-comment-pin-z-index)!important}"],changeDetection:0});let r=o;return r})();var To=(()=>{let o=class o{constructor(e,t,a,i,d,m){this.commentService=e,this.domService=t,this.componentFactoryResolver=a,this.injector=i,this.appRef=d,this.loggingService=m,this.commentsPinById={},this.commentPinTemplate$=new De(null),this.reattachTimes=new Map,this.reattachStopped=new Set,this.customPinEvents$=new Lt}setCommentPin(e){try{if(!this.commentsPinById[e.annotationId])this.setPinPortal(e);else{let t=!1;if(e?.ghostComment?t=e?.ghostComment?.targetElement?.xpath!==this.commentsPinById[e.annotationId]?.[0]?.annotation?.ghostComment?.targetElement?.xpath:this.commentsPinById[e.annotationId]?.[0]?.annotation?.ghostComment?t=!0:t=e.targetElement?.xpath!==this.commentsPinById[e.annotationId]?.[0]?.annotation?.targetElement?.xpath,!t&&this.isPinTargetChangedByIdScopedAnchoring(e)&&(t=!0),!t)this.commentsPinById[e.annotationId]?.forEach(a=>{let i=a.portalRef,d=a.userTargetElement,m=a.pinHostElement;if(document.body.contains(d)&&document.body.contains(m))i&&(i.instance.setCommentPinAnnotation(e),this.updateElementOffset(e));else{let u=a.pinHostDomPortalOutlet;u&&(this.removeCommentPinHostAttributes(e.annotationId,a.pinHostElement),this.removeCommentDisabledAttribute(m),u.detach(),delete this.commentsPinById[e.annotationId],e.ghostComment&&this.unselectCommentAnnotation(e),this.setPinPortal(e))}});else{let a=this.commentsPinById[e.annotationId]??[];a.some(i=>i.pinHostDomPortalOutlet)&&(a.forEach(i=>{this.removeCommentPinHostAttributes(e.annotationId,i.pinHostElement),this.removeCommentDisabledAttribute(i.pinHostElement),i.pinHostDomPortalOutlet?.detach()}),delete this.commentsPinById[e.annotationId],e.ghostComment&&this.unselectCommentAnnotation(e),this.setPinPortal(e))}}}catch(t){this.loggingService.catch("Error in CommentPinPortalService setCommentPin: ",t)}}reattachDetachedPins(e){try{e?.forEach(t=>{let a=t?.annotationId,i=this.commentsPinById[a];!i?.some(m=>!document.body.contains(m.userTargetElement)||!document.body.contains(m.pinHostElement)||!m.pinHostElement.contains(m.portalRef?.location?.nativeElement))||this.reattachStopped.has(a)||i.some(m=>Dr(m.pinHostElement)||Dr(m.userTargetElement))||this.allowReattach(a)&&(i.forEach(m=>{this.removeCommentPinHostAttributes(a,m.pinHostElement),this.removeCommentDisabledAttribute(m.pinHostElement),m.pinHostDomPortalOutlet?.detach()}),delete this.commentsPinById[a],t.ghostComment&&this.unselectCommentAnnotation(t),this.setPinPortal(t))})}catch(t){this.loggingService.catch("Error in CommentPinPortalService reattachDetachedPins: ",t)}}allowReattach(e){try{let t=Date.now(),a=(this.reattachTimes.get(e)||[]).filter(i=>t-i<o.REATTACH_WINDOW_MS);return a.length>=o.REATTACH_LIMIT?(this.reattachStopped.add(e),this.reattachTimes.delete(e),this.loggingService.log(`[Velt] Comment pin ${e}: its element keeps removing the pin; not re-attaching it again.`),!1):(a.push(t),this.reattachTimes.set(e,a),!0)}catch(t){return this.loggingService.catch("Error in CommentPinPortalService allowReattach: ",t),!1}}unselectCommentAnnotation(e){try{this.loggingService.log("%c[WB] Calling CommentPinPortalService FUNCTION: unselectCommentAnnotation","color: green;"),this.domService.getSelectedAnnotationsMap()?.[e?.annotationId]&&this.domService.toggleAnnotationSelection(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService unselectCommentAnnotation: ",t)}}isPinTargetChangedByIdScopedAnchoring(e){let t=this.commentsPinById[e.annotationId],a=this.commentService.getIdScopedAnchoringVersion?.()??0;if(!t?.length||t.every(m=>(m.idScopedAnchoringVersion??0)===a))return!1;let i=this.commentService.getElementFromComments(e)??[],d=i.length!==t.length||i.some((m,u)=>m!==t[u].userTargetElement);return d||t.forEach(m=>{m.idScopedAnchoringVersion=a}),d}setPinPortal(e){try{let t=this.commentService.getElementFromComments(e);t.length>0&&(this.commentsPinById[e.annotationId]=[],t.forEach(a=>{if(a){let i=this.domService.getHostElement(a),d=new pu(bp),m=new hu(i,this.appRef,this.injector),u=m.attach(d);u.instance.setCommentPinAnnotation(e),u.instance.setTargetElement(a);let f=a?.getAttribute(Z.ATTRIBUTES.VELT_SOURCE_ID);f&&u.instance.setSourceId(f),this.commentsPinById[e.annotationId].push({pinHostDomPortalOutlet:m,pinPortal:d,portalRef:u,annotation:JSON.parse(JSON.stringify(e)),userTargetElement:a,pinHostElement:i,idScopedAnchoringVersion:this.commentService.getIdScopedAnchoringVersion?.()??0}),this.setCommentPinHostAttributes(e.annotationId,i),this.setCommentDisabledAttribute(i),this.updateElementOffset(e)}}))}catch(t){this.loggingService.catch("Error in CommentPinPortalService setPinPortal: ",t)}}setCommentPinHostAttributes(e,t){try{let a=t.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST);if(a){let i=a.split(",");i.includes(e)||(i.push(e),t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,i.join(",")))}else t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,e);this.domService.isElementOriginallyStatic(t)&&t.offsetHeight>0&&(OC(t)||t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC,"true"))}catch(a){this.loggingService.catch("Error in CommentPinPortalService setCommentPinHostAttributes: ",a)}}removeCommentPinHostAttributes(e,t){try{let a=t.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST);if(a){let i=a.split(","),d=i.indexOf(e);d>-1&&(i.splice(d,1),i.length>0?t.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST,i.join(",")):t.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST))}t?.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST)||t.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)}catch(a){this.loggingService.catch("Error in CommentPinPortalService removeCommentPinHostAttributes: ",a)}}setCommentDisabledAttribute(e){try{this.commentService.getPopoverMode()&&e.setAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED,"auto")}catch(t){this.loggingService.catch("Error in CommentPinPortalService setCommentDisabledAttribute: ",t)}}removeCommentDisabledAttribute(e){try{e?.getAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED)==="auto"&&e.removeAttribute(Z.ATTRIBUTES.VELT_COMMENT_DISABLED)}catch(t){this.loggingService.catch("Error in CommentPinPortalService removeCommentDisabledAttribute: ",t)}}updateElementOffset(e){try{for(let t of this.commentsPinById[e.annotationId]){let{portalRef:a,userTargetElement:i,pinHostElement:d}=t,m=this.domService.getElementOffset(i,d);a.instance.setOffsetLeft(m.offsetLeft),a.instance.setOffsetTop(m.offsetTop)}}catch(t){this.loggingService.catch("Error in CommentPinPortalService updateElementOffset: ",t)}}checkPinsToRemove(e){try{let t=new Set(e.map(a=>a.annotationId));Object.keys(this.commentsPinById).forEach(a=>{t.has(a)||(this.commentService.customPinsById.has(a)&&this.commentService.customPinsById.delete(a),this.commentsPinById[a].forEach(d=>{d.pinHostDomPortalOutlet.detach(),this.removeCommentPinHostAttributes(a,d.pinHostElement),this.removeCommentDisabledAttribute(d.pinHostElement),this.domService.removeHighlightFromElement(d.pinHostElement),d.userTargetElement&&this.domService.removeHighlightFromElement(d.userTargetElement)}),delete this.commentsPinById[a])})}catch(t){this.loggingService.catch("Error in CommentPinPortalService checkPinsToRemove: ",t)}}getAnnotationIdsByUserTargetElement(e){try{let t=[];return Object.keys(this.commentsPinById||{}).forEach(a=>{this.commentsPinById[a]?.forEach(d=>{d.userTargetElement===e&&t.push(a)})}),t?.length>0?Array.from(new Set(t)):[]}catch(t){return this.loggingService.catch("Error in CommentPinPortalService getAnnotationIdsByUserTargetElement: ",t),[]}}setCommentPinOverrideTemplate(e){this.commentPinTemplate$.next(e)}getCommentPinTemplate$(){return this.commentPinTemplate$}emitCustomPinEvent(e){try{let{element:t,annotation:a}=e;a&&this.commentService.customPinsById.set(a.annotationId,t),this.customPinEvents$.next(e)}catch(t){this.loggingService.catch("Error in CommentPinPortalService emitCustomPinEvent",t)}}getCustomPinEvents$(){return this.customPinEvents$}};o.REATTACH_LIMIT=20,o.REATTACH_WINDOW_MS=1e3,o.\u0275fac=function(t){return new(t||o)(be(ae),be(Re),be(lu),be(nu),be(du),be(A))},o.\u0275prov=et({token:o,factory:o.\u0275fac,providedIn:"root"});let r=o;return r})();var Br="data-velt-suggestion-inline",Vm="data-velt-mark",Wh="data-velt-before",Jh="data-velt-after",Hh="typing",Cp="velt-comment-text",Yh="velt-suggestion-inline-removed",Kh="velt-suggestion-inline-added",hk="velt-suggestion-inline-style",r3=5e3,n3=1e3,o3=100,a3=`
2
2
  [${Br}] { text-decoration: none; }
3
3
  ${Cp}[${Br}],
4
4
  ${Cp}[${Br}][comment-available] {