zidane-gui 9.3.1 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/out/main/chunks/{remote-hosts-B8_tzg_n.js → remote-hosts-CSiGJAfm.js} +1 -1
  2. package/out/main/chunks/{session-search-sql-2EUzjHAT.js → session-search-sql-D51BmAO2.js} +5 -5
  3. package/out/main/index.js +4397 -4086
  4. package/out/main/session-search-worker.js +1 -1
  5. package/out/preload/index.mjs +36 -2
  6. package/out/renderer/assets/{24BXRY42-eTlQfl4v.js → 24BXRY42-0UXaaWjY.js} +1 -1
  7. package/out/renderer/assets/{4FHPYW2L-BHx1bBmw.js → 4FHPYW2L-BWpHahlW.js} +1 -1
  8. package/out/renderer/assets/{4LWW3ZNH-D7lTurDT.js → 4LWW3ZNH-CPyJ9o9Y.js} +1 -1
  9. package/out/renderer/assets/{5XYWFMKW-e04QMbw9.js → 5XYWFMKW-ZZpHHfGa.js} +1 -1
  10. package/out/renderer/assets/{64PMEAB3-DTIFpDpU.js → 64PMEAB3-DOEnEuzl.js} +1 -1
  11. package/out/renderer/assets/{6BEWHPQE-BrYtHcZG.js → 6BEWHPQE-C2ZZckdj.js} +1 -1
  12. package/out/renderer/assets/{6PIGVMFT-CoAPPYTl.js → 6PIGVMFT-CRGq6eh3.js} +1 -1
  13. package/out/renderer/assets/{75JW6PN6-JbXPfJg4.js → 75JW6PN6-CYzAa9yx.js} +1 -1
  14. package/out/renderer/assets/{7XWI72E6-CFY3Kecs.js → 7XWI72E6-C_GZbyIF.js} +1 -1
  15. package/out/renderer/assets/{BGW36YJW-DhmSG9tb.js → BGW36YJW-BAwgTZ_z.js} +1 -1
  16. package/out/renderer/assets/{CGIZI67J-Cr9B0EmW.js → CGIZI67J-BxXITbQC.js} +1 -1
  17. package/out/renderer/assets/{CodeEditor-C6EJBlGG.js → CodeEditor-CLsAw7eu.js} +2 -2
  18. package/out/renderer/assets/{ComposerEditor-oFIdMkLB.js → ComposerEditor-BqnIn2NQ.js} +1 -1
  19. package/out/renderer/assets/{DNNCRC2E-CMqlK0W6.js → DNNCRC2E-kbsNJgPT.js} +1 -1
  20. package/out/renderer/assets/DiffsTab--BHt7StP.js +3 -0
  21. package/out/renderer/assets/{E67EBMDD-C_T2QnwF.js → E67EBMDD-BOeJkFNZ.js} +1 -1
  22. package/out/renderer/assets/{EFYWJBJK-Cbn-VZcb.js → EFYWJBJK-CFT5CQUG.js} +1 -1
  23. package/out/renderer/assets/{EXE5EH6O-SXdUe5We.js → EXE5EH6O-Cbj5xPKl.js} +1 -1
  24. package/out/renderer/assets/{EditorWorkers-bVeEZI8X.js → EditorWorkers-CXBU_HFf.js} +1 -1
  25. package/out/renderer/assets/{FilesTab-DtM2Q5R0.js → FilesTab-CZHD0eBx.js} +4 -4
  26. package/out/renderer/assets/{G6GPDDNC-XfFyRa0j.js → G6GPDDNC-Ax6dML4i.js} +1 -1
  27. package/out/renderer/assets/{G76NGGFM-Bj_m2WLJ.js → G76NGGFM-BxPXXNt_.js} +1 -1
  28. package/out/renderer/assets/{GH6G3TJC-wPRy41Zv.js → GH6G3TJC-CiCXY2r6.js} +1 -1
  29. package/out/renderer/assets/{HPNUA7RO-BhLNmX-t.js → HPNUA7RO-DiyW9VGu.js} +1 -1
  30. package/out/renderer/assets/{HQRGC5D7-dvTAT1Uv.js → HQRGC5D7-ArfvIYAC.js} +1 -1
  31. package/out/renderer/assets/{IX6Z2TVR-CzV_umYo.js → IX6Z2TVR-Df9chdw8.js} +1 -1
  32. package/out/renderer/assets/IconButtonTip-D0dQOfg6.js +1 -0
  33. package/out/renderer/assets/{J77NQRCJ-DTwwq3Ci.js → J77NQRCJ-DOWauTsf.js} +1 -1
  34. package/out/renderer/assets/{JAD36DTZ-DArKsMUT.js → JAD36DTZ-CJDdMCD5.js} +1 -1
  35. package/out/renderer/assets/{LF3NJQAX-DjYdE7YV.js → LF3NJQAX-B89ZqOpY.js} +1 -1
  36. package/out/renderer/assets/{LRZCOFJZ-C7m8fw-0.js → LRZCOFJZ-BBX_wZ5T.js} +1 -1
  37. package/out/renderer/assets/{N5NF2FGY-CqGhgjNF.js → N5NF2FGY-BoIFu-8L.js} +1 -1
  38. package/out/renderer/assets/{N7OWWQHY-BRk68LVa.js → N7OWWQHY-CloOgGu1.js} +1 -1
  39. package/out/renderer/assets/{NT5JY5WP-B1NtxJ-K.js → NT5JY5WP-BhjzefjG.js} +1 -1
  40. package/out/renderer/assets/{OT7W3RNY-CtDQ--Ld.js → OT7W3RNY-BRzBqtKB.js} +1 -1
  41. package/out/renderer/assets/{P67P66DB-LeAz_z3Z.js → P67P66DB-Dw-K1Ghu.js} +1 -1
  42. package/out/renderer/assets/{PFLLLM7K-CgODCVD8.js → PFLLLM7K-DfSPUrIT.js} +1 -1
  43. package/out/renderer/assets/{PUAMC4MJ-9REX_vGK.js → PUAMC4MJ-BnY1F2cF.js} +1 -1
  44. package/out/renderer/assets/{PVFCHRLY-CK5jTRjy.js → PVFCHRLY-BcyVPS3n.js} +1 -1
  45. package/out/renderer/assets/{PinnedSavedView-Dtdra7Gq.js → PinnedSavedView-ciRhY0cN.js} +1 -1
  46. package/out/renderer/assets/{QQW2P742-B2snHr_6.js → QQW2P742-D6aitZ24.js} +1 -1
  47. package/out/renderer/assets/{S63OEDPG-BeWWF1tc.js → S63OEDPG-Dlz1a9cD.js} +1 -1
  48. package/out/renderer/assets/{SG5TVYLW-ClCsbQ87.js → SG5TVYLW-Bu7LZZpx.js} +1 -1
  49. package/out/renderer/assets/{SavedViewArtifact-ATjDgAUF.js → SavedViewArtifact-CM9L4mc8.js} +1 -1
  50. package/out/renderer/assets/{SidebarPreviewPane-DHllX0GN.js → SidebarPreviewPane-DkOCt7Gb.js} +1 -1
  51. package/out/renderer/assets/{TranscriptViews-DD_JshFH.js → TranscriptViews-aYvP71ow.js} +1 -1
  52. package/out/renderer/assets/{UGRSUGA2-jP6nv8HL.js → UGRSUGA2-avwOtJG1.js} +1 -1
  53. package/out/renderer/assets/{V44WA6U7-Dr_tS3uH.js → V44WA6U7-DMF87Y7j.js} +1 -1
  54. package/out/renderer/assets/{V67O4WWV-BRn52u9c.js → V67O4WWV-BsDLuBDb.js} +1 -1
  55. package/out/renderer/assets/{VBUCM3YD-0sLtn_Zp.js → VBUCM3YD-C6FrRswP.js} +1 -1
  56. package/out/renderer/assets/{VINGRCPA-n98Gf7V0.js → VINGRCPA-Do3Pv3Tc.js} +1 -1
  57. package/out/renderer/assets/{ViewBlock-DdcTHRu3.js → ViewBlock-B-ppjb34.js} +3 -3
  58. package/out/renderer/assets/{ViewCharts-BAw6tExV.js → ViewCharts-jvS22ppO.js} +2 -2
  59. package/out/renderer/assets/{ViewCustom-BzwMbjqg.js → ViewCustom-yFkoy6a-.js} +1 -1
  60. package/out/renderer/assets/{ViewExtension-Ch5_33Ra.js → ViewExtension-DuHxho6W.js} +1 -1
  61. package/out/renderer/assets/{ViewInputs-BHooAs2f.js → ViewInputs-VAMDh56H.js} +1 -1
  62. package/out/renderer/assets/{ViewMcpApp-CJnOESMk.js → ViewMcpApp-CH_W9CZt.js} +1 -1
  63. package/out/renderer/assets/{ViewSessionAction-BHJv5QNb.js → ViewSessionAction-66veqRhO.js} +1 -1
  64. package/out/renderer/assets/{ViewTables-DBTupg46.js → ViewTables-CKKDcYKH.js} +1 -1
  65. package/out/renderer/assets/{WL6DNKX4-Csfp__Nw.js → WL6DNKX4-Cq-YK4Uf.js} +1 -1
  66. package/out/renderer/assets/{WQ63CJYP-oSbguA5n.js → WQ63CJYP-fjrhTSVs.js} +1 -1
  67. package/out/renderer/assets/{XOYAOB3S-DfDDKmX8.js → XOYAOB3S-CAQPI0he.js} +1 -1
  68. package/out/renderer/assets/{Y5LQLG3M-BnZ8APdi.js → Y5LQLG3M-DKntYAaW.js} +1 -1
  69. package/out/renderer/assets/{YIK6JTN6-Bunk5CDx.js → YIK6JTN6-CcjcC5JX.js} +1 -1
  70. package/out/renderer/assets/{core-BbPUgmX7.js → core-Cj89wpQh.js} +4 -4
  71. package/out/renderer/assets/{file-tabs-CFdJBYJ9.js → file-tabs-PoAgFa7v.js} +1 -1
  72. package/out/renderer/assets/{ghostty-web-Dn7o-dzQ.js → ghostty-web-DiMuvUtH.js} +1 -1
  73. package/out/renderer/assets/{highlights-eTGcn9lP.js → highlights-7WH0ppQl.js} +1 -1
  74. package/out/renderer/assets/{highlights-D4Jo_Sz0.js → highlights-DnSmFBdQ.js} +1 -1
  75. package/out/renderer/assets/index-CiuUSFeC.js +11 -0
  76. package/out/renderer/assets/kit-CD3F-f6F.js +147 -0
  77. package/out/renderer/assets/{langs-CXhlGiW6.js → langs-D5CRC9qz.js} +1 -1
  78. package/out/renderer/assets/{lazy-D3tN-GAO.js → lazy-CUmWiDAP.js} +3 -3
  79. package/out/renderer/assets/{loader-DGyfh0zB.js → loader-CPY9efuc.js} +1 -1
  80. package/out/renderer/assets/{pierre-theme-BZvsTYqQ.js → pierre-theme-BrzM0xZU.js} +3 -3
  81. package/out/renderer/assets/setting-demos-BW7cG2_G.css +1 -0
  82. package/out/renderer/assets/setting-demos-DEURBrvf.js +1 -0
  83. package/out/renderer/assets/{shiki-Wqv4XEGM.js → shiki-DFrbO9j3.js} +1 -1
  84. package/out/renderer/assets/{sidebar-layout-sK8ujsHX.js → sidebar-layout-fobokay5.js} +1 -1
  85. package/out/renderer/assets/{stream-tokenizer-C18hljKL.js → stream-tokenizer-CT1HAjvR.js} +1 -1
  86. package/out/renderer/assets/{themes-Dfx1_kFe.js → themes-Cj62ov9J.js} +1 -1
  87. package/out/renderer/assets/{useFind-BBxfQuQ2.js → useFind-Cdl0rVJO.js} +3 -3
  88. package/out/renderer/assets/{useFolderChanges-BcfSJoBT.js → useFolderChanges-C9L_NOgw.js} +2 -2
  89. package/out/renderer/assets/{view-preview-B2Rj--lZ.js → view-preview-BvCO9WZH.js} +1 -1
  90. package/out/renderer/assets/{zoom-reset-l-YVDJrI.js → zoom-reset-COqHFP45.js} +1 -1
  91. package/out/renderer/index.html +5 -5
  92. package/out/renderer/view-preview.html +6 -6
  93. package/package.json +2 -2
  94. package/out/renderer/assets/DiffsTab-D690H0Dy.js +0 -3
  95. package/out/renderer/assets/IconButtonTip-P9QUxPjA.js +0 -1
  96. package/out/renderer/assets/index-c95EBMdk.js +0 -8
  97. package/out/renderer/assets/kit-C9O_D5xC.js +0 -147
  98. package/out/renderer/assets/setting-demos-B0787McX.js +0 -1
  99. package/out/renderer/assets/setting-demos-vtrBsYTd.css +0 -1
@@ -1,4 +1,4 @@
1
- import{j as jsxRuntimeExports,r as reactExports}from"./vendor-react-CxJ4vs-5.js";import{ap as useEditorEnvironment,t as useLabels,H as buttonClass}from"./kit-C9O_D5xC.js";import{i as isFullyTransparent,s as surfacesMatch,j as relativeLuminance,p as pickReadableForeground,k as isDarkSurface,l as hoverWouldEraseText,m as deriveMutedFg,n as contrastRatio,o as compositeOverBg,D as DEFAULT_THEMES,q as areFileRenderOptionsEqual,t as isFilePlainText,v as getHighlighterIfLoaded,w as getFiletypeFromFileName,H as HighlighterDisposedError,x as linesFromFileContents,y as DEFAULT_RENDER_RANGE,z as areThemesAttached,B as areLanguagesAttached,C as renderFileWithHighlighter,E as createGutterGap,F as createGutterItem,G as createHastElement,I as getSharedHighlighter,J as createGutterWrapper,K as EMPTY_LINE_ANNOTATIONS,L as areThemesEqual,M as getThemes,N as EMPTY_RENDER_RANGE,O as isHandledWorkerPoolError,Q as CUSTOM_HEADER_SLOT_ID,S as HEADER_PREFIX_SLOT_ID,T as HEADER_FILENAME_SUFFIX_SLOT_ID,U as HEADER_METADATA_SLOT_ID,V as DEFAULT_VIRTUAL_FILE_METRICS,X as computeVirtualFileMetrics,Y as getVirtualFileHeaderHeight,Z as getVirtualFileHeaderRegion,_ as getVirtualFilePaddingBottom,$ as computeLineOffsets,a0 as countLineBreaks,a1 as LRUMapPkg,a2 as WorkerPoolContext,a3 as DIFFS_TAG_NAME,P as PREFERRED_HIGHLIGHTER,a4 as DIFFS_UNSAFE_CSS,a5 as DIFFS_HOST_STYLE,a6 as VIRTUALIZER_CONFIG,a7 as DEFAULT_TOKENIZE_MAX_LENGTH}from"./pierre-theme-BZvsTYqQ.js";import{g as getLineAnnotationName,a as areFileTargetsEqual,b as applyLineTextWithNewline,c as areRenderRangesEqual,i as isDefaultRenderRange,e as shouldRenderFileAnnotations,f as getFileAnnotations,h as createAnnotationElement,j as createFileHeaderElement,k as createContentColumn,l as getHighlighterOptions,r as resolvePreferredHighlighter,m as createPreElement,n as shouldUseTokenTransformer,R as ResizeManager,I as InteractionManager,p as pluckInteractionOptions,o as resolveEditSessionSlotName,q as adoptEditSessionAnnotations,w as writeEditSessionAnnotations,t as prerenderHTMLIfNecessary,v as createAnnotationWrapperNode,x as createGutterUtilityContentNode,y as createUnsafeCSSStyleNode,z as wrapUnsafeCSS,A as getMeasuredScrollbarGutter,B as upsertHostThemeStyle,C as wrapThemeCSS,D as patchScrollbarGutterSize,E as isSafari,G as getOrCreateCodeNode,H as guardWebKitScrollDuringRebuild,J as isStyleNode,S as SVGSpriteSheet$1,K as arePrePropertiesEqual,L as setPreNodeProperties,M as areObjectsEqual,N as areOptionsEqual,O as includesFileAnnotations,P as FILE_ANNOTATION_DOM_KEY,Q as isMacLike,T as recordLineAnnotationSource,U as getLineAnnotationSource,V as cloneHunks,W as dequeueRender,X as queueRender,Y as isGutterUtilityPath,Z as GutterUtilitySlotStyles,_ as useVirtualizer,$ as useCreateEditor,a0 as useStableCallback,a1 as useForceUpdate,a2 as useNextRenderData,a3 as noopRender,a4 as templateRender,a5 as useDetachCleanup,a6 as revealOnHighlight,a7 as scrollReachOnRender,a8 as EditProvider,a9 as Virtualizer,u as useFind,aa as fileLines,F as FindBar}from"./useFind-BBxfQuQ2.js";import{a as addEventListener,g as getLineNumberAttr,h,e as endsWithLineBreak,b as getGraphemeSegmenter,c as createSegmenter,r as round,f as extend,l as lookupScrollContainer,i as clampDomOffset}from"./utils-qCteL8MB.js";import{h as hastToHtml}from"./hastToHtml-C4ea9WpN.js";const colorUtils={compositeOverBg,contrastRatio,deriveMutedFg,hoverWouldEraseText,isDarkSurface,isFullyTransparent,pickReadableForeground,relativeLuminance,surfacesMatch};function isLineCacheForFile(lineCache,file){return file.cacheKey==null?lineCache.file===file&&lineCache.sourceContents===file.contents:lineCache.cacheKey===file.cacheKey}let instanceId$2=-1;var FileRenderer=class{options;annotationSlotName;onRenderUpdate;workerManager;__id=`file-renderer:${++instanceId$2}`;file;renderCache;pendingHighlightResult;computedLang="text";lineAnnotations={};lineCache;pendingStructuralRows;textDocumentCache=new WeakMap;ownedRows=new WeakSet;editSessionActive=!1;get fileCache(){return this.renderCache?.file}constructor(options={theme:DEFAULT_THEMES},annotationSlotName=getLineAnnotationName,onRenderUpdate,workerManager){this.options=options,this.annotationSlotName=annotationSlotName,this.onRenderUpdate=onRenderUpdate,this.workerManager=workerManager}setOptions(options){this.options=options}mergeOptions(options){this.options={...this.options,...options}}setLineAnnotations(lineAnnotations){this.lineAnnotations={};for(const annotation of lineAnnotations){const arr=this.lineAnnotations[annotation.lineNumber]??[];this.lineAnnotations[annotation.lineNumber]=arr,arr.push(annotation)}}cleanUp(){this.endEditSession(),this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}beginEditSession(file,externalFile){const{editSessionActive:wasAlreadyActive,renderCache}=this;if(this.editSessionActive=!0,wasAlreadyActive||(this.pendingHighlightResult=void 0),this.file=file,renderCache==null||wasAlreadyActive&&renderCache.file===file)return;if(wasAlreadyActive){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}const{options}=this.getRenderOptions(file),cacheBelongsToSession=renderCache.file===file,cacheBelongsToExternal=externalFile!=null&&areFileTargetsEqual(renderCache.file,externalFile),{result}=renderCache;if(!renderCache.highlighted||result==null||!areFileRenderOptionsEqual(renderCache.options,options)||!cacheBelongsToSession&&!cacheBelongsToExternal){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}if(cacheBelongsToSession)return;this.renderCache={...renderCache,file,result:{...result,code:[...result.code]}};const{lineCache}=this;lineCache!=null&&externalFile!=null&&isLineCacheForFile(lineCache,externalFile)?this.lineCache={cacheKey:void 0,file,sourceContents:file.contents,lines:lineCache.lines}:this.lineCache=void 0}endEditSession(settledFile){if(this.editSessionActive=!1,this.pendingHighlightResult=void 0,this.file==null){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}const{renderCache}=this;settledFile==null||renderCache==null||renderCache.file===settledFile||!areFileTargetsEqual(renderCache.file,settledFile)||(renderCache.file=settledFile)}editorRenderReady(){return this.renderCache?.options.useTokenTransformer===!0&&this.renderCache.highlighted&&this.renderCache.result!=null}recycle(){this.editSessionActive?(this.renderCache!=null&&(this.renderCache.renderRange=void 0),this.pendingHighlightResult=void 0,this.pendingStructuralRows=void 0):(this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap),this.workerManager?.cleanUpTasks(this),this.file=void 0}clearRenderCache(){this.pendingStructuralRows=void 0,this.renderCache=void 0,this.pendingHighlightResult=void 0}hydrate(file){this.file=file;const{options}=this.getRenderOptions(file),massiveFile=isFileMassive(this.getOrCreateLineCache(file).length,this.getTokenizeMaxLength());let cache=this.workerManager?.getFileResultCache(file);cache!=null&&!areFileRenderOptionsEqual(options,cache.options)&&(cache=void 0),this.renderCache??={file,hydrated:!0,options,highlighted:!massiveFile&&!isFilePlainText(file),result:massiveFile?void 0:cache?.result,renderRange:void 0};const workerManager=this.getHighlightWorkerManager(file);workerManager!=null?this.renderCache.result==null&&!massiveFile&&workerManager.highlightFileAST(this,file):getHighlighterIfLoaded({theme:this.getLocalHighlightTheme()})==null&&(this.computedLang=file.lang??getFiletypeFromFileName(file.name),this.initializeHighlighter().catch(error=>{error instanceof HighlighterDisposedError||this.onHighlightError(error)}))}getHighlightWorkerManager(file){const{editSessionActive,workerManager}=this;return!editSessionActive&&workerManager?.isWorkingPool()===!0&&!workerManager.shouldHighlightOnMainThread(file)?workerManager:void 0}cacheHighlightResult(file,renderResult){const{editSessionActive,workerManager}=this;!editSessionActive&&workerManager?.isWorkingPool()===!0&&workerManager.setFileResultCache(file.cacheKey,renderResult)}getLocalHighlightTheme(){return this.workerManager?.getFileRenderOptions().theme??this.options.theme??DEFAULT_THEMES}getEffectiveCodeOptions(){const poolOptions=this.workerManager?.isWorkingPool()===!0?this.workerManager.getFileRenderOptions():void 0;return{theme:this.getLocalHighlightTheme(),tokenizeMaxLineLength:poolOptions?.tokenizeMaxLineLength??this.options.tokenizeMaxLineLength}}getRenderOptions(file){const options=(()=>{if(this.workerManager?.isWorkingPool()===!0){const poolOptions=this.workerManager.getFileRenderOptions();return this.editSessionActive&&poolOptions.useTokenTransformer!==!0?{...poolOptions,useTokenTransformer:!0}:poolOptions}const{tokenizeMaxLineLength=1e3}=this.options;return{theme:this.getLocalHighlightTheme(),useTokenTransformer:this.editSessionActive||this.options.useTokenTransformer===!0,tokenizeMaxLineLength}})(),{renderCache}=this;return renderCache?.result==null?{options,forceHighlight:!0}:!areFileTargetsEqual(file,renderCache.file)||!areFileRenderOptionsEqual(options,renderCache.options)?{options,forceHighlight:!0}:{options,forceHighlight:!1}}getFileForNextRender(file){const{options}=this.getRenderOptions(file);if(this.getReadyRenderResult(file,options)!=null)return file;const{renderCache}=this;if(renderCache==null)return file;if(areFileTargetsEqual(renderCache.file,file))return renderCache.file;const lines=linesFromFileContents(file.contents),forcePlainText=file.contents.length===0||isFilePlainText(file)||isFileMassive(lines.length,this.getTokenizeMaxLength());return this.canRenderFile(file,options,forcePlainText)?file:renderCache.file}canRenderFile(file,options,forcePlainText){const{renderCache}=this;return renderCache==null||areFileTargetsEqual(renderCache.file,file)?!0:forcePlainText?renderCache.result==null&&renderCache.hydrated!==!0||this.workerManager?.isWorkingPool()===!0&&!this.workerManager.shouldHighlightOnMainThread(file)||getHighlighterIfLoaded({theme:options.theme})!=null:renderCache.result==null&&renderCache.hydrated!==!0?!0:this.getHighlightWorkerManager(file)!=null?!renderCache.highlighted:getHighlighterIfLoaded({theme:options.theme})!=null}getOrCreateLineCache(file){let{lineCache}=this;return(lineCache==null||!isLineCacheForFile(lineCache,file))&&(lineCache={cacheKey:file.cacheKey,file,sourceContents:file.contents,lines:linesFromFileContents(file.contents)}),this.lineCache=lineCache,lineCache.lines}getLineCount(file){const lines=this.getOrCreateLineCache(file);return this.textDocumentCache.get(file)?.lineCount??lines.length}updateRenderCache(dirtyLines,themeType,lineCountChangeInFlight=!1){this.pendingStructuralRows=void 0;const{renderCache}=this;if(renderCache==null)return;const{file,result}=renderCache;if(result==null)return;const pendingStructuralRows=lineCountChangeInFlight?new Map:void 0;this.pendingStructuralRows=pendingStructuralRows;const lineCache=this.lineCache!=null&&isLineCacheForFile(this.lineCache,file)?this.lineCache:void 0;for(const[line,tokens]of dirtyLines){if(pendingStructuralRows==null&&lineCache!=null&&line<lineCache.lines.length){const lineText=tokens.map(token=>token[2]).join("");lineCache.lines[line]=applyLineTextWithNewline(lineCache.lines[line]??"",lineText)}const row={type:"element",tagName:"div",properties:{"data-line":line+1,"data-line-type":"context","data-line-index":line},children:tokens.map(([char,fg,text])=>char===0&&fg===""?text===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:text}:{type:"element",tagName:"span",properties:{"data-char":char,style:`color:${fg};`},children:[{type:"text",value:text}]})};this.ownedRows.add(row),pendingStructuralRows!=null?pendingStructuralRows.set(line,row):result.code[line]=row}result.baseThemeType=themeType,renderCache.isDirty=!0,pendingStructuralRows==null&&lineCache!=null&&(file.contents=lineCache.lines.join(""),lineCache.sourceContents=file.contents)}applyDocumentChange(textDocument){const{pendingStructuralRows,renderCache}=this;this.pendingStructuralRows=void 0;const file=this.file??renderCache?.file;if(file==null)return;const result=renderCache?.result,previousLines=this.lineCache!=null&&isLineCacheForFile(this.lineCache,file)?this.lineCache.lines:linesFromFileContents(file.contents),nextLines=linesFromFileContents(textDocument.getText());if(result!=null&&previousLines.length!==nextLines.length){const maxShared=Math.min(previousLines.length,nextLines.length);let prefix=0;for(;prefix<maxShared&&previousLines[prefix]===nextLines[prefix];)prefix++;let suffix=0;for(;suffix<maxShared-prefix&&previousLines[previousLines.length-1-suffix]===nextLines[nextLines.length-1-suffix];)suffix++;const previousCode=result.code;result.code=new Array(nextLines.length);for(let i=0;i<prefix;i++)result.code[i]=previousCode[i];for(let i=0;i<suffix;i++)result.code[nextLines.length-1-i]=previousCode[previousLines.length-1-i];if(pendingStructuralRows!==void 0)for(const[line,row]of pendingStructuralRows)line<nextLines.length&&(result.code[line]=row);for(let i=prefix;i<nextLines.length-suffix;i++)result.code[i]??=this.ownRow({type:"element",tagName:"div",properties:{"data-line":i+1,"data-line-type":"context","data-line-index":i},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:textDocument.getLineText(i)}]}]});for(let i=0;i<result.code.length;i++){const line=result.code[i];if(line?.type==="element"&&(line.properties["data-line"]!==i+1||line.properties["data-line-index"]!==i)){const row=this.ownedRows.has(line)?line:this.ownRow({...line,properties:{...line.properties}});row.properties["data-line"]=i+1,row.properties["data-line-index"]=i,result.code[i]=row}}renderCache!=null&&(renderCache.isDirty=!0)}const contents=textDocument.getText();this.lineCache={cacheKey:file.cacheKey,file,sourceContents:contents,lines:nextLines},this.textDocumentCache.set(file,textDocument),file.contents=contents}ownRow(row){return this.ownedRows.add(row),row}renderFile(file=this.file,renderRange=DEFAULT_RENDER_RANGE){if(this.file=file,file==null){this.pendingHighlightResult=void 0;return}let{options,forceHighlight}=this.getRenderOptions(file);const readyResult=this.getReadyRenderResult(file,options);this.pendingHighlightResult=void 0,readyResult!=null&&(this.renderCache={...readyResult,file,renderRange:void 0},forceHighlight=!1),this.renderCache??={file,highlighted:!1,options,result:void 0,renderRange:void 0};const lines=this.getOrCreateLineCache(file),hasContent=file.contents.length>0,forcePlainText=!hasContent||isFilePlainText(file)||isFileMassive(lines.length,this.getTokenizeMaxLength()),canRenderFile=this.canRenderFile(file,options,forcePlainText),newContent=!areFileTargetsEqual(file,this.renderCache.file),newRenderRange=!areRenderRangesEqual(this.renderCache.renderRange,renderRange),workerManager=this.getHighlightWorkerManager(file);if(workerManager!=null){const preserveHydratedContent=this.renderCache.result==null&&this.renderCache.highlighted&&!forcePlainText&&!newContent&&isDefaultRenderRange(renderRange);canRenderFile&&!preserveHydratedContent&&(forcePlainText||this.renderCache.result==null||!this.renderCache.highlighted&&(newContent||newRenderRange))&&(this.renderCache.file=file,this.renderCache.options=options,this.renderCache.highlighted=!1,(this.renderCache.result==null||newContent||newRenderRange||forceHighlight)&&(this.renderCache.result=workerManager.getPlainFileAST(file,renderRange.startingLine,renderRange.totalLines,lines)),this.renderCache.renderRange=renderRange),!forcePlainText&&hasContent&&(!this.renderCache.highlighted||forceHighlight)&&workerManager.highlightFileAST(this,file)}else{this.computedLang=file.lang??getFiletypeFromFileName(file.name);const highlighter=getHighlighterIfLoaded(),hasThemes=highlighter!=null&&areThemesAttached(options.theme,highlighter),hasLangs=highlighter!=null&&areLanguagesAttached(this.computedLang,highlighter),canHighlight=!forcePlainText&&hasLangs,lazyLineAST=Number.isFinite(renderRange.totalLines);if(canRenderFile&&highlighter!=null&&hasThemes&&(forceHighlight||forcePlainText||!this.renderCache.highlighted&&canHighlight||this.renderCache.result==null)){const{result,options:options2}=this.renderFileWithHighlighter(file,highlighter,forcePlainText||!hasLangs,lazyLineAST);this.renderCache={file,options:options2,highlighted:canHighlight,result,renderRange:void 0},canHighlight&&this.cacheHighlightResult(file,{result,options:options2})}(!hasThemes||!forcePlainText&&!hasLangs)&&this.asyncHighlight(file,lazyLineAST).then(({result,options:options2})=>{forcePlainText||this.cacheHighlightResult(file,{result,options:options2}),this.applyHighlightResult(file,result,options2,!forcePlainText)}).catch(error=>{error instanceof HighlighterDisposedError||this.onHighlightError(error)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,renderRange,this.renderCache.result):void 0}async asyncRender(file,renderRange=DEFAULT_RENDER_RANGE){this.file=file;const{result}=await this.asyncHighlight(file,Number.isFinite(renderRange.totalLines));return this.processFileResult(file,renderRange,result)}async asyncHighlight(file,lazyLineAST=!1){const forcePlainText=isFileMassive(this.getOrCreateLineCache(file).length,this.getTokenizeMaxLength());this.computedLang=forcePlainText?"text":file.lang??getFiletypeFromFileName(file.name);let highlighter=getHighlighterIfLoaded();const hasThemes=highlighter!=null&&areThemesAttached(this.getLocalHighlightTheme(),highlighter),hasLangs=forcePlainText||highlighter!=null&&areLanguagesAttached(this.computedLang,highlighter);return(highlighter==null||!hasThemes||!hasLangs)&&(highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(file,highlighter,forcePlainText,lazyLineAST)}renderFileWithHighlighter(file,highlighter,forcePlainText=!1,lazyLineAST=!1){const{options}=this.getRenderOptions(file);return{result:renderFileWithHighlighter(file,highlighter,options,{forcePlainText,lazyLineAST}),options}}processFileResult(file,renderRange,{code,themeStyles,baseThemeType}){const totalLines=this.getLineCount(file),{disableFileHeader=!1}=this.options,contentArray=[],gutter=createGutterWrapper(),endLine=Math.min(renderRange.startingLine+renderRange.totalLines,totalLines);let rowCount=0;const fileLevelAnnotations=shouldRenderFileAnnotations(renderRange)?getFileAnnotations(this.lineAnnotations):void 0;fileLevelAnnotations!=null&&(gutter.children.push(createGutterGap("context","annotation",1)),contentArray.push(createAnnotationElement({hunkIndex:-1,lineIndex:-1,annotations:fileLevelAnnotations.map(annotation=>this.annotationSlotName(annotation))})),rowCount++);for(let lineIndex=renderRange.startingLine;lineIndex<endLine;lineIndex++){const lineNumber=lineIndex+1,line=code[lineIndex];if(line==null){const message="FileRenderer.processFileResult: Line doesnt exist";throw console.error(message,{name:file.name,lineIndex,lineNumber}),new Error(message)}gutter.children.push(createGutterItem("context",lineNumber,`${lineIndex}`)),contentArray.push(line),rowCount++;const annotations=this.lineAnnotations[lineNumber];annotations!=null&&(gutter.children.push(createGutterGap("context","annotation",1)),contentArray.push(createAnnotationElement({hunkIndex:0,lineIndex:lineNumber,annotations:annotations.map(annotation=>this.annotationSlotName(annotation))})),rowCount++)}return gutter.properties.style=`grid-row: span ${rowCount}`,{file,gutterAST:gutter.children??[],contentAST:contentArray,preAST:this.createPreElement(totalLines),headerAST:disableFileHeader?void 0:this.renderHeader(file),totalLines,rowCount,themeStyles,baseThemeType,bufferBefore:renderRange.bufferBefore,bufferAfter:renderRange.bufferAfter,css:""}}renderHeader(file){const{headerRenderMode="default",stickyHeader=!1}=this.options;return createFileHeaderElement({fileOrDiff:file,mode:headerRenderMode,stickyHeader})}renderFullHTML(result){return hastToHtml(this.renderFullAST(result))}renderFullAST(result,children=[]){return children.push(createHastElement({tagName:"code",children:this.renderCodeAST(result),properties:{"data-code":""}})),{...result.preAST,children}}renderCodeAST(result){const gutter=createGutterWrapper();return gutter.children=result.gutterAST,gutter.properties.style=`grid-row: span ${result.rowCount}`,[gutter,createContentColumn(result.contentAST,result.rowCount)]}renderPartialHTML(children,includeCodeNode=!1){return includeCodeNode?hastToHtml(createHastElement({tagName:"code",children,properties:{"data-code":""}})):hastToHtml(children)}initializeHighlighter(){return getSharedHighlighter(getHighlighterOptions(this.computedLang,{theme:this.getLocalHighlightTheme(),preferredHighlighter:resolvePreferredHighlighter(this.workerManager,this.options)}))}onHighlightSuccess(file,result,options,highlighted=!0){this.editSessionActive||this.applyHighlightResult(file,result,options,highlighted)}applyHighlightResult(file,result,options,highlighted=!0){const{file:currentFile,renderCache}=this;currentFile==null||renderCache==null||!areFileTargetsEqual(file,currentFile)||!areFileRenderOptionsEqual(options,this.getRenderOptions(currentFile).options)||(renderCache.result==null||!renderCache.highlighted||!areFileRenderOptionsEqual(renderCache.options,options)||!areFileTargetsEqual(renderCache.file,currentFile))&&(this.pendingHighlightResult={file:currentFile,options,highlighted,result},this.onRenderUpdate?.())}getMatchingWorkerResultCache(file,options){if(this.editSessionActive)return;const cache=this.workerManager?.getFileResultCache(file);if(!(cache==null||!areFileRenderOptionsEqual(options,cache.options)))return cache}getReadyRenderResult(file,options){const{pendingHighlightResult}=this;if(pendingHighlightResult!=null&&areFileTargetsEqual(pendingHighlightResult.file,file)&&areFileRenderOptionsEqual(pendingHighlightResult.options,options))return pendingHighlightResult;const workerCache=this.getMatchingWorkerResultCache(file,options);if(!(workerCache==null||this.hasHighlightedRenderCache(file,options)))return{file,highlighted:!0,...workerCache}}hasHighlightedRenderCache(file,options){const{renderCache}=this;return renderCache?.result!=null&&renderCache.highlighted&&areFileTargetsEqual(file,renderCache.file)&&areFileRenderOptionsEqual(options,renderCache.options)}onHighlightError(error){console.error(error)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(totalLines){const{disableLineNumbers=!1,overflow="scroll"}=this.options;return createPreElement({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers,overflow,split:!1,totalLines})}};function isFileMassive(lineCount,tokenizeMaxLength){return lineCount>tokenizeMaxLength}function areLineAnnotationsEqual(annotationA,annotationB){return annotationA.lineNumber===annotationB.lineNumber&&annotationA.metadata===annotationB.metadata}function getFileRendererOptions(options){return{theme:options?.theme,disableLineNumbers:options?.disableLineNumbers,overflow:options?.overflow,themeType:options?.themeType,collapsed:options?.collapsed,disableFileHeader:options?.disableFileHeader,disableVirtualizationBuffers:options?.disableVirtualizationBuffers,stickyHeader:options?.stickyHeader,preferredHighlighter:options?.preferredHighlighter,useCSSClasses:options?.useCSSClasses,useTokenTransformer:shouldUseTokenTransformer(options),tokenizeMaxLineLength:options?.tokenizeMaxLineLength,tokenizeMaxLength:options?.tokenizeMaxLength,unsafeCSS:options?.unsafeCSS,headerRenderMode:options?.renderCustomHeader!=null?"custom":"default"}}const EMPTY_STRINGS=[""];function createEditSessionFile(file){const editSessionFile={...file};return delete editSessionFile.cacheKey,editSessionFile}let instanceId$1=-1;var File$1=class{options;workerManager;requestOwnerRender;static LoadedCustomComponent=!0;__id=`file:${++instanceId$1}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;get lineAnnotations(){return this.renderedData?.lineAnnotations??EMPTY_LINE_ANNOTATIONS}managersDirty=!1;file;editSession;renderedData;pendingData;forceRenderOverride;renderRange;enabled=!0;editor;constructor(options={theme:DEFAULT_THEMES},workerManager,requestOwnerRender){this.options=options,this.workerManager=workerManager,this.requestOwnerRender=requestOwnerRender,this.fileRenderer=new FileRenderer(options,this.getAnnotationSlotName,this.handleHighlightRender,this.workerManager),this.resizeManager=new ResizeManager,this.interactionManager=new InteractionManager("file",pluckInteractionOptions(options)),this.workerManager?.subscribeToThemeChanges(this)}getAnnotationSlotName=annotation=>resolveEditSessionSlotName(this.editSession?.annotations,annotation,getLineAnnotationName);handleHighlightRender=()=>{this.rerender()};rerender(){const file=this.getInputFile();!this.enabled||file==null||this.requestRender()||this.render({file,forceRender:!0,renderRange:this.renderRange})}requestRender(){const{requestOwnerRender}=this;return this.editSession!=null||requestOwnerRender==null?!1:(this.forceRenderOverride=!0,requestOwnerRender(),!0)}get isComponentManaged(){return this.requestOwnerRender!=null}getTheme(){return this.workerManager?.getFileRenderOptions().theme??this.options.theme??DEFAULT_THEMES}getInputFile(){return this.file}getWorkingFile(fallbackFile=this.file){return this.editSession?.file??fallbackFile}getRenderedFile(){return this.renderedData?.file}__getNextRenderData({file,lineAnnotations}){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null)return{file,lineAnnotations:lineAnnotations!=null&&this.isNewAnnotations(lineAnnotations)?lineAnnotations:sessionAnnotations.provided};const workingFile=this.getWorkingFile(file)??file,nextFile=this.fileRenderer.getFileForNextRender(workingFile);return{file:nextFile,lineAnnotations:lineAnnotations!=null&&areFileTargetsEqual(nextFile,workingFile)?lineAnnotations:this.getAnnotationsForFile(nextFile)}}getLatestAnnotations(){return this.pendingData?.lineAnnotations??this.editSession?.annotations?.current??this.lineAnnotations}getAnnotationsForFile(file){const{pendingData}=this;return pendingData!=null&&areFileTargetsEqual(file,pendingData.file)?pendingData.lineAnnotations:this.lineAnnotations}adoptRenderData(file){const{pendingData}=this,matchesPending=pendingData!=null&&areFileTargetsEqual(file,pendingData.file);this.renderedData={file,lineAnnotations:matchesPending?pendingData.lineAnnotations:this.lineAnnotations},matchesPending&&(this.pendingData=void 0)}isNewAnnotations(lineAnnotations){const session=this.editSession?.annotations;return lineAnnotations===this.getLatestAnnotations()?!1:session==null||lineAnnotations!==session.provided&&lineAnnotations!==session.current}updateInputFile(incomingFile,lineAnnotations){if(areFileTargetsEqual(this.getInputFile(),incomingFile))return!1;const hadSession=this.editSession!=null,previousAnnotations=this.getLatestAnnotations();return this.file=incomingFile,hadSession||this.editor!=null?this.installEditSession(incomingFile,hadSession?void 0:this.editor?.__getDocumentContents(incomingFile),!0):this.editSession=void 0,this.editSession?.annotations!=null&&lineAnnotations!=null&&(this.editSession.annotations=adoptEditSessionAnnotations(lineAnnotations,getLineAnnotationName,this.editSession.annotations)),this.pendingData={file:this.editSession?.file??incomingFile,lineAnnotations:this.editSession?.annotations?.current??lineAnnotations??previousAnnotations},!0}installEditSession(inputFile,retainedDocument,hostReplacement=!1){const usesInputDocument=retainedDocument==null||retainedDocument.name===inputFile.name&&retainedDocument.lang===inputFile.lang&&retainedDocument.contents===inputFile.contents,file=createEditSessionFile(retainedDocument??inputFile),annotations=this.editSession?.annotations??adoptEditSessionAnnotations(this.getLatestAnnotations(),getLineAnnotationName);this.editSession={file,inputFile,externalReplacement:hostReplacement&&usesInputDocument,annotations},this.pendingData={file,lineAnnotations:annotations.current},this.fileRenderer.beginEditSession(file,usesInputDocument?inputFile:void 0)}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(options){options!=null&&(this.options=options,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(pluckInteractionOptions(this.options))}mergeOptions(options){this.options={...this.options,...options}}setThemeType(themeType){(this.options.themeType??"system")!==themeType&&(this.mergeOptions({themeType}),this.applyCachedThemeState(themeType))}applyCachedThemeState(themeType){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const effectiveThemeType=this.appliedThemeCSS.baseThemeType??themeType;return this.appliedThemeCSS.themeType===effectiveThemeType?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,themeType,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!areThemesEqual(this.appliedThemeCSS.theme,this.getTheme())}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(lineAnnotations){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null){if(!this.isNewAnnotations(lineAnnotations))return;writeEditSessionAnnotations(sessionAnnotations,lineAnnotations,getLineAnnotationName)}const file=this.getWorkingFile();file!=null&&(this.pendingData={file,lineAnnotations})}syncEditSessionAnnotationsFromEditor(lineAnnotations){const session=this.editSession?.annotations;return session==null||lineAnnotations===session.current?!1:(session.current=lineAnnotations,this.renderedData!=null&&(this.renderedData.lineAnnotations=lineAnnotations),this.pendingData=void 0,this.fileRenderer.setLineAnnotations(lineAnnotations),this.renderAnnotations(),!0)}setSelectedLines(range,options){this.interactionManager.setSelection(range,options)}setEditorActiveLine(lineNumber,options){this.interactionManager.setEditorActiveLine(lineNumber,{lineNumberOnly:options?.lineNumberOnly,side:options?.side??"additions"})}getCodeScrollLeft(){return this.code?.scrollLeft??0}setCodeScrollLeft(position){this.code!=null&&(this.code.scrollLeft=position)}__getEffectiveCodeOptions(){return{...this.options,...this.fileRenderer.getEffectiveCodeOptions()}}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,{disableAnnotations:overflow==="wrap",columnVariables:this.shouldApplyColumnVariables(overflow)?"apply":"measure"}),this.managersDirty=!1}shouldApplyColumnVariables(overflow){return overflow==="scroll"&&this.lineAnnotations.length>0}cleanUp(recycle=!1){const editor=this.editor;this.emitPostRender(!0),editor?.cleanUp(recycle?"recycle":"discard"),recycle||(this.editor=void 0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isComponentManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,recycle||(this.renderedData=void 0,this.pendingData=void 0),this.clearAuxiliaryNodes(),this.pre?.remove(),this.pre=void 0,this.code=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement?.remove(),this.headerElement=void 0,this.clearHeaderSlots(),this.lastRenderedHeaderHTML=void 0,recycle||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,recycle?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0,this.editSession=void 0),this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(props){const{fileContainer,prerenderedHTML,preventEmit=!1,file,lineAnnotations}=props;if(!this.enabled)throw new Error("File.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("File.hydrate: hydrate can only be called before the instance has rendered or hydrated");this.hydrateElements(fileContainer,prerenderedHTML);const forceEditorRender=this.editor!=null;forceEditorRender||shouldRenderCode(this.pre,file,this.options.collapsed)||shouldRenderHeader(this.headerElement,file,this.options.disableFileHeader)?this.render({...props,forceRender:forceEditorRender||props.forceRender,preventEmit:!0}):this.hydrationSetup({file,lineAnnotations}),preventEmit||this.emitPostRender()}hydrateElements(fileContainer,prerenderedHTML){this.fileContainer!==fileContainer&&this.emitPostRender(!0),prerenderHTMLIfNecessary(fileContainer,prerenderedHTML);for(const element of Array.from(fileContainer.shadowRoot?.children??[])){if(element instanceof SVGElement){this.spriteSVG=element;continue}if(element instanceof HTMLElement){if(element instanceof HTMLPreElement){this.pre=element,this.appliedPreAttributes=void 0;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-theme-css")){this.themeCSSStyle=element;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=element,this.appliedUnsafeCSS=element.textContent;continue}if("diffsHeader"in element.dataset){this.headerElement=element,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=fileContainer,this.hydrateMeasuredScrollbar()}hydrationSetup({file,lineAnnotations}){this.renderedData={file,lineAnnotations:lineAnnotations??this.getLatestAnnotations()},this.pendingData=void 0,this.file=file,this.fileRenderer.setOptions(getFileRendererOptions(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(file),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(file=this.getWorkingFile()){return file!=null?this.fileRenderer.getOrCreateLineCache(file):EMPTY_STRINGS}updateBuffers(renderRange){this.pre!=null&&this.applyBuffers(this.pre,renderRange)}syncRenderViewToEditor(){const{editor,fileContainer,renderRange}=this,lineAnnotations=this.getLatestAnnotations(),file=this.getWorkingFile();if(editor==null||fileContainer==null||file==null)return;const syncEditor=highlighter2=>{!this.enabled||this.editor!==editor||this.fileContainer!==fileContainer||this.getWorkingFile()!==file||editor.__syncRenderView({highlighter:highlighter2,fileContainer,file,lineAnnotations,renderRange,externalDocument:this.editSession?.externalReplacement===!0})},theme=this.getTheme(),lang=file.lang??getFiletypeFromFileName(file.name),highlighter=getHighlighterIfLoaded({theme,lang});highlighter!=null?syncEditor(highlighter):getSharedHighlighter({themes:getThemes(theme),langs:Array.from(new Set(["text",lang])),preferredHighlighter:resolvePreferredHighlighter(this.workerManager,this.options)}).then(syncEditor).catch(error=>{error instanceof HighlighterDisposedError||console.error(error)})}__acknowledgeDocumentUpdate(){this.editSession!=null&&(this.editSession.externalReplacement=!1)}__acceptEditorChange(event){const{lineAnnotations}=event;lineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(lineAnnotations)}emitEditChange(event){const{onEditChange}=this.options;onEditChange?.(event)}__captureDocumentSessionState(){}__attachEditor(editor){if(this.editor!=null)throw new Error("File.__attachEditor: an editor is already attached");this.editor=editor;const detach=()=>{this.editor=void 0,this.fileRenderer.endEditSession()};try{return this.resumeEditorRendering(editor),detach}catch(error){throw detach(),error}}__resumeEditor(editor){if(this.editor!==editor)throw new Error("File.__resumeEditor: editor association changed");this.resumeEditorRendering(editor)}resumeEditorRendering(editor){if(this.editSession!=null)this.fileRenderer.beginEditSession(this.editSession.file);else{const inputFile=this.getInputFile();inputFile!=null&&this.installEditSession(inputFile,editor.__getDocumentContents(inputFile))}const editSessionFile=this.editSession?.file;this.fileRenderer.editorRenderReady()?(editSessionFile!=null&&this.fileRenderer.fileCache===editSessionFile&&this.adoptRenderData(editSessionFile),this.syncRenderViewToEditor()):this.rerender()}__completeEditSession(editor,mode){this.settleEditSession(mode==="install",editor)}settleEditSession(installResult,editor){const{editSession}=this;if(editSession==null)return;const{file:editSessionFile,inputFile,annotations:editSessionAnnotations}=editSession,inputAnnotations=editSessionAnnotations?.provided??this.lineAnnotations;if(this.editor!=null)throw new Error("File.__completeEditSession: detach the editor before completing the session");const sessionAnnotationsCurrent=editSessionAnnotations?.current;let acceptedFile,failed=!1,failure;if(editor==null)throw new Error("File.__completeEditSession: editor is required for completion");const completedFile={...editSessionFile},event={file:completedFile,editor,originalFile:inputFile,lineAnnotations:sessionAnnotationsCurrent,originalLineAnnotations:inputAnnotations};Object.freeze(event);try{if(editor.__emitEditComplete(event),this.options.onEditComplete?.(event)==="accept"){if(completedFile.cacheKey!=null&&completedFile.cacheKey===inputFile.cacheKey)throw new Error("File.__completeEditSession: an accepted file must not reuse the replaced file cacheKey");acceptedFile=completedFile}}catch(error){failed=!0,failure=error}const settledFile=installResult&&acceptedFile!=null?acceptedFile:inputFile,settledAnnotations=installResult&&acceptedFile!=null?sessionAnnotationsCurrent??inputAnnotations:inputAnnotations;if(this.editSession=void 0,this.file=settledFile,this.pendingData={file:settledFile,lineAnnotations:settledAnnotations},this.fileRenderer.endEditSession(settledFile),areFileTargetsEqual(this.getRenderedFile(),settledFile)&&this.adoptRenderData(settledFile),installResult&&this.fileContainer!=null&&this.rerender(),failed)throw failure}applyDocumentChange(textDocument,newLineAnnotations){const editSessionFile=this.editSession?.file;if(editSessionFile==null)throw new Error("File.applyDocumentChange: requires an active edit session");this.fileRenderer.beginEditSession(editSessionFile),this.fileRenderer.applyDocumentChange(textDocument),newLineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(newLineAnnotations)}applySuspendedDocumentChange(textDocument,newLineAnnotations){this.editSession!=null&&(this.applyDocumentChange(textDocument,newLineAnnotations),this.fileRenderer.clearRenderCache())}updateRenderCache(dirtyLines,themeType,options){const editSessionFile=this.editSession?.file;if(editSessionFile==null)throw new Error("File.updateRenderCache: requires an active edit session");this.fileRenderer.beginEditSession(editSessionFile),this.fileRenderer.updateRenderCache(dirtyLines,themeType,options?.lineCountChangeInFlight)}render({file,fileContainer,forceRender=!1,preventEmit=!1,containerWrapper,deferManagers=!1,lineAnnotations,renderRange}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");forceRender=this.forceRenderOverride??forceRender,this.forceRenderOverride=void 0,this.editor?.__postponeBgTokenizeToNextFrame();const{collapsed=!1,themeType="system"}=this.options,nextRenderRange=collapsed?void 0:renderRange,previousRenderRange=this.renderRange,themeChanged=this.hasThemeChanged(),annotationsChanged=lineAnnotations!=null&&(lineAnnotations.length>0||this.getLatestAnnotations().length>0)?this.isNewAnnotations(lineAnnotations):!1,didFileChange=!areFileTargetsEqual(this.getInputFile(),file);didFileChange&&this.updateInputFile(file,lineAnnotations);const workingFile=this.getWorkingFile(file)??file;if(!collapsed&&!forceRender&&areRenderRangesEqual(nextRenderRange,this.renderRange)&&!didFileChange&&!annotationsChanged&&!themeChanged){const rendered=this.applyCachedThemeState(themeType);return rendered&&this.finalizeRender(),rendered}this.renderRange=nextRenderRange,didFileChange&&(this.cachedHeaderHTML=void 0),this.fileRenderer.setOptions(getFileRendererOptions(this.options)),this.syncInteractionOptions(),lineAnnotations!=null&&this.setLineAnnotations(lineAnnotations);const nextRenderFile=this.fileRenderer.getFileForNextRender(workingFile);this.fileRenderer.setLineAnnotations(this.getAnnotationsForFile(nextRenderFile));const{disableErrorHandling=!1,disableFileHeader=!1}=this.options;if(disableFileHeader&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),fileContainer=this.getOrCreateFileContainerNode(fileContainer,containerWrapper),this.applyCachedThemeState(themeType),collapsed){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const fileResult=this.fileRenderer.renderFile(workingFile,EMPTY_RENDER_RANGE);fileResult!=null&&this.applyThemeState(fileContainer,fileResult.themeStyles,themeType,fileResult.baseThemeType),fileResult?.headerAST!=null&&this.applyHeaderToDOM(fileResult.headerAST,fileContainer,fileResult.file),this.adoptRenderData(fileResult?.file??workingFile),this.injectUnsafeCSS()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return this.finalizeRender(),preventEmit||this.emitPostRender(),!0}try{const pre=this.getOrCreatePreNode(fileContainer);let renderedFile=this.getRenderedFile();if(!this.canPartiallyRender(forceRender,annotationsChanged,didFileChange||themeChanged||!areFileTargetsEqual(this.getRenderedFile(),workingFile))||!this.applyPartialRender(workingFile,previousRenderRange,nextRenderRange)){const fileResult=this.fileRenderer.renderFile(workingFile,nextRenderRange);if(fileResult==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.isWorkingPool()&&this.workerManager.initialize().catch(()=>{}).then(()=>this.rerender()),!1;this.applyThemeState(fileContainer,fileResult.themeStyles,themeType,fileResult.baseThemeType),fileResult.headerAST!=null&&this.applyHeaderToDOM(fileResult.headerAST,fileContainer,fileResult.file),this.applyFullRender(fileResult,pre),renderedFile=fileResult.file}this.applyBuffers(pre,nextRenderRange),this.injectUnsafeCSS(),renderedFile!=null&&this.adoptRenderData(renderedFile),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,deferManagers||this.flushManagers(),this.finalizeRender(),this.editor!=null&&this.syncRenderViewToEditor()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return preventEmit||this.emitPostRender(),!0}finalizeRender(){}emitPostRender(unmount=!1){const{fileContainer,options:{onPostRender}}=this;if(unmount){if(!this.mounted||(this.mounted=!1,fileContainer==null))return;onPostRender?.(fileContainer,this,"unmount");return}if(fileContainer==null)return;const phase=this.mounted?"update":"mount";this.mounted=!0,onPostRender?.(fileContainer,this,phase)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(forceRender,annotationsChanged,didContentChange){return!(forceRender||annotationsChanged||didContentChange)}renderPlaceholder(height){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const shadowRoot=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",shadowRoot.appendChild(this.placeHolder)}return this.setPlaceholderHeight(height)}setPlaceholderHeight(height){return this.placeHolder==null?!1:(this.placeHolder.style.setProperty("height",`${height}px`),!0)}async primeHighlightCache(file=this.getInputFile()){const{workerManager}=this;if(file==null||workerManager==null||!workerManager.isWorkingPool()||file.cacheKey==null||isFilePlainText(file))return;const tokenizeMaxLength=this.options.tokenizeMaxLength??1e5;this.fileRenderer.getOrCreateLineCache(file).length>tokenizeMaxLength||await workerManager.primeFileHighlightCache(file).catch(error=>{isHandledWorkerPoolError(error)||console.error(error)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isComponentManaged||this.fileContainer==null){for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear();return}const staleAnnotations=new Map(this.annotationCache),{renderAnnotation}=this.options,{renderedData}=this;if(renderAnnotation!=null&&renderedData!=null){const{file,lineAnnotations}=renderedData;for(const[index,annotation]of lineAnnotations.entries()){const name=this.getAnnotationSlotName(annotation),id=`${index}-${name}`;let cache=this.annotationCache.get(id);if(cache==null||cache.file!==file||!areLineAnnotationsEqual(annotation,cache.annotation)){cache?.element.remove();const content=renderAnnotation(annotation,file);if(content==null)continue;cache={element:createAnnotationWrapperNode(name),annotation,file},cache.element.appendChild(content),this.fileContainer.appendChild(cache.element),this.annotationCache.set(id,cache)}staleAnnotations.delete(id)}}for(const[id,{element}]of staleAnnotations.entries())this.annotationCache.delete(id),element.remove()}renderGutterUtility(){const{renderGutterUtility}=this.options;if(this.fileContainer==null||renderGutterUtility==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const element=renderGutterUtility(this.interactionManager.getHoveredLine);if(element!=null&&this.gutterUtilityContent!=null)return;if(element==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const gutterUtilityContent=createGutterUtilityContentNode();gutterUtilityContent.appendChild(element),this.fileContainer.appendChild(gutterUtilityContent),this.gutterUtilityContent=gutterUtilityContent}injectUnsafeCSS(){const{unsafeCSS}=this.options;this.pre?.toggleAttribute("data-custom-styles",!!unsafeCSS);const shadowRoot=this.fileContainer?.shadowRoot;if(shadowRoot!=null){if(unsafeCSS==null||unsafeCSS===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===shadowRoot&&this.appliedUnsafeCSS===unsafeCSS||(this.unsafeCSSStyle??=createUnsafeCSSStyleNode(),this.unsafeCSSStyle.parentNode!==shadowRoot&&shadowRoot.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=wrapUnsafeCSS(unsafeCSS),this.appliedUnsafeCSS=unsafeCSS)}}applyThemeState(container,themeStyles,themeType,baseThemeType){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"}),effectiveThemeType=baseThemeType??themeType,currentTheme=this.getTheme(),theme=typeof currentTheme=="string"?currentTheme:{...currentTheme},scrollbarGutter=getMeasuredScrollbarGutter(shadowRoot);if(this.themeCSSStyle?.parentNode===shadowRoot&&this.appliedThemeCSS?.themeStyles===themeStyles&&this.appliedThemeCSS.themeType===effectiveThemeType&&this.appliedThemeCSS.scrollbarGutter===scrollbarGutter){this.appliedThemeCSS.theme=theme;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===shadowRoot){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter};return}this.themeCSSStyle=upsertHostThemeStyle({shadowRoot,currentNode:this.themeCSSStyle,themeCSS:wrapThemeCSS(themeStyles,effectiveThemeType,scrollbarGutter)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter}:void 0}hydrateMeasuredScrollbar(){const shadowRoot=this.fileContainer?.shadowRoot;shadowRoot==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=patchScrollbarGutterSize(this.themeCSSStyle.textContent??"",getMeasuredScrollbarGutter(shadowRoot)))}shouldGuardRebuildScroll(){return this.editor!=null&&isSafari()}applyFullRender(result,pre){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(pre,result);const code=this.code=getOrCreateCodeNode({code:this.code}),codeAst=this.fileRenderer.renderCodeAST(result);this.editor?.__captureFocusForDOMReplacement();const applyColumns=()=>{if(code.childElementCount>=2)for(let i=0;i<2;i++){const domEl=code.children[i],astEl=codeAst[i];domEl.innerHTML=hastToHtml(astEl.children),domEl.style.cssText=astEl.properties.style}else code.innerHTML=hastToHtml(codeAst);pre.contains(code)||pre.replaceChildren(code)};this.shouldGuardRebuildScroll()?guardWebKitScrollDuringRebuild(pre,applyColumns):applyColumns(),this.lastRowCount=result.rowCount}applyPartialRender(file,previousRenderRange,renderRange){if(previousRenderRange==null||renderRange==null)return!1;const{code}=this,columns=code!=null?this.getColumns(code):void 0;if(code==null||columns==null)return!1;const previousStart=previousRenderRange.startingLine,nextStart=renderRange.startingLine,previousEnd=previousRenderRange.totalLines===1/0?Number.POSITIVE_INFINITY:previousStart+previousRenderRange.totalLines,nextEnd=renderRange.totalLines===1/0?Number.POSITIVE_INFINITY:nextStart+renderRange.totalLines,overlapStart=Math.max(previousStart,nextStart),overlapEnd=Math.min(previousEnd,nextEnd);if(overlapEnd<=overlapStart)return!1;if(!this.trimDOMToOverlap(columns.gutter,overlapStart,overlapEnd)||!this.trimDOMToOverlap(columns.content,overlapStart,overlapEnd))throw new Error("File.applyPartialRender: failed to trim to overlap");let{length:rowCount}=columns.content.children;const renderChunk=(startingLine,totalLines)=>{if(!(totalLines<=0))return this.fileRenderer.renderFile(file,{startingLine,totalLines,bufferBefore:0,bufferAfter:0})},prependResult=nextStart<overlapStart?renderChunk(nextStart,overlapStart-nextStart):void 0;if(prependResult===void 0&&nextStart<overlapStart)return!1;const appendTotalLines=nextEnd===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,nextEnd-overlapEnd),appendResult=nextEnd>overlapEnd?renderChunk(overlapEnd,appendTotalLines):void 0;return appendResult===void 0&&nextEnd>overlapEnd?!1:(this.cleanupErrorWrapper(),prependResult!=null&&(columns.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(prependResult.gutterAST)),columns.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(prependResult.contentAST)),rowCount+=prependResult.rowCount),appendResult!=null&&(columns.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(appendResult.gutterAST)),columns.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(appendResult.contentAST)),rowCount+=appendResult.rowCount),this.lastRowCount!==rowCount&&(columns.gutter.style.setProperty("grid-row",`span ${rowCount}`),columns.content.style.setProperty("grid-row",`span ${rowCount}`),this.lastRowCount=rowCount),!0)}getColumns(code){const gutter=code.children[0],content=code.children[1];if(!(!(gutter instanceof HTMLElement)||!(content instanceof HTMLElement)||gutter.dataset.gutter==null||content.dataset.content==null))return{gutter,content}}trimDOMToOverlap(container,overlapStart,overlapEnd){const boundaryIndices=this.getDOMBoundaryIndices(container,[overlapStart,overlapEnd]),startIndex=boundaryIndices.get(overlapStart)??container.children.length,endIndex=boundaryIndices.get(overlapEnd)??container.children.length;if(startIndex>endIndex)return!1;for(let i=container.children.length-1;i>=endIndex;i-=1)container.children[i]?.remove();for(let i=startIndex-1;i>=0;i-=1)container.children[i]?.remove();return!0}getDOMBoundaryIndices(container,boundaries){const sortedBoundaries=[...new Set(boundaries)].sort((a,b)=>a-b),boundaryIndices=new Map;if(sortedBoundaries.length===0)return boundaryIndices;let boundaryIndex=0,nextBoundary=sortedBoundaries[boundaryIndex];const{children}=container;nextBoundary===0&&(boundaryIndices.set(0,0),boundaryIndex+=1,nextBoundary=sortedBoundaries[boundaryIndex]);for(let i=0;i<children.length;i+=1){const child=children[i];if(!(child instanceof HTMLElement))continue;const lineIndex=this.getLineIndexFromDOMNode(child);if(lineIndex!=null){for(;nextBoundary!=null&&lineIndex>=nextBoundary;)boundaryIndices.set(nextBoundary,i),boundaryIndex+=1,nextBoundary=sortedBoundaries[boundaryIndex];if(boundaryIndex>=sortedBoundaries.length)break}}for(const boundary of sortedBoundaries)boundaryIndices.has(boundary)||boundaryIndices.set(boundary,children.length);return boundaryIndices}getLineIndexFromDOMNode(node){const lineIndexAttr=node.dataset.lineIndex;if(lineIndexAttr==null)return;const parsed=Number(lineIndexAttr);return Number.isNaN(parsed)?void 0:parsed}applyBuffers(pre,renderRange){if(renderRange==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}renderRange.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",pre.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${renderRange.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),renderRange.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",pre.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${renderRange.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(headerAST,container,file){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const headerHTML=this.cachedHeaderHTML??hastToHtml(headerAST);if(this.cachedHeaderHTML=headerHTML,headerHTML!==this.lastRenderedHeaderHTML){const tempDiv=document.createElement("div");tempDiv.innerHTML=headerHTML;const newHeader=tempDiv.firstElementChild;if(!(newHeader instanceof HTMLElement))return;this.headerElement!=null?container.shadowRoot?.replaceChild(newHeader,this.headerElement):container.shadowRoot?.prepend(newHeader),this.headerElement=newHeader,this.lastRenderedHeaderHTML=headerHTML}if(this.isComponentManaged)return;const{renderHeaderPrefix,renderHeaderFilenameSuffix,renderCustomHeader,renderHeaderMetadata}=this.options;if(renderCustomHeader!=null){const content=renderCustomHeader(file)??void 0;this.headerCustom=this.upsertHeaderSlotElement(container,this.headerCustom,CUSTOM_HEADER_SLOT_ID,content),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const prefix=renderHeaderPrefix?.(file)??void 0,suffix=renderHeaderFilenameSuffix?.(file)??void 0,content=renderHeaderMetadata?.(file)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(container,this.headerPrefix,HEADER_PREFIX_SLOT_ID,prefix),this.headerFilenameSuffix=this.upsertHeaderSlotElement(container,this.headerFilenameSuffix,HEADER_FILENAME_SUFFIX_SLOT_ID,suffix),this.headerMetadata=this.upsertHeaderSlotElement(container,this.headerMetadata,HEADER_METADATA_SLOT_ID,content),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(container,current,slot,content){if(content==null){current?.remove();return}const element=current??this.createHeaderSlotElement(slot);return current==null&&container.appendChild(element),this.replaceHeaderSlotContent(element,content),element}replaceHeaderSlotContent(element,content){element.replaceChildren(),content instanceof Element?element.appendChild(content):element.innerText=`${content}`}createHeaderSlotElement(slot){const element=document.createElement("div");return element.slot=slot,element}getOrCreateFileContainerNode(fileContainer,parentNode){const{fileContainer:previousContainer}=this,nextContainer=fileContainer??previousContainer??document.createElement("diffs-container"),containerChanged=previousContainer!==nextContainer;return previousContainer!=null&&containerChanged&&this.editor?.__captureFocusForDOMReplacement(),containerChanged&&this.emitPostRender(!0),this.fileContainer=nextContainer,previousContainer!=null&&containerChanged&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),parentNode!=null&&this.fileContainer.parentNode!==parentNode&&parentNode.appendChild(this.fileContainer),containerChanged&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(fileContainer){const{shadowRoot}=fileContainer;if(shadowRoot!=null)for(const element of shadowRoot.children)element instanceof SVGElement?this.spriteSVG??=element:isStyleNode(element)&&element.hasAttribute("data-theme-css")?(this.themeCSSStyle??=element,this.hasAdoptedThemeCSS=!0):isStyleNode(element)&&element.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=element,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(fileContainer){const shadowRoot=fileContainer.shadowRoot??fileContainer.attachShadow({mode:"open"});if(this.spriteSVG==null){const fragment=document.createElement("div");fragment.innerHTML=SVGSpriteSheet$1;const firstChild=fragment.firstChild;firstChild instanceof SVGElement&&(this.spriteSVG=firstChild)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==shadowRoot&&shadowRoot.appendChild(this.spriteSVG)}getOrCreatePreNode(container){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,shadowRoot.appendChild(this.pre)):this.pre.parentNode!==shadowRoot&&(this.editor?.__captureFocusForDOMReplacement(),container.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(pre){this.code=void 0;for(const child of Array.from(pre.children))if(child instanceof HTMLElement&&child.hasAttribute("data-code")){this.code=child;return}}applyPreNodeAttributes(pre,{totalLines}){const{overflow="scroll",disableLineNumbers=!1}=this.options,preProperties={type:"file",split:!1,overflow,disableLineNumbers,diffIndicators:"none",disableBackground:!0,totalLines};arePrePropertiesEqual(preProperties,this.appliedPreAttributes)||(setPreNodeProperties(pre,preProperties),this.appliedPreAttributes=preProperties)}applyErrorToDOM(error,container){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",shadowRoot.appendChild(this.errorWrapper);const errorMessage=document.createElement("div");errorMessage.dataset.errorMessage="",errorMessage.innerText=error.message,this.errorWrapper.appendChild(errorMessage);const errorStack=document.createElement("pre");errorStack.dataset.errorStack="",errorStack.innerText=error.stack??"No Error Stack",this.errorWrapper.appendChild(errorStack)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function shouldRenderCode(pre,file,collapsed=!1){return!collapsed&&pre==null&&file!=null}function shouldRenderHeader(headerElement,file,disableFileHeader=!1){return headerElement==null&&file!=null&&!disableFileHeader}const LAYOUT_CHECKPOINT_INTERVAL=5e3,NO_GHOST_TEXT_ROWS=new Map;let instanceId=-1;function hasFileLayoutOptionChanged(previousOptions,nextOptions){return(previousOptions.overflow??"scroll")!==(nextOptions.overflow??"scroll")||(previousOptions.collapsed??!1)!==(nextOptions.collapsed??!1)||(previousOptions.disableLineNumbers??!1)!==(nextOptions.disableLineNumbers??!1)||(previousOptions.disableFileHeader??!1)!==(nextOptions.disableFileHeader??!1)||previousOptions.unsafeCSS!==nextOptions.unsafeCSS}var VirtualizedFile=class extends File$1{virtualizer;metrics;__id=`virtualized-file:${++instanceId}`;renderType="virtualized";top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0,ghostTextRows:NO_GHOST_TEXT_ROWS};pendingRender;isVisible=!1;isSetup=!1;layoutDirty=!0;currentCollapsed;constructor(options,virtualizer,metrics=DEFAULT_VIRTUAL_FILE_METRICS,workerManager,requestOwnerRender){super(options,workerManager,requestOwnerRender),this.virtualizer=virtualizer,this.metrics=metrics}setMetrics(metrics,force=!1){const nextMetrics=computeVirtualFileMetrics(metrics);!force&&areObjectsEqual(this.metrics,nextMetrics)||(this.metrics=nextMetrics,this.resetLayoutCache())}setLineAnnotations(lineAnnotations){this.syncLineAnnotations(lineAnnotations)&&(this.forceRenderOverride=!0)}syncLineAnnotations(lineAnnotations){return lineAnnotations==null||!this.isNewAnnotations(lineAnnotations)||lineAnnotations.length===0&&this.getLatestAnnotations().length===0?!1:(super.setLineAnnotations(lineAnnotations),!0)}syncEditSessionAnnotationsFromEditor(lineAnnotations){return super.syncEditSessionAnnotationsFromEditor(lineAnnotations)?(this.forceRenderOverride=!0,!0):!1}hasLineAnnotations(){return this.getLayoutAnnotations().some(annotation=>annotation.lineNumber>0)}hasUniformLineHeights(){const{overflow="scroll"}=this.options;return overflow==="scroll"&&!this.hasLineAnnotations()&&this.cache.heights.size===0}getLineHeight(lineIndex,hasMetadataLine=!1){const cached=this.cache.heights.get(lineIndex);if(cached!=null)return cached;const multiplier=hasMetadataLine?2:1;return this.metrics.lineHeight*multiplier}setOptions(options){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(options==null)return;const{options:previousOptions}=this,optionsChanged=!areOptionsEqual(previousOptions,options),layoutChanged=hasFileLayoutOptionChanged(previousOptions,options);super.setOptions(options),layoutChanged&&this.resetLayoutCache(!0),optionsChanged&&(this.forceRenderOverride=!0),optionsChanged&&this.virtualizer.instanceChanged(this,layoutChanged)}setThemeType(themeType){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(themeType)}resetLayoutCache(recompute=!1,resetRenderRange=!0){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.ghostTextRows=NO_GHOST_TEXT_ROWS,this.renderRange!=null&&resetRenderRange&&(this.renderRange=void 0),recompute&&this.isSimpleMode()&&this.computeApproximateSize()}applyGhostTextRows(ghostTextRows){const{heights,ghostTextRows:previous}=this.cache;if(previous===ghostTextRows)return!1;const{lineHeight}=this.metrics;let changed=!1;for(const lineIndex of new Set([...previous.keys(),...ghostTextRows.keys()])){const previousRows=previous.get(lineIndex)??0,rows=ghostTextRows.get(lineIndex)??0;if(rows===previousRows)continue;const height=(heights.get(lineIndex)??lineHeight)-previousRows*lineHeight+rows*lineHeight;height===lineHeight?heights.delete(lineIndex):heights.set(lineIndex,height),changed=!0}return this.cache.ghostTextRows=ghostTextRows,changed}reconcileHeights(){let hasHeightChange=!1;if(this.fileContainer==null||this.getLayoutFile()==null)return this.height!==0&&(hasHeightChange=!0),this.height=0,hasHeightChange;const{overflow="scroll"}=this.options;this.top=this.getVirtualizedTop();const ghostTextRows=this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS;hasHeightChange=this.applyGhostTextRows(ghostTextRows);const measureAllRows=overflow!=="scroll"||this.lineAnnotations.length>0||this.isResizeDebuggingEnabled();if(this.placeHolder!=null||!measureAllRows&&this.cache.heights.size===0&&this.cache.fileAnnotationHeight===0)return hasHeightChange&&(this.computeApproximateSize(!0),this.setPlaceholderHeight(this.height)),hasHeightChange;const{lineHeight}=this.metrics;if(this.code==null)return hasHeightChange;const content=this.code.children[1];if(!(content instanceof HTMLElement))return hasHeightChange;if(this.renderRange!=null&&shouldRenderFileAnnotations(this.renderRange)){const nextFileAnnotationHeight=measureFileAnnotationHeight(content)??0;nextFileAnnotationHeight!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=nextFileAnnotationHeight,hasHeightChange=!0)}for(const line of content.children){if(!(line instanceof HTMLElement))continue;const lineIndexAttr=line.dataset.lineIndex;if(lineIndexAttr==null)continue;const lineIndex=Number(lineIndexAttr),ghostHeight=(ghostTextRows.get(lineIndex)??0)*lineHeight,cachedHeight=this.cache.heights.get(lineIndex);if(!measureAllRows&&(cachedHeight==null||cachedHeight===lineHeight+ghostHeight))continue;let measuredHeight=line.getBoundingClientRect().height+ghostHeight,hasMetadata=!1;line.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in line.nextElementSibling.dataset||"noNewline"in line.nextElementSibling.dataset)&&("noNewline"in line.nextElementSibling.dataset&&(hasMetadata=!0),measuredHeight+=line.nextElementSibling.getBoundingClientRect().height);const expectedHeight=this.getLineHeight(lineIndex,hasMetadata);measuredHeight!==expectedHeight&&(hasHeightChange=!0,measuredHeight===this.metrics.lineHeight*(hasMetadata?2:1)?this.cache.heights.delete(lineIndex):this.cache.heights.set(lineIndex,measuredHeight))}return(hasHeightChange||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),hasHeightChange}onRender=dirty=>{const file=this.getInputFile();return this.fileContainer==null||file==null?!1:(dirty&&(this.top=this.getVirtualizedTop()),this.render({file}))};updateCodeViewLayout(file,top,reset,lineAnnotations){const targetChanged=!areFileTargetsEqual(this.getInputFile(),file);targetChanged&&this.updateInputFile(file,lineAnnotations);const{pendingRenderFile,layoutFileChanged,renderedFileChanged,annotationsChanged}=this.updatePendingRender(file,lineAnnotations);let shouldResetLayoutCache=reset?.resetFileLayoutCache===!0||layoutFileChanged;reset?.metrics!=null&&(this.metrics=reset.metrics,shouldResetLayoutCache=!0);const{collapsed=!1}=this.options;return this.currentCollapsed!==collapsed&&(this.currentCollapsed=collapsed,shouldResetLayoutCache=!0),shouldResetLayoutCache&&this.resetLayoutCache(),targetChanged&&(this.layoutDirty=!0),!this.forceRenderOverride&&(targetChanged||renderedFileChanged||annotationsChanged)&&(this.forceRenderOverride=!0),this.top=top,this.computeApproximateSize(!1,pendingRenderFile),this.height}getLayoutFile(){return this.pendingRender?.file??this.getRenderedFile()}getLayoutAnnotations(){const{pendingRender}=this;return pendingRender!=null?this.getAnnotationsForFile(pendingRender.file):this.lineAnnotations}getLinePosition(lineNumber){const file=this.getLayoutFile();if(file==null||lineNumber<1)return;const{disableFileHeader=!1,collapsed=!1}=this.options,lastLineIndex=this.fileRenderer.getLineCount(file)-1;if(collapsed)return{top:getVirtualFileHeaderHeight(this.metrics,disableFileHeader),height:0};let top=getVirtualFileHeaderRegion(this.metrics,disableFileHeader);if(lastLineIndex<0)return{top,height:0};const clampedLineIndex=Math.min(Math.max(lineNumber-1,0),lastLineIndex),{lineHeight}=this.metrics;if(top+=this.cache.fileAnnotationHeight,this.hasUniformLineHeights())return{top:top+clampedLineIndex*lineHeight,height:lineHeight};const checkpoint=this.getLayoutCheckpointBeforeLineIndex(clampedLineIndex);top=checkpoint?.top??top;for(let lineIndex=checkpoint?.lineIndex??0;lineIndex<clampedLineIndex;lineIndex++)top+=this.getLineHeight(lineIndex,!1);return{top,height:this.getLineHeight(clampedLineIndex,!1)}}getEditorViewport(){return this.virtualizer.type==="simple"?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(localViewportTop){const file=this.getLayoutFile();if(file==null||this.renderRange==null)return;const{disableFileHeader=!1,collapsed=!1}=this.options;if(collapsed||this.renderRange.totalLines<=0)return;const lastLineIndex=this.fileRenderer.getLineCount(file)-1;if(lastLineIndex<0)return;const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),firstRenderedLineIndex=Math.min(this.renderRange.startingLine,lastLineIndex),lastRenderedLineIndex=Math.min(firstRenderedLineIndex+this.renderRange.totalLines-1,lastLineIndex);if(lastRenderedLineIndex<firstRenderedLineIndex)return;const{fileAnnotationHeight}=this.cache;if(this.hasUniformLineHeights()){const{lineHeight}=this.metrics,firstRenderedLineTop=headerRegion+(firstRenderedLineIndex===0?fileAnnotationHeight:this.renderRange.bufferBefore),lineIndex=firstRenderedLineIndex+Math.max(Math.ceil((localViewportTop-firstRenderedLineTop)/lineHeight),0);return lineIndex>lastRenderedLineIndex?void 0:{lineNumber:lineIndex+1,top:headerRegion+fileAnnotationHeight+lineIndex*lineHeight}}let top=headerRegion+(firstRenderedLineIndex===0?fileAnnotationHeight:this.renderRange.bufferBefore);for(let lineIndex=firstRenderedLineIndex;lineIndex<=lastRenderedLineIndex;lineIndex++){if(top>=localViewportTop)return{lineNumber:lineIndex+1,top};top+=this.getLineHeight(lineIndex)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(windowSpecs){const file=this.getLayoutFile();if(this.top==null||file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const renderRange=windowSpecs!=null?this.computeRenderRangeFromWindow(file,this.top,windowSpecs):this.renderRange;if(renderRange==null)return;const{bufferBefore,bufferAfter,totalLines}=renderRange;let headerOnlyOffset=0;if(totalLines===0){const activeWindow=windowSpecs??this.virtualizer.getWindowSpecs();this.top<activeWindow.top&&(headerOnlyOffset=bufferAfter)}return{topOffset:this.top+bufferBefore+headerOnlyOffset,height:this.height-(bufferBefore+bufferAfter)}}cleanUp(recycle=!1){const hadGhostTextRows=this.cache.ghostTextRows.size>0;hadGhostTextRows&&(this.layoutDirty=!0);const shouldRecomputeLayout=recycle&&this.isAdvancedMode()&&this.fileContainer!=null&&(hadGhostTextRows||!areFileTargetsEqual(this.getRenderedFile(),this.getWorkingFile()));this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),recycle||this.resetLayoutCache(),this.pendingRender=void 0,this.isSetup=!1,super.cleanUp(recycle),shouldRecomputeLayout&&this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(force=!1,file=this.getLayoutFile()){const shouldValidateSize=this.isResizeDebuggingEnabled();if(!force&&!this.layoutDirty&&!shouldValidateSize)return;const isFirstCompute=this.height===0;if(this.height=0,this.cache.checkpoints=[],file==null){this.layoutDirty=!1;return}this.applyGhostTextRows(this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS);const{disableFileHeader=!1,collapsed=!1}=this.options,{lineHeight}=this.metrics,lineCount=this.fileRenderer.getLineCount(file);if(collapsed){this.height+=getVirtualFileHeaderHeight(this.metrics,disableFileHeader),this.layoutDirty=!1;return}const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),paddingBottom=getVirtualFilePaddingBottom(this.metrics);if(this.height+=headerRegion,this.height+=this.cache.fileAnnotationHeight,this.hasUniformLineHeights())this.height+=lineCount*lineHeight;else for(let lineIndex=0;lineIndex<lineCount;lineIndex++)this.addLayoutCheckpoint(lineIndex,this.height),this.height+=this.getLineHeight(lineIndex,!1);if(lineCount>0&&(this.height+=paddingBottom),this.fileContainer!=null&&shouldValidateSize&&!isFirstCompute){const rect=this.fileContainer.getBoundingClientRect();rect.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:file.name,elementHeight:rect.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(visible){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,visible&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!visible&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){if(!this.enabled||this.getInputFile()==null)return;const workingFile=this.getWorkingFile(),nextRenderFile=workingFile==null?void 0:this.fileRenderer.getFileForNextRender(workingFile);this.isSimpleMode()&&(this.pendingRender=void 0),this.forceRenderOverride=!0,!(this.isSimpleMode()&&this.requestRender())&&this.virtualizer.instanceChanged(this,!areFileTargetsEqual(this.getRenderedFile(),nextRenderFile))}get isComponentManaged(){return this.getAdvancedVirtualizer()?.isComponentManaged??super.isComponentManaged}syncGhostTextRows(){const codeView=this.getAdvancedVirtualizer();codeView!=null?(codeView.capturePendingLayoutAnchor(),this.layoutDirty=!0,codeView.instanceChanged(this,!0)):this.getSimpleVirtualizer()?.requestHeightReconcile(this)}applyDocumentChange(textDocument,newLineAnnotations,shouldUpdateBuffer=!1){const{renderRange:previousRenderRange}=this;this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(textDocument,newLineAnnotations),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(this.isSimpleMode(),!1);const file=this.getRenderedFile();if(!this.isSimpleMode())this.computeApproximateSize(!0);else if(shouldUpdateBuffer&&previousRenderRange!=null&&file!=null){const windowSpecs=this.virtualizer.getWindowSpecs(),renderRange=this.computeRenderRangeFromWindow(file,this.top??0,windowSpecs);renderRange.bufferAfter!==previousRenderRange.bufferAfter&&this.updateBuffers(renderRange)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}render({fileContainer,file,forceRender=!1,lineAnnotations,...props}){const didFileChange=!areFileTargetsEqual(this.getInputFile(),file);didFileChange&&(this.updateInputFile(file,lineAnnotations),this.cachedHeaderHTML=void 0);const{pendingRenderFile,layoutFileChanged,renderedFileChanged,annotationsChanged}=this.pendingRender!=null&&this.pendingRender.workingFile===(this.getWorkingFile(file)??file)?{pendingRenderFile:this.pendingRender.file,layoutFileChanged:!1,renderedFileChanged:!1,annotationsChanged:this.syncLineAnnotations(lineAnnotations)}:this.updatePendingRender(file,lineAnnotations),{forceRenderOverride,isSetup}=this;if(this.forceRenderOverride=void 0,layoutFileChanged&&this.resetLayoutCache(),fileContainer=this.getOrCreateFileContainerNode(fileContainer),isSetup)this.top??=this.getVirtualizedTop(),this.layoutDirty&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,pendingRenderFile));else{this.computeApproximateSize(!1,pendingRenderFile);const virtualizer=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(virtualizer==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");virtualizer.connect(fileContainer,this),this.isVisible=virtualizer.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!didFileChange||!isSetup))return this.renderPlaceholder(this.height);const windowSpecs=this.virtualizer.getWindowSpecs(),fileTop=this.top??0,renderRange=this.computeRenderRangeFromWindow(pendingRenderFile,fileTop,windowSpecs);return super.render({file,fileContainer,renderRange,lineAnnotations,forceRender:(forceRenderOverride??forceRender)||annotationsChanged||renderedFileChanged||didFileChange,...props})}finalizeRender(){if(this.getRenderedFile()!==this.pendingRender?.file)throw new Error("VirtualizedFile.render: rendered a different file than its prepared layout");this.pendingRender=void 0,this.isSimpleMode()&&this.getSimpleVirtualizer()?.requestHeightReconcile(this)}updatePendingRender(nextFile,lineAnnotations){const workingFile=this.getWorkingFile(nextFile)??nextFile,previousRenderedFile=this.getRenderedFile(),previousLayoutFile=this.pendingRender?.file??previousRenderedFile,pendingRenderFile=this.fileRenderer.getFileForNextRender(workingFile);return this.pendingRender={workingFile,file:pendingRenderFile},{pendingRenderFile,annotationsChanged:this.syncLineAnnotations(lineAnnotations),layoutFileChanged:!areFileTargetsEqual(previousLayoutFile,pendingRenderFile),renderedFileChanged:!areFileTargetsEqual(previousRenderedFile,pendingRenderFile)}}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(lineIndex,top){lineIndex%LAYOUT_CHECKPOINT_INTERVAL===0&&this.cache.checkpoints.push({lineIndex,top})}getLayoutCheckpointBeforeLineIndex(lineIndex){if(lineIndex<=0||this.cache.checkpoints.length===0)return;let low=0,high=this.cache.checkpoints.length-1,result;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");checkpoint.lineIndex<=lineIndex?(result=checkpoint,low=mid+1):high=mid-1}return result}getLayoutCheckpointBeforeTop(top,hunkLineCount){let low=0,high=this.cache.checkpoints.length-1,resultIndex=-1;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");checkpoint.top<=top?(resultIndex=mid,low=mid+1):high=mid-1}if(hunkLineCount==null)return resultIndex>=0?this.cache.checkpoints[resultIndex]:void 0;for(let index=resultIndex;index>=0;index--){const checkpoint=this.cache.checkpoints[index];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(checkpoint.lineIndex%hunkLineCount===0)return checkpoint}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(file,fileTop,{top,bottom}){const{disableFileHeader=!1}=this.options,{hunkLineCount,lineHeight}=this.metrics,lineCount=this.fileRenderer.getLineCount(file),fileHeight=this.height,headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),paddingBottom=lineCount>0?getVirtualFilePaddingBottom(this.metrics):0,{fileAnnotationHeight}=this.cache,codeRegionTop=headerRegion+fileAnnotationHeight,codeRowsHeight=Math.max(0,fileHeight-headerRegion-fileAnnotationHeight-paddingBottom),hasFileAnnotations=includesFileAnnotations(this.getLayoutAnnotations()),fileAnnotationTop=fileTop+headerRegion,measuredFileAnnotationVisible=fileAnnotationHeight>0&&hasFileAnnotations&&fileAnnotationTop<bottom&&fileAnnotationTop+fileAnnotationHeight>top;if(fileTop<top-fileHeight||fileTop>bottom)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};if(lineCount<=hunkLineCount)return{startingLine:0,totalLines:hunkLineCount,bufferBefore:0,bufferAfter:0};const estimatedTargetLines=Math.ceil(Math.max(bottom-top,0)/lineHeight),totalLines=Math.ceil(estimatedTargetLines/hunkLineCount)*hunkLineCount+hunkLineCount,totalHunks=totalLines/hunkLineCount,viewportCenter=(top+bottom)/2;if(this.hasUniformLineHeights()){const sourceRowsTop=fileTop+codeRegionTop,sourceRowsBottom=sourceRowsTop+codeRowsHeight;if(!measuredFileAnnotationVisible&&!(sourceRowsTop<bottom&&sourceRowsBottom>top))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};const centerLine=Math.floor(measuredFileAnnotationVisible&&viewportCenter<fileTop+codeRegionTop?0:(viewportCenter-(fileTop+codeRegionTop))/lineHeight),idealStartHunk2=Math.floor(centerLine/hunkLineCount)-Math.floor(totalHunks/2),totalHunksInFile=Math.ceil(lineCount/hunkLineCount),startingLine2=Math.max(0,Math.min(idealStartHunk2,totalHunksInFile))*hunkLineCount,clampedTotalLines2=idealStartHunk2<0?totalLines+idealStartHunk2*hunkLineCount:totalLines,bufferBefore2=startingLine2===0?0:fileAnnotationHeight+startingLine2*lineHeight,renderedLines=Math.min(clampedTotalLines2,lineCount-startingLine2);return{startingLine:startingLine2,totalLines:clampedTotalLines2,bufferBefore:bufferBefore2,bufferAfter:Math.max(0,(lineCount-startingLine2-renderedLines)*lineHeight)}}const overflowHunks=totalHunks,hunkOffsets=[],checkpoint=this.getLayoutCheckpointBeforeTop(Math.max(0,top-fileTop-totalLines*lineHeight*2),hunkLineCount);let absoluteLineTop=fileTop+(checkpoint?.top??codeRegionTop),currentLine=checkpoint?.lineIndex??0,firstVisibleHunk,centerHunk,overflowCounter;const startingLineIndex=checkpoint?.lineIndex??0;for(let lineIndex=startingLineIndex;lineIndex<lineCount;lineIndex++){const isAtHunkBoundary=currentLine%hunkLineCount===0,currentHunk=Math.floor(currentLine/hunkLineCount);if(isAtHunkBoundary&&(hunkOffsets[currentHunk]=absoluteLineTop-(fileTop+codeRegionTop),overflowCounter!=null)){if(overflowCounter<=0)break;overflowCounter--}const lineHeight2=this.getLineHeight(lineIndex,!1);absoluteLineTop>top-lineHeight2&&absoluteLineTop<bottom&&(firstVisibleHunk??=currentHunk),absoluteLineTop+lineHeight2>viewportCenter&&(centerHunk??=currentHunk),overflowCounter==null&&absoluteLineTop>=bottom&&isAtHunkBoundary&&(overflowCounter=overflowHunks),currentLine++,absoluteLineTop+=lineHeight2}if(firstVisibleHunk==null)if(measuredFileAnnotationVisible)firstVisibleHunk=0,centerHunk=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};centerHunk??=firstVisibleHunk;const idealStartHunk=Math.round(centerHunk-totalHunks/2),maxStartHunk=Math.max(0,Math.ceil(lineCount/hunkLineCount)-totalHunks),startHunk=Math.max(0,Math.min(idealStartHunk,maxStartHunk)),startingLine=startHunk*hunkLineCount,clampedTotalLines=idealStartHunk<0?totalLines+idealStartHunk*hunkLineCount:totalLines,codeBufferBefore=hunkOffsets[startHunk]??0,bufferBefore=startingLine===0?0:fileAnnotationHeight+codeBufferBefore,finalHunkIndex=startHunk+clampedTotalLines/hunkLineCount,bufferAfter=finalHunkIndex<hunkOffsets.length?codeRowsHeight-hunkOffsets[finalHunkIndex]:codeRowsHeight-(absoluteLineTop-fileTop-codeRegionTop);return{startingLine,totalLines:clampedTotalLines,bufferBefore,bufferAfter:Math.max(0,bufferAfter)}}};function measureFileAnnotationHeight(content){let height;for(const child of content.children)child instanceof HTMLElement&&child.dataset.lineAnnotation===FILE_ANNOTATION_DOM_KEY&&(height=Math.max(height??0,child.getBoundingClientRect().height));return height}const DEFAULT_EDIT_STACK_MAX_ENTRIES=100,COALESCING_MODE_INSERT="insert",COALESCING_MODE_BACKSPACE="backspace",COALESCING_MODE_DELETE="delete";var EditStack=class EditStack2{#undoStack=[];#redoStack=[];#maxEntries;#canCoalesce=!1;constructor(options){this.#maxEntries=Math.max(1,options?.maxEntries??DEFAULT_EDIT_STACK_MAX_ENTRIES)}get canUndo(){return this.#undoStack.length>0}get canRedo(){return this.#redoStack.length>0}getState(){return{undoStack:this.#undoStack.map(cloneEditStackEntryForState),redoStack:this.#redoStack.map(cloneEditStackEntryForState),maxEntries:this.#maxEntries,canCoalesce:this.#canCoalesce}}getLiveState(){return Object.defineProperties({},{undoStack:{enumerable:!0,get:()=>this.#undoStack},redoStack:{enumerable:!0,get:()=>this.#redoStack},maxEntries:{enumerable:!0,get:()=>this.#maxEntries},canCoalesce:{enumerable:!0,get:()=>this.#canCoalesce}})}static fromState(state){const stack=new EditStack2({maxEntries:state.maxEntries});return stack.#undoStack=state.undoStack,stack.#redoStack=state.redoStack,stack.#canCoalesce=state.canCoalesce,stack}clear(){this.#undoStack.length=0,this.#redoStack.length=0,this.#canCoalesce=!1}clearRedo(){this.#redoStack.length=0}push(entry){this.#undoStack.push(entry),this.clearRedo(),this.#canCoalesce=!0,this.#undoStack.length>this.#maxEntries&&this.#undoStack.shift()}setLastUndoSelectionsAfter(selections){const lastEntry=this.#undoStack[this.#undoStack.length-1];lastEntry!==void 0&&(lastEntry.selectionsAfter=selections.map(selection=>({...selection})))}setLastUndoLineAnnotations(lineAnnotationsBefore,lineAnnotationsAfter){const lastEntry=this.#undoStack[this.#undoStack.length-1];lastEntry!==void 0&&(lastEntry.lineAnnotationsBefore=lineAnnotationsBefore.slice(),lastEntry.lineAnnotationsAfter=lineAnnotationsAfter.slice())}peekUndo(){return this.#undoStack[this.#undoStack.length-1]}peekUndoForCoalescing(){return this.#canCoalesce?this.peekUndo():void 0}replaceLastUndo(entry){if(this.#undoStack.length===0){this.push(entry);return}this.#undoStack[this.#undoStack.length-1]=entry,this.clearRedo(),this.#canCoalesce=!0}popUndoToRedo(){const entry=this.#undoStack.pop();if(entry!==void 0)return this.#redoStack.push(entry),this.#canCoalesce=!1,entry}popRedoToUndo(){const entry=this.#redoStack.pop();if(entry!==void 0)return this.#undoStack.push(entry),this.#canCoalesce=!1,entry}};function cloneEditStackEntry(entry){return{...entry,forwardEdits:entry.forwardEdits.map(edit=>({...edit})),inverseEdits:entry.inverseEdits.map(edit=>({...edit})),selectionsBefore:entry.selectionsBefore?.map(cloneSelection),selectionsAfter:entry.selectionsAfter?.map(cloneSelection),lineAnnotationsBefore:entry.lineAnnotationsBefore?.slice(),lineAnnotationsAfter:entry.lineAnnotationsAfter?.slice()}}function cloneEditStackEntryForState(entry){return{...cloneEditStackEntry(entry),lineAnnotationsBefore:entry.lineAnnotationsBefore?.map(annotation=>({...annotation})),lineAnnotationsAfter:entry.lineAnnotationsAfter?.map(annotation=>({...annotation}))}}function cloneSelection(selection){return{...selection,start:{...selection.start},end:{...selection.end}}}function createEditStackEntry(textDocument,resolvedEdits,versionBefore,versionAfter,selectionsBefore,selectionsAfter,lineAnnotationsBefore,lineAnnotationsAfter){const forwardEdits=[...resolvedEdits].sort((a,b)=>a.start-b.start),inverseEdits=[];let coalescingMode;if(selectionsBefore?.length===forwardEdits.length){const caretOffsets=[];for(const selection of selectionsBefore){if(selection.start.line!==selection.end.line||selection.start.character!==selection.end.character)break;caretOffsets.push(textDocument.offsetAt(selection.start))}if(caretOffsets.length===forwardEdits.length){caretOffsets.sort((a,b)=>a-b);let isBackspace=!0,isDelete=!0;for(let i=0;i<forwardEdits.length;i++){const edit=forwardEdits[i];if(edit.text.length>0||edit.start===edit.end){isBackspace=!1,isDelete=!1;break}isBackspace&&=caretOffsets[i]===edit.end,isDelete&&=caretOffsets[i]===edit.start}coalescingMode=isBackspace?COALESCING_MODE_BACKSPACE:isDelete?COALESCING_MODE_DELETE:void 0}}for(let i=0,offsetDelta=0;i<forwardEdits.length;i++){const edit=forwardEdits[i],replacedText=textDocument.getTextSlice(edit.start,edit.end),startAfterEdit=edit.start+offsetDelta;inverseEdits.push({start:startAfterEdit,end:startAfterEdit+edit.text.length,text:replacedText}),offsetDelta+=edit.text.length-(edit.end-edit.start)}return{forwardEdits:forwardEdits.map(edit=>({...edit})),inverseEdits,versionBefore,versionAfter,selectionsBefore:selectionsBefore?.map(selection=>({...selection})),selectionsAfter:selectionsAfter?.map(selection=>({...selection})),lineAnnotationsBefore:lineAnnotationsBefore?.slice(),lineAnnotationsAfter:lineAnnotationsAfter?.slice(),coalescingMode}}function shouldCoalesceEditStackEntry(previousEntry,nextEntry){if(previousEntry===void 0||previousEntry.undoBoundary===!0||nextEntry.undoBoundary===!0||previousEntry.forwardEdits.length===0||previousEntry.forwardEdits.length!==previousEntry.inverseEdits.length||previousEntry.forwardEdits.length!==nextEntry.forwardEdits.length||nextEntry.forwardEdits.length!==nextEntry.inverseEdits.length)return!1;let mode;for(let i=0;i<previousEntry.forwardEdits.length;i++){const previousForward=previousEntry.forwardEdits[i],previousInverse=previousEntry.inverseEdits[i],nextForward=nextEntry.forwardEdits[i],nextInverse=nextEntry.inverseEdits[i],mappedNextStart=mapOffsetAfterForwardBatchToBefore(nextForward.start,previousEntry.forwardEdits),previousWasInsert=previousForward.start<=previousForward.end&&previousForward.text.length>0&&!previousForward.text.includes(`
1
+ import{j as jsxRuntimeExports,r as reactExports}from"./vendor-react-CxJ4vs-5.js";import{ap as useEditorEnvironment,bs as useLatest,t as useLabels,H as buttonClass}from"./kit-CD3F-f6F.js";import{i as isFullyTransparent,s as surfacesMatch,j as relativeLuminance,p as pickReadableForeground,k as isDarkSurface,l as hoverWouldEraseText,m as deriveMutedFg,n as contrastRatio,o as compositeOverBg,D as DEFAULT_THEMES,q as areFileRenderOptionsEqual,t as isFilePlainText,v as getHighlighterIfLoaded,w as getFiletypeFromFileName,H as HighlighterDisposedError,x as linesFromFileContents,y as DEFAULT_RENDER_RANGE,z as areThemesAttached,B as areLanguagesAttached,C as renderFileWithHighlighter,E as createGutterGap,F as createGutterItem,G as createHastElement,I as getSharedHighlighter,J as createGutterWrapper,K as EMPTY_LINE_ANNOTATIONS,L as areThemesEqual,M as getThemes,N as EMPTY_RENDER_RANGE,O as isHandledWorkerPoolError,Q as CUSTOM_HEADER_SLOT_ID,S as HEADER_PREFIX_SLOT_ID,T as HEADER_FILENAME_SUFFIX_SLOT_ID,U as HEADER_METADATA_SLOT_ID,V as DEFAULT_VIRTUAL_FILE_METRICS,X as computeVirtualFileMetrics,Y as getVirtualFileHeaderHeight,Z as getVirtualFileHeaderRegion,_ as getVirtualFilePaddingBottom,$ as computeLineOffsets,a0 as countLineBreaks,a1 as LRUMapPkg,a2 as WorkerPoolContext,a3 as DIFFS_TAG_NAME,P as PREFERRED_HIGHLIGHTER,a4 as DIFFS_UNSAFE_CSS,a5 as DIFFS_HOST_STYLE,a6 as VIRTUALIZER_CONFIG,a7 as DEFAULT_TOKENIZE_MAX_LENGTH}from"./pierre-theme-BrzM0xZU.js";import{g as getLineAnnotationName,a as areFileTargetsEqual,b as applyLineTextWithNewline,c as areRenderRangesEqual,i as isDefaultRenderRange,e as shouldRenderFileAnnotations,f as getFileAnnotations,h as createAnnotationElement,j as createFileHeaderElement,k as createContentColumn,l as getHighlighterOptions,r as resolvePreferredHighlighter,m as createPreElement,n as shouldUseTokenTransformer,R as ResizeManager,I as InteractionManager,p as pluckInteractionOptions,o as resolveEditSessionSlotName,q as adoptEditSessionAnnotations,w as writeEditSessionAnnotations,t as prerenderHTMLIfNecessary,v as createAnnotationWrapperNode,x as createGutterUtilityContentNode,y as createUnsafeCSSStyleNode,z as wrapUnsafeCSS,A as getMeasuredScrollbarGutter,B as upsertHostThemeStyle,C as wrapThemeCSS,D as patchScrollbarGutterSize,E as isSafari,G as getOrCreateCodeNode,H as guardWebKitScrollDuringRebuild,J as isStyleNode,S as SVGSpriteSheet$1,K as arePrePropertiesEqual,L as setPreNodeProperties,M as areObjectsEqual,N as areOptionsEqual,O as includesFileAnnotations,P as FILE_ANNOTATION_DOM_KEY,Q as isMacLike,T as recordLineAnnotationSource,U as getLineAnnotationSource,V as cloneHunks,W as dequeueRender,X as queueRender,Y as isGutterUtilityPath,Z as GutterUtilitySlotStyles,_ as useVirtualizer,$ as useCreateEditor,a0 as useStableCallback,a1 as useForceUpdate,a2 as useNextRenderData,a3 as noopRender,a4 as templateRender,a5 as useDetachCleanup,a6 as revealOnHighlight,a7 as scrollReachOnRender,a8 as EditProvider,a9 as Virtualizer,u as useFind,aa as fileLines,F as FindBar}from"./useFind-Cdl0rVJO.js";import{a as addEventListener,g as getLineNumberAttr,h,e as endsWithLineBreak,b as getGraphemeSegmenter,c as createSegmenter,r as round,f as extend,l as lookupScrollContainer,i as clampDomOffset}from"./utils-qCteL8MB.js";import{h as hastToHtml}from"./hastToHtml-C4ea9WpN.js";const colorUtils={compositeOverBg,contrastRatio,deriveMutedFg,hoverWouldEraseText,isDarkSurface,isFullyTransparent,pickReadableForeground,relativeLuminance,surfacesMatch};function isLineCacheForFile(lineCache,file){return file.cacheKey==null?lineCache.file===file&&lineCache.sourceContents===file.contents:lineCache.cacheKey===file.cacheKey}let instanceId$2=-1;var FileRenderer=class{options;annotationSlotName;onRenderUpdate;workerManager;__id=`file-renderer:${++instanceId$2}`;file;renderCache;pendingHighlightResult;computedLang="text";lineAnnotations={};lineCache;pendingStructuralRows;textDocumentCache=new WeakMap;ownedRows=new WeakSet;editSessionActive=!1;get fileCache(){return this.renderCache?.file}constructor(options={theme:DEFAULT_THEMES},annotationSlotName=getLineAnnotationName,onRenderUpdate,workerManager){this.options=options,this.annotationSlotName=annotationSlotName,this.onRenderUpdate=onRenderUpdate,this.workerManager=workerManager}setOptions(options){this.options=options}mergeOptions(options){this.options={...this.options,...options}}setLineAnnotations(lineAnnotations){this.lineAnnotations={};for(const annotation of lineAnnotations){const arr=this.lineAnnotations[annotation.lineNumber]??[];this.lineAnnotations[annotation.lineNumber]=arr,arr.push(annotation)}}cleanUp(){this.endEditSession(),this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}beginEditSession(file,externalFile){const{editSessionActive:wasAlreadyActive,renderCache}=this;if(this.editSessionActive=!0,wasAlreadyActive||(this.pendingHighlightResult=void 0),this.file=file,renderCache==null||wasAlreadyActive&&renderCache.file===file)return;if(wasAlreadyActive){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}const{options}=this.getRenderOptions(file),cacheBelongsToSession=renderCache.file===file,cacheBelongsToExternal=externalFile!=null&&areFileTargetsEqual(renderCache.file,externalFile),{result}=renderCache;if(!renderCache.highlighted||result==null||!areFileRenderOptionsEqual(renderCache.options,options)||!cacheBelongsToSession&&!cacheBelongsToExternal){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}if(cacheBelongsToSession)return;this.renderCache={...renderCache,file,result:{...result,code:[...result.code]}};const{lineCache}=this;lineCache!=null&&externalFile!=null&&isLineCacheForFile(lineCache,externalFile)?this.lineCache={cacheKey:void 0,file,sourceContents:file.contents,lines:lineCache.lines}:this.lineCache=void 0}endEditSession(settledFile){if(this.editSessionActive=!1,this.pendingHighlightResult=void 0,this.file==null){this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap;return}const{renderCache}=this;settledFile==null||renderCache==null||renderCache.file===settledFile||!areFileTargetsEqual(renderCache.file,settledFile)||(renderCache.file=settledFile)}editorRenderReady(){return this.renderCache?.options.useTokenTransformer===!0&&this.renderCache.highlighted&&this.renderCache.result!=null}recycle(){this.editSessionActive?(this.renderCache!=null&&(this.renderCache.renderRange=void 0),this.pendingHighlightResult=void 0,this.pendingStructuralRows=void 0):(this.clearRenderCache(),this.lineCache=void 0,this.textDocumentCache=new WeakMap),this.workerManager?.cleanUpTasks(this),this.file=void 0}clearRenderCache(){this.pendingStructuralRows=void 0,this.renderCache=void 0,this.pendingHighlightResult=void 0}hydrate(file){this.file=file;const{options}=this.getRenderOptions(file),massiveFile=isFileMassive(this.getOrCreateLineCache(file).length,this.getTokenizeMaxLength());let cache=this.workerManager?.getFileResultCache(file);cache!=null&&!areFileRenderOptionsEqual(options,cache.options)&&(cache=void 0),this.renderCache??={file,hydrated:!0,options,highlighted:!massiveFile&&!isFilePlainText(file),result:massiveFile?void 0:cache?.result,renderRange:void 0};const workerManager=this.getHighlightWorkerManager(file);workerManager!=null?this.renderCache.result==null&&!massiveFile&&workerManager.highlightFileAST(this,file):getHighlighterIfLoaded({theme:this.getLocalHighlightTheme()})==null&&(this.computedLang=file.lang??getFiletypeFromFileName(file.name),this.initializeHighlighter().catch(error=>{error instanceof HighlighterDisposedError||this.onHighlightError(error)}))}getHighlightWorkerManager(file){const{editSessionActive,workerManager}=this;return!editSessionActive&&workerManager?.isWorkingPool()===!0&&!workerManager.shouldHighlightOnMainThread(file)?workerManager:void 0}cacheHighlightResult(file,renderResult){const{editSessionActive,workerManager}=this;!editSessionActive&&workerManager?.isWorkingPool()===!0&&workerManager.setFileResultCache(file.cacheKey,renderResult)}getLocalHighlightTheme(){return this.workerManager?.getFileRenderOptions().theme??this.options.theme??DEFAULT_THEMES}getEffectiveCodeOptions(){const poolOptions=this.workerManager?.isWorkingPool()===!0?this.workerManager.getFileRenderOptions():void 0;return{theme:this.getLocalHighlightTheme(),tokenizeMaxLineLength:poolOptions?.tokenizeMaxLineLength??this.options.tokenizeMaxLineLength}}getRenderOptions(file){const options=(()=>{if(this.workerManager?.isWorkingPool()===!0){const poolOptions=this.workerManager.getFileRenderOptions();return this.editSessionActive&&poolOptions.useTokenTransformer!==!0?{...poolOptions,useTokenTransformer:!0}:poolOptions}const{tokenizeMaxLineLength=1e3}=this.options;return{theme:this.getLocalHighlightTheme(),useTokenTransformer:this.editSessionActive||this.options.useTokenTransformer===!0,tokenizeMaxLineLength}})(),{renderCache}=this;return renderCache?.result==null?{options,forceHighlight:!0}:!areFileTargetsEqual(file,renderCache.file)||!areFileRenderOptionsEqual(options,renderCache.options)?{options,forceHighlight:!0}:{options,forceHighlight:!1}}getFileForNextRender(file){const{options}=this.getRenderOptions(file);if(this.getReadyRenderResult(file,options)!=null)return file;const{renderCache}=this;if(renderCache==null)return file;if(areFileTargetsEqual(renderCache.file,file))return renderCache.file;const lines=linesFromFileContents(file.contents),forcePlainText=file.contents.length===0||isFilePlainText(file)||isFileMassive(lines.length,this.getTokenizeMaxLength());return this.canRenderFile(file,options,forcePlainText)?file:renderCache.file}canRenderFile(file,options,forcePlainText){const{renderCache}=this;return renderCache==null||areFileTargetsEqual(renderCache.file,file)?!0:forcePlainText?renderCache.result==null&&renderCache.hydrated!==!0||this.workerManager?.isWorkingPool()===!0&&!this.workerManager.shouldHighlightOnMainThread(file)||getHighlighterIfLoaded({theme:options.theme})!=null:renderCache.result==null&&renderCache.hydrated!==!0?!0:this.getHighlightWorkerManager(file)!=null?!renderCache.highlighted:getHighlighterIfLoaded({theme:options.theme})!=null}getOrCreateLineCache(file){let{lineCache}=this;return(lineCache==null||!isLineCacheForFile(lineCache,file))&&(lineCache={cacheKey:file.cacheKey,file,sourceContents:file.contents,lines:linesFromFileContents(file.contents)}),this.lineCache=lineCache,lineCache.lines}getLineCount(file){const lines=this.getOrCreateLineCache(file);return this.textDocumentCache.get(file)?.lineCount??lines.length}updateRenderCache(dirtyLines,themeType,lineCountChangeInFlight=!1){this.pendingStructuralRows=void 0;const{renderCache}=this;if(renderCache==null)return;const{file,result}=renderCache;if(result==null)return;const pendingStructuralRows=lineCountChangeInFlight?new Map:void 0;this.pendingStructuralRows=pendingStructuralRows;const lineCache=this.lineCache!=null&&isLineCacheForFile(this.lineCache,file)?this.lineCache:void 0;for(const[line,tokens]of dirtyLines){if(pendingStructuralRows==null&&lineCache!=null&&line<lineCache.lines.length){const lineText=tokens.map(token=>token[2]).join("");lineCache.lines[line]=applyLineTextWithNewline(lineCache.lines[line]??"",lineText)}const row={type:"element",tagName:"div",properties:{"data-line":line+1,"data-line-type":"context","data-line-index":line},children:tokens.map(([char,fg,text])=>char===0&&fg===""?text===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:text}:{type:"element",tagName:"span",properties:{"data-char":char,style:`color:${fg};`},children:[{type:"text",value:text}]})};this.ownedRows.add(row),pendingStructuralRows!=null?pendingStructuralRows.set(line,row):result.code[line]=row}result.baseThemeType=themeType,renderCache.isDirty=!0,pendingStructuralRows==null&&lineCache!=null&&(file.contents=lineCache.lines.join(""),lineCache.sourceContents=file.contents)}applyDocumentChange(textDocument){const{pendingStructuralRows,renderCache}=this;this.pendingStructuralRows=void 0;const file=this.file??renderCache?.file;if(file==null)return;const result=renderCache?.result,previousLines=this.lineCache!=null&&isLineCacheForFile(this.lineCache,file)?this.lineCache.lines:linesFromFileContents(file.contents),nextLines=linesFromFileContents(textDocument.getText());if(result!=null&&previousLines.length!==nextLines.length){const maxShared=Math.min(previousLines.length,nextLines.length);let prefix=0;for(;prefix<maxShared&&previousLines[prefix]===nextLines[prefix];)prefix++;let suffix=0;for(;suffix<maxShared-prefix&&previousLines[previousLines.length-1-suffix]===nextLines[nextLines.length-1-suffix];)suffix++;const previousCode=result.code;result.code=new Array(nextLines.length);for(let i=0;i<prefix;i++)result.code[i]=previousCode[i];for(let i=0;i<suffix;i++)result.code[nextLines.length-1-i]=previousCode[previousLines.length-1-i];if(pendingStructuralRows!==void 0)for(const[line,row]of pendingStructuralRows)line<nextLines.length&&(result.code[line]=row);for(let i=prefix;i<nextLines.length-suffix;i++)result.code[i]??=this.ownRow({type:"element",tagName:"div",properties:{"data-line":i+1,"data-line-type":"context","data-line-index":i},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:textDocument.getLineText(i)}]}]});for(let i=0;i<result.code.length;i++){const line=result.code[i];if(line?.type==="element"&&(line.properties["data-line"]!==i+1||line.properties["data-line-index"]!==i)){const row=this.ownedRows.has(line)?line:this.ownRow({...line,properties:{...line.properties}});row.properties["data-line"]=i+1,row.properties["data-line-index"]=i,result.code[i]=row}}renderCache!=null&&(renderCache.isDirty=!0)}const contents=textDocument.getText();this.lineCache={cacheKey:file.cacheKey,file,sourceContents:contents,lines:nextLines},this.textDocumentCache.set(file,textDocument),file.contents=contents}ownRow(row){return this.ownedRows.add(row),row}renderFile(file=this.file,renderRange=DEFAULT_RENDER_RANGE){if(this.file=file,file==null){this.pendingHighlightResult=void 0;return}let{options,forceHighlight}=this.getRenderOptions(file);const readyResult=this.getReadyRenderResult(file,options);this.pendingHighlightResult=void 0,readyResult!=null&&(this.renderCache={...readyResult,file,renderRange:void 0},forceHighlight=!1),this.renderCache??={file,highlighted:!1,options,result:void 0,renderRange:void 0};const lines=this.getOrCreateLineCache(file),hasContent=file.contents.length>0,forcePlainText=!hasContent||isFilePlainText(file)||isFileMassive(lines.length,this.getTokenizeMaxLength()),canRenderFile=this.canRenderFile(file,options,forcePlainText),newContent=!areFileTargetsEqual(file,this.renderCache.file),newRenderRange=!areRenderRangesEqual(this.renderCache.renderRange,renderRange),workerManager=this.getHighlightWorkerManager(file);if(workerManager!=null){const preserveHydratedContent=this.renderCache.result==null&&this.renderCache.highlighted&&!forcePlainText&&!newContent&&isDefaultRenderRange(renderRange);canRenderFile&&!preserveHydratedContent&&(forcePlainText||this.renderCache.result==null||!this.renderCache.highlighted&&(newContent||newRenderRange))&&(this.renderCache.file=file,this.renderCache.options=options,this.renderCache.highlighted=!1,(this.renderCache.result==null||newContent||newRenderRange||forceHighlight)&&(this.renderCache.result=workerManager.getPlainFileAST(file,renderRange.startingLine,renderRange.totalLines,lines)),this.renderCache.renderRange=renderRange),!forcePlainText&&hasContent&&(!this.renderCache.highlighted||forceHighlight)&&workerManager.highlightFileAST(this,file)}else{this.computedLang=file.lang??getFiletypeFromFileName(file.name);const highlighter=getHighlighterIfLoaded(),hasThemes=highlighter!=null&&areThemesAttached(options.theme,highlighter),hasLangs=highlighter!=null&&areLanguagesAttached(this.computedLang,highlighter),canHighlight=!forcePlainText&&hasLangs,lazyLineAST=Number.isFinite(renderRange.totalLines);if(canRenderFile&&highlighter!=null&&hasThemes&&(forceHighlight||forcePlainText||!this.renderCache.highlighted&&canHighlight||this.renderCache.result==null)){const{result,options:options2}=this.renderFileWithHighlighter(file,highlighter,forcePlainText||!hasLangs,lazyLineAST);this.renderCache={file,options:options2,highlighted:canHighlight,result,renderRange:void 0},canHighlight&&this.cacheHighlightResult(file,{result,options:options2})}(!hasThemes||!forcePlainText&&!hasLangs)&&this.asyncHighlight(file,lazyLineAST).then(({result,options:options2})=>{forcePlainText||this.cacheHighlightResult(file,{result,options:options2}),this.applyHighlightResult(file,result,options2,!forcePlainText)}).catch(error=>{error instanceof HighlighterDisposedError||this.onHighlightError(error)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,renderRange,this.renderCache.result):void 0}async asyncRender(file,renderRange=DEFAULT_RENDER_RANGE){this.file=file;const{result}=await this.asyncHighlight(file,Number.isFinite(renderRange.totalLines));return this.processFileResult(file,renderRange,result)}async asyncHighlight(file,lazyLineAST=!1){const forcePlainText=isFileMassive(this.getOrCreateLineCache(file).length,this.getTokenizeMaxLength());this.computedLang=forcePlainText?"text":file.lang??getFiletypeFromFileName(file.name);let highlighter=getHighlighterIfLoaded();const hasThemes=highlighter!=null&&areThemesAttached(this.getLocalHighlightTheme(),highlighter),hasLangs=forcePlainText||highlighter!=null&&areLanguagesAttached(this.computedLang,highlighter);return(highlighter==null||!hasThemes||!hasLangs)&&(highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(file,highlighter,forcePlainText,lazyLineAST)}renderFileWithHighlighter(file,highlighter,forcePlainText=!1,lazyLineAST=!1){const{options}=this.getRenderOptions(file);return{result:renderFileWithHighlighter(file,highlighter,options,{forcePlainText,lazyLineAST}),options}}processFileResult(file,renderRange,{code,themeStyles,baseThemeType}){const totalLines=this.getLineCount(file),{disableFileHeader=!1}=this.options,contentArray=[],gutter=createGutterWrapper(),endLine=Math.min(renderRange.startingLine+renderRange.totalLines,totalLines);let rowCount=0;const fileLevelAnnotations=shouldRenderFileAnnotations(renderRange)?getFileAnnotations(this.lineAnnotations):void 0;fileLevelAnnotations!=null&&(gutter.children.push(createGutterGap("context","annotation",1)),contentArray.push(createAnnotationElement({hunkIndex:-1,lineIndex:-1,annotations:fileLevelAnnotations.map(annotation=>this.annotationSlotName(annotation))})),rowCount++);for(let lineIndex=renderRange.startingLine;lineIndex<endLine;lineIndex++){const lineNumber=lineIndex+1,line=code[lineIndex];if(line==null){const message="FileRenderer.processFileResult: Line doesnt exist";throw console.error(message,{name:file.name,lineIndex,lineNumber}),new Error(message)}gutter.children.push(createGutterItem("context",lineNumber,`${lineIndex}`)),contentArray.push(line),rowCount++;const annotations=this.lineAnnotations[lineNumber];annotations!=null&&(gutter.children.push(createGutterGap("context","annotation",1)),contentArray.push(createAnnotationElement({hunkIndex:0,lineIndex:lineNumber,annotations:annotations.map(annotation=>this.annotationSlotName(annotation))})),rowCount++)}return gutter.properties.style=`grid-row: span ${rowCount}`,{file,gutterAST:gutter.children??[],contentAST:contentArray,preAST:this.createPreElement(totalLines),headerAST:disableFileHeader?void 0:this.renderHeader(file),totalLines,rowCount,themeStyles,baseThemeType,bufferBefore:renderRange.bufferBefore,bufferAfter:renderRange.bufferAfter,css:""}}renderHeader(file){const{headerRenderMode="default",stickyHeader=!1}=this.options;return createFileHeaderElement({fileOrDiff:file,mode:headerRenderMode,stickyHeader})}renderFullHTML(result){return hastToHtml(this.renderFullAST(result))}renderFullAST(result,children=[]){return children.push(createHastElement({tagName:"code",children:this.renderCodeAST(result),properties:{"data-code":""}})),{...result.preAST,children}}renderCodeAST(result){const gutter=createGutterWrapper();return gutter.children=result.gutterAST,gutter.properties.style=`grid-row: span ${result.rowCount}`,[gutter,createContentColumn(result.contentAST,result.rowCount)]}renderPartialHTML(children,includeCodeNode=!1){return includeCodeNode?hastToHtml(createHastElement({tagName:"code",children,properties:{"data-code":""}})):hastToHtml(children)}initializeHighlighter(){return getSharedHighlighter(getHighlighterOptions(this.computedLang,{theme:this.getLocalHighlightTheme(),preferredHighlighter:resolvePreferredHighlighter(this.workerManager,this.options)}))}onHighlightSuccess(file,result,options,highlighted=!0){this.editSessionActive||this.applyHighlightResult(file,result,options,highlighted)}applyHighlightResult(file,result,options,highlighted=!0){const{file:currentFile,renderCache}=this;currentFile==null||renderCache==null||!areFileTargetsEqual(file,currentFile)||!areFileRenderOptionsEqual(options,this.getRenderOptions(currentFile).options)||(renderCache.result==null||!renderCache.highlighted||!areFileRenderOptionsEqual(renderCache.options,options)||!areFileTargetsEqual(renderCache.file,currentFile))&&(this.pendingHighlightResult={file:currentFile,options,highlighted,result},this.onRenderUpdate?.())}getMatchingWorkerResultCache(file,options){if(this.editSessionActive)return;const cache=this.workerManager?.getFileResultCache(file);if(!(cache==null||!areFileRenderOptionsEqual(options,cache.options)))return cache}getReadyRenderResult(file,options){const{pendingHighlightResult}=this;if(pendingHighlightResult!=null&&areFileTargetsEqual(pendingHighlightResult.file,file)&&areFileRenderOptionsEqual(pendingHighlightResult.options,options))return pendingHighlightResult;const workerCache=this.getMatchingWorkerResultCache(file,options);if(!(workerCache==null||this.hasHighlightedRenderCache(file,options)))return{file,highlighted:!0,...workerCache}}hasHighlightedRenderCache(file,options){const{renderCache}=this;return renderCache?.result!=null&&renderCache.highlighted&&areFileTargetsEqual(file,renderCache.file)&&areFileRenderOptionsEqual(options,renderCache.options)}onHighlightError(error){console.error(error)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(totalLines){const{disableLineNumbers=!1,overflow="scroll"}=this.options;return createPreElement({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers,overflow,split:!1,totalLines})}};function isFileMassive(lineCount,tokenizeMaxLength){return lineCount>tokenizeMaxLength}function areLineAnnotationsEqual(annotationA,annotationB){return annotationA.lineNumber===annotationB.lineNumber&&annotationA.metadata===annotationB.metadata}function getFileRendererOptions(options){return{theme:options?.theme,disableLineNumbers:options?.disableLineNumbers,overflow:options?.overflow,themeType:options?.themeType,collapsed:options?.collapsed,disableFileHeader:options?.disableFileHeader,disableVirtualizationBuffers:options?.disableVirtualizationBuffers,stickyHeader:options?.stickyHeader,preferredHighlighter:options?.preferredHighlighter,useCSSClasses:options?.useCSSClasses,useTokenTransformer:shouldUseTokenTransformer(options),tokenizeMaxLineLength:options?.tokenizeMaxLineLength,tokenizeMaxLength:options?.tokenizeMaxLength,unsafeCSS:options?.unsafeCSS,headerRenderMode:options?.renderCustomHeader!=null?"custom":"default"}}const EMPTY_STRINGS=[""];function createEditSessionFile(file){const editSessionFile={...file};return delete editSessionFile.cacheKey,editSessionFile}let instanceId$1=-1;var File$1=class{options;workerManager;requestOwnerRender;static LoadedCustomComponent=!0;__id=`file:${++instanceId$1}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;get lineAnnotations(){return this.renderedData?.lineAnnotations??EMPTY_LINE_ANNOTATIONS}managersDirty=!1;file;editSession;renderedData;pendingData;forceRenderOverride;renderRange;enabled=!0;editor;constructor(options={theme:DEFAULT_THEMES},workerManager,requestOwnerRender){this.options=options,this.workerManager=workerManager,this.requestOwnerRender=requestOwnerRender,this.fileRenderer=new FileRenderer(options,this.getAnnotationSlotName,this.handleHighlightRender,this.workerManager),this.resizeManager=new ResizeManager,this.interactionManager=new InteractionManager("file",pluckInteractionOptions(options)),this.workerManager?.subscribeToThemeChanges(this)}getAnnotationSlotName=annotation=>resolveEditSessionSlotName(this.editSession?.annotations,annotation,getLineAnnotationName);handleHighlightRender=()=>{this.rerender()};rerender(){const file=this.getInputFile();!this.enabled||file==null||this.requestRender()||this.render({file,forceRender:!0,renderRange:this.renderRange})}requestRender(){const{requestOwnerRender}=this;return this.editSession!=null||requestOwnerRender==null?!1:(this.forceRenderOverride=!0,requestOwnerRender(),!0)}get isComponentManaged(){return this.requestOwnerRender!=null}getTheme(){return this.workerManager?.getFileRenderOptions().theme??this.options.theme??DEFAULT_THEMES}getInputFile(){return this.file}getWorkingFile(fallbackFile=this.file){return this.editSession?.file??fallbackFile}getRenderedFile(){return this.renderedData?.file}__getNextRenderData({file,lineAnnotations}){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null)return{file,lineAnnotations:lineAnnotations!=null&&this.isNewAnnotations(lineAnnotations)?lineAnnotations:sessionAnnotations.provided};const workingFile=this.getWorkingFile(file)??file,nextFile=this.fileRenderer.getFileForNextRender(workingFile);return{file:nextFile,lineAnnotations:lineAnnotations!=null&&areFileTargetsEqual(nextFile,workingFile)?lineAnnotations:this.getAnnotationsForFile(nextFile)}}getLatestAnnotations(){return this.pendingData?.lineAnnotations??this.editSession?.annotations?.current??this.lineAnnotations}getAnnotationsForFile(file){const{pendingData}=this;return pendingData!=null&&areFileTargetsEqual(file,pendingData.file)?pendingData.lineAnnotations:this.lineAnnotations}adoptRenderData(file){const{pendingData}=this,matchesPending=pendingData!=null&&areFileTargetsEqual(file,pendingData.file);this.renderedData={file,lineAnnotations:matchesPending?pendingData.lineAnnotations:this.lineAnnotations},matchesPending&&(this.pendingData=void 0)}isNewAnnotations(lineAnnotations){const session=this.editSession?.annotations;return lineAnnotations===this.getLatestAnnotations()?!1:session==null||lineAnnotations!==session.provided&&lineAnnotations!==session.current}updateInputFile(incomingFile,lineAnnotations){if(areFileTargetsEqual(this.getInputFile(),incomingFile))return!1;const hadSession=this.editSession!=null,previousAnnotations=this.getLatestAnnotations();return this.file=incomingFile,hadSession||this.editor!=null?this.installEditSession(incomingFile,hadSession?void 0:this.editor?.__getDocumentContents(incomingFile),!0):this.editSession=void 0,this.editSession?.annotations!=null&&lineAnnotations!=null&&(this.editSession.annotations=adoptEditSessionAnnotations(lineAnnotations,getLineAnnotationName,this.editSession.annotations)),this.pendingData={file:this.editSession?.file??incomingFile,lineAnnotations:this.editSession?.annotations?.current??lineAnnotations??previousAnnotations},!0}installEditSession(inputFile,retainedDocument,hostReplacement=!1){const usesInputDocument=retainedDocument==null||retainedDocument.name===inputFile.name&&retainedDocument.lang===inputFile.lang&&retainedDocument.contents===inputFile.contents,file=createEditSessionFile(retainedDocument??inputFile),annotations=this.editSession?.annotations??adoptEditSessionAnnotations(this.getLatestAnnotations(),getLineAnnotationName);this.editSession={file,inputFile,externalReplacement:hostReplacement&&usesInputDocument,annotations},this.pendingData={file,lineAnnotations:annotations.current},this.fileRenderer.beginEditSession(file,usesInputDocument?inputFile:void 0)}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(options){options!=null&&(this.options=options,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(pluckInteractionOptions(this.options))}mergeOptions(options){this.options={...this.options,...options}}setThemeType(themeType){(this.options.themeType??"system")!==themeType&&(this.mergeOptions({themeType}),this.applyCachedThemeState(themeType))}applyCachedThemeState(themeType){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const effectiveThemeType=this.appliedThemeCSS.baseThemeType??themeType;return this.appliedThemeCSS.themeType===effectiveThemeType?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,themeType,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!areThemesEqual(this.appliedThemeCSS.theme,this.getTheme())}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(lineAnnotations){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null){if(!this.isNewAnnotations(lineAnnotations))return;writeEditSessionAnnotations(sessionAnnotations,lineAnnotations,getLineAnnotationName)}const file=this.getWorkingFile();file!=null&&(this.pendingData={file,lineAnnotations})}syncEditSessionAnnotationsFromEditor(lineAnnotations){const session=this.editSession?.annotations;return session==null||lineAnnotations===session.current?!1:(session.current=lineAnnotations,this.renderedData!=null&&(this.renderedData.lineAnnotations=lineAnnotations),this.pendingData=void 0,this.fileRenderer.setLineAnnotations(lineAnnotations),this.renderAnnotations(),!0)}setSelectedLines(range,options){this.interactionManager.setSelection(range,options)}setEditorActiveLine(lineNumber,options){this.interactionManager.setEditorActiveLine(lineNumber,{lineNumberOnly:options?.lineNumberOnly,side:options?.side??"additions"})}getCodeScrollLeft(){return this.code?.scrollLeft??0}setCodeScrollLeft(position){this.code!=null&&(this.code.scrollLeft=position)}__getEffectiveCodeOptions(){return{...this.options,...this.fileRenderer.getEffectiveCodeOptions()}}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,{disableAnnotations:overflow==="wrap",columnVariables:this.shouldApplyColumnVariables(overflow)?"apply":"measure"}),this.managersDirty=!1}shouldApplyColumnVariables(overflow){return overflow==="scroll"&&this.lineAnnotations.length>0}cleanUp(recycle=!1){const editor=this.editor;this.emitPostRender(!0),editor?.cleanUp(recycle?"recycle":"discard"),recycle||(this.editor=void 0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isComponentManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,recycle||(this.renderedData=void 0,this.pendingData=void 0),this.clearAuxiliaryNodes(),this.pre?.remove(),this.pre=void 0,this.code=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement?.remove(),this.headerElement=void 0,this.clearHeaderSlots(),this.lastRenderedHeaderHTML=void 0,recycle||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,recycle?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0,this.editSession=void 0),this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(props){const{fileContainer,prerenderedHTML,preventEmit=!1,file,lineAnnotations}=props;if(!this.enabled)throw new Error("File.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("File.hydrate: hydrate can only be called before the instance has rendered or hydrated");this.hydrateElements(fileContainer,prerenderedHTML);const forceEditorRender=this.editor!=null;forceEditorRender||shouldRenderCode(this.pre,file,this.options.collapsed)||shouldRenderHeader(this.headerElement,file,this.options.disableFileHeader)?this.render({...props,forceRender:forceEditorRender||props.forceRender,preventEmit:!0}):this.hydrationSetup({file,lineAnnotations}),preventEmit||this.emitPostRender()}hydrateElements(fileContainer,prerenderedHTML){this.fileContainer!==fileContainer&&this.emitPostRender(!0),prerenderHTMLIfNecessary(fileContainer,prerenderedHTML);for(const element of Array.from(fileContainer.shadowRoot?.children??[])){if(element instanceof SVGElement){this.spriteSVG=element;continue}if(element instanceof HTMLElement){if(element instanceof HTMLPreElement){this.pre=element,this.appliedPreAttributes=void 0;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-theme-css")){this.themeCSSStyle=element;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=element,this.appliedUnsafeCSS=element.textContent;continue}if("diffsHeader"in element.dataset){this.headerElement=element,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=fileContainer,this.hydrateMeasuredScrollbar()}hydrationSetup({file,lineAnnotations}){this.renderedData={file,lineAnnotations:lineAnnotations??this.getLatestAnnotations()},this.pendingData=void 0,this.file=file,this.fileRenderer.setOptions(getFileRendererOptions(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(file),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(file=this.getWorkingFile()){return file!=null?this.fileRenderer.getOrCreateLineCache(file):EMPTY_STRINGS}updateBuffers(renderRange){this.pre!=null&&this.applyBuffers(this.pre,renderRange)}syncRenderViewToEditor(){const{editor,fileContainer,renderRange}=this,lineAnnotations=this.getLatestAnnotations(),file=this.getWorkingFile();if(editor==null||fileContainer==null||file==null)return;const syncEditor=highlighter2=>{!this.enabled||this.editor!==editor||this.fileContainer!==fileContainer||this.getWorkingFile()!==file||editor.__syncRenderView({highlighter:highlighter2,fileContainer,file,lineAnnotations,renderRange,externalDocument:this.editSession?.externalReplacement===!0})},theme=this.getTheme(),lang=file.lang??getFiletypeFromFileName(file.name),highlighter=getHighlighterIfLoaded({theme,lang});highlighter!=null?syncEditor(highlighter):getSharedHighlighter({themes:getThemes(theme),langs:Array.from(new Set(["text",lang])),preferredHighlighter:resolvePreferredHighlighter(this.workerManager,this.options)}).then(syncEditor).catch(error=>{error instanceof HighlighterDisposedError||console.error(error)})}__acknowledgeDocumentUpdate(){this.editSession!=null&&(this.editSession.externalReplacement=!1)}__acceptEditorChange(event){const{lineAnnotations}=event;lineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(lineAnnotations)}emitEditChange(event){const{onEditChange}=this.options;onEditChange?.(event)}__captureDocumentSessionState(){}__attachEditor(editor){if(this.editor!=null)throw new Error("File.__attachEditor: an editor is already attached");this.editor=editor;const detach=()=>{this.editor=void 0,this.fileRenderer.endEditSession()};try{return this.resumeEditorRendering(editor),detach}catch(error){throw detach(),error}}__resumeEditor(editor){if(this.editor!==editor)throw new Error("File.__resumeEditor: editor association changed");this.resumeEditorRendering(editor)}resumeEditorRendering(editor){if(this.editSession!=null)this.fileRenderer.beginEditSession(this.editSession.file);else{const inputFile=this.getInputFile();inputFile!=null&&this.installEditSession(inputFile,editor.__getDocumentContents(inputFile))}const editSessionFile=this.editSession?.file;this.fileRenderer.editorRenderReady()?(editSessionFile!=null&&this.fileRenderer.fileCache===editSessionFile&&this.adoptRenderData(editSessionFile),this.syncRenderViewToEditor()):this.rerender()}__completeEditSession(editor,mode){this.settleEditSession(mode==="install",editor)}settleEditSession(installResult,editor){const{editSession}=this;if(editSession==null)return;const{file:editSessionFile,inputFile,annotations:editSessionAnnotations}=editSession,inputAnnotations=editSessionAnnotations?.provided??this.lineAnnotations;if(this.editor!=null)throw new Error("File.__completeEditSession: detach the editor before completing the session");const sessionAnnotationsCurrent=editSessionAnnotations?.current;let acceptedFile,failed=!1,failure;if(editor==null)throw new Error("File.__completeEditSession: editor is required for completion");const completedFile={...editSessionFile},event={file:completedFile,editor,originalFile:inputFile,lineAnnotations:sessionAnnotationsCurrent,originalLineAnnotations:inputAnnotations};Object.freeze(event);try{if(editor.__emitEditComplete(event),this.options.onEditComplete?.(event)==="accept"){if(completedFile.cacheKey!=null&&completedFile.cacheKey===inputFile.cacheKey)throw new Error("File.__completeEditSession: an accepted file must not reuse the replaced file cacheKey");acceptedFile=completedFile}}catch(error){failed=!0,failure=error}const settledFile=installResult&&acceptedFile!=null?acceptedFile:inputFile,settledAnnotations=installResult&&acceptedFile!=null?sessionAnnotationsCurrent??inputAnnotations:inputAnnotations;if(this.editSession=void 0,this.file=settledFile,this.pendingData={file:settledFile,lineAnnotations:settledAnnotations},this.fileRenderer.endEditSession(settledFile),areFileTargetsEqual(this.getRenderedFile(),settledFile)&&this.adoptRenderData(settledFile),installResult&&this.fileContainer!=null&&this.rerender(),failed)throw failure}applyDocumentChange(textDocument,newLineAnnotations){const editSessionFile=this.editSession?.file;if(editSessionFile==null)throw new Error("File.applyDocumentChange: requires an active edit session");this.fileRenderer.beginEditSession(editSessionFile),this.fileRenderer.applyDocumentChange(textDocument),newLineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(newLineAnnotations)}applySuspendedDocumentChange(textDocument,newLineAnnotations){this.editSession!=null&&(this.applyDocumentChange(textDocument,newLineAnnotations),this.fileRenderer.clearRenderCache())}updateRenderCache(dirtyLines,themeType,options){const editSessionFile=this.editSession?.file;if(editSessionFile==null)throw new Error("File.updateRenderCache: requires an active edit session");this.fileRenderer.beginEditSession(editSessionFile),this.fileRenderer.updateRenderCache(dirtyLines,themeType,options?.lineCountChangeInFlight)}render({file,fileContainer,forceRender=!1,preventEmit=!1,containerWrapper,deferManagers=!1,lineAnnotations,renderRange}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");forceRender=this.forceRenderOverride??forceRender,this.forceRenderOverride=void 0,this.editor?.__postponeBgTokenizeToNextFrame();const{collapsed=!1,themeType="system"}=this.options,nextRenderRange=collapsed?void 0:renderRange,previousRenderRange=this.renderRange,themeChanged=this.hasThemeChanged(),annotationsChanged=lineAnnotations!=null&&(lineAnnotations.length>0||this.getLatestAnnotations().length>0)?this.isNewAnnotations(lineAnnotations):!1,didFileChange=!areFileTargetsEqual(this.getInputFile(),file);didFileChange&&this.updateInputFile(file,lineAnnotations);const workingFile=this.getWorkingFile(file)??file;if(!collapsed&&!forceRender&&areRenderRangesEqual(nextRenderRange,this.renderRange)&&!didFileChange&&!annotationsChanged&&!themeChanged){const rendered=this.applyCachedThemeState(themeType);return rendered&&this.finalizeRender(),rendered}this.renderRange=nextRenderRange,didFileChange&&(this.cachedHeaderHTML=void 0),this.fileRenderer.setOptions(getFileRendererOptions(this.options)),this.syncInteractionOptions(),lineAnnotations!=null&&this.setLineAnnotations(lineAnnotations);const nextRenderFile=this.fileRenderer.getFileForNextRender(workingFile);this.fileRenderer.setLineAnnotations(this.getAnnotationsForFile(nextRenderFile));const{disableErrorHandling=!1,disableFileHeader=!1}=this.options;if(disableFileHeader&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),fileContainer=this.getOrCreateFileContainerNode(fileContainer,containerWrapper),this.applyCachedThemeState(themeType),collapsed){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const fileResult=this.fileRenderer.renderFile(workingFile,EMPTY_RENDER_RANGE);fileResult!=null&&this.applyThemeState(fileContainer,fileResult.themeStyles,themeType,fileResult.baseThemeType),fileResult?.headerAST!=null&&this.applyHeaderToDOM(fileResult.headerAST,fileContainer,fileResult.file),this.adoptRenderData(fileResult?.file??workingFile),this.injectUnsafeCSS()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return this.finalizeRender(),preventEmit||this.emitPostRender(),!0}try{const pre=this.getOrCreatePreNode(fileContainer);let renderedFile=this.getRenderedFile();if(!this.canPartiallyRender(forceRender,annotationsChanged,didFileChange||themeChanged||!areFileTargetsEqual(this.getRenderedFile(),workingFile))||!this.applyPartialRender(workingFile,previousRenderRange,nextRenderRange)){const fileResult=this.fileRenderer.renderFile(workingFile,nextRenderRange);if(fileResult==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.isWorkingPool()&&this.workerManager.initialize().catch(()=>{}).then(()=>this.rerender()),!1;this.applyThemeState(fileContainer,fileResult.themeStyles,themeType,fileResult.baseThemeType),fileResult.headerAST!=null&&this.applyHeaderToDOM(fileResult.headerAST,fileContainer,fileResult.file),this.applyFullRender(fileResult,pre),renderedFile=fileResult.file}this.applyBuffers(pre,nextRenderRange),this.injectUnsafeCSS(),renderedFile!=null&&this.adoptRenderData(renderedFile),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,deferManagers||this.flushManagers(),this.finalizeRender(),this.editor!=null&&this.syncRenderViewToEditor()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return preventEmit||this.emitPostRender(),!0}finalizeRender(){}emitPostRender(unmount=!1){const{fileContainer,options:{onPostRender}}=this;if(unmount){if(!this.mounted||(this.mounted=!1,fileContainer==null))return;onPostRender?.(fileContainer,this,"unmount");return}if(fileContainer==null)return;const phase=this.mounted?"update":"mount";this.mounted=!0,onPostRender?.(fileContainer,this,phase)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(forceRender,annotationsChanged,didContentChange){return!(forceRender||annotationsChanged||didContentChange)}renderPlaceholder(height){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const shadowRoot=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",shadowRoot.appendChild(this.placeHolder)}return this.setPlaceholderHeight(height)}setPlaceholderHeight(height){return this.placeHolder==null?!1:(this.placeHolder.style.setProperty("height",`${height}px`),!0)}async primeHighlightCache(file=this.getInputFile()){const{workerManager}=this;if(file==null||workerManager==null||!workerManager.isWorkingPool()||file.cacheKey==null||isFilePlainText(file))return;const tokenizeMaxLength=this.options.tokenizeMaxLength??1e5;this.fileRenderer.getOrCreateLineCache(file).length>tokenizeMaxLength||await workerManager.primeFileHighlightCache(file).catch(error=>{isHandledWorkerPoolError(error)||console.error(error)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isComponentManaged||this.fileContainer==null){for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear();return}const staleAnnotations=new Map(this.annotationCache),{renderAnnotation}=this.options,{renderedData}=this;if(renderAnnotation!=null&&renderedData!=null){const{file,lineAnnotations}=renderedData;for(const[index,annotation]of lineAnnotations.entries()){const name=this.getAnnotationSlotName(annotation),id=`${index}-${name}`;let cache=this.annotationCache.get(id);if(cache==null||cache.file!==file||!areLineAnnotationsEqual(annotation,cache.annotation)){cache?.element.remove();const content=renderAnnotation(annotation,file);if(content==null)continue;cache={element:createAnnotationWrapperNode(name),annotation,file},cache.element.appendChild(content),this.fileContainer.appendChild(cache.element),this.annotationCache.set(id,cache)}staleAnnotations.delete(id)}}for(const[id,{element}]of staleAnnotations.entries())this.annotationCache.delete(id),element.remove()}renderGutterUtility(){const{renderGutterUtility}=this.options;if(this.fileContainer==null||renderGutterUtility==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const element=renderGutterUtility(this.interactionManager.getHoveredLine);if(element!=null&&this.gutterUtilityContent!=null)return;if(element==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const gutterUtilityContent=createGutterUtilityContentNode();gutterUtilityContent.appendChild(element),this.fileContainer.appendChild(gutterUtilityContent),this.gutterUtilityContent=gutterUtilityContent}injectUnsafeCSS(){const{unsafeCSS}=this.options;this.pre?.toggleAttribute("data-custom-styles",!!unsafeCSS);const shadowRoot=this.fileContainer?.shadowRoot;if(shadowRoot!=null){if(unsafeCSS==null||unsafeCSS===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===shadowRoot&&this.appliedUnsafeCSS===unsafeCSS||(this.unsafeCSSStyle??=createUnsafeCSSStyleNode(),this.unsafeCSSStyle.parentNode!==shadowRoot&&shadowRoot.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=wrapUnsafeCSS(unsafeCSS),this.appliedUnsafeCSS=unsafeCSS)}}applyThemeState(container,themeStyles,themeType,baseThemeType){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"}),effectiveThemeType=baseThemeType??themeType,currentTheme=this.getTheme(),theme=typeof currentTheme=="string"?currentTheme:{...currentTheme},scrollbarGutter=getMeasuredScrollbarGutter(shadowRoot);if(this.themeCSSStyle?.parentNode===shadowRoot&&this.appliedThemeCSS?.themeStyles===themeStyles&&this.appliedThemeCSS.themeType===effectiveThemeType&&this.appliedThemeCSS.scrollbarGutter===scrollbarGutter){this.appliedThemeCSS.theme=theme;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===shadowRoot){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter};return}this.themeCSSStyle=upsertHostThemeStyle({shadowRoot,currentNode:this.themeCSSStyle,themeCSS:wrapThemeCSS(themeStyles,effectiveThemeType,scrollbarGutter)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter}:void 0}hydrateMeasuredScrollbar(){const shadowRoot=this.fileContainer?.shadowRoot;shadowRoot==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=patchScrollbarGutterSize(this.themeCSSStyle.textContent??"",getMeasuredScrollbarGutter(shadowRoot)))}shouldGuardRebuildScroll(){return this.editor!=null&&isSafari()}applyFullRender(result,pre){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(pre,result);const code=this.code=getOrCreateCodeNode({code:this.code}),codeAst=this.fileRenderer.renderCodeAST(result);this.editor?.__captureFocusForDOMReplacement();const applyColumns=()=>{if(code.childElementCount>=2)for(let i=0;i<2;i++){const domEl=code.children[i],astEl=codeAst[i];domEl.innerHTML=hastToHtml(astEl.children),domEl.style.cssText=astEl.properties.style}else code.innerHTML=hastToHtml(codeAst);pre.contains(code)||pre.replaceChildren(code)};this.shouldGuardRebuildScroll()?guardWebKitScrollDuringRebuild(pre,applyColumns):applyColumns(),this.lastRowCount=result.rowCount}applyPartialRender(file,previousRenderRange,renderRange){if(previousRenderRange==null||renderRange==null)return!1;const{code}=this,columns=code!=null?this.getColumns(code):void 0;if(code==null||columns==null)return!1;const previousStart=previousRenderRange.startingLine,nextStart=renderRange.startingLine,previousEnd=previousRenderRange.totalLines===1/0?Number.POSITIVE_INFINITY:previousStart+previousRenderRange.totalLines,nextEnd=renderRange.totalLines===1/0?Number.POSITIVE_INFINITY:nextStart+renderRange.totalLines,overlapStart=Math.max(previousStart,nextStart),overlapEnd=Math.min(previousEnd,nextEnd);if(overlapEnd<=overlapStart)return!1;if(!this.trimDOMToOverlap(columns.gutter,overlapStart,overlapEnd)||!this.trimDOMToOverlap(columns.content,overlapStart,overlapEnd))throw new Error("File.applyPartialRender: failed to trim to overlap");let{length:rowCount}=columns.content.children;const renderChunk=(startingLine,totalLines)=>{if(!(totalLines<=0))return this.fileRenderer.renderFile(file,{startingLine,totalLines,bufferBefore:0,bufferAfter:0})},prependResult=nextStart<overlapStart?renderChunk(nextStart,overlapStart-nextStart):void 0;if(prependResult===void 0&&nextStart<overlapStart)return!1;const appendTotalLines=nextEnd===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,nextEnd-overlapEnd),appendResult=nextEnd>overlapEnd?renderChunk(overlapEnd,appendTotalLines):void 0;return appendResult===void 0&&nextEnd>overlapEnd?!1:(this.cleanupErrorWrapper(),prependResult!=null&&(columns.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(prependResult.gutterAST)),columns.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(prependResult.contentAST)),rowCount+=prependResult.rowCount),appendResult!=null&&(columns.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(appendResult.gutterAST)),columns.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(appendResult.contentAST)),rowCount+=appendResult.rowCount),this.lastRowCount!==rowCount&&(columns.gutter.style.setProperty("grid-row",`span ${rowCount}`),columns.content.style.setProperty("grid-row",`span ${rowCount}`),this.lastRowCount=rowCount),!0)}getColumns(code){const gutter=code.children[0],content=code.children[1];if(!(!(gutter instanceof HTMLElement)||!(content instanceof HTMLElement)||gutter.dataset.gutter==null||content.dataset.content==null))return{gutter,content}}trimDOMToOverlap(container,overlapStart,overlapEnd){const boundaryIndices=this.getDOMBoundaryIndices(container,[overlapStart,overlapEnd]),startIndex=boundaryIndices.get(overlapStart)??container.children.length,endIndex=boundaryIndices.get(overlapEnd)??container.children.length;if(startIndex>endIndex)return!1;for(let i=container.children.length-1;i>=endIndex;i-=1)container.children[i]?.remove();for(let i=startIndex-1;i>=0;i-=1)container.children[i]?.remove();return!0}getDOMBoundaryIndices(container,boundaries){const sortedBoundaries=[...new Set(boundaries)].sort((a,b)=>a-b),boundaryIndices=new Map;if(sortedBoundaries.length===0)return boundaryIndices;let boundaryIndex=0,nextBoundary=sortedBoundaries[boundaryIndex];const{children}=container;nextBoundary===0&&(boundaryIndices.set(0,0),boundaryIndex+=1,nextBoundary=sortedBoundaries[boundaryIndex]);for(let i=0;i<children.length;i+=1){const child=children[i];if(!(child instanceof HTMLElement))continue;const lineIndex=this.getLineIndexFromDOMNode(child);if(lineIndex!=null){for(;nextBoundary!=null&&lineIndex>=nextBoundary;)boundaryIndices.set(nextBoundary,i),boundaryIndex+=1,nextBoundary=sortedBoundaries[boundaryIndex];if(boundaryIndex>=sortedBoundaries.length)break}}for(const boundary of sortedBoundaries)boundaryIndices.has(boundary)||boundaryIndices.set(boundary,children.length);return boundaryIndices}getLineIndexFromDOMNode(node){const lineIndexAttr=node.dataset.lineIndex;if(lineIndexAttr==null)return;const parsed=Number(lineIndexAttr);return Number.isNaN(parsed)?void 0:parsed}applyBuffers(pre,renderRange){if(renderRange==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}renderRange.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",pre.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${renderRange.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),renderRange.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",pre.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${renderRange.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(headerAST,container,file){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const headerHTML=this.cachedHeaderHTML??hastToHtml(headerAST);if(this.cachedHeaderHTML=headerHTML,headerHTML!==this.lastRenderedHeaderHTML){const tempDiv=document.createElement("div");tempDiv.innerHTML=headerHTML;const newHeader=tempDiv.firstElementChild;if(!(newHeader instanceof HTMLElement))return;this.headerElement!=null?container.shadowRoot?.replaceChild(newHeader,this.headerElement):container.shadowRoot?.prepend(newHeader),this.headerElement=newHeader,this.lastRenderedHeaderHTML=headerHTML}if(this.isComponentManaged)return;const{renderHeaderPrefix,renderHeaderFilenameSuffix,renderCustomHeader,renderHeaderMetadata}=this.options;if(renderCustomHeader!=null){const content=renderCustomHeader(file)??void 0;this.headerCustom=this.upsertHeaderSlotElement(container,this.headerCustom,CUSTOM_HEADER_SLOT_ID,content),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const prefix=renderHeaderPrefix?.(file)??void 0,suffix=renderHeaderFilenameSuffix?.(file)??void 0,content=renderHeaderMetadata?.(file)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(container,this.headerPrefix,HEADER_PREFIX_SLOT_ID,prefix),this.headerFilenameSuffix=this.upsertHeaderSlotElement(container,this.headerFilenameSuffix,HEADER_FILENAME_SUFFIX_SLOT_ID,suffix),this.headerMetadata=this.upsertHeaderSlotElement(container,this.headerMetadata,HEADER_METADATA_SLOT_ID,content),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(container,current,slot,content){if(content==null){current?.remove();return}const element=current??this.createHeaderSlotElement(slot);return current==null&&container.appendChild(element),this.replaceHeaderSlotContent(element,content),element}replaceHeaderSlotContent(element,content){element.replaceChildren(),content instanceof Element?element.appendChild(content):element.innerText=`${content}`}createHeaderSlotElement(slot){const element=document.createElement("div");return element.slot=slot,element}getOrCreateFileContainerNode(fileContainer,parentNode){const{fileContainer:previousContainer}=this,nextContainer=fileContainer??previousContainer??document.createElement("diffs-container"),containerChanged=previousContainer!==nextContainer;return previousContainer!=null&&containerChanged&&this.editor?.__captureFocusForDOMReplacement(),containerChanged&&this.emitPostRender(!0),this.fileContainer=nextContainer,previousContainer!=null&&containerChanged&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),parentNode!=null&&this.fileContainer.parentNode!==parentNode&&parentNode.appendChild(this.fileContainer),containerChanged&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(fileContainer){const{shadowRoot}=fileContainer;if(shadowRoot!=null)for(const element of shadowRoot.children)element instanceof SVGElement?this.spriteSVG??=element:isStyleNode(element)&&element.hasAttribute("data-theme-css")?(this.themeCSSStyle??=element,this.hasAdoptedThemeCSS=!0):isStyleNode(element)&&element.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=element,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(fileContainer){const shadowRoot=fileContainer.shadowRoot??fileContainer.attachShadow({mode:"open"});if(this.spriteSVG==null){const fragment=document.createElement("div");fragment.innerHTML=SVGSpriteSheet$1;const firstChild=fragment.firstChild;firstChild instanceof SVGElement&&(this.spriteSVG=firstChild)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==shadowRoot&&shadowRoot.appendChild(this.spriteSVG)}getOrCreatePreNode(container){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,shadowRoot.appendChild(this.pre)):this.pre.parentNode!==shadowRoot&&(this.editor?.__captureFocusForDOMReplacement(),container.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(pre){this.code=void 0;for(const child of Array.from(pre.children))if(child instanceof HTMLElement&&child.hasAttribute("data-code")){this.code=child;return}}applyPreNodeAttributes(pre,{totalLines}){const{overflow="scroll",disableLineNumbers=!1}=this.options,preProperties={type:"file",split:!1,overflow,disableLineNumbers,diffIndicators:"none",disableBackground:!0,totalLines};arePrePropertiesEqual(preProperties,this.appliedPreAttributes)||(setPreNodeProperties(pre,preProperties),this.appliedPreAttributes=preProperties)}applyErrorToDOM(error,container){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",shadowRoot.appendChild(this.errorWrapper);const errorMessage=document.createElement("div");errorMessage.dataset.errorMessage="",errorMessage.innerText=error.message,this.errorWrapper.appendChild(errorMessage);const errorStack=document.createElement("pre");errorStack.dataset.errorStack="",errorStack.innerText=error.stack??"No Error Stack",this.errorWrapper.appendChild(errorStack)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function shouldRenderCode(pre,file,collapsed=!1){return!collapsed&&pre==null&&file!=null}function shouldRenderHeader(headerElement,file,disableFileHeader=!1){return headerElement==null&&file!=null&&!disableFileHeader}const LAYOUT_CHECKPOINT_INTERVAL=5e3,NO_GHOST_TEXT_ROWS=new Map;let instanceId=-1;function hasFileLayoutOptionChanged(previousOptions,nextOptions){return(previousOptions.overflow??"scroll")!==(nextOptions.overflow??"scroll")||(previousOptions.collapsed??!1)!==(nextOptions.collapsed??!1)||(previousOptions.disableLineNumbers??!1)!==(nextOptions.disableLineNumbers??!1)||(previousOptions.disableFileHeader??!1)!==(nextOptions.disableFileHeader??!1)||previousOptions.unsafeCSS!==nextOptions.unsafeCSS}var VirtualizedFile=class extends File$1{virtualizer;metrics;__id=`virtualized-file:${++instanceId}`;renderType="virtualized";top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0,ghostTextRows:NO_GHOST_TEXT_ROWS};pendingRender;isVisible=!1;isSetup=!1;layoutDirty=!0;currentCollapsed;constructor(options,virtualizer,metrics=DEFAULT_VIRTUAL_FILE_METRICS,workerManager,requestOwnerRender){super(options,workerManager,requestOwnerRender),this.virtualizer=virtualizer,this.metrics=metrics}setMetrics(metrics,force=!1){const nextMetrics=computeVirtualFileMetrics(metrics);!force&&areObjectsEqual(this.metrics,nextMetrics)||(this.metrics=nextMetrics,this.resetLayoutCache())}setLineAnnotations(lineAnnotations){this.syncLineAnnotations(lineAnnotations)&&(this.forceRenderOverride=!0)}syncLineAnnotations(lineAnnotations){return lineAnnotations==null||!this.isNewAnnotations(lineAnnotations)||lineAnnotations.length===0&&this.getLatestAnnotations().length===0?!1:(super.setLineAnnotations(lineAnnotations),!0)}syncEditSessionAnnotationsFromEditor(lineAnnotations){return super.syncEditSessionAnnotationsFromEditor(lineAnnotations)?(this.forceRenderOverride=!0,!0):!1}hasLineAnnotations(){return this.getLayoutAnnotations().some(annotation=>annotation.lineNumber>0)}hasUniformLineHeights(){const{overflow="scroll"}=this.options;return overflow==="scroll"&&!this.hasLineAnnotations()&&this.cache.heights.size===0}getLineHeight(lineIndex,hasMetadataLine=!1){const cached=this.cache.heights.get(lineIndex);if(cached!=null)return cached;const multiplier=hasMetadataLine?2:1;return this.metrics.lineHeight*multiplier}setOptions(options){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(options==null)return;const{options:previousOptions}=this,optionsChanged=!areOptionsEqual(previousOptions,options),layoutChanged=hasFileLayoutOptionChanged(previousOptions,options);super.setOptions(options),layoutChanged&&this.resetLayoutCache(!0),optionsChanged&&(this.forceRenderOverride=!0),optionsChanged&&this.virtualizer.instanceChanged(this,layoutChanged)}setThemeType(themeType){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(themeType)}resetLayoutCache(recompute=!1,resetRenderRange=!0){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.ghostTextRows=NO_GHOST_TEXT_ROWS,this.renderRange!=null&&resetRenderRange&&(this.renderRange=void 0),recompute&&this.isSimpleMode()&&this.computeApproximateSize()}applyGhostTextRows(ghostTextRows){const{heights,ghostTextRows:previous}=this.cache;if(previous===ghostTextRows)return!1;const{lineHeight}=this.metrics;let changed=!1;for(const lineIndex of new Set([...previous.keys(),...ghostTextRows.keys()])){const previousRows=previous.get(lineIndex)??0,rows=ghostTextRows.get(lineIndex)??0;if(rows===previousRows)continue;const height=(heights.get(lineIndex)??lineHeight)-previousRows*lineHeight+rows*lineHeight;height===lineHeight?heights.delete(lineIndex):heights.set(lineIndex,height),changed=!0}return this.cache.ghostTextRows=ghostTextRows,changed}reconcileHeights(){let hasHeightChange=!1;if(this.fileContainer==null||this.getLayoutFile()==null)return this.height!==0&&(hasHeightChange=!0),this.height=0,hasHeightChange;const{overflow="scroll"}=this.options;this.top=this.getVirtualizedTop();const ghostTextRows=this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS;hasHeightChange=this.applyGhostTextRows(ghostTextRows);const measureAllRows=overflow!=="scroll"||this.lineAnnotations.length>0||this.isResizeDebuggingEnabled();if(this.placeHolder!=null||!measureAllRows&&this.cache.heights.size===0&&this.cache.fileAnnotationHeight===0)return hasHeightChange&&(this.computeApproximateSize(!0),this.setPlaceholderHeight(this.height)),hasHeightChange;const{lineHeight}=this.metrics;if(this.code==null)return hasHeightChange;const content=this.code.children[1];if(!(content instanceof HTMLElement))return hasHeightChange;if(this.renderRange!=null&&shouldRenderFileAnnotations(this.renderRange)){const nextFileAnnotationHeight=measureFileAnnotationHeight(content)??0;nextFileAnnotationHeight!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=nextFileAnnotationHeight,hasHeightChange=!0)}for(const line of content.children){if(!(line instanceof HTMLElement))continue;const lineIndexAttr=line.dataset.lineIndex;if(lineIndexAttr==null)continue;const lineIndex=Number(lineIndexAttr),ghostHeight=(ghostTextRows.get(lineIndex)??0)*lineHeight,cachedHeight=this.cache.heights.get(lineIndex);if(!measureAllRows&&(cachedHeight==null||cachedHeight===lineHeight+ghostHeight))continue;let measuredHeight=line.getBoundingClientRect().height+ghostHeight,hasMetadata=!1;line.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in line.nextElementSibling.dataset||"noNewline"in line.nextElementSibling.dataset)&&("noNewline"in line.nextElementSibling.dataset&&(hasMetadata=!0),measuredHeight+=line.nextElementSibling.getBoundingClientRect().height);const expectedHeight=this.getLineHeight(lineIndex,hasMetadata);measuredHeight!==expectedHeight&&(hasHeightChange=!0,measuredHeight===this.metrics.lineHeight*(hasMetadata?2:1)?this.cache.heights.delete(lineIndex):this.cache.heights.set(lineIndex,measuredHeight))}return(hasHeightChange||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),hasHeightChange}onRender=dirty=>{const file=this.getInputFile();return this.fileContainer==null||file==null?!1:(dirty&&(this.top=this.getVirtualizedTop()),this.render({file}))};updateCodeViewLayout(file,top,reset,lineAnnotations){const targetChanged=!areFileTargetsEqual(this.getInputFile(),file);targetChanged&&this.updateInputFile(file,lineAnnotations);const{pendingRenderFile,layoutFileChanged,renderedFileChanged,annotationsChanged}=this.updatePendingRender(file,lineAnnotations);let shouldResetLayoutCache=reset?.resetFileLayoutCache===!0||layoutFileChanged;reset?.metrics!=null&&(this.metrics=reset.metrics,shouldResetLayoutCache=!0);const{collapsed=!1}=this.options;return this.currentCollapsed!==collapsed&&(this.currentCollapsed=collapsed,shouldResetLayoutCache=!0),shouldResetLayoutCache&&this.resetLayoutCache(),targetChanged&&(this.layoutDirty=!0),!this.forceRenderOverride&&(targetChanged||renderedFileChanged||annotationsChanged)&&(this.forceRenderOverride=!0),this.top=top,this.computeApproximateSize(!1,pendingRenderFile),this.height}getLayoutFile(){return this.pendingRender?.file??this.getRenderedFile()}getLayoutAnnotations(){const{pendingRender}=this;return pendingRender!=null?this.getAnnotationsForFile(pendingRender.file):this.lineAnnotations}getLinePosition(lineNumber){const file=this.getLayoutFile();if(file==null||lineNumber<1)return;const{disableFileHeader=!1,collapsed=!1}=this.options,lastLineIndex=this.fileRenderer.getLineCount(file)-1;if(collapsed)return{top:getVirtualFileHeaderHeight(this.metrics,disableFileHeader),height:0};let top=getVirtualFileHeaderRegion(this.metrics,disableFileHeader);if(lastLineIndex<0)return{top,height:0};const clampedLineIndex=Math.min(Math.max(lineNumber-1,0),lastLineIndex),{lineHeight}=this.metrics;if(top+=this.cache.fileAnnotationHeight,this.hasUniformLineHeights())return{top:top+clampedLineIndex*lineHeight,height:lineHeight};const checkpoint=this.getLayoutCheckpointBeforeLineIndex(clampedLineIndex);top=checkpoint?.top??top;for(let lineIndex=checkpoint?.lineIndex??0;lineIndex<clampedLineIndex;lineIndex++)top+=this.getLineHeight(lineIndex,!1);return{top,height:this.getLineHeight(clampedLineIndex,!1)}}getEditorViewport(){return this.virtualizer.type==="simple"?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(localViewportTop){const file=this.getLayoutFile();if(file==null||this.renderRange==null)return;const{disableFileHeader=!1,collapsed=!1}=this.options;if(collapsed||this.renderRange.totalLines<=0)return;const lastLineIndex=this.fileRenderer.getLineCount(file)-1;if(lastLineIndex<0)return;const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),firstRenderedLineIndex=Math.min(this.renderRange.startingLine,lastLineIndex),lastRenderedLineIndex=Math.min(firstRenderedLineIndex+this.renderRange.totalLines-1,lastLineIndex);if(lastRenderedLineIndex<firstRenderedLineIndex)return;const{fileAnnotationHeight}=this.cache;if(this.hasUniformLineHeights()){const{lineHeight}=this.metrics,firstRenderedLineTop=headerRegion+(firstRenderedLineIndex===0?fileAnnotationHeight:this.renderRange.bufferBefore),lineIndex=firstRenderedLineIndex+Math.max(Math.ceil((localViewportTop-firstRenderedLineTop)/lineHeight),0);return lineIndex>lastRenderedLineIndex?void 0:{lineNumber:lineIndex+1,top:headerRegion+fileAnnotationHeight+lineIndex*lineHeight}}let top=headerRegion+(firstRenderedLineIndex===0?fileAnnotationHeight:this.renderRange.bufferBefore);for(let lineIndex=firstRenderedLineIndex;lineIndex<=lastRenderedLineIndex;lineIndex++){if(top>=localViewportTop)return{lineNumber:lineIndex+1,top};top+=this.getLineHeight(lineIndex)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(windowSpecs){const file=this.getLayoutFile();if(this.top==null||file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const renderRange=windowSpecs!=null?this.computeRenderRangeFromWindow(file,this.top,windowSpecs):this.renderRange;if(renderRange==null)return;const{bufferBefore,bufferAfter,totalLines}=renderRange;let headerOnlyOffset=0;if(totalLines===0){const activeWindow=windowSpecs??this.virtualizer.getWindowSpecs();this.top<activeWindow.top&&(headerOnlyOffset=bufferAfter)}return{topOffset:this.top+bufferBefore+headerOnlyOffset,height:this.height-(bufferBefore+bufferAfter)}}cleanUp(recycle=!1){const hadGhostTextRows=this.cache.ghostTextRows.size>0;hadGhostTextRows&&(this.layoutDirty=!0);const shouldRecomputeLayout=recycle&&this.isAdvancedMode()&&this.fileContainer!=null&&(hadGhostTextRows||!areFileTargetsEqual(this.getRenderedFile(),this.getWorkingFile()));this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),recycle||this.resetLayoutCache(),this.pendingRender=void 0,this.isSetup=!1,super.cleanUp(recycle),shouldRecomputeLayout&&this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(force=!1,file=this.getLayoutFile()){const shouldValidateSize=this.isResizeDebuggingEnabled();if(!force&&!this.layoutDirty&&!shouldValidateSize)return;const isFirstCompute=this.height===0;if(this.height=0,this.cache.checkpoints=[],file==null){this.layoutDirty=!1;return}this.applyGhostTextRows(this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS);const{disableFileHeader=!1,collapsed=!1}=this.options,{lineHeight}=this.metrics,lineCount=this.fileRenderer.getLineCount(file);if(collapsed){this.height+=getVirtualFileHeaderHeight(this.metrics,disableFileHeader),this.layoutDirty=!1;return}const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),paddingBottom=getVirtualFilePaddingBottom(this.metrics);if(this.height+=headerRegion,this.height+=this.cache.fileAnnotationHeight,this.hasUniformLineHeights())this.height+=lineCount*lineHeight;else for(let lineIndex=0;lineIndex<lineCount;lineIndex++)this.addLayoutCheckpoint(lineIndex,this.height),this.height+=this.getLineHeight(lineIndex,!1);if(lineCount>0&&(this.height+=paddingBottom),this.fileContainer!=null&&shouldValidateSize&&!isFirstCompute){const rect=this.fileContainer.getBoundingClientRect();rect.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:file.name,elementHeight:rect.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(visible){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,visible&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!visible&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){if(!this.enabled||this.getInputFile()==null)return;const workingFile=this.getWorkingFile(),nextRenderFile=workingFile==null?void 0:this.fileRenderer.getFileForNextRender(workingFile);this.isSimpleMode()&&(this.pendingRender=void 0),this.forceRenderOverride=!0,!(this.isSimpleMode()&&this.requestRender())&&this.virtualizer.instanceChanged(this,!areFileTargetsEqual(this.getRenderedFile(),nextRenderFile))}get isComponentManaged(){return this.getAdvancedVirtualizer()?.isComponentManaged??super.isComponentManaged}syncGhostTextRows(){const codeView=this.getAdvancedVirtualizer();codeView!=null?(codeView.capturePendingLayoutAnchor(),this.layoutDirty=!0,codeView.instanceChanged(this,!0)):this.getSimpleVirtualizer()?.requestHeightReconcile(this)}applyDocumentChange(textDocument,newLineAnnotations,shouldUpdateBuffer=!1){const{renderRange:previousRenderRange}=this;this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(textDocument,newLineAnnotations),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(this.isSimpleMode(),!1);const file=this.getRenderedFile();if(!this.isSimpleMode())this.computeApproximateSize(!0);else if(shouldUpdateBuffer&&previousRenderRange!=null&&file!=null){const windowSpecs=this.virtualizer.getWindowSpecs(),renderRange=this.computeRenderRangeFromWindow(file,this.top??0,windowSpecs);renderRange.bufferAfter!==previousRenderRange.bufferAfter&&this.updateBuffers(renderRange)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}render({fileContainer,file,forceRender=!1,lineAnnotations,...props}){const didFileChange=!areFileTargetsEqual(this.getInputFile(),file);didFileChange&&(this.updateInputFile(file,lineAnnotations),this.cachedHeaderHTML=void 0);const{pendingRenderFile,layoutFileChanged,renderedFileChanged,annotationsChanged}=this.pendingRender!=null&&this.pendingRender.workingFile===(this.getWorkingFile(file)??file)?{pendingRenderFile:this.pendingRender.file,layoutFileChanged:!1,renderedFileChanged:!1,annotationsChanged:this.syncLineAnnotations(lineAnnotations)}:this.updatePendingRender(file,lineAnnotations),{forceRenderOverride,isSetup}=this;if(this.forceRenderOverride=void 0,layoutFileChanged&&this.resetLayoutCache(),fileContainer=this.getOrCreateFileContainerNode(fileContainer),isSetup)this.top??=this.getVirtualizedTop(),this.layoutDirty&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,pendingRenderFile));else{this.computeApproximateSize(!1,pendingRenderFile);const virtualizer=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(virtualizer==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");virtualizer.connect(fileContainer,this),this.isVisible=virtualizer.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!didFileChange||!isSetup))return this.renderPlaceholder(this.height);const windowSpecs=this.virtualizer.getWindowSpecs(),fileTop=this.top??0,renderRange=this.computeRenderRangeFromWindow(pendingRenderFile,fileTop,windowSpecs);return super.render({file,fileContainer,renderRange,lineAnnotations,forceRender:(forceRenderOverride??forceRender)||annotationsChanged||renderedFileChanged||didFileChange,...props})}finalizeRender(){if(this.getRenderedFile()!==this.pendingRender?.file)throw new Error("VirtualizedFile.render: rendered a different file than its prepared layout");this.pendingRender=void 0,this.isSimpleMode()&&this.getSimpleVirtualizer()?.requestHeightReconcile(this)}updatePendingRender(nextFile,lineAnnotations){const workingFile=this.getWorkingFile(nextFile)??nextFile,previousRenderedFile=this.getRenderedFile(),previousLayoutFile=this.pendingRender?.file??previousRenderedFile,pendingRenderFile=this.fileRenderer.getFileForNextRender(workingFile);return this.pendingRender={workingFile,file:pendingRenderFile},{pendingRenderFile,annotationsChanged:this.syncLineAnnotations(lineAnnotations),layoutFileChanged:!areFileTargetsEqual(previousLayoutFile,pendingRenderFile),renderedFileChanged:!areFileTargetsEqual(previousRenderedFile,pendingRenderFile)}}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(lineIndex,top){lineIndex%LAYOUT_CHECKPOINT_INTERVAL===0&&this.cache.checkpoints.push({lineIndex,top})}getLayoutCheckpointBeforeLineIndex(lineIndex){if(lineIndex<=0||this.cache.checkpoints.length===0)return;let low=0,high=this.cache.checkpoints.length-1,result;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");checkpoint.lineIndex<=lineIndex?(result=checkpoint,low=mid+1):high=mid-1}return result}getLayoutCheckpointBeforeTop(top,hunkLineCount){let low=0,high=this.cache.checkpoints.length-1,resultIndex=-1;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");checkpoint.top<=top?(resultIndex=mid,low=mid+1):high=mid-1}if(hunkLineCount==null)return resultIndex>=0?this.cache.checkpoints[resultIndex]:void 0;for(let index=resultIndex;index>=0;index--){const checkpoint=this.cache.checkpoints[index];if(checkpoint==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(checkpoint.lineIndex%hunkLineCount===0)return checkpoint}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(file,fileTop,{top,bottom}){const{disableFileHeader=!1}=this.options,{hunkLineCount,lineHeight}=this.metrics,lineCount=this.fileRenderer.getLineCount(file),fileHeight=this.height,headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),paddingBottom=lineCount>0?getVirtualFilePaddingBottom(this.metrics):0,{fileAnnotationHeight}=this.cache,codeRegionTop=headerRegion+fileAnnotationHeight,codeRowsHeight=Math.max(0,fileHeight-headerRegion-fileAnnotationHeight-paddingBottom),hasFileAnnotations=includesFileAnnotations(this.getLayoutAnnotations()),fileAnnotationTop=fileTop+headerRegion,measuredFileAnnotationVisible=fileAnnotationHeight>0&&hasFileAnnotations&&fileAnnotationTop<bottom&&fileAnnotationTop+fileAnnotationHeight>top;if(fileTop<top-fileHeight||fileTop>bottom)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};if(lineCount<=hunkLineCount)return{startingLine:0,totalLines:hunkLineCount,bufferBefore:0,bufferAfter:0};const estimatedTargetLines=Math.ceil(Math.max(bottom-top,0)/lineHeight),totalLines=Math.ceil(estimatedTargetLines/hunkLineCount)*hunkLineCount+hunkLineCount,totalHunks=totalLines/hunkLineCount,viewportCenter=(top+bottom)/2;if(this.hasUniformLineHeights()){const sourceRowsTop=fileTop+codeRegionTop,sourceRowsBottom=sourceRowsTop+codeRowsHeight;if(!measuredFileAnnotationVisible&&!(sourceRowsTop<bottom&&sourceRowsBottom>top))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};const centerLine=Math.floor(measuredFileAnnotationVisible&&viewportCenter<fileTop+codeRegionTop?0:(viewportCenter-(fileTop+codeRegionTop))/lineHeight),idealStartHunk2=Math.floor(centerLine/hunkLineCount)-Math.floor(totalHunks/2),totalHunksInFile=Math.ceil(lineCount/hunkLineCount),startingLine2=Math.max(0,Math.min(idealStartHunk2,totalHunksInFile))*hunkLineCount,clampedTotalLines2=idealStartHunk2<0?totalLines+idealStartHunk2*hunkLineCount:totalLines,bufferBefore2=startingLine2===0?0:fileAnnotationHeight+startingLine2*lineHeight,renderedLines=Math.min(clampedTotalLines2,lineCount-startingLine2);return{startingLine:startingLine2,totalLines:clampedTotalLines2,bufferBefore:bufferBefore2,bufferAfter:Math.max(0,(lineCount-startingLine2-renderedLines)*lineHeight)}}const overflowHunks=totalHunks,hunkOffsets=[],checkpoint=this.getLayoutCheckpointBeforeTop(Math.max(0,top-fileTop-totalLines*lineHeight*2),hunkLineCount);let absoluteLineTop=fileTop+(checkpoint?.top??codeRegionTop),currentLine=checkpoint?.lineIndex??0,firstVisibleHunk,centerHunk,overflowCounter;const startingLineIndex=checkpoint?.lineIndex??0;for(let lineIndex=startingLineIndex;lineIndex<lineCount;lineIndex++){const isAtHunkBoundary=currentLine%hunkLineCount===0,currentHunk=Math.floor(currentLine/hunkLineCount);if(isAtHunkBoundary&&(hunkOffsets[currentHunk]=absoluteLineTop-(fileTop+codeRegionTop),overflowCounter!=null)){if(overflowCounter<=0)break;overflowCounter--}const lineHeight2=this.getLineHeight(lineIndex,!1);absoluteLineTop>top-lineHeight2&&absoluteLineTop<bottom&&(firstVisibleHunk??=currentHunk),absoluteLineTop+lineHeight2>viewportCenter&&(centerHunk??=currentHunk),overflowCounter==null&&absoluteLineTop>=bottom&&isAtHunkBoundary&&(overflowCounter=overflowHunks),currentLine++,absoluteLineTop+=lineHeight2}if(firstVisibleHunk==null)if(measuredFileAnnotationVisible)firstVisibleHunk=0,centerHunk=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};centerHunk??=firstVisibleHunk;const idealStartHunk=Math.round(centerHunk-totalHunks/2),maxStartHunk=Math.max(0,Math.ceil(lineCount/hunkLineCount)-totalHunks),startHunk=Math.max(0,Math.min(idealStartHunk,maxStartHunk)),startingLine=startHunk*hunkLineCount,clampedTotalLines=idealStartHunk<0?totalLines+idealStartHunk*hunkLineCount:totalLines,codeBufferBefore=hunkOffsets[startHunk]??0,bufferBefore=startingLine===0?0:fileAnnotationHeight+codeBufferBefore,finalHunkIndex=startHunk+clampedTotalLines/hunkLineCount,bufferAfter=finalHunkIndex<hunkOffsets.length?codeRowsHeight-hunkOffsets[finalHunkIndex]:codeRowsHeight-(absoluteLineTop-fileTop-codeRegionTop);return{startingLine,totalLines:clampedTotalLines,bufferBefore,bufferAfter:Math.max(0,bufferAfter)}}};function measureFileAnnotationHeight(content){let height;for(const child of content.children)child instanceof HTMLElement&&child.dataset.lineAnnotation===FILE_ANNOTATION_DOM_KEY&&(height=Math.max(height??0,child.getBoundingClientRect().height));return height}const DEFAULT_EDIT_STACK_MAX_ENTRIES=100,COALESCING_MODE_INSERT="insert",COALESCING_MODE_BACKSPACE="backspace",COALESCING_MODE_DELETE="delete";var EditStack=class EditStack2{#undoStack=[];#redoStack=[];#maxEntries;#canCoalesce=!1;constructor(options){this.#maxEntries=Math.max(1,options?.maxEntries??DEFAULT_EDIT_STACK_MAX_ENTRIES)}get canUndo(){return this.#undoStack.length>0}get canRedo(){return this.#redoStack.length>0}getState(){return{undoStack:this.#undoStack.map(cloneEditStackEntryForState),redoStack:this.#redoStack.map(cloneEditStackEntryForState),maxEntries:this.#maxEntries,canCoalesce:this.#canCoalesce}}getLiveState(){return Object.defineProperties({},{undoStack:{enumerable:!0,get:()=>this.#undoStack},redoStack:{enumerable:!0,get:()=>this.#redoStack},maxEntries:{enumerable:!0,get:()=>this.#maxEntries},canCoalesce:{enumerable:!0,get:()=>this.#canCoalesce}})}static fromState(state){const stack=new EditStack2({maxEntries:state.maxEntries});return stack.#undoStack=state.undoStack,stack.#redoStack=state.redoStack,stack.#canCoalesce=state.canCoalesce,stack}clear(){this.#undoStack.length=0,this.#redoStack.length=0,this.#canCoalesce=!1}clearRedo(){this.#redoStack.length=0}push(entry){this.#undoStack.push(entry),this.clearRedo(),this.#canCoalesce=!0,this.#undoStack.length>this.#maxEntries&&this.#undoStack.shift()}setLastUndoSelectionsAfter(selections){const lastEntry=this.#undoStack[this.#undoStack.length-1];lastEntry!==void 0&&(lastEntry.selectionsAfter=selections.map(selection=>({...selection})))}setLastUndoLineAnnotations(lineAnnotationsBefore,lineAnnotationsAfter){const lastEntry=this.#undoStack[this.#undoStack.length-1];lastEntry!==void 0&&(lastEntry.lineAnnotationsBefore=lineAnnotationsBefore.slice(),lastEntry.lineAnnotationsAfter=lineAnnotationsAfter.slice())}peekUndo(){return this.#undoStack[this.#undoStack.length-1]}peekUndoForCoalescing(){return this.#canCoalesce?this.peekUndo():void 0}replaceLastUndo(entry){if(this.#undoStack.length===0){this.push(entry);return}this.#undoStack[this.#undoStack.length-1]=entry,this.clearRedo(),this.#canCoalesce=!0}popUndoToRedo(){const entry=this.#undoStack.pop();if(entry!==void 0)return this.#redoStack.push(entry),this.#canCoalesce=!1,entry}popRedoToUndo(){const entry=this.#redoStack.pop();if(entry!==void 0)return this.#undoStack.push(entry),this.#canCoalesce=!1,entry}};function cloneEditStackEntry(entry){return{...entry,forwardEdits:entry.forwardEdits.map(edit=>({...edit})),inverseEdits:entry.inverseEdits.map(edit=>({...edit})),selectionsBefore:entry.selectionsBefore?.map(cloneSelection),selectionsAfter:entry.selectionsAfter?.map(cloneSelection),lineAnnotationsBefore:entry.lineAnnotationsBefore?.slice(),lineAnnotationsAfter:entry.lineAnnotationsAfter?.slice()}}function cloneEditStackEntryForState(entry){return{...cloneEditStackEntry(entry),lineAnnotationsBefore:entry.lineAnnotationsBefore?.map(annotation=>({...annotation})),lineAnnotationsAfter:entry.lineAnnotationsAfter?.map(annotation=>({...annotation}))}}function cloneSelection(selection){return{...selection,start:{...selection.start},end:{...selection.end}}}function createEditStackEntry(textDocument,resolvedEdits,versionBefore,versionAfter,selectionsBefore,selectionsAfter,lineAnnotationsBefore,lineAnnotationsAfter){const forwardEdits=[...resolvedEdits].sort((a,b)=>a.start-b.start),inverseEdits=[];let coalescingMode;if(selectionsBefore?.length===forwardEdits.length){const caretOffsets=[];for(const selection of selectionsBefore){if(selection.start.line!==selection.end.line||selection.start.character!==selection.end.character)break;caretOffsets.push(textDocument.offsetAt(selection.start))}if(caretOffsets.length===forwardEdits.length){caretOffsets.sort((a,b)=>a-b);let isBackspace=!0,isDelete=!0;for(let i=0;i<forwardEdits.length;i++){const edit=forwardEdits[i];if(edit.text.length>0||edit.start===edit.end){isBackspace=!1,isDelete=!1;break}isBackspace&&=caretOffsets[i]===edit.end,isDelete&&=caretOffsets[i]===edit.start}coalescingMode=isBackspace?COALESCING_MODE_BACKSPACE:isDelete?COALESCING_MODE_DELETE:void 0}}for(let i=0,offsetDelta=0;i<forwardEdits.length;i++){const edit=forwardEdits[i],replacedText=textDocument.getTextSlice(edit.start,edit.end),startAfterEdit=edit.start+offsetDelta;inverseEdits.push({start:startAfterEdit,end:startAfterEdit+edit.text.length,text:replacedText}),offsetDelta+=edit.text.length-(edit.end-edit.start)}return{forwardEdits:forwardEdits.map(edit=>({...edit})),inverseEdits,versionBefore,versionAfter,selectionsBefore:selectionsBefore?.map(selection=>({...selection})),selectionsAfter:selectionsAfter?.map(selection=>({...selection})),lineAnnotationsBefore:lineAnnotationsBefore?.slice(),lineAnnotationsAfter:lineAnnotationsAfter?.slice(),coalescingMode}}function shouldCoalesceEditStackEntry(previousEntry,nextEntry){if(previousEntry===void 0||previousEntry.undoBoundary===!0||nextEntry.undoBoundary===!0||previousEntry.forwardEdits.length===0||previousEntry.forwardEdits.length!==previousEntry.inverseEdits.length||previousEntry.forwardEdits.length!==nextEntry.forwardEdits.length||nextEntry.forwardEdits.length!==nextEntry.inverseEdits.length)return!1;let mode;for(let i=0;i<previousEntry.forwardEdits.length;i++){const previousForward=previousEntry.forwardEdits[i],previousInverse=previousEntry.inverseEdits[i],nextForward=nextEntry.forwardEdits[i],nextInverse=nextEntry.inverseEdits[i],mappedNextStart=mapOffsetAfterForwardBatchToBefore(nextForward.start,previousEntry.forwardEdits),previousWasInsert=previousForward.start<=previousForward.end&&previousForward.text.length>0&&!previousForward.text.includes(`
2
2
  `)&&!previousInverse.text.includes(`
3
3
  `),nextIsInsert=nextForward.start===nextForward.end&&nextForward.text.length>0&&!nextForward.text.includes(`
4
4
  `)&&nextInverse.text.length===0;if(previousWasInsert&&nextIsInsert){if(nextForward.start!==previousInverse.end||(mode??=COALESCING_MODE_INSERT,mode!==COALESCING_MODE_INSERT||previousEntry.coalescingMode!==void 0&&previousEntry.coalescingMode!==COALESCING_MODE_INSERT||nextEntry.coalescingMode!==void 0&&nextEntry.coalescingMode!==COALESCING_MODE_INSERT))return!1;continue}const previousWasDelete=previousForward.text.length===0&&previousForward.end>previousForward.start&&previousInverse.text.length>0,nextIsDelete=nextForward.text.length===0&&nextForward.end>nextForward.start&&nextInverse.text.length>0;if(previousWasDelete&&nextIsDelete){let nextMode;if(mappedNextStart===previousForward.end)nextMode=COALESCING_MODE_DELETE;else{if(mappedNextStart+(nextForward.end-nextForward.start)!==previousForward.start)return!1;nextMode=COALESCING_MODE_BACKSPACE}if(mode??=nextMode,mode!==nextMode||previousEntry.coalescingMode!==void 0&&previousEntry.coalescingMode!==nextMode||nextEntry.coalescingMode!==void 0&&nextEntry.coalescingMode!==nextMode)return!1;continue}return!1}return mode!==void 0}function coalesceEditStackEntries(previousEntry,nextEntry){const forwardEdits=[],replacedTexts=[];let coalescingMode;for(let i=0;i<previousEntry.forwardEdits.length;i++){const previousForward=previousEntry.forwardEdits[i],previousInverse=previousEntry.inverseEdits[i],nextForward=nextEntry.forwardEdits[i],nextInverse=nextEntry.inverseEdits[i],mappedNextStart=mapOffsetAfterForwardBatchToBefore(nextForward.start,previousEntry.forwardEdits);if(previousForward.text.length>0){coalescingMode??=COALESCING_MODE_INSERT,forwardEdits.push({start:previousForward.start,end:previousForward.end,text:previousForward.text+nextForward.text}),replacedTexts.push(previousInverse.text);continue}if(mappedNextStart===previousForward.end){coalescingMode??=COALESCING_MODE_DELETE,forwardEdits.push({start:previousForward.start,end:mappedNextStart+(nextForward.end-nextForward.start),text:""}),replacedTexts.push(previousInverse.text+nextInverse.text);continue}coalescingMode??=COALESCING_MODE_BACKSPACE,forwardEdits.push({start:Math.min(previousForward.start,mappedNextStart),end:previousForward.end,text:""}),replacedTexts.push(nextInverse.text+previousInverse.text)}return{forwardEdits,inverseEdits:buildInverseEditsFromReplacedTexts(forwardEdits,replacedTexts),versionBefore:previousEntry.versionBefore,versionAfter:nextEntry.versionAfter,selectionsBefore:previousEntry.selectionsBefore?.slice(),selectionsAfter:nextEntry.selectionsAfter?.slice(),lineAnnotationsBefore:previousEntry.lineAnnotationsBefore?.slice(),lineAnnotationsAfter:nextEntry.lineAnnotationsAfter?.slice(),coalescingMode}}function buildInverseEditsFromReplacedTexts(forwardEdits,replacedTexts){const inverseEdits=[];for(let i=0,offsetDelta=0;i<forwardEdits.length;i++){const edit=forwardEdits[i],startAfterEdit=edit.start+offsetDelta;inverseEdits.push({start:startAfterEdit,end:startAfterEdit+edit.text.length,text:replacedTexts[i]}),offsetDelta+=edit.text.length-(edit.end-edit.start)}return inverseEdits}function mapOffsetAfterForwardBatchToBefore(offsetAfter,forwardEdits){let offset=offsetAfter;for(const edit of forwardEdits){const oldLength=edit.end-edit.start,newLength=edit.text.length,delta=newLength-oldLength;if(!(offset<edit.start)){if(offset>=edit.start+newLength){offset-=delta;continue}offset=edit.start+Math.min(offset-edit.start,oldLength)}}return offset}const MAX_FIND_MATCHES=1e5,LINE_FEED=10,CARRIAGE_RETURN=13,WORD_SEPARATORS="`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";var Piece=class{source;offset;length;lineOffsetStart;lineOffsetEnd;hasVirtualTrailingCRBreak;firstCharCode;lastCharCode;static Original=0;static Added=1;constructor(source,offset,length,lineOffsetStart,lineOffsetEnd,hasVirtualTrailingCRBreak,firstCharCode,lastCharCode){this.source=source,this.offset=offset,this.length=length,this.lineOffsetStart=lineOffsetStart,this.lineOffsetEnd=lineOffsetEnd,this.hasVirtualTrailingCRBreak=hasVirtualTrailingCRBreak,this.firstCharCode=firstCharCode,this.lastCharCode=lastCharCode}get lineBreakCount(){return this.lineOffsetEnd-this.lineOffsetStart+(this.hasVirtualTrailingCRBreak?1:0)}},TextBuffer=class{text;lineOffsets;constructor(text){this.text=text,this.lineOffsets=computeLineOffsets(text)}append(text){const offset=this.text.length;for(let i=0;i<text.length;i++){const charCode=text.charCodeAt(i);charCode!==LINE_FEED&&charCode!==CARRIAGE_RETURN||(charCode===CARRIAGE_RETURN&&text.charCodeAt(i+1)===LINE_FEED&&i++,this.lineOffsets.push(offset+i+1))}return this.text+=text,offset}},PieceNode=class{piece;subtreeLength;subtreeLineBreakCount;subtreeFirstCharCode;subtreeLastCharCode;left=null;right=null;parent=null;priority=0;constructor(piece,subtreeLength=piece.length,subtreeLineBreakCount=piece.lineBreakCount,subtreeFirstCharCode=piece.firstCharCode,subtreeLastCharCode=piece.lastCharCode){this.piece=piece,this.subtreeLength=subtreeLength,this.subtreeLineBreakCount=subtreeLineBreakCount,this.subtreeFirstCharCode=subtreeFirstCharCode,this.subtreeLastCharCode=subtreeLastCharCode}updateSubtreeLength(){this.subtreeLength=(this.left?.subtreeLength??0)+this.piece.length+(this.right?.subtreeLength??0),this.subtreeLineBreakCount=(this.left?.subtreeLineBreakCount??0)+this.piece.lineBreakCount+(this.right?.subtreeLineBreakCount??0)-(formsCRLF(this.left?.subtreeLastCharCode,this.piece.firstCharCode)?1:0)-(formsCRLF(this.piece.lastCharCode,this.right?.subtreeFirstCharCode)?1:0),this.subtreeFirstCharCode=this.left?.subtreeFirstCharCode??this.piece.firstCharCode,this.subtreeLastCharCode=this.right?.subtreeLastCharCode??this.piece.lastCharCode}},PieceTable=class{#original;#add=new TextBuffer("");#root=null;#length=0;#lineCount=0;#lastVisitedLine=null;#lastVisitedLineLength=null;#lastPosition=null;#priorityState=2654435769;constructor(originalText){this.#original=new TextBuffer(originalText);const piece=this.#createPiece(Piece.Original,0,originalText.length);this.#root=piece.length>0?this.#createNode(piece):null,this.#length=this.#root?.subtreeLength??0,this.#lineCount=(this.#root?.subtreeLineBreakCount??0)+1}get lineCount(){return this.#lineCount}getText(range){if(range===void 0)return this.#textFromPieces();const start=this.offsetAt(range.start),end=this.offsetAt(range.end);return this.getTextSlice(start,end)}getLineText(line,includeLineBreak=!1){if(this.#lastVisitedLine!==null&&this.#lastVisitedLine[0]===line&&this.#lastVisitedLine[1]===includeLineBreak)return this.#lastVisitedLine[2];const offset=this.#getLineOffset(line);if(offset===void 0)throw new Error(`Line index out of range: ${line}`);const text=this.getTextSlice(offset[0],offset[1],!includeLineBreak);return this.#lastVisitedLine=[line,includeLineBreak,text],this.#lastVisitedLineLength=[line,includeLineBreak,text.length],text}getLineLength(line,includeLineBreak=!1){const lastVisitedLineLength=this.#lastVisitedLineLength,lastVisitedLine=this.#lastVisitedLine;if(lastVisitedLineLength!==null&&lastVisitedLineLength[0]===line&&lastVisitedLineLength[1]===includeLineBreak)return lastVisitedLineLength[2];if(lastVisitedLine!==null&&lastVisitedLine[0]===line&&lastVisitedLine[1]===includeLineBreak){const length2=lastVisitedLine[2].length;return this.#lastVisitedLineLength=[line,includeLineBreak,length2],length2}const offset=this.#getLineOffset(line);if(offset===void 0)throw new Error(`Line index out of range: ${line}`);const[start,end]=offset;let length=end-start;if(!includeLineBreak)for(;length>0&&isEOL(this.charAt(start+length-1).charCodeAt(0));)length--;return this.#lastVisitedLineLength=[line,includeLineBreak,length],length}getTextSlice(start,end,trimEOF=!1){if(start>=end)return"";const sliceStart=clamp(start,0,this.#length),sliceEnd=clamp(end,sliceStart,this.#length);if(sliceStart>=sliceEnd)return"";const location=this.#findPieceAtOffset(sliceStart);if(location===void 0)return"";const chunks=[];let[node,offsetInPiece]=location,remaining=sliceEnd-sliceStart;for(;node!==null&&remaining>0;){const takeLength=Math.min(node.piece.length-offsetInPiece,remaining),buffer=this.#bufferFor(node.piece.source),start2=node.piece.offset+offsetInPiece;let end2=start2+takeLength;if(trimEOF)for(;end2>start2&&isEOL(buffer.text.charCodeAt(end2-1));)end2--;chunks.push(buffer.text.slice(start2,end2)),remaining-=takeLength,offsetInPiece=0,node=this.#nextNode(node)}return chunks.join("")}charAt(offset){const location=this.#findPieceAtOffset(offset);if(location===void 0)return"";const[node,offsetInPiece]=location;return this.#bufferFor(node.piece.source).text.charAt(node.piece.offset+offsetInPiece)}includes(needle){if(needle.length===0)return!0;const prefixTable=createPrefixTable(needle);let matched=0,found=!1;return this.#forEachPieceSegment(segment=>{for(let offset=segment.start;offset<segment.end;offset++){const charCode=segment.text.charCodeAt(offset);for(;matched>0&&charCode!==needle.charCodeAt(matched);)matched=prefixTable[matched-1];if(charCode===needle.charCodeAt(matched)&&matched++,matched===needle.length)return found=!0,!1}return!0}),found}findNextNonOverlappingSubstring(needle,occupied){if(needle.length===0||needle.length>this.#length)return;const ranges=normalizeRanges(occupied,this.#length),pivot=ranges.reduce((max,[,end])=>Math.max(max,end),0),prefixTable=createPrefixTable(needle);let matched=0,documentOffset=0,wrappedOffset,foundOffset;return this.#forEachPieceSegment(segment=>{for(let offset=segment.start;offset<segment.end;offset++){const charCode=segment.text.charCodeAt(offset);for(;matched>0&&charCode!==needle.charCodeAt(matched);)matched=prefixTable[matched-1];if(charCode===needle.charCodeAt(matched)&&matched++,matched===needle.length){const start=documentOffset-needle.length+1;if(!rangeOverlaps(ranges,start,start+needle.length)){if(start>=pivot)return foundOffset=start,!1;wrappedOffset??=start}matched=prefixTable[matched-1]}documentOffset++}return!0}),foundOffset??wrappedOffset}search(searchParams){if(searchParams.text.length===0||this.#length===0)return[];if(searchParams.text.includes(`
@@ -64,7 +64,7 @@ import{j as jsxRuntimeExports,r as reactExports}from"./vendor-react-CxJ4vs-5.js"
64
64
  `}),this.#editorStyleElement=h("style",{dataset:"editorCss",textContent:editor_default}),this.#themeStyleElement=h("style",{dataset:"editorThemeCss"}),this.#spriteElement=createSpriteElement(),this.#overlayElement=h("div",{dataset:"editorOverlay"});const replacementFocusTargetIsContent=event=>{const target=event.composedPath()[0];return target instanceof Node&&this.#contentElement?.contains(target)===!0},cancelReplacementFocus=()=>{this.#replacementFocusRequest!=null&&(this.#replacementFocusRequest=void 0,this.#contentHasFocus=!1,this.#shouldIgnoreSelectionChange=!1)},finishMouseSelection=event=>{if(event.pointerType!=="mouse")return;const refocusEditor=this.#isGutterMouseDown;this.#resetSelectionGesture(),refocusEditor&&this.#focus(),this.#options.enabledSelectionAction===!0&&this.#selections!==void 0&&this.#selections.length>0&&!isCollapsedSelection(this.#selections.at(-1))&&this.#updateSelections(this.#selections)};this.#globalEventDisposes=[addEventListener(document,"focusin",event=>{replacementFocusTargetIsContent(event)||cancelReplacementFocus()},{passive:!0}),addEventListener(document,"pointerdown",event=>{replacementFocusTargetIsContent(event)||queueMicrotask(cancelReplacementFocus)},{capture:!0,passive:!0}),addEventListener(document,"selectionchange",()=>{const shadowRoot=this.#fileContainer?.shadowRoot;if(this.#shouldIgnoreSelectionChange||this.#suppressNativeSelectionSync||shadowRoot==null||!this.#contentHasFocus||this.#selections!==void 0&&this.#selections.length>1&&!this.#isContentMouseDown)return;const selectionRaw=document.getSelection();if(selectionRaw==null)return;let composedRange;if(typeof selectionRaw.getComposedRanges=="function"?composedRange=selectionRaw.getComposedRanges({shadowRoots:[shadowRoot]})?.[0]:composedRange=getShadowRootRange(shadowRoot),composedRange===void 0||!this.#rangeBelongsToEditor(composedRange))return;const selection=convertSelection(composedRange,0);if(selection!==void 0){if(this.#isContentMouseDown&&this.#shiftKeyPressed&&this.#selections!==void 0&&this.#selections.length>0){const primarySelection=this.#selections.at(-1);this.#updateSelections([extendSelection(primarySelection,selection)]);return}if(this.#selectionStart!==void 0)selection.direction=createSelectionFrom(this.#selectionStart,selection).direction;else if(this.#isContentMouseDown)this.#selectionStart=selection;else if(this.#selections!==void 0&&this.#selections.length===1){const previous=this.#selections[0];comparePosition(previous.start,selection.start)===0&&comparePosition(previous.end,selection.end)===0&&(selection.direction=previous.direction)}this.#altColumnDrag!==void 0&&(this.#altColumnDrag.focusLine=getCaretPosition(selection).line,this.#updateAltColumnSelections())||(this.#reservedSelections!==void 0?this.#updateSelections([...this.#reservedSelections.filter(reservedSelection=>!selectionIntersects(reservedSelection,selection)),selection]):this.#updateSelections([selection]))}},{passive:!0}),addEventListener(document,"pointerup",finishMouseSelection,{passive:!0}),addEventListener(document,"pointercancel",finishMouseSelection,{passive:!0}),addEventListener(document,"keydown",e=>{e.key==="Shift"?this.#selectionStart=this.#selections?.at(-1):e.key==="Alt"&&!e.repeat&&this.#contentHasFocus&&this.#options.editPrediction?.mode==="subtle"&&(this.#editPredictionRevealed=!this.#editPredictionRevealed,this.#updateSelections(this.#selections??[]))},{passive:!0}),addEventListener(document,"keyup",e=>{e.key==="Shift"&&(this.#selectionStart=void 0)},{passive:!0})]}#resetSelectionGesture(){this.#selectEventDisposes?.forEach(dispose=>dispose()),this.#selectEventDisposes=void 0,this.#shouldIgnoreSelectionChange=!1,this.#isGutterMouseDown=!1,this.#isContentMouseDown=!1,this.#altColumnDrag=void 0,this.#shiftKeyPressed=!1,this.#selectionStart=void 0,this.#reservedSelections=void 0}#replaceSelectEventListeners(disposes){this.#selectEventDisposes?.forEach(dispose=>dispose()),this.#selectEventDisposes=disposes}#isLineSelectionEnabled(){return this.#fileInstance?.options.enableLineSelection===!0}#preserveEditorSelectionsForGutterGesture(){this.#suppressNativeSelectionSync=this.#selections!==void 0}#listenContentElement(contentEl,gutterEl){const{onFocus,onBlur}=this.#options,targetIsContentElement=e=>{const target=e.composedPath()[0];return target!==void 0&&(target===contentEl||contentEl.contains(target))};this.#editorEventDisposes?.forEach(dispose=>dispose()),this.#editorEventDisposes=[addEventListener(contentEl,"focus",()=>{this.#contentHasFocus=!0,onFocus?.(),!this.#isContentMouseDown&&!this.#shouldIgnoreSelectionChange&&this.#selections!==void 0&&this.#selections.length>0&&this.#setWindowSelection(this.#selections.at(-1))},{passive:!0}),addEventListener(contentEl,"blur",()=>{this.#replacementFocusRequest?.target===contentEl&&(this.#replacementFocusRequest=void 0,this.#shouldIgnoreSelectionChange=!1),this.#contentHasFocus=!1,onBlur?.()},{passive:!0}),addEventListener(contentEl,"pointerdown",e=>{if(this.#canMountSelectionAction=!0,this.#suppressNativeSelectionSync=!1,e.pointerType!=="mouse")return;if(this.#altColumnDrag=void 0,this.#isDeletedLineTarget(e)){this.#setDeletedTextSelectionActive(!0),this.#selections!==void 0&&this.#updateSelections([]);return}this.#setDeletedTextSelectionActive(!1),this.#markerRenderer?.removePopover();const selectEventDisposes=[];if(isSafari()&&this.#lineAnnotations!==void 0&&this.#lineAnnotations.length>0){const annotationDisposes=[...contentEl.querySelectorAll("[data-line-annotation]")].map(el=>[addEventListener(el,"mouseenter",()=>{this.#shouldIgnoreSelectionChange=!0}),addEventListener(el,"mouseleave",()=>{this.#shouldIgnoreSelectionChange=!1})]).flat();selectEventDisposes.push(...annotationDisposes)}this.#isContentMouseDown=!0;const isAltColumnDrag=e.button===0&&e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey;if(this.#selectionStart=void 0,isAltColumnDrag?(this.#altColumnDrag={pointerId:e.pointerId,startClientX:e.clientX,clientX:e.clientX,startScrollLeft:contentEl.parentElement?.scrollLeft??0},this.#reservedSelections=void 0,this.#selections=void 0,this.#updateSelections([]),selectEventDisposes.push(addEventListener(document,"pointermove",moveEvent=>{const drag=this.#altColumnDrag;drag===void 0||moveEvent.pointerType!=="mouse"||moveEvent.pointerId!==drag.pointerId||(drag.clientX=moveEvent.clientX,this.#updateAltColumnSelections())},{capture:!0,passive:!0}))):e.button===0&&isPrimaryModifier(e)&&(this.#reservedSelections=this.#selections?.map(selection=>({...selection}))),this.#replaceSelectEventListeners(selectEventDisposes),e.shiftKey){const primarySelection=this.#selections?.at(-1);if(primarySelection!==void 0){const pos=primarySelection.direction===-1?primarySelection.end:primarySelection.start;this.#setWindowSelection({start:pos,end:pos,direction:0})}this.#shiftKeyPressed=!0}},{passive:!0}),addEventListener(contentEl,"keydown",e=>{if(!targetIsContentElement(e)||(this.#canMountSelectionAction=!0,this.#suppressNativeSelectionSync=!1,e.isComposing||e.keyCode===229))return;if(e.key==="Tab"&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.isComposing&&!this.#isComposing&&(!e.altKey||this.#options.editPrediction?.mode==="subtle")&&this.#editPrediction?.rendered===!0){this.#acceptEditPrediction(),e.preventDefault();return}if(e.key==="Escape"&&this.#editPrediction!==void 0){this.#cancelEditPrediction(!0),e.preventDefault();return}const command=resolveEditorCommandFromKeyboardEvent(e,this.#options.keymap);if(command!==void 0){e.preventDefault(),command==="simplifySelection"&&(this.#searchPanel?.close(),this.#searchPanel=void 0,this.#retainSearchPanelFocus=!1,this.#selectionAction?.cleanup(),this.#selectionAction=void 0),this.#runCommand(command);return}const mvShortcut=isMoveCursorShortcut(e),textDocument=this.#editSession?.document;if(this.#selections!==void 0&&this.#selections.length>0&&mvShortcut!==void 0&&textDocument!==void 0){const cursorMoveOptions={getSoftLineOffsets:this.#isWrap?line=>this.#wrapLineTextOrWholeLine(line):void 0,resolveRenderableLine:this.#resolveRenderableLine};e.shiftKey?this.#updateSelections(mapSelectionShift(textDocument,this.#selections,mvShortcut,cursorMoveOptions)):this.#updateSelections(mapCursorMove(textDocument,this.#selections,mvShortcut,cursorMoveOptions)),this.#scrollToPrimaryCaret(),e.preventDefault();return}if((e.key.length===1?e.key.toLowerCase():e.key)==="v"&&isPrimaryModifier(e)){if(e.repeat&&this.#isDiff){e.preventDefault();return}if(this.#options.clipboard!==void 0){e.preventDefault(),queueRender(this.#handleCustomPasteEvent);return}}if(this.#searchPanel!==void 0){const findAgain=resolveFindAgainShortcut(e);if(findAgain!==void 0){e.preventDefault(),this.#searchPanel.navigate(findAgain==="previous");return}}}),addEventListener(contentEl,"copy",e=>{targetIsContentElement(e)&&(e.preventDefault(),this.#isDeletedTextSelectionActive()?e.clipboardData?.setData("text",this.#deletedTextForClipboard()):this.#writeSelectionClipboardData(e.clipboardData,this.#getSelectionText(),this.#getSelectionClipboardTexts()))}),addEventListener(contentEl,"cut",e=>{if(targetIsContentElement(e))if(e.preventDefault(),this.#isDeletedTextSelectionActive())e.clipboardData?.setData("text",this.#deletedTextForClipboard());else{const selectionTexts=this.#getSelectionClipboardTexts();this.#writeSelectionClipboardData(e.clipboardData,this.#cutSelectionText(),selectionTexts)}}),addEventListener(contentEl,"paste",e=>{if(!targetIsContentElement(e))return;e.preventDefault();const clipboardData=e.clipboardData,textDocument=this.#editSession?.document;if(clipboardData===null||textDocument===void 0)return;let text=clipboardData.getData("text");const selectionCount=this.#selections?.length??0;if(selectionCount>1){const multiSelectionText=clipboardData.getData(MULTI_SELECTION_CLIPBOARD_TYPE);if(multiSelectionText!==void 0)try{const selectionTexts=JSON.parse(multiSelectionText);Array.isArray(selectionTexts)&&selectionTexts.length===selectionCount&&(text=selectionTexts)}catch{}}this.#replaceSelectionText(Array.isArray(text)?text.map(t=>textDocument.normalizeEol(t)):textDocument.normalizeEol(text),void 0,!0,"document")}),addEventListener(contentEl,"beforeinput",e=>{if(targetIsContentElement(e)){if(e.inputType==="insertCompositionText"){this.#cancelEditPrediction(!0);return}e.preventDefault(),this.#handleInput(e.inputType,e.data)}}),addEventListener(contentEl,"drop",e=>{targetIsContentElement(e)&&e.preventDefault()}),addEventListener(contentEl,"compositionstart",e=>{targetIsContentElement(e)&&(this.#cancelEditPrediction(!0),this.#isComposing=!0,this.#shouldIgnoreSelectionChange=!0)},{passive:!0}),addEventListener(contentEl,"compositionend",e=>{if(!targetIsContentElement(e))return;this.#shouldIgnoreSelectionChange=!1;const wasComposing=this.#isComposing;this.#isComposing=!1,(e.data!==""||!wasComposing)&&this.#handleInput("insertText",e.data)},{passive:!0})];const deletionsCode=this.#fileContainer?.shadowRoot?.querySelector("[data-deletions]");if(deletionsCode!=null&&this.#editorEventDisposes.push(addEventListener(deletionsCode,"pointerdown",e=>{const path=e.composedPath();if(isGutterUtilityPath(path)){this.#preserveEditorSelectionsForGutterGesture();return}const target=path[0],gutterRow=target instanceof HTMLElement?target.closest("[data-column-number]"):null;if(gutterRow instanceof HTMLElement){if(this.#isLineSelectionEnabled()){this.#preserveEditorSelectionsForGutterGesture();return}if(this.#beginDeletionGutterSelection(gutterRow,deletionsCode,e.pointerType==="mouse"))return}this.#setDeletedTextSelectionActive(!0),this.#selections!==void 0&&this.#updateSelections([])},{passive:!0})),gutterEl!==void 0){const resolveGutterTarget=(eventTarget,includeContentLine=!1)=>{let target=eventTarget;return target?.dataset.lineNumberContent!==void 0?target=target.parentElement??void 0:includeContentLine&&target?.tagName==="SPAN"&&(target=target.closest("[data-line]")),target},resolveEditableLine=target=>{if(target===void 0)return;const lineType=target.dataset.lineType,lineNumber=getLineNumberAttr(target)??getLineNumberAttr(target,"columnNumber");if(!(lineNumber===void 0||lineType===void 0||!isLineEditable(lineType)))return lineNumber-1};this.#editorEventDisposes.push(addEventListener(gutterEl,"pointerdown",e=>{const path=e.composedPath();if(isGutterUtilityPath(path)){this.#preserveEditorSelectionsForGutterGesture();return}const gutterRow=resolveGutterTarget(path[0]);if(gutterRow!==void 0&&this.#isLineSelectionEnabled()){this.#preserveEditorSelectionsForGutterGesture();return}if(gutterRow?.dataset.lineType==="change-deletion"){const code=gutterRow.closest("[data-code]");code!=null&&this.#beginDeletionGutterSelection(gutterRow,code,e.pointerType==="mouse");return}if(e.pointerType!=="mouse")return;const textDocument=this.#editSession?.document,lineIndex=resolveEditableLine(gutterRow);if(lineIndex===void 0||textDocument===void 0)return;this.#canMountSelectionAction=!0,this.#markerRenderer?.removePopover();const selection=this.#spanLineSelection(lineIndex,lineIndex,textDocument);this.#isGutterMouseDown=!0,this.#selectionStart=selection,this.#updateSelections([selection]),this.#setWindowSelection(selection),this.#focus(),this.#replaceSelectEventListeners([addEventListener(document,"mousemove",e2=>{if(!this.#isGutterMouseDown)return;const textDocument2=this.#editSession?.document,lineIndex2=resolveEditableLine(resolveGutterTarget(e2.composedPath()[0],!0));if(lineIndex2===void 0||textDocument2===void 0)return;const anchorLine=this.#selectionStart?.start.line??lineIndex2,selection2=this.#spanLineSelection(anchorLine,lineIndex2,textDocument2);this.#selectionStart??=selection2,this.#updateSelections([selection2]),this.#focus(selection2.direction===-1?selection2.start:selection2.end)},{passive:!0})])},{passive:!0}))}this.#markerRenderer?.listenHover(contentEl),this.#resizeObserver?.disconnect(),this.#resizeObserver=new ResizeObserver(this.#handleLayoutResize),this.#resizeObserver.observe(contentEl),this.#resizeObserver.observe(contentEl.parentElement),this.#computeContentOffset(contentEl)}#handleCustomPasteEvent=async()=>{const clipboard=this.#options.clipboard;if(clipboard!==void 0){let text=await clipboard.readText();const selectionCount=this.#selections?.length??0;if(selectionCount>1){const multiSelectionText=await clipboard.readText(MULTI_SELECTION_CLIPBOARD_TYPE);try{const selectionTexts=JSON.parse(multiSelectionText);Array.isArray(selectionTexts)&&selectionTexts.length===selectionCount&&(text=selectionTexts)}catch{}}const textDocument=this.#editSession?.document;textDocument!=null&&this.#replaceSelectionText(Array.isArray(text)?text.map(t=>textDocument.normalizeEol(t)):textDocument.normalizeEol(text),void 0,!0,"document")}};#computeContentOffset(contentEl){this.#isDiff&&this.#diffSyle==="split"&&this.#isWrap&&(this.#contentOffset={top:contentEl.offsetTop-this.#metrics.paddingTop,left:contentEl.offsetLeft-this.#getGutterWidth()},this.#options.__debug===!0&&console.log("[diffs/editor] content offset:",this.#contentOffset))}get#activeContentOffset(){if(this.#isDiff&&this.#diffSyle==="split"&&this.#isWrap)return this.#contentOffset}#runCommand(command){const textDocument=this.#editSession?.document;if(textDocument!=null)switch(command){case"openSearchPanel":this.#openSearchPanel("find");break;case"openSearchReplacePanel":this.#openSearchPanel("replace");break;case"findNextMatch":{const selections=this.#selections;if(selections===void 0)break;if(selections.some(isCollapsedSelection)){const expanded=selections.map(sel=>isCollapsedSelection(sel)?expandCollapsedSelectionToWord(textDocument,sel):sel);this.#updateSelections(expanded),this.focus()}else{const nextMatch=findNextMatch(textDocument,selections);if(nextMatch!==void 0){this.#updateSelections(nextMatch);const primaryMatch=nextMatch.at(-1);primaryMatch!==void 0&&this.#revealLineIfCollapsed(getCaretPosition(primaryMatch).line),this.#scrollToPrimaryCaret()}}break}case"moveLineUp":case"moveLineDown":this.#moveSelectedLines(command==="moveLineUp"?-1:1);break;case"copyLineUp":case"copyLineDown":this.#copySelectedLines(command==="copyLineUp"?-1:1);break;case"simplifySelection":{const selections=this.#selections,primarySelection=selections?.at(-1);if(selections===void 0||primarySelection===void 0)break;if(selections.length>1)this.#updateSelections([primarySelection]),this.#focus(getCaretPosition(primarySelection));else if(!isCollapsedSelection(primarySelection)){const caret=getCaretPosition(primarySelection);this.#updateSelections([{start:caret,end:caret,direction:0}]),this.#focus(caret)}break}case"insertBlankLine":this.#insertBlankLine();break;case"deleteHardLineForward":this.#deleteHardLineForward();break;case"toggleComment":case"toggleBlockComment":{const selections=this.#selections;if(selections===void 0)break;const{lineComment,blockComment}=resolveCommentConfig(textDocument.languageId,this.#options.languageCommentConfig);if(command==="toggleComment"&&lineComment!==null){this.#applyCommandEdits(resolveLineCommentEdits(textDocument,selections,lineComment));break}const linewise=command==="toggleComment",result=resolveBlockCommentEdits(textDocument,selections,blockComment,linewise);result!==void 0&&this.#applyCommandEdits(result.edits,linewise?void 0:document2=>result.nextSelectionOffsets.map(([start,end,direction])=>({start:document2.positionAt(start),end:document2.positionAt(end),direction})));break}case"indent":case"outdent":case"indentLess":case"indentMore":if(this.#selections!==void 0){const edits=[],nextSelections=[],editedLines=new Set,sameLineIndents=[];for(const selection of this.#selections){const startLine=selection.start.line,outdent=command==="outdent"||command==="indentLess",lineBased=command==="indentLess"||command==="indentMore";if(startLine!==selection.end.line||outdent||lineBased){const ret=resolveIndentEdits(textDocument,selection,this.#metrics.tabSize,outdent);for(const edit of ret[0]){const line=edit.range.start.line;editedLines.has(line)||(editedLines.add(line),edits.push(edit))}nextSelections.push(ret[1])}else{const text=textDocument.charAt({line:startLine,character:0})===" "?" ":" ".repeat(this.#metrics.tabSize);edits.push({range:selection,newText:text}),sameLineIndents.push({line:startLine,startCharacter:selection.start.character,addedLength:text.length-(selection.end.character-selection.start.character),selectionIndex:nextSelections.length});const nextPosition={line:selection.start.line,character:selection.start.character+text.length};nextSelections.push({start:nextPosition,end:nextPosition,direction:0})}}for(const indent of sameLineIndents){let shift=0;for(const other of sameLineIndents)other.line===indent.line&&other.startCharacter<indent.startCharacter&&(shift+=other.addedLength);if(shift!==0){const current=nextSelections[indent.selectionIndex],position={line:indent.line,character:current.start.character+shift};nextSelections[indent.selectionIndex]={start:position,end:position,direction:0}}}const change=textDocument.applyEdits(edits,!0,this.#selections,nextSelections);change!==void 0&&this.#applyChange(change,nextSelections)}break;case"selectAll":{const fullSelection=getDocumentFullSelection(textDocument);this.#updateSelections([fullSelection]),this.focus();const renderedLineRanges=this.#getRenderedEditableLineRanges(),firstRenderedLine=renderedLineRanges[0]?.[0],lastRenderedLine=renderedLineRanges.at(-1)?.[1];firstRenderedLine!==void 0&&lastRenderedLine!==void 0&&(this.#suppressNativeSelectionSync=!0,this.#setWindowSelection({start:{line:firstRenderedLine,character:0},end:{line:lastRenderedLine,character:textDocument.getLineLength(lastRenderedLine)},direction:1}));break}case"moveCursorToDocStart":case"moveCursorToDocEnd":{const boundarySelection=getDocumentBoundarySelection(textDocument,command==="moveCursorToDocEnd",this.#isDiff);this.#updateSelections([boundarySelection]),this.#revealLineIfCollapsed(getCaretPosition(boundarySelection).line),this.#scrollToPrimaryCaret()}break;case"expandSelectionDocStart":case"expandSelectionDocEnd":{const atEnd=command==="expandSelectionDocEnd",selections=this.#selections;if(selections!==void 0){const boundarySelection=getDocumentBoundarySelection(textDocument,atEnd,this.#isDiff);this.#updateSelections(extendSelections(selections,boundarySelection)),this.#revealLineIfCollapsed(getCaretPosition(boundarySelection).line),this.#scrollToPrimaryCaret()}}break;case"undo":case"redo":this.#applyHistoryChange(command)}}#applyHistoryChange(command){const textDocument=this.#editSession?.document;if(textDocument==null||command==="undo"&&!textDocument.canUndo||command==="redo"&&!textDocument.canRedo)return;const selections=this.#selections,selectionOffsets=selections?.map(selection=>[textDocument.offsetAt(selection.start),textDocument.offsetAt(selection.end)]),result=command==="undo"?textDocument.undo():textDocument.redo();if(result===void 0)return;const[change,recordedSelections,lineAnnotations,selectionEdits]=result,nextSelections=recordedSelections??(selections!==void 0&&selectionOffsets!==void 0&&selectionEdits!==void 0?remapSelectionsAfterEdits(textDocument,selections,selectionOffsets,selectionEdits):void 0),replayedLineAnnotations=lineAnnotations??(this.#lineAnnotations!=null?applyDocumentChangeToLineAnnotations(change,this.#lineAnnotations):void 0);this.#applyChange(change,nextSelections,replayedLineAnnotations)}#applyCommandEdits(edits,resolveNextSelections){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0)return;const remapSelections=resolveNextSelections===void 0,selectionOffsets=remapSelections?selections.map(selection=>[textDocument.offsetAt(selection.start),textDocument.offsetAt(selection.end)]):void 0,resolvedEdits=remapSelections?edits.map(edit=>{const start=textDocument.offsetAt(edit.range.start),end=textDocument.offsetAt(edit.range.end);return{start:Math.min(start,end),end:Math.max(start,end),text:edit.newText}}).sort((a,b)=>{const startOrder=a.start-b.start;return startOrder!==0?startOrder:a.end-b.end}):void 0,change=textDocument.applyEdits(edits,!0,selections,void 0,!0);if(change===void 0)return;const nextSelections=remapSelections?remapSelectionsAfterEdits(textDocument,selections,selectionOffsets,resolvedEdits):resolveNextSelections(textDocument);textDocument.setLastUndoSelectionsAfter(nextSelections),this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#copySelectedLines(direction){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0)return;const blocks=getSelectedLineBlocks(selections);if(blocks.length===0)return;const copiedLinesBefore=[];let copiedLineCount=0;const edits=[];for(const block of blocks){copiedLinesBefore.push(copiedLineCount);const blockLineCount=block.endLine-block.startLine+1;copiedLineCount+=blockLineCount;const text=textDocument.getText({start:{line:block.startLine,character:0},end:{line:block.endLine,character:textDocument.getLineLength(block.endLine)}});if(direction>0){const position={line:block.startLine,character:0};edits.push({range:{start:position,end:position},newText:text+textDocument.eol})}else if(block.endLine<textDocument.lineCount-1){const position={line:block.endLine+1,character:0};edits.push({range:{start:position,end:position},newText:text+textDocument.eol})}else{const position={line:block.endLine,character:textDocument.getLineLength(block.endLine)};edits.push({range:{start:position,end:position},newText:textDocument.eol+text})}}const nextSelections=selections.map(selection=>{const line=selection.start.line;let low=0,high=blocks.length-1;for(;low<=high;){const middle=low+high>>>1,block2=blocks[middle];if(line<block2.startLine)high=middle-1;else if(line>block2.endLine)low=middle+1;else{low=middle;break}}const blockIndex=Math.max(0,low<=high?low:high),block=blocks[blockIndex],shift=copiedLinesBefore[blockIndex]+(direction>0?block.endLine-block.startLine+1:0);return{start:{...selection.start,line:selection.start.line+shift},end:{...selection.end,line:selection.end.line+shift},direction:selection.direction}});this.#applyCommandEdits(edits,()=>nextSelections)}#insertBlankLine(){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0)return;const selectionLines=selections.map(selection=>getCaretPosition(selection).line),targetLines=Array.from(new Set(selectionLines)).sort((a,b)=>a-b),targetIndex=new Map,indents=new Map,edits=[];for(let index=0;index<targetLines.length;index++){const line=targetLines[index],lineText=textDocument.getLineText(line),indent=/^\s*/.exec(lineText)?.[0]??"";targetIndex.set(line,index),indents.set(line,indent);const position={line,character:textDocument.getLineLength(line)};edits.push({range:{start:position,end:position},newText:textDocument.eol+indent})}const nextSelections=selections.map((_,index)=>{const line=selectionLines[index],position={line:line+1+targetIndex.get(line),character:indents.get(line).length};return{start:position,end:position,direction:0}});this.#applyCommandEdits(edits,()=>nextSelections)}#moveSelectedLines(direction){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0)return;const blocks=getSelectedLineBlocks(selections);if(blocks.length===0||direction<0&&blocks[0].startLine===0||direction>0&&blocks.at(-1).endLine>=textDocument.lineCount-1)return;const lineCount=textDocument.lineCount,lineRangeEnd=line=>line<lineCount-1?{line:line+1,character:0}:{line,character:textDocument.getLineLength(line)},getLinesText=(lines,appendFinalLineBreak)=>{const text=lines.map(line=>textDocument.getLineText(line)).join(textDocument.eol);return appendFinalLineBreak?text+textDocument.eol:text},edits=[];if(direction<0)for(const block of blocks){const previousLine=block.startLine-1,blockLines=[];for(let line=block.startLine;line<=block.endLine;line++)blockLines.push(line);edits.push({range:{start:{line:previousLine,character:0},end:lineRangeEnd(block.endLine)},newText:getLinesText([...blockLines,previousLine],block.endLine<lineCount-1)})}else for(let index=blocks.length-1;index>=0;index--){const block=blocks[index],nextLine=block.endLine+1,blockLines=[];for(let line=block.startLine;line<=block.endLine;line++)blockLines.push(line);edits.push({range:{start:{line:block.startLine,character:0},end:lineRangeEnd(nextLine)},newText:getLinesText([nextLine,...blockLines],nextLine<lineCount-1)})}const lastBlock=blocks.at(-1),lastLineLengthAfterMove=direction>0&&lastBlock.endLine===lineCount-2?textDocument.getLineLength(lastBlock.endLine):textDocument.getLineLength(lineCount-1),nextSelections=selections.map(selection=>shiftSelectionLines(selection,direction,lineCount,line=>line===lineCount-1?lastLineLengthAfterMove:textDocument.getLineLength(line))),change=textDocument.applyEdits(edits,!0,selections,nextSelections,!0);change!==void 0&&this.#applyChange(change,nextSelections)}#handleLayoutResize=()=>{const lineAnnotations=this.#lineAnnotations?.length??0,prevGutterWidth=this.#gutterWidthCache,prevContentWidth=this.#contentWidthCache;this.#gutterWidthCache=void 0,this.#contentWidthCache=void 0;const gutterWidthChanged=this.#getGutterWidth()!==prevGutterWidth,contentWidthChanged=this.#getContentWidth()!==prevContentWidth;!gutterWidthChanged&&!contentWidthChanged||(this.#lineElementsCache.clear(),this.#lastAccessedCharX=void 0,this.#metrics.clearTextWidthCache(),contentWidthChanged&&(this.#wrapLineOffsetsCache.clear(),(this.#isWrap||lineAnnotations>0)&&this.#lineYCache.clear()),(this.#selections!==void 0||this.#matches!==void 0||this.#markerRenderer!==void 0)&&(this.#updateSelections(this.#selections??[]),this.#selections!==void 0&&this.#contentHasFocus&&this.focus()),this.#markerRenderer?.removePopover(),this.#computeContentOffset(this.#contentElement),this.#renderCarets())};#remeasureMetricsOnFontLoad(){if(this.#fontRemeasureScheduled)return;const fonts=document.fonts;fonts!==void 0&&(this.#fontRemeasureScheduled=!0,fonts.ready.then(()=>{this.#contentElement===void 0||!this.#metrics.remeasureCharacterWidth()||(this.#gutterWidthCache=void 0,this.#contentWidthCache=void 0,this.#resetCache(),this.#wrapLineOffsetsCache.clear(),(this.#selections!==void 0||this.#matches!==void 0||this.#markerRenderer!==void 0)&&this.#updateSelections(this.#selections??[]),this.#renderCarets(),this.#markerRenderer?.removePopover())}))}#rerender(change,newLineAnnotations,renderRange=this.#renderRange,shouldUpdateBuffer){const tokenizer=this.#tokenizer,fileInstance=this.#fileInstance,applyDocumentChange=this.#applyDocumentChange,textDocument=this.#editSession?.document,gutterEl=this.#gutterElement,contentEl=this.#contentElement;if(tokenizer==null||fileInstance==null||applyDocumentChange==null||textDocument==null||contentEl==null)return;tokenizer.stopBackgroundTokenize();const t=performance.now(),dirtyLines=tokenizer.tokenize(change,renderRange,!this.#isDiff&&this.#virtualizedInstance!=null),t2=performance.now();if(dirtyLines.size>0){const children=contentEl.children,dirtyLineIndexes=new Set;for(const lineIndex of dirtyLines.keys())this.#isLineRenderable(lineIndex)&&dirtyLineIndexes.add(lineIndex);for(let i=0;i<children.length;i++){const child=children[i];if(child!==void 0){const lineNumber=getLineNumberAttr(child),lineType=child.dataset.lineType;if(lineNumber===void 0||lineType==="change-deletion")continue;const lineIndex=lineNumber-1;if(dirtyLineIndexes.has(lineIndex)){const tokens=dirtyLines.get(lineIndex);if(child.replaceChildren(...renderLineTokens(tokens)),dirtyLineIndexes.delete(lineIndex),dirtyLineIndexes.size===0)break}}}if(dirtyLineIndexes.size>0){let lastRenderedLineNumber=0;for(let i=children.length-1;i>=0;i--){const child=children[i],lineNumber=getLineNumberAttr(child);if(lineNumber!==void 0&&child.dataset.lineType!=="change-deletion"){lastRenderedLineNumber=lineNumber;break}}for(const lineIndex of dirtyLineIndexes){if(lineIndex<lastRenderedLineNumber)continue;const tokens=dirtyLines.get(lineIndex),lineNumber=String(lineIndex+1);h("div",{dataset:{line:lineNumber,lineType:"context",lineIndex:lineIndex.toString()},children:renderLineTokens(tokens)},contentEl),gutterEl!==void 0&&h("div",{dataset:{lineType:"context",columnNumber:lineNumber,lineIndex:lineIndex.toString()},children:[h("span",{dataset:{lineNumberContent:""},textContent:lineNumber})]},gutterEl)}}}if(change.lineDelta<0)for(const children of[contentEl.children,gutterEl?.children??[]])for(let i=children.length-1;i>=0;i--){const child=children[i],lineNumber=getLineNumberAttr(child)??getLineNumberAttr(child,"columnNumber"),lineType=child.dataset.lineType;if(!(lineNumber===void 0||lineType==="change-deletion")){if(lineNumber-1<change.lineCount)break;child.remove()}}const didLineCountChange=change.lineDelta!==0;if(didLineCountChange){let gridRow=contentEl.children.length;for(const child of contentEl.children){const{bufferSize}=child.dataset;bufferSize!==void 0&&(gridRow+=parseInt(bufferSize)-1)}contentEl.style.gridRow="span "+gridRow,gutterEl!==void 0&&(gutterEl.style.gridRow="span "+gridRow)}fileInstance.updateRenderCache(dirtyLines,tokenizer.themeType,{shouldRefreshDiffsView:this.#isDiff&&!didLineCountChange,lineCountChangeInFlight:didLineCountChange,changedDocumentLines:this.#isDiff&&!didLineCountChange?getChangedDocumentLines(textDocument,change):void 0,documentLineCount:textDocument.lineCount}),didLineCountChange&&applyDocumentChange(textDocument,newLineAnnotations,shouldUpdateBuffer),(didLineCountChange||this.#isDiff&&this.#diffSyle==="unified")&&this.#resetCache(),newLineAnnotations!=null&&(this.#lineAnnotations=newLineAnnotations,(!this.#isDiff||!didLineCountChange)&&renderLineAnnotations(newLineAnnotations,contentEl,gutterEl,fileInstance.getAnnotationSlotName)),this.#renderCarets(),this.#options.__debug===!0&&console.log(`[diffs/editor] re-render in: ${round(performance.now()-t2)}ms,`,`tokenize in: ${round(t2-t)}ms (${dirtyLines.size} dirty lines)`)}#handleInput(inputType,data){switch(inputType){case"insertText":{const text=data??"",textDocument=this.#editSession?.document,selections=this.#selections,autoSurroundTexts=textDocument!==void 0&&selections!==void 0?getAutoSurroundReplacementTexts(textDocument,selections,text,this.#options.autoSurround):void 0;this.#replaceSelectionText(autoSurroundTexts??text);break}case"insertCompositionText":break;case"insertLineBreak":case"insertParagraph":this.#replaceSelectionText(this.#editSession?.document?.eol??`
65
65
  `);break;case"deleteContentBackward":this.#deleteSelectionText();break;case"deleteContentForward":this.#deleteSelectionText(!0);break;case"deleteSoftLineBackward":case"deleteHardLineBackward":this.#deleteSoftLineBackward();break;case"deleteWordBackward":this.#deleteWordBackward();break;case"insertTranspose":this.#insertTranspose();break;default:console.warn(`[diffs] Unknown input type: ${inputType}`,data)}}#focus(position,preventScroll=!0,shouldFocus){this.#contentHasFocus=!0,position!==void 0?(this.#shouldIgnoreSelectionChange=!0,this.#setWindowSelection({start:position,end:position,direction:0}),queueRender(()=>{if(shouldFocus?.()===!1||!this.#contentHasFocus){this.#shouldIgnoreSelectionChange=!1;return}this.#contentElement?.focus({preventScroll}),queueRender(()=>{this.#shouldIgnoreSelectionChange=!1})})):shouldFocus?.()!==!1?this.#contentElement?.focus({preventScroll}):this.#contentHasFocus=!1}#restoreReplacementFocus(position){const request=this.#replacementFocusRequest;if(request==null)return;if(this.#retainSearchPanelFocus){this.#replacementFocusRequest=void 0,this.#contentHasFocus=!1,this.#shouldIgnoreSelectionChange=!1;return}const contentElement=this.#contentElement;if(contentElement==null||!this.#replacementFocusIsAvailable(contentElement)){this.#replacementFocusRequest=void 0,this.#contentHasFocus=!1;return}const shouldFocus=()=>{if(this.#replacementFocusRequest!==request)return!1;const shouldRestore=this.#replacementFocusIsAvailable(contentElement);return this.#replacementFocusRequest=void 0,shouldRestore};if(position!=null){this.#focus(position,!0,shouldFocus);return}const primarySelection=this.#selections?.at(-1);if(primarySelection==null){this.#focus(void 0,!0,shouldFocus);return}const primaryPosition=primarySelection.direction===-1?primarySelection.end:primarySelection.start;this.#focus(primaryPosition,!0,shouldFocus)}#replacementFocusIsAvailable(contentElement){const fileContainer=this.#fileContainer,shadowRoot=fileContainer?.shadowRoot;if(fileContainer==null||shadowRoot==null||this.#contentElement!==contentElement||!shadowRoot.contains(contentElement))return!1;const{activeElement:shadowActiveElement}=shadowRoot;if(shadowActiveElement===contentElement||shadowActiveElement!=null&&contentElement.contains(shadowActiveElement))return!0;if(shadowActiveElement!=null)return!1;const{ownerDocument}=fileContainer,{activeElement}=ownerDocument;return activeElement==null||activeElement===ownerDocument.body||activeElement===ownerDocument.documentElement||activeElement===fileContainer}#getFirstVisibleLineNumber(offset=0){const contentElement=this.#contentElement,fileContainer=this.#fileContainer;if(this.#editSession?.document==null||contentElement==null||fileContainer==null)return;const viewport=this.#getScrollViewport();if(viewport===void 0)return;let viewportTop,viewportBottom;if(viewport instanceof HTMLElement){const viewportRect=viewport.getBoundingClientRect();viewportTop=viewportRect.top,viewportBottom=viewportRect.bottom}else viewportTop=0,viewportBottom=viewport.defaultView?.innerHeight??0;const stickyHeader=fileContainer.shadowRoot?.querySelector("[data-diffs-header][data-sticky]");if(stickyHeader!=null&&(viewportTop=Math.max(viewportTop,stickyHeader.getBoundingClientRect().bottom)),Number.isFinite(offset)&&(viewportTop+=Math.max(0,offset)),!(viewportBottom<=viewportTop))for(const child of contentElement.children){const row=child,lineNumber=getLineNumberAttr(row),lineType=row.dataset.lineType;if(lineNumber==null||lineType==null||!isLineEditable(lineType))continue;const rowRect=row.getBoundingClientRect();if(!(rowRect.bottom<=rowRect.top)&&rowRect.top>=viewportTop&&rowRect.top<viewportBottom)return lineNumber}}#focusAtPosition(position,preventScroll){const selection={start:position,end:position,direction:0};this.#canMountSelectionAction=!1,this.#updateSelections([selection]),this.#revealLineIfCollapsed(position.line),preventScroll?this.#focus(position,!0):this.#scrollToPrimaryCaret()}#setWindowSelection(selection){const winSelection=window.getSelection();if(winSelection===null)return;let{start,end,direction}=selection;comparePosition(start,end)>0&&([start,end]=[end,start]);const startLineElement=this.#getLineElement(start.line),endLineElement=this.#getLineElement(end.line);if(startLineElement===void 0||endLineElement===void 0)return;let[anchorNode,anchorOffset]=getSelectionAnchor(startLineElement,start.character),[focusNode,focusOffset]=getSelectionAnchor(endLineElement,end.character);direction===-1&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]);try{winSelection.setBaseAndExtent(anchorNode,clampDomOffset(anchorNode,anchorOffset),focusNode,clampDomOffset(focusNode,focusOffset))}catch(err){console.error("[diffs/editor] failed to update window selection:",err)}}#scrollToPrimaryCaret(noFocus=!1,scrollPosition="nearest"){const primarySelection=this.#selections?.at(-1);if(primarySelection===void 0)return;const primaryCaretElement=this.#primaryCaretElement;if(primaryCaretElement!==void 0){if(primaryCaretElement.scrollIntoView({block:scrollPosition,inline:"nearest"}),!noFocus){const position=primarySelection.direction===-1?primarySelection.end:primarySelection.start;this.#replacementFocusRequest!==void 0?this.#restoreReplacementFocus(position):this.#focus(position)}}else{const pos=getCaretPosition(primarySelection);this.#scrollToLine(pos.line,pos.character,noFocus)}}#getScrollMargin(){const top=this.#searchPanel!==void 0?48:0,start=this.#getGutterWidth()+this.#metrics.ch;return`${top}px ${this.#metrics.ch}px 0 ${start}px`}#scrollToLine(line,char=0,noFocus=!1){this.__postponeBgTokenizeToNextFrame();const virtualCaret=h("div",{style:{position:"absolute",left:"0",width:"2px",height:this.#metrics.lineHeight+"px",scrollMargin:this.#getScrollMargin()}});if(this.#getLineElement(line)!==void 0){const[left,wrapLine]=this.#getCharX(line,char),lineY=this.#getLineY(line)+wrapLine*this.#metrics.lineHeight;if(virtualCaret.style.top=lineY+"px",virtualCaret.style.left=left+"px",this.#overlayElement?.appendChild(virtualCaret),virtualCaret.scrollIntoView({block:"center",inline:"nearest"}),!noFocus){const position={line,character:char};this.#replacementFocusRequest!==void 0?this.#restoreReplacementFocus(position):this.#focus(position)}this.#scrollingToLine=void 0,this.#scrollingToLineChar=void 0,this.#scrollingToLineFixed=!1,this.#scrollingToLineNoFocus=!1}else{const modelLinePosition=this.#virtualizedInstance?.getLinePosition?.(line+1);if(modelLinePosition!==void 0)virtualCaret.style.top=modelLinePosition.top+"px",this.#fileContainer?.shadowRoot?.appendChild(virtualCaret),virtualCaret.scrollIntoView({block:"center",inline:"nearest"}),modelLinePosition.height>0&&this.#isLineRenderable(line)?(this.#scrollingToLine=line,this.#scrollingToLineChar=char,this.#scrollingToLineNoFocus=noFocus):(this.#scrollingToLine=void 0,this.#scrollingToLineChar=void 0,this.#scrollingToLineNoFocus=!1);else{let yFix=0;if(this.#scrollingToLine===line&&this.#contentElement!==void 0)for(let i=this.#contentElement.childElementCount-1;i>=0;i--){const child=this.#contentElement.children[i],lineType=child.dataset.lineType,lineNumber=getLineNumberAttr(child);if(lineType!==void 0&&isLineEditable(lineType)&&lineNumber!==void 0){yFix=(line-(lineNumber-1))*this.#metrics.lineHeight;break}}const approximateLineY=((this.#lineAnnotations??[]).filter(annotation=>annotation.lineNumber<line).length+line)*this.#metrics.lineHeight+yFix;virtualCaret.style.top=approximateLineY+"px",this.#fileContainer?.shadowRoot?.appendChild(virtualCaret),virtualCaret.scrollIntoView({block:"center",inline:"nearest"}),this.#scrollingToLine===line&&(yFix===0||this.#scrollingToLineFixed)||!this.#isLineRenderable(line)?(this.#scrollingToLine=void 0,this.#scrollingToLineChar=void 0,this.#scrollingToLineFixed=!1,this.#scrollingToLineNoFocus=!1):(this.#scrollingToLine=line,this.#scrollingToLineChar=char,this.#scrollingToLineFixed=yFix!==0,this.#scrollingToLineNoFocus=noFocus)}}virtualCaret.remove()}#spanLineSelection(anchorLine,focusLine,textDocument){const lineStart=line=>({line,character:0}),lineEnd2=line=>({line,character:textDocument.getLineText(line).length});return focusLine<anchorLine?{start:lineStart(focusLine),end:lineEnd2(anchorLine),direction:-1}:{start:lineStart(anchorLine),end:lineEnd2(focusLine),direction:1}}#isDeletedLineTarget(event){const target=event.composedPath()[0];return target instanceof HTMLElement&&target.closest("[data-line]")?.getAttribute("data-line-type")==="change-deletion"}#selectDeletedLines(anchorContent,focusContent,deletionsCode){const rows=[...deletionsCode.querySelectorAll("[data-content] > [data-line]")],anchorIndex=rows.indexOf(anchorContent),focusIndex=rows.indexOf(focusContent),[topContent,bottomContent]=focusIndex<anchorIndex?[focusContent,anchorContent]:[anchorContent,focusContent],winSelection=window.getSelection();if(winSelection!==null){const range=document.createRange();range.setStart(topContent,0),range.setEnd(bottomContent,bottomContent.childNodes.length),winSelection.removeAllRanges(),winSelection.addRange(range)}this.#setDeletedTextSelectionActive(!0),this.#updateSelections([]),this.#setEditorActiveLineSafe(getLineNumberAttr(focusContent)??null,!0,"deletions");const lo=Math.min(anchorIndex,focusIndex),hi=Math.max(anchorIndex,focusIndex);this.#deletedSelectionText=lo<0?"":rows.slice(lo,hi+1).filter(row=>row.getAttribute("data-line-type")==="change-deletion").map(row=>row.textContent??"").join(`
66
66
  `)}#contentRowForGutterRow(gutterRow,contentColumn){const gutterColumn=gutterRow.parentElement;if(gutterColumn==null||contentColumn==null)return;const index=[...gutterColumn.children].indexOf(gutterRow),row=contentColumn.children[index];return row instanceof HTMLElement?row:void 0}#beginDeletionGutterSelection(gutterRow,code,isMouse){const contentColumn=code.querySelector("[data-content]"),anchorContent=this.#contentRowForGutterRow(gutterRow,contentColumn);return anchorContent===void 0?!1:(this.#selectDeletedLines(anchorContent,anchorContent,code),isMouse&&this.#replaceSelectEventListeners([addEventListener(document,"mousemove",moveEvent=>{const moveTarget=moveEvent.composedPath()[0],moveGutter=moveTarget instanceof HTMLElement?moveTarget.closest("[data-column-number]"):null;if(moveGutter instanceof HTMLElement&&code.contains(moveGutter)){const focusContent=this.#contentRowForGutterRow(moveGutter,contentColumn);focusContent!==void 0&&this.#selectDeletedLines(anchorContent,focusContent,code)}},{passive:!0})]),!0)}#isDeletedTextSelectionActive(){return this.#fileContainer?.shadowRoot?.querySelector("pre")?.hasAttribute("data-deleted-text-selection")??!1}#deletedTextForClipboard(){return this.#deletedSelectionText!==""?this.#deletedSelectionText:window.getSelection()?.toString()??""}#setDeletedTextSelectionActive(active){const pre=this.#fileContainer?.shadowRoot?.querySelector("pre");pre!=null&&(active?(pre.setAttribute("data-deleted-text-selection",""),this.#setEditorActiveLineSafe(null),this.#deletedSelectionText=""):(pre.removeAttribute("data-deleted-text-selection"),this.#deletedSelectionText=""))}#setEditorActiveLineSafe(lineNumber,lineNumberOnly=!1,side="additions"){try{this.#fileInstance?.setEditorActiveLine(lineNumber,{lineNumberOnly,side})}catch{}}#scheduleThemeSelectionRefresh(){this.#themeSelectionRefreshFrame===void 0&&(this.#themeSelectionRefreshFrame=requestAnimationFrame(()=>{this.#themeSelectionRefreshFrame=void 0,(this.#selections!==void 0||this.#matches!==void 0||this.#markerRenderer!==void 0)&&this.#updateSelections(this.#selections??[])}))}#updateAltColumnSelections(){const drag=this.#altColumnDrag,selectionStart=this.#selectionStart,textDocument=this.#editSession?.document;if(drag===void 0||drag.focusLine===void 0||selectionStart===void 0||textDocument===void 0)return!1;const anchor=selectionStart.direction===-1?selectionStart.end:selectionStart.start,scrollLeft=this.#contentElement?.parentElement?.scrollLeft??0,characterDeltaRaw=(drag.clientX-drag.startClientX+scrollLeft-drag.startScrollLeft)/this.#metrics.ch,characterDelta=characterDeltaRaw<0?-Math.round(-characterDeltaRaw):Math.round(characterDeltaRaw),focusCharacter=Math.max(0,anchor.character+characterDelta),goal={line:drag.focusLine,character:focusCharacter};if(drag.renderedGoal!==void 0&&comparePosition(drag.renderedGoal,goal)===0)return!0;drag.renderedGoal=goal;const selections=[],step=goal.line<anchor.line?-1:1;for(let line=anchor.line;;line+=step){if(this.#isLineRenderable(line)){const lineText=textDocument.getLineText(line),anchorOffset=Math.min(anchor.character,lineText.length),focusOffset=Math.min(focusCharacter,lineText.length),anchorCharacter=snapCharacterToGraphemeBoundary(lineText,anchorOffset),lineFocusCharacter=focusOffset===anchorOffset?anchorCharacter:snapCharacterToGraphemeBoundary(lineText,focusOffset);selections.push({start:{line,character:Math.min(anchorCharacter,lineFocusCharacter)},end:{line,character:Math.max(anchorCharacter,lineFocusCharacter)},direction:anchorCharacter===lineFocusCharacter?0:anchorCharacter<lineFocusCharacter?1:-1})}if(line===goal.line)break}return this.#updateSelections(selections),!0}#removeRenderedEditPrediction(){for(const[key,element]of this.#overlayElements??[])key.startsWith("editPrediction")&&(element.remove(),this.#overlayElements?.delete(key))}#composeEditPredictionGroup(textDocument,edits,startIndex){const firstEdit=edits[startIndex];let endIndex=startIndex,endLine=firstEdit.range.end.line;for(;endIndex+1<edits.length&&edits[endIndex+1].range.start.line<=endLine;)endIndex++,endLine=Math.max(endLine,edits[endIndex].range.end.line);if(endIndex===startIndex&&(firstEdit.newText.length===0||comparePosition(firstEdit.range.start,firstEdit.range.end)===0))return{edit:firstEdit,endIndex};const start=firstEdit.range.start,end={line:endLine,character:textDocument.getLineLength(endLine)},parts=[];let consumed=textDocument.offsetAt(start);for(let index=startIndex;index<=endIndex;index++){const edit=edits[index],editStart=textDocument.offsetAt(edit.range.start),editEnd=textDocument.offsetAt(edit.range.end);parts.push(textDocument.getTextSlice(consumed,editStart),edit.newText),consumed=editEnd}return parts.push(textDocument.getTextSlice(consumed,textDocument.offsetAt(end))),{edit:{range:{start,end},newText:parts.join("")},endIndex}}#getEditPredictionGroups(){const prediction=this.#editPrediction,textDocument=this.#editSession?.document;if(prediction==null||textDocument==null||prediction.document!==textDocument||prediction.version!==textDocument.version||this.#options.editPrediction?.mode==="subtle"&&!this.#editPredictionRevealed)return;const{edits}=prediction.response,groups=[];let allVisible=edits.length>0;for(let startIndex=0;startIndex<edits.length;){const{edit,endIndex}=this.#composeEditPredictionGroup(textDocument,edits,startIndex);for(let line=edit.range.start.line;allVisible&&line<=edit.range.end.line;line++)allVisible=this.#isLineVisible(line);groups.push({edit,startIndex,endIndex}),startIndex=endIndex+1}return{groups,allVisible}}#fillGhostTextElement(element,newText,anchorLeft,lineLeft,insertionSuffix){this.#isWrap?(element.dataset.wrap="",element.style.width=`calc(100cqw - ${lineLeft}px)`):(delete element.dataset.wrap,element.style.width="max-content");const lines=newText.split(/\r\n|\r|\n/);for(let lineIndex=0;lineIndex<lines.length;lineIndex++){const lineText=lines[lineIndex],suffix=lineIndex===lines.length-1?insertionSuffix:void 0,isEmpty=lineText.length===0&&suffix===void 0,line=h("span",{dataset:isEmpty?["editPredictionLine","empty"]:"editPredictionLine",textContent:isEmpty?"​":lineText},element);suffix!==void 0&&h("span",{dataset:"editPredictionSuffix"},line).append(suffix),lineIndex===0&&anchorLeft!==lineLeft&&(line.style.textIndent=`${anchorLeft-lineLeft}px`)}}#cloneInsertionSuffix(group){const prediction=this.#editPrediction,textDocument=this.#editSession?.document;if(prediction==null||textDocument==null)return;const{edit,startIndex,endIndex}=group,{start,end}=edit.range;if(!(comparePosition(start,end)===0&&start.character<textDocument.getLineLength(start.line))||prediction.response.edits[startIndex-1]?.range.end.line===start.line||prediction.response.edits[endIndex+1]?.range.start.line===start.line)return;const sourceLine=this.#getLineElement(start.line);if(sourceLine===void 0)return document.createTextNode(textDocument.getLineText(start.line).slice(start.character));const[suffixNode,suffixOffset]=getSelectionAnchor(sourceLine,start.character),suffixRange=document.createRange();suffixRange.selectNodeContents(sourceLine),suffixRange.setStart(suffixNode,clampDomOffset(suffixNode,suffixOffset));const suffix=suffixRange.cloneContents();return suffix.firstChild?.textContent===""&&suffix.firstChild.remove(),suffix}#measureGhostTextRows(group){const{edit}=group,{start}=edit.range,[anchorLeft,anchorWrapLine]=this.#getCharX(start.line,start.character);let anchorVisualLines=1,ghostVisualLines=edit.newText.split(/\r\n|\r|\n/).length;const overlayElement=this.#overlayElement;if(this.#isWrap&&overlayElement!=null){anchorVisualLines=Math.max(1,this.#wrapLineTextOrWholeLine(start.line).length-1);const probe=h("span",{dataset:"editPrediction",style:{visibility:"hidden"}},overlayElement);this.#fillGhostTextElement(probe,edit.newText,anchorLeft,this.#getCharX(start.line,0)[0],this.#cloneInsertionSuffix(group));const{width,height}=probe.getBoundingClientRect();probe.remove();const{lineHeight}=this.#metrics;width>0&&height>0&&lineHeight>0&&(ghostVisualLines=Math.round(height/lineHeight))}return Math.max(0,ghostVisualLines-(anchorVisualLines-anchorWrapLine))}#syncEditPredictionSpacers(notifyComponent=!0){const nextSpacers=new Map,ghostTextRows=new Map,previousRows=this.#ghostTextRows;let rowsChanged=!1;const contentElement=this.#contentElement,composed=this.#getEditPredictionGroups();if(contentElement!=null&&composed!=null&&composed.allVisible){for(const group of composed.groups){const{edit}=group;if(edit.newText.length===0)continue;const count=this.#measureGhostTextRows(group);count>(ghostTextRows.get(edit.range.start.line)??0)&&ghostTextRows.set(edit.range.start.line,count)}if(ghostTextRows.size>0){let rowIndexes;const startingLine=this.#renderRange?.startingLine??0;for(const[line,count]of ghostTextRows){rowsChanged||=previousRows.get(line)!==count;const lineElement=this.#getLineElement(line);if(lineElement===void 0)continue;let rowIndex=line-startingLine;if(contentElement.children[rowIndex]!==lineElement){if(rowIndexes===void 0){rowIndexes=new Map;for(let index=0;index<contentElement.children.length;index++)rowIndexes.set(contentElement.children[index],index)}rowIndex=rowIndexes.get(lineElement)??-1}if(rowIndex<0)continue;nextSpacers.set(lineElement,count);const gutterRow=this.#gutterElement?.children[rowIndex];gutterRow instanceof HTMLElement&&nextSpacers.set(gutterRow,count);const partner=this.#deletionsColumnPartner(rowIndex);partner!=null&&(nextSpacers.set(partner.content,(nextSpacers.get(partner.content)??0)+count),nextSpacers.set(partner.gutter,(nextSpacers.get(partner.gutter)??0)+count))}}}let changed=!1;for(const[element,count]of this.#editPredictionSpacers)nextSpacers.get(element)!==count&&(delete element.dataset.editPredictionSpacer,element.style.removeProperty("--diffs-edit-prediction-spacer-height"),changed=!0);for(const[element,count]of nextSpacers)this.#editPredictionSpacers.get(element)!==count&&(element.dataset.editPredictionSpacer="",element.style.setProperty("--diffs-edit-prediction-spacer-height",`${count}lh`),changed=!0);this.#editPredictionSpacers=nextSpacers,(rowsChanged||ghostTextRows.size!==previousRows.size)&&(this.#ghostTextRows=ghostTextRows,notifyComponent&&this.#virtualizedInstance?.syncGhostTextRows()),changed&&this.#resetCache()}#deletionsColumnPartner(rowIndex){const deletionsColumn=this.#deletionsColumn,contentElement=this.#contentElement;if(deletionsColumn==null||contentElement==null||!this.#isDiff||this.#diffSyle!=="split"||this.#isWrap)return;let track=0;for(let index=0;index<rowIndex;index++)track+=gridTrackSpan(contentElement.children[index]);const{content,gutter}=deletionsColumn;let covered=0;for(let index=0;index<content.children.length;index++){const child=content.children[index];if(covered+=gridTrackSpan(child),covered>track){const gutterChild=gutter.children[index];if(!(child instanceof HTMLElement)||!(gutterChild instanceof HTMLElement))throw new Error("Editor: deletions column rows and gutter cells are out of step");return{content:child,gutter:gutterChild}}}}#cancelEditPrediction(removeRendered,notifyComponent=!0){this.#editPredictionTimer!==void 0&&(clearTimeout(this.#editPredictionTimer),this.#editPredictionTimer=void 0),this.#editPredictionAbortController?.abort(),this.#editPredictionAbortController=void 0,this.#editPredictionGeneration++,this.#editPredictionRevealed=!1,this.#retryEditPredictionOnRender=!1,this.#editPrediction=void 0,this.#syncEditPredictionSpacers(notifyComponent),removeRendered&&this.#removeRenderedEditPrediction()}#includesEditPredictionPath(path){const options=this.#options.editPrediction;if(options===void 0)return!1;const normalizedPath=path.replaceAll("\\","/");return(options.include===void 0||options.include.some(pattern=>matchesEditPredictionPattern(normalizedPath,pattern)))&&options.exclude?.some(pattern=>matchesEditPredictionPattern(normalizedPath,pattern))!==!0}#scheduleEditPrediction(){this.#cancelEditPrediction(!0);const selection=this.#selections?.[0];if(this.#options.editPrediction===void 0||this.#editSession?.document===void 0||this.#editSession?.fileInfo===void 0||this.#selections?.length!==1||selection===void 0||!isCollapsedSelection(selection))return;const document2=this.#editSession?.document,cursorOffset=document2.offsetAt(getCaretPosition(selection));this.#editPredictionTimer=setTimeout(()=>{this.#editPredictionTimer=void 0;const options=this.#options.editPrediction,currentSelection=this.#selections?.[0],path=this.#editSession?.fileInfo?.name;if(options===void 0||path===void 0||this.#editSession?.document!==document2||this.#selections?.length!==1||currentSelection===void 0||!isCollapsedSelection(currentSelection)||document2.offsetAt(getCaretPosition(currentSelection))!==cursorOffset||!this.#includesEditPredictionPath(path))return;const isLineEditable2=line=>this.#isLineInRenderRange(line)&&this.#isLineRenderable(line);if(!isLineEditable2(getCaretPosition(currentSelection).line)){this.#retryEditPredictionOnRender=!0;return}const request=buildEditPredictionRequest(path,document2,cursorOffset,this.#editPredictionHistory,isLineEditable2);if(request===void 0)return;const excerptStartOffset=document2.offsetAt({line:request.excerptStartLine,character:0}),editableStart=excerptStartOffset+request.editableRange.start,editableEnd=excerptStartOffset+request.editableRange.end,controller=new AbortController,generation=++this.#editPredictionGeneration;this.#editPredictionAbortController=controller;let prediction;try{prediction=options.provider.predict(request,{signal:controller.signal})}catch{this.#editPredictionAbortController=void 0;return}Promise.resolve(prediction).then(response=>{const selection2=this.#selections?.[0];if(controller.signal.aborted||generation!==this.#editPredictionGeneration||this.#editPredictionAbortController!==controller||this.#editSession?.document!==document2||document2.version!==request.version||this.#selections?.length!==1||selection2===void 0||!isCollapsedSelection(selection2)||document2.offsetAt(getCaretPosition(selection2))!==cursorOffset||response==null||!Array.isArray(response.edits)||response.edits.length===0||response.edits.length>MAX_EDIT_PREDICTION_RESPONSE_EDITS||response.newCursor==null)return;const resolvedEdits=[];let responseBytes=0;for(const edit of response.edits){if(edit==null||typeof edit.newText!="string"||!isValidEditPredictionPosition(document2,edit.range?.start)||!isValidEditPredictionPosition(document2,edit.range?.end)||comparePosition(edit.range.start,edit.range.end)>0||(responseBytes+=editPredictionTextEncoder.encode(edit.newText).byteLength,responseBytes>MAX_EDIT_PREDICTION_RESPONSE_BYTES))return;const start=document2.offsetAt(edit.range.start),end=document2.offsetAt(edit.range.end),resolvedEdit=document2.resolveEdits([edit])[0];if(resolvedEdit.start!==start||resolvedEdit.end!==end)return;resolvedEdits.push(resolvedEdit)}resolvedEdits.sort((left,right)=>{const startDelta=left.start-right.start;return startDelta===0?left.end-right.end:startDelta});for(let index=0;index<resolvedEdits.length;index++){const edit=resolvedEdits[index];if(edit.start<editableStart||edit.end>editableEnd||index>0&&resolvedEdits[index-1].end>edit.start)return}const edits=resolvedEdits.filter(edit=>edit.text!==document2.getTextSlice(edit.start,edit.end));if(edits.length===0)return;const firstEditPosition=document2.positionAt(edits[0].start),lastEditPosition=document2.positionAt(edits.at(-1).end),affectedStart=document2.offsetAt({line:firstEditPosition.line,character:0}),affectedEnd=document2.offsetAt({line:lastEditPosition.line,character:document2.getLineLength(lastEditPosition.line)}),predictedParts=[];let consumed=affectedStart;for(const edit of edits)predictedParts.push(document2.getTextSlice(consumed,edit.start),edit.text),consumed=edit.end;predictedParts.push(document2.getTextSlice(consumed,affectedEnd));const predictedLines=predictedParts.join("").split(/\r\n|\r|\n/),affectedEndLine=firstEditPosition.line+predictedLines.length-1,lineDelta=predictedLines.length-(lastEditPosition.line-firstEditPosition.line+1),newCursor=response.newCursor;if(!(!Number.isInteger(newCursor.line)||!Number.isInteger(newCursor.character)||newCursor.line<0||newCursor.character<0)){if(newCursor.line>=firstEditPosition.line&&newCursor.line<=affectedEndLine){const line=predictedLines[newCursor.line-firstEditPosition.line];if(newCursor.character>line.length||splitsSurrogatePair(line,newCursor.character))return}else{const originalLine=newCursor.line<firstEditPosition.line?newCursor.line:newCursor.line-lineDelta;if(originalLine<0||originalLine>=document2.lineCount||newCursor.character>document2.getLineLength(originalLine))return;const originalOffset=document2.offsetAt({line:originalLine,character:newCursor.character});if(splitsSurrogatePair(document2.charAt(originalOffset-1)+document2.charAt(originalOffset),1))return}this.#editPrediction={document:document2,version:request.version,cursorOffset,rendered:!1,response:{edits:edits.map(edit=>({range:{start:document2.positionAt(edit.start),end:document2.positionAt(edit.end)},newText:edit.text})),newCursor:{...newCursor}}},this.#updateSelections(this.#selections)}}).catch(()=>{}).finally(()=>{this.#editPredictionAbortController===controller&&(this.#editPredictionAbortController=void 0)})},EDIT_PREDICTION_DEBOUNCE_MS)}#recordEditPredictionHistory(change,source){const textDocument=this.#editSession?.document,path=this.#editSession?.fileInfo?.name,transaction=getTextDocumentChangeTransaction(change);textDocument===void 0||path===void 0||transaction===void 0||!this.#includesEditPredictionPath(path)||(this.#editPredictionHistory=recordEditPrediction(this.#editPredictionHistory,path,textDocument,transaction,source))}#acceptEditPrediction(){const prediction=this.#editPrediction,textDocument=this.#editSession?.document,selection=this.#selections?.[0];if(prediction===void 0||!prediction.rendered||textDocument===void 0||prediction.document!==textDocument||prediction.version!==textDocument.version||this.#selections?.length!==1||selection===void 0||!isCollapsedSelection(selection)||textDocument.offsetAt(getCaretPosition(selection))!==prediction.cursorOffset)return;const{edits,newCursor}=prediction.response;this.#cancelEditPrediction(!0);const change=textDocument.applyEdits(edits.map(edit=>({range:{start:{...edit.range.start},end:{...edit.range.end}},newText:edit.newText})),!0,this.#selections,void 0,!0);if(change===void 0){this.#scheduleEditPrediction();return}const cursor=textDocument.normalizePosition(newCursor),nextSelections=[{start:cursor,end:cursor,direction:0}];textDocument.setLastUndoSelectionsAfter(nextSelections),this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change),{editSource:"prediction"})}#renderEditPrediction(renderCtx){const prediction=this.#editPrediction,textDocument=this.#editSession?.document;prediction!==void 0&&(prediction.rendered=!1);const composed=this.#getEditPredictionGroups();if(!(prediction==null||textDocument==null||composed==null||!composed.allVisible)){for(const group of composed.groups){const{edit,endIndex}=group,{start,end}=edit.range,isDeletion=edit.newText.length===0,isReplacement=comparePosition(start,end)!==0,lineLength=textDocument.getLineLength(start.line),isMidLineInsertion=!isReplacement&&start.character<lineLength;if(isReplacement?this.#renderSelection(renderCtx,isDeletion?"editPredictionDeletion":"editPredictionReplacement",{start,end}):isMidLineInsertion&&this.#renderSelection(renderCtx,"editPredictionInsertion",{start,end:{line:start.line,character:lineLength}}),isDeletion)continue;const[anchorLeft,anchorWrapLine]=this.#getCharX(start.line,start.character),lineLeft=this.#getCharX(start.line,0)[0],anchorTop=this.#getLineY(start.line)+anchorWrapLine*this.#metrics.lineHeight,key=`editPrediction-${endIndex}`;let element=this.#overlayElements?.get(key);if(element!==void 0?(this.#overlayElements?.delete(key),element.replaceChildren()):element=h("span",{ariaHidden:"true",contentEditable:"false",dataset:"editPrediction"},renderCtx.fragment),isReplacement){element.dataset.replacement="";const lineElement=this.#getLineElement(start.line);lineElement!==void 0&&element.style.setProperty("--diffs-edit-prediction-bg",getComputedStyle(lineElement).getPropertyValue("--diffs-line-bg"))}else delete element.dataset.replacement,element.style.removeProperty("--diffs-edit-prediction-bg");this.#fillGhostTextElement(element,edit.newText,anchorLeft,lineLeft,this.#cloneInsertionSuffix(group)),element.style.transform=`translateX(${lineLeft}px) translateY(${anchorTop}px)`,renderCtx.elements.set(key,element)}prediction.rendered=!0}}#updateSelections(selections){this.__postponeBgTokenizeToNextFrame();const previousSelections=this.#selections;let selectionsChanged=previousSelections?.length!==selections.length;if(!selectionsChanged&&previousSelections!==void 0)for(let i=0;i<selections.length;i++){const previous=previousSelections[i],next=selections[i];if(previous.direction!==next.direction||comparePosition(previous.start,next.start)!==0||comparePosition(previous.end,next.end)!==0){selectionsChanged=!0;break}}if(selectionsChanged&&this.#cancelEditPrediction(!0),this.#syncEditPredictionSpacers(),this.#primaryCaretElement=void 0,this.#setEditorActiveLineSafe(null),selections.length===0&&this.#matches===void 0&&this.#markerRenderer===void 0){this.#selections=void 0,this.#overlayElements?.forEach(el=>el.remove()),this.#overlayElements?.clear(),this.#selectionAction?.cleanup(),this.#selectionAction=void 0,selectionsChanged&&this.#scheduleEditPrediction();return}const fragment=document.createDocumentFragment(),renderCtx={fragment,elements:new Map};if(selections.length>0){const normalizedSelections=mergeOverlappingSelections(selections),primarySelection=normalizedSelections.at(-1);this.#selections=normalizedSelections;const hasNonEmptySelection=normalizedSelections.some(selection=>!isCollapsedSelection(selection)),caretLine=getCaretPosition(primarySelection).line+1;this.#setEditorActiveLineSafe(caretLine,hasNonEmptySelection);for(const selection of normalizedSelections)isCollapsedSelection(selection)||this.#renderSelection(renderCtx,"selection",selection),this.#renderCaret(renderCtx,selection,selection===primarySelection);const bracketMatchRanges=this.#options.matchBrackets!==!1&&this.#editSession?.document!=null&&this.#tokenizer!==void 0&&isCollapsedSelection(primarySelection)?findBracketMatchRanges(this.#editSession?.document,this.#tokenizer,primarySelection.start):void 0;if(bracketMatchRanges!==void 0)for(const range of bracketMatchRanges)this.#renderSelection(renderCtx,"bracketMatch",range)}const textDocument=this.#editSession?.document;if(this.#matches!==void 0&&textDocument!==void 0){const matches=this.#matches,renderRange=this.#renderRange,renderedLineRanges=renderRange!=null&&Number.isFinite(renderRange.totalLines)||this.#isDiff&&this.#fileDiffInstance?.options.expandUnchanged!==!0?this.#getRenderedEditableLineRanges():void 0,primarySelection=this.#selections?.at(-1),primaryStartOffset=primarySelection!==void 0?textDocument.offsetAt(primarySelection.start):-1,primaryEndOffset=primarySelection!==void 0?textDocument.offsetAt(primarySelection.end):-1;let firstMatchIndex=0;const rangeCount=renderedLineRanges?.length??1;for(let rangeIndex=0;rangeIndex<rangeCount;rangeIndex++){let visibleEndOffset=1/0;const lineRange2=renderedLineRanges?.[rangeIndex];if(lineRange2!==void 0){const[firstLine,lastLine]=lineRange2,visibleStartOffset=textDocument.offsetAt({line:firstLine,character:0}),endLine=lastLine+1;visibleEndOffset=endLine<textDocument.lineCount?textDocument.offsetAt({line:endLine,character:0}):textDocument.offsetAt({line:endLine-1,character:textDocument.getLineLength(endLine-1)});let low=firstMatchIndex,high=matches.length;for(;low<high;){const middle=low+Math.floor((high-low)/2);matches[middle][1]<=visibleStartOffset?low=middle+1:high=middle}firstMatchIndex=low}for(;firstMatchIndex<matches.length;firstMatchIndex++){const[startOffset,endOffset]=matches[firstMatchIndex];if(startOffset>=visibleEndOffset)break;const range={start:textDocument.positionAt(startOffset),end:textDocument.positionAt(endOffset)},isFocused=primaryStartOffset===startOffset&&primaryEndOffset===endOffset;this.#renderSelection(renderCtx,"match",range,isFocused?"focus":void 0)}}}if(this.#markerRenderer!==void 0&&textDocument!==void 0)for(const marker of this.#markerRenderer.markers)this.#renderSelection(renderCtx,"marker",marker,markerSeverityDatasetKey(marker.severity));this.#renderEditPrediction(renderCtx),this.#overlayElement?.appendChild(fragment),this.#overlayElements?.forEach(el=>el.remove()),this.#overlayElements?.clear(),this.#overlayElements=renderCtx.elements,this.#updateSelectionActionPopover(),selectionsChanged&&this.#scheduleEditPrediction()}#renderCarets(){const carets=this.#carets,renderCaret=this.#options.renderCaret,overlayElement=this.#overlayElement;if(this.#caretHighlightElements?.forEach(element=>element.remove()),this.#caretHighlightElements=void 0,carets===void 0||renderCaret===void 0||overlayElement===void 0){this.#caretElements?.forEach(element=>element.remove()),this.#caretElements=void 0;return}const elements=this.#caretElements??=new Map;for(const[trackedCaret,element]of elements)this.#isLineVisible(trackedCaret.caret.focus.line)||(element.remove(),elements.delete(trackedCaret));const fragment=document.createDocumentFragment(),highlightElements=[];for(const trackedCaret of carets){const{caret}=trackedCaret,{line,character}=caret.focus;if(trackedCaret.anchorOffset!==trackedCaret.focusOffset){const highlightContext={fragment,elements:new Map};this.#renderSelection(highlightContext,"caretHighlight",trackedCaret.anchorOffset<trackedCaret.focusOffset?{start:caret.anchor,end:caret.focus}:{start:caret.focus,end:caret.anchor},void 0,caret.focus);for(const highlightElement of highlightContext.elements.values())highlightElement.style.setProperty("--diffs-caret-highlight-bg",`color-mix(in srgb, ${caret.metadata.color} 32%, transparent)`),highlightElements.push(highlightElement)}if(!this.#isLineVisible(line))continue;let element=elements.get(trackedCaret);element===void 0&&(element=h("div",{dataset:"remoteCaret",children:[renderCaret(caret)]},fragment),elements.set(trackedCaret,element));const[left,wrapLine]=this.#getCharX(line,character),top=this.#getLineY(line)+wrapLine*this.#metrics.lineHeight;element.style.transform=`translateX(${left}px) translateY(${top}px)`}this.#caretHighlightElements=highlightElements,overlayElement.appendChild(fragment)}#renderSelection(renderCtx,type,range,extraDataset,connectedCaret){if(this.#editSession?.document==null)return;const{start,end}=range;let firstLine=start.line,endLine=end.line+1;if(this.#renderRange!==void 0){const{startingLine,totalLines}=this.#renderRange;firstLine=Math.max(firstLine,startingLine),endLine=Math.min(endLine,startingLine+totalLines)}for(let line=firstLine;line<endLine;line++){if(!this.#isLineVisible(line))continue;const isLastLine=line===end.line,startChar=line===start.line?start.character:0,endChar=isLastLine?end.character:this.#editSession?.document.getLineLength(line);if(startChar===endChar&&(type==="editPredictionDeletion"||type==="editPredictionReplacement")){if(isLastLine&&line!==start.line)continue;const[left2,wrapLine]=this.#getCharX(line,startChar);this.#renderSelectionBlock(renderCtx,type,line,wrapLine,left2,this.#metrics.ch,extraDataset);continue}if(this.#isWrap){const contentWidth=this.#getContentWidth(),lineText=this.#editSession?.document.getLineText(line);if(2*this.#metrics.ch+this.#metrics.measureTextWidth(lineText)>contentWidth){this.#renderWrappedSelection(renderCtx,line,lineText,startChar,endChar,isLastLine,type,extraDataset,connectedCaret);continue}}let left=0,width=0,paddingEnd=0;startChar===0?left=this.#getGutterWidth()+this.#metrics.ch+(this.#activeContentOffset?.left??0):left=this.#getCharX(line,startChar)[0],!isLastLine&&type==="selection"&&(paddingEnd=this.#metrics.ch),startChar===endChar?width=paddingEnd:width=this.#getCharX(line,endChar)[0]-left+paddingEnd,this.#renderSelectionBlock(renderCtx,type,line,0,left,width,extraDataset,{start:connectedCaret?.line===start.line&&connectedCaret.character===start.character&&line===start.line,end:connectedCaret?.line===end.line&&connectedCaret.character===end.character&&line===end.line})}}#renderWrappedSelection(renderCtx,line,lineText,startChar,endChar,isLastLine,type,extraDataset,connectedCaret){const wrapOffsets=this.#wrapLineTextOrWholeLine(line),segmentCount=wrapOffsets.length-1,offsetLeft=this.#getGutterWidth()+this.#metrics.ch+(this.#activeContentOffset?.left??0);for(let wrapLine=0;wrapLine<segmentCount;wrapLine++){const segmentStart=wrapOffsets[wrapLine],segmentEnd=wrapOffsets[wrapLine+1],wrapStartChar=Math.max(startChar,segmentStart),wrapEndChar=Math.min(endChar,segmentEnd);if(wrapStartChar>wrapEndChar)continue;const segmentStartWidth=this.#segmentTextWidth(lineText,segmentStart,wrapStartChar),segmentLeft=offsetLeft+segmentStartWidth;let paddingEnd=0;!isLastLine&&wrapLine===segmentCount-1&&type==="selection"&&(paddingEnd=this.#metrics.ch);const segmentWidth=wrapStartChar===wrapEndChar?paddingEnd:this.#segmentTextWidth(lineText,segmentStart,wrapEndChar)-segmentStartWidth+paddingEnd;this.#renderSelectionBlock(renderCtx,type,line,wrapLine,segmentLeft,segmentWidth,extraDataset,{start:connectedCaret?.line===line&&connectedCaret.character===startChar&&wrapStartChar===startChar,end:connectedCaret?.line===line&&connectedCaret.character===endChar&&wrapEndChar===endChar})}}#segmentTextWidth(lineText,segmentStart,character){if(character<=segmentStart)return 0;const segmentText=lineText.slice(segmentStart,character),asciiColumns=getExpandedAsciiTextColumns(segmentText,this.#metrics.tabSize);return asciiColumns!==-1?asciiColumns*this.#metrics.ch:this.#metrics.measureTextWidth(segmentText)}#renderSelectionBlock(renderCtx,type,line,wrapLine,left,width,extraDataset,connectedCaretEdge){if(width===0)return;const{ch,lineHeight}=this.#metrics,y=this.#getLineY(line)+wrapLine*lineHeight,cacheKey=`${type}-${line}/${wrapLine}-${left}-${width} ${extraDataset??""}`,overlayEls=this.#overlayElements,rounded=(this.#options.roundedSelection??!0)&&(type==="selection"||type==="caretHighlight"),addRoundedCorner=(line2,wrapLine2,left2,radius)=>{const top=this.#getLineY(line2)+wrapLine2*lineHeight,lineElement=this.#getLineElement(line2);let cornerBg="initial";lineElement!==void 0&&(lineElement.dataset.lineType==="change-addition"||lineElement.dataset.selectedLine!==void 0)&&(cornerBg=getComputedStyle(lineElement).getPropertyValue("--diffs-line-bg"));const css=`width:${ch}px;transform:translateX(${left2}px) translateY(${top}px);--diffs-selection-corner-bg:${cornerBg}`,dataset={selectionCorner:"",[radius]:""},cacheKeyPrefix=`${type}-block-${line2}/${wrapLine2}-${left2}-1ch`;let cacheKey2=cacheKeyPrefix+"-"+radius;if(radius==="rbl"){const prevCornerKey=cacheKeyPrefix+"-rtl",prevCorner=renderCtx.elements.get(prevCornerKey);prevCorner!==void 0&&(prevCorner.remove(),renderCtx.elements.delete(prevCornerKey),cacheKey2+="-rtl",dataset.rtl="")}let cornerEl=renderCtx.elements.get(cacheKey2);cornerEl===void 0&&(overlayEls?.has(cacheKey2)===!0?(cornerEl=overlayEls.get(cacheKey2),cornerEl.style.cssText=css,overlayEls.delete(cacheKey2)):cornerEl=h("div",{dataset:type==="caretHighlight"?"caretHighlightRange":"selectionRange",style:{cssText:css},children:[h("div",{dataset})]},renderCtx.fragment),renderCtx.elements.set(cacheKey2,cornerEl))},addRadiusStyle=element=>{const end=left+width,dataset=element.dataset,previousSelectionRange=renderCtx.previousSelectionRange;if((previousSelectionRange===void 0||previousSelectionRange.line!==line||previousSelectionRange.wrapLine!==wrapLine)&&(renderCtx.previousSelectionRange={element,line,wrapLine,left,width}),previousSelectionRange===void 0||end<=previousSelectionRange.left)["rtl","rtr","rbl","rbr"].forEach(key=>{dataset[key]=""});else{const prevLine=previousSelectionRange.line,prevWrapLine=previousSelectionRange.wrapLine,prevLeft=previousSelectionRange.left,prevDataset=previousSelectionRange.element.dataset,prevEnd=prevLeft+previousSelectionRange.width;prevLeft>left&&addRoundedCorner(prevLine,prevWrapLine,prevLeft-ch,"rbr"),delete prevDataset.rbl,delete dataset.rtl,delete dataset.rtr,end>=prevEnd&&delete prevDataset.rbr,end>prevEnd&&(addRoundedCorner(prevLine,prevWrapLine,prevEnd,"rbl"),dataset.rtr=""),end<prevEnd&&addRoundedCorner(line,wrapLine,end,"rtl"),left<prevLeft&&(dataset.rtl=""),dataset.rbl="",dataset.rbr=""}connectedCaretEdge?.start===!0&&(delete dataset.rtl,delete dataset.rbl),connectedCaretEdge?.end===!0&&(delete dataset.rtr,delete dataset.rbr)};let rangeEl=renderCtx.elements.get(cacheKey);if(rangeEl!==void 0){rounded&&addRadiusStyle(rangeEl);return}if(overlayEls?.has(cacheKey)===!0?(rangeEl=overlayEls.get(cacheKey),overlayEls.delete(cacheKey)):rangeEl=h("div",{dataset:extraDataset?[type+"Range",extraDataset]:type+"Range"},renderCtx.fragment),rangeEl.style.width=`${width}px`,rangeEl.style.transform=`translateX(${left}px) translateY(${y}px)`,type==="editPredictionInsertion"||type==="editPredictionReplacement"){const lineElement=this.#getLineElement(line);lineElement!==void 0&&rangeEl.style.setProperty("--diffs-edit-prediction-bg",getComputedStyle(lineElement).getPropertyValue("--diffs-line-bg"))}else rangeEl.style.removeProperty("--diffs-edit-prediction-bg");rounded&&addRadiusStyle(rangeEl),renderCtx.elements.set(cacheKey,rangeEl)}#renderCaret(renderCtx,selection,isPrimary){const{line,character}=getCaretPosition(selection);if(!this.#isLineVisible(line))return;const[left,wrapLine]=this.#getCharX(line,character),cacheKey="caret-"+line+"/"+wrapLine+":"+character;if(renderCtx.elements.has(cacheKey))return;const x=left-1,y=this.#getLineY(line)+wrapLine*this.#metrics.lineHeight,caretEl=h("div",{dataset:"caret",style:{transform:`translateX(${x}px) translateY(${y}px)`}},renderCtx.fragment);renderCtx.elements.set(cacheKey,caretEl),isPrimary&&(caretEl.style.scrollMargin=this.#getScrollMargin(),this.#primaryCaretElement=caretEl)}#updateSelectionActionPopover(){const primarySelection=this.#selections?.at(-1),overlayElement=this.#overlayElement,textDocument=this.#editSession?.document,renderSelectionAction=this.#options.renderSelectionAction,cleanup=()=>{this.#selectionAction?.cleanup(),this.#selectionAction=void 0};if(this.#options.enabledSelectionAction!==!0||renderSelectionAction===void 0||primarySelection===void 0||isCollapsedSelection(primarySelection)||this.#isContentMouseDown||overlayElement===void 0||textDocument===void 0){cleanup();return}const head=getCaretPosition(primarySelection);if(!this.#isLineVisible(head.line)){cleanup();return}if(this.#selectionAction===void 0){if(!this.#canMountSelectionAction)return;const getActiveSelection=()=>this.#selections?.at(-1)??primarySelection,selectionActionElement=renderSelectionAction({textDocument,get selection(){return getActiveSelection()},applyEdits:edits=>this.applyEdits(edits),getSelectionText:()=>this.#editSession?.document?.getText(getActiveSelection())??"",replaceSelectionText:text=>{this.#replaceSelectionText(text,[getActiveSelection()])},close:()=>{cleanup(),this.#scrollToPrimaryCaret()}});this.#selectionAction=new SelectionActionWidget(selectionActionElement,overlayElement,()=>this.#updateSelectionActionPopover()),this.#getPopoverManager().resetPlacement(SELECTION_ACTION_POPOVER_PLACEMENT_KEY)}const lineHeight=this.#metrics.lineHeight,isBackward=primarySelection.direction===-1,preferred={placeAbove:isBackward,anchor:head},fallback=isBackward?{placeAbove:!1,anchor:primarySelection.end}:{placeAbove:!0,anchor:primarySelection.start},popoverHeight=this.#selectionAction.height,candidateGeometry=candidate=>{const[left2,candidateWrapLine]=this.#getCharX(candidate.anchor.line,candidate.anchor.character),rowTop=this.#getLineY(candidate.anchor.line)+candidateWrapLine*lineHeight,anchorTop2=candidate.placeAbove?rowTop:rowTop+lineHeight,top=candidate.placeAbove?anchorTop2-popoverHeight:anchorTop2;return{top,bottom:top+popoverHeight,left:left2,anchorTop:anchorTop2,rowTop}},preferredGeometry=candidateGeometry(preferred),lineCount=textDocument.lineCount,atDocumentEdge=isBackward?head.line<3:head.line>=lineCount-3,fallbackGeometry=this.#isLineVisible(fallback.anchor.line)?candidateGeometry(fallback):void 0,popoverManager=this.#getPopoverManager(),viewport=popoverManager.getPlacementBounds(),useFallback=fallbackGeometry!==void 0&&popoverManager.choosePlacement({preferred:preferredGeometry,fallback:fallbackGeometry,viewport,popoverHeight,atDocumentEdge,placementKey:SELECTION_ACTION_POPOVER_PLACEMENT_KEY})==="fallback";fallbackGeometry===void 0&&popoverManager.setPlacement("preferred",SELECTION_ACTION_POPOVER_PLACEMENT_KEY);const{placeAbove}=useFallback?fallback:preferred,{left,anchorTop}=useFallback&&fallbackGeometry!==void 0?fallbackGeometry:preferredGeometry,selectionTop=isBackward?preferredGeometry.rowTop:fallbackGeometry?.rowTop??-1/0,selectionBottom=(isBackward?fallbackGeometry?.rowTop??1/0:preferredGeometry.rowTop)+(primarySelection.end.line>primarySelection.start.line&&primarySelection.end.character===0?0:lineHeight),isSelectionVisible=viewport===void 0||selectionBottom>viewport.top&&selectionTop<viewport.bottom;this.#selectionAction.reposition(left,anchorTop,this.#getGutterWidth(),placeAbove,isSelectionVisible,viewport)}#openSearchPanel(mode){if(this.#searchPanel!==void 0){this.#searchPanel.setMode(mode);return}this.#renderSearchPanel(mode)}#renderSearchPanel(mode){this.#searchPanel?.cleanup();const textDocument=this.#editSession?.document,preElement=this.#fileContainer?.shadowRoot?.querySelector("pre"),selections=this.#selections;if(textDocument===void 0||preElement==null)return;let defaultQuery="",initialMatch;if(selections!==void 0&&selections.length>0){let primarySelection=selections.at(-1);if(isCollapsedSelection(primarySelection)){primarySelection=expandCollapsedSelectionToWord(textDocument,primarySelection),this.#updateSelections([...selections.slice(0,-1),primarySelection]);const selectionText=textDocument.getText(primarySelection);selectionText!==""&&!selectionText.includes(`
67
- `)&&(defaultQuery=selectionText,initialMatch=[textDocument.offsetAt(primarySelection.start),textDocument.offsetAt(primarySelection.end)])}}const scrollToMatch=([startOffset,endOffset],retainFocus)=>{const nextSelection=createSelectionFromAnchorAndFocusOffsets(textDocument,startOffset,endOffset);this.#updateSelections([nextSelection]),this.#revealLineIfCollapsed(getCaretPosition(nextSelection).line),this.#scrollToPrimaryCaret(!0),this.#retainSearchPanelFocus=retainFocus},searchPanel=new SearchPanelWidget({textDocument,containerElement:preElement,defaultQuery,mode,initialMatch,scrollToMatch,applyReplace:edits=>{if(edits.length===0)return;const change=textDocument.applyEdits(edits.map(edit=>({range:{start:textDocument.positionAt(edit.start),end:textDocument.positionAt(edit.end)},newText:edit.text})),!0,this.#selections);change!==void 0&&this.#applyChange(change,void 0,this.#applyChangeToLineAnnotations(change),{skipSearchRefresh:!0})},onUpdate:(allMatches,options)=>{if(allMatches.length===0){this.#matches=void 0,this.#updateSelections(this.#selections??[]);return}if(this.#matches=allMatches,options?.syncSelection===!1){this.#updateSelections(this.#selections??[]);const primarySelection2=this.#selections?.at(-1);if(primarySelection2!==void 0){const startOffset=textDocument.offsetAt(primarySelection2.start),endOffset=textDocument.offsetAt(primarySelection2.end);for(const match of allMatches)if(match[0]===startOffset&&match[1]===endOffset)return match}return}const primarySelection=this.#selections?.at(-1);let searchOffset=0,nextMatch;primarySelection!==void 0&&(searchOffset=textDocument.offsetAt(primarySelection.start));for(const m of allMatches)if(m[0]>=searchOffset){nextMatch=m;break}return nextMatch!==void 0?scrollToMatch(nextMatch,!0):this.#updateSelections(this.#selections??[]),nextMatch},onClose:()=>{this.#searchPanel=void 0,this.#retainSearchPanelFocus=!1,this.#matches=void 0,this.#updateSelections(this.#selections??[])}});this.#searchPanel=searchPanel,this.#retainSearchPanelFocus=!1}#getSelectionText(){const textDocument=this.#editSession?.document,selections=this.#selections;return textDocument===void 0||selections===void 0?"":getSelectionText(textDocument,selections)}#getSelectionClipboardTexts(){const textDocument=this.#editSession?.document,selections=this.#selections;return textDocument===void 0||selections===void 0?[]:getSelectionClipboardTexts(textDocument,selections)}#writeSelectionClipboardData(clipboardData,text,selectionTexts){clipboardData!==null&&(clipboardData.setData("text",text),selectionTexts.length>1&&clipboardData.setData(MULTI_SELECTION_CLIPBOARD_TYPE,JSON.stringify(selectionTexts)))}#cutSelectionText(){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0||selections.length===0)return"";if(selections.some(selection=>isCollapsedSelection(selection))){const cut=resolveSelectionCut(textDocument,selections);return this.#applySelectionCutEdits(cut.edits,cut.nextSelectionOffsets),cut.text}const text=getSelectionText(textDocument,selections);return this.#replaceSelectionText("",void 0,!0),text}#applySelectionCutEdits(edits,nextSelectionOffsets){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0||edits.length===0)return;const change=textDocument.applyResolvedEdits(edits,!0,selections,void 0,!0);if(change===void 0)return;const nextSelections=nextSelectionOffsets.map(offset=>{const caret=textDocument.positionAt(offset);return{start:caret,end:caret,direction:0}});textDocument.setLastUndoSelectionsAfter(nextSelections),this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#replaceSelectionText(text,selections=this.#selections,undoBoundary=!1,textOrder="selection"){if(selections===void 0)return;const textDocument=this.#editSession?.document,primarySelection=selections.at(-1);if(textDocument===void 0||primarySelection===void 0)return;const{nextSelections,change}=Array.isArray(text)&&text.length===selections.length?applyTextReplaceToSelections(textDocument,selections,text,this.#lineAnnotations,undoBoundary,textOrder):applyTextChangeToSelections(textDocument,selections,{start:textDocument.offsetAt(primarySelection.start),end:textDocument.offsetAt(primarySelection.end),text:Array.isArray(text)?text.join(textDocument.eol):text},this.#lineAnnotations,void 0,undoBoundary);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteSelectionText(forward=!1){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteCharacterToSelections(textDocument,selections,forward,this.#lineAnnotations,this.#metrics.tabSize);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteSoftLineBackward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const getSoftLineStart=this.#isWrap?(line,character)=>{const wrapOffsets=this.#wrapLineTextOrWholeLine(line);for(let w=0;w+1<wrapOffsets.length;w++){const segmentStart=wrapOffsets[w],segmentEnd=wrapOffsets[w+1];if(character>=segmentStart&&character<=segmentEnd)return segmentStart}return 0}:void 0,{nextSelections,change}=applyDeleteSoftLineBackwardToSelections(textDocument,selections,getSoftLineStart,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteWordBackward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteWordBackwardToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteHardLineForward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteHardLineForwardToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#insertTranspose(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyTransposeToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#applyChange(change,newSelections,newLineAnnotations,options){this.#editPrediction!=null&&this.#cancelEditPrediction(!0);const textDocument=this.#editSession?.document;if(textDocument!==void 0&&this.#carets!==void 0)for(const trackedCaret of this.#carets)trackedCaret.anchorOffset=remapOffsetThroughEdits(trackedCaret.anchorOffset,change.changes),trackedCaret.focusOffset=remapOffsetThroughEdits(trackedCaret.focusOffset,change.changes),trackedCaret.caret.anchor=textDocument.positionAt(trackedCaret.anchorOffset),trackedCaret.caret.focus=textDocument.positionAt(trackedCaret.focusOffset);if(change.lineDelta!==0||this.#isWrap)for(const line of this.#lineYCache.keys())line>=change.startLine&&this.#lineYCache.delete(line);if(this.#wrapLineOffsetsCache.size>0)if(change.lineDelta===0&&(change.changedLineRanges.length===1||change.changedLineChanges?.every(([,,editLineDelta])=>editLineDelta===0)===!0))for(const[rangeStart,rangeEnd]of change.changedLineRanges)for(let line=rangeStart;line<=rangeEnd;line++)this.#wrapLineOffsetsCache.delete(line);else for(const line of this.#wrapLineOffsetsCache.keys())line>=change.startLine&&this.#wrapLineOffsetsCache.delete(line);this.#lastAccessedCharX=void 0;let renderRange=this.#renderRange,shouldUpdateBuffer;if(renderRange!==void 0&&newSelections!==void 0&&newSelections.length>0){const primarySelection=newSelections.at(-1),renderRangeEndLine=renderRange.startingLine+renderRange.totalLines;if(primarySelection.end.line>=renderRangeEndLine){const widenedTotalLines=primarySelection.end.line-renderRange.startingLine+1,maxWidenLines=this.#viewportWindowLines===void 0||this.#viewportWindowLines===1/0?1/0:this.#viewportWindowLines*MAX_EDIT_WIDEN_WINDOW_MULTIPLE;change.startLine<=renderRangeEndLine&&widenedTotalLines<=maxWidenLines&&this.#isLineRenderable(primarySelection.end.line)?(primarySelection.end.line>renderRangeEndLine&&(shouldUpdateBuffer=!0),renderRange={...renderRange,totalLines:widenedTotalLines},this.#renderRange=renderRange):shouldUpdateBuffer=!0}}if(this.#isRendering&&this.#tokenizer!=null&&this.#contentElement!=null?this.#rerender(change,newLineAnnotations,renderRange,shouldUpdateBuffer):textDocument!=null&&(this.#applySuspendedDocumentChange?.(textDocument,newLineAnnotations),newLineAnnotations!=null&&(this.#lineAnnotations=newLineAnnotations)),newSelections!=null&&this.#updateSelections(newSelections),this.#fileInstance?.__acknowledgeDocumentUpdate(),this.#checkpointEditSessionState(),this.#recordEditPredictionHistory(change,options?.editSource??"user"),this.#scheduleEditPrediction(),this.#emitChange(change.changes,newLineAnnotations??this.#lineAnnotations),options?.skipSearchRefresh!==!0&&this.#searchPanel!==void 0&&this.#matches!==void 0&&this.#searchPanel.updateMatches({syncSelection:!1}),newSelections!=null&&options?.skipFocus!==!0){const revealTarget=newSelections.at(-1);if(revealTarget!==void 0&&this.#revealLineIfCollapsed(getCaretPosition(revealTarget).line),this.#primaryCaretElement!==void 0)requestAnimationFrame(()=>{this.#primaryCaretElement?.scrollIntoView({block:"nearest",inline:"nearest"})});else if(newSelections.length>0){const pos=getCaretPosition(newSelections.at(-1));this.#scrollToLine(pos.line,pos.character)}this.focus({preventScroll:!0})}}#emitChange(changes,lineAnnotations){const file=this.getFile(),publishChange=this.#publishChange;file==null||publishChange==null||publishChange(changes,file,lineAnnotations)}#applyChangeToLineAnnotations(change){if(this.#lineAnnotations!=null){const nextLineAnnotations=applyDocumentChangeToLineAnnotations(change,this.#lineAnnotations);if(nextLineAnnotations!=null)return this.#editSession?.document?.setLastUndoLineAnnotations(this.#lineAnnotations,nextLineAnnotations),nextLineAnnotations}}#getRenderedEditableLineRanges(){const contentElement=this.#contentElement;if(contentElement===void 0)return[];const ranges=[];for(const child of contentElement.children){const el=child,lineType=el.dataset.lineType,lineNumber=getLineNumberAttr(el);if(lineNumber===void 0||lineType===void 0||!isLineEditable(lineType))continue;const line=lineNumber-1,current=ranges.at(-1);current!==void 0&&line<=current[1]+1?current[1]=Math.max(current[1],line):ranges.push([line,line])}return ranges}#isLineInRenderRange(line){const renderRange=this.#renderRange;return renderRange==null||line>=renderRange.startingLine&&line<renderRange.startingLine+renderRange.totalLines}#getLineElement(line){let lineElement=this.#lineElementsCache.get(line);if(lineElement!==void 0)return lineElement??void 0;const renderRange=this.#renderRange;if(!this.#isLineInRenderRange(line))return;const contentElement=this.#contentElement;if(contentElement!==void 0){if(renderRange!==void 0){const{startingLine}=renderRange,{children}=contentElement;for(let i=line-startingLine;i<=children.length;i++){const child=children[i];if(child===void 0)break;const lineNumber=getLineNumberAttr(child),lineType=child.dataset.lineType;if(lineNumber!==void 0&&lineNumber===line+1&&lineType!==void 0&&isLineEditable(lineType)){lineElement=child;break}}}return lineElement??=contentElement.querySelector(`[data-line="${line+1}"]`+(this.#diffSyle==="unified"?':not([data-line-type="change-deletion"])':"")),lineElement!==void 0&&this.#lineElementsCache.set(line,lineElement),lineElement??void 0}}#getGutterWidth(){if(this.#gutterElement===void 0)return 0;if(this.#gutterWidthCache===void 0){const diffsColumnNumberWidth=this.#contentElement?.parentElement?.style.getPropertyValue("--diffs-column-number-width");diffsColumnNumberWidth!==void 0&&diffsColumnNumberWidth.length>2&&diffsColumnNumberWidth.endsWith("px")?this.#gutterWidthCache=parseInt(diffsColumnNumberWidth.slice(0,-2),10):this.#gutterWidthCache=this.#gutterElement.offsetWidth}return this.#gutterWidthCache}#getContentWidth(){if(this.#contentElement===void 0)return 0;if(this.#contentWidthCache===void 0){const diffsColumnContentWidth=this.#contentElement.parentElement?.style.getPropertyValue("--diffs-column-content-width");diffsColumnContentWidth!==void 0&&diffsColumnContentWidth.length>2&&diffsColumnContentWidth.endsWith("px")?this.#contentWidthCache=parseFloat(diffsColumnContentWidth.slice(0,-2)):this.#contentWidthCache=this.#contentElement.offsetWidth}return this.#contentWidthCache}#getLineY(line){const cachedY=this.#lineYCache.get(line);if(cachedY!==void 0)return cachedY;const lineElement=this.#getLineElement(line);if(lineElement===void 0)return-1;let y=lineElement.offsetTop+this.#metrics.paddingTop;return y+=this.#activeContentOffset?.top??0,this.#lineYCache.set(line,y),y}#getCharX(line,char){if(this.#lastAccessedCharX!==void 0&&this.#lastAccessedCharX[0]===line&&this.#lastAccessedCharX[1]===char)return[this.#lastAccessedCharX[2],this.#lastAccessedCharX[3]];const lineText=this.#editSession?.document?.getLineText(line),offsetLeft=this.#getGutterWidth()+this.#metrics.ch;if(lineText===void 0||lineText.length===0||char<=0)return[offsetLeft+(this.#activeContentOffset?.left??0),0];const boundedCharacter=snapTextOffsetToUnicodeBoundary(lineText,Math.min(char,lineText.length)),textBeforeCharacter=lineText.slice(0,boundedCharacter),asciiColumns=getExpandedAsciiTextColumns(textBeforeCharacter,this.#metrics.tabSize);let left=0,wrapLine=0;if(asciiColumns!==-1?left=offsetLeft+asciiColumns*this.#metrics.ch:left=offsetLeft+this.#metrics.measureTextWidth(textBeforeCharacter),this.#isWrap){const contentWidth=this.#getContentWidth();if(2*this.#metrics.ch+this.#metrics.measureTextWidth(lineText)>contentWidth){const wrapOffsets=this.#wrapLineText(line);if(wrapOffsets==null)return[left+(this.#activeContentOffset?.left??0),0];for(let w=0;w+1<wrapOffsets.length;w++){const segmentStart=wrapOffsets[w];if(boundedCharacter<=wrapOffsets[w+1]){wrapLine=w;const prefixInSegment=lineText.slice(segmentStart,boundedCharacter),segmentAsciiColumns=getExpandedAsciiTextColumns(prefixInSegment,this.#metrics.tabSize);segmentAsciiColumns!==-1?left=offsetLeft+segmentAsciiColumns*this.#metrics.ch:left=offsetLeft+this.#metrics.measureTextWidth(prefixInSegment);break}}}left+=this.#activeContentOffset?.left??0}return this.#lastAccessedCharX!==void 0?(this.#lastAccessedCharX[0]=line,this.#lastAccessedCharX[1]=char,this.#lastAccessedCharX[2]=left,this.#lastAccessedCharX[3]=wrapLine):this.#lastAccessedCharX=[line,char,left,wrapLine],[left,wrapLine]}#wrapLineText(line){const cachedOffsets=this.#wrapLineOffsetsCache.get(line);if(cachedOffsets!==void 0)return cachedOffsets;this.#wrapLineOffsetsCache.size>=MAX_WRAP_OFFSETS_CACHE_LINES&&this.#wrapLineOffsetsCache.clear();const lineText=this.#editSession?.document?.getLineText(line);if(lineText===void 0||lineText.length===0){const offsets=new Uint32Array([0]);return this.#wrapLineOffsetsCache.set(line,offsets),offsets}const contentElement=this.#contentElement;if(contentElement==null||!contentElement.isConnected)return;const div=h("div",{style:{position:"absolute",top:"0",left:"0",width:"100%",boxSizing:"border-box",visibility:"hidden",pointerEvents:"none",whiteSpace:"pre-wrap",wordBreak:"break-word",font:"inherit",paddingInline:"1ch",tabSize:this.#metrics.tabSize.toString()},textContent:lineText},contentElement),textNode=div.firstChild,range=document.createRange(),starts=[];try{const divRect=div.getBoundingClientRect();if(divRect.width===0)return;const unicodeOffsets=getUnicodeMeasurementOffsets(lineText),wrapLineStartLeft=divRect.left+this.#metrics.ch,graphemeCount=unicodeOffsets===void 0?lineText.length:unicodeOffsets.length-1,graphemeStart=index=>unicodeOffsets===void 0?index:unicodeOffsets[index],measureGrapheme=index=>{range.setStart(textNode,graphemeStart(index)),range.setEnd(textNode,graphemeStart(index+1));const clientRects=range.getClientRects();return clientRects.item(clientRects.length-1)??range.getBoundingClientRect()};starts.push(0);let lastTop=measureGrapheme(0).top,searchStart=1;for(;searchStart<graphemeCount;){let low=searchStart,high=graphemeCount;for(;low<high;){const mid=low+high>>1;measureGrapheme(mid).top>lastTop?high=mid:low=mid+1}if(low>=graphemeCount)break;const{left,top}=measureGrapheme(low),startsPastLineStart=isSafari()&&left-wrapLineStartLeft>this.#metrics.ch/2;starts.push(graphemeStart(startsPastLineStart?low-1:low)),lastTop=top,searchStart=low+1}const offsets=new Uint32Array(starts.length+1);for(let i=0;i<starts.length;i++)offsets[i]=starts[i];return offsets[starts.length]=lineText.length,this.#wrapLineOffsetsCache.set(line,offsets),offsets}finally{div.remove()}}#wrapLineTextOrWholeLine(line){const offsets=this.#wrapLineText(line);if(offsets!==void 0)return offsets;const length=this.#editSession?.document?.getLineText(line)?.length??0;return Uint32Array.of(0,length)}#rangeBelongsToEditor({startContainer,endContainer}){const contentEl=this.#contentElement;return contentEl===void 0?!1:contentEl.contains(startContainer)&&contentEl.contains(endContainer)}#isLineVisible(line){const lineCount=this.#editSession?.document?.lineCount??0;return line<0||line>=lineCount?!1:this.#getLineElement(line)!==void 0}};function getEditSession({type,editStateKey,owner,initialState,previousSession}){if(initialState!=null&&initialState.type!==type)throw new TypeError(`Editor: initialState: a ${initialState.type} state cannot initialize a ${type} editor`);const initialSession=initialState;return editStateKey!=null?EditStateManager.activate(type,editStateKey,owner,initialSession):initialSession??previousSession??(type==="file"?{type:"file"}:{type:"file-diff"})}function gridTrackSpan(child){return child instanceof HTMLElement?Number(child.dataset.bufferSize??1):1}function isValidEditPredictionPosition(document2,position){return position!==void 0&&Number.isInteger(position.line)&&Number.isInteger(position.character)&&position.line>=0&&position.line<document2.lineCount&&position.character>=0&&position.character<=document2.getLineLength(position.line)}function splitsSurrogatePair(text,offset){const previous=text.charCodeAt(offset-1),next=text.charCodeAt(offset);return offset>0&&offset<text.length&&previous>=55296&&previous<=56319&&next>=56320&&next<=57343}function renderFileChildren({file,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderAnnotation,lineAnnotations,renderGutterUtility,getHoveredLine,getAnnotationSlotName=getLineAnnotationName}){const customHeader=renderCustomHeader?.(file),prefix=renderHeaderPrefix?.(file),suffix=renderHeaderFilenameSuffix?.(file),metadata=renderHeaderMetadata?.(file);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[customHeader!=null?jsxRuntimeExports.jsx("div",{slot:CUSTOM_HEADER_SLOT_ID,children:customHeader}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[prefix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-prefix",children:prefix}),suffix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-filename-suffix",children:suffix}),metadata!=null&&jsxRuntimeExports.jsx("div",{slot:"header-metadata",children:metadata})]}),renderAnnotation!=null&&lineAnnotations?.map((annotation,index)=>jsxRuntimeExports.jsx("div",{slot:getAnnotationSlotName(annotation),children:renderAnnotation(annotation,file)},index)),renderGutterUtility!=null&&jsxRuntimeExports.jsx("div",{slot:"gutter-utility-slot",style:GutterUtilitySlotStyles,children:renderGutterUtility(getHoveredLine)})]})}const useIsomorphicLayoutEffect=typeof window>"u"?reactExports.useEffect:reactExports.useLayoutEffect;function useFileInstance({file,options,editorOptions,editStateKey,lineAnnotations,selectedLines,prerenderedHTML,metrics,hasGutterRenderUtility,hasCustomHeader,disableWorkerPool,edit,onEditChange:_onEditChange,onEditComplete:_onEditComplete}){const simpleVirtualizer=useVirtualizer(),controlledSelection=selectedLines!==void 0,poolManager=reactExports.useContext(WorkerPoolContext),createEditor2=useCreateEditor(),handleOnEditChange=useStableCallback(event=>_onEditChange?.(event)),onEditChange=_onEditChange!=null?handleOnEditChange:void 0,acceptedCache=reactExports.useRef(null),handleOnEditComplete=useStableCallback(event=>{const decision=_onEditComplete?.(event)??"reject";return decision==="accept"&&(acceptedCache.current={file:{installed:event.file,stale:event.originalFile},annotations:{installed:event.lineAnnotations,stale:event.originalLineAnnotations}}),decision}),onEditComplete=_onEditComplete!=null?handleOnEditComplete:void 0,instanceRef=reactExports.useRef(null),forceUpdate=useForceUpdate(),accepted=useAcceptedValues(acceptedCache,file,lineAnnotations),renderData=useNextRenderData(instanceRef,accepted)??{file,lineAnnotations:lineAnnotations??EMPTY_LINE_ANNOTATIONS},disposeEditorRef=reactExports.useRef(null),getEditor=useStableCallback(()=>{if(createEditor2==null)throw new Error("File: EditContext is not attached");return createEditor2("file",editorOptions??{},editStateKey)}),ref=useStableCallback(node=>{if(node!=null){if(instanceRef.current!=null)throw new Error("File: An instance should not already exist when a node is created");simpleVirtualizer!=null?instanceRef.current=new VirtualizedFile(mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),simpleVirtualizer,metrics,disableWorkerPool?void 0:poolManager,forceUpdate):instanceRef.current=new File$1(mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),disableWorkerPool?void 0:poolManager,forceUpdate),edit&&disposeEditorRef.current==null&&(disposeEditorRef.current=applyEdit(instanceRef.current,getEditor)),instanceRef.current.hydrate({file,fileContainer:node,lineAnnotations,prerenderedHTML})}else{if(instanceRef.current==null)throw new Error("File: A File instance should exist when unmounting");instanceRef.current.cleanUp(),instanceRef.current=null,disposeEditorRef.current=null}});useIsomorphicLayoutEffect(()=>{const{current:instance}=instanceRef;if(instance==null)return;const newOptions=mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),forceRender=!areOptionsEqual(instance.options,newOptions);if(instance.setOptions(newOptions),!edit&&disposeEditorRef.current!=null){const{current:disposeEditor}=disposeEditorRef;disposeEditorRef.current=null,disposeEditor()}const resolved=resolveAcceptedValues(file,lineAnnotations,acceptedCache);instance.render({file:resolved.file,lineAnnotations:resolved.lineAnnotations,forceRender}),selectedLines!==void 0&&instance.setSelectedLines(selectedLines),edit&&disposeEditorRef.current==null&&(disposeEditorRef.current=applyEdit(instance,getEditor),forceUpdate())});const getHoveredLine=reactExports.useCallback(()=>instanceRef.current?.getHoveredLine(),[]),getAnnotationSlotName=reactExports.useCallback(annotation=>instanceRef.current?.getAnnotationSlotName(annotation)??getLineAnnotationName(annotation),[]);return{...renderData,ref,getHoveredLine,getAnnotationSlotName}}function useAcceptedValues(acceptedCache,file,lineAnnotations){"use no memo";return getAcceptedValues(file,lineAnnotations,acceptedCache.current)}function getAcceptedValues(file,lineAnnotations,accepted){return{file:accepted?.file!=null&&areFileTargetsEqual(file,accepted.file.stale)?accepted.file.installed:file,lineAnnotations:accepted?.annotations!=null&&lineAnnotations===accepted.annotations.stale?accepted.annotations.installed:lineAnnotations}}function resolveAcceptedValues(file,lineAnnotations,acceptedCache){const{current:accepted}=acceptedCache,resolved=getAcceptedValues(file,lineAnnotations,accepted);return accepted==null||(accepted.file!=null&&!areFileTargetsEqual(file,accepted.file.stale)&&(accepted.file=null),lineAnnotations!==accepted.annotations?.stale&&(accepted.annotations=null),accepted.file==null&&accepted.annotations==null&&(acceptedCache.current=null)),resolved}function mergeFileOptions({options,controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete}){return{...options,controlledSelection,renderCustomHeader:hasCustomHeader?noopRender:options?.renderCustomHeader,renderGutterUtility:hasGutterRenderUtility?noopRender:options?.renderGutterUtility,onEditChange,onEditComplete}}function applyEdit(instance,getEditor){const editor=getEditor();try{return editor.edit(instance)}catch(error){throw editor.cleanUp(),error}}function File2({file,lineAnnotations,selectedLines,options,editorOptions,editStateKey,metrics,className,style,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,prerenderedHTML,renderGutterUtility,disableWorkerPool=!1,edit=!1,onEditChange,onEditComplete}){const{ref,getHoveredLine,getAnnotationSlotName,file:renderedFile,lineAnnotations:renderedAnnotations}=useFileInstance({file,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,prerenderedHTML,hasGutterRenderUtility:renderGutterUtility!=null,hasCustomHeader:renderCustomHeader!=null,disableWorkerPool,edit,onEditChange,onEditComplete}),children=renderFileChildren({file:renderedFile,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderGutterUtility,lineAnnotations:renderedAnnotations,getHoveredLine,getAnnotationSlotName});return jsxRuntimeExports.jsx(DIFFS_TAG_NAME,{ref,className,style,children:templateRender(children,prerenderedHTML)})}const WORD_CHAR=/[\p{L}\p{N}_$]/u;function wordAt(text,offset){if(offset<0||offset>=text.length||!WORD_CHAR.test(text[offset]))return null;let start=offset;for(;start>0&&WORD_CHAR.test(text[start-1]);)start--;let end=offset+1;for(;end<text.length&&WORD_CHAR.test(text[end]);)end++;return{start,end,text:text.slice(start,end)}}function lineRange(token,start,end){const row=token.closest("[data-line]");if(!row||end<=start)return null;const from=pointIn(row,start,!1),to=pointIn(row,end,!0);if(!from||!to)return null;const range=document.createRange();return range.setStart(from.node,from.offset),range.setEnd(to.node,to.offset),range}function pointIn(row,at,closing){for(const span of row.querySelectorAll("[data-char]")){let offset=at-Number(span.dataset.char);if(!(offset>=0))continue;const texts=document.createTreeWalker(span,NodeFilter.SHOW_TEXT);for(let node=texts.nextNode();node;node=texts.nextNode()){if(offset<node.data.length||closing&&offset===node.data.length)return{node,offset};offset-=node.data.length}}return null}function offsetAt(rect,chars,clientX){if(chars<=0||rect.width<=0)return 0;const raw=Math.floor((clientX-rect.left)/rect.width*chars);return Math.min(chars-1,Math.max(0,raw))}function offsetIn(element,clientX,clientY){const node=element.firstChild,chars=node?.textContent?.length??0,estimate=()=>offsetAt(element.getBoundingClientRect(),chars,clientX);if(!node||node.nodeType!==Node.TEXT_NODE||chars===0)return estimate();const doc=document;let hit=null;const root=element.getRootNode();if(typeof doc.caretPositionFromPoint=="function")hit=doc.caretPositionFromPoint(clientX,clientY,root instanceof ShadowRoot?{shadowRoots:[root]}:void 0);else if(typeof doc.caretRangeFromPoint=="function"){const range=doc.caretRangeFromPoint(clientX,clientY);range&&(hit={offsetNode:range.startContainer,offset:range.startOffset})}if(!hit||hit.offsetNode!==node)return estimate();let offset=Math.min(chars-1,Math.max(0,hit.offset));if(offset>0){const probe=document.createRange();probe.setStart(node,offset),probe.setEnd(node,offset),probe.getBoundingClientRect().left>clientX&&offset--}return offset}const createEditor=(type,options,key)=>new Editor(type,options,key);function FileViewInner({name,contents,wrap=!1,hideHeader=!1,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,edit,tabSize,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted,annotations,renderAnnotation,className,virtualize}){const{shikiTheme:theme,appearance}=useEditorEnvironment(),selectable=onSelectionEnd!==void 0,host=useDetachCleanup(),latest=reactExports.useRef({onSelectionEnd,onGutterAction,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted,renderAnnotation,edit,wrap});latest.current={onSelectionEnd,onGutterAction,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted,renderAnnotation,edit,wrap};const highlightedOnce=reactExports.useRef(!1),words=reactExports.useMemo(()=>wordHover({enter:(t,e)=>latest.current.onTokenEnter?.(t,e),leave:()=>latest.current.onTokenLeave?.()}),[]),stable=reactExports.useMemo(()=>({onLineSelectionEnd:r=>latest.current.onSelectionEnd?.(r),onGutterUtilityClick:r=>latest.current.onGutterAction?.(r),onTokenEnter:(t,e)=>words.enter(t,e),onTokenLeave:()=>words.leave(),onTokenClick:(t,e)=>{const token=words.token(t,e.clientX,e.clientY);token&&latest.current.onTokenClick?.(token,e)},renderAnnotation:a=>latest.current.renderAnnotation?.(a)??null,onEditChange:e=>latest.current.edit?.onChange(e.file.contents,e.changes.map(c=>({range:c.range,text:c.text}))),onEditComplete:e=>latest.current.edit?.onComplete?.(e)??"reject",onPostRender:(node,instance,phase)=>{const highlighted=phase!=="unmount"&&isHighlighted(instance,node);revealOnHighlight(node,highlighted,phase,phase!=="unmount"&&colorsFile(instance)),scrollReachOnRender(node,!latest.current.wrap,phase),!(phase==="unmount"||highlightedOnce.current||!latest.current.onHighlighted)&&highlighted&&(highlightedOnce.current=!0,latest.current.onHighlighted())}}),[words]),hasTokenHandlers=onTokenEnter!==void 0,hasTokenClick=onTokenClick!==void 0,hasGutter=onGutterAction!==void 0,options=reactExports.useMemo(()=>({theme,themeType:appearance,overflow:wrap?"wrap":"scroll",disableFileHeader:hideHeader,stickyHeader:!hideHeader,unsafeCSS:DIFFS_UNSAFE_CSS,preferredHighlighter:PREFERRED_HIGHLIGHTER,onPostRender:stable.onPostRender,...selectable?{enableLineSelection:!0,onLineSelectionEnd:stable.onLineSelectionEnd}:{},...hasGutter?{enableGutterUtility:!0,onGutterUtilityClick:stable.onGutterUtilityClick}:{},...hasTokenHandlers?{onTokenEnter:stable.onTokenEnter,onTokenLeave:stable.onTokenLeave}:{},...hasTokenClick?{onTokenClick:stable.onTokenClick}:{}}),[theme,appearance,wrap,hideHeader,selectable,hasGutter,hasTokenHandlers,hasTokenClick,stable]),file=reactExports.useMemo(()=>({name,contents,cacheKey:`${name}\0${contentHash(contents)}`}),[name,contents]),lineAnnotations=reactExports.useMemo(()=>annotations?[...annotations]:void 0,[annotations]),style=reactExports.useMemo(()=>tabSize?{...DIFFS_HOST_STYLE,tabSize}:DIFFS_HOST_STYLE,[tabSize]),view=jsxRuntimeExports.jsx(EditProvider,{createEditor,children:jsxRuntimeExports.jsx(File2,{file,className,style,...edit?{edit:!0,editorOptions:edit.options,editStateKey:edit.stateKey,onEditChange:stable.onEditChange,onEditComplete:stable.onEditComplete}:{},...selectable?{selectedLines:selectedLines??null}:{},...lineAnnotations?{lineAnnotations}:{},...renderAnnotation?{renderAnnotation:stable.renderAnnotation}:{},options})});return jsxRuntimeExports.jsx("div",{ref:host,className:"contents",onContextMenu,children:virtualize?jsxRuntimeExports.jsx(Virtualizer,{className:virtualize.className,contentClassName:"min-h-full",config:VIRTUALIZER_CONFIG,children:view}):view})}const LINK_HIGHLIGHT="zg-link";function setLinkHighlight(range){const registry=CSS.highlights;if(!registry)return;if(!range){registry.delete(LINK_HIGHLIGHT);return}const Highlight=globalThis.Highlight;Highlight&&registry.set(LINK_HIGHLIGHT,new Highlight(range))}function wordRange(element,word){const node=element.firstChild;if(!node||node.nodeType!==Node.TEXT_NODE)return null;const range=document.createRange();return range.setStart(node,word.start),range.setEnd(node,Math.min(word.end,node.textContent?.length??word.end)),range}function wordHover(handlers){let span=null,pointer=null,current=null,link=null,leaving=!1;const inLink=(t,offset)=>{const at=t.lineCharStart+offset;return link!==null&&link.line===t.lineNumber&&at>=link.start&&at<link.end},keyAt=(t,offset)=>{if(inLink(t,offset))return"link";const word=wordAt(t.tokenText,offset);return word?`${t.lineNumber}:${t.lineCharStart+word.start}`:null},draw=(t,word,columns)=>{const exact=columns?lineRange(t.tokenElement,columns.column-1,columns.endColumn-1):null,range=exact??wordRange(t.tokenElement,word);range&&(link=exact?{line:t.lineNumber,start:columns.column-1,end:columns.endColumn-1}:{line:t.lineNumber,start:t.lineCharStart+word.start,end:t.lineCharStart+word.end},setLinkHighlight(range),pointer&&inLink(pointer.token,pointer.offset)&&(current="link"))},erase=()=>{setLinkHighlight(null),link=null,current==="link"&&(current=null)},tokenAt=(t,offset)=>{const word=inLink(t,offset)?spanWord(t.tokenText,link.start-t.lineCharStart,link.end-t.lineCharStart):wordAt(t.tokenText,offset);return word?{lineNumber:t.lineNumber,lineCharStart:t.lineCharStart,text:t.tokenText,element:t.tokenElement,word,column:t.lineCharStart+offset+1,link:(on,columns)=>on?draw(t,word,columns):erase()}:null},resolve=(t,clientX,clientY)=>tokenAt(t,offsetIn(t.tokenElement,clientX,clientY)),onMove=e=>{if(!span)return;const offset=offsetIn(span.tokenElement,e.clientX,e.clientY);if(pointer={token:span,offset},keyAt(span,offset)===current)return;current&&handlers.leave(),current=keyAt(span,offset);const token=current?tokenAt(span,offset):null;token&&handlers.enter(token,e)},track=t=>{span?.tokenElement.removeEventListener("pointermove",onMove),span=t,t?.tokenElement.addEventListener("pointermove",onMove)},leave=()=>{leaving=!1,pointer=null,current&&handlers.leave(),current=null};return{enter(t,e){track(t),leaving&&!inLink(t,offsetIn(t.tokenElement,e.clientX,e.clientY))&&leave(),leaving=!1,onMove(e)},leave(){if(track(null),current!=="link")return leave();leaving=!0,queueMicrotask(()=>leaving&&leave())},token:resolve}}function spanWord(text,start,end){const from=Math.max(0,start),to=Math.min(text.length,end);return from<to?{start:from,end:to,text:text.slice(from,to)}:null}function isHighlighted(instance,node){const cache=instance?.fileRenderer?.renderCache;return cache&&typeof cache.highlighted=="boolean"?cache.highlighted:node.shadowRoot?.querySelector("[data-line] span[class], [data-line] span[style]")!==null}function colorsFile(instance){const renderer=instance?.fileRenderer,file=renderer?.renderCache?.file;if(!file?.contents||(file.lang??getFiletypeFromFileName(file.name))==="text")return!1;const max=renderer?.getTokenizeMaxLength?.()??DEFAULT_TOKENIZE_MAX_LENGTH;return file.contents.length<=max||file.contents.split(`
67
+ `)&&(defaultQuery=selectionText,initialMatch=[textDocument.offsetAt(primarySelection.start),textDocument.offsetAt(primarySelection.end)])}}const scrollToMatch=([startOffset,endOffset],retainFocus)=>{const nextSelection=createSelectionFromAnchorAndFocusOffsets(textDocument,startOffset,endOffset);this.#updateSelections([nextSelection]),this.#revealLineIfCollapsed(getCaretPosition(nextSelection).line),this.#scrollToPrimaryCaret(!0),this.#retainSearchPanelFocus=retainFocus},searchPanel=new SearchPanelWidget({textDocument,containerElement:preElement,defaultQuery,mode,initialMatch,scrollToMatch,applyReplace:edits=>{if(edits.length===0)return;const change=textDocument.applyEdits(edits.map(edit=>({range:{start:textDocument.positionAt(edit.start),end:textDocument.positionAt(edit.end)},newText:edit.text})),!0,this.#selections);change!==void 0&&this.#applyChange(change,void 0,this.#applyChangeToLineAnnotations(change),{skipSearchRefresh:!0})},onUpdate:(allMatches,options)=>{if(allMatches.length===0){this.#matches=void 0,this.#updateSelections(this.#selections??[]);return}if(this.#matches=allMatches,options?.syncSelection===!1){this.#updateSelections(this.#selections??[]);const primarySelection2=this.#selections?.at(-1);if(primarySelection2!==void 0){const startOffset=textDocument.offsetAt(primarySelection2.start),endOffset=textDocument.offsetAt(primarySelection2.end);for(const match of allMatches)if(match[0]===startOffset&&match[1]===endOffset)return match}return}const primarySelection=this.#selections?.at(-1);let searchOffset=0,nextMatch;primarySelection!==void 0&&(searchOffset=textDocument.offsetAt(primarySelection.start));for(const m of allMatches)if(m[0]>=searchOffset){nextMatch=m;break}return nextMatch!==void 0?scrollToMatch(nextMatch,!0):this.#updateSelections(this.#selections??[]),nextMatch},onClose:()=>{this.#searchPanel=void 0,this.#retainSearchPanelFocus=!1,this.#matches=void 0,this.#updateSelections(this.#selections??[])}});this.#searchPanel=searchPanel,this.#retainSearchPanelFocus=!1}#getSelectionText(){const textDocument=this.#editSession?.document,selections=this.#selections;return textDocument===void 0||selections===void 0?"":getSelectionText(textDocument,selections)}#getSelectionClipboardTexts(){const textDocument=this.#editSession?.document,selections=this.#selections;return textDocument===void 0||selections===void 0?[]:getSelectionClipboardTexts(textDocument,selections)}#writeSelectionClipboardData(clipboardData,text,selectionTexts){clipboardData!==null&&(clipboardData.setData("text",text),selectionTexts.length>1&&clipboardData.setData(MULTI_SELECTION_CLIPBOARD_TYPE,JSON.stringify(selectionTexts)))}#cutSelectionText(){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0||selections.length===0)return"";if(selections.some(selection=>isCollapsedSelection(selection))){const cut=resolveSelectionCut(textDocument,selections);return this.#applySelectionCutEdits(cut.edits,cut.nextSelectionOffsets),cut.text}const text=getSelectionText(textDocument,selections);return this.#replaceSelectionText("",void 0,!0),text}#applySelectionCutEdits(edits,nextSelectionOffsets){const textDocument=this.#editSession?.document,selections=this.#selections;if(textDocument===void 0||selections===void 0||edits.length===0)return;const change=textDocument.applyResolvedEdits(edits,!0,selections,void 0,!0);if(change===void 0)return;const nextSelections=nextSelectionOffsets.map(offset=>{const caret=textDocument.positionAt(offset);return{start:caret,end:caret,direction:0}});textDocument.setLastUndoSelectionsAfter(nextSelections),this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#replaceSelectionText(text,selections=this.#selections,undoBoundary=!1,textOrder="selection"){if(selections===void 0)return;const textDocument=this.#editSession?.document,primarySelection=selections.at(-1);if(textDocument===void 0||primarySelection===void 0)return;const{nextSelections,change}=Array.isArray(text)&&text.length===selections.length?applyTextReplaceToSelections(textDocument,selections,text,this.#lineAnnotations,undoBoundary,textOrder):applyTextChangeToSelections(textDocument,selections,{start:textDocument.offsetAt(primarySelection.start),end:textDocument.offsetAt(primarySelection.end),text:Array.isArray(text)?text.join(textDocument.eol):text},this.#lineAnnotations,void 0,undoBoundary);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteSelectionText(forward=!1){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteCharacterToSelections(textDocument,selections,forward,this.#lineAnnotations,this.#metrics.tabSize);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteSoftLineBackward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const getSoftLineStart=this.#isWrap?(line,character)=>{const wrapOffsets=this.#wrapLineTextOrWholeLine(line);for(let w=0;w+1<wrapOffsets.length;w++){const segmentStart=wrapOffsets[w],segmentEnd=wrapOffsets[w+1];if(character>=segmentStart&&character<=segmentEnd)return segmentStart}return 0}:void 0,{nextSelections,change}=applyDeleteSoftLineBackwardToSelections(textDocument,selections,getSoftLineStart,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteWordBackward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteWordBackwardToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#deleteHardLineForward(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyDeleteHardLineForwardToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#insertTranspose(){const selections=this.#selections,textDocument=this.#editSession?.document;if(selections===void 0||textDocument===void 0)return;const{nextSelections,change}=applyTransposeToSelections(textDocument,selections,this.#lineAnnotations);change!==void 0&&this.#applyChange(change,nextSelections,this.#applyChangeToLineAnnotations(change))}#applyChange(change,newSelections,newLineAnnotations,options){this.#editPrediction!=null&&this.#cancelEditPrediction(!0);const textDocument=this.#editSession?.document;if(textDocument!==void 0&&this.#carets!==void 0)for(const trackedCaret of this.#carets)trackedCaret.anchorOffset=remapOffsetThroughEdits(trackedCaret.anchorOffset,change.changes),trackedCaret.focusOffset=remapOffsetThroughEdits(trackedCaret.focusOffset,change.changes),trackedCaret.caret.anchor=textDocument.positionAt(trackedCaret.anchorOffset),trackedCaret.caret.focus=textDocument.positionAt(trackedCaret.focusOffset);if(change.lineDelta!==0||this.#isWrap)for(const line of this.#lineYCache.keys())line>=change.startLine&&this.#lineYCache.delete(line);if(this.#wrapLineOffsetsCache.size>0)if(change.lineDelta===0&&(change.changedLineRanges.length===1||change.changedLineChanges?.every(([,,editLineDelta])=>editLineDelta===0)===!0))for(const[rangeStart,rangeEnd]of change.changedLineRanges)for(let line=rangeStart;line<=rangeEnd;line++)this.#wrapLineOffsetsCache.delete(line);else for(const line of this.#wrapLineOffsetsCache.keys())line>=change.startLine&&this.#wrapLineOffsetsCache.delete(line);this.#lastAccessedCharX=void 0;let renderRange=this.#renderRange,shouldUpdateBuffer;if(renderRange!==void 0&&newSelections!==void 0&&newSelections.length>0){const primarySelection=newSelections.at(-1),renderRangeEndLine=renderRange.startingLine+renderRange.totalLines;if(primarySelection.end.line>=renderRangeEndLine){const widenedTotalLines=primarySelection.end.line-renderRange.startingLine+1,maxWidenLines=this.#viewportWindowLines===void 0||this.#viewportWindowLines===1/0?1/0:this.#viewportWindowLines*MAX_EDIT_WIDEN_WINDOW_MULTIPLE;change.startLine<=renderRangeEndLine&&widenedTotalLines<=maxWidenLines&&this.#isLineRenderable(primarySelection.end.line)?(primarySelection.end.line>renderRangeEndLine&&(shouldUpdateBuffer=!0),renderRange={...renderRange,totalLines:widenedTotalLines},this.#renderRange=renderRange):shouldUpdateBuffer=!0}}if(this.#isRendering&&this.#tokenizer!=null&&this.#contentElement!=null?this.#rerender(change,newLineAnnotations,renderRange,shouldUpdateBuffer):textDocument!=null&&(this.#applySuspendedDocumentChange?.(textDocument,newLineAnnotations),newLineAnnotations!=null&&(this.#lineAnnotations=newLineAnnotations)),newSelections!=null&&this.#updateSelections(newSelections),this.#fileInstance?.__acknowledgeDocumentUpdate(),this.#checkpointEditSessionState(),this.#recordEditPredictionHistory(change,options?.editSource??"user"),this.#scheduleEditPrediction(),this.#emitChange(change.changes,newLineAnnotations??this.#lineAnnotations),options?.skipSearchRefresh!==!0&&this.#searchPanel!==void 0&&this.#matches!==void 0&&this.#searchPanel.updateMatches({syncSelection:!1}),newSelections!=null&&options?.skipFocus!==!0){const revealTarget=newSelections.at(-1);if(revealTarget!==void 0&&this.#revealLineIfCollapsed(getCaretPosition(revealTarget).line),this.#primaryCaretElement!==void 0)requestAnimationFrame(()=>{this.#primaryCaretElement?.scrollIntoView({block:"nearest",inline:"nearest"})});else if(newSelections.length>0){const pos=getCaretPosition(newSelections.at(-1));this.#scrollToLine(pos.line,pos.character)}this.focus({preventScroll:!0})}}#emitChange(changes,lineAnnotations){const file=this.getFile(),publishChange=this.#publishChange;file==null||publishChange==null||publishChange(changes,file,lineAnnotations)}#applyChangeToLineAnnotations(change){if(this.#lineAnnotations!=null){const nextLineAnnotations=applyDocumentChangeToLineAnnotations(change,this.#lineAnnotations);if(nextLineAnnotations!=null)return this.#editSession?.document?.setLastUndoLineAnnotations(this.#lineAnnotations,nextLineAnnotations),nextLineAnnotations}}#getRenderedEditableLineRanges(){const contentElement=this.#contentElement;if(contentElement===void 0)return[];const ranges=[];for(const child of contentElement.children){const el=child,lineType=el.dataset.lineType,lineNumber=getLineNumberAttr(el);if(lineNumber===void 0||lineType===void 0||!isLineEditable(lineType))continue;const line=lineNumber-1,current=ranges.at(-1);current!==void 0&&line<=current[1]+1?current[1]=Math.max(current[1],line):ranges.push([line,line])}return ranges}#isLineInRenderRange(line){const renderRange=this.#renderRange;return renderRange==null||line>=renderRange.startingLine&&line<renderRange.startingLine+renderRange.totalLines}#getLineElement(line){let lineElement=this.#lineElementsCache.get(line);if(lineElement!==void 0)return lineElement??void 0;const renderRange=this.#renderRange;if(!this.#isLineInRenderRange(line))return;const contentElement=this.#contentElement;if(contentElement!==void 0){if(renderRange!==void 0){const{startingLine}=renderRange,{children}=contentElement;for(let i=line-startingLine;i<=children.length;i++){const child=children[i];if(child===void 0)break;const lineNumber=getLineNumberAttr(child),lineType=child.dataset.lineType;if(lineNumber!==void 0&&lineNumber===line+1&&lineType!==void 0&&isLineEditable(lineType)){lineElement=child;break}}}return lineElement??=contentElement.querySelector(`[data-line="${line+1}"]`+(this.#diffSyle==="unified"?':not([data-line-type="change-deletion"])':"")),lineElement!==void 0&&this.#lineElementsCache.set(line,lineElement),lineElement??void 0}}#getGutterWidth(){if(this.#gutterElement===void 0)return 0;if(this.#gutterWidthCache===void 0){const diffsColumnNumberWidth=this.#contentElement?.parentElement?.style.getPropertyValue("--diffs-column-number-width");diffsColumnNumberWidth!==void 0&&diffsColumnNumberWidth.length>2&&diffsColumnNumberWidth.endsWith("px")?this.#gutterWidthCache=parseInt(diffsColumnNumberWidth.slice(0,-2),10):this.#gutterWidthCache=this.#gutterElement.offsetWidth}return this.#gutterWidthCache}#getContentWidth(){if(this.#contentElement===void 0)return 0;if(this.#contentWidthCache===void 0){const diffsColumnContentWidth=this.#contentElement.parentElement?.style.getPropertyValue("--diffs-column-content-width");diffsColumnContentWidth!==void 0&&diffsColumnContentWidth.length>2&&diffsColumnContentWidth.endsWith("px")?this.#contentWidthCache=parseFloat(diffsColumnContentWidth.slice(0,-2)):this.#contentWidthCache=this.#contentElement.offsetWidth}return this.#contentWidthCache}#getLineY(line){const cachedY=this.#lineYCache.get(line);if(cachedY!==void 0)return cachedY;const lineElement=this.#getLineElement(line);if(lineElement===void 0)return-1;let y=lineElement.offsetTop+this.#metrics.paddingTop;return y+=this.#activeContentOffset?.top??0,this.#lineYCache.set(line,y),y}#getCharX(line,char){if(this.#lastAccessedCharX!==void 0&&this.#lastAccessedCharX[0]===line&&this.#lastAccessedCharX[1]===char)return[this.#lastAccessedCharX[2],this.#lastAccessedCharX[3]];const lineText=this.#editSession?.document?.getLineText(line),offsetLeft=this.#getGutterWidth()+this.#metrics.ch;if(lineText===void 0||lineText.length===0||char<=0)return[offsetLeft+(this.#activeContentOffset?.left??0),0];const boundedCharacter=snapTextOffsetToUnicodeBoundary(lineText,Math.min(char,lineText.length)),textBeforeCharacter=lineText.slice(0,boundedCharacter),asciiColumns=getExpandedAsciiTextColumns(textBeforeCharacter,this.#metrics.tabSize);let left=0,wrapLine=0;if(asciiColumns!==-1?left=offsetLeft+asciiColumns*this.#metrics.ch:left=offsetLeft+this.#metrics.measureTextWidth(textBeforeCharacter),this.#isWrap){const contentWidth=this.#getContentWidth();if(2*this.#metrics.ch+this.#metrics.measureTextWidth(lineText)>contentWidth){const wrapOffsets=this.#wrapLineText(line);if(wrapOffsets==null)return[left+(this.#activeContentOffset?.left??0),0];for(let w=0;w+1<wrapOffsets.length;w++){const segmentStart=wrapOffsets[w];if(boundedCharacter<=wrapOffsets[w+1]){wrapLine=w;const prefixInSegment=lineText.slice(segmentStart,boundedCharacter),segmentAsciiColumns=getExpandedAsciiTextColumns(prefixInSegment,this.#metrics.tabSize);segmentAsciiColumns!==-1?left=offsetLeft+segmentAsciiColumns*this.#metrics.ch:left=offsetLeft+this.#metrics.measureTextWidth(prefixInSegment);break}}}left+=this.#activeContentOffset?.left??0}return this.#lastAccessedCharX!==void 0?(this.#lastAccessedCharX[0]=line,this.#lastAccessedCharX[1]=char,this.#lastAccessedCharX[2]=left,this.#lastAccessedCharX[3]=wrapLine):this.#lastAccessedCharX=[line,char,left,wrapLine],[left,wrapLine]}#wrapLineText(line){const cachedOffsets=this.#wrapLineOffsetsCache.get(line);if(cachedOffsets!==void 0)return cachedOffsets;this.#wrapLineOffsetsCache.size>=MAX_WRAP_OFFSETS_CACHE_LINES&&this.#wrapLineOffsetsCache.clear();const lineText=this.#editSession?.document?.getLineText(line);if(lineText===void 0||lineText.length===0){const offsets=new Uint32Array([0]);return this.#wrapLineOffsetsCache.set(line,offsets),offsets}const contentElement=this.#contentElement;if(contentElement==null||!contentElement.isConnected)return;const div=h("div",{style:{position:"absolute",top:"0",left:"0",width:"100%",boxSizing:"border-box",visibility:"hidden",pointerEvents:"none",whiteSpace:"pre-wrap",wordBreak:"break-word",font:"inherit",paddingInline:"1ch",tabSize:this.#metrics.tabSize.toString()},textContent:lineText},contentElement),textNode=div.firstChild,range=document.createRange(),starts=[];try{const divRect=div.getBoundingClientRect();if(divRect.width===0)return;const unicodeOffsets=getUnicodeMeasurementOffsets(lineText),wrapLineStartLeft=divRect.left+this.#metrics.ch,graphemeCount=unicodeOffsets===void 0?lineText.length:unicodeOffsets.length-1,graphemeStart=index=>unicodeOffsets===void 0?index:unicodeOffsets[index],measureGrapheme=index=>{range.setStart(textNode,graphemeStart(index)),range.setEnd(textNode,graphemeStart(index+1));const clientRects=range.getClientRects();return clientRects.item(clientRects.length-1)??range.getBoundingClientRect()};starts.push(0);let lastTop=measureGrapheme(0).top,searchStart=1;for(;searchStart<graphemeCount;){let low=searchStart,high=graphemeCount;for(;low<high;){const mid=low+high>>1;measureGrapheme(mid).top>lastTop?high=mid:low=mid+1}if(low>=graphemeCount)break;const{left,top}=measureGrapheme(low),startsPastLineStart=isSafari()&&left-wrapLineStartLeft>this.#metrics.ch/2;starts.push(graphemeStart(startsPastLineStart?low-1:low)),lastTop=top,searchStart=low+1}const offsets=new Uint32Array(starts.length+1);for(let i=0;i<starts.length;i++)offsets[i]=starts[i];return offsets[starts.length]=lineText.length,this.#wrapLineOffsetsCache.set(line,offsets),offsets}finally{div.remove()}}#wrapLineTextOrWholeLine(line){const offsets=this.#wrapLineText(line);if(offsets!==void 0)return offsets;const length=this.#editSession?.document?.getLineText(line)?.length??0;return Uint32Array.of(0,length)}#rangeBelongsToEditor({startContainer,endContainer}){const contentEl=this.#contentElement;return contentEl===void 0?!1:contentEl.contains(startContainer)&&contentEl.contains(endContainer)}#isLineVisible(line){const lineCount=this.#editSession?.document?.lineCount??0;return line<0||line>=lineCount?!1:this.#getLineElement(line)!==void 0}};function getEditSession({type,editStateKey,owner,initialState,previousSession}){if(initialState!=null&&initialState.type!==type)throw new TypeError(`Editor: initialState: a ${initialState.type} state cannot initialize a ${type} editor`);const initialSession=initialState;return editStateKey!=null?EditStateManager.activate(type,editStateKey,owner,initialSession):initialSession??previousSession??(type==="file"?{type:"file"}:{type:"file-diff"})}function gridTrackSpan(child){return child instanceof HTMLElement?Number(child.dataset.bufferSize??1):1}function isValidEditPredictionPosition(document2,position){return position!==void 0&&Number.isInteger(position.line)&&Number.isInteger(position.character)&&position.line>=0&&position.line<document2.lineCount&&position.character>=0&&position.character<=document2.getLineLength(position.line)}function splitsSurrogatePair(text,offset){const previous=text.charCodeAt(offset-1),next=text.charCodeAt(offset);return offset>0&&offset<text.length&&previous>=55296&&previous<=56319&&next>=56320&&next<=57343}function renderFileChildren({file,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderAnnotation,lineAnnotations,renderGutterUtility,getHoveredLine,getAnnotationSlotName=getLineAnnotationName}){const customHeader=renderCustomHeader?.(file),prefix=renderHeaderPrefix?.(file),suffix=renderHeaderFilenameSuffix?.(file),metadata=renderHeaderMetadata?.(file);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[customHeader!=null?jsxRuntimeExports.jsx("div",{slot:CUSTOM_HEADER_SLOT_ID,children:customHeader}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[prefix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-prefix",children:prefix}),suffix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-filename-suffix",children:suffix}),metadata!=null&&jsxRuntimeExports.jsx("div",{slot:"header-metadata",children:metadata})]}),renderAnnotation!=null&&lineAnnotations?.map((annotation,index)=>jsxRuntimeExports.jsx("div",{slot:getAnnotationSlotName(annotation),children:renderAnnotation(annotation,file)},index)),renderGutterUtility!=null&&jsxRuntimeExports.jsx("div",{slot:"gutter-utility-slot",style:GutterUtilitySlotStyles,children:renderGutterUtility(getHoveredLine)})]})}const useIsomorphicLayoutEffect=typeof window>"u"?reactExports.useEffect:reactExports.useLayoutEffect;function useFileInstance({file,options,editorOptions,editStateKey,lineAnnotations,selectedLines,prerenderedHTML,metrics,hasGutterRenderUtility,hasCustomHeader,disableWorkerPool,edit,onEditChange:_onEditChange,onEditComplete:_onEditComplete}){const simpleVirtualizer=useVirtualizer(),controlledSelection=selectedLines!==void 0,poolManager=reactExports.useContext(WorkerPoolContext),createEditor2=useCreateEditor(),handleOnEditChange=useStableCallback(event=>_onEditChange?.(event)),onEditChange=_onEditChange!=null?handleOnEditChange:void 0,acceptedCache=reactExports.useRef(null),handleOnEditComplete=useStableCallback(event=>{const decision=_onEditComplete?.(event)??"reject";return decision==="accept"&&(acceptedCache.current={file:{installed:event.file,stale:event.originalFile},annotations:{installed:event.lineAnnotations,stale:event.originalLineAnnotations}}),decision}),onEditComplete=_onEditComplete!=null?handleOnEditComplete:void 0,instanceRef=reactExports.useRef(null),forceUpdate=useForceUpdate(),accepted=useAcceptedValues(acceptedCache,file,lineAnnotations),renderData=useNextRenderData(instanceRef,accepted)??{file,lineAnnotations:lineAnnotations??EMPTY_LINE_ANNOTATIONS},disposeEditorRef=reactExports.useRef(null),getEditor=useStableCallback(()=>{if(createEditor2==null)throw new Error("File: EditContext is not attached");return createEditor2("file",editorOptions??{},editStateKey)}),ref=useStableCallback(node=>{if(node!=null){if(instanceRef.current!=null)throw new Error("File: An instance should not already exist when a node is created");simpleVirtualizer!=null?instanceRef.current=new VirtualizedFile(mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),simpleVirtualizer,metrics,disableWorkerPool?void 0:poolManager,forceUpdate):instanceRef.current=new File$1(mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),disableWorkerPool?void 0:poolManager,forceUpdate),edit&&disposeEditorRef.current==null&&(disposeEditorRef.current=applyEdit(instanceRef.current,getEditor)),instanceRef.current.hydrate({file,fileContainer:node,lineAnnotations,prerenderedHTML})}else{if(instanceRef.current==null)throw new Error("File: A File instance should exist when unmounting");instanceRef.current.cleanUp(),instanceRef.current=null,disposeEditorRef.current=null}});useIsomorphicLayoutEffect(()=>{const{current:instance}=instanceRef;if(instance==null)return;const newOptions=mergeFileOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),forceRender=!areOptionsEqual(instance.options,newOptions);if(instance.setOptions(newOptions),!edit&&disposeEditorRef.current!=null){const{current:disposeEditor}=disposeEditorRef;disposeEditorRef.current=null,disposeEditor()}const resolved=resolveAcceptedValues(file,lineAnnotations,acceptedCache);instance.render({file:resolved.file,lineAnnotations:resolved.lineAnnotations,forceRender}),selectedLines!==void 0&&instance.setSelectedLines(selectedLines),edit&&disposeEditorRef.current==null&&(disposeEditorRef.current=applyEdit(instance,getEditor),forceUpdate())});const getHoveredLine=reactExports.useCallback(()=>instanceRef.current?.getHoveredLine(),[]),getAnnotationSlotName=reactExports.useCallback(annotation=>instanceRef.current?.getAnnotationSlotName(annotation)??getLineAnnotationName(annotation),[]);return{...renderData,ref,getHoveredLine,getAnnotationSlotName}}function useAcceptedValues(acceptedCache,file,lineAnnotations){"use no memo";return getAcceptedValues(file,lineAnnotations,acceptedCache.current)}function getAcceptedValues(file,lineAnnotations,accepted){return{file:accepted?.file!=null&&areFileTargetsEqual(file,accepted.file.stale)?accepted.file.installed:file,lineAnnotations:accepted?.annotations!=null&&lineAnnotations===accepted.annotations.stale?accepted.annotations.installed:lineAnnotations}}function resolveAcceptedValues(file,lineAnnotations,acceptedCache){const{current:accepted}=acceptedCache,resolved=getAcceptedValues(file,lineAnnotations,accepted);return accepted==null||(accepted.file!=null&&!areFileTargetsEqual(file,accepted.file.stale)&&(accepted.file=null),lineAnnotations!==accepted.annotations?.stale&&(accepted.annotations=null),accepted.file==null&&accepted.annotations==null&&(acceptedCache.current=null)),resolved}function mergeFileOptions({options,controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete}){return{...options,controlledSelection,renderCustomHeader:hasCustomHeader?noopRender:options?.renderCustomHeader,renderGutterUtility:hasGutterRenderUtility?noopRender:options?.renderGutterUtility,onEditChange,onEditComplete}}function applyEdit(instance,getEditor){const editor=getEditor();try{return editor.edit(instance)}catch(error){throw editor.cleanUp(),error}}function File2({file,lineAnnotations,selectedLines,options,editorOptions,editStateKey,metrics,className,style,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,prerenderedHTML,renderGutterUtility,disableWorkerPool=!1,edit=!1,onEditChange,onEditComplete}){const{ref,getHoveredLine,getAnnotationSlotName,file:renderedFile,lineAnnotations:renderedAnnotations}=useFileInstance({file,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,prerenderedHTML,hasGutterRenderUtility:renderGutterUtility!=null,hasCustomHeader:renderCustomHeader!=null,disableWorkerPool,edit,onEditChange,onEditComplete}),children=renderFileChildren({file:renderedFile,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderGutterUtility,lineAnnotations:renderedAnnotations,getHoveredLine,getAnnotationSlotName});return jsxRuntimeExports.jsx(DIFFS_TAG_NAME,{ref,className,style,children:templateRender(children,prerenderedHTML)})}const WORD_CHAR=/[\p{L}\p{N}_$]/u;function wordAt(text,offset){if(offset<0||offset>=text.length||!WORD_CHAR.test(text[offset]))return null;let start=offset;for(;start>0&&WORD_CHAR.test(text[start-1]);)start--;let end=offset+1;for(;end<text.length&&WORD_CHAR.test(text[end]);)end++;return{start,end,text:text.slice(start,end)}}function lineRange(token,start,end){const row=token.closest("[data-line]");if(!row||end<=start)return null;const from=pointIn(row,start,!1),to=pointIn(row,end,!0);if(!from||!to)return null;const range=document.createRange();return range.setStart(from.node,from.offset),range.setEnd(to.node,to.offset),range}function pointIn(row,at,closing){for(const span of row.querySelectorAll("[data-char]")){let offset=at-Number(span.dataset.char);if(!(offset>=0))continue;const texts=document.createTreeWalker(span,NodeFilter.SHOW_TEXT);for(let node=texts.nextNode();node;node=texts.nextNode()){if(offset<node.data.length||closing&&offset===node.data.length)return{node,offset};offset-=node.data.length}}return null}function offsetAt(rect,chars,clientX){if(chars<=0||rect.width<=0)return 0;const raw=Math.floor((clientX-rect.left)/rect.width*chars);return Math.min(chars-1,Math.max(0,raw))}function offsetIn(element,clientX,clientY){const node=element.firstChild,chars=node?.textContent?.length??0,estimate=()=>offsetAt(element.getBoundingClientRect(),chars,clientX);if(!node||node.nodeType!==Node.TEXT_NODE||chars===0)return estimate();const doc=document;let hit=null;const root=element.getRootNode();if(typeof doc.caretPositionFromPoint=="function")hit=doc.caretPositionFromPoint(clientX,clientY,root instanceof ShadowRoot?{shadowRoots:[root]}:void 0);else if(typeof doc.caretRangeFromPoint=="function"){const range=doc.caretRangeFromPoint(clientX,clientY);range&&(hit={offsetNode:range.startContainer,offset:range.startOffset})}if(!hit||hit.offsetNode!==node)return estimate();let offset=Math.min(chars-1,Math.max(0,hit.offset));if(offset>0){const probe=document.createRange();probe.setStart(node,offset),probe.setEnd(node,offset),probe.getBoundingClientRect().left>clientX&&offset--}return offset}const createEditor=(type,options,key)=>new Editor(type,options,key);function FileViewInner({name,contents,wrap=!1,hideHeader=!1,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,edit,tabSize,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted,annotations,renderAnnotation,className,virtualize}){const{shikiTheme:theme,appearance}=useEditorEnvironment(),selectable=onSelectionEnd!==void 0,host=useDetachCleanup(),latest=useLatest({onSelectionEnd,onGutterAction,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted,renderAnnotation,edit,wrap}),highlightedOnce=reactExports.useRef(!1),words=reactExports.useMemo(()=>wordHover({enter:(t,e)=>latest().onTokenEnter?.(t,e),leave:()=>latest().onTokenLeave?.()}),[latest]),stable=reactExports.useMemo(()=>({onLineSelectionEnd:r=>latest().onSelectionEnd?.(r),onGutterUtilityClick:r=>latest().onGutterAction?.(r),onTokenEnter:(t,e)=>words.enter(t,e),onTokenLeave:()=>words.leave(),onTokenClick:(t,e)=>{const token=words.token(t,e.clientX,e.clientY);token&&latest().onTokenClick?.(token,e)},renderAnnotation:a=>latest().renderAnnotation?.(a)??null,onEditChange:e=>latest().edit?.onChange(e.file.contents,e.changes.map(c=>({range:c.range,text:c.text}))),onEditComplete:e=>latest().edit?.onComplete?.(e)??"reject",onPostRender:(node,instance,phase)=>{const highlighted=phase!=="unmount"&&isHighlighted(instance,node);revealOnHighlight(node,highlighted,phase,phase!=="unmount"&&colorsFile(instance));const current=latest();scrollReachOnRender(node,!current.wrap,phase),!(phase==="unmount"||highlightedOnce.current||!current.onHighlighted)&&highlighted&&(highlightedOnce.current=!0,current.onHighlighted())}}),[words,latest]),hasTokenHandlers=onTokenEnter!==void 0,hasTokenClick=onTokenClick!==void 0,hasGutter=onGutterAction!==void 0,options=reactExports.useMemo(()=>({theme,themeType:appearance,overflow:wrap?"wrap":"scroll",disableFileHeader:hideHeader,stickyHeader:!hideHeader,unsafeCSS:DIFFS_UNSAFE_CSS,preferredHighlighter:PREFERRED_HIGHLIGHTER,onPostRender:stable.onPostRender,...selectable?{enableLineSelection:!0,onLineSelectionEnd:stable.onLineSelectionEnd}:{},...hasGutter?{enableGutterUtility:!0,onGutterUtilityClick:stable.onGutterUtilityClick}:{},...hasTokenHandlers?{onTokenEnter:stable.onTokenEnter,onTokenLeave:stable.onTokenLeave}:{},...hasTokenClick?{onTokenClick:stable.onTokenClick}:{}}),[theme,appearance,wrap,hideHeader,selectable,hasGutter,hasTokenHandlers,hasTokenClick,stable]),file=reactExports.useMemo(()=>({name,contents,cacheKey:`${name}\0${contentHash(contents)}`}),[name,contents]),lineAnnotations=reactExports.useMemo(()=>annotations?[...annotations]:void 0,[annotations]),style=reactExports.useMemo(()=>tabSize?{...DIFFS_HOST_STYLE,tabSize}:DIFFS_HOST_STYLE,[tabSize]),view=jsxRuntimeExports.jsx(EditProvider,{createEditor,children:jsxRuntimeExports.jsx(File2,{file,className,style,...edit?{edit:!0,editorOptions:edit.options,editStateKey:edit.stateKey,onEditChange:stable.onEditChange,onEditComplete:stable.onEditComplete}:{},...selectable?{selectedLines:selectedLines??null}:{},...lineAnnotations?{lineAnnotations}:{},...renderAnnotation?{renderAnnotation:stable.renderAnnotation}:{},options})});return jsxRuntimeExports.jsx("div",{ref:host,className:"contents",onContextMenu,children:virtualize?jsxRuntimeExports.jsx(Virtualizer,{className:virtualize.className,contentClassName:"min-h-full",config:VIRTUALIZER_CONFIG,children:view}):view})}const LINK_HIGHLIGHT="zg-link";function setLinkHighlight(range){const registry=CSS.highlights;if(!registry)return;if(!range){registry.delete(LINK_HIGHLIGHT);return}const Highlight=globalThis.Highlight;Highlight&&registry.set(LINK_HIGHLIGHT,new Highlight(range))}function wordRange(element,word){const node=element.firstChild;if(!node||node.nodeType!==Node.TEXT_NODE)return null;const range=document.createRange();return range.setStart(node,word.start),range.setEnd(node,Math.min(word.end,node.textContent?.length??word.end)),range}function wordHover(handlers){let span=null,pointer=null,current=null,link=null,leaving=!1;const inLink=(t,offset)=>{const at=t.lineCharStart+offset;return link!==null&&link.line===t.lineNumber&&at>=link.start&&at<link.end},keyAt=(t,offset)=>{if(inLink(t,offset))return"link";const word=wordAt(t.tokenText,offset);return word?`${t.lineNumber}:${t.lineCharStart+word.start}`:null},draw=(t,word,columns)=>{const exact=columns?lineRange(t.tokenElement,columns.column-1,columns.endColumn-1):null,range=exact??wordRange(t.tokenElement,word);range&&(link=exact?{line:t.lineNumber,start:columns.column-1,end:columns.endColumn-1}:{line:t.lineNumber,start:t.lineCharStart+word.start,end:t.lineCharStart+word.end},setLinkHighlight(range),pointer&&inLink(pointer.token,pointer.offset)&&(current="link"))},erase=()=>{setLinkHighlight(null),link=null,current==="link"&&(current=null)},tokenAt=(t,offset)=>{const word=inLink(t,offset)?spanWord(t.tokenText,link.start-t.lineCharStart,link.end-t.lineCharStart):wordAt(t.tokenText,offset);return word?{lineNumber:t.lineNumber,lineCharStart:t.lineCharStart,text:t.tokenText,element:t.tokenElement,word,column:t.lineCharStart+offset+1,link:(on,columns)=>on?draw(t,word,columns):erase()}:null},resolve=(t,clientX,clientY)=>tokenAt(t,offsetIn(t.tokenElement,clientX,clientY)),onMove=e=>{if(!span)return;const offset=offsetIn(span.tokenElement,e.clientX,e.clientY);if(pointer={token:span,offset},keyAt(span,offset)===current)return;current&&handlers.leave(),current=keyAt(span,offset);const token=current?tokenAt(span,offset):null;token&&handlers.enter(token,e)},track=t=>{span?.tokenElement.removeEventListener("pointermove",onMove),span=t,t?.tokenElement.addEventListener("pointermove",onMove)},leave=()=>{leaving=!1,pointer=null,current&&handlers.leave(),current=null};return{enter(t,e){track(t),leaving&&!inLink(t,offsetIn(t.tokenElement,e.clientX,e.clientY))&&leave(),leaving=!1,onMove(e)},leave(){if(track(null),current!=="link")return leave();leaving=!0,queueMicrotask(()=>leaving&&leave())},token:resolve}}function spanWord(text,start,end){const from=Math.max(0,start),to=Math.min(text.length,end);return from<to?{start:from,end:to,text:text.slice(from,to)}:null}function isHighlighted(instance,node){const cache=instance?.fileRenderer?.renderCache;return cache&&typeof cache.highlighted=="boolean"?cache.highlighted:node.shadowRoot?.querySelector("[data-line] span[class], [data-line] span[style]")!==null}function colorsFile(instance){const renderer=instance?.fileRenderer,file=renderer?.renderCache?.file;if(!file?.contents||(file.lang??getFiletypeFromFileName(file.name))==="text")return!1;const max=renderer?.getTokenizeMaxLength?.()??DEFAULT_TOKENIZE_MAX_LENGTH;return file.contents.length<=max||file.contents.split(`
68
68
  `).length<=max}const FileView=reactExports.memo(FileViewInner);function contentHash(text){let h2=2166136261;for(let i=0;i<text.length;i++)h2^=text.charCodeAt(i),h2=Math.imul(h2,16777619);return(h2>>>0).toString(36)+text.length.toString(36)}const ARM_ON_IDLE_LINES=3e3,FOCUS_RETRY_FRAMES=60,SCROLLER="zg-code-scroller flex-1 min-h-0 overflow-auto outline-none",BAR_BUTTON=buttonClass({variant:"secondary",size:"xs"});function CodeEditorInner({path,doc,sessionKey,readOnly=!1,visible=!0,findAsk=0,markers,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,onTokenEnter,onTokenLeave,onTokenClick,annotations,renderAnnotation,scrollerClassName=SCROLLER,hostAttributes,children,className,style},ref){const{settings:ed,reducedMotion}=useEditorEnvironment(),labels=useLabels(),editable=!readOnly&&ed.editing,[armed,setArmed]=reactExports.useState(doc.dirty),editing=editable&&armed,hostRef=reactExports.useRef(null),editorRef=reactExports.useRef(null),pendingCaret=reactExports.useRef(null),caretAskedFrom=reactExports.useRef(null);reactExports.useImperativeHandle(ref,()=>({host:()=>hostRef.current,editor:()=>editorRef.current,placeCaret:caret=>{const editor=editorRef.current;if(editor){try{editor.focus({...caret,preventScroll:!0})}catch{}return}editable&&(pendingCaret.current=caret,caretAskedFrom.current=document.activeElement,setArmed(!0))}}),[editable]);const armEditor=e=>{if(!editable||armed||e.button!==0)return;const route=e.nativeEvent.composedPath(),lineEl=route.find(n=>n instanceof HTMLElement&&n.hasAttribute("data-line"));if(!lineEl||route.some(n=>n instanceof HTMLElement&&(n.hasAttribute("data-column-number")||n.hasAttribute("data-line-annotation"))))return;const lineNumber=Number.parseInt(lineEl.getAttribute("data-line")??"",10),character=caretCharacterAt(lineEl,e.clientX);pendingCaret.current=Number.isFinite(lineNumber)?{lineNumber,character}:null,caretAskedFrom.current=null,setArmed(!0)},[highlighted,setHighlighted]=reactExports.useState(!1),onHighlighted=reactExports.useCallback(()=>setHighlighted(!0),[]),large=reactExports.useMemo(()=>countLines(doc.base.contents)>ARM_ON_IDLE_LINES,[doc.base.contents]);reactExports.useEffect(()=>{if(!editable||armed||!highlighted||!visible||large)return;if(window.requestIdleCallback){const id2=window.requestIdleCallback(()=>setArmed(!0),{timeout:2e3});return()=>window.cancelIdleCallback(id2)}const id=window.setTimeout(setArmed,300,!0);return()=>window.clearTimeout(id)},[editable,armed,highlighted,visible,large]);const[editorTick,setEditorTick]=reactExports.useState(0);reactExports.useEffect(()=>{const editor=editorRef.current;if(!(!editor||!markers))try{editor.setMarkers([...markers])}catch{}},[markers,editorTick]);const saveRef=reactExports.useRef(doc.save);reactExports.useLayoutEffect(()=>{saveRef.current=doc.save});const editorOptions=reactExports.useMemo(()=>({roundedSelection:ed.roundedSelection,matchBrackets:ed.matchBrackets,autoSurround:ed.autoSurround,clipboard:{readText:()=>navigator.clipboard.readText()},onAttach:editor=>{editorRef.current=editor,setEditorTick(t=>t+1);const caret=pendingCaret.current,askedFrom=caretAskedFrom.current;pendingCaret.current=null,caretAskedFrom.current=null;const scrollerFocused=!caret&&!!hostRef.current&&document.activeElement!==null&&hostRef.current.contains(document.activeElement);(caret||scrollerFocused)&&requestAnimationFrame(()=>{const active=document.activeElement;if(!(askedFrom&&active!==askedFrom&&!hostRef.current?.contains(active)))try{editor.focus(caret?{...caret,preventScroll:!0}:void 0)}catch{}})},...ed.saveOn==="blur"?{onBlur:()=>{saveRef.current()}}:{}}),[ed.roundedSelection,ed.matchBrackets,ed.autoSurround,ed.saveOn]);reactExports.useEffect(()=>{hostRef.current?.querySelector(".zg-code-scroller")?.setAttribute("tabindex","-1")},[sessionKey]);const wasVisible=reactExports.useRef(visible);reactExports.useEffect(()=>{const became=visible&&!wasVisible.current;if(wasVisible.current=visible,!became)return;let id=0,tries=0;const tick=()=>{const host=hostRef.current;if(!host)return;const editor=editorRef.current;if(editor)try{editor.focus({preventScroll:!0})}catch{}host.contains(document.activeElement)||host.querySelector(".zg-code-scroller")?.focus({preventScroll:!0}),!(host.contains(document.activeElement)&&(!editor||host.querySelector("diffs-container")?.shadowRoot?.activeElement!=null))&&tries++<FOCUS_RETRY_FRAMES&&(id=requestAnimationFrame(tick))};return id=requestAnimationFrame(tick),()=>cancelAnimationFrame(id)},[visible]);const contents=doc.contents,find=useFind({parts:()=>[{part:"",lines:fileLines(contents)}],version:contents,surfaces:()=>{const root=hostRef.current?.querySelector("diffs-container")?.shadowRoot;return root?[{part:"",root}]:[]},scroller:()=>hostRef.current?.querySelector(".zg-code-scroller")??null,fallback:(m,scroller)=>estimateLineTop(scroller,m.line),smooth:!reducedMotion}),seenAsk=reactExports.useRef(findAsk);reactExports.useEffect(()=>{if(findAsk===seenAsk.current||(seenAsk.current=findAsk,!visible))return;const editor=editorRef.current,root=hostRef.current?.querySelector("diffs-container")?.shadowRoot;if(editing&&editor&&root){try{editor.focus({preventScroll:!0})}catch{}const target=root.activeElement;if(target){const mac=navigator.platform.toLowerCase().includes("mac");target.dispatchEvent(new globalThis.KeyboardEvent("keydown",{key:"f",code:"KeyF",metaKey:mac,ctrlKey:!mac,bubbles:!0,composed:!0,cancelable:!0}));return}}find.show()},[findAsk]);const onKeyDown=e=>{if(!e.target.closest('[role="search"]')){if(editable&&!armed&&isEditKey(e)){setArmed(!0);return}editing&&(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="s"&&(e.preventDefault(),doc.save())}};return jsxRuntimeExports.jsxs("div",{ref:hostRef,"data-zg-keyscope":"editor",...hostAttributes,className:["flex-1 min-h-0 flex flex-col",className].filter(Boolean).join(" "),style,onKeyDown,onPointerDownCapture:armEditor,children:[doc.conflict&&jsxRuntimeExports.jsxs("div",{role:"status",className:"shrink-0 flex items-center gap-2 px-3 min-h-8 py-1 text-zg-meta bg-zg-warn-soft text-[var(--zg-text)]",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-warning text-zg-label text-zg-warn shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"flex-1 min-w-0 leading-4",title:labels.editorConflictDetail,children:labels.editorConflict}),jsxRuntimeExports.jsx("button",{type:"button",onClick:doc.discard,className:BAR_BUTTON,children:labels.editorReload}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>{doc.save(!0)},className:`${BAR_BUTTON} text-zg-danger`,children:labels.editorOverwrite})]}),jsxRuntimeExports.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[jsxRuntimeExports.jsx(FindBar,{find,label:labels.findInFile}),jsxRuntimeExports.jsx(FileView,{name:path,contents:doc.seed,hideHeader:!0,wrap:ed.wordWrap,tabSize:ed.tabSize,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,onTokenEnter,onTokenLeave,onTokenClick,onHighlighted:armed?void 0:onHighlighted,annotations,renderAnnotation,virtualize:{className:scrollerClassName},edit:editing?{options:editorOptions,stateKey:sessionKey,onChange:doc.onEditorChange}:void 0},sessionKey)]}),children]})}const CodeEditor=reactExports.memo(reactExports.forwardRef(CodeEditorInner));function countLines(text){let n=1;for(let i=text.indexOf(`
69
69
  `);i!==-1;i=text.indexOf(`
70
70
  `,i+1))n++;return n}function isEditKey(e){return e.metaKey||e.ctrlKey||e.altKey?!1:e.key.length===1||e.key==="Enter"||e.key==="Backspace"||e.key==="Delete"}function caretCharacterAt(lineEl,clientX){const text=lineEl.textContent??"",walker=document.createTreeWalker(lineEl,NodeFilter.SHOW_TEXT);let offset=0;const range=document.createRange();for(let node=walker.nextNode();node;node=walker.nextNode()){const len=node.textContent?.length??0;range.selectNodeContents(node);const rect=range.getBoundingClientRect();if(clientX<rect.left)return offset;if(clientX<=rect.right&&len>0){const perChar=rect.width/len;return offset+Math.min(len,Math.round((clientX-rect.left)/perChar))}offset+=len}return text.length}function estimateLineTop(scroller,line){const probe=scroller.querySelector("diffs-container")?.shadowRoot?.querySelector("[data-line]:not([data-column-number])");if(!probe)return;const probeLine=Number(probe.getAttribute("data-line")),rect=probe.getBoundingClientRect();return!Number.isFinite(probeLine)||rect.height<=0?void 0:{top:rect.top-scroller.getBoundingClientRect().top+scroller.scrollTop+(line-probeLine)*rect.height}}const CodeEditor$1=Object.freeze(Object.defineProperty({__proto__:null,CodeEditor},Symbol.toStringTag,{value:"Module"}));export{CodeEditor as C,EditStateManager as E,CodeEditor$1 as a};