collabmd 0.1.46 → 0.1.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/client/assets/{CodeMirrorEditor-UCMRAMCV-CYM5nxUi.js → CodeMirrorEditor-UCMRAMCV-BPH4FJkv.js} +1 -1
- package/dist/client/assets/JetBrainsMono-Regular-BQaDgvhP.woff2 +0 -0
- package/dist/client/assets/{abnfDiagram-N423BO3Z-CUMTFJhI.js → abnfDiagram-VCTEODGH-BNDLzJ7L.js} +1 -1
- package/dist/client/assets/architecture-7GRP2DOG-BMOPAkUC.js +1 -0
- package/dist/client/assets/{architectureDiagram-T3A2C74G-w25m71oV.js → architectureDiagram-5GKGNRK7-I39sYjHI.js} +1 -1
- package/dist/client/assets/babel-CY5KOv-I.js +16 -0
- package/dist/client/assets/base-BYODPHdS.js +1 -0
- package/dist/client/assets/blockDiagram-NRAW4CY4-C6DtJy5Y.js +129 -0
- package/dist/client/assets/browser-BKLM0ThC-IxjwuOIz-BBqQnUEb.js +1 -0
- package/dist/client/assets/c4Diagram-UCG6FXSJ-CtWtxS9_.js +38 -0
- package/dist/client/assets/channel-CaoKA_We.js +1 -0
- package/dist/client/assets/{chunk-U6XO7XAA-BFxjP5U3.js → chunk-2ZTRR5NV-C2qZJila.js} +1 -1
- package/dist/client/assets/{chunk-YOTPTUD7-D0vRKqYp.js → chunk-3Z5EZCMW-DMniOlPd.js} +1 -1
- package/dist/client/assets/{chunk-BIQX33UG-DZEsGuSn.js → chunk-5V3GS4D5-i-ZDOEnP.js} +1 -1
- package/dist/client/assets/{chunk-MOZMSUNE-XVucA-n6.js → chunk-6AZGARVD-BB6FqMl-.js} +1 -1
- package/dist/client/assets/{chunk-5JV3BV7I-Cy5pj3QY.js → chunk-6EIED4P4-DdUJkP0f.js} +1 -1
- package/dist/client/assets/{chunk-R7FJI6CG-Cnn3gE-Y.js → chunk-6K3QC6MW-CqVsVn-y.js} +1 -1
- package/dist/client/assets/{chunk-OSBZ3O6U-CrKZOUOr.js → chunk-6TQVIW2G-DKlLbNIP.js} +1 -1
- package/dist/client/assets/{chunk-JG7HCLWE-BYfiSaVt.js → chunk-747NJXEK-BFkZPlab.js} +1 -1
- package/dist/client/assets/{chunk-NSK5VX7P-TLH37VXI.js → chunk-75Z2AOVW-CdFSaPjz.js} +1 -1
- package/dist/client/assets/chunk-CKBBP62Z-DG26UiBv.js +2 -0
- package/dist/client/assets/{chunk-3NCLNEKW-Y2Jf_LI-.js → chunk-CLGD4ZFX-DQLgbQrv.js} +1 -1
- package/dist/client/assets/chunk-DSNCTWBM-8xkug7fQ.js +2 -0
- package/dist/client/assets/chunk-DU6HZSFF-COXDzJK1.js +127 -0
- package/dist/client/assets/{chunk-2GRJ4B5K-DhnlUv3F.js → chunk-F27PBJKO-CNHIFhjo.js} +1 -1
- package/dist/client/assets/{chunk-YGJVY4SA-CjSe7Bx7.js → chunk-FLYJHZSQ-Be7lKF17.js} +1 -1
- package/dist/client/assets/{chunk-KEIR6QF5-BICK3FdT.js → chunk-FOHPRMQF-DHwB1DNv.js} +2 -2
- package/dist/client/assets/{chunk-5RXB4S5H-BWrwFqMI.js → chunk-G27WJ6UU-D9-eg537.js} +2 -2
- package/dist/client/assets/chunk-GMAD6QVW-CbcBqPM5.js +72 -0
- package/dist/client/assets/{chunk-QBLGF6JB-CxAyS2mW.js → chunk-I5DQTOEV-Hm2LfiYI.js} +1 -1
- package/dist/client/assets/{chunk-5FCAYU7R-Dh5nylU8.js → chunk-ICYGCRZG-749o-pGJ.js} +1 -1
- package/dist/client/assets/{chunk-CQNSW5MT-B8S09OIh.js → chunk-IH6LHLGP-CC6I9F3i.js} +1 -1
- package/dist/client/assets/chunk-JQ64N6SF-DSFNH4bh.js +1 -0
- package/dist/client/assets/{chunk-CYSBUYHQ-C1Rf4art.js → chunk-KI3K4JFJ-Rma-0k_M.js} +1 -1
- package/dist/client/assets/{chunk-GF5L2VYU-DkJpO7ff.js → chunk-LCL6LL3I-DmDkVukh.js} +1 -1
- package/dist/client/assets/chunk-LNGE3PJU-DWpGwHrW.js +34 -0
- package/dist/client/assets/chunk-OBVCFTLP-BJR7u1jh.js +1 -0
- package/dist/client/assets/{chunk-5TONJI2A-DQOY3q1H.js → chunk-OUJLGHUK-D0j2JRSg.js} +1 -1
- package/dist/client/assets/chunk-P2QGCYS3-BRpqY32H.js +1 -0
- package/dist/client/assets/{chunk-KBJHAD2P-CB_3zWUf.js → chunk-POPQ4Y6H-Cb4SlVZF.js} +1 -1
- package/dist/client/assets/{chunk-4I5QYGJK-CCB2YcIH.js → chunk-PWAF6VOD-Cz8IwBB5.js} +1 -1
- package/dist/client/assets/chunk-R7TYR2AO-CTd0Yj98.js +10 -0
- package/dist/client/assets/chunk-RHFEMEQ7-CWY8cf4H.js +168 -0
- package/dist/client/assets/chunk-RM4UPSZO-CWRwxNWJ.js +41 -0
- package/dist/client/assets/{chunk-6Q2QTUOP-CPlWzBtc.js → chunk-SVP7TREG-CyHOmcac.js} +1 -1
- package/dist/client/assets/chunk-TEH6E4GO-DVayPj-q.js +62 -0
- package/dist/client/assets/{chunk-EMLP6XTP-RLD4nXpI.js → chunk-UY3FDG6J-CnmaAkG5.js} +1 -1
- package/dist/client/assets/{chunk-5HE753X5-Bw-yg4kO.js → chunk-XHIXRSVI-BFQ6B8BE.js} +1 -1
- package/dist/client/assets/classDiagram-DTDB5LWJ-7fEmn0zV.js +1 -0
- package/dist/client/assets/classDiagram-v2-JRS7N3AN-7fEmn0zV.js +1 -0
- package/dist/client/assets/comment-ui-shared-DuoyznXW.js +7 -0
- package/dist/client/assets/cynefin-OW5HDTMX-7tP7QfM3.js +1 -0
- package/dist/client/assets/{cynefinDiagram-MW4NZA55-CJxXfJek.js → cynefinDiagram-5FMLGOSQ-CdTPi2yO.js} +1 -1
- package/dist/client/assets/dagre-3AP2YEHR-5gtJtd0O.js +4 -0
- package/dist/client/assets/dagre-PrKaheQc.js +1 -0
- package/dist/client/assets/{diagram-7IWD3JNH-B2d2Bm15.js → diagram-S7CK7UJ4-BudWz9WU.js} +4 -4
- package/dist/client/assets/{diagram-UB23O5K3-DJcKCwv9.js → diagram-UQ7AKVKN-3v4rbH-s.js} +1 -1
- package/dist/client/assets/{diagram-B4RE2ZJO-NP4UAwjR.js → diagram-VSXAHHWV-CQRVEZR7.js} +1 -1
- package/dist/client/assets/{diagram-Q27KOJAE-DylDuwor.js → diagram-VX7I27RA-C_-rj0sw.js} +1 -1
- package/dist/client/assets/{diagram-LBJQPF4R-D1FJQV8t.js → diagram-Z3DM3KII-B4yxavgj.js} +1 -1
- package/dist/client/assets/direct-engine-DdrQKpgq-CtKfQzCt.js +5 -0
- package/dist/client/assets/dist-73RPdcyU.js +1 -0
- package/dist/client/assets/{dist-Bm6pf9Bl.js → dist-BJ1bJs33.js} +1 -1
- package/dist/client/assets/{dist-BalScOwZ.js → dist-BK9QvQrc.js} +1 -1
- package/dist/client/assets/{dist-DLMiIsNC.js → dist-BPHLJ09L.js} +1 -1
- package/dist/client/assets/{dist-Bf8f4HmM.js → dist-B_yQaEv_.js} +1 -1
- package/dist/client/assets/{dist-CC5IrQMG.js → dist-BeajGMhO.js} +1 -1
- package/dist/client/assets/{dist-PDZ3bSqm.js → dist-Bw3VIE_v.js} +1 -1
- package/dist/client/assets/{dist-xElaxbia.js → dist-ByrG2qBA.js} +1 -1
- package/dist/client/assets/{dist-ule2n6ak.js → dist-C5NgpdG5.js} +1 -1
- package/dist/client/assets/dist-CH-sQu3r.js +1 -0
- package/dist/client/assets/dist-CKS_-are.js +1 -0
- package/dist/client/assets/{dist-D-Z6FLem.js → dist-CdmKGRGr.js} +1 -1
- package/dist/client/assets/dist-ChRoo3IB.js +9 -0
- package/dist/client/assets/{dist-dtAdgL39.js → dist-CietwTVS.js} +1 -1
- package/dist/client/assets/{dist-jv4WdPnK.js → dist-D37Hyu3h.js} +1 -1
- package/dist/client/assets/dist-D3fehAZ2.js +2 -0
- package/dist/client/assets/{dist-BEwK4csK.js → dist-D5wCC32z.js} +1 -1
- package/dist/client/assets/{dist-shrl6K_0.js → dist-DDUn5zTz.js} +1 -1
- package/dist/client/assets/{dist-CZgOmxK6.js → dist-DGEbEfw4.js} +1 -1
- package/dist/client/assets/{dist-B5HTH2BO.js → dist-DVy5woUy.js} +1 -1
- package/dist/client/assets/{dist-DZKu9Cs8.js → dist-DZAAWTG-.js} +1 -1
- package/dist/client/assets/{dist-TjMh8n1u.js → dist-Dir5dDKZ.js} +1 -1
- package/dist/client/assets/dist-Dl_tpDSr.js +1 -0
- package/dist/client/assets/{dist-FWJsgGYI.js → dist-DuH3ZrHo.js} +1 -1
- package/dist/client/assets/{dist-BjHJDtyU.js → dist-DutPuFmC.js} +1 -1
- package/dist/client/assets/{dist-Cqhv5LAk.js → dist-LQ4kDCKz.js} +1 -1
- package/dist/client/assets/{dist-CCP_AKPG.js → dist-RKBTaQMb.js} +1 -1
- package/dist/client/assets/{dist-BoVBdSjk.js → dist-Tw-Fxpeb.js} +1 -1
- package/dist/client/assets/dist-eBx8q6Sy.js +1 -0
- package/dist/client/assets/{dist-rGBmqxC7.js → dist-mj2Ht75J.js} +1 -1
- package/dist/client/assets/{dist-BDt3rz7l.js → dist-netZOQtD.js} +1 -1
- package/dist/client/assets/document-formatter-Dxl_a8XO.js +2 -0
- package/dist/client/assets/{drawio-editor-FzY1cVw8.js → drawio-editor-BVaNNtYp.js} +2 -2
- package/dist/client/assets/{drawioEditor-BjiKJqlc.js → drawioEditor-BkIBlXx0.js} +2 -2
- package/dist/client/assets/{ebnfDiagram-BXEA7PRR-nw0wmA6y.js → ebnfDiagram-PWID7BFC-OXa8VEp1.js} +1 -1
- package/dist/client/assets/editor-session-DMyVdHLj.js +54 -0
- package/dist/client/assets/embedded-editor-base-B3l6Xy65.css +1 -0
- package/dist/client/assets/embedpdf-BmE13ZZ0.js +1 -0
- package/dist/client/assets/embedpdf-DA4bA119-BPqZxwjc.js +2363 -0
- package/dist/client/assets/{en-7NFCYGKX-BrgYZAEe.js → en-SJ2YIMFF-CJBL3nkq.js} +1 -1
- package/dist/client/assets/erDiagram-SSCWMZ5O-C-iy6VkX.js +99 -0
- package/dist/client/assets/estree-CuT_pB8K.js +44 -0
- package/dist/client/assets/eventmodeling-NTZA5JFV-BR2FzK4R.js +1 -0
- package/dist/client/assets/excalidraw-editor-BbSbI80a.css +1 -0
- package/dist/client/assets/excalidraw-editor-BjYaNEMY.js +9 -0
- package/dist/client/assets/excalidrawEditor-ChqF_d82.js +2 -0
- package/dist/client/assets/export-page-Dyu0XCbu.js +57 -0
- package/dist/client/assets/exportDocument-CJBx4Xjx.css +1 -0
- package/dist/client/assets/exportDocument-Dgvfa2Sd.js +2 -0
- package/dist/client/assets/{file-icon-svg-CQAjlWjK.js → file-icon-svg-Y_kpF957.js} +1 -1
- package/dist/client/assets/file-kind-BwMIcZbi.js +1 -0
- package/dist/client/assets/file-search-DDLyyLDU.js +1 -0
- package/dist/client/assets/flowDiagram-A5DVABFB-CiW1eN8C.js +1 -0
- package/dist/client/assets/{ganttDiagram-PKOTCBZU-BnM97BCT.js → ganttDiagram-EL5Y4UJY-DtKHAbez.js} +1 -1
- package/dist/client/assets/gitGraph-4MIJSDKK-DYlXv_yJ.js +1 -0
- package/dist/client/assets/{gitGraphDiagram-DS77QQ5N-BQpQhjuN.js → gitGraphDiagram-WWUBYQGX-oue8fQ5o.js} +1 -1
- package/dist/client/assets/github-dark.min-BV82VuKq.css +1 -0
- package/dist/client/assets/github.min-v3dd8CNH.css +1 -0
- package/dist/client/assets/html-Cdnr2qzU.js +25 -0
- package/dist/client/assets/image-ZVKINSPA-0zXSnE7M.js +1 -0
- package/dist/client/assets/index-CSNIMyOP.css +1 -0
- package/dist/client/assets/index-DG3N2Ps-.js +2 -0
- package/dist/client/assets/info-A6RAGUB7-BlU-8_xu.js +1 -0
- package/dist/client/assets/{infoDiagram-6WML65LV-DYB8HCDQ.js → infoDiagram-RXCK75RN-BMzo6KIn.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-WSZJBQD7-Coz_P3t6.js → ishikawaDiagram-5VMMS53U-BIM3h287.js} +1 -1
- package/dist/client/assets/{journeyDiagram-NVQOT4AX-B6edChce.js → journeyDiagram-EYS64GPL-mF6Lh8O-.js} +1 -1
- package/dist/client/assets/{kanban-definition-27J2QSJJ-BFd9-cLc.js → kanban-definition-3QL26DDD-DLN2NyoR.js} +2 -2
- package/dist/client/assets/{line-B_S_S8kV.js → line-BfTWJmgf.js} +1 -1
- package/dist/client/assets/main-D0wCxpVn.js +903 -0
- package/dist/client/assets/markdown-CByV-4CU.js +70 -0
- package/dist/client/assets/{mermaid-parser.core-CUVdebAV.js → mermaid-parser.core-Bl0efOMt.js} +2 -2
- package/dist/client/assets/mermaid.core-BJRLUQZE.js +11 -0
- package/dist/client/assets/{mindmap-definition-FAOFIHXS-C9PQ38Al.js → mindmap-definition-FBJOCRG2-CRyHaHTk.js} +1 -1
- package/dist/client/assets/packet-AYTQ26CC-BSJEH9Lb.js +1 -0
- package/dist/client/assets/pdfium-RAgkpwfK.wasm +0 -0
- package/dist/client/assets/{pegDiagram-VL7TDLO6-BMZUrSaU.js → pegDiagram-XKGWAZYB-B31fKPR2.js} +1 -1
- package/dist/client/assets/pie-WAS4IAKB-qxv01Y8W.js +1 -0
- package/dist/client/assets/{pieDiagram-7S7Q4E2Y-h8kbCL9o.js → pieDiagram-E7YTZNPT-B5OZPb88.js} +1 -1
- package/dist/client/assets/preview-render-compiler-CrJIooVD.js +35 -0
- package/dist/client/assets/preview-render-compiler-O0JxBVNF.js +1 -0
- package/dist/client/assets/{preview-render-profile-CE-5rVTC.js → preview-render-profile-B4RWYWHt.js} +1 -1
- package/dist/client/assets/preview-render-worker-_QTxqKvP.js +60 -0
- package/dist/client/assets/prod-BiYPMR1i.js +177 -0
- package/dist/client/assets/prod-VxdGZ5Ly.js +1 -0
- package/dist/client/assets/{quadrantDiagram-CIZ2JOQS-CkElyfMi.js → quadrantDiagram-AXDQQJYC-Drrw14YH.js} +1 -1
- package/dist/client/assets/quick-switcher-controller-CaEjEtq_.js +1 -0
- package/dist/client/assets/radar-RG4KPBEZ-B6h6pWOs.js +1 -0
- package/dist/client/assets/railroad-74A4TZTK-CGtTWdGc.js +1 -0
- package/dist/client/assets/railroad-abnf-HS5TGJTU-Cq7y22IA.js +1 -0
- package/dist/client/assets/railroad-ebnf-LZEXJU2U-V0aQVv9m.js +1 -0
- package/dist/client/assets/railroad-peg-WCYAUIDC-BQiIsX_p.js +1 -0
- package/dist/client/assets/{railroadDiagram-AXF67PYL-c75gnikD.js → railroadDiagram-O6MQD6OU-BPifP0MB.js} +1 -1
- package/dist/client/assets/{requirementDiagram-LRYGKXZP-mNxKLuHS.js → requirementDiagram-EFPCY7ZU-CRZG6mRB.js} +2 -2
- package/dist/client/assets/{sankeyDiagram-W5VNT64P-0OhplksI.js → sankeyDiagram-P5KCCOFB-DvarEJpo.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-SI44F4Z6-BJ_yAocC.js → sequenceDiagram-WJ2MYXX4-B4oWlb-w.js} +1 -1
- package/dist/client/assets/standalone-6z5x8CWe.js +29 -0
- package/dist/client/assets/{stateDiagram-OKZ733FA-Cc83O86s.js → stateDiagram-HBIQ2CUA-qbHIIqRZ.js} +1 -1
- package/dist/client/assets/stateDiagram-v2-4QOOHH4V-B--gjrit.js +1 -0
- package/dist/client/assets/swimlanes-XN3QIQJK-xB6CtUGj.js +1 -0
- package/dist/client/assets/swimlanesDiagram-VK2B7HYN-DO8XNXEg.js +8 -0
- package/dist/client/assets/{timeline-definition-Z64GVDOM-BWDAGTHz.js → timeline-definition-24CTP7MA-Lj_yTNlY.js} +1 -1
- package/dist/client/assets/treeView-Q6P3EWNA-BTTYcvrF.js +1 -0
- package/dist/client/assets/treemap-WGGIJYW6-Cg7tyfH8.js +1 -0
- package/dist/client/assets/{vault-api-client-_LpV1aIn.js → vault-api-client-BkwdFjx0.js} +2 -2
- package/dist/client/assets/vault-utils-DvoSftJT.js +22 -0
- package/dist/client/assets/{vennDiagram-T6HMQDX7-LOSsnlMB.js → vennDiagram-4TSXK5OY-BekRp5Y0.js} +1 -1
- package/dist/client/assets/wardley-WFR3VGLG-C6N1rULY.js +1 -0
- package/dist/client/assets/{wardleyDiagram-T6FBY63Y-BxII3foY.js → wardleyDiagram-VM6X3IG4-kdnV_Hdm.js} +1 -1
- package/dist/client/assets/worker-engine-m0rlHn8R-S8mpn_O0.js +17369 -0
- package/dist/client/assets/{xychartDiagram-ELKLHX3M-B-pTEjju.js → xychartDiagram-S5SC5T6Z-DufGwNSB.js} +3 -3
- package/dist/client/assets/yaml-9ltHPDNO.js +154 -0
- package/dist/client/drawio-editor.html +1 -1
- package/dist/client/excalidraw-editor.html +1 -1
- package/dist/client/export-document.html +3 -3
- package/dist/client/index.html +56 -24
- package/package.json +22 -18
- package/src/client/app/index.html +53 -21
- package/src/client/application/app-shell/comments-feature.js +2 -3
- package/src/client/application/app-shell/export-feature.js +17 -1
- package/src/client/application/app-shell/git-feature.js +30 -11
- package/src/client/application/app-shell/presence-feature.js +2 -2
- package/src/client/application/app-shell/ui-feature-identity.js +13 -0
- package/src/client/application/app-shell/ui-feature-shell.js +228 -9
- package/src/client/application/app-shell-elements.js +5 -0
- package/src/client/application/pdf-preview-controller.js +53 -970
- package/src/client/application/preview-render-compiler.js +3 -0
- package/src/client/application/quick-switcher-loader.js +1 -1
- package/src/client/application/workspace-coordinator.js +21 -4
- package/src/client/application/workspace-preview-controller.js +120 -5
- package/src/client/application/workspace-route-controller.js +4 -1
- package/src/client/assets/vendor/highlight/github-dark.min.css +2 -10
- package/src/client/assets/vendor/highlight/github.min.css +2 -10
- package/src/client/assets/vendor/jetbrains-mono/JetBrainsMono-Regular.woff2 +0 -0
- package/src/client/assets/vendor/jetbrains-mono/OFL.txt +93 -0
- package/src/client/bootstrap/collabmd-app-shell.js +31 -8
- package/src/client/domain/document-formatter.js +193 -0
- package/src/client/domain/file-search.js +73 -0
- package/src/client/domain/git-labels.js +5 -0
- package/src/client/domain/vault-paths.js +6 -4
- package/src/client/domain/wiki-link-completions.js +20 -20
- package/src/client/drawio-editor.js +8 -3
- package/src/client/excalidraw-editor.js +163 -6
- package/src/client/export/export-host.js +57 -36
- package/src/client/export/export-page.js +20 -6
- package/src/client/export/export-pipeline.js +322 -22
- package/src/client/infrastructure/editor-session.js +4 -0
- package/src/client/infrastructure/editor-view-adapter.js +60 -14
- package/src/client/presentation/bases-preview-controller.js +35 -11
- package/src/client/presentation/comment-ui/comment-ui-render.js +4 -0
- package/src/client/presentation/comment-ui-controller.js +2 -0
- package/src/client/presentation/excalidraw-embed-controller.js +7 -0
- package/src/client/presentation/file-action-controller.js +15 -2
- package/src/client/presentation/file-explorer-controller.js +3 -5
- package/src/client/presentation/file-explorer-view.js +43 -45
- package/src/client/presentation/file-history-view-controller.js +6 -1
- package/src/client/presentation/file-tree-state.js +5 -14
- package/src/client/presentation/git-diff-view-controller.js +36 -11
- package/src/client/presentation/git-panel-controller.js +12 -8
- package/src/client/presentation/quick-switcher-controller.js +92 -153
- package/src/client/styles/components/scrollbars.css +10 -0
- package/src/client/styles/export-document.css +44 -29
- package/src/client/styles/features/collaboration-presence.css +13 -1
- package/src/client/styles/features/preview-markdown.css +79 -0
- package/src/client/styles/features/quick-switcher.css +8 -0
- package/src/client/styles/foundation/themes.css +1 -0
- package/src/client/styles/foundation/tokens.css +8 -0
- package/src/client/styles/layout/shell.css +73 -339
- package/src/client/styles/layout/sidebar.css +42 -4
- package/src/client/styles/layout/view-modes.css +2 -0
- package/src/client/styles/overrides/codemirror.css +31 -19
- package/src/client/styles/overrides/highlightjs.css +20 -4
- package/src/client/styles/surfaces/excalidraw-editor.css +42 -0
- package/src/domain/file-kind.js +12 -1
- package/src/server/domain/ripgrep-search-service.js +110 -37
- package/src/server/infrastructure/git/git-service.js +23 -11
- package/src/server/infrastructure/http/create-git-api-command-handler.js +3 -1
- package/src/server/infrastructure/http/create-structurizr-api-handler.js +4 -2
- package/src/server/infrastructure/persistence/path-utils.js +10 -4
- package/src/server/infrastructure/persistence/vault-file-store.js +2 -0
- package/src/server/infrastructure/structurizr/structurizr-workspace-service.js +33 -7
- package/dist/client/assets/architecture-TIHT7OUA-CsHfPErM.js +0 -1
- package/dist/client/assets/base-CxPEiHuy.js +0 -1
- package/dist/client/assets/blockDiagram-VBNYF7ZC-CipJt9Jl.js +0 -132
- package/dist/client/assets/c4Diagram-5PPSVZJV-B5ktVx6g.js +0 -10
- package/dist/client/assets/channel-4Jkmq93I.js +0 -1
- package/dist/client/assets/chunk-7BUUIJ7U-Bb538aSH.js +0 -1
- package/dist/client/assets/chunk-7Z6QIM7H-BP9Pdsm9.js +0 -10
- package/dist/client/assets/chunk-ERSWUTIN-hHdvnhaY.js +0 -41
- package/dist/client/assets/chunk-I66GZJ75-CVFiiffQ.js +0 -127
- package/dist/client/assets/chunk-J7OUQ5F2-4CEb7pvH.js +0 -2
- package/dist/client/assets/chunk-JQJVKLGR-cx8X_24v.js +0 -156
- package/dist/client/assets/chunk-QR6OTTB3-CDAA_5Ib.js +0 -62
- package/dist/client/assets/chunk-RYQCIY6F-D-a0zH8K.js +0 -1
- package/dist/client/assets/chunk-UBXNYLIW-Bhk-PbFK.js +0 -1
- package/dist/client/assets/chunk-W5SLKNZC-BdNSCxZ9.js +0 -1
- package/dist/client/assets/chunk-WRU74C26-h6_XkD3_.js +0 -70
- package/dist/client/assets/chunk-ZIRB5QZD-O39ZBUk3.js +0 -32
- package/dist/client/assets/classDiagram-JCYQIIEL-L7lsyW_w.js +0 -1
- package/dist/client/assets/classDiagram-v2-OCEON4UE-L7lsyW_w.js +0 -1
- package/dist/client/assets/comment-ui-shared-BC4pt4w8.js +0 -7
- package/dist/client/assets/cynefin-VYW2F7L2-Ds2Fw2Y0.js +0 -1
- package/dist/client/assets/dagre-Buvkdvvj.js +0 -1
- package/dist/client/assets/dagre-VZM6K2ZE-L1xArOGs.js +0 -4
- package/dist/client/assets/dist-B5Jf1SLZ.js +0 -2
- package/dist/client/assets/dist-BKW4PALF.js +0 -1
- package/dist/client/assets/dist-BWcHHOx-.js +0 -1
- package/dist/client/assets/dist-DaYdhcVs.js +0 -1
- package/dist/client/assets/dist-Kh2COra_.js +0 -1
- package/dist/client/assets/dist-tOaegDYS2.js +0 -1
- package/dist/client/assets/editor-session-Cm9ekeNo.js +0 -54
- package/dist/client/assets/embedded-editor-base-CwTkk911.css +0 -1
- package/dist/client/assets/erDiagram-JOGREHBK-cYUpEKpf.js +0 -85
- package/dist/client/assets/es-DXGV3RHd.js +0 -22
- package/dist/client/assets/eventmodeling-45OFAUF4-CLEiVx5s.js +0 -1
- package/dist/client/assets/excalidraw-editor-B46zsTFI.js +0 -9
- package/dist/client/assets/excalidraw-editor-Bt7gMSoh.css +0 -1
- package/dist/client/assets/excalidrawEditor-CT2pHq7e.js +0 -2
- package/dist/client/assets/export-page-A7NHawJY.js +0 -39
- package/dist/client/assets/exportDocument-B2L8fe34.css +0 -1
- package/dist/client/assets/exportDocument-BaqcOAAW.js +0 -2
- package/dist/client/assets/file-kind-BbqgGzpc.js +0 -1
- package/dist/client/assets/flowDiagram-UKHOOZJN-D0ypP0Ez.js +0 -1
- package/dist/client/assets/gitGraph-TEB2WS4Q-CZFBqwW-.js +0 -1
- package/dist/client/assets/github-dark.min-Z5exjX_n.css +0 -1
- package/dist/client/assets/github.min-D2BCvnWf.css +0 -1
- package/dist/client/assets/image-QXRYHUNP-SWEV8H0J.js +0 -1
- package/dist/client/assets/index-ClbjMBVt.js +0 -2
- package/dist/client/assets/index-Pum8ET-5.css +0 -1
- package/dist/client/assets/info-DKCQHKI2--1InqQeT.js +0 -1
- package/dist/client/assets/main-B3uPyqic.js +0 -893
- package/dist/client/assets/map-BaFkSB1l.js +0 -1
- package/dist/client/assets/mermaid.core-DN-lF51U.js +0 -11
- package/dist/client/assets/packet-7NZHBO7P-BGMXB0XL.js +0 -1
- package/dist/client/assets/pdf-BL9Pr2D5.js +0 -54
- package/dist/client/assets/pdf.worker-CLesOks4.mjs +0 -64857
- package/dist/client/assets/pdf_viewer-FVkkThnz.js +0 -551
- package/dist/client/assets/pie-RZYD4A2V-DgYg3tCt.js +0 -1
- package/dist/client/assets/preview-render-compiler-BD-XhkS2.js +0 -35
- package/dist/client/assets/preview-render-compiler-BKedaMxx.js +0 -1
- package/dist/client/assets/preview-render-worker-CiPqc9n6.js +0 -60
- package/dist/client/assets/prod-Dy20X7eT.js +0 -1
- package/dist/client/assets/prod-hnwh7wRM.js +0 -177
- package/dist/client/assets/quick-switcher-controller-fqOYR7qR.js +0 -12
- package/dist/client/assets/radar-I7S5WNFK-Ag-zp_Rq.js +0 -1
- package/dist/client/assets/railroad-3IZDKUUU-aibJDIDV.js +0 -1
- package/dist/client/assets/railroad-abnf-AHOZXSZD-BBMEuvIl.js +0 -1
- package/dist/client/assets/railroad-ebnf-EBAXGLYW-Be1nseej.js +0 -1
- package/dist/client/assets/railroad-peg-LSFZ7HO6-DIvD-Eyb.js +0 -1
- package/dist/client/assets/stateDiagram-v2-UEYNNEHI-B1-BufUk.js +0 -1
- package/dist/client/assets/swimlanes-SLNWSIFB-oVTWEJIj.js +0 -2
- package/dist/client/assets/swimlanesDiagram-ULZ7WXOC-C5OTVwEu.js +0 -8
- package/dist/client/assets/treeView-QDETBFTQ-uHZ-3Fz8.js +0 -1
- package/dist/client/assets/treemap-6X3UGDF4-BnUKyy3l.js +0 -1
- package/dist/client/assets/vault-utils-wdQ0RNR9.js +0 -1
- package/dist/client/assets/wardley-OPB4EBWU-Da7TLC2F.js +0 -1
|
@@ -1,893 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./pdf-BL9Pr2D5.js","./preload-helper-HclGiUj8.js","./pdf_viewer-FVkkThnz.js","./mermaid.core-DN-lF51U.js","./chunk-Y2CYZVJY-DsF7k-Jl.js","./src-oBChb5qS.js","./rolldown-runtime-Dd_uD5pT.js","./chunk-I66GZJ75-CVFiiffQ.js","./chunk-NSK5VX7P-TLH37VXI.js","./dist-B_J_HbC0.js","./chunk-3NCLNEKW-Y2Jf_LI-.js","./chunk-4I5QYGJK-CCB2YcIH.js","./chunk-WRU74C26-h6_XkD3_.js","./chunk-7BUUIJ7U-Bb538aSH.js","./chunk-UBXNYLIW-Bhk-PbFK.js","./chunk-W5SLKNZC-BdNSCxZ9.js","./chunk-QR6OTTB3-CDAA_5Ib.js","./rough.esm-Dy-Kn_BL.js","./chunk-7Z6QIM7H-BP9Pdsm9.js","./line-B_S_S8kV.js","./path-fybaL0A-.js","./array-BifhSqXX.js","./chunk-J7OUQ5F2-4CEb7pvH.js","./chunk-ZIRB5QZD-O39ZBUk3.js","./preview-render-compiler-BKedaMxx.js","./preview-render-compiler-BD-XhkS2.js","./es-DXGV3RHd.js","./file-kind-BbqgGzpc.js","./preview-render-profile-CE-5rVTC.js","./vault-utils-wdQ0RNR9.js","./prod-Dy20X7eT.js","./chunk-ERSWUTIN-hHdvnhaY.js","./chunk-SRAX5OIU-KFQikY-4.js","./prod-hnwh7wRM.js","./jsx-runtime-BpzPEenQ.js","./chunk-YGJVY4SA-CjSe7Bx7.js","./chunk-7XWMRXBY-CfMzEq80.js","./excalidraw-mermaid-stub-BNckbX2n.js","./editor-session-Cm9ekeNo.js","./dist-CCP_AKPG.js","./dist-Bm6pf9Bl.js","./dist-Bf8f4HmM.js","./dist-PDZ3bSqm.js","./dist-D-Z6FLem.js","./dist-BDt3rz7l.js","./dist-BalScOwZ.js","./dist-FWJsgGYI.js","./dist-xElaxbia.js","./runtime-config-BLrEKVO1.js","./yjs-provider-reset-guard-DE0vINDP.js","./comment-threads-9J6Em-_y.js","./comment-thread-store-CdcwrObc.js","./quick-switcher-controller-fqOYR7qR.js","./file-icon-svg-CQAjlWjK.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as e}from"./preload-helper-HclGiUj8.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v}from"./file-kind-BbqgGzpc.js";import{i as y,n as ee,r as te}from"./preview-render-profile-CE-5rVTC.js";import{n as b,t as x}from"./vault-utils-wdQ0RNR9.js";import{a as S,c as ne,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as re,t as ie,u as ae}from"./vault-api-client-_LpV1aIn.js";import{a as P,c as oe,d as se,f as ce,g as le,i as ue,l as F,m as de,n as fe,o as I,p as pe,r as me,s as he,t as ge,u as _e}from"./runtime-config-BLrEKVO1.js";import{n as ve,r as ye,t as be}from"./yjs-provider-reset-guard-DE0vINDP.js";import{r as xe}from"./drawio-room-yBUzk-vg.js";import{a as Se,i as Ce,n as we,o as Te,r as Ee,t as L}from"./browser-utils--H_DkyEF.js";import{f as De,p as Oe,t as ke,u as Ae}from"./comment-threads-9J6Em-_y.js";import{C as je,S as Me,T as Ne,_ as Pe,a as Fe,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,l as Ue,n as We,o as Ge,p as Ke,r as qe,s as Je,t as Ye,u as Xe,v as Ze,w as Qe,x as $e,y as et}from"./comment-ui-shared-BC4pt4w8.js";import{a as tt,c as nt,d as rt,f as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./preview-diagram-utils-txBCoW8d.js";import{t as gt}from"./file-icon-svg-CQAjlWjK.js";var _t=612,vt=792,yt=960,bt=`720px 0px`,xt=2,R=Object.freeze({default:1,max:2,min:.5,renderDebounceMs:100,step:.25,wheelSensitivity:.01});function St(e){return e?.name===`RenderingCancelledException`||e?.name===`AbortException`}var Ct=class{constructor({previewContainer:e,outlineController:t=null}){this.previewContainer=e,this.outlineController=t,this.pdfJsPromise=null,this.pdfJsApi=null,this.pdfViewerApi=null,this.loadingTask=null,this.pdfDocument=null,this.findEventBus=null,this.findController=null,this.pdfLinkService=null,this.intersectionObserver=null,this.resizeObserver=null,this.pageStates=new Map,this.visiblePages=new Set,this.renderToken=0,this.shell=null,this.zoom=R.default,this.zoomControls=null,this.navigationControls=null,this.searchControls=null,this.pdfNavigationStack=[],this.findState=null,this.currentPageNumber=1,this.zoomRenderTimerId=0,this.pageFitWidth=_t,this.pageLayoutZoom=R.default,this.pinchStartDistance=0,this.pinchStartZoom=R.default}async loadPdfJs(){return this.pdfJsPromise||=e(()=>import(`./pdf-BL9Pr2D5.js`).then(async t=>(t.GlobalWorkerOptions.workerSrc=new URL(``+new URL(`pdf.worker-CLesOks4.mjs`,import.meta.url).href,``+import.meta.url).toString(),globalThis.pdfjsLib=t,{pdfjs:t,pdfViewer:await e(()=>import(`./pdf_viewer-FVkkThnz.js`),__vite__mapDeps([2,1]),import.meta.url)})),__vite__mapDeps([0,1]),import.meta.url),this.pdfJsPromise}async render({filePath:e,renderHost:t,displayName:n}){let r=this.renderToken;this.zoom=R.default,this.pageLayoutZoom=R.default,this.pinchStartDistance=0,this.pinchStartZoom=R.default,this.currentPageNumber=1,this.pdfNavigationStack=[],this.outlineController?.clearPdfOutline?.();let i=F(`/download/file?path=${encodeURIComponent(e)}`),a=this.createShell({displayName:n,filePath:e,url:i});t.replaceChildren(a),this.shell=a;try{let{pdfjs:e,pdfViewer:t}=await this.loadPdfJs();if(this.pdfJsApi=e,this.pdfViewerApi=t,r!==this.renderToken)return;this.loadingTask=e.getDocument({url:i}),this.loadingTask.onPassword=(e,t)=>{if(r!==this.renderToken||this.shell!==a){e(Error(`PDF preview cancelled`));return}this.showPasswordPrompt(a,e,t)};let n=await this.loadingTask.promise;if(r!==this.renderToken){await n.destroy();return}this.pdfDocument=n,this.initializeFindController(n,t),this.loadPdfOutline(n,r),this.buildPageStates(n.numPages,a.querySelector(`.pdf-file-preview-pages`)),this.setStatus(`${n.numPages} ${n.numPages===1?`page`:`pages`}`),this.observePages(r),this.searchControls?.input.value.trim()&&this.dispatchFind()}catch(e){r===this.renderToken&&!St(e)&&this.showError(a)}finally{r===this.renderToken&&(this.loadingTask=null)}}showPasswordPrompt(e,t,n){let r=e.querySelector(`.pdf-file-preview-pages`);if(!r)return;let i=n===this.pdfJsApi?.PasswordResponses?.INCORRECT_PASSWORD;this.setStatus(i?`Incorrect password`:`Password required`);let a=document.createElement(`form`);a.className=`pdf-file-preview-password-prompt`;let o=document.createElement(`h2`);o.className=`pdf-file-preview-password-title`,o.textContent=i?`Incorrect PDF password`:`Password required`;let s=document.createElement(`p`);s.className=`pdf-file-preview-password-copy`,s.textContent=i?`The password was incorrect. Try again.`:`Enter the password to preview this PDF.`;let c=document.createElement(`label`);c.className=`pdf-file-preview-password-field`,c.textContent=`PDF password`;let l=document.createElement(`input`);l.type=`password`,l.className=`ui-input`,l.autocomplete=`off`,l.spellcheck=!1,l.setAttribute(`aria-label`,`PDF password`),c.appendChild(l);let u=document.createElement(`button`);u.type=`submit`,u.className=`ui-button ui-button--primary`,u.textContent=`Unlock PDF`,a.addEventListener(`submit`,e=>{e.preventDefault(),u.disabled=!0,l.disabled=!0,t(l.value)}),a.append(o,s,c,u),r.replaceChildren(a),l.focus()}async loadPdfOutline(e,t){try{let n=typeof e.getOutline==`function`?await e.getOutline():null;if(t!==this.renderToken||this.pdfDocument!==e)return;if(!Array.isArray(n)||n.length===0){this.outlineController?.clearPdfOutline?.();return}this.outlineController?.setPdfOutline?.(n,n=>this.navigateToPdfOutline(n,e,t))}catch{t===this.renderToken&&this.pdfDocument===e&&this.outlineController?.clearPdfOutline?.()}}async navigateToPdfOutline(e,t,n){if(n!==this.renderToken||this.pdfDocument!==t)return;let r=typeof e?.url==`string`?e.url.trim():``;if(r){try{let e=new URL(r,window.location.href);(e.protocol===`http:`||e.protocol===`https:`)&&window.open(e.href,`_blank`,`noopener,noreferrer`)}catch{}return}let i=this.pdfLinkService;if(!(!i||i.pdfDocument!==t||e?.dest==null))try{await i.goToDestination(e.dest)}catch{}}initializeFindController(e,t){let n=this,r=new t.EventBus,i=t=>{n.pdfDocument===e&&(n.currentPageNumber=x(Number(t)||1,1,e.numPages),n.scrollToPage(n.currentPageNumber))},a={get currentPageNumber(){return n.currentPageNumber},set currentPageNumber(e){i(e)},scrollPageIntoView({pageNumber:e,destArray:t}){t&&n.recordPdfNavigation(n.currentPageNumber,e),i(e)}},o=new t.PDFLinkService({eventBus:r});o.setDocument(e),o.setViewer(a);let s=new t.PDFFindController({eventBus:r,linkService:o,delay:0,updateMatchesCountOnProgress:!0});this.findState=t.FindState.FOUND,s.onIsPageVisible=e=>this.visiblePages.has(e),r.on(`updatefindmatchescount`,({matchesCount:e})=>this.updateFindStatus(e,!0)),r.on(`updatefindcontrolstate`,({state:e,matchesCount:t})=>{this.findState=e,this.updateFindStatus(t)}),this.findEventBus=r,this.findController=s,this.pdfLinkService=o,s.setDocument(e),this.updateFindControls()}scrollToPage(e){(this.pageStates.get(e)?.pageShell)?.scrollIntoView?.({behavior:`auto`,block:`center`,inline:`nearest`})}recordPdfNavigation(e,t){!Number.isInteger(e)||!Number.isInteger(t)||e===t||(this.pdfNavigationStack.push(e),this.updateNavigationControls())}goBack(){let e=this.pdfNavigationStack.pop();if(!Number.isInteger(e)){this.updateNavigationControls();return}this.currentPageNumber=e,this.scrollToPage(e),this.updateNavigationControls()}updateNavigationControls(){this.navigationControls?.backButton&&(this.navigationControls.backButton.disabled=this.pdfNavigationStack.length===0)}setFindStatus(e){this.searchControls?.status&&(this.searchControls.status.textContent=e)}updateFindStatus(e,t=!1){if(!this.searchControls?.input.value.trim()){this.setFindStatus(``);return}let n=Number(e?.current)||0,r=Number(e?.total)||0,i=this.findState===this.pdfViewerApi?.FindState.PENDING&&(!t||r===0)?`Searching…`:r>0?`${n} of ${r}`:`No matches`;this.setFindStatus(i)}updateFindControls(){let e=this.searchControls;if(!e)return;let t=!e.input.value.trim()||!this.findController;e.previousButton.disabled=t,e.nextButton.disabled=t}dispatchFind(){let e=this.searchControls?.input.value.trim()||``;if(!e){this.findState=this.pdfViewerApi?.FindState.FOUND??null,this.findEventBus?.dispatch(`findbarclose`,{source:this}),this.setFindStatus(``),this.updateFindControls();return}if(!this.findEventBus||!this.findController){this.setFindStatus(`Loading…`),this.updateFindControls();return}this.findState=this.pdfViewerApi?.FindState.PENDING??null,this.setFindStatus(`Searching…`),this.updateFindControls(),this.findEventBus.dispatch(`find`,{source:this,type:``,query:e,phraseSearch:!0,caseSensitive:!1,entireWord:!1,highlightAll:!0,findPrevious:!1,matchDiacritics:!1})}dispatchFindAgain(e=!1){let t=this.searchControls?.input.value.trim()||``;!t||!this.findEventBus||!this.findController||this.findEventBus.dispatch(`find`,{source:this,type:`again`,query:t,phraseSearch:!0,caseSensitive:!1,entireWord:!1,highlightAll:!0,findPrevious:e,matchDiacritics:!1})}createShell({displayName:e,filePath:t,url:n}){let r=document.createElement(`section`);r.className=`pdf-file-preview-shell`,r.setAttribute(`aria-label`,`${e} PDF preview`);let i=document.createElement(`div`);i.className=`pdf-file-preview-toolbar`;let a=document.createElement(`span`);a.className=`pdf-file-preview-status`,a.setAttribute(`role`,`status`),a.setAttribute(`aria-live`,`polite`),a.textContent=`Loading PDF preview…`;let o=document.createElement(`div`);o.className=`pdf-file-preview-zoom-controls`;let s=document.createElement(`button`);s.type=`button`,s.className=`pdf-file-preview-zoom-button ui-preview-action`,s.setAttribute(`aria-label`,`Zoom out`),s.title=`Zoom out`,s.textContent=`−`,s.addEventListener(`click`,()=>this.setZoom(this.zoom-R.step));let c=document.createElement(`span`);c.className=`pdf-file-preview-zoom-label`,c.setAttribute(`aria-live`,`polite`);let l=document.createElement(`button`);l.type=`button`,l.className=`pdf-file-preview-zoom-button ui-preview-action`,l.setAttribute(`aria-label`,`Zoom in`),l.title=`Zoom in`,l.textContent=`+`,l.addEventListener(`click`,()=>this.setZoom(this.zoom+R.step)),o.append(s,c,l),this.zoomControls={zoomInButton:l,zoomLabel:c,zoomOutButton:s},this.updateZoomControls();let u=document.createElement(`button`);u.type=`button`,u.className=`pdf-file-preview-back-button ui-preview-action`,u.setAttribute(`aria-label`,`Back to previous page`),u.title=`Back to previous page`,u.textContent=`←`,u.addEventListener(`click`,()=>this.goBack()),this.navigationControls={backButton:u},this.updateNavigationControls();let d=document.createElement(`a`);d.className=`pdf-file-preview-download`,d.href=n,d.download=String(t).split(`/`).pop()||e,d.textContent=`Download`,d.setAttribute(`aria-label`,`Download ${e}`);let f=document.createElement(`div`);f.className=`pdf-file-preview-find-controls`;let p=document.createElement(`input`);p.type=`search`,p.className=`pdf-file-preview-find-input`,p.placeholder=`Find in PDF`,p.setAttribute(`aria-label`,`Find in PDF`),p.addEventListener(`input`,()=>this.dispatchFind()),p.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),p.value=``,this.dispatchFind(),p.blur();return}e.key===`Enter`&&(e.preventDefault(),this.dispatchFindAgain(e.shiftKey))});let m=document.createElement(`span`);m.className=`pdf-file-preview-find-status`,m.setAttribute(`role`,`status`),m.setAttribute(`aria-live`,`polite`);let h=document.createElement(`button`);h.type=`button`,h.className=`pdf-file-preview-find-button ui-preview-action`,h.setAttribute(`aria-label`,`Previous match`),h.title=`Previous match`,h.textContent=`‹`,h.addEventListener(`click`,()=>this.dispatchFindAgain(!0));let g=document.createElement(`button`);g.type=`button`,g.className=`pdf-file-preview-find-button ui-preview-action`,g.setAttribute(`aria-label`,`Next match`),g.title=`Next match`,g.textContent=`›`,g.addEventListener(`click`,()=>this.dispatchFindAgain()),f.append(p,m,h,g),this.searchControls={input:p,nextButton:g,previousButton:h,status:m},this.updateFindControls();let _=document.createElement(`div`);_.className=`pdf-file-preview-toolbar-start`,_.append(u,a,o,f),i.append(_,d);let v=document.createElement(`div`);v.className=`pdf-file-preview-pages`,v.setAttribute(`aria-label`,`PDF pages`),v.addEventListener(`wheel`,e=>this.handleWheelZoom(e),{passive:!1}),v.addEventListener(`touchstart`,e=>this.handleTouchStart(e),{passive:!0}),v.addEventListener(`touchmove`,e=>this.handleTouchMove(e),{passive:!1});let y=e=>this.handleTouchEnd(e);return v.addEventListener(`touchend`,y,{passive:!0}),v.addEventListener(`touchcancel`,y,{passive:!0}),r.append(i,v),r}buildPageStates(e,t){this.pageStates.clear(),this.visiblePages.clear(),t.replaceChildren();for(let n=1;n<=e;n+=1){let r=document.createElement(`article`);r.className=`pdf-page`,r.dataset.pageNumber=String(n),r.setAttribute(`aria-label`,`Page ${n} of ${e}`),r.style.aspectRatio=`${_t} / ${vt}`,t.appendChild(r),this.pageStates.set(n,{canvas:null,needsRender:!1,page:null,pageShell:r,renderPromise:null,renderTask:null,renderedWidth:0,pageView:null})}this.commitPageZoom()}observePages(e){let t=this.shell?.querySelector(`.pdf-file-preview-pages`);t&&(typeof IntersectionObserver==`function`?(this.intersectionObserver=new IntersectionObserver(t=>this.handlePageIntersections(t,e),{root:this.previewContainer,rootMargin:bt}),this.pageStates.forEach(({pageShell:e})=>this.intersectionObserver.observe(e))):(this.visiblePages.add(1),this.renderPage(1,e)),typeof ResizeObserver==`function`&&(this.resizeObserver=new ResizeObserver(()=>{this.commitPageZoom({preserveLiveZoom:!!this.zoomRenderTimerId}),this.scheduleVisiblePageRender()}),this.resizeObserver.observe(t)))}handlePageIntersections(e,t){t===this.renderToken&&e.forEach(e=>{let n=Number(e.target.dataset.pageNumber);if(e.isIntersecting){this.visiblePages.add(n),this.currentPageNumber=Math.min(...this.visiblePages),this.renderPage(n,t);return}this.visiblePages.delete(n),this.releasePage(n)})}disposePageView(e,t=e.pageView){t&&(t.reset?.(),t.div?.remove(),e.pageView===t&&(e.pageView=null,e.canvas=null,e.renderTask=null,e.renderedWidth=0))}async renderPage(e,t){let n=this.pageStates.get(e);if(!n||!this.pdfDocument||t!==this.renderToken)return;let r=this.getPageWidth(n.pageShell);if(n.canvas&&Math.abs(n.renderedWidth-r)<1){n.needsRender=!1;return}return n.renderPromise?n.renderPromise:(n.needsRender=!1,n.renderPromise=(async()=>{let i=null,a=!1;try{let o=n.page??await this.pdfDocument.getPage(e);if(t!==this.renderToken)return;n.page=o;let s=o.getViewport({scale:1});n.pageShell.style.aspectRatio=`${s.width} / ${s.height}`;let c=r/s.width,l=o.getViewport({scale:c}),u=l.userUnit||1;n.pageShell.style.setProperty(`--scale-factor`,String(l.scale)),n.pageShell.style.setProperty(`--user-unit`,String(u)),n.pageShell.style.setProperty(`--total-scale-factor`,String(l.scale*u)),n.pageShell.style.setProperty(`--scale-round-x`,`1px`),n.pageShell.style.setProperty(`--scale-round-y`,`1px`),this.disposePageView(n),i=new this.pdfViewerApi.PDFPageView({annotationMode:this.pdfJsApi.AnnotationMode.ENABLE,container:n.pageShell,defaultViewport:l,enableAutoLinking:!1,eventBus:this.findEventBus,id:e,layerProperties:{findController:this.findController,linkService:this.pdfLinkService},maxCanvasPixels:Math.ceil(l.width*l.height*xt**2),scale:l.scale/this.pdfJsApi.PixelsPerInch.PDF_TO_CSS_UNITS,textLayerMode:1}),i.setPdfPage(o),n.pageView=i;let d=i.draw();if(n.renderTask=i.renderTask,await d,i.canvas&&(i.canvas.className=`pdf-page-canvas`,i.canvas.setAttribute(`aria-label`,`Rendered page ${e}`)),!(t===this.renderToken&&this.visiblePages.has(e)&&n.pageView===i&&i.canvas&&Math.abs(this.getPageWidth(n.pageShell)-r)<1)){this.disposePageView(n,i),t===this.renderToken&&this.visiblePages.has(e)&&this.scheduleVisiblePageRender();return}n.canvas=i.canvas,n.renderedWidth=r,a=!0}catch(r){i&&!a&&this.disposePageView(n,i),!St(r)&&t===this.renderToken&&(n.pageShell.replaceChildren(),this.setStatus(`Unable to render page ${e}`))}finally{n.pageView===i&&(n.renderTask=null)}})().finally(()=>{n.renderPromise=null;let r=n.needsRender;n.needsRender=!1,r&&this.visiblePages.has(e)&&t===this.renderToken&&this.renderPage(e,t)}),n.renderPromise)}handleWheelZoom(e){if(!e.ctrlKey)return;e.preventDefault();let t=Number.isFinite(e.deltaY)?e.deltaY:0,n=x(-t*R.wheelSensitivity,-R.step/2,R.step/2);n!==0&&this.setZoom(this.zoom+n)}getPinchDistance(e){if(!e||e.length!==2)return 0;let[t,n]=e,r=Math.hypot(n.clientX-t.clientX,n.clientY-t.clientY);return Number.isFinite(r)&&r>0?r:0}handleTouchStart(e){if(e.touches?.length!==2)return;let t=this.getPinchDistance(e.touches);t>0&&(this.pinchStartDistance=t,this.pinchStartZoom=this.zoom)}handleTouchMove(e){if(e.touches?.length!==2)return;this.pinchStartDistance||this.handleTouchStart(e);let t=this.getPinchDistance(e.touches);!t||!this.pinchStartDistance||(this.setZoom(this.pinchStartZoom*(t/this.pinchStartDistance)),e.preventDefault())}handleTouchEnd(e){e.touches?.length!==2&&(this.pinchStartDistance=0,this.pinchStartZoom=this.zoom)}cancelVisiblePageRenders(){this.visiblePages.forEach(e=>{let t=this.pageStates.get(e);t&&(t.needsRender=!1,this.disposePageView(t))})}scheduleVisiblePageRender(){this.zoomRenderTimerId&&window.clearTimeout(this.zoomRenderTimerId),this.zoomRenderTimerId=window.setTimeout(()=>{this.zoomRenderTimerId=0,this.commitPageZoom({measure:!1}),this.visiblePages.forEach(e=>{let t=this.pageStates.get(e);t&&(t.needsRender=!0),this.renderPage(e,this.renderToken)})},R.renderDebounceMs)}setZoom(e){let t=x(e,R.min,R.max);t!==this.zoom&&(this.cancelVisiblePageRenders(),this.zoom=t,this.updateZoomControls(),this.applyLivePageZoom(),this.scheduleVisiblePageRender())}updateZoomControls(){if(!this.zoomControls)return;let e=`${Math.round(this.zoom*100)}%`;this.zoomControls.zoomLabel.textContent=e,this.zoomControls.zoomLabel.setAttribute(`aria-label`,`Zoom ${e}`),this.zoomControls.zoomOutButton.disabled=this.zoom<=R.min,this.zoomControls.zoomInButton.disabled=this.zoom>=R.max}applyLivePageZoom(){let e=this.shell?.querySelector(`.pdf-file-preview-pages`);if(!e)return;let t=this.pageLayoutZoom>0?this.zoom/this.pageLayoutZoom:1;if(Math.abs(t-1)<.001){e.style.removeProperty(`transform`),e.style.removeProperty(`transform-origin`),e.style.removeProperty(`will-change`);return}e.style.transformOrigin=`top center`,e.style.transform=`scale(${t})`,e.style.willChange=`transform`}commitPageZoom({measure:e=!0,preserveLiveZoom:t=!1}={}){let n=this.shell?.querySelector(`.pdf-file-preview-pages`);if(!n)return;if(e){let e=window.getComputedStyle(n),t=Number.parseFloat(e.paddingLeft||`0`)+Number.parseFloat(e.paddingRight||`0`),r=n.clientWidth-t;this.pageFitWidth=Math.min(yt,r>0?r:this.previewContainer?.clientWidth||_t)}let r=t?this.pageLayoutZoom:this.zoom;n.style.setProperty(`--pdf-page-width`,`${Math.max(1,this.pageFitWidth*r)}px`),!t&&(this.pageLayoutZoom=this.zoom,n.style.removeProperty(`transform`),n.style.removeProperty(`transform-origin`),n.style.removeProperty(`will-change`))}getPageWidth(e){return e.offsetWidth||e.getBoundingClientRect().width||this.previewContainer?.clientWidth||_t}releasePage(e){let t=this.pageStates.get(e);t&&(t.needsRender=!0,this.disposePageView(t),t.pageShell.replaceChildren())}setStatus(e){let t=this.shell?.querySelector(`.pdf-file-preview-status`);t&&(t.textContent=e)}showError(e){this.setStatus(`Unable to render PDF`);let t=e.querySelector(`.pdf-file-preview-pages`);if(!t)return;let n=document.createElement(`div`);n.className=`pdf-file-preview-error`,n.textContent=`This PDF could not be rendered in the browser.`,t.replaceChildren(n)}cancel(){this.renderToken+=1,this.zoomRenderTimerId&&=(window.clearTimeout(this.zoomRenderTimerId),0),this.intersectionObserver?.disconnect(),this.resizeObserver?.disconnect(),this.intersectionObserver=null,this.resizeObserver=null,this.pageStates.forEach(e=>this.disposePageView(e)),this.findEventBus?.dispatch(`findbarclose`,{source:this}),this.findController?.setDocument(null),this.outlineController?.clearPdfOutline?.(),(this.loadingTask?.destroy?.())?.catch?.(()=>{}),(this.pdfDocument?.destroy?.())?.catch?.(()=>{}),this.loadingTask=null,this.pdfDocument=null,this.findEventBus=null,this.findController=null,this.pdfLinkService=null,this.pdfJsApi=null,this.pdfViewerApi=null,this.pageStates.clear(),this.visiblePages.clear(),this.zoomControls=null,this.navigationControls=null,this.searchControls=null,this.pdfNavigationStack=[],this.findState=null,this.currentPageNumber=1,this.zoom=R.default,this.pageFitWidth=_t,this.pageLayoutZoom=R.default,this.pinchStartDistance=0,this.pinchStartZoom=R.default,this.shell=null}},wt=Object.freeze({htmlLabels:!1,flowchart:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},startOnLoad:!1,theme:`default`}),Tt=/^\s*%%\{\s*(?:init|initialize)\s*:[\s\S]*?\}%%\s*\n?/gim,Et=0;function Dt(){return Et+=1,`mermaid-export-${Et.toString(36)}`}async function Ot(e){if(typeof e.toBlob==`function`){let t=await new Promise(t=>e.toBlob(t,`image/png`));if(t instanceof Blob)return t}return kt(e.toDataURL(`image/png`))}function kt(e){let[t=``,n=``]=String(e).split(`,`,2),r=t.match(/^data:([^;,]+)?/u)?.[1]||`application/octet-stream`;if(t.includes(`;base64`)){let e=atob(n),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return new Blob([t],{type:r})}return new Blob([decodeURIComponent(n)],{type:r})}function At(e){let t=e.cloneNode(!0);if(!(t instanceof SVGSVGElement))throw Error(`Renderer returned invalid SVG`);t.style.removeProperty(`display`),t.style.removeProperty(`margin`),t.style.removeProperty(`max-width`),t.style.removeProperty(`height`),t.style.removeProperty(`width`),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`);let{width:n,height:r}=rt(t);return t.setAttribute(`width`,String(Math.max(1,Math.ceil(n)))),t.setAttribute(`height`,String(Math.max(1,Math.ceil(r)))),t}function jt(e,{padding:t=16}={}){let n=At(e);if(typeof e.getBBox!=`function`)return n;try{let r=e.getBBox();if(!r||r.width<=0||r.height<=0)return n;let i=Math.max(0,Number(t)||0),a=Math.ceil(r.width+i*2),o=Math.ceil(r.height+i*2),s=[Math.floor(r.x-i),Math.floor(r.y-i),a,o];return n.setAttribute(`viewBox`,s.join(` `)),n.setAttribute(`width`,String(a)),n.setAttribute(`height`,String(o)),n.setAttribute(`preserveAspectRatio`,`xMidYMid meet`),n}catch{return n}}function Mt({currentFilePath:e=``,diagramKind:t=`diagram`,sourceLine:n=``,targetPath:r=``}={}){let a=w(r);if(a)return o(a)||`${t}-diagram`;let s=w(e),c=o(s)||`document`;return t===`mermaid`&&i(e)||t===`plantuml`&&p(e)?c:n?`${c}-${t}-L${n}`:`${c}-${t}`}function Nt(e={}){let t=Mt(e);return{baseName:t,pngFileName:`${t}.png`,svgFileName:`${t}.svg`}}function Pt(e){let t=At(e);return dt(t)}function Ft(e,t={}){return dt(jt(e,t))}function It(e){let t=String(e??``).replace(Tt,``);if(t=`%%{init: ${JSON.stringify(wt)}}%%\n${t}`,/^\s*gantt\b/m.test(t)&&!/\btodayMarker\b/.test(t)){let e=t.split(`
|
|
3
|
-
`),n=e.findIndex(e=>/^\s*gantt\b/.test(e));n!==-1&&(e.splice(n+1,0,` todayMarker off`),t=e.join(`
|
|
4
|
-
`))}return t}async function Lt(e,t){if(!e?.initialize||!e?.run)throw Error(`Mermaid runtime is unavailable`);e.initialize(wt);let n=document.createElement(`div`);n.style.position=`fixed`,n.style.left=`-10000px`,n.style.top=`0`,n.style.width=`1200px`,n.style.visibility=`hidden`,n.style.pointerEvents=`none`,document.body.appendChild(n);try{let r=document.createElement(`div`);r.className=`mermaid mermaid-export-node`,r.id=Dt(),r.textContent=It(t),n.appendChild(r),await e.run({nodes:[r]});let i=r.querySelector(`svg`);if(!(i instanceof SVGSVGElement))throw Error(`Mermaid export returned no SVG`);return Ft(i,{padding:24})}finally{n.remove()}}async function Rt(e){let t=it(e),n=await nt(tt(t)),r=document.createElement(`div`);r.innerHTML=t;let i=r.querySelector(`svg`),{width:a,height:o}=i?rt(i):{height:n.naturalHeight||800,width:n.naturalWidth||1200},s=document.createElement(`canvas`);s.width=Math.max(1,Math.ceil(a)),s.height=Math.max(1,Math.ceil(o));let c=s.getContext(`2d`);if(!c)throw Error(`Canvas is unavailable`);return c.fillStyle=`#ffffff`,c.fillRect(0,0,s.width,s.height),c.drawImage(n,0,0,s.width,s.height),Ot(s)}async function zt(e){if(typeof ClipboardItem!=`function`||!navigator.clipboard?.write)throw Error(`Clipboard image copy is unavailable`);await navigator.clipboard.write([new ClipboardItem({[e.type||`image/png`]:e})])}function Bt(e){return`data-${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}var Vt=class{constructor(e,{batchSize:t,datasetKeys:n,loadFileSource:r=null,filePathLabel:i,requestIdleRenderFn:a=Te,cancelIdleRenderFn:o=L,intersectionObserverFactory:s=(e,t)=>new IntersectionObserver(e,t),isNearViewportFn:c=Ee,requestAnimationFrameFn:l=e=>requestAnimationFrame(e),shellClassName:u,sourceClassName:d}){this.renderer=e,this.batchSize=t,this.datasetKeys=n,this.loadFileSource=r,this.filePathLabel=i,this.requestIdleRenderFn=a,this.cancelIdleRenderFn=o,this.intersectionObserverFactory=s,this.isNearViewportFn=c,this.requestAnimationFrameFn=l,this.shellClassName=u,this.sourceClassName=d,this.shellSelector=`.${u}`,this.sourceSelector=`.${d}`,this.attributeNames=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Bt(t)])),this.observer=null,this.idleId=null,this.pendingShells=[],this.hydrationInProgress=!1,this.hydrationToken=0,this.hydrationRenderVersion=null,this.instanceCounter=0,this.preservedShells=[],this.fileInflightRequests=new Map}destroy(){this.cancelHydration(),this.clearPreservedShells()}cancelHydration(){this.hydrationToken+=1,this.hydrationRenderVersion=null,this.observer&&=(this.observer.disconnect(),null),this.cancelIdleRenderFn(this.idleId),this.idleId=null,this.pendingShells=[],this.hydrationInProgress=!1}cancelPendingIdleWork(){this.cancelIdleRenderFn(this.idleId),this.idleId=null}clearPreservedShells(){this.preservedShells.forEach(({shell:e})=>{this.renderer.diagramChrome?.destroyShell?.(e)}),this.preservedShells.length=0}getPreviewShells(){let e=this.renderer.previewElement;if(!e)return[];let t=e.ownerDocument?.querySelectorAll?.(this.shellSelector);return t?Array.from(t):Array.from(e.querySelectorAll(this.shellSelector))}getPreservationIdentity(e){let t=e?.getAttribute?.(this.attributeNames.sourceLine);return t?`${this.shellClassName}:${t}`:null}isShellRenderable(e){return this.isShellHydrated(e)||e?.getAttribute?.(`data-diagram-output`)===`true`}isShellError(e){return e?.getAttribute?.(`data-diagram-state`)===`error`}hasPendingWork(){return this.hydrationInProgress||this.pendingShells.length>0}preserveHydratedShellsForCommit(){this.preservedShells.length=0,this.renderer.previewElement&&this.getPreviewShells().filter(e=>this.isShellRenderable(e)).forEach(e=>{let t=e.dataset[this.datasetKeys.key],n=e.querySelector(this.sourceSelector)?.textContent??``,r=e.dataset[this.datasetKeys.target]??``;!t||!n&&!r||(e.isConnected&&(this.renderer.diagramChrome?.captureShellViewState?.(e),e.remove()),this.preservedShells.push({key:t,identity:this.getPreservationIdentity(e),shell:e,source:n,target:r}))})}reconcileHydratedShells(){let e=this.renderer.previewElement;if(!e||this.preservedShells.length===0){this.clearPreservedShells();return}let t=!1;Array.from(e.querySelectorAll(`${this.shellSelector}[${this.attributeNames.key}]`)).forEach(e=>{let n=e.dataset[this.datasetKeys.key],r=n?this.preservedShells.findIndex(e=>e.key===n):-1;if(r===-1){let t=this.getPreservationIdentity(e);r=t?this.preservedShells.findIndex(e=>e.identity===t):-1}if(r===-1)return;let i=this.preservedShells[r],a=e.querySelector(this.sourceSelector)?.textContent??``,o=e.dataset[this.datasetKeys.target]??``,s=this.isShellRenderable(i.shell)&&a!==i.source&&!o;if(!ct({nextSource:a,nextTarget:o,preservedSource:i.source,preservedTarget:i.target})&&!s)return;this.syncPreservedShell(i.shell,e,{sourceChanged:s}),e.replaceWith(i.shell);let c=this.renderer.diagramChrome?.getShellViewState?.(i.shell),l=i.shell.querySelector(`.diagram-preview-frame`);c&&l&&(l.scrollLeft=c.scrollLeft??0,l.scrollTop=c.scrollTop??0),t||=i.shell.classList.contains(`is-maximized`),this.preservedShells.splice(r,1)}),this.preservedShells.forEach(({shell:e})=>{this.renderer.diagramChrome?.destroyShell?.(e)}),this.preservedShells.length=0,this.handleReconcile({restoredMaximizedShell:t})}handleReconcile(){}syncPreservedShell(e,t,{sourceChanged:n=!1}={}){at(e,t,this.attributeNames.sourceLine),at(e,t,this.attributeNames.sourceLineEnd),at(e,t,this.attributeNames.key),at(e,t,this.attributeNames.target),at(e,t,this.attributeNames.label),at(e,t,this.attributeNames.sourceHash),e.classList.add(this.shellClassName),this.removeDatasetValue(e,`queued`);let r=t.querySelector(this.sourceSelector),i=e.querySelector(this.sourceSelector);if(!i&&r&&(i=r.cloneNode(!0),e.prepend(i)),i&&r){let e=r.textContent??``;(e||!t.dataset[this.datasetKeys.target])&&(i.textContent=e),i.hidden=!0}if(n){this.markShellPending(e);return}if(this.isShellError(e)){e.dataset[this.datasetKeys.hydrated]=`true`;return}this.markShellHydrated(e)}getShellErrorCard(e){return e?.querySelector?.(`:scope > .diagram-preview-error-card`)??null}notifyShellLayoutChange(){this.renderer.onPreviewLayoutChange?.({renderVersion:this.renderer.activeRenderVersion})}clearShellErrorCard(e){e&&(this.getShellErrorCard(e)?.remove?.(),this.notifyShellLayoutChange())}getShellLabel(e){return e?.dataset?.[this.datasetKeys.label]||`${this.filePathLabel} diagram`}markShellRendered(e){e&&(e.setAttribute(`data-diagram-output`,`true`),e.removeAttribute(`data-diagram-state`),e.removeAttribute(`aria-busy`),this.clearShellErrorCard(e))}markShellPending(e){return this.isShellRenderable(e)?(this.removeDatasetValue(e,`hydrated`),e.setAttribute(`data-diagram-output`,`true`),e.setAttribute(`data-diagram-state`,`pending`),e.setAttribute(`aria-busy`,`true`),this.getShellErrorCard(e)&&this.clearShellErrorCard(e),!0):!1}markShellError(e,t){if(!this.isShellRenderable(e))return!1;let n=st(t);e.dataset[this.datasetKeys.hydrated]=`true`,e.setAttribute(`data-diagram-output`,`true`),e.setAttribute(`data-diagram-state`,`error`),e.removeAttribute(`aria-busy`),this.getShellErrorCard(e)?.remove?.();let r=this.shellClassName.replace(/-shell$/,``);return e.append(mt({key:e.dataset[this.datasetKeys.key],kind:r,label:this.getShellLabel(e),message:n,subtitle:`Showing the last valid result.`})),this.notifyShellLayoutChange(),!0}clearShellOutput(e){this.removeDatasetValue(e,`hydrated`),e?.removeAttribute?.(`data-diagram-output`),e?.removeAttribute?.(`data-diagram-state`),e?.removeAttribute?.(`aria-busy`),this.clearShellErrorCard(e)}markPending(){this.cancelHydration(),this.getPreviewShells().filter(e=>this.isShellRenderable(e)).forEach(e=>{this.markShellPending(e)})}retryShell(e){e?.isConnected&&(this.removeDatasetValue(e,`hydrated`),this.markShellPending(e),this.enqueueShell(e,{prioritize:!0}))}isHydrationCurrent(e,t,n=this.hydrationToken){return!!(t?.isConnected&&n===this.hydrationToken&&(e==null||e===this.hydrationRenderVersion&&e===this.renderer.activeRenderVersion))}setupHydration(e){let t=this.renderer.previewElement,n=this.renderer.previewContainer;if(!t||!n)return 0;let r=Array.from(t.querySelectorAll(this.shellSelector));if(r.length===0)return 0;this.hydrationToken+=1;let i=this.hydrationToken;return this.hydrationRenderVersion=e,this.observer=this.intersectionObserverFactory(e=>{e.forEach(e=>{e.isIntersecting&&this.enqueueShell(e.target)})},{root:n,rootMargin:this.renderer.isLargeDocument?`180px 0px`:`420px 0px`}),r.forEach(e=>this.observer.observe(e)),this.requestAnimationFrameFn(()=>{this.isHydrationCurrent(e,t,i)&&(this.hydrateVisibleShells(),this.renderer.updateHydrationPhase())}),r.length}hydrateVisibleShells(){let e=this.renderer.previewElement,t=this.renderer.previewContainer;if(this.renderer.hydrationPaused||!e||!t)return;let n=this.renderer.isLargeDocument?180:420;Array.from(e.querySelectorAll(this.shellSelector)).forEach(e=>{this.isNearViewportFn(e,t,n)&&this.enqueueShell(e,{prioritize:!0})})}enqueueShell(e,{prioritize:t=!1}={}){!e?.isConnected||this.isShellHydrated(e)||this.isShellQueued(e)||(e.dataset[this.datasetKeys.queued]=`true`,t?this.pendingShells.unshift(e):this.pendingShells.push(e),!this.renderer.hydrationPaused&&(this.renderer.updateHydrationPhase(),this.scheduleHydration()))}scheduleHydration(){this.renderer.hydrationPaused||this.hydrationInProgress||this.idleId!==null||(this.idleId=this.requestIdleRenderFn(()=>{this.idleId=null,this.flushHydrationQueue()},500))}async flushHydrationQueue(){if(this.renderer.hydrationPaused||this.hydrationInProgress)return;let e=this.hydrationToken,t=this.hydrationRenderVersion,n=[];for(;this.pendingShells.length>0&&n.length<this.batchSize;){let e=this.pendingShells.shift();!e?.isConnected||this.isShellHydrated(e)||(this.removeDatasetValue(e,`queued`),n.push(e))}if(n.length===0){this.renderer.updateHydrationPhase();return}this.hydrationInProgress=!0,this.renderer.setPhase(`hydrating`);let r;try{r=await this.prepareHydrationBatch(n)}catch(t){if(e!==this.hydrationToken)return;this.handlePrepareHydrationBatchError(n,t),this.hydrationInProgress=!1,this.renderer.updateHydrationPhase();return}for(let i of n){if(e!==this.hydrationToken)return;await this.hydrateShell(i,r,{hydrationToken:e,renderVersion:t})}e===this.hydrationToken&&(this.hydrationInProgress=!1,this.pendingShells.length>0&&this.scheduleHydration(),this.renderer.updateHydrationPhase())}async prepareHydrationBatch(){return null}handlePrepareHydrationBatchError(e,t){}async hydrateShell(){throw Error(`hydrateShell must be implemented by subclasses`)}markShellHydrated(e){this.markShellRendered(e),e.dataset[this.datasetKeys.hydrated]=`true`,e.dataset[this.datasetKeys.instanceId]=String(++this.instanceCounter)}isShellHydrated(e){return e?.dataset?.[this.datasetKeys.hydrated]===`true`}removeDatasetValue(e,t){let n=this.datasetKeys[t];!n||!e||(e.removeAttribute?.(this.attributeNames[t]),e.dataset&&delete e.dataset[n])}isShellQueued(e){return e?.dataset?.[this.datasetKeys.queued]===`true`}async fetchSource(e){let t=String(e??``).trim();if(!t)throw Error(`Missing ${this.filePathLabel} file path`);if(this.fileInflightRequests.has(t))return this.fileInflightRequests.get(t);if(typeof this.loadFileSource!=`function`)throw Error(`Missing ${this.filePathLabel} source loader`);let n=this.loadFileSource(t).finally(()=>{this.fileInflightRequests.delete(t)});return this.fileInflightRequests.set(t,n),n}},Ht=class extends Vt{constructor(e,{loadFileSource:t=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`mermaidHydrated`,instanceId:`mermaidInstanceId`,key:`mermaidKey`,label:`mermaidLabel`,queued:`mermaidQueued`,sourceHash:`mermaidSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`mermaidTarget`},filePathLabel:`Mermaid`,loadFileSource:t,shellClassName:`mermaid-shell`,sourceClassName:`mermaid-source`}),this.currentTheme=document.documentElement?.dataset.theme===`light`?`light`:`dark`,this.diagramChrome=e.diagramChrome,this.loader=null,this.runtime=null}cancelHydration({preserveActiveShell:e=!1}={}){super.cancelHydration(),e||this.diagramChrome?.cancelActiveShell?.(`mermaid`)}applyTheme(e){this.currentTheme=e;let t=this.runtime;t&&(this.configureMermaid(t),this.resetHydratedShells())}configureMermaid(e){e.initialize({startOnLoad:!1,htmlLabels:!1,flowchart:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},theme:this.currentTheme===`dark`?`dark`:`default`,themeVariables:this.currentTheme===`dark`?{background:`#11161d`,clusterBkg:`#141a22`,edgeLabelBackground:`#11161d`,lineColor:`#9aa7b4`,mainBkg:`#171d26`,nodeBorder:`#303c4b`,primaryBorderColor:`#60a5fa`,primaryColor:`#172a45`,primaryTextColor:`#e6edf3`,secondaryColor:`#1c2530`,tertiaryColor:`#11161d`,titleColor:`#e6edf3`}:{}})}ensureMermaid(){return this.runtime?(this.configureMermaid(this.runtime),Promise.resolve(this.runtime)):(this.loader||=e(()=>import(`./mermaid.core-DN-lF51U.js`).then(e=>{let t=e?.default;if(!t)throw Error(`Mermaid runtime failed to initialize`);return this.runtime=t,this.configureMermaid(t),t}),__vite__mapDeps([3,1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]),import.meta.url).catch(e=>{throw this.loader=null,this.runtime=null,Error(e instanceof Error?e.message:`Failed to load Mermaid runtime`)}),this.loader)}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`mermaid-maximized-open`),this.diagramChrome?.syncActiveShell?.()}async prepareHydrationBatch(){return this.ensureMermaid()}handlePrepareHydrationBatchError(e,t){console.warn(`[preview] Mermaid runtime failed to load:`,t)}createRenderHost(){let e=document.createElement(`div`);return e.style.position=`fixed`,e.style.left=`-10000px`,e.style.top=`0`,e.style.width=`1200px`,e.style.visibility=`hidden`,e.style.pointerEvents=`none`,document.body.appendChild(e),e}async hydrateShell(e,t,{hydrationToken:n,renderVersion:r}={}){if(!t||!e?.isConnected||this.isShellHydrated(e)||!this.isHydrationCurrent(r,e,n))return;let i=e.querySelector(`.mermaid-source`);i||(i=document.createElement(`span`),i.className=`mermaid-source`,i.hidden=!0,e.appendChild(i));let a=i.textContent??``;try{if(!a.trim()&&e.dataset.mermaidTarget){if(a=await this.fetchSource(e.dataset.mermaidTarget),!e.isConnected)return;i.textContent=a}if(!a.trim())throw Error(e.dataset.mermaidTarget?`Mermaid file is empty`:`Mermaid source is empty`);if(!this.isHydrationCurrent(r,e,n))return;let o=a;a=this.prepareSource(a),e.querySelector(`.mermaid-placeholder-card`)?.remove();let s=document.createElement(`div`);s.className=`mermaid mermaid-render-node`,s.id=e.dataset.mermaidKey||`mermaid-${Date.now()}`;let c=e.getAttribute(`data-source-line`),l=e.getAttribute(`data-source-line-end`);c&&s.setAttribute(`data-source-line`,c),l&&s.setAttribute(`data-source-line-end`,l),s.textContent=a;let u=this.createRenderHost();try{if(u.appendChild(s),await t.run({nodes:[s]}),!this.isHydrationCurrent(r,e,n)||!s.isConnected||s.parentElement!==u)return;this.enhanceDiagram(e,s,o),this.markShellHydrated(e)}finally{u.remove()}}catch(t){if(console.warn(`[preview] Mermaid render failed:`,t),!this.isHydrationCurrent(r,e,n)||this.markShellError(e,t))return;if(this.diagramChrome?.destroyShell?.(e),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),!e.querySelector(`.mermaid-placeholder-card`)){let n=e.dataset.mermaidKey||`mermaid`,r=st(t);i?.after(mt({key:n,kind:`mermaid`,label:e.dataset.mermaidLabel||`Mermaid diagram`,message:r}))}}}prepareSource(e){let t=String(e??``);if(!/%%\{[\s\S]*?\binit\s*:/m.test(t)){let e=this.getPreviewInitConfig(t);e&&(t=`%%{init: ${JSON.stringify(e)}}%%\n${t}`)}if(!/^\s*gantt\b/m.test(t)||/\btodayMarker\b/.test(t))return t;let n=t.split(`
|
|
5
|
-
`),r=n.findIndex(e=>/^\s*gantt\b/.test(e));return r===-1?t:(n.splice(r+1,0,` todayMarker off`),n.join(`
|
|
6
|
-
`))}getPreviewInitConfig(e){return/^\s*stateDiagram(?:-v2)?\b/m.test(e)||/^\s*classDiagram\b/m.test(e)||/^\s*gantt\b/m.test(e)?{htmlLabels:!1}:null}resetHydratedShells(){let e=this.renderer.previewElement;if(!e)return;let t=Array.from(e.querySelectorAll(`.mermaid-shell[data-mermaid-hydrated="true"]`)),n=this.diagramChrome?.syncActiveShell?.();n?.classList?.contains(`mermaid-shell`)&&!t.includes(n)&&t.push(n),t.length!==0&&t.forEach(e=>{this.diagramChrome?.destroyShell?.(e),this.clearShellOutput(e),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),e.querySelector(`.mermaid-placeholder-card`)||e.querySelector(`.mermaid-source`)?.after(lt(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}async renderExportSvgMarkup(e){let t=await this.ensureMermaid();try{return await Lt(t,e._diagramRenderedSource??e.querySelector(`.mermaid-source`)?.textContent??``)}finally{this.configureMermaid(t)}}enhanceDiagram(e,t,n=``){let r=t.querySelector(`svg`);if(!r){t.remove();return}let{width:i,height:a}=ht(r);t.remove(),this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Nt({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`mermaid`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.mermaidTarget||``}),exportSvgMarkup:()=>this.renderExportSvgMarkup(e),kind:`mermaid`,sourceSelector:`.mermaid-source`}),e._diagramRenderedSource=n}},Ut=class extends Vt{constructor(e,{loadFileSource:t=null,renderClient:n=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`plantumlHydrated`,instanceId:`plantumlInstanceId`,key:`plantumlKey`,label:`plantumlLabel`,queued:`plantumlQueued`,sourceHash:`plantumlSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`plantumlTarget`},filePathLabel:`PlantUML`,loadFileSource:t,shellClassName:`plantuml-shell`,sourceClassName:`plantuml-source`}),this.diagramChrome=e.diagramChrome,this.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map}cancelHydration({preserveActiveShell:e=!1}={}){super.cancelHydration(),e||this.diagramChrome?.cancelActiveShell?.(`plantuml`)}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`plantuml-maximized-open`),this.diagramChrome?.syncActiveShell?.()}async hydrateShell(e,t,{hydrationToken:n,renderVersion:r}={}){if(!e?.isConnected||this.isShellHydrated(e)||!this.isHydrationCurrent(r,e,n))return;let i=e.querySelector(`.plantuml-source`);i||(i=document.createElement(`span`),i.className=`plantuml-source`,i.hidden=!0,e.appendChild(i)),e.querySelector(`.plantuml-placeholder-card`)?.remove();try{let t=i.textContent??``;if(!t.trim()&&e.dataset.plantumlTarget){if(t=await this.fetchSource(e.dataset.plantumlTarget),!e.isConnected)return;i.textContent=t}if(!t.trim())throw Error(e.dataset.plantumlTarget?`PlantUML file is empty`:`PlantUML source is empty`);if(!this.isHydrationCurrent(r,e,n))return;let a=await this.fetchSvg(t);if(!this.isHydrationCurrent(r,e,n))return;this.enhanceDiagram(e,a),this.markShellHydrated(e)}catch(t){if(console.warn(`[preview] PlantUML render failed:`,t),!this.isHydrationCurrent(r,e,n)||this.markShellError(e,t))return;let a=e.dataset.plantumlKey||`plantuml`,o=st(t);e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||i?.after(mt({key:a,kind:`plantuml`,label:e.dataset.plantumlLabel||`PlantUML diagram`,message:o}))}}async fetchSvg(e){let t=e;if(this.svgCache.has(t))return this.svgCache.get(t);if(this.svgInflightRequests.has(t))return this.svgInflightRequests.get(t);let n=this.renderClient.renderSvg(e).then(e=>{let n=it(e);return this.svgCache.set(t,n),n}).finally(()=>{this.svgInflightRequests.delete(t)});return this.svgInflightRequests.set(t,n),n}resetShell(e,{clearCache:t=!1,message:n=`Renders server-side when visible`}={}){let r=e.querySelector(`.plantuml-source`)?.textContent??``;t&&r&&(this.svgCache.delete(r),this.svgInflightRequests.delete(r)),this.diagramChrome?.destroyShell?.(e),this.clearShellOutput(e),e.removeAttribute(`data-plantuml-instance-id`),e.removeAttribute(`data-plantuml-queued`),e.classList.remove(`is-maximized`),this.diagramChrome?.syncBodyMaximizedClasses?.(),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||e.querySelector(`.plantuml-source`)?.after(ft(e.dataset.plantumlKey||`plantuml`,n))}enhanceDiagram(e,t){let n=document.createElement(`div`);n.innerHTML=t;let r=n.querySelector(`svg`);if(!r)throw Error(`Renderer returned invalid SVG`);let{width:i,height:a}=pt(r);this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Nt({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`plantuml`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.plantumlTarget||``}),exportSvgMarkup:()=>Pt(r),kind:`plantuml`,onReload:()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})},sourceSelector:`.plantuml-source`})}},Wt={copy:`
|
|
7
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
8
|
-
<path d="M5.5 5.5h6.8v8h-6.8z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
9
|
-
<path d="M3.7 10.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v.7" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
10
|
-
</svg>
|
|
11
|
-
`,download:`
|
|
12
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
13
|
-
<path d="M8 2.2v7.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
14
|
-
<path d="M5.3 7.2 8 10l2.7-2.8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
15
|
-
<path d="M3 12.8h10" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
16
|
-
</svg>
|
|
17
|
-
`,edit:`
|
|
18
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
19
|
-
<path d="M11.8 1.8a1.5 1.5 0 0 1 2.1 2.1l-7.2 7.2-3.2.9.9-3.2z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
20
|
-
<path d="M10.7 2.9l2.4 2.4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
21
|
-
</svg>
|
|
22
|
-
`,fit:`
|
|
23
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
24
|
-
<path d="M5.5 6.2V3H2.3M10.5 6.2V3h3.2M10.5 9.8V13h3.2M5.5 9.8V13H2.3" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
25
|
-
<path d="M5.5 6.2h5M5.5 9.8h5" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
26
|
-
</svg>
|
|
27
|
-
`,maximize:`
|
|
28
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
29
|
-
<path d="M6 2H2v4M10 2h4v4M14 10v4h-4M2 10v4h4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
30
|
-
</svg>
|
|
31
|
-
`,refresh:`
|
|
32
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
33
|
-
<path d="M13 4.5V1.8M13 1.8h-2.7M13 11.5v2.7M13 14.2h-2.7" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
34
|
-
<path d="M12.3 4.2A5.3 5.3 0 1 0 13 11.8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
35
|
-
</svg>
|
|
36
|
-
`,restore:`
|
|
37
|
-
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
38
|
-
<path d="M6 5V2H2M10 5V2h4M10 11v3h4M6 11v3H2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
39
|
-
<path d="M4.5 4.5h7v7h-7z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
40
|
-
</svg>
|
|
41
|
-
`};function z(e,t){if(!(e instanceof HTMLElement))return;let n=Wt[t];if(!n){e.classList.remove(`is-icon-only`),e.classList.remove(`ui-preview-action--icon-only`);return}e.classList.add(`is-icon-only`),e.classList.add(`ui-preview-action--icon-only`),e.dataset.icon=t,e.innerHTML=n.trim()}var Gt=Object.freeze({animationDurationMs:160,default:1,max:3,min:.1,step:.1,wheelSensitivity:.01}),Kt=Object.freeze({mermaid:{...Gt,fitMax:Gt.max,min:.5},plantuml:{...Gt,fitMax:Gt.default}}),qt=Object.freeze({mermaid:{bodyClassName:`mermaid-maximized-open`,buttonClassName:`mermaid-zoom-btn ui-preview-action`,frameClassName:`mermaid-frame diagram-preview-frame`,maximizeButtonClassName:`mermaid-maximize-btn`,maximizedRootClassName:`mermaid-maximized-root`,maximizedRootDatasetKey:`mermaidMaximizedRoot`,toolbarClassName:`mermaid-toolbar diagram-preview-toolbar`,zoomLabelClassName:`mermaid-zoom-label diagram-preview-zoom-label`},plantuml:{bodyClassName:`plantuml-maximized-open`,buttonClassName:`plantuml-tool-btn ui-preview-action`,frameClassName:`plantuml-frame diagram-preview-frame`,maximizeButtonClassName:`plantuml-maximize-btn`,maximizedRootClassName:`plantuml-maximized-root`,maximizedRootDatasetKey:`plantumlMaximizedRoot`,toolbarClassName:`plantuml-toolbar diagram-preview-toolbar`,zoomLabelClassName:`plantuml-zoom-label diagram-preview-zoom-label`}});function Jt(e){return qt[e]??qt.mermaid}function Yt(e){return Kt[e]??Kt.mermaid}function Xt(e){return e instanceof SVGSVGElement}var Zt=class{constructor({documentRef:e=document,toastController:t=null,windowRef:n=window}={}){this.document=e,this.window=n,this.toastController=t,this.activeMaximizedShell=null,this.maximizedRoots=new Map,this.resizeObservers=new Set,this.shellControllers=new WeakMap,this.shellViewStates=new WeakMap,this.shellRefits=new WeakMap}destroy(){this.destroyAllShells(),this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.maximizedRoots.forEach(e=>e.remove()),this.maximizedRoots.clear(),this.activeMaximizedShell=null}destroyAllShells(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.activeMaximizedShell=null,this.document.body.classList.remove(`mermaid-maximized-open`,`plantuml-maximized-open`)}destroyShell(e){this.shellControllers.get(e)?.destroy?.(),this.shellControllers.delete(e),this.shellViewStates.delete(e),this.shellRefits.delete(e),this.activeMaximizedShell===e&&(this.restoreShellMount(e),this.activeMaximizedShell=null),this.syncBodyMaximizedClasses()}captureShellViewState(e){let t=this.shellControllers.get(e)?.getViewState?.()??null;return t&&this.shellViewStates.set(e,t),t}getShellViewState(e){return this.shellViewStates.get(e)??this.shellControllers.get(e)?.getViewState?.()??null}cancelActiveShell(e){let t=this.syncActiveShell();if(!t?.classList?.contains(`${e}-shell`))return;let n=this.shellControllers.get(t);this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell=null,n?.syncMaximizeButtonState?.(),n?.scheduleResetZoomToFit?.({force:!0}),this.syncBodyMaximizedClasses()}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)}),this.document.body.classList.remove(`mermaid-maximized-open`,`plantuml-maximized-open`)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.activeMaximizedShell=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)}),null)}scheduleActiveRefit({kind:e=null,root:t=null}={}){let n=this.syncActiveShell();if(n){this.shellRefits.get(n)?.({force:!0});return}let r=e?`.${e}-shell[data-${e}-hydrated="true"]`:`.mermaid-shell[data-mermaid-hydrated="true"], .plantuml-shell[data-plantuml-hydrated="true"]`;Array.from(t?.querySelectorAll?.(r)??[]).forEach(e=>{this.shellRefits.get(e)?.()})}ensureMaximizedRoot(e){let t=Jt(e),n=this.maximizedRoots.get(e);if(n?.isConnected&&n.parentElement===this.document.body)return n;let r=this.document.body.querySelector(`[data-${e}-maximized-root="true"]`);return r||(r=this.document.createElement(`div`),r.dataset[t.maximizedRootDatasetKey]=`true`,r.className=t.maximizedRootClassName,this.document.body.appendChild(r)),this.maximizedRoots.set(e,r),r}mountShellInMaximizedRoot(e,t){let n=this.ensureMaximizedRoot(t);n.hidden=!1,e._diagramChromeRestoreParent=e.parentElement||null,e._diagramChromeRestoreNextSibling=e.nextSibling||null,n.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._diagramChromeRestoreParent,n=e._diagramChromeRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._diagramChromeRestoreParent=null,e._diagramChromeRestoreNextSibling=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)})}syncBodyMaximizedClasses(){let e=this.syncActiveShell();for(let[t,n]of Object.entries(qt))this.document.body.classList.toggle(n.bodyClassName,!!e?.classList?.contains(`${t}-shell`))}createButton(e,t,n,{icon:r=``}={}){let i=Jt(e),a=this.document.createElement(`button`);return a.type=`button`,a.className=i.buttonClassName,a.setAttribute(`aria-label`,n),a.title=n,r?z(a,r):a.textContent=t,a}createToolbar({kind:e,includeReload:t=!1}){let n=Jt(e),r=this.document.createElement(`div`);r.className=n.toolbarClassName;let i=this.document.createElement(`div`);i.className=`diagram-preview-toolbar-group`;let a=this.document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let o=this.createButton(e,`−`,`Zoom out`),s=this.createButton(e,`+`,`Zoom in`),c=this.createButton(e,``,`Reset zoom`,{icon:`fit`}),l=this.createButton(e,``,`Copy image`,{icon:`copy`}),u=this.createButton(e,``,`Download SVG`,{icon:`download`}),d=t?this.createButton(e,``,`Reload diagram`,{icon:`refresh`}):null,f=this.createButton(e,``,`Maximize diagram`,{icon:`maximize`});f.classList.add(n.maximizeButtonClassName);let p=this.document.createElement(`span`);return p.className=n.zoomLabelClassName,p.setAttribute(`aria-live`,`polite`),i.append(o,p,c,s),a.append(l,u),d&&a.append(d),a.append(f),r.append(i,a),{copyButton:l,decreaseButton:o,downloadButton:u,increaseButton:s,maximizeButton:f,reloadButton:d,resetButton:c,toolbar:r,zoomLabel:p}}attachShellResizeObserver(e,t,n){if(typeof ResizeObserver!=`function`||!e?.isConnected||!(t instanceof HTMLElement))return null;let r=new ResizeObserver(()=>n());return r.observe(t),r.observe(e),this.resizeObservers.add(r),r}async copyExportImage(e,t){try{let{pngFileName:n}=t(),r=await Rt(await e());try{await zt(r),this.toastController?.show?.(`Diagram copied`)}catch{we(r,n),this.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.toastController?.show?.(`Failed to copy diagram`)}}async downloadExportSvg(e,t){try{let{svgFileName:n}=t(),r=new Blob([await e()],{type:`image/svg+xml;charset=utf-8`});we(r,n),this.toastController?.show?.(`Diagram download started`)}catch{this.toastController?.show?.(`Failed to download diagram`)}}syncMaximizeButtonState(e,t){let n=e.classList.contains(`is-maximized`);z(t,n?`restore`:`maximize`);let r=n?`Restore diagram size`:`Maximize diagram`;t.setAttribute(`aria-label`,r),t.title=r}setMaximizedState(e,t,n,r,i){if(i){let i=this.syncActiveShell();if(i&&i!==e){let e=this.shellControllers.get(i);this.restoreShellMount(i),i.classList.remove(`is-maximized`),this.activeMaximizedShell=null,e?.scheduleResetZoomToFit?.({force:!0}),e?.syncMaximizeButtonState?.()}this.mountShellInMaximizedRoot(e,t),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,this.syncMaximizeButtonState(e,n),this.syncBodyMaximizedClasses(),r({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&(this.activeMaximizedShell=null),this.syncMaximizeButtonState(e,n),this.syncBodyMaximizedClasses(),r({force:!0})}mount(e,{baseHeight:t,baseWidth:n,diagramElement:r,exportFileNames:i,exportSvgMarkup:a,kind:o,onReload:s=null,sourceSelector:c}={}){if(!e?.isConnected||!Xt(r))return null;let l=Jt(o),u=Yt(o),d=e.querySelector(l.frameClassName.split(` `).map(e=>`.${e}`).join(``)),f=d?ut(d).width:0,p=this.getShellViewState(e);this.destroyShell(e);let{copyButton:m,decreaseButton:h,downloadButton:g,increaseButton:_,maximizeButton:v,reloadButton:y,resetButton:ee,toolbar:te,zoomLabel:b}=this.createToolbar({includeReload:typeof s==`function`,kind:o}),S=this.document.createElement(`div`);S.className=l.frameClassName;let ne=!!(p&&(p.scrollLeft>0||p.scrollTop>0)),C=!!(ne&&d?.isConnected&&d.clientWidth>0&&d.clientHeight>0),w=!!(C&&!e.classList.contains(`is-maximized`)&&!e.style.position);w&&(e.style.position=`relative`),ne&&!C&&(S.style.visibility=`hidden`),C&&Object.assign(S.style,{height:`${d.clientHeight}px`,left:`0`,pointerEvents:`none`,position:`absolute`,top:`0`,visibility:`hidden`,width:`${d.clientWidth}px`});let T=u.default,E=null,D=null,O=null,k=null,A=null,j=!!(p?.hasManualZoom||p?.scrollLeft>0||p?.scrollTop>0),M=f>0&&Number.isFinite(n)&&n>0,N=Number.isFinite(p?.zoom),re=M?f:0,ie=!1;r.style.maxWidth=`none`;let ae=()=>{let e=ut(S);if(!Number.isFinite(n)||n<=0||e.width<=0)return u.default;let t=e.width/n;return!Number.isFinite(t)||t<=0?u.default:x(t,u.min,u.fitMax)},P=e=>{T=x(e,u.min,u.max),r.style.width=`${n*T}px`,r.style.height=`${t*T}px`,b.textContent=`${Math.round(T*100)}%`,h.disabled=T<=u.min,_.disabled=T>=u.max},oe=N?x(p.zoom,u.min,u.max):M?x(f/n,u.min,u.fitMax):u.default,se=()=>({x:S.scrollLeft+S.clientWidth/2,y:S.scrollTop+S.clientHeight/2}),ce=(e,t,n,r)=>{if(e===0)return;let i=t/e;S.scrollLeft=n.x*i-r.x,S.scrollTop=n.y*i-r.y},le=(e,t,n)=>{ce(e,t,n,{x:S.clientWidth/2,y:S.clientHeight/2})},ue=e=>{let t=x(e,u.min,u.max);if(E){D=t;return}let n=T;if(t===n)return;D=t;let r=se(),i=performance.now(),a=e=>{let t=x((e-i)/u.animationDurationMs,0,1),o=ot(t),s=n+(D-n)*o;if(P(s),le(n,s,r),t<1){E=this.window.requestAnimationFrame(a);return}E=null;let c=D;D=null,P(c),le(n,c,r)};E=this.window.requestAnimationFrame(a)},F=()=>{E&&=(this.window.cancelAnimationFrame(E),null),D=null},de=e=>{j=!0,ue((D??T)+e)},fe=()=>{let e=ae();j=!1,re=ut(S).width,A=null,F(),P(e),S.scrollLeft=0,S.scrollTop=0},I=({force:t=!1}={})=>{ie||=t,O&&this.window.cancelAnimationFrame(O),O=this.window.requestAnimationFrame(()=>{if(O=null,!e.isConnected)return;let t=ie;ie=!1;let n=ut(S).width,r=Math.abs(n-re)>1;!t&&j||!t&&n>0&&re>0&&!r||fe()})},pe=this.attachShellResizeObserver(e,S,()=>I()),me=(e,t)=>{let n=S.getBoundingClientRect();return{x:Number(e)-n.left,y:Number(t)-n.top}},he=e=>{if(!e||e.length!==2)return null;let t=e[0],n=e[1],r=me((t.clientX+n.clientX)/2,(t.clientY+n.clientY)/2),i=Math.hypot(n.clientX-t.clientX,n.clientY-t.clientY);return!Number.isFinite(i)||i<=0?null:{center:r,distance:i}},ge=e=>{let t=he(e);return t?(F(),A={contentPoint:{x:S.scrollLeft+t.center.x,y:S.scrollTop+t.center.y},distance:t.distance,zoom:T},!0):!1},_e=e=>{let t=he(e);return!t||!A&&!ge(e)?!1:(j=!0,P(A.zoom*(t.distance/A.distance)),ce(A.zoom,T,A.contentPoint,t.center),!0)};h.addEventListener(`click`,()=>de(-u.step)),_.addEventListener(`click`,()=>de(u.step)),S.addEventListener(`wheel`,e=>{if(!e.ctrlKey)return;e.preventDefault();let t=Number.isFinite(e.deltaY)?e.deltaY:0,n=x(-t*u.wheelSensitivity,-u.step/2,u.step/2);n!==0&&de(n)},{passive:!1}),S.addEventListener(`touchstart`,e=>{e.touches.length===2&&ge(e.touches)},{passive:!0}),S.addEventListener(`touchmove`,e=>{e.touches.length===2&&_e(e.touches)&&e.preventDefault()},{passive:!1});let ve=e=>{e.touches.length!==2&&(A=null)};S.addEventListener(`touchend`,ve),S.addEventListener(`touchcancel`,ve),ee.addEventListener(`click`,()=>{I({force:!0})}),m.addEventListener(`click`,()=>this.copyExportImage(a,i)),g.addEventListener(`click`,()=>this.downloadExportSvg(a,i)),y?.addEventListener(`click`,()=>s()),v.addEventListener(`click`,()=>{this.setMaximizedState(e,o,v,I,!e.classList.contains(`is-maximized`))}),S.appendChild(r);let ye=c?e.querySelector(c):null,be=ye?[ye,te,S]:[te,S];ye&&(ye.hidden=!0),C?e.append(S):e.replaceChildren(...be),P(oe);let xe=()=>{let e=Math.max(0,S.scrollWidth-S.clientWidth),t=Math.max(0,S.scrollHeight-S.clientHeight),n=x(p.scrollLeft??0,0,e),r=x(p.scrollTop??0,0,t);return S.scrollLeft=n,S.scrollTop=r,S.clientWidth>0&&S.clientHeight>0&&S.scrollLeft===n&&S.scrollTop===r};C?(xe(),k=this.window.requestAnimationFrame(()=>{k=null,e.replaceChildren(...be),S.removeAttribute(`style`),w&&(e.style.position=``),P(oe),xe()})):ne&&(xe()?S.style.visibility=``:this.window.requestAnimationFrame(()=>{S.isConnected&&(xe(),S.style.visibility=``)}));let Se={destroy:()=>{E&&this.window.cancelAnimationFrame(E),O&&this.window.cancelAnimationFrame(O),k&&this.window.cancelAnimationFrame(k),pe?.disconnect?.(),this.resizeObservers.delete(pe)},getViewState:()=>({hasManualZoom:j,scrollLeft:S.scrollLeft,scrollTop:S.scrollTop,zoom:T}),scheduleResetZoomToFit:I,syncMaximizeButtonState:()=>this.syncMaximizeButtonState(e,v)};return this.shellControllers.set(e,Se),this.shellRefits.set(e,I),this.syncMaximizeButtonState(e,v),!M&&!N&&I({force:!0}),Se}};function Qt(){return new Worker(new URL(``+new URL(`preview-render-worker-CiPqc9n6.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var $t=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=L,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-BKedaMxx.js`),__vite__mapDeps([24,25,26,6,27,28,29]),import.meta.url),createWorkerFn:i=Qt,getFileList:a,getSourceFilePath:o=null,getWikiLinkAutoCreate:s=null,idleTimeoutMs:c=500,requestIdleRenderFn:l=Te}={}){this.attachmentApiPath=t,this.cancelIdleRenderFn=n,this.compilePreviewDocumentLoader=r,this.createWorkerFn=i,this.getFileList=a,this.getSourceFilePath=o,this.getWikiLinkAutoCreate=s,this.idleTimeoutMs=c,this.requestIdleRenderFn=l,this.worker=null,this.workerDisabled=!1,this.workerJob=null,this.workerPrewarmId=null,this.handleWorkerMessage=e=>{if(!this.workerJob||e.data?.renderVersion!==this.workerJob.renderVersion)return;let t=this.workerJob;if(this.workerJob=null,e.data?.error){t.reject(Error(e.data.error));return}t.resolve({html:e.data.html,stats:e.data.stats})},this.handleWorkerError=e=>{let t=Error(e.message||`Preview worker failed`);this.workerJob&&=(this.workerJob.reject(t),null),this.reset(`Preview worker failed`,{disable:!0})}}hasPendingJob(){return this.workerJob!==null}schedulePrewarm({timeout:e=this.idleTimeoutMs}={}){this.workerDisabled||this.worker||this.workerPrewarmId!==null||(this.workerPrewarmId=this.requestIdleRenderFn(()=>{this.workerPrewarmId=null,this.ensureWorker()},e))}ensureWorker(){if(this.workerDisabled)return null;if(this.worker)return this.worker;try{return this.worker=this.createWorkerFn(),this.worker.addEventListener(`message`,this.handleWorkerMessage),this.worker.addEventListener(`error`,this.handleWorkerError),this.worker}catch{return this.workerDisabled=!0,null}}async compile(e,t,{frontmatterCollapsed:n=!1,frontmatterInteractive:r=!1}={}){if(this.ensureWorker()){this.workerJob&&this.reset(`Superseded preview render`);let i=this.ensureWorker();return new Promise((a,o)=>{this.workerJob={reject:o,renderVersion:t,resolve:a},i.postMessage({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,renderVersion:t,sourceFilePath:this.getSourceFilePath?.()??``,wikiLinkAutoCreate:this.getWikiLinkAutoCreate?.()??!0})})}let{compilePreviewDocument:i}=await this.compilePreviewDocumentLoader();return i({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,sourceFilePath:this.getSourceFilePath?.()??``,wikiLinkAutoCreate:this.getWikiLinkAutoCreate?.()??!0})}cancelWorkerJob(e){this.workerJob&&=(this.workerJob.reject(Error(e)),null)}reset(e,{disable:t=!1}={}){this.cancelWorkerJob(e),this.worker&&=(this.worker.removeEventListener(`message`,this.handleWorkerMessage),this.worker.removeEventListener(`error`,this.handleWorkerError),this.worker.terminate(),null),t&&(this.workerDisabled=!0)}destroy(e=`Preview renderer destroyed`){this.workerPrewarmId!==null&&this.cancelIdleRenderFn(this.workerPrewarmId),this.workerPrewarmId=null,this.reset(e)}},en=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=L,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:r=ee,idleTimeoutMs:i=500,requestAnimationFrameFn:a=e=>requestAnimationFrame(e),requestIdleRenderFn:o=Te,setTimeoutFn:s=(e,t)=>setTimeout(e,t)}={}){this.cancelAnimationFrameFn=e,this.cancelIdleRenderFn=t,this.clearTimeoutFn=n,this.getRenderProfileFn=r,this.idleTimeoutMs=i,this.requestAnimationFrameFn=a,this.requestIdleRenderFn=o,this.setTimeoutFn=s,this.frameId=null,this.idleId=null,this.timeoutId=null}queue({markdownText:e,onRenderRequested:t,renderVersion:n}){let r=this.getRenderProfileFn(e);this.cancel();let i=()=>{this.frameId=this.requestAnimationFrameFn(()=>{this.frameId=null,this.timeoutId=null,t?.(e,n)})},a=()=>{if(r.deferUntilIdle){this.idleId=this.requestIdleRenderFn(()=>{this.idleId=null,i()},this.idleTimeoutMs);return}i()};this.timeoutId=this.setTimeoutFn(a,r.debounceMs)}cancel(){this.clearTimeoutFn(this.timeoutId),this.frameId&&this.cancelAnimationFrameFn(this.frameId),this.cancelIdleRenderFn(this.idleId),this.frameId=null,this.idleId=null,this.timeoutId=null}destroy(){this.cancel()}},tn=class{constructor({getContent:e,getFileList:t,getSourceFilePath:n,getWikiLinkAutoCreate:r=null,loadFileSource:i=null,onAfterRenderCommit:a,onBeforeRenderCommit:o,onPreviewLayoutChange:s,onRenderComplete:c,outlineController:l,plantUmlRenderClient:u=null,previewContainer:d,previewElement:f,toastController:p=null}){this.getContent=e,this.getFileList=t,this.getSourceFilePath=n,this.getWikiLinkAutoCreate=r,this.loadFileSource=i,this.onAfterRenderCommit=a,this.onBeforeRenderCommit=o,this.onPreviewLayoutChange=s,this.onRenderComplete=c,this.outlineController=l,this.plantUmlRenderClient=u,this.previewContainer=d,this.previewElement=f,this.toastController=p,this.renderHost=null,this.pendingRenderVersion=0,this.activeRenderVersion=0,this.readyRenderVersion=0,this.currentStats=null,this.isLargeDocument=!1,this.hydrationPaused=!1,this.frontmatterCollapsed=!1,this.handlePreviewClick=e=>{if(e.target.closest(`.frontmatter-toggle`)){e.preventDefault(),this.frontmatterCollapsed=!this.frontmatterCollapsed,this.applyFrontmatterState(),this.handleFrontmatterLayoutChange();return}let t=e.target.closest(`.mermaid-placeholder-btn`);if(t){let n=t.closest(`.mermaid-shell`);if(!n)return;e.preventDefault(),t.closest(`.diagram-preview-error-card`)?this.mermaidHydrator.retryShell(n):this.mermaidHydrator.enqueueShell(n,{prioritize:!0});return}let n=e.target.closest(`.plantuml-placeholder-btn`);if(n){let t=n.closest(`.plantuml-shell`);if(!t)return;e.preventDefault(),n.closest(`.diagram-preview-error-card`)?this.plantUmlHydrator.retryShell(t):this.plantUmlHydrator.enqueueShell(t,{prioritize:!0})}},this.handleWindowResize=()=>{this.scheduleActiveMermaidRefit(),this.scheduleActivePlantUmlRefit()},this.diagramChrome=new Zt({toastController:p}),this.mermaidHydrator=new Ht(this,{loadFileSource:i}),this.plantUmlHydrator=new Ut(this,{loadFileSource:i,renderClient:u}),this.renderScheduler=new en({getRenderProfileFn:ee}),this.renderExecutor=new $t({attachmentApiPath:F(`/attachment`),getFileList:()=>this.getFileList?.()??[],getSourceFilePath:()=>this.getSourceFilePath?.()??``,getWikiLinkAutoCreate:()=>this.getWikiLinkAutoCreate?.()??!0,idleTimeoutMs:500}),this.previewElement?.addEventListener(`click`,this.handlePreviewClick),window.addEventListener(`resize`,this.handleWindowResize),this.setPhase(`ready`)}ensureRenderHost(){if(!this.previewElement)return null;if(this.renderHost?.isConnected&&this.renderHost.parentElement===this.previewElement)return this.renderHost;let e=this.previewElement.querySelector(`[data-preview-render-host="true"]`);return e||(e=document.createElement(`div`),e.dataset.previewRenderHost=`true`,this.previewElement.appendChild(e)),this.renderHost=e,this.renderHost}normalizePreviewChildren(e=this.renderHost){this.previewElement&&Array.from(this.previewElement.children).forEach(t=>{t!==e&&t.dataset.drawioOverlayRoot!==`true`&&t.dataset.excalidrawOverlayRoot!==`true`&&t.dataset.videoOverlayRoot!==`true`&&t.remove()})}getReservedPreviewHeight(){let e=this.renderHost?.getBoundingClientRect?.().height??0,t=this.previewContainer?.clientHeight??0;return Math.max(Math.round(e),Math.round(t),320)}beginDocumentLoad(){this.renderScheduler.cancel(),this.mermaidHydrator.cancelHydration(),this.plantUmlHydrator.cancelHydration(),this.mermaidHydrator.clearPreservedShells(),this.plantUmlHydrator.clearPreservedShells(),this.diagramChrome.clearActiveShell(),this.onBeforeRenderCommit?.(this.previewElement),this.pendingRenderVersion+=1,this.activeRenderVersion=this.pendingRenderVersion,this.readyRenderVersion=0,this.currentStats=null,this.isLargeDocument=!1,this.frontmatterCollapsed=!1,this.renderExecutor.hasPendingJob()&&this.renderExecutor.reset(`Document changed`);let e=this.ensureRenderHost();this.normalizePreviewChildren(e);let t=this.getReservedPreviewHeight();e&&(e.replaceChildren(),e.style.minHeight=`${t}px`);let n=document.createElement(`div`);n.className=`preview-shell`,n.style.minHeight=`${t}px`,n.textContent=`Rendering preview…`,e?.append(n),this.setPhase(`shell`)}applyTheme(e){let t=document.getElementById(`hljs-theme`);if(t){let{darkHref:n,lightHref:r}=t.dataset;t.href=e===`dark`?n:r}this.mermaidHydrator.applyTheme(e)}queueRender(){let e=this.getContent();this.renderScheduler.cancel(),this.mermaidHydrator.markPending(),this.plantUmlHydrator.markPending(),this.pendingRenderVersion+=1;let t=this.pendingRenderVersion;this.renderScheduler.queue({markdownText:e,onRenderRequested:(e,t)=>{this.render(e,t)},renderVersion:t})}async render(e=this.getContent(),t=this.pendingRenderVersion){if(this.previewElement)try{let n=await this.renderExecutor.compile(e,t,{frontmatterCollapsed:this.frontmatterCollapsed,frontmatterInteractive:!0});if(t!==this.pendingRenderVersion)return;this.commitBaseRender(n,t)}catch(e){if(t!==this.pendingRenderVersion)return;console.warn(`[preview] Failed to render preview:`,e)}}destroy(){this.renderScheduler.destroy(),this.diagramChrome.destroy(),this.mermaidHydrator.destroy(),this.plantUmlHydrator.destroy(),this.renderExecutor.destroy(),this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),window.removeEventListener(`resize`,this.handleWindowResize)}setPhase(e){this.previewElement&&(this.previewElement.dataset.renderPhase=e)}scheduleActiveMermaidRefit(){this.diagramChrome.scheduleActiveRefit({kind:`mermaid`,root:this.previewElement})}scheduleActivePlantUmlRefit(){this.diagramChrome.scheduleActiveRefit({kind:`plantuml`,root:this.previewElement})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){this.mermaidHydrator.cancelPendingIdleWork(),this.plantUmlHydrator.cancelPendingIdleWork();return}this.mermaidHydrator.hydrateVisibleShells(),this.mermaidHydrator.scheduleHydration(),this.plantUmlHydrator.hydrateVisibleShells(),this.plantUmlHydrator.scheduleHydration(),this.updateHydrationPhase()}scheduleWorkerPrewarm({timeout:e=500}={}){this.renderExecutor.schedulePrewarm({timeout:e})}commitBaseRender({html:e,stats:t},n){this.activeRenderVersion=n,this.readyRenderVersion=0,this.currentStats=t,this.isLargeDocument=te(t),this.mermaidHydrator.cancelHydration({preserveActiveShell:!0}),this.plantUmlHydrator.cancelHydration({preserveActiveShell:!0}),document.body.classList.remove(`mermaid-maximized-open`),document.body.classList.remove(`plantuml-maximized-open`),this.mermaidHydrator.preserveHydratedShellsForCommit(),this.plantUmlHydrator.preserveHydratedShellsForCommit(),this.onBeforeRenderCommit?.(this.previewElement);let r=this.ensureRenderHost();this.normalizePreviewChildren(r),r&&(r.innerHTML=e),this.applyFrontmatterState(),this.mermaidHydrator.reconcileHydratedShells(),this.plantUmlHydrator.reconcileHydratedShells(),this.setPhase(`base`),this.outlineController.refresh(),this.onAfterRenderCommit?.(this.previewElement,{...t,isLargeDocument:this.isLargeDocument,renderVersion:n});let i=this.mermaidHydrator.setupHydration(n),a=this.plantUmlHydrator.setupHydration(n);i===0&&a===0&&this.notifyReady()}applyFrontmatterState(){let e=this.renderHost?.querySelector?.(`.frontmatter-block`);if(!(e instanceof HTMLElement))return;let t=this.frontmatterCollapsed,n=e.querySelector(`.frontmatter-toggle`),r=e.querySelector(`.frontmatter-summary`),i=e.querySelector(`.frontmatter-content`);e.dataset.collapsed=t?`true`:`false`,n instanceof HTMLButtonElement&&(n.setAttribute(`aria-expanded`,t?`false`:`true`),n.textContent=t?`Show`:`Hide`),r instanceof HTMLElement&&(r.hidden=!t),i instanceof HTMLElement&&(i.hidden=t)}handleFrontmatterLayoutChange(){this.outlineController.refresh(),this.onPreviewLayoutChange?.({isLargeDocument:this.isLargeDocument,renderVersion:this.activeRenderVersion,stats:this.currentStats})}updateHydrationPhase(){if(this.hydrationPaused&&(this.mermaidHydrator.hasPendingWork()||this.plantUmlHydrator.hasPendingWork())){this.setPhase(`base`);return}if(this.mermaidHydrator.hasPendingWork()||this.plantUmlHydrator.hasPendingWork()){this.setPhase(`hydrating`);return}this.notifyReady()}notifyReady(){this.renderHost&&(this.renderHost.style.minHeight=``),this.setPhase(`ready`),this.readyRenderVersion!==this.activeRenderVersion&&(this.readyRenderVersion=this.activeRenderVersion,this.onRenderComplete?.({isLargeDocument:this.isLargeDocument,stats:this.currentStats}))}};async function nn(e){if(e.quickSwitcher)return e.quickSwitcher;e.quickSwitcherModulePromise||=e.loadQuickSwitcherController();let t;try{t=await e.quickSwitcherModulePromise}catch(t){throw e.quickSwitcherModulePromise=null,console.error(`[quick-switcher] Failed to load file search.`,t),e.toastController?.show?.(`Failed to load file search. Try again.`,{dismissible:!0}),t}return e.quickSwitcher||=new t({getFileList:()=>e.fileExplorer.flatFiles,getFileMetadata:()=>e.fileExplorer.fileEntries,getRecentFiles:()=>e.preferences?.getRecentFiles?.()??[],getSearchConfig:()=>e.runtimeConfig.search??{},onFileSelect:t=>e.workspaceRouteController.handleFileSelection(t,{closeSidebarOnMobile:!0,revealInTree:!0}),onTextMatchSelect:t=>{t?.file&&e.navigation.navigateToFile(t.file,{column:t.column,drawioMode:t.kind===`drawio`?`text`:null,line:t.line,matchLength:t.matchLength})},searchText:t=>e.vaultApiClient.searchText(t)}),e.quickSwitcher}async function rn(e){try{(await nn(e)).toggle()}catch{}}var an=class{constructor({backlinksPanel:e,clearInitialFileBootstrap:t,clearStaticPreviewDocument:n=null,closeSidebarOnMobile:r,drawioEmbed:i,elements:a,excalidrawEmbed:o,fileHistoryView:s=null,fileExplorer:c,getIsTabActive:l,getSessionLoadToken:u,gitDiffView:d,gitPanel:f,imageLightbox:p=null,lobby:m,navigation:h,previewRenderer:g,renderAvatars:_,renderPresence:v,requestPreviewRouteAnchor:y=null,resetPreviewMode:ee,scrollSyncController:te,setSession:b,setSessionLoadToken:x,setSidebarTab:S,setSidebarVisibility:ne,setCurrentFilePath:C,showGitCommit:w,showGitDiff:T,showGitFileHistory:E,showGitFilePreview:D,showGitHistory:O,syncMainChrome:k,videoEmbed:A,workspaceCoordinator:j,layoutController:M}){this.backlinksPanel=e,this.clearInitialFileBootstrap=t,this.clearStaticPreviewDocument=n,this.closeSidebarOnMobile=r,this.drawioEmbed=i??{setHydrationPaused(){}},this.elements=a,this.excalidrawEmbed=o,this.fileHistoryView=s,this.fileExplorer=c,this.getIsTabActive=l,this.getSessionLoadToken=u,this.gitDiffView=d,this.gitPanel=f,this.imageLightbox=p,this.lobby=m,this.navigation=h,this.previewRenderer=g,this.renderAvatars=_,this.renderPresence=v,this.requestPreviewRouteAnchor=y,this.resetPreviewMode=ee,this.scrollSyncController=te,this.setSession=b,this.setSessionLoadToken=x,this.setSidebarTab=S,this.setSidebarVisibility=ne??(()=>{}),this.setCurrentFilePath=C,this.showGitCommit=w,this.showGitDiff=T,this.showGitFileHistory=E,this.showGitFilePreview=D,this.showGitHistory=O,this.syncMainChrome=k,this.videoEmbed=A,this.workspaceCoordinator=j,this.layoutController=M,this.pendingTreeRevealPath=null,this.preserveSidebarTabRoutePath=null}async handleHashChange(){if(!this.getIsTabActive())return;let e=this.navigation.getHashRoute(),t=e.type===`file`?e.filePath:null;if(await this.prepareActiveExcalidrawDisconnect(t)){if(e.type===`empty`){this.requestPreviewRouteAnchor?.(null),this.gitPanel.setSelection(),this.showEmptyState(),this.syncMainChrome({mode:`empty`,title:`CollabMD`});return}if(e.type===`git-diff`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitDiff(e);return}if(e.type===`git-file-history`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`files`),await this.showGitFileHistory(e);return}if(e.type===`git-file-preview`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`files`),await this.showGitFilePreview(e);return}if(e.type===`git-history`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitHistory();return}if(e.type===`git-commit`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitCommit(e);return}this.preserveSidebarTabRoutePath===e.filePath?this.preserveSidebarTabRoutePath=null:(this.preserveSidebarTabRoutePath=null,this.setSidebarTab(`files`)),await this.openFile(e.filePath,{drawioMode:e.drawioMode||null})&&(this.revealEditorMatch(e),this.requestPreviewRouteAnchor?.(e.anchor??null,e.filePath))}}showEmptyState(){this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.workspaceCoordinator.cleanupSession(),this.clearStaticPreviewDocument?.(),this.setSession(null),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.resetPreviewMode(),this.elements.outlineToggle?.classList.remove(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.setCurrentFilePath(null),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(null),this.elements.emptyState?.classList.remove(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear(),this.elements.activeFileName&&(this.elements.activeFileName.textContent=`CollabMD`)}showDiffState(){this.fileHistoryView?.hide?.(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(null),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(null),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.remove(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.outlineToggle?.classList.add(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}showFileHistoryState(e){this.gitDiffView.hide(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(e),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(e),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.remove(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.outlineToggle?.classList.add(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}showPreviewOnlyState(e){this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(e),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(e),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.remove(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}async openFile(e,t={}){let n=this.pendingTreeRevealPath===e;return n&&(this.pendingTreeRevealPath=null),this.imageLightbox?.close?.(),this.gitPanel.setSelection(),this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.clearStaticPreviewDocument?.(),this.syncMainChrome({mode:`editor`}),await this.workspaceCoordinator.openFile(e,t),this.setSession(this.workspaceCoordinator.getSession()),n&&this.revealFileInTree(e,{clearSearch:!0}),!0}async prepareActiveExcalidrawDisconnect(e=null){let t=this.workspaceCoordinator.stateStore?.get?.(`currentFilePath`)||null;return t&&t!==e&&this.workspaceCoordinator.isExcalidrawFile?.(t)&&!await this.excalidrawEmbed.prepareFileDisconnect(t,{timeoutMs:1e4})?(this.navigation.navigateToFile(t),!1):!0}preserveSidebarTabForNextFileRoute(e){this.preserveSidebarTabRoutePath=e||null}cleanupSession(){this.workspaceCoordinator.cleanupSession(),this.setSession(this.workspaceCoordinator.getSession())}handleFileSelection(e,{closeSidebarOnMobile:t=!1,revealInTree:n=!1}={}){let r=this.navigation.getHashRoute?.()??null,i=r?.type===`file`&&r.filePath===e&&!r.drawioMode;if(n&&(this.pendingTreeRevealPath=e,i)){this.pendingTreeRevealPath=null,this.revealFileInTree(e,{clearSearch:!0});return}t&&!n&&this.closeSidebarOnMobile(),this.navigation.navigateToFile(e)}revealFileInTree(e,{clearSearch:t=!1}={}){this.setSidebarTab(`files`),this.setSidebarVisibility(!0),this.fileExplorer.revealFile?.(e,{clearSearch:t})}revealEditorMatch(e={}){if(!Number.isFinite(e.line))return!1;let t=this.workspaceCoordinator.getSession?.();return t?.revealSearchMatch?.({column:e.column,length:e.matchLength,line:e.line})??t?.scrollToLine?.(e.line,.2)??!1}resetPreviewSurface(){this.imageLightbox?.close?.(),this.previewRenderer.setHydrationPaused(!1),this.drawioEmbed.setHydrationPaused(!1),this.excalidrawEmbed.setHydrationPaused(!1),this.videoEmbed?.detachForCommit(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks()}},on=class{constructor({getFileList:e,navigation:t,refreshExplorer:n,toastController:r,vaultApiClient:i,wikiLinkAutoCreate:a=!0}){this.getFileList=e,this.navigation=t,this.refreshExplorer=n,this.toastController=r,this.vaultApiClient=i,this.wikiLinkAutoCreate=a}handleWikiLinkClick(e){let t=y(e,this.getFileList());if(t){this.navigation.navigateToFile(t);return}if(!this.wikiLinkAutoCreate){this.toastController.show(`Wiki-link target does not exist`);return}let n=this.normalizeNewWikiFilePath(e);if(!n){this.toastController.show(`Cannot create an empty wiki-link target`);return}this.createAndOpenFile(n,e)}normalizeNewWikiFilePath(e){let t=k(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:re(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},sn=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:r,elements:i,excalidrawEmbed:a,getDisplayName:o,getSession:s,isDrawioFile:c,isExcalidrawFile:l,isBaseFile:u,isImageFile:d,isPdfFile:f,isMermaidFile:p,isPlantUmlFile:m,layoutController:h,outlineController:g,previewRenderer:_,pdfPreview:v=null,schedulePreviewLayoutSync:y,scrollSyncController:ee,structurizrPreview:te=null,videoEmbed:b}){this.backlinksPanel=e,this.basesPreview=t??{reconcileEmbeds(){},renderStandalone(){}},this.drawioEmbed=r??{detachForCommit(){},hydrateVisibleEmbeds(){},reconcileEmbeds(){},setHydrationPaused(){},syncLayout(){},updateLocalUser(){},updateTheme(){}},this.elements=i,this.excalidrawEmbed=a,this.getDisplayName=o,this.getSession=s,this.isDrawioFile=c??(()=>!1),this.isExcalidrawFile=l??(()=>!1),this.isBaseFile=u??n,this.isImageFile=d??(()=>!1),this.isPdfFile=f??(()=>!1),this.isMermaidFile=p??(()=>!1),this.isPlantUmlFile=m??(()=>!1),this.layoutController=h,this.outlineController=g,this.previewRenderer=_,this.pdfPreview=v??{cancel(){},render(){}},this.schedulePreviewLayoutSyncCallback=y,this.scrollSyncController=ee,this.structurizrPreview=te??{queueSync(){},render:async()=>!1,reset(){}},this.videoEmbed=b}createDiagramPreviewDocument(e,t=``){let n=String(t??``),r=Math.max(...n.match(/`+/g)?.map(e=>e.length)??[0]),i="`".repeat(Math.max(3,r+1));return`${i}${e}\n${n}\n${i}`}getPreviewSource(e,{drawioMode:t=null}={}){let n=this.getSession()?.getText()??``;return this.isMermaidFile(e)?this.createDiagramPreviewDocument(`mermaid`,n):this.isPlantUmlFile(e)?this.createDiagramPreviewDocument(`plantuml`,n):this.isDrawioFile(e)&&t===`text`?this.createDiagramPreviewDocument(`xml`,n):n}resetPreviewMode(){this.pdfPreview.cancel(),this.elements.previewContainer?.classList?.remove(`is-pdf-file-preview`),this.elements.previewContent?.classList.remove(`is-drawio-file-preview`),this.elements.previewContent?.classList.remove(`is-excalidraw-file-preview`),this.elements.previewContent?.classList.remove(`is-base-file-preview`),this.elements.previewContent?.classList.remove(`is-image-file-preview`),this.elements.previewContent?.classList.remove(`is-pdf-file-preview`),this.elements.previewContent?.classList.remove(`is-mermaid-file-preview`),this.elements.previewContent?.classList.remove(`is-plantuml-file-preview`),this.elements.previewContent?.classList.remove(`is-structurizr-file-preview`),this.structurizrPreview.reset()}syncFileChrome(e,{drawioMode:t=null,preferPreviewForBase:n=!1}={}){let r=this.isDrawioFile(e),i=this.isExcalidrawFile(e),a=this.isBaseFile(e),o=this.isImageFile(e),s=this.isPdfFile(e),c=_(e),l=this.isMermaidFile(e),d=this.isPlantUmlFile(e),p=u(e),m=f(e),h=i||r&&t!==`text`;if(this.backlinksPanel.setDisplayMode?.(h?`header`:`dock`),this.elements.editorFindButton?.classList.toggle(`hidden`,!c),this.elements.markdownToolbar?.classList.toggle(`hidden`,!c),this.elements.exportMenuGroup?.classList.toggle(`hidden`,!c),this.elements.outlineToggle?.classList.toggle(`hidden`,m||o||s||a),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,d),this.elements.previewContent?.classList.toggle(`is-structurizr-file-preview`,p),p&&(this.outlineController.close(),this.backlinksPanel.clear()),r&&t!==`text`||i||o||s||a&&n){this.layoutController.setView(`preview`,{persist:!1}),this.outlineController.close(),this.backlinksPanel.clear();return}(l||d)&&(this.outlineController.close(),this.backlinksPanel.clear())}renderExcalidrawFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-excalidraw-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`excalidraw-embed-placeholder`,r.dataset.embedKey=`${e}#file-preview`,r.dataset.embedLabel=this.getDisplayName(e),r.dataset.embedTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading Excalidraw preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.excalidrawEmbed.reconcileEmbeds(t,{isLargeDocument:!1}),this.drawioEmbed.hydrateVisibleEmbeds(),this.excalidrawEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderDrawioFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-drawio-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`drawio-embed-placeholder`,r.dataset.drawioKey=`${e}#file-preview`,r.dataset.drawioLabel=this.getDisplayName(e),r.dataset.drawioMode=`edit`,r.dataset.drawioTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading draw.io preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.drawioEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderImageFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-image-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`figure`);r.className=`image-file-preview-shell`;let i=document.createElement(`img`);i.className=`image-file-preview-image`,i.alt=this.getDisplayName(e),i.src=F(`/attachment?path=${encodeURIComponent(e)}`),r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderPdfFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),this.elements.previewContainer?.classList?.add(`is-pdf-file-preview`),t.classList.add(`is-pdf-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n),n&&(this.pdfPreview.render({displayName:this.getDisplayName(e),filePath:e,renderHost:n}),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}async renderBaseFilePreview(e,{source:t=null}={}){let n=this.elements.previewContent;if(!n)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),n.classList.add(`is-base-file-preview`);let r=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(r),r&&(r.style.minHeight=``),await this.basesPreview.renderStandalone({filePath:e,renderHost:r,source:typeof t==`string`?t:this.getSession()?.getText?.()??null}),n.dataset.renderPhase=`ready`,this.outlineController.close(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(n),this.schedulePreviewLayoutSyncCallback({delayMs:0})}async renderStructurizrFilePreview(e,{source:t=null}={}){let n=this.elements.previewContent;if(!n)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),n.classList.add(`is-structurizr-file-preview`);let r=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(r),r&&(r.style.minHeight=``),await this.structurizrPreview.render({filePath:e,renderHost:r,source:typeof t==`string`?t:this.getSession()?.getText?.()??``}),n.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(n),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderTextFilePreview({content:e=``}={}){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode();let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`preview-shell`;let i=document.createElement(`pre`),a=document.createElement(`code`);a.textContent=String(e??``),i.appendChild(a),r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}createResizeHandler(e){let t=null;return()=>{clearTimeout(t),t=setTimeout(()=>{e?.(),this.schedulePreviewLayoutSyncCallback({delayMs:0})},100)}}initializePreviewLayoutObserver(e=()=>{}){if(typeof ResizeObserver!=`function`||!this.elements.previewContent)return null;let t=new ResizeObserver(()=>{e()});return t.observe(this.elements.previewContent),t}schedulePreviewLayoutSync({hydrationPaused:e,previewLayoutSyncTimer:t,setPendingPreviewLayoutSync:n,setPreviewLayoutSyncTimer:r,delayMs:i=120}){if(e){n(!0);return}clearTimeout(t),r(setTimeout(()=>{r(null);let t=!!this.getSession(),i=this.elements.previewContent?.classList?.contains?.(`is-drawio-file-preview`)??!1,a=this.elements.previewContent?.classList?.contains?.(`is-excalidraw-file-preview`)??!1;if(!(!t&&!i&&!a||!this.elements.previewContent)&&this.elements.previewContent.dataset.renderPhase!==`shell`){if(e){n(!0);return}this.videoEmbed?.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),!((i||a)&&!t)&&(this.scrollSyncController.invalidatePreviewBlocks(),this.scrollSyncController.warmPreviewBlocks({onReady:()=>{this.getSession()&&(this.scrollSyncController.realignAfterLayoutChange(),this.outlineController.scheduleActiveHeadingUpdate())}}))}},i))}handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:t,previewLayoutSyncTimer:n,setHydrationPaused:r,setPendingPreviewLayoutSync:i,setPreviewLayoutSyncTimer:a}){let o=!!e;if(r(o),this.previewRenderer.setHydrationPaused(o),this.drawioEmbed.setHydrationPaused(o),this.excalidrawEmbed.setHydrationPaused(o),o){clearTimeout(n),a(null),i(!0);return}t&&(i(!1),this.schedulePreviewLayoutSync({delayMs:0,hydrationPaused:!1,previewLayoutSyncTimer:null,setPendingPreviewLayoutSync:i,setPreviewLayoutSyncTimer:a}))}},cn=300,ln=20,un=50;function dn(e=``){let t=String(e??``).replace(/^#/,``);if(!t)return``;try{return decodeURIComponent(t)}catch{return t}}function fn(e){try{let t=e?.contentDocument,n=t?.querySelector(`.joint-layers`),r=t?.querySelector(`#diagram-viewport`),i=n?new DOMMatrixReadOnly(getComputedStyle(n).transform).a:0;return{scrollLeft:r?.scrollLeft??0,scrollTop:r?.scrollTop??0,zoom:Number.isFinite(i)&&i>0?i:null}}catch{return null}}var pn=class{constructor({enabled:e=!1,syncWorkspace:t}){this.enabled=!!e,this.syncWorkspace=t,this.iframe=null,this.shell=null,this.status=null,this.maximizeButton=null,this.filePath=null,this.viewKey=``,this.lastVersion=null,this.syncTimer=null,this.syncToken=0,this.frameFitTimer=null,this.frameHost=null,this.pendingIframe=null,this.pendingVersion=null,this.handleFrameLoad=e=>{let t=e?.currentTarget||this.iframe;if(t)try{t===this.iframe&&(this.viewKey=dn(t.contentWindow?.location?.hash||``)||this.viewKey,t.contentWindow?.addEventListener(`hashchange`,this.handleFrameHashChange)),this.prepareFrame(t)}catch{t===this.pendingIframe&&this.commitPendingIframe(t)}},this.handleFrameHashChange=()=>{try{this.viewKey=dn(this.iframe?.contentWindow?.location?.hash||``)||this.viewKey}catch{}}}setStatus(e=``,{error:t=!1}={}){this.status&&(this.status.textContent=e,this.status.hidden=!e,this.status.classList.toggle(`is-error`,t))}prepareFrame(e=this.iframe){if(!e?.contentDocument?.head){e===this.pendingIframe&&this.commitPendingIframe(e);return}e.contentWindow?.dispatchEvent(new Event(`resize`)),this.scheduleFrameFit(e,e===this.pendingIframe?()=>this.commitPendingIframe(e):null)}fitFrameToCanvas(e=this.iframe){let t=e?.contentDocument,n=t?.querySelector(`#diagram-canvas`);if(!n||e===this.pendingIframe&&!t.querySelector(`.joint-layers`))return!1;try{let t=e?.contentWindow?.structurizr?.diagram;t?.setEmbedded?.(!0),t?.resize?.(),t?.zoomToWidthOrHeight?.()}catch{}let{width:r,height:i}=n.getBoundingClientRect();return!(!r||!i)}disposeFrame(e){if(e){try{e.contentWindow?.removeEventListener?.(`hashchange`,this.handleFrameHashChange)}catch{}e.removeEventListener(`load`,this.handleFrameLoad),e.remove()}}discardPendingIframe(){this.pendingIframe&&(clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.disposeFrame(this.pendingIframe),this.pendingIframe=null,this.pendingVersion=null)}commitPendingIframe(e){if(e!==this.pendingIframe||!this.shell?.isConnected)return;let t=this.iframe,n=this.pendingVersion,r=fn(t);if(this.pendingIframe=null,this.pendingVersion=null,r?.zoom)try{e.contentWindow?.structurizr?.diagram?.zoomTo?.(r.zoom)}catch{}try{let t=e.contentDocument?.querySelector(`#diagram-viewport`);t&&r&&(t.scrollLeft=r.scrollLeft,t.scrollTop=r.scrollTop)}catch{}this.disposeFrame(t),e.style.visibility=``,e.style.pointerEvents=``,e.removeAttribute(`aria-hidden`),this.iframe=e,this.lastVersion=n;try{this.viewKey=dn(e.contentWindow?.location?.hash||``)||this.viewKey,e.contentWindow?.addEventListener(`hashchange`,this.handleFrameHashChange)}catch{}this.setStatus(``)}createIframe(){let e=document.createElement(`iframe`);return e.className=`structurizr-preview-iframe`,e.title=`Structurizr architecture diagram`,e.loading=`eager`,e.referrerPolicy=`same-origin`,e.addEventListener(`load`,this.handleFrameLoad),e}syncMaximizeButtonState(){if(!this.maximizeButton||!this.shell)return;let e=this.shell.classList.contains(`is-maximized`);z(this.maximizeButton,e?`restore`:`maximize`);let t=e?`Restore diagram size`:`Maximize diagram`;this.maximizeButton.title=t,this.maximizeButton.setAttribute(`aria-label`,t)}setMaximized(e){let t=!!e;this.shell?.classList.toggle(`is-maximized`,t),document.body?.classList.toggle(`structurizr-maximized-open`,t),this.syncMaximizeButtonState(),this.iframe?.contentWindow?.dispatchEvent(new Event(`resize`))}scheduleFrameFit(e=this.iframe,t=null){if(!e)return;clearTimeout(this.frameFitTimer);let n=0,r=()=>{if(this.frameFitTimer=null,this.fitFrameToCanvas(e)||n>=ln){t?.();return}n+=1,this.frameFitTimer=setTimeout(r,un)};r()}mount(e,t){if(this.filePath&&this.filePath!==t&&(this.setMaximized(!1),this.discardPendingIframe(),this.disposeFrame(this.iframe),this.iframe=null,this.lastVersion=null,this.viewKey=``),this.filePath=t,this.shell?.isConnected&&this.shell.parentElement===e)return;clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.shell=document.createElement(`section`),this.shell.className=`structurizr-preview-shell diagram-preview-shell`,this.shell.dataset.structurizrPreview=`true`;let n=document.createElement(`div`);n.className=`structurizr-preview-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`structurizr-preview-label`,r.textContent=String(t).split(`/`).pop()?.replace(/\.dsl$/i,``)||`Structurizr`,this.maximizeButton=document.createElement(`button`),this.maximizeButton.type=`button`,this.maximizeButton.className=`structurizr-preview-btn ui-preview-action ui-preview-action--icon-only`,this.maximizeButton.dataset.action=`toggle-maximize`,this.maximizeButton.addEventListener(`click`,e=>{e.preventDefault(),this.setMaximized(!this.shell?.classList.contains(`is-maximized`))}),n.append(r,this.maximizeButton),this.syncMaximizeButtonState(),this.status=document.createElement(`div`),this.status.className=`structurizr-preview-status`,this.status.setAttribute(`aria-live`,`polite`),this.status.setAttribute(`role`,`status`),this.status.hidden=!0,this.frameHost=document.createElement(`div`),this.frameHost.className=`structurizr-preview-stage`,this.shell.append(n,this.status,this.frameHost),e?.replaceChildren(this.shell),this.iframe=null,this.pendingIframe=null,this.pendingVersion=null,this.lastVersion=null}async render({filePath:e,renderHost:t,source:n=``}){return this.mount(t,e),this.syncNow({filePath:e,source:String(n??``)})}queueSync({filePath:e,source:t=``}={}){clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=null,this.syncNow({filePath:e,source:String(t??``)})},cn)}async syncNow({filePath:e,source:t=``}={}){if(e!==this.filePath)return!1;let n=++this.syncToken;if(!this.enabled)return this.setStatus(`Structurizr preview is not configured. Start CollabMD with --local-structurizr.`,{error:!0}),!1;this.iframe||this.setStatus(`Validating Structurizr workspace…`);try{let r=await this.syncWorkspace({path:e,source:t});if(n!==this.syncToken||e!==this.filePath)return!1;let i=r?.version||null,a=_e(`/workspace/1/diagrams`),o=this.viewKey?`#${encodeURIComponent(this.viewKey)}`:``;if(!this.iframe){let e=this.createIframe();this.iframe=e,this.frameHost?.appendChild(e),e.src=`${a}${o}`,this.lastVersion=i}else if(i!==this.lastVersion){this.discardPendingIframe();let e=this.createIframe();e.style.visibility=`hidden`,e.style.pointerEvents=`none`,e.setAttribute(`aria-hidden`,`true`),this.pendingIframe=e,this.pendingVersion=i,this.frameHost?.appendChild(e),e.src=`${a}${o}`}return this.setStatus(``),!0}catch(t){return n!==this.syncToken||e!==this.filePath||this.setStatus(t?.message||`Failed to load Structurizr workspace.`,{error:!0}),!1}}reset(){this.setMaximized(!1),clearTimeout(this.syncTimer),this.syncTimer=null,clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.syncToken+=1,this.discardPendingIframe(),this.disposeFrame(this.iframe),this.iframe=null,this.frameHost=null,this.shell=null,this.status=null,this.maximizeButton=null,this.filePath=null,this.lastVersion=null,this.viewKey=``}},mn=150;function hn(e){return new Promise(t=>{setTimeout(t,e)})}var gn=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getVimModeEnabled:s,getLocalUser:c,getStoredUserName:l,getTheme:u,isBaseFile:d,isDrawioFile:f,isExcalidrawFile:p,isImageFile:m,isPdfFile:h,isMermaidFile:g,isPlantUmlFile:_,isStructurizrWorkspaceFile:v,isTabActive:y,loadBootstrapContent:ee=null,loadEditorSessionClass:te,loadBacklinks:b,onBeforeFileOpen:x,onConnectionChange:S,onContentChange:ne,onCommentsChange:C,onFileAwarenessChange:w,onFileOpenError:T,onFileOpenReady:E,onImagePaste:D,onSelectionChange:O,onSessionAssigned:k=null,onFileOpenMetric:A=null,onRenderBasePreview:j,onRenderExcalidrawPreview:M,onRenderDrawioPreview:N,onRenderImagePreview:re,onRenderPdfPreview:ie,onRenderStructurizrPreview:ae,onSyncWrapToggle:P,onUpdateActiveFile:oe,onUpdateCurrentFile:se,onUpdateLobbyCurrentFile:ce,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:F,scrollContainerForSession:de,shouldUseDrawioPreview:fe=null,showEditorLoading:I,stateStore:pe}){this.attachEditorScroller=e,this.beginDocumentLoad=t,this.cleanupAfterSessionDestroy=n,this.createEditorSession=r,this.getDisplayName=i,this.getFileList=a,this.getLineWrappingEnabled=o,this.getVimModeEnabled=s??(()=>!1),this.getLocalUser=c,this.getStoredUserName=l,this.getTheme=u,this.isBaseFile=d??(()=>!1),this.isDrawioFile=f??(()=>!1),this.isExcalidrawFile=p??(()=>!1),this.isImageFile=m??(()=>!1),this.isPdfFile=h??(()=>!1),this.isMermaidFile=g??(()=>!1),this.isPlantUmlFile=_??(()=>!1),this.isStructurizrWorkspaceFile=v??(()=>!1),this.isTabActive=y,this.loadBootstrapContent=ee,this.loadEditorSessionClassPort=te,this.loadBacklinks=b,this.onBeforeFileOpen=x,this.onConnectionChange=S,this.onContentChange=ne,this.onCommentsChange=C,this.onFileAwarenessChange=w,this.onFileOpenError=T,this.onFileOpenReady=E,this.onImagePaste=D,this.onSelectionChange=O,this.onSessionAssigned=k,this.onFileOpenMetric=A,this.onRenderBasePreview=j,this.onRenderDrawioPreview=N,this.onRenderExcalidrawPreview=M,this.onRenderImagePreview=re,this.onRenderPdfPreview=ie,this.onRenderStructurizrPreview=ae,this.onSyncWrapToggle=P,this.onUpdateActiveFile=oe,this.onUpdateCurrentFile=se,this.onUpdateLobbyCurrentFile=ce,this.onUpdateVisibleChrome=le,this.onViewModeReset=ue,this.renderPresence=F,this.scrollContainerForSession=de,this.shouldUseDrawioPreview=fe??(()=>!0),this.showEditorLoading=I,this.stateStore=pe,this.session=null}getSession(){return this.session}loadEditorSessionClass(){return this.loadEditorSessionClassPort()}waitForNextPaint(){return new Promise(e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})})}reportFileOpenMetric(e,t,n={}){this.onFileOpenMetric?.(e,{filePath:this.stateStore.currentFilePath,loadToken:t,...n})}cleanupSession(){this.session?.destroy(),this.session=null,this.attachEditorScroller(null),this.cleanupAfterSessionDestroy()}prepareForFileOpen(e,{drawioMode:n=null,resetConnectionState:r=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.connectionHelpShown=!1,r&&(this.stateStore.connectionState={status:`connecting`,unreachable:!1}),this.stateStore.currentDrawioMode=n??null,this.stateStore.currentFilePath=e,this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:n,isMarkdown:_(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:t(e)}}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:r,isExcalidraw:i=!1,isImage:a=!1,isPdf:o=!1,supportsBacklinks:s}){i&&this.onRenderExcalidrawPreview(r),(e||n(r))&&this.onRenderBasePreview(r),t&&this.onRenderDrawioPreview(r),a&&this.onRenderImagePreview(r),o&&this.onRenderPdfPreview(r),this.isStructurizrWorkspaceFile(r)&&this.onRenderStructurizrPreview(r,{source:this.session?.getText?.()??``}),this.onSyncWrapToggle(),s&&this.loadBacklinks(r)}async openFile(e,{drawioMode:t=null}={}){if(!this.isTabActive())return;let n=t??null,r=this.stateStore.currentDrawioMode??null,i=this.isDrawioFile(e)&&t!==`text`&&this.shouldUseDrawioPreview(e),a=this.isExcalidrawFile(e),o=this.isBaseFile(e),s=this.isImageFile(e),c=this.isPdfFile(e),l=this.isMermaidFile(e),u=this.isPlantUmlFile(e),d=this.isStructurizrWorkspaceFile(e);if(e===this.stateStore.currentFilePath&&n===r&&(this.session||i||a||s||c)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let f=++this.stateStore.sessionLoadToken,p=performance.now();this.cleanupSession();let m=this.prepareForFileOpen(e,{drawioMode:n,resetConnectionState:!i&&!a&&!s&&!c});if(this.reportFileOpenMetric(`open_started`,f,{filePath:e}),i||a||s||c){if(this.onSessionAssigned?.(null),f!==this.stateStore.sessionLoadToken)return;this.onFileOpenReady(null),this.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,isPdf:c,session:null,supportsBacklinks:m.supportsBacklinks});return}let h=await this.loadEditorSessionClass(),g=this.createEditorSession(h,{filePath:e,getFileList:this.getFileList,lineWrappingEnabled:this.getLineWrappingEnabled(),localUser:this.getLocalUser(),vimModeEnabled:this.getVimModeEnabled(),onAwarenessChange:e=>this.onFileAwarenessChange(e),onConnectionChange:e=>this.onConnectionChange(e),onCommentsChange:e=>this.onCommentsChange?.(e),onContentChange:()=>{a||this.onContentChange({isBase:o,isMermaid:l,isPlantUml:u,isStructurizrWorkspace:d})},onImagePaste:e=>this.onImagePaste?.(e),preferredUserName:this.getStoredUserName(),onSelectionChange:e=>this.onSelectionChange?.(e),theme:this.getTheme()});this.session=g,this.onSessionAssigned?.(g);try{let t=!1,n=!1,r=!1,i=async r=>{t||f!==this.stateStore.sessionLoadToken||(t=!0,this.attachEditorScroller(this.scrollContainerForSession(g)),g.applyTheme(this.getTheme()),this.onFileOpenReady(g),this.reportFileOpenMetric(`editor_ready`,f,{reason:r}),g.requestMeasure(),await this.waitForNextPaint(),!(n||f!==this.stateStore.sessionLoadToken)&&(n=!0,this.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:g,supportsBacklinks:m.supportsBacklinks})))},s=this.loadBootstrapContent?(async()=>{this.reportFileOpenMetric(`bootstrap_fetch_started`,f);try{let t=await this.loadBootstrapContent(e);return this.reportFileOpenMetric(`bootstrap_fetch_completed`,f,{found:t!==null}),t}catch(e){return this.reportFileOpenMetric(`bootstrap_fetch_completed`,f,{error:e.message,found:!1}),null}})():Promise.resolve(null),c=g.initialize(e),l=(async()=>(await c,f!==this.stateStore.sessionLoadToken||(await g.waitForInitialSync(null),f!==this.stateStore.sessionLoadToken)?!1:(r=!0,g.activateCollaborativeView?.(),this.attachEditorScroller(this.scrollContainerForSession(g)),g.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,f),g.ensureInitialContent?.(),t?g.requestMeasure():await i(`live-sync`),!0)))(),u=(async()=>{let n=await s;if(n===null||r||t||f!==this.stateStore.sessionLoadToken)return!1;let a=performance.now()-p,o=Math.max(0,mn-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),hn(o).then(()=>`timeout`)])===`live-sync`||r||t||f!==this.stateStore.sessionLoadToken||!g.showBootstrapContent({content:n,filePath:e})&&!g.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,f),await i(`bootstrap`),!0)})();if(await c,f!==this.stateStore.sessionLoadToken){g.destroy();return}if(await Promise.all([l,u]),f!==this.stateStore.sessionLoadToken){g.destroy();return}t||(g.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),g.destroy(),this.attachEditorScroller(null),this.session===g&&(this.session=null),f!==this.stateStore.sessionLoadToken)return;this.onFileOpenError()}}};function _n(e=document){return{currentUserName:e.getElementById(`currentUserName`),chatContainer:e.getElementById(`chatContainer`),chatEmptyState:e.getElementById(`chatEmptyState`),chatForm:e.getElementById(`chatForm`),chatInput:e.getElementById(`chatInput`),chatMessages:e.getElementById(`chatMessages`),chatPanel:e.getElementById(`chatPanel`),chatCloseButton:e.getElementById(`chatCloseBtn`),chatStatus:e.getElementById(`chatStatus`),chatToastContainer:e.getElementById(`chatToastContainer`),chatNotificationButton:e.getElementById(`chatNotificationBtn`),chatNotificationMuteButton:e.getElementById(`chatNotificationMuteBtn`),chatNotificationStatus:e.getElementById(`chatNotificationStatus`),chatToggleBadge:e.getElementById(`chatToggleBadge`),chatToggleButton:e.getElementById(`chatToggleBtn`),gitCommitCancel:e.getElementById(`gitCommitCancel`),gitCommitCopy:e.getElementById(`gitCommitCopy`),gitCommitDialog:e.getElementById(`gitCommitDialog`),gitCommitForm:e.getElementById(`gitCommitForm`),gitCommitInput:e.getElementById(`gitCommitInput`),gitCommitSubmit:e.getElementById(`gitCommitSubmit`),gitCommitTitle:e.getElementById(`gitCommitTitle`),gitResetCancel:e.getElementById(`gitResetCancel`),gitResetCopy:e.getElementById(`gitResetCopy`),gitResetDialog:e.getElementById(`gitResetDialog`),gitResetFileName:e.getElementById(`gitResetFileName`),gitResetSubmit:e.getElementById(`gitResetSubmit`),gitResetTitle:e.getElementById(`gitResetTitle`),displayNameCancel:e.getElementById(`displayNameCancel`),displayNameCopy:e.getElementById(`displayNameCopy`),displayNameDialog:e.getElementById(`displayNameDialog`),displayNameForm:e.getElementById(`displayNameForm`),displayNameInput:e.getElementById(`displayNameInput`),displayNameSubmit:e.getElementById(`displayNameSubmit`),displayNameTitle:e.getElementById(`displayNameTitle`),editNameButton:e.getElementById(`editNameBtn`),editorFindButton:e.getElementById(`editorFindBtn`),editorContainer:e.getElementById(`editorContainer`),exportDocxButton:e.getElementById(`exportDocxBtn`),exportMenuGroup:e.getElementById(`exportMenuGroup`),exportPdfButton:e.getElementById(`exportPdfBtn`),markdownToolbar:e.getElementById(`markdownToolbar`),editorPage:e.getElementById(`editor-page`),diffPage:e.getElementById(`diff-page`),fileSearch:e.getElementById(`fileSearch`),fileHistoryButton:e.getElementById(`fileHistoryBtn`),fileHistoryButtonLabel:e.getElementById(`fileHistoryBtnLabel`),filesSidebarTab:e.getElementById(`filesSidebarTab`),gitSearch:e.getElementById(`gitSearch`),gitSearchInput:e.getElementById(`gitSearchInput`),gitSidebarTab:e.getElementById(`gitSidebarTab`),gitOperationStatus:e.getElementById(`gitOperationStatus`),lineInfo:e.getElementById(`lineInfo`),mobileViewToggle:e.getElementById(`mobileViewToggle`),previewContent:e.getElementById(`previewContent`),previewContainer:e.getElementById(`previewContainer`),presencePanel:e.getElementById(`presencePanel`),presencePanelList:e.getElementById(`presencePanelList`),presencePanelStatus:e.getElementById(`presencePanelStatus`),searchFilesButton:e.getElementById(`searchFilesBtn`),toolbarSearchButton:e.getElementById(`toolbarSearchBtn`),shareButton:e.getElementById(`shareBtn`),toastContainer:e.getElementById(`toastContainer`),toggleWrapButton:e.getElementById(`toggleWrapBtn`),toggleVimModeButton:e.getElementById(`toggleVimModeBtn`),userAvatars:e.getElementById(`userAvatars`),userCount:e.getElementById(`userCount`),wrapToggleLabel:e.getElementById(`wrapToggleLabel`),vimModeToggleLabel:e.getElementById(`vimModeToggleLabel`),activeFileName:e.getElementById(`activeFileName`),sidebarToggle:e.getElementById(`sidebarToggle`),sidebarClose:e.getElementById(`sidebarClose`),sidebarBackdrop:e.getElementById(`sidebarBackdrop`),sidebar:e.getElementById(`sidebar`),sidebarResizer:e.getElementById(`sidebarResizer`),emptyState:e.getElementById(`emptyState`),emptyStateNewFileBtn:e.getElementById(`emptyStateNewFileBtn`),emptyStateSearchBtn:e.getElementById(`emptyStateSearchBtn`),backlinksPanel:e.getElementById(`backlinksPanel`),backlinksHeaderPanel:e.getElementById(`backlinksHeaderPanel`),backlinksInlinePanel:e.getElementById(`backlinksInlinePanel`),commentSelectionButton:e.getElementById(`commentSelectionBtn`),commentsDrawer:e.getElementById(`commentsDrawer`),commentsDrawerEmpty:e.getElementById(`commentsDrawerEmpty`),commentsDrawerList:e.getElementById(`commentsDrawerList`),commentsSidebarTab:e.getElementById(`commentsSidebarTab`),commentsToggleButton:e.getElementById(`commentsToggle`),commentOverviewPanel:e.getElementById(`commentOverviewPanel`),outlineToggle:e.getElementById(`outlineToggle`),tabLockCopy:e.getElementById(`tabLockCopy`),tabLockOverlay:e.getElementById(`tabLockOverlay`),tabLockTakeoverButton:e.getElementById(`tabLockTakeoverBtn`),tabLockTitle:e.getElementById(`tabLockTitle`),toolbarCenter:e.getElementById(`toolbarCenter`),toolbarDiffBadge:e.getElementById(`toolbarDiffBadge`),toolbarOverflowMenu:e.getElementById(`toolbarOverflowMenu`),toolbarOverflowToggle:e.getElementById(`toolbarOverflowToggle`),toolbarViewToggle:e.getElementById(`toolbarViewToggle`),sidebarTabs:e.getElementById(`sidebarTabs`)}}var vn=`collabmd-chat-alerts-muted-until`,yn=36e5;function bn(e){return e.lobby?.getConnectionState?.()??{status:`connected`,unreachable:!1}}function xn(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}function Sn(){try{let e=Number(globalThis.localStorage?.getItem(vn));return!Number.isFinite(e)||e<=Date.now()?(globalThis.localStorage?.removeItem(vn),0):e}catch{return 0}}function Cn(e){try{e>0?globalThis.localStorage?.setItem(vn,String(e)):globalThis.localStorage?.removeItem(vn)}catch{}}var wn={updateChatMessages(e,{initial:t=!1}={}){let n=new Set(this.chatMessageIds),r=this.lobby.getLocalUser()?.peerId??null;if(this.chatMessages=e,this.chatMessageIds=new Set(e.map(e=>e.id)),!this.chatInitialSyncComplete){t&&(this.chatInitialSyncComplete=!0),this.renderChat();return}let i=e.filter(e=>!n.has(e.id)&&e.peerId&&e.peerId!==r);this.chatIsOpen?this.chatUnreadCount=0:i.length>0&&(this.chatUnreadCount+=i.length);for(let e of i)this.maybeNotifyChatMessage(e);this.renderChat()},toggleChatPanel(){if(this.chatIsOpen){this.closeChatPanel({restoreFocus:!0});return}this.openChatPanel()},openChatPanel(){this.chatIsOpen=!0,this.chatUnreadCount=0,this.renderChat({stickToBottom:!0}),requestAnimationFrame(()=>{this.elements.chatInput?.focus()})},closeChatPanel({restoreFocus:e=!1}={}){this.chatIsOpen&&(this.chatIsOpen=!1,this.renderChat({messagesChanged:!1}),e&&requestAnimationFrame(()=>this.elements.chatToggleButton?.focus()))},handleChatSubmit(){let e=bn(this);if(this.isTabActive===!1||e.status!==`connected`)return;let t=this.elements.chatInput;if(t){if(!this.lobby.sendChatMessage(t.value)){t.focus();return}if(t.value=``,!this.chatIsOpen){this.openChatPanel();return}this.renderChat({stickToBottom:!0})}},renderChat({messagesChanged:e=!0,stickToBottom:t=!1}={}){this.elements.chatContainer?.classList.toggle(`is-open`,this.chatIsOpen),this.elements.chatPanel?.classList.toggle(`hidden`,!this.chatIsOpen),this.syncChatToggleButton(),this.syncChatNotificationButton();let n=this.elements.chatMessages,r=this.elements.chatEmptyState,i=bn(this),a=i.status===`connected`,o=a&&this.chatInitialSyncComplete&&this.isTabActive!==!1;this.elements.chatStatus&&(this.elements.chatStatus.textContent=this.chatInitialSyncComplete?a?`${this.globalUsers.length} online`:i.unreachable?`Server unreachable`:`Reconnecting...`:`Syncing...`);let s=this.elements.chatForm?.querySelector?.(`button[type="submit"]`);if(s&&(s.disabled=!o,s.title=o?`Send message`:`Chat is unavailable while disconnected`),!n||!this.chatIsOpen||!e)return;if(this.chatMessages.length===0){n.replaceChildren(),r?.classList.remove(`hidden`),n.classList.add(`hidden`);return}r?.classList.add(`hidden`),n.classList.remove(`hidden`);let c=t||xn(n),l=document.createDocumentFragment();this.chatMessages.forEach(e=>{l.appendChild(this.createChatMessageElement(e))}),n.replaceChildren(l),c&&this.scrollChatToBottom()},createChatMessageElement(e){let t=document.createElement(`article`),n=e.peerId===this.lobby.getLocalUser()?.peerId;t.className=`chat-message`,t.classList.toggle(`is-local`,n);let r=document.createElement(`div`);r.className=`chat-message-avatar`;let i=e.userColor||`var(--color-primary-active)`;r.style.backgroundColor=i,r.style.color=De(e.userColor),r.textContent=(e.userName||`?`).charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let a=document.createElement(`div`);a.className=`chat-message-body`;let o=document.createElement(`div`);o.className=`chat-message-meta`;let s=document.createElement(`span`);s.className=`chat-message-author`,s.textContent=n?`${e.userName} (you)`:e.userName;let c=document.createElement(`span`);c.className=`chat-message-time`,c.textContent=this.formatChatTimestamp(e.createdAt),o.append(s,c);let l=this.getChatMessageFileLabel(e.filePath);if(l){let e=document.createElement(`span`);e.className=`ui-pill chat-message-file`,e.textContent=l,o.append(e)}let u=document.createElement(`p`);return u.className=`chat-message-text`,u.textContent=e.text,a.append(o,u),t.append(r,a),t},scrollChatToBottom(){let e=this.elements.chatMessages;e&&requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight})},formatChatTimestamp(e){if(!Number.isFinite(e))return``;try{return this.chatTimeFormatter.format(new Date(e))}catch{return``}},getChatMessageFileLabel(e){return e?this.getDisplayName(e):``},formatChatToastMessage(e){let t=e?.userName||`Someone`,n=String(e?.text??``).replace(/\s+/g,` `).trim();return`${t}: ${n.length>88?`${n.slice(0,85).trimEnd()}...`:n}`},syncChatNotificationButton(){let e=this.elements.chatNotificationButton,t=this.elements.chatNotificationMuteButton,n=this.elements.chatNotificationStatus;if(!e&&!t&&!n)return;let r=this.notifications?.getPermission?.()??`unsupported`,i=r===`granted`,a=i&&Sn()>0,o=r===`denied`,s=i?{text:a?`Alerts muted`:`Alerts on`,label:a?`Desktop alerts muted`:`Desktop alerts enabled`}:o?{text:`Alerts blocked`,label:`Desktop alerts blocked in browser settings`}:null;if(e&&(e.classList.toggle(`hidden`,r!=="default"),e.disabled=!1,e.removeAttribute(`aria-pressed`),e.textContent=`Enable desktop alerts`,e.title=`Allow desktop alerts for new chat messages`),t){t.classList.toggle(`hidden`,!i),t.disabled=!1,t.setAttribute(`aria-pressed`,String(a));let e=a?`Unmute desktop alerts`:`Mute desktop alerts for one hour`;t.setAttribute(`aria-label`,e),t.title=e}n&&(n.classList.toggle(`hidden`,!s),n.textContent=s?.text??``,s?(n.setAttribute(`aria-label`,s.label),n.title=s.label):(n.removeAttribute(`aria-label`),n.removeAttribute(`title`)),n.classList.toggle(`ui-status-badge--accent`,i&&!a),n.classList.toggle(`ui-status-badge--muted`,o||a))},async handleChatNotificationToggle(){let e=await this.notifications?.requestPermission?.();if(this.syncChatNotificationButton(),e!==`granted`){if(e===`denied`){(this.chatToastController??this.toastController)?.show(`Desktop alerts are blocked. Allow them in browser site settings.`,{duration:5e3,tone:`warning`});return}e===`unsupported`&&(this.chatToastController??this.toastController)?.show(`This browser does not support desktop alerts.`,{duration:5e3,tone:`warning`})}},toggleChatNotificationMute(){Cn(Sn()>0?0:Date.now()+yn),this.renderChat({messagesChanged:!1})},syncChatToggleButton(){let e=this.elements.chatToggleButton,t=this.elements.chatToggleBadge;if(!e)return;let n=this.chatUnreadCount>0,r=n&&!this.chatIsOpen;e.classList.toggle(`is-active`,this.chatIsOpen),e.classList.toggle(`is-unread`,r),e.setAttribute(`aria-controls`,`chatPanel`),e.setAttribute(`aria-expanded`,String(this.chatIsOpen)),e.setAttribute(`aria-label`,n?`Open team chat, ${this.chatUnreadCount} unread`:`Open team chat`),e.title=this.chatUnreadCount>0?`Team chat (${this.chatUnreadCount} unread)`:`Team chat`,t&&(t.classList.toggle(`hidden`,!n),t.textContent=this.chatUnreadCount>9?`9+`:String(this.chatUnreadCount))},maybeNotifyChatMessage(e){if(!this.chatInitialSyncComplete||this.isTabActive===!1||this.chatIsOpen||Sn()>0)return;let t=!!(globalThis.document?.hidden||globalThis.document?.visibilityState===`hidden`),n=typeof globalThis.document?.hasFocus==`function`?globalThis.document.hasFocus():!t,r=null;(t||!n)&&(r=this.notifications?.show?.({body:String(e?.text??``).replace(/\s+/g,` `).trim(),onClick:()=>{window.focus?.(),r?.close?.(),this.openChatPanel()},tag:`collabmd-chat-${e?.id??`message`}`,title:`New message from ${e?.userName||`Someone`}`})),!r&&(this.chatToastController??this.toastController).show(this.formatChatToastMessage(e),4e3)}},Tn={createCommentThread(e){let t=this.session?.createCommentThread(e);return t&&this.scheduleCommentOverviewRefresh(),t},replyToCommentThread(e,t){let n=this.session?.replyToCommentThread(e,t);return n&&this.scheduleCommentOverviewRefresh(),n},resolveCommentThread(e){let t=this.session?.deleteCommentThread(e);return t&&this.scheduleCommentOverviewRefresh(),t},getCommentFileKind(e=this.currentFilePath){return m(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=v(e)&&!this.isExcalidrawFile(e);this.commentUi.setCurrentFile(e,{fileKind:this.getCommentFileKind(e),supported:t}),this.handleCommentThreadsChange(this.session?.getCommentThreads?.()??[]),this.handleCommentSelectionChange(this.session?.getCurrentSelectionCommentAnchor?.()??null)},handleCommentSelectionChange(e){this.commentUi.setSelectionAnchor(e)},handleCommentThreadsChange(e=[]){this.commentUi.setThreads(e),this.focusPendingCommentOverviewThread()},handleCommentEditorContentChange(){this.commentUi.handleEditorContentChange()},refreshCommentUiLayout(){this.commentUi.refreshLayout()},scheduleCommentOverviewRefresh({delayMs:e=900}={}){clearTimeout(this._commentOverviewRefreshTimer),this._commentOverviewRefreshTimer=setTimeout(()=>{this._commentOverviewRefreshTimer=null,this._commentOverviewStale=!1,this.commentsOverview?.refresh?.()},e)},handleCommentOverviewWorkspaceTreeChange(){this._commentOverviewStale=!0,this.activeSidebarTab===`comments`&&this.scheduleCommentOverviewRefresh({delayMs:0})},refreshCommentOverviewForSidebarOpen(){this._commentOverviewStale=!1,this.commentsOverview?.refresh?.()},async openCommentOverviewThread({anchor:e=null,filePath:t,threadId:n}={}){if(!t||!n)return;let r=m(t)===`excalidraw`,i=Number.isFinite(e?.startLine)?e.startLine:null;if(r||(this._pendingCommentOverviewFocus={attempts:0,filePath:t,line:i,threadId:n}),this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),this.workspaceRouteController?.preserveSidebarTabForNextFileRoute?.(t),this.navigation.navigateToFile(t,r?void 0:{line:i}),(this.currentFilePath!==t||!this.session)&&await this.workspaceRouteController.openFile(t),this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),r){this.excalidrawEmbed?.openCommentThread?.(t,n);return}this.focusPendingCommentOverviewThread()},focusPendingCommentOverviewThread(){let e=this._pendingCommentOverviewFocus;return!e||e.filePath!==this.currentFilePath?!1:(Number.isFinite(e.line)&&this.session?.scrollToLine?.(e.line,.2),this.commentUi.openThreadFromOverview?.(e.threadId)?(this._pendingCommentOverviewFocus=null,this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),!0):e.attempts>=8?(this._pendingCommentOverviewFocus=null,this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),!1):(e.attempts+=1,clearTimeout(this._commentOverviewFocusTimer),this._commentOverviewFocusTimer=setTimeout(()=>{this._commentOverviewFocusTimer=null,this.focusPendingCommentOverviewThread()},120),!1))}},En=`collabmd-export-page`,Dn=`collabmd-export-host`,On=500,kn=6e4,An=new Map,jn=null;function Mn(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Nn(e){return e===`pdf`?`pdf`:`docx`}function Pn({filePath:e,format:t,jobId:n}){let r=new URL(se(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,Nn(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function Fn({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:Nn(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:Dn,title:String(a??``),type:`bootstrap`}}function In(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function Ln(e,{notifyError:t=!1,message:n=``}={}){let r=An.get(e);r&&(In(r),An.delete(e),t&&n&&jn?.(n))}function Rn({onError:e=null}={}){jn=typeof e==`function`?e:null,!window.__collabmdExportBridgeInitialized&&(window.addEventListener(`message`,e=>{if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==En)return;let n=String(t.jobId??``).trim();if(!n)return;let r=An.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){Ln(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){Ln(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&Ln(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function zn({fileList:e=[],filePath:t,format:n,markdownText:r=``,title:i=``}={}){let a=String(t??``).trim();if(!a)throw Error(`No markdown note is open`);let o=Mn(),s=Pn({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return An.set(o,{closePollId:window.setInterval(()=>{c.closed&&Ln(o,{message:`Export window was closed before the export completed`,notifyError:!0})},On),payload:Fn({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{Ln(o,{message:`Export timed out before it completed`,notifyError:!0})},kn),window:c}),c.focus?.(),o}var Bn={initializeExportBridge(){this._exportBridgeInitialized||=(Rn({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!_(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await zn({fileList:this.fileExplorer?.flatDocumentFiles??[],filePath:t,format:e,markdownText:this.session?.getText?.()??``,title:this.getDisplayName(t)}),!0}catch(e){return this.toastController?.show(e instanceof Error?e.message:`Failed to start export`),!1}}};function Vn(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function Hn(e=[]){return Array.from(new Map((e??[]).filter(e=>e?.oldPath&&e?.newPath&&e.oldPath!==e.newPath).map(e=>[`${e.oldPath}:${e.newPath}`,{newPath:e.newPath,oldPath:e.oldPath}])).values())}function Un(e=[]){return(e??[]).filter(e=>e?.path&&Number.isFinite(e?.from)&&Number.isFinite(e?.to)).map(e=>({from:Math.max(0,Math.round(e.from)),path:e.path,to:Math.max(0,Math.round(e.to))}))}function Wn({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:Vn(e),deletedPaths:Vn(t),refreshExplorer:n!==!1,renamedPaths:Hn(r)}}function Gn(e){return!e||typeof e!=`object`||typeof e.id!=`string`?null:{action:typeof e.action==`string`?e.action:`workspace`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),highlightRanges:Un(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:Vn(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:Wn(e.workspaceChange)}}var Kn={formatPullBackupToast(e=null){let t=Number(e?.fileCount||0);return t===1?`Pulled latest changes. 1 overlapping local file was backed up.`:t>1?`Pulled latest changes. ${t} overlapping local files were backed up.`:`Pulled latest changes. Overlapping local changes were recorded in a pull backup.`},setGitOperationStatus(e=``){let t=this.elements.gitOperationStatus;if(!t)return;let n=String(e??``).trim();t.textContent=n,t.classList.toggle(`hidden`,!n)},async runGitActionWithStatus(e,t){this.setGitOperationStatus(e);try{return await t()}finally{this.setGitOperationStatus(``)}},handleGitDiffSelection(e,{closeSidebarOnMobile:t=!1,scope:n=`working-tree`}={}){t&&this.closeSidebarOnMobile(),this.navigation.navigateToGitDiff({filePath:e,scope:n})},handleGitCommitSelection(e,{closeSidebarOnMobile:t=!1,historyFilePath:n=null,path:r=null}={}){t&&this.closeSidebarOnMobile(),this.navigation.navigateToGitCommit({hash:e,historyFilePath:n,path:r})},handleGitHistorySelection({closeSidebarOnMobile:e=!1}={}){e&&this.closeSidebarOnMobile(),this.navigation.navigateToGitHistory()},handleGitFileHistorySelection(e=this.currentFilePath,{closeSidebarOnMobile:t=!1}={}){t&&this.closeSidebarOnMobile(),e&&this.navigation.navigateToGitFileHistory({filePath:e})},handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n=null,closeSidebarOnMobile:r=!1}={}){r&&this.closeSidebarOnMobile(),!(!e||!t)&&this.navigation.navigateToGitFilePreview({hash:e,path:t,currentFilePath:n})},handleGitRepoChange(e,t=null){this.gitRepoAvailable=!!e,this.elements.sidebarTabs?.classList.remove(`hidden`),this.elements.gitSidebarTab?.classList.toggle(`hidden`,!this.gitRepoAvailable);let n=e&&t?.summary?.changedFiles>0;if(this.elements.gitSidebarTab?.classList.toggle(`has-changes`,n),this.gitDiffView.setRepoStatus(this.gitRepoAvailable?t:null),!this.gitRepoAvailable&&this.activeSidebarTab===`git`){this.syncFileHistoryButton({mode:this.navigation.getHashRoute().type===`git-file-preview`?`history-preview`:`editor`}),this.setSidebarTab(`files`);return}let r=this.navigation.getHashRoute().type;this.gitRepoAvailable&&(r===`git-diff`||r===`git-commit`||r===`git-history`)&&this.activeSidebarTab!==`git`&&this.setSidebarTab(`git`),this.syncFileHistoryButton({filePath:this.currentFilePath,mode:r===`git-file-preview`?`history-preview`:r===`file`?`editor`:`empty`})},syncFileHistoryButton({filePath:e=this.currentFilePath,mode:t=`editor`}={}){let n=this.elements.fileHistoryButton,r=this.elements.fileHistoryButtonLabel;if(!(!n||!r)){if(!(this.gitRepoAvailable&&this.supportsFileHistory?.(e))){n.classList.add(`hidden`);return}if(n.classList.remove(`hidden`),t===`history-preview`){r.textContent=`Back to History`,n.setAttribute(`aria-label`,`Back to file history`),n.title=`Back to file history`;return}if(t!==`editor`){n.classList.add(`hidden`);return}r.textContent=`History`,n.setAttribute(`aria-label`,`Open file history`),n.title=`View file history`}},syncMainChrome({badgeLabel:e=``,mode:t,title:n=null}={}){let r=t===`diff`||t===`history`||t===`history-preview`;this.elements.toolbarViewToggle?.classList.toggle(`hidden`,r),this.elements.mobileViewToggle?.classList.toggle(`hidden`,r),this.elements.userCount?.classList.toggle(`hidden`,r),this.elements.toolbarDiffBadge?.classList.toggle(`hidden`,!e),this.elements.toolbarDiffBadge&&(this.elements.toolbarDiffBadge.textContent=e),n&&this.elements.activeFileName&&(this.elements.activeFileName.textContent=n),this.syncFileHistoryButton({filePath:this.currentFilePath,mode:t})},async showGitDiff({filePath:e=null,scope:t=`all`}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setSelection(e?{path:e,scope:t,source:`workspace`}:{}),this.gitPanel.setMode(`changes`),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({filePath:e,scope:t})}),this.syncFileHistoryButton({filePath:e,mode:`diff`}),await this.gitDiffView.openWorkspaceDiff({filePath:e,scope:t})},async showGitCommit({hash:e,path:t=null,historyFilePath:n=null}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection(e?{commitHash:e,path:t,source:`commit`}:{source:`commit`}),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({commitHash:e,path:t,source:`commit`})}),this.syncFileHistoryButton({filePath:t,mode:`diff`}),await this.gitDiffView.openCommitDiff({hash:e,historyFilePath:n,path:t})},async showGitHistory(){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection({source:`commit`}),this.workspaceRouteController?.showEmptyState?.(),this.syncMainChrome({mode:`empty`,title:`Git History`}),this.syncFileHistoryButton({mode:`empty`})},async showGitFileHistory({filePath:e=null}={}){if(!e){this.workspaceRouteController?.showEmptyState?.();return}this.clearStaticPreviewDocument?.(),this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(e,{fileKind:this.getCommentFileKind(e),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showFileHistoryState?.(e),this.syncMainChrome({badgeLabel:`History`,mode:`history`,title:this.getDisplayName(e)}),this.syncFileHistoryButton({filePath:e,mode:`history`}),await this.fileHistoryView.openFileHistory({filePath:e})},async _loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:n}){let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});if(this.setStaticPreviewDocument?.({...r,currentFilePath:n}),this.workspacePreviewController.resetPreviewMode(),this.elements.markdownToolbar?.classList.add(`hidden`),this.elements.outlineToggle?.classList.toggle(`hidden`,r.fileKind!==`markdown`),r.fileKind===`markdown`||r.fileKind===`mermaid`||r.fileKind===`plantuml`){r.fileKind===`mermaid`?this.elements.previewContent?.classList.add(`is-mermaid-file-preview`):r.fileKind===`plantuml`&&this.elements.previewContent?.classList.add(`is-plantuml-file-preview`),this.previewRenderer.beginDocumentLoad(),this.previewRenderer.queueRender();return}this.elements.outlineToggle?.classList.add(`hidden`),this.workspacePreviewController.renderTextFilePreview({content:r.content,filePath:n})},_handleGitFilePreviewError(e,t){console.error(`[git-preview] Failed to load file snapshot:`,e),this.clearStaticPreviewDocument?.(),this.toastController.show(`Failed to load historical file preview`),this.workspacePreviewController.renderTextFilePreview({content:`Failed to load historical file preview.`,filePath:t}),this.elements.outlineToggle?.classList.add(`hidden`)},async showGitFilePreview({hash:e,filePath:t=null,currentFilePath:n=null}={}){let r=String(n??``).trim()||t;if(!e||!t||!r){this.workspaceRouteController?.showEmptyState?.();return}this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(r,{fileKind:this.getCommentFileKind(r),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showPreviewOnlyState?.(r),this.layoutController.setView(`preview`,{persist:!1}),this.syncMainChrome({badgeLabel:`History Preview`,mode:`history-preview`,title:this.getDisplayName(r)}),this.syncFileHistoryButton({filePath:r,mode:`history-preview`});try{await this._loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:r})}catch(e){this._handleGitFilePreviewError(e,r)}},async postGitAction(e,t){let n=crypto.randomUUID();this.pendingWorkspaceRequestIds?.add(n);try{switch(e){case`stage`:return await this.gitApiClient.stageFile({path:t.path,requestId:n});case`unstage`:return await this.gitApiClient.unstageFile({path:t.path,requestId:n});case`push`:return await this.gitApiClient.pushBranch({requestId:n});case`pull`:return await this.gitApiClient.pullBranch({requestId:n});case`reset-file`:return await this.gitApiClient.resetFile({path:t.path,requestId:n});case`commit`:return await this.gitApiClient.commit({message:t.message,requestId:n});default:throw Error(`Unsupported git action: ${e}`)}}catch(e){throw this.pendingWorkspaceRequestIds?.delete(n),e}},async refreshWorkspaceAfterGitAction({filePath:e=null,preferredScope:t=null}={}){await this.fileExplorer.refresh(),await this.refreshGitAfterAction({filePath:e,preferredScope:t})},async refreshGitAfterAction({filePath:e=null,preferredScope:t=null}={}){await this.gitPanel.refresh({force:!0});let n=this.navigation.getHashRoute();if(n.type===`git-history`){await this.showGitHistory();return}if(n.type===`git-file-history`){await this.showGitFileHistory({filePath:n.filePath});return}if(n.type===`git-file-preview`){await this.showGitFilePreview({hash:n.hash,filePath:n.filePath,currentFilePath:n.currentFilePath});return}if(n.type===`git-commit`){await this.showGitCommit({hash:n.hash,path:n.path,historyFilePath:n.historyFilePath});return}if(n.type!==`git-diff`)return;let r=e??n.filePath,i=t??n.scope;if(i!==n.scope||r!==n.filePath){this.navigation.navigateToGitDiff({filePath:r,scope:i});return}await this.showGitDiff({filePath:n.filePath,scope:n.scope})},async finalizeGitAction({action:e,filePath:t=null,preferredScope:n=null,result:r={},showLocalFileToast:i=!1}={}){let a=Wn(r.workspaceChange);return await this.refreshWorkspaceAfterGitAction({filePath:t,preferredScope:n}),this.handleWorkspaceChangeForCurrentFile(a,{action:e,local:!0,showToast:i}),a},handleWorkspaceChangeForCurrentFile(e,{action:t=`git`,local:n=!1,showToast:r=!0}={}){let i=this.currentFilePath;if(!i)return!1;let a=e.deletedPaths.includes(i),o=e.renamedPaths.find(e=>e.oldPath===i);if(!a&&!o)return!1;if(!r)return o?this.navigation.navigateToFile(o.newPath):this.navigation.navigateToFile(null),!0;let s=this.getDisplayName(i);return o?(this.navigation.navigateToFile(o.newPath),this.toastController.show(n?`${s} moved to ${this.getDisplayName(o.newPath)}`:`${s} moved on disk`),!0):(this.navigation.navigateToFile(null),this.toastController.show(n?`${s} was removed by ${t}`:`${s} was removed after a ${t} operation`),!0)},async handleIncomingWorkspaceEvent(e){if(!this.isTabActive||!e)return;if(e.requestId&&this.pendingWorkspaceRequestIds?.has(e.requestId)){this.pendingWorkspaceRequestIds.delete(e.requestId);return}let t=Wn(e.workspaceChange);e.origin===`git`&&await this.refreshGitAfterAction(),this.handleWorkspaceChangeForCurrentFile(t,{action:e.action||e.origin||`workspace`,local:!1,showToast:!0});let n=[...t.changedPaths,...t.deletedPaths,...t.renamedPaths.flatMap(e=>[e.oldPath,e.newPath])].some(e=>/(?:\.dsl$|(?:^|\/)workspace\.json$)/iu.test(e));if(this.currentFilePath&&this.isStructurizrWorkspaceFile?.(this.currentFilePath)&&n&&this.structurizrPreview?.queueSync({filePath:this.currentFilePath,source:this.session?.getText?.()??``}),e.origin===`filesystem`&&this.currentFilePath&&t.changedPaths.includes(this.currentFilePath)){let n=t.changedPaths.length===1&&Array.isArray(e.highlightRanges)?e.highlightRanges.find(e=>e.path===this.currentFilePath):null;n&&this.session?.flashExternalUpdate?.(n)||this.toastController.show(`${this.getDisplayName(this.currentFilePath)} updated from disk`)}this.currentFilePath&&Array.isArray(e.reloadRequiredPaths)&&e.reloadRequiredPaths.includes(this.currentFilePath)&&this.toastController.show(`${this.getDisplayName(this.currentFilePath)} needs a manual reload`)},async stageGitFile(e,{scope:t=`working-tree`}={}){e&&await this.runGitActionWithStatus(`Staging changes...`,async()=>{let n=await this.postGitAction(`stage`,{path:e});await this.finalizeGitAction({action:`stage`,filePath:e,preferredScope:t===`all`?`all`:`staged`,result:n})})},async unstageGitFile(e,{scope:t=`staged`}={}){e&&await this.runGitActionWithStatus(`Unstaging changes...`,async()=>{let n=await this.postGitAction(`unstage`,{path:e});await this.finalizeGitAction({action:`unstage`,filePath:e,preferredScope:t===`all`?`all`:`working-tree`,result:n})})},async pushGitBranch(){await this.runGitActionWithStatus(`Pushing branch...`,async()=>{try{let e=await this.postGitAction(`push`,{});await this.finalizeGitAction({action:`push`,result:e})}catch(e){this.toastController.show(e.message||`Failed to push branch`)}})},async pullGitBranch(){await this.runGitActionWithStatus(`Pulling branch...`,async()=>{try{let e=await this.postGitAction(`pull`,{});await this.finalizeGitAction({action:`pull`,result:e,showLocalFileToast:!0}),e.pullBackup&&this.toastController.show(this.formatPullBackupToast(e.pullBackup),5e3)}catch(e){if(e?.code===`pull_diverged_ff_only`){this.toastController.show(`Cannot pull because local and remote commits have diverged. Fast-forward only pull is not possible.`,5e3);return}if(e?.code===`pull_conflicted_after_autostash`){this.toastController.show(`Pull updated the branch, but reapplying local changes caused conflicts. Review the conflicted files and the pull backup summary.`,6e3);return}this.toastController.show(e.message||`Failed to pull branch`)}})},openGitResetDialog(e){if(!this.isTabActive||!e)return;let t=this.elements.gitResetDialog;!t||!this.elements.gitResetFileName||(this.pendingGitResetPath=e,this.elements.gitResetTitle&&(this.elements.gitResetTitle.textContent=`Reset file to current branch`),this.elements.gitResetCopy&&(this.elements.gitResetCopy.textContent=`Restore this file from the current checked-out branch. If this branch does not contain the file, the file will be deleted locally.`),this.elements.gitResetFileName.value=e,this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`),this.elements.gitResetSubmit?.toggleAttribute(`disabled`,!1),!t.open&&(typeof t.showModal==`function`?t.showModal():t.setAttribute(`open`,`true`)))},async handleGitResetSubmit(){let e=this.pendingGitResetPath,t=this.elements.gitResetDialog,n=this.elements.gitResetSubmit;if(!(!e||!t)){n?.toggleAttribute(`disabled`,!0),n&&(n.textContent=`Resetting...`);try{await this.runGitActionWithStatus(`Resetting file...`,async()=>{let t=await this.postGitAction(`reset-file`,{path:e});await this.finalizeGitAction({action:`reset`,filePath:e,result:t,showLocalFileToast:!0})}),t.close()}catch(e){this.toastController.show(e.message||`Failed to reset file`)}finally{n&&(n.textContent=`Reset File`),n?.toggleAttribute(`disabled`,!1)}}},openGitCommitDialog(){if(!this.isTabActive)return;let e=this.elements.gitCommitDialog,t=this.elements.gitCommitInput;if(!(!e||!t)){if(this.elements.gitCommitTitle&&(this.elements.gitCommitTitle.textContent=`Commit staged changes`),this.elements.gitCommitCopy){let e=Number(this.gitPanel.status?.summary?.staged||0);this.elements.gitCommitCopy.textContent=e>0?`${e} staged file${e===1?``:`s`} will be included.`:`All staged changes will be included.`}this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`),t.value=``,!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,`true`),requestAnimationFrame(()=>{t.focus(),t.select()}))}},async handleGitCommitSubmit(){let e=this.elements.gitCommitDialog,t=this.elements.gitCommitInput,n=this.elements.gitCommitSubmit,r=String(t?.value??``).trim();if(!(!e||!t)){if(!r){t.focus(),this.toastController.show(`Commit message cannot be empty`);return}n?.toggleAttribute(`disabled`,!0),n&&(n.textContent=`Committing...`);try{await this.runGitActionWithStatus(`Committing changes...`,async()=>{let e=await this.postGitAction(`commit`,{message:r});await this.finalizeGitAction({action:`commit`,result:e})}),e.close()}catch(e){this.toastController.show(e.message||`Failed to commit staged changes`)}finally{n&&(n.textContent=`Commit staged changes`),n?.toggleAttribute(`disabled`,!1)}}}},qn=5;function Jn(e,t){return String(e?.name??``).localeCompare(String(t?.name??``),void 0,{sensitivity:`base`})}function Yn(e){let t=!!e.session,n=!!(e.currentFilePath&&e.isDrawioFile?.(e.currentFilePath)),r=!!(e.currentFilePath&&e.isExcalidrawFile?.(e.currentFilePath)),i=!!(e.currentFilePath&&e.isImageFile?.(e.currentFilePath)),a=!!(e.currentFilePath&&e.isPdfFile?.(e.currentFilePath));return!t&&(!e.currentFilePath||n||r||i||a)?e.lobby?.getConnectionState?.()??e.connectionState:e.connectionState}function Xn(e,t){let n=[...e],r=n.findIndex(e=>e.isLocal);if(r>0){let[e]=n.splice(r,1);n.unshift(e)}let i=n.findIndex(e=>!e.isLocal&&e.clientId===t),a=+!!n[0]?.isLocal;if(i>a){let[e]=n.splice(i,1);n.splice(a,0,e)}return n}function Zn(e,t){let n=e.filter(e=>e.isLocal).sort(Jn),r=e.filter(e=>!e.isLocal),i=r.filter(e=>e.clientId===t).sort(Jn),a=r.filter(e=>e.clientId!==t).sort(Jn);return[...n,...i,...a]}function Qn(e,t){return t.currentFile&&t.currentFile===e.currentFilePath?`Here`:t.currentFile?e.getDisplayName(t.currentFile):`No file`}var $n={updateGlobalUsers(e){this.globalUsers=e,this.syncFollowedUser(),this.renderAvatars(),this.renderChat({messagesChanged:!1}),this.renderPresence(),this.syncCurrentUserName()},updateFileAwareness(e){this.syncFollowedUser()},renderPresence(){let e=this.elements.userCount;if(!e)return;let t=Yn(this),n=this.globalUsers.length>0;if(t.status!==`connected`&&(this.presencePanelOpen=!1),e.type=`button`,e.setAttribute(`aria-controls`,`presencePanel`),e.setAttribute(`aria-expanded`,String(this.presencePanelOpen)),e.classList.toggle(`is-active`,this.presencePanelOpen),t.status===`connected`){e.textContent=`${this.globalUsers.length} online`,e.style.opacity=`1`,e.disabled=!n,e.setAttribute(`aria-label`,`Show ${this.globalUsers.length} online users`),this.renderPresencePanel();return}if(t.status===`connecting`){e.textContent=t.unreachable?`Unreachable`:`Connecting...`,e.style.opacity=`0.6`,e.disabled=!0,e.setAttribute(`aria-label`,e.textContent),this.renderPresencePanel();return}e.textContent=`Offline`,e.style.opacity=`0.6`,e.disabled=!0,e.setAttribute(`aria-label`,`Offline`),this.renderPresencePanel()},renderAvatars(){let e=this.elements.userAvatars;if(!e)return;e.replaceChildren();let t=Xn(this.globalUsers,this.followedUserClientId);if(t.slice(0,qn).forEach(t=>{let n=document.createElement(t.isLocal?`div`:`button`);n.className=`user-avatar`,n.classList.toggle(`is-local`,t.isLocal),n.style.backgroundColor=t.color,n.style.color=De(t.color),n.classList.toggle(`is-following`,t.clientId===this.followedUserClientId);let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=t.name.charAt(0).toUpperCase(),n.appendChild(r);let i=t.currentFile&&t.currentFile===this.currentFilePath,a=t.currentFile?this.getDisplayName(t.currentFile):`No file`;if(t.isLocal){let e=document.createElement(`span`);e.className=`user-avatar-self-label`,e.textContent=`You`,n.appendChild(e),n.title=`${t.name} (you) — ${a}`,n.setAttribute(`role`,`img`),n.setAttribute(`aria-label`,`${t.name} (you) — ${a}`)}else{n.type=`button`,n.classList.add(`user-avatar-button`),i||n.classList.add(`different-file`);let e=t.clientId===this.followedUserClientId?`Stop following ${t.name}`:i?`Follow ${t.name}`:`Follow ${t.name} — ${a}`;n.title=e,n.setAttribute(`aria-label`,e),n.addEventListener(`click`,()=>this.toggleFollowUser(t.clientId))}e.appendChild(n)}),t.length>qn){let n=document.createElement(`button`);n.type=`button`,n.className=`user-avatar user-avatar-button user-avatar-overflow-trigger`,n.style.backgroundColor=`var(--color-surface-dynamic)`,n.style.color=`var(--color-text-muted)`,n.setAttribute(`aria-controls`,`presencePanel`),n.setAttribute(`aria-expanded`,String(this.presencePanelOpen)),n.setAttribute(`aria-label`,`Show ${t.length} online users`),n.setAttribute(`data-presence-panel-trigger`,`true`),n.title=`Show ${t.length} online users`,n.addEventListener(`click`,()=>this.openPresencePanel());let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=`+${t.length-qn}`,n.appendChild(r),e.appendChild(n)}},openPresencePanel(){Yn(this).status===`connected`&&this.globalUsers.length!==0&&(this.presencePanelOpen=!0,this.closeChatPanel?.(),this.closeToolbarOverflowMenu?.(),this.renderAvatars(),this.renderPresence())},closePresencePanel(){this.presencePanelOpen&&(this.presencePanelOpen=!1,this.renderAvatars(),this.renderPresence())},togglePresencePanel(){if(this.presencePanelOpen){this.closePresencePanel();return}this.openPresencePanel()},renderPresencePanel(){let e=this.elements.presencePanel,t=this.elements.presencePanelList,n=this.elements.presencePanelStatus;if(!e||!t||(e.classList.toggle(`hidden`,!this.presencePanelOpen),e.setAttribute(`aria-hidden`,String(!this.presencePanelOpen)),!this.presencePanelOpen))return;let r=Zn(this.globalUsers,this.followedUserClientId),i=Yn(this);if(n){if(i.status===`connected`){let e=this.globalUsers.filter(e=>!e.isLocal).length;n.textContent=e===0?`You’re the only person here right now.`:`${e} ${e===1?`teammate`:`teammates`} online. Select someone to follow.`}else n.textContent=i.status===`connecting`?i.unreachable?`Server unreachable.`:`Connecting presence...`:`Presence is offline.`}if(t.replaceChildren(),r.length===0){let e=document.createElement(`div`);e.className=`presence-panel-empty-state`,e.textContent=i.status===`connected`?`Nobody else is here yet.`:`Presence will appear here when the connection is active.`,t.appendChild(e);return}let a=document.createDocumentFragment();r.forEach(e=>{let t=document.createElement(`article`);t.className=`presence-panel-user`,t.classList.toggle(`is-local`,e.isLocal),t.classList.toggle(`is-following`,e.clientId===this.followedUserClientId);let n=document.createElement(e.isLocal?`div`:`button`);n.className=`presence-panel-user-button`;let r=document.createElement(`span`);r.className=`presence-panel-user-avatar`,r.style.backgroundColor=e.color,r.style.color=De(e.color),r.textContent=e.name.charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`span`);i.className=`presence-panel-user-body`;let o=document.createElement(`span`);o.className=`presence-panel-user-topline`;let s=document.createElement(`span`);if(s.className=`presence-panel-user-name`,s.textContent=e.name,o.appendChild(s),e.isLocal){let e=document.createElement(`span`);e.className=`presence-panel-user-badge`,e.textContent=`You`,o.appendChild(e)}else if(e.clientId===this.followedUserClientId){let e=document.createElement(`span`);e.className=`presence-panel-user-badge`,e.textContent=`Following`,o.appendChild(e)}let c=document.createElement(`span`);if(c.className=`presence-panel-user-file`,c.textContent=Qn(this,e),i.append(o,c),n.append(r,i),e.isLocal)n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,`${e.name} (you) — ${c.textContent}`);else{let t=e.clientId===this.followedUserClientId;n.type=`button`,n.setAttribute(`aria-label`,t?`Keep following ${e.name}`:`Follow ${e.name} — ${c.textContent}`),n.addEventListener(`click`,()=>{this.startFollowingUser(e.clientId,{closePanel:!0})})}if(t.appendChild(n),!e.isLocal&&e.clientId===this.followedUserClientId){let n=document.createElement(`button`);n.type=`button`,n.className=`presence-panel-user-stop`,n.textContent=`Stop`,n.setAttribute(`aria-label`,`Stop following ${e.name}`),n.addEventListener(`click`,e=>{e.stopPropagation(),this.stopFollowingUser({closePanel:!0})}),t.appendChild(n)}a.appendChild(t)}),t.appendChild(a)},startFollowingUser(e,{closePanel:t=!1}={}){if(!e)return;let n=this.globalUsers.find(t=>t.clientId===e&&!t.isLocal);if(n){if(this.followedUserClientId=e,this.followedCursorSignature=``,t&&this.presencePanelOpen?this.closePresencePanel():(this.renderAvatars(),this.renderPresencePanel()),n.currentFile&&n.currentFile!==this.currentFilePath){this.navigation.navigateToFile(n.currentFile);return}requestAnimationFrame(()=>{this.followedUserClientId===e&&this.followUserCursor(n,{force:!0})})}},toggleFollowUser(e){if(e){if(this.followedUserClientId===e){this.stopFollowingUser();return}this.startFollowingUser(e)}},stopFollowingUser({closePanel:e=!1}={}){this.followedUserClientId&&(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)&&this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,null),this.followedUserClientId=null,this.followedCursorSignature=``,e&&this.presencePanelOpen?this.closePresencePanel():(this.renderAvatars(),this.renderPresencePanel()))},syncFollowedUser(){if(!this.followedUserClientId)return;let e=this.globalUsers.find(e=>e.clientId===this.followedUserClientId);if(!e||e.isLocal){this.stopFollowingUser();return}if(e.currentFile&&e.currentFile!==this.currentFilePath){this.navigation.navigateToFile(e.currentFile);return}this.followUserCursor(e)},followUserCursor(e,{force:t=!1}={}){if(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)){this.followExcalidrawUser(e,{force:t});return}let n=this.resolveFileClientId(e.peerId),r=n==null?null:this.session?.getUserViewport(n),i=n==null?null:this.session?.getUserCursor(n),a=i?.cursorHead??null,o=i?.cursorLine??null,s=i?.cursorAnchor??null,c=r?.topLine??null,l=r?.viewportRatio??.35;if(!e||c==null&&(a==null||o==null)){this.followedCursorSignature=``;return}let u=`${e.clientId}:${c??`no-viewport`}:${s??`no-anchor`}:${a??`no-head`}`;!t&&u===this.followedCursorSignature||(n!=null&&this.session?.scrollToUserViewport(n)||n!=null&&this.session?.scrollToUserCursor(n,`center`)||a!=null&&this.session?.scrollToPosition(a,`center`)||o!=null&&this.session?.scrollToLine(o,l))&&(this.followedCursorSignature=u)},followExcalidrawUser(e,{force:t=!1}={}){if(!e?.peerId||!this.currentFilePath){this.followedCursorSignature=``;return}let n=`excalidraw:${this.currentFilePath}:${e.peerId}`;!t&&n===this.followedCursorSignature||Promise.resolve(this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,e.peerId)).then(t=>{t!==!1&&this.followedUserClientId===e.clientId&&(this.followedCursorSignature=n)}).catch(()=>{})},resolveFileClientId(e){if(!e||!this.session?.awareness)return null;for(let[t,n]of this.session.awareness.getStates())if(n.user?.peerId===e)return t;return null}};function er(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function tr({mode:e=`edit`}={}){if(this.isIdentityManagedByAuth()||!this.isTabActive)return;let t=this.elements.displayNameDialog,n=this.elements.displayNameInput,r=this.elements.displayNameTitle,i=this.elements.displayNameCopy,a=this.elements.displayNameCancel,o=this.elements.displayNameSubmit;if(!t||!n)return;let s=e===`onboarding`;r&&(r.textContent=s?`Choose your display name`:`Update display name`),i&&(i.textContent=s?`Pick a name collaborators will see. You can skip for now and continue as a guest.`:`Your name will be visible to everyone editing this vault.`),a&&(a.textContent=s?`Skip for now`:`Cancel`),o&&(o.textContent=s?`Continue`:`Save name`),n.value=s?``:this.getCurrentUserName(),!t.open&&(typeof t.showModal==`function`?t.showModal():t.setAttribute(`open`,`true`),requestAnimationFrame(()=>{n.focus(),n.select()}))}function nr(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function rr(){if(this.isIdentityManagedByAuth())return;let e=this.elements.displayNameInput,t=this.elements.displayNameDialog;if(!e||!t)return;let n=this.session?this.session.setUserName(e.value):Oe(e.value);if(!n){e.focus(),this.toastController.show(`Name must be 1-24 characters`);return}this.preferences.setUserName(n),this.lobby.setUserName(n);let r=this.lobby.getLocalUser();this.drawioEmbed?.updateLocalUser(r),this.excalidrawEmbed?.updateLocalUser(r),this.syncCurrentUserName(),this.renderChat(),t.close()}function ir(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function ar(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function or(){return this.preferences.getUserName()}function sr(){let e=this.elements.currentUserName;if(!e)return;let t=this.getCurrentUserName();e.textContent=t||`Set name`,e.classList.toggle(`has-name`,!!t),this.isIdentityManagedByAuth()||this.elements.editNameButton?.setAttribute(`aria-label`,`${t||`Set name`}. Change display name`)}function cr(){let e=this.isIdentityManagedByAuth();this.elements.editNameButton?.classList.toggle(`hidden`,e),this.elements.editNameButton?.toggleAttribute(`disabled`,e),e&&this.elements.displayNameDialog?.open&&this.elements.displayNameDialog.close()}var lr={getCurrentUser:ir,getCurrentUserName:ar,getStoredUserName:or,handleDisplayNameSubmit:rr,isIdentityManagedByAuth:er,openDisplayNameDialog:tr,promptForDisplayNameIfNeeded:nr,syncCurrentUserName:sr,syncIdentityManagementUi:cr},ur=0,dr=2e3,fr=8,pr=`
|
|
42
|
-
<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false">
|
|
43
|
-
<path d="M10 13.5 14 9.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
|
44
|
-
<path d="M9.35 7.55 10.6 6.3a4.2 4.2 0 0 1 5.95 5.95l-1.25 1.25" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
|
45
|
-
<path d="m14.65 16.45-1.25 1.25a4.2 4.2 0 0 1-5.95-5.95L8.7 10.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
|
46
|
-
</svg>
|
|
47
|
-
`;function mr(){this.initializeExportBridge?.(),this.renderMarkdownToolbar?.(),this.initializeVisualViewportBinding?.(),this.themeController.initialize(),this.previewRenderer.applyTheme(this.themeController.getTheme()),this.previewRenderer.scheduleWorkerPrewarm(),this.scheduleEditorSessionPrewarm?.(),this.outlineController.initialize(),this.layoutController.initialize(),this.scrollSyncController.initialize(),this.fileExplorer.initialize(),this.gitPanel.initialize(),this.gitDiffView.initialize(),this.fileHistoryView.initialize(),this.commentsOverview?.initialize?.(),this.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncVimModeToggle(),this.syncToolbarOverflowVisibility?.(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.initializeSidebarResizer?.(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.workspaceRouteController.handleHashChange());let e=this.createResizeHandler();window.addEventListener(`resize`,()=>{e(),this.syncToolbarOverflowVisibility?.()}),this.fileExplorerReadyPromise=this.fileExplorer.refresh().then(()=>{if(this.fileExplorerReady=!0,this.commentsOverview?.refresh?.(),this.runtimeConfig?.gitEnabled!==!1&&this.gitPanel.refresh({force:!0}),this.isTabActive)return this.workspaceRouteController.handleHashChange()})}function hr(){this.versionMonitor?.start()}function gr(){let e=document.documentElement,t=window.visualViewport;if(e){if(!t){e.style.setProperty(`--app-viewport-height`,`100dvh`),e.style.setProperty(`--app-viewport-offset-top`,`0px`);return}e.style.setProperty(`--app-viewport-height`,`${Math.round(t.height)}px`),e.style.setProperty(`--app-viewport-offset-top`,`${Math.round(t.offsetTop)}px`)}}function _r(){this.syncVisualViewportBounds?.();let e=window.visualViewport;if(!e)return;let t=()=>this.syncVisualViewportBounds?.();e.addEventListener(`resize`,t,{passive:!0}),e.addEventListener(`scroll`,t,{passive:!0}),window.addEventListener(`orientationchange`,t)}function vr(e=null){if(this._reloadPromptShown)return;this._reloadPromptShown=!0;let t=String(e?.build?.packageVersion??this.runtimeConfig?.build?.packageVersion??``).trim(),n=t?`Version ${t} is available. Reload to update.`:`A new version is available. Reload to update.`;this.toastController.show(n,{actionLabel:`Reload`,dismissible:!0,duration:ur,onAction:()=>window.location.reload()})}function yr(){let e=()=>{this.toggleQuickSwitcher(),this.closeToolbarOverflowMenu?.()};this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.toolbarSearchButton?.addEventListener(`click`,e),this.elements.searchFilesButton?.addEventListener(`click`,e),this.elements.exportDocxButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`docx`),this.closeToolbarOverflowMenu?.()}),this.elements.exportPdfButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`pdf`),this.closeToolbarOverflowMenu?.()}),this.elements.fileHistoryButton?.addEventListener(`click`,()=>{let e=this.navigation.getHashRoute();if(e.type===`git-file-preview`){this.handleGitFileHistorySelection(e.currentFilePath??e.filePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.();return}this.handleGitFileHistorySelection(this.currentFilePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.()}),this.elements.editNameButton?.addEventListener(`click`,()=>{this.openDisplayNameDialog(),this.closeToolbarOverflowMenu?.()})}function br(){this.elements.displayNameCancel?.addEventListener(`click`,()=>{this.elements.displayNameDialog?.close()}),this.elements.gitCommitCancel?.addEventListener(`click`,()=>{this.elements.gitCommitDialog?.close()}),this.elements.gitResetCancel?.addEventListener(`click`,()=>{this.elements.gitResetDialog?.close()}),this.elements.gitResetSubmit?.addEventListener(`click`,()=>{this.handleGitResetSubmit()}),this.elements.gitCommitDialog?.addEventListener(`close`,()=>{this.elements.gitCommitInput&&(this.elements.gitCommitInput.value=``),this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`)}),this.elements.gitResetDialog?.addEventListener(`close`,()=>{this.pendingGitResetPath=null,this.elements.gitResetFileName&&(this.elements.gitResetFileName.value=``),this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`)}),this.elements.displayNameForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleDisplayNameSubmit()}),this.elements.gitCommitForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleGitCommitSubmit()})}function xr(){this.elements.emptyStateNewFileBtn?.addEventListener(`click`,()=>{this.fileExplorer.actionController.openRootCreateMenu({anchor:this.elements.emptyStateNewFileBtn})}),this.elements.emptyStateSearchBtn?.addEventListener(`click`,()=>{this.toggleQuickSwitcher()}),this.elements.chatToggleButton?.addEventListener(`click`,()=>{this.closePresencePanel?.(),this.toggleChatPanel(),this.closeToolbarOverflowMenu?.()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),this.elements.chatNotificationMuteButton?.addEventListener(`click`,()=>{this.toggleChatNotificationMute()}),this.elements.chatCloseButton?.addEventListener(`click`,()=>{this.closeChatPanel({restoreFocus:!0})}),this.elements.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),yr.call(this),br.call(this),this.elements.markdownToolbar?.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),this.elements.markdownToolbar?.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),this.elements.tabLockTakeoverButton?.addEventListener(`click`,()=>{this.handleTabTakeover()}),this.elements.toggleWrapButton?.addEventListener(`click`,()=>{this.toggleLineWrapping()}),this.elements.toggleVimModeButton?.addEventListener(`click`,()=>{this.toggleVimMode()}),this.elements.userCount?.addEventListener(`click`,e=>{e.preventDefault(),this.togglePresencePanel?.()}),this.elements.editorFindButton?.addEventListener(`click`,()=>{this.runEditorCommand?.(`openSearch`)}),this.elements.toolbarOverflowToggle?.addEventListener(`click`,e=>{e.preventDefault(),this.closePresencePanel?.(),this.toggleToolbarOverflowMenu()}),this.elements.toolbarOverflowMenu?.addEventListener(`click`,e=>{let t=e.target instanceof Element?e.target.closest(`button`):null;t&&t!==this.elements.toggleVimModeButton&&this.closeToolbarOverflowMenu()}),this.elements.previewContent?.addEventListener(`click`,e=>{this.handlePreviewContentClick?.(e)}),this.elements.sidebarToggle?.addEventListener(`click`,()=>{this.closeToolbarOverflowMenu(),this.toggleSidebar()}),this.elements.sidebarClose?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.sidebarBackdrop?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.filesSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`files`)}),this.elements.gitSidebarTab?.addEventListener(`click`,()=>{this.gitRepoAvailable&&this.setSidebarTab(`git`)}),this.elements.commentsSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`comments`)}),document.addEventListener(`pointerdown`,e=>{this.handleDocumentPointerDown(e)}),document.addEventListener(`keydown`,e=>{this.handleDocumentKeydown(e)},{capture:!0})}function Sr(e){this.handleMarkdownToolbarDocumentPointerDown?.(e);let t=e.target instanceof Element?e.target:null;this.toolbarOverflowOpen&&!this.elements.toolbarOverflowMenu?.contains(t)&&!this.elements.toolbarOverflowToggle?.contains(t)&&this.closeToolbarOverflowMenu(),this.presencePanelOpen&&!this.elements.presencePanel?.contains(t)&&!t?.closest?.(`[data-presence-panel-trigger="true"]`)&&this.closePresencePanel?.(),this.chatIsOpen&&(this.elements.chatContainer?.contains(t)||this.closeChatPanel({restoreFocus:!1}))}function Cr(e){if(e.key===`Escape`&&this.toolbarOverflowOpen){this.closeToolbarOverflowMenu();return}if(e.key===`Escape`&&this.presencePanelOpen){this.closePresencePanel?.();return}if(e.key===`Escape`&&this.chatIsOpen){this.closeChatPanel({restoreFocus:!0});return}E(e)&&(e.preventDefault(),e.stopPropagation(),this.toggleQuickSwitcher())}function wr(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function Tr(e){return!e.closest(`input[data-task-checkbox="true"]`)&&!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function Er(e){let t=window.getSelection();return!!(!t?.isCollapsed&&e.contains(t.anchorNode)&&e.contains(t.focusNode))}function Dr(e=``){let t=String(e??``).trim();if(!t)return``;try{return decodeURIComponent(t)}catch{return t}}function Or(e,t,{behavior:n=`smooth`}={}){if(!e||!t)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=e.scrollTop+(i.top-r.top);e.scrollTo({behavior:n,top:Math.max(a,0)})}async function kr(e){await navigator.clipboard.writeText(e)}function Ar(e){if(!(e instanceof HTMLElement))return``;let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`.preview-heading-link-button`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()):e.textContent.trim()}function jr(){return globalThis.performance?.now?.()??Date.now()}function Mr(e,t,{behavior:n=`auto`}={}){if(!(e instanceof HTMLElement)||!t)return!1;if(this.outlineController?.navigateToHeading?.(e,t,{behavior:n}))return!0;let r=this.elements.previewContainer??document.getElementById(`previewContainer`);if(!r)return!1;this.scrollSyncController?.suspendSync?.(250),Or(r,e,{behavior:n});let i=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);return Number.isFinite(i)&&this.session?.scrollToLine?.(i,0),!0}function Nr(e){if(!this.currentFilePath||!e)return``;let t=new URL(window.location.href);return t.hash=de(this.currentFilePath,{anchor:e,drawioMode:this.currentDrawioMode??null}),t.toString()}async function Pr(e){let t=this.createPreviewHeadingLinkUrl(e);if(!t){this.toastController.show(`Failed to copy section link`);return}try{await kr(t),this.toastController.show(`Section link copied`)}catch{this.toastController.show(`Failed to copy section link`)}}function Fr(){let e=this.elements.previewContent?.querySelectorAll?.(`h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]`)??[];Array.from(e).forEach(e=>{if(!(e instanceof HTMLElement)||!e.id)return;let t=Ar(e),n=e.querySelector(`:scope > .preview-heading-link-button`);n instanceof HTMLButtonElement||(n=document.createElement(`button`),n.type=`button`,n.className=`ui-icon-button preview-heading-link-button`,n.innerHTML=pr,e.appendChild(n)),n.dataset.previewHeadingAnchor=e.id,n.setAttribute(`aria-label`,`Copy link to ${t}`),n.setAttribute(`title`,`Copy link to this section`)})}function Ir(e,t=this.currentFilePath){let n=String(e??``).trim();return this._pendingPreviewRouteAnchor=n?{applied:!1,appliedCount:0,anchorId:n,filePath:t??this.currentFilePath??null,stabilizeUntil:jr()+dr}:null,this._pendingPreviewRouteAnchor?this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!1}):!1}function Lr({allowExpired:e=!1,behavior:t=`auto`,clearMissing:n=!1}={}){let r=this._pendingPreviewRouteAnchor;if(!r)return!1;if(!e&&r.applied&&r.stabilizeUntil<=jr())return this._pendingPreviewRouteAnchor=null,!1;if(r.filePath&&this.currentFilePath&&r.filePath!==this.currentFilePath)return!1;let i=document.getElementById(r.anchorId);return!(i instanceof HTMLElement)||!this.elements.previewContent?.contains(i)?(!r.applied&&n&&r.filePath&&r.filePath===this.currentFilePath&&(this._pendingPreviewRouteAnchor=null),!1):this.navigatePreviewHeading(i,r.anchorId,{behavior:t})?(r.applied=!0,r.appliedCount=(r.appliedCount??0)+1,r.stabilizeUntil=jr()+dr,r.appliedCount>=fr&&(this._pendingPreviewRouteAnchor=null),!0):!1}function Rr(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`button.preview-heading-link-button[data-preview-heading-anchor]`);if(t instanceof HTMLButtonElement){e.preventDefault(),this.copyPreviewHeadingLink(t.dataset.previewHeadingAnchor||``);return}let n=e.target.closest(`a.wiki-link[data-wiki-target]`);if(n){e.preventDefault(),this.wikiLinkFileController.handleWikiLinkClick(n.dataset.wikiTarget);return}let r=e.target.closest(`a[href]`),i=r?.getAttribute(`href`)?.trim()||``;if(r&&i.startsWith(`#`)&&!le(i)){if(e.preventDefault(),i===`#`||i.toLowerCase()===`#top`){this.scrollSyncController?.suspendSync?.(250),(this.elements.previewContainer??document.getElementById(`previewContainer`))?.scrollTo({top:0,behavior:`smooth`});return}let t=Dr(i.slice(1));if(!t)return;let n=document.getElementById(t);if(!n||!this.elements.previewContent?.contains(n))return;this.navigatePreviewHeading(n,t,{behavior:`smooth`});return}let a=e.target.closest(`.task-list-item[data-source-line]`);if(!a||wr(e.target,a)||Tr(e.target)||Er(a))return;e.preventDefault();let o=Number.parseInt(a.getAttribute(`data-source-line`)||``,10);Number.isFinite(o)&&this.session?.toggleTaskListItem?.(o)}function zr(e){this.toolbarOverflowOpen=!!e,this.elements.toolbarOverflowToggle?.setAttribute(`aria-expanded`,String(this.toolbarOverflowOpen)),this.elements.toolbarOverflowToggle?.classList.toggle(`active`,this.toolbarOverflowOpen),this.elements.toolbarOverflowToggle?.closest(`.toolbar-right`)?.classList.toggle(`is-overflow-open`,this.toolbarOverflowOpen),this.toolbarOverflowOpen||this.elements.toolbarOverflowMenu?.querySelectorAll(`details[open]`).forEach(e=>{e.removeAttribute(`open`)})}function Br(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Vr(){this.setToolbarOverflowOpen(!1)}function Hr(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function Ur(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&!this.isPdfFile?.(this.currentFilePath)&&!this.isStructurizrWorkspaceFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e)}function Wr(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),this.renderChat({messagesChanged:!1}),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function Gr(){let e=!(this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping());this.session?.setLineWrapping(e),this.preferences.setLineWrappingEnabled(e),this.syncWrapToggle(e),this.session?.requestMeasure(),this.scrollSyncController.syncPreviewToEditor()}function Kr(){return this.preferences.getLineWrappingEnabled()}function qr(){let e=!(this.session?.isVimModeEnabled?.()??this.getStoredVimMode());this.session?.setVimMode?.(e),this.preferences.setVimModeEnabled(e),this.syncVimModeToggle(e)}function Jr(){return this.preferences.getVimModeEnabled()}function Yr(e){let t=e??this.session?.isVimModeEnabled?.()??this.getStoredVimMode(),n=this.elements.vimModeToggleLabel,r=this.elements.toggleVimModeButton;n&&(n.textContent=t?`On`:`Off`),r&&(r.setAttribute(`aria-label`,`${t?`Disable`:`Enable`} Vim keybindings`),r.setAttribute(`title`,`${t?`Disable`:`Enable`} Vim keybindings`),r.setAttribute(`aria-pressed`,String(t)))}function Xr(e){let t=e??this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping(),n=this.elements.wrapToggleLabel,r=this.elements.toggleWrapButton,i=t?`Wrap on`:`Wrap off`;n&&(n.textContent=i),r&&r.setAttribute(`aria-label`,`${i}. ${t?`Disable line wrap`:`Enable line wrap`}`)}function Zr(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{t(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function Qr(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
48
|
-
<div class="editor-loading" id="editorLoading">
|
|
49
|
-
<div class="loading-spinner"></div>
|
|
50
|
-
<span class="loading-text">Loading file...</span>
|
|
51
|
-
</div>`)}function $r(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.querySelector(`#editorLoading`)?.remove())}function ei(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
52
|
-
<div class="editor-loading" id="editorLoading">
|
|
53
|
-
<span class="loading-text">Failed to load file</span>
|
|
54
|
-
</div>`)}function ti(){document.documentElement.removeAttribute(`data-initial-file-requested`)}var ni={applyPendingPreviewRouteAnchor:Lr,bindEvents:xr,clearInitialFileBootstrap:ti,closeToolbarOverflowMenu:Vr,copyPreviewHeadingLink:Pr,createPreviewHeadingLinkUrl:Nr,getStoredLineWrapping:Kr,getStoredVimMode:Jr,handleConnectionChange:Wr,handleDocumentKeydown:Cr,handleDocumentPointerDown:Sr,handlePreviewContentClick:Rr,handleThemeChange:Ur,hideEditorLoading:$r,initialize:mr,initializeVisualViewportBinding:_r,initializeVersionMonitoring:hr,isPlainQuickSwitcherShortcut:E,navigatePreviewHeading:Mr,promptForVersionReload:vr,requestPreviewRouteAnchor:Ir,scheduleBacklinkRefresh:Zr,setToolbarOverflowOpen:zr,showEditorLoadError:ei,showEditorLoading:Qr,syncPreviewHeadingLinkButtons:Fr,syncVisualViewportBounds:gr,syncToolbarOverflowVisibility:Br,syncVimModeToggle:Yr,syncWrapToggle:Xr,toggleToolbarOverflowMenu:Hr,toggleLineWrapping:Gr,toggleVimMode:qr},ri=260,ii=220,ai=420,oi=16;function si(){let e=this.elements.sidebar,t=this.elements.sidebarResizer;if(!e||!t)return;let n=ri,r=null,i=0,a=ri,o=e=>Math.round(Math.max(ii,Math.min(ai,e))),s=r=>{n=o(r),e.style.setProperty(`--sidebar-width`,`${n}px`),t.setAttribute(`aria-valuenow`,String(n))},c=t=>{(t?.pointerId==null||t.pointerId===r)&&r!==null&&(r=null,e.classList.remove(`is-resizing`),document.body.style.cursor=``,document.body.style.userSelect=``)};s(ri),t.addEventListener(`pointerdown`,o=>{this.isMobileViewport()||e.classList.contains(`collapsed`)||(r=o.pointerId,i=o.clientX,a=e.getBoundingClientRect().width||n,e.classList.add(`is-resizing`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,t.setPointerCapture?.(o.pointerId),o.preventDefault())}),t.addEventListener(`pointermove`,e=>{e.pointerId===r&&s(a+e.clientX-i)}),t.addEventListener(`pointerup`,c),t.addEventListener(`pointercancel`,c),t.addEventListener(`lostpointercapture`,c),t.addEventListener(`keydown`,t=>{if(!(this.isMobileViewport()||e.classList.contains(`collapsed`))){if(t.key===`ArrowLeft`||t.key===`ArrowRight`){t.preventDefault(),s(n+(t.key===`ArrowRight`?oi:-16));return}(t.key===`Home`||t.key===`End`)&&(t.preventDefault(),s(t.key===`Home`?ii:ai))}})}function ci(){return this.mobileBreakpointQuery.matches}function li(){let e=this.elements.sidebar;!e||!this.isMobileViewport()||e.classList.contains(`collapsed`)||this.setSidebarVisibility(!1)}function ui(){let e=this.elements.sidebar;if(!e)return;let t=e.classList.contains(`collapsed`);this.setSidebarVisibility(t)}function di(){if(!this.elements.sidebar)return;let e=this.isMobileViewport(),t=this.preferences.getSidebarVisible(),n=!0;t===`true`?n=!0:(t===`false`||e)&&(n=!1),this.applySidebarVisibility(n)}function fi(e){this.applySidebarVisibility(e),this.preferences.setSidebarVisible(e)}function pi(e){let t=this.elements.sidebar;if(!t)return;let n=this.isMobileViewport(),r=!e,i=r&&n,a=e&&n;t.classList.toggle(`collapsed`,r),t.toggleAttribute(`hidden`,i),t.setAttribute(`aria-hidden`,r?`true`:`false`),t.inert=r;let o=this.elements.sidebarBackdrop;o?.toggleAttribute(`hidden`,!a),o?.setAttribute(`aria-hidden`,a?`false`:`true`),o&&(o.inert=!a)}function mi(e){let t=e===`git`&&this.gitRepoAvailable?`git`:e===`comments`?`comments`:`files`;this.activeSidebarTab=t,this.elements.filesSidebarTab?.classList.toggle(`active`,t===`files`),this.elements.commentsSidebarTab?.classList.toggle(`active`,t===`comments`),this.elements.gitSidebarTab?.classList.toggle(`active`,t===`git`),document.getElementById(`fileTree`)?.classList.toggle(`hidden`,t!==`files`),this.elements.fileSearch?.classList.toggle(`hidden`,t!==`files`),this.elements.commentOverviewPanel?.classList.toggle(`hidden`,t!==`comments`),this.elements.gitSearch?.classList.toggle(`hidden`,t!==`git`),document.getElementById(`gitPanel`)?.classList.toggle(`active`,t===`git`),document.getElementById(`gitPanel`)?.classList.toggle(`hidden`,t!==`git`),this.gitPanel.setActive(t===`git`),t===`comments`&&this.refreshCommentOverviewForSidebarOpen?.()}var hi={applySidebarVisibility:pi,closeSidebarOnMobile:li,initializeSidebarResizer:si,isMobileViewport:ci,restoreSidebarState:di,setSidebarTab:mi,setSidebarVisibility:fi,toggleSidebar:ui};function gi(){this.tabActivityLock.tryActivate({takeover:!0})}function _i({takeover:e=!1}={}){let t=!this.isTabActive;this.isTabActive=!0,this.hideTabLockOverlay(),this.lobby.provider||this.lobby.connect(),this.workspaceSync.provider||this.workspaceSync.connect(),t&&(this.fileExplorerReady&&this.workspaceRouteController.handleHashChange(),this.promptForDisplayNameIfNeeded()),e&&this.toastController.show(`This tab is now active`)}async function vi({reason:e}={}){let t=this.isTabActive,n=this.currentFilePath,r=!!(n&&this.isExcalidrawFile?.(n));this.isTabActive=!1,this.elements.displayNameDialog?.open&&this.elements.displayNameDialog.close(),this.lobby.disconnect(),this.workspaceSync.disconnect(),this.globalUsers=[],this.chatMessages=[],this.chatMessageIds.clear(),this.chatUnreadCount=0,this.chatInitialSyncComplete=!1,this.presencePanelOpen=!1,this.followedUserClientId=null,this.followedCursorSignature=``,this.connectionState={status:`disconnected`,unreachable:!1},this.showTabLockOverlay({reason:e}),r&&await this.excalidrawEmbed.prepareFileDisconnect(n),this.showEmptyState(),this.renderChat(),t&&e===`taken-over`&&this.toastController.show(`Another tab took over this session`)}function yi({reason:e}={}){let t=this.elements.tabLockOverlay,n=this.elements.tabLockTitle,r=this.elements.tabLockCopy;t&&(n&&(n.textContent=e===`taken-over`?`This tab is no longer active`:`This vault is active in another tab`),r&&(r.textContent=e===`taken-over`?`Another tab took over the live session. This tab is now disconnected until you explicitly take over here again.`:`To avoid duplicate presence and chat, only one tab can stay connected at a time. Use the other tab, or take over the session here.`),t.classList.remove(`hidden`))}function bi(){this.elements.tabLockOverlay?.classList.add(`hidden`)}var xi={handleTabActivated:_i,handleTabBlocked:vi,handleTabTakeover:gi,hideTabLockOverlay:bi,showTabLockOverlay:yi},B=Object.freeze({bold:`
|
|
55
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
56
|
-
<path d="M7 5h6a4 4 0 0 1 0 8H7z"/>
|
|
57
|
-
<path d="M7 13h7a4 4 0 0 1 0 8H7z"/>
|
|
58
|
-
</svg>
|
|
59
|
-
`,italic:`
|
|
60
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
61
|
-
<path d="M14 4h6"/>
|
|
62
|
-
<path d="M4 20h6"/>
|
|
63
|
-
<path d="M14 4 10 20"/>
|
|
64
|
-
</svg>
|
|
65
|
-
`,strikethrough:`
|
|
66
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
67
|
-
<path d="M6 6.5c1.4-1.2 3.2-1.9 5.4-1.9 3.1 0 5.6 1.4 5.6 3.9 0 2.1-1.7 3-4.3 3.5l-2.4.5c-2.7.5-4.3 1.6-4.3 3.6 0 2.7 2.7 4.2 6 4.2 2.1 0 4.2-.6 5.7-1.8"/>
|
|
68
|
-
<path d="M3 12h18"/>
|
|
69
|
-
</svg>
|
|
70
|
-
`,link:`
|
|
71
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
72
|
-
<path d="M10 13a5 5 0 0 0 7.54.54l2.92-2.92a5 5 0 0 0-7.07-7.07L11.5 5.4"/>
|
|
73
|
-
<path d="M14 11a5 5 0 0 0-7.54-.54L3.54 13.38a5 5 0 1 0 7.07 7.07L12.5 18.6"/>
|
|
74
|
-
</svg>
|
|
75
|
-
`,image:`
|
|
76
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
77
|
-
<rect x="3" y="5" width="18" height="14" rx="2"/>
|
|
78
|
-
<circle cx="9" cy="10" r="1.5"/>
|
|
79
|
-
<path d="m21 16-5.5-5.5L7 19"/>
|
|
80
|
-
</svg>
|
|
81
|
-
`,video:`
|
|
82
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
83
|
-
<rect x="3" y="5" width="18" height="14" rx="2"/>
|
|
84
|
-
<path d="m10 9 5 3-5 3z" fill="currentColor" stroke="none"/>
|
|
85
|
-
</svg>
|
|
86
|
-
`,table:`
|
|
87
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
88
|
-
<rect x="3" y="5" width="18" height="14" rx="1"/>
|
|
89
|
-
<path d="M3 10h18"/>
|
|
90
|
-
<path d="M9 5v14"/>
|
|
91
|
-
<path d="M15 5v14"/>
|
|
92
|
-
</svg>
|
|
93
|
-
`,code:`
|
|
94
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
95
|
-
<path d="m8 9-4 3 4 3"/>
|
|
96
|
-
<path d="m16 9 4 3-4 3"/>
|
|
97
|
-
<path d="m13 6-2 12"/>
|
|
98
|
-
</svg>
|
|
99
|
-
`,horizontalRule:`
|
|
100
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
101
|
-
<path d="M4 12h16"/>
|
|
102
|
-
<path d="M9 8h6"/>
|
|
103
|
-
<path d="M9 16h6"/>
|
|
104
|
-
</svg>
|
|
105
|
-
`,indent:`
|
|
106
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
107
|
-
<path d="M4 6h16"/>
|
|
108
|
-
<path d="M10 12h10"/>
|
|
109
|
-
<path d="M10 18h10"/>
|
|
110
|
-
<path d="m4 9 4 3-4 3"/>
|
|
111
|
-
</svg>
|
|
112
|
-
`,outdent:`
|
|
113
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
114
|
-
<path d="M4 6h16"/>
|
|
115
|
-
<path d="M10 12h10"/>
|
|
116
|
-
<path d="M10 18h10"/>
|
|
117
|
-
<path d="m8 9-4 3 4 3"/>
|
|
118
|
-
</svg>
|
|
119
|
-
`,redo:`
|
|
120
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
121
|
-
<path d="M21 7v6h-6"/>
|
|
122
|
-
<path d="M20 13a8 8 0 0 0-14-3"/>
|
|
123
|
-
</svg>
|
|
124
|
-
`,undo:`
|
|
125
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
126
|
-
<path d="M3 7v6h6"/>
|
|
127
|
-
<path d="M4 13a8 8 0 0 1 14-3"/>
|
|
128
|
-
</svg>
|
|
129
|
-
`,chevronDown:`
|
|
130
|
-
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
131
|
-
<path d="m6 9 6 6 6-6"/>
|
|
132
|
-
</svg>
|
|
133
|
-
`}),Si=Object.freeze([{action:`paragraph`,label:`Paragraph`,shortLabel:`P`,title:`Paragraph`},{action:`heading-1`,label:`Heading 1`,shortLabel:`H1`,title:`Heading 1`},{action:`heading-2`,label:`Heading 2`,shortLabel:`H2`,title:`Heading 2`},{action:`heading-3`,label:`Heading 3`,shortLabel:`H3`,title:`Heading 3`},{action:`heading-4`,label:`Heading 4`,shortLabel:`H4`,title:`Heading 4`},{action:`heading-5`,label:`Heading 5`,shortLabel:`H5`,title:`Heading 5`},{action:`heading-6`,label:`Heading 6`,shortLabel:`H6`,title:`Heading 6`},{action:`quote`,label:`Quote`,shortLabel:`Quote`,title:`Block quote`},{action:`bullet-list`,label:`Bullet list`,shortLabel:`List`,title:`Bullet list`},{action:`numbered-list`,label:`Numbered list`,shortLabel:`1.`,title:`Numbered list`},{action:`task-list`,label:`Task list`,shortLabel:`Task`,title:`Task list`},{action:`code-block`,label:`Code block`,shortLabel:`Code`,title:`Code block`}]),Ci=Object.freeze([{action:`bold`,label:`Bold`,title:`Bold`,icon:B.bold},{action:`italic`,label:`Italic`,title:`Italic`,icon:B.italic},{action:`strikethrough`,label:`Strikethrough`,title:`Strikethrough`,icon:B.strikethrough},{action:`code`,label:`Inline code`,title:`Inline code`,icon:B.code}]),wi=Object.freeze([{commandId:`undo`,label:`Undo`,title:`Undo`,icon:B.undo},{commandId:`redo`,label:`Redo`,title:`Redo`,icon:B.redo},{commandId:`indentMore`,label:`Indent`,title:`Indent`,icon:B.indent},{commandId:`indentLess`,label:`Outdent`,title:`Outdent`,icon:B.outdent}]),Ti=Object.freeze([{action:`link`,label:`Insert link`,title:`Insert link`,icon:B.link},{action:`image`,label:`Insert image`,title:`Insert image`,icon:B.image},{action:`video`,label:`Insert video`,title:`Insert video`,icon:B.video}]),Ei=Object.freeze([{action:`table`,label:`Insert table`,title:`Insert table`,icon:B.table},{action:`horizontal-rule`,label:`Insert horizontal rule`,title:`Insert horizontal rule`,icon:B.horizontalRule}]),Di=Object.freeze([{kind:`buttons`,groupLabel:`Edit`,actions:wi,mobileOnly:!0},{kind:`block-menu`,actions:Si},{kind:`buttons`,groupLabel:`Inline formatting`,actions:Ci},{kind:`buttons`,groupLabel:`Media and links`,actions:Ti},{kind:`buttons`,groupLabel:`Insert`,actions:Ei}]),Oi=[...Si,...Ci,...Ti,...Ei],ki=new Map(Oi.map(e=>[e.action,e]));function Ai(e){return ki.get(e)??null}function ji(){return Si}function Mi(e){return Si.some(t=>t.action===e)}function Ni(e){return Ai(e)?.shortLabel??`P`}function Pi(){return B}var Fi=`image/png,image/jpeg,image/webp,image/gif,image/svg+xml`,Ii=`paragraph`;function Li(e){return e===`heading`?`heading-2`:String(e??``).trim()}function Ri(e){return e.map(e=>`<button type="button" class="ui-icon-button ui-icon-button--toolbar ui-toolbar-action" ${e.commandId?`data-editor-command="${b(e.commandId)}"`:`data-markdown-action="${b(e.action)}"`} aria-label="${b(e.label)}" title="${b(e.title)}">${e.icon}</button>`).join(``)}function zi(e){return`
|
|
134
|
-
<div class="markdown-toolbar-block-menu-shell">
|
|
135
|
-
<button
|
|
136
|
-
type="button"
|
|
137
|
-
class="ui-button ui-button--ghost markdown-toolbar-block-trigger"
|
|
138
|
-
data-markdown-block-menu-toggle
|
|
139
|
-
aria-haspopup="menu"
|
|
140
|
-
aria-expanded="false"
|
|
141
|
-
title="Block formatting"
|
|
142
|
-
>
|
|
143
|
-
<span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${b(Ni(e))}</span>
|
|
144
|
-
<span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${Pi().chevronDown}</span>
|
|
145
|
-
</button>
|
|
146
|
-
</div>
|
|
147
|
-
`}function Bi(e){return ji().map(t=>{let n=t.action===e;return`
|
|
148
|
-
<button
|
|
149
|
-
type="button"
|
|
150
|
-
class="markdown-toolbar-menu-item${n?` is-active`:``}"
|
|
151
|
-
data-markdown-block-action="${b(t.action)}"
|
|
152
|
-
role="menuitemradio"
|
|
153
|
-
aria-checked="${n?`true`:`false`}"
|
|
154
|
-
title="${b(t.title)}"
|
|
155
|
-
>
|
|
156
|
-
<span class="markdown-toolbar-menu-item-label">${b(t.label)}</span>
|
|
157
|
-
<span class="markdown-toolbar-menu-item-shortcut">${b(t.shortLabel)}</span>
|
|
158
|
-
</button>
|
|
159
|
-
`}).join(``)}function Vi(e){return Di.map(t=>t.kind===`block-menu`?zi(e):`
|
|
160
|
-
<div class="markdown-toolbar-group${t.mobileOnly?` markdown-toolbar-group--mobile-only`:``}" role="group" aria-label="${b(t.groupLabel)}">
|
|
161
|
-
${Ri(t.actions)}
|
|
162
|
-
</div>
|
|
163
|
-
`).join(``)}function Hi(){let e=Li(this._activeMarkdownBlockAction||Ii);return Mi(e)?e:Ii}function Ui(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Vi(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function Wi(){return this._markdownBlockMenuPopover??null}function Gi(){let e=this.elements?.editorContainer??document.body,t=this.getMarkdownBlockMenuPopover();t?t.parentElement!==e&&e?.appendChild(t):(t=document.createElement(`div`),t.className=`markdown-toolbar-popover hidden`,t.innerHTML=`<div class="markdown-toolbar-menu" data-markdown-block-menu role="menu" aria-label="Block formatting"></div>`,t.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),t.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),e?.appendChild(t),this._markdownBlockMenuPopover=t);let n=t.querySelector(`[data-markdown-block-menu]`);n&&(n.innerHTML=Bi(this.getActiveMarkdownBlockAction()))}function Ki(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=Ai(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=Ni(t));let i=e.querySelector(`[data-markdown-block-menu-toggle]`);i&&n&&(i.setAttribute(`aria-label`,`${n.label}. Block formatting`),i.setAttribute(`title`,`${n.label}. Block formatting`));let a=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);[...e.querySelectorAll(`[data-markdown-block-action]`),...a].forEach(e=>{let n=e.getAttribute(`data-markdown-block-action`)===t;e.classList.toggle(`is-active`,n),e.setAttribute(`aria-checked`,n?`true`:`false`)})}function qi(e){let t=Li(e);Mi(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Ji(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Yi(){let e=this.getMarkdownBlockMenuPopover(),t=this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`),n=e?.parentElement;if(!e||!t||!(n instanceof HTMLElement))return;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getBoundingClientRect(),o=a.width||176,s=a.height||240,c=r.left-i.left,l=Math.max(8,i.width-o-8),u=r.bottom-i.top+6,d=u+s<=i.height-8;e.style.left=`${Math.max(8,Math.min(c,l))}px`,e.style.top=`${d?u:Math.max(8,r.top-i.top-s-6)}px`}function Xi(){let e=this.elements?.markdownToolbar;e&&(this.renderMarkdownBlockMenuPopover(),e.classList.add(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.remove(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`true`),this.positionMarkdownBlockMenu())}function Zi(){let e=this.elements?.markdownToolbar;e&&(e.classList.remove(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.add(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`false`))}function Qi(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function $i(e){let t=e.target instanceof Element?e.target:null;if(!t)return;let n=t.closest(`[data-editor-command]`)?.getAttribute(`data-editor-command`);if(n){e.preventDefault(),this.runEditorCommand(n);return}if(t.closest(`[data-markdown-block-menu-toggle]`)){e.preventDefault(),this.toggleMarkdownBlockMenu();return}let r=t.closest(`[data-markdown-block-action]`);if(r){e.preventDefault();let t=r.getAttribute(`data-markdown-block-action`);this.closeMarkdownBlockMenu(),t&&this.applyMarkdownToolbarAction(t);return}let i=t.closest(`[data-markdown-action]`)?.getAttribute(`data-markdown-action`);i&&this.applyMarkdownToolbarAction(i)}function ea(e){if(!this.isMarkdownBlockMenuOpen()){e.target instanceof Element&&e.target.closest(`[data-markdown-block-menu-toggle]`)&&[`ArrowDown`,`Enter`,` `].includes(e.key)&&(e.preventDefault(),this.openMarkdownBlockMenu(),this.getMarkdownBlockMenuPopover()?.querySelector(`[data-markdown-block-action]`)?.focus());return}if(e.key===`Escape`){e.preventDefault(),this.closeMarkdownBlockMenu(),this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`)?.focus();return}let t=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);if(t.length===0)return;let n=t.findIndex(t=>t===e.target);n<0||(e.key===`ArrowDown`?(e.preventDefault(),t[(n+1)%t.length]?.focus()):e.key===`ArrowUp`&&(e.preventDefault(),t[(n-1+t.length)%t.length]?.focus()))}function ta(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function na(e){if(!this.session||!_(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=Li(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}Mi(t)&&this.setActiveMarkdownBlockAction(t)}function ra(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function ia(){let[e]=await Se({accept:Fi});e&&await this.handleEditorImageInsert(e)}async function aa(e){if(!this.session||!_(this.currentFilePath))return console.warn(`[ui] Ignoring image insert because there is no active markdown session.`,{currentFilePath:this.currentFilePath,hasSession:!!this.session}),!1;let t=this.currentFilePath,n=this.session;try{console.debug(`[ui] Uploading image attachment.`,{fileName:e?.name||``,size:e?.size??null,sourcePath:t,type:e?.type||``});let r=await this.vaultApiClient.uploadImageAttachment({file:e,fileName:e?.name||``,sourcePath:t});return await this.fileExplorer.refresh(),this.currentFilePath===t&&this.session&&this.session===n&&typeof r?.markdown==`string`&&(console.debug(`[ui] Inserting uploaded image markdown into the editor.`,{sourcePath:t,storedPath:r.path??``}),this.session.insertText(r.markdown)),!0}catch(e){return console.error(`[ui] Failed to insert image attachment:`,e),this.toastController.show(e.message||`Failed to upload image`),!1}}async function oa(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var sa={applyMarkdownToolbarAction:na,copyCurrentLink:oa,closeMarkdownBlockMenu:Zi,getActiveMarkdownBlockAction:Hi,getMarkdownBlockMenuPopover:Wi,handleEditorImageInsert:aa,handleMarkdownToolbarClick:$i,handleMarkdownToolbarDocumentPointerDown:ta,handleMarkdownToolbarKeydown:ea,handleToolbarImageInsert:ia,isMarkdownBlockMenuOpen:Ji,openMarkdownBlockMenu:Xi,positionMarkdownBlockMenu:Yi,renderMarkdownBlockMenuPopover:Gi,renderMarkdownToolbar:Ui,runEditorCommand:ra,setActiveMarkdownBlockAction:qi,syncMarkdownToolbarBlockUi:Ki,toggleMarkdownBlockMenu:Qi},ca={isBaseFile:n,isDrawioFile:h,isExcalidrawFile:r,isImageFile:l,isPdfFile:a,isMermaidFile:i,isPlantUmlFile:p,isStructurizrWorkspaceFile:u,getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.workspacePreviewController.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.workspacePreviewController.createDiagramPreviewDocument(`plantuml`,e.content):String(e.content??``):this.workspacePreviewController.getPreviewSource(this.currentFilePath,{drawioMode:this.currentDrawioMode??null})},getStaticPreviewDocument(){return this._staticPreviewDocument??null},setStaticPreviewDocument(e){let t=e?.filePath??e?.path??null,n=e?.currentFilePath??t;this._staticPreviewDocument=e?{content:String(e.content??``),currentFilePath:n,fileKind:e.fileKind??m(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=m(e);return t!==null&&t!==`image`&&t!==`pdf`},getDisplayName(e){return o(String(e??``).split(`/`).pop())},handleLayoutViewRequest(e){return!this.currentFilePath||!this.isDrawioFile(this.currentFilePath)?!0:this.currentDrawioMode===`text`?e!==`preview`||(this.layoutController.isMobileViewport?.()&&this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath),!1):e===`preview`||(this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath,{drawioMode:`text`}),!1)},renderBaseFilePreview(e,t){return clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=null,this.workspacePreviewController.renderBaseFilePreview(e,t)},scheduleBaseFilePreview(e,t){let n=this.sessionLoadToken;clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=setTimeout(()=>{this._basePreviewRenderTimer=null,e===this.currentFilePath&&n===this.sessionLoadToken&&this.renderBaseFilePreview(e,t)},180)},createResizeHandler(){return this.workspacePreviewController.createResizeHandler(()=>this.restoreSidebarState())},initializePreviewLayoutObserver(){this._previewLayoutResizeObserver?.disconnect(),this._previewLayoutResizeObserver=this.workspacePreviewController.initializePreviewLayoutObserver(()=>this.schedulePreviewLayoutSync())},schedulePreviewLayoutSync({delayMs:e=120}={}){this.workspacePreviewController.schedulePreviewLayoutSync({delayMs:e,hydrationPaused:this._previewHydrationPaused,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},handleEditorScrollActivityChange(e){this.workspacePreviewController.handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:this._pendingPreviewLayoutSync,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setHydrationPaused:e=>{this._previewHydrationPaused=e},setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},showEmptyState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showEmptyState()},showDiffState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showDiffState()}},la=`__lobby__`;function ua(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function da(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function fa(e){if(!e||typeof e!=`object`||typeof e.id!=`string`)return null;let t=e.workspaceChange&&typeof e.workspaceChange==`object`?e.workspaceChange:{};return{action:typeof e.action==`string`?e.action:`git`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),id:e.id,peerId:typeof e.peerId==`string`?e.peerId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:{changedPaths:Array.isArray(t.changedPaths)?t.changedPaths.filter(Boolean):[],deletedPaths:Array.isArray(t.deletedPaths)?t.deletedPaths.filter(Boolean):[],refreshExplorer:t.refreshExplorer!==!1,renamedPaths:Array.isArray(t.renamedPaths)?t.renamedPaths.filter(e=>e?.oldPath&&e?.newPath):[]}}}var pa=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=ce(),this.ydoc=new ye,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=Ae(e),this.currentFile=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds=new Set,this.handleAwarenessChange=()=>{this._emitChange()},this.handleChatMessagesChange=()=>{this._emitChatChange()},this.handleWorkspaceEventsChange=()=>{this._emitWorkspaceEvents()}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new ve(this.wsBaseUrl,la,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),be(this.provider),this.awareness=this.provider.awareness,this.awareness.setLocalStateField(`user`,this.localUser),this.awareness.setLocalStateField(`currentFile`,this.currentFile),this.awareness.on(`change`,this.handleAwarenessChange),this.chatMessages.observe(this.handleChatMessagesChange),this.workspaceEvents.observe(this.handleWorkspaceEventsChange),this.provider.on(`status`,({status:e})=>{this._connected=e===`connected`,this._emitChange()}),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this._primeWorkspaceEventCache(),this._emitChange(),this._emitChatChange({initial:!0}))}))}setCurrentFile(e){this.currentFile=e,this.awareness&&this.awareness.setLocalStateField(`currentFile`,e)}setUserName(e){e&&(this.localUser={...this.localUser,name:e},this.awareness&&this.awareness.setLocalStateField(`user`,this.localUser))}getLocalUser(){return this.localUser}sendChatMessage(e){let t=ua(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:da(this.localUser.peerId),peerId:this.localUser.peerId,text:t,userColor:this.localUser.color,userName:this.localUser.name};return this.ydoc.transact(()=>{this.chatMessages.push([n]);let e=this.chatMessages.length-40;e>0&&this.chatMessages.delete(0,e)},`lobby-chat-message`),n}sendWorkspaceEvent({action:e=`git`,sourceRef:t=null,workspaceChange:n={}}={}){let r=fa({action:e,createdAt:Date.now(),id:da(this.localUser.peerId),peerId:this.localUser.peerId,sourceRef:t,workspaceChange:n});return r?(this.ydoc.transact(()=>{this.workspaceEvents.push([r]);let e=this.workspaceEvents.length-40;e>0&&this.workspaceEvents.delete(0,e)},`lobby-workspace-event`),this.seenWorkspaceEventIds.add(r.id),r):null}getMessages(){return this.chatMessages.toArray().filter(e=>e&&typeof e.id==`string`&&typeof e.peerId==`string`&&typeof e.text==`string`&&typeof e.userName==`string`)}getUsers(){if(!this.awareness)return[];let e=[];return this.awareness.getStates().forEach((t,n)=>{t.user&&e.push({...t.user,clientId:n,currentFile:t.currentFile??null,isLocal:n===this.awareness.clientID})}),e}getConnectionState(){return this._connected?{status:`connected`,unreachable:!1}:this.provider?{status:`connecting`,unreachable:!1}:{status:`disconnected`,unreachable:!1}}disconnect(){this.provider&&(this.awareness?.off(`change`,this.handleAwarenessChange),this.chatMessages?.unobserve(this.handleChatMessagesChange),this.workspaceEvents?.unobserve(this.handleWorkspaceEventsChange)),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.awareness=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds.clear()}destroy(){this.disconnect(),this.ydoc?.destroy(),this.ydoc=null}_emitChange(){this.onChange?.(this.getUsers())}_emitChatChange(e={}){this.onChatChange?.(this.getMessages(),e)}_primeWorkspaceEventCache(){this.workspaceEvents.toArray().forEach(e=>{let t=fa(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=fa(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}};function V(e,t,n){try{return e.getItem(t)??n}catch{return n}}function ma(e,t,n){try{e.setItem(t,n)}catch{}}var ha=20,ga=class{constructor({fileTreeShowExtensionsKey:e,lineWrappingKey:t,recentFilesKey:n=`collabmd-recent-files`,vimModeKey:r=`collabmd-editor-vim-mode`,sidebarVisibleKey:i,userNameKey:a,storage:o=globalThis.localStorage}){this.fileTreeShowExtensionsKey=e,this.lineWrappingKey=t,this.recentFilesKey=n,this.sidebarVisibleKey=i,this.storage=o,this.userNameKey=a,this.vimModeKey=r}getUserName(){return V(this.storage,this.userNameKey,``)||``}setUserName(e){ma(this.storage,this.userNameKey,e)}getFileTreeShowExtensions(){return V(this.storage,this.fileTreeShowExtensionsKey,null)===`true`}setFileTreeShowExtensions(e){ma(this.storage,this.fileTreeShowExtensionsKey,e?`true`:`false`)}getLineWrappingEnabled(){return V(this.storage,this.lineWrappingKey,null)!==`false`}setLineWrappingEnabled(e){ma(this.storage,this.lineWrappingKey,String(e))}getVimModeEnabled(){return V(this.storage,this.vimModeKey,null)===`true`}setVimModeEnabled(e){ma(this.storage,this.vimModeKey,String(e))}getRecentFiles(){let e=V(this.storage,this.recentFilesKey,`[]`);try{let t=JSON.parse(e);return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`&&e))]:[]}catch{return[]}}recordRecentFile(e){if(!e)return;let t=[e,...this.getRecentFiles().filter(t=>t!==e)];ma(this.storage,this.recentFilesKey,JSON.stringify(t.slice(0,ha)))}getSidebarVisible(){return V(this.storage,this.sidebarVisibleKey,null)}setSidebarVisible(e){ma(this.storage,this.sidebarVisibleKey,e?`true`:`false`)}},_a=class{getApi(){return typeof globalThis.Notification==`function`?globalThis.Notification:null}getPermission(){return this.getApi()?.permission??`unsupported`}async requestPermission(){let e=this.getApi();if(!e||typeof e.requestPermission!=`function`)return`unsupported`;if(e.permission!=="default")return e.permission;try{return await e.requestPermission()}catch{return e.permission??`default`}}show({body:e,onClick:t,tag:n,title:r}={}){let i=this.getApi();if(!i||i.permission!==`granted`||!e)return null;try{let a=new i(r,{body:e,renotify:!0,tag:n});return t&&(a.onclick=t),a}catch{return null}}},va=6e4;function ya(e){return String(e?.build?.id??e?.buildId??``).trim()}var ba=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=va,onUpdateAvailable:i=null,runtimeConfig:a={basePath:``},versionUrl:o=null,windowRef:s=globalThis.window??globalThis}={}){this.currentBuildId=String(e??``).trim(),this.documentRef=t,this.fetchImpl=n,this.intervalHandle=null,this.intervalMs=Math.max(5e3,Number(r)||va),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||_e(`/version.json`,a),this.windowRef=s,this.handleFocus=()=>{this.checkNow({force:!0})},this.handleVisibilityChange=()=>{this.documentRef?.hidden||this.checkNow({force:!0})}}start(){!this.fetchImpl||this.intervalHandle||(this.documentRef?.addEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.addEventListener?.(`focus`,this.handleFocus),this.intervalHandle=this.windowRef?.setInterval?.(()=>{this.checkNow()},this.intervalMs)??null,this.checkNow({force:!0}))}stop(){this.intervalHandle&&=(this.windowRef?.clearInterval?.(this.intervalHandle),null),this.documentRef?.removeEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.removeEventListener?.(`focus`,this.handleFocus)}async checkNow({force:e=!1}={}){if(!this.fetchImpl||this.isChecking||this.updateDetected||!e&&this.documentRef?.hidden)return!1;this.isChecking=!0;try{let e=await this.fetchImpl(this.versionUrl,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e?.ok)return!1;let t=await e.json().catch(()=>null),n=ya(t);return n?this.currentBuildId?n!==this.currentBuildId&&(this.updateDetected=!0,this.onUpdateAvailable?.(t),!0):(this.currentBuildId=n,!1):!1}catch{return!1}finally{this.isChecking=!1}}};function xa(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n!=null&&n!==``&&t.set(e,String(n))}),t}var Sa=new class{async readStatus({force:e=!1}={}){let t=await fetch(F(`/git/status${e?`?force=true`:``}`));return N(t,`Failed to load git status`)}async readPullBackups(){let e=await fetch(F(`/git/pull-backups`));return N(e,`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=xa({limit:e,offset:t}),r=await fetch(F(`/git/history?${n.toString()}`));return N(r,`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=xa({limit:t,offset:n,path:e}),i=await fetch(F(`/git/file-history?${r.toString()}`));return N(i,`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=xa({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r}),a=await fetch(F(`/git/diff?${i.toString()}`));return N(a,`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=xa({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r}),a=await fetch(F(`/git/commit?${i.toString()}`));return N(a,`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=xa({hash:e,path:t}),r=await fetch(F(`/git/file-snapshot?${n.toString()}`));return N(r,`Failed to load historical file preview`)}getFileAttachmentUrl({hash:e,path:t}={}){let n=xa({hash:e,path:t});return F(`/git/file-attachment?${n.toString()}`)}async stageFile({path:e,requestId:t=null}={}){return this.#e(`/git/stage`,{path:e},{requestId:t,fallbackError:`Failed to stage file`})}async unstageFile({path:e,requestId:t=null}={}){return this.#e(`/git/unstage`,{path:e},{requestId:t,fallbackError:`Failed to unstage file`})}async pushBranch({requestId:e=null}={}){return this.#e(`/git/push`,{},{requestId:e,fallbackError:`Failed to push branch`})}async pullBranch({requestId:e=null}={}){return this.#e(`/git/pull`,{},{requestId:e,fallbackError:`Failed to pull branch`})}async resetFile({path:e,requestId:t=null}={}){return this.#e(`/git/reset-file`,{path:e},{requestId:t,fallbackError:`Failed to reset file`})}async commit({message:e,requestId:t=null}={}){return this.#e(`/git/commit`,{message:e},{requestId:t,fallbackError:`Failed to commit staged changes`})}async#e(e,t,{fallbackError:n,requestId:r=null}={}){let i=await fetch(F(e),{body:JSON.stringify(t),headers:A(r,{"Content-Type":`application/json`}),method:`POST`});return N(i,n)}},Ca=`collabmd-active-tab-lock`,wa=`collabmd-tab-id`,Ta=`collabmd-tab-lock`,Ea=4e3;function Da(){return Date.now()}function Oa(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${Da()}-${Math.random().toString(36).slice(2,10)}`}function ka(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var Aa=class{constructor({heartbeatIntervalMs:e=Ea,onBlocked:t,onActivated:n,onStolen:r}={}){this.heartbeatIntervalMs=e,this.staleAfterMs=e*3,this.onBlocked=t,this.onActivated=n,this.onStolen=r,this.tabId=this.getOrCreateTabId(),this.channel=null,this.heartbeatTimer=null,this.isOwner=!1,this.handleStorageEvent=this.handleStorageEvent.bind(this),this.handlePageHide=this.handlePageHide.bind(this)}initialize(){window.addEventListener(`storage`,this.handleStorageEvent),window.addEventListener(`pagehide`,this.handlePageHide),`BroadcastChannel`in globalThis&&(this.channel=new BroadcastChannel(Ta),this.channel.addEventListener(`message`,e=>{this.handleChannelMessage(e.data)}))}destroy(){this.release(),window.removeEventListener(`storage`,this.handleStorageEvent),window.removeEventListener(`pagehide`,this.handlePageHide),this.channel?.close(),this.channel=null}tryActivate({takeover:e=!1}={}){let t=this.readLock();return this.isFreshLock(t)&&t.tabId!==this.tabId&&!e?(this.isOwner=!1,this.stopHeartbeat(),this.onBlocked?.({reason:`active-elsewhere`,ownerTabId:t.tabId}),!1):(this.writeLock(),this.startHeartbeat(),this.isOwner=!0,this.channel?.postMessage({type:`claimed`,takeover:e,tabId:this.tabId}),this.onActivated?.({takeover:e}),!0)}release(){this.readLock()?.tabId===this.tabId&&(localStorage.removeItem(Ca),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(wa);if(e)return e;let t=Oa();return window.sessionStorage.setItem(wa,t),t}catch{return Oa()}}readLock(){try{return ka(window.localStorage.getItem(Ca))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&Da()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(Ca,JSON.stringify({tabId:this.tabId,updatedAt:Da()}))}catch{}}startHeartbeat(){this.stopHeartbeat(),this.writeLock(),this.heartbeatTimer=window.setInterval(()=>{if(!this.isOwner){this.stopHeartbeat();return}this.writeLock()},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer&&=(window.clearInterval(this.heartbeatTimer),null)}handleStorageEvent(e){if(e.key!==Ca)return;let t=ka(e.newValue);this.handleExternalLockChange(t)}handleChannelMessage(e){!e||typeof e!=`object`||e.tabId===this.tabId||e.type===`claimed`&&this.handleExternalLockChange(this.readLock())}handleExternalLockChange(e){this.isOwner&&this.isFreshLock(e)&&e.tabId!==this.tabId&&(this.isOwner=!1,this.stopHeartbeat(),this.onStolen?.({ownerTabId:e.tabId}))}handlePageHide(){this.release()}},ja=`__workspace__`;function Ma(e=``){return String(e??``).trim().replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}function Na(e=``){let t=Ma(e);if(!t)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Pa(e={}){return Na(e?.path??``)}function Fa(e){if(!e?.path||!e?.type)return null;if(e.nodeType===`directory`||e.type===`directory`)return{children:[],name:e.name,path:e.path,type:`directory`};let t={name:e.name,path:e.path,type:e.type},n=Number(e.mtimeMs);return Number.isFinite(n)&&(t.mtimeMs=n),t}function Ia(e=[]){return e.sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),e.forEach(e=>{Array.isArray(e.children)&&Ia(e.children)}),e}function La(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Ra(e=[],t=`asc`){let n=t===`desc`?-1:1;return[...e].sort((e,t)=>{let r=e.split(`/`).length-t.split(`/`).length;return r===0?e.localeCompare(t,void 0,{sensitivity:`base`})*n:r*n})}var za=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=La(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=Fa(e);t&&this.nodesByPath.set(e.path,t)}),Ra(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,Pa(this.entriesByPath.get(e)))}),Ia(this.roots),this.roots}getTree(){return this.roots}applyMapChanges(e,t){let n=[],r=[];return e.forEach((e,t)=>{e.action===`delete`?n.push(t):r.push(t)}),Ra(n,`desc`).forEach(e=>{this.removeEntry(e)}),Ra(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Ia(this.roots),this.roots}removeEntry(e){let t=this.nodesByPath.get(e);if(!t){this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e);return}this.detachNode(e,t),this.nodesByPath.delete(e),this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e)}upsertEntry(e,t){if(!t?.path||!t?.type){this.removeEntry(e);return}let n=Fa(t);if(!n){this.removeEntry(e);return}let r=this.nodesByPath.get(e);!r||r.type===`directory`!=(n.type===`directory`)?(r&&this.detachNode(e,r),r=n,this.nodesByPath.set(e,r)):(r.name=n.name,r.path=n.path,r.type=n.type,n.mtimeMs===void 0?delete r.mtimeMs:r.mtimeMs=n.mtimeMs,r.type===`directory`&&!Array.isArray(r.children)&&(r.children=[]),r.type!==`directory`&&Array.isArray(r.children)&&delete r.children),this.entriesByPath.set(e,t),this.attachNode(e,r,Pa(t)),r.type===`directory`&&this.rehomeChildren(e)}detachNode(e,t){let n=this.nodeParentPathByPath.get(e)||``,r=n?this.nodesByPath.get(n)?.children:this.roots,i=r?.indexOf?.(t)??-1;i>=0&&r.splice(i,1),this.nodeParentPathByPath.delete(e)}attachNode(e,t,n=``){let r=this.nodesByPath.get(n)?.type===`directory`?n:``,i=this.nodeParentPathByPath.get(e);if(i===r)return;i!==void 0&&this.detachNode(e,t);let a=r?this.nodesByPath.get(r)?.children:this.roots;a.includes(t)||a.push(t),this.nodeParentPathByPath.set(e,r)}rehomeChildren(e){this.entriesByPath.forEach((t,n)=>{if(Pa(t)!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Ba=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new ye,this.entries=this.ydoc.getMap(`entries`),this.events=this.ydoc.getArray(`events`),this.provider=null,this._didInitialSync=!1,this.seenEventIds=new Set,this.treeModel=new za,this.handleEntriesChange=e=>{!this._didInitialSync||!e||this.onTreeChange(this.treeModel.applyMapChanges(e.changes.keys,this.entries),{changedPaths:Array.from(e.changes.keys.keys()),reset:!1})},this.handleEventsChange=()=>{if(!this._didInitialSync){this.primeEventCache();return}this.events.toArray().forEach(e=>{let t=Gn(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new ve(ce(),ja,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),be(this.provider),this.entries.observe(this.handleEntriesChange),this.events.observe(this.handleEventsChange),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this.primeEventCache(),this.onTreeChange(this.treeModel.reset(this.entries.toJSON()),{changedPaths:[],reset:!0}))}))}primeEventCache(){this.events.toArray().forEach(e=>{let t=Gn(e);t&&this.seenEventIds.add(t.id)})}disconnect(){this.entries.unobserve(this.handleEntriesChange),this.events.unobserve(this.handleEventsChange),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this._didInitialSync=!1,this.seenEventIds.clear(),this.treeModel.reset(new Map)}destroy(){this.disconnect(),this.ydoc.destroy()}},Va=class{constructor({documentRef:e=document,headerPanelElement:t=null,inlinePanelElement:n=null,loadBacklinks:r=null,onFileSelect:i,panelElement:a}){this.documentRef=e,this.headerPanel=t,this.panelRoot=a,this.inlinePanel=n,this.loadBacklinks=r,this.onFileSelect=i,this._expanded=!1,this._currentFile=null,this._displayMode=`dock`,this._fetchController=null,this._backlinks=[],this._pendingOutsidePointer=null;let o=this.panelRoot?.querySelector(`[data-backlinks-variant="dock"]`)??this.panelRoot;this.panels=[this._createPanelRef(o,this.panelRoot),this._createPanelRef(this.headerPanel,this.headerPanel),this._createPanelRef(this.inlinePanel,this.inlinePanel)].filter(Boolean),this.handleDocumentPointerDown=e=>{if(!this._expanded)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}(e?.pointerType!==`mouse`||e?.button===0)&&(this._pendingOutsidePointer={pointerId:e?.pointerId??`mouse`,startX:Number(e?.clientX??0),startY:Number(e?.clientY??0)})},this.handleDocumentPointerMove=e=>{if(!this._pendingOutsidePointer)return;let t=Math.abs(Number(e?.clientX??0)-this._pendingOutsidePointer.startX),n=Math.abs(Number(e?.clientY??0)-this._pendingOutsidePointer.startY);(t>10||n>10)&&(this._pendingOutsidePointer=null)},this.handleDocumentPointerEnd=e=>{if(!this._expanded||!this._pendingOutsidePointer)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}this._pendingOutsidePointer=null,this.close()},this.handleDocumentKeyDown=e=>{!this._expanded||e?.key!==`Escape`||(e.preventDefault?.(),this.close())},this.bindEvents()}bindEvents(){this.panels.forEach(e=>{e.header?.addEventListener(`click`,()=>{this._backlinks.length!==0&&(this._expanded=!this._expanded,this._pendingOutsidePointer=null,this._applyExpandState())})}),this.documentRef?.addEventListener?.(`pointerdown`,this.handleDocumentPointerDown),this.documentRef?.addEventListener?.(`pointermove`,this.handleDocumentPointerMove,{passive:!0}),this.documentRef?.addEventListener?.(`pointerup`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`pointercancel`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`keydown`,this.handleDocumentKeyDown)}async load(e){let t=e!==this._currentFile;if(this._currentFile=e,t&&(this._expanded=!1),!e){this._backlinks=[],this._render();return}this._fetchController?.abort(),this._fetchController=new AbortController;try{let t=await this.loadBacklinks(e,{signal:this._fetchController.signal});if(this._currentFile!==e)return;this._backlinks=t}catch(e){if(e.name===`AbortError`)return;console.warn(`[backlinks] Failed to load:`,e.message),this._backlinks=[]}this._render()}setDisplayMode(e=`dock`){let t=e===`header`?`header`:`dock`;this._displayMode!==t&&(this._displayMode=t,this._expanded=!1,this._pendingOutsidePointer=null,this._render())}clear(){this._currentFile=null,this._backlinks=[],this._expanded=!1,this._render()}close(){this._expanded&&(this._expanded=!1,this._pendingOutsidePointer=null,this._applyExpandState())}_createPanelRef(e,t=e){return e?{panel:e,header:e.querySelector(`.backlinks-header`),toggle:e.querySelector(`.backlinks-toggle`),countBadge:e.querySelector(`.backlinks-count`),body:e.querySelector(`.backlinks-body`),list:e.querySelector(`.backlinks-list`),root:t}:null}_render(){let e=this._backlinks.length,t=e===1?`Linked Mention`:`Linked Mentions`,n=!!this._currentFile&&e>0;n||(this._expanded=!1),this.panels.forEach(r=>{let i=n&&this._shouldShowPanel(r);r.root?.classList?.toggle?.(`hidden`,!i),r.countBadge.textContent=n?String(e):``,r.toggle.textContent=t,r.header?.classList.toggle(`backlinks-header-empty`,!i),i?this._renderList(r.list):r.list.innerHTML=``}),this._applyExpandState()}_shouldShowPanel(e){let t=e.panel?.getAttribute?.(`data-backlinks-variant`)??``;return t===`header`?this._displayMode===`header`:t!==`dock`||this._displayMode===`dock`}_renderList(e){if(!e)return;e.innerHTML=``;let t=this.documentRef?.createDocumentFragment?.(),n=t??e;this._backlinks.forEach(e=>{n.appendChild(this._createBacklinkItem(e))}),t&&e.appendChild(t)}_createBacklinkItem(e){let t=o(e.file.split(`/`).pop()),n=e.file.includes(`/`)?e.file.substring(0,e.file.lastIndexOf(`/`)):``,r=this.documentRef.createElement(`button`);r.type=`button`,r.className=`backlink-item`,r.addEventListener(`click`,()=>{this.close(),this.onFileSelect?.(e.file)});let i=this.documentRef.createElement(`div`);if(i.className=`backlink-file-name`,i.innerHTML=`
|
|
164
|
-
<svg class="backlink-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
165
|
-
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
166
|
-
<polyline points="14 2 14 8 20 8"/>
|
|
167
|
-
</svg>
|
|
168
|
-
<span>${b(t)}</span>
|
|
169
|
-
${n?`<span class="backlink-dir">${b(n)}</span>`:``}
|
|
170
|
-
`,r.appendChild(i),e.contexts.slice(0,3).forEach(e=>{let t=this.documentRef.createElement(`div`);t.className=`backlink-context`,t.textContent=e,r.appendChild(t)}),e.contexts.length>3){let t=this.documentRef.createElement(`div`);t.className=`backlink-context backlink-more`,t.textContent=`+${e.contexts.length-3} more`,r.appendChild(t)}return r}_applyExpandState(){this.panels.forEach(e=>{let t=this._expanded&&this._backlinks.length>0&&this._shouldShowPanel(e);e.panel.classList.toggle(`expanded`,t),e.header?.setAttribute(`aria-expanded`,String(t)),e.header?.setAttribute(`aria-disabled`,String(this._backlinks.length===0)),e.body?.setAttribute(`aria-hidden`,String(!t)),e.body?.toggleAttribute(`inert`,!t)})}};function Ha(e){return Array.isArray(e)?e:[]}function Ua({copy:e,title:t,tone:n=``}){let r=document.createElement(`div`);r.className=`comment-overview-empty ui-empty-state ui-empty-state--compact`,n&&(r.dataset.tone=n);let i=document.createElement(`p`);i.className=`ui-empty-state-title`,i.textContent=t;let a=document.createElement(`p`);return a.className=`ui-empty-state-copy`,a.textContent=e,r.append(i,a),r}var Wa=class{constructor({panelElement:e,toastController:t=null,vaultApiClient:n,onOverviewChange:r=null,onThreadSelect:i=null}){this.panel=e,this.toastController=t,this.vaultApiClient=n,this.onOverviewChange=r,this.onThreadSelect=i,this.overview={files:[],generatedAt:0,totalThreadCount:0},this.loading=!1,this.errorMessage=``,this.refreshPromise=null,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`})}initialize(){this.render()}getThreadCounts(){return new Map(Ha(this.overview.files).map(e=>[e.filePath,Number(e.threadCount||0)]))}async refresh(){return this.refreshPromise?this.refreshPromise:(this.loading=!0,this.render(),this.refreshPromise=(async()=>{try{let e=await this.vaultApiClient.readCommentOverview();this.errorMessage=``,this.setOverview(e?.overview??e??{},{render:!1})}catch(e){console.error(`[comments] Failed to load comment overview:`,e.message),this.errorMessage=`Unable to load open comments.`,this.toastController?.show?.(`Failed to load comments`)}finally{this.loading=!1,this.refreshPromise=null,this.render()}})(),this.refreshPromise)}setOverview(e={},{render:t=!0}={}){this.errorMessage=``,this.overview={files:Ha(e.files),generatedAt:Number(e.generatedAt||0),totalThreadCount:Number(e.totalThreadCount||0)},this.onOverviewChange?.(this.overview,{threadCounts:this.getThreadCounts()}),t&&this.render()}render(){if(!this.panel)return;if(this.panel.replaceChildren(),this.errorMessage){let e=Ua({copy:this.errorMessage,title:`Comments unavailable`,tone:`error`});e.setAttribute(`role`,`alert`),this.panel.appendChild(e);return}if(this.loading&&Ha(this.overview.files).length===0){let e=Ua({copy:`Checking the vault for active threads…`,title:`Loading comments`});e.setAttribute(`role`,`status`),this.panel.appendChild(e);return}let e=Ha(this.overview.files);if(e.length===0){let e=Ua({copy:`Open comments from any document will appear here.`,title:`You’re all caught up`});this.panel.appendChild(e);return}let t=document.createDocumentFragment();e.forEach(e=>{t.appendChild(this.createFileGroup(e))}),this.panel.appendChild(t)}createFileGroup(e){let t=document.createElement(`section`);t.className=`comment-overview-file`;let n=document.createElement(`div`);n.className=`comment-overview-file-header`;let r=document.createElement(`div`);r.className=`comment-overview-file-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-overview-file-title`,i.textContent=o(w(e.filePath));let a=document.createElement(`span`);a.className=`comment-overview-file-path`,a.textContent=M(e.filePath)||e.filePath;let s=document.createElement(`span`);return s.className=`comment-overview-file-count`,s.textContent=String(e.threadCount||Ha(e.threads).length),r.append(i,a),n.append(r,s),t.appendChild(n),Ha(e.threads).forEach(n=>{t.appendChild(this.createThreadButton(e.filePath,n))}),t}createThreadButton(e,t){let n=Number(t.messageCount||0),r=Fe({authorName:t.latestMessage?.userName||t.createdByName||`Anonymous`,lineLabel:Xe(t.anchor),messageCount:n,previewBody:t.latestMessage?.bodyPreview||``,quote:t.anchor?.quote||`Source anchored comment`,timestamp:this.formatTimestamp(t.latestActivityAt)});return r.addEventListener(`click`,()=>{this.onThreadSelect?.({anchor:t.anchor,filePath:e,threadId:t.id})}),r}formatTimestamp(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}};function Ga(...e){return e.flat().flatMap(e=>e&&typeof e==`object`?Object.keys(e).filter(t=>e[t]):e||[]).join(` `)}function H(e={}){return Ga(`ui-input`,e.extra??[])}function U(e={}){let{variant:t=`secondary`,size:n=`md`,toggle:r=!1,toolbar:i=!1,action:a=!1,wide:o=!1,surface:s=!1,pill:c=!1,hidden:l=!1,active:u=!1,extra:d=[]}=e;return Ga(`ui-button`,t&&`ui-button--${t}`,n!==`md`&&`ui-button--${n}`,{"ui-button--toggle":r,"ui-button--toolbar":i,"ui-button--action":a,"ui-button--wide":o,"ui-button--surface":s,"ui-button--pill":c,active:u,hidden:l},d)}function Ka(){if(this.cardRoot?.isConnected&&this.cardRoot.parentElement===document.body)return this.cardRoot;let e=document.createElement(`div`);return e.className=`comment-card-root hidden`,document.body.appendChild(e),this.cardRoot=e,e}function qa(e=`editor`,t=null,n=null){let r=n?.anchor??this.session?.getCurrentSelectionCommentAnchor?.();if(!r)return;this.selectionAnchor=r,this.reactionPicker=null;let i=e===`editor`&&t?`editor-chip`:e,a=t??(e===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.():this.session?.getCommentAnchorClientRect?.(r));this.activeCard={anchor:r,composerDraft:null,mode:`create`,origin:i,previewRange:n?.range??null,replyThreadId:null,sourceRect:a??null},this.render()}function Ja(e,{anchor:t,origin:n,sourceRect:r}){this.reactionPicker=null,this.activeCard={anchor:t,groupKey:e.key,groupThreadIds:e.threads.map(e=>e.id),mode:`group`,origin:n,replyDrafts:{},replyThreadId:null,sourceRect:r},this.renderDrawer(),this.renderCard()}function Ya(){let e=this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`;this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),e&&this.clearPreviewSelection(),this.scheduleLayoutRefresh()}function Xa(){return this.activeCard?this.activeCard.origin===`editor`?this.session?.getCommentAnchorClientRect?.(this.activeCard.anchor)??this.activeCard.sourceRect:this.activeCard.origin===`editor-chip`?this.activeCard.sourceRect:this.activeCard.origin===`preview`?Je(Array.from(this.activeCard.previewRange?.getClientRects?.()??[]))||(this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect??this.activeCard.sourceRect):this.activeCard.origin===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.()??this.activeCard.sourceRect:this.activeCard.sourceRect:null}function Za(e){return e instanceof HTMLTextAreaElement?{selectionDirection:e.selectionDirection??`none`,selectionEnd:e.selectionEnd,selectionStart:e.selectionStart,value:e.value}:null}function Qa(){if(!this.activeCard)return;let e=this.cardRoot?.querySelector(`.comment-card-input`),t=Za(e);if(t){if(this.activeCard.mode===`create`){this.activeCard.composerDraft=t;return}this.activeCard.mode===`group`&&this.activeCard.replyThreadId&&(this.activeCard.replyDrafts={...this.activeCard.replyDrafts??{},[this.activeCard.replyThreadId]:t})}}function $a(e,t=null){return{element:e,selectionDirection:t?.selectionDirection??`none`,selectionEnd:Number.isInteger(t?.selectionEnd)?t.selectionEnd:null,selectionStart:Number.isInteger(t?.selectionStart)?t.selectionStart:null}}function eo(){let e=this.ensureCardRoot();if(this.captureActiveCardDraft(),e.replaceChildren(),e.classList.toggle(`hidden`,!this.activeCard),!this.activeCard){this.pendingCardFocusElement=null,e.style.visibility=``;return}this.pendingCardFocusElement=null;let t=document.createElement(`section`);t.className=`comment-card`,t.addEventListener(`click`,e=>{!this.reactionPicker||e.target?.closest?.(`.comment-reaction-picker-wrap`)||(this.reactionPicker=null,requestAnimationFrame(()=>{this.activeCard&&this.renderCard()}))});let n=document.createElement(`div`);n.className=`ui-record-header comment-card-header`;let r=document.createElement(`div`);r.className=`comment-card-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-card-title`,i.textContent=this.activeCard.mode===`create`?`New comment`:`Comment threads`;let a=document.createElement(`p`);a.className=`comment-card-meta`,a.textContent=Xe(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-card-close`]}),o.setAttribute(`aria-label`,`Close comments`),o.textContent=`Close`,o.addEventListener(`click`,()=>this.closeCard()),n.append(r,o),t.appendChild(n);let s=document.createElement(`div`);if(s.className=`comment-card-scroll`,this.activeCard.mode===`create`&&this.activeCard.anchor?.fallbackToLines){let e=document.createElement(`p`);e.className=`comment-card-anchor-note`,e.textContent=`Exact preview mapping was unavailable. This comment will be anchored to ${Xe(this.activeCard.anchor).toLowerCase()}.`,s.appendChild(e)}if(this.activeCard.anchor?.quote){let e=document.createElement(`p`);e.className=`comment-card-quote`,e.textContent=this.activeCard.anchor.quote,s.appendChild(e)}if(this.activeCard.mode===`create`)s.appendChild(this.createComposer());else{let e=this.getThreadGroups().find(e=>e.key===this.activeCard.groupKey);if(!e){this.closeCard();return}e.threads.forEach(e=>{s.appendChild(this.createThreadElement(e))})}e.style.visibility=`hidden`,t.appendChild(s),e.appendChild(t),this.updateReactionPickerPosition(t),this.positionCard(t),e.style.visibility=``,this.flushPendingCardFocus(),this.scheduleLayoutRefresh()}function to(e){let t=Ve(e);if(!t)return;let{picker:n,scroll:r,wrap:i}=t;n.classList.remove(`is-upward`),n.style.maxHeight=``;let a=i.getBoundingClientRect(),o=r.getBoundingClientRect(),s=n.getBoundingClientRect(),c=window.innerHeight-12,l=Math.min(o.bottom,c),u=Math.max(o.top,12),d=Math.max(l-a.bottom-8,0),f=Math.max(a.top-u-8,0),p=s.height>d&&f>d,m=Math.max(p?f:d,120);n.classList.toggle(`is-upward`,p),n.style.maxHeight=`${m}px`}function no(){let e=this.cardRoot?.firstElementChild;if(!e||!this.activeCard){this.cardRoot&&(this.cardRoot.style.visibility=``);return}this.positionCard(e),this.cardRoot.style.visibility=``,this.flushPendingCardFocus()}function ro(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=H({extra:`comment-card-input`}),t.rows=4,t.maxLength=ke,t.placeholder=`Add context, feedback, or a question...`,t.value=this.activeCard?.composerDraft?.value??``;let n=document.createElement(`div`);n.className=`ui-record-actions comment-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=U({variant:`secondary`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=U({variant:`primary`}),i.textContent=`Post comment`,n.append(r,i),e.append(t,n),e.addEventListener(`submit`,async e=>{if(e.preventDefault(),!await this.onCreateThread?.({anchor:this.activeCard?.anchor,body:t.value})){t.focus();return}this.closeCard()}),this.pendingCardFocusElement=$a(t,this.activeCard?.composerDraft),e}function io(e){let t=document.createElement(`article`);t.className=`comment-thread-card`;let n=document.createElement(`div`);n.className=`ui-record-actions comment-thread-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let i=this.activeCard?.replyThreadId===e.id;r.classList.toggle(`is-active`,i),r.textContent=`Reply`,r.setAttribute(`aria-pressed`,String(i)),r.setAttribute(`aria-label`,i?`Cancel reply`:`Reply to thread`),r.title=i?`Cancel reply`:`Reply to thread`,r.addEventListener(`click`,()=>{i&&this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:i?null:e.id},this.renderCard()});let a=document.createElement(`button`);return a.type=`button`,a.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),a.textContent=`Resolve`,a.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),n.append(r,a),e.messages.forEach((r,i)=>{t.appendChild(this.createMessageElement(e,r,{actions:i===0?n:null,isThreadStart:i===0}))}),this.activeCard?.replyThreadId===e.id&&t.appendChild(this.createReplyComposer(e)),t}function ao(e,t,{actions:n=null,isThreadStart:r=!1}={}){let i=document.createElement(`div`);i.className=`comment-message-card`,i.classList.toggle(`is-thread-start`,r);let a=document.createElement(`div`);a.className=`ui-record-meta comment-message-card-meta`;let o=document.createElement(`span`);o.className=`comment-message-card-author`,o.textContent=t.userName;let s=document.createElement(`span`);s.className=`comment-message-card-time`,s.textContent=this.formatTimestamp(t.createdAt);let c=Le(t.body,`comment-message-card-body comment-markdown`);return a.append(o,s),n&&a.appendChild(n),i.append(a,c),i.appendChild(this.createReactionBar(e,t)),i}function oo(e,t){let n=this.session?.getLocalUser?.()?.userId??``,r=document.createElement(`div`);r.className=`comment-reaction-bar`;let i=new Set((t.reactions??[]).map(e=>e.emoji)),a=document.createElement(`div`);a.className=`comment-reaction-chips`,(t.reactions??[]).forEach(r=>{let i=document.createElement(`button`);i.type=`button`,i.className=`ui-chip-button ui-chip-button--comment comment-reaction-chip`,i.classList.toggle(`is-active`,Be(r,n)),i.setAttribute(`aria-pressed`,String(Be(r,n))),i.title=r.users?.map(e=>e.userName).join(`, `)||r.emoji;let o=document.createElement(`span`);o.className=`comment-reaction-chip-emoji`,o.textContent=r.emoji;let s=document.createElement(`span`);s.className=`comment-reaction-chip-count`,s.textContent=Re(r),i.append(o,s),i.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,r.emoji)}),a.appendChild(i)});let o=document.createElement(`div`);o.className=`comment-reaction-actions`,We.filter(e=>!i.has(e)).forEach(n=>{o.appendChild(this.createQuickReactionButton(e,t,n))});let s=document.createElement(`div`);s.className=`comment-reaction-picker-wrap`;let c=document.createElement(`button`);return c.type=`button`,c.className=`ui-chip-button ui-chip-button--comment comment-reaction-more-trigger`,c.dataset.reactionPickerToggle=`true`,c.setAttribute(`aria-expanded`,String(Ze(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{let n=Ze(this.reactionPicker,e.id,t.id);this.reactionPicker=n?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),Ze(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function so(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-quick-add`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)}),r}function co(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,Ye.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function lo(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-picker-btn`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)&&(this.reactionPicker=null,this.renderCard())}),r}function uo(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=this.activeCard?.replyDrafts?.[e.id]??null,r=document.createElement(`textarea`);r.className=H({extra:`comment-card-input`}),r.rows=3,r.maxLength=ke,r.placeholder=`Reply to thread...`,r.value=n?.value??``;let i=document.createElement(`div`);i.className=`ui-record-actions comment-card-actions`;let a=document.createElement(`button`);a.type=`button`,a.className=U({variant:`secondary`}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()});let o=document.createElement(`button`);return o.type=`submit`,o.className=U({variant:`primary`}),o.textContent=`Reply`,i.append(a,o),t.append(r,i),this.pendingCardFocusElement=$a(r,n),t.addEventListener(`submit`,async t=>{if(t.preventDefault(),!await this.onReplyToThread?.(e.id,r.value)){r.focus();return}this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()}),t}function fo(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=x((n-i.width)/2,16,n-i.width-16),o=x((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=x(t.left,16,n-Math.min(i.width,520)-16),c=t.bottom+14,c+i.height>r-16&&(c=Math.max(t.top-i.height-14,16))),this.cardRoot.style.left=`${s}px`,this.cardRoot.style.top=`${c}px`,this.cardRoot.style.width=`${Math.min(Math.max(i.width,520),n-32)}px`}function po(){let e=this.pendingCardFocusElement,t=e instanceof HTMLElement?e:e?.element;if(!(t instanceof HTMLElement)||!t.isConnected){this.pendingCardFocusElement=null;return}this.pendingCardFocusElement=null;let n=()=>{if(!t.isConnected)return;let n=document.activeElement;n instanceof HTMLElement&&this.editorContainer?.contains(n)&&n.blur(),t.focus({preventScroll:!0}),t instanceof HTMLTextAreaElement&&Number.isInteger(e?.selectionStart)&&Number.isInteger(e?.selectionEnd)&&t.setSelectionRange(e.selectionStart,e.selectionEnd,e.selectionDirection??`none`)};n(),document.activeElement!==t&&requestAnimationFrame(()=>{n(),document.activeElement!==t&&setTimeout(()=>{n()},50)})}var mo={captureActiveCardDraft:Qa,closeCard:Ya,createComposer:ro,createPendingFocusTarget:$a,createMessageElement:ao,createQuickReactionButton:so,createReactionBar:oo,createReactionPicker:co,createReactionPickerButton:lo,createReplyComposer:uo,createTextareaDraft:Za,createThreadElement:io,ensureCardRoot:Ka,flushPendingCardFocus:po,openComposerForSelection:qa,openThreadGroup:Ja,positionCard:fo,renderCard:eo,repositionActiveCard:no,updateCardSourceRect:Xa,updateReactionPickerPosition:to};function ho(e,t,n){e.classList.toggle(`is-active`,t),e.classList.toggle(`is-hovered`,n),e.classList.toggle(`is-passive`,!t&&!n)}function go(){let e=this.getThreadGroups();this.renderEditorLayer(e),this.renderPreviewLayer(e),this.repositionActiveCard()}function _o(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function vo(){if(this.editorLayer?.isConnected&&this.editorLayer.parentElement===this.editorContainer)return this.editorLayer;let e=document.createElement(`div`);return e.className=`comment-editor-layer`,this.editorContainer?.appendChild(e),this.editorLayer=e,e}function yo(e=this.getThreadGroups()){let t=this.ensureEditorLayer();if(!this.supported||!this.session){t.childElementCount>0&&t.replaceChildren();return}let n=this.editorContainer?.getBoundingClientRect?.();if(!n){t.childElementCount>0&&t.replaceChildren();return}let r=new Map(Array.from(t.querySelectorAll(`.comment-editor-badge`)).map(e=>[e.dataset.commentEditorGroupKey,e])),i=new Set,a=[];e.forEach(e=>{let o=this.session.getCommentAnchorClientRect?.(e.anchor);if(!o)return;let s=Ne(o,n);if(s.bottom<0||s.top>n.height)return;let c=r.get(e.key);c||(c=document.createElement(`button`),c.type=`button`,c.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,c.dataset.commentEditorGroupKey=e.key,c.addEventListener(`pointerdown`,e=>{e.preventDefault()}),c.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([c.dataset.commentEditorGroupKey])}),c.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),c.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([c.dataset.commentEditorGroupKey])}),c.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),c.addEventListener(`click`,()=>{let e=c.commentGroup;e&&this.openThreadGroup(e,{anchor:e.anchor,origin:`editor`,sourceRect:c.commentSourceRect})}),t.appendChild(c)),c.commentGroup=e,c.commentSourceRect=o,c.dataset.count!==String(e.threads.length)&&(c.dataset.count=String(e.threads.length),c.replaceChildren(He(e.threads.length)));let l=this.activeCard?.groupKey===e.key,u=this.hoveredEditorGroupKeys.includes(e.key);ho(c,l,u),c.setAttribute(`aria-label`,`${e.threads.length} comment thread${e.threads.length===1?``:`s`}`);let d=Math.max(s.top,8);c.style.top=`${d}px`,c.style.left=`${Math.max(n.width-36,8)}px`,c.title=`${e.threads.length} comment${e.threads.length===1?``:`s`}`,i.add(e.key),a.push(d)}),r.forEach((e,t)=>{i.has(t)||e.remove()});let o=t.querySelector(`.comment-selection-chip`);if(!this.committedSelectionAnchor||this.activeCard?.mode===`create`){o?.remove();return}let s=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),c=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??s;if(!c){o?.remove();return}let l=Ne(c,n);if(l.bottom<0||l.top>n.height){o?.remove();return}let u=x(l.top,8,Math.max(n.height-36,8));for(;a.some(e=>Math.abs(e-u)<32);)u=x(u+36,8,Math.max(n.height-36,8));o||(o=document.createElement(`button`),o.type=`button`,o.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,o.textContent=`Comment`,o.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,o.getBoundingClientRect())}),t.appendChild(o)),o.style.top=`${u}px`,o.style.right=`12px`}function bo(){if(this.previewLayer?.isConnected&&this.previewLayer.parentElement===this.previewElement)return this.previewLayer;let e=document.createElement(`div`);e.className=`comment-preview-highlights`;let t=document.createElement(`div`);return t.className=`comment-preview-layer`,this.previewElement?.append(e,t),this.previewHighlightLayer=e,this.previewLayer=t,t}function xo(e){let t=this.previewLayer?.querySelector(`.comment-preview-selection-chip`),n=this.activeCard?.mode===`create`?null:this.previewSelection;if(!n){t?.remove();return}let r=Je(Array.from(n.range?.getClientRects?.()??[]))||n.rect;if(!r){t?.remove();return}t||(t=document.createElement(`button`),t.type=`button`,t.className=`ui-chip-button ui-chip-button--comment comment-preview-selection-chip`,t.textContent=`Comment`,t.setAttribute(`aria-label`,`Comment on selected preview text`),t.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation()}),t.addEventListener(`click`,()=>{this.openComposerForSelection(`preview`,t.getBoundingClientRect(),t.previewSelection)}),this.previewLayer?.appendChild(t)),t.previewSelection=n,t.style.left=`${x(r.left-e.left,8,Math.max(this.previewElement.clientWidth-88,8))}px`,t.style.top=`${x(r.bottom-e.top+8,8,Math.max(this.previewElement.clientHeight-36,8))}px`}function So(e=this.getThreadGroups()){if(this.ensurePreviewLayer(),!this.supported||!this.previewElement){this.previewLayer?.childElementCount>0&&this.previewLayer.replaceChildren(),this.previewHighlightLayer?.childElementCount>0&&this.previewHighlightLayer.replaceChildren(),this.previewHoverRegions=[];return}let t=this.previewElement.getBoundingClientRect(),n={diagramShells:Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)),sourceBlocks:Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(e=>Pe(e))},r=new Map(Array.from(this.previewHighlightLayer?.querySelectorAll(`[data-comment-preview-highlight-key]`)??[]).map(e=>[e.dataset.commentPreviewHighlightKey,e])),i=new Set,a=({groupKey:e=``,isActive:n,isHovered:a,key:o,rect:s})=>{let c=r.get(o);c||(c=document.createElement(`div`),c.className=`comment-preview-highlight`,c.dataset.commentPreviewHighlightKey=o,this.previewHighlightLayer?.appendChild(c)),e?(c.dataset.commentPreviewGroupKey=e,c.dataset.commentPreviewGroupKeys=e):(delete c.dataset.commentPreviewGroupKey,delete c.dataset.commentPreviewGroupKeys),ho(c,n,a),c.style.left=`${s.left-t.left}px`,c.style.top=`${s.top-t.top}px`,c.style.width=`${s.width}px`,c.style.height=`${s.height}px`,i.add(o)};if(this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`){let e=Array.from(this.activeCard.previewRange?.getClientRects?.()??[]);(e.length>0?e:[this.resolvePreviewTarget(this.activeCard.anchor,n)?.bubbleRect].filter(Boolean)).forEach((e,t)=>{a({isActive:!0,isHovered:!1,key:`selection:${t}`,rect:e})})}let o=[];e.forEach(e=>{let t=this.resolvePreviewTarget(e.anchor,n);if(!t?.bubbleRect)return;o.push({key:e.key,rects:t.hoverRects?.length>0?t.hoverRects:[t.bubbleRect]});let r=this.activeCard?.groupKey===e.key,i=this.hoveredPreviewGroupKeys.includes(e.key);t.highlightRects?.forEach((t,n)=>{a({groupKey:e.key,isActive:r,isHovered:i,key:`${e.key}:highlight:${n}`,rect:t})})}),xo.call(this,t),r.forEach((e,t)=>{i.has(t)||e.remove()}),this.previewHoverRegions=o,this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function Co(){this.previewSelection=null,window.getSelection()?.removeAllRanges(),this.scheduleLayoutRefresh()}function wo(e,{diagramShells:t=null,sourceBlocks:n=null}={}){if(!this.previewElement||!e)return null;let r=(t??Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`))).find(t=>$e(t,e));if(r){let e=r.getBoundingClientRect();return{bubbleRect:e,highlightRects:[],hoverRects:[e]}}let i=(n??Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(e=>Pe(e))).filter(t=>$e(t,e));if(e.kind===`text`&&e.quote){let t=i.map(t=>({element:t,range:Ue(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:Je(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let a=i[0];if(!a)return null;let o=a.getBoundingClientRect();return{bubbleRect:o,highlightRects:[],hoverRects:[o]}}function To(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return t?.dataset?.commentPreviewGroupKey?[t.dataset.commentPreviewGroupKey]:je(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function Eo(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);if(r.length>0)return r;let i=this.previewHoverRegions.filter(n=>n.rects.some(n=>Me(e,t,n))).map(e=>e.key);return Ie(i)}function Do(e=[]){let t=Ie(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.syncHoveredCommentClasses())}function Oo(e=[]){let t=Ie(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.syncHoveredCommentClasses())}function ko(){this.editorLayer?.querySelectorAll(`.comment-editor-badge`).forEach(e=>{let t=e.dataset.commentEditorGroupKey;ho(e,this.activeCard?.groupKey===t,this.hoveredEditorGroupKeys.includes(t))}),[...Array.from(this.previewLayer?.querySelectorAll(`[data-comment-preview-group-key]`)??[]),...Array.from(this.previewHighlightLayer?.querySelectorAll(`[data-comment-preview-group-key]`)??[])].forEach(e=>{let t=e.dataset.commentPreviewGroupKey;ho(e,this.activeCard?.groupKey===t,this.hoveredPreviewGroupKeys.includes(t))})}function Ao(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}var jo={clearPreviewSelection:Co,ensureEditorLayer:vo,ensurePreviewLayer:bo,getPreviewGroupKeysAtPoint:Eo,getPreviewGroupKeysForTarget:To,refreshLayout:go,renderEditorLayer:yo,renderPreviewLayer:So,resolvePreviewTarget:wo,scheduleLayoutRefresh:_o,syncHoveredCommentClasses:ko,syncHoveredPreviewGroupsFromTarget:Ao,updateHoveredEditorGroups:Oo,updateHoveredPreviewGroups:Do};function Mo(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function No(){let e=this.threads.length,t=this.supported&&!!this.session;if(this.commentSelectionButton?.classList.toggle(`hidden`,!t),this.commentsToggleButton?.classList.toggle(`hidden`,!this.supported),this.commentSelectionButton&&(this.commentSelectionButton.disabled=!this.selectionAnchor),this.commentsToggleButton){this.commentsToggleButton.classList.toggle(`active`,this.drawerOpen),this.commentsToggleButton.setAttribute(`aria-expanded`,String(this.drawerOpen));let t=e>0?`Comments ${e}`:`Comments`,n=this.commentsToggleButton.querySelector(`.ui-action-label`);n?n.textContent=t:this.commentsToggleButton.textContent=t}}function Po(){if(!this.commentsDrawer||!this.commentsDrawerList||(this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),!this.supported||!this.drawerOpen))return;this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=Ke(e),r=e.threads.reduce((e,t)=>e+(Array.isArray(t.messages)?t.messages.length:0),0),i=Fe({authorName:n?.userName||e.threads[0]?.createdByName||`Anonymous`,buttonClassName:`comment-overview-thread comments-drawer-item`,footerClassName:`comment-overview-thread-footer comments-drawer-item-footer`,headerClassName:`comment-overview-thread-header comments-drawer-item-header`,lineClassName:`comment-overview-thread-line comments-drawer-item-title`,lineLabel:Xe(e.anchor),messageCount:r,previewBody:n?.body||``,previewClassName:`comment-markdown comment-overview-thread-preview comments-drawer-item-preview`,quote:e.anchor?.quote||e.anchor?.excerpt||`Source anchored comment`,quoteClassName:`comment-overview-thread-quote comments-drawer-item-quote`,timestamp:n?this.formatTimestamp(n.createdAt):``});i.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),i.addEventListener(`pointerdown`,e=>{e.preventDefault()}),i.addEventListener(`click`,()=>{this.onNavigateToLine?.(e.anchor?.startLine??1),this.openThreadGroup(e,{anchor:e.anchor,origin:`editor`,sourceRect:this.session?.getCommentAnchorClientRect?.(e.anchor)??i.getBoundingClientRect()})}),t.appendChild(i)}),this.commentsDrawerList.appendChild(t)}function Fo(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var Io={formatTimestamp:Fo,render:Mo,renderDrawer:Po,renderToolbar:No};function Lo(e){this.session?.getScrollContainer?.()?.removeEventListener(`scroll`,this.handleEditorScroll),this.session=e,this.selectionAnchor=e?.getCurrentSelectionCommentAnchor?.()??null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.previewSelection=null,this.reactionPicker=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,e?.getScrollContainer?.()?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}),this.render()}function Ro(e,{fileKind:t=`markdown`,supported:n=!1}={}){let r=this.currentFile!==e;this.currentFile=e,this.fileKind=t,this.supported=!!(e&&n),r&&(this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.activeCard=null,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.reactionPicker=null),this.supported||(this.drawerOpen=!1,this.activeCard=null,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.reactionPicker=null),this.render()}function zo(e){if(this.selectionAnchor=this.supported?e:null,!this.supported||!this.selectionAnchor){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(!et(this.selectionAnchor)){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pendingSelectionAnchor=this.selectionAnchor,this.activeCard?.mode===`create`){this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pointerSelecting){this.clearSelectionRevealTimer(),this.committedSelectionAnchor=null,this.renderToolbar(),this.scheduleLayoutRefresh();return}if(qe(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function Bo(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function Vo(e=[]){this.threads=Qe(e);let t=this.getThreadGroups();if(this.activeCard?.mode===`group`){let e=Array.isArray(this.activeCard.groupThreadIds)?this.activeCard.groupThreadIds:[],n=t.find(e=>e.key===this.activeCard.groupKey)??t.find(t=>t.threads.length===e.length&&t.threads.every(t=>e.includes(t.id)));n?(this.activeCard={...this.activeCard,anchor:n.anchor,groupKey:n.key,groupThreadIds:n.threads.map(e=>e.id)},this.activeCard.replyThreadId&&!n.threads.some(e=>e.id===this.activeCard.replyThreadId)&&(this.activeCard.replyThreadId=null)):this.activeCard=null}this.reactionPicker&&!this.threads.some(e=>e.id===this.reactionPicker.threadId&&e.messages?.some(e=>e.id===this.reactionPicker.messageId))&&(this.reactionPicker=null),this.render()}function Ho(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function Uo(){this.setDrawerOpen(!1)}function Wo(e){if(!e||!this.supported)return!1;let t=this.getThreadGroups().find(t=>t.threads.some(t=>t.id===e));return t?(this.onNavigateToLine?.(t.anchor?.startLine??1),this.openThreadGroup(t,{anchor:t.anchor,origin:`editor`,sourceRect:this.session?.getCommentAnchorClientRect?.(t.anchor)??null}),!0):!1}function Go(){let e=new Map;return this.threads.forEach(t=>{let n=ze(t.anchor),r=e.get(n);if(r){r.threads.push(t);return}e.set(n,{anchor:t.anchor,key:n,threads:[t]})}),Array.from(e.values()).sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0))}function Ko(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function qo(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!qe(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var Jo={attachSession:Lo,clearSelectionRevealTimer:Ko,closeDrawer:Uo,getThreadGroups:Go,handleEditorContentChange:Bo,openThreadFromOverview:Wo,scheduleSelectionReveal:qo,setCurrentFile:Ro,setDrawerOpen:Ho,setSelectionAnchor:zo,setThreads:Vo},Yo=class{constructor({commentSelectionButton:e,commentsDrawer:t,commentsDrawerEmpty:n,commentsDrawerList:r,commentsToggleButton:i,editorContainer:a,onWillOpenDrawer:o,onCreateThread:s,onNavigateToLine:c,onReplyToThread:l,onToggleReaction:u,onResolveThread:d,previewContainer:f,previewElement:p}){this.commentSelectionButton=e,this.commentsDrawer=t,this.commentsDrawerEmpty=n,this.commentsDrawerList=r,this.commentsToggleButton=i,this.editorContainer=a,this.onWillOpenDrawer=o,this.onCreateThread=s,this.onNavigateToLine=c,this.onReplyToThread=l,this.onToggleReaction=u,this.onResolveThread=d,this.previewContainer=f,this.previewElement=p,this.currentFile=null,this.fileKind=`markdown`,this.supported=!1,this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.selectionRevealTimer=0,this.pointerSelecting=!1,this.session=null,this.activeCard=null,this.hoveredEditorGroupKeys=[],this.hoveredEditorGroupKeysSignature=``,this.hoveredPreviewGroupKeys=[],this.hoveredPreviewGroupKeysSignature=``,this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.editorLayer=null,this.previewLayer=null,this.previewHighlightLayer=null,this.cardRoot=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.layoutFrame=0,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`}),this.handleEditorScroll=()=>this.scheduleLayoutRefresh(),this.handlePreviewScroll=()=>this.scheduleLayoutRefresh(),this.handleWindowResize=()=>this.scheduleLayoutRefresh(),this.handlePreviewPointerMove=e=>{this.lastPreviewPointerPosition={x:e.clientX,y:e.clientY},this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(e.clientX,e.clientY))},this.handlePreviewPointerLeave=()=>{this.lastPreviewPointerPosition=null,this.updateHoveredPreviewGroups([])},this.handlePreviewFocusIn=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.target))},this.handlePreviewFocusOut=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.relatedTarget))},this.handleDocumentSelectionChange=()=>{if(this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`)return;let e=this.supported&&this.fileKind===`markdown`?Ge(window.getSelection(),this.previewElement,this.session?.getText?.()??``):null;!e&&!this.previewSelection||(this.previewSelection=e,this.scheduleLayoutRefresh())},this.handleCommentSelectionButtonPointerDown=e=>{e.preventDefault()},this.handleEditorPointerDown=e=>{e.button!==0||!this.supported||!this.session||!e.target?.closest?.(`.cm-editor`)||e.target?.closest?.(`.comment-editor-layer`)||(this.pointerSelecting=!0,this.clearSelectionRevealTimer(),this.committedSelectionAnchor&&(this.committedSelectionAnchor=null,this.scheduleLayoutRefresh()))},this.handleDocumentPointerUp=()=>{this.pointerSelecting&&requestAnimationFrame(()=>{let e=this.supported?this.session?.getCurrentSelectionCommentAnchor?.()??null:null;this.pointerSelecting=!1,this.selectionAnchor=e,this.renderToolbar(),this.pendingSelectionAnchor=et(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=et(e)&&this.activeCard?.mode!==`create`?e:null,this.scheduleLayoutRefresh()})},this.handleEditorFocusOut=e=>{let t=e.relatedTarget;t instanceof Node&&(this.editorContainer?.contains(t)||this.cardRoot?.contains(t)||this.commentSelectionButton?.contains(t))||(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.handleDocumentPointerDown=e=>{let t=e.target;if(this.activeCard&&this.cardRoot){if(this.cardRoot.contains(t))return;this.closeCard()}this.drawerOpen&&(t instanceof Node&&(this.commentsDrawer?.contains(t)||this.commentsToggleButton?.contains(t))||this.closeDrawer())},this.handleDocumentKeyDown=e=>{if(e.key===`Escape`&&this.reactionPicker){this.reactionPicker=null,this.renderCard();return}e.key===`Escape`&&this.activeCard&&this.closeCard(),e.key===`Escape`&&this.previewSelection&&this.clearPreviewSelection(),e.key===`Escape`&&this.committedSelectionAnchor&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.commentSelectionButton?.addEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.commentSelectionButton?.addEventListener(`click`,()=>{this.openComposerForSelection(`toolbar`)}),this.commentsToggleButton?.addEventListener(`click`,()=>{this.setDrawerOpen(!this.drawerOpen)}),this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.previewElement?.addEventListener(`pointermove`,this.handlePreviewPointerMove,{passive:!0}),this.previewElement?.addEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.addEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.addEventListener(`focusout`,this.handlePreviewFocusOut),this.editorContainer?.addEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.addEventListener(`focusout`,this.handleEditorFocusOut),window.addEventListener(`resize`,this.handleWindowResize),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerUp),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown),document.addEventListener(`keydown`,this.handleDocumentKeyDown),document.addEventListener(`selectionchange`,this.handleDocumentSelectionChange)}destroy(){this.layoutFrame&&=(cancelAnimationFrame(this.layoutFrame),0),this.attachSession(null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.previewElement?.removeEventListener(`pointermove`,this.handlePreviewPointerMove),this.previewElement?.removeEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.removeEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.removeEventListener(`focusout`,this.handlePreviewFocusOut),this.commentSelectionButton?.removeEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.editorContainer?.removeEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.removeEventListener(`focusout`,this.handleEditorFocusOut),window.removeEventListener(`resize`,this.handleWindowResize),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerUp),document.removeEventListener(`pointerdown`,this.handleDocumentPointerDown),document.removeEventListener(`keydown`,this.handleDocumentKeyDown),document.removeEventListener(`selectionchange`,this.handleDocumentSelectionChange),this.previewHoverRegions=[],this.previewSelection=null,this.cardRoot?.remove(),this.editorLayer?.remove(),this.previewLayer?.remove(),this.pendingCardFocusElement=null}};Object.assign(Yo.prototype,Jo,Io,jo,mo);function Xo(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function Zo(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Qo=class{constructor({mobileBreakpointQuery:e=Xo()}={}){this.mobileBreakpointQuery=e,this.activeAnchor=null,this.desktopMenu=null,this.mobileBackdrop=null,this.mobileSheet=null,this.documentPointerDownHandler=null,this.windowResizeHandler=null,this.boundClose=()=>this.close()}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isOpen(){return!!(this.desktopMenu||this.mobileSheet)}toggle(e={}){if(this.isOpen()){this.close();return}this.open(e)}open({anchor:e=null,items:t=[],title:n=`Create`}={}){if(this.close({restoreFocus:!1}),!(!Array.isArray(t)||t.length===0)){if(this.activeAnchor=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,this.activeAnchor?.setAttribute(`aria-expanded`,`true`),this.isMobileViewport()){this.openMobileSheet({items:t,title:n});return}this.openDesktopMenu({anchor:this.activeAnchor,items:t,title:n})}}close({restoreFocus:e=!0}={}){this.desktopMenu&&=(this.desktopMenu.remove(),null),this.mobileBackdrop&&=(this.mobileBackdrop.remove(),null),this.mobileSheet&&=(this.mobileSheet.remove(),null),this.documentPointerDownHandler&&=(document.removeEventListener(`pointerdown`,this.documentPointerDownHandler),null),this.windowResizeHandler&&typeof window<`u`&&window.removeEventListener(`resize`,this.windowResizeHandler),this.windowResizeHandler=null;let t=this.activeAnchor;this.activeAnchor?.setAttribute(`aria-expanded`,`false`),this.activeAnchor=null,e&&t?.focus?.()}openDesktopMenu({anchor:e,items:t,title:n}){let r=document.createElement(`div`);r.className=`create-menu`,r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,n),this.renderMenuItems(r,t),document.body.appendChild(r),this.positionDesktopMenu(r,e),r.addEventListener(`keydown`,e=>{this.handleDesktopMenuKeyDown(e,r)}),this.documentPointerDownHandler=t=>{r.contains(t.target)||e?.contains?.(t.target)||this.close()},this.windowResizeHandler=this.boundClose,setTimeout(()=>{document.addEventListener(`pointerdown`,this.documentPointerDownHandler)},0),typeof window<`u`&&window.addEventListener(`resize`,this.windowResizeHandler),this.desktopMenu=r,Zo(r)[0]?.focus()}openMobileSheet({items:e,title:t}){let n=document.createElement(`button`);n.type=`button`,n.className=`file-action-sheet-backdrop`,n.setAttribute(`aria-label`,`Close ${t.toLowerCase()} menu`);let r=document.createElement(`div`);r.className=`file-action-sheet create-action-sheet`;let i=document.createElement(`div`);i.className=`create-action-sheet-header`,i.textContent=t,r.appendChild(i),this.renderMenuItems(r,e,{mobile:!0});let a=document.createElement(`button`);a.type=`button`,a.className=U({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-cancel`]}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.close()}),r.appendChild(a),n.addEventListener(`click`,()=>{this.close()}),document.body.append(n,r),this.mobileBackdrop=n,this.mobileSheet=r}renderMenuItems(e,t,{mobile:n=!1}={}){let r=null;t.forEach(t=>{if(t.group&&t.group!==r){let i=document.createElement(`div`);i.className=n?`create-action-sheet-group`:`create-menu-group`,i.textContent=t.group,e.appendChild(i),r=t.group}let i=document.createElement(`button`);i.type=`button`,i.className=n?U({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-item`,`create-action-sheet-option`]}):`create-menu-item`,i.setAttribute(`role`,n?`button`:`menuitem`),i.dataset.actionId=t.id;let a=document.createElement(`span`);a.className=`create-menu-item-icon`,a.setAttribute(`aria-hidden`,`true`),a.innerHTML=t.icon||``,i.appendChild(a);let o=document.createElement(`span`);o.className=`create-menu-item-copy`;let s=document.createElement(`span`);s.className=`create-menu-item-label`,s.textContent=t.label,o.appendChild(s);let c=t.meta||t.hint;if(c){let e=document.createElement(`span`);e.className=`create-menu-item-meta`,e.textContent=c,o.appendChild(e)}i.appendChild(o),i.addEventListener(`click`,()=>{this.close({restoreFocus:!1}),t.onSelect?.()}),e.appendChild(i)})}positionDesktopMenu(e,t){let n=e.getBoundingClientRect(),r=t?.getBoundingClientRect?.(),i=r?.left??8,a=Math.max(8,window.innerWidth-n.width-8),o=Math.max(8,Math.min(i,a)),s=(r?.bottom??8)+8,c=window.innerHeight-n.height-8;s>c&&r&&(s=Math.max(8,r.top-n.height-8)),e.style.left=`${o}px`,e.style.top=`${Math.max(8,s)}px`}handleDesktopMenuKeyDown(e,t){let n=Zo(t);if(n.length===0)return;let r=Math.max(0,n.indexOf(document.activeElement));switch(e.key){case`ArrowDown`:e.preventDefault(),n[(r+1)%n.length]?.focus();break;case`ArrowUp`:e.preventDefault(),n[(r-1+n.length)%n.length]?.focus();break;case`Home`:e.preventDefault(),n[0]?.focus();break;case`End`:e.preventDefault(),n[n.length-1]?.focus();break;case`Escape`:e.preventDefault(),this.close();break;case`Tab`:this.close({restoreFocus:!1})}}};function $o(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function es(e,t,n){return`${e} ${e===1?t:n}`}var ts=g.join(`,`);function ns(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function rs(e,t){return t?{...e,requestId:t}:e}var is=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,onShowFileExtensionsChange:r,pendingWorkspaceRequestIds:i=null,showFileExtensions:a=!1,state:o,toastController:s,vaultClient:c,view:l,refresh:u}){this.onFileDelete=t,this.onFileSelect=n,this.onShowFileExtensionsChange=r,this.pendingWorkspaceRequestIds=i,this.showFileExtensions=!!a,this.state=o,this.toastController=s,this.vaultClient=c,this.view=l,this.refresh=u,this.createButton=document.getElementById(`sidebarCreateBtn`),this.fileExplorerOptionsButton=document.getElementById(`fileExplorerOptionsBtn`),this.actionDialog=document.getElementById(`fileActionDialog`),this.actionForm=document.getElementById(`fileActionForm`),this.actionTitle=document.getElementById(`fileActionTitle`),this.actionCopy=document.getElementById(`fileActionCopy`),this.actionField=document.getElementById(`fileActionField`),this.actionLabel=document.getElementById(`fileActionLabel`),this.actionInput=document.getElementById(`fileActionInput`),this.actionHint=document.getElementById(`fileActionHint`),this.actionNote=document.getElementById(`fileActionNote`),this.actionCancelButton=document.getElementById(`fileActionCancel`),this.actionSubmitButton=document.getElementById(`fileActionSubmit`),this.createMenu=new Qo({mobileBreakpointQuery:e}),this.fileExplorerOptionsMenu=new Qo({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),this.fileExplorerOptionsButton?.addEventListener(`click`,()=>{this.openFileExplorerOptionsMenu({anchor:this.fileExplorerOptionsButton})}),this.actionCancelButton?.addEventListener(`click`,()=>this.closeActionDialog()),this.actionForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleActionSubmit()}),this.actionDialog?.addEventListener(`close`,()=>this.resetActionDialog())}getCreateActions({parentDir:e=``}={}){return[{contextLabel:`Upload files`,group:`File`,hint:`Supported vault files`,icon:this.getCreateActionIcon(`upload`),id:`upload`,label:`Upload files`,meta:`Multiple`,onSelect:()=>{this.handleUploadFiles({parentDir:e})}},{contextLabel:`New markdown file`,group:`Note`,hint:`Markdown`,icon:this.getCreateActionIcon(`markdown`),id:`markdown`,label:`Markdown note`,meta:`.md`,onSelect:()=>this.handleNewFile({parentDir:e})},{contextLabel:`New base file`,group:`Note`,hint:`Base`,icon:this.getCreateActionIcon(`base`),id:`base`,label:`Base file`,meta:`.base`,onSelect:()=>this.handleNewBase({parentDir:e})},{contextLabel:`New Excalidraw drawing`,group:`Diagram`,hint:`Excalidraw`,icon:this.getCreateActionIcon(`excalidraw`),id:`excalidraw`,label:`Excalidraw drawing`,meta:`.excalidraw`,onSelect:()=>this.handleNewDrawing({parentDir:e})},{contextLabel:`New draw.io diagram`,group:`Diagram`,hint:`draw.io`,icon:this.getCreateActionIcon(`drawio`),id:`drawio`,label:`draw.io diagram`,meta:`.drawio`,onSelect:()=>this.handleNewDrawio({parentDir:e})},{contextLabel:`New Mermaid diagram`,group:`Diagram`,hint:`Mermaid`,icon:this.getCreateActionIcon(`mermaid`),id:`mermaid`,label:`Mermaid diagram`,meta:`.mmd`,onSelect:()=>this.handleNewMermaid({parentDir:e})},{contextLabel:`New PlantUML diagram`,group:`Diagram`,hint:`PlantUML`,icon:this.getCreateActionIcon(`plantuml`),id:`plantuml`,label:`PlantUML diagram`,meta:`.puml`,onSelect:()=>this.handleNewPlantUml({parentDir:e})},{contextLabel:`New Structurizr workspace`,group:`Diagram`,hint:`Structurizr DSL`,icon:this.getCreateActionIcon(`structurizr`),id:`structurizr`,label:`Structurizr workspace`,meta:`.dsl`,onSelect:()=>this.handleNewStructurizr({parentDir:e})},{contextLabel:`New folder`,group:`Structure`,hint:`Folder`,icon:this.getCreateActionIcon(`folder`),id:`folder`,label:`Folder`,meta:`folder`,onSelect:()=>this.handleNewFolder({parentDir:e})}]}createContextMenuItems(e=``){return this.getCreateActions({parentDir:e}).map(e=>({label:e.contextLabel,onSelect:e.onSelect}))}getDirectoryContextMenuItems(e){return[...this.createContextMenuItems(e),{label:`Rename / move`,onSelect:()=>this.handleRenameDirectory(e)},{label:`Download`,onSelect:()=>this.handleDownloadDirectory(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Download`,onSelect:()=>this.handleDownloadFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){case`upload`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M5 20h14"/></svg>`;case`base`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`;case`drawio`:case`plantuml`:case`structurizr`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;case`excalidraw`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;case`folder`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`;case`mermaid`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`;default:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}}showError(e,t){this.showToast(t?.message?`${e}: ${t.message}`:e)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=crypto.randomUUID();return this.pendingWorkspaceRequestIds.add(e),e}clearPendingWorkspaceRequestId(e){e&&this.pendingWorkspaceRequestIds?.delete(e)}async runWorkspaceMutation(e){let t=this.createPendingWorkspaceRequestId();try{return await e(t)}catch(e){throw this.clearPendingWorkspaceRequestId(t),e}}openActionDialog({title:e,copy:t,label:n=`Path`,hint:r=``,note:i=``,placeholder:a=``,value:o=``,submitLabel:s=`Save`,destructive:c=!1,requiresInput:l=!0,emptyMessage:u=`A value is required`,onSubmit:d}){!this.actionDialog||!this.actionTitle||!this.actionCopy||!this.actionSubmitButton||!this.actionCancelButton||l&&!this.actionInput||(this.actionDialog.open&&(typeof this.actionDialog.close==`function`?this.actionDialog.close():(this.actionDialog.removeAttribute(`open`),this.resetActionDialog())),this.pendingAction={requiresInput:l,emptyMessage:u,onSubmit:d},this.createMenu.close({restoreFocus:!1}),this.fileExplorerOptionsMenu.close({restoreFocus:!1}),this.view?.removeContextMenu?.(),this.actionTitle.textContent=e,this.actionCopy.textContent=t,this.actionField&&(this.actionField.hidden=!l),this.actionLabel&&(this.actionLabel.textContent=n),this.actionInput&&(this.actionInput.value=o,this.actionInput.placeholder=a,this.actionInput.required=l,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=r,this.actionHint.hidden=!l||!r),this.actionNote&&(this.actionNote.textContent=i,this.actionNote.hidden=!i,this.actionNote.classList.toggle(`is-danger`,c)),this.actionSubmitButton.textContent=s,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.classList.toggle(`ui-button--primary`,!c),this.actionSubmitButton.classList.toggle(`ui-button--danger`,c),this.actionCancelButton.disabled=!1,typeof this.actionDialog.showModal==`function`?this.actionDialog.showModal():this.actionDialog.setAttribute(`open`,`true`),requestAnimationFrame(()=>{if(!l||!this.actionInput){this.actionSubmitButton.focus();return}this.actionInput.focus(),o&&this.actionInput.select()}))}resetActionDialog(){this.pendingAction=null,this.actionBusy=!1,this.actionField&&(this.actionField.hidden=!1),this.actionLabel&&(this.actionLabel.textContent=`Path`),this.actionInput&&(this.actionInput.value=``,this.actionInput.placeholder=``,this.actionInput.required=!0,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=``,this.actionHint.hidden=!0),this.actionNote&&(this.actionNote.textContent=``,this.actionNote.hidden=!0,this.actionNote.classList.remove(`is-danger`)),this.actionSubmitButton&&(this.actionSubmitButton.textContent=`Save`,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.className=U({variant:`primary`})),this.actionCancelButton&&(this.actionCancelButton.disabled=!1)}closeActionDialog(){if(this.actionDialog){if(this.actionDialog.open&&typeof this.actionDialog.close==`function`){this.actionDialog.close();return}this.actionDialog.removeAttribute(`open`),this.resetActionDialog()}}setActionDialogBusy(e){this.actionBusy=e,this.actionInput&&(this.actionInput.disabled=e||!(this.pendingAction?.requiresInput??!0)),this.actionCancelButton&&(this.actionCancelButton.disabled=e),this.actionSubmitButton&&(this.actionSubmitButton.disabled=e)}async handleActionSubmit(){if(!this.pendingAction?.onSubmit||this.actionBusy)return;let e=this.pendingAction.requiresInput,t=e?this.actionInput?.value.trim()??``:void 0;if(e&&!t){this.showToast(this.pendingAction.emptyMessage),this.actionInput?.focus();return}this.setActionDialogBusy(!0);let n;try{n=await this.pendingAction.onSubmit(t)}catch(e){this.showError(`Failed to complete action`,e)}if(this.setActionDialogBusy(!1),n!==!1){this.closeActionDialog();return}e&&this.actionInput&&(this.actionInput.focus(),this.actionInput.select())}async uploadVaultFiles(e=[],{parentDir:t=``}={}){let n=k(t),r=!1;for(let t of Array.from(e??[])){let e=w(t?.name),i=D(n,e);if(!e||!s(i)){this.showToast(`Unsupported file type: ${e||`unnamed file`}`);continue}try{await this.runWorkspaceMutation(e=>this.vaultClient.uploadFile({file:t,path:i,requestId:e})),r=!0,this.state.expandDirectoryPath(i,{includeLeaf:!1})}catch(t){this.showToast(`${e}: ${t?.message||`Failed to upload file`}`)}}return r&&await this.refresh(),r}async handleUploadFiles({parentDir:e=``}={}){let t=await Se({accept:ts,multiple:!0});return t.length!==0&&this.uploadVaultFiles(t,{parentDir:e})}async createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile(rs({content:t,path:e},n))),this.state.expandDirectoryPath(e,{includeLeaf:!1}),await this.refresh(),n&&this.onFileSelect?.(e),!0}catch(e){return this.showToast(e?.message||r),!1}}async createDirectory(e){let t=k(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,rs({},e))),this.state.expandDirectoryPath(t),await this.refresh(),!0}catch(e){return this.showToast(e?.message||`Failed to create folder`),!1}}async renameVaultFile(e,t,n){let r=k(t);if(!r)return this.showToast(`File path is required`),!1;let i=d(r);if(i&&i.toLowerCase()!==String(n??``).toLowerCase())return this.showToast(`File type changes are not supported during rename. Keep the ${n} extension.`),!1;let a=i?r:`${r}${n}`;if(!w(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(rs({newPath:a,oldPath:e},t))),this.state.expandDirectoryPath(a,{includeLeaf:!1}),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=a,this.onFileSelect?.(a)),!0}catch(e){return this.showToast(e?.message||`Failed to rename`),!1}}async renameDirectory(e,t){let n=k(t);if(!n)return this.showToast(`Folder path is required`),!1;if(n===e)return!0;try{if(await this.runWorkspaceMutation(t=>this.vaultClient.renameDirectory(rs({newPath:n,oldPath:e},t))),this.state.replaceExpandedDirectoryPrefix(e,n),this.state.expandDirectoryPath(n),await this.refresh(),this.state.activeFilePath&&this.state.activeFilePath.startsWith(`${e}/`)){let t=$o(this.state.activeFilePath,e,n);this.state.activeFilePath=t,this.onFileSelect?.(t)}return!0}catch(e){return this.showToast(e?.message||`Failed to rename folder`),!1}}async deleteVaultFile(e){try{return await this.runWorkspaceMutation(t=>this.vaultClient.deleteFile(e,rs({},t))),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=null,this.onFileDelete?.(e)),!0}catch(e){return this.showToast(e?.message||`Failed to delete`),!1}}async deleteDirectory(e,{recursive:t=!1}={}){try{await this.runWorkspaceMutation(n=>this.vaultClient.deleteDirectory(e,rs({recursive:t},n)));let n=this.state.activeFilePath;return await this.refresh(),this.state.removeExpandedDirectoryPrefix(e),n&&n.startsWith(`${e}/`)&&(this.state.activeFilePath=null,this.onFileDelete?.(n)),!0}catch(e){return this.showToast(e?.message||`Failed to delete folder`),!1}}planMoveEntryByDrop({destinationDirectory:e=``,sourcePath:t=``,sourceType:n=`file`}={}){let r=k(t),i=k(e),a=M(r),o=w(r);return!r||!o?{ok:!1,reason:`Invalid item to move`}:a===i?{ok:!1,reason:`Item is already in that folder`}:n===`directory`?i===r?{ok:!1,reason:`A folder cannot be moved into itself`}:i.startsWith(`${r}/`)?{ok:!1,reason:`A folder cannot be moved into one of its descendants`}:{nextPath:D(i,o),ok:!0}:{extension:d(r)||`.md`,nextPath:D(i,o),ok:!0}}canMoveEntryByDrop(e={}){return this.planMoveEntryByDrop(e).ok}async moveEntryByDrop(e={}){let t=this.planMoveEntryByDrop(e);return t.ok?e.sourceType===`directory`?this.renameDirectory(e.sourcePath,t.nextPath):this.renameVaultFile(e.sourcePath,t.nextPath,t.extension):(this.showToast(t.reason),!1)}async downloadFileEntry(e){try{return await this.vaultClient.downloadFile(e),!0}catch(e){return this.showToast(e?.message||`Failed to download file`),!1}}async downloadDirectoryEntry(e){try{return await this.vaultClient.downloadDirectory(e),!0}catch(e){return this.showToast(e?.message||`Failed to download folder`),!1}}getCreateContext(e=``){let t=k(e);return{hintPrefix:t?`Use "/" to create nested items under this folder.`:`Use "/" to place it inside a folder.`,inputLabelSuffix:t?`name or path`:`path`,note:t?`Parent folder: ${t}`:``,normalizedParentDir:t}}openRootCreateMenu({anchor:e=this.createButton}={}){this.openCreateMenu({anchor:e,parentDir:``})}openCreateMenu({anchor:e=this.createButton,parentDir:t=``}={}){this.view?.removeContextMenu?.(),this.fileExplorerOptionsMenu.close({restoreFocus:!1}),this.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}openFileExplorerOptionsMenu({anchor:e=this.fileExplorerOptionsButton}={}){this.view?.removeContextMenu?.(),this.createMenu.close({restoreFocus:!1}),this.fileExplorerOptionsMenu.toggle({anchor:e,items:[{icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"></path><circle cx="12" cy="12" r="2.5"></circle></svg>`,id:`show-file-extensions`,label:`Show file extensions`,meta:this.showFileExtensions?`On`:`Off`,onSelect:()=>{this.showFileExtensions=!this.showFileExtensions,this.onShowFileExtensionsChange?.(this.showFileExtensions)}}],title:`File explorer options`})}handleNewFile({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create markdown file`,copy:t.normalizedParentDir?`Add a new note inside the selected folder. It opens immediately after creation.`:`Add a new note to the vault. It opens immediately after creation.`,label:`File ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".md" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`my-note`:`notes/my-note`,submitLabel:`Create file`,emptyMessage:`File path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`File path is required`),!1;let r=C(D(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,re(r),{errorMessage:`Failed to create file`,openAfterCreate:!0})}})}handleNewBase({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create base file`,copy:t.normalizedParentDir?"Add a new `.base` file inside the selected folder. It opens immediately after creation.":"Add a new `.base` file to the vault. It opens immediately after creation.",label:`Base ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".base" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`table-view`:`views/table-view`,submitLabel:`Create base`,emptyMessage:`Base path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Base path is required`),!1;let r=S(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create base file`,openAfterCreate:!0})}})}handleNewFolder({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create folder`,copy:t.normalizedParentDir?`Add a new folder inside the selected folder.`:`Add a new folder to organize notes and diagrams.`,label:`Folder ${t.inputLabelSuffix}`,hint:t.hintPrefix,note:t.note,placeholder:t.normalizedParentDir?`archive`:`notes/archive`,submitLabel:`Create folder`,emptyMessage:`Folder path is required`,onSubmit:e=>this.createDirectory(D(t.normalizedParentDir,e))})}handleNewDrawing({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Excalidraw drawing`,copy:t.normalizedParentDir?`Start a new drawing inside the selected folder.`:`Start a new drawing file in the vault.`,label:`Drawing ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".excalidraw" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create drawing`,emptyMessage:`Drawing path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=C(D(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,ns(),{errorMessage:`Failed to create drawing`,openAfterCreate:!0})}})}handleNewMermaid({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Mermaid diagram`,copy:t.normalizedParentDir?"Create a new `.mmd` or `.mermaid` file inside the selected folder.":"Create a new `.mmd` or `.mermaid` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".mmd" is added automatically unless you enter ".mermaid".`,note:t.note,placeholder:t.normalizedParentDir?`flow`:`diagrams/flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ne(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Mermaid diagram`,openAfterCreate:!0})}})}handleNewDrawio({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create draw.io diagram`,copy:t.normalizedParentDir?"Create a new `.drawio` diagram inside the selected folder.":"Create a new `.drawio` diagram with a native starter document.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".drawio" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=j(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create draw.io diagram`,openAfterCreate:!0})}})}handleNewPlantUml({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create PlantUML diagram`,copy:t.normalizedParentDir?"Create a new `.puml` or `.plantuml` file inside the selected folder.":"Create a new `.puml` or `.plantuml` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".puml" is added automatically unless you enter ".plantuml".`,note:t.note,placeholder:t.normalizedParentDir?`sequence-flow`:`diagrams/sequence-flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=O(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleNewStructurizr({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Structurizr workspace`,copy:t.normalizedParentDir?`Create a collaborative C4 workspace inside the selected folder.`:`Create a collaborative C4 workspace in the vault.`,label:`Workspace ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".dsl" is added automatically. workspace.dsl is conventional; any workspace .dsl file can render.`,note:t.note,placeholder:`workspace`,submitLabel:`Create workspace`,emptyMessage:`Workspace path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Workspace path is required`),!1;let r=ae(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Structurizr workspace`,openAfterCreate:!0})}})}handleRenameFile(e){let t=d(e)||`.md`;this.openActionDialog({title:`Rename or move file`,copy:`Update the relative path without changing the file type.`,label:`Path`,hint:`Use "/" to move the file into another folder. ${t} is kept automatically.`,value:e,submitLabel:`Save file path`,emptyMessage:`File path is required`,onSubmit:n=>this.renameVaultFile(e,n,t)})}handleRenameDirectory(e){this.openActionDialog({title:`Rename or move folder`,copy:`Update the relative path for this folder and everything inside it.`,label:`Path`,hint:`Use "/" to move the folder into another location in the vault.`,value:e,submitLabel:`Save folder path`,emptyMessage:`Folder path is required`,onSubmit:t=>this.renameDirectory(e,t)})}handleDelete(e){this.openActionDialog({title:`Delete file`,copy:`This permanently removes the file from the vault.`,note:e,submitLabel:`Delete file`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteVaultFile(e)})}handleDeleteDirectory(e){let{directoryCount:t,fileCount:n}=this.state.getDirectoryDescendantSummary(e),r=t>0||n>0,i=r?`This will permanently remove ${es(n,`file`,`files`)} and ${es(t,`nested folder`,`nested folders`)} inside this folder.`:`This permanently removes the empty folder from the vault.`;this.openActionDialog({title:r?`Delete folder and contents`:`Delete folder`,copy:i,note:e,submitLabel:r?`Delete folder and contents`:`Delete folder`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteDirectory(e,{recursive:r})})}handleDownloadFile(e){this.downloadFileEntry(e)}handleDownloadDirectory(e){this.downloadDirectoryEntry(e)}};function as(e,t=[],n=[],r=[]){for(let i of e)if(!(!i?.path||!i?.type)){if(n.push({lowerPath:String(i.path).toLowerCase(),name:i.name,path:i.path,type:i.type}),i.type===`file`||i.type===`base`||i.type===`excalidraw`||i.type===`drawio`||i.type===`mermaid`||i.type===`plantuml`||i.type===`structurizr`||i.type===`pdf`||i.type===`image`){t.push(i.path),r.push({mtimeMs:i.mtimeMs,path:i.path});continue}i.type===`directory`&&Array.isArray(i.children)&&as(i.children,t,n,r)}return{fileEntries:r,files:t,searchEntries:n}}function os(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=os(n.children,t);if(e)return e}}return null}function ss(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=ss(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function cs(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var ls=class{constructor(){this.tree=[],this.flatFiles=[],this.flatFileEntries=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=as(this.tree,[],[],[]);this.flatFiles=t.files,this.flatFileEntries=t.fileEntries,this.flatSearchEntries=t.searchEntries}setSearchQuery(e){this.searchQuery=String(e??``).trim().toLowerCase()}getSearchMatches(){return this.searchQuery?this.flatSearchEntries.filter(e=>e.lowerPath.includes(this.searchQuery)).map(e=>({name:e.name,path:e.path,type:e.type})):[]}getNode(e){return os(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:ss(t)}setActiveFile(e){this.activeFilePath=e||null,e&&this.expandDirectoryPath(e,{includeLeaf:!1})}toggleDirectory(e){return this.expandedDirs.has(e)?(this.expandedDirs.delete(e),!1):(this.expandedDirs.add(e),!0)}expandDirectoryPath(e,{includeLeaf:t=!0}={}){let n=k(e);if(!n)return;let r=n.split(`/`),i=t?r.length:Math.max(r.length-1,0),a=``;for(let e=0;e<i;e+=1)a=a?`${a}/${r[e]}`:r[e],this.expandedDirs.add(a)}replaceExpandedDirectoryPrefix(e,t){let n=new Set;this.expandedDirs.forEach(r=>{if(r===e||r.startsWith(`${e}/`)){n.add(cs(r,e,t));return}n.add(r)}),this.expandedDirs=n}removeExpandedDirectoryPrefix(e){let t=new Set;this.expandedDirs.forEach(n=>{n===e||n.startsWith(`${e}/`)||t.add(n)}),this.expandedDirs=t}};function us(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=us(n.children,t);if(e)return e}}return null}var ds=420,fs=10,ps=700,ms=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onEntryDrop:t,onDirectorySelect:n,onDirectoryToggle:r,onFileContextMenu:i,onFileSelect:a,onSearchChange:o,onTreeContextMenu:s,onValidateDrop:c}){this.onEntryDrop=t,this.onDirectorySelect=n,this.onDirectoryToggle=r,this.onFileContextMenu=i,this.onFileSelect=a,this.onSearchChange=o,this.onTreeContextMenu=s,this.onValidateDrop=c,this.mobileBreakpointQuery=e,this.treeContainer=document.getElementById(`fileTree`),this.searchInput=document.getElementById(`fileSearchInput`),this.renderedDirectoryWrappers=new Map,this.renderedChildContainers=new Map,this.renderedFileItems=new Map,this.lastRenderMode=`tree`,this.longPressTimer=0,this.longPressContext=null,this.suppressedActivationTarget=null,this.contextMenuCloseHandler=null,this.actionSheetCloseHandler=null,this.dragSource=null,this.currentSearchQuery=``,this.activeDropTarget=null,this.invalidDropAttempt=null,this.autoExpandTimer=0,this.autoExpandTargetPath=``,this.rootDropZone=null,this.threadCounts=new Map,this.showFileExtensions=!1}initialize(){this.searchInput?.addEventListener(`input`,e=>{this.onSearchChange?.(e.target.value)}),this.treeContainer?.addEventListener(`contextmenu`,e=>{e.target.closest(`.file-tree-item`)||(e.preventDefault(),this.onTreeContextMenu?.(e))}),this.treeContainer?.addEventListener(`pointerdown`,e=>{e.target.closest(`.file-tree-item`)||this.startLongPress(e,()=>{this.onTreeContextMenu?.({clientX:Number(e.clientX||0),clientY:Number(e.clientY||0),preventDefault(){},target:this.treeContainer})},this.treeContainer)}),this.treeContainer?.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),this.treeContainer?.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`scroll`,()=>{this.cancelLongPress()},{passive:!0}),this.treeContainer?.addEventListener(`dragover`,e=>{this.handleTreeDragOver(e)}),this.treeContainer?.addEventListener(`drop`,e=>{this.handleTreeDrop(e)}),this.treeContainer?.addEventListener(`dragleave`,e=>{this.handleTreeDragLeave(e)})}revealFile(e){this.renderedFileItems.get(e)?.scrollIntoView({block:`nearest`})}setActiveFile(e){if(this.treeContainer?.querySelector(`.file-tree-file.active`)?.classList.remove(`active`),!e)return!0;let t=this.renderedFileItems.get(e);return t?.classList.add(`active`),!!t}setThreadCounts(e){this.threadCounts=e instanceof Map?e:new Map,this.renderedFileItems.forEach((e,t)=>{let n=Number(this.threadCounts.get(t)??0)||0,r=e.querySelector(`.file-tree-comment-count`);if(e.classList.toggle(`has-comments`,n>0),n<=0){delete e.dataset.threadCount,r?.remove();return}e.dataset.threadCount=String(n),r||(r=document.createElement(`span`),r.className=`file-tree-comment-count`,e.appendChild(r)),r.textContent=String(n),r.setAttribute(`aria-label`,`${n} open comment thread${n===1?``:`s`}`)})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,showFileExtensions:o=!1,threadCounts:s=new Map,tree:c}){if(!this.treeContainer)return;if(this.threadCounts=s instanceof Map?s:new Map,this.showFileExtensions=!!o,this.currentSearchQuery=String(a??``),this.currentSearchQuery&&this.clearDragFeedback(),this.searchInput&&this.searchInput.value!==a&&(this.searchInput.value=a),a){this.lastRenderMode=`search`,this.renderSearchResults(i,e);return}if(r||this.lastRenderMode!==`tree`||!Array.isArray(t)||t.length===0){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let l=Array.from(new Set(t.map(e=>M(e)))).sort((e,t)=>e.split(`/`).length-t.split(`/`).length).filter((e,t,n)=>!n.slice(0,t).some(t=>t&&e.startsWith(`${t}/`)));if(l.includes(``)){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of l)if(!this.rerenderDirectoryBranch(t,c,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}this.lastRenderMode=`tree`}renderSearchResults(e,t){if(!this.treeContainer)return;if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No matches</div>`;return}let n=document.createDocumentFragment();for(let r of e){if(r.type===`directory`){n.appendChild(this.createSearchDirectoryItem(r));continue}n.appendChild(this.createFileItem({activeFilePath:t,depth:0,filePath:r.path,fileType:r.type||(c(r.path)??`file`),name:r.name||w(r.path)}))}this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();r.appendChild(this.createRootDropZone()),this.renderNodes(e,r,{activeFilePath:t,depth:0,expandedDirs:n}),this.treeContainer.appendChild(r)}resetTreeIndexes(){this.renderedDirectoryWrappers.clear(),this.renderedChildContainers.clear(),this.renderedFileItems.clear()}renderNodes(e,t,{activeFilePath:n,depth:r,expandedDirs:i}){for(let a of e){if(a.type===`directory`){t.appendChild(this.createDirectoryItem(a,{activeFilePath:n,depth:r,expandedDirs:i}));continue}t.appendChild(this.createFileItem({activeFilePath:n,depth:r,filePath:a.path,fileType:a.type,name:a.name}))}}createDirectoryItem(e,{activeFilePath:t,depth:n,expandedDirs:r}){let i=document.createElement(`div`);i.className=`file-tree-group`;let a=document.createElement(`button`);a.className=`file-tree-item file-tree-dir`,a.style.setProperty(`--depth`,n),a.dataset.depth=n;let o=r.has(e.path);if(a.setAttribute(`aria-expanded`,String(o)),a.dataset.path=e.path,a.dataset.entryType=`directory`,a.innerHTML=`
|
|
171
|
-
<svg class="file-tree-chevron${o?` expanded`:``}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
|
|
172
|
-
<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
|
|
173
|
-
<span class="file-tree-name">${b(e.name)}</span>
|
|
174
|
-
`,this.configureDragSource(a,{path:e.path,type:`directory`}),this.bindDirectoryDropTarget(a,e.path),a.addEventListener(`click`,t=>{this.consumeSuppressedActivation(a,t)||this.onDirectoryToggle?.(e.path)}),a.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{directoryPath:e.path,type:`directory`})}),i.appendChild(a),this.renderedDirectoryWrappers.set(e.path,i),o&&Array.isArray(e.children)){let a=document.createElement(`div`);a.className=`file-tree-children`,this.renderedChildContainers.set(e.path,a),this.renderNodes(e.children,a,{activeFilePath:t,depth:n+1,expandedDirs:r}),i.appendChild(a)}else this.renderedChildContainers.delete(e.path);return i}createSearchDirectoryItem(e){let t=document.createElement(`button`);return t.className=`file-tree-item file-tree-dir`,t.style.setProperty(`--depth`,0),t.dataset.depth=0,t.dataset.path=e.path,t.dataset.entryType=`directory`,t.innerHTML=`
|
|
175
|
-
<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
|
|
176
|
-
<span class="file-tree-name">${b(e.name||w(e.path))}</span>
|
|
177
|
-
`,t.addEventListener(`click`,n=>{this.consumeSuppressedActivation(t,n)||this.onDirectorySelect?.(e.path)}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(t,()=>{this.onFileContextMenu?.(this.createLongPressEvent(t),{directoryPath:e.path,type:`directory`})}),t}rerenderDirectoryBranch(e,t,{activeFilePath:n,expandedDirs:r}){let i=this.renderedDirectoryWrappers.get(e),a=us(t,e);if(!i||a?.type!==`directory`)return!1;let o=i.querySelector(`.file-tree-dir`),s=r.has(e);o?.setAttribute(`aria-expanded`,String(s)),o?.querySelector(`.file-tree-chevron`)?.classList.toggle(`expanded`,s);let c=Number(o?.dataset.depth??0),l=this.renderedChildContainers.get(e)??i.querySelector(`.file-tree-children`);return this.clearRenderedDescendants(e),s?(l?l.innerHTML=``:(l=document.createElement(`div`),l.className=`file-tree-children`,i.appendChild(l)),this.renderedChildContainers.set(e,l),this.renderNodes(a.children??[],l,{activeFilePath:n,depth:c+1,expandedDirs:r}),!0):(l?.remove(),this.renderedChildContainers.delete(e),!0)}clearRenderedDescendants(e){let t=`${e}/`;Array.from(this.renderedDirectoryWrappers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedDirectoryWrappers.delete(e)}),Array.from(this.renderedChildContainers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedChildContainers.delete(e)}),Array.from(this.renderedFileItems.keys()).forEach(e=>{e.startsWith(t)&&this.renderedFileItems.delete(e)})}createFileItem({activeFilePath:e,depth:t,filePath:n,fileType:r=`file`,name:i}){let a=document.createElement(`button`);a.className=`file-tree-item file-tree-file`;let s=Number(this.threadCounts.get(n)??0),c=r===`drawio`,l=r===`excalidraw`,u=r===`base`,d=r===`image`,f=r===`pdf`,p=r===`mermaid`,m=r===`plantuml`,h=r===`structurizr`;u&&a.classList.add(`is-base`),c&&a.classList.add(`is-drawio`),l&&a.classList.add(`is-excalidraw`),d&&a.classList.add(`is-image`),f&&a.classList.add(`is-pdf`),p&&a.classList.add(`is-mermaid`),m&&a.classList.add(`is-plantuml`),h&&a.classList.add(`is-structurizr`),n===e&&a.classList.add(`active`),s>0&&a.classList.add(`has-comments`),a.style.setProperty(`--depth`,t),a.dataset.depth=t,a.dataset.path=n,a.dataset.entryType=`file`,s>0&&(a.dataset.threadCount=String(s));let g=this.showFileExtensions?String(i??``):o(i);return a.innerHTML=`
|
|
178
|
-
${gt(n)}
|
|
179
|
-
<span class="file-tree-name">${b(g)}</span>
|
|
180
|
-
${s>0?`<span class="file-tree-comment-count" aria-label="${s} open comment thread${s===1?``:`s`}">${s}</span>`:``}
|
|
181
|
-
`,this.configureDragSource(a,{path:n,type:`file`}),a.addEventListener(`click`,e=>{this.consumeSuppressedActivation(a,e)||this.onFileSelect?.(n)}),a.addEventListener(`contextmenu`,e=>{e.preventDefault(),this.onFileContextMenu?.(e,{filePath:n,type:`file`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{filePath:n,type:`file`})}),this.renderedFileItems.set(n,a),a}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isDragAndDropEnabled(){return!this.isMobileViewport()&&!this.currentSearchQuery}configureDragSource(e,t){if(!(e instanceof HTMLElement))return;let n=this.isDragAndDropEnabled();e.draggable=n,n&&(e.addEventListener(`dragstart`,n=>{this.dragSource={path:t.path,type:t.type},document.body?.classList.add(`is-file-tree-dragging`),this.treeContainer&&(this.treeContainer.dataset.dragActive=`true`),e.classList.add(`is-dragging`),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t.path))}),e.addEventListener(`dragend`,()=>{e.classList.remove(`is-dragging`);let t=this.dragSource;this.invalidDropAttempt&&t&&this.onEntryDrop?.(this.invalidDropAttempt),this.dragSource=null,this.invalidDropAttempt=null,this.clearDragFeedback()}),t.type===`file`&&(e.addEventListener(`dragenter`,e=>{this.handleNonDropTargetDragOver(e)}),e.addEventListener(`dragover`,e=>{this.handleNonDropTargetDragOver(e)})))}bindDirectoryDropTarget(e,t){!(e instanceof HTMLElement)||this.isMobileViewport()||(e.addEventListener(`dragenter`,n=>{this.handleDirectoryDragEnter(n,e,t)}),e.addEventListener(`dragover`,n=>{this.handleDirectoryDragOver(n,e,t)}),e.addEventListener(`drop`,e=>{this.handleDirectoryDrop(e,t)}))}createRootDropZone(){let e=document.createElement(`div`);return e.className=`file-tree-root-drop-zone`,e.textContent=`Drop here to move to vault root`,e.addEventListener(`dragenter`,e=>{this.handleRootZoneDragEnter(e)}),e.addEventListener(`dragover`,e=>{this.handleRootZoneDragOver(e)}),e.addEventListener(`drop`,e=>{this.handleRootZoneDrop(e)}),this.rootDropZone=e,e}validateDrop(e){return!this.dragSource||this.currentSearchQuery?!1:this.onValidateDrop?.({destinationDirectory:e,sourcePath:this.dragSource.path,sourceType:this.dragSource.type})===!0}setDropTarget(e){if(this.activeDropTarget?.element&&this.activeDropTarget.element!==e?.element&&this.activeDropTarget.element.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget?.root&&!e?.root&&this.treeContainer?.classList.remove(`is-drop-target-root`,`is-drop-invalid`),this.activeDropTarget?.rootZone&&!e?.rootZone&&this.rootDropZone?.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget=e,!e||e.isValid?this.invalidDropAttempt=null:this.dragSource&&(this.invalidDropAttempt={destinationDirectory:e.destinationDirectory||``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type}),e){if(e.root){this.treeContainer?.classList.toggle(`is-drop-target-root`,e.isValid),this.treeContainer?.classList.toggle(`is-drop-invalid`,!e.isValid);return}if(e.rootZone){this.rootDropZone?.classList.toggle(`is-drop-target`,e.isValid),this.rootDropZone?.classList.toggle(`is-drop-invalid`,!e.isValid);return}e.element.classList.toggle(`is-drop-target`,e.isValid),e.element.classList.toggle(`is-drop-invalid`,!e.isValid)}}scheduleAutoExpand(e,t){e.getAttribute(`aria-expanded`)!==`true`&&this.autoExpandTargetPath!==t&&(this.cancelAutoExpand(),this.autoExpandTargetPath=t,this.autoExpandTimer=window.setTimeout(()=>{this.autoExpandTimer=0,this.autoExpandTargetPath=``,e.isConnected&&e.getAttribute(`aria-expanded`)!==`true`&&this.onDirectoryToggle?.(t)},ps))}cancelAutoExpand(){this.autoExpandTimer&&=(window.clearTimeout(this.autoExpandTimer),0),this.autoExpandTargetPath=``}clearDragFeedback(){this.cancelAutoExpand(),this.setDropTarget(null),document.body?.classList.remove(`is-file-tree-dragging`),this.treeContainer&&delete this.treeContainer.dataset.dragActive}handleDirectoryDragEnter(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDragOver(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);e.dataTransfer&&(e.dataTransfer.dropEffect=r?`move`:`none`),this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDrop(e,t){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let n={destinationDirectory:t,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(n)}handleTreeDragOver(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault(),this.cancelAutoExpand();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.setDropTarget({destinationDirectory:``,element:this.treeContainer,isValid:t,root:!0})}handleTreeDrop(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleTreeDragLeave(e){if(!this.dragSource||!this.treeContainer)return;let t=e.relatedTarget;t&&this.treeContainer.contains(t)||this.clearDragFeedback()}handleRootZoneDragEnter(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDragOver(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDrop(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleNonDropTargetDragOver(e){this.dragSource&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=`none`),this.clearDragFeedback())}bindLongPress(e,t){!(e instanceof HTMLElement)||typeof t!=`function`||(e.addEventListener(`pointerdown`,n=>{this.startLongPress(n,t,e)}),e.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),e.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),e.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),e.addEventListener(`pointerleave`,()=>{this.cancelLongPress()}))}startLongPress(e,t,n=null){this.isMobileViewport()&&[`touch`,`pen`].includes(String(e.pointerType||``))&&Number(e.button??0)===0&&(this.cancelLongPress(),this.longPressContext={callback:t,pointerId:e.pointerId,startX:Number(e.clientX||0),startY:Number(e.clientY||0),target:n??e.currentTarget??e.target??null},this.longPressTimer=window.setTimeout(()=>{let e=this.longPressContext;this.longPressTimer=0,e&&(this.suppressedActivationTarget=e.target,e.callback(),this.longPressContext=null)},ds))}handleLongPressPointerMove(e){if(!this.longPressContext||e.pointerId!==this.longPressContext.pointerId)return;let t=Math.abs(Number(e.clientX||0)-this.longPressContext.startX),n=Math.abs(Number(e.clientY||0)-this.longPressContext.startY);(t>fs||n>fs)&&this.cancelLongPress()}cancelLongPress(){this.longPressTimer&&=(window.clearTimeout(this.longPressTimer),0),this.longPressContext=null}createLongPressEvent(e){return{clientX:this.longPressContext?.startX??0,clientY:this.longPressContext?.startY??0,preventDefault(){},stopPropagation(){},target:e}}consumeSuppressedActivation(e,t){return this.suppressedActivationTarget===e&&(this.suppressedActivationTarget=null,t?.preventDefault?.(),t?.stopPropagation?.(),!0)}showContextMenu(e,t){if(this.removeContextMenu(),!Array.isArray(t)||t.length===0)return;if(this.isMobileViewport()){this.showActionSheet(t);return}let n=document.createElement(`div`);n.className=`file-context-menu`;for(let e of t){let t=document.createElement(`button`);t.className=`file-context-item${e.danger?` file-context-danger`:``}`,t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)}document.body.appendChild(n);let r=n.getBoundingClientRect(),i=Math.max(8,window.innerWidth-r.width-8),a=Math.max(8,window.innerHeight-r.height-8);n.style.left=`${Math.max(8,Math.min(e.clientX,i))}px`,n.style.top=`${Math.max(8,Math.min(e.clientY,a))}px`;let o=e=>{n.contains(e.target)||this.removeContextMenu()};this.contextMenuCloseHandler=o,setTimeout(()=>document.addEventListener(`click`,o),0)}showActionSheet(e){let t=document.createElement(`button`);t.type=`button`,t.className=`file-action-sheet-backdrop`,t.setAttribute(`aria-label`,`Close file actions`);let n=document.createElement(`div`);n.className=`file-action-sheet`,e.forEach(e=>{let t=document.createElement(`button`);t.type=`button`,t.className=U({variant:`secondary`,extra:[`file-action-sheet-item`,e.danger?`file-context-danger`:``]}),t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)});let r=document.createElement(`button`);r.type=`button`,r.className=U({variant:`ghost`,extra:`file-action-sheet-item`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>{this.removeContextMenu()}),n.appendChild(r),t.addEventListener(`click`,()=>{this.removeContextMenu()}),document.body.append(t,n),this.actionSheetCloseHandler=()=>{t.remove(),n.remove(),this.actionSheetCloseHandler=null}}removeContextMenu(){this.cancelLongPress(),this.clearDragFeedback(),document.querySelectorAll(`.file-context-menu`).forEach(e=>e.remove()),this.contextMenuCloseHandler&&=(document.removeEventListener(`click`,this.contextMenuCloseHandler),null),this.actionSheetCloseHandler?.()}},hs=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,onShowFileExtensionsChange:i,showFileExtensions:a=!1,toastController:o,vaultClient:s}){this.onFileSelect=t,this.onFileDelete=n,this.onShowFileExtensionsChange=i,this.toastController=o,this.vaultClient=s,this.state=new ls,this.showFileExtensions=!!a,this.threadCounts=new Map,this.view=new ms({mobileBreakpointQuery:e,onDirectorySelect:e=>{this.state.expandDirectoryPath(e),this.state.setSearchQuery(``),this.renderTree({reset:!0})},onDirectoryToggle:e=>{this.state.toggleDirectory(e),this.view.rerenderDirectoryBranch(e,this.state.tree,{activeFilePath:this.state.activeFilePath,expandedDirs:this.state.expandedDirs})||this.renderTree()},onEntryDrop:e=>this.actionController.moveEntryByDrop(e),onFileContextMenu:(e,t)=>{if(t.type===`directory`){this.view.showContextMenu(e,this.actionController.getDirectoryContextMenuItems(t.directoryPath));return}this.view.showContextMenu(e,this.actionController.getFileContextMenuItems(t.filePath))},onFileSelect:e=>{this.onFileSelect?.(e)},onValidateDrop:e=>this.actionController.canMoveEntryByDrop(e),onSearchChange:e=>{this.state.setSearchQuery(e),this.renderTree()},onTreeContextMenu:e=>{this.view.showContextMenu(e,this.actionController.createContextMenuItems())}}),this.actionController=new is({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,onShowFileExtensionsChange:e=>{this.showFileExtensions=!!e,this.onShowFileExtensionsChange?.(this.showFileExtensions),this.renderTree()},pendingWorkspaceRequestIds:r,showFileExtensions:this.showFileExtensions,refresh:()=>this.refresh(),state:this.state,toastController:this.toastController,vaultClient:this.vaultClient,view:this.view})}initialize(){this.view.initialize(),this.actionController.initialize()}async refresh(){try{let e=await this.vaultClient.readTree();this.setTree(e.tree||[])}catch(e){console.error(`[explorer] Failed to load file tree:`,e.message)}}setTree(e,{changedPaths:t=null,reset:n=!1}={}){this.state.setTree(e),this.renderTree({changedPaths:t,reset:n})}setActiveFile(e){let t=this.state.expandedDirs.size;if(this.state.setActiveFile(e),this.state.searchQuery){this.view.setActiveFile(e);return}(this.state.expandedDirs.size!==t||!this.view.setActiveFile(e))&&this.renderTree()}setThreadCounts(e=new Map){this.threadCounts=e instanceof Map?new Map(e):new Map(Object.entries(e??{})),this.view.setThreadCounts(this.threadCounts)}revealFile(e,{clearSearch:t=!1}={}){t&&this.state.setSearchQuery(``),this.state.setActiveFile(e),this.renderTree({reset:t}),this.view.revealFile(e)}get flatFiles(){return this.state.flatFiles}get fileEntries(){return this.state.flatFileEntries}get flatDocumentFiles(){return this.state.flatFiles.filter(e=>!l(e))}renderTree({changedPaths:e=null,reset:t=!1}={}){this.view.render({activeFilePath:this.state.activeFilePath,changedPaths:e,expandedDirs:this.state.expandedDirs,reset:t,searchMatches:this.state.getSearchMatches(),searchQuery:this.state.searchQuery,showFileExtensions:this.showFileExtensions,threadCounts:this.threadCounts,tree:this.state.tree})}},gs=30;function _s(e=``){let t=w(e),n=M(e);return n?`
|
|
182
|
-
<span class="file-history-path">${b(t)}</span>
|
|
183
|
-
<span class="file-history-dir">${b(n)}</span>
|
|
184
|
-
`:`<span class="file-history-path">${b(t)}</span>`}function vs(e={}){let t=[String(e.authorName||`Unknown`),String(e.relativeDateLabel||``)];return e.status===`renamed`&&e.oldPath&&t.push(`Renamed from ${e.oldPath}`),t.filter(Boolean).map(e=>b(e)).join(` · `)}function ys(e={}){return e.type===`local`?`local`:`commit:${String(e.hash||``).trim()}:${String(e.pathAtCommit||``).trim()}`}function bs(){return{commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}var xs=class{constructor({diffRenderer:e=null,gitApiClient:t=null,onOpenCommitDiff:n=()=>{},onOpenFile:r=()=>{},onOpenPreview:i=()=>{},onOpenWorkspaceDiff:a=()=>{},toastController:o=null}={}){this.diffRenderer=e,this.gitApiClient=t,this.onOpenCommitDiff=n,this.onOpenFile=r,this.onOpenPreview=i,this.onOpenWorkspaceDiff=a,this.toastController=o,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.isActive=!1,this.currentFilePath=null,this.localChanges=null,this.history=bs(),this.diffMode=`unified`,this.selectedEntryKey=null,this.detailCache=new Map,this.detailErrors=new Map,this.historyListElement=null,this.historyListScrollTop=0,this.loadingEntryKey=null,this.selectionRequestToken=0}initialize(){this.openEditorButton?.addEventListener(`click`,()=>{this.isActive&&this.currentFilePath&&this.onOpenFile?.(this.currentFilePath)}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.diffMode||(this.diffMode=t,this.render())})}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-file-history-select]`):null;if(t){let e=this.findEntryByKey(t.getAttribute(`data-file-history-select`));e&&this.selectEntry(e);return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-diff]`)){this.openSelectedDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-preview]`)){this.openSelectedPreview();return}e.target instanceof Element&&e.target.closest(`[data-file-history-load-more]`)&&this.loadMore()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content?.classList.remove(`diff-content--history`),this.content&&(this.content.innerHTML=``),this.currentFilePath=null,this.localChanges=null,this.history=bs(),this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0}getEntries(){let e=[];this.localChanges&&e.push({...this.localChanges,key:`local`,label:`Local changes`,pathAtCommit:this.currentFilePath,type:`local`});for(let t of this.history.commits??[])e.push({...t,key:ys({...t,type:`commit`}),type:`commit`});return e}findEntryByKey(e){return this.getEntries().find(t=>t.key===e)??null}getSelectedEntry(){return this.findEntryByKey(this.selectedEntryKey)}getDefaultEntry(){return this.getEntries()[0]??null}getSelectedDetailState(){let e=this.getSelectedEntry();return e?{detail:this.detailCache.get(e.key)??null,entry:e,error:this.detailErrors.get(e.key)??``,loading:this.loadingEntryKey===e.key}:null}async openFileHistory({filePath:e}){this.isActive=!0,this.currentFilePath=String(e??``).trim()||null,this.localChanges=null,this.history={...bs(),loading:!0},this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0,this.renderLoading();try{let[e,t]=await Promise.all([this.loadLocalChanges().catch(()=>null),this.fetchHistoryPage({offset:0})]);this.localChanges=e,this.history=t;let n=this.getDefaultEntry();return n?(await this.selectEntry(n),{history:t,localChanges:e}):(this.render(),{history:t,localChanges:e})}catch(e){return console.error(`[file-history] Failed to load file history:`,e),this.toastController?.show(`Failed to load file history`),this.localChanges=null,this.history={...bs(),error:`Failed to load file history`,loaded:!0},this.render(),{history:this.history,localChanges:null}}}async loadLocalChanges(){if(!this.currentFilePath)return null;let e=await this.gitApiClient.readDiff({metaOnly:!0,path:this.currentFilePath,scope:`all`}),t=e.files?.[0];return t?{...t,summary:e.summary??{additions:Number(t.stats?.additions||0),deletions:Number(t.stats?.deletions||0),filesChanged:1}}:null}async fetchHistoryPage({offset:e=0}={}){if(!this.currentFilePath)return{...bs(),loaded:!0};let t=await this.gitApiClient.readFileHistory({limit:gs,offset:e,path:this.currentFilePath}),n=Array.isArray(t.commits)?t.commits:[];return{commits:n,error:``,hasMore:!!t.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e+n.length}}async loadSelectedDetail(e){if(!e)return null;if(e.type===`local`){let t=await this.gitApiClient.readDiff({path:this.currentFilePath||``,scope:`all`});return{detail:t.files?.[0]??null,summary:t.summary??e.summary??null}}let t=await this.gitApiClient.readCommit({hash:e.hash||``,path:e.pathAtCommit||``});return{commit:t.commit??null,detail:t.files?.[0]??null,summary:t.summary??null}}async selectEntry(e){if(!e)return null;let t=e.key||ys(e);this.selectedEntryKey=t,this.detailErrors.delete(t);let n=this.detailCache.get(t);if(n)return this.loadingEntryKey=null,this.render(),n;this.loadingEntryKey=t,this.render();let r=++this.selectionRequestToken;try{let n=await this.loadSelectedDetail(e);return this.detailCache.set(t,n),this.detailErrors.delete(t),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),n}catch(n){return console.error(`[file-history] Failed to load selected diff:`,n),this.toastController?.show(e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),this.detailErrors.set(t,e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),null}}async loadMore(){if(!(!this.currentFilePath||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.fetchHistoryPage({offset:this.history.offset});this.history={commits:[...this.history.commits,...e.commits],error:``,hasMore:e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e.offset},this.render()}catch(e){console.error(`[file-history] Failed to load more history:`,e),this.toastController?.show(`Failed to load file history`),this.history={...this.history,error:`Failed to load file history`,loadingMore:!1},this.render()}}}openSelectedDiff(){let e=this.getSelectedEntry();if(e){if(e.type===`local`){this.onOpenWorkspaceDiff?.(this.currentFilePath);return}this.onOpenCommitDiff?.(e.hash,{historyFilePath:this.currentFilePath,path:e.pathAtCommit})}}openSelectedPreview(){let e=this.getSelectedEntry();!e||e.type!==`commit`||this.onOpenPreview?.({currentFilePath:this.currentFilePath,hash:e.hash,path:e.pathAtCommit})}renderDiffFileHeader(e={}){return typeof this.diffRenderer?.renderFileHeader==`function`?this.diffRenderer.renderFileHeader(e):`
|
|
185
|
-
<div class="diff-file-header">
|
|
186
|
-
<span class="diff-file-path">${b(e.path||this.currentFilePath||``)}</span>
|
|
187
|
-
</div>
|
|
188
|
-
`}renderDiffMarkup(e={}){if(typeof this.diffRenderer?.renderDiffDetail==`function`){let t=this.diffRenderer.mode;this.diffRenderer.mode=this.diffMode;let n=this.diffRenderer.renderDiffDetail(e,0,{includeHeader:!0});return this.diffRenderer.mode=t,n}return`
|
|
189
|
-
${this.renderDiffFileHeader(e)}
|
|
190
|
-
<div class="diff-empty-state">Diff renderer unavailable.</div>
|
|
191
|
-
`}syncToolbar(){let e=this.getSelectedDetailState(),t=e?.entry??null,n=e?.detail?.summary??t?.summary??(t?{additions:Number(t.additions||0),deletions:Number(t.deletions||0)}:null),r=!!t;this.syncToolbarIndicators(t,n,r),this.syncToolbarButtonStates(r)}syncToolbarIndicators(e,t,n){let r=Number(t?.additions||0),i=Number(t?.deletions||0);this.fileIndicator&&(this.fileIndicator.textContent=e?.type===`commit`?e.shortHash||`Commit`:e?.type===`local`?`Local changes`:`History`),this.stats&&(this.stats.innerHTML=`
|
|
192
|
-
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${r}</span>
|
|
193
|
-
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${i}</span>
|
|
194
|
-
`,this.stats.classList.toggle(`hidden`,!n))}syncToolbarButtonStates(e){this.backToHistoryButton?.classList.add(`hidden`),this.gitActionsGroup?.classList.add(`hidden`),this.layoutToggle?.classList.add(`hidden`),this.prevButton?.classList.add(`hidden`),this.nextButton?.classList.add(`hidden`),this.actionsDivider?.classList.add(`hidden`),this.editorActionsGroup?.classList.remove(`hidden`),this.modeButtons.forEach(t=>{t.classList.toggle(`hidden`,!e),t.classList.toggle(`active`,t.getAttribute(`data-diff-mode`)===this.diffMode)}),this.openEditorButton?.toggleAttribute(`disabled`,!this.currentFilePath),this.openEditorButton&&(this.openEditorButton.textContent=`Open File`),this.primaryActionButton?.toggleAttribute(`disabled`,!0),this.commitButton?.toggleAttribute(`disabled`,!0)}renderLoading(){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">Loading file history...</div>`),this.historyListElement=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">${b(e)}</div>`),this.historyListElement=null,this.syncToolbar())}captureListScroll(){this.historyListElement&&(this.historyListScrollTop=Number(this.historyListElement.scrollTop||0))}restoreListScroll(){if(!this.content?.querySelector){this.historyListElement=null;return}let e=this.content.querySelector(`[data-file-history-list]`);this.historyListElement=e??null,e&&(e.scrollTop=this.historyListScrollTop,e.addEventListener(`scroll`,()=>{this.historyListScrollTop=Number(e.scrollTop||0)},{passive:!0}))}renderScopeLabels(e={}){let t=[];return e.hasStagedChanges&&t.push(`staged`),e.hasWorkingTreeChanges&&t.push(`working tree`),e.hasUntrackedChanges&&t.push(`untracked`),t.length>0?t.join(` · `):`working tree`}renderHistoryItem(e={}){let t=e.key===this.selectedEntryKey,n=Number(e.additions??e.summary?.additions??0),r=Number(e.deletions??e.summary?.deletions??0),i=e.type===`local`?`Live workspace`:vs(e),a=e.type===`local`?`Local changes`:e.subject||e.shortHash||`Commit`,o=e.type===`local`?`<span class="ui-pill-badge ui-pill-badge--accent file-history-item-badge">Live</span>`:`<span class="ui-pill-badge ui-pill-badge--code file-history-item-badge">${b(e.shortHash||``)}</span>`;return`
|
|
195
|
-
<button
|
|
196
|
-
class="ui-record-surface file-history-item${t?` active`:``}${e.type===`local`?` file-history-item-local`:``}"
|
|
197
|
-
type="button"
|
|
198
|
-
data-file-history-select="${b(e.key)}"
|
|
199
|
-
aria-current="${t?`true`:`false`}"
|
|
200
|
-
>
|
|
201
|
-
<span class="file-history-item-top">
|
|
202
|
-
<span class="file-history-item-copy">
|
|
203
|
-
<span class="file-history-item-title">${b(a)}</span>
|
|
204
|
-
<span class="file-history-item-meta">${e.type===`local`?b(this.renderScopeLabels(e)):i}</span>
|
|
205
|
-
</span>
|
|
206
|
-
${o}
|
|
207
|
-
</span>
|
|
208
|
-
<span class="file-history-item-stats">
|
|
209
|
-
<span class="git-change-add">+${n}</span>
|
|
210
|
-
<span class="git-change-del">-${r}</span>
|
|
211
|
-
</span>
|
|
212
|
-
</button>
|
|
213
|
-
`}renderSelectedHeader(e){let t=e?.entry;return t?`
|
|
214
|
-
<div class="file-history-detail-header">
|
|
215
|
-
<div class="file-history-detail-copy">
|
|
216
|
-
<span class="file-history-detail-kicker">${t.type===`local`?`Live workspace`:`Commit ${b(t.shortHash||``)}`}</span>
|
|
217
|
-
<h2 class="file-history-detail-title">${t.type===`local`?`Local changes`:b(t.subject||t.shortHash||`Commit`)}</h2>
|
|
218
|
-
<p class="file-history-detail-meta">${t.type===`local`?b(this.renderScopeLabels(t)):vs(t)}</p>
|
|
219
|
-
</div>
|
|
220
|
-
<div class="file-history-detail-actions">
|
|
221
|
-
<button
|
|
222
|
-
class="${U({variant:`secondary`,action:!0,surface:!0})}"
|
|
223
|
-
type="button"
|
|
224
|
-
data-file-history-open-selected-diff
|
|
225
|
-
>
|
|
226
|
-
Open Standalone Diff
|
|
227
|
-
</button>
|
|
228
|
-
${t.type===`commit`?`
|
|
229
|
-
<button
|
|
230
|
-
class="${U({variant:`primary`,action:!0})}"
|
|
231
|
-
type="button"
|
|
232
|
-
data-file-history-open-selected-preview
|
|
233
|
-
>
|
|
234
|
-
Preview File
|
|
235
|
-
</button>
|
|
236
|
-
`:``}
|
|
237
|
-
</div>
|
|
238
|
-
</div>
|
|
239
|
-
`:`
|
|
240
|
-
<div class="file-history-detail-header">
|
|
241
|
-
<div class="file-history-detail-copy">
|
|
242
|
-
<span class="file-history-detail-kicker">History</span>
|
|
243
|
-
<h2 class="file-history-detail-title">No selection</h2>
|
|
244
|
-
<p class="file-history-detail-meta">Choose a history item to inspect the file diff.</p>
|
|
245
|
-
</div>
|
|
246
|
-
</div>
|
|
247
|
-
`}renderSelectedBody(e){let t=e?.entry;return t?e.loading?`
|
|
248
|
-
<section class="diff-file-block file-history-diff-block">
|
|
249
|
-
${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
|
|
250
|
-
<div class="diff-empty-state">Loading diff...</div>
|
|
251
|
-
</section>
|
|
252
|
-
`:e.error?`
|
|
253
|
-
<section class="diff-file-block file-history-diff-block">
|
|
254
|
-
${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
|
|
255
|
-
<div class="diff-empty-state">${b(e.error)}</div>
|
|
256
|
-
</section>
|
|
257
|
-
`:e.detail?.detail?`
|
|
258
|
-
<section class="diff-file-block file-history-diff-block">
|
|
259
|
-
${this.renderDiffMarkup(e.detail.detail)}
|
|
260
|
-
</section>
|
|
261
|
-
`:`<div class="diff-empty-state">No diff available for this history item.</div>`:`<div class="diff-empty-state">Select a history entry to inspect this file.</div>`}render(){if(!this.isActive)return;if(this.page?.classList.remove(`hidden`),this.captureListScroll(),this.syncToolbar(),!this.currentFilePath){this.renderEmpty(`No file selected.`);return}if(this.history.loading&&!this.history.loaded){this.renderLoading();return}if(!(this.localChanges||(this.history.commits?.length??0)>0)){this.renderEmpty(this.history.error||`No history found for this file.`);return}if(!this.content)return;this.content.classList.add(`diff-content--history`);let e=this.getSelectedDetailState();this.content.innerHTML=`
|
|
262
|
-
<section class="file-history-shell">
|
|
263
|
-
<aside class="file-history-sidebar" aria-label="File history entries">
|
|
264
|
-
<header class="file-history-sidebar-header">
|
|
265
|
-
<span class="file-history-kicker">File history</span>
|
|
266
|
-
<div class="file-history-title">${_s(this.currentFilePath)}</div>
|
|
267
|
-
<p class="file-history-sidebar-copy">Select an entry to inspect the exact changes for this file.</p>
|
|
268
|
-
</header>
|
|
269
|
-
<div class="file-history-list" data-file-history-list>
|
|
270
|
-
${this.getEntries().map(e=>this.renderHistoryItem(e)).join(``)}
|
|
271
|
-
</div>
|
|
272
|
-
${this.history.hasMore?`
|
|
273
|
-
<div class="git-history-footer file-history-footer">
|
|
274
|
-
<button
|
|
275
|
-
class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
|
|
276
|
-
type="button"
|
|
277
|
-
data-file-history-load-more
|
|
278
|
-
${this.history.loadingMore?`disabled`:``}
|
|
279
|
-
>
|
|
280
|
-
${this.history.loadingMore?`Loading...`:`Load More`}
|
|
281
|
-
</button>
|
|
282
|
-
</div>
|
|
283
|
-
`:``}
|
|
284
|
-
</aside>
|
|
285
|
-
<section class="file-history-detail">
|
|
286
|
-
${this.renderSelectedHeader(e)}
|
|
287
|
-
<div class="file-history-detail-body">
|
|
288
|
-
${this.renderSelectedBody(e)}
|
|
289
|
-
</div>
|
|
290
|
-
</section>
|
|
291
|
-
</section>
|
|
292
|
-
`,this.restoreListScroll()}};function Ss(e={}){return Ga(`ui-segmented-control`,{"ui-segmented-control--pill":e.pill,hidden:e.hidden},e.extra??[])}function Cs(e={}){return Ga(`ui-segmented-btn`,{active:e.active,hidden:e.hidden},e.extra??[])}function ws(){return`base-${Math.random().toString(36).slice(2,10)}`}function Ts(e=``){return/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu.test(String(e??``).trim())}function Es(e=``){return/^https?:\/\/.+\.(?:png|jpe?g|webp|gif|svg)(?:[?#].*)?$/iu.test(String(e??``).trim())}function Ds(e){return Object.prototype.toString.call(e)===`[object Object]`}function Os(e=`and`){return{children:[],conjunction:e,type:`group`}}function ks(e,t,n){let r=e.image||t.find(e=>[`cover`,`image`].includes(String(e.id??``).toLowerCase()))?.id||null;return r?n.cells[r]??null:null}function W(e){return String(e?.text??``)}function As(e=``){return F(`/attachment?path=${encodeURIComponent(e)}`)}function js(e={}){if(e?.type===`image`&&e.path)return As(e.path);if(e?.type===`link`){if(e.external&&Es(e.url))return e.url;if(e.path&&l(e.path))return As(e.path)}let t=W(e);return Es(t)?t:l(t)?As(t):``}function Ms(e={}){let t=e?.type||`string`;if(t===`empty`)return`<span class="bases-value bases-value-empty">—</span>`;if(t===`boolean`)return`<span class="bases-value bases-value-boolean">${e.value?`True`:`False`}</span>`;if(t===`image`&&e.path)return`<img class="bases-inline-image" src="${b(As(e.path))}" alt="${b(W(e))}">`;if(t===`list`)return`<span class="bases-value-list">${(e.items??[]).map(e=>`<span class="bases-value-pill">${Ms(e)}</span>`).join(``)}</span>`;if(t===`link`){if(e.external&&e.url)return`<a class="bases-link" href="${b(e.url)}" target="_blank" rel="noopener noreferrer">${b(W(e))}</a>`;if(e.path)return`<button type="button" class="${b(U({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(e.path)}">${b(W(e))}</button>`}if(t===`file`&&e.path)return`<button type="button" class="${b(U({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(e.path)}">${b(W(e))}</button>`;let n=W(e);return`<span class="bases-value">${b(n)}</span>`}function Ns(e,t){let n=t?.cells?.[e.id]??null;return t?.path&&n&&n.type!==`empty`&&(e.id===`file.name`||e.id===`file.basename`)?`<button type="button" class="${b(U({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(t.path)}">${b(W(n))}</button>`:Ms(n)}function Ps(e=[]){return!Array.isArray(e)||e.length===0?``:`<div class="bases-summaries">${e.map(e=>`<div class="bases-summary"><span class="bases-summary-label">${b(e.label)}</span><span class="bases-summary-value">${b(W(e.value))}</span></div>`).join(``)}</div>`}function Fs(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Ps(t.summaries)}</header><div class="bases-table-shell"><table class="bases-table"><thead><tr>${e.map(e=>`<th>${b(e.label)}</th>`).join(``)}</tr></thead><tbody>${(t.rows??[]).map(t=>`<tr>${e.map(e=>`<td>${Ns(e,t)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div></section>`).join(``)}function Is(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Ps(t.summaries)}</header><ul class="bases-list">${(t.rows??[]).map(t=>`<li class="bases-list-item">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<span class="bases-list-field"><strong>${b(e.label)}:</strong> ${Ns(e,t)}</span>`}).join(``)}</li>`).join(``)}</ul></section>`).join(``)}function Ls(e,t,n){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Ps(t.summaries)}</header><div class="bases-cards">${(t.rows??[]).map(t=>{let r=ks(n,e,t),i=W(r),a=``;if(Ts(i))a=`<div class="bases-card-media bases-card-media-color" style="--bases-card-swatch:${b(i)}"></div>`;else{let e=js(r);e&&(a=`<img class="bases-card-media" src="${b(e)}" alt="${b(i)}">`)}return`<article class="bases-card">${a}<div class="bases-card-body">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<div class="bases-card-field"><div class="bases-card-label">${b(e.label)}</div><div class="bases-card-value">${Ns(e,t)}</div></div>`}).join(``)}</div></article>`}).join(``)}</div></section>`).join(``)}function Rs(e){if(!e.view.supported)return`<div class="bases-unsupported">CollabMD parsed this view but does not render the <code>${b(e.view.type)}</code> layout yet.</div>`;switch(e.view.type){case`cards`:return Ls(e.columns,e.groups,e.view);case`list`:return Is(e.columns,e.groups);default:return Fs(e.columns,e.groups)}}function zs(e){return(e.views??[]).map(t=>`<button type="button" class="${b(Cs({active:t.id===e.view.id,extra:`bases-view-tab`}))}" data-base-view="${b(t.id)}">${b(t.name)}</button>`).join(``)}function G(e){return e?.meta??{}}function Bs(e){return G(e).availableProperties??[]}function Vs(e){let t=G(e).activeViewConfig?.order;return Array.isArray(t)&&t.length>0?[...t]:Array.isArray(e?.columns)?e.columns.map(e=>e.id).filter(Boolean):[]}function Hs(e,t=``){return Bs(e).find(e=>e.id===t)??null}function Us(e,t=``){return Hs(e,t)?.filterOperators??[`is`,`is not`,`contains`,`does not contain`,`is empty`,`is not empty`]}function K(e){let t=G(e).activeViewConfig??{};return{filters:t.filters??null,groupBy:t.groupBy??null,order:Array.isArray(t.order)?[...t.order]:[],sort:Array.isArray(t.sort)?t.sort.map(e=>({...e})):[]}}function Ws(e){return!!(e?.payload?.path&&e?.payload?.sourcePath&&e.payload.path===e.payload.sourcePath)}function Gs(e,t,n,r){let i=n.ui?.openPanel===t,a=!!G(r).editable;return`<button type="button" class="${b(U({variant:i?`primary`:`secondary`,pill:!0,extra:[`bases-toolbar-btn`,i?`is-active`:``]}))}" data-base-panel="${b(t)}"${a?``:` disabled`}>${b(e)}</button>`}function Ks(e,t=``){if(!e||e.type!==`group`||!t)return e;let n=(e.children??[]).flatMap(e=>{if(e?.type===`group`){let n=Ks(e,t);return n?[n]:[]}return e?.propertyId===t?[]:[e]});return{...e,children:n}}function qs(e,t=``,n=e?.result){let r=G(n).activeViewConfig?.filters??null,i=Y(r),a=t&&i?tc(Ks(i,t),n):r;return JSON.stringify({filters:a,path:e?.payload?.path??``,source:e?.payload?.source??null,sourcePath:e?.payload?.sourcePath??``,view:n?.view?.id??e?.payload?.view??``})}function Js(e,t=``,n=e?.result){let r=e?.propertyValueOptions?.get(t)??null;return r&&r.cacheKey===qs(e,t,n)?r.values??[]:[]}function Ys(e,t){return[Gs(`Sort`,`sort`,t,e),Gs(`Filter`,`filter`,t,e),Gs(`Properties`,`properties`,t,e)].join(``)}function Xs(e,{allowBlank:t=!1,selected:n=``}={}){let r=[];return t&&r.push(`<option value=""${n?``:` selected`}>Property</option>`),Bs(e).forEach(e=>{r.push(`<option value="${b(e.id)}"${e.id===n?` selected`:``}>${b(e.label)}</option>`)}),r.join(``)}function Zs(e){let t=K(e),n=Hs(e,t.groupBy?.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}],r=t.sort??[];return`
|
|
293
|
-
<section class="bases-panel-card">
|
|
294
|
-
<div class="bases-panel-section">
|
|
295
|
-
<div class="bases-panel-title">Group by</div>
|
|
296
|
-
<div class="bases-sort-row">
|
|
297
|
-
<select class="${b(H({extra:`bases-select bases-sort-property`}))}" data-base-group-by-property>
|
|
298
|
-
${Xs(e,{allowBlank:!0,selected:t.groupBy?.property??``})}
|
|
299
|
-
</select>
|
|
300
|
-
<select class="${b(H({extra:`bases-select bases-sort-direction`}))}" data-base-group-by-direction${t.groupBy?.property?``:` disabled`}>
|
|
301
|
-
${n.map(e=>`<option value="${b(e.id)}"${e.id===(t.groupBy?.direction??`asc`)?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
302
|
-
</select>
|
|
303
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-clear-group-by${t.groupBy?.property?``:` disabled`}>Clear</button>
|
|
304
|
-
</div>
|
|
305
|
-
</div>
|
|
306
|
-
<div class="bases-panel-section">
|
|
307
|
-
<div class="bases-panel-title">Sort by</div>
|
|
308
|
-
<div class="bases-sort-list">
|
|
309
|
-
${r.map((t,n)=>{let i=Hs(e,t.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}];return`
|
|
310
|
-
<div class="bases-sort-row">
|
|
311
|
-
<select class="${b(H({extra:`bases-select bases-sort-property`}))}" data-base-sort-property="${n}">
|
|
312
|
-
${Xs(e,{selected:t.property})}
|
|
313
|
-
</select>
|
|
314
|
-
<select class="${b(H({extra:`bases-select bases-sort-direction`}))}" data-base-sort-direction="${n}">
|
|
315
|
-
${i.map(e=>`<option value="${b(e.id)}"${e.id===t.direction?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
316
|
-
</select>
|
|
317
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:up"${n===0?` disabled`:``}>↑</button>
|
|
318
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:down"${n===r.length-1?` disabled`:``}>↓</button>
|
|
319
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-delete="${n}">Delete</button>
|
|
320
|
-
</div>
|
|
321
|
-
`}).join(``)}
|
|
322
|
-
</div>
|
|
323
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-add>Add sort</button>
|
|
324
|
-
</div>
|
|
325
|
-
</section>
|
|
326
|
-
`}function Qs(e=[]){return e.join(`.`)}function q(e=``){return String(e??``).split(`.`).filter(e=>e!==``).map(e=>Number.parseInt(e,10)).filter(Number.isFinite)}function $s(e=``){return JSON.stringify(String(e??``))}function J(e=``,t=`text`,n=`is`){let r=String(e??``).trim();return!r&&n!==`is`&&n!==`is not`?`""`:t===`boolean`?r===`false`?`false`:`true`:t===`number`&&Number.isFinite(Number(r))?String(Number(r)):$s(r)}function ec(e,t=null){if(!e?.propertyId||!e?.operator)return``;let n=e.propertyId,r=t?.valueType??`text`;switch(e.operator){case`contains`:return`${n}.contains(${J(e.value,r,e.operator)})`;case`does not contain`:return`!${n}.contains(${J(e.value,r,e.operator)})`;case`starts with`:return`${n}.startsWith(${J(e.value,r,e.operator)})`;case`ends with`:return`${n}.endsWith(${J(e.value,r,e.operator)})`;case`is`:return`${n} == ${J(e.value,r,e.operator)}`;case`is not`:return`${n} != ${J(e.value,r,e.operator)}`;case`>`:case`>=`:case`<`:case`<=`:return`${n} ${e.operator} ${J(e.value,r,e.operator)}`;case`is empty`:return`${n}.isEmpty()`;case`is not empty`:return`!${n}.isEmpty()`;default:return``}}function tc(e,t){if(!e||e.type!==`group`)return null;let n=(e.children??[]).map(e=>e?.type===`group`?tc(e,t):ec(e,Hs(t,e?.propertyId))).filter(Boolean);return n.length===0?null:e.conjunction===`not`?{not:n}:{[e.conjunction]:n}}function nc(e=``){let t=String(e??``).trim();return t?t===`true`||t===`false`?t:t===`null`?``:/^-?\d+(?:\.\d+)?$/u.test(t)?t:t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).replace(/\\(["'])/gu,`$1`):t:``}function rc(e=``){let t=String(e??``).trim(),n=[[/^!([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is not empty`,propertyId:t,type:`rule`,value:``})],[/^([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is empty`,propertyId:t,type:`rule`,value:``})],[/^!([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`does not contain`,propertyId:t,type:`rule`,value:nc(n)})],[/^([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`contains`,propertyId:t,type:`rule`,value:nc(n)})],[/^([A-Za-z0-9_.]+)\.startsWith\((.+)\)$/u,(e,t,n)=>({operator:`starts with`,propertyId:t,type:`rule`,value:nc(n)})],[/^([A-Za-z0-9_.]+)\.endsWith\((.+)\)$/u,(e,t,n)=>({operator:`ends with`,propertyId:t,type:`rule`,value:nc(n)})],[/^([A-Za-z0-9_.]+)\s*(==|!=|>=|<=|>|<)\s*(.+)$/u,(e,t,n,r)=>({operator:{"!=":`is not`,"==":`is`,"<":`<`,"<=":`<=`,">":`>`,">=":`>=`}[n]??n,propertyId:t,type:`rule`,value:nc(r)})]];for(let[e,r]of n){let n=t.match(e);if(n)return r(...n)}return null}function Y(e){if(!e)return Os(`and`);if(typeof e==`string`){let t=rc(e);return t?{children:[t],conjunction:`and`,type:`group`}:null}if(!Ds(e))return null;if(Array.isArray(e.and)){let t=e.and.map(e=>Y(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`and`,type:`group`}:null}if(Array.isArray(e.or)){let t=e.or.map(e=>Y(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`or`,type:`group`}:null}if(e.not!=null){let t=(Array.isArray(e.not)?e.not:(()=>{let t=Y(e.not);return t?t.type===`group`&&t.conjunction===`or`?t.children??[]:[t]:[]})()).flatMap(e=>{let t=e?.type?e:Y(e);return t?t.type===`group`&&t.conjunction===`and`&&t.children?.length===1&&t.children[0]?.type===`rule`?t.children:[t]:[null]});return t.every(Boolean)?{children:t,conjunction:`not`,type:`group`}:null}return null}function ic(e){return e?typeof e==`string`?e:JSON.stringify(e,null,2):``}function ac(e=``){let t=String(e??``).trim();return t?t.startsWith(`{`)||t.startsWith(`[`)?JSON.parse(t):t:null}function oc(e,t=[]){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function X(e,t=[],n){if(t.length===0)return n(e);let[r,...i]=t;return{...e,children:(e.children??[]).map((e,t)=>t===r?X(e,i,n):e)}}function sc(e,t=[]){if(t.length===0)return e;let n=t.slice(0,-1),r=t[t.length-1];return X(e,n,e=>({...e,children:(e.children??[]).filter((e,t)=>t!==r)}))}function cc(e,t=[],n){return X(e,t,e=>({...e,children:[...e.children??[],n]}))}function lc(e,t=``){return Xs(e,{allowBlank:!0,selected:t})}function uc(e={}){return String(e?.text??e?.value??``).trim()}function dc(e,t){return e.ui.builderFilter??Y(K(t).filters)??Os(`and`)}function fc(e,t,n,r){let i=Qs(n),a=Us(e,t.propertyId),o=String(t.value??``).trim().toLowerCase(),s=Js(r,t.propertyId,e).map(e=>({count:e?.count,text:uc(e)})).filter((e,t,n)=>e.text&&n.findIndex(t=>t.text===e.text)===t),c=s.some(e=>e.text.toLowerCase()===o),l=s.filter(e=>!o||e.text.toLowerCase().includes(o)),u=!o||c?s:l.length>0?l:s,d=u.length>0&&![`is empty`,`is not empty`].includes(t.operator);return{encodedPath:i,operators:a,suggestionListId:`bases-filter-suggestions-${b(r.key)}-${b(i.replace(/\./g,`-`))}`,suggestionsEnabled:d,valueInputClasses:H({extra:d?`bases-filter-value bases-filter-value--suggestions`:`bases-filter-value`}),valueSuggestions:u,valueDisabled:[`is empty`,`is not empty`].includes(t.operator)}}function pc(e,t=``){return e.suggestionsEnabled?`
|
|
327
|
-
<div class="bases-filter-suggestion-list" id="${e.suggestionListId}" role="listbox">
|
|
328
|
-
${e.valueSuggestions.slice(0,8).map(n=>`
|
|
329
|
-
<button
|
|
330
|
-
type="button"
|
|
331
|
-
class="bases-filter-suggestion"
|
|
332
|
-
data-base-filter-suggestion="${b(e.encodedPath)}"
|
|
333
|
-
data-base-filter-suggestion-value="${b(n.text)}"
|
|
334
|
-
role="option"
|
|
335
|
-
aria-selected="${n.text===String(t??``)?`true`:`false`}"
|
|
336
|
-
>
|
|
337
|
-
<span class="bases-filter-suggestion-label">${b(n.text)}</span>
|
|
338
|
-
${n.count==null?``:`<span class="bases-filter-suggestion-meta">${b(String(n.count))}</span>`}
|
|
339
|
-
</button>
|
|
340
|
-
`).join(``)}
|
|
341
|
-
</div>
|
|
342
|
-
`:``}function mc(e,t,n,r){let i=fc(e,t,n,r);return`
|
|
343
|
-
<div class="bases-filter-value-combobox${i.suggestionsEnabled?` has-suggestions`:``}">
|
|
344
|
-
<input class="${b(i.valueInputClasses)}" type="text" value="${b(t.value??``)}" data-base-filter-value="${b(i.encodedPath)}"${i.suggestionsEnabled?` aria-controls="${i.suggestionListId}" aria-haspopup="listbox" aria-autocomplete="list" autocomplete="off"`:``}${i.valueDisabled?` disabled`:``}>
|
|
345
|
-
${pc(i,t.value??``)}
|
|
346
|
-
</div>
|
|
347
|
-
`}function hc(e,t,n,r){let i=fc(e,t,n,r);return`
|
|
348
|
-
<div class="bases-filter-row">
|
|
349
|
-
<select class="${b(H({extra:`bases-select bases-filter-property`}))}" data-base-filter-property="${b(i.encodedPath)}">
|
|
350
|
-
${lc(e,t.propertyId)}
|
|
351
|
-
</select>
|
|
352
|
-
<select class="${b(H({extra:`bases-select bases-filter-operator`}))}" data-base-filter-operator="${b(i.encodedPath)}">
|
|
353
|
-
${i.operators.map(e=>`<option value="${b(e)}"${e===t.operator?` selected`:``}>${b(e)}</option>`).join(``)}
|
|
354
|
-
</select>
|
|
355
|
-
${mc(e,t,n,r)}
|
|
356
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(i.encodedPath)}">Delete</button>
|
|
357
|
-
</div>
|
|
358
|
-
`}function gc(e,t,n,{fallbackToFullRender:r=!0}={}){let i=Tc(e)?.querySelector?.(`[data-base-panel-slot]`)??null,a=Qs(n),o=i?.querySelector?.(`[data-base-filter-value="${a}"]`)??null,s=o?.parentElement?.classList?.contains(`bases-filter-value-combobox`)?o.parentElement:null,c=oc(dc(e,t),n);if(!o||!s||!c||c.type!==`rule`||typeof o.insertAdjacentHTML!=`function`)return r&&Oc(e,t),!1;let l=fc(t,c,n,e);return s.classList.toggle(`has-suggestions`,l.suggestionsEnabled),o.className=l.valueInputClasses,o.disabled=l.valueDisabled,o.value!==String(c.value??``)&&(o.value=String(c.value??``)),l.suggestionsEnabled?(o.setAttribute(`aria-controls`,l.suggestionListId),o.setAttribute(`aria-haspopup`,`listbox`),o.setAttribute(`aria-autocomplete`,`list`),o.setAttribute(`autocomplete`,`off`)):(o.removeAttribute(`aria-controls`),o.removeAttribute(`aria-haspopup`),o.removeAttribute(`aria-autocomplete`),o.removeAttribute(`autocomplete`)),s.querySelector(`.bases-filter-suggestion-list`)?.remove?.(),l.suggestionsEnabled&&o.insertAdjacentHTML(`afterend`,pc(l,c.value??``)),!0}function _c(e,t,n=[]){if(e){if(e.type===`rule`){t(e,n);return}(e.children??[]).forEach((e,r)=>{_c(e,t,[...n,r])})}}function vc(e,t,n,r,{isRoot:i=!1}={}){let a=Qs(n);return`
|
|
359
|
-
<div class="bases-filter-group"${i?` data-base-filter-root`:``}>
|
|
360
|
-
<div class="bases-filter-group-header">
|
|
361
|
-
<select class="${b(H({extra:`bases-select bases-filter-conjunction`}))}" data-base-filter-conjunction="${b(a)}">
|
|
362
|
-
${[`and`,`or`,`not`].map(e=>`<option value="${e}"${t.conjunction===e?` selected`:``}>${b({and:`All the following are true`,not:`None of the following are true`,or:`Any of the following are true`}[e])}</option>`).join(``)}
|
|
363
|
-
</select>
|
|
364
|
-
${i?``:`<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(a)}">Delete group</button>`}
|
|
365
|
-
</div>
|
|
366
|
-
<div class="bases-filter-children">
|
|
367
|
-
${(t.children??[]).map((t,i)=>t?.type===`group`?vc(e,t,[...n,i],r):hc(e,t,[...n,i],r)).join(``)}
|
|
368
|
-
</div>
|
|
369
|
-
<div class="bases-filter-actions-row">
|
|
370
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-add-rule="${b(a)}">Add filter</button>
|
|
371
|
-
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-add-group="${b(a)}">Add filter group</button>
|
|
372
|
-
</div>
|
|
373
|
-
</div>
|
|
374
|
-
`}function yc(e,t){let n=K(e).filters,r=t.ui.builderFilter??Y(n);t.ui.builderFilter??(t.ui.builderFilter=r);let i=r?t.ui.filterMode??`builder`:`advanced`,a=t.ui.rawFilterText??ic(n);return`
|
|
375
|
-
<section class="bases-panel-card">
|
|
376
|
-
<div class="bases-panel-title-row">
|
|
377
|
-
<div class="bases-panel-title">This view</div>
|
|
378
|
-
${r?`
|
|
379
|
-
<div class="bases-toggle-row">
|
|
380
|
-
<button type="button" class="${b(U({variant:i===`builder`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="builder">Builder</button>
|
|
381
|
-
<button type="button" class="${b(U({variant:i===`advanced`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="advanced">Advanced</button>
|
|
382
|
-
</div>
|
|
383
|
-
`:``}
|
|
384
|
-
</div>
|
|
385
|
-
${i===`advanced`?`
|
|
386
|
-
<label class="bases-filter-advanced-label">
|
|
387
|
-
<textarea class="${b(H({extra:`bases-filter-advanced`}))}" data-base-filter-advanced>${b(a)}</textarea>
|
|
388
|
-
</label>
|
|
389
|
-
<div class="bases-filter-actions-row">
|
|
390
|
-
<button type="button" class="${b(U({variant:`primary`,size:`compact`}))}" data-base-filter-save-advanced>Save filter</button>
|
|
391
|
-
</div>
|
|
392
|
-
`:vc(e,r??Os(`and`),[],t,{isRoot:!0})}
|
|
393
|
-
</section>
|
|
394
|
-
`}function bc(e,t){let n=String(t.ui.propertySearch??``).trim().toLowerCase(),r=new Set(Vs(e)),i=Bs(e).filter(e=>!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n));return`
|
|
395
|
-
<section class="bases-panel-card">
|
|
396
|
-
<label class="bases-properties-search">
|
|
397
|
-
<input class="${b(H({extra:`bases-properties-search-input`}))}" type="search" value="${b(t.ui.propertySearch??``)}" placeholder="Find property" data-base-properties-search>
|
|
398
|
-
</label>
|
|
399
|
-
<div class="bases-properties-list" data-base-properties-list>
|
|
400
|
-
${i.map(e=>`
|
|
401
|
-
<label class="bases-property-option">
|
|
402
|
-
<input type="checkbox" data-base-property-toggle="${b(e.id)}"${r.has(e.id)?` checked`:``}>
|
|
403
|
-
<span class="bases-property-option-label">${b(e.label)}</span>
|
|
404
|
-
<span class="bases-property-option-meta">${b(e.kind)}</span>
|
|
405
|
-
</label>
|
|
406
|
-
`).join(``)}
|
|
407
|
-
</div>
|
|
408
|
-
</section>
|
|
409
|
-
`}function xc(e){let t=e?.querySelector?.(`[data-base-properties-list]`)??null,n=e?.querySelector?.(`[data-base-properties-search]`)??null,r=typeof document<`u`?document.activeElement:null,i=null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`properties-search`}}else if(r?.dataset?.baseFilterValue!=null){let t=String(r.dataset.baseFilterValue),n=e?.querySelector?.(`[data-base-filter-value="${t}"]`)??null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={path:t,selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`filter-value`}}}return{focusedControl:i,propertiesListScrollTop:t?t.scrollTop:null}}function Sc(e,t){if(t){if(t.propertiesListScrollTop!=null){let n=e?.querySelector?.(`[data-base-properties-list]`)??null;n&&(n.scrollTop=t.propertiesListScrollTop)}if(t.focusedControl?.type===`properties-search`){let n=e?.querySelector?.(`[data-base-properties-search]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart));return}if(t.focusedControl?.type===`filter-value`&&t.focusedControl.path!=null){let n=e?.querySelector?.(`[data-base-filter-value="${t.focusedControl.path}"]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart))}}}function Cc(e,t){if(!t.ui?.openPanel)return``;if(!G(e).editable)return`<section class="bases-panel-card"><div class="bases-readonly-note">Inline base previews are read-only. Open the .base file to edit its sort, filter, and properties.</div></section>`;switch(t.ui.openPanel){case`filter`:return yc(e,t);case`properties`:return bc(e,t);default:return Zs(e)}}function wc(e,t){return`
|
|
410
|
-
<section class="bases-shell" data-base-shell-key="${b(t.key)}">
|
|
411
|
-
<header class="bases-toolbar">
|
|
412
|
-
<div class="bases-toolbar-main">
|
|
413
|
-
<div class="${b(Ss({pill:!0,extra:`bases-tabs`}))}" data-base-tabs>
|
|
414
|
-
${zs(e)}
|
|
415
|
-
</div>
|
|
416
|
-
<div class="bases-meta" data-base-meta>${b(String(e.totalRows??0))} results</div>
|
|
417
|
-
</div>
|
|
418
|
-
<div class="bases-toolbar-actions">
|
|
419
|
-
<div class="bases-toolbar-edit-actions" data-base-action-slot>${Ys(e,t)}</div>
|
|
420
|
-
<label class="bases-search-shell" aria-label="Search this base">
|
|
421
|
-
<svg class="bases-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
422
|
-
<circle cx="11" cy="11" r="7"></circle>
|
|
423
|
-
<path d="m20 20-3.5-3.5"></path>
|
|
424
|
-
</svg>
|
|
425
|
-
<input class="${b(H({extra:`bases-search-input`}))}" type="search" value="${b(t.search)}" placeholder="Search this base" aria-label="Search this base">
|
|
426
|
-
</label>
|
|
427
|
-
<button type="button" class="${b(U({variant:`secondary`,pill:!0,extra:`bases-export-btn`}))}">Export CSV</button>
|
|
428
|
-
</div>
|
|
429
|
-
</header>
|
|
430
|
-
<div class="bases-panels" data-base-panel-slot>${Cc(e,t)}</div>
|
|
431
|
-
<div data-base-summary-slot>${Ps(e.summaries)}</div>
|
|
432
|
-
<div class="bases-content" data-base-content>${Rs(e)}</div>
|
|
433
|
-
</section>
|
|
434
|
-
`}function Tc(e){return e?.placeholder?.querySelector?e.placeholder.querySelector(`[data-base-shell-key="${e.key}"]`)??e.placeholder.querySelector(`.bases-shell`):null}function Ec(e){e?.classList&&(e.classList.add(`is-hydrated`),e.classList.remove(`diagram-preview-shell`))}function Dc(e,t,{actions:n=!0,body:r=!0,meta:i=!0,panel:a=!0,summary:o=!0,tabs:s=!0}={}){let c=Tc(e);if(!c?.querySelector){e.placeholder.innerHTML=wc(t,e),Ec(e.placeholder);return}let l=c.querySelector(`[data-base-tabs]`);s&&l&&(l.innerHTML=zs(t));let u=c.querySelector(`[data-base-meta]`);i&&u&&(u.textContent=`${String(t.totalRows??0)} results`);let d=c.querySelector(`[data-base-action-slot]`);n&&d&&(d.innerHTML=Ys(t,e));let f=c.querySelector(`[data-base-panel-slot]`);if(a&&f){let n=xc(f);f.innerHTML=Cc(t,e),Sc(f,n)}let p=c.querySelector(`[data-base-summary-slot]`);o&&p&&(p.innerHTML=Ps(t.summaries));let m=c.querySelector(`[data-base-content]`);r&&m&&(m.innerHTML=Rs(t));let h=c.querySelector(`.bases-search-input`);h&&h.value!==e.search&&(h.value=e.search)}function Oc(e,t){Dc(e,t,{actions:!1,body:!1,meta:!1,summary:!1,tabs:!1})}var kc=class{constructor({getActiveFilePath:e=()=>``,getSession:t=()=>null,onOpenFile:n,previewElement:r,replaceBaseSource:i=null,toastController:a,vaultApiClient:o}){this.getActiveFilePath=e,this.getSession=t,this.onOpenFile=n,this.previewElement=r,this.replaceBaseSource=i,this.toastController=a,this.vaultApiClient=o,this.entries=new Map,this.searchTimers=new Map,this.applyFilterSuggestion=(e,t,n)=>{this.updateBuilderFilter(e,e=>X(e,t,e=>({...e,value:n})))},this.persistBuilderFilter=e=>{let t=dc(e,e.result);e.ui.builderFilter=t,this.updateViewConfig(e,n=>(n.filters=tc(t,e.result),n))},this.handlePointerDown=e=>{let t=e.target.closest(`[data-base-filter-suggestion]`);if(!t)return;let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;e.preventDefault();let i=q(t.dataset.baseFilterSuggestion||``),a=t.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,i,a)},this.handleClick=e=>{let t=e.target.closest(`[data-base-open-file]`);if(t){e.preventDefault(),this.onOpenFile?.(t.dataset.baseOpenFile||``);return}let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=e.target.closest(`.bases-view-tab`);if(i){r.payload.view=i.dataset.baseView||``,r.ui.openPanel=``,this.renderEntry(r);return}let a=e.target.closest(`[data-base-panel]`);if(a){let e=a.dataset.basePanel||``;r.ui.openPanel=r.ui.openPanel===e?``:e,r.ui.rawFilterText=ic(K(r.result).filters),Oc(r,r.result);return}if(e.target.closest(`.bases-export-btn`)){this.exportEntry(r);return}if(e.target.closest(`[data-base-sort-add]`)){this.updateViewConfig(r,e=>{let t=new Set((e.sort??[]).map(e=>e.property)),n=Bs(r.result).find(e=>!t.has(e.id))?.id??`file.name`;return e.sort=[...e.sort??[],{direction:`asc`,property:n}],e});return}let o=e.target.closest(`[data-base-sort-delete]`);if(o){let e=Number.parseInt(o.dataset.baseSortDelete||``,10);this.updateViewConfig(r,t=>(t.sort=(t.sort??[]).filter((t,n)=>n!==e),t));return}let s=e.target.closest(`[data-base-sort-move]`);if(s){let[e,t]=String(s.dataset.baseSortMove||``).split(`:`),n=Number.parseInt(e,10);this.updateViewConfig(r,e=>{let r=[...e.sort??[]],i=t===`up`?n-1:n+1;return i<0||i>=r.length?e:([r[n],r[i]]=[r[i],r[n]],e.sort=r,e)});return}if(e.target.closest(`[data-base-clear-group-by]`)){this.updateViewConfig(r,e=>(e.groupBy=null,e));return}let c=e.target.closest(`[data-base-filter-mode]`);if(c){r.ui.filterMode=c.dataset.baseFilterMode||`builder`,r.ui.filterMode===`advanced`&&(r.ui.rawFilterText=ic(K(r.result).filters),r.ui.builderFilter=null),Oc(r,r.result);return}if(e.target.closest(`[data-base-filter-save-advanced]`)){this.saveAdvancedFilter(r);return}let l=e.target.closest(`[data-base-filter-add-rule]`);if(l){let e=q(l.dataset.baseFilterAddRule||``);this.updateBuilderFilter(r,t=>cc(t,e,{operator:`is`,propertyId:Bs(r.result)[0]?.id??`file.name`,type:`rule`,value:``}));return}let u=e.target.closest(`[data-base-filter-add-group]`);if(u){let e=q(u.dataset.baseFilterAddGroup||``);this.updateBuilderFilter(r,t=>cc(t,e,Os(`and`)));return}let d=e.target.closest(`[data-base-filter-remove]`);if(d){let e=q(d.dataset.baseFilterRemove||``);this.updateBuilderFilter(r,t=>sc(t,e));return}let f=e.target.closest(`[data-base-filter-suggestion]`);if(f){if(e.preventDefault?.(),e.detail!=null&&e.detail!==0)return;let t=q(f.dataset.baseFilterSuggestion||``),n=f.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,t,n)}},this.handleInput=e=>{let t=e.target.closest(`.bases-search-input`);if(t){let e=t.closest(`[data-base-shell-key]`),n=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!n)return;n.search=t.value||``,clearTimeout(this.searchTimers.get(n.key)),this.searchTimers.set(n.key,setTimeout(()=>{n.payload.search=n.search,this.renderEntry(n)},180));return}let n=e.target.closest(`[data-base-properties-search]`);if(n){let e=n.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.propertySearch=n.value||``,Oc(t,t.result);return}let r=e.target.closest(`[data-base-filter-advanced]`);if(r){let e=r.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.rawFilterText=r.value||``;return}let i=e.target.closest(`[data-base-filter-value]`);if(i){let e=i.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;let n=q(i.dataset.baseFilterValue||``),r=t.ui.builderFilter??Y(K(t.result).filters)??Os(`and`);t.ui.builderFilter=X(r,n,e=>({...e,value:i.value||``})),gc(t,t.result,n)}},this.handleChange=e=>{let t=e.target.closest(`[data-base-shell-key]`),n=t?this.entries.get(t.dataset.baseShellKey||``):null;if(!n)return;let r=e.target.closest(`[data-base-group-by-property]`);if(r){this.updateViewConfig(n,e=>(e.groupBy=r.value?{direction:e.groupBy?.direction??`asc`,property:r.value}:null,e));return}let i=e.target.closest(`[data-base-group-by-direction]`);if(i){this.updateViewConfig(n,e=>(e.groupBy=e.groupBy?.property?{direction:i.value||`asc`,property:e.groupBy.property}:null,e));return}let a=e.target.closest(`[data-base-sort-property]`);if(a){let e=Number.parseInt(a.dataset.baseSortProperty||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,property:a.value}:t),t));return}let o=e.target.closest(`[data-base-sort-direction]`);if(o){let e=Number.parseInt(o.dataset.baseSortDirection||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,direction:o.value||`asc`}:t),t));return}let s=e.target.closest(`[data-base-property-toggle]`);if(s){let e=s.dataset.basePropertyToggle||``;this.updateViewConfig(n,t=>{let r=t.order?.length>0?[...t.order]:Vs(n.result),i=r.indexOf(e);return s.checked&&i===-1&&r.push(e),!s.checked&&i>=0&&r.splice(i,1),t.order=r,t});return}let c=e.target.closest(`[data-base-filter-conjunction]`);if(c){let e=q(c.dataset.baseFilterConjunction||``);this.updateBuilderFilter(n,t=>X(t,e,e=>({...e,conjunction:c.value||`and`})));return}let l=e.target.closest(`[data-base-filter-property]`);if(l){let e=q(l.dataset.baseFilterProperty||``);(async()=>{await this.updateBuilderFilter(n,t=>X(t,e,e=>{let t=Us(n.result,l.value)[0]??`is`;return{...e,operator:t,propertyId:l.value,value:``}})),await this.ensurePropertyValues(n,l.value)})();return}let u=e.target.closest(`[data-base-filter-operator]`);if(u){let e=q(u.dataset.baseFilterOperator||``);this.updateBuilderFilter(n,t=>X(t,e,e=>({...e,operator:u.value||`is`})));return}e.target.closest(`[data-base-filter-value]`)&&this.persistBuilderFilter(n)},this.handleFocusIn=e=>{let t=e.target.closest(`[data-base-filter-value]`);if(!t)return;let n=t.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=q(t.dataset.baseFilterValue||``),a=Y(K(r.result).filters),o=a?oc(a,i):null;o?.propertyId&&this.ensurePropertyValues(r,o.propertyId)},this.previewElement?.addEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.addEventListener(`click`,this.handleClick),this.previewElement?.addEventListener(`input`,this.handleInput),this.previewElement?.addEventListener(`change`,this.handleChange),this.previewElement?.addEventListener(`focusin`,this.handleFocusIn)}ensureEntryState(e){e.ui||={builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``},Object.prototype.hasOwnProperty.call(e.ui,`builderFilter`)||(e.ui.builderFilter=null),e.propertyValueOptions||=new Map}destroy(){this.previewElement?.removeEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.removeEventListener(`click`,this.handleClick),this.previewElement?.removeEventListener(`input`,this.handleInput),this.previewElement?.removeEventListener(`change`,this.handleChange),this.previewElement?.removeEventListener(`focusin`,this.handleFocusIn),this.searchTimers.forEach(e=>clearTimeout(e)),this.searchTimers.clear(),this.entries.clear()}reconcileEmbeds(e=this.previewElement){e&&Array.from(e.querySelectorAll(`.bases-embed-placeholder[data-base-key]`)).forEach(e=>{let t=e.dataset.baseKey||ws(),n=this.entries.get(t),r={path:e.dataset.basePath||``,search:``,source:e.dataset.baseSource||null,sourcePath:e.dataset.baseSourcePath||``,view:e.dataset.baseView||``},i=n??{key:t,payload:r,placeholder:e,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.payload=r,i.placeholder=e,this.entries.set(t,i),this.renderEntry(i)})}async renderStandalone({filePath:e,renderHost:t,source:n=null}){let r=`standalone:${e}`,i=this.entries.get(r)??{key:r,payload:{path:e,search:``,source:n,sourcePath:e,view:``},placeholder:t,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.placeholder=t,i.payload.path=e,i.payload.source=typeof n==`string`?n:null,i.payload.sourcePath=e,this.entries.set(r,i),await this.renderEntry(i)}async renderEntry(e){if(this.ensureEntryState(e),!e?.placeholder?.isConnected)return;let t=(e.requestVersion??0)+1;e.requestVersion=t;let n=!!Tc(e);n||(e.placeholder.innerHTML=`<div class="preview-shell">Loading base…</div>`);try{let n=await this.vaultApiClient.queryBase({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;e.result=n.result,e.ui.builderFilter=Y(K(e.result).filters),e.ui.rawFilterText||(e.ui.rawFilterText=ic(K(e.result).filters)),Dc(e,e.result)}catch(r){if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;if(n){let t=Tc(e)?.querySelector?.(`[data-base-content]`)??null;if(t){t.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`;return}}e.placeholder.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`}}async exportEntry(e){this.ensureEntryState(e);try{let t=await this.vaultApiClient.exportBaseCsv({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});we(t.blob,Ce(t.contentDisposition,`base.csv`),{removeDelayMs:0,revokeDelayMs:0})}catch(e){this.toastController?.show?.(e.message||`Failed to export base CSV`)}}async ensurePropertyValues(e,t=``){if(this.ensureEntryState(e),!t)return;let n=qs(e,t);if((e.propertyValueOptions.get(t)??null)?.cacheKey!==n)try{let r=await this.vaultApiClient.queryBasePropertyValues({activeFilePath:this.getActiveFilePath?.()??``,...e.payload,propertyId:t});if(e.propertyValueOptions.set(t,{cacheKey:n,values:r.result?.values??[]}),e.result&&e.ui.openPanel===`filter`){let n=!1;_c(dc(e,e.result),(r,i)=>{r.propertyId===t&&(n=gc(e,e.result,i,{fallbackToFullRender:!1})||n)}),n||Oc(e,e.result)}}catch{e.propertyValueOptions.set(t,{cacheKey:n,values:[]})}}async applyTransformedSource(e,t){if(this.ensureEntryState(e),Ws(e)){e.payload.source=t.source,this.replaceBaseSource?.({path:e.payload.path,source:t.source});return}await this.vaultApiClient.writeFile({content:t.source,path:e.payload.path}),e.payload.source=null}async updateViewConfig(e,t){if(this.ensureEntryState(e),!e?.result||!G(e.result).editable)return;let n=t(K(e.result));try{let t=(await this.vaultApiClient.transformBase({activeFilePath:this.getActiveFilePath?.()??``,mutation:{config:n,type:`set-view-config`,view:e.result.view.id},...e.payload})).result;await this.applyTransformedSource(e,t),e.result=t.result,e.ui.rawFilterText=ic(K(e.result).filters),Dc(e,e.result)}catch(e){this.toastController?.show?.(e.message||`Failed to update base`)}}async updateBuilderFilter(e,t){this.ensureEntryState(e);let n=t(e.ui.builderFilter??Y(K(e.result).filters)??Os(`and`));e.ui.builderFilter=n,await this.updateViewConfig(e,t=>(t.filters=tc(n,e.result),t))}async saveAdvancedFilter(e){this.ensureEntryState(e);try{let t=ac(e.ui.rawFilterText??``);e.ui.builderFilter=Y(t),await this.updateViewConfig(e,e=>(e.filters=t,e))}catch(e){this.toastController?.show?.(e.message||`Invalid advanced filter`)}}},Ac=`https://viewer.diagrams.net/js/viewer-static.min.js`,jc=null;function Mc(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):jc||(jc=new Promise((e,t)=>{let n=document.querySelector(`script[data-collabmd-drawio-viewer]`),r=n instanceof HTMLScriptElement?n:document.createElement(`script`),i=()=>{r.removeEventListener(`error`,a),r.removeEventListener(`load`,o)},a=()=>{i(),jc=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){jc=null,t(Error(`draw.io viewer did not initialize`));return}e(window.GraphViewer)};r.addEventListener(`error`,a,{once:!0}),r.addEventListener(`load`,o,{once:!0}),n?window.GraphViewer?.processElements&&o():(r.src=Ac,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),jc)}function Nc({ariaLabel:e=``,className:t=`drawio-viewer-frame`,onActivate:n=null,source:r=``,theme:i=`dark`}={}){let a=document.createElement(`div`);return a.className=t,e&&a.setAttribute(`aria-label`,e),typeof n==`function`&&(a.dataset.action=`open-file`,a.setAttribute(`role`,`button`),a.setAttribute(`tabindex`,`0`),a.addEventListener(`click`,e=>{e.preventDefault(),n()}),a.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())})),a.dataset.mxgraph=JSON.stringify({"check-visible-state":!1,center:!0,border:0,"dark-mode":i===`light`?`light`:`dark`,editable:!1,fit:1,lightbox:!1,nav:!1,resize:!1,tooltips:!1,xml:String(r??``)}),a}async function Pc(e,t={}){let n=await Mc(),r=Nc(t);return e.replaceChildren(r),typeof n.createViewerForElement==`function`?n.createViewerForElement(r):n.processElements(),r}var Fc=360,Ic=class{constructor({getLocalUser:e,getTheme:t,onOpenFile:n=null,onOpenTextFile:r=null,onToggleQuickSwitcher:i=null,previewContainer:a,previewElement:o,toastController:s,vaultApiClient:c}){this.getLocalUser=e,this.getTheme=t,this.onOpenFile=n,this.onOpenTextFile=r,this.onToggleQuickSwitcher=i,this.previewContainer=a,this.previewElement=o,this.toastController=s,this.vaultApiClient=c,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.instanceCounter=0,this.maximizedEntry=null,this.overlayRoot=null,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),L(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),document.body.classList.remove(`drawio-maximized-open`),this.embedEntries.forEach(e=>e.wrapper?.remove()),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){L(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){this.hydrationPaused=!!e,this.hydrationPaused||this.hydrateVisibleEmbeds()}reconcileEmbeds(e){this._exitMaximizedEntry();let t=Array.from(e.querySelectorAll(`.drawio-embed-placeholder[data-drawio-key]`)).map(e=>({filePath:e.dataset.drawioTarget||``,key:e.dataset.drawioKey||``,label:e.dataset.drawioLabel||e.dataset.drawioTarget||``,mode:e.dataset.drawioMode===`edit`?`edit`:`view`,placeholder:e})),n=new Map;t.forEach(e=>{let t=this.embedEntries.get(e.key)||null,r=t&&this.entryMatchesDescriptor(t,e)?t:this.createEntry(e);t&&t!==r&&this.destroyEntry(t),r.filePath=e.filePath,r.key=e.key,r.label=e.label,r.mode=e.mode,r.placeholder=e.placeholder,n.set(e.key,r)}),this.embedEntries.forEach((e,t)=>{n.has(t)||this.destroyEntry(e)}),this.embedEntries=n,this.embedEntries.forEach(e=>{e.wrapper?this.attachWrapper(e):e.queued=!1}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}createEntry(e){return{...e,iframe:null,imageElement:null,inlineHeightPx:null,instanceId:``,queued:!1,viewerElement:null,wrapper:null}}entryMatchesDescriptor(e,t){return!!(e&&e.filePath===t.filePath&&e.mode===t.mode)}hydrateVisibleEmbeds(){this.embedEntries.forEach(e=>{e.wrapper||!e.placeholder?.isConnected||(e.mode===`edit`||Ee(e.placeholder,this.previewContainer,Fc))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Te(()=>{this.hydrationIdleId=null,this.hydrationQueue.splice(0).forEach(e=>{e.queued=!1,this.hydrateEntry(e)})},200)))}hydrateEntry(e){if(!(!e.placeholder?.isConnected||e.wrapper)){if(e.mode===`view`){this.hydrateViewerEntry(e);return}this.hydrateIframeEntry(e)}}hydrateIframeEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell${e.mode===`edit`?` is-direct-file`:``}`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),e.mode!==`edit`&&n.appendChild(this.createOpenButton(e)),n.appendChild(this.createMaximizeButton(e,t));let a=document.createElement(`iframe`);a.className=`drawio-embed-iframe`,a.loading=`lazy`,a.referrerPolicy=`strict-origin-when-cross-origin`,e.instanceId=`drawio-${++this.instanceCounter}`,a.dataset.instanceId=e.instanceId,a.src=this.buildIframeUrl(e),t.append(n,a),e.iframe=a,e.wrapper=t,this.attachWrapper(e)}async hydrateViewerEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell is-static-preview`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),n.append(this.createOpenButton(e),this.createMaximizeButton(e,t));let a=document.createElement(`div`);a.className=`drawio-viewer-shell`,a.dataset.filePath=e.filePath;let o=document.createElement(`div`);o.className=`preview-shell`,o.textContent=`Rendering draw.io preview…`,a.appendChild(o),t.append(n,a),e.iframe=null,e.wrapper=t,e.viewerElement=a,this.attachWrapper(e);try{await this.renderViewerEntry(e),this.syncEntryLayout(e)}catch(t){this.renderViewerFallback(e,t instanceof Error?t.message:`Failed to render draw.io preview`),this.syncEntryLayout(e)}}async renderViewerEntry(e){let{content:t}=await this.vaultApiClient.readFile(e.filePath);if(!e.wrapper?.isConnected||!e.viewerElement?.isConnected)return;let n=this.getTheme?.()===`light`?`light`:`dark`;e.viewerElement=await Pc(e.wrapper.querySelector(`.drawio-viewer-shell`)??e.viewerElement,{ariaLabel:`Open ${e.label.replace(/\.drawio$/i,``)}`,className:`mxgraph drawio-viewer-frame`,onActivate:()=>this.onOpenFile?.(e.filePath),source:String(t??``),theme:n})}buildIframeUrl(e){let t=new URL(se(`/drawio-editor.html`)),n=this.getLocalUser?.()??{};return t.searchParams.set(`file`,e.filePath),t.searchParams.set(`hostMode`,e.mode===`edit`?`file-preview`:`embed`),t.searchParams.set(`instanceId`,e.instanceId),t.searchParams.set(`mode`,e.mode===`edit`?`edit`:`view`),t.searchParams.set(`theme`,this.getTheme?.()===`light`?`light`:`dark`),n.name&&t.searchParams.set(`userName`,n.name),n.peerId&&t.searchParams.set(`peerId`,n.peerId),e.mode===`edit`&&t.searchParams.set(`leaseRoom`,xe(e.filePath)),t.toString()}updateTheme(e){this.embedEntries.forEach(t=>{t.iframe?.contentWindow&&t.iframe.contentWindow.postMessage({source:`collabmd-host`,theme:e,type:`set-theme`},window.location.origin),t.mode===`view`&&t.wrapper?.isConnected&&t.viewerElement?.isConnected&&this.renderViewerEntry(t).catch(e=>{this.renderViewerFallback(t,e instanceof Error?e.message:`Failed to render draw.io preview`)})})}updateLocalUser(){}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this.shouldInlineEntry(e)&&this.syncEntryLayout(e)})}attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.findPlaceholder(e);if(!t)return;if(e.placeholder=t,this.syncMountedEntryMetadata(e),this.shouldInlineEntry(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this.ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this.syncEntryLayout(e)}destroyEntry(e){this.maximizedEntry?.key===e?.key&&this._exitMaximizedEntry(),this.resetPlaceholderLayout(e),e?.wrapper?.remove(),e&&(e.placeholder=null,e.wrapper=null,e.iframe=null,e.viewerElement=null)}findPlaceholder(e){return this.previewElement?.querySelector?.(`.drawio-embed-placeholder[data-drawio-key="${e.key}"]`)??null}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector?.(`[data-drawio-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.drawioOverlayRoot=`true`,e.className=`drawio-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}shouldInlineEntry(e){return e?.key===`${e?.filePath}#file-preview`}syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.drawioKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this.shouldInlineEntry(e))),e.iframe&&(e.iframe.title=`draw.io: ${e.filePath}`)}resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this.shouldInlineEntry(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-drawio-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}syncEntryLayout(e){if(!e?.wrapper||this.shouldInlineEntry(e))return;let t=e.placeholder?.isConnected?e.placeholder:this.findPlaceholder(e);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.drawioHydrated=`true`,t.style.pointerEvents=`none`;let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.offsetHeight||Math.ceil(e.wrapper.getBoundingClientRect?.().height||0)||e.inlineHeightPx||420;if(n||(e.inlineHeightPx=r),t.style.height=`${Math.ceil(e.inlineHeightPx||r)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=``;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.margin=`0`}createOpenButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,t.dataset.action=`open-file`,t.dataset.filePath=e.filePath,t.title=`Edit in draw.io`,t.setAttribute(`aria-label`,`Edit in draw.io`),z(t,`edit`),t.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),t}createMaximizeButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,n.dataset.action=`toggle-maximize`,n.dataset.filePath=e.filePath,n.dataset.drawioKey=e.key,n.addEventListener(`click`,n=>{n.preventDefault(),this.maximizedEntry?.key===e.key?this._exitMaximizedEntry():this._enterMaximizedEntry(e,t),this._syncMaximizeButtons()}),(()=>{let t=this.maximizedEntry?.key===e.key;z(n,t?`restore`:`maximize`),n.title=t?`Restore diagram size`:`Maximize diagram`,n.setAttribute(`aria-label`,t?`Restore diagram size`:`Maximize diagram`)})(),n}_enterMaximizedEntry(e,t=e?.wrapper){if(!(!e?.wrapper||e.wrapper!==t)&&this.maximizedEntry?.key!==e.key){if(this._exitMaximizedEntry(),e.wrapper.parentElement){let t=document.createElement(`div`);t.className=`drawio-maximize-spacer`,t.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=t,e.wrapper.parentElement.insertBefore(t,e.wrapper)}e.wrapper.classList.add(`is-maximized`),e.wrapper.dataset.drawioMaximized=`true`,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,document.body.classList.add(`drawio-maximized-open`),this.maximizedEntry=e,this.overlayRoot?.classList.add(`has-maximized-entry`),this.syncEntryLayout(e)}}_exitMaximizedEntry(){let e=this.maximizedEntry;if(!e?.wrapper){this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`);return}let{maximizeSpacer:t}=e;e.wrapper.classList.remove(`is-maximized`),delete e.wrapper.dataset.drawioMaximized,e.wrapper.style.width=``,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,t?.parentElement&&t.remove(),e.maximizeSpacer=null,e.restoreParent=null,e.restoreNextSibling=null,this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`),this.overlayRoot?.classList.remove(`has-maximized-entry`),this.syncEntryLayout(e)}_syncMaximizeButtons(){this.embedEntries.forEach(e=>{let t=e.wrapper?.querySelector(`.drawio-embed-btn[data-action="toggle-maximize"]`);if(!(t instanceof HTMLElement))return;let n=this.maximizedEntry?.key===e.key;z(t,n?`restore`:`maximize`),t.title=n?`Restore diagram size`:`Maximize diagram`,t.setAttribute(`aria-label`,n?`Restore diagram size`:`Maximize diagram`)})}_findEntryByInstanceId(e){for(let t of this.embedEntries.values())if(t.instanceId===e)return t;return null}_isMessageFromEntry(e,t){return!!(t?.iframe?.contentWindow&&e.source===t.iframe.contentWindow)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`drawio-editor`)return;let n=this._findEntryByInstanceId(t.instanceId);if(n&&this._isMessageFromEntry(e,n)){if(t.type===`fallback-text`){if(n.mode===`view`){this.renderViewerFallback(n,`Failed to render draw.io preview`);return}this.onOpenTextFile?.(n.filePath);return}if(t.type===`error`){if(n.mode===`view`){this.renderViewerFallback(n,t.message||`Failed to load draw.io preview`);return}this.toastController?.show?.(t.message||`Failed to load draw.io`);return}if(t.type===`request-open-file`){this.onOpenFile?.(n.filePath);return}t.type===`request-toggle-quick-switcher`&&this.onToggleQuickSwitcher?.()}}_onPreviewClick(e){let t=e.target.closest(`.drawio-embed-placeholder-btn`);if(t){let n=t.closest(`.drawio-embed-placeholder`)?.dataset.drawioKey||``,r=this.embedEntries.get(n);r&&(e.preventDefault(),this.hydrateEntry(r));return}}_onKeyDown(e){e.key===`Escape`&&(this._exitMaximizedEntry(),this._syncMaximizeButtons())}renderViewerFallback(e,t){if(!e.wrapper)return;let n=e.wrapper.querySelector(`.drawio-viewer-shell, .drawio-viewer-frame`);if(!n)return;let r=document.createElement(`div`);r.className=`preview-shell`,r.textContent=t,n.replaceChildren(r),e.viewerElement=r}};function Lc(e,t){let n=new Map;t.forEach(t=>{let r=e.get(t.key)??{filePath:t.filePath,iframe:null,instanceId:null,key:t.key,label:t.label,placeholder:t.placeholder,queued:!1,wrapper:null};r.filePath=t.filePath,r.key=t.key,r.label=t.label,r.placeholder=t.placeholder,n.set(t.key,r)});let r=[];return e.forEach((e,t)=>{n.has(t)||r.push(e)}),{nextEntries:n,removedEntries:r}}var Rc=420,zc=500,Bc=15e3,Vc=800,Hc=3,Uc=200,Wc=`/excalidraw-editor.html`;function Gc(e,t){let n=e?.querySelectorAll?.(`.excalidraw-embed-placeholder[data-embed-key]`);return Array.from(n||[]).find(e=>e.dataset?.embedKey===t)||null}var Kc=class{constructor({getTheme:e,getLocalUser:t,onOpenFile:n=null,onToggleQuickSwitcher:r=null,previewContainer:i,previewElement:a,toastController:o}){this.getTheme=e,this.getLocalUser=t,this.onOpenFile=n,this.onToggleQuickSwitcher=r,this.previewContainer=i,this.previewElement=a,this.toastController=o,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.hydrationInProgress=!1,this.instanceCounter=0,this.isLargeDocument=!1,this.maximizedEmbed=null,this.overlayRoot=null,this.warmCacheRoot=null,this.warmEntry=null,this.placeholderObserver=null,this.followedPeerIdsByFilePath=new Map,this.pendingDisconnectRequests=new Map,this.disconnectRequestCounter=0,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),this._disconnectPlaceholderObserver(),L(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEmbed(),document.body.classList.remove(`excalidraw-maximized-open`),this.embedEntries.forEach(e=>{this._clearEntryBootTimeout(e),e.resizerCleanup?.(),e.resizerCleanup=null,e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.warmEntry&&=(this._clearEntryBootTimeout(this.warmEntry),this.warmEntry.resizerCleanup?.(),this.warmEntry.resizerCleanup=null,this.warmEntry.wrapper?.remove(),null),this.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.warmCacheRoot?.remove(),this.warmCacheRoot=null}async setFollowedUser(e,t=null){if(!e)return!1;this.followedPeerIdsByFilePath.set(e,t||null);let n=this._findEntryByFilePath(e);return!n||(n.wrapper||await this._hydrateEntry(n),n.followedPeerId=this.followedPeerIdsByFilePath.get(e)??null,this._syncEntryFollowState(n),!0)}detachForCommit(){this._disconnectPlaceholderObserver(),L(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1,this._exitMaximizedEmbed(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){L(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),L(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1;let n=Array.from(e.querySelectorAll(`.excalidraw-embed-placeholder[data-embed-key]`)).map(e=>({filePath:e.dataset.embedTarget,key:e.dataset.embedKey,label:e.dataset.embedLabel||e.dataset.embedTarget,placeholder:e})),{nextEntries:r,removedEntries:i}=Lc(this.embedEntries,n);this._captureWarmEntry(i),this._adoptReusableEntries(r,i),i.forEach(e=>this._destroyEntry(e)),this.embedEntries=r,this._ensurePlaceholderObserver(),this.embedEntries.forEach(e=>{if(e.queued=!1,e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),e.wrapper){this._hydrateEntry(e);return}e.placeholder&&this.placeholderObserver?.observe(e.placeholder)}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}hydrateVisibleEmbeds(){if(this.hydrationPaused)return;let e=this.isLargeDocument?180:420;this.embedEntries.forEach(t=>{t.wrapper||!t.placeholder?.isConnected||Ee(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this._forEachManagedEntry(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this._forEachManagedEntry(t=>{this._syncEntryUser(t,e)})}openCommentThread(e,t){if(!e||!t)return!1;let n=this._findEntryByFilePath(e);return n?(n.pendingCommentThreadId=t,n.isReady?this._postPendingCommentThread(n):n.wrapper||this._enqueueHydration(n,{prioritize:!0}),!0):!1}prepareFileDisconnect(e,{timeoutMs:t=1e4}={}){let n=this._findEntryByFilePath(e);if(!n?.iframe?.contentWindow)return Promise.resolve(!0);let r=`disconnect-${++this.disconnectRequestCounter}`;return new Promise(e=>{let i=t=>{if(!this.pendingDisconnectRequests.has(r))return;let n=this.pendingDisconnectRequests.get(r);window.clearTimeout(n.timeoutId),this.pendingDisconnectRequests.delete(r),e(t)},a=window.setTimeout(()=>{if(!window.confirm(`This diagram has not reconnected, so its latest queued changes may not be saved. Discard pending changes and leave?`)){this._postMessageToEntry(n,{source:`collabmd-host`,type:`cancel-disconnect`,requestId:r}),this.toastController?.show?.(`Stayed on the diagram while it reconnects`),i(!1);return}this._postMessageToEntry(n,{source:`collabmd-host`,type:`discard-and-disconnect`,requestId:r});let e=this.pendingDisconnectRequests.get(r);e&&(e.timeoutId=window.setTimeout(()=>i(!0),1e3))},t);this.pendingDisconnectRequests.set(r,{entry:n,resolve:i,timeoutId:a}),this._postMessageToEntry(n,{source:`collabmd-host`,type:`prepare-disconnect`,requestId:r})})}_ensurePlaceholderObserver(){this.previewContainer&&(this.placeholderObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(!e.isIntersecting)return;let t=this.embedEntries.get(e.target.dataset.embedKey);t&&this._enqueueHydration(t)})},{root:this.previewContainer,rootMargin:this.isLargeDocument?`180px 0px`:`420px 0px`}))}_disconnectPlaceholderObserver(){this.placeholderObserver&&=(this.placeholderObserver.disconnect(),null)}_enqueueHydration(e,{prioritize:t=!1}={}){if(!(!e||e.wrapper||e.queued)&&(e.queued=!0,t?this.hydrationQueue.unshift(e.key):this.hydrationQueue.push(e.key),!this.hydrationPaused)){if(t&&!this.hydrationInProgress&&this.hydrationIdleId===null){this._flushHydrationQueue();return}this._scheduleHydration()}}_scheduleHydration(){this.hydrationPaused||this.hydrationInProgress||this.hydrationIdleId!==null||(this.hydrationIdleId=Te(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},zc))}async _flushHydrationQueue(){if(this.hydrationPaused||this.hydrationInProgress)return;let e=null;for(;this.hydrationQueue.length>0&&!e;){let t=this.hydrationQueue.shift(),n=this.embedEntries.get(t);if(!n||n.wrapper||!n.placeholder?.isConnected){n&&(n.queued=!1);continue}e=n}e&&(this.hydrationInProgress=!0,e.queued=!1,await this._hydrateEntry(e),this.hydrationInProgress=!1,this.hydrationQueue.length>0&&this._scheduleHydration())}async _hydrateEntry(e){if(!(!e.placeholder?.isConnected&&!e.wrapper)){if(e.isParked=!1,!e.wrapper){let t=this._createEmbedContainer(e);e.header=t.header,e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.maxButton=t.maxButton,e.openButton=t.openButton,e.instanceId=t.instanceId,e.resizerCleanup=t.resizerCleanup,e.isReady=!1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=e.bootFilePath,e.loadedMode=e.bootMode,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(e),this._entryNeedsHardReload(e)&&this._reloadEntry(e),this._attachWrapper(e)}}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:Gc(this.previewElement,e.key);if(!t)return;if(e.placeholder=t,this._syncMountedEntryMetadata(e),this._shouldInlineFilePreview(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this._ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this._syncEntryLayout(e)}_adoptReusableEntries(e,t){e.forEach((n,r)=>{if(n.wrapper||n.iframe)return;let i=this._claimReusableEntry(n,t);i&&(i.filePath=n.filePath,i.key=n.key,i.label=n.label,i.placeholder=n.placeholder,i.queued=!1,e.set(r,i))})}_destroyEntry(e){this.pendingDisconnectRequests.forEach((t,n)=>{t.entry===e&&(t.resolve(!1),this.pendingDisconnectRequests.delete(n))}),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),this._clearEntryBootTimeout(e),e.resizerCleanup?.(),e.resizerCleanup=null,this.warmEntry===e&&(this.warmEntry=null),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e,t=Bc){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},t)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Hc){this._clearEntryBootTimeout(e),this.toastController?.show(`Excalidraw embed timed out: ${e.label}`);return}await this._retryEntryBootstrap(e)}}async _retryEntryBootstrap(e){e&&(this._clearEntryBootTimeout(e),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.header=null,e.labelElement=null,e.maxButton=null,e.openButton=null,e.instanceId=null,e.isReady=!1,e.isParked=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,await this._hydrateEntry(e))}_findEntryByContentWindow(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.iframe?.contentWindow===e)return t;return this.warmEntry?.iframe?.contentWindow===e?this.warmEntry:null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return this.warmEntry?.filePath===e?this.warmEntry:null}_updateEmbedLabel(e){e.labelElement&&(e.labelElement.textContent=e.label.replace(/\.excalidraw$/i,``))}_syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.embedKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this._isFilePreviewEntry(e))),e.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`),e.openButton&&(this._isFilePreviewEntry(e)?e.openButton.remove():!e.openButton.isConnected&&e.header&&e.header.insertBefore(e.openButton,e.maxButton||null))}_buildIframeUrl(e){let t=new URL(se(Wc)),n=this.getTheme?.()||`dark`;t.searchParams.set(`file`,e.filePath),t.searchParams.set(`theme`,n),t.searchParams.set(`boot`,e.instanceId||``),this._isFilePreviewEntry(e)||t.searchParams.set(`mode`,`preview`);let r=this.getLocalUser?.();r?.name&&t.searchParams.set(`userName`,r.name),r?.color&&t.searchParams.set(`userColor`,r.color),r?.colorLight&&t.searchParams.set(`userColorLight`,r.colorLight),r?.peerId&&t.searchParams.set(`userPeerId`,r.peerId);let i=new URLSearchParams(window.location.search),a=pe();return a&&t.searchParams.set(`server`,a),i.get(`test`)===`1`&&t.searchParams.set(`test`,`1`),i.has(`syncTimeoutMs`)&&t.searchParams.set(`syncTimeoutMs`,i.get(`syncTimeoutMs`)),i.get(`excalidrawDebug`)===`1`&&t.searchParams.set(`excalidrawDebug`,`1`),t}_createEmbedContainer(e){let t=document.createElement(`div`);t.className=`excalidraw-embed diagram-preview-shell`,t.dataset.embedKey=e.key,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`excalidraw-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`excalidraw-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;let i=document.createElement(`span`);i.className=`excalidraw-embed-label`,i.textContent=e.label.replace(/\.excalidraw$/i,``);let a=document.createElement(`button`);a.type=`button`,a.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,a.title=`Edit in Excalidraw`,a.setAttribute(`aria-label`,`Edit in Excalidraw`),z(a,`edit`);let o=document.createElement(`button`);o.type=`button`,o.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,o.title=`Maximize diagram`,o.setAttribute(`aria-label`,`Maximize diagram`),z(o,`maximize`),n.append(r,i),this._isFilePreviewEntry(e)||n.append(a),n.append(o);let s=document.createElement(`iframe`);s.className=`excalidraw-embed-iframe`,s.dataset.instanceId=String(++this.instanceCounter),e.instanceId=s.dataset.instanceId,s.src=this._buildIframeUrl(e).toString(),s.setAttribute(`loading`,`eager`),s.title=`Excalidraw: ${e.filePath}`,s.style.height=`${Rc}px`;let c=document.createElement(`div`);c.className=`excalidraw-embed-resizer`,c.title=`Drag to resize`;let l=this._setupResizer(c,s,()=>{this._syncEntryLayout(e),this._requestPreviewViewportFit(e)});t.append(n,s,c);let u=!1,d=`${Rc}px`,f=()=>{z(o,u?`restore`:`maximize`),o.title=u?`Restore diagram size`:`Maximize diagram`,o.setAttribute(`aria-label`,u?`Restore diagram size`:`Maximize diagram`)},p=()=>{u&&(u=!1,t.classList.remove(`is-maximized`),f(),document.body.classList.remove(`excalidraw-maximized-open`),this._restoreMaximizedEntryLayout(e),s.style.height=d,this.maximizedEmbed?.wrapper===t&&(this.maximizedEmbed=null),this._syncEntryLayout(e),this._requestPreviewViewportFit(e))},m=()=>{u||(this._exitMaximizedEmbed(),u=!0,d=s.style.height||`${Rc}px`,this._enterMaximizedEntryLayout(e),t.classList.add(`is-maximized`),f(),document.body.classList.add(`excalidraw-maximized-open`),this.maximizedEmbed={wrapper:t,exit:p},this._syncEntryLayout(e),this._requestPreviewViewportFit(e))};return o.addEventListener(`click`,()=>{u?p():m()}),a.addEventListener(`click`,t=>{t.preventDefault(),this._exitMaximizedEmbed(),this.onOpenFile?.(e.filePath)}),f(),{header:n,iframe:s,instanceId:s.dataset.instanceId,labelElement:i,maxButton:o,openButton:a,resizerCleanup:l,wrapper:t}}_ensureWarmCacheRoot(){if(this.warmCacheRoot?.isConnected&&this.warmCacheRoot.parentElement===document.body)return this.warmCacheRoot;let e=document.body.querySelector(`[data-excalidraw-warm-cache-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawWarmCacheRoot=`true`,e.className=`excalidraw-warm-cache-root`,document.body.appendChild(e)),this.warmCacheRoot=e,e}_setupResizer(e,t,n=null){let r=0,i=0,a=!1,o=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Uc),Vc);t.style.height=`${a}px`,t.style.pointerEvents=`none`},s=()=>{a&&(a=!1,t.style.pointerEvents=``,document.removeEventListener(`pointermove`,o),document.removeEventListener(`pointerup`,c))},c=()=>{s(),n?.()},l=e=>{e.preventDefault(),a=!0,r=e.clientY,i=t.offsetHeight,document.addEventListener(`pointermove`,o),document.addEventListener(`pointerup`,c)};return e.addEventListener(`pointerdown`,l),()=>{e.removeEventListener?.(`pointerdown`,l),s()}}_ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector(`[data-excalidraw-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawOverlayRoot=`true`,e.className=`excalidraw-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_isFilePreviewEntry(e){return e?.key===`${e?.filePath}#file-preview`}_getEntryMode(e){return this._isFilePreviewEntry(e)?`edit`:`preview`}_shouldInlineFilePreview(e){return this._isFilePreviewEntry(e)}_entryNeedsHardReload(e){let t=this._getEntryMode(e);return!!(e?.wrapper&&e.iframe&&(e.isReady?e.loadedFilePath!==e.filePath||e.loadedMode!==t:e.bootFilePath!==e.filePath||e.bootMode!==t))}_setEntryLoadingState(e,t){e?.wrapper&&(e.wrapper.classList.toggle(`is-loading`,!!t),e.wrapper.setAttribute(`aria-busy`,t?`true`:`false`))}_forEachManagedEntry(e){let t=new Set;this.embedEntries.forEach(n=>{!n||t.has(n)||(t.add(n),e(n))}),this.warmEntry&&!t.has(this.warmEntry)&&e(this.warmEntry)}_claimEntryFromRemovedEntries(e,t){let n=e.findIndex(e=>(e.wrapper||e.iframe)&&t(e));if(n<0)return null;let[r]=e.splice(n,1);return r}_claimReusableEntry(e,t){let n=this._getEntryMode(e);return this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath&&this._getEntryMode(t)===n)||(this._isFilePreviewEntry(e)?this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath)||this._claimWarmEntry()||this._claimEntryFromRemovedEntries(t,e=>this._isFilePreviewEntry(e)):null)}_claimWarmEntry(){let e=this.warmEntry;return e?(this.warmEntry=null,e):null}_captureWarmEntry(e){let t=this._claimEntryFromRemovedEntries(e,e=>this._isFilePreviewEntry(e));t&&(this.warmEntry&&this.warmEntry!==t&&this._destroyEntry(this.warmEntry),this.warmEntry=t,this._parkWarmEntry(t))}_parkWarmEntry(e){if(!e?.wrapper)return;this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed();let t=this._ensureWarmCacheRoot();this._setEntryLoadingState(e,!1),e.isParked=!0,e.isReady=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,e.placeholder=null,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper),this._postMessageToEntry(e,{source:`collabmd-host`,type:`park-room`})}_reloadEntry(e){e?.iframe&&(this._clearEntryBootTimeout(e),this._setEntryLoadingState(e,!0),e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=null,e.loadedMode=null,e.iframe.src=this._buildIframeUrl(e).toString(),this._armEntryBootTimeout(e))}_resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this._shouldInlineFilePreview(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-embed-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}_enterMaximizedEntryLayout(e){if(e?.wrapper){if(this._shouldInlineFilePreview(e)&&e.wrapper.parentElement&&!e.maximizeSpacer){let t=document.createElement(`div`);t.className=`excalidraw-maximize-spacer`,t.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=t,e.wrapper.parentElement.insertBefore(t,e.wrapper)}e.wrapper.dataset.excalidrawMaximized=`true`,e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=`0`,this.overlayRoot?.classList.add(`has-maximized-entry`)}}_restoreMaximizedEntryLayout(e){if(!e?.wrapper)return;let{maximizeSpacer:t}=e;delete e.wrapper.dataset.excalidrawMaximized,e.wrapper.style.width=``,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,t?.parentElement&&t.remove(),e.maximizeSpacer=null,this.overlayRoot?.classList.remove(`has-maximized-entry`)}_syncEntryLayout(e){if(!e?.wrapper||this._shouldInlineFilePreview(e))return;let t=e.placeholder?.isConnected?e.placeholder:Gc(this.previewElement,e.key);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.embedHydrated=`true`,t.style.pointerEvents=`none`,this._isFilePreviewEntry(e)&&t.childElementCount>0&&t.replaceChildren();let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.querySelector(`.excalidraw-embed-header`)?.offsetHeight||0,i=e.iframe?.offsetHeight||Number.parseFloat(e.iframe?.style.height||``)||Rc,a=n?0:e.wrapper.querySelector(`.excalidraw-embed-resizer`)?.offsetHeight||0,o=Math.ceil(r+i+a);if(n||(e.inlineHeightPx=o),t.style.height=`${Math.ceil(e.inlineHeightPx||o||Rc)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=`0`;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,e.wrapper.style.margin=`0`}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this._shouldInlineFilePreview(e)&&this._syncEntryLayout(e)})}_onPreviewClick(e){let t=e.target.closest(`.excalidraw-embed-placeholder-btn`);if(!t)return;e.preventDefault();let n=this.embedEntries.get(t.dataset.embedKey);n&&this._hydrateEntry(n)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`excalidraw-editor`)return;let n=this._findEntryByContentWindow(e.source);if(n){if(t.type===`ready`){if(n.isParked)return;n.isReady=!0,this._clearEntryBootTimeout(n),n.loadedFilePath=n.bootFilePath||n.filePath,n.loadedMode=n.bootMode||this._getEntryMode(n),this._setEntryLoadingState(n,!1),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n),this._postPendingCommentThread?.(n),this._entryNeedsHardReload(n)&&this._hydrateEntry(n);return}if(t.type===`request-toggle-quick-switcher`){this.onToggleQuickSwitcher?.();return}if(t.type===`error`){if(n.isParked)return;n.isReady=!1,this._handleEntryBootTimeout(n);return}if(t.type===`disconnect-ready`){let e=this.pendingDisconnectRequests.get(t.requestId);e?.entry===n&&e.resolve(!0);return}if(t.type===`disconnect-blocked`){n.authorityState=t.state||`reconnecting-readonly`,this.toastController?.show?.(`Waiting for the diagram to reconnect before leaving`);return}if(t.type===`excalidraw-authority-state`){n.authorityState=t.state||`closed`,n.hasPendingWrites=!!t.hasPendingWrites;return}t.type===`park-blocked`&&(n.authorityState=t.state||`reconnecting-readonly`)}}_onKeyDown(e){e.key===`Escape`&&this._exitMaximizedEmbed()}_exitMaximizedEmbed(){this.maximizedEmbed?.exit&&this.maximizedEmbed.exit(),this.maximizedEmbed=null,document.body.classList.remove(`excalidraw-maximized-open`)}_postMessageToEntry(e,t){e?.iframe?.contentWindow?.postMessage(t,window.location.origin)}_postPendingCommentThread(e){!e?.isReady||!e.pendingCommentThreadId||(this._postMessageToEntry(e,{source:`collabmd-host`,threadId:e.pendingCommentThreadId,type:`open-comment-thread`}),e.pendingCommentThreadId=null)}_requestPreviewViewportFit(e){this._isFilePreviewEntry(e)||this._postMessageToEntry(e,{source:`collabmd-host`,type:`fit-preview-viewport`})}_syncEntryUser(e,t=null){let n=t||this.getLocalUser?.();n&&this._postMessageToEntry(e,{source:`collabmd-host`,type:`set-user`,user:{color:n.color||``,colorLight:n.colorLight||``,name:n.name||``,peerId:n.peerId||``}})}_syncEntryFollowState(e){!e?.isReady||e.followedPeerId===void 0||this._postMessageToEntry(e,{source:`collabmd-host`,type:`follow-user`,peerId:e.followedPeerId})}},qc=Object.freeze({".gif":`GIF`,".jpeg":`JPEG`,".jpg":`JPEG`,".png":`PNG`,".svg":`SVG`,".webp":`WebP`});function Jc(e=null){return e?.fileKind||m(e?.path)||null}function Yc(e=``){let t=String(e??``).toLowerCase(),n=Object.keys(qc).find(e=>t.endsWith(e));return n?qc[n]:`Image`}function Z(e=``){try{let t=JSON.parse(String(e??``));return!t||typeof t!=`object`||!Array.isArray(t.elements)?null:t}catch{return null}}function Xc(e=[]){if(e.length===0)return null;let t=e.join(`
|
|
435
|
-
`);return Z(t)?t:e.find(e=>Z(e))??null}function Zc(e={}){let t=[],n=[];for(let r of e.hunks??[])for(let e of r.lines??[])e.type===`context`?(t.push(e.content),n.push(e.content)):e.type===`deletion`?t.push(e.content):e.type===`addition`&&n.push(e.content);let r=Xc(t),i=Xc(n),a=e.status===`added`||e.status===`untracked`,o=e.status===`deleted`;return{after:o?null:Z(i),before:a?null:Z(r),afterSource:o?``:i||``,beforeSource:a?``:r||``}}function Qc(e=null){return Array.isArray(e?.elements)?e.elements.filter(e=>e&&!e.isDeleted):[]}function $c(e){if(!e||typeof e!=`object`)return``;let t={...e};return delete t.version,delete t.versionNonce,JSON.stringify(t)}function el(e,t){if(!e&&!t)return null;let n=new Map(Qc(e).map(e=>[e.id,e])),r=new Map(Qc(t).map(e=>[e.id,e])),i=0,a=0,o=0;for(let[e,t]of r)n.has(e)?$c(n.get(e))!==$c(t)&&(o+=1):i+=1;for(let e of n.keys())r.has(e)||(a+=1);return{added:i,afterCount:r.size,beforeCount:n.size,removed:a,updated:o}}function tl(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(+(t<10240))} KB`:`${(t/1048576).toFixed(1)} MB`}function nl(e){return/<(?:mxfile|mxGraphModel|diagram)\b/iu.test(String(e??``))}function rl(e){return String(e??``).replace(/>\s*</gu,`>
|
|
436
|
-
<`).trim()}function il(e=[]){if(e.length===0)return``;let t=e.join(`
|
|
437
|
-
`);return nl(t)?t:e.find(e=>nl(e))??``}function al(e={}){let t=[],n=[];for(let r of e.hunks??[])for(let e of r.lines??[])e.type===`context`?(t.push(e.content),n.push(e.content)):e.type===`deletion`?t.push(e.content):e.type===`addition`&&n.push(e.content);let r=typeof e.drawioBeforeSource==`string`?e.drawioBeforeSource:il(t),i=typeof e.drawioAfterSource==`string`?e.drawioAfterSource:il(n),a=e.status===`added`||e.status===`untracked`;return{after:e.status===`deleted`?``:i,before:a?``:r}}function ol(e){return String(e??``).replace(/"/gu,`"`).replace(/'/gu,`'`).replace(/&/gu,`&`).replace(/</gu,`<`).replace(/>/gu,`>`)}function sl(e){let t=new Map,n=/<mxCell\b([^>]*?)(?:\/|>([\s\S]*?)<\/mxCell\s*)>/giu,r;for(;(r=n.exec(String(e??``)))!==null;){let e=ol(r[1].match(/\bid\s*=\s*(['"])(.*?)\1/iu)?.[2]||``);if(!e||e===`0`||e===`1`)continue;let n=`${r[1]}${r[2]||``}`.replace(/\s+/gu,` `).trim();t.set(e,n)}return t}function cl(e){return/<mxGraphModel\b/iu.test(String(e??``))&&sl(e).size===0}function ll(e,t){if(!e&&!t)return null;let n=sl(e),r=sl(t),i=n.size>0||r.size>0,a=0,o=0,s=0;if(i){for(let[e,t]of r)n.has(e)?n.get(e)!==t&&(s+=1):a+=1;for(let e of n.keys())r.has(e)||(o+=1);e!==t&&a===0&&o===0&&s===0&&(s=1)}else{let n=!!e,r=!!t;a=!n&&r?1:0,o=n&&!r?1:0,s=n&&r&&e!==t?1:0}return{added:a,afterCount:r.size,beforeCount:n.size,cellBased:i,removed:o,updated:s}}function ul(e){return`diff-section-${encodeURIComponent(String(e??``)).replace(/%/g,`_`)}`}function dl(e){switch(e){case`added`:case`untracked`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;default:return`ui-status-badge--warning`}}function fl(e=!1){return`<svg class="diff-section-chevron${e?` collapsed`:``}" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function pl(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ml(e,t,n){let r=0,i=Math.min(e.length,t.length)-n;for(;r<i;){let n=e.length-1-r,i=t.length-1-r;if(e[n]!==t[i])break;r+=1}return r}function hl(e,t){let n=pl(e,t),r=ml(e,t,n),i=Math.max(n,e.length-r),a=Math.max(n,t.length-r);return{leftHtml:`${b(e.slice(0,n))}${i>n?`<span class="diff-highlight-del">${b(e.slice(n,i))}</span>`:``}${b(e.slice(i))}`,rightHtml:`${b(t.slice(0,n))}${a>n?`<span class="diff-highlight-add">${b(t.slice(n,a))}</span>`:``}${b(t.slice(a))}`}}function gl(e=[]){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.type===`context`||r.type===`note`){t.push({additions:[],context:[r],deletions:[]});continue}if(r.type!==`deletion`&&r.type!==`addition`)continue;let i=[],a=[];for(;n<e.length&&e[n].type===`deletion`;)i.push(e[n]),n+=1;for(;n<e.length&&e[n].type===`addition`;)a.push(e[n]),n+=1;--n,t.push({additions:a,context:[],deletions:i})}return t}function _l(e,t,n){let r=Number.isInteger(e.oldLine)?e.oldLine:``,i=Number.isInteger(e.newLine)?e.newLine:``,a=e.type===`note`?`note`:e.type,o=e.type===`context`||e.type===`note`?` `:t;return`
|
|
438
|
-
<div class="diff-line ${a}">
|
|
439
|
-
<div class="diff-line-numbers">
|
|
440
|
-
<span class="diff-line-num">${r}</span>
|
|
441
|
-
<span class="diff-line-num">${i}</span>
|
|
442
|
-
</div>
|
|
443
|
-
<div class="diff-line-prefix">${b(o)}</div>
|
|
444
|
-
<div class="diff-line-content">${n}</div>
|
|
445
|
-
</div>
|
|
446
|
-
`}function vl(e,t){let n=e?b(e.content):``,r=t?b(t.content):``;if(e&&t&&e.type===`deletion`&&t.type===`addition`){let i=hl(e.content,t.content);n=i.leftHtml,r=i.rightHtml}return`
|
|
447
|
-
<div class="diff-split-row">
|
|
448
|
-
<div class="diff-split-line ${e?.type||`empty`}">
|
|
449
|
-
<span class="diff-split-num">${Number.isInteger(e?.oldLine)?e.oldLine:``}</span>
|
|
450
|
-
<span class="diff-split-content">${n}</span>
|
|
451
|
-
</div>
|
|
452
|
-
<div class="diff-split-line ${t?.type||`empty`}">
|
|
453
|
-
<span class="diff-split-num">${Number.isInteger(t?.newLine)?t.newLine:``}</span>
|
|
454
|
-
<span class="diff-split-content">${r}</span>
|
|
455
|
-
</div>
|
|
456
|
-
</div>
|
|
457
|
-
`}var yl=class{constructor({getTheme:e=()=>`dark`,gitApiClient:t=null,onBackToHistory:n=null,onCommitStaged:r=null,onOpenFile:i=null,onStageFile:a=null,onUnstageFile:o=null,toastController:s=null,vaultApiClient:c=null}={}){this.getTheme=e,this.gitApiClient=t,this.onBackToHistory=n,this.onCommitStaged=r,this.onOpenFile=i,this.onStageFile=a,this.onUnstageFile=o,this.toastController=s,this.vaultApiClient=c,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.scrollContainer=document.getElementById(`diffScroll`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.layoutButtons=Array.from(document.querySelectorAll(`[data-diff-layout]`)),this.isActive=!1,this.mode=`unified`,this.layoutMode=`focused`,this.source=`workspace`,this.data=null,this.currentIndex=0,this.activeFilePath=null,this.fileCache=new Map,this.fileErrors=new Map,this.loadingFiles=new Set,this.collapsedFiles=new Set,this.fileLoadPromises=new Map,this.excalidrawPreviewPayloads=new Map,this.excalidrawPreviewCounter=0,this.drawioPreviewPayloads=new Map,this.drawioPreviewCounter=0,this.requestScope=`all`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}initialize(){this.prevButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(-1)}),this.nextButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(1)}),this.backToHistoryButton?.addEventListener(`click`,()=>{this.isActive&&this.commitMeta?.hash&&this.onBackToHistory?.({hash:this.commitMeta.hash,historyFilePath:this.historyFilePath})}),this.openEditorButton?.addEventListener(`click`,()=>{if(!this.isActive||this.source!==`workspace`)return;let e=this.getCurrentFile();e?.path&&this.onOpenFile?.(e.path)}),this.primaryActionButton?.addEventListener(`click`,()=>{if(!this.isActive)return;let e=this.getPrimaryAction();e&&this.handleFileAction(e)}),this.commitButton?.addEventListener(`click`,()=>{this.isActive&&this.handleFileAction(`commit`)}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-load-full-diff]`):null;if(t){let e=t.getAttribute(`data-diff-file-path`)||this.activeFilePath;e&&this.loadFileForPath(e,{forceFullPatch:!0});return}let n=e.target instanceof Element?e.target.closest(`[data-diff-section-toggle]`):null;if(n){let e=n.getAttribute(`data-diff-section-toggle`);e&&this.toggleFileSection(e);return}let r=e.target instanceof Element?e.target.closest(`[data-diff-index-path]`):null;if(r){let e=r.getAttribute(`data-diff-index-path`);e&&this.handleIndexSelection(e)}}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.mode||(this.mode=t,this.render())})}),this.layoutButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-layout`);!t||t===this.layoutMode||this.setLayoutMode(t)})}),this.scrollContainer?.addEventListener(`scroll`,()=>{this.isActive&&this.handleScrollSelection()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content&&(this.content.innerHTML=``),this.data=null,this.source=`workspace`,this.layoutMode=`focused`,this.currentIndex=0,this.activeFilePath=null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=`all`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}async openWorkspaceDiff({filePath:e=null,scope:t=`all`}={}){this.isActive=!0,this.source=`workspace`,this.layoutMode=`focused`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.activeFilePath=e,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=t,this.renderLoading(`Loading diff summary...`);try{let n=await this.gitApiClient.readDiff({metaOnly:!0,path:e,scope:t});this.data=n;let r=e?Math.max(0,n.files.findIndex(t=>t.path===e)):0;return this.currentIndex=r,this.activeFilePath=n.files?.[r]?.path??null,(n.files?.length??0)===0?(this.render(),n):(await this.loadCurrentFile(),n)}catch(e){return console.error(`[git-diff] Failed to load diff:`,e),this.toastController?.show(`Failed to load git diff`),this.data={files:[],metaOnly:!1,source:`workspace`,summary:{additions:0,deletions:0,filesChanged:0}},this.renderEmpty(`Failed to load git diff`),this.data}}async openCommitDiff({hash:e,path:t=null,historyFilePath:n=null}={}){this.isActive=!0,this.source=`commit`,this.layoutMode=`stacked`,this.commitHash=String(e??``).trim()||null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=String(n??``).trim()||null,this.activeFilePath=t||null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=`all`,this.renderLoading(`Loading commit summary...`);try{let e=await this.gitApiClient.readCommit({hash:this.commitHash||``,metaOnly:!0});this.data=e,this.commitMeta=e.commit??null,this.commitBaseRef=e.baseRef||null;let n=t?Math.max(0,e.files.findIndex(e=>e.path===t)):0;return this.currentIndex=n,this.activeFilePath=e.files?.[n]?.path??null,this.collapsedFiles=new Set((e.files??[]).map(e=>e.path).filter(e=>e&&e!==this.activeFilePath)),(e.files?.length??0)===0?(this.render(),e):(this.activeFilePath&&await this.loadFileForPath(this.activeFilePath,{render:!1}),this.render(),e)}catch(e){return console.error(`[git-diff] Failed to load commit:`,e),this.toastController?.show(`Failed to load git commit`),this.data={commit:null,files:[],metaOnly:!1,source:`commit`,summary:{additions:0,deletions:0,filesChanged:0}},this.commitMeta=null,this.renderEmpty(`Failed to load git commit`),this.data}}async open(e={}){return this.openWorkspaceDiff(e)}async setLayoutMode(e){let t=e===`stacked`?`stacked`:`focused`;if(this.source!==`commit`){this.layoutMode=`focused`,this.render();return}if(this.layoutMode=t,this.activeFilePath&&this.setActiveFilePath(this.activeFilePath),this.layoutMode===`focused`){await this.loadCurrentFile();return}this.activeFilePath&&(this.collapsedFiles.delete(this.activeFilePath),await this.loadFileForPath(this.activeFilePath,{render:!1})),this.render()}navigateFile(e){if(!this.data?.files?.length||this.source===`commit`&&this.layoutMode===`stacked`)return;let t=Math.max(0,Math.min(this.currentIndex+e,this.data.files.length-1));t!==this.currentIndex&&(this.currentIndex=t,this.activeFilePath=this.data.files[t]?.path??null,this.scrollContainer?.scrollTo({top:0,behavior:`auto`}),this.loadCurrentFile())}renderLoading(e=`Loading git diff...`){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${b(e)}</div>`),this.data=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${b(e)}</div>`),this.syncToolbar())}renderUnifiedHunk(e){let t=[];for(let n of gl(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(_l(e,` `,b(e.content)));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1){let e=n.deletions[r]??null,i=n.additions[r]??null,a=e&&i?hl(e.content,i.content):null;e&&t.push(_l(e,`-`,a?.leftHtml??b(e.content))),i&&t.push(_l(i,`+`,a?.rightHtml??b(i.content)))}}return`
|
|
458
|
-
<div class="diff-hunk-header">${b(e.header)}</div>
|
|
459
|
-
${t.join(``)}
|
|
460
|
-
`}getGitImageUrl(e,t){return!e||!t?``:typeof this.gitApiClient?.getFileAttachmentUrl==`function`?this.gitApiClient.getFileAttachmentUrl({hash:e,path:t}):F(`/git/file-attachment?hash=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`)}getCurrentImageUrl(e){return e?F(`/attachment?path=${encodeURIComponent(e)}`):``}getImageDiffSources(e){let t=e.status===`added`||e.status===`untracked`,n=e.status===`deleted`,r=e.oldPath||e.path,i=e.path;return this.source===`commit`?{after:n?``:this.getGitImageUrl(this.commitHash,i),before:t?``:this.getGitImageUrl(this.commitBaseRef,r)}:{after:n?``:this.getCurrentImageUrl(i),before:t?``:this.getGitImageUrl(`HEAD`,r)}}renderImagePane({file:e,label:t,source:n,emptyLabel:r}){let i=n?`<img class="diff-media-image" src="${b(n)}" alt="${b(`${t} ${e.path}`)}" loading="lazy" decoding="async">`:`<div class="diff-media-empty"><span class="diff-media-empty-icon" aria-hidden="true">—</span><span>${b(r)}</span></div>`;return`
|
|
461
|
-
<div class="diff-media-pane">
|
|
462
|
-
<div class="diff-media-pane-header">
|
|
463
|
-
<span class="diff-media-pane-label">${b(t)}</span>
|
|
464
|
-
<span class="diff-media-pane-meta">${b(Yc(e.path))}</span>
|
|
465
|
-
</div>
|
|
466
|
-
<div class="diff-media-canvas">${i}</div>
|
|
467
|
-
</div>
|
|
468
|
-
`}renderImageDiff(e){let t=this.getImageDiffSources(e),n=tl(e.byteLength);return`
|
|
469
|
-
<section class="diff-special diff-media-diff" aria-label="Image diff">
|
|
470
|
-
<div class="diff-special-header">
|
|
471
|
-
<div>
|
|
472
|
-
<span class="diff-special-eyebrow">Binary preview</span>
|
|
473
|
-
<h2 class="diff-special-title">Image comparison</h2>
|
|
474
|
-
</div>
|
|
475
|
-
<span class="diff-special-note">${b(Yc(e.path))}${n?` · ${b(n)}`:``}</span>
|
|
476
|
-
</div>
|
|
477
|
-
<div class="diff-media-grid">
|
|
478
|
-
${this.renderImagePane({emptyLabel:`No previous image`,file:e,label:`Before`,source:t.before})}
|
|
479
|
-
${this.renderImagePane({emptyLabel:`No image in this revision`,file:e,label:`After`,source:t.after})}
|
|
480
|
-
</div>
|
|
481
|
-
<p class="diff-special-footnote">Image bytes are shown as a visual comparison instead of a text patch.</p>
|
|
482
|
-
</section>
|
|
483
|
-
`}registerExcalidrawPreview(e){if(!e)return``;this.excalidrawPreviewCounter+=1;let t=`diff-excalidraw-preview-${this.excalidrawPreviewCounter.toString(36)}`;return this.excalidrawPreviewPayloads.set(t,e),t}renderExcalidrawPane({label:e,scene:t,source:n,emptyLabel:r}){let i=this.registerExcalidrawPreview(t),a=t?`
|
|
484
|
-
<div class="diff-excalidraw-preview" data-diff-excalidraw-preview="${b(i)}">
|
|
485
|
-
<span class="diff-excalidraw-preview-loading">Rendering diagram…</span>
|
|
486
|
-
</div>
|
|
487
|
-
`:`<div class="diff-excalidraw-preview diff-excalidraw-preview--empty"><span>${b(r)}</span></div>`,o=n?`
|
|
488
|
-
<details class="diff-excalidraw-source">
|
|
489
|
-
<summary>Structured scene</summary>
|
|
490
|
-
<pre>${b(n)}</pre>
|
|
491
|
-
</details>
|
|
492
|
-
`:``;return`
|
|
493
|
-
<div class="diff-excalidraw-pane">
|
|
494
|
-
<div class="diff-excalidraw-pane-header">
|
|
495
|
-
<span class="diff-media-pane-label">${b(e)}</span>
|
|
496
|
-
<span class="diff-media-pane-meta">${t?`${Qc(t).length} elements`:`—`}</span>
|
|
497
|
-
</div>
|
|
498
|
-
${a}
|
|
499
|
-
${o}
|
|
500
|
-
</div>
|
|
501
|
-
`}renderExcalidrawDiff(e){let t=Zc(e),n=el(t.before,t.after)??{added:0,afterCount:0,beforeCount:0,removed:0,updated:0},r=!!(t.before||t.after),i=e.tooLarge&&e.canLoadFullPatch?`<button class="${U({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${b(e.path)}">Load full diff</button>`:``;return`
|
|
502
|
-
<section class="diff-special diff-excalidraw-diff" aria-label="Excalidraw diff">
|
|
503
|
-
<div class="diff-special-header">
|
|
504
|
-
<div>
|
|
505
|
-
<span class="diff-special-eyebrow">Diagram-aware preview</span>
|
|
506
|
-
<h2 class="diff-special-title">Excalidraw scene changes</h2>
|
|
507
|
-
</div>
|
|
508
|
-
<span class="diff-special-note">${r?`${n.afterCount} visible elements`:`Scene preview unavailable`}</span>
|
|
509
|
-
</div>
|
|
510
|
-
<div class="diff-scene-summary" aria-label="Scene change summary">
|
|
511
|
-
<span class="diff-scene-stat diff-scene-stat--add"><strong>+${n.added}</strong><span>added</span></span>
|
|
512
|
-
<span class="diff-scene-stat diff-scene-stat--update"><strong>~${n.updated}</strong><span>updated</span></span>
|
|
513
|
-
<span class="diff-scene-stat diff-scene-stat--remove"><strong>-${n.removed}</strong><span>removed</span></span>
|
|
514
|
-
</div>
|
|
515
|
-
<div class="diff-excalidraw-grid">
|
|
516
|
-
${this.renderExcalidrawPane({emptyLabel:`No previous scene`,label:`Before`,scene:t.before,source:t.beforeSource?JSON.stringify(t.before||Z(t.beforeSource),null,2):``})}
|
|
517
|
-
${this.renderExcalidrawPane({emptyLabel:e.tooLarge?`Load the full diff to preview this scene`:`No scene in this revision`,label:`After`,scene:t.after,source:t.afterSource?JSON.stringify(t.after||Z(t.afterSource),null,2):``})}
|
|
518
|
-
</div>
|
|
519
|
-
${i}
|
|
520
|
-
<p class="diff-special-footnote">The preview compares drawable elements by id; expand “Structured scene” when you need the underlying JSON.</p>
|
|
521
|
-
</section>
|
|
522
|
-
`}async readDrawioSource({hash:e=null,path:t=null,current:n=!1}={}){if(!t)return``;try{if(n){let e=await this.vaultApiClient?.readFile?.(t);return typeof e?.content==`string`?e.content:``}if(!e||typeof this.gitApiClient?.readFileSnapshot!=`function`)return``;let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});return typeof r?.content==`string`?r.content:``}catch{return``}}async enrichDrawioDetail(e){let t=al(e),n=t.before,r=t.after,i=e.status===`added`||e.status===`untracked`,a=e.status===`deleted`,o=e.oldPath||e.path,s=e.path;return!i&&!nl(n)&&(n=await this.readDrawioSource({current:!1,hash:this.source===`commit`?this.commitBaseRef:`HEAD`,path:o})),!a&&!nl(r)&&(r=await this.readDrawioSource({current:this.source!==`commit`,hash:this.source===`commit`?this.commitHash:null,path:s})),{...e,drawioAfterSource:r,drawioBeforeSource:n}}registerDrawioPreview(e){if(!e)return``;this.drawioPreviewCounter+=1;let t=`diff-drawio-preview-${this.drawioPreviewCounter.toString(36)}`;return this.drawioPreviewPayloads.set(t,e),t}renderDrawioPane({emptyLabel:e,label:t,source:n}){let r=cl(n),i=r?``:this.registerDrawioPreview(n),a=n&&!r?`
|
|
523
|
-
<div class="diff-drawio-preview" data-diff-drawio-preview="${b(i)}">
|
|
524
|
-
<span class="diff-drawio-preview-loading">Rendering draw.io preview…</span>
|
|
525
|
-
</div>
|
|
526
|
-
`:`<div class="diff-drawio-preview diff-drawio-preview--empty"><span>${b(r?`No drawable cells`:e)}</span></div>`,o=n?`
|
|
527
|
-
<details class="diff-drawio-source">
|
|
528
|
-
<summary>XML source</summary>
|
|
529
|
-
<pre>${b(rl(n))}</pre>
|
|
530
|
-
</details>
|
|
531
|
-
`:``;return`
|
|
532
|
-
<div class="diff-drawio-pane">
|
|
533
|
-
<div class="diff-drawio-pane-header">
|
|
534
|
-
<span class="diff-media-pane-label">${b(t)}</span>
|
|
535
|
-
<span class="diff-media-pane-meta">draw.io</span>
|
|
536
|
-
</div>
|
|
537
|
-
${a}
|
|
538
|
-
${o}
|
|
539
|
-
</div>
|
|
540
|
-
`}renderDrawioDiff(e){let t=al(e),n=ll(t.before,t.after)??{added:0,afterCount:0,beforeCount:0,cellBased:!1,removed:0,updated:0},r=t.before||t.after?n.cellBased?`${n.afterCount} drawable cells`:`Source-level comparison`:`Preview unavailable`,i=e.tooLarge&&e.canLoadFullPatch?`<button class="${U({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${b(e.path)}">Load full diff</button>`:``;return`
|
|
541
|
-
<section class="diff-special diff-drawio-diff" aria-label="draw.io diff">
|
|
542
|
-
<div class="diff-special-header">
|
|
543
|
-
<div>
|
|
544
|
-
<span class="diff-special-eyebrow">Diagram-aware preview</span>
|
|
545
|
-
<h2 class="diff-special-title">draw.io diagram changes</h2>
|
|
546
|
-
</div>
|
|
547
|
-
<span class="diff-special-note">${b(r)}</span>
|
|
548
|
-
</div>
|
|
549
|
-
<div class="diff-scene-summary" aria-label="draw.io change summary">
|
|
550
|
-
<span class="diff-scene-stat diff-scene-stat--add"><strong>+${n.added}</strong><span>added</span></span>
|
|
551
|
-
<span class="diff-scene-stat diff-scene-stat--update"><strong>~${n.updated}</strong><span>updated</span></span>
|
|
552
|
-
<span class="diff-scene-stat diff-scene-stat--remove"><strong>-${n.removed}</strong><span>removed</span></span>
|
|
553
|
-
</div>
|
|
554
|
-
<div class="diff-drawio-grid">
|
|
555
|
-
${this.renderDrawioPane({emptyLabel:`No previous diagram`,label:`Before`,source:t.before})}
|
|
556
|
-
${this.renderDrawioPane({emptyLabel:e.tooLarge?`Load the full diff to preview this diagram`:`No diagram in this revision`,label:`After`,source:t.after})}
|
|
557
|
-
</div>
|
|
558
|
-
${i}
|
|
559
|
-
<p class="diff-special-footnote">Both revisions use the draw.io viewer; expand “XML source” when you need the underlying document.</p>
|
|
560
|
-
</section>
|
|
561
|
-
`}async hydrateExcalidrawPreviews(){if(this.excalidrawPreviewPayloads.size===0||!this.content)return;let t;try{({exportToSvg:t}=await e(()=>import(`./prod-Dy20X7eT.js`),__vite__mapDeps([30,31,6,1,32,33,34,35,36,37]),import.meta.url))}catch(e){console.warn(`[git-diff] Excalidraw preview renderer unavailable:`,e);return}for(let[e,n]of this.excalidrawPreviewPayloads){let r=this.content.querySelector?.(`[data-diff-excalidraw-preview="${e}"]`);if(r)try{let e=await t({appState:{exportBackground:!0,exportWithDarkMode:!1,viewBackgroundColor:n.appState?.viewBackgroundColor||`#ffffff`},elements:Qc(n),exportPadding:24,files:n.files||null});r.replaceChildren(e),r.classList.add(`is-ready`)}catch(e){console.warn(`[git-diff] Failed to render Excalidraw scene preview:`,e),r.textContent=`Visual preview unavailable`,r.classList.add(`is-error`)}}}async hydrateDrawioPreviews(){if(!(this.drawioPreviewPayloads.size===0||!this.content))for(let[e,t]of this.drawioPreviewPayloads){let n=this.content.querySelector?.(`[data-diff-drawio-preview="${e}"]`);if(n)try{await Pc(n,{ariaLabel:`draw.io diagram diff preview`,className:`mxgraph drawio-viewer-frame diff-drawio-viewer-frame`,source:t,theme:this.getTheme?.()===`light`?`light`:`dark`}),n.classList.add(`is-ready`)}catch(e){console.warn(`[git-diff] Failed to render draw.io diagram preview:`,e),n.textContent=`Visual preview unavailable`,n.classList.add(`is-error`)}}}renderFileHeader(e){let t=Jc(e)===`image`?`<span class="diff-file-header-kind">${b(Yc(e.path))} image</span>`:`<span class="diff-file-header-stats"><span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span><span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span></span>`;return`
|
|
562
|
-
<div class="diff-file-header">
|
|
563
|
-
<span class="diff-file-path">${b(e.path)}</span>
|
|
564
|
-
<span class="ui-status-badge ${dl(e.status)}">${b(e.status)}</span>
|
|
565
|
-
${t}
|
|
566
|
-
</div>
|
|
567
|
-
`}renderUnifiedFileBody(e){return`
|
|
568
|
-
${e.isBinary?`<div class="diff-binary-message">${b(e.binaryMessage||`Binary file changed`)}</div>`:``}
|
|
569
|
-
${e.hunks.map(e=>this.renderUnifiedHunk(e)).join(``)}
|
|
570
|
-
`}renderSplitFileBody(e){return`
|
|
571
|
-
<div class="diff-split">
|
|
572
|
-
<div class="diff-split-pane">
|
|
573
|
-
<div class="diff-split-pane-header">Before</div>
|
|
574
|
-
${e.hunks.map(e=>{let t=[];for(let n of gl(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(vl(e,e));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1)t.push(vl(n.deletions[r]??null,n.additions[r]??null))}return`
|
|
575
|
-
<div class="diff-split-hunk">${b(e.header)}</div>
|
|
576
|
-
${t.join(``)}
|
|
577
|
-
`}).join(``)}
|
|
578
|
-
</div>
|
|
579
|
-
</div>
|
|
580
|
-
`}renderDiffDetail(e,t,{includeHeader:n=!0}={}){if(!e)return`<div class="diff-empty-state">Select a file to load its diff.</div>`;let r=Jc(e);if(r===`image`)return`${n?this.renderFileHeader(e):``}${this.renderImageDiff(e)}`;if(r===`excalidraw`)return`${n?this.renderFileHeader(e):``}${this.renderExcalidrawDiff(e)}`;if(r===`drawio`)return`${n?this.renderFileHeader(e):``}${this.renderDrawioDiff(e)}`;if(e.tooLarge)return`
|
|
581
|
-
${n?this.renderFileHeader(e):``}
|
|
582
|
-
<div class="diff-limit-card">
|
|
583
|
-
<strong>Large diff withheld</strong>
|
|
584
|
-
<span>This file diff is large enough to impact rendering performance.</span>
|
|
585
|
-
<button class="${U({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${b(e.path)}">Load full diff</button>
|
|
586
|
-
</div>
|
|
587
|
-
`;let i=this.mode===`split`?this.renderSplitFileBody(e,t):this.renderUnifiedFileBody(e,t);return`${n?this.renderFileHeader(e):``}${i}`}renderFocusedFileBody(){let e=this.getCurrentFile();if(!e)return`<div class="diff-empty-state">No changes to display.</div>`;if(this.isFileLoading(e.path))return`
|
|
588
|
-
<section class="diff-file-block">
|
|
589
|
-
${this.renderFileHeader(e)}
|
|
590
|
-
<div class="diff-empty-state">Loading file diff...</div>
|
|
591
|
-
</section>
|
|
592
|
-
`;let t=this.fileErrors.get(e.path);return t?`
|
|
593
|
-
<section class="diff-file-block">
|
|
594
|
-
${this.renderFileHeader(e)}
|
|
595
|
-
<div class="diff-empty-state">${b(t)}</div>
|
|
596
|
-
</section>
|
|
597
|
-
`:`
|
|
598
|
-
<section class="diff-file-block" data-diff-file-index="${this.currentIndex}">
|
|
599
|
-
${this.renderDiffDetail(this.getFileDetail(e.path)??e,this.currentIndex)}
|
|
600
|
-
</section>
|
|
601
|
-
`}renderCommitHeader(){return this.source!==`commit`||!this.commitMeta?``:`
|
|
602
|
-
<section class="diff-commit-header">
|
|
603
|
-
<div class="diff-commit-subject">${b(this.commitMeta.subject||this.commitMeta.shortHash||`Commit`)}</div>
|
|
604
|
-
<div class="diff-commit-meta">
|
|
605
|
-
<span>${b(this.commitMeta.shortHash||``)}</span>
|
|
606
|
-
<span>${b(this.commitMeta.authorName||`Unknown`)}</span>
|
|
607
|
-
<span title="${b(this.commitMeta.authoredAt||``)}">${b(this.commitMeta.relativeDateLabel||``)}</span>
|
|
608
|
-
${this.commitMeta.isMergeCommit?`<span>Merge commit</span>`:``}
|
|
609
|
-
</div>
|
|
610
|
-
<div class="diff-commit-meta diff-commit-meta-secondary">
|
|
611
|
-
<span>${b(this.commitMeta.hash||``)}</span>
|
|
612
|
-
<span>${Number(this.data?.summary?.filesChanged||0)} file${Number(this.data?.summary?.filesChanged||0)===1?``:`s`}</span>
|
|
613
|
-
</div>
|
|
614
|
-
</section>
|
|
615
|
-
`}renderCommitIndex(){return`
|
|
616
|
-
<aside class="diff-commit-index" aria-label="Changed files in commit">
|
|
617
|
-
<div class="diff-commit-index-header">Changed Files</div>
|
|
618
|
-
<div class="diff-commit-index-list">
|
|
619
|
-
${(this.data?.files??[]).map((e,t)=>{let n=this.activeFilePath===e.path,r=M(e.path);return`
|
|
620
|
-
<button
|
|
621
|
-
class="ui-record-surface diff-index-item${n?` active`:``}"
|
|
622
|
-
type="button"
|
|
623
|
-
data-diff-index-path="${b(e.path)}"
|
|
624
|
-
aria-current="${n?`true`:`false`}"
|
|
625
|
-
>
|
|
626
|
-
<span class="ui-record-header diff-index-item-top">
|
|
627
|
-
<span class="ui-record-title diff-index-item-name">${b(w(e.path))}</span>
|
|
628
|
-
<span class="ui-status-badge ${dl(e.status)}">${b(e.status)}</span>
|
|
629
|
-
</span>
|
|
630
|
-
${r?`<span class="ui-record-subtitle diff-index-item-path">${b(r)}</span>`:``}
|
|
631
|
-
<span class="ui-record-meta diff-index-item-meta">
|
|
632
|
-
<span>${t+1}</span>
|
|
633
|
-
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
|
|
634
|
-
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
|
|
635
|
-
</span>
|
|
636
|
-
</button>
|
|
637
|
-
`}).join(``)}
|
|
638
|
-
</div>
|
|
639
|
-
</aside>
|
|
640
|
-
`}renderStackedSection(e,t){let n=this.isFileCollapsed(e.path),r=this.activeFilePath===e.path,i=this.isFileLoading(e.path),a=this.fileErrors.get(e.path),o=this.getFileDetail(e.path)??e,s=n?``:i?`<div class="diff-empty-state">Loading file diff...</div>`:a?`<div class="diff-empty-state">${b(a)}</div>`:this.renderDiffDetail(o,t,{includeHeader:!1});return`
|
|
641
|
-
<section
|
|
642
|
-
class="diff-commit-section${r?` active`:``}${n?` collapsed`:``}"
|
|
643
|
-
id="${ul(e.path)}"
|
|
644
|
-
data-diff-section-path="${b(e.path)}"
|
|
645
|
-
>
|
|
646
|
-
<button
|
|
647
|
-
class="diff-commit-section-header"
|
|
648
|
-
type="button"
|
|
649
|
-
data-diff-section-toggle="${b(e.path)}"
|
|
650
|
-
>
|
|
651
|
-
<span class="diff-commit-section-main">
|
|
652
|
-
${fl(n)}
|
|
653
|
-
<span class="diff-commit-section-copy">
|
|
654
|
-
<span class="diff-commit-section-name">${b(w(e.path))}</span>
|
|
655
|
-
${M(e.path)?`<span class="diff-commit-section-path">${b(M(e.path))}</span>`:``}
|
|
656
|
-
</span>
|
|
657
|
-
</span>
|
|
658
|
-
<span class="diff-commit-section-meta">
|
|
659
|
-
<span class="ui-status-badge ${dl(e.status)}">${b(e.status)}</span>
|
|
660
|
-
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
|
|
661
|
-
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
|
|
662
|
-
</span>
|
|
663
|
-
</button>
|
|
664
|
-
<div class="diff-commit-section-body${n?` hidden`:``}">
|
|
665
|
-
${s}
|
|
666
|
-
</div>
|
|
667
|
-
</section>
|
|
668
|
-
`}renderCommitBody(){return this.layoutMode===`focused`?`
|
|
669
|
-
<div class="diff-commit-shell diff-commit-shell-focused">
|
|
670
|
-
${this.renderCommitIndex()}
|
|
671
|
-
<div class="diff-commit-main">
|
|
672
|
-
${this.renderFocusedFileBody()}
|
|
673
|
-
</div>
|
|
674
|
-
</div>
|
|
675
|
-
`:`
|
|
676
|
-
<div class="diff-commit-shell diff-commit-shell-stacked">
|
|
677
|
-
${this.renderCommitIndex()}
|
|
678
|
-
<div class="diff-commit-main">
|
|
679
|
-
<div class="diff-commit-sections">
|
|
680
|
-
${(this.data?.files??[]).map((e,t)=>this.renderStackedSection(e,t)).join(``)}
|
|
681
|
-
</div>
|
|
682
|
-
</div>
|
|
683
|
-
</div>
|
|
684
|
-
`}getCurrentFile(){let e=this.data?.files??[];return e.length===0?null:e[this.currentIndex]??e[0]??null}getFileByPath(e){return(this.data?.files??[]).find(t=>t.path===e)??null}setActiveFilePath(e,{syncIndex:t=!0}={}){if(this.activeFilePath=e,!t)return;let n=Math.max(0,(this.data?.files??[]).findIndex(t=>t.path===e));n>=0&&(this.currentIndex=n)}getCacheKeyForPath(e){return e?this.source===`commit`?`commit:${this.commitHash}:${e}`:`workspace:${this.requestScope}:${e}`:null}getCurrentCacheKey(){return this.getCacheKeyForPath(this.getCurrentFile()?.path??null)}getCurrentFileDetail(){let e=this.getCurrentCacheKey();return e?this.fileCache.get(e):null}getFileDetail(e){let t=this.getCacheKeyForPath(e);return t?this.fileCache.get(t):null}isFileCollapsed(e){return this.collapsedFiles.has(e)}isFileLoading(e){return this.loadingFiles.has(e)}getCurrentActionState(){if(this.source===`commit`)return{canCommit:!1,canStage:!1,canUnstage:!1};let e=this.getCurrentFile(),t=this.getCurrentFileDetail()??e,n=Number(this.repoStatus?.summary?.staged||0);return t?.path?{canCommit:n>0,canStage:!!(t.hasWorkingTreeChanges||t.hasUntrackedChanges),canUnstage:!!t.hasStagedChanges}:{canCommit:n>0,canStage:!1,canUnstage:!1}}getPrimaryAction(){if(this.source===`commit`)return null;let e=this.getCurrentActionState();return e.canStage&&!e.canUnstage?`stage`:e.canUnstage&&!e.canStage||this.requestScope===`staged`&&e.canUnstage?`unstage`:e.canStage?`stage`:e.canUnstage?`unstage`:null}async handleFileAction(e){if(this.source===`commit`)return;let t=this.getCurrentFile();if(!(!t?.path||this.pendingAction)){this.pendingAction=e,this.syncToolbar();try{e===`stage`?await this.onStageFile?.(t.path,{scope:this.requestScope}):e===`unstage`?await this.onUnstageFile?.(t.path,{scope:this.requestScope}):e===`commit`&&await this.onCommitStaged?.()}finally{this.pendingAction=null,this.syncToolbar()}}}setRepoStatus(e){this.repoStatus=e,this.syncToolbar()}async handleIndexSelection(e){if(this.getFileByPath(e)){if(this.setActiveFilePath(e),this.source===`commit`&&this.layoutMode===`stacked`){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}await this.loadFileForPath(e)}}async toggleFileSection(e){if(this.source===`commit`&&this.layoutMode===`stacked`){if(this.setActiveFilePath(e),this.collapsedFiles.has(e)){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}this.collapsedFiles.add(e),this.render()}}scrollToFileSection(e){if(!this.content)return;let t=ul(e),n=()=>{let e=document.getElementById?.(t)??null;if(e){if(this.scrollContainer?.scrollTo&&this.scrollContainer.getBoundingClientRect&&e.getBoundingClientRect){let t=this.scrollContainer.getBoundingClientRect(),n=e.getBoundingClientRect(),r=Number(this.scrollContainer.scrollTop)||0,i=Math.max(0,r+(n.top-t.top)-8);this.scrollContainer.scrollTo({top:i,behavior:`smooth`});return}e.scrollIntoView?.({behavior:`smooth`,block:`start`})}};if(typeof requestAnimationFrame==`function`){requestAnimationFrame(n);return}setTimeout(n,0)}handleScrollSelection(){if(this.source!==`commit`||this.layoutMode!==`stacked`||!this.scrollContainer||!this.content)return;let e=Array.from(this.content.querySelectorAll?.(`[data-diff-section-path]`)??[]);if(e.length===0)return;let t=this.scrollContainer.getBoundingClientRect?.();if(!t)return;let n=t.top+120,r=null;for(let t of e){let e=t.getBoundingClientRect?.();if(!e)continue;let i=t.getAttribute?.(`data-diff-section-path`);if(i){if(e.top<=n)r=i;else if(r)break;else{r=i;break}}}r&&r!==this.activeFilePath&&(this.setActiveFilePath(r),this.render())}async loadCurrentFile({forceFullPatch:e=!1}={}){let t=this.getCurrentFile();return t?.path?this.loadFileForPath(t.path,{forceFullPatch:e}):(this.render(),null)}async loadFileForPath(e,{forceFullPatch:t=!1,render:n=!0}={}){let r=this.getFileByPath(e);if(!r?.path)return n&&this.render(),null;this.setActiveFilePath(e);let i=this.getCacheKeyForPath(e),a=i?this.fileCache.get(i):null;if(a&&(!a.tooLarge||!t))return n&&this.render(),a;let o=`${e}:${t?`full`:`partial`}`;if(this.fileLoadPromises.has(o))return this.fileLoadPromises.get(o);this.loadingFiles.add(e),this.fileErrors.delete(e),n&&this.render();let s=(async()=>{try{let n;if(this.source===`commit`){let i=await this.gitApiClient.readCommit({allowLargePatch:t,hash:this.commitHash||``,path:e});n={...r,...i.files?.[0]??{}}}else{let i=await this.gitApiClient.readDiff({allowLargePatch:t,path:e,scope:this.requestScope});n={...r,...i.files?.[0]??{}}}return Jc(n)===`drawio`&&(n=await this.enrichDrawioDetail(n)),i&&this.fileCache.set(i,n),this.fileErrors.delete(e),n}catch(t){console.error(`[git-diff] Failed to load file diff:`,t);let n=this.source===`commit`?`Failed to load commit file diff`:`Failed to load file diff`;return this.fileErrors.set(e,n),this.toastController?.show(n),null}finally{this.loadingFiles.delete(e),this.fileLoadPromises.delete(o),this.render()}})();return this.fileLoadPromises.set(o,s),s}syncToolbar(){let e=this.data?.files?.length??0,t=e===0?0:this.currentIndex+1,n=this.source===`commit`,r=n&&this.layoutMode===`stacked`;if(this.fileIndicator&&(r?this.fileIndicator.textContent=`${e} file${e===1?``:`s`}`:this.fileIndicator.textContent=e>0?`${t} / ${e} files`:`0 / 0 files`),this.stats){let e=(this.data?.files??[]).filter(e=>Jc(e)===`image`).reduce((e,t)=>({additions:e.additions+Number(t.stats?.additions||0),deletions:e.deletions+Number(t.stats?.deletions||0)}),{additions:0,deletions:0}),t=this.data?.files??[],n=t.length>0&&t.every(e=>Jc(e)===`image`),r=Number(this.data?.summary?.additions??0),i=Number(this.data?.summary?.deletions??0),a=n?0:Math.max(0,r-e.additions),o=n?0:Math.max(0,i-e.deletions);this.stats.innerHTML=`
|
|
685
|
-
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${a}</span>
|
|
686
|
-
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${o}</span>
|
|
687
|
-
`}this.modeButtons.forEach(e=>{e.classList.remove(`hidden`),e.classList.toggle(`active`,e.getAttribute(`data-diff-mode`)===this.mode)}),this.layoutButtons.forEach(e=>{e.classList.toggle(`active`,e.getAttribute(`data-diff-layout`)===this.layoutMode)});let i=!!this.getCurrentFile()?.path,a=this.getCurrentActionState(),o=this.getPrimaryAction();this.backToHistoryButton?.classList.toggle(`hidden`,!n),this.gitActionsGroup?.classList.toggle(`hidden`,n),this.editorActionsGroup?.classList.toggle(`hidden`,n),this.actionsDivider?.classList.toggle(`hidden`,n),this.layoutToggle?.classList.toggle(`hidden`,!n),this.stats?.classList.remove(`hidden`),this.openEditorButton&&(this.openEditorButton.textContent=`Open in Editor`),this.openEditorButton?.toggleAttribute(`disabled`,!i||n),this.primaryActionButton&&(this.primaryActionButton.textContent=this.pendingAction===o?`Working...`:o===`unstage`?`Unstage`:`Stage`,this.primaryActionButton.toggleAttribute(`disabled`,n||!i||!o||!!this.pendingAction)),this.commitButton&&(this.commitButton.textContent=this.pendingAction===`commit`?`Working...`:`Commit Staged`),this.commitButton?.toggleAttribute(`disabled`,n||!a.canCommit||!!this.pendingAction),this.prevButton?.classList.remove(`hidden`),this.nextButton?.classList.remove(`hidden`),this.prevButton?.classList.toggle(`hidden`,r),this.nextButton?.classList.toggle(`hidden`,r),this.prevButton?.toggleAttribute(`disabled`,r||this.currentIndex<=0),this.nextButton?.toggleAttribute(`disabled`,r||e===0||this.currentIndex>=e-1)}render(){if(this.isActive){if(this.page?.classList.remove(`hidden`),(this.data?.files??[]).length===0){this.renderEmpty(this.source===`commit`?`No commit changes to display.`:`No changes to display.`);return}this.content&&(this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.source===`commit`?this.content.innerHTML=`${this.renderCommitHeader()}${this.renderCommitBody()}`:this.content.innerHTML=this.renderFocusedFileBody(),this.syncToolbar(),this.hydrateExcalidrawPreviews(),this.hydrateDrawioPreviews())}}getToolbarTitle({commitHash:e=null,filePath:t=null,path:n=null,scope:r=`all`,source:i=`workspace`}={}){return i===`commit`||this.source===`commit`?this.layoutMode===`stacked`?this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:n?w(n):this.activeFilePath?w(this.activeFilePath):this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:t?w(t):r===`staged`?`Staged Changes`:r===`working-tree`?`Working Tree Changes`:`All Changes`}},bl=30,xl=1e4;function Sl(){return`<svg class="git-file-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}function Cl(){return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M13 6h3a2 2 0 0 1 2 2v7"/><path d="M6 9v12"/></svg>`}function wl(e){return`<svg class="git-section-chevron${e?` collapsed`:``}" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function Tl(e){switch(e){case`commit`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>`;case`pull`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="m18 13-6 6-6-6"/></svg>`;case`push`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5"/><path d="m6 11 6-6 6 6"/></svg>`;case`unstage`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 12H8"/><path d="m12 16-4-4 4-4"/></svg>`;case`reset`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>`;default:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`}}function El(e){switch(e){case`added`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;case`untracked`:return`ui-status-badge--muted`;default:return`ui-status-badge--warning`}}function Dl(e={},t={}){let n=Number(e.additions||0),r=Number(e.deletions||0);return Number(e.changedFiles||0)>0||n>0||r>0?`
|
|
688
|
-
<span class="git-change-stats" aria-label="Local diff summary">
|
|
689
|
-
<span class="git-change-add">+${n}</span>
|
|
690
|
-
<span class="git-change-del">-${r}</span>
|
|
691
|
-
</span>
|
|
692
|
-
`:t.upstream||Number(t.ahead||0)>0||Number(t.behind||0)>0?`
|
|
693
|
-
<span class="git-sync-info" aria-label="Remote sync status">
|
|
694
|
-
<span class="git-sync-metric git-sync-metric--ahead">↑${Number(t.ahead||0)}</span>
|
|
695
|
-
<span class="git-sync-metric git-sync-metric--behind">↓${Number(t.behind||0)}</span>
|
|
696
|
-
</span>
|
|
697
|
-
`:`<span class="git-sync-info git-sync-info-muted">Clean</span>`}function Ol(e={}){let t=String(e.subject||``).trim()||e.shortHash||`Commit`;return b(t)}var kl=class{constructor({enabled:e=!0,gitApiClient:t=null,onCommitStaged:n=()=>{},onOpenPullBackup:r=()=>{},onPullBranch:i=()=>{},onPushBranch:a=()=>{},onRepoChange:o=()=>{},onResetFile:s=()=>{},onSelectCommit:c=()=>{},onSelectDiff:l=()=>{},onStageFile:u=()=>{},onUnstageFile:d=()=>{},onViewAllDiff:f=()=>{},searchInput:p=null,toastController:m=null}={}){this.enabled=e,this.gitApiClient=t,this.onCommitStaged=n,this.onOpenPullBackup=r,this.onPullBranch=i,this.onPushBranch=a,this.onRepoChange=o,this.onResetFile=s,this.onSelectCommit=c,this.onSelectDiff=l,this.onStageFile=u,this.onUnstageFile=d,this.onViewAllDiff=f,this.searchInput=p,this.toastController=m,this.panel=document.getElementById(`gitPanel`),this.pullBackups=[],this.status=null,this.active=!1,this.refreshTimer=null,this.searchQuery=``,this.panelMode=`changes`,this.collapsedSections=new Set,this.selection={commitHash:null,path:null,scope:null,source:`workspace`},this.pendingActionKey=null,this.history={commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}_handlePanelModeClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-panel-mode]`):null;if(t){let e=t.getAttribute(`data-git-panel-mode`);return(e===`changes`||e===`history`)&&this.setMode(e),!0}return!1}_handleSectionToggleClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-section-toggle]`):null;return t?(this.toggleSection(t.getAttribute(`data-git-section-toggle`)),!0):!1}_handleCommitHistoryClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-commit-hash]`):null;if(t&&!e.target.closest(`[data-git-history-load-more]`)){let e=t.getAttribute(`data-git-commit-hash`);return e&&this.onSelectCommit(e,{path:this.selection.commitHash===e?this.selection.path:null}),!0}return!1}_handleFileSelectionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-path]`):null;if(t&&!e.target.closest(`[data-git-file-action]`)){let e=t.getAttribute(`data-git-path`);return e&&this.onSelectDiff(e,{scope:t.getAttribute(`data-git-scope`)||`working-tree`}),!0}return!1}_handleFileActionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-file-action]`):null;if(t){let n=t.getAttribute(`data-git-file-action`),r=t.getAttribute(`data-git-path`);return n&&r&&(e.preventDefault(),e.stopPropagation(),this.handleFileAction(n,r,t.getAttribute(`data-git-scope`)||`working-tree`)),!0}return!1}_handlePanelClick(e){if(this._handlePanelModeClick(e)||this._handleSectionToggleClick(e)||this._handleCommitHistoryClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-history-load-more]`)){this.loadMoreHistory();return}if(this._handleFileSelectionClick(e))return;let t=e.target instanceof Element?e.target.closest(`[data-git-pull-backup-path]`):null;if(t){let e=t.getAttribute(`data-git-pull-backup-path`);e&&this.onOpenPullBackup(e);return}if(this._handleFileActionClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-view-all]`)){this.onViewAllDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-git-commit-staged]`)){this.handleCommitStaged();return}let n=e.target instanceof Element?e.target.closest(`[data-git-sync-action]`):null;if(n){let e=n.getAttribute(`data-git-sync-action`);(e===`pull`||e===`push`)&&this.handleSyncAction(e)}}initialize(){this.panel?.addEventListener(`click`,e=>{this._handlePanelClick(e)}),this.searchInput?.addEventListener(`input`,e=>{this.searchQuery=String(e.target?.value??``).trim().toLowerCase(),this.render()}),this.syncSearchUi()}setActive(e){let t=!!e;if(!(this.active===t&&(!t||this.refreshTimer||this.panelMode===`history`))){if(this.active=t,!this.active){this.stopStatusPolling();return}this.syncSearchUi(),this.refresh({force:!1,includeHistory:this.panelMode===`history`}),this.panelMode===`changes`?this.ensureStatusPolling():this.stopStatusPolling()}}async setMode(e,{forceHistoryRefresh:t=!1}={}){let n=e===`history`?`history`:`changes`,r=this.panelMode!==n;if(this.panelMode=n,this.syncSearchUi(),this.render(),this.active){if(this.panelMode===`changes`){this.ensureStatusPolling(),r&&await this.refresh({force:!1,includeHistory:!1});return}this.stopStatusPolling(),(t||r||!this.history.loaded)&&await this.refreshHistory({force:t||r})}}setSelection({commitHash:e=null,path:t=null,scope:n=null,source:r=`workspace`}={}){this.selection={commitHash:e,path:t,scope:n,source:r},(r===`commit`||e)&&(this.panelMode=`history`,this.syncSearchUi()),this.render()}toggleSection(e){e&&(this.collapsedSections.has(e)?this.collapsedSections.delete(e):this.collapsedSections.add(e),this.render())}ensureStatusPolling(){this.refreshTimer||!this.active||this.panelMode!==`changes`||(this.refreshTimer=setInterval(()=>{this.refresh({force:!1,includeHistory:!1})},xl))}stopStatusPolling(){clearInterval(this.refreshTimer),this.refreshTimer=null}syncSearchUi(){this.searchInput&&(this.searchInput.setAttribute(`placeholder`,this.panelMode===`history`?`Filter loaded commits...`:`Search changes...`),this.searchInput.setAttribute(`aria-label`,this.panelMode===`history`?`Filter loaded commits`:`Search changed files`))}async refresh({force:e=!1,includeHistory:t=this.panelMode===`history`}={}){let n=await this.refreshStatus({force:e});return t&&n.isGitRepo&&await this.refreshHistory({force:e}),n}async refreshStatus({force:e=!1}={}){if(!this.enabled)return this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status;try{let t=await this.gitApiClient.readStatus({force:e});if(this.status=t,this.pullBackups=[],t.isGitRepo)try{let e=await this.gitApiClient.readPullBackups();this.pullBackups=Array.isArray(e.backups)?e.backups:[]}catch(e){console.error(`[git-panel] Failed to load pull backups:`,e)}else this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0};return this.onRepoChange(!!t.isGitRepo,t),this.render(),t}catch(e){return console.error(`[git-panel] Failed to load git status:`,e),this.toastController?.show(`Failed to load git status`),this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status}}async refreshHistory({force:e=!1}={}){if(!this.status?.isGitRepo)return this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.render(),this.history;if(this.history.loading&&!e)return this.history;this.history={...this.history,error:``,loading:!0,loadingMore:!1},e&&(this.history={...this.history,commits:[],hasMore:!1,loaded:!1,offset:0}),this.render();try{let e=await this.gitApiClient.readHistory({limit:bl,offset:0});return this.history={commits:Array.isArray(e.commits)?e.commits:[],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:Array.isArray(e.commits)?e.commits.length:0},this.render(),this.history}catch(e){return console.error(`[git-panel] Failed to load git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loading:!1,loadingMore:!1},this.render(),this.history}}async loadMoreHistory(){if(!(!this.status?.isGitRepo||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.gitApiClient.readHistory({limit:bl,offset:this.history.offset}),t=Array.isArray(e.commits)?e.commits:[];this.history={commits:[...this.history.commits,...t],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:this.history.offset+t.length},this.render()}catch(e){console.error(`[git-panel] Failed to load more git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loadingMore:!1},this.render()}}}filterFiles(e=[]){return this.searchQuery?e.filter(e=>e.path.toLowerCase().includes(this.searchQuery)||String(e.oldPath||``).toLowerCase().includes(this.searchQuery)):e}filterCommits(e=[]){return this.searchQuery?e.filter(e=>String(e.subject||``).toLowerCase().includes(this.searchQuery)||String(e.shortHash||``).toLowerCase().includes(this.searchQuery)||String(e.authorName||``).toLowerCase().includes(this.searchQuery)):e}async handleFileAction(e,t,n){let r=`${e}:${n}:${t}`;if(this.pendingActionKey!==r){this.pendingActionKey=r,this.render();try{e===`stage`?await this.onStageFile(t,{scope:n}):e===`unstage`?await this.onUnstageFile(t,{scope:n}):e===`reset`&&await this.onResetFile(t,{scope:n})}finally{this.pendingActionKey=null,this.render()}}}async handleCommitStaged(){let e=`commit-staged`;if(this.pendingActionKey!==e){this.pendingActionKey=e,this.render();try{await this.onCommitStaged()}finally{this.pendingActionKey=null,this.render()}}}async handleSyncAction(e){let t=`sync:${e}`;if(this.pendingActionKey!==t){this.pendingActionKey=t,this.render();try{e===`pull`?await this.onPullBranch():e===`push`&&await this.onPushBranch()}finally{this.pendingActionKey=null,this.render()}}}renderSection(e){let t=this.filterFiles(e.files);if(t.length===0)return``;let n=this.collapsedSections.has(e.key);return`
|
|
698
|
-
<section class="git-section">
|
|
699
|
-
<button class="git-section-header" type="button" data-git-section-toggle="${b(e.key)}">
|
|
700
|
-
${wl(n)}
|
|
701
|
-
${b(e.label)}
|
|
702
|
-
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${t.length}</span>
|
|
703
|
-
</button>
|
|
704
|
-
<div class="git-file-list${n?` hidden`:``}">
|
|
705
|
-
${t.map(e=>this.renderFile(e)).join(``)}
|
|
706
|
-
</div>
|
|
707
|
-
</section>
|
|
708
|
-
`}renderPullBackupsSection(){return!Array.isArray(this.pullBackups)||this.pullBackups.length===0?``:`
|
|
709
|
-
<section class="git-section">
|
|
710
|
-
<button class="git-section-header" type="button" data-git-section-toggle="pull-backups">
|
|
711
|
-
${wl(this.collapsedSections.has(`pull-backups`))}
|
|
712
|
-
Pull Backups
|
|
713
|
-
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${this.pullBackups.length}</span>
|
|
714
|
-
</button>
|
|
715
|
-
<div class="git-file-list${this.collapsedSections.has(`pull-backups`)?` hidden`:``}">
|
|
716
|
-
${this.pullBackups.map(e=>this.renderPullBackup(e)).join(``)}
|
|
717
|
-
</div>
|
|
718
|
-
</section>
|
|
719
|
-
`}renderPullBackup(e){let t=String(e?.createdAt||``).replace(`T`,` `).replace(/\.\d+Z?$/u,`Z`),n=Number(e?.fileCount||0);return`
|
|
720
|
-
<div class="ui-item-row git-file-row">
|
|
721
|
-
<button
|
|
722
|
-
class="ui-item-main git-file-item"
|
|
723
|
-
type="button"
|
|
724
|
-
data-git-pull-backup-path="${b(e.summaryPath||``)}"
|
|
725
|
-
>
|
|
726
|
-
${Sl()}
|
|
727
|
-
<span class="ui-item-copy git-file-copy">
|
|
728
|
-
<span class="ui-item-title git-file-name">Pull backup ${b(e.id||``)}</span>
|
|
729
|
-
<span class="ui-item-subtitle git-file-path">${b(`${t} · ${e.branch||`HEAD`} · ${n} file${n===1?``:`s`}`)}</span>
|
|
730
|
-
</span>
|
|
731
|
-
<span class="ui-status-badge ui-status-badge--warning">BK</span>
|
|
732
|
-
</button>
|
|
733
|
-
</div>
|
|
734
|
-
`}renderFile(e){let t=this.selection.source===`workspace`&&this.selection.path===e.path&&this.selection.scope===e.scope,n=M(e.path),r=w(e.path),i=String(e.path||``),a=El(e.status),o=e.scope===`staged`?{label:`Unstage`,value:`unstage`}:{label:`Stage`,value:`stage`},s=`${o.value}:${e.scope}:${e.path}`,c=this.pendingActionKey===s,l=`reset:${e.scope}:${e.path}`,u=this.pendingActionKey===l;return`
|
|
735
|
-
<div class="ui-item-row git-file-row${t?` active`:``}">
|
|
736
|
-
<button
|
|
737
|
-
class="ui-item-main git-file-item${t?` active`:``}"
|
|
738
|
-
type="button"
|
|
739
|
-
data-git-path="${b(e.path)}"
|
|
740
|
-
data-git-scope="${b(e.scope)}"
|
|
741
|
-
title="${b(i)}"
|
|
742
|
-
>
|
|
743
|
-
${Sl()}
|
|
744
|
-
<span class="ui-item-copy git-file-copy">
|
|
745
|
-
<span class="ui-item-title git-file-name">${b(r)}</span>
|
|
746
|
-
${n?`<span class="ui-item-subtitle git-file-path">${b(n)}</span>`:``}
|
|
747
|
-
</span>
|
|
748
|
-
<span class="ui-status-badge ${a}">${b(e.code)}</span>
|
|
749
|
-
</button>
|
|
750
|
-
<div class="ui-item-actions git-file-actions">
|
|
751
|
-
<button
|
|
752
|
-
class="ui-icon-button ui-action-icon ui-action-icon--surface"
|
|
753
|
-
type="button"
|
|
754
|
-
data-git-file-action="reset"
|
|
755
|
-
data-git-path="${b(e.path)}"
|
|
756
|
-
data-git-scope="${b(e.scope)}"
|
|
757
|
-
aria-label="Reset ${b(r)}"
|
|
758
|
-
title="Reset to current branch"
|
|
759
|
-
${u?`disabled`:``}
|
|
760
|
-
>
|
|
761
|
-
${u?`...`:Tl(`reset`)}
|
|
762
|
-
</button>
|
|
763
|
-
<button
|
|
764
|
-
class="ui-icon-button ui-action-icon ui-action-icon--surface"
|
|
765
|
-
type="button"
|
|
766
|
-
data-git-file-action="${o.value}"
|
|
767
|
-
data-git-path="${b(e.path)}"
|
|
768
|
-
data-git-scope="${b(e.scope)}"
|
|
769
|
-
aria-label="${b(o.label)} ${b(r)}"
|
|
770
|
-
title="${b(o.label)}"
|
|
771
|
-
${c?`disabled`:``}
|
|
772
|
-
>
|
|
773
|
-
${c?`...`:Tl(o.value)}
|
|
774
|
-
</button>
|
|
775
|
-
</div>
|
|
776
|
-
</div>
|
|
777
|
-
`}renderPanelModes(){return`
|
|
778
|
-
<div class="${Ss({pill:!0,extra:`git-panel-mode-switch`})}" role="tablist" aria-label="Git panel modes">
|
|
779
|
-
<button
|
|
780
|
-
class="${Cs({active:this.panelMode===`changes`,extra:`git-panel-mode-btn`})}"
|
|
781
|
-
type="button"
|
|
782
|
-
data-git-panel-mode="changes"
|
|
783
|
-
aria-selected="${this.panelMode===`changes`}"
|
|
784
|
-
>
|
|
785
|
-
Changes
|
|
786
|
-
</button>
|
|
787
|
-
<button
|
|
788
|
-
class="${Cs({active:this.panelMode===`history`,extra:`git-panel-mode-btn`})}"
|
|
789
|
-
type="button"
|
|
790
|
-
data-git-panel-mode="history"
|
|
791
|
-
aria-selected="${this.panelMode===`history`}"
|
|
792
|
-
>
|
|
793
|
-
History
|
|
794
|
-
</button>
|
|
795
|
-
</div>
|
|
796
|
-
`}renderHistoryRow(e){let t=this.selection.source===`commit`&&this.selection.commitHash===e.hash,n=Number(e.filesChanged||0);return`
|
|
797
|
-
<button
|
|
798
|
-
class="ui-record-surface git-history-row${t?` active`:``}"
|
|
799
|
-
type="button"
|
|
800
|
-
data-git-commit-hash="${b(e.hash||``)}"
|
|
801
|
-
title="${b(e.authoredAt||``)}"
|
|
802
|
-
>
|
|
803
|
-
<span class="ui-record-header git-history-row-top">
|
|
804
|
-
<span class="ui-record-title git-history-subject">${Ol(e)}</span>
|
|
805
|
-
<span class="ui-pill-badge ui-pill-badge--code git-history-hash">${b(e.shortHash||``)}</span>
|
|
806
|
-
</span>
|
|
807
|
-
<span class="ui-record-meta git-history-row-meta">
|
|
808
|
-
<span>${b(e.authorName||`Unknown`)}</span>
|
|
809
|
-
<span>${b(e.relativeDateLabel||``)}</span>
|
|
810
|
-
<span>${n} file${n===1?``:`s`}</span>
|
|
811
|
-
${e.isMergeCommit?`<span>Merge</span>`:``}
|
|
812
|
-
</span>
|
|
813
|
-
<span class="ui-record-meta git-history-row-stats">
|
|
814
|
-
<span class="git-change-add">+${Number(e.additions||0)}</span>
|
|
815
|
-
<span class="git-change-del">-${Number(e.deletions||0)}</span>
|
|
816
|
-
</span>
|
|
817
|
-
</button>
|
|
818
|
-
`}renderHistoryPanel(){let e=this.filterCommits(this.history.commits);return this.history.loading&&!this.history.loaded?`<div class="git-panel-empty">Loading git history...</div>`:this.history.error&&!this.history.loaded?`<div class="git-panel-empty">${b(this.history.error)}</div>`:this.history.loaded&&e.length===0&&this.history.commits.length===0?`<div class="git-panel-empty">No commits yet on this branch.</div>`:this.history.loaded&&e.length===0?`<div class="git-panel-empty">No loaded commits match your filter.</div>`:`
|
|
819
|
-
<div class="git-history-list">
|
|
820
|
-
${e.map(e=>this.renderHistoryRow(e)).join(``)}
|
|
821
|
-
</div>
|
|
822
|
-
${this.history.hasMore?`
|
|
823
|
-
<div class="git-history-footer">
|
|
824
|
-
<button
|
|
825
|
-
class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
|
|
826
|
-
type="button"
|
|
827
|
-
data-git-history-load-more
|
|
828
|
-
${this.history.loadingMore?`disabled`:``}
|
|
829
|
-
>
|
|
830
|
-
${this.history.loadingMore?`Loading...`:`Load More`}
|
|
831
|
-
</button>
|
|
832
|
-
</div>
|
|
833
|
-
`:``}
|
|
834
|
-
`}renderChangesPanel(){let e=this.renderPullBackupsSection(),t=(this.status.sections??[]).map(e=>this.renderSection(e)).filter(Boolean).join(``),n=!!this.status.summary?.changedFiles,r=Number(this.status.summary?.staged||0)>0,i=this.pendingActionKey===`commit-staged`;return`
|
|
835
|
-
${e}
|
|
836
|
-
${t||`<div class="git-panel-empty">No local changes</div>`}
|
|
837
|
-
${n?`
|
|
838
|
-
<div class="git-panel-footer">
|
|
839
|
-
<div class="git-panel-footer-actions">
|
|
840
|
-
<button class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0})}" type="button" data-git-view-all>
|
|
841
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M2 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
|
|
842
|
-
View Full Diff
|
|
843
|
-
</button>
|
|
844
|
-
<button
|
|
845
|
-
class="${U({variant:`primary`,action:!0,wide:!0,extra:`git-footer-commit-btn`})}"
|
|
846
|
-
type="button"
|
|
847
|
-
data-git-commit-staged
|
|
848
|
-
${!r||i?`disabled`:``}
|
|
849
|
-
>
|
|
850
|
-
${i?`Working...`:`Commit Staged`}
|
|
851
|
-
</button>
|
|
852
|
-
</div>
|
|
853
|
-
</div>
|
|
854
|
-
`:``}
|
|
855
|
-
`}renderEmpty(e){this.panel&&(this.panel.innerHTML=`
|
|
856
|
-
<div class="git-panel-empty ui-empty-state ui-empty-state--compact">
|
|
857
|
-
<p class="ui-empty-state-copy">${b(e)}</p>
|
|
858
|
-
</div>
|
|
859
|
-
`)}render(){if(!this.panel)return;if(!this.status){this.renderEmpty(`Loading git status...`);return}if(!this.status.isGitRepo){this.renderEmpty(`Git is unavailable for this vault.`);return}let e=this.status.branch??{},t=!!e.upstream,n=this.pendingActionKey===`sync:pull`,r=this.pendingActionKey===`sync:push`;this.panel.innerHTML=`
|
|
860
|
-
<div class="git-branch-bar">
|
|
861
|
-
<div class="git-branch-meta">
|
|
862
|
-
<span class="git-branch-name">
|
|
863
|
-
${Cl()}
|
|
864
|
-
${b(e.name||`HEAD`)}
|
|
865
|
-
</span>
|
|
866
|
-
${Dl(this.status.summary,e)}
|
|
867
|
-
</div>
|
|
868
|
-
<div class="git-branch-actions" role="group" aria-label="Remote sync actions">
|
|
869
|
-
<button
|
|
870
|
-
class="${U({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
|
|
871
|
-
type="button"
|
|
872
|
-
data-git-sync-action="pull"
|
|
873
|
-
title="${t?`Pull remote changes (fast-forward only)`:`No upstream branch configured`}"
|
|
874
|
-
aria-label="Pull branch"
|
|
875
|
-
${!t||n?`disabled`:``}
|
|
876
|
-
>
|
|
877
|
-
${n?`...`:`${Tl(`pull`)}<span>Pull</span>`}
|
|
878
|
-
</button>
|
|
879
|
-
<button
|
|
880
|
-
class="${U({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
|
|
881
|
-
type="button"
|
|
882
|
-
data-git-sync-action="push"
|
|
883
|
-
title="${t?`Push local commits`:`No upstream branch configured`}"
|
|
884
|
-
aria-label="Push branch"
|
|
885
|
-
${!t||r?`disabled`:``}
|
|
886
|
-
>
|
|
887
|
-
${r?`...`:`${Tl(`push`)}<span>Push</span>`}
|
|
888
|
-
</button>
|
|
889
|
-
</div>
|
|
890
|
-
${this.renderPanelModes()}
|
|
891
|
-
</div>
|
|
892
|
-
${this.panelMode===`history`?this.renderHistoryPanel():this.renderChangesPanel()}
|
|
893
|
-
`}},Al=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onMeasureEditor:t,onViewRequest:n=null}){this.mobileBreakpointQuery=e,this.onMeasureEditor=t,this.onViewRequest=n,this.preferredView=`split`,this.mobileShowsEditor=!this.isMobileViewport(),this.currentView=this.mobileShowsEditor?this.preferredView:`preview`,this.editorLayout=document.getElementById(`editorLayout`),this.editorPane=document.getElementById(`editorPane`),this.previewPane=document.getElementById(`previewPane`),this.mobileToggleButton=document.getElementById(`mobileViewToggle`),this.resizer=document.getElementById(`resizer`),this.viewButtons=Array.from(document.querySelectorAll(`.view-btn`))}isMobileViewport(){return this.mobileBreakpointQuery.matches}initialize(){this.viewButtons.forEach(e=>{e.addEventListener(`click`,()=>{this.onViewRequest?.(e.dataset.view)!==!1&&this.setView(e.dataset.view)})}),this.mobileToggleButton?.addEventListener(`click`,()=>this.toggleMobileView()),this.initializeResizer(),this.restorePreferredView()}primeView(e){if(e){if(this.isMobileViewport()){this.mobileShowsEditor=e!==`preview`;return}this.preferredView=e}}reset(){this.restorePreferredView(),this.editorPane&&(this.editorPane.style.flex=``),this.previewPane&&(this.previewPane.style.flex=``),this.updateResizerValue()}restorePreferredView(){let e=this.isMobileViewport()?this.mobileShowsEditor?`split`:`preview`:this.preferredView;this.applyView(e),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`)}applyView(e){this.currentView=e,this.editorLayout?.setAttribute(`data-view`,e),this.syncViewButtons()}setView(e,{persist:t=!0}={}){e&&(t&&(this.preferredView=e),this.applyView(e),(e===`split`||e===`editor`)&&this.scheduleEditorMeasure())}toggleMobileView(){let e=!this.mobileShowsEditor,t=e?`split`:`preview`;this.onViewRequest?.(t)!==!1&&(this.mobileShowsEditor=e,this.applyView(t),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`),this.mobileShowsEditor&&this.scheduleEditorMeasure())}scheduleEditorMeasure(){this.onMeasureEditor&&setTimeout(()=>this.onMeasureEditor(),50)}updateMobileToggleButton(e){this.mobileToggleButton&&(this.mobileToggleButton.innerHTML=`${e===`Editor`?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="8" y1="8" x2="16" y2="8"/><line x1="8" y1="12" x2="14" y2="12"/><line x1="8" y1="16" x2="12" y2="16"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`}<span class="ui-toolbar-button-label">${e}</span>`)}syncViewButtons(){this.viewButtons.forEach(e=>{let t=e.dataset.view===this.currentView;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,String(t))})}updateResizerValue(){if(!this.resizer||!this.editorLayout||!this.editorPane)return;let e=this.editorLayout.offsetWidth;if(!Number.isFinite(e)||e<=0)return;let t=Math.round(this.editorPane.offsetWidth/e*100);this.resizer.setAttribute(`aria-valuenow`,String(Math.max(20,Math.min(80,t))))}applyEditorPaneWidth(e){if(!this.editorLayout||!this.editorPane||!this.previewPane)return;let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(200,Math.min(t-200,e))/t*100;this.editorPane.style.flex=`0 0 ${n}%`,this.previewPane.style.flex=`1`,this.updateResizerValue()}initializeResizer(){if(!this.resizer||!this.editorLayout||!this.editorPane||!this.previewPane)return;let e=!1,t=0,n=0;this.resizer.addEventListener(`mousedown`,r=>{e=!0,t=r.clientX,n=this.editorPane.offsetWidth,this.resizer.classList.add(`dragging`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,r.preventDefault()}),document.addEventListener(`mousemove`,r=>{if(!e)return;let i=r.clientX-t;this.applyEditorPaneWidth(n+i)}),document.addEventListener(`mouseup`,()=>{e&&(e=!1,this.resizer.classList.remove(`dragging`),document.body.style.cursor=``,document.body.style.userSelect=``,this.scheduleEditorMeasure())}),this.resizer.addEventListener(`keydown`,e=>{let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(24,Math.round(t*.05));if(e.key===`ArrowLeft`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth-n),this.scheduleEditorMeasure();return}if(e.key===`ArrowRight`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth+n),this.scheduleEditorMeasure();return}if(e.key===`Home`){e.preventDefault(),this.applyEditorPaneWidth(t*.2),this.scheduleEditorMeasure();return}e.key===`End`&&(e.preventDefault(),this.applyEditorPaneWidth(t*.8),this.scheduleEditorMeasure())}),this.updateResizerValue()}},jl=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onNavigateToHeading:t,onWillOpen:n}={}){this.outlineOpen=!1,this.activeHeadingFrame=null,this.activeHeadingId=null,this.headings=[],this.pinnedHeadingId=null,this.pdfOutline=null,this.onNavigateToPdfOutline=null,this.onNavigateToHeading=t,this.onWillOpen=n,this.panel=document.getElementById(`outlinePanel`),this.closeButton=document.getElementById(`outlineClose`),this.navigation=document.getElementById(`outlineNav`),this.previewContainer=document.getElementById(`previewContainer`),this.toggleButton=document.getElementById(`outlineToggle`),this.mobileBreakpointQuery=e,this.handlePreviewScroll=()=>this.scheduleActiveHeadingUpdate(),this.handleDocumentPointerDown=e=>{if(!this.outlineOpen)return;let t=e.target;t instanceof Node&&(this.panel?.contains(t)||this.toggleButton?.contains(t))||this.close()}}initialize(){this.toggleButton?.addEventListener(`click`,()=>this.toggle()),this.closeButton?.addEventListener(`click`,()=>this.close()),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown)}toggle(){this.setOpenState(!this.outlineOpen)}close(){this.setOpenState(!1)}setOpenState(e){if(e&&!this.outlineOpen&&this.onWillOpen?.(),this.outlineOpen=e,this.panel?.classList.toggle(`hidden`,!this.outlineOpen),this.toggleButton?.classList.toggle(`active`,this.outlineOpen),this.panel?.setAttribute(`aria-hidden`,String(!this.outlineOpen)),this.toggleButton?.setAttribute(`aria-expanded`,String(this.outlineOpen)),this.outlineOpen){this.refresh();return}this.cleanup()}refresh(){if(!this.navigation)return;if(!this.outlineOpen){this.cleanup();return}if(this.pdfOutline){this.renderPdfOutline();return}let e=document.getElementById(`previewContent`)?.querySelectorAll(`h1, h2, h3, h4, h5, h6`)??[];if(e.length===0){this.navigation.innerHTML=`<div class="outline-empty">No headings found</div>`,this.cleanup();return}let t=Array.from(e).map((e,t)=>(e.id||=`heading-${t}-${e.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)}`,{id:e.id,level:Number.parseInt(e.tagName[1],10),sourceLine:Number.parseInt(e.getAttribute(`data-source-line`)||``,10),text:e.textContent.trim()}));this.navigation.innerHTML=t.map(e=>`<button class="outline-item" data-level="${e.level}" data-target="${e.id}"${Number.isFinite(e.sourceLine)?` data-source-line="${e.sourceLine}"`:``} title="${e.text.replace(/"/g,`"`)}">${e.text}</button>`).join(``),this.navigation.querySelectorAll(`.outline-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=document.getElementById(e.dataset.target);this.navigateToHeading(t,e.dataset.target,{behavior:`auto`}),this.mobileBreakpointQuery.matches&&this.close()})}),this.observeHeadings(Array.from(e))}setPdfOutline(e,t){if(this.cleanup(),this.pdfOutline=Array.isArray(e)&&e.length>0?e:null,this.onNavigateToPdfOutline=this.pdfOutline?t:null,this.activeHeadingId=null,this.toggleButton?.classList.toggle(`hidden`,!this.pdfOutline),!this.pdfOutline){this.navigation?.replaceChildren(),this.close();return}this.outlineOpen&&this.renderPdfOutline()}clearPdfOutline(){this.pdfOutline=null,this.onNavigateToPdfOutline=null,this.activeHeadingId=null,this.pinnedHeadingId=null,this.navigation?.replaceChildren(),this.toggleButton?.classList.add(`hidden`),this.close()}renderPdfOutline(){if(!this.navigation||!this.pdfOutline)return;this.cleanup(),this.navigation.replaceChildren();let e=document.createDocumentFragment(),t=0,n=(r,i=1)=>{r.forEach(r=>{if(!r||typeof r!=`object`)return;let a=String(r.title??``).trim();if(a){let n=`pdf-outline-${t}`,o=document.createElement(`button`);o.type=`button`,o.className=`outline-item`,o.dataset.level=String(Math.min(i,6)),o.dataset.target=n,o.title=a,o.textContent=a,o.addEventListener(`click`,()=>{this.setActiveItem(n,{behavior:`auto`}),this.onNavigateToPdfOutline?.(r),this.mobileBreakpointQuery.matches&&this.close()}),e.appendChild(o),t+=1}Array.isArray(r.items)&&n(r.items,Math.min(i+1,6))})};if(n(this.pdfOutline),e.childNodes.length===0){this.navigation.innerHTML=`<div class="outline-empty">No outline found</div>`;return}this.navigation.appendChild(e)}cleanup({preservePinnedHeading:e=!1}={}){this.activeHeadingFrame&&=(cancelAnimationFrame(this.activeHeadingFrame),null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.headings=[],e||(this.pinnedHeadingId=null)}setActiveItem(e,{scrollIntoView:t=!0,behavior:n=`smooth`}={}){this.activeHeadingId=e,this.navigation?.querySelectorAll(`.outline-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.target===e)}),t&&this.navigation?.querySelector(`.outline-item.active`)?.scrollIntoView({behavior:n,block:`nearest`})}observeHeadings(e){if(this.cleanup({preservePinnedHeading:!0}),!this.previewContainer||e.length===0)return;this.headings=e,this.previewContainer.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0});let t=this.getPinnedHeading();if(t){this.setActiveItem(t.id,{behavior:`auto`,scrollIntoView:!0});return}this.updateActiveHeading()}scheduleActiveHeadingUpdate(){this.activeHeadingFrame||=requestAnimationFrame(()=>{this.activeHeadingFrame=null,this.updateActiveHeading()})}updateActiveHeading(){if(!this.previewContainer||this.headings.length===0)return;let e=this.getPinnedHeading();if(e&&this.shouldKeepPinnedHeadingActive(e)){this.setActiveItem(e.id,{behavior:`auto`,scrollIntoView:!0});return}this.pinnedHeadingId=null;let t=this.previewContainer.scrollTop,n=this.headings[0];for(let e of this.headings){if(this.getHeadingScrollTop(e)>t)break;n=e}this.setActiveItem(n.id,{behavior:`auto`,scrollIntoView:!0})}getHeadingScrollTop(e){if(!this.previewContainer)return 0;let t=this.previewContainer.getBoundingClientRect(),n=e.getBoundingClientRect();return this.previewContainer.scrollTop+(n.top-t.top)}getPinnedHeading(){return this.pinnedHeadingId?this.headings.find(e=>e.id===this.pinnedHeadingId)??null:null}shouldKeepPinnedHeadingActive(e){if(!this.previewContainer||!e?.isConnected)return!1;let t=this.getHeadingScrollTop(e)-this.previewContainer.scrollTop,n=t+e.getBoundingClientRect().height,r=this.previewContainer.clientHeight*.45;return n>-48&&t<r}notifyHeadingNavigation(e,t){if(!e)return;let n=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);this.onNavigateToHeading?.({headingId:t,sourceLine:Number.isFinite(n)?n:null})}navigateToHeading(e,t,{behavior:n=`auto`}={}){return!e||!t?!1:(this.pinnedHeadingId=t,this.notifyHeadingNavigation(e,t),this.scrollHeadingIntoView(e,{behavior:n}),this.setActiveItem(t,{behavior:n}),!0)}scrollHeadingIntoView(e,{behavior:t=`smooth`}={}){if(!e||!this.previewContainer)return;let n=this.previewContainer.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.previewContainer.scrollTop+(r.top-n.top);this.previewContainer.scrollTo({behavior:t,top:Math.max(i,0)})}},Ml=.35,Nl=120,Pl=12,Fl=2;function Il(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function Ll(e){return Math.max(e,0)}function Rl(e){return Math.max(e.clientHeight*Ml,Pl)}function zl(e){return(e?.scrollTop??0)<=Fl}function Bl(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function Vl(e){return!e.querySelector(`[data-source-line]`)}var Hl=class{constructor({getEditorLineNumber:e,onEditorScrollActivityChange:t,previewContainer:n,previewElement:r,scrollEditorToLine:i}){this.getEditorLineNumber=e,this.onEditorScrollActivityChange=t,this.previewContainer=n,this.previewElement=r,this.scrollEditorToLine=i,this.editorScroller=null,this.editorScrollActive=!1,this.editorScrollIdleTimer=null,this.lockedElements=new Set,this.pendingSync=null,this.frameId=null,this.previewBlocks=null,this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.largeDocumentMode=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.handleEditorScroll=()=>{if(!(!this.editorScroller||this.lockedElements.has(this.editorScroller)||this.isSuspended())){if(this.lastInteractionSource=`editor`,this.largeDocumentMode){this.setEditorScrollActive(!0),this.scheduleEditorScrollIdle(),this.scheduleSync(this.editorScroller,this.previewContainer,{preferApproximateMapping:!0});return}this.scheduleSync(this.editorScroller,this.previewContainer)}},this.handlePreviewScroll=()=>{!this.previewContainer||this.lockedElements.has(this.previewContainer)||this.isSuspended()||(this.lastInteractionSource=`preview`,this.scheduleSync(this.previewContainer,this.editorScroller))}}initialize(){this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0})}attachEditorScroller(e){this.editorScroller!==e&&(this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=e,this.editorScroller?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}))}syncPreviewToEditor(){this.lastInteractionSource=`editor`,this.sync(this.editorScroller,this.previewContainer)}syncEditorToPreview(){this.lastInteractionSource=`preview`,this.sync(this.previewContainer,this.editorScroller)}destroy(){this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=null,clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.pendingSync=null,this.previewBlocks=null,L(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.lockedElements.clear(),this.editorScrollActive=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.frameId&&=(cancelAnimationFrame(this.frameId),null)}scheduleSync(e,t,{preferApproximateMapping:n=!1}={}){!e||!t||this.lockedElements.has(e)||this.isSuspended()||(this.pendingSync={preferApproximateMapping:n,source:e,target:t},!this.frameId&&(this.frameId=requestAnimationFrame(()=>{if(this.frameId=null,!this.pendingSync)return;let{preferApproximateMapping:e,source:t,target:n}=this.pendingSync;this.pendingSync=null,this.sync(t,n,{preferApproximateMapping:e})})))}invalidatePreviewBlocks(){this.previewBlocks=null,L(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[]}setLargeDocumentMode(e){this.largeDocumentMode=!!e,this.largeDocumentMode||(clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1))}warmPreviewBlocks({onReady:e}={}){if(typeof e==`function`&&(this.previewBlocks?e(this.previewBlocks):this.previewBlocksReadyCallbacks.push(e)),!this.largeDocumentMode){this.previewBlocks||=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks();return}this.previewBlocks||this.previewBlocksWarmId!==null||(this.previewBlocksWarmId=Te(()=>{this.previewBlocksWarmId=null,this.previewBlocks=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks()},500))}realignAfterLayoutChange(){let e=()=>{if(this.lastInteractionSource===`preview`){this.syncEditorToPreview();return}this.syncPreviewToEditor()};if(this.largeDocumentMode&&!this.previewBlocks){this.warmPreviewBlocks({onReady:()=>e()});return}e()}suspendSync(e=250){this.suspendedUntil=performance.now()+e}isSuspended(){return performance.now()<this.suspendedUntil}flushPreviewBlocksReadyCallbacks(){this.previewBlocksReadyCallbacks.length!==0&&this.previewBlocksReadyCallbacks.splice(0).forEach(e=>{try{e(this.previewBlocks??[])}catch(e){console.warn(`[scroll-sync] Preview block callback failed:`,e)}})}setEditorScrollActive(e){this.editorScrollActive!==e&&(this.editorScrollActive=e,this.onEditorScrollActivityChange?.(e))}scheduleEditorScrollIdle(){clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=setTimeout(()=>{this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1),this.syncPreviewToEditor()},Nl)}sync(e,t,{preferApproximateMapping:n=!1}={}){if(!e||!t||this.lockedElements.has(e)||this.isSuspended())return;if(!n&&e===this.editorScroller&&t===this.previewContainer){let e=this.getPreviewScrollTopForEditorLine();if(e!==null){this.setScrollTop(t,e);return}}if(e===this.previewContainer&&t===this.editorScroller){let e=this.getEditorLineNumberForPreviewScroll();if(e!==null){this.lockedElements.add(t),this.scrollEditorToLine?.(e,Ml),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=Il(e),i=Il(t),a=r>0?e.scrollTop/r:0,o=i>0?i*a:0;this.setScrollTop(t,o)}setScrollTop(e,t){this.lockedElements.add(e),e.scrollTop=Ll(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if(zl(this.editorScroller))return 0;let e=this.getEditorLineNumber?.();if(!Number.isFinite(e))return null;let t=this.getPreviewBlocks();if(t.length===0||!this.previewContainer)return null;let{block:n,index:r}=this.findBlockForLine(t,e),i=this.getPreviewSpan(t,r),a=Math.max(n.end-n.start,1),o=x((e-n.start)/a,0,1),s=Il(this.previewContainer),c=Rl(this.previewContainer);return x(n.top+i*o-c,0,s)}getEditorLineNumberForPreviewScroll(){if(!this.previewContainer)return null;let e=this.getPreviewBlocks();if(e.length===0)return null;let t=this.previewContainer.scrollTop+Rl(this.previewContainer),{block:n,index:r}=this.findBlockForScrollTop(e,t),i=this.getPreviewSpan(e,r),a=Math.max(n.end-n.start,1),o=i>0?x((t-n.top)/i,0,1):0;return Math.round(n.start+a*o)}getPreviewBlocks(){return this.previewBlocks?this.previewBlocks:!this.previewContainer||!this.previewElement||this.largeDocumentMode?[]:(this.previewBlocks=this.buildPreviewBlocks(),this.previewBlocks)}buildPreviewBlocks(){let e=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).map(e=>{let t=Number.parseInt(e.getAttribute(`data-source-line`)||``,10),n=Number.parseInt(e.getAttribute(`data-source-line-end`)||``,10);return Number.isFinite(t)?{element:e,end:Number.isFinite(n)?Math.max(n,t+1):t+1,start:t,top:Bl(this.previewContainer,e)}:null}).filter(Boolean).sort((e,t)=>e.top-t.top||e.start-t.start||e.end-t.end),t=e.filter(e=>Vl(e.element)),n=t.length>0?t:e;return n.filter((e,t)=>{let r=n[t-1];return!r||Math.abs(r.top-e.top)>1||r.start!==e.start||r.end!==e.end})}findBlockForLine(e,t){let n=null,r=-1;for(let i=0;i<e.length;i+=1){let a=e[i];if(t>=a.start&&t<a.end){if(!n){n=a,r=i;continue}let e=n.end-n.start,t=a.end-a.start;(t<e||t===e&&a.start>=n.start)&&(n=a,r=i)}}if(n)return{block:n,index:r};let i=0;for(let n=0;n<e.length&&!(e[n].start>t);n+=1)i=n;return{block:e[i],index:i}}findBlockForScrollTop(e,t){for(let n=0;n<e.length;n+=1)if(t<this.getPreviewSpan(e,n)+e[n].top)return{block:e[n],index:n};let n=e.length-1;return{block:e[n],index:n}}getPreviewSpan(e,t){if(!this.previewContainer)return 1;let n=e[t],r=e[t+1],i=n.element.getBoundingClientRect().height;if(!r){let e=Il(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},Ul=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>`,Wl=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,Gl=class{constructor({storageKey:e=`collabmd-theme`,onChange:t}){this.storageKey=e,this.onChange=t,this.currentTheme=`dark`}initialize(){this.currentTheme=this.readPreferredTheme(),this.applyTheme(),document.querySelectorAll(`[data-theme-toggle]`).forEach(e=>{e.addEventListener(`click`,()=>this.toggle())})}getTheme(){return this.currentTheme}toggle(){this.currentTheme=this.currentTheme===`dark`?`light`:`dark`,this.persistTheme(),this.applyTheme()}readPreferredTheme(){try{let e=window.localStorage.getItem(this.storageKey);if(e===`light`||e===`dark`)return e}catch{}return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}persistTheme(){try{window.localStorage.setItem(this.storageKey,this.currentTheme)}catch{}}applyTheme(){document.documentElement.setAttribute(`data-theme`,this.currentTheme),this.updateToggleIcons(),this.onChange?.(this.currentTheme)}updateToggleIcons(){let e=this.currentTheme===`dark`?`Dark`:`Light`,t=this.currentTheme===`dark`?`light`:`dark`,n=this.currentTheme===`dark`?Wl:Ul;document.querySelectorAll(`[data-theme-toggle]`).forEach(r=>{let i=r.querySelector(`[data-theme-toggle-icon]`),a=r.querySelector(`[data-theme-toggle-state]`);i?i.innerHTML=n:r.innerHTML=n,a&&(a.textContent=e,a.dataset.theme=this.currentTheme),r.setAttribute(`aria-label`,`Theme: ${e}. Switch to ${t} mode`),r.setAttribute(`title`,`Theme: ${e}. Switch to ${t} mode`)})}},Kl=class{constructor(e){this.container=e}show(e,t=3e3){if(!this.container)return null;let n=typeof t==`number`?{duration:t}:{...t??{}},r=Number(n.duration)>0?Number(n.duration):0,i=document.createElement(`div`);i.className=`toast`,typeof n.tone==`string`&&n.tone&&(i.dataset.tone=n.tone);let a=document.createElement(`span`);a.className=`toast__message`,a.textContent=e,i.appendChild(a);let o=()=>{!i.isConnected||i.classList.contains(`leaving`)||(i.classList.add(`leaving`),i.addEventListener(`animationend`,()=>i.remove(),{once:!0}))};if(n.actionLabel&&typeof n.onAction==`function`){let e=document.createElement(`button`);e.className=`toast__action`,e.type=`button`,e.textContent=n.actionLabel,e.addEventListener(`click`,()=>{n.onAction(),n.closeOnAction!==!1&&o()}),i.appendChild(e)}if(n.dismissible){let e=document.createElement(`button`);e.className=`toast__dismiss`,e.type=`button`,e.setAttribute(`aria-label`,`Dismiss notification`),e.textContent=`Close`,e.addEventListener(`click`,o),i.appendChild(e)}return this.container.appendChild(i),r>0&&setTimeout(o,r),i}},ql=16/9,Jl=240,Yl=720,Xl=180;function Zl(e){return Math.max(Xl,Math.min(Yl,Math.ceil(e||Jl)))}var Ql=class{constructor({previewElement:e}){this.previewElement=e,this.embedEntries=new Map,this.overlayRoot=null}destroy(){this.embedEntries.forEach(e=>{e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){this.embedEntries.forEach(e=>{e.placeholder=null})}reconcileEmbeds(e=this.previewElement){if(this.previewElement=e,!e)return;let t=Array.from(e.querySelectorAll(`.video-embed-placeholder[data-video-embed-key]`)).map(e=>({filePath:e.dataset.videoEmbedSource,key:e.dataset.videoEmbedKey,label:e.dataset.videoEmbedLabel||`Embedded video`,placeholder:e,source:e.dataset.videoEmbedSource||``,kind:e.dataset.videoEmbedKind||``,url:e.dataset.videoEmbedUrl||``,mimeType:e.dataset.videoEmbedMimeType||``})),{nextEntries:n,removedEntries:r}=Lc(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||ql,e.kind=e.placeholder?.dataset.videoEmbedKind||e.kind,e.label=e.placeholder?.dataset.videoEmbedLabel||e.label,e.mimeType=e.placeholder?.dataset.videoEmbedMimeType||e.mimeType,e.source=e.placeholder?.dataset.videoEmbedSource||e.source,e.url=e.placeholder?.dataset.videoEmbedUrl||e.url,e.wrapper||this._createEmbed(e),this._attachWrapper(e)}),this.syncLayout(),this.embedEntries.size===0&&(this.overlayRoot?.remove(),this.overlayRoot=null)}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&this._syncEntryLayout(e)})}_destroyEntry(e){e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}_createEmbed(e){let t=document.createElement(`div`);if(t.className=`video-embed video-embed-shell diagram-preview-shell is-${e.kind}`,e.kind===`youtube`){let n=document.createElement(`div`);n.className=`video-embed-frame video-embed-frame-youtube`;let r=document.createElement(`iframe`);r.className=`video-embed-iframe`,r.title=e.label||`Embedded YouTube video`,r.referrerPolicy=`strict-origin-when-cross-origin`,r.allow=`accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share`,r.allowFullscreen=!0,n.appendChild(r),t.appendChild(n),e.mediaElement=r}else{let n=document.createElement(`video`);n.className=`video-embed-player`,n.controls=!0,n.preload=`metadata`,n.playsInline=!0,e.label&&(n.title=e.label,n.setAttribute(`aria-label`,e.label));let r=document.createElement(`source`);r.src=e.url,e.mimeType&&(r.type=e.mimeType),n.appendChild(r),n.addEventListener(`loadedmetadata`,()=>{Number.isFinite(n.videoWidth)&&Number.isFinite(n.videoHeight)&&n.videoWidth>0&&n.videoHeight>0&&(e.aspectRatio=n.videoWidth/n.videoHeight,this._syncEntryLayout(e))}),t.appendChild(n),e.mediaElement=n}e.wrapper=t}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.videoEmbedHydrated=`true`,t.style.pointerEvents=`none`;let n=this._ensureOverlayRoot();e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper)}_syncEntryLayout(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t||!e.wrapper)return;e.placeholder=t;let n=t.offsetWidth||t.clientWidth||0;if(n<=0&&e.inlineHeightPx)return;let r=Zl(n>0?n/(e.aspectRatio||ql):e.inlineHeightPx);e.inlineHeightPx=r,Q(t,`height`,`${r}px`),Q(e.wrapper,`position`,`absolute`),Q(e.wrapper,`top`,`${t.offsetTop}px`),Q(e.wrapper,`left`,`${t.offsetLeft}px`),Q(e.wrapper,`width`,`${t.offsetWidth}px`),Q(e.wrapper,`height`,`${r}px`),Q(e.wrapper,`margin`,`0`),Q(e.wrapper,`pointerEvents`,`auto`),this._hydrateEntryMedia(e)}_ensureOverlayRoot(){let e=this.previewElement?.querySelector(`[data-video-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.videoOverlayRoot=`true`,e.className=`video-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_hydrateEntryMedia(e){if(e.kind!==`youtube`)return;let t=e.mediaElement;t instanceof HTMLIFrameElement&&(!e.url||t.getAttribute(`src`)===e.url||e.wrapper?.offsetWidth<=0||e.wrapper?.offsetHeight<=0||(e.hydrateFrameId||=requestAnimationFrame(()=>{if(e.hydrateFrameId=null,!e.url||t.getAttribute(`src`)===e.url)return;let n=Math.round(e.wrapper?.offsetWidth||0),r=Math.round(e.wrapper?.offsetHeight||0);n<=0||r<=0||(t.width=String(n),t.height=String(r),t.src=e.url)})))}};function Q(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var $=1,$l=6,eu=.25,tu=2,nu=6;function ru(e){let t=Number(e);return Number.isFinite(t)?Math.min($l,Math.max($,Math.round(t*100)/100)):$}function iu(e,{contentSize:t=0,scale:n=1,viewportSize:r=0}={}){let i=Number(e),a=Number(t),o=Number(n),s=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))return 0;let c=(a*o-s)/2;return c<=0?0:Math.min(Math.max(i,-c),c)}function au(e){return!!e?.ctrlKey}var ou=class{constructor({previewElement:e,documentRef:t=document,windowRef:n=window}){this.previewElement=e,this.document=t,this.window=n,this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.isOpen=!1,this.scale=$,this.offsetX=0,this.offsetY=0,this.activePointerId=null,this.dragStartX=0,this.dragStartY=0,this.dragOriginX=0,this.dragOriginY=0,this.touchPointers=new Map,this.pinchPointerIds=[],this.pinchStartDistance=0,this.pinchStartScale=$,this.pinchStartOffsetX=0,this.pinchStartOffsetY=0,this.pinchStartCenter={x:0,y:0},this.didDrag=!1,this.resetButton=null,this.handlePreviewClick=e=>{let t=e.target;if(!(t instanceof this.window.Element))return;let n=t.closest(`img`);!n||!this.previewElement?.contains(n)||n.closest(`[data-video-overlay-root="true"], [data-excalidraw-overlay-root="true"]`)||(e.preventDefault(),e.stopImmediatePropagation?.(),this.openFromImage(n))},this.handleKeyDown=e=>{if(this.isOpen){if(e.key===`Escape`){e.preventDefault(),this.close();return}if(e.key===`+`||e.key===`=`){e.preventDefault(),this.zoomBy(eu);return}if(e.key===`-`){e.preventDefault(),this.zoomBy(-.25);return}e.key===`0`&&(e.preventDefault(),this.resetView())}},this.handleWindowResize=()=>{this.isOpen&&(this.clampOffsets(),this.syncTransform())},this.previewElement?.addEventListener(`click`,this.handlePreviewClick),this.document.addEventListener(`keydown`,this.handleKeyDown),this.window.addEventListener(`resize`,this.handleWindowResize)}destroy(){this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),this.document.removeEventListener(`keydown`,this.handleKeyDown),this.window.removeEventListener(`resize`,this.handleWindowResize),this.close(),this.overlayRoot?.remove(),this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.resetButton=null}openFromImage(e){let t=e?.currentSrc||e?.getAttribute?.(`src`)||``;return t?(this.ensureOverlayRoot(),this.resetView(),this.titleElement.textContent=e.getAttribute(`alt`)||`Image preview`,this.imageElement.src=t,this.imageElement.alt=e.getAttribute(`alt`)||``,this.overlayRoot.hidden=!1,this.isOpen=!0,this.document.body.classList.add(`image-lightbox-open`),this.syncTransform(),this.overlayRoot.focus?.(),!0):!1}close(){!this.isOpen&&!this.overlayRoot||(this.stopDrag(),this.touchPointers.clear(),this.pinchPointerIds=[],this.pinchStartDistance=0,this.didDrag=!1,this.viewport?.classList?.remove(`is-dragging`),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.isOpen=!1,this.document.body.classList.remove(`image-lightbox-open`))}resetView(){this.scale=$,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=ru(e),this.clampOffsets(),this.syncTransform()}capturePointer(e){try{this.viewport?.setPointerCapture?.(e)}catch{}}releasePointer(e){try{this.viewport?.releasePointerCapture?.(e)}catch{}}getViewportPointFromClient(e,t){if(!this.viewport)return{x:0,y:0};let n=this.viewport.getBoundingClientRect();return{x:Number(e)-n.left-n.width/2,y:Number(t)-n.top-n.height/2}}setScaleAroundViewportPoint(e,t,{originScale:n=this.scale,originOffsetX:r=this.offsetX,originOffsetY:i=this.offsetY,targetViewportPoint:a=t}={}){let o=ru(e),s=Number(n)>0?Number(n):$,c=Number.isFinite(t?.x)?t.x:0,l=Number.isFinite(t?.y)?t.y:0,u=Number.isFinite(a?.x)?a.x:c,d=Number.isFinite(a?.y)?a.y:l;this.scale=o,this.offsetX=u-(c-r)/s*o,this.offsetY=d-(l-i)/s*o,this.clampOffsets(),this.syncTransform()}startDrag(e,t,n){return!this.viewport||this.scale<=$?!1:(this.activePointerId=e,this.dragStartX=t,this.dragStartY=n,this.dragOriginX=this.offsetX,this.dragOriginY=this.offsetY,this.viewport.classList.add(`is-dragging`),this.capturePointer(e),!0)}stopDrag(e=this.activePointerId){e===this.activePointerId&&(this.activePointerId=null),this.viewport?.classList?.remove(`is-dragging`),e!==null&&this.releasePointer(e),this.imageElement&&(this.imageElement.style.cursor=this.scale>$?`grab`:`zoom-in`)}updateDrag(e,t,n){return!this.isOpen||this.activePointerId!==e?!1:(!this.didDrag&&(Math.abs(t-this.dragStartX)>=nu||Math.abs(n-this.dragStartY)>=nu)&&(this.didDrag=!0),this.offsetX=this.dragOriginX+(t-this.dragStartX),this.offsetY=this.dragOriginY+(n-this.dragStartY),this.clampOffsets(),this.syncTransform(),!0)}getTrackedTouchPointers(){return Array.from(this.touchPointers.values())}getActivePinchPointers(){if(this.pinchPointerIds.length===2){let e=this.pinchPointerIds.map(e=>this.touchPointers.get(e)).filter(Boolean);if(e.length===2)return e}return this.getTrackedTouchPointers().slice(0,2)}startPinchGesture(){let[e,t]=this.getActivePinchPointers();if(!e||!t)return!1;this.stopDrag(),this.pinchPointerIds=[e.pointerId,t.pointerId],this.pinchStartDistance=Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)||1,this.pinchStartScale=this.scale,this.pinchStartOffsetX=this.offsetX,this.pinchStartOffsetY=this.offsetY;let n=this.getViewportPointFromClient((e.clientX+t.clientX)/2,(e.clientY+t.clientY)/2);return this.pinchStartCenter=n,!0}updatePinchGesture(){let[e,t]=this.getActivePinchPointers();if(!e||!t)return!1;let n=Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY);if(!Number.isFinite(n)||n<=0)return!1;let r=this.getViewportPointFromClient((e.clientX+t.clientX)/2,(e.clientY+t.clientY)/2),i=this.pinchStartScale*(n/this.pinchStartDistance);return this.setScaleAroundViewportPoint(i,this.pinchStartCenter,{originScale:this.pinchStartScale,originOffsetX:this.pinchStartOffsetX,originOffsetY:this.pinchStartOffsetY,targetViewportPoint:r}),!this.didDrag&&(Math.abs(n-this.pinchStartDistance)>=nu||Math.abs(r.x-this.pinchStartCenter.x)>=nu||Math.abs(r.y-this.pinchStartCenter.y)>=nu)&&(this.didDrag=!0),!0}syncTouchGestureAfterPointerChange(){if(this.touchPointers.size>=2){this.startPinchGesture();return}if(this.pinchPointerIds=[],this.pinchStartDistance=0,this.touchPointers.size===1&&this.scale>$){let[e]=this.getTrackedTouchPointers();this.startDrag(e.pointerId,e.clientX,e.clientY);return}this.stopDrag()}clampOffsets(){if(!this.viewport||!this.imageElement){this.offsetX=0,this.offsetY=0;return}this.offsetX=iu(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=iu(this.offsetY,{contentSize:this.imageElement.offsetHeight||0,scale:this.scale,viewportSize:this.viewport.clientHeight||0})}syncTransform(){this.imageElement&&(this.imageElement.style.transform=`translate3d(${this.offsetX}px, ${this.offsetY}px, 0) scale(${this.scale})`,this.imageElement.style.cursor=this.scale>$?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=$&&this.offsetX===0&&this.offsetY===0))}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.document.body)return this.overlayRoot;let e=this.document.createElement(`div`);e.className=`image-lightbox-root`,e.dataset.imageLightboxRoot=`true`,e.hidden=!0,e.tabIndex=-1;let t=this.document.createElement(`button`);t.className=`image-lightbox-backdrop`,t.type=`button`,t.setAttribute(`aria-label`,`Close image preview`),t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.close()});let n=this.document.createElement(`div`);n.className=`image-lightbox-shell`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,`Image preview`),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=this.document.createElement(`div`);r.className=`image-lightbox-toolbar`;let i=this.document.createElement(`div`);i.className=`image-lightbox-title`,i.textContent=`Image preview`;let a=this.document.createElement(`div`);a.className=`image-lightbox-controls`;let o=this.createControlButton(`-`,`Zoom out`,()=>this.zoomBy(-.25)),s=this.document.createElement(`span`);s.className=`image-lightbox-zoom-label`,s.textContent=`100%`;let c=this.createControlButton(`+`,`Zoom in`,()=>this.zoomBy(eu)),l=this.createControlButton(`Reset`,`Reset zoom and position`,()=>this.resetView()),u=this.createControlButton(`Close`,`Close image preview`,()=>this.close());a.append(o,s,c,l,u),r.append(i,a);let d=this.document.createElement(`div`);d.className=`image-lightbox-viewport`;let f=this.document.createElement(`img`);f.className=`image-lightbox-image`,f.alt=``,f.addEventListener(`load`,()=>{this.clampOffsets(),this.syncTransform()}),d.addEventListener(`wheel`,e=>{if(!this.isOpen)return;if(au(e)){e.preventDefault(),this.zoomBy(e.deltaY<0?eu:-.25);return}if(this.scale<=$)return;let t=Number.isFinite(e.deltaX)?e.deltaX:0,n=Number.isFinite(e.deltaY)?e.deltaY:0;(t!==0||n!==0)&&(e.preventDefault(),this.offsetX-=t,this.offsetY-=n,this.clampOffsets(),this.syncTransform())},{passive:!1}),d.addEventListener(`pointerdown`,e=>{if(this.isOpen){if(e.pointerType===`touch`){this.touchPointers.size===0&&(this.didDrag=!1),this.touchPointers.set(e.pointerId,{clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId}),this.capturePointer(e.pointerId),this.syncTouchGestureAfterPointerChange(),(this.touchPointers.size>1||this.scale>$)&&e.preventDefault();return}this.scale<=$||e.button!==0||(this.didDrag=!1,this.startDrag(e.pointerId,e.clientX,e.clientY),e.preventDefault())}}),d.addEventListener(`pointermove`,e=>{if(this.isOpen){if(e.pointerType===`touch`&&this.touchPointers.has(e.pointerId)){if(this.touchPointers.set(e.pointerId,{clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId}),this.touchPointers.size>=2){this.updatePinchGesture(),e.preventDefault();return}this.updateDrag(e.pointerId,e.clientX,e.clientY)&&e.preventDefault();return}this.updateDrag(e.pointerId,e.clientX,e.clientY)}});let p=e=>{if(e.pointerType===`touch`){this.touchPointers.delete(e.pointerId),this.releasePointer(e.pointerId),this.activePointerId===e.pointerId&&this.stopDrag(e.pointerId),this.syncTouchGestureAfterPointerChange();return}this.activePointerId===e.pointerId&&this.stopDrag(e.pointerId)};return d.addEventListener(`pointerup`,p),d.addEventListener(`pointercancel`,p),d.addEventListener(`lostpointercapture`,p),f.addEventListener(`click`,e=>{if(this.isOpen){if(e.preventDefault(),e.stopPropagation(),this.didDrag){this.didDrag=!1;return}this.scale<=$&&this.setScale(tu)}}),d.appendChild(f),n.append(r,d),e.append(t,n),this.document.body.appendChild(e),this.overlayRoot=e,this.viewport=d,this.imageElement=f,this.zoomLabel=s,this.titleElement=i,this.resetButton=l,this.syncTransform(),e}createControlButton(e,t,n,{className:r=``}={}){let i=this.document.createElement(`button`);return i.className=`image-lightbox-btn ${r}`.trim(),i.type=`button`,i.setAttribute(`aria-label`,t),i.textContent=e,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(e)}),i}},su=[wn,Tn,Bn,Kn,$n,{...ni,...hi,...lr,...sa,...xi},ca],cu=class{constructor(){for(let e of su)for(let[t,n]of Object.entries(e))t in this||(this[t]=n);this.elements=_n(document),this.runtimeConfig=fe(),this.activeSidebarTab=`files`,this.chatInitialSyncComplete=!1,this.chatIsOpen=!1,this.chatMessageIds=new Set,this.chatMessages=[],this.chatUnreadCount=0,this.connectionHelpShown=!1,this.connectionState={status:`disconnected`,unreachable:!1},this.currentDrawioMode=null,this.currentFilePath=null,this.fileExplorerReady=!1,this.followedCursorSignature=``,this.followedUserClientId=null,this.gitRepoAvailable=!1,this.globalUsers=[],this.isTabActive=!1,this.presencePanelOpen=!1,this.sessionLoadToken=0,this.navigation={getHashRoute:ge,navigateToFile:me,navigateToGitCommit:ue,navigateToGitDiff:P,navigateToGitFileHistory:I,navigateToGitFilePreview:he,navigateToGitHistory:oe},this.preferences=new ga({fileTreeShowExtensionsKey:`collabmd-file-tree-show-extensions`,lineWrappingKey:`collabmd-editor-line-wrap`,recentFilesKey:`collabmd-recent-files`,vimModeKey:`collabmd-editor-vim-mode`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new _a,this.gitApiClient=Sa,this.vaultApiClient=ie,this._session=null,this._hasPromptedForDisplayName=!1,this._basePreviewRenderTimer=null,this._backlinkRefreshTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this._previewLayoutResizeObserver=null,this._previewLayoutSyncTimer=null,this._reloadPromptShown=!1,this._staticPreviewDocument=null,this.pendingGitResetPath=null,this.chatTimeFormatter=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}),this.lobbyChatMessageMaxLength=280,this.quickSwitcher=null,this.quickSwitcherModulePromise=null,this.fileExplorerReadyPromise=Promise.resolve(),this.mobileBreakpointQuery=window.matchMedia(`(max-width: 768px)`),this.pendingWorkspaceRequestIds=new Set,this._fileOpenPerf=null,this.versionMonitor=new ba({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new pa({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Ba({onTreeChange:(e,t={})=>{this.fileExplorer.setTree(e,t),this.handleCommentOverviewWorkspaceTreeChange?.(),this.fileExplorerReady=!0},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new Kl(this.elements.toastContainer),this.chatToastController=new Kl(this.elements.chatToastContainer),this.fileExplorer=new hs({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:!0}),onShowFileExtensionsChange:e=>{this.preferences.setFileTreeShowExtensions(e)},pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,showFileExtensions:this.preferences.getFileTreeShowExtensions(),toastController:this.toastController,vaultClient:this.vaultApiClient}),this.commentsOverview=new Wa({onOverviewChange:(e,{threadCounts:t})=>{this.fileExplorer.setThreadCounts(t)},onThreadSelect:e=>this.openCommentOverviewThread(e),panelElement:this.elements.commentOverviewPanel,toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitPanel=new kl({enabled:this.runtimeConfig.gitEnabled!==!1,gitApiClient:this.gitApiClient,onCommitStaged:()=>this.openGitCommitDialog(),onOpenPullBackup:e=>e&&this.navigation.navigateToFile(e),onPullBranch:()=>this.pullGitBranch(),onPushBranch:()=>this.pushGitBranch(),onRepoChange:(e,t)=>this.handleGitRepoChange(e,t),onResetFile:(e,{scope:t})=>this.openGitResetDialog(e,{scope:t}),onSelectCommit:(e,{path:t})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!0,path:t}),onSelectDiff:(e,{scope:t})=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!0,scope:t}),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),onViewAllDiff:()=>this.handleGitDiffSelection(null,{closeSidebarOnMobile:!0,scope:`all`}),searchInput:this.elements.gitSearchInput,toastController:this.toastController}),this.outlineController=new jl({mobileBreakpointQuery:this.mobileBreakpointQuery,onNavigateToHeading:({sourceLine:e})=>{Number.isFinite(e)&&(this.scrollSyncController.suspendSync(250),this.session?.scrollToLine(e,0))},onWillOpen:()=>this.commentUi?.closeDrawer()}),this.videoEmbed=new Ql({previewElement:this.elements.previewContent}),this.basesPreview=new kc({getActiveFilePath:()=>this.currentFilePath,getSession:()=>this.session,onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewElement:this.elements.previewContent,replaceBaseSource:({path:e,source:t})=>{e&&e===this.currentFilePath&&this.session?.replaceText?.(t)},toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.imageLightbox=new ou({previewElement:this.elements.previewContent}),this.previewRenderer=new tn({getContent:()=>this.getPreviewSource(),getFileList:()=>this.fileExplorer.flatDocumentFiles,getWikiLinkAutoCreate:()=>this.runtimeConfig.wikiLinkAutoCreate!==!1,loadFileSource:async e=>{let t=await this.vaultApiClient.readFile(e);return String(t?.content??``)},getSourceFilePath:()=>this.currentFilePath,onAfterRenderCommit:(e,t)=>{this.recordFileOpenMetric(`preview_committed`,{chars:t?.chars??0,renderVersion:t?.renderVersion??0}),this.videoEmbed.reconcileEmbeds(this.elements.previewContent),this.basesPreview.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.reconcileEmbeds(this.elements.previewContent),this.excalidrawEmbed.reconcileEmbeds(this.elements.previewContent,{isLargeDocument:t.isLargeDocument}),this.scrollSyncController.setLargeDocumentMode(t.isLargeDocument),this.syncPreviewHeadingLinkButtons(),this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!0}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onBeforeRenderCommit:()=>{this.videoEmbed.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit()},onPreviewLayoutChange:()=>{this.scrollSyncController.invalidatePreviewBlocks(),this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!1}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onRenderComplete:()=>{this.applyPendingPreviewRouteAnchor({allowExpired:!0,behavior:`auto`,clearMissing:!0}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.vaultApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.themeController=new Gl({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new Al({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new Hl({getEditorLineNumber:()=>this.session?.getTopVisibleLineNumber(.35)??1,onEditorScrollActivityChange:e=>this.handleEditorScrollActivityChange(e),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,scrollEditorToLine:(e,t)=>this.session?.scrollToLine(e,t)}),this.pdfPreview=new Ct({outlineController:this.outlineController,previewContainer:this.elements.previewContainer}),this.backlinksPanel=new Va({headerPanelElement:this.elements.backlinksHeaderPanel,inlinePanelElement:this.elements.backlinksInlinePanel,loadBacklinks:(e,t={})=>this.vaultApiClient.readBacklinks(e,t),onFileSelect:e=>this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:!0}),panelElement:this.elements.backlinksPanel}),this.excalidrawEmbed=new Kc({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onToggleQuickSwitcher:()=>{this.toggleQuickSwitcher()},previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.drawioEmbed=new Ic({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenTextFile:e=>e&&this.navigation.navigateToFile(e,{drawioMode:`text`}),onToggleQuickSwitcher:()=>{this.toggleQuickSwitcher()},previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.commentUi=new Yo({commentSelectionButton:this.elements.commentSelectionButton,commentsDrawer:this.elements.commentsDrawer,commentsDrawerEmpty:this.elements.commentsDrawerEmpty,commentsDrawerList:this.elements.commentsDrawerList,commentsToggleButton:this.elements.commentsToggleButton,editorContainer:this.elements.editorContainer,onWillOpenDrawer:()=>this.outlineController.close(),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,onCreateThread:({anchor:e,body:t})=>this.createCommentThread({anchor:e,body:t}),onNavigateToLine:e=>{let t=this.session;this.scrollSyncController.suspendSync(250),t?.scrollToLine(e,.2)&&requestAnimationFrame(()=>{this.session===t&&(this.scrollSyncController.suspendSync(0),this.scrollSyncController.syncPreviewToEditor())})},onReplyToThread:(e,t)=>this.replyToCommentThread(e,t),onToggleReaction:(e,t,n)=>this.session?.toggleCommentReaction(e,t,n),onResolveThread:e=>this.resolveCommentThread(e)}),this.structurizrPreview=new pn({enabled:this.runtimeConfig.structurizrEnabled===!0,syncWorkspace:e=>this.vaultApiClient.syncStructurizrWorkspace(e)}),this.workspacePreviewController=new sn({backlinksPanel:this.backlinksPanel,basesPreview:this.basesPreview,drawioEmbed:this.drawioEmbed,elements:this.elements,excalidrawEmbed:this.excalidrawEmbed,getDisplayName:e=>this.getDisplayName(e),getSession:()=>this.session,isBaseFile:e=>this.isBaseFile(e),isDrawioFile:e=>this.isDrawioFile(e),isExcalidrawFile:e=>this.isExcalidrawFile(e),isImageFile:e=>this.isImageFile(e),isPdfFile:e=>this.isPdfFile(e),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),layoutController:this.layoutController,structurizrPreview:this.structurizrPreview,outlineController:this.outlineController,pdfPreview:this.pdfPreview,previewRenderer:this.previewRenderer,schedulePreviewLayoutSync:e=>this.schedulePreviewLayoutSync(e),scrollSyncController:this.scrollSyncController,videoEmbed:this.videoEmbed}),this.wikiLinkFileController=new on({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient,wikiLinkAutoCreate:this.runtimeConfig.wikiLinkAutoCreate!==!1}),this.gitDiffView=new yl({getTheme:()=>this.themeController.getTheme(),gitApiClient:this.gitApiClient,onBackToHistory:({historyFilePath:e}={})=>{if(e){this.navigation.navigateToGitFileHistory({filePath:e});return}this.navigation.navigateToGitHistory()},onCommitStaged:()=>this.openGitCommitDialog(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.fileHistoryView=new xs({diffRenderer:this.gitDiffView,gitApiClient:this.gitApiClient,onOpenCommitDiff:(e,{historyFilePath:t,path:n})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!1,historyFilePath:t,path:n}),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenPreview:({hash:e,path:t,currentFilePath:n})=>this.handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n}),onOpenWorkspaceDiff:e=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!1,scope:`all`}),toastController:this.toastController}),this.tabActivityLock=new Aa({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new gn({attachEditorScroller:e=>this.scrollSyncController.attachEditorScroller(e),beginDocumentLoad:()=>this.previewRenderer.beginDocumentLoad(),cleanupAfterSessionDestroy:()=>{this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.outlineController.cleanup(),this.followedCursorSignature=``,clearTimeout(this._backlinkRefreshTimer)},createEditorSession:(e,t)=>new e({editorContainer:this.elements.editorContainer,getFileList:t.getFileList,initialTheme:t.theme,lineInfoElement:this.elements.lineInfo,lineWrappingEnabled:t.lineWrappingEnabled,localUser:t.localUser,vimModeEnabled:t.vimModeEnabled,onImagePaste:t.onImagePaste,onAwarenessChange:t.onAwarenessChange,onCommentsChange:t.onCommentsChange,onConnectionChange:t.onConnectionChange,onContentChange:t.onContentChange,onSelectionChange:t.onSelectionChange,preferredUserName:t.preferredUserName}),getDisplayName:e=>this.getDisplayName(e),getFileList:()=>this.fileExplorer.flatDocumentFiles,getLineWrappingEnabled:()=>this.getStoredLineWrapping(),getVimModeEnabled:()=>this.getStoredVimMode(),getLocalUser:()=>this.lobby.getLocalUser(),getStoredUserName:()=>this.getStoredUserName(),getTheme:()=>this.themeController.getTheme(),isBaseFile:e=>this.isBaseFile(e),isDrawioFile:e=>this.isDrawioFile(e),isExcalidrawFile:e=>this.isExcalidrawFile(e),isImageFile:e=>this.isImageFile(e),isPdfFile:e=>this.isPdfFile(e),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),isStructurizrWorkspaceFile:e=>this.isStructurizrWorkspaceFile(e),isTabActive:()=>this.isTabActive,loadBootstrapContent:async e=>{let t=await this.vaultApiClient.readFile(e);return typeof t?.content==`string`?t.content:null},loadEditorSessionClass:()=>this.loadEditorSessionClass(),loadBacklinks:e=>this.backlinksPanel.load(e),onBeforeFileOpen:()=>{clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=null,this.session=null,this.commentUi.attachSession(null),this.layoutController.reset(),this.workspacePreviewController.resetPreviewMode(),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.remove(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.clearInitialFileBootstrap()},onConnectionChange:e=>this.handleConnectionChange(e),onContentChange:({isBase:e,isMermaid:t,isPlantUml:n,isStructurizrWorkspace:r})=>{if(this.handleCommentEditorContentChange(),e){this.scheduleBaseFilePreview(this.currentFilePath,{source:this.session?.getText?.()??``});return}if(r){this.structurizrPreview.queueSync({filePath:this.currentFilePath,source:this.session?.getText?.()??``});return}this.previewRenderer.queueRender(),!t&&!n&&this.scheduleBacklinkRefresh()},onCommentsChange:e=>this.handleCommentThreadsChange(e),onFileAwarenessChange:e=>this.updateFileAwareness(e),onFileOpenError:()=>{this.showEditorLoadError(),this.syncWrapToggle(),this.toastController.show(`Failed to initialize editor`)},onFileOpenReady:()=>{this.hideEditorLoading(),this.currentFilePath&&this.preferences.recordRecentFile(this.currentFilePath)},onSelectionChange:e=>this.handleCommentSelectionChange(e),onImagePaste:e=>this.handleEditorImageInsert(e),onFileOpenMetric:(e,t)=>this.recordFileOpenMetric(e,t),onSessionAssigned:e=>{this.session=e,this.commentUi.attachSession(e)},onRenderDrawioPreview:e=>this.workspacePreviewController.renderDrawioFilePreview(e),onRenderBasePreview:e=>this.renderBaseFilePreview(e),onRenderExcalidrawPreview:e=>this.workspacePreviewController.renderExcalidrawFilePreview(e),onRenderImagePreview:e=>this.workspacePreviewController.renderImageFilePreview(e),onRenderPdfPreview:e=>this.workspacePreviewController.renderPdfFilePreview(e),onRenderStructurizrPreview:(e,t)=>this.workspacePreviewController.renderStructurizrFilePreview(e,t),onSyncWrapToggle:()=>this.syncWrapToggle(),onUpdateActiveFile:e=>this.fileExplorer.setActiveFile(e),onUpdateCurrentFile:e=>{this.currentFilePath=e},onUpdateLobbyCurrentFile:e=>this.lobby.setCurrentFile(e),onUpdateVisibleChrome:(e,{displayName:t})=>{this.workspacePreviewController.syncFileChrome(e,{drawioMode:this.currentDrawioMode,preferPreviewForBase:this.isBaseFile(e)}),this.syncCommentChrome(e),this.syncFileHistoryButton({filePath:e,mode:`editor`}),this.elements.activeFileName&&(this.elements.activeFileName.textContent=t)},onViewModeReset:()=>this.workspacePreviewController.resetPreviewMode(),renderPresence:()=>this.renderPresence(),scrollContainerForSession:e=>e.getScrollContainer(),shouldUseDrawioPreview:()=>!!this.runtimeConfig.drawioBaseUrl,showEditorLoading:()=>this.showEditorLoading(),stateStore:this}),this.workspaceRouteController=new an({backlinksPanel:this.backlinksPanel,clearInitialFileBootstrap:()=>this.clearInitialFileBootstrap(),clearStaticPreviewDocument:()=>this.clearStaticPreviewDocument(),closeSidebarOnMobile:()=>this.closeSidebarOnMobile(),drawioEmbed:this.drawioEmbed,elements:this.elements,excalidrawEmbed:this.excalidrawEmbed,fileHistoryView:this.fileHistoryView,fileExplorer:this.fileExplorer,getIsTabActive:()=>this.isTabActive,getSessionLoadToken:()=>this.sessionLoadToken,gitDiffView:this.gitDiffView,gitPanel:this.gitPanel,imageLightbox:this.imageLightbox,layoutController:this.layoutController,lobby:this.lobby,navigation:this.navigation,previewRenderer:this.previewRenderer,requestPreviewRouteAnchor:(e,t)=>this.requestPreviewRouteAnchor(e,t),renderAvatars:()=>this.renderAvatars(),renderPresence:()=>this.renderPresence(),resetPreviewMode:()=>this.workspacePreviewController.resetPreviewMode(),scrollSyncController:this.scrollSyncController,setCurrentFilePath:e=>{this.currentFilePath=e,e||(this.commentUi.setCurrentFile(null,{supported:!1}),this.handleCommentThreadsChange([]),this.handleCommentSelectionChange(null))},setSession:e=>{this.session=e,this.commentUi.attachSession(e)},setSessionLoadToken:e=>{this.sessionLoadToken=e},setSidebarTab:e=>this.setSidebarTab(e),setSidebarVisibility:e=>this.setSidebarVisibility(e),showGitCommit:e=>this.showGitCommit(e),showGitDiff:e=>this.showGitDiff(e),showGitFileHistory:e=>this.showGitFileHistory(e),showGitFilePreview:e=>this.showGitFilePreview(e),showGitHistory:()=>this.showGitHistory(),syncMainChrome:e=>this.syncMainChrome(e),videoEmbed:this.videoEmbed,workspaceCoordinator:this.workspaceCoordinator})}get session(){return this._session}set session(e){this._session=e}publishFileOpenPerf(){typeof window>`u`||(window.__COLLABMD_PERF__??={},window.__COLLABMD_PERF__.fileOpen=this._fileOpenPerf?{...this._fileOpenPerf,details:{...this._fileOpenPerf.details},marks:{...this._fileOpenPerf.marks}}:null)}recordFileOpenMetric(e,t={}){if(e===`open_started`){this._fileOpenPerf={details:{filePath:t.filePath||this.currentFilePath||``,loadToken:t.loadToken??0},marks:{open_started:performance.now()}},this.publishFileOpenPerf();return}this._fileOpenPerf&&(t.loadToken??this._fileOpenPerf.details.loadToken)===this._fileOpenPerf.details.loadToken&&(this._fileOpenPerf.marks[e]=performance.now(),t.filePath&&(this._fileOpenPerf.details.filePath=t.filePath),Object.entries(t).forEach(([e,t])=>{e!==`filePath`&&e!==`loadToken`&&(this._fileOpenPerf.details[e]=t)}),this.publishFileOpenPerf())}loadEditorSessionClass(){return this._editorSessionModulePromise||=e(()=>import(`./editor-session-Cm9ekeNo.js`).then(e=>e.EditorSession),__vite__mapDeps([38,1,39,40,41,42,43,44,45,46,47,27,48,49,50,51]),import.meta.url),this._editorSessionModulePromise}scheduleEditorSessionPrewarm({timeout:e=1500}={}){if(this._editorSessionModulePromise||this._editorSessionPrewarmHandle)return;let t=()=>{this._editorSessionPrewarmHandle=null,this.loadEditorSessionClass()};if(typeof window.requestIdleCallback==`function`){this._editorSessionPrewarmHandle=window.requestIdleCallback(t,{timeout:e});return}this._editorSessionPrewarmHandle=window.setTimeout(t,0)}loadQuickSwitcherController(){return e(()=>import(`./quick-switcher-controller-fqOYR7qR.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([52,27,29,53]),import.meta.url)}async ensureQuickSwitcher(){return nn(this)}async toggleQuickSwitcher(){return rn(this)}};async function lu(){await T(),new cu().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{lu()},{once:!0}):lu();
|