import{o as e,t}from"./chunk-CNMia1zD.js";import{l as n}from"./src-BFy5RBR8.js";import{T as r,d as i,h as a,i as o,k as s,l as c}from"./utils-BakkG8Vx.js";import{d as l,f as u,i as d,m as f,s as p,t as m,y as h}from"./hooks.module-5xe-uC6c.js";import{Dt as g,E as _,Et as v,F as y,I as b,K as x,O as S,Q as ee,ct as te,nt as ne,pt as re}from"./content_renderer-CoENEE63.js";import{n as C,s as w,t as T}from"./options-CDt8ZGCW.js";import{p as ie,t as ae}from"./compat.module-PCbCX7TU.js";import{t as E}from"./jsxRuntime.module--xb8gfv5.js";import{t as oe}from"./math-BjY8tSx6.js";import{n as se}from"./NoteList-DSkThDng.js";import{A as D,C as ce,G as le,J as ue,L as de,Q as O,U as k,V as fe,Z as pe,b as me,g as he,m as ge,n as A,o as j,u as M,v as _e,y as N}from"./hooks-CSTgmcXO.js";import{r as P}from"./experimental_features-3wqZ4yO-.js";import{t as F}from"./ActionButton-CbWZL7Kr.js";import{A as I,B as ve,D as ye,E as be,F as xe,G as L,H as R,K as Se,L as Ce,M as we,N as Te,O as Ee,R as De,S as Oe,U as ke,V as Ae,W as je,a as Me,b as Ne,d as Pe,i as Fe,j as Ie,k as Le,l as Re,o as ze,p as Be,q as Ve,r as He,t as Ue,u as We,v as Ge,x as Ke,y as qe,z as Je}from"./layout_commons-tNIV6Gmi.js";import{p as Ye}from"./i18n-Bp_koSZq.js";import{t as Xe}from"./Dropdown-CzkWLbhy.js";import{a as Ze}from"./FormList-BjfvxCF_.js";import{t as z}from"./Icon-rHGhZ_GT.js";import{n as Qe,t as $e}from"./resizer-CeDm6w98.js";import{t as B}from"./Modal-Dk3Wl80T.js";import{t as V}from"./Button-XVZ6KZoL.js";import{t as et}from"./FormCheckbox-DFFBeTyz.js";import{t as tt}from"./FormFileUpload-Ct7-T5Us.js";import{t as nt}from"./FormGroup--CU8SFQh.js";import{t as rt}from"./import-C426ww2P.js";import{t as it}from"./RawHtml-B22MTZKG.js";import{n as at,t as H}from"./RightPanelWidget-x6ws479r.js";import{t as ot}from"./formatters-b4WGxWvj.js";import{t as st}from"./note_tree-UW6ZSyvv.js";import{c as ct}from"./src-B85i7mku.js";import{t as lt}from"./NoItems-CjX4hzvd.js";import{t as ut}from"./text_notes-Dx59Ftl5.js";import{n as U,r as dt,t as ft}from"./useLlmChat-DMeVmtzC.js";l();function pt(){let{note:e,noteId:t}=ce(),[n,r]=p();k(`apiLogMessages`,({messages:e,noteId:n})=>{n===t&&r(e)}),f(()=>r(void 0),[e]);let i=e?.mime.startsWith(`application/javascript;env=`)&&n?.length;return E(`div`,{className:`api-log-widget ${i?``:`hidden-ext`}`,children:i&&E(h,{children:[E(F,{icon:`bx bx-x`,className:`close-api-log-button`,text:w(`api_log.close`),onClick:()=>r(void 0)}),E(`div`,{className:`api-log-container`,children:n.join(`
`)})]})})}l();function mt({isHorizontalLayout:e}){let[t,n]=p(T.is(`leftPaneVisible`));return k(`setLeftPaneVisibility`,({leftPaneVisible:e})=>{n(e??!t)}),f(()=>{$e.setupLeftPaneResizer(t)},[t]),E(F,{className:`${e?`toggle-button`:`launcher-button`} left-pane-toggle-button ${t?`action-collapse`:`action-expand`}`,text:w(t?`left_pane_toggle.hide_panel`:`left_pane_toggle.show_panel`),triggerCommand:t?`hideLeftPane`:`showLeftPane`,icon:e?`bx bx-sidebar`:`bx bx-chevrons-left`})}l();function ht(){let[e,t]=p(T.is(`rightPaneVisible`));return k(`toggleRightPane`,u(()=>{t(e=>!e)},[])),E(F,{className:_(`toggle-button right-pane-toggle-button bx-flip-horizontal`,e?`action-collapse`:`action-expand`),text:w(`right_pane.toggle`),icon:`bx bx-sidebar`,triggerCommand:`toggleRightPane`})}var gt=class extends ke{noteContext;thisElement;parentElement;resizeObserver;currentHeight=0;currentSafeMargin=NaN;constructor(){super(),this.class(`content-header-widget`),this.css(`contain`,`unset`),this.resizeObserver=new ResizeObserver(this.onResize.bind(this))}setNoteContextEvent({noteContext:e}){this.noteContext=e,this.init()}init(){if(this.parentElement=this.parent?.$widget.get(0),!this.parentElement){console.warn(`No parent set for <ContentHeader>.`);return}this.thisElement=this.$widget.get(0),this.resizeObserver.observe(this.thisElement),this.parentElement.addEventListener(`scroll`,this.updateSafeMargin.bind(this))}updateSafeMargin(){let e=Math.max(this.currentHeight-this.parentElement.scrollTop,0);e!==this.currentSafeMargin&&(this.currentSafeMargin=e,this.triggerEvent(`contentSafeMarginChanged`,{top:e,noteContext:this.noteContext}))}onResize(e){for(let t of e)t.target===this.thisElement&&(this.currentHeight=t.contentRect.height,this.updateSafeMargin())}},_t=class extends R{currentLeftPaneVisible;constructor(){super(`column`),this.currentLeftPaneVisible=T.is(`leftPaneVisible`),this.id(`left-pane`),this.css(`height`,`100%`),this.collapsible()}isEnabled(){return super.isEnabled()&&this.currentLeftPaneVisible}setLeftPaneVisibilityEvent({leftPaneVisible:e}){this.currentLeftPaneVisible=e??!this.currentLeftPaneVisible;let t=this.isEnabled();if(this.toggleInt(t),this.parent?.$widget.toggleClass(`left-pane-hidden`,!t),t)this.triggerEvent(`focusTree`,{});else{let e=b.tabManager.getActiveContext()?.ntxId;document.querySelector(`.note-split[data-ntx-id="${e}"]`)?.contains(document.activeElement)||this.triggerEvent(`focusOnDetail`,{ntxId:e})}T.save(`leftPaneVisible`,this.currentLeftPaneVisible.toString())}},vt=class extends R{rightPaneHidden;firstRender;constructor(){super(`column`),this.id(`right-pane`),this.css(`height`,`100%`),this.collapsible(),this.rightPaneHidden=!1,this.firstRender=!0}isEnabled(){return super.isEnabled()&&!this.rightPaneHidden&&this.children.length>0&&!!this.children.find(e=>e.isEnabled()&&e.canBeShown())}async handleEventInChildren(e,t){let n=super.handleEventInChildren(e,t);return[`activeContextChanged`,`noteSwitchedAndActivated`,`noteSwitched`].includes(e)&&(n?n.then(()=>this.reEvaluateRightPaneVisibilityCommand()):this.reEvaluateRightPaneVisibilityCommand()),n}reEvaluateRightPaneVisibilityCommand(){let e=!this.isHiddenInt(),t=this.isEnabled();(e!==t||this.firstRender)&&(this.toggleInt(t),$e.setupRightPaneResizer(),this.firstRender=!1)}toggleRightPaneEvent(){this.rightPaneHidden=!this.rightPaneHidden,this.reEvaluateRightPaneVisibilityCommand()}};l();function yt(){let[e,t]=p(!1);return k(`showPasswordNotSet`,()=>t(!0)),E(B,{size:`md`,className:`password-not-set-dialog`,title:w(`password_not_set.title`),footer:E(V,{icon:`bx bx-lock`,text:w(`password_not_set.go_to_password_options`),onClick:()=>{t(!1),b.triggerCommand(`showOptions`,{section:`_optionsPassword`})}}),onHidden:()=>t(!1),show:e,children:[E(`p`,{children:w(`password_not_set.body1`)}),E(`p`,{children:w(`password_not_set.body2`)})]})}l();function bt(){let[e,t]=p(),[n,r]=p(null),[i,a]=p(T.is(`compressImages`)),[o,s]=p(!1),[c,l]=p(void 0),[u,d]=p(!1);return k(`showUploadAttachmentsDialog`,({noteId:e})=>{t(e),d(!0)}),f(()=>{e&&te.getNoteTitle(e).then(e=>l(w(`upload_attachments.files_will_be_uploaded`,{noteTitle:e})))},[e]),E(B,{className:`upload-attachments-dialog`,size:`lg`,title:w(`upload_attachments.upload_attachments_to_note`),footer:E(V,{text:w(`upload_attachments.upload`),kind:`primary`,disabled:!n||o}),onSubmit:async()=>{if(!n||!e)return;s(!0);let t=Array.from(n);await rt.uploadFiles(`attachments`,e,t,{shrinkImages:i}),s(!1),d(!1)},onHidden:()=>{d(!1),r(null)},show:u,children:[E(nt,{name:`files`,label:w(`upload_attachments.choose_files`),description:c,children:E(tt,{onChange:r,multiple:!0})}),E(nt,{name:`shrink-images`,label:w(`upload_attachments.options`),children:E(et,{hint:w(`upload_attachments.tooltip`),label:w(`upload_attachments.shrink_images`),currentValue:i,onChange:a})})]})}var xt=`<button class="button-widget bx"
      data-bs-toggle="tooltip"
      title=""></button>`,St=class extends pe{settings;tooltip;isEnabled(){return!0}doRender(){this.$widget=$(xt),this.tooltip=new v(this.$widget[0],{html:!0,title:()=>this.getTitle()||``,trigger:`hover`,placement:i(this.settings.titlePlacement),fallbackPlacements:[i(this.settings.titlePlacement)]}),this.settings.onContextMenu&&this.$widget.on(`contextmenu`,e=>(this.tooltip.hide(),this.settings.onContextMenu&&this.settings.onContextMenu(e),!1)),super.doRender()}getTitle(){return typeof this.settings.title==`function`?this.settings.title():this.settings.title}refreshIcon(){for(let e of this.$widget[0].classList)e.startsWith(`bx-`)&&this.$widget.removeClass(e);let e=typeof this.settings.icon==`function`?this.settings.icon():this.settings.icon;e&&this.$widget.addClass(e)}initialRenderCompleteEvent(){this.refreshIcon()}icon(e){return this.settings.icon=e,this}title(e){return this.settings.title=e,this}titlePlacement(e){return this.settings.titlePlacement=e,this}onContextMenu(e){return this.settings.onContextMenu=e,this}},W=class extends St{constructor(){super(),this.settings={titlePlacement:`right`,title:null,icon:null,onContextMenu:null}}doRender(){super.doRender(),this.settings.onClick?this.$widget.on(`click`,e=>{this.$widget.tooltip(`hide`),this.settings.onClick&&this.settings.onClick(this,e)}):console.warn(w(`onclick_button.no_click_handler`,{componentId:this.componentId}),this.settings),this.settings.onAuxClick&&this.$widget.on(`auxclick`,e=>{this.$widget.tooltip(`hide`),this.settings.onAuxClick&&this.settings.onAuxClick(this,e)})}onClick(e){return this.settings.onClick=e,this}onAuxClick(e){return this.settings.onAuxClick=e,this}},Ct=`<div class="highlights-list-widget">
    <style>
        .highlights-list-widget {
            padding: 10px;
            contain: none;
            overflow: auto;
            position: relative;
        }

        .highlights-list > ol {
            padding-inline-start: 20px;
        }

        .highlights-list li {
            cursor: pointer;
            margin-bottom: 3px;
            text-align: justify;
            word-wrap: break-word;
            hyphens: auto;
        }

        .highlights-list li:hover {
            font-weight: bold;
        }
    </style>

    <span class="highlights-list"></span>
</div>`,wt=class extends at{$highlightsList;get widgetTitle(){return w(`highlights_list_2.title`)}get widgetButtons(){return[new W().icon(`bx-cog`).title(w(`highlights_list_2.options`)).titlePlacement(`left`).onClick(()=>b.tabManager.openContextWithNote(`_optionsTextNotes`,{activate:!0})).class(`icon-action`),new W().icon(`bx-x`).titlePlacement(`left`).onClick(e=>e.triggerCommand(`closeHlt`)).class(`icon-action`)]}isEnabled(){return super.isEnabled()&&this.note!=null&&this.note.type===`text`&&!this.noteContext?.viewScope?.highlightsListTemporarilyHidden&&this.noteContext?.viewScope?.viewMode===`default`}async doRenderBody(){this.$body.empty().append($(Ct)),this.$highlightsList=this.$body.find(`.highlights-list`)}async refreshWithNote(e){this.noteContext?.viewScope?.highlightsListPreviousVisible?this.toggleInt(!0):this.toggleInt(!1);let t=JSON.parse(T.get(`highlightsList`));if(e?.isLabelTruthy(`hideHighlightWidget`)||!t.length){this.toggleInt(!1),this.triggerCommand(`reEvaluateRightPaneVisibility`);return}let n=null,r=-1;if(e&&this.note?.type===`text`){let i=await e.getNoteComplement();i&&`content`in i&&({$highlightsList:n,hlLiCount:r}=await this.getHighlightList(i.content,t))}this.$highlightsList.empty(),n&&this.$highlightsList.append(n),r>0?(this.toggleInt(!0),this.noteContext?.viewScope&&(this.noteContext.viewScope.highlightsListPreviousVisible=!0)):(this.toggleInt(!1),this.noteContext?.viewScope&&(this.noteContext.viewScope.highlightsListPreviousVisible=!1)),this.triggerCommand(`reEvaluateRightPaneVisibility`)}async getHighlightList(e,t){let n=/<span[^>]*style\s*=\s*[^>]*background-color:[^>]*?>[\s\S]*?<\/span>/gi,r=/<span[^>]*style\s*=\s*[^>]*[^-]color:[^>]*?>[\s\S]*?<\/span>/gi,i=/(<i>[\s\S]*?<\/i>|<em>[\s\S]*?<\/em>)/gi,a=/<strong>[\s\S]*?<\/strong>/gi,o=/<u>[\s\S]*?<\/u>/g,s=``,c=``;t.includes(`bgColor`)&&(s+=`,span[style*="background-color"]:not(section.include-note span[style*="background-color"])`,c+=`|${n.source}`),t.includes(`color`)&&(s+=`,span[style*="color"]:not(section.include-note span[style*="color"])`,c+=`|${r.source}`),t.includes(`italic`)&&(s+=`,i:not(section.include-note i)`,s+=`,em:not(section.include-note em)`,c+=`|${i.source}`),t.includes(`bold`)&&(s+=`,strong:not(section.include-note strong)`,c+=`|${a.source}`),t.includes(`underline`)&&(s+=`,u:not(section.include-note u)`,c+=`|${o.source}`),s=s.substring(1),c=`(${c.substring(1)})`;let l=new RegExp(c,`gi`),u=$(`<ol>`),d=-1,f=0;for(let t=null,n=0;(t=l.exec(e))!==null;n++){let e=t[0],r=t.index,i=l.lastIndex;if(!e.startsWith(`<strong><a href="#fnref`)){if(d!==-1&&r===d)u.children().last().append(e);else if($(e).text().trim())u.append($(`<li>`).html(e).on(`click`,()=>this.jumpToHighlightsList(s,n))),f++;else continue;d=i}}return{$highlightsList:u,hlLiCount:f,findSubStr:s}}async jumpToHighlightsList(e,t){if(!this.noteContext)return;let n=await this.noteContext.isReadOnly(),r;if(n){let t=await this.noteContext.getContentElement();t&&(r=t.find(e).filter(function(){if(e.indexOf(`color`)>=0&&e.indexOf(`background-color`)<0){let e=this.style.color;return!($(this).prop(`tagName`)===`SPAN`&&e===``)}return!0}).filter(function(){let t=$(this);return t.parent(e).length===0&&t.parent().parent(e).length===0&&t.parent().parent().parent(e).length===0&&t.parent().parent().parent().parent(e).length===0}))}else{let t=(await this.noteContext.getTextEditor())?.editing.view.domRoots.values().next().value;t&&(r=$(t).find(e).filter(function(){let t=$(this);if(e.indexOf(`color`)>=0&&e.indexOf(`background-color`)<0){let e=this.style.color;return!(t.prop(`tagName`)===`SPAN`&&e===``)}return!0}).filter(function(){let t=$(this);return t.parent(e).length===0&&t.parent().parent(e).length===0&&t.parent().parent().parent(e).length===0&&t.parent().parent().parent().parent(e).length===0}))}r&&r[t]?r[t].scrollIntoView({behavior:`smooth`,block:`center`}):console.warn(`Unable to find the target element in the highlights list.`)}async closeHltCommand(){this.noteContext?.viewScope&&(this.noteContext.viewScope.highlightsListTemporarilyHidden=!0),await this.refresh(),this.triggerCommand(`reEvaluateRightPaneVisibility`),b.triggerEvent(`reEvaluateHighlightsListWidgetVisibility`,{noteId:this.noteId})}async showHighlightsListWidgetEvent({noteId:e}){this.noteId===e&&(await this.refresh(),this.triggerCommand(`reEvaluateRightPaneVisibility`),b.triggerEvent(`reEvaluateHighlightsListWidgetVisibility`,{noteId:this.noteId}))}async entitiesReloadedEvent({loadResults:e}){(this.noteId&&e.isNoteContentReloaded(this.noteId)||e.getAttributeRows().find(e=>e.type===`label`&&(e.name?.toLowerCase().includes(`readonly`)||e.name===`hideHighlightWidget`)&&O.isAffecting(e,this.note)))&&await this.refresh()}};ie(),l();function Tt(){let{note:e,noteContext:t}=A(),n=D(e,`type`),{isReadOnly:r}=ge(e,t);return E(h,{children:[n===`text`&&r&&E(jt,{}),n===`text`&&!r&&E(kt,{})]})}function Et({shown:e,setShown:t}){return E(B,{className:`highlights-list-options-modal`,size:`md`,title:w(`highlights_list_2.modal_title`),show:e,onHidden:()=>t(!1),children:E(ut,{})})}function Dt({highlights:e,scrollToHighlight:t}){let[n]=ue(`highlightsList`),r=new Set(n||[]),i=e.filter(e=>{let{attrs:t}=e;return r.has(`bold`)&&t.bold||r.has(`italic`)&&t.italic||r.has(`underline`)&&t.underline||r.has(`color`)&&!!t.color||r.has(`bgColor`)&&!!t.background}),[a,o]=p(!1);return E(h,{children:[E(H,{id:`highlights`,title:w(`highlights_list_2.title_with_count`,{count:i.length}),contextMenuItems:[{title:w(`highlights_list_2.menu_configure`),uiIcon:`bx bx-cog`,handler:()=>o(!0)}],grow:!0,children:E(`span`,{className:`highlights-list`,children:i.length>0?E(`ol`,{children:i.map(e=>E(Ot,{highlight:e,onClick:()=>t(e)},e.id))}):E(`div`,{className:`no-highlights`,children:w(`highlights_list_2.no_highlights`)})})}),ae(E(Et,{shown:a,setShown:o}),document.body)]})}function Ot({highlight:e,onClick:t}){let n=m(null);return N(n,[e.text]),E(`li`,{onClick:t,children:E(it,{containerRef:n,style:{fontWeight:e.attrs.bold?`700`:void 0,fontStyle:e.attrs.italic?`italic`:void 0,textDecoration:e.attrs.underline?`underline`:void 0,color:e.attrs.color,backgroundColor:e.attrs.background},html:e.text})})}function kt(){let{note:e,noteContext:t}=A(),n=fe(t),[r,i]=p([]);return f(()=>{if(!n)return;i(At(n));let e=()=>{n.model.document.differ.getChanges().some(e=>e.type===`insert`||e.type===`remove`||e.type===`attribute`&&(e.attributeKey===`bold`||e.attributeKey===`italic`||e.attributeKey===`underline`||e.attributeKey===`fontColor`||e.attributeKey===`fontBackgroundColor`))&&i(At(n))};return n.model.document.on(`change:data`,e),()=>n.model.document.off(`change:data`,e)},[n,e]),E(Dt,{highlights:r,scrollToHighlight:u(e=>{if(!n)return;let t=n.model.createPositionAt(e.textNode,`before`),r=n.editing.mapper.toViewPosition(t),i=n.editing.view.domConverter.viewPositionToDom(r);i&&(i.parent instanceof HTMLElement?i.parent.scrollIntoView():i.parent instanceof Text&&i.parent.parentElement?.scrollIntoView())},[n])})}function At(e){let t=[],n=e.model.document.getRoot();if(!n)return[];for(let{item:i}of e.model.createRangeIn(n).getWalker({ignoreElementEnd:!0})){if(!i.is(`$textProxy`)||!i.data.trim())continue;let n={bold:i.hasAttribute(`bold`),italic:i.hasAttribute(`italic`),underline:i.hasAttribute(`underline`),color:i.getAttribute(`fontColor`),background:i.getAttribute(`fontBackgroundColor`)};if(Object.values(n).some(Boolean)){let a=i.data;try{let t=e.model.createPositionAt(i.textNode,`before`),n=e.editing.mapper.toViewPosition(t),r=e.editing.view.domConverter.viewPositionToDom(n);r?.parent instanceof HTMLElement&&(a=r.parent.innerHTML)}catch{}t.push({id:r(),text:a,attrs:n,textNode:i.textNode,offset:i.startOffset})}}return t}function jt(){let{noteContext:e}=A();return E(Dt,{highlights:Mt(j(e)),scrollToHighlight:u(e=>{e.element.scrollIntoView()},[])})}function Mt(e){if(!e)return[];let t=[],n=new Set,i=e.querySelectorAll(`[style*="background-color"], [style*="color"]`);for(let e of i){if(n.has(e)||!e.textContent?.trim())continue;let i={bold:!!e.closest(`strong`),italic:!!e.closest(`em`),underline:!!e.closest(`u`),background:e.style.backgroundColor,color:e.style.color};Object.values(i).some(Boolean)&&(n.add(e),t.push({id:r(),text:e.innerHTML,element:e,attrs:i}))}let a=e.querySelectorAll(`strong, em, u, b, i`);for(let e of a){if(n.has(e)||Array.from(n).some(t=>t.contains(e))||!e.textContent?.trim())continue;let i={bold:e.matches(`strong, b`),italic:e.matches(`em, i`),underline:e.matches(`u`),background:e.style.backgroundColor,color:e.style.color};Object.values(i).some(Boolean)&&(n.add(e),t.push({id:r(),text:e.innerHTML,element:e,attrs:i}))}return t}var Nt={text:`bx bxs-comment-detail`,highlight:`bx bx-highlight`};function Pt(){let{note:e}=A(),t=D(e,`type`),n=D(e,`mime`),r=M(`pdfAnnotations`);return t!==`file`||n!==`application/pdf`||!r||r.annotations.length===0?null:E(H,{id:`pdf-annotations`,title:w(`pdf.annotations`,{count:r.annotations.length}),children:E(`div`,{className:`pdf-annotations-list`,children:r.annotations.map(e=>E(Ft,{annotation:e,onNavigate:r.scrollToAnnotation},e.id))})})}function Ft({annotation:e,onNavigate:t}){let n=e.contents?`bx bxs-comment-detail`:Nt[e.type]??`bx bx-comment`;return E(`div`,{className:`pdf-annotation-item`,onClick:()=>t(e.id,e.pageNumber),style:e.color?{backgroundColor:e.color}:void 0,children:[E(z,{icon:n}),E(`div`,{className:`pdf-annotation-info`,children:[e.highlightedText&&E(`div`,{className:`pdf-annotation-highlighted-text`,children:e.highlightedText}),e.contents&&E(`div`,{className:`pdf-annotation-contents`,children:e.contents}),e.author&&E(`div`,{className:`pdf-annotation-author`,children:e.author})]})]})}function It(){let{note:e}=A(),t=D(e,`type`),n=D(e,`mime`),r=M(`pdfAttachments`);return t!==`file`||n!==`application/pdf`||!r||r.attachments.length===0?null:E(H,{id:`pdf-attachments`,title:w(`pdf.attachments`,{count:r.attachments.length}),children:E(`div`,{className:`pdf-attachments-list`,children:r.attachments.map(e=>E(Lt,{attachment:e,onDownload:r.downloadAttachment},e.filename))})})}function Lt({attachment:e,onDownload:t}){let n=c(e.size);return E(`div`,{className:`pdf-attachment-item`,onClick:()=>t(e.filename),children:[E(z,{icon:`bx bx-paperclip`}),E(`div`,{className:`pdf-attachment-info`,children:[E(`div`,{className:`pdf-attachment-filename`,children:e.filename}),E(`div`,{className:`pdf-attachment-size`,children:n})]}),E(z,{icon:`bx bx-download`})]})}function Rt(){let{note:e}=A(),t=D(e,`type`),n=D(e,`mime`),r=M(`pdfLayers`);return t!==`file`||n!==`application/pdf`?null:r?.layers&&r.layers.length>0&&E(H,{id:`pdf-layers`,title:w(`pdf.layers`,{count:r.layers.length}),children:E(`div`,{className:`pdf-layers-list`,children:r.layers.map(e=>E(zt,{layer:e,onToggle:r.toggleLayer},e.id))})})}function zt({layer:e,onToggle:t}){return E(`div`,{className:`pdf-layer-item ${e.visible?`visible`:`hidden`}`,onClick:()=>t(e.id,!e.visible),children:[E(z,{icon:e.visible?`bx bx-show`:`bx bx-hide`}),E(`div`,{className:`pdf-layer-name`,children:e.name})]})}l();var Bt=180,G=2;function Vt(){let{note:e}=A(),t=D(e,`type`),n=D(e,`mime`),r=M(`pdfPages`);return t!==`file`||n!==`application/pdf`?null:r&&E(H,{id:`pdf-pages`,title:w(`pdf.pages`,{count:r?.totalPages||0}),grow:!0,children:E(Ht,{pagesData:r},e?.noteId)})}function Ht({pagesData:e}){let[t,n]=p(new Map),r=m(new Set),i=m(null),[a,o]=p(0);f(()=>{function e(e){let{pageNumber:t,dataUrl:r}=e.detail;n(e=>new Map(e).set(t,r))}return window.addEventListener(`pdf-thumbnail`,e),()=>{window.removeEventListener(`pdf-thumbnail`,e)}},[]),f(()=>{let e=i.current;if(!e)return;let t=new ResizeObserver(([e])=>{o(e.contentRect.height)});return t.observe(e),()=>t.disconnect()},[]);let s=u(n=>{!r.current.has(n)&&!t.has(n)&&e&&(r.current.add(n),e.requestThumbnail(n))},[e,t]);return!e||e.totalPages===0?E(`div`,{className:`no-pages`,children:`No pages available`}):E(`div`,{ref:i,className:`pdf-pages-list`,children:a>0&&E(Le,{rowComponent:Ut,rowCount:Math.ceil(e.totalPages/G),rowHeight:Bt,rowProps:{totalPages:e.totalPages,thumbnails:t,currentPage:e.currentPage,requestThumbnail:s,scrollToPage:e.scrollToPage},style:{height:a}})})}function Ut({index:e,style:t,...n}){let{totalPages:r,thumbnails:i,currentPage:a,requestThumbnail:o,scrollToPage:s}=n,c=e*G+1;return E(`div`,{style:t,className:`pdf-page-row`,children:Array.from({length:G},(e,t)=>c+t).filter(e=>e<=r).map(e=>E(Wt,{pageNumber:e,isActive:e===a,thumbnail:i.get(e),requestThumbnail:o,scrollToPage:s},e))})}function Wt({pageNumber:e,isActive:t,thumbnail:n,requestThumbnail:r,scrollToPage:i}){let a=m(!1);return f(()=>{!n&&!a.current&&(a.current=!0,r(e))},[e,n,r]),E(`div`,{className:`pdf-page-item ${t?`active`:``}`,onClick:()=>i(e),children:[E(`div`,{className:`pdf-page-thumbnail`,children:n?E(`img`,{src:n,alt:w(`pdf.pages_alt`,{pageNumber:e})}):E(`div`,{className:`pdf-page-loading`,children:w(`pdf.pages_loading`)})}),E(`div`,{className:`pdf-page-number`,children:e})]})}l();function Gt(){let[e,t]=p(null),[n,r]=p([]),i=m(null),{noteId:a,note:o}=A(),s=D(me(e),`title`)||w(`sidebar_chat.title`),c=m(e);c.current=e;let l=ft(()=>g.scheduleUpdate(),{defaultEnableNoteTools:!0,supportsExtendedThinking:!0}),d=m(l);d.current=l;let g=de(async()=>{let e=c.current;if(!e)return;let t=d.current.getContent();try{await C.put(`notes/${e}/data`,{content:JSON.stringify(t)})}catch(e){console.error(`Failed to save chat:`,e)}});f(()=>{l.setContextNoteId(a??void 0)},[a,l.setContextNoteId]),f(()=>{l.setChatNoteId(e??void 0)},[e,l.setChatNoteId]),f(()=>{let e=!1;return(async()=>{try{let n=await x.getMostRecentLlmChat();if(e)return;if(n){t(n.noteId);try{let t=await C.get(`notes/${n.noteId}/blob`);if(!e&&t?.content){let e=JSON.parse(t.content);d.current.loadFromContent(e)}}catch(e){console.error(`Failed to load chat content:`,e)}}else t(null),d.current.clearMessages()}catch(e){console.error(`Failed to load sidebar chat:`,e)}})(),()=>{e=!0}},[]);let _=u(async n=>{if(n.preventDefault(),!l.input.trim()||l.isStreaming)return;let r=e;if(!r)try{let e=await x.getOrCreateLlmChat();e&&(t(e.noteId),r=e.noteId)}catch(e){console.error(`Failed to create sidebar chat:`,e);return}if(!r){console.error(`Cannot send message: no chat note available`);return}l.setChatNoteId(r),await l.handleSubmit(n)},[e,l]),v=u(e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),_(e))},[_]),y=u(async()=>{await g.updateNowIfNecessary();try{let e=await x.createLlmChat();e&&(t(e.noteId),d.current.clearMessages())}catch(e){console.error(`Failed to create new chat:`,e)}},[g]),b=u(async()=>{if(e){await g.updateNowIfNecessary();try{await C.post(`special-notes/save-llm-chat`,{llmChatNoteId:e});let n=await x.createLlmChat();n&&(t(n.noteId),d.current.clearMessages())}catch(e){console.error(`Failed to save chat to permanent location:`,e)}}},[e,g]),S=u(async()=>{try{r(await x.getRecentLlmChats(10))}catch(e){console.error(`Failed to load recent chats:`,e)}},[]),ee=u(async n=>{if(i.current?.hide(),n!==e){await g.updateNowIfNecessary();try{let e=await C.get(`notes/${n}/blob`);if(e?.content){let r=JSON.parse(e.content);t(n),d.current.loadFromContent(r)}}catch(e){console.error(`Failed to load selected chat:`,e)}}},[e,g]);return E(H,{id:`sidebar-chat`,title:s,grow:!0,buttons:E(h,{children:[E(F,{icon:`bx bx-plus`,text:w(`sidebar_chat.new_chat`),onClick:y}),E(Xe,{text:``,buttonClassName:`bx bx-history`,title:w(`sidebar_chat.history`),iconAction:!0,hideToggleArrow:!0,dropdownContainerClassName:`tn-dropdown-menu-scrollable`,dropdownOptions:{popperConfig:{strategy:`fixed`}},dropdownRef:i,onShown:S,children:n.length===0?E(Ze,{disabled:!0,children:w(`sidebar_chat.no_chats`)}):n.map(t=>E(Ze,{icon:`bx bx-message-square-dots`,className:t.noteId===e?`active`:``,onClick:()=>ee(t.noteId),children:E(`div`,{className:`sidebar-chat-history-item-content`,children:[t.noteId===e?E(`strong`,{children:t.title}):E(`span`,{children:t.title}),E(`span`,{className:`sidebar-chat-history-date`,children:ot(new Date(t.dateModified),`short`,`short`)})]})},t.noteId))}),E(F,{icon:`bx bx-save`,text:w(`sidebar_chat.save_chat`),onClick:b,disabled:l.messages.length===0})]}),children:E(`div`,{className:`sidebar-chat-container`,children:[E(`div`,{className:`sidebar-chat-messages`,ref:l.scrollContainerRef,children:[l.messages.length===0&&!l.isStreaming&&E(lt,{icon:`bx bx-conversation`,text:w(`sidebar_chat.empty_state`)}),l.messages.map(e=>E(U,{message:e},e.id)),l.isStreaming&&l.streamingThinking&&E(U,{message:{id:`streaming-thinking`,role:`assistant`,content:l.streamingThinking,createdAt:new Date().toISOString(),type:`thinking`},isStreaming:!0}),l.isStreaming&&l.streamingBlocks.length>0&&E(U,{message:{id:`streaming`,role:`assistant`,content:l.streamingBlocks,createdAt:new Date().toISOString(),citations:l.pendingCitations.length>0?l.pendingCitations:void 0},isStreaming:!0}),E(`div`,{ref:l.messagesEndRef})]}),E(dt,{chat:l,rows:2,activeNoteId:a??void 0,activeNoteTitle:o?.title,onSubmit:_,onKeyDown:v})]})})}l();function Kt(){let{note:e,noteContext:t}=A(),n=D(e,`type`),r=D(e,`mime`),{isReadOnly:i}=ge(e,t);return E(H,{id:`toc`,title:w(`toc.table_of_contents`),grow:!0,children:[(n===`text`&&i||n===`doc`)&&E($t,{}),n===`text`&&!i&&E(Zt,{}),n===`file`&&r===`application/pdf`&&E(qt,{}),e?.isMarkdown()&&E(qt,{})]})}function qt(){let e=M(`toc`);return E(K,{headings:e?.headings||[],scrollToHeading:e?.scrollToHeading||(()=>{}),activeHeadingId:e?.activeHeadingId})}function K({headings:e,scrollToHeading:t,activeHeadingId:n}){let r=Yt(e);return E(`span`,{className:`toc`,children:r.length>0?E(`ol`,{children:r.map(e=>E(Jt,{heading:e,scrollToHeading:t,activeHeadingId:n},e.id))}):E(`div`,{className:`no-headings`,children:w(`toc.no_headings`)})})}function Jt({heading:e,scrollToHeading:t,activeHeadingId:n}){let[r,i]=p(!1),a=e.id===n,o=m(null);return N(o,[e.text]),E(h,{children:[E(`li`,{className:_(r&&`collapsed`,a&&`active`),children:[e.children.length>0&&E(z,{className:`collapse-button`,icon:`bx bx-chevron-down`,onClick:()=>i(!r)}),E(it,{containerRef:o,className:`item-content`,onClick:()=>t(e),html:e.text})]}),e.children.length>0&&E(`ol`,{children:e.children.map(e=>E(Jt,{heading:e,scrollToHeading:t,activeHeadingId:n},e.id))})]})}function Yt(e){let t={level:0,text:``,children:[],id:`_root`},n=[t];for(let t of e){let e={...t,children:[]};for(;n.length>1&&n[n.length-1].level>=t.level;)n.pop();n[n.length-1].children.push(e),n.push(e)}return t.children}var Xt=`tocId`;function Zt(){let{note:e,noteContext:t}=A(),n=fe(t),[r,i]=p([]);return f(()=>{if(!n)return;i(Qt(n));let e=()=>{n.model.document.differ.getChanges().some(e=>e.type===`insert`||e.type===`remove`||e.type===`attribute`&&ct(e,n))&&requestAnimationFrame(()=>{i(Qt(n))})};return n.model.document.on(`change:data`,e),()=>n.model.document.off(`change:data`,e)},[n,e]),E(K,{headings:r,scrollToHeading:u(e=>{if(!n)return;let t=n.editing.mapper.toViewElement(e.element);t&&n.editing.view.domConverter.mapViewToDom(t)?.scrollIntoView()},[n])})}function Qt(e){let t=[],n=e.model.document.getRoot();return n?(e.model.change(i=>{for(let{type:a,item:o}of e.model.createRangeIn(n).getWalker()){if(a!==`elementStart`||!o.is(`element`)||!o.name.startsWith(`heading`))continue;let n=Number(o.name.replace(`heading`,``)),s=e.editing.mapper.toViewElement(o),c=``;if(s){let t=e.editing.view.domConverter.mapViewToDom(s);if(t instanceof HTMLElement){let e=t.cloneNode(!0),n=e.querySelectorAll(`.ck-math-tex`),r=0;for(let e of o.getChildren()){if(!e.is(`element`,`mathtex-inline`))continue;if(r>=n.length)break;let t=String(e.getAttribute(`equation`)??``),i=document.createElement(`span`);i.className=`math-tex`,i.textContent=`\\(${t}\\)`,n[r].replaceWith(i),r++}c=e.innerHTML}}c||=Array.from(o.getChildren()).map(e=>e.is(`$text`)?e.data:``).join(``);let l=o.getAttribute(Xt);l||(l=r(),i.setAttribute(Xt,l,o)),t.push({level:n,text:c,element:o,id:l})}}),t):[]}function $t(){let{noteContext:e}=A();return E(K,{headings:en(j(e)),scrollToHeading:u(e=>{e.element.scrollIntoView()},[])})}function en(e){if(!e)return[];let t=[];for(let n of e.querySelectorAll(`h1,h2,h3,h4,h5,h6`))t.push({id:r(),level:parseInt(n.tagName.substring(1),10),text:n.innerHTML,element:n});return t}l();var tn=5;function nn({widgetsByParent:e}){let[t,n]=p(T.is(`rightPaneVisible`)),r=rn(t,e);return an(t),k(`toggleRightPane`,u(()=>{n(e=>{let t=!e;return T.save(`rightPaneVisible`,t.toString()),t})},[])),E(`div`,{id:`right-pane`,children:t&&(r.length>0?r:E(lt,{icon:`bx bx-sidebar`,text:w(`right_pane.empty_message`),children:E(V,{text:w(`right_pane.empty_button`),triggerCommand:`toggleRightPane`})}))})}function rn(e,t){let{note:n}=A(),r=D(n,`type`),i=D(n,`mime`),[a]=ue(`highlightsList`),o=r===`file`&&i===`application/pdf`;if(!e)return[];let s=[{el:E(Kt,{}),enabled:r===`text`||r===`doc`||o||!!n?.isMarkdown()},{el:E(Vt,{}),enabled:o},{el:E(It,{}),enabled:o},{el:E(Rt,{}),enabled:o},{el:E(Pt,{}),enabled:o},{el:E(Tt,{}),enabled:r===`text`&&a.length>0},{el:E(Gt,{}),enabled:r!==`llmChat`&&P(`llm`),position:1e3},...t.getLegacyWidgets(`right-pane`).map(e=>({el:E(on,{originalWidget:e},e._noteId),enabled:!0,position:e.position})),...t.getPreactWidgets(`right-pane`).map(e=>{let t=e.render;return{el:E(t,{}),enabled:!0,position:e.position}})],c=10;for(let e of s)e.position||(e.position=c,c+=10);return s.filter(e=>e.enabled).toSorted((e,t)=>(e.position??10)-(t.position??10)).map(e=>e.el)}function an(e){f(()=>{if(!e)return;let t=Math.max(tn,T.getInt(`rightPaneWidth`)??tn),n=Qe([`#center-pane`,`#right-pane`],{sizes:[100-t,t],gutterSize:5,minSize:[300,180],rtl:glob.isRtl,onDragEnd:e=>T.save(`rightPaneWidth`,Math.round(e[1]))});return()=>n.destroy()},[e])}function on({originalWidget:e}){let t=m(null);return E(H,{id:e._noteId,title:e.widgetTitle,containerRef:t,contextMenuItems:[{title:w(`right_pane.custom_widget_go_to_source`),uiIcon:`bx bx-code-curly`,handler:()=>b.tabManager.openInNewTab(e._noteId,null,!0)}],children:E(sn,{originalWidget:e})})}function sn({originalWidget:e}){let{noteContext:t}=A(),[n]=_e(()=>(e.contentSized(),e.doRender=function(){this.$widget=$(`<div>`),this.$body=this.$widget;let e=this.doRenderBody();typeof e==`object`&&`catch`in e?this.initialized=e.catch(e=>{this.logRenderingError(e)}):this.initialized=Promise.resolve()},e),{noteContext:t});return n}var cn=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.getSize=n()})(window,function(){function e(e){let t=parseFloat(e);return e.indexOf(`%`)==-1&&!isNaN(t)&&t}let t=[`paddingLeft`,`paddingRight`,`paddingTop`,`paddingBottom`,`marginLeft`,`marginRight`,`marginTop`,`marginBottom`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`borderBottomWidth`];t.length;function n(){let e={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0};return t.forEach(t=>{e[t]=0}),e}function r(r){if(typeof r==`string`&&(r=document.querySelector(r)),!(r&&typeof r==`object`&&r.nodeType))return;let i=getComputedStyle(r);if(i.display==`none`)return n();let a={};a.width=r.offsetWidth,a.height=r.offsetHeight;let o=a.isBorderBox=i.boxSizing==`border-box`;t.forEach(e=>{let t=i[e],n=parseFloat(t);a[e]=isNaN(n)?0:n});let s=a.paddingLeft+a.paddingRight,c=a.paddingTop+a.paddingBottom,l=a.marginLeft+a.marginRight,u=a.marginTop+a.marginBottom,d=a.borderLeftWidth+a.borderRightWidth,f=a.borderTopWidth+a.borderBottomWidth,p=e(i.width);p!==!1&&(a.width=p+(o?0:s+d));let m=e(i.height);return m!==!1&&(a.height=m+(o?0:c+f)),a.innerWidth=a.width-(s+d),a.innerHeight=a.height-(c+f),a.outerWidth=a.width+l,a.outerHeight=a.height+u,a}return r})})),ln=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.EvEmitter=n()})(typeof window<`u`?window:e,function(){function e(){}let t=e.prototype;return t.on=function(e,t){if(!e||!t)return this;let n=this._events=this._events||{},r=n[e]=n[e]||[];return r.includes(t)||r.push(t),this},t.once=function(e,t){if(!e||!t)return this;this.on(e,t);let n=this._onceEvents=this._onceEvents||{},r=n[e]=n[e]||{};return r[t]=!0,this},t.off=function(e,t){let n=this._events&&this._events[e];if(!n||!n.length)return this;let r=n.indexOf(t);return r!=-1&&n.splice(r,1),this},t.emitEvent=function(e,t){let n=this._events&&this._events[e];if(!n||!n.length)return this;n=n.slice(0),t||=[];let r=this._onceEvents&&this._onceEvents[e];for(let i of n)r&&r[i]&&(this.off(e,i),delete r[i]),i.apply(this,t);return this},t.allOff=function(){return delete this._events,delete this._onceEvents,this},e})})),un=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(e,ln()):e.Unidragger=n(e,e.EvEmitter)})(typeof window<`u`?window:e,function(e,t){function n(){}let r=n.prototype=Object.create(t.prototype);r.handleEvent=function(e){let t=`on`+e.type;this[t]&&this[t](e)};let i,a;`ontouchstart`in e?(i=`touchstart`,a=[`touchmove`,`touchend`,`touchcancel`]):e.PointerEvent?(i=`pointerdown`,a=[`pointermove`,`pointerup`,`pointercancel`]):(i=`mousedown`,a=[`mousemove`,`mouseup`]),r.touchActionValue=`none`,r.bindHandles=function(){this._bindHandles(`addEventListener`,this.touchActionValue)},r.unbindHandles=function(){this._bindHandles(`removeEventListener`,``)},r._bindHandles=function(t,n){this.handles.forEach(r=>{r[t](i,this),r[t](`click`,this),e.PointerEvent&&(r.style.touchAction=n)})},r.bindActivePointerEvents=function(){a.forEach(t=>{e.addEventListener(t,this)})},r.unbindActivePointerEvents=function(){a.forEach(t=>{e.removeEventListener(t,this)})},r.withPointer=function(e,t){t.pointerId===this.pointerIdentifier&&this[e](t,t)},r.withTouch=function(e,t){let n;for(let e of t.changedTouches)e.identifier===this.pointerIdentifier&&(n=e);n&&this[e](t,n)},r.onmousedown=function(e){this.pointerDown(e,e)},r.ontouchstart=function(e){this.pointerDown(e,e.changedTouches[0])},r.onpointerdown=function(e){this.pointerDown(e,e)};let o=[`TEXTAREA`,`INPUT`,`SELECT`,`OPTION`],s=[`radio`,`checkbox`,`button`,`submit`,`image`,`file`];return r.pointerDown=function(e,t){let n=o.includes(e.target.nodeName),r=s.includes(e.target.type),i=!n||r;!this.isPointerDown&&!e.button&&i&&(this.isPointerDown=!0,this.pointerIdentifier=t.pointerId===void 0?t.identifier:t.pointerId,this.pointerDownPointer={pageX:t.pageX,pageY:t.pageY},this.bindActivePointerEvents(),this.emitEvent(`pointerDown`,[e,t]))},r.onmousemove=function(e){this.pointerMove(e,e)},r.onpointermove=function(e){this.withPointer(`pointerMove`,e)},r.ontouchmove=function(e){this.withTouch(`pointerMove`,e)},r.pointerMove=function(e,t){let n={x:t.pageX-this.pointerDownPointer.pageX,y:t.pageY-this.pointerDownPointer.pageY};this.emitEvent(`pointerMove`,[e,t,n]),!this.isDragging&&this.hasDragStarted(n)&&this.dragStart(e,t),this.isDragging&&this.dragMove(e,t,n)},r.hasDragStarted=function(e){return Math.abs(e.x)>3||Math.abs(e.y)>3},r.dragStart=function(e,t){this.isDragging=!0,this.isPreventingClicks=!0,this.emitEvent(`dragStart`,[e,t])},r.dragMove=function(e,t,n){this.emitEvent(`dragMove`,[e,t,n])},r.onmouseup=function(e){this.pointerUp(e,e)},r.onpointerup=function(e){this.withPointer(`pointerUp`,e)},r.ontouchend=function(e){this.withTouch(`pointerUp`,e)},r.pointerUp=function(e,t){this.pointerDone(),this.emitEvent(`pointerUp`,[e,t]),this.isDragging?this.dragEnd(e,t):this.staticClick(e,t)},r.dragEnd=function(e,t){this.isDragging=!1,setTimeout(()=>delete this.isPreventingClicks),this.emitEvent(`dragEnd`,[e,t])},r.pointerDone=function(){this.isPointerDown=!1,delete this.pointerIdentifier,this.unbindActivePointerEvents(),this.emitEvent(`pointerDone`)},r.onpointercancel=function(e){this.withPointer(`pointerCancel`,e)},r.ontouchcancel=function(e){this.withTouch(`pointerCancel`,e)},r.pointerCancel=function(e,t){this.pointerDone(),this.emitEvent(`pointerCancel`,[e,t])},r.onclick=function(e){this.isPreventingClicks&&e.preventDefault()},r.staticClick=function(e,t){let n=e.type===`mouseup`;n&&this.isIgnoringMouseUp||(this.emitEvent(`staticClick`,[e,t]),n&&(this.isIgnoringMouseUp=!0,setTimeout(()=>{delete this.isIgnoringMouseUp},400)))},n})})),dn=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(e,cn(),un()):e.Draggabilly=n(e,e.getSize,e.Unidragger)})(typeof window<`u`?window:e,function(e,t,n){function r(){}let i=e.jQuery;function a(e,t){this.element=typeof e==`string`?document.querySelector(e):e,i&&(this.$element=i(this.element)),this.options={},this.option(t),this._create()}let o=a.prototype=Object.create(n.prototype);o.option=function(e){this.options={...this.options,...e}};let s=[`relative`,`absolute`,`fixed`];o._create=function(){this.position={},this._getPosition(),this.startPoint={x:0,y:0},this.dragPoint={x:0,y:0},this.startPosition={...this.position};let e=getComputedStyle(this.element);s.includes(e.position)||(this.element.style.position=`relative`),this.on(`pointerDown`,this.handlePointerDown),this.on(`pointerUp`,this.handlePointerUp),this.on(`dragStart`,this.handleDragStart),this.on(`dragMove`,this.handleDragMove),this.on(`dragEnd`,this.handleDragEnd),this.setHandles(),this.enable()},o.setHandles=function(){let{handle:e}=this.options;typeof e==`string`?this.handles=this.element.querySelectorAll(e):typeof e==`object`&&e.length?this.handles=e:e instanceof HTMLElement?this.handles=[e]:this.handles=[this.element]};let c=[`dragStart`,`dragMove`,`dragEnd`],l=o.emitEvent;o.emitEvent=function(t,n){if(!this.isEnabled&&c.includes(t))return;l.call(this,t,n);let r=e.jQuery;if(!r||!this.$element)return;let i,a=n;n&&n[0]instanceof Event&&([i,...a]=n);let o=r.Event(i);o.type=t,this.$element.trigger(o,a)},o._getPosition=function(){let e=getComputedStyle(this.element),t=this._getPositionCoord(e.left,`width`),n=this._getPositionCoord(e.top,`height`);this.position.x=isNaN(t)?0:t,this.position.y=isNaN(n)?0:n,this._addTransformPosition(e)},o._getPositionCoord=function(e,n){if(e.includes(`%`)){let r=t(this.element.parentNode);return r?parseFloat(e)/100*r[n]:0}return parseInt(e,10)},o._addTransformPosition=function(e){let t=e.transform;if(!t.startsWith(`matrix`))return;let n=t.split(`,`),r=t.startsWith(`matrix3d`)?12:4,i=parseInt(n[r],10),a=parseInt(n[r+1],10);this.position.x+=i,this.position.y+=a},o.handlePointerDown=function(e,t){this.isEnabled&&(this.pointerDownPointer={pageX:t.pageX,pageY:t.pageY},e.preventDefault(),document.activeElement.blur(),this.bindActivePointerEvents(e),this.element.classList.add(`is-pointer-down`))},o.handleDragStart=function(){this.isEnabled&&(this._getPosition(),this.measureContainment(),this.startPosition.x=this.position.x,this.startPosition.y=this.position.y,this.setLeftTop(),this.dragPoint.x=0,this.dragPoint.y=0,this.element.classList.add(`is-dragging`),this.animate())},o.measureContainment=function(){let e=this.getContainer();if(!e)return;let n=t(this.element),r=t(e),{borderLeftWidth:i,borderRightWidth:a,borderTopWidth:o,borderBottomWidth:s}=r,c=this.element.getBoundingClientRect(),l=e.getBoundingClientRect(),u=i+a,d=o+s,f=this.relativeStartPosition={x:c.left-(l.left+i),y:c.top-(l.top+o)};this.containSize={width:r.width-u-f.x-n.width,height:r.height-d-f.y-n.height}},o.getContainer=function(){let e=this.options.containment;if(e)return e instanceof HTMLElement?e:typeof e==`string`?document.querySelector(e):this.element.parentNode},o.handleDragMove=function(e,t,n){if(!this.isEnabled)return;let r=n.x,i=n.y,a=this.options.grid,o=a&&a[0],s=a&&a[1];r=u(r,o),i=u(i,s),r=this.containDrag(`x`,r,o),i=this.containDrag(`y`,i,s),r=this.options.axis==`y`?0:r,i=this.options.axis==`x`?0:i,this.position.x=this.startPosition.x+r,this.position.y=this.startPosition.y+i,this.dragPoint.x=r,this.dragPoint.y=i};function u(e,t,n){return t?(n||=`round`,Math[n](e/t)*t):e}o.containDrag=function(e,t,n){if(!this.options.containment)return t;let r=e==`x`?`width`:`height`,i=this.relativeStartPosition[e],a=u(-i,n,`ceil`),o=this.containSize[r];return o=u(o,n,`floor`),Math.max(a,Math.min(o,t))},o.handlePointerUp=function(){this.element.classList.remove(`is-pointer-down`)},o.handleDragEnd=function(){this.isEnabled&&(this.element.style.transform=``,this.setLeftTop(),this.element.classList.remove(`is-dragging`))},o.animate=function(){this.isDragging&&(this.positionDrag(),requestAnimationFrame(()=>this.animate()))},o.setLeftTop=function(){let{x:e,y:t}=this.position;this.element.style.left=`${e}px`,this.element.style.top=`${t}px`},o.positionDrag=function(){let{x:e,y:t}=this.dragPoint;this.element.style.transform=`translate3d(${e}px, ${t}px, 0)`},o.setPosition=function(e,t){this.position.x=e,this.position.y=t,this.setLeftTop()},o.enable=function(){this.isEnabled||(this.isEnabled=!0,this.bindHandles())},o.disable=function(){this.isEnabled&&(this.isEnabled=!1,this.isDragging&&this.dragEnd(),this.unbindHandles())};let d=[`transform`,`left`,`top`,`position`];return o.destroy=function(){this.disable(),d.forEach(e=>{this.element.style[e]=``}),this.unbindHandles(),this.$element&&this.$element.removeData(`draggabilly`)},o._init=r,i&&i.bridget&&i.bridget(`draggabilly`,a),a})}))()),fn=s.isDesktop(),pn=100,q=240,mn=5,hn=36,gn=36,_n=fn?50:15,J=5,vn=84,yn=60,bn=48,xn=`
<div class="note-tab">
  <div class="note-tab-wrapper">
    <div class="note-tab-drag-handle"></div>
    <div class="note-tab-icon"></div>
    <div class="note-tab-title"></div>
    <div class="note-tab-close bx bx-x" title="${w(`tab_row.close_tab`)}"></div>
  </div>
</div>`,Sn=`<div class="tab-row-container-anchor"></div>`,Cn=`<div class="note-new-tab" data-trigger-command="openNewTab" title="${w(`tab_row.add_new_tab`)}">+</div>`,wn=`<div class="tab-row-filler"></div>`,Tn=`
<div class="tab-row-widget">
    <style>
    .tab-row-widget {
        display:flex;
        box-sizing: border-box;
        position: relative;
        width: 100%;
        background: var(--main-background-color);
        user-select: none;
    }

    .tab-row-widget.full-width {
        background: var(--launcher-pane-background-color);
    }

    .tab-row-widget * {
        box-sizing: inherit;
        font: inherit;
    }

    .tab-row-widget .tab-row-widget-container {
        box-sizing: border-box;
        position: relative;
        height: 100%;
    }

    .tab-row-widget .note-tab {
        position: absolute;
        left: 0;
        width: 240px;
        border: 0;
        margin: 0;
        z-index: 1;
        pointer-events: none;
    }

    .note-new-tab {
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 0 0 ${gn}px;
        height: ${gn}px;
        padding: 1px;
        font-size: 24px;
        cursor: pointer;
        box-sizing: border-box;
    }

    .note-new-tab:hover {
        background-color: var(--accented-background-color);
        border-radius: var(--button-border-radius);
    }

    .tab-row-filler {
        box-sizing: border-box;
        -webkit-app-region: drag;
        min-width: ${_n}px;
        flex-grow: 1;
    }

    .tab-row-container-anchor{
        position: absolute;
        left: 0;
        width: 0px;
        height: 36px;
        border: 0;
        margin: 0;
        z-index: 1;
        cursor: pointer;
        box-sizing: border-box;
    }
    body.mobile .tab-row-filler {
        display: none;
    }

    .tab-row-widget .note-tab[active] {
        z-index: 5;
    }

    .tab-row-widget .note-tab,
    .tab-row-widget .note-tab * {
        cursor: default;
    }

    .tab-row-widget .note-tab.note-tab-was-just-added {
        top: 10px;
        animation: note-tab-was-just-added 120ms forwards ease-in-out;
    }

    .tab-row-widget .note-tab .note-tab-wrapper {
        position: absolute;
        display: flex;
        align-items: center;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        height: 36px;
        padding: 7px 5px 7px 11px;
        border-radius: 8px;
        overflow: hidden;
        pointer-events: all;
        color: var(--inactive-tab-text-color);
        --tab-background-color: var(--workspace-tab-background-color);
        background-color: var(--tab-background-color, var(--inactive-tab-background-color));
    }

    .tab-row-widget .note-tab[active] .note-tab-wrapper {
        font-weight: bold;
        color: var(--active-tab-text-color);
        background-color : var(--tab-background-color, var(--active-tab-background-color));
    }

    .tab-row-widget .note-tab[is-mini] .note-tab-wrapper {
        padding-inline-start: 2px;
        padding-inline-end: 2px;
    }

    .tab-row-widget .note-tab .note-tab-title {
        flex: 1;
        vertical-align: top;
        overflow: hidden;
        white-space: nowrap;
    }

    .tab-row-widget .note-tab .note-tab-icon {
        position: relative;
        padding-inline-end: 3px;
    }

    .tab-row-widget .note-tab[is-small] .note-tab-title {
        margin-inline-start: 0;
    }

    .tab-row-widget .note-tab .note-tab-drag-handle {
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 50;
    }

    .tab-row-widget .note-tab .note-tab-close {
        flex: 0 0 22px;
        border-radius: 50%;
        z-index: 100;
        width: 22px;
        height: 22px;
        cursor: pointer;
        text-align: center;
    }

    .tab-scroll-button-left, .tab-scroll-button-right {
        display: none;
        flex: 0 0 ${hn}px;
        height: ${hn}px;
        padding: 1px 1px 1px 1px;
        align-items: center;
        justify-content: center;
        cursor: pointer;
    }

    .tab-scroll-button-left {
        color: var(--active-tab-text-color);
        box-shadow: inset -1px 0 0 0 var(--main-border-color);
    }

    .tab-scroll-button-right {
        color: var(--active-tab-text-color);
        box-shadow: inset 1px 0 0 0 var(--main-border-color);
    }

    .tab-scroll-button-left.disabled,
    .tab-scroll-button-right.disabled {
        color: var(--inactive-tab-text-color);
        box-shadow: none;
        pointer-events: none;
    }

    .tab-scroll-button-left:hover,
    .tab-scroll-button-right:hover {
        background-color: var(--tab-background-color, var(--inactive-tab-hover-background-color));
    }

    .tab-row-widget .note-tab:hover .note-tab-wrapper {
        background-color: var(--tab-background-color, var(--inactive-tab-hover-background-color));
    }

    .tab-row-widget .note-tab[active]:hover .note-tab-wrapper {
        background-color: var(--tab-background-color, var(--active-tab-hover-background-color));
    }

    body.desktop .tab-row-widget .note-tab .note-tab-close:hover {
        background-color: var(--hover-item-background-color);
        color: var(--hover-item-text-color);
    }

    .tab-row-widget .note-tab[is-smaller] .note-tab-close {
        margin-inline-start: auto;
    }
    .tab-row-widget .note-tab[is-mini]:not([active]) .note-tab-close {
        display: none;
    }
    .tab-row-widget .note-tab[is-mini][active] .note-tab-close {
        margin-inline-start: auto;
        margin-inline-end: auto;
    }
    @-moz-keyframes note-tab-was-just-added {
        to {
            top: 0;
        }
    }
    @-webkit-keyframes note-tab-was-just-added {
        to {
            top: 0;
        }
    }
    @-o-keyframes note-tab-was-just-added {
        to {
            top: 0;
        }
    }
    @keyframes note-tab-was-just-added {
        to {
            top: 0;
        }
    }
    .tab-row-widget.tab-row-widget-is-sorting .note-tab:not(.note-tab-is-dragging),
    .tab-row-widget:not(.tab-row-widget-is-sorting) .note-tab.note-tab-was-just-dragged {
        transition: transform 120ms ease-in-out;
    }
    .tab-row-widget-wrapper {
        display: flex;
        box-sizing: border-box;
        width: 100%;
        height: 100%;
    }

    .tab-row-widget-scrolling-container {
        overflow-x: auto;
        overflow-y: hidden;
        scrollbar-width: none; /* Firefox */
    }

    /* Chrome/Safari */
    .tab-row-widget-scrolling-container::-webkit-scrollbar {
        display: none;
    }

    </style>
    <div class="tab-scroll-button-left bx bx-chevron-left"></div>
    <div class="tab-row-widget-scrolling-container">
        <div class="tab-row-widget-container"></div>
    </div>
    <div class="tab-scroll-button-right bx bx-chevron-right"></div>
</div>`,En=class extends S{isDragging;showNoteIcons;draggabillies;draggabillyDragging;$style;$tabScrollingContainer;$tabContainer;$scrollButtonLeft;$scrollButtonRight;$containerAnchor;$filler;$newTab;updateScrollTimeout;newTabOuterWidth=0;scrollButtonsOuterWidth=0;doRender(){this.$widget=$(Tn),this.$tabScrollingContainer=this.$widget.children(`.tab-row-widget-scrolling-container`),this.$tabContainer=this.$widget.find(`.tab-row-widget-container`),this.$scrollButtonLeft=this.$widget.children(`.tab-scroll-button-left`),this.$scrollButtonRight=this.$widget.children(`.tab-scroll-button-right`);let e=window.getComputedStyle(document.documentElement);this.showNoteIcons=e.getPropertyValue(`--tab-note-icons`)===`true`,this.draggabillies=[],this.setupStyle(),this.setupEvents(),this.setupContainerAnchor(),this.setupDraggabilly(),this.setupNewButton(),this.setupFiller(),this.layoutTabs(),this.setVisibility(),this.setupScrollEvents(),this.$widget.on(`contextmenu`,`.note-tab`,e=>{e.preventDefault();let t=$(e.target).closest(`.note-tab`).attr(`data-ntx-id`);ee.show({x:e.pageX,y:e.pageY,items:[{title:w(`tab_row.close`),command:`closeTab`,uiIcon:`bx bx-x`},{title:w(`tab_row.close_other_tabs`),command:`closeOtherTabs`,uiIcon:`bx bx-empty`,enabled:b.tabManager.noteContexts.length!==1},{title:w(`tab_row.close_right_tabs`),command:`closeRightTabs`,uiIcon:`bx bx-empty`,enabled:b.tabManager.noteContexts?.at(-1)?.ntxId!==t},{title:w(`tab_row.close_all_tabs`),command:`closeAllTabs`,uiIcon:`bx bx-empty`},{kind:`separator`},{title:w(`tab_row.reopen_last_tab`),command:`reopenLastTab`,uiIcon:`bx bx-undo`,enabled:b.tabManager.recentlyClosedTabs.length!==0},{kind:`separator`},{title:w(`tab_row.move_tab_to_new_window`),command:`moveTabToNewWindow`,uiIcon:`bx bx-window-open`},{title:w(`tab_row.copy_tab_to_new_window`),command:`copyTabToNewWindow`,uiIcon:`bx bx-empty`}],selectMenuItemHandler:({command:e})=>{e&&this.triggerCommand(e,{ntxId:t})}})})}setupStyle(){this.$style=$(`<style>`),this.$widget.append(this.$style)}scrollTabContainer(e,t=`smooth`){this.$tabScrollingContainer[0].scrollBy({left:e,behavior:t})}setupScrollEvents(){ne(this.$tabScrollingContainer),this.$scrollButtonLeft[0].addEventListener(`click`,()=>this.scrollTabContainer(-210)),this.$scrollButtonRight[0].addEventListener(`click`,()=>this.scrollTabContainer(210)),this.$tabScrollingContainer[0].addEventListener(`scroll`,()=>{clearTimeout(this.updateScrollTimeout),this.updateScrollTimeout=setTimeout(()=>{this.updateScrollButtonState()},100)})}updateScrollButtonState(){let e=this.$tabScrollingContainer[0].scrollLeft,t=this.$tabScrollingContainer[0].scrollWidth,n=this.$tabScrollingContainer[0].clientWidth;this.$scrollButtonLeft.toggleClass(`disabled`,Math.abs(e)<=1),this.$scrollButtonRight.toggleClass(`disabled`,Math.abs(e+n-t)<=1)}setScrollButtonVisibility(e=!0){e?(this.$scrollButtonLeft.css(`display`,`flex`),this.$scrollButtonRight.css(`display`,`flex`),clearTimeout(this.updateScrollTimeout),this.updateScrollTimeout=setTimeout(()=>{this.updateScrollButtonState()},200)):(this.$scrollButtonLeft.css(`display`,`none`),this.$scrollButtonRight.css(`display`,`none`))}setupEvents(){new ResizeObserver(e=>{this.cleanUpPreviouslyDraggedTabs(),this.layoutTabs()}).observe(this.$widget[0]),this.tabEls.forEach(e=>this.setTabCloseEvent(e))}setVisibility(){this.$widget.show()}get tabEls(){return Array.prototype.slice.call(this.$widget.find(`.note-tab`))}updateOuterWidth(){this.newTabOuterWidth==0&&(this.newTabOuterWidth=this.$newTab?.outerWidth(!0)??0),this.scrollButtonsOuterWidth==0&&(this.scrollButtonsOuterWidth=(this.$scrollButtonLeft?.outerWidth(!0)??0)+(this.$scrollButtonRight?.outerWidth(!0)??0))}get tabWidths(){let e=this.tabEls.length;this.updateOuterWidth();let t=Math.floor((this.$widget.width()??0)-this.newTabOuterWidth-_n);(pn+J)*e>t?(t-=this.scrollButtonsOuterWidth,this.setScrollButtonVisibility(!0)):this.setScrollButtonVisibility(!1);let n=(e-1)*J+mn,r=(t-n)/e,i=Math.floor(Math.max(pn,Math.min(q,r))),a=i*e+n,o=t-a,s=[],c=o;for(let t=0;t<e;t+=1){let e=+(i<q&&c>=1);s.push(i+e),c>=1&&--c}return s}getTabPositions(){let e=[],t=mn;this.tabWidths.forEach(n=>{e.push(t),t+=n+J}),t-=J;let n=t;return glob.isRtl&&e.reverse(),{tabPositions:e,anchorPosition:n}}layoutTabs(){let e=this.tabWidths;this.tabEls.forEach((t,n)=>{let r=e[n];t.style.width=`${r}px`,t.removeAttribute(`is-small`),t.removeAttribute(`is-smaller`),t.removeAttribute(`is-mini`),r<vn&&t.setAttribute(`is-small`,``),r<yn&&t.setAttribute(`is-smaller`,``),r<bn&&t.setAttribute(`is-mini`,``)});let t=``,{tabPositions:n,anchorPosition:r}=this.getTabPositions();n.forEach((e,n)=>{t+=`.note-tab:nth-child(${n+1}) { transform: translate3d(${e}px, 0, 0)} `}),t+=`.tab-row-container-anchor { transform: translate3d(${r}px, 0, 0) } `,t+=`.tab-row-widget-container {width: ${r}px}`,this.$style.html(t)}addTab(e){let t=$(xn).attr(`data-ntx-id`,e);g.updateDisplayedShortcuts(t),t.addClass(`note-tab-was-just-added`),setTimeout(()=>t.removeClass(`note-tab-was-just-added`),500),this.$containerAnchor.before(t),this.setVisibility(),this.setTabCloseEvent(t),this.updateTitle(t,w(`tab_row.new_tab`)),this.cleanUpPreviouslyDraggedTabs(),this.layoutTabs(),this.setupDraggabilly()}closeActiveTabCommand({$el:e}){let t=e.closest(`.note-tab`).attr(`data-ntx-id`);b.tabManager.removeNoteContext(t??null)}setTabCloseEvent(e){e.on(`mousedown`,t=>{if(t.which===2)return b.tabManager.removeNoteContext(e.attr(`data-ntx-id`)??null),!0}),e.find(`.note-tab-close`).on(`click`,e=>(this.triggerCommand(`closeActiveTab`,{$el:$(e.target)}),!0))}get activeTabEl(){return this.$widget.find(`.note-tab[active]`)[0]}activeContextChangedEvent(){let e=b.tabManager.getActiveContext();if(!e)return;e.mainNtxId&&(e=b.tabManager.getNoteContextById(e.mainNtxId));let t=this.getTabById(e.ntxId)[0],n=this.activeTabEl;n!==t&&(n&&n.removeAttribute(`active`),t&&t.setAttribute(`active`,``))}newNoteContextCreatedEvent({noteContext:e}){!e.mainNtxId&&e.ntxId&&this.addTab(e.ntxId)}removeTab(e){let t=this.getTabById(e)[0];t&&(t.parentNode?.removeChild(t),this.cleanUpPreviouslyDraggedTabs(),this.layoutTabs(),this.setupDraggabilly(),this.setVisibility())}getNtxIdsInOrder(){return this.tabEls.map(e=>e.getAttribute(`data-ntx-id`))}updateTitle(e,t){e.attr(`title`,t),e.find(`.note-tab-title`).text(t)}getTabById(e){return this.$widget.find(`[data-ntx-id='${e}']`)}getTabId(e){return e.attr(`data-ntx-id`)}noteContextRemovedEvent({ntxIds:e}){for(let t of e)this.removeTab(t)}cleanUpPreviouslyDraggedTabs(){this.tabEls.forEach(e=>e.classList.remove(`note-tab-was-just-dragged`))}setupDraggabilly(){let e=this.tabEls,{tabPositions:t}=this.getTabPositions(),n=0;this.isDragging&&this.draggabillyDragging&&(this.isDragging=!1,this.$widget.removeClass(`tab-row-widget-is-sorting`),this.draggabillyDragging.element.classList.remove(`note-tab-is-dragging`),this.draggabillyDragging.element.style.transform=``,this.draggabillyDragging.dragEnd(),this.draggabillyDragging.isDragging=!1,this.draggabillyDragging.positionDrag=()=>{},this.draggabillyDragging.destroy(),this.draggabillyDragging=null),this.draggabillies.forEach(e=>e.destroy()),e.forEach((e,r)=>{let i=t[r],a=new dn.default(e,{axis:`x`,handle:`.note-tab-drag-handle`,containment:this.$tabContainer[0]});this.draggabillies.push(a),a.on(`staticClick`,()=>{b.tabManager.activateNoteContext(e.getAttribute(`data-ntx-id`))}),a.on(`dragStart`,()=>{this.isDragging=!0,this.draggabillyDragging=a,e.classList.add(`note-tab-is-dragging`),this.$widget.addClass(`tab-row-widget-is-sorting`),n=this.$tabScrollingContainer?.scrollLeft()??0,a.positionDrag=()=>{}}),a.on(`dragEnd`,()=>{this.isDragging=!1;let t=(this.$tabScrollingContainer?.scrollLeft()??0)-n,r=parseFloat(e.style.left)+t,i=this.$tabContainer[0]?.offsetWidth-e.offsetWidth,a=Math.min(i,Math.max(0,r));e.style.transform=`translate3d(0, 0, 0)`,requestAnimationFrame(t=>{e.style.left=`0`,e.style.transform=`translate3d(${a}px, 0, 0)`,requestAnimationFrame(t=>{e.classList.remove(`note-tab-is-dragging`),this.$widget.removeClass(`tab-row-widget-is-sorting`),e.classList.add(`note-tab-was-just-dragged`),requestAnimationFrame(t=>{e.style.transform=``,this.layoutTabs(),this.setupDraggabilly()})})})}),a.on(`dragMove`,(r,a,o)=>{let s=this.tabEls,c=s.indexOf(e),l=this.$tabScrollingContainer[0]?.getBoundingClientRect(),u=a.pageX;u<l.left?this.scrollTabContainer(-105):u>l.right&&this.scrollTabContainer(105);let d=(this.$tabScrollingContainer?.scrollLeft()??0)-n,f=o.x+d,p=this.$tabContainer[0]?.offsetWidth-e.offsetWidth-i,m=-i;f=Math.min(p,Math.max(m,f)),e.style.transform=`translate3d(${f}px, 0, 0)`;let h=i+f,g=this.closest(h,t),_=Math.max(0,Math.min(s.length,g));c!==_&&this.animateTabMove(e,c,_),Math.abs(o.y)>100&&this.triggerCommand(`moveTabToNewWindow`,{ntxId:this.getTabId($(e))})})})}animateTabMove(e,t,n){if(n<t)e.parentNode?.insertBefore(e,this.tabEls[n]);else{let t=this.tabEls[n+1]||this.$containerAnchor[0];e.parentNode?.insertBefore(e,t)}this.triggerEvent(`tabReorder`,{ntxIdsInOrder:this.getNtxIdsInOrder()}),this.layoutTabs()}setupNewButton(){this.$newTab=$(Cn),this.$widget.append(this.$newTab)}setupFiller(){this.$filler=$(wn),this.$widget.append(this.$filler)}setupContainerAnchor(){this.$containerAnchor=$(Sn),this.$tabContainer.append(this.$containerAnchor)}closest(e,t){let n=1/0,r=-1;return t.forEach((t,i)=>{Math.abs(e-t)<n&&(n=Math.abs(e-t),r=i)}),r}noteSwitchedAndActivatedEvent({noteContext:e}){this.activeContextChangedEvent(),this.updateTabById(e.mainNtxId||e.ntxId)}noteSwitchedEvent({noteContext:e}){this.updateTabById(e.mainNtxId||e.ntxId)}noteContextReorderEvent({oldMainNtxId:e,newMainNtxId:t}){!e||!t||(this.getTabById(e).attr(`data-ntx-id`,t),this.updateTabById(t))}contextsReopenedEvent({mainNtxId:e,tabPosition:t}){if(!e||t<0)return;let n=this.getTabById(e)[0];n&&n.parentNode&&n.parentNode.insertBefore(n,this.tabEls[t])}updateTabById(e){let t=this.getTabById(e);t[0].scrollIntoView({behavior:`smooth`});let n=b.tabManager.getNoteContextById(e);this.updateTab(t,n)}async updateTab(e,t){if(!e.length)return;for(let t of Array.from(e[0].classList))t!==`note-tab`&&e.removeClass(t);let n=``;if(t){let r=y.getNoteFromCache(t.hoistedNoteId);r?(e.find(`.note-tab-wrapper`).css(`--workspace-tab-background-color`,r.getWorkspaceTabBackgroundColor()),this.showNoteIcons||(n=r.getWorkspaceIconClass())):e.find(`.note-tab-wrapper`).removeAttr(`style`)}let{note:r}=t;if(!r){this.updateTitle(e,w(`tab_row.new_tab`));return}let i=await t.getNavigationTitle();i&&this.updateTitle(e,i),e.addClass(r.getCssClass()),e.addClass(s.getNoteTypeClass(r.type)),e.addClass(s.getMimeTypeClass(r.mime)),this.showNoteIcons&&(n=r.getIcon()),n&&e.find(`.note-tab-icon`).removeClass().addClass(`note-tab-icon`).addClass(n)}async entitiesReloadedEvent({loadResults:e}){for(let t of b.tabManager.noteContexts)if(t.noteId&&(e.isNoteReloaded(t.noteId)||e.getAttributeRows().find(e=>[`workspace`,`iconClass`,`workspaceIconClass`,`workspaceTabBackgroundColor`].includes(e.name||``)&&O.isAffecting(e,t.note)))){let e=this.getTabById(t.ntxId);this.updateTab(e,t)}}frocaReloadedEvent(){for(let e of b.tabManager.noteContexts){let t=this.getTabById(e.ntxId);this.updateTab(t,e)}}hoistedNoteChangedEvent({ntxId:e}){let t=this.getTabById(e);if(t&&e){let n=b.tabManager.getNoteContextById(e);this.updateTab(t,n)}}};l();function Dn(){let e=d(()=>a()?o(`@electron/remote`).getCurrentWebContents():void 0,[]),t=e?Te(e):void 0,{canGoBack:n,canGoForward:r}=On(e),i=he(`_lbBackInHistory`),s=he(`_lbForwardInHistory`);return E(`div`,{className:`tab-history-navigation-buttons`,children:[!i&&E(F,{icon:`bx bx-left-arrow-alt`,text:w(`tab_history_navigation_buttons.go-back`),triggerCommand:`backInNoteHistory`,onContextMenu:t,disabled:!n}),!s&&E(F,{icon:`bx bx-right-arrow-alt`,text:w(`tab_history_navigation_buttons.go-forward`),triggerCommand:`forwardInNoteHistory`,onContextMenu:t,disabled:!r})]})}function On(e){let[t,n]=p(e?.navigationHistory.canGoBack()),[r,i]=p(e?.navigationHistory.canGoForward());return f(()=>{if(!e)return;let t=()=>{n(e.navigationHistory.canGoBack()),i(e.navigationHistory.canGoForward())};return e.on(`did-navigate`,t),e.on(`did-navigate-in-page`,t),()=>{e.removeListener(`did-navigate`,t),e.removeListener(`did-navigate-in-page`,t)}},[e]),e?{canGoBack:t,canGoForward:r}:{canGoBack:!0,canGoForward:!0}}function kn(){let[e]=le(`nativeTitleBarVisible`);return E(`div`,{className:`title-bar-buttons`,children:a()&&e&&E(h,{children:[E(Y,{className:`minimize-btn`,icon:`bx bx-minus`,onClick:({window:e})=>e.minimize()}),E(Y,{className:`maximize-btn`,icon:`bx bx-checkbox`,onClick:({window:e})=>{e.isMaximized()?e.unmaximize():e.maximize()}}),E(Y,{className:`close-btn`,icon:`bx bx-x`,onClick:({window:e})=>e.close()})]})})}function Y({className:e,icon:t,onClick:n}){return E(`div`,{className:e,children:E(`button`,{className:`btn ${t}`,onClick:()=>{let e=o(`@electron/remote`).BrowserWindow.getFocusedWindow();e&&n({window:e})}})})}var An=`<div class="toc-widget">
    <style>
        .toc-widget {
            padding: 10px;
            contain: none;
            overflow: auto;
            position: relative;
            padding-inline-start:0px !important;
        }

        .toc ol {
            position: relative;
            overflow: hidden;
            padding-inline-start: 0px;
            transition: max-height 0.3s ease;
        }

        .toc li.collapsed + ol {
            display:none;
        }

        .toc li + ol:before {
            content: "";
            position: absolute;
            height: 100%;
            border-inline-start: 1px solid var(--main-border-color);
            z-index: 10;
        }

        .toc li {
            display: flex;
            position: relative;
            list-style: none;
            align-items: center;
            padding-inline-start: 7px;
            cursor: pointer;
            text-align: justify;
            word-wrap: break-word;
            hyphens: auto;
        }

        .toc > ol {
            --toc-depth-level: 1;
        }
        .toc > ol > ol {
            --toc-depth-level: 2;
        }
        .toc > ol > ol > ol {
            --toc-depth-level: 3;
        }
        .toc > ol > ol > ol > ol {
            --toc-depth-level: 4;
        }
        .toc > ol > ol > ol > ol > ol {
            --toc-depth-level: 5;
        }

        .toc > ol ol::before {
            inset-inline-start: calc((var(--toc-depth-level) - 2) * 20px + 14px);
        }

        .toc li {
            padding-inline-start: calc((var(--toc-depth-level) - 1) * 20px + 4px);
        }

        .toc li .collapse-button {
            display: flex;
            position: relative;
            width: 21px;
            height: 21px;
            flex-shrink: 0;
            align-items: center;
            justify-content: center;
            transition: transform 0.3s ease;
        }

        .toc li.collapsed .collapse-button {
            transform: rotate(-90deg);
        }

        .toc li .item-content {
            margin-inline-start: 25px;
            flex: 1;
        }

        .toc li .collapse-button + .item-content {
            margin-inline-start: 4px;
        }

        .toc li:hover {
            font-weight: bold;
        }
    </style>

    <span class="toc"></span>
</div>`,jn=class extends at{$toc;tocLabelValue;get widgetTitle(){return w(`toc.table_of_contents`)}get widgetButtons(){return[new W().icon(`bx-cog`).title(w(`toc.options`)).titlePlacement(`left`).onClick(()=>b.tabManager.openContextWithNote(`_optionsTextNotes`,{activate:!0})).class(`icon-action`),new W().icon(`bx-x`).titlePlacement(`left`).onClick(e=>e.triggerCommand(`closeToc`)).class(`icon-action`)]}isEnabled(){if(!super.isEnabled()||!this.note)return!1;let e=this.note.type===`doc`&&this.note.noteId.startsWith(`_help`);return(this.note.type===`text`||e)&&!this.noteContext?.viewScope?.tocTemporarilyHidden&&this.noteContext?.viewScope?.viewMode===`default`}async doRenderBody(){this.$body.empty().append($(An)),this.$toc=this.$body.find(`.toc`)}async refreshWithNote(e){if(this.toggleInt(!!this.noteContext?.viewScope?.tocPreviousVisible),this.tocLabelValue=e.getLabelValue(`toc`),this.tocLabelValue===`hide`){this.toggleInt(!1),this.triggerCommand(`reEvaluateRightPaneVisibility`);return}if(!(!this.note||!this.noteContext?.viewScope)){if(this.note.type===`text`){let t=await e.getBlob();if(t){let e=await this.getToc(t.content);this.#e(e)}return}this.note.type===`doc`&&setTimeout(async()=>{let e=await this.noteContext?.getContentElement();if(e){let t=e.html(),n=await this.getToc(t);this.#e(n)}else console.warn(`Unable to get content element for doctype`)},250)}}#e({$toc:e,headingCount:t}){this.$toc.empty(),e&&this.$toc.append(e);let n=this.tocLabelValue,r=n===``||n===`show`||t>=(T.getInt(`minTocHeadings`)??0);this.toggleInt(r),this.noteContext?.viewScope&&(this.noteContext.viewScope.tocPreviousVisible=r),this.triggerCommand(`reEvaluateRightPaneVisibility`)}async replaceMathTextWithKatax(e){var t=[...e.matchAll(/<span class="math-tex">\\\(([\s\S]*?)\\\)<\/span>/g)];let n=e;if(t.length>0)for(let e of t){let t=e[1],r;try{r=oe.renderToString(t,{throwOnError:!1})}catch(n){if(n instanceof ReferenceError&&n.message.includes(`katex is not defined`))try{r=oe.renderToString(t,{throwOnError:!1})}catch(t){console.error(`KaTeX rendering error after loading library:`,t),r=e[0]}else console.error(`KaTeX rendering error:`,n),r=e[0]}n=n.replace(e[0],r)}return n}async getToc(e){let t=/<h(\d+)[^>]*>(.*?)<\/h\1>/gi,n=$(`<ol>`),r=2,i=[n],a;this.noteContext?.viewScope?.tocCollapsedHeadings instanceof Set||(this.noteContext.viewScope.tocCollapsedHeadings=new Set);let o=this.noteContext.viewScope.tocCollapsedHeadings,s=new Set,c=0;for(let n=null,l=0;(n=t.exec(e))!==null;l++){let e=parseInt(n[1]),t=e-r;if(t>0)for(let n=0;n<t;n++){let t=$(`<ol>`);if(i[i.length-1].append(t),i.push(t),a){let n=`h${e}_${l}_${a?.text().trim()}`;this.setupCollapsibleHeading(t,a,n,o,s)}}else if(t<0)for(let e=0;e<-t&&i.length>1;++e)i.pop();r=e;let u=await this.replaceMathTextWithKatax(n[2]),d=$(`<div class="item-content">`).html(u),f=$(`<li>`).append(d).on(`click`,()=>this.jumpToHeading(l));i[i.length-1].append(f),c=l,a=f}for(let e of o)s.has(e)||o.delete(e);return n=this.pullLeft(n),{$toc:n,headingCount:c}}pullLeft(e){for(;e.children().length===1;){let t=e.children(`:first`);if(t[0].tagName.toLowerCase()!==`ol`)break;e=t}return e}async jumpToHeading(e){if(!this.note||!this.noteContext)return;let t=this.note.type===`doc`,n=await this.noteContext.isReadOnly(),r=null;if(n||t)r=await this.noteContext.getContentElement();else{let e=await this.noteContext.getTextEditor();e?.sourceElement&&(r=$(e.sourceElement))}(r?.find(`:header:not(section.include-note :header)`)?.[e])?.scrollIntoView({behavior:`smooth`})}async setupCollapsibleHeading(e,t,n,r,i){if(t&&t.find(`.collapse-button`).length===0){let a=$(`<div class="collapse-button bx bx-chevron-down"></div>`);t.prepend(a),r?.has(n)?(t.addClass(`collapsed`),i.add(n)):t.removeClass(`collapsed`),a.on(`click`,i=>{if(i.stopPropagation(),t.hasClass(`animating`))return;let o=!t.hasClass(`collapsed`);t.addClass(`animating`),o?(e.css(`maxHeight`,`${e.prop(`scrollHeight`)}px`),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.css(`maxHeight`,`0px`),a.css(`transform`,`rotate(-90deg)`)})}),setTimeout(()=>{e.css(`maxHeight`,``),t.addClass(`collapsed`),t.removeClass(`animating`)},300)):(t.removeClass(`collapsed`),e.css(`maxHeight`,`0px`),requestAnimationFrame(()=>{e.css(`maxHeight`,`${e.prop(`scrollHeight`)}px`),a.css(`transform`,``)}),setTimeout(()=>{e.css(`maxHeight`,``),t.removeClass(`animating`)},300)),o?r.add(n):r.delete(n)})}}async closeTocCommand(){this.noteContext?.viewScope&&(this.noteContext.viewScope.tocTemporarilyHidden=!0),await this.refresh(),this.triggerCommand(`reEvaluateRightPaneVisibility`),b.triggerEvent(`reEvaluateTocWidgetVisibility`,{noteId:this.noteId})}async showTocWidgetEvent({noteId:e}){this.noteId===e&&(await this.refresh(),this.triggerCommand(`reEvaluateRightPaneVisibility`),b.triggerEvent(`reEvaluateTocWidgetVisibility`,{noteId:this.noteId}))}async entitiesReloadedEvent({loadResults:e}){(this.noteId&&e.isNoteContentReloaded(this.noteId)||e.getAttributeRows().find(e=>e.type===`label`&&((e.name??``).toLowerCase().includes(`readonly`)||e.name===`toc`)&&O.isAffecting(e,this.note)))&&await this.refresh()}},X={notes:{},attachments:{}};function Z(e){if(e!==`notes`&&e!==`attachments`)throw Error(`Unrecognized type '${e}', should be 'notes' or 'attachments'`)}function Mn(e,t){return Z(e),X[e][t]}function Nn(e,t){Z(e),delete X[e][t]}function Pn(e,t){Z(e),delete X[e][t]}re.subscribeToMessages(async e=>{e.type===`openedFileUpdated`&&(Z(e.entityType),X[e.entityType][e.entityId]=e,b.triggerEvent(`openedFileUpdated`,{entityType:e.entityType,entityId:e.entityId,lastModifiedMs:e.lastModifiedMs,filePath:e.filePath}))});var Q={getFileModificationStatus:Mn,fileModificationUploaded:Nn,ignoreModification:Pn},Fn=`
<div class="dropdown watched-file-update-status-widget alert alert-warning">
    <style>
        .watched-file-update-status-widget {
            margin: 10px;
            contain: none;
        }
    </style>

    <p>${w(`watched_file_update_status.file_last_modified`)}</p>

    <div style="display: flex; flex-direction: row; justify-content: flex-start; gap: 8px;">
        <button class="btn btn-sm file-upload-button">${w(`watched_file_update_status.upload_modified_file`)}</button>

        <button class="btn btn-sm ignore-this-change-button">${w(`watched_file_update_status.ignore_this_change`)}</button>
    </div>
</div>`,In=class extends pe{$filePath;$fileLastModified;$fileUploadButton;$ignoreThisChangeButton;isEnabled(){let{entityType:e,entityId:t}=this.getEntity();return super.isEnabled()&&!!e&&!!t&&!!Q.getFileModificationStatus(e,t)}doRender(){this.$widget=$(Fn),this.$filePath=this.$widget.find(`.file-path`),this.$fileLastModified=this.$widget.find(`.file-last-modified`),this.$fileUploadButton=this.$widget.find(`.file-upload-button`),this.$fileUploadButton.on(`click`,async()=>{let{entityType:e,entityId:t}=this.getEntity();await C.post(`${e}/${t}/upload-modified-file`,{filePath:this.$filePath.text()}),e&&t&&Q.fileModificationUploaded(e,t),this.refresh()}),this.$ignoreThisChangeButton=this.$widget.find(`.ignore-this-change-button`),this.$ignoreThisChangeButton.on(`click`,()=>{let{entityType:e,entityId:t}=this.getEntity();e&&t&&Q.ignoreModification(e,t),this.refresh()})}async refreshWithNote(e){let{entityType:t,entityId:r}=this.getEntity();if(!t||!r)return;let i=Q.getFileModificationStatus(t,r);this.$filePath.text(i.filePath),i.lastModifiedMs&&this.$fileLastModified.text(n.default.unix(i.lastModifiedMs/1e3).format(`HH:mm:ss`))}getEntity(){if(!this.noteContext)return{};let{viewScope:e}=this.noteContext;return e?.viewMode===`attachments`&&e.attachmentId?{entityType:`attachments`,entityId:e.attachmentId}:{entityType:`notes`,entityId:this.noteId}}openedFileUpdatedEvent(e){console.log(e);let{entityType:t,entityId:n}=this.getEntity();e.entityType===t&&e.entityId===n&&this.refresh()}},Ln=class{customWidgets;constructor(e){this.customWidgets=e}getRootWidget(e){e.noteTreeWidget=new st;let t=T.get(`layoutOrientation`)===`horizontal`,n=this.#e(t),r=s.isElectron(),i=window.glob.platform===`darwin`,a=window.glob.platform===`win32`,o=window.glob.hasNativeTitleBar,c=t||r&&!o&&i,l=!o&&!i&&!a,u=P(`new-layout`),d=new Ae(!0).setParent(e).class(`${t?`horizontal`:`vertical`}-layout`).optChild(c,new R(`row`).class(`tab-row-container`).child(new R(`row`).id(`tab-row-left-spacer`)).optChild(t,E(mt,{isHorizontalLayout:!0})).child(E(Dn,{})).child(new En().class(`full-width`)).optChild(u,E(ht,{})).optChild(l,E(kn,{})).css(`height`,`40px`).css(`background-color`,`var(--launcher-pane-background-color)`).setParent(e)).optChild(t,n).child(new R(`row`).css(`flex-grow`,`1`).id(`horizontal-main-container`).optChild(!t,n).child(new _t().optChild(!t,new we).child(e.noteTreeWidget).child(...this.customWidgets.get(`left-pane`))).child(new R(`column`).id(`rest-pane`).css(`flex-grow`,`1`).optChild(!c,new R(`row`).class(`tab-row-container`).child(E(Dn,{})).child(new En).optChild(u,E(ht,{})).optChild(l,E(kn,{})).css(`height`,`40px`).css(`align-items`,`center`)).optChild(u,E(Re,{})).child(new R(`row`).filling().collapsible().id(`vertical-main-container`).child(new R(`column`).filling().collapsible().id(`center-pane`).child(new Je(()=>new Pe().child(new R(`row`).class(`title-row note-split-title`).cssBlock(`.title-row > * { margin: 5px; }`).child(E(Ee,{})).child(E(ye,{})).optChild(u,E(Ke,{})).child(E(Ie,{baseSize:0,growthFactor:1})).optChild(!u,E(L,{direction:`left`})).optChild(!u,E(L,{direction:`right`})).optChild(!u,E(Ve,{})).optChild(!u,E(Se,{})).optChild(u,E(ze,{}))).optChild(!u,E(Me,{})).child(new In).optChild(!u,E(Ce,{items:xe})).child(new ve().filling().optChild(u,E(be,{})).optChild(u,E(Ge,{})).optChild(!u,new gt().child(E(We,{})).child(E(Oe,{}))).optChild(!u,E(qe,{})).child(E(Ne,{})).child(E(se,{media:`screen`})).child(E(He,{})).child(E(Fe,{}))).child(E(pt,{})).child(new De).child(...this.customWidgets.get(`note-detail-pane`)))).child(...this.customWidgets.get(`center-pane`))).optChild(!u,new vt().child(new jn).child(new wt).child(...this.customWidgets.get(`right-pane`))).optChild(u,E(nn,{widgetsByParent:this.customWidgets}))).optChild(!t&&u,E(Be,{})))).optChild(t&&u,E(Be,{})).child(E(je,{})).child(E(yt,{})).child(E(bt,{}));return Ue(d),d}#e(e){let t;return t=e?new R(`row`).css(`height`,`53px`).class(`horizontal`).child(E(I,{isHorizontalLayout:!0})).child(E(Ye,{isHorizontalLayout:!0})):new R(`column`).css(`width`,`53px`).class(`vertical`).child(E(Ye,{isHorizontalLayout:!1})).child(E(I,{isHorizontalLayout:!1})).child(E(mt,{isHorizontalLayout:!1})),t.id(`launcher-pane`),t}};export{Ln as default};