collabmd 0.1.34 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CodeMirrorEditor-UCMRAMCV-Bg0dawOb.js → CodeMirrorEditor-UCMRAMCV-CvLFeHXu.js} +1 -1
- package/dist/client/assets/_baseFor-Bfo4esZ5.js +1 -0
- package/dist/client/assets/arc-tRoMuWFi.js +1 -0
- package/dist/client/assets/architecture-YZFGNWBL-CtU43_5T.js +1 -0
- package/dist/client/assets/{architectureDiagram-2XIMDMQ5-kYbOThe4.js → architectureDiagram-Q4EWVU46-CVdcOotN.js} +4 -4
- package/dist/client/assets/blockDiagram-DXYQGD6D-B_gNUKQ4.js +132 -0
- package/dist/client/assets/c4Diagram-AHTNJAMY-BSDwfduG.js +10 -0
- package/dist/client/assets/channel-BDb1g_mJ.js +1 -0
- package/dist/client/assets/chunk-2KRD3SAO-C6u8y11R.js +1 -0
- package/dist/client/assets/chunk-336JU56O-Ch9X5KoM.js +2 -0
- package/dist/client/assets/{chunk-HHEYEP7N-DlevL8bq.js → chunk-426QAEUC-CwJ7loGf.js} +1 -1
- package/dist/client/assets/chunk-4TB4RGXK-BEsauZP5.js +206 -0
- package/dist/client/assets/chunk-5FUZZQ4R-6x8SlhH9.js +62 -0
- package/dist/client/assets/chunk-5PVQY5BW-R5SE6dhE.js +2 -0
- package/dist/client/assets/chunk-67CJDMHE-CjXw5hFa.js +1 -0
- package/dist/client/assets/chunk-7N4EOEYR-DNHyuswJ.js +1 -0
- package/dist/client/assets/chunk-AA7GKIK3-DayE4IF_.js +1 -0
- package/dist/client/assets/chunk-BSJP7CBP-CexlYBxB.js +1 -0
- package/dist/client/assets/chunk-CIAEETIT-CkDJ4DYI.js +1 -0
- package/dist/client/assets/{chunk-KX2RTZJC-BTiOJb7N.js → chunk-EDXVE4YY-BVR_nF3y.js} +1 -1
- package/dist/client/assets/chunk-ENJZ2VHE-CFVWytAB.js +10 -0
- package/dist/client/assets/chunk-FOC6F5B3-DzCiCLGs.js +1 -0
- package/dist/client/assets/chunk-ICPOFSXX-B9LPHgU7.js +122 -0
- package/dist/client/assets/chunk-K5T4RW27-kmGSebVE.js +94 -0
- package/dist/client/assets/chunk-KGLVRYIC-DVjPRsaR.js +1 -0
- package/dist/client/assets/chunk-LIHQZDEY-DKFj13sC.js +1 -0
- package/dist/client/assets/chunk-NU2UP6EN-UVL-wkIc.js +35 -0
- package/dist/client/assets/chunk-ORNJ4GCN-D0uTAC-5.js +1 -0
- package/dist/client/assets/{chunk-NQ4KR5QH-CMJKI6Oj.js → chunk-OYMX7WX6-nWiNHNyD.js} +25 -14
- package/dist/client/assets/{chunk-PU5JKC2W-D_6N6t8f.js → chunk-U2HBQHQK-Bue4Ufzn.js} +6 -6
- package/dist/client/assets/{chunk-PQ6SQG4A-D1AbThjy.js → chunk-X2U36JSP-CRE6lp7n.js} +1 -1
- package/dist/client/assets/{chunk-XPW4576I-DJr4_4Yy.js → chunk-XPW4576I-BL5M-tF8.js} +1 -1
- package/dist/client/assets/{chunk-JSJVCQXG-DPQ9cPJt.js → chunk-YZCP3GAM-D7Z5wUWA.js} +1 -1
- package/dist/client/assets/chunk-ZZ45TVLE-CBbl1Qec.js +1 -0
- package/dist/client/assets/classDiagram-6PBFFD2Q-MIbgV5UL.js +1 -0
- package/dist/client/assets/classDiagram-v2-HSJHXN6E-Bb70vg2O.js +1 -0
- package/dist/client/assets/clike-BFTLRaGS.js +1 -0
- package/dist/client/assets/clone-D6JWrlxJ.js +1 -0
- package/dist/client/assets/{coffeescript-B_7eyHAa.js → coffeescript-B7GZajzV.js} +1 -1
- package/dist/client/assets/{cose-bilkent-S5V4N54A-DASO2hrk.js → cose-bilkent-S5V4N54A-xxgR5OJ-.js} +1 -1
- package/dist/client/assets/{cypher-DE6I2lIA.js → cypher-DEGl2llJ.js} +1 -1
- package/dist/client/assets/cytoscape.esm-B3PRdePO.js +321 -0
- package/dist/client/assets/{d-BNkKjn0o.js → d-BspB0dox.js} +1 -1
- package/dist/client/assets/dagre-KV5264BT-C2K9mFg1.js +4 -0
- package/dist/client/assets/dagre-VaFYRFbD.js +1 -0
- package/dist/client/assets/diagram-5BDNPKRD-DE0M0jaM.js +10 -0
- package/dist/client/assets/diagram-G4DWMVQ6-BfaRuSTT.js +24 -0
- package/dist/client/assets/diagram-MMDJMWI5-91Bly_hN.js +43 -0
- package/dist/client/assets/diagram-TYMM5635-fBkLwZGN.js +24 -0
- package/dist/client/assets/{dist-BzpfHRaE.js → dist-74GtnE06.js} +1 -1
- package/dist/client/assets/dist-B3lARV_e.js +1 -0
- package/dist/client/assets/{dist-O1z0Ayg0.js → dist-BCvzlTeb.js} +1 -1
- package/dist/client/assets/{dist-DsL7sqZR.js → dist-BMlUxhOz.js} +1 -1
- package/dist/client/assets/dist-BSED50tI.js +13 -0
- package/dist/client/assets/{dist-B-02vKOA.js → dist-Bkn7JaJv.js} +1 -1
- package/dist/client/assets/dist-Bq8Z0WUT.js +1 -0
- package/dist/client/assets/{dist-E_jPb93e.js → dist-Bzb9nPam.js} +1 -1
- package/dist/client/assets/{dist-CL-jjdvG.js → dist-C0e9kfNh.js} +1 -1
- package/dist/client/assets/dist-C8wdW7W4.js +1 -0
- package/dist/client/assets/dist-CDUQ5ELn.js +1 -0
- package/dist/client/assets/dist-CHSg_nUM.js +1 -0
- package/dist/client/assets/dist-CSAH9iuE.js +6 -0
- package/dist/client/assets/{dist-CxfohGIV.js → dist-CSNMpi-w.js} +1 -1
- package/dist/client/assets/dist-CZPTvk_g2.js +1 -0
- package/dist/client/assets/{dist-k47-Io7D.js → dist-Co8HE14w.js} +1 -1
- package/dist/client/assets/{dist-Bc2ND6i3.js → dist-CqU98NzX.js} +1 -1
- package/dist/client/assets/{dist-BzbYwa8m.js → dist-D0dQAc9b.js} +1 -1
- package/dist/client/assets/{dist-Dyt7n5Ui.js → dist-D1-dK0Dk.js} +1 -1
- package/dist/client/assets/{dist-B4uQVR_X.js → dist-DAKGEzm0.js} +1 -1
- package/dist/client/assets/dist-DBzteOlY.js +1 -0
- package/dist/client/assets/{dist-CjII8VDS.js → dist-DSRCADL9.js} +1 -1
- package/dist/client/assets/{dist-lDhnP-K1.js → dist-DdR2aYqj.js} +1 -1
- package/dist/client/assets/{dist-DUvaQ-Bj.js → dist-DidT3Jay.js} +1 -1
- package/dist/client/assets/dist-Doo91MTa.js +1 -0
- package/dist/client/assets/{dist-BLAlZer_.js → dist-Dwy75xI6.js} +1 -1
- package/dist/client/assets/{dist-3uAMa5w5.js → dist-FC9LftvP.js} +1 -1
- package/dist/client/assets/{dist-CGV1S_as.js → dist-PPAeaw4t.js} +1 -1
- package/dist/client/assets/{dist-BtnXjRx0.js → dist-VPEWg0Ob.js} +1 -1
- package/dist/client/assets/{dist-CXpKYW9s.js → dist-cQSK4Xor.js} +1 -1
- package/dist/client/assets/{dist-rMhng5DK.js → dist-r5I9Jgww.js} +1 -1
- package/dist/client/assets/drawio-editor-CWLEpwps.js +9 -0
- package/dist/client/assets/{drawioEditor-D6clB5OH.js → drawioEditor-5rJhxjA4.js} +2 -2
- package/dist/client/assets/{ecl-M7Iek4lq.js → ecl-D9rhJ9-u.js} +1 -1
- package/dist/client/assets/{editor-session-Dzy_85Wp.js → editor-session-CLOuvy37.js} +3 -3
- package/dist/client/assets/{erDiagram-INFDFZHY-DlIf-fb7.js → erDiagram-SMLLAGMA-DUQcqEQ1.js} +33 -18
- package/dist/client/assets/excalidraw-editor-ukEKPqGJ.js +9 -0
- package/dist/client/assets/{excalidraw-mermaid-stub-Bwe-bKcT.js → excalidraw-mermaid-stub-Df0Q2qkW.js} +1 -1
- package/dist/client/assets/excalidraw-scene-CDK3oDnm.js +176 -0
- package/dist/client/assets/excalidrawEditor-BJ8QLmWc.js +2 -0
- package/dist/client/assets/{export-page-PeexH2QK.js → export-page-D2rCmrUH.js} +2 -2
- package/dist/client/assets/exportDocument-Dunnjgii.js +2 -0
- package/dist/client/assets/{fcl-BWKK0S4-.js → fcl-CUXJFJn1.js} +1 -1
- package/dist/client/assets/flatten-CX_XvnUf.js +1 -0
- package/dist/client/assets/flowDiagram-DWJPFMVM-B_A5JyId.js +162 -0
- package/dist/client/assets/ganttDiagram-T4ZO3ILL-HM3CD7bk.js +292 -0
- package/dist/client/assets/gitGraph-7Q5UKJZL-BrBlB49D.js +1 -0
- package/dist/client/assets/gitGraphDiagram-UUTBAWPF-Dw7twZDm.js +106 -0
- package/dist/client/assets/graphlib-DDD4Vdye.js +1 -0
- package/dist/client/assets/{groovy-BEKazBrO.js → groovy-Di--Vb9Z.js} +1 -1
- package/dist/client/assets/{haxe-BY9d_5nB.js → haxe-CcPA1xnA.js} +1 -1
- package/dist/client/assets/image-XLNPCCAD-BFNybKza.js +1 -0
- package/dist/client/assets/{image-blob-reduce.esm-DriR2zT9.js → image-blob-reduce.esm-DiuPkovC.js} +1 -1
- package/dist/client/assets/{index-BLrtj9YM.js → index-BbziNMqE.js} +2 -2
- package/dist/client/assets/info-OMHHGYJF-BcmgcSx1.js +1 -0
- package/dist/client/assets/{infoDiagram-LFFYTUFH-DFTI0nfs.js → infoDiagram-42DDH7IO-DX-d3DMp.js} +1 -1
- package/dist/client/assets/isEmpty-BKDbo1FH.js +1 -0
- package/dist/client/assets/ishikawaDiagram-UXIWVN3A-BHmsxpMs.js +70 -0
- package/dist/client/assets/{javascript-CdiVhQeA.js → javascript-gTK9fxz6.js} +1 -1
- package/dist/client/assets/javascript-qUBHINSy.js +1 -0
- package/dist/client/assets/{journeyDiagram-4ABVD52K-DDur6iHm.js → journeyDiagram-VCZTEJTY-jxDSjgE1.js} +2 -2
- package/dist/client/assets/{jsx-runtime-C2p7wRmT.js → jsx-runtime-B_8UNt-W.js} +1 -1
- package/dist/client/assets/{kanban-definition-K7BYSVSG-dA6NPLsg.js → kanban-definition-6JOO6SKY-od3qY1mE.js} +2 -2
- package/dist/client/assets/line-CZsGUM4H.js +1 -0
- package/dist/client/assets/{lua-kutgyRGY.js → lua-Cg0FqIlO.js} +1 -1
- package/dist/client/assets/main-CN0kbtGk.js +1369 -0
- package/dist/client/assets/mermaid-parser.core-DtIbxv6L.js +4 -0
- package/dist/client/assets/mermaid-runtime-vVJfjscE.js +11 -0
- package/dist/client/assets/{mindmap-definition-YRQLILUH-DjQcsPoe.js → mindmap-definition-QFDTVHPH-C9qrdAqo.js} +39 -11
- package/dist/client/assets/packet-4T2RLAQJ-DYYSvRuJ.js +1 -0
- package/dist/client/assets/pica-BEurQXMu.js +2 -0
- package/dist/client/assets/pie-ZZUOXDRM-cG65Mc64.js +1 -0
- package/dist/client/assets/pieDiagram-DEJITSTG-BHXxj7wl.js +30 -0
- package/dist/client/assets/{preview-render-compiler-BjLlHmiQ.js → preview-render-compiler-BHeDhYho.js} +2 -2
- package/dist/client/assets/preview-render-compiler-D3QM1Ryz.js +1 -0
- package/dist/client/assets/{preview-render-profile-CR4dJZrp.js → preview-render-profile-BF6os3x9.js} +5 -5
- package/dist/client/assets/{preview-render-worker-B4dH2yxj.js → preview-render-worker-C4AFtMIr.js} +6 -6
- package/dist/client/assets/{pug-DkUcLYWt.js → pug-lkTEco3G.js} +1 -1
- package/dist/client/assets/{python-CZtTmYkS.js → python-BUyhM0Ew.js} +1 -1
- package/dist/client/assets/{q-I27iQntV.js → q-Dls1OX0D.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-337W2JSQ-CYKgdx7K.js → quadrantDiagram-34T5L4WZ-CWW7LORF.js} +1 -1
- package/dist/client/assets/{quick-switcher-controller-DcyllYpm.js → quick-switcher-controller-B1erSgJ1.js} +1 -1
- package/dist/client/assets/{r-DN_EydfL.js → r-DeZ8Mdev.js} +1 -1
- package/dist/client/assets/radar-PYXPWWZC-Bmpup_xw.js +1 -0
- package/dist/client/assets/reduce-C6FuFJbE.js +1 -0
- package/dist/client/assets/requirementDiagram-MS252O5E-CTljNdQH.js +84 -0
- package/dist/client/assets/{room-yJaBAoEU.js → room-DI7DXGeS.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-WA2Y5GQK-CfHe3D6R.js → sankeyDiagram-XADWPNL6-CCfFkC74.js} +1 -1
- package/dist/client/assets/sequenceDiagram-FGHM5R23-BD9vj6WG.js +157 -0
- package/dist/client/assets/{sparql-BOvq0dv7.js → sparql-vm8qNO8J.js} +1 -1
- package/dist/client/assets/sql-GL7dVWcd.js +1 -0
- package/dist/client/assets/stateDiagram-FHFEXIEX-CpiX3KPd.js +1 -0
- package/dist/client/assets/stateDiagram-v2-QKLJ7IA2-D_5ufPqT.js +1 -0
- package/dist/client/assets/{swift-BCxe4-cw.js → swift-CKcKnWv9.js} +1 -1
- package/dist/client/assets/timeline-definition-GMOUNBTQ-BafRAkSF.js +120 -0
- package/dist/client/assets/treeView-SZITEDCU-NbjhK5cw.js +1 -0
- package/dist/client/assets/treemap-W4RFUUIX-DJzRbb-x.js +1 -0
- package/dist/client/assets/{turtle-GBz_E4RG.js → turtle-BkP3ExOG.js} +1 -1
- package/dist/client/assets/{vault-api-client-p7h7cXKM.js → vault-api-client-DSx3mWkH.js} +1 -1
- package/dist/client/assets/{vault-utils-5Xr0MXCb.js → vault-utils-CRpy8MQz.js} +1 -1
- package/dist/client/assets/vennDiagram-DHZGUBPP-DSngq_Zj.js +34 -0
- package/dist/client/assets/{verilog-C4wTycyo.js → verilog-DSARZZPc.js} +1 -1
- package/dist/client/assets/{vhdl-Bwndeg44.js → vhdl-CnYyYTpa.js} +1 -1
- package/dist/client/assets/wardley-RL74JXVD-DTNoH_BY.js +1 -0
- package/dist/client/assets/wardleyDiagram-NUSXRM2D-CAEd2kJG.js +20 -0
- package/dist/client/assets/{xychartDiagram-JWTSCODW-C3vA70iJ.js → xychartDiagram-5P7HB3ND-BScQpnru.js} +6 -6
- package/dist/client/assets/{yjs-provider-reset-guard-CtERLBID.js → yjs-provider-reset-guard-_Q3mj6tP.js} +1 -1
- package/dist/client/drawio-editor.html +1 -1
- package/dist/client/excalidraw-editor.html +1 -1
- package/dist/client/export-document.html +1 -1
- package/dist/client/index.html +1 -1
- package/package.json +11 -11
- package/src/client/application/app-shell/ui-feature-shell.js +5 -2
- package/src/client/application/quick-switcher-loader.js +39 -0
- package/src/client/bootstrap/collabmd-app-shell.js +16 -20
- package/src/client/domain/keyboard-shortcuts.js +8 -0
- package/src/client/drawio-editor.js +13 -0
- package/src/client/excalidraw-editor.js +13 -0
- package/src/client/infrastructure/excalidraw-room-client.js +1 -1
- package/src/client/infrastructure/workspace-sync-client.js +26 -3
- package/src/client/presentation/comment-ui/comment-ui-card.js +83 -3
- package/src/client/presentation/comment-ui/comment-ui-state.js +25 -2
- package/src/client/presentation/drawio-embed-controller.js +18 -0
- package/src/client/presentation/excalidraw-embed-controller.js +7 -0
- package/src/client/presentation/git-panel-controller.js +2 -0
- package/src/server/domain/backlink-index.js +33 -72
- package/src/server/domain/bases/base-index-snapshot-store.js +46 -62
- package/src/server/domain/markdown-reference-extractor.js +233 -0
- package/src/server/infrastructure/persistence/vault-file-store.js +39 -4
- package/src/server/infrastructure/workspace/file-system-sync-service.js +37 -11
- package/dist/client/assets/_basePickBy-Dv0sK1l7.js +0 -1
- package/dist/client/assets/_baseUniq-DKYX57ji.js +0 -1
- package/dist/client/assets/arc-DrfYGhWk.js +0 -1
- package/dist/client/assets/architecture-PBZL5I3N-DiglIZi9.js +0 -1
- package/dist/client/assets/blockDiagram-WCTKOSBZ-GIgTqnhk.js +0 -132
- package/dist/client/assets/c4Diagram-IC4MRINW-CkHO1i_L.js +0 -10
- package/dist/client/assets/channel-CgsU9TSN.js +0 -1
- package/dist/client/assets/chunk-7E7YKBS2-TdU92i9i.js +0 -1
- package/dist/client/assets/chunk-7R4GIKGN-mqd2GwMg.js +0 -80
- package/dist/client/assets/chunk-C72U2L5F-CJKQWBtz.js +0 -1
- package/dist/client/assets/chunk-EGIJ26TM-C4nq20om.js +0 -1
- package/dist/client/assets/chunk-GEFDOKGD-Bs7FmFox.js +0 -2
- package/dist/client/assets/chunk-GLR3WWYH-qQe2O5VQ.js +0 -2
- package/dist/client/assets/chunk-KYZI473N-CTSCuqRb.js +0 -53
- package/dist/client/assets/chunk-L3YUKLVL-CJZMBtKF.js +0 -1
- package/dist/client/assets/chunk-MX3YWQON-DQpSwRf6.js +0 -1
- package/dist/client/assets/chunk-NU2UP6EN-DlUENSHU.js +0 -35
- package/dist/client/assets/chunk-O4XLMI2P-CcVxZh41.js +0 -7
- package/dist/client/assets/chunk-OZEHJAEY-DjBZbgu0.js +0 -1
- package/dist/client/assets/chunk-R5LLSJPH-CkjKXM73.js +0 -1
- package/dist/client/assets/chunk-WL4C6EOR-axcuKSup.js +0 -189
- package/dist/client/assets/chunk-XIRO2GV7-4wqVHjs_.js +0 -1
- package/dist/client/assets/chunk-XZSTWKYB-C8Y_hIKZ.js +0 -94
- package/dist/client/assets/chunk-YBOYWFTD-CKg4ymFF.js +0 -1
- package/dist/client/assets/classDiagram-VBA2DB6C-BHZpvOxK.js +0 -1
- package/dist/client/assets/classDiagram-v2-RAHNMMFH-DA7HMUUs.js +0 -1
- package/dist/client/assets/clike-1_ZsiVV8.js +0 -1
- package/dist/client/assets/clone-Dgi8Z4IL.js +0 -1
- package/dist/client/assets/cytoscape.esm-Czjc507F.js +0 -321
- package/dist/client/assets/dagre-CfB3Fw33.js +0 -1
- package/dist/client/assets/dagre-KLK3FWXG-CC7tq2Ky.js +0 -4
- package/dist/client/assets/diagram-E7M64L7V-CMt7BN5M.js +0 -24
- package/dist/client/assets/diagram-IFDJBPK2-BFMBUGpd.js +0 -43
- package/dist/client/assets/diagram-P4PSJMXO-CviA1xXr.js +0 -24
- package/dist/client/assets/dist-3bQB_we3.js +0 -1
- package/dist/client/assets/dist-8Igu3Ee_2.js +0 -1
- package/dist/client/assets/dist-BU8uusJX.js +0 -1
- package/dist/client/assets/dist-BVB8rn7o.js +0 -1
- package/dist/client/assets/dist-D5QOYy7y.js +0 -6
- package/dist/client/assets/dist-DIi0uqLJ.js +0 -1
- package/dist/client/assets/dist-DJ16N7ol.js +0 -1
- package/dist/client/assets/dist-DWJL3_bF.js +0 -13
- package/dist/client/assets/dist-OQE68wIX.js +0 -1
- package/dist/client/assets/dist-x7PIEmJu.js +0 -1
- package/dist/client/assets/drawio-editor-BMTwP5mD.js +0 -9
- package/dist/client/assets/excalidraw-editor-CAP9F8CB.js +0 -9
- package/dist/client/assets/excalidraw-scene-BF_bT1OL.js +0 -176
- package/dist/client/assets/excalidrawEditor-DD4AvzYP.js +0 -2
- package/dist/client/assets/exportDocument-Zfwq1XVx.js +0 -2
- package/dist/client/assets/flowDiagram-PKNHOUZH-C_t-mkwb.js +0 -162
- package/dist/client/assets/ganttDiagram-A5KZAMGK-BtK9Tb--.js +0 -292
- package/dist/client/assets/gitGraph-HDMCJU4V-CT7YfbD3.js +0 -1
- package/dist/client/assets/gitGraphDiagram-K3NZZRJ6-DULDLGiJ.js +0 -65
- package/dist/client/assets/graphlib-BgRST-Qg.js +0 -1
- package/dist/client/assets/image-XLNPCCAD-CFiKwiWK.js +0 -1
- package/dist/client/assets/info-3K5VOQVL-DUpNyDC-.js +0 -1
- package/dist/client/assets/isArrayLikeObject-BId_dPHM.js +0 -1
- package/dist/client/assets/isEmpty-CVvRj8fj.js +0 -1
- package/dist/client/assets/ishikawaDiagram-PHBUUO56-DpBuDpC6.js +0 -70
- package/dist/client/assets/javascript-UJe68_xi.js +0 -1
- package/dist/client/assets/line-B2GMovaI.js +0 -1
- package/dist/client/assets/main-CfSHaGes.js +0 -1368
- package/dist/client/assets/math-B-LMBwub.js +0 -1
- package/dist/client/assets/mermaid-parser.core-B1ogGcR8.js +0 -4
- package/dist/client/assets/mermaid-runtime-Bn8A6DGx.js +0 -11
- package/dist/client/assets/packet-RMMSAZCW-DEwNbIrA.js +0 -1
- package/dist/client/assets/pica-C1TdTz-C.js +0 -2
- package/dist/client/assets/pie-UPGHQEXC-D5M_lSjo.js +0 -1
- package/dist/client/assets/pieDiagram-SKSYHLDU-jhHouFpk.js +0 -30
- package/dist/client/assets/preview-render-compiler-Duy_3IcP.js +0 -1
- package/dist/client/assets/radar-KQ55EAFF-AU1qh3Bw.js +0 -1
- package/dist/client/assets/requirementDiagram-Z7DCOOCP-D9SHxoW7.js +0 -73
- package/dist/client/assets/sequenceDiagram-2WXFIKYE-CZsMMqAJ.js +0 -145
- package/dist/client/assets/sql-DDFeQNTK.js +0 -1
- package/dist/client/assets/stateDiagram-RAJIS63D-CoNZjTYV.js +0 -1
- package/dist/client/assets/stateDiagram-v2-FVOUBMTO-1zOw6NmQ.js +0 -1
- package/dist/client/assets/timeline-definition-YZTLITO2-DSe2mrG8.js +0 -61
- package/dist/client/assets/treemap-KZPCXAKY-C9UI2fwP.js +0 -1
- package/dist/client/assets/vennDiagram-LZ73GAT5-xSzaIpy1.js +0 -34
- /package/dist/client/assets/{chunk-55IACEB6-CpncB3ru.js → chunk-55IACEB6-DLqevMSj.js} +0 -0
- /package/dist/client/assets/{chunk-QZHKN3VN-CgLPFSk5.js → chunk-QZHKN3VN-BnOS2iQW.js} +0 -0
- /package/dist/client/assets/{drawio-room-DEivFyNV.js → drawio-room-1i6Nn0_Z.js} +0 -0
- /package/dist/client/assets/{excalidraw-mermaid-stub-BZPU4ZhU.js → excalidraw-mermaid-stub-DzxtBcQW.js} +0 -0
- /package/dist/client/assets/{file-kind-DBptLlF_.js → file-kind-DmKq2MvD.js} +0 -0
- /package/dist/client/assets/{preview-diagram-utils-COt-IYMD.js → preview-diagram-utils-D8VypUft.js} +0 -0
- /package/dist/client/assets/{rough.esm-DE_lJ5Ge.js → rough.esm-BU2knLt9.js} +0 -0
- /package/dist/client/assets/{runtime-config-CqhchMC4.js → runtime-config-DWTejofP.js} +0 -0
|
@@ -0,0 +1,1369 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid-runtime-vVJfjscE.js","./preload-helper-Bo9GmnuQ.js","./chunk-U2HBQHQK-Bue4Ufzn.js","./src-Pgt9Gp65.js","./chunk-DpHwWhuW.js","./chunk-5PVQY5BW-R5SE6dhE.js","./dist-DBzteOlY.js","./chunk-ICPOFSXX-B9LPHgU7.js","./_baseFor-Bfo4esZ5.js","./isEmpty-BKDbo1FH.js","./chunk-336JU56O-Ch9X5KoM.js","./chunk-5FUZZQ4R-6x8SlhH9.js","./chunk-X2U36JSP-CRE6lp7n.js","./chunk-ZZ45TVLE-CBbl1Qec.js","./rough.esm-BU2knLt9.js","./chunk-ENJZ2VHE-CFVWytAB.js","./line-CZsGUM4H.js","./path-DIlZIGue.js","./array-B3agRrCs.js","./chunk-BSJP7CBP-CexlYBxB.js","./chunk-426QAEUC-CwJ7loGf.js","./chunk-XPW4576I-BL5M-tF8.js","./preview-render-compiler-D3QM1Ryz.js","./preview-render-compiler-BHeDhYho.js","./preview-render-profile-BF6os3x9.js","./vault-utils-CRpy8MQz.js","./file-kind-DmKq2MvD.js","./editor-session-CLOuvy37.js","./dist-Doo91MTa.js","./dist-BSED50tI.js","./dist-CDUQ5ELn.js","./dist-CSAH9iuE.js","./dist-CSNMpi-w.js","./dist-Bkn7JaJv.js","./dist-BCvzlTeb.js","./dist-Bzb9nPam.js","./dist-DAKGEzm0.js","./yjs-provider-reset-guard-_Q3mj6tP.js","./room-DI7DXGeS.js","./runtime-config-DWTejofP.js","./quick-switcher-controller-B1erSgJ1.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r as i}from"./preview-render-profile-BF6os3x9.js";import{a,c as o,d as s,f as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./file-kind-DmKq2MvD.js";import{i as y,n as b,t as x}from"./vault-utils-CRpy8MQz.js";import{n as ee,r as te,t as S}from"./vault-api-client-DSx3mWkH.js";import{a as C,c as ne,d as re,f as ie,i as ae,l as w,n as T,o as E,r as D,s as oe,t as O,u as k}from"./runtime-config-DWTejofP.js";import{n as se,r as ce,t as le}from"./yjs-provider-reset-guard-_Q3mj6tP.js";import{r as ue}from"./drawio-room-1i6Nn0_Z.js";import{a as de,c as fe,d as pe,f as me,h as he,i as ge,l as _e,m as ve,n as A,o as ye,p as be,r as xe,s as Se,t as j,u as Ce}from"./preview-diagram-utils-D8VypUft.js";import{l as we,n as Te,r as Ee,t as De}from"./room-DI7DXGeS.js";var Oe={edit:`
|
|
3
|
+
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
4
|
+
<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"/>
|
|
5
|
+
<path d="M10.7 2.9l2.4 2.4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
6
|
+
</svg>
|
|
7
|
+
`,maximize:`
|
|
8
|
+
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
9
|
+
<path d="M6 2H2v4M10 2h4v4M14 10v4h-4M2 10v4h4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
10
|
+
</svg>
|
|
11
|
+
`,refresh:`
|
|
12
|
+
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
13
|
+
<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"/>
|
|
14
|
+
<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"/>
|
|
15
|
+
</svg>
|
|
16
|
+
`,restore:`
|
|
17
|
+
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
18
|
+
<path d="M6 5V2H2M10 5V2h4M10 11v3h4M6 11v3H2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
19
|
+
<path d="M4.5 4.5h7v7h-7z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
20
|
+
</svg>
|
|
21
|
+
`};function M(e,t){if(!(e instanceof HTMLElement))return;let n=Oe[t];if(!n){e.classList.remove(`is-icon-only`);return}e.classList.add(`is-icon-only`),e.dataset.icon=t,e.innerHTML=n.trim()}function ke(e){return`data-${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}var Ae=class{constructor(e,{batchSize:t,datasetKeys:n,fetchFn:r=null,loadFileSource:i=null,filePathLabel:a,requestIdleRenderFn:o=me,cancelIdleRenderFn:s=xe,intersectionObserverFactory:c=(e,t)=>new IntersectionObserver(e,t),isNearViewportFn:l=Ce,requestAnimationFrameFn:u=e=>requestAnimationFrame(e),shellClassName:d,sourceClassName:f}){this.renderer=e,this.batchSize=t,this.datasetKeys=n,this.loadFileSource=i??this.createLegacyFileSourceLoader(r),this.filePathLabel=a,this.requestIdleRenderFn=o,this.cancelIdleRenderFn=s,this.intersectionObserverFactory=c,this.isNearViewportFn=l,this.requestAnimationFrameFn=u,this.shellClassName=d,this.sourceClassName=f,this.shellSelector=`.${d}`,this.sourceSelector=`.${f}`,this.attributeNames=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,ke(t)])),this.observer=null,this.idleId=null,this.pendingShells=[],this.hydrationInProgress=!1,this.instanceCounter=0,this.preservedShells=new Map,this.fileInflightRequests=new Map}createLegacyFileSourceLoader(e){return typeof e==`function`?async t=>{let n=await e(w(`/file?path=${encodeURIComponent(t)}`)),r=await n.json().catch(()=>({}));if(!n.ok||r?.ok===!1)throw Error(r?.error||`Failed to load ${this.filePathLabel.toLowerCase()} source`);return String(r?.content??``)}:null}destroy(){this.cancelHydration(),this.preservedShells.clear()}cancelHydration(){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.clear()}hasPendingWork(){return this.hydrationInProgress||this.pendingShells.length>0}preserveHydratedShellsForCommit(){this.preservedShells.clear();let e=this.renderer.previewElement;e&&Array.from(e.querySelectorAll(`${this.shellSelector}[${this.attributeNames.hydrated}="true"][${this.attributeNames.key}]`)).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&&e.remove(),this.preservedShells.set(t,{key:t,shell:e,source:n,target:r}))})}reconcileHydratedShells(){let e=this.renderer.previewElement;if(!e||this.preservedShells.size===0){this.preservedShells.clear();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.get(n):null;r&&ve({nextSource:e.querySelector(this.sourceSelector)?.textContent??``,nextTarget:e.dataset[this.datasetKeys.target]??``,preservedSource:r.source,preservedTarget:r.target})&&(this.syncPreservedShell(r.shell,e),e.replaceWith(r.shell),t||=r.shell.classList.contains(`is-maximized`),this.preservedShells.delete(n))}),this.preservedShells.clear(),this.handleReconcile({restoredMaximizedShell:t})}handleReconcile(){}syncPreservedShell(e,t){he(e,t,this.attributeNames.sourceLine),he(e,t,this.attributeNames.sourceLineEnd),he(e,t,this.attributeNames.key),he(e,t,this.attributeNames.target),he(e,t,this.attributeNames.label),he(e,t,this.attributeNames.sourceHash),e.classList.add(this.shellClassName),e.dataset[this.datasetKeys.hydrated]=`true`,this.removeDatasetValue(e,`queued`);let n=t.querySelector(this.sourceSelector),r=e.querySelector(this.sourceSelector);if(!r&&n&&(r=n.cloneNode(!0),e.prepend(r)),r&&n){let e=n.textContent??``;(e||!t.dataset[this.datasetKeys.target])&&(r.textContent=e),r.hidden=!0}}setupHydration(e){let t=this.renderer.previewElement,n=this.renderer.previewContainer;if(!t||!n)return 0;let r=Array.from(t.querySelectorAll(this.shellSelector));return r.length===0?0:(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(()=>{e===this.renderer.activeRenderVersion&&(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=[];for(;this.pendingShells.length>0&&e.length<this.batchSize;){let t=this.pendingShells.shift();!t?.isConnected||this.isShellHydrated(t)||(this.removeDatasetValue(t,`queued`),e.push(t))}if(e.length===0){this.renderer.updateHydrationPhase();return}this.hydrationInProgress=!0,this.renderer.setPhase(`hydrating`);let t;try{t=await this.prepareHydrationBatch(e)}catch(t){this.handlePrepareHydrationBatchError(e,t),this.hydrationInProgress=!1,this.renderer.updateHydrationPhase();return}for(let n of e)await this.hydrateShell(n,t);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){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}},je=class extends Ae{constructor(e,{fetchFn:t=null,loadFileSource:n=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`mermaidHydrated`,instanceId:`mermaidInstanceId`,key:`mermaidKey`,label:`mermaidLabel`,queued:`mermaidQueued`,sourceHash:`mermaidSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`mermaidTarget`},fetchFn:t,filePathLabel:`Mermaid`,loadFileSource:n,shellClassName:`mermaid-shell`,sourceClassName:`mermaid-source`}),this.renderer=e,this.currentTheme=document.documentElement?.dataset.theme===`light`?`light`:`dark`,this.loader=null,this.runtime=null,this.shellRefits=new WeakMap,this.activeMaximizedShell=null,this.maximizedRoot=null}destroy(){this.cancelHydration(),this.preservedShells.clear(),this.clearActiveShell(),this.maximizedRoot?.remove(),this.maximizedRoot=null}cancelHydration(){super.cancelHydration();let e=this.syncActiveShell();e&&(this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.clearActiveShell(),document.body.classList.remove(`mermaid-maximized-open`))}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.clearActiveShell(),null)}ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-mermaid-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.mermaidMaximizedRoot=`true`,e.className=`mermaid-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}mountShellInMaximizedRoot(e){if(!e)return;let t=this.ensureMaximizedRoot();t.hidden=!1,e._mermaidRestoreParent=e.parentElement||null,e._mermaidRestoreNextSibling=e.nextSibling||null,t.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._mermaidRestoreParent,n=e._mermaidRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._mermaidRestoreParent=null,e._mermaidRestoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}applyTheme(e){this.currentTheme=e;let t=this.runtime;t&&(this.configureMermaid(t),this.resetHydratedShells())}configureMermaid(e){e.initialize({startOnLoad:!1,flowchart:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},theme:this.currentTheme===`dark`?`dark`:`default`,themeVariables:this.currentTheme===`dark`?{background:`#161822`,clusterBkg:`#1a1c28`,edgeLabelBackground:`#161822`,lineColor:`#8b8ba0`,mainBkg:`#1c1e2c`,nodeBorder:`#383a50`,primaryBorderColor:`#383a50`,primaryColor:`#818cf8`,primaryTextColor:`#e2e2ea`,secondaryColor:`#1c1e2c`,tertiaryColor:`#161822`,titleColor:`#e2e2ea`}:{}})}ensureMermaid(){return this.runtime?(this.configureMermaid(this.runtime),Promise.resolve(this.runtime)):(this.loader||=e(()=>import(`./mermaid-runtime-vVJfjscE.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([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]),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.syncActiveShell()}async prepareHydrationBatch(){return this.ensureMermaid()}handlePrepareHydrationBatchError(e,t){console.warn(`[preview] Mermaid runtime failed to load:`,t)}async hydrateShell(e,t){if(!t||!e?.isConnected||this.isShellHydrated(e))return;let n=e.querySelector(`.mermaid-source`);n||(n=document.createElement(`span`),n.className=`mermaid-source`,n.hidden=!0,e.appendChild(n));let r=n.textContent??``;try{if(!r.trim()&&e.dataset.mermaidTarget){if(r=await this.fetchSource(e.dataset.mermaidTarget),!e.isConnected)return;n.textContent=r}if(!r.trim())throw Error(e.dataset.mermaidTarget?`Mermaid file is empty`:`Mermaid source is empty`);r=this.prepareSource(r),e.querySelector(`.mermaid-placeholder-card`)?.remove();let i=document.createElement(`div`);i.className=`mermaid mermaid-render-node`,i.id=e.dataset.mermaidKey||`mermaid-${Date.now()}`;let a=e.getAttribute(`data-source-line`),o=e.getAttribute(`data-source-line-end`);if(a&&i.setAttribute(`data-source-line`,a),o&&i.setAttribute(`data-source-line-end`,o),i.textContent=r,e.appendChild(i),await t.run({nodes:[i]}),!i.isConnected||e!==i.parentElement)return;this.enhanceDiagram(e,i),this.markShellHydrated(e)}catch(t){console.warn(`[preview] Mermaid render failed:`,t),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),e.querySelector(`.mermaid-placeholder-card`)||n?.after(de(e.dataset.mermaidKey||`mermaid`,{label:e.dataset.mermaidLabel||`Mermaid diagram`,message:t instanceof Error?t.message:`Render failed`}))}}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(`
|
|
22
|
+
`),r=n.findIndex(e=>/^\s*gantt\b/.test(e));return r===-1?t:(n.splice(r+1,0,` todayMarker off`),n.join(`
|
|
23
|
+
`))}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.syncActiveShell();n&&!t.includes(n)&&t.push(n),t.length!==0&&t.forEach(e=>{this.shellRefits.delete(e),e.removeAttribute(`data-mermaid-hydrated`),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(ge(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}enhanceDiagram(e,t){let n=t.querySelector(`svg`);if(!n){t.remove();return}let r=document.createElement(`div`);r.className=`mermaid-toolbar diagram-preview-toolbar`;let i=this.createZoomButton(`−`,`Zoom out`),a=this.createZoomButton(`+`,`Zoom in`),o=this.createZoomButton(`Reset`,`Reset zoom`),s=this.createZoomButton(`Max`,`Maximize diagram`);s.classList.add(`mermaid-maximize-btn`),M(s,`maximize`);let c=document.createElement(`span`);c.className=`mermaid-zoom-label diagram-preview-zoom-label`,c.setAttribute(`aria-live`,`polite`),r.append(i,c,o,a,s);let l=document.createElement(`div`);l.className=`mermaid-frame diagram-preview-frame`;let{width:u,height:d}=pe(n),f=j.default,p=1,m=null,h=null,g=!1,_=0,v=!1,y=null,b=0,ee=0,te=0,S=0;n.style.display=`block`,n.style.margin=`0 auto`,n.style.maxWidth=`none`;let C=()=>{let e=fe(l);if(!Number.isFinite(u)||u<=0||e.width<=0)return j.default;let t=e.width/u;return!Number.isFinite(t)||t<=0?j.default:x(t,j.min,j.max)},ne=e=>{f=x(e,j.min,j.max),n.style.width=`${u*f}px`,n.style.height=`${d*f}px`,c.textContent=`${Math.round(f*100)}%`,i.disabled=f<=j.min,a.disabled=f>=j.max;let t=fe(l),r=u*f>t.width||d*f>t.height;l.classList.toggle(`is-pannable`,r),n.style.margin=r?`0`:`0 auto`},re=()=>({x:l.scrollLeft+l.clientWidth/2,y:l.scrollTop+l.clientHeight/2}),ie=(e,t,n)=>{if(e===0)return;let r=t/e;l.scrollLeft=n.x*r-l.clientWidth/2,l.scrollTop=n.y*r-l.clientHeight/2},ae=e=>{let t=x(e,j.min,j.max),n=f;if(t===n)return;let r=re(),i=performance.now();m&&cancelAnimationFrame(m);let a=e=>{let o=x((e-i)/j.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(ne(c),ie(n,c,r),o<1){m=requestAnimationFrame(a);return}m=null,ne(t),ie(n,t,r)};m=requestAnimationFrame(a)},w=e=>{g=!0,ae(f+e)},T=({animate:e=!1}={})=>{if(p=C(),g=!1,_=fe(l).width,e&&Math.abs(p-f)>.001){ae(p);return}m&&=(cancelAnimationFrame(m),null),ne(p),l.scrollLeft=0,l.scrollTop=0},E=({force:t=!1}={})=>{h&&cancelAnimationFrame(h),h=requestAnimationFrame(()=>{if(h=null,!e.isConnected)return;let n=fe(l).width,r=Math.abs(n-_)>1;!t&&g||!t&&_>0&&!r||T()})};this.shellRefits.set(e,E),i.addEventListener(`click`,()=>w(-j.step)),a.addEventListener(`click`,()=>w(j.step)),o.addEventListener(`click`,()=>{T({animate:!0})});let D=()=>{let t=e.classList.contains(`is-maximized`);M(s,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;s.setAttribute(`aria-label`,n),s.title=n},oe=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.mermaid-maximize-btn`);e&&(M(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`mermaid-maximized-open`),D(),E({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`mermaid-maximized-open`),D(),E({force:!0})};D(),s.addEventListener(`click`,()=>{oe(!e.classList.contains(`is-maximized`))});let O=()=>{if(v){if(v=!1,l.classList.remove(`is-dragging`),y!==null&&typeof l.releasePointerCapture==`function`)try{l.releasePointerCapture(y)}catch{}y=null}};l.addEventListener(`pointerdown`,e=>{e.button!==0||!l.classList.contains(`is-pannable`)||(m&&=(cancelAnimationFrame(m),null),v=!0,y=e.pointerId,b=e.clientX,ee=e.clientY,te=l.scrollLeft,S=l.scrollTop,l.classList.add(`is-dragging`),l.setPointerCapture?.(e.pointerId),e.preventDefault())}),l.addEventListener(`pointermove`,e=>{v&&(l.scrollLeft=te-(e.clientX-b),l.scrollTop=S-(e.clientY-ee))}),l.addEventListener(`pointerup`,O),l.addEventListener(`pointercancel`,O),l.addEventListener(`lostpointercapture`,O),l.appendChild(n);let k=e.querySelector(`.mermaid-source`);t.remove(),e.replaceChildren(),k&&(k.hidden=!0,e.appendChild(k)),e.append(r,l),E({force:!0})}scheduleActiveRefit(){let e=this.syncActiveShell();if(e){this.shellRefits.get(e)?.();return}let t=this.renderer.previewElement;t&&Array.from(t.querySelectorAll(`.mermaid-shell[data-mermaid-hydrated="true"]`)).forEach(e=>{this.shellRefits.get(e)?.()})}createZoomButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`mermaid-zoom-btn ui-preview-action`,n.setAttribute(`aria-label`,t),n.title=t,n.textContent=e,n}},Me=class extends Ae{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.renderer=e,this.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map,this.shellRefits=new WeakMap,this.activeMaximizedShell=null,this.maximizedRoot=null,this.resizeFrameId=null}destroy(){this.cancelHydration(),this.preservedShells.clear(),this.clearActiveShell(),this.resizeFrameId&&=(cancelAnimationFrame(this.resizeFrameId),null),this.maximizedRoot?.remove(),this.maximizedRoot=null}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.clearActiveShell(),null)}scheduleActiveRefit(){this.resizeFrameId&&cancelAnimationFrame(this.resizeFrameId),this.resizeFrameId=requestAnimationFrame(()=>{this.resizeFrameId=null;let e=this.syncActiveShell();e&&this.shellRefits.get(e)?.()})}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`plantuml-maximized-open`),this.syncActiveShell()}ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-plantuml-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.plantumlMaximizedRoot=`true`,e.className=`plantuml-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}mountShellInMaximizedRoot(e){if(!e)return;let t=this.ensureMaximizedRoot();t.hidden=!1,e._plantumlRestoreParent=e.parentElement||null,e._plantumlRestoreNextSibling=e.nextSibling||null,t.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._plantumlRestoreParent,n=e._plantumlRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._plantumlRestoreParent=null,e._plantumlRestoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}async hydrateShell(e){if(!e?.isConnected||this.isShellHydrated(e))return;let t=e.querySelector(`.plantuml-source`);t||(t=document.createElement(`span`),t.className=`plantuml-source`,t.hidden=!0,e.appendChild(t)),e.querySelector(`.plantuml-placeholder-card`)?.remove();try{let n=t.textContent??``;if(!n.trim()&&e.dataset.plantumlTarget){if(n=await this.fetchSource(e.dataset.plantumlTarget),!e.isConnected)return;t.textContent=n}if(!n.trim())throw Error(e.dataset.plantumlTarget?`PlantUML file is empty`:`PlantUML source is empty`);let r=await this.fetchSvg(n);if(!e.isConnected)return;this.enhanceDiagram(e,r),this.markShellHydrated(e)}catch(n){console.warn(`[preview] PlantUML render failed:`,n),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||t?.after(ye(e.dataset.plantumlKey||`plantuml`,n instanceof Error?n.message:`Render failed`))}}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=be(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.shellRefits.delete(e),this.activeMaximizedShell===e&&(this.restoreShellMount(e),this.clearActiveShell()),e.removeAttribute(`data-plantuml-hydrated`),e.removeAttribute(`data-plantuml-instance-id`),e.removeAttribute(`data-plantuml-queued`),e.classList.remove(`is-maximized`),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||e.querySelector(`.plantuml-source`)?.after(ye(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 i=document.createElement(`div`);i.className=`plantuml-toolbar diagram-preview-toolbar`;let a=document.createElement(`div`);a.className=`plantuml-frame diagram-preview-frame`;let o=this.createToolButton(`−`,`Zoom out`),s=this.createToolButton(`+`,`Zoom in`),c=this.createToolButton(`Reset`,`Reset zoom`),l=this.createToolButton(`Reload`,`Reload diagram`),u=this.createToolButton(`Max`,`Maximize diagram`);u.classList.add(`plantuml-maximize-btn`),M(l,`refresh`),M(u,`maximize`);let d=document.createElement(`span`);d.className=`plantuml-zoom-label diagram-preview-zoom-label`,d.setAttribute(`aria-live`,`polite`),i.append(o,d,c,s,l,u);let{width:f,height:p}=_e(r),m=A.default,h=1,g=null,_=!1,v=null,y=0,b=0,ee=0,te=0;r.style.display=`block`,r.style.margin=`0 auto`,r.style.maxWidth=`none`;let S=()=>{let e=fe(a);return!Number.isFinite(f)||f<=0||e.width<=0?A.default:x(Math.min(A.default,e.width/f),A.min,A.max)},C=e=>{m=x(e,A.min,A.max),r.style.width=`${f*m}px`,r.style.height=`${p*m}px`,d.textContent=`${Math.round(m*100)}%`,o.disabled=m<=A.min,s.disabled=m>=A.max;let t=fe(a),n=f*m>t.width||p*m>t.height;a.classList.toggle(`is-pannable`,n)},ne=()=>({x:a.scrollLeft+a.clientWidth/2,y:a.scrollTop+a.clientHeight/2}),re=(e,t,n)=>{if(e===0)return;let r=t/e;a.scrollLeft=n.x*r-a.clientWidth/2,a.scrollTop=n.y*r-a.clientHeight/2},ie=e=>{let t=x(e,A.min,A.max),n=m;if(t===n)return;let r=ne(),i=performance.now();g&&cancelAnimationFrame(g);let a=e=>{let o=x((e-i)/A.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(C(c),re(n,c,r),o<1){g=requestAnimationFrame(a);return}g=null,C(t),re(n,t,r)};g=requestAnimationFrame(a)},ae=e=>{ie(m+e)},w=({animate:e=!1}={})=>{if(h=S(),e&&Math.abs(h-m)>.001){ie(h);return}g&&=(cancelAnimationFrame(g),null),C(h),a.scrollLeft=0,a.scrollTop=0},T=null,E=()=>{T&&cancelAnimationFrame(T),T=requestAnimationFrame(()=>{T=null,e.isConnected&&w()})};this.shellRefits.set(e,E),o.addEventListener(`click`,()=>ae(-A.step)),s.addEventListener(`click`,()=>ae(A.step)),c.addEventListener(`click`,()=>{w({animate:!0})});let D=()=>{let t=e.classList.contains(`is-maximized`);M(u,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;u.setAttribute(`aria-label`,n),u.title=n},oe=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.plantuml-maximize-btn`);e&&(M(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`plantuml-maximized-open`),D(),E();return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),D(),E()};l.addEventListener(`click`,()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})}),D(),u.addEventListener(`click`,()=>{oe(!e.classList.contains(`is-maximized`))});let O=()=>{if(_){if(_=!1,a.classList.remove(`is-dragging`),v!==null&&typeof a.releasePointerCapture==`function`)try{a.releasePointerCapture(v)}catch{}v=null}};a.addEventListener(`pointerdown`,e=>{e.button!==0||!a.classList.contains(`is-pannable`)||(g&&=(cancelAnimationFrame(g),null),_=!0,v=e.pointerId,y=e.clientX,b=e.clientY,ee=a.scrollLeft,te=a.scrollTop,a.classList.add(`is-dragging`),a.setPointerCapture?.(e.pointerId),e.preventDefault())}),a.addEventListener(`pointermove`,e=>{_&&(a.scrollLeft=ee-(e.clientX-y),a.scrollTop=te-(e.clientY-b))}),a.addEventListener(`pointerup`,O),a.addEventListener(`pointercancel`,O),a.addEventListener(`lostpointercapture`,O),a.appendChild(r);let k=e.querySelector(`.plantuml-source`);e.replaceChildren(),k&&(k.hidden=!0,e.appendChild(k)),e.append(i,a),h=S(),C(h)}createToolButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`plantuml-tool-btn ui-preview-action`,n.setAttribute(`aria-label`,t),n.title=t,n.textContent=e,n}};function Ne(){return new Worker(new URL(``+new URL(`preview-render-worker-C4AFtMIr.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var Pe=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=xe,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-D3QM1Ryz.js`),__vite__mapDeps([22,23,24,4,25,26]),import.meta.url),createWorkerFn:i=Ne,getFileList:a,getSourceFilePath:o=null,idleTimeoutMs:s=500,requestIdleRenderFn:c=me}={}){this.attachmentApiPath=t,this.cancelIdleRenderFn=n,this.compilePreviewDocumentLoader=r,this.createWorkerFn=i,this.getFileList=a,this.getSourceFilePath=o,this.idleTimeoutMs=s,this.requestIdleRenderFn=c,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?.()??``})})}let{compilePreviewDocument:i}=await this.compilePreviewDocumentLoader();return i({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,sourceFilePath:this.getSourceFilePath?.()??``})}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)}},Fe=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=xe,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:i=r,idleTimeoutMs:a=500,requestAnimationFrameFn:o=e=>requestAnimationFrame(e),requestIdleRenderFn:s=me,setTimeoutFn:c=(e,t)=>setTimeout(e,t)}={}){this.cancelAnimationFrameFn=e,this.cancelIdleRenderFn=t,this.clearTimeoutFn=n,this.getRenderProfileFn=i,this.idleTimeoutMs=a,this.requestAnimationFrameFn=o,this.requestIdleRenderFn=s,this.setTimeoutFn=c,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)})};this.timeoutId=this.setTimeoutFn(()=>{if(r.deferUntilIdle){this.idleId=this.requestIdleRenderFn(()=>{this.idleId=null,i()},this.idleTimeoutMs);return}i()},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()}},Ie=class{constructor({getContent:e,getFileList:t,loadFileSource:n=null,getSourceFilePath:i,onAfterRenderCommit:a,onBeforeRenderCommit:o,onPreviewLayoutChange:s,onRenderComplete:c,outlineController:l,plantUmlRenderClient:u=null,previewContainer:d,previewElement:f}){this.getContent=e,this.getFileList=t,this.loadFileSource=n,this.getSourceFilePath=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.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(),this.enqueueMermaidShell(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(),this.enqueuePlantUmlShell(t,{prioritize:!0})}},this.handleWindowResize=()=>{this.mermaidHydrator.scheduleActiveRefit(),this.plantUmlHydrator.scheduleActiveRefit()},this.mermaidHydrator=new je(this,{loadFileSource:n}),this.plantUmlHydrator=new Me(this,{loadFileSource:n,renderClient:u}),this.renderScheduler=new Fe({getRenderProfileFn:r}),this.renderExecutor=new Pe({attachmentApiPath:w(`/attachment`),getFileList:()=>this.getFileList?.()??[],getSourceFilePath:()=>this.getSourceFilePath?.()??``,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.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.cancelScheduledRender(),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),this.mermaidHydrator.clearPreservedShells(),this.plantUmlHydrator.clearPreservedShells(),this.clearActivePlantUmlShell(),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.resetWorker(`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)}configureMermaid(e){this.mermaidHydrator.configureMermaid(e)}ensureMermaid(){return this.mermaidHydrator.ensureMermaid()}queueRender(){let e=this.getContent();this.cancelScheduledRender(),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.compilePreview(e,t);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.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)}cancelScheduledRender(){this.renderScheduler.cancel()}cancelMermaidHydration(){this.mermaidHydrator.cancelHydration()}cancelPlantUmlHydration(){this.plantUmlHydrator.cancelHydration()}clearActivePlantUmlShell(){this.plantUmlHydrator.clearActiveShell()}scheduleActiveMermaidRefit(){this.mermaidHydrator.scheduleActiveRefit()}syncActivePlantUmlShell(){return this.plantUmlHydrator.syncActiveShell()}scheduleActivePlantUmlRefit(){this.plantUmlHydrator.scheduleActiveRefit()}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()}resetWorker(e,{disable:t=!1}={}){this.renderExecutor.reset(e,{disable:t})}scheduleWorkerPrewarm({timeout:e=500}={}){this.renderExecutor.schedulePrewarm({timeout:e})}async compilePreview(e,t){return this.renderExecutor.compile(e,t,{frontmatterCollapsed:this.frontmatterCollapsed,frontmatterInteractive:!0})}commitBaseRender({html:e,stats:t},n){this.activeRenderVersion=n,this.readyRenderVersion=0,this.currentStats=t,this.isLargeDocument=i(t),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),document.body.classList.remove(`mermaid-maximized-open`),document.body.classList.remove(`plantuml-maximized-open`),this.preserveHydratedMermaidsForCommit(),this.preserveHydratedPlantUmlsForCommit(),this.onBeforeRenderCommit?.(this.previewElement);let r=this.ensureRenderHost();this.normalizePreviewChildren(r),r&&(r.innerHTML=e),this.applyFrontmatterState(),this.reconcileHydratedMermaids(),this.reconcileHydratedPlantUmls(),this.setPhase(`base`),this.outlineController.refresh(),this.onAfterRenderCommit?.(this.previewElement,{...t,isLargeDocument:this.isLargeDocument,renderVersion:n});let a=this.setupMermaidHydration(n),o=this.setupPlantUmlHydration(n);a===0&&o===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})}preserveHydratedMermaidsForCommit(){this.mermaidHydrator.preserveHydratedShellsForCommit()}preserveHydratedPlantUmlsForCommit(){this.plantUmlHydrator.preserveHydratedShellsForCommit()}reconcileHydratedMermaids(){this.mermaidHydrator.reconcileHydratedShells()}reconcileHydratedPlantUmls(){this.plantUmlHydrator.reconcileHydratedShells()}syncPreservedMermaidShell(e,t){this.mermaidHydrator.syncPreservedShell(e,t)}syncPreservedPlantUmlShell(e,t){this.plantUmlHydrator.syncPreservedShell(e,t)}setupMermaidHydration(e){return this.mermaidHydrator.setupHydration(e)}hydrateVisibleMermaids(){this.mermaidHydrator.hydrateVisibleShells()}enqueueMermaidShell(e,{prioritize:t=!1}={}){this.mermaidHydrator.enqueueShell(e,{prioritize:t})}scheduleMermaidHydration(){this.mermaidHydrator.scheduleHydration()}async flushMermaidHydrationQueue(){await this.mermaidHydrator.flushHydrationQueue()}async hydrateMermaidShell(e,t){await this.mermaidHydrator.hydrateShell(e,t)}resetHydratedMermaids(){this.mermaidHydrator.resetHydratedShells()}setupPlantUmlHydration(e){return this.plantUmlHydrator.setupHydration(e)}hydrateVisiblePlantUmls(){this.plantUmlHydrator.hydrateVisibleShells()}enqueuePlantUmlShell(e,{prioritize:t=!1}={}){this.plantUmlHydrator.enqueueShell(e,{prioritize:t})}schedulePlantUmlHydration(){this.plantUmlHydrator.scheduleHydration()}async flushPlantUmlHydrationQueue(){await this.plantUmlHydrator.flushHydrationQueue()}async hydratePlantUmlShell(e){await this.plantUmlHydrator.hydrateShell(e)}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 fetchPlantUmlSvg(e){return this.plantUmlHydrator.fetchSvg(e)}async fetchPlantUmlSource(e){return this.plantUmlHydrator.fetchSource(e)}async fetchMermaidSource(e){return this.mermaidHydrator.fetchSource(e)}resetPlantUmlShell(e,{clearCache:t=!1,message:n=`Renders server-side when visible`}={}){this.plantUmlHydrator.resetShell(e,{clearCache:t,message:n})}enhancePlantUmlDiagram(e,t){this.plantUmlHydrator.enhanceDiagram(e,t)}enhanceMermaidDiagram(e,t){this.mermaidHydrator.enhanceDiagram(e,t)}createMermaidZoomButton(e,t){return this.mermaidHydrator.createZoomButton(e,t)}createPlantUmlToolButton(e,t){return this.plantUmlHydrator.createToolButton(e,t)}};async function Le(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,onFileSelect:t=>e.handleFileSelection(t,{closeSidebarOnMobile:!0})}),e.quickSwitcher}async function Re(e){try{(await Le(e)).toggle()}catch{}}var ze=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,resetPreviewMode:y,scrollSyncController:b,setSession:x,setSessionLoadToken:ee,setSidebarTab:te,setCurrentFilePath:S,showGitCommit:C,showGitDiff:ne,showGitFileHistory:re,showGitFilePreview:ie,showGitHistory:ae,syncMainChrome:w,videoEmbed:T,workspaceCoordinator:E,layoutController:D}){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.resetPreviewMode=y,this.scrollSyncController=b,this.setSession=x,this.setSessionLoadToken=ee,this.setSidebarTab=te,this.setCurrentFilePath=S,this.showGitCommit=C,this.showGitDiff=ne,this.showGitFileHistory=re,this.showGitFilePreview=ie,this.showGitHistory=ae,this.syncMainChrome=w,this.videoEmbed=T,this.workspaceCoordinator=E,this.layoutController=D}async handleHashChange(){if(!this.getIsTabActive())return;let e=this.navigation.getHashRoute();if(e.type===`empty`){this.gitPanel.setSelection(),this.showEmptyState(),this.syncMainChrome({mode:`empty`,title:`CollabMD`});return}if(e.type===`git-diff`){this.setSidebarTab(`git`),await this.showGitDiff(e);return}if(e.type===`git-file-history`){this.setSidebarTab(`files`),await this.showGitFileHistory(e);return}if(e.type===`git-file-preview`){this.setSidebarTab(`files`),await this.showGitFilePreview(e);return}if(e.type===`git-history`){this.setSidebarTab(`git`),await this.showGitHistory();return}if(e.type===`git-commit`){this.setSidebarTab(`git`),await this.showGitCommit(e);return}this.setSidebarTab(`files`),await this.openFile(e.filePath,{drawioMode:e.drawioMode||null})}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={}){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())}cleanupSession(){this.workspaceCoordinator.cleanupSession(),this.setSession(this.workspaceCoordinator.getSession())}handleFileSelection(e,{closeSidebarOnMobile:t=!1}={}){t&&this.closeSidebarOnMobile(),this.navigation.navigateToFile(e)}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()}};function N(e){let t=String(e??``).trim().replace(/\\/g,`/`).replace(/^\/+/u,``).split(`/`).map(e=>e.trim()).filter(Boolean);return t.some(e=>e===`.`||e===`..`)?``:t.join(`/`)}function P(e,t){let n=N(e),r=N(t);return n?r?`${n}/${r}`:n:r}function Be(e,t){return e.toLowerCase().endsWith(t.toLowerCase())?e:`${e}${t}`}function Ve(e){return`# ${c(String(e??``).split(`/`).pop()||``)||`Untitled`}\n\n`}function He(e){let t=N(e),n=l(t)?t:`${t}.base`;return{content:[`views:`,` - type: table`,` name: Table`,` order:`,` - file.name`,``].join(`
|
|
24
|
+
`),path:n}}function Ue(e){let t=N(e),n=v(t)?t:`${t}.mmd`;return{content:[`flowchart TD`,` A[Start] --> B{Decide}`,` B -->|Yes| C[Ship it]`,` B -->|No| D[Revise]`,``].join(`
|
|
25
|
+
`),path:n}}function We(e){let t=N(e),n=p(t)?t:`${t}.drawio`;return{content:[`<mxfile host="app.diagrams.net" modified="2026-01-01T00:00:00.000Z" agent="CollabMD" version="24.7.17">`,` <diagram id="page-1" name="Page-1">`,` <mxGraphModel dx="1200" dy="800" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">`,` <root>`,` <mxCell id="0" />`,` <mxCell id="1" parent="0" />`,` </root>`,` </mxGraphModel>`,` </diagram>`,`</mxfile>`,``].join(`
|
|
26
|
+
`),path:n}}function Ge(e){let t=N(e),n=s(t)?t:`${t}.puml`;return{content:[`@startuml`,`Alice -> Bob: Hello`,`@enduml`,``].join(`
|
|
27
|
+
`),path:n}}var Ke=class{constructor({getFileList:e,navigation:t,refreshExplorer:n,toastController:r,vaultApiClient:i}){this.getFileList=e,this.navigation=t,this.refreshExplorer=n,this.toastController=r,this.vaultApiClient=i}handleWikiLinkClick(e){let t=y(e,this.getFileList());if(t){this.navigation.navigateToFile(t);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=N(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:Ve(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},qe=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:n,elements:r,excalidrawEmbed:i,getDisplayName:a,getSession:o,isDrawioFile:s,isExcalidrawFile:c,isBaseFile:u,isImageFile:d,isMermaidFile:f,isPlantUmlFile:p,layoutController:m,outlineController:h,previewRenderer:g,schedulePreviewLayoutSync:_,scrollSyncController:v,videoEmbed:y}){this.backlinksPanel=e,this.basesPreview=t??{reconcileEmbeds(){},renderStandalone(){}},this.drawioEmbed=n??{detachForCommit(){},hydrateVisibleEmbeds(){},reconcileEmbeds(){},setHydrationPaused(){},syncLayout(){},updateLocalUser(){},updateTheme(){}},this.elements=r,this.excalidrawEmbed=i,this.getDisplayName=a,this.getSession=o,this.isDrawioFile=s??(()=>!1),this.isExcalidrawFile=c??(()=>!1),this.isBaseFile=u??l,this.isImageFile=d??(()=>!1),this.isMermaidFile=f??(()=>!1),this.isPlantUmlFile=p??(()=>!1),this.layoutController=m,this.outlineController=h,this.previewRenderer=g,this.schedulePreviewLayoutSyncCallback=_,this.scrollSyncController=v,this.videoEmbed=y}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.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-mermaid-file-preview`),this.elements.previewContent?.classList.remove(`is-plantuml-file-preview`)}syncFileChrome(e,{drawioMode:t=null,preferPreviewForBase:n=!1}={}){let r=this.isDrawioFile(e),i=this.isExcalidrawFile(e),o=this.isBaseFile(e),s=this.isImageFile(e),c=u(e),l=this.isMermaidFile(e),d=this.isPlantUmlFile(e),f=a(e),p=i||r&&t!==`text`;if(this.backlinksPanel.setDisplayMode?.(p?`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`,f||s||o),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,d),r&&t!==`text`||i||s||o&&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=w(`/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})}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.replaceChildren(),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})}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.previewRenderer.scheduleActiveMermaidRefit(),this.previewRenderer.scheduleActivePlantUmlRefit(),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}))}},Je=class{constructor({attachEditorScroller:e,createEditorSession:t,loadEditorSessionClass:n,scrollContainerForSession:r}){this.attachEditorScroller=e,this.createEditorSession=t,this.loadEditorSessionClass=n,this.scrollContainerForSession=r}async createSession(e){let t=await this.loadEditorSessionClass();return this.createEditorSession(t,e)}attachSessionScroller(e){this.attachEditorScroller(this.scrollContainerForSession(e))}clearSessionScroller(){this.attachEditorScroller(null)}},Ye=class{constructor({beginDocumentLoad:e,getDisplayName:t,loadBacklinks:n,onBeforeFileOpen:r,onRenderDrawioPreview:i,onFileOpenError:a,onFileOpenReady:o,onRenderBasePreview:s,onRenderExcalidrawPreview:c,onRenderImagePreview:l,onSyncWrapToggle:u,onUpdateActiveFile:d,onUpdateCurrentFile:f,onUpdateLobbyCurrentFile:p,onUpdateVisibleChrome:m,onViewModeReset:h,renderPresence:g,showEditorLoading:_,stateStore:v}){this.beginDocumentLoad=e??(()=>{}),this.getDisplayName=t??(e=>e),this.loadBacklinks=n??(()=>{}),this.onBeforeFileOpen=r??(()=>{}),this.onRenderDrawioPreview=i??(()=>{}),this.onFileOpenError=a??(()=>{}),this.onFileOpenReady=o??(()=>{}),this.onRenderBasePreview=s??(()=>{}),this.onRenderExcalidrawPreview=c??(()=>{}),this.onRenderImagePreview=l??(()=>{}),this.onSyncWrapToggle=u??(()=>{}),this.onUpdateActiveFile=d??(()=>{}),this.onUpdateCurrentFile=f??(()=>{}),this.onUpdateLobbyCurrentFile=p??(()=>{}),this.onUpdateVisibleChrome=m??(()=>{}),this.onViewModeReset=h??(()=>{}),this.renderPresence=g??(()=>{}),this.showEditorLoading=_??(()=>{}),this.stateStore=v}prepareForFileOpen(e,{drawioMode:t=null,resetConnectionState:n=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.set(`connectionHelpShown`,!1),n&&this.stateStore.set(`connectionState`,{status:`connecting`,unreachable:!1}),this.stateStore.set(`currentDrawioMode`,t??null),this.stateStore.set(`currentFilePath`,e),this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:t,isMarkdown:u(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:m(e)}}markFileOpenReady(e){this.onFileOpenReady(e)}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:n,isExcalidraw:r=!1,isImage:i=!1,supportsBacklinks:a}){r&&this.onRenderExcalidrawPreview(n),(e||l(n))&&this.onRenderBasePreview(n),t&&this.onRenderDrawioPreview(n),i&&this.onRenderImagePreview(n),this.onSyncWrapToggle(),a&&this.loadBacklinks(n)}handleFileOpenError(){this.onFileOpenError()}},Xe=150;function Ze(e){return new Promise(t=>{setTimeout(t,e)})}var Qe=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getLocalUser:s,getStoredUserName:c,getTheme:l,isBaseFile:u,isDrawioFile:d,isExcalidrawFile:f,isImageFile:p,isMermaidFile:m,isPlantUmlFile:h,isTabActive:g,loadBootstrapContent:_=null,loadEditorSessionClass:v,loadBacklinks:y,onBeforeFileOpen:b,onConnectionChange:x,onContentChange:ee,onCommentsChange:te,onFileAwarenessChange:S,onFileOpenError:C,onFileOpenReady:ne,onImagePaste:re,onSelectionChange:ie,onSessionAssigned:ae=null,onFileOpenMetric:w=null,onRenderBasePreview:T,onRenderExcalidrawPreview:E,onRenderDrawioPreview:D,onRenderImagePreview:oe,onSyncWrapToggle:O,onUpdateActiveFile:k,onUpdateCurrentFile:se,onUpdateLobbyCurrentFile:ce,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:de,scrollContainerForSession:fe,shouldUseDrawioPreview:pe=null,showEditorLoading:me,stateStore:he}){this.attachEditorScroller=e,this.beginDocumentLoad=t,this.cleanupAfterSessionDestroy=n,this.createEditorSession=r,this.getDisplayName=i,this.getFileList=a,this.getLineWrappingEnabled=o,this.getLocalUser=s,this.getStoredUserName=c,this.getTheme=l,this.isBaseFile=u??(()=>!1),this.isDrawioFile=d??(()=>!1),this.isExcalidrawFile=f??(()=>!1),this.isImageFile=p??(()=>!1),this.isMermaidFile=m??(()=>!1),this.isPlantUmlFile=h??(()=>!1),this.isTabActive=g,this.loadBootstrapContent=_,this.loadEditorSessionClassPort=v,this.loadBacklinks=y,this.onBeforeFileOpen=b,this.onConnectionChange=x,this.onContentChange=ee,this.onCommentsChange=te,this.onFileAwarenessChange=S,this.onFileOpenError=C,this.onFileOpenReady=ne,this.onImagePaste=re,this.onSelectionChange=ie,this.onSessionAssigned=ae,this.onFileOpenMetric=w,this.onRenderBasePreview=T,this.onRenderExcalidrawPreview=E,this.onSyncWrapToggle=O,this.onUpdateActiveFile=k,this.onUpdateCurrentFile=se,this.onUpdateLobbyCurrentFile=ce,this.onUpdateVisibleChrome=le,this.renderPresence=de,this.shouldUseDrawioPreview=pe??(()=>!0),this.stateStore=he,this.session=null,this.lifecycle=new Je({attachEditorScroller:e,createEditorSession:r,loadEditorSessionClass:()=>this.loadEditorSessionClassPort(),scrollContainerForSession:fe}),this.chromeController=new Ye({beginDocumentLoad:t,getDisplayName:i,loadBacklinks:y,onBeforeFileOpen:b,onRenderDrawioPreview:D,onFileOpenError:C,onFileOpenReady:ne,onRenderBasePreview:T,onRenderExcalidrawPreview:E,onRenderImagePreview:oe,onSyncWrapToggle:O,onUpdateActiveFile:k,onUpdateCurrentFile:se,onUpdateLobbyCurrentFile:ce,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:de,showEditorLoading:me,stateStore:he})}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.get(`currentFilePath`),loadToken:t,...n})}cleanupSession(){this.session?.destroy(),this.session=null,this.lifecycle.clearSessionScroller(),this.cleanupAfterSessionDestroy()}async openFile(e,{drawioMode:t=null}={}){if(!this.isTabActive())return;let n=t??null,r=this.stateStore.get(`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.isMermaidFile(e),l=this.isPlantUmlFile(e);if(e===this.stateStore.get(`currentFilePath`)&&n===r&&(this.session||i||a||s)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let u=this.stateStore.nextSessionLoadToken(),d=performance.now();this.cleanupSession();let f=this.chromeController.prepareForFileOpen(e,{drawioMode:n,resetConnectionState:!i&&!a&&!s});if(this.reportFileOpenMetric(`open_started`,u,{filePath:e}),i||a||s){if(this.onSessionAssigned?.(null),u!==this.stateStore.get(`sessionLoadToken`))return;this.chromeController.markFileOpenReady(null),this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,session:null,supportsBacklinks:f.supportsBacklinks});return}let p=await this.lifecycle.createSession({filePath:e,getFileList:this.getFileList,lineWrappingEnabled:this.getLineWrappingEnabled(),localUser:this.getLocalUser(),onAwarenessChange:e=>this.onFileAwarenessChange(e),onConnectionChange:e=>this.onConnectionChange(e),onCommentsChange:e=>this.onCommentsChange?.(e),onContentChange:()=>{a||this.onContentChange({isBase:o,isMermaid:c,isPlantUml:l})},onImagePaste:e=>this.onImagePaste?.(e),preferredUserName:this.getStoredUserName(),onSelectionChange:e=>this.onSelectionChange?.(e),theme:this.getTheme()});this.session=p,this.onSessionAssigned?.(p);try{let t=!1,n=!1,r=!1,i=async r=>{t||u!==this.stateStore.get(`sessionLoadToken`)||(t=!0,this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.chromeController.markFileOpenReady(p),this.reportFileOpenMetric(`editor_ready`,u,{reason:r}),p.requestMeasure(),await this.waitForNextPaint(),!(n||u!==this.stateStore.get(`sessionLoadToken`))&&(n=!0,this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:p,supportsBacklinks:f.supportsBacklinks})))},s=this.loadBootstrapContent?(async()=>{this.reportFileOpenMetric(`bootstrap_fetch_started`,u);try{let t=await this.loadBootstrapContent(e);return this.reportFileOpenMetric(`bootstrap_fetch_completed`,u,{found:t!==null}),t}catch(e){return this.reportFileOpenMetric(`bootstrap_fetch_completed`,u,{error:e.message,found:!1}),null}})():Promise.resolve(null),c=p.initialize(e),l=(async()=>(await c,u!==this.stateStore.get(`sessionLoadToken`)||(await p.waitForInitialSync(null),u!==this.stateStore.get(`sessionLoadToken`))?!1:(r=!0,p.activateCollaborativeView?.(),this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,u),p.ensureInitialContent?.(),t?p.requestMeasure():await i(`live-sync`),!0)))(),m=(async()=>{let n=await s;if(n===null||r||t||u!==this.stateStore.get(`sessionLoadToken`))return!1;let a=performance.now()-d,o=Math.max(0,Xe-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),Ze(o).then(()=>`timeout`)])===`live-sync`||r||t||u!==this.stateStore.get(`sessionLoadToken`)||!p.showBootstrapContent({content:n,filePath:e})&&!p.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,u),await i(`bootstrap`),!0)})();if(await c,u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}if(await Promise.all([l,m]),u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}t||(p.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),p.destroy(),this.lifecycle.clearSessionScroller(),this.session===p&&(this.session=null),u!==this.stateStore.get(`sessionLoadToken`))return;this.chromeController.handleFileOpenError()}}},$e=class{constructor(e={}){this.state={activeSidebarTab:`files`,chatInitialSyncComplete:!1,chatIsOpen:!1,chatMessageIds:new Set,chatMessages:[],chatUnreadCount:0,connectionHelpShown:!1,connectionState:{status:`disconnected`,unreachable:!1},currentDrawioMode:null,currentFilePath:null,fileExplorerReady:!1,followedCursorSignature:``,followedUserClientId:null,gitRepoAvailable:!1,globalUsers:[],isTabActive:!1,sessionLoadToken:0,...e}}get(e){return this.state[e]}set(e,t){return this.state[e]=t,t}nextSessionLoadToken(){let e=Number(this.state.sessionLoadToken||0)+1;return this.state.sessionLoadToken=e,e}replaceChatState({initialSyncComplete:e,isOpen:t,messageIds:n,messages:r,unreadCount:i}){this.state.chatMessages=Array.isArray(r)?r:[],this.state.chatMessageIds=n instanceof Set?n:new Set,this.state.chatUnreadCount=Number.isFinite(i)?i:0,this.state.chatIsOpen=!!t,this.state.chatInitialSyncComplete=!!e}};function et(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`),chatNotificationButton:e.getElementById(`chatNotificationBtn`),chatPanel:e.getElementById(`chatPanel`),chatStatus:e.getElementById(`chatStatus`),chatToastContainer:e.getElementById(`chatToastContainer`),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`),searchFilesButton:e.getElementById(`searchFilesBtn`),shareButton:e.getElementById(`shareBtn`),toastContainer:e.getElementById(`toastContainer`),toggleWrapButton:e.getElementById(`toggleWrapBtn`),userAvatars:e.getElementById(`userAvatars`),userCount:e.getElementById(`userCount`),wrapToggleLabel:e.getElementById(`wrapToggleLabel`),activeFileName:e.getElementById(`activeFileName`),sidebarToggle:e.getElementById(`sidebarToggle`),sidebarClose:e.getElementById(`sidebarClose`),sidebar:e.getElementById(`sidebar`),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`),commentsToggleButton:e.getElementById(`commentsToggle`),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`),sidebarTabs:e.getElementById(`sidebarTabs`)}}var F={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();return}this.openChatPanel()},openChatPanel(){this.chatIsOpen=!0,this.chatUnreadCount=0,this.renderChat(),requestAnimationFrame(()=>{this.elements.chatInput?.focus(),this.scrollChatToBottom()})},closeChatPanel(){this.chatIsOpen&&(this.chatIsOpen=!1,this.renderChat())},handleChatSubmit(){if(!this.isTabActive)return;let e=this.elements.chatInput;if(e){if(!this.lobby.sendChatMessage(e.value)){e.focus();return}if(e.value=``,!this.chatIsOpen){this.openChatPanel();return}this.renderChat()}},renderChat(){this.elements.chatContainer?.classList.toggle(`is-open`,this.chatIsOpen),this.elements.chatPanel?.classList.toggle(`hidden`,!this.chatIsOpen),this.syncChatToggleButton(),this.syncChatNotificationButton();let e=this.elements.chatMessages,t=this.elements.chatEmptyState;if(this.elements.chatStatus&&(this.elements.chatStatus.textContent=this.chatInitialSyncComplete?`${this.globalUsers.length} online`:`Syncing...`),!e)return;if(e.replaceChildren(),this.chatMessages.length===0){t?.classList.remove(`hidden`),e.classList.add(`hidden`);return}t?.classList.add(`hidden`),e.classList.remove(`hidden`);let n=document.createDocumentFragment();this.chatMessages.forEach(e=>{n.appendChild(this.createChatMessageElement(e))}),e.appendChild(n),this.chatIsOpen&&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`,r.style.backgroundColor=e.userColor||`var(--color-primary)`,r.textContent=(e.userName||`?`).charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`div`);i.className=`chat-message-body`;let a=document.createElement(`div`);a.className=`chat-message-meta`;let o=document.createElement(`span`);o.className=`chat-message-author`,o.textContent=n?`${e.userName} (you)`:e.userName;let s=document.createElement(`span`);s.className=`chat-message-time`,s.textContent=this.formatChatTimestamp(e.createdAt),a.append(o,s);let c=this.getChatMessageFileLabel(e.filePath);if(c){let e=document.createElement(`span`);e.className=`chat-message-file`,e.textContent=c,a.append(e)}let l=document.createElement(`p`);return l.className=`chat-message-text`,l.textContent=e.text,i.append(a,l),t.append(r,i),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}`},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-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))},syncChatNotificationButton(){let e=this.elements.chatNotificationButton;if(!e)return;let t=this.notifications.getPermission();this.chatNotificationPermission=t;let n=`Enable alerts`,r=`Enable browser notifications for new chat messages`,i=!1;t===`unsupported`?(n=`No alerts`,r=`Browser notifications are unavailable here`):t===`denied`?(n=`Alerts blocked`,r=`Browser notifications are blocked for this site`):t===`granted`&&(i=this.chatNotificationsEnabled,n=i?`Alerts on`:`Alerts off`,r=i?`Disable browser notifications for chat`:`Enable browser notifications for chat`),e.textContent=n,e.title=r,e.setAttribute(`aria-pressed`,String(i)),e.classList.toggle(`is-enabled`,i),e.classList.toggle(`is-blocked`,t===`denied`)},async handleChatNotificationToggle(){let e=this.notifications.getPermission();if(this.chatNotificationPermission=e,e===`unsupported`){this.toastController.show(`Browser notifications are unavailable here`),this.syncChatNotificationButton();return}if(e===`denied`){this.chatNotificationsEnabled=!1,this.preferences.setChatNotificationsEnabled(!1),this.toastController.show(`Browser notifications are blocked for this site`),this.syncChatNotificationButton();return}if(e===`default`){let e=await this.notifications.requestPermission();if(this.chatNotificationPermission=e,e!==`granted`){this.chatNotificationsEnabled=!1,this.preferences.setChatNotificationsEnabled(!1),e===`denied`&&this.toastController.show(`Browser notifications were blocked`),this.syncChatNotificationButton();return}this.chatNotificationsEnabled=!0,this.preferences.setChatNotificationsEnabled(!0),this.syncChatNotificationButton();return}this.chatNotificationsEnabled=!this.chatNotificationsEnabled,this.preferences.setChatNotificationsEnabled(this.chatNotificationsEnabled),this.syncChatNotificationButton()},maybeNotifyChatMessage(e){if(this.chatInitialSyncComplete){if(document.hidden){this.maybeShowBrowserChatNotification(e);return}!this.isTabActive||this.chatIsOpen||(this.chatToastController??this.toastController).show(this.formatChatToastMessage(e),4e3)}},maybeShowBrowserChatNotification(e){if(!this.chatNotificationsEnabled||this.notifications.getPermission()!==`granted`)return;let t=`CollabMD chat • ${e.userName}`,n=this.getChatMessageFileLabel(e.filePath),r=n?`${n}: ${e.text}`:e.text,i=this.notifications.createNotification({body:r,onClick:()=>{e.filePath&&this.navigation.navigateToFile(e.filePath)},tag:`collabmd-chat-${e.id}`,title:t});i&&setTimeout(()=>{i.close?.()},6e3)}},tt={getCommentFileKind(e=this.currentFilePath){return f(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=d(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)},handleCommentEditorContentChange(){this.commentUi.handleEditorContentChange()},refreshCommentUiLayout(){this.commentUi.refreshLayout()}},nt=`collabmd-export-page`,rt=`collabmd-export-host`,it=500,at=6e4,ot=new Map,st=null;function ct(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function lt(e){return e===`pdf`?`pdf`:`docx`}function ut({filePath:e,format:t,jobId:n}){let r=new URL(re(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,lt(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function dt({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:lt(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:rt,title:String(a??``),type:`bootstrap`}}function ft(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function pt(e,{notifyError:t=!1,message:n=``}={}){let r=ot.get(e);r&&(ft(r),ot.delete(e),t&&n&&st?.(n))}function mt({onError:e=null}={}){st=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!==nt)return;let n=String(t.jobId??``).trim();if(!n)return;let r=ot.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){pt(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){pt(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&pt(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function ht({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=ct(),s=ut({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return ot.set(o,{closePollId:window.setInterval(()=>{c.closed&&pt(o,{message:`Export window was closed before the export completed`,notifyError:!0})},it),payload:dt({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{pt(o,{message:`Export timed out before it completed`,notifyError:!0})},at),window:c}),c.focus?.(),o}var gt={initializeExportBridge(){this._exportBridgeInitialized||=(mt({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!u(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await ht({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 _t(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function vt(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 yt(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 bt({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:_t(e),deletedPaths:_t(t),refreshExplorer:n!==!1,renamedPaths:vt(r)}}function xt(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:yt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:_t(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:bt(e.workspaceChange)}}function St(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`workspace-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Ct(e={}){return bt(e)}var I={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.toggle(`hidden`,!this.gitRepoAvailable),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.toolbarCenter?.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.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.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.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=St();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=Ct(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=Ct(e.workspaceChange);if(e.origin===`git`&&await this.refreshGitAfterAction(),this.handleWorkspaceChangeForCurrentFile(t,{action:e.action||e.origin||`workspace`,local:!1,showToast:!0}),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)}}}},L={updateGlobalUsers(e){this.globalUsers=e,this.syncFollowedUser(),this.renderAvatars(),this.renderChat(),this.renderPresence(),this.syncCurrentUserName()},updateFileAwareness(e){this.syncFollowedUser()},renderPresence(){let e=this.elements.userCount;if(!e)return;let t=!!this.session,n=!!(this.currentFilePath&&this.isDrawioFile?.(this.currentFilePath)),r=!!(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)),i=!!(this.currentFilePath&&this.isImageFile?.(this.currentFilePath)),a=!t&&(!this.currentFilePath||n||r||i)?this.lobby?.getConnectionState?.()??this.connectionState:this.connectionState;if(a.status===`connected`){e.textContent=`${this.globalUsers.length} online`,e.style.opacity=`1`;return}if(a.status===`connecting`){e.textContent=a.unreachable?`Unreachable`:`Connecting...`,e.style.opacity=`0.6`;return}e.textContent=`Offline`,e.style.opacity=`0.6`},renderAvatars(){let e=this.elements.userAvatars;if(!e)return;e.innerHTML=``;let t=[...this.globalUsers],n=t.findIndex(e=>e.isLocal);if(n>0){let[e]=t.splice(n,1);t.unshift(e)}let r=t.findIndex(e=>!e.isLocal&&e.clientId===this.followedUserClientId),i=+!!t[0]?.isLocal;if(r>i){let[e]=t.splice(r,1);t.splice(i,0,e)}if(t.slice(0,5).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.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>5){let n=document.createElement(`div`);n.className=`user-avatar`,n.style.backgroundColor=`var(--color-surface-dynamic)`,n.style.color=`var(--color-text-muted)`;let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=`+${t.length-5}`,n.appendChild(r),e.appendChild(n)}},toggleFollowUser(e){if(!e)return;if(this.followedUserClientId===e){this.stopFollowingUser();return}let t=this.globalUsers.find(t=>t.clientId===e&&!t.isLocal);if(t){if(this.followedUserClientId=e,this.followedCursorSignature=``,this.renderAvatars(),t.currentFile&&t.currentFile!==this.currentFilePath){this.navigation.navigateToFile(t.currentFile);return}requestAnimationFrame(()=>{this.followedUserClientId===e&&this.followUserCursor(t,{force:!0})})}},stopFollowingUser(){this.followedUserClientId&&(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)&&this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,null),this.followedUserClientId=null,this.followedCursorSignature=``,this.renderAvatars())},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 wt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function Tt({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 Et(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function Dt(){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):Te(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 Ot(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function kt(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function At(){return this.preferences.getUserName()}function jt(){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 Mt(){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 Nt={getCurrentUser:Ot,getCurrentUserName:kt,getStoredUserName:At,handleDisplayNameSubmit:Dt,isIdentityManagedByAuth:wt,openDisplayNameDialog:Tt,promptForDisplayNameIfNeeded:Et,syncCurrentUserName:jt,syncIdentityManagementUi:Mt},Pt=0;function Ft(){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.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncToolbarOverflowVisibility?.(),this.syncChatNotificationButton(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.gitPanel.refresh({force:!0}),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.handleHashChange());let e=this.createResizeHandler();window.addEventListener(`resize`,()=>{e(),this.syncToolbarOverflowVisibility?.()}),this.fileExplorerReadyPromise=this.fileExplorer.refresh().then(()=>{if(this.fileExplorerReady=!0,this.isTabActive)return this.handleHashChange()})}function It(){this.versionMonitor?.start()}function Lt(){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 Rt(){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 zt(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:Pt,onAction:()=>window.location.reload()})}function Bt(){this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.searchFilesButton?.addEventListener(`click`,()=>{this.toggleQuickSwitcher(),this.closeToolbarOverflowMenu?.()}),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 Vt(){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 Ht(){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.toggleChatPanel(),this.closeToolbarOverflowMenu?.()}),this.elements.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),Bt.call(this),Vt.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.editorFindButton?.addEventListener(`click`,()=>{this.runEditorCommand?.(`openSearch`)}),this.elements.toolbarOverflowToggle?.addEventListener(`click`,e=>{e.preventDefault(),this.toggleToolbarOverflowMenu()}),this.elements.toolbarOverflowMenu?.addEventListener(`click`,e=>{e.target instanceof Element&&e.target.closest(`button`)&&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.filesSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`files`)}),this.elements.gitSidebarTab?.addEventListener(`click`,()=>{this.gitRepoAvailable&&this.setSidebarTab(`git`)}),document.addEventListener(`pointerdown`,e=>{this.handleDocumentPointerDown(e)}),document.addEventListener(`keydown`,e=>{this.handleDocumentKeydown(e)},{capture:!0})}function Ut(e){this.handleMarkdownToolbarDocumentPointerDown?.(e),this.toolbarOverflowOpen&&!this.elements.toolbarOverflowMenu?.contains(e.target)&&!this.elements.toolbarOverflowToggle?.contains(e.target)&&this.closeToolbarOverflowMenu(),this.chatIsOpen&&(this.elements.chatContainer?.contains(e.target)||this.closeChatPanel())}function Wt(e){if(e.key===`Escape`&&this.toolbarOverflowOpen){this.closeToolbarOverflowMenu();return}if(e.key===`Escape`&&this.chatIsOpen){this.closeChatPanel();return}ee(e)&&(e.preventDefault(),e.stopPropagation(),this.toggleQuickSwitcher())}function Gt(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function Kt(e){return e.closest(`input[data-task-checkbox="true"]`)?!1:!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function qt(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`a.wiki-link[data-wiki-target]`);if(t){e.preventDefault(),this.handleWikiLinkClick(t.dataset.wikiTarget);return}let n=e.target.closest(`.task-list-item[data-source-line]`);if(!n||Gt(e.target,n)||Kt(e.target))return;e.preventDefault();let r=Number.parseInt(n.getAttribute(`data-source-line`)||``,10);Number.isFinite(r)&&this.session?.toggleTaskListItem?.(r)}function Jt(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 Yt(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Xt(){this.setToolbarOverflowOpen(!1)}function Zt(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function Qt(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e)}function $t(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function en(){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 tn(){return this.preferences.getLineWrappingEnabled()}function nn(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 rn(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{m(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function an(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
28
|
+
<div class="editor-loading" id="editorLoading">
|
|
29
|
+
<div class="loading-spinner"></div>
|
|
30
|
+
<span class="loading-text">Loading file...</span>
|
|
31
|
+
</div>`)}function on(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.querySelector(`#editorLoading`)?.remove())}function sn(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
32
|
+
<div class="editor-loading" id="editorLoading">
|
|
33
|
+
<span class="loading-text">Failed to load file</span>
|
|
34
|
+
</div>`)}function cn(){document.documentElement.removeAttribute(`data-initial-file-requested`)}var ln={bindEvents:Ht,clearInitialFileBootstrap:cn,closeToolbarOverflowMenu:Xt,getStoredLineWrapping:tn,handleConnectionChange:$t,handleDocumentKeydown:Wt,handleDocumentPointerDown:Ut,handlePreviewContentClick:qt,handleThemeChange:Qt,hideEditorLoading:on,initialize:Ft,initializeVisualViewportBinding:Rt,initializeVersionMonitoring:It,isPlainQuickSwitcherShortcut:ee,promptForVersionReload:zt,scheduleBacklinkRefresh:rn,setToolbarOverflowOpen:Jt,showEditorLoadError:sn,showEditorLoading:an,syncVisualViewportBounds:Lt,syncToolbarOverflowVisibility:Yt,syncWrapToggle:nn,toggleToolbarOverflowMenu:Zt,toggleLineWrapping:en};function un(){return this.mobileBreakpointQuery.matches}function dn(){let e=this.elements.sidebar;!e||!this.isMobileViewport()||e.classList.contains(`collapsed`)||this.setSidebarVisibility(!1)}function fn(){let e=this.elements.sidebar;if(!e)return;let t=e.classList.contains(`collapsed`);this.setSidebarVisibility(t)}function pn(){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 mn(e){this.applySidebarVisibility(e),this.preferences.setSidebarVisible(e)}function hn(e){let t=this.elements.sidebar;if(!t)return;let n=!e,r=n&&this.isMobileViewport();t.classList.toggle(`collapsed`,n),t.toggleAttribute(`hidden`,r),t.setAttribute(`aria-hidden`,r?`true`:`false`),t.inert=n}function gn(e){let t=e===`git`&&this.gitRepoAvailable?`git`:`files`;this.activeSidebarTab=t,this.elements.filesSidebarTab?.classList.toggle(`active`,t===`files`),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.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`)}var _n={applySidebarVisibility:hn,closeSidebarOnMobile:dn,isMobileViewport:un,restoreSidebarState:pn,setSidebarTab:gn,setSidebarVisibility:mn,toggleSidebar:fn};function vn(){this.tabActivityLock.tryActivate({takeover:!0})}function yn({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.handleHashChange(),this.promptForDisplayNameIfNeeded()),e&&this.toastController.show(`This tab is now active`)}async function bn({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.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 xn({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 Sn(){this.elements.tabLockOverlay?.classList.add(`hidden`)}var Cn={handleTabActivated:yn,handleTabBlocked:bn,handleTabTakeover:vn,hideTabLockOverlay:Sn,showTabLockOverlay:xn},R=Object.freeze({bold:`
|
|
35
|
+
<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">
|
|
36
|
+
<path d="M7 5h6a4 4 0 0 1 0 8H7z"/>
|
|
37
|
+
<path d="M7 13h7a4 4 0 0 1 0 8H7z"/>
|
|
38
|
+
</svg>
|
|
39
|
+
`,italic:`
|
|
40
|
+
<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">
|
|
41
|
+
<path d="M14 4h6"/>
|
|
42
|
+
<path d="M4 20h6"/>
|
|
43
|
+
<path d="M14 4 10 20"/>
|
|
44
|
+
</svg>
|
|
45
|
+
`,strikethrough:`
|
|
46
|
+
<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">
|
|
47
|
+
<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"/>
|
|
48
|
+
<path d="M3 12h18"/>
|
|
49
|
+
</svg>
|
|
50
|
+
`,link:`
|
|
51
|
+
<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">
|
|
52
|
+
<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"/>
|
|
53
|
+
<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"/>
|
|
54
|
+
</svg>
|
|
55
|
+
`,image:`
|
|
56
|
+
<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">
|
|
57
|
+
<rect x="3" y="5" width="18" height="14" rx="2"/>
|
|
58
|
+
<circle cx="9" cy="10" r="1.5"/>
|
|
59
|
+
<path d="m21 16-5.5-5.5L7 19"/>
|
|
60
|
+
</svg>
|
|
61
|
+
`,video:`
|
|
62
|
+
<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">
|
|
63
|
+
<rect x="3" y="5" width="18" height="14" rx="2"/>
|
|
64
|
+
<path d="m10 9 5 3-5 3z" fill="currentColor" stroke="none"/>
|
|
65
|
+
</svg>
|
|
66
|
+
`,table:`
|
|
67
|
+
<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">
|
|
68
|
+
<rect x="3" y="5" width="18" height="14" rx="1"/>
|
|
69
|
+
<path d="M3 10h18"/>
|
|
70
|
+
<path d="M9 5v14"/>
|
|
71
|
+
<path d="M15 5v14"/>
|
|
72
|
+
</svg>
|
|
73
|
+
`,code:`
|
|
74
|
+
<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">
|
|
75
|
+
<path d="m8 9-4 3 4 3"/>
|
|
76
|
+
<path d="m16 9 4 3-4 3"/>
|
|
77
|
+
<path d="m13 6-2 12"/>
|
|
78
|
+
</svg>
|
|
79
|
+
`,horizontalRule:`
|
|
80
|
+
<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">
|
|
81
|
+
<path d="M4 12h16"/>
|
|
82
|
+
<path d="M9 8h6"/>
|
|
83
|
+
<path d="M9 16h6"/>
|
|
84
|
+
</svg>
|
|
85
|
+
`,indent:`
|
|
86
|
+
<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">
|
|
87
|
+
<path d="M4 6h16"/>
|
|
88
|
+
<path d="M10 12h10"/>
|
|
89
|
+
<path d="M10 18h10"/>
|
|
90
|
+
<path d="m4 9 4 3-4 3"/>
|
|
91
|
+
</svg>
|
|
92
|
+
`,outdent:`
|
|
93
|
+
<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">
|
|
94
|
+
<path d="M4 6h16"/>
|
|
95
|
+
<path d="M10 12h10"/>
|
|
96
|
+
<path d="M10 18h10"/>
|
|
97
|
+
<path d="m8 9-4 3 4 3"/>
|
|
98
|
+
</svg>
|
|
99
|
+
`,redo:`
|
|
100
|
+
<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">
|
|
101
|
+
<path d="M21 7v6h-6"/>
|
|
102
|
+
<path d="M20 13a8 8 0 0 0-14-3"/>
|
|
103
|
+
</svg>
|
|
104
|
+
`,undo:`
|
|
105
|
+
<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">
|
|
106
|
+
<path d="M3 7v6h6"/>
|
|
107
|
+
<path d="M4 13a8 8 0 0 1 14-3"/>
|
|
108
|
+
</svg>
|
|
109
|
+
`,chevronDown:`
|
|
110
|
+
<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">
|
|
111
|
+
<path d="m6 9 6 6 6-6"/>
|
|
112
|
+
</svg>
|
|
113
|
+
`}),wn=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`}]),Tn=Object.freeze([{action:`bold`,label:`Bold`,title:`Bold`,icon:R.bold},{action:`italic`,label:`Italic`,title:`Italic`,icon:R.italic},{action:`strikethrough`,label:`Strikethrough`,title:`Strikethrough`,icon:R.strikethrough},{action:`code`,label:`Inline code`,title:`Inline code`,icon:R.code}]),En=Object.freeze([{commandId:`undo`,label:`Undo`,title:`Undo`,icon:R.undo},{commandId:`redo`,label:`Redo`,title:`Redo`,icon:R.redo},{commandId:`indentMore`,label:`Indent`,title:`Indent`,icon:R.indent},{commandId:`indentLess`,label:`Outdent`,title:`Outdent`,icon:R.outdent}]),Dn=Object.freeze([{action:`link`,label:`Insert link`,title:`Insert link`,icon:R.link},{action:`image`,label:`Insert image`,title:`Insert image`,icon:R.image},{action:`video`,label:`Insert video`,title:`Insert video`,icon:R.video}]),On=Object.freeze([{action:`table`,label:`Insert table`,title:`Insert table`,icon:R.table},{action:`horizontal-rule`,label:`Insert horizontal rule`,title:`Insert horizontal rule`,icon:R.horizontalRule}]),kn=Object.freeze([{kind:`buttons`,groupLabel:`Edit`,actions:En,mobileOnly:!0},{kind:`block-menu`,actions:wn},{kind:`buttons`,groupLabel:`Inline formatting`,actions:Tn},{kind:`buttons`,groupLabel:`Media and links`,actions:Dn},{kind:`buttons`,groupLabel:`Insert`,actions:On}]),An=[...wn,...Tn,...Dn,...On],jn=new Map(An.map(e=>[e.action,e]));function Mn(e){return jn.get(e)??null}function Nn(){return wn}function Pn(e){return wn.some(t=>t.action===e)}function Fn(e){return Mn(e)?.shortLabel??`P`}function In(){return R}var Ln=`image/png,image/jpeg,image/webp,image/gif,image/svg+xml`,Rn=`paragraph`;function z(e){return String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`)}function zn(e){return e===`heading`?`heading-2`:String(e??``).trim()}function Bn(e){return e.map(e=>`<button type="button" class="ui-icon-button ui-icon-button--toolbar ui-toolbar-action" ${e.commandId?`data-editor-command="${z(e.commandId)}"`:`data-markdown-action="${z(e.action)}"`} aria-label="${z(e.label)}" title="${z(e.title)}">${e.icon}</button>`).join(``)}function Vn(e){return`
|
|
114
|
+
<div class="markdown-toolbar-block-menu-shell">
|
|
115
|
+
<button
|
|
116
|
+
type="button"
|
|
117
|
+
class="ui-button ui-button--ghost markdown-toolbar-block-trigger"
|
|
118
|
+
data-markdown-block-menu-toggle
|
|
119
|
+
aria-haspopup="menu"
|
|
120
|
+
aria-expanded="false"
|
|
121
|
+
title="Block formatting"
|
|
122
|
+
>
|
|
123
|
+
<span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${z(Fn(e))}</span>
|
|
124
|
+
<span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${In().chevronDown}</span>
|
|
125
|
+
</button>
|
|
126
|
+
</div>
|
|
127
|
+
`}function Hn(e){return Nn().map(t=>{let n=t.action===e;return`
|
|
128
|
+
<button
|
|
129
|
+
type="button"
|
|
130
|
+
class="markdown-toolbar-menu-item${n?` is-active`:``}"
|
|
131
|
+
data-markdown-block-action="${z(t.action)}"
|
|
132
|
+
role="menuitemradio"
|
|
133
|
+
aria-checked="${n?`true`:`false`}"
|
|
134
|
+
title="${z(t.title)}"
|
|
135
|
+
>
|
|
136
|
+
<span class="markdown-toolbar-menu-item-label">${z(t.label)}</span>
|
|
137
|
+
<span class="markdown-toolbar-menu-item-shortcut">${z(t.shortLabel)}</span>
|
|
138
|
+
</button>
|
|
139
|
+
`}).join(``)}function Un(e){return kn.map(t=>t.kind===`block-menu`?Vn(e):`
|
|
140
|
+
<div class="markdown-toolbar-group${t.mobileOnly?` markdown-toolbar-group--mobile-only`:``}" role="group" aria-label="${z(t.groupLabel)}">
|
|
141
|
+
${Bn(t.actions)}
|
|
142
|
+
</div>
|
|
143
|
+
`).join(``)}function Wn(){let e=zn(this._activeMarkdownBlockAction||Rn);return Pn(e)?e:Rn}function Gn(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Un(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function Kn(){return this._markdownBlockMenuPopover??null}function qn(){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=Hn(this.getActiveMarkdownBlockAction()))}function Jn(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=Mn(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=Fn(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 Yn(e){let t=zn(e);Pn(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Xn(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Zn(){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 Qn(){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 $n(){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 er(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function tr(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 nr(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 rr(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function ir(e){if(!this.session||!u(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=zn(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}Pn(t)&&this.setActiveMarkdownBlockAction(t)}function ar(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function or(){let e=await this.pickImageFile();e&&await this.handleEditorImageInsert(e)}function sr(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=Ln,t.style.position=`fixed`,t.style.left=`-9999px`,document.body.appendChild(t);let n=!1,r=null,i=i=>{n||(n=!0,r&&window.clearTimeout(r),window.removeEventListener(`focus`,a),t.remove(),e(i))},a=()=>{r=window.setTimeout(()=>{n||t.files?.length||i(null)},250)};t.addEventListener(`change`,()=>{i(t.files?.[0]??null)},{once:!0}),t.addEventListener(`cancel`,()=>{i(null)},{once:!0}),window.addEventListener(`focus`,a,{once:!0}),t.click()})}async function cr(e){if(!this.session||!u(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 lr(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var ur={applyMarkdownToolbarAction:ir,copyCurrentLink:lr,closeMarkdownBlockMenu:$n,getActiveMarkdownBlockAction:Wn,getMarkdownBlockMenuPopover:Kn,handleEditorImageInsert:cr,handleMarkdownToolbarClick:tr,handleMarkdownToolbarDocumentPointerDown:rr,handleMarkdownToolbarKeydown:nr,handleToolbarImageInsert:or,isMarkdownBlockMenuOpen:Xn,openMarkdownBlockMenu:Qn,positionMarkdownBlockMenu:Zn,renderMarkdownBlockMenuPopover:qn,pickImageFile:sr,renderMarkdownToolbar:Gn,runEditorCommand:ar,setActiveMarkdownBlockAction:Yn,syncMarkdownToolbarBlockUi:Jn,toggleMarkdownBlockMenu:er},B={...ln,..._n,...Nt,...ur,...Cn},V={isExcalidrawFile(e){return g(e)},isBaseFile(e){return l(e)},isDrawioFile(e){return p(e)},isImageFile(e){return o(e)},isMermaidFile(e){return v(e)},isPlantUmlFile(e){return s(e)},createDiagramPreviewDocument(e,t=``){return this.workspacePreviewController.createDiagramPreviewDocument(e,t)},getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.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??f(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=f(e);return t!==null&&t!==`image`},getDisplayName(e){return c(String(e??``).split(`/`).pop())},resetPreviewMode(){this.workspacePreviewController.resetPreviewMode()},syncFileChrome(e,t={}){this.workspacePreviewController.syncFileChrome(e,t)},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):!0:e===`preview`?!0:(this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath,{drawioMode:`text`}),!1)},renderExcalidrawFilePreview(e){this.workspacePreviewController.renderExcalidrawFilePreview(e)},renderDrawioFilePreview(e){this.workspacePreviewController.renderDrawioFilePreview(e)},renderImageFilePreview(e){this.workspacePreviewController.renderImageFilePreview(e)},renderBaseFilePreview(e){return this.workspacePreviewController.renderBaseFilePreview(e)},renderTextFilePreview(e){this.workspacePreviewController.renderTextFilePreview(e)},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}})},async handleHashChange(){await this.workspaceRouteController.handleHashChange()},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()},async openFile(e){await this.workspaceRouteController.openFile(e)},cleanupSession(){this.workspaceRouteController.cleanupSession()},handleWikiLinkClick(e){this.wikiLinkFileController.handleWikiLinkClick(e)},normalizeNewWikiFilePath(e){return this.wikiLinkFileController.normalizeNewWikiFilePath(e)},async createAndOpenFile(e,t){await this.wikiLinkFileController.createAndOpenFile(e,t)},handleFileSelection(e,{closeSidebarOnMobile:t=!1}={}){this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:t})}},dr=`__lobby__`;function fr(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function pr(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function mr(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 hr=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=ie(),this.ydoc=new ce,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=De(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 se(this.wsBaseUrl,dr,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),le(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.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=fr(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:pr(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=mr({action:e,createdAt:Date.now(),id:pr(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=mr(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=mr(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}},gr=class{getHashRoute(){return O()}navigateToFile(e,t){D(e,t)}navigateToGitDiff(e){C(e)}navigateToGitCommit(e){ae(e)}navigateToGitHistory(){ne()}navigateToGitFileHistory(e){E(e)}navigateToGitFilePreview(e){oe(e)}},_r=class{constructor({NotificationImpl:e=globalThis.Notification,focusWindow:t=()=>globalThis.window?.focus?.()}={}){this.NotificationImpl=e,this.focusWindow=t}getPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.permission:`unsupported`}async requestPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.requestPermission():`unsupported`}createNotification({body:e,onClick:t,tag:n,title:r}){if(typeof this.NotificationImpl!=`function`)return null;let i=new this.NotificationImpl(r,{body:e,tag:n});return typeof t==`function`&&i.addEventListener(`click`,()=>{this.focusWindow(),t()}),i}},vr=class{constructor({chatNotificationsKey:e,lineWrappingKey:t,sidebarVisibleKey:n,userNameKey:r,storage:i=globalThis.localStorage}){this.chatNotificationsKey=e,this.lineWrappingKey=t,this.sidebarVisibleKey=n,this.storage=i,this.userNameKey=r}getUserName(){try{return this.storage.getItem(this.userNameKey)||``}catch{return``}}setUserName(e){try{this.storage.setItem(this.userNameKey,e)}catch{}}getLineWrappingEnabled(){try{return this.storage.getItem(this.lineWrappingKey)!==`false`}catch{return!0}}setLineWrappingEnabled(e){try{this.storage.setItem(this.lineWrappingKey,String(e))}catch{}}getSidebarVisible(){try{return this.storage.getItem(this.sidebarVisibleKey)}catch{return null}}setSidebarVisible(e){try{this.storage.setItem(this.sidebarVisibleKey,e?`true`:`false`)}catch{}}getChatNotificationsEnabled(){try{return this.storage.getItem(this.chatNotificationsKey)===`true`}catch{return!1}}setChatNotificationsEnabled(e){try{this.storage.setItem(this.chatNotificationsKey,String(e))}catch{}}},yr=6e4;function br(e){return String(e?.build?.id??e?.buildId??``).trim()}var xr=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=yr,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)||yr),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||k(`/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=br(t);return n?this.currentBuildId?n===this.currentBuildId?!1:(this.updateDetected=!0,this.onUpdateAvailable?.(t),!0):(this.currentBuildId=n,!1):!1}catch{return!1}finally{this.isChecking=!1}}},Sr=new class{async readBacklinks(e,{signal:t}={}){let n=await fetch(w(`/backlinks?file=${encodeURIComponent(e)}`),{signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`Failed to load backlinks`);return Array.isArray(r.backlinks)?r.backlinks:[]}};function Cr(e,t={}){let n={...t};return e&&(n[`X-CollabMD-Request-Id`]=String(e)),n}async function H(e,t){let n=await e.json().catch(()=>({}));if(!e.ok||n.ok===!1){let r=Error(n.error||t);throw r.status=e.status,r.body=n,typeof n?.code==`string`&&(r.code=n.code),r}return n}function wr(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n==null||n===``||t.set(e,String(n))}),t}var Tr=new class{async readStatus({force:e=!1}={}){return H(await fetch(w(`/git/status${e?`?force=true`:``}`)),`Failed to load git status`)}async readPullBackups(){return H(await fetch(w(`/git/pull-backups`)),`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=wr({limit:e,offset:t});return H(await fetch(w(`/git/history?${n.toString()}`)),`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=wr({limit:t,offset:n,path:e});return H(await fetch(w(`/git/file-history?${r.toString()}`)),`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=wr({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r});return H(await fetch(w(`/git/diff?${i.toString()}`)),`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=wr({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r});return H(await fetch(w(`/git/commit?${i.toString()}`)),`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=wr({hash:e,path:t});return H(await fetch(w(`/git/file-snapshot?${n.toString()}`)),`Failed to load historical file preview`)}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}={}){return H(await fetch(w(e),{body:JSON.stringify(t),headers:Cr(r,{"Content-Type":`application/json`}),method:`POST`}),n)}},Er=new class{async renderSvg(e){let t=await fetch(w(`/plantuml/render`),{body:JSON.stringify({source:e}),headers:{"Content-Type":`application/json`},method:`POST`}),n=await t.json().catch(()=>null);if(!t.ok||!n?.ok||typeof n.svg!=`string`)throw Error(n?.error||`Failed to render PlantUML`);return n.svg}},Dr=`collabmd-active-tab-lock`,Or=`collabmd-tab-id`,kr=`collabmd-tab-lock`,Ar=4e3;function jr(){return Date.now()}function Mr(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${jr()}-${Math.random().toString(36).slice(2,10)}`}function Nr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var Pr=class{constructor({heartbeatIntervalMs:e=Ar,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(kr),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(Dr),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(Or);if(e)return e;let t=Mr();return window.sessionStorage.setItem(Or,t),t}catch{return Mr()}}readLock(){try{return Nr(window.localStorage.getItem(Dr))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&jr()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(Dr,JSON.stringify({tabId:this.tabId,updatedAt:jr()}))}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!==Dr)return;let t=Nr(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()}},Fr=`__workspace__`;function Ir(e=``){return String(e??``).trim().replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}function Lr(e=``){let t=Ir(e);if(!t)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Rr(e={}){return Lr(e?.path??``)}function zr(e){return!e?.path||!e?.type?null:e.nodeType===`directory`||e.type===`directory`?{children:[],name:e.name,path:e.path,type:`directory`}:{name:e.name,path:e.path,type:e.type}}function Br(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)&&Br(e.children)}),e}function Vr(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Hr(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 Ur=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=Vr(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=zr(e);t&&this.nodesByPath.set(e.path,t)}),Hr(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,Rr(this.entriesByPath.get(e)))}),Br(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)}),Hr(n,`desc`).forEach(e=>{this.removeEntry(e)}),Hr(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Br(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=zr(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,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,Rr(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(Rr(t)!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Wr=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new ce,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 Ur,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=xt(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new se(ie(),Fr,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),le(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=xt(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()}},Gr=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`:!0}_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=c(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=`
|
|
144
|
+
<svg class="backlink-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
145
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
146
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
147
|
+
</svg>
|
|
148
|
+
<span>${b(t)}</span>
|
|
149
|
+
${n?`<span class="backlink-dir">${b(n)}</span>`:``}
|
|
150
|
+
`,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 Kr(...e){let t=[];for(let n of e)if(n){if(Array.isArray(n)){let e=Kr(...n);e&&t.push(e);continue}if(typeof n==`object`){Object.entries(n).forEach(([e,n])=>{n&&t.push(e)});continue}t.push(String(n))}return t.join(` `)}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 Kr(`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 qr(e={}){let{toolbar:t=!1,action:n=!1,surface:r=!1,hidden:i=!1,extra:a=[]}=e;return Kr(`ui-icon-button`,{"ui-icon-button--toolbar":t,"ui-icon-button--action":n,"ui-icon-button--surface":r,hidden:i},a)}function W(e={}){return Kr(`ui-input`,e.extra??[])}function Jr(e={}){return Kr(`ui-segmented-control`,{"ui-segmented-control--pill":e.pill,hidden:e.hidden},e.extra??[])}function G(e={}){return Kr(`ui-segmented-btn`,{active:e.active,hidden:e.hidden},e.extra??[])}function Yr(){return`base-${Math.random().toString(36).slice(2,10)}`}function Xr(e=``){return/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu.test(String(e??``).trim())}function Zr(e=``){return/^https?:\/\/.+\.(?:png|jpe?g|webp|gif|svg)(?:[?#].*)?$/iu.test(String(e??``).trim())}function Qr(e){return Object.prototype.toString.call(e)===`[object Object]`}function $r(e=`and`){return{children:[],conjunction:e,type:`group`}}function ei(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 K(e){return String(e?.text??``)}function ti(e=``){return w(`/attachment?path=${encodeURIComponent(e)}`)}function ni(e={}){if(e?.type===`image`&&e.path)return ti(e.path);if(e?.type===`link`){if(e.external&&Zr(e.url))return e.url;if(e.path&&o(e.path))return ti(e.path)}let t=K(e);return Zr(t)?t:o(t)?ti(t):``}function ri(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(ti(e.path))}" alt="${b(K(e))}">`;if(t===`list`)return`<span class="bases-value-list">${(e.items??[]).map(e=>`<span class="bases-value-pill">${ri(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(K(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(K(e))}</button>`}return t===`file`&&e.path?`<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(K(e))}</button>`:`<span class="bases-value">${b(K(e))}</span>`}function ii(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(K(n))}</button>`:ri(n)}function ai(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(K(e.value))}</span></div>`).join(``)}</div>`}function oi(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${ai(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>${ii(e,t)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div></section>`).join(``)}function si(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${ai(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> ${ii(e,t)}</span>`}).join(``)}</li>`).join(``)}</ul></section>`).join(``)}function ci(e,t,n){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${ai(t.summaries)}</header><div class="bases-cards">${(t.rows??[]).map(t=>{let r=ei(n,e,t),i=K(r),a=``;if(Xr(i))a=`<div class="bases-card-media bases-card-media-color" style="--bases-card-swatch:${b(i)}"></div>`;else{let e=ni(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">${ii(e,t)}</div></div>`}).join(``)}</div></article>`}).join(``)}</div></section>`).join(``)}function li(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 ci(e.columns,e.groups,e.view);case`list`:return si(e.columns,e.groups);default:return oi(e.columns,e.groups)}}function ui(e){return(e.views??[]).map(t=>`<button type="button" class="${b(G({active:t.id===e.view.id,extra:`bases-view-tab`}))}" data-base-view="${b(t.id)}">${b(t.name)}</button>`).join(``)}function di(e){return e?.meta??{}}function fi(e){return di(e).availableProperties??[]}function pi(e){let t=di(e).activeViewConfig?.order;return Array.isArray(t)&&t.length>0?[...t]:Array.isArray(e?.columns)?e.columns.map(e=>e.id).filter(Boolean):[]}function mi(e,t=``){return fi(e).find(e=>e.id===t)??null}function hi(e,t=``){return mi(e,t)?.filterOperators??[`is`,`is not`,`contains`,`does not contain`,`is empty`,`is not empty`]}function q(e){let t=di(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 gi(e){return!!(e?.payload?.path&&e?.payload?.sourcePath&&e.payload.path===e.payload.sourcePath)}function _i(e,t,n,r){let i=n.ui?.openPanel===t,a=!!di(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 vi(e,t=``){if(!e||e.type!==`group`||!t)return e;let n=(e.children??[]).flatMap(e=>{if(e?.type===`group`){let n=vi(e,t);return n?[n]:[]}return e?.propertyId===t?[]:[e]});return{...e,children:n}}function yi(e,t=``,n=e?.result){let r=di(n).activeViewConfig?.filters??null,i=Y(r),a=t&&i?Oi(vi(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 bi(e,t=``,n=e?.result){let r=e?.propertyValueOptions?.get(t)??null;return r&&r.cacheKey===yi(e,t,n)?r.values??[]:[]}function xi(e,t){return[_i(`Sort`,`sort`,t,e),_i(`Filter`,`filter`,t,e),_i(`Properties`,`properties`,t,e)].join(``)}function Si(e,{allowBlank:t=!1,selected:n=``}={}){let r=[];return t&&r.push(`<option value=""${n?``:` selected`}>Property</option>`),fi(e).forEach(e=>{r.push(`<option value="${b(e.id)}"${e.id===n?` selected`:``}>${b(e.label)}</option>`)}),r.join(``)}function Ci(e){let t=q(e),n=mi(e,t.groupBy?.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}],r=t.sort??[];return`
|
|
151
|
+
<section class="bases-panel-card">
|
|
152
|
+
<div class="bases-panel-section">
|
|
153
|
+
<div class="bases-panel-title">Group by</div>
|
|
154
|
+
<div class="bases-sort-row">
|
|
155
|
+
<select class="${b(W({extra:`bases-select bases-sort-property`}))}" data-base-group-by-property>
|
|
156
|
+
${Si(e,{allowBlank:!0,selected:t.groupBy?.property??``})}
|
|
157
|
+
</select>
|
|
158
|
+
<select class="${b(W({extra:`bases-select bases-sort-direction`}))}" data-base-group-by-direction${t.groupBy?.property?``:` disabled`}>
|
|
159
|
+
${n.map(e=>`<option value="${b(e.id)}"${e.id===(t.groupBy?.direction??`asc`)?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
160
|
+
</select>
|
|
161
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-clear-group-by${t.groupBy?.property?``:` disabled`}>Clear</button>
|
|
162
|
+
</div>
|
|
163
|
+
</div>
|
|
164
|
+
<div class="bases-panel-section">
|
|
165
|
+
<div class="bases-panel-title">Sort by</div>
|
|
166
|
+
<div class="bases-sort-list">
|
|
167
|
+
${r.map((t,n)=>{let i=mi(e,t.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}];return`
|
|
168
|
+
<div class="bases-sort-row">
|
|
169
|
+
<select class="${b(W({extra:`bases-select bases-sort-property`}))}" data-base-sort-property="${n}">
|
|
170
|
+
${Si(e,{selected:t.property})}
|
|
171
|
+
</select>
|
|
172
|
+
<select class="${b(W({extra:`bases-select bases-sort-direction`}))}" data-base-sort-direction="${n}">
|
|
173
|
+
${i.map(e=>`<option value="${b(e.id)}"${e.id===t.direction?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
174
|
+
</select>
|
|
175
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:up"${n===0?` disabled`:``}>↑</button>
|
|
176
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:down"${n===r.length-1?` disabled`:``}>↓</button>
|
|
177
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-delete="${n}">Delete</button>
|
|
178
|
+
</div>
|
|
179
|
+
`}).join(``)}
|
|
180
|
+
</div>
|
|
181
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-sort-add>Add sort</button>
|
|
182
|
+
</div>
|
|
183
|
+
</section>
|
|
184
|
+
`}function wi(e=[]){return e.join(`.`)}function J(e=``){return String(e??``).split(`.`).filter(e=>e!==``).map(e=>Number.parseInt(e,10)).filter(Number.isFinite)}function Ti(e=``){return JSON.stringify(String(e??``))}function Ei(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)):Ti(r)}function Di(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(${Ei(e.value,r,e.operator)})`;case`does not contain`:return`!${n}.contains(${Ei(e.value,r,e.operator)})`;case`starts with`:return`${n}.startsWith(${Ei(e.value,r,e.operator)})`;case`ends with`:return`${n}.endsWith(${Ei(e.value,r,e.operator)})`;case`is`:return`${n} == ${Ei(e.value,r,e.operator)}`;case`is not`:return`${n} != ${Ei(e.value,r,e.operator)}`;case`>`:case`>=`:case`<`:case`<=`:return`${n} ${e.operator} ${Ei(e.value,r,e.operator)}`;case`is empty`:return`${n}.isEmpty()`;case`is not empty`:return`!${n}.isEmpty()`;default:return``}}function Oi(e,t){if(!e||e.type!==`group`)return null;let n=(e.children??[]).map(e=>e?.type===`group`?Oi(e,t):Di(e,mi(t,e?.propertyId))).filter(Boolean);return n.length===0?null:e.conjunction===`not`?{not:n}:{[e.conjunction]:n}}function ki(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 Ai(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:ki(n)})],[/^([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`contains`,propertyId:t,type:`rule`,value:ki(n)})],[/^([A-Za-z0-9_.]+)\.startsWith\((.+)\)$/u,(e,t,n)=>({operator:`starts with`,propertyId:t,type:`rule`,value:ki(n)})],[/^([A-Za-z0-9_.]+)\.endsWith\((.+)\)$/u,(e,t,n)=>({operator:`ends with`,propertyId:t,type:`rule`,value:ki(n)})],[/^([A-Za-z0-9_.]+)\s*(==|!=|>=|<=|>|<)\s*(.+)$/u,(e,t,n,r)=>({operator:{"!=":`is not`,"==":`is`,"<":`<`,"<=":`<=`,">":`>`,">=":`>=`}[n]??n,propertyId:t,type:`rule`,value:ki(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 $r(`and`);if(typeof e==`string`){let t=Ai(e);return t?{children:[t],conjunction:`and`,type:`group`}:null}if(!Qr(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 ji(e){return e?typeof e==`string`?e:JSON.stringify(e,null,2):``}function Mi(e=``){let t=String(e??``).trim();return t?t.startsWith(`{`)||t.startsWith(`[`)?JSON.parse(t):t:null}function Ni(e,t=[]){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function Pi(e,t=[],n){if(t.length===0)return n(e);let[r,...i]=t;return{...e,children:(e.children??[]).map((e,t)=>t===r?Pi(e,i,n):e)}}function Fi(e,t=[]){if(t.length===0)return e;let n=t.slice(0,-1),r=t[t.length-1];return Pi(e,n,e=>({...e,children:(e.children??[]).filter((e,t)=>t!==r)}))}function Ii(e,t=[],n){return Pi(e,t,e=>({...e,children:[...e.children??[],n]}))}function Li(e,t=``){return Si(e,{allowBlank:!0,selected:t})}function Ri(e={}){return String(e?.text??e?.value??``).trim()}function zi(e,t){return e.ui.builderFilter??Y(q(t).filters)??$r(`and`)}function Bi(e,t,n,r){let i=wi(n),a=hi(e,t.propertyId),o=String(t.value??``).trim().toLowerCase(),s=bi(r,t.propertyId,e).map(e=>({count:e?.count,text:Ri(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:W({extra:d?`bases-filter-value bases-filter-value--suggestions`:`bases-filter-value`}),valueSuggestions:u,valueDisabled:[`is empty`,`is not empty`].includes(t.operator)}}function Vi(e,t=``){return e.suggestionsEnabled?`
|
|
185
|
+
<div class="bases-filter-suggestion-list" id="${e.suggestionListId}" role="listbox">
|
|
186
|
+
${e.valueSuggestions.slice(0,8).map(n=>`
|
|
187
|
+
<button
|
|
188
|
+
type="button"
|
|
189
|
+
class="bases-filter-suggestion"
|
|
190
|
+
data-base-filter-suggestion="${b(e.encodedPath)}"
|
|
191
|
+
data-base-filter-suggestion-value="${b(n.text)}"
|
|
192
|
+
role="option"
|
|
193
|
+
aria-selected="${n.text===String(t??``)?`true`:`false`}"
|
|
194
|
+
>
|
|
195
|
+
<span class="bases-filter-suggestion-label">${b(n.text)}</span>
|
|
196
|
+
${n.count==null?``:`<span class="bases-filter-suggestion-meta">${b(String(n.count))}</span>`}
|
|
197
|
+
</button>
|
|
198
|
+
`).join(``)}
|
|
199
|
+
</div>
|
|
200
|
+
`:``}function Hi(e,t,n,r){let i=Bi(e,t,n,r);return`
|
|
201
|
+
<div class="bases-filter-value-combobox${i.suggestionsEnabled?` has-suggestions`:``}">
|
|
202
|
+
<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`:``}>
|
|
203
|
+
${Vi(i,t.value??``)}
|
|
204
|
+
</div>
|
|
205
|
+
`}function Ui(e,t,n,r){let i=Bi(e,t,n,r);return`
|
|
206
|
+
<div class="bases-filter-row">
|
|
207
|
+
<select class="${b(W({extra:`bases-select bases-filter-property`}))}" data-base-filter-property="${b(i.encodedPath)}">
|
|
208
|
+
${Li(e,t.propertyId)}
|
|
209
|
+
</select>
|
|
210
|
+
<select class="${b(W({extra:`bases-select bases-filter-operator`}))}" data-base-filter-operator="${b(i.encodedPath)}">
|
|
211
|
+
${i.operators.map(e=>`<option value="${b(e)}"${e===t.operator?` selected`:``}>${b(e)}</option>`).join(``)}
|
|
212
|
+
</select>
|
|
213
|
+
${Hi(e,t,n,r)}
|
|
214
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(i.encodedPath)}">Delete</button>
|
|
215
|
+
</div>
|
|
216
|
+
`}function Wi(e,t,n,{fallbackToFullRender:r=!0}={}){let i=$i(e)?.querySelector?.(`[data-base-panel-slot]`)??null,a=wi(n),o=i?.querySelector?.(`[data-base-filter-value="${a}"]`)??null,s=o?.parentElement?.classList?.contains(`bases-filter-value-combobox`)?o.parentElement:null,c=Ni(zi(e,t),n);if(!o||!s||!c||c.type!==`rule`||typeof o.insertAdjacentHTML!=`function`)return r&&ta(e,t),!1;let l=Bi(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`,Vi(l,c.value??``)),!0}function Gi(e,t,n=[]){if(e){if(e.type===`rule`){t(e,n);return}(e.children??[]).forEach((e,r)=>{Gi(e,t,[...n,r])})}}function Ki(e,t,n,r,{isRoot:i=!1}={}){let a=wi(n);return`
|
|
217
|
+
<div class="bases-filter-group"${i?` data-base-filter-root`:``}>
|
|
218
|
+
<div class="bases-filter-group-header">
|
|
219
|
+
<select class="${b(W({extra:`bases-select bases-filter-conjunction`}))}" data-base-filter-conjunction="${b(a)}">
|
|
220
|
+
${[`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(``)}
|
|
221
|
+
</select>
|
|
222
|
+
${i?``:`<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(a)}">Delete group</button>`}
|
|
223
|
+
</div>
|
|
224
|
+
<div class="bases-filter-children">
|
|
225
|
+
${(t.children??[]).map((t,i)=>t?.type===`group`?Ki(e,t,[...n,i],r):Ui(e,t,[...n,i],r)).join(``)}
|
|
226
|
+
</div>
|
|
227
|
+
<div class="bases-filter-actions-row">
|
|
228
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-add-rule="${b(a)}">Add filter</button>
|
|
229
|
+
<button type="button" class="${b(U({variant:`secondary`,size:`compact`}))}" data-base-filter-add-group="${b(a)}">Add filter group</button>
|
|
230
|
+
</div>
|
|
231
|
+
</div>
|
|
232
|
+
`}function qi(e,t){let n=q(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??ji(n);return`
|
|
233
|
+
<section class="bases-panel-card">
|
|
234
|
+
<div class="bases-panel-title-row">
|
|
235
|
+
<div class="bases-panel-title">This view</div>
|
|
236
|
+
${r?`
|
|
237
|
+
<div class="bases-toggle-row">
|
|
238
|
+
<button type="button" class="${b(U({variant:i===`builder`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="builder">Builder</button>
|
|
239
|
+
<button type="button" class="${b(U({variant:i===`advanced`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="advanced">Advanced</button>
|
|
240
|
+
</div>
|
|
241
|
+
`:``}
|
|
242
|
+
</div>
|
|
243
|
+
${i===`advanced`?`
|
|
244
|
+
<label class="bases-filter-advanced-label">
|
|
245
|
+
<textarea class="${b(W({extra:`bases-filter-advanced`}))}" data-base-filter-advanced>${b(a)}</textarea>
|
|
246
|
+
</label>
|
|
247
|
+
<div class="bases-filter-actions-row">
|
|
248
|
+
<button type="button" class="${b(U({variant:`primary`,size:`compact`}))}" data-base-filter-save-advanced>Save filter</button>
|
|
249
|
+
</div>
|
|
250
|
+
`:Ki(e,r??$r(`and`),[],t,{isRoot:!0})}
|
|
251
|
+
</section>
|
|
252
|
+
`}function Ji(e,t){let n=String(t.ui.propertySearch??``).trim().toLowerCase(),r=new Set(pi(e)),i=fi(e).filter(e=>!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n));return`
|
|
253
|
+
<section class="bases-panel-card">
|
|
254
|
+
<label class="bases-properties-search">
|
|
255
|
+
<input class="${b(W({extra:`bases-properties-search-input`}))}" type="search" value="${b(t.ui.propertySearch??``)}" placeholder="Find property" data-base-properties-search>
|
|
256
|
+
</label>
|
|
257
|
+
<div class="bases-properties-list" data-base-properties-list>
|
|
258
|
+
${i.map(e=>`
|
|
259
|
+
<label class="bases-property-option">
|
|
260
|
+
<input type="checkbox" data-base-property-toggle="${b(e.id)}"${r.has(e.id)?` checked`:``}>
|
|
261
|
+
<span class="bases-property-option-label">${b(e.label)}</span>
|
|
262
|
+
<span class="bases-property-option-meta">${b(e.kind)}</span>
|
|
263
|
+
</label>
|
|
264
|
+
`).join(``)}
|
|
265
|
+
</div>
|
|
266
|
+
</section>
|
|
267
|
+
`}function Yi(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 Xi(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 Zi(e,t){if(!t.ui?.openPanel)return``;if(!di(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 qi(e,t);case`properties`:return Ji(e,t);default:return Ci(e)}}function Qi(e,t){return`
|
|
268
|
+
<section class="bases-shell" data-base-shell-key="${b(t.key)}">
|
|
269
|
+
<header class="bases-toolbar">
|
|
270
|
+
<div class="bases-toolbar-main">
|
|
271
|
+
<div class="${b(Jr({pill:!0,extra:`bases-tabs`}))}" data-base-tabs>
|
|
272
|
+
${ui(e)}
|
|
273
|
+
</div>
|
|
274
|
+
<div class="bases-meta" data-base-meta>${b(String(e.totalRows??0))} results</div>
|
|
275
|
+
</div>
|
|
276
|
+
<div class="bases-toolbar-actions">
|
|
277
|
+
<div class="bases-toolbar-edit-actions" data-base-action-slot>${xi(e,t)}</div>
|
|
278
|
+
<label class="bases-search-shell" aria-label="Search this base">
|
|
279
|
+
<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">
|
|
280
|
+
<circle cx="11" cy="11" r="7"></circle>
|
|
281
|
+
<path d="m20 20-3.5-3.5"></path>
|
|
282
|
+
</svg>
|
|
283
|
+
<input class="${b(W({extra:`bases-search-input`}))}" type="search" value="${b(t.search)}" placeholder="Search this base" aria-label="Search this base">
|
|
284
|
+
</label>
|
|
285
|
+
<button type="button" class="${b(U({variant:`secondary`,pill:!0,extra:`bases-export-btn`}))}">Export CSV</button>
|
|
286
|
+
</div>
|
|
287
|
+
</header>
|
|
288
|
+
<div class="bases-panels" data-base-panel-slot>${Zi(e,t)}</div>
|
|
289
|
+
<div data-base-summary-slot>${ai(e.summaries)}</div>
|
|
290
|
+
<div class="bases-content" data-base-content>${li(e)}</div>
|
|
291
|
+
</section>
|
|
292
|
+
`}function $i(e){return e?.placeholder?.querySelector?e.placeholder.querySelector(`[data-base-shell-key="${e.key}"]`)??e.placeholder.querySelector(`.bases-shell`):null}function ea(e){e?.classList&&(e.classList.add(`is-hydrated`),e.classList.remove(`diagram-preview-shell`))}function ta(e,t){let n=$i(e);if(!n?.querySelector){e.placeholder.innerHTML=Qi(t,e),ea(e.placeholder);return}let r=n.querySelector(`[data-base-tabs]`);r&&(r.innerHTML=ui(t));let i=n.querySelector(`[data-base-meta]`);i&&(i.textContent=`${String(t.totalRows??0)} results`);let a=n.querySelector(`[data-base-action-slot]`);a&&(a.innerHTML=xi(t,e));let o=n.querySelector(`[data-base-panel-slot]`);if(o){let n=Yi(o);o.innerHTML=Zi(t,e),Xi(o,n)}let s=n.querySelector(`[data-base-summary-slot]`);s&&(s.innerHTML=ai(t.summaries));let c=n.querySelector(`[data-base-content]`);c&&(c.innerHTML=li(t));let l=n.querySelector(`.bases-search-input`);l&&l.value!==e.search&&(l.value=e.search)}function na(e,t=`base.csv`){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}function ra(e=``){let t=e.match(/filename\*=UTF-8''([^;]+)/iu);return t?decodeURIComponent(t[1]):e.match(/filename="([^"]+)"/iu)?.[1]||`base.csv`}var ia=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=>Pi(e,t,e=>({...e,value:n})))},this.persistBuilderFilter=e=>{let t=zi(e,e.result);e.ui.builderFilter=t,this.updateViewConfig(e,n=>(n.filters=Oi(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=J(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=ji(q(r.result).filters),ta(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=fi(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=ji(q(r.result).filters),r.ui.builderFilter=null),ta(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=J(l.dataset.baseFilterAddRule||``);this.updateBuilderFilter(r,t=>Ii(t,e,{operator:`is`,propertyId:fi(r.result)[0]?.id??`file.name`,type:`rule`,value:``}));return}let u=e.target.closest(`[data-base-filter-add-group]`);if(u){let e=J(u.dataset.baseFilterAddGroup||``);this.updateBuilderFilter(r,t=>Ii(t,e,$r(`and`)));return}let d=e.target.closest(`[data-base-filter-remove]`);if(d){let e=J(d.dataset.baseFilterRemove||``);this.updateBuilderFilter(r,t=>Fi(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=J(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||``,ta(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=J(i.dataset.baseFilterValue||``),r=t.ui.builderFilter??Y(q(t.result).filters)??$r(`and`);t.ui.builderFilter=Pi(r,n,e=>({...e,value:i.value||``})),Wi(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]:pi(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=J(c.dataset.baseFilterConjunction||``);this.updateBuilderFilter(n,t=>Pi(t,e,e=>({...e,conjunction:c.value||`and`})));return}let l=e.target.closest(`[data-base-filter-property]`);if(l){let e=J(l.dataset.baseFilterProperty||``);(async()=>{await this.updateBuilderFilter(n,t=>Pi(t,e,e=>{let t=hi(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=J(u.dataset.baseFilterOperator||``);this.updateBuilderFilter(n,t=>Pi(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=J(t.dataset.baseFilterValue||``),a=Y(q(r.result).filters),o=a?Ni(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||Yr(),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=!!$i(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(q(e.result).filters),e.ui.rawFilterText||(e.ui.rawFilterText=ji(q(e.result).filters)),ta(e,e.result)}catch(r){if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;if(n){let t=$i(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});na(t.blob,ra(t.contentDisposition))}catch(e){this.toastController?.show?.(e.message||`Failed to export base CSV`)}}async ensurePropertyValues(e,t=``){if(this.ensureEntryState(e),!t)return;let n=yi(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;Gi(zi(e,e.result),(r,i)=>{r.propertyId===t&&(n=Wi(e,e.result,i,{fallbackToFullRender:!1})||n)}),n||ta(e,e.result)}}catch{e.propertyValueOptions.set(t,{cacheKey:n,values:[]})}}async applyTransformedSource(e,t){if(this.ensureEntryState(e),gi(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||!di(e.result).editable)return;let n=t(q(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=ji(q(e.result).filters),ta(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(q(e.result).filters)??$r(`and`));e.ui.builderFilter=n,await this.updateViewConfig(e,t=>(t.filters=Oi(n,e.result),t))}async saveAdvancedFilter(e){this.ensureEntryState(e);try{let t=Mi(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`)}}};function aa(e,t,n,r,i,a){return e?.(t,n,r,i,a)??a.renderToken(t,n,r)}function oa(e=``){return`<p>${b(String(e??``)).replace(/\n/g,`<br>`)}</p>`}function sa(){let e=t({breaks:!0,highlight(e,t){try{return t&&n.getLanguage(t)?n.highlight(e,{ignoreIllegals:!0,language:t}).value:n.highlightAuto(e).value}catch{return b(e)}},html:!1,linkify:!0,typographer:!0}),r=e.renderer.rules.link_open,i=e.renderer.rules.table_open,a=e.renderer.rules.table_close;return e.renderer.rules.link_open=(e,t,n,i,a)=>(e[t].attrSet(`target`,`_blank`),e[t].attrSet(`rel`,`noopener noreferrer`),aa(r,e,t,n,i,a)),e.renderer.rules.table_open=(e,t,n,r,a)=>`<div class="comment-markdown-table">${aa(i,e,t,n,r,a)}`,e.renderer.rules.table_close=(e,t,n,r,i)=>`${aa(a,e,t,n,r,i)}</div>`,e}var ca=sa();function la(e=``){let t=String(e??``);try{return ca.render(t)}catch{return oa(t)}}var ua=Object.freeze([`👍`,`❤️`,`🎉`,`👀`,`🚀`]),da=Object.freeze([`😂`,`🔥`,`✅`,`🙏`,`💡`,`🤔`,`👏`,`😄`,`🎯`,`🙌`]);function fa(e,t,n){return Math.min(Math.max(e,t),n)}function pa(e=[]){return[...e].sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0)||e.createdAt-t.createdAt)}function ma(e){return e?.anchorKind||e?.kind||`line`}function ha(e){return ma(e)===`text`&&Number.isFinite(e?.startIndex)&&Number.isFinite(e?.endIndex)&&e.endIndex>e.startIndex}function ga(e,t){return e===t?!0:!e||!t?!1:ma(e)===ma(t)&&(e.startIndex??null)===(t.startIndex??null)&&(e.endIndex??null)===(t.endIndex??null)&&(e.startLine??null)===(t.startLine??null)&&(e.endLine??null)===(t.endLine??null)&&(e.anchorQuote??e.quote??``)===(t.anchorQuote??t.quote??``)}function _a(e){return e?((e.kind||e.anchorKind)===`text`&&e.quote,e.startLine===e.endLine?`Line ${e.startLine}`:`Lines ${e.startLine}-${e.endLine}`):`No source anchor`}function va(e={}){return[e.kind||e.anchorKind||`line`,e.startLine??0,e.endLine??0,e.quote||``].join(`::`)}function ya(e){return e&&!e.querySelector(`[data-source-line]`)}function ba(e){let t=Number.parseInt(e||``,10);return Number.isFinite(t)?t:null}function xa(e=[]){return e.reduce((e,t)=>e?(t?.createdAt??0)>=(e?.createdAt??0)?t:e:t,null)}function Sa(e){return e?.threads?.reduce((e,t)=>{let n=xa(t?.messages??[]);return n&&(n.createdAt??0)>=(e?.createdAt??0)?n:e},null)}function Ca(e,t=`comment-markdown`){let n=document.createElement(`div`);return n.className=t,n.innerHTML=la(e),n}function wa(e,t){return!!(t&&e?.users?.some(e=>e?.userId===t))}function Ta(e){return String(Array.isArray(e?.users)?e.users.length:0)}function Ea(e,t,n){return e?.threadId===t&&e?.messageId===n}function Da(e){let t=e?.querySelector?.(`.comment-reaction-picker`),n=t?.closest?.(`.comment-reaction-picker-wrap`),r=e?.querySelector?.(`.comment-card-scroll`);return!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||!(r instanceof HTMLElement)?null:{picker:t,scroll:r,wrap:n}}function Oa(e,t){let n=ba(e?.getAttribute?.(`data-source-line`)),r=ba(e?.getAttribute?.(`data-source-line-end`))??n;return!n||!r||!t?!1:t.startLine<=r&&t.endLine>=n}function ka(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=``,r=[],i=!0;for(;t.nextNode();){let e=t.currentNode,a=e.textContent||``;for(let t=0;t<a.length;t+=1){let o=a[t];if(/\s/.test(o)){if(i)continue;n+=` `,r.push({node:e,offset:t}),i=!0;continue}n+=o,r.push({node:e,offset:t}),i=!1}}for(;n.endsWith(` `);)n=n.slice(0,-1),r.pop();return{map:r,normalized:n}}function Aa(e,t){let n=we(t);if(!e||!n)return null;let r=ka(e);if(!r.normalized)return null;let i=r.normalized.indexOf(n);if(i<0||r.normalized.indexOf(n,i+1)>=0)return null;let a=r.map[i],o=r.map[i+n.length-1];if(!a||!o)return null;let s=document.createRange();return s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset+1),s}function ja(e,t){return{bottom:e.bottom-t.top,height:e.height,left:e.left-t.left,right:e.right-t.left,top:e.top-t.top,width:e.width}}function Ma(e=[]){if(!Array.isArray(e)||e.length===0)return null;let t=Math.min(...e.map(e=>e.left)),n=Math.min(...e.map(e=>e.top)),r=Math.max(...e.map(e=>e.right)),i=Math.max(...e.map(e=>e.bottom));return{bottom:i,height:i-n,left:t,right:r,top:n,width:r-t}}function Na(e,t,n){return n?e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom:!1}function Pa(e=[]){return[...new Set(e.filter(Boolean))].sort()}function Fa(e=[]){return Pa(e).join(` `)}function Ia(e){let t=document.createDocumentFragment(),n=document.createElement(`span`);if(n.className=`comment-marker-icon`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`
|
|
293
|
+
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
294
|
+
<path d="M3 4.75A1.75 1.75 0 0 1 4.75 3h6.5A1.75 1.75 0 0 1 13 4.75v4.5A1.75 1.75 0 0 1 11.25 11H8.9L6.5 13v-2H4.75A1.75 1.75 0 0 1 3 9.25v-4.5Z" stroke="currentColor" stroke-width="1.35" stroke-linejoin="round"/>
|
|
295
|
+
</svg>
|
|
296
|
+
`,t.appendChild(n),e>1){let n=document.createElement(`span`);n.className=`comment-marker-count`,n.textContent=String(e),t.appendChild(n)}return t}function La(){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 Ra(e=`editor`,t=null){let n=this.session?.getCurrentSelectionCommentAnchor?.();n&&(this.selectionAnchor=n,this.reactionPicker=null,this.activeCard={anchor:n,composerDraft:null,mode:`create`,origin:e===`editor`&&t?`editor-chip`:e,replyThreadId:null,sourceRect:t??(e===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.():this.session?.getCommentAnchorClientRect?.(n))},this.render())}function za(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 Ba(){this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),this.scheduleLayoutRefresh()}function Va(){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`?this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect??this.activeCard.sourceRect:this.activeCard.origin===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.()??this.activeCard.sourceRect:this.activeCard.sourceRect:null}function Ha(e){return e instanceof HTMLTextAreaElement?{selectionDirection:e.selectionDirection??`none`,selectionEnd:e.selectionEnd,selectionStart:e.selectionStart,value:e.value}:null}function Ua(){if(!this.activeCard)return;let e=this.cardRoot?.querySelector(`.comment-card-input`),t=Ha(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 Wa(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 Ga(){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=_a(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.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 Ka(e){let t=Da(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 qa(){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 Ja(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=W({extra:`comment-card-input`}),t.rows=4,t.maxLength=Ee,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=Wa(t,this.activeCard?.composerDraft),e}function Ya(e){let t=document.createElement(`article`);t.className=`comment-thread-card`;let n=document.createElement(`div`);n.className=`ui-record-header comment-thread-card-header`;let r=document.createElement(`div`);r.className=`comment-thread-card-heading`;let i=document.createElement(`span`);i.className=`comment-thread-card-author`,i.textContent=e.createdByName;let a=document.createElement(`span`);a.className=`comment-thread-card-time`,a.textContent=this.formatTimestamp(e.createdAt);let o=document.createElement(`div`);o.className=`ui-record-actions comment-thread-card-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]}),s.textContent=`Jump`,s.addEventListener(`click`,()=>this.onNavigateToLine?.(e.anchor?.startLine??1));let c=document.createElement(`button`);c.type=`button`,c.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let l=this.activeCard?.replyThreadId===e.id;c.classList.toggle(`is-active`,l),c.textContent=`Reply`,c.setAttribute(`aria-pressed`,String(l)),c.setAttribute(`aria-label`,l?`Cancel reply`:`Reply to thread`),c.title=l?`Cancel reply`:`Reply to thread`,c.addEventListener(`click`,()=>{l&&this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:l?null:e.id},this.renderCard()});let u=document.createElement(`button`);return u.type=`button`,u.className=U({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),u.textContent=`Resolve`,u.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),o.append(s,c,u),r.append(i,a),n.append(r,o),t.append(n),e.messages.forEach(n=>{t.appendChild(this.createMessageElement(e,n))}),this.activeCard?.replyThreadId===e.id&&t.appendChild(this.createReplyComposer(e)),t}function Xa(e,t){let n=document.createElement(`div`);n.className=`comment-message-card`;let r=document.createElement(`div`);r.className=`ui-record-meta comment-message-card-meta`;let i=document.createElement(`span`);i.className=`comment-message-card-author`,i.textContent=t.userName;let a=document.createElement(`span`);a.className=`comment-message-card-time`,a.textContent=this.formatTimestamp(t.createdAt);let o=Ca(t.body,`comment-message-card-body comment-markdown`);return r.append(i,a),n.append(r,o),n.appendChild(this.createReactionBar(e,t)),n}function Za(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`,wa(r,n)),i.setAttribute(`aria-pressed`,String(wa(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=Ta(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`,ua.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(Ea(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{this.reactionPicker=Ea(this.reactionPicker,e.id,t.id)?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),Ea(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function Qa(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 $a(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,da.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function eo(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 to(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=W({extra:`comment-card-input`}),r.rows=3,r.maxLength=Ee,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=Wa(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 no(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=fa((n-i.width)/2,16,n-i.width-16),o=fa((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=fa(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 ro(){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 io={captureActiveCardDraft:Ua,closeCard:Ba,createComposer:Ja,createPendingFocusTarget:Wa,createMessageElement:Xa,createQuickReactionButton:Qa,createReactionBar:Za,createReactionPicker:$a,createReactionPickerButton:eo,createReplyComposer:to,createTextareaDraft:Ha,createThreadElement:Ya,ensureCardRoot:La,flushPendingCardFocus:ro,openComposerForSelection:Ra,openThreadGroup:za,positionCard:no,renderCard:Ga,repositionActiveCard:qa,updateCardSourceRect:Va,updateReactionPickerPosition:Ka};function ao(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function oo(e=0){if(!this.previewElement)return!1;let t=this.supported&&e>0,n=0,r=0;if(t){let t=getComputedStyle(this.previewElement),i=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-reserved`))||0,a=Number.parseFloat(t.paddingRight)||0,o=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-inset`))||0,s=Math.max(a-i,0),c=Math.max(e+o-s,0),l=this.previewContainer?.getBoundingClientRect(),u=this.previewElement.getBoundingClientRect(),d=l?Math.max(l.right-u.right,0):0;r=Math.min(d,c),n=Math.max(c-r,0)}let i=`${Math.ceil(n)}px`,a=`${Math.floor(r)}px`,o=this.previewElement.style.getPropertyValue(`--preview-comment-rail-reserved`)!==i||this.previewElement.style.getPropertyValue(`--preview-comment-rail-offset`)!==a;return o&&(this.previewElement.style.setProperty(`--preview-comment-rail-reserved`,i),this.previewElement.style.setProperty(`--preview-comment-rail-offset`,a)),o}function so(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function co(){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 lo(){let e=this.ensureEditorLayer();if(e.replaceChildren(),!this.supported||!this.session)return;let t=this.editorContainer?.getBoundingClientRect?.();if(!t)return;let n=this.getThreadGroups(),r=[];if(n.forEach(n=>{let i=this.session.getCommentAnchorClientRect?.(n.anchor);if(!i)return;let a=ja(i,t);if(a.bottom<0||a.top>t.height)return;let o=document.createElement(`button`);o.type=`button`,o.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,o.dataset.count=String(n.threads.length);let s=this.activeCard?.groupKey===n.key,c=this.hoveredEditorGroupKeys.includes(n.key);o.classList.toggle(`is-active`,s),o.classList.toggle(`is-hovered`,c),o.classList.toggle(`is-passive`,!s&&!c),o.setAttribute(`aria-label`,`${n.threads.length} comment thread${n.threads.length===1?``:`s`}`),o.appendChild(Ia(n.threads.length));let l=Math.max(a.top,8);o.style.top=`${l}px`,o.style.left=`${Math.max(t.width-36,8)}px`,o.title=`${n.threads.length} comment${n.threads.length===1?``:`s`}`,o.addEventListener(`pointerdown`,e=>{e.preventDefault()}),o.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`click`,()=>{this.openThreadGroup(n,{anchor:n.anchor,origin:`editor`,sourceRect:i})}),e.appendChild(o),r.push(l)}),!this.committedSelectionAnchor||this.activeCard?.mode===`create`)return;let i=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),a=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??i;if(!a)return;let o=ja(a,t);if(o.bottom<0||o.top>t.height)return;let s=fa(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=fa(s+36,8,Math.max(t.height-36,8));let c=document.createElement(`button`);c.type=`button`,c.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,c.textContent=`Comment`,c.style.top=`${s}px`,c.style.right=`12px`,c.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,c.getBoundingClientRect())}),e.appendChild(c)}function uo(){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 fo(){if(this.ensurePreviewLayer(),this.previewLayer?.replaceChildren(),this.previewHighlightLayer?.replaceChildren(),!this.supported||!this.previewElement){this.previewHoverRegions=[],this.syncPreviewRailLayout(0);return}let e=this.previewElement.getBoundingClientRect(),t=this.getThreadGroups(),n=[],r=[],i=this.shouldRenderPassivePreviewMarkers(),a=[];t.forEach(t=>{let o=this.resolvePreviewTarget(t.anchor);if(!o?.bubbleRect)return;r.push({key:t.key,rects:o.hoverRects?.length>0?o.hoverRects:[o.bubbleRect]});let s=this.activeCard?.groupKey===t.key,c=this.hoveredPreviewGroupKeys.includes(t.key),l=s||c;if(o.highlightRects?.forEach(t=>{let n=document.createElement(`div`);n.className=`comment-preview-highlight`,n.classList.toggle(`is-active`,s),n.classList.toggle(`is-hovered`,c),n.classList.toggle(`is-passive`,!l),n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,this.previewHighlightLayer?.appendChild(n)}),!i&&!l)return;let u=document.createElement(`button`);u.type=`button`,u.className=`ui-state-marker ui-state-marker--comment comment-preview-badge`,u.dataset.commentPreviewGroupKeys=t.key,u.classList.toggle(`is-active`,s),u.classList.toggle(`is-hovered`,c),u.classList.toggle(`is-passive`,!l),u.setAttribute(`aria-label`,`${t.threads.length} comment thread${t.threads.length===1?``:`s`}`),u.appendChild(Ia(t.threads.length));let d=fa(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=fa(d+30,6,Math.max(this.previewElement.clientHeight-30,6));u.style.top=`${d}px`,u.title=`${t.threads.length} comment${t.threads.length===1?``:`s`}`,u.addEventListener(`pointerdown`,e=>{e.preventDefault()}),u.addEventListener(`click`,()=>{this.openThreadGroup(t,{anchor:t.anchor,origin:`preview`,sourceRect:u.getBoundingClientRect()})}),this.previewLayer?.appendChild(u),n.push(d),a.push(u)}),this.previewHoverRegions=r;let o=a.reduce((e,t)=>Math.max(e,t.offsetWidth||28),0);this.syncPreviewRailLayout(o)&&this.scheduleLayoutRefresh(),this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function po(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>Oa(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>ya(t)&&Oa(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:Aa(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:Ma(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function mo(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return Fa(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function ho(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);return r.length>0?r:Pa(this.previewHoverRegions.filter(n=>n.rects.some(n=>Na(e,t,n))).map(e=>e.key))}function go(e=[]){let t=Pa(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function _o(e=[]){let t=Pa(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function vo(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function yo(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var bo={ensureEditorLayer:co,ensurePreviewLayer:uo,getPreviewGroupKeysAtPoint:ho,getPreviewGroupKeysForTarget:mo,refreshLayout:ao,renderEditorLayer:lo,renderPreviewLayer:fo,resolvePreviewTarget:po,scheduleLayoutRefresh:so,shouldRenderPassivePreviewMarkers:yo,syncHoveredPreviewGroupsFromTarget:vo,syncPreviewRailLayout:oo,updateHoveredEditorGroups:_o,updateHoveredPreviewGroups:go};function xo(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function So(){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 Co(){if(!this.commentsDrawer||!this.commentsDrawerList)return;this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),!this.supported||e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ui-record-surface comments-drawer-item`,n.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),n.addEventListener(`pointerdown`,e=>{e.preventDefault()}),n.addEventListener(`click`,()=>{this.openThreadGroup(e,{anchor:e.anchor,origin:`drawer`,sourceRect:n.getBoundingClientRect()})});let r=document.createElement(`div`);r.className=`ui-record-header comments-drawer-item-header`;let i=document.createElement(`span`);i.className=`comments-drawer-item-title`,i.textContent=_a(e.anchor);let a=document.createElement(`span`);a.className=`ui-pill-badge ui-pill-badge--count ui-pill-badge--accent comments-drawer-item-count`,a.textContent=String(e.threads.length),r.append(i,a);let o=document.createElement(`p`);o.className=`comments-drawer-item-quote`,o.textContent=e.anchor.quote||e.anchor.excerpt||`Source anchored comment`;let s=Sa(e),c=Ca(s?.body||``,`comment-markdown comments-drawer-item-preview`),l=document.createElement(`div`);l.className=`ui-record-meta comments-drawer-item-footer`;let u=document.createElement(`span`);u.textContent=`${e.threads.length} thread${e.threads.length===1?``:`s`}`;let d=document.createElement(`span`);d.className=`comments-drawer-item-updated`,d.textContent=s?`${s.userName} • ${this.formatTimestamp(s.createdAt)}`:``,l.append(u,d),n.append(r,o,c,l),t.appendChild(n)}),this.commentsDrawerList.appendChild(t)}function wo(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var To={formatTimestamp:wo,render:xo,renderDrawer:Co,renderToolbar:So};function Eo(e){this.session?.getScrollContainer?.()?.removeEventListener(`scroll`,this.handleEditorScroll),this.session=e,this.selectionAnchor=e?.getCurrentSelectionCommentAnchor?.()??null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.reactionPicker=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,e?.getScrollContainer?.()?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}),this.render()}function Do(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.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.reactionPicker=null),this.render()}function Oo(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(!ha(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(ga(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function ko(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function Ao(e=[]){this.threads=pa(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 jo(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function Mo(){this.setDrawerOpen(!1)}function No(){let e=new Map;return this.threads.forEach(t=>{let n=va(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 Po(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function Fo(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!ga(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var Io={attachSession:Eo,clearSelectionRevealTimer:Po,closeDrawer:Mo,getThreadGroups:No,handleEditorContentChange:ko,scheduleSelectionReveal:Fo,setCurrentFile:Do,setDrawerOpen:jo,setSelectionAnchor:Oo,setThreads:Ao},Lo=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.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.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=ha(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=ha(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.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)}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),this.previewHoverRegions=[],this.cardRoot?.remove(),this.editorLayer?.remove(),this.previewLayer?.remove(),this.pendingCardFocusElement=null}};Object.assign(Lo.prototype,Io,To,bo,io);var Ro=360,zo=`https://viewer.diagrams.net/js/viewer-static.min.js`,Bo=null;function Vo(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>e({didTimeout:!1,timeRemaining:()=>0}),1)}function Ho(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Uo(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}function Wo(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):Bo||(Bo=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(),Bo=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){Bo=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=zo,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),Bo)}var Go=class{constructor({getLocalUser:e,getTheme:t,onOpenFile:n=null,onOpenTextFile:r=null,onToggleQuickSwitcher:i=null,previewContainer:a,previewElement:o,toastController:s}){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.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.instanceCounter=0,this.maximizedEntry=null,this.maximizedRoot=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),Ho(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.maximizedRoot?.remove(),this.maximizedRoot=null}detachForCommit(){Ho(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.embedEntries.forEach(e=>{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?{...t,...e}:{...e,iframe:null,imageElement:null,instanceId:``,queued:!1,viewerElement:null,wrapper:null};n.set(e.key,r)}),this.embedEntries.forEach((e,t)=>{n.has(t)||e.wrapper?.remove()}),this.embedEntries=n,this.embedEntries.forEach(e=>{e.wrapper?e.placeholder?.replaceWith(e.wrapper):e.queued=!1}),this.hydrationPaused||this.hydrateVisibleEmbeds()}hydrateVisibleEmbeds(){this.embedEntries.forEach(e=>{e.wrapper||!e.placeholder?.isConnected||(e.mode===`edit`||Uo(e.placeholder,this.previewContainer,Ro))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Vo(()=>{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,e.placeholder.replaceWith(t)}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,e.placeholder.replaceWith(t);try{await this.renderViewerEntry(e)}catch(t){this.renderViewerFallback(e,t instanceof Error?t.message:`Failed to render draw.io preview`)}}async renderViewerEntry(e){let[{content:t},n]=await Promise.all([S.readFile(e.filePath),Wo()]);if(!e.wrapper?.isConnected||!e.viewerElement?.isConnected)return;let r=this.getTheme?.()===`light`?`light`:`dark`,i=document.createElement(`div`);i.className=`mxgraph drawio-viewer-frame`,i.dataset.action=`open-file`,i.dataset.filePath=e.filePath,i.setAttribute(`role`,`button`),i.setAttribute(`tabindex`,`0`),i.setAttribute(`aria-label`,`Open ${e.label.replace(/\.drawio$/i,``)}`),i.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),i.addEventListener(`keydown`,t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),this.onOpenFile?.(e.filePath))}),i.dataset.mxgraph=JSON.stringify({"check-visible-state":!1,center:!0,border:0,"dark-mode":r,editable:!1,fit:1,lightbox:!1,nav:!1,resize:!1,toolbar:``,tooltips:!1,xml:String(t??``)}),e.viewerElement.replaceChildren(i),e.viewerElement=i,n.processElements()}buildIframeUrl(e){let t=new URL(re(`/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`,ue(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(){}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`),M(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;M(n,t?`restore`:`maximize`),n.title=t?`Restore diagram size`:`Maximize diagram`,n.setAttribute(`aria-label`,t?`Restore diagram size`:`Maximize diagram`)})(),n}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-drawio-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.drawioMaximizedRoot=`true`,e.className=`drawio-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}_enterMaximizedEntry(e,t=e?.wrapper){if(!e?.wrapper||e.wrapper!==t||this.maximizedEntry?.key===e.key)return;this._exitMaximizedEntry();let n=this._ensureMaximizedRoot(),r=e.wrapper.parentElement;if(!r)return;let i=document.createElement(`div`);i.className=`drawio-maximize-spacer`,i.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=i,e.restoreParent=r,e.restoreNextSibling=e.wrapper.nextSibling||null,r.insertBefore(i,e.wrapper),n.hidden=!1,n.appendChild(e.wrapper),e.wrapper.classList.add(`is-maximized`),document.body.classList.add(`drawio-maximized-open`),this.maximizedEntry=e}_exitMaximizedEntry(){let e=this.maximizedEntry;if(!e?.wrapper){this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`);return}let{maximizeSpacer:t,restoreNextSibling:n,restoreParent:r}=e;e.wrapper.classList.remove(`is-maximized`),t?.parentElement?t.replaceWith(e.wrapper):r?.isConnected&&(n?.parentElement===r?r.insertBefore(e.wrapper,n):r.appendChild(e.wrapper)),e.maximizeSpacer=null,e.restoreParent=null,e.restoreNextSibling=null,this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`),this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}_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;M(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 Ko(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 qo=420,Jo=500,Yo=15e3,Xo=800,Zo=3,Qo=200,$o=`/excalidraw-editor.html`;function es(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function ts(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function ns(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}var rs=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.maximizedRoot=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(),ts(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEmbed(),document.body.classList.remove(`excalidraw-maximized-open`),this.embedEntries.forEach(e=>{this._clearEntryBootTimeout(e),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.warmEntry&&=(this._clearEntryBootTimeout(this.warmEntry),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.maximizedRoot?.remove(),this.maximizedRoot=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):!0}detachForCommit(){this._disconnectPlaceholderObserver(),ts(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1,this._exitMaximizedEmbed(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.maximizedRoot&&(this.maximizedRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){ts(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),ts(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}=Ko(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||ns(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)})}prepareFileDisconnect(e,{timeoutMs:t=250}={}){let n=this._findEntryByFilePath(e);if(!n?.iframe?.contentWindow)return Promise.resolve(!1);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(()=>{i(!1)},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=es(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},Jo))}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.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:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${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),this.warmEntry===e&&(this.warmEntry=null),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e,t=Yo){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)>=Zo){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(re($o)),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=i.get(`server`);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`)),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`),M(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`),M(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=`${qo}px`;let c=document.createElement(`div`);c.className=`excalidraw-embed-resizer`,c.title=`Drag to resize`,this._setupResizer(c,s,()=>this._syncEntryLayout(e)),t.append(n,s,c);let l=!1,u=`${qo}px`,d=()=>{M(o,l?`restore`:`maximize`),o.title=l?`Restore diagram size`:`Maximize diagram`,o.setAttribute(`aria-label`,l?`Restore diagram size`:`Maximize diagram`)},f=()=>{l&&(l=!1,t.classList.remove(`is-maximized`),d(),document.body.classList.remove(`excalidraw-maximized-open`),this._restoreWrapperMount(e),s.style.height=u,this.maximizedEmbed?.wrapper===t&&(this.maximizedEmbed=null),this._syncEntryLayout(e))},p=()=>{l||(this._exitMaximizedEmbed(),l=!0,u=s.style.height||`${qo}px`,this._mountWrapperInMaximizedRoot(e),t.classList.add(`is-maximized`),d(),document.body.classList.add(`excalidraw-maximized-open`),this.maximizedEmbed={wrapper:t,exit:f},this._syncEntryLayout(e))};return o.addEventListener(`click`,()=>{l?f():p()}),a.addEventListener(`click`,t=>{t.preventDefault(),this._exitMaximizedEmbed(),this.onOpenFile?.(e.filePath)}),d(),{header:n,iframe:s,instanceId:s.dataset.instanceId,labelElement:i,maxButton:o,openButton:a,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=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Qo),Xo);t.style.height=`${a}px`,t.style.pointerEvents=`none`},o=()=>{t.style.pointerEvents=``,document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),n?.()};e.addEventListener(`pointerdown`,e=>{e.preventDefault(),r=e.clientY,i=t.offsetHeight,document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o)})}_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}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-excalidraw-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawMaximizedRoot=`true`,e.className=`excalidraw-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=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=``)}_mountWrapperInMaximizedRoot(e){if(!e?.wrapper)return;let t=this._ensureMaximizedRoot();t.hidden=!1,e.restoreParent=e.wrapper.parentElement||null,e.restoreNextSibling=e.wrapper.nextSibling||null,e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}_restoreWrapperMount(e){if(e?.wrapper){if(this._shouldInlineFilePreview(e)){let{restoreParent:t,restoreNextSibling:n}=e;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e.wrapper,n):t.appendChild(e.wrapper))}else{let t=this._ensureOverlayRoot();t.hidden=!1,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}e.restoreParent=null,e.restoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}}_syncEntryLayout(e){if(!e?.wrapper||this._shouldInlineFilePreview(e))return;let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${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||``)||qo,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||qo)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,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`}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._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)}}}_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)}_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})}};function is(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function as(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var os=class{constructor({mobileBreakpointQuery:e=is()}={}){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,as(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=as(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});break}}};function ss(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function cs(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function ls(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function us(e,t,n){return`${e} ${e===1?t:n}`}function ds(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function fs(e,t){return t?{...e,requestId:t}:e}var ps=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,pendingWorkspaceRequestIds:r=null,state:i,toastController:a,vaultClient:o,view:s,refresh:c}){this.onFileDelete=t,this.onFileSelect=n,this.pendingWorkspaceRequestIds=r,this.state=i,this.toastController=a,this.vaultClient=o,this.view=s,this.refresh=c,this.createButton=document.getElementById(`sidebarCreateBtn`),this.refreshButton=document.getElementById(`refreshFilesBtn`),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 os({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),this.refreshButton?.addEventListener(`click`,()=>this.refresh()),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:`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 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`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`: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)}ensureExtension(e,t){return Be(e,t)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=St();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.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 createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile(fs({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=N(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,fs({},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=N(t);if(!r)return this.showToast(`File path is required`),!1;let i=_(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(!ss(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(fs({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=N(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(fs({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=ls(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,fs({},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,fs({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=N(t),i=N(e),a=cs(r),o=ss(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:P(i,o),ok:!0}:{extension:_(r)||`.md`,nextPath:P(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=N(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.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}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=N(e);if(!n)return this.showToast(`File path is required`),!1;let r=this.ensureExtension(P(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,Ve(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=N(e);if(!n)return this.showToast(`Base path is required`),!1;let r=He(P(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(P(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=N(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=this.ensureExtension(P(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,ds(),{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=N(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Ue(P(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=N(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=We(P(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=N(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Ge(P(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=_(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 ${us(n,`file`,`files`)} and ${us(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 ms(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({lowerPath:String(r.path).toLowerCase(),name:r.name,path:r.path,type:r.type}),r.type===`file`||r.type===`base`||r.type===`excalidraw`||r.type===`drawio`||r.type===`mermaid`||r.type===`plantuml`||r.type===`image`){t.push(r.path);continue}r.type===`directory`&&Array.isArray(r.children)&&ms(r.children,t,n)}return{files:t,searchEntries:n}}function hs(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=hs(n.children,t);if(e)return e}}return null}function gs(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=gs(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function _s(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var vs=class{constructor(){this.tree=[],this.flatFiles=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=ms(this.tree,[],[]);this.flatFiles=t.files,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 hs(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:gs(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=N(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(_s(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 ys(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function bs(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function xs(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=xs(n.children,t);if(e)return e}}return null}var Ss=420,Cs=10,ws=700,Ts=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.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}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)})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,tree:o}){if(!this.treeContainer)return;if(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(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let s=Array.from(new Set(t.map(e=>bs(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(s.includes(``)){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of s)if(!this.rerenderDirectoryBranch(t,o,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(o,{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||(h(r.path)??`file`),name:r.name||ys(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()}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=`
|
|
297
|
+
<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>
|
|
298
|
+
<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>
|
|
299
|
+
<span class="file-tree-name">${b(e.name)}</span>
|
|
300
|
+
`,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=`
|
|
301
|
+
<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>
|
|
302
|
+
<span class="file-tree-name">${b(e.name||ys(e.path))}</span>
|
|
303
|
+
`,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=xs(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)})}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 o=r===`drawio`,s=r===`excalidraw`,l=r===`base`,u=r===`image`,d=r===`mermaid`,f=r===`plantuml`;return l&&a.classList.add(`is-base`),o&&a.classList.add(`is-drawio`),s&&a.classList.add(`is-excalidraw`),u&&a.classList.add(`is-image`),d&&a.classList.add(`is-mermaid`),f&&a.classList.add(`is-plantuml`),n===e&&a.classList.add(`active`),a.style.setProperty(`--depth`,t),a.dataset.depth=t,a.dataset.path=n,a.dataset.entryType=`file`,a.innerHTML=`
|
|
304
|
+
${this.getFileIconSvg({isBase:l,isDrawio:o,isExcalidraw:s,isImage:u,isMermaid:d,isPlantUml:f})}
|
|
305
|
+
<span class="file-tree-name">${b(c(i))}</span>
|
|
306
|
+
`,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`})}),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)},ws))}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)},Ss))}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>Cs||n>Cs)&&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):!1}getFileIconSvg({isBase:e,isDrawio:t,isExcalidraw:n,isImage:r,isMermaid:i,isPlantUml:a}){return e?`<svg class="file-tree-icon" 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>`:t?`<svg class="file-tree-icon" 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>`:n?`<svg class="file-tree-icon" 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>`:r?`<svg class="file-tree-icon" 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="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.5"/><path d="m21 16-5-5L7 20"/><path d="m14 14 2 2"/></svg>`:i?`<svg class="file-tree-icon" 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>`:a?`<svg class="file-tree-icon" 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>`:`<svg class="file-tree-icon" 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>`}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?.()}},Es=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,toastController:i,vaultClient:a=S}){this.onFileSelect=t,this.onFileDelete=n,this.toastController=i,this.vaultClient=a,this.state=new vs,this.view=new Ts({mobileBreakpointQuery:e,onDirectorySelect:e=>{this.state.expandDirectoryPath(e),this.state.setSearchQuery(``),this.renderTree({reset:!0})},onDirectoryToggle:e=>{this.state.toggleDirectory(e),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 ps({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,pendingWorkspaceRequestIds:r,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){this.state.setActiveFile(e),this.renderTree()}get flatFiles(){return this.state.flatFiles}get flatDocumentFiles(){return this.state.flatFiles.filter(e=>!o(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,tree:this.state.tree})}},Ds=30;function Os(e){return String(e??``).split(`/`).pop()||``}function ks(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function As(e=``){let t=Os(e),n=ks(e);return n?`
|
|
307
|
+
<span class="file-history-path">${b(t)}</span>
|
|
308
|
+
<span class="file-history-dir">${b(n)}</span>
|
|
309
|
+
`:`<span class="file-history-path">${b(t)}</span>`}function js(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 Ms(e={}){return e.type===`local`?`local`:`commit:${String(e.hash||``).trim()}:${String(e.pathAtCommit||``).trim()}`}function Ns(){return{commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}var Ps=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=Ns(),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=Ns(),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:Ms({...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={...Ns(),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={...Ns(),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{...Ns(),loaded:!0};let t=await this.gitApiClient.readFileHistory({limit:Ds,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||Ms(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):`
|
|
310
|
+
<div class="diff-file-header">
|
|
311
|
+
<span class="diff-file-path">${b(e.path||this.currentFilePath||``)}</span>
|
|
312
|
+
</div>
|
|
313
|
+
`}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`
|
|
314
|
+
${this.renderDiffFileHeader(e)}
|
|
315
|
+
<div class="diff-empty-state">Diff renderer unavailable.</div>
|
|
316
|
+
`}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=`
|
|
317
|
+
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${r}</span>
|
|
318
|
+
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${i}</span>
|
|
319
|
+
`,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`:js(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`
|
|
320
|
+
<button
|
|
321
|
+
class="ui-record-surface file-history-item${t?` active`:``}${e.type===`local`?` file-history-item-local`:``}"
|
|
322
|
+
type="button"
|
|
323
|
+
data-file-history-select="${b(e.key)}"
|
|
324
|
+
aria-current="${t?`true`:`false`}"
|
|
325
|
+
>
|
|
326
|
+
<span class="file-history-item-top">
|
|
327
|
+
<span class="file-history-item-copy">
|
|
328
|
+
<span class="file-history-item-title">${b(a)}</span>
|
|
329
|
+
<span class="file-history-item-meta">${e.type===`local`?b(this.renderScopeLabels(e)):i}</span>
|
|
330
|
+
</span>
|
|
331
|
+
${o}
|
|
332
|
+
</span>
|
|
333
|
+
<span class="file-history-item-stats">
|
|
334
|
+
<span class="git-change-add">+${n}</span>
|
|
335
|
+
<span class="git-change-del">-${r}</span>
|
|
336
|
+
</span>
|
|
337
|
+
</button>
|
|
338
|
+
`}renderSelectedHeader(e){let t=e?.entry;return t?`
|
|
339
|
+
<div class="file-history-detail-header">
|
|
340
|
+
<div class="file-history-detail-copy">
|
|
341
|
+
<span class="file-history-detail-kicker">${t.type===`local`?`Live workspace`:`Commit ${b(t.shortHash||``)}`}</span>
|
|
342
|
+
<h2 class="file-history-detail-title">${t.type===`local`?`Local changes`:b(t.subject||t.shortHash||`Commit`)}</h2>
|
|
343
|
+
<p class="file-history-detail-meta">${t.type===`local`?b(this.renderScopeLabels(t)):js(t)}</p>
|
|
344
|
+
</div>
|
|
345
|
+
<div class="file-history-detail-actions">
|
|
346
|
+
<button
|
|
347
|
+
class="${U({variant:`secondary`,action:!0,surface:!0})}"
|
|
348
|
+
type="button"
|
|
349
|
+
data-file-history-open-selected-diff
|
|
350
|
+
>
|
|
351
|
+
Open Standalone Diff
|
|
352
|
+
</button>
|
|
353
|
+
${t.type===`commit`?`
|
|
354
|
+
<button
|
|
355
|
+
class="${U({variant:`primary`,action:!0})}"
|
|
356
|
+
type="button"
|
|
357
|
+
data-file-history-open-selected-preview
|
|
358
|
+
>
|
|
359
|
+
Preview File
|
|
360
|
+
</button>
|
|
361
|
+
`:``}
|
|
362
|
+
</div>
|
|
363
|
+
</div>
|
|
364
|
+
`:`
|
|
365
|
+
<div class="file-history-detail-header">
|
|
366
|
+
<div class="file-history-detail-copy">
|
|
367
|
+
<span class="file-history-detail-kicker">History</span>
|
|
368
|
+
<h2 class="file-history-detail-title">No selection</h2>
|
|
369
|
+
<p class="file-history-detail-meta">Choose a history item to inspect the file diff.</p>
|
|
370
|
+
</div>
|
|
371
|
+
</div>
|
|
372
|
+
`}renderSelectedBody(e){let t=e?.entry;return t?e.loading?`
|
|
373
|
+
<section class="diff-file-block file-history-diff-block">
|
|
374
|
+
${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
|
|
375
|
+
<div class="diff-empty-state">Loading diff...</div>
|
|
376
|
+
</section>
|
|
377
|
+
`:e.error?`
|
|
378
|
+
<section class="diff-file-block file-history-diff-block">
|
|
379
|
+
${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
|
|
380
|
+
<div class="diff-empty-state">${b(e.error)}</div>
|
|
381
|
+
</section>
|
|
382
|
+
`:e.detail?.detail?`
|
|
383
|
+
<section class="diff-file-block file-history-diff-block">
|
|
384
|
+
${this.renderDiffMarkup(e.detail.detail)}
|
|
385
|
+
</section>
|
|
386
|
+
`:`<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=`
|
|
387
|
+
<section class="file-history-shell">
|
|
388
|
+
<aside class="file-history-sidebar" aria-label="File history entries">
|
|
389
|
+
<header class="file-history-sidebar-header">
|
|
390
|
+
<span class="file-history-kicker">File history</span>
|
|
391
|
+
<div class="file-history-title">${As(this.currentFilePath)}</div>
|
|
392
|
+
<p class="file-history-sidebar-copy">Select an entry to inspect the exact changes for this file.</p>
|
|
393
|
+
</header>
|
|
394
|
+
<div class="file-history-list" data-file-history-list>
|
|
395
|
+
${this.getEntries().map(e=>this.renderHistoryItem(e)).join(``)}
|
|
396
|
+
</div>
|
|
397
|
+
${this.history.hasMore?`
|
|
398
|
+
<div class="git-history-footer file-history-footer">
|
|
399
|
+
<button
|
|
400
|
+
class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
|
|
401
|
+
type="button"
|
|
402
|
+
data-file-history-load-more
|
|
403
|
+
${this.history.loadingMore?`disabled`:``}
|
|
404
|
+
>
|
|
405
|
+
${this.history.loadingMore?`Loading...`:`Load More`}
|
|
406
|
+
</button>
|
|
407
|
+
</div>
|
|
408
|
+
`:``}
|
|
409
|
+
</aside>
|
|
410
|
+
<section class="file-history-detail">
|
|
411
|
+
${this.renderSelectedHeader(e)}
|
|
412
|
+
<div class="file-history-detail-body">
|
|
413
|
+
${this.renderSelectedBody(e)}
|
|
414
|
+
</div>
|
|
415
|
+
</section>
|
|
416
|
+
</section>
|
|
417
|
+
`,this.restoreListScroll()}};function Fs(e){return String(e??``).split(`/`).pop()||``}function Is(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function Ls(e){return`diff-section-${encodeURIComponent(String(e??``)).replace(/%/g,`_`)}`}function Rs(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 zs(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 Bs(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function Vs(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 Hs(e,t){let n=Bs(e,t),r=Vs(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 Us(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 Ws(e,t,n){let r=Number.isInteger(e.oldLine)?e.oldLine:``,i=Number.isInteger(e.newLine)?e.newLine:``;return`
|
|
418
|
+
<div class="diff-line ${e.type===`note`?`note`:e.type}">
|
|
419
|
+
<div class="diff-line-numbers">
|
|
420
|
+
<span class="diff-line-num">${r}</span>
|
|
421
|
+
<span class="diff-line-num">${i}</span>
|
|
422
|
+
</div>
|
|
423
|
+
<div class="diff-line-prefix">${b(e.type===`context`||e.type===`note`?` `:t)}</div>
|
|
424
|
+
<div class="diff-line-content">${n}</div>
|
|
425
|
+
</div>
|
|
426
|
+
`}function Gs(e,t){let n=e?b(e.content):``,r=t?b(t.content):``;if(e&&t&&e.type===`deletion`&&t.type===`addition`){let i=Hs(e.content,t.content);n=i.leftHtml,r=i.rightHtml}return`
|
|
427
|
+
<div class="diff-split-row">
|
|
428
|
+
<div class="diff-split-line ${e?.type||`empty`}">
|
|
429
|
+
<span class="diff-split-num">${Number.isInteger(e?.oldLine)?e.oldLine:``}</span>
|
|
430
|
+
<span class="diff-split-content">${n}</span>
|
|
431
|
+
</div>
|
|
432
|
+
<div class="diff-split-line ${t?.type||`empty`}">
|
|
433
|
+
<span class="diff-split-num">${Number.isInteger(t?.newLine)?t.newLine:``}</span>
|
|
434
|
+
<span class="diff-split-content">${r}</span>
|
|
435
|
+
</div>
|
|
436
|
+
</div>
|
|
437
|
+
`}var Ks=class{constructor({gitApiClient:e=null,onBackToHistory:t=null,onCommitStaged:n=null,onOpenFile:r=null,onStageFile:i=null,onUnstageFile:a=null,toastController:o=null}={}){this.gitApiClient=e,this.onBackToHistory=t,this.onCommitStaged=n,this.onOpenFile=r,this.onStageFile=i,this.onUnstageFile=a,this.toastController=o,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.requestScope=`all`,this.commitHash=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.requestScope=`all`,this.commitHash=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.commitMeta=null,this.historyFilePath=null,this.activeFilePath=e,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.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.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.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;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 Us(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(Ws(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?Hs(e.content,i.content):null;e&&t.push(Ws(e,`-`,a?.leftHtml??b(e.content))),i&&t.push(Ws(i,`+`,a?.rightHtml??b(i.content)))}}return`
|
|
438
|
+
<div class="diff-hunk-header">${b(e.header)}</div>
|
|
439
|
+
${t.join(``)}
|
|
440
|
+
`}renderFileHeader(e){return`
|
|
441
|
+
<div class="diff-file-header">
|
|
442
|
+
<span class="diff-file-path">${b(e.path)}</span>
|
|
443
|
+
<span class="ui-status-badge ${Rs(e.status)}">${b(e.status)}</span>
|
|
444
|
+
<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>
|
|
445
|
+
</div>
|
|
446
|
+
`}renderUnifiedFileBody(e){return`
|
|
447
|
+
${e.isBinary?`<div class="diff-binary-message">${b(e.binaryMessage||`Binary file changed`)}</div>`:``}
|
|
448
|
+
${e.hunks.map(e=>this.renderUnifiedHunk(e)).join(``)}
|
|
449
|
+
`}renderSplitFileBody(e){return`
|
|
450
|
+
<div class="diff-split">
|
|
451
|
+
<div class="diff-split-pane">
|
|
452
|
+
<div class="diff-split-pane-header">Before</div>
|
|
453
|
+
${e.hunks.map(e=>{let t=[];for(let n of Us(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(Gs(e,e));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1)t.push(Gs(n.deletions[r]??null,n.additions[r]??null))}return`
|
|
454
|
+
<div class="diff-split-hunk">${b(e.header)}</div>
|
|
455
|
+
${t.join(``)}
|
|
456
|
+
`}).join(``)}
|
|
457
|
+
</div>
|
|
458
|
+
</div>
|
|
459
|
+
`}renderDiffDetail(e,t,{includeHeader:n=!0}={}){if(!e)return`<div class="diff-empty-state">Select a file to load its diff.</div>`;if(e.tooLarge)return`
|
|
460
|
+
${n?this.renderFileHeader(e):``}
|
|
461
|
+
<div class="diff-limit-card">
|
|
462
|
+
<strong>Large diff withheld</strong>
|
|
463
|
+
<span>This file diff is large enough to impact rendering performance.</span>
|
|
464
|
+
<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>
|
|
465
|
+
</div>
|
|
466
|
+
`;let r=this.mode===`split`?this.renderSplitFileBody(e,t):this.renderUnifiedFileBody(e,t);return`${n?this.renderFileHeader(e):``}${r}`}renderFocusedFileBody(){let e=this.getCurrentFile();if(!e)return`<div class="diff-empty-state">No changes to display.</div>`;if(this.isFileLoading(e.path))return`
|
|
467
|
+
<section class="diff-file-block">
|
|
468
|
+
${this.renderFileHeader(e)}
|
|
469
|
+
<div class="diff-empty-state">Loading file diff...</div>
|
|
470
|
+
</section>
|
|
471
|
+
`;let t=this.fileErrors.get(e.path);return t?`
|
|
472
|
+
<section class="diff-file-block">
|
|
473
|
+
${this.renderFileHeader(e)}
|
|
474
|
+
<div class="diff-empty-state">${b(t)}</div>
|
|
475
|
+
</section>
|
|
476
|
+
`:`
|
|
477
|
+
<section class="diff-file-block" data-diff-file-index="${this.currentIndex}">
|
|
478
|
+
${this.renderDiffDetail(this.getFileDetail(e.path)??e,this.currentIndex)}
|
|
479
|
+
</section>
|
|
480
|
+
`}renderCommitHeader(){return this.source!==`commit`||!this.commitMeta?``:`
|
|
481
|
+
<section class="diff-commit-header">
|
|
482
|
+
<div class="diff-commit-subject">${b(this.commitMeta.subject||this.commitMeta.shortHash||`Commit`)}</div>
|
|
483
|
+
<div class="diff-commit-meta">
|
|
484
|
+
<span>${b(this.commitMeta.shortHash||``)}</span>
|
|
485
|
+
<span>${b(this.commitMeta.authorName||`Unknown`)}</span>
|
|
486
|
+
<span title="${b(this.commitMeta.authoredAt||``)}">${b(this.commitMeta.relativeDateLabel||``)}</span>
|
|
487
|
+
${this.commitMeta.isMergeCommit?`<span>Merge commit</span>`:``}
|
|
488
|
+
</div>
|
|
489
|
+
<div class="diff-commit-meta diff-commit-meta-secondary">
|
|
490
|
+
<span>${b(this.commitMeta.hash||``)}</span>
|
|
491
|
+
<span>${Number(this.data?.summary?.filesChanged||0)} file${Number(this.data?.summary?.filesChanged||0)===1?``:`s`}</span>
|
|
492
|
+
</div>
|
|
493
|
+
</section>
|
|
494
|
+
`}renderCommitIndex(){return`
|
|
495
|
+
<aside class="diff-commit-index" aria-label="Changed files in commit">
|
|
496
|
+
<div class="diff-commit-index-header">Changed Files</div>
|
|
497
|
+
<div class="diff-commit-index-list">
|
|
498
|
+
${(this.data?.files??[]).map((e,t)=>{let n=this.activeFilePath===e.path,r=Is(e.path);return`
|
|
499
|
+
<button
|
|
500
|
+
class="ui-record-surface diff-index-item${n?` active`:``}"
|
|
501
|
+
type="button"
|
|
502
|
+
data-diff-index-path="${b(e.path)}"
|
|
503
|
+
aria-current="${n?`true`:`false`}"
|
|
504
|
+
>
|
|
505
|
+
<span class="ui-record-header diff-index-item-top">
|
|
506
|
+
<span class="ui-record-title diff-index-item-name">${b(Fs(e.path))}</span>
|
|
507
|
+
<span class="ui-status-badge ${Rs(e.status)}">${b(e.status)}</span>
|
|
508
|
+
</span>
|
|
509
|
+
${r?`<span class="ui-record-subtitle diff-index-item-path">${b(r)}</span>`:``}
|
|
510
|
+
<span class="ui-record-meta diff-index-item-meta">
|
|
511
|
+
<span>${t+1}</span>
|
|
512
|
+
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
|
|
513
|
+
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
|
|
514
|
+
</span>
|
|
515
|
+
</button>
|
|
516
|
+
`}).join(``)}
|
|
517
|
+
</div>
|
|
518
|
+
</aside>
|
|
519
|
+
`}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`
|
|
520
|
+
<section
|
|
521
|
+
class="diff-commit-section${r?` active`:``}${n?` collapsed`:``}"
|
|
522
|
+
id="${Ls(e.path)}"
|
|
523
|
+
data-diff-section-path="${b(e.path)}"
|
|
524
|
+
>
|
|
525
|
+
<button
|
|
526
|
+
class="diff-commit-section-header"
|
|
527
|
+
type="button"
|
|
528
|
+
data-diff-section-toggle="${b(e.path)}"
|
|
529
|
+
>
|
|
530
|
+
<span class="diff-commit-section-main">
|
|
531
|
+
${zs(n)}
|
|
532
|
+
<span class="diff-commit-section-copy">
|
|
533
|
+
<span class="diff-commit-section-name">${b(Fs(e.path))}</span>
|
|
534
|
+
${Is(e.path)?`<span class="diff-commit-section-path">${b(Is(e.path))}</span>`:``}
|
|
535
|
+
</span>
|
|
536
|
+
</span>
|
|
537
|
+
<span class="diff-commit-section-meta">
|
|
538
|
+
<span class="ui-status-badge ${Rs(e.status)}">${b(e.status)}</span>
|
|
539
|
+
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
|
|
540
|
+
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
|
|
541
|
+
</span>
|
|
542
|
+
</button>
|
|
543
|
+
<div class="diff-commit-section-body${n?` hidden`:``}">
|
|
544
|
+
${s}
|
|
545
|
+
</div>
|
|
546
|
+
</section>
|
|
547
|
+
`}renderCommitBody(){return this.layoutMode===`focused`?`
|
|
548
|
+
<div class="diff-commit-shell diff-commit-shell-focused">
|
|
549
|
+
${this.renderCommitIndex()}
|
|
550
|
+
<div class="diff-commit-main">
|
|
551
|
+
${this.renderFocusedFileBody()}
|
|
552
|
+
</div>
|
|
553
|
+
</div>
|
|
554
|
+
`:`
|
|
555
|
+
<div class="diff-commit-shell diff-commit-shell-stacked">
|
|
556
|
+
${this.renderCommitIndex()}
|
|
557
|
+
<div class="diff-commit-main">
|
|
558
|
+
<div class="diff-commit-sections">
|
|
559
|
+
${(this.data?.files??[]).map((e,t)=>this.renderStackedSection(e,t)).join(``)}
|
|
560
|
+
</div>
|
|
561
|
+
</div>
|
|
562
|
+
</div>
|
|
563
|
+
`}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=Ls(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 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?.summary?.additions??0,t=this.data?.summary?.deletions??0;this.stats.innerHTML=`
|
|
564
|
+
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e}</span>
|
|
565
|
+
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${t}</span>
|
|
566
|
+
`}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.source===`commit`?this.content.innerHTML=`${this.renderCommitHeader()}${this.renderCommitBody()}`:this.content.innerHTML=this.renderFocusedFileBody(),this.syncToolbar())}}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?Fs(n):this.activeFilePath?Fs(this.activeFilePath):this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:t?Fs(t):r===`staged`?`Staged Changes`:r===`working-tree`?`Working Tree Changes`:`All Changes`}},qs=30,Js=1e4;function Ys(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function Xs(e){return String(e??``).split(`/`).pop()||``}function Zs(){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 Qs(){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 $s(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 ec(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 tc(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 nc(e={},t={}){let n=Number(e.additions||0),r=Number(e.deletions||0);return Number(e.changedFiles||0)>0||n>0||r>0?`
|
|
567
|
+
<span class="git-change-stats" aria-label="Local diff summary">
|
|
568
|
+
<span class="git-change-add">+${n}</span>
|
|
569
|
+
<span class="git-change-del">-${r}</span>
|
|
570
|
+
</span>
|
|
571
|
+
`:t.upstream||Number(t.ahead||0)>0||Number(t.behind||0)>0?`
|
|
572
|
+
<span class="git-sync-info" aria-label="Remote sync status">
|
|
573
|
+
<span class="git-sync-metric git-sync-metric--ahead">↑${Number(t.ahead||0)}</span>
|
|
574
|
+
<span class="git-sync-metric git-sync-metric--behind">↓${Number(t.behind||0)}</span>
|
|
575
|
+
</span>
|
|
576
|
+
`:`<span class="git-sync-info git-sync-info-muted">Clean</span>`}function rc(e={}){return b(String(e.subject||``).trim()||e.shortHash||`Commit`)}var ic=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})},Js))}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:qs,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:qs,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`
|
|
577
|
+
<section class="git-section">
|
|
578
|
+
<button class="git-section-header" type="button" data-git-section-toggle="${b(e.key)}">
|
|
579
|
+
${$s(n)}
|
|
580
|
+
${b(e.label)}
|
|
581
|
+
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${t.length}</span>
|
|
582
|
+
</button>
|
|
583
|
+
<div class="git-file-list${n?` hidden`:``}">
|
|
584
|
+
${t.map(e=>this.renderFile(e)).join(``)}
|
|
585
|
+
</div>
|
|
586
|
+
</section>
|
|
587
|
+
`}renderPullBackupsSection(){return!Array.isArray(this.pullBackups)||this.pullBackups.length===0?``:`
|
|
588
|
+
<section class="git-section">
|
|
589
|
+
<button class="git-section-header" type="button" data-git-section-toggle="pull-backups">
|
|
590
|
+
${$s(this.collapsedSections.has(`pull-backups`))}
|
|
591
|
+
Pull Backups
|
|
592
|
+
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${this.pullBackups.length}</span>
|
|
593
|
+
</button>
|
|
594
|
+
<div class="git-file-list${this.collapsedSections.has(`pull-backups`)?` hidden`:``}">
|
|
595
|
+
${this.pullBackups.map(e=>this.renderPullBackup(e)).join(``)}
|
|
596
|
+
</div>
|
|
597
|
+
</section>
|
|
598
|
+
`}renderPullBackup(e){let t=String(e?.createdAt||``).replace(`T`,` `).replace(/\.\d+Z?$/u,`Z`),n=Number(e?.fileCount||0);return`
|
|
599
|
+
<div class="ui-item-row git-file-row">
|
|
600
|
+
<button
|
|
601
|
+
class="ui-item-main git-file-item"
|
|
602
|
+
type="button"
|
|
603
|
+
data-git-pull-backup-path="${b(e.summaryPath||``)}"
|
|
604
|
+
>
|
|
605
|
+
${Zs()}
|
|
606
|
+
<span class="ui-item-copy git-file-copy">
|
|
607
|
+
<span class="ui-item-title git-file-name">Pull backup ${b(e.id||``)}</span>
|
|
608
|
+
<span class="ui-item-subtitle git-file-path">${b(`${t} · ${e.branch||`HEAD`} · ${n} file${n===1?``:`s`}`)}</span>
|
|
609
|
+
</span>
|
|
610
|
+
<span class="ui-status-badge ui-status-badge--warning">BK</span>
|
|
611
|
+
</button>
|
|
612
|
+
</div>
|
|
613
|
+
`}renderFile(e){let t=this.selection.source===`workspace`&&this.selection.path===e.path&&this.selection.scope===e.scope,n=Ys(e.path),r=Xs(e.path),i=String(e.path||``),a=tc(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`
|
|
614
|
+
<div class="ui-item-row git-file-row${t?` active`:``}">
|
|
615
|
+
<button
|
|
616
|
+
class="ui-item-main git-file-item${t?` active`:``}"
|
|
617
|
+
type="button"
|
|
618
|
+
data-git-path="${b(e.path)}"
|
|
619
|
+
data-git-scope="${b(e.scope)}"
|
|
620
|
+
title="${b(i)}"
|
|
621
|
+
>
|
|
622
|
+
${Zs()}
|
|
623
|
+
<span class="ui-item-copy git-file-copy">
|
|
624
|
+
<span class="ui-item-title git-file-name">${b(r)}</span>
|
|
625
|
+
${n?`<span class="ui-item-subtitle git-file-path">${b(n)}</span>`:``}
|
|
626
|
+
</span>
|
|
627
|
+
<span class="ui-status-badge ${a}">${b(e.code)}</span>
|
|
628
|
+
</button>
|
|
629
|
+
<div class="ui-item-actions git-file-actions">
|
|
630
|
+
<button
|
|
631
|
+
class="ui-icon-button ui-action-icon ui-action-icon--surface"
|
|
632
|
+
type="button"
|
|
633
|
+
data-git-file-action="reset"
|
|
634
|
+
data-git-path="${b(e.path)}"
|
|
635
|
+
data-git-scope="${b(e.scope)}"
|
|
636
|
+
aria-label="Reset ${b(r)}"
|
|
637
|
+
title="Reset to current branch"
|
|
638
|
+
${u?`disabled`:``}
|
|
639
|
+
>
|
|
640
|
+
${u?`...`:ec(`reset`)}
|
|
641
|
+
</button>
|
|
642
|
+
<button
|
|
643
|
+
class="ui-icon-button ui-action-icon ui-action-icon--surface"
|
|
644
|
+
type="button"
|
|
645
|
+
data-git-file-action="${o.value}"
|
|
646
|
+
data-git-path="${b(e.path)}"
|
|
647
|
+
data-git-scope="${b(e.scope)}"
|
|
648
|
+
aria-label="${b(o.label)} ${b(r)}"
|
|
649
|
+
title="${b(o.label)}"
|
|
650
|
+
${c?`disabled`:``}
|
|
651
|
+
>
|
|
652
|
+
${c?`...`:ec(o.value)}
|
|
653
|
+
</button>
|
|
654
|
+
</div>
|
|
655
|
+
</div>
|
|
656
|
+
`}renderPanelModes(){return`
|
|
657
|
+
<div class="${Jr({pill:!0,extra:`git-panel-mode-switch`})}" role="tablist" aria-label="Git panel modes">
|
|
658
|
+
<button
|
|
659
|
+
class="${G({active:this.panelMode===`changes`,extra:`git-panel-mode-btn`})}"
|
|
660
|
+
type="button"
|
|
661
|
+
data-git-panel-mode="changes"
|
|
662
|
+
aria-selected="${this.panelMode===`changes`}"
|
|
663
|
+
>
|
|
664
|
+
Changes
|
|
665
|
+
</button>
|
|
666
|
+
<button
|
|
667
|
+
class="${G({active:this.panelMode===`history`,extra:`git-panel-mode-btn`})}"
|
|
668
|
+
type="button"
|
|
669
|
+
data-git-panel-mode="history"
|
|
670
|
+
aria-selected="${this.panelMode===`history`}"
|
|
671
|
+
>
|
|
672
|
+
History
|
|
673
|
+
</button>
|
|
674
|
+
</div>
|
|
675
|
+
`}renderHistoryRow(e){let t=this.selection.source===`commit`&&this.selection.commitHash===e.hash,n=Number(e.filesChanged||0);return`
|
|
676
|
+
<button
|
|
677
|
+
class="ui-record-surface git-history-row${t?` active`:``}"
|
|
678
|
+
type="button"
|
|
679
|
+
data-git-commit-hash="${b(e.hash||``)}"
|
|
680
|
+
title="${b(e.authoredAt||``)}"
|
|
681
|
+
>
|
|
682
|
+
<span class="ui-record-header git-history-row-top">
|
|
683
|
+
<span class="ui-record-title git-history-subject">${rc(e)}</span>
|
|
684
|
+
<span class="ui-pill-badge ui-pill-badge--code git-history-hash">${b(e.shortHash||``)}</span>
|
|
685
|
+
</span>
|
|
686
|
+
<span class="ui-record-meta git-history-row-meta">
|
|
687
|
+
<span>${b(e.authorName||`Unknown`)}</span>
|
|
688
|
+
<span>${b(e.relativeDateLabel||``)}</span>
|
|
689
|
+
<span>${n} file${n===1?``:`s`}</span>
|
|
690
|
+
${e.isMergeCommit?`<span>Merge</span>`:``}
|
|
691
|
+
</span>
|
|
692
|
+
<span class="ui-record-meta git-history-row-stats">
|
|
693
|
+
<span class="git-change-add">+${Number(e.additions||0)}</span>
|
|
694
|
+
<span class="git-change-del">-${Number(e.deletions||0)}</span>
|
|
695
|
+
</span>
|
|
696
|
+
</button>
|
|
697
|
+
`}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>`:`
|
|
698
|
+
<div class="git-history-list">
|
|
699
|
+
${e.map(e=>this.renderHistoryRow(e)).join(``)}
|
|
700
|
+
</div>
|
|
701
|
+
${this.history.hasMore?`
|
|
702
|
+
<div class="git-history-footer">
|
|
703
|
+
<button
|
|
704
|
+
class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
|
|
705
|
+
type="button"
|
|
706
|
+
data-git-history-load-more
|
|
707
|
+
${this.history.loadingMore?`disabled`:``}
|
|
708
|
+
>
|
|
709
|
+
${this.history.loadingMore?`Loading...`:`Load More`}
|
|
710
|
+
</button>
|
|
711
|
+
</div>
|
|
712
|
+
`:``}
|
|
713
|
+
`}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`
|
|
714
|
+
${e}
|
|
715
|
+
${t||`<div class="git-panel-empty">No local changes</div>`}
|
|
716
|
+
${n?`
|
|
717
|
+
<div class="git-panel-footer">
|
|
718
|
+
<div class="git-panel-footer-actions">
|
|
719
|
+
<button class="${U({variant:`secondary`,size:`compact`,action:!0,surface:!0})}" type="button" data-git-view-all>
|
|
720
|
+
<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>
|
|
721
|
+
View Full Diff
|
|
722
|
+
</button>
|
|
723
|
+
<button
|
|
724
|
+
class="${U({variant:`primary`,action:!0,wide:!0,extra:`git-footer-commit-btn`})}"
|
|
725
|
+
type="button"
|
|
726
|
+
data-git-commit-staged
|
|
727
|
+
${!r||i?`disabled`:``}
|
|
728
|
+
>
|
|
729
|
+
${i?`Working...`:`Commit Staged`}
|
|
730
|
+
</button>
|
|
731
|
+
</div>
|
|
732
|
+
</div>
|
|
733
|
+
`:``}
|
|
734
|
+
`}renderEmpty(e){this.panel&&(this.panel.innerHTML=`<div class="git-panel-empty">${b(e)}</div>`)}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=`
|
|
735
|
+
<div class="git-branch-bar">
|
|
736
|
+
<div class="git-branch-meta">
|
|
737
|
+
<span class="git-branch-name">
|
|
738
|
+
${Qs()}
|
|
739
|
+
${b(e.name||`HEAD`)}
|
|
740
|
+
</span>
|
|
741
|
+
${nc(this.status.summary,e)}
|
|
742
|
+
</div>
|
|
743
|
+
<div class="git-branch-actions" role="group" aria-label="Remote sync actions">
|
|
744
|
+
<button
|
|
745
|
+
class="${U({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
|
|
746
|
+
type="button"
|
|
747
|
+
data-git-sync-action="pull"
|
|
748
|
+
title="${t?`Pull remote changes (fast-forward only)`:`No upstream branch configured`}"
|
|
749
|
+
aria-label="Pull branch"
|
|
750
|
+
${!t||n?`disabled`:``}
|
|
751
|
+
>
|
|
752
|
+
${n?`...`:`${ec(`pull`)}<span>Pull</span>`}
|
|
753
|
+
</button>
|
|
754
|
+
<button
|
|
755
|
+
class="${U({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
|
|
756
|
+
type="button"
|
|
757
|
+
data-git-sync-action="push"
|
|
758
|
+
title="${t?`Push local commits`:`No upstream branch configured`}"
|
|
759
|
+
aria-label="Push branch"
|
|
760
|
+
${!t||r?`disabled`:``}
|
|
761
|
+
>
|
|
762
|
+
${r?`...`:`${ec(`push`)}<span>Push</span>`}
|
|
763
|
+
</button>
|
|
764
|
+
</div>
|
|
765
|
+
${this.renderPanelModes()}
|
|
766
|
+
</div>
|
|
767
|
+
${this.panelMode===`history`?this.renderHistoryPanel():this.renderChangesPanel()}
|
|
768
|
+
`}},ac=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()}},oc=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.onNavigateToHeading=t,this.onWillOpen=n,this.panel=document.getElementById(`outlinePanel`),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()),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.outlineOpen){this.refresh();return}this.cleanup()}refresh(){if(!this.navigation)return;if(!this.outlineOpen){this.cleanup();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.pinnedHeadingId=e.dataset.target,this.notifyHeadingNavigation(t,e.dataset.target),this.scrollHeadingIntoView(t,{behavior:`auto`}),this.setActiveItem(e.dataset.target,{behavior:`auto`}),this.mobileBreakpointQuery.matches&&this.close()})}),this.observeHeadings(Array.from(e))}cleanup(){this.activeHeadingFrame&&=(cancelAnimationFrame(this.activeHeadingFrame),null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.headings=[],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){this.cleanup(),!(!this.previewContainer||e.length===0)&&(this.headings=e,this.previewContainer.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),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})}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)})}},sc=.35,cc=120,lc=12,uc=2;function dc(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function fc(e){return Math.max(e,0)}function pc(e){return Math.max(e.clientHeight*sc,lc)}function mc(e){return(e?.scrollTop??0)<=uc}function hc(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function gc(e){return!e.querySelector(`[data-source-line]`)}function _c(e){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:500}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function vc(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}var yc=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,vc(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,vc(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=_c(()=>{this.previewBlocksWarmId=null,this.previewBlocks=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks()}))}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()},cc)}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,sc),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=dc(e),i=dc(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=fc(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if(mc(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=dc(this.previewContainer),c=pc(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+pc(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:hc(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=>gc(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=dc(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},bc=`<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>`,xc=`<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>`,Sc=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`?xc:bc;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`)})}},Cc=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`;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}},wc=16/9,Tc=240,Ec=720,Dc=180;function Oc(e){return Math.max(Dc,Math.min(Ec,Math.ceil(e||Tc)))}var kc=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}=Ko(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||wc,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=Oc(n>0?n/(e.aspectRatio||wc):e.inlineHeightPx);e.inlineHeightPx=r,X(t,`height`,`${r}px`),X(e.wrapper,`position`,`absolute`),X(e.wrapper,`top`,`${t.offsetTop}px`),X(e.wrapper,`left`,`${t.offsetLeft}px`),X(e.wrapper,`width`,`${t.offsetWidth}px`),X(e.wrapper,`height`,`${r}px`),X(e.wrapper,`margin`,`0`),X(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 X(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var Z=1,Ac=6,jc=.25,Mc=2,Nc=6;function Pc(e){let t=Number(e);return Number.isFinite(t)?Math.min(Ac,Math.max(Z,Math.round(t*100)/100)):Z}function Fc(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)}var Ic=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=Z,this.offsetX=0,this.offsetY=0,this.activePointerId=null,this.dragStartX=0,this.dragStartY=0,this.dragOriginX=0,this.dragOriginY=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(jc);return}if(e.key===`-`){e.preventDefault(),this.zoomBy(-jc);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.activePointerId=null,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=Z,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=Pc(e),this.clampOffsets(),this.syncTransform()}clampOffsets(){if(!this.viewport||!this.imageElement){this.offsetX=0,this.offsetY=0;return}this.offsetX=Fc(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=Fc(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>Z?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=Z&&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.document.createElement(`span`);o.className=`image-lightbox-zoom-label`,o.textContent=`100%`;let s=this.createControlButton(`Reset`,`Reset zoom and position`,()=>this.resetView()),c=this.createControlButton(`Close`,`Close image preview`,()=>this.close());a.append(o,s,c),r.append(i,a);let l=this.document.createElement(`div`);l.className=`image-lightbox-viewport`;let u=this.document.createElement(`img`);u.className=`image-lightbox-image`,u.alt=``,u.addEventListener(`load`,()=>{this.clampOffsets(),this.syncTransform()}),l.addEventListener(`wheel`,e=>{this.isOpen&&(e.preventDefault(),this.zoomBy(e.deltaY<0?jc:-jc))},{passive:!1}),l.addEventListener(`pointerdown`,e=>{!this.isOpen||this.scale<=Z||e.button!==0||(this.activePointerId=e.pointerId,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOriginX=this.offsetX,this.dragOriginY=this.offsetY,this.didDrag=!1,l.classList.add(`is-dragging`),l.setPointerCapture?.(e.pointerId),e.preventDefault())}),l.addEventListener(`pointermove`,e=>{!this.isOpen||this.activePointerId!==e.pointerId||(!this.didDrag&&(Math.abs(e.clientX-this.dragStartX)>=Nc||Math.abs(e.clientY-this.dragStartY)>=Nc)&&(this.didDrag=!0),this.offsetX=this.dragOriginX+(e.clientX-this.dragStartX),this.offsetY=this.dragOriginY+(e.clientY-this.dragStartY),this.clampOffsets(),this.syncTransform())});let d=e=>{this.activePointerId===e.pointerId&&(this.activePointerId=null,l.classList.remove(`is-dragging`),l.releasePointerCapture?.(e.pointerId),this.imageElement.style.cursor=this.scale>Z?`grab`:`zoom-in`)};return l.addEventListener(`pointerup`,d),l.addEventListener(`pointercancel`,d),u.addEventListener(`click`,e=>{if(this.isOpen){if(e.preventDefault(),e.stopPropagation(),this.didDrag){this.didDrag=!1;return}this.scale<=Z&&this.setScale(Mc)}}),l.appendChild(u),n.append(r,l),e.append(t,n),this.document.body.appendChild(e),this.overlayRoot=e,this.viewport=l,this.imageElement=u,this.zoomLabel=o,this.titleElement=i,this.resetButton=s,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}},Lc=globalThis,Rc=e=>e,zc=Lc.trustedTypes,Bc=zc?zc.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Vc=`$lit$`,Q=`lit$${Math.random().toFixed(9).slice(2)}$`,Hc=`?`+Q,Uc=`<${Hc}>`,Wc=document,Gc=()=>Wc.createComment(``),Kc=e=>e===null||typeof e!=`object`&&typeof e!=`function`,qc=Array.isArray,Jc=e=>qc(e)||typeof e?.[Symbol.iterator]==`function`,Yc=`[
|
|
769
|
+
\f\r]`,Xc=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Zc=/-->/g,Qc=/>/g,$c=RegExp(`>|${Yc}(?:([^\\s"'>=/]+)(${Yc}*=${Yc}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),el=/'/g,tl=/"/g,nl=/^(?:script|style|textarea|title)$/i,rl=(e=>(t,...n)=>({_$litType$:e,strings:t,values:n}))(1),il=Symbol.for(`lit-noChange`),$=Symbol.for(`lit-nothing`),al=new WeakMap,ol=Wc.createTreeWalker(Wc,129);function sl(e,t){if(!qc(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Bc===void 0?t:Bc.createHTML(t)}var cl=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Xc;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Xc?c[1]===`!--`?o=Zc:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=$c):(nl.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=$c):o=Qc:o===$c?c[0]===`>`?(o=i??Xc,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?$c:c[3]===`"`?tl:el):o===tl||o===el?o=$c:o===Zc||o===Qc?o=Xc:(o=$c,i=void 0);let d=o===$c&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Xc?n+Uc:l>=0?(r.push(s),n.slice(0,l)+Vc+n.slice(l)+Q+d):n+Q+(l===-2?t:d)}return[sl(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},ll=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=cl(t,n);if(this.el=e.createElement(l,r),ol.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=ol.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Vc)){let t=u[o++],n=i.getAttribute(e).split(Q),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ml:r[1]===`?`?hl:r[1]===`@`?gl:pl}),i.removeAttribute(e)}else e.startsWith(Q)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(nl.test(i.tagName)){let e=i.textContent.split(Q),t=e.length-1;if(t>0){i.textContent=zc?zc.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Gc()),ol.nextNode(),c.push({type:2,index:++a});i.append(e[t],Gc())}}}else if(i.nodeType===8)if(i.data===Hc)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Q,e+1))!==-1;)c.push({type:7,index:a}),e+=Q.length-1}a++}}static createElement(e,t){let n=Wc.createElement(`template`);return n.innerHTML=e,n}};function ul(e,t,n=e,r){if(t===il)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Kc(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=ul(e,i._$AS(e,t.values),i,r)),t}var dl=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Wc).importNode(t,!0);ol.currentNode=r;let i=ol.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new fl(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new _l(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=ol.nextNode(),a++)}return ol.currentNode=Wc,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},fl=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=$,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=ul(this,e,t),Kc(e)?e===$||e==null||e===``?(this._$AH!==$&&this._$AR(),this._$AH=$):e!==this._$AH&&e!==il&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Jc(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==$&&Kc(this._$AH)?this._$AA.nextSibling.data=e:this.T(Wc.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=ll.createElement(sl(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new dl(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=al.get(e.strings);return t===void 0&&al.set(e.strings,t=new ll(e)),t}k(t){qc(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Gc()),this.O(Gc()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Rc(e).nextSibling;Rc(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},pl=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=$,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=$}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=ul(this,e,t,0),a=!Kc(e)||e!==this._$AH&&e!==il,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=ul(this,r[n+o],t,o),s===il&&(s=this._$AH[o]),a||=!Kc(s)||s!==this._$AH[o],s===$?e=$:e!==$&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===$?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ml=class extends pl{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===$?void 0:e}},hl=class extends pl{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==$)}},gl=class extends pl{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=ul(this,e,t,0)??$)===il)return;let n=this._$AH,r=e===$&&n!==$||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==$&&(n===$||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},_l=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){ul(this,e)}},vl=Lc.litHtmlPolyfillSupport;vl?.(ll,fl),(Lc.litHtmlVersions??=[]).push(`3.3.2`);var yl=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new fl(t.insertBefore(Gc(),e),e,void 0,n??{})}return i._$AI(e),i};function bl(e={}){let{tone:t=`accent`,count:n=!1,hidden:r=!1,extra:i=[]}=e;return Kr(`ui-pill-badge`,t&&`ui-pill-badge--${t}`,{"ui-pill-badge--count":n,hidden:r},i)}function xl(){return rl`
|
|
770
|
+
<a href="#editorContainer" class="sr-only skip-link">Skip to editor</a>
|
|
771
|
+
|
|
772
|
+
<div class="app-shell">
|
|
773
|
+
<aside id="sidebar" class="sidebar">
|
|
774
|
+
<div class="sidebar-header">
|
|
775
|
+
<div class="sidebar-brand">
|
|
776
|
+
<svg width="20" height="20" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
777
|
+
<rect x="6" y="8" width="28" height="38" rx="4" stroke="var(--color-primary)" stroke-width="2" fill="var(--color-primary)" fill-opacity="0.12"></rect>
|
|
778
|
+
<rect x="22" y="10" width="28" height="38" rx="4" stroke="var(--color-primary)" stroke-width="2" fill="var(--color-primary)" fill-opacity="0.25"></rect>
|
|
779
|
+
<path d="M14 20l4 10 1.5-4 4-1.5L14 20z" fill="var(--color-primary)" opacity="0.7"></path>
|
|
780
|
+
<path d="M38 28l-4-10-1.5 4-4 1.5L38 28z" fill="var(--color-primary)"></path>
|
|
781
|
+
</svg>
|
|
782
|
+
<span class="sidebar-title">CollabMD</span>
|
|
783
|
+
</div>
|
|
784
|
+
<div class="sidebar-actions">
|
|
785
|
+
<button class=${qr({extra:`sidebar-close-btn`})} id="sidebarClose" aria-label="Close sidebar" title="Close sidebar">
|
|
786
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
787
|
+
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
788
|
+
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
789
|
+
</svg>
|
|
790
|
+
</button>
|
|
791
|
+
<div class="sidebar-create-shell">
|
|
792
|
+
<button
|
|
793
|
+
class=${U({variant:`secondary`,size:`compact`,pill:!0,extra:`sidebar-create-btn`})}
|
|
794
|
+
id="sidebarCreateBtn"
|
|
795
|
+
aria-label="Create"
|
|
796
|
+
aria-expanded="false"
|
|
797
|
+
aria-haspopup="menu"
|
|
798
|
+
title="Create file or folder"
|
|
799
|
+
>
|
|
800
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
801
|
+
<line x1="12" y1="5" x2="12" y2="19"></line>
|
|
802
|
+
<line x1="5" y1="12" x2="19" y2="12"></line>
|
|
803
|
+
</svg>
|
|
804
|
+
<span class="sidebar-create-btn-label">Create</span>
|
|
805
|
+
</button>
|
|
806
|
+
</div>
|
|
807
|
+
<button class=${qr()} id="refreshFilesBtn" aria-label="Refresh" title="Refresh file list">
|
|
808
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
809
|
+
<polyline points="23 4 23 10 17 10"></polyline>
|
|
810
|
+
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
|
|
811
|
+
</svg>
|
|
812
|
+
</button>
|
|
813
|
+
</div>
|
|
814
|
+
</div>
|
|
815
|
+
<div class="ui-nav-tabs hidden" id="sidebarTabs">
|
|
816
|
+
<button class="ui-nav-tab active" id="filesSidebarTab" type="button">
|
|
817
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
818
|
+
<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"></path>
|
|
819
|
+
</svg>
|
|
820
|
+
Files
|
|
821
|
+
</button>
|
|
822
|
+
<button class="ui-nav-tab hidden" id="gitSidebarTab" type="button">
|
|
823
|
+
<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">
|
|
824
|
+
<circle cx="18" cy="18" r="3"></circle>
|
|
825
|
+
<circle cx="6" cy="6" r="3"></circle>
|
|
826
|
+
<path d="M13 6h3a2 2 0 0 1 2 2v7"></path>
|
|
827
|
+
<path d="M6 9v12"></path>
|
|
828
|
+
</svg>
|
|
829
|
+
Git
|
|
830
|
+
</button>
|
|
831
|
+
</div>
|
|
832
|
+
<div class="sidebar-search" id="fileSearch">
|
|
833
|
+
<input
|
|
834
|
+
type="text"
|
|
835
|
+
class=${W({extra:`sidebar-search-input`})}
|
|
836
|
+
id="fileSearchInput"
|
|
837
|
+
placeholder="Search files..."
|
|
838
|
+
autocomplete="off"
|
|
839
|
+
spellcheck="false"
|
|
840
|
+
aria-label="Search files"
|
|
841
|
+
>
|
|
842
|
+
</div>
|
|
843
|
+
<div class="sidebar-search hidden" id="gitSearch">
|
|
844
|
+
<input
|
|
845
|
+
type="text"
|
|
846
|
+
class=${W({extra:`sidebar-search-input`})}
|
|
847
|
+
id="gitSearchInput"
|
|
848
|
+
placeholder="Search changes..."
|
|
849
|
+
autocomplete="off"
|
|
850
|
+
spellcheck="false"
|
|
851
|
+
aria-label="Search changed files"
|
|
852
|
+
>
|
|
853
|
+
</div>
|
|
854
|
+
<nav id="fileTree" class="file-tree" aria-label="File explorer"></nav>
|
|
855
|
+
<div id="gitPanel" class="git-panel hidden" aria-label="Git changes"></div>
|
|
856
|
+
</aside>
|
|
857
|
+
|
|
858
|
+
<main class="main-area" id="mainContent">
|
|
859
|
+
<header class="toolbar" role="banner">
|
|
860
|
+
<div class="toolbar-left">
|
|
861
|
+
<button class=${U({variant:`ghost`,toolbar:!0})} id="sidebarToggle" aria-label="Toggle sidebar" title="Toggle sidebar">
|
|
862
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
863
|
+
<line x1="3" y1="6" x2="21" y2="6"></line>
|
|
864
|
+
<line x1="3" y1="12" x2="21" y2="12"></line>
|
|
865
|
+
<line x1="3" y1="18" x2="21" y2="18"></line>
|
|
866
|
+
</svg>
|
|
867
|
+
</button>
|
|
868
|
+
<div class="toolbar-room-info">
|
|
869
|
+
<span class="toolbar-room-name" id="activeFileName">CollabMD</span>
|
|
870
|
+
<span class=${bl({tone:`accent`,extra:`toolbar-badge`})} id="userCount"></span>
|
|
871
|
+
<span class=${bl({tone:`accent`,hidden:!0,extra:`toolbar-badge`})} id="toolbarDiffBadge">Diff</span>
|
|
872
|
+
<span class=${bl({tone:`accent`,hidden:!0,extra:`toolbar-badge`})} id="gitOperationStatus" aria-live="polite" aria-atomic="true"></span>
|
|
873
|
+
</div>
|
|
874
|
+
</div>
|
|
875
|
+
|
|
876
|
+
<div class="toolbar-center" id="toolbarCenter">
|
|
877
|
+
<div class=${Jr({extra:`view-toggle`})} role="group" aria-label="View mode">
|
|
878
|
+
<button class=${G({active:!0,extra:`view-btn`})} data-view="split" aria-label="Split view" aria-pressed="true" title="Split view">
|
|
879
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
880
|
+
<rect x="3" y="3" width="18" height="18" rx="2"></rect>
|
|
881
|
+
<line x1="12" y1="3" x2="12" y2="21"></line>
|
|
882
|
+
</svg>
|
|
883
|
+
</button>
|
|
884
|
+
<button class=${G({extra:`view-btn`})} data-view="editor" aria-label="Editor only" aria-pressed="false" title="Editor only">
|
|
885
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
886
|
+
<rect x="3" y="3" width="18" height="18" rx="2"></rect>
|
|
887
|
+
<line x1="8" y1="8" x2="16" y2="8"></line>
|
|
888
|
+
<line x1="8" y1="12" x2="14" y2="12"></line>
|
|
889
|
+
<line x1="8" y1="16" x2="12" y2="16"></line>
|
|
890
|
+
</svg>
|
|
891
|
+
</button>
|
|
892
|
+
<button class=${G({extra:`view-btn`})} data-view="preview" aria-label="Preview only" aria-pressed="false" title="Preview only">
|
|
893
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
894
|
+
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
|
|
895
|
+
<circle cx="12" cy="12" r="3"></circle>
|
|
896
|
+
</svg>
|
|
897
|
+
</button>
|
|
898
|
+
</div>
|
|
899
|
+
</div>
|
|
900
|
+
|
|
901
|
+
<div class="toolbar-right">
|
|
902
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`mobile-view-toggle`})} id="mobileViewToggle" aria-label="Toggle editor/preview" title="Toggle view">
|
|
903
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
904
|
+
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
|
|
905
|
+
<circle cx="12" cy="12" r="3"></circle>
|
|
906
|
+
</svg>
|
|
907
|
+
<span class="ui-toolbar-button-label">Preview</span>
|
|
908
|
+
</button>
|
|
909
|
+
|
|
910
|
+
<div class="user-avatars toolbar-presence-cluster" id="userAvatars"></div>
|
|
911
|
+
|
|
912
|
+
<div class="chat-container" id="chatContainer">
|
|
913
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`chat-toggle-btn`})} id="chatToggleBtn" aria-label="Open team chat" aria-expanded="false" title="Team chat">
|
|
914
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
915
|
+
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
916
|
+
</svg>
|
|
917
|
+
<span class="ui-toolbar-button-label">Chat</span>
|
|
918
|
+
<span class=${bl({tone:`solid`,count:!0,hidden:!0,extra:`chat-toggle-badge`})} id="chatToggleBadge">0</span>
|
|
919
|
+
</button>
|
|
920
|
+
<div class="toast-container chat-toast-container" id="chatToastContainer" aria-live="polite" aria-atomic="true"></div>
|
|
921
|
+
|
|
922
|
+
<section class="chat-panel hidden" id="chatPanel" aria-label="Team chat">
|
|
923
|
+
<div class="chat-panel-header">
|
|
924
|
+
<div>
|
|
925
|
+
<h2 class="chat-panel-title">Team chat</h2>
|
|
926
|
+
<p class="chat-panel-status" id="chatStatus">Syncing...</p>
|
|
927
|
+
</div>
|
|
928
|
+
<button
|
|
929
|
+
class=${U({variant:`secondary`,size:`compact`,pill:!0,surface:!0,action:!0,extra:`chat-notification-action`})}
|
|
930
|
+
id="chatNotificationBtn"
|
|
931
|
+
type="button"
|
|
932
|
+
>
|
|
933
|
+
Enable alerts
|
|
934
|
+
</button>
|
|
935
|
+
</div>
|
|
936
|
+
|
|
937
|
+
<div class="chat-empty-state" id="chatEmptyState">
|
|
938
|
+
Temporary room chat for whoever is online right now.
|
|
939
|
+
</div>
|
|
940
|
+
<div class="chat-messages hidden" id="chatMessages" role="log" aria-live="polite" aria-relevant="additions text"></div>
|
|
941
|
+
|
|
942
|
+
<form class="chat-form" id="chatForm">
|
|
943
|
+
<input
|
|
944
|
+
type="text"
|
|
945
|
+
class=${W({extra:`chat-input`})}
|
|
946
|
+
id="chatInput"
|
|
947
|
+
placeholder="Send a quick update..."
|
|
948
|
+
autocomplete="off"
|
|
949
|
+
spellcheck="true"
|
|
950
|
+
maxlength="280"
|
|
951
|
+
aria-label="Team chat message"
|
|
952
|
+
>
|
|
953
|
+
<button type="submit" class=${U({variant:`primary`,extra:`chat-send-btn`})}>Send</button>
|
|
954
|
+
</form>
|
|
955
|
+
</section>
|
|
956
|
+
</div>
|
|
957
|
+
|
|
958
|
+
<button
|
|
959
|
+
class=${U({variant:`ghost`,toolbar:!0,extra:`toolbar-overflow-toggle`})}
|
|
960
|
+
id="toolbarOverflowToggle"
|
|
961
|
+
aria-label="Open more actions"
|
|
962
|
+
aria-expanded="false"
|
|
963
|
+
title="More actions"
|
|
964
|
+
>
|
|
965
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
966
|
+
<circle cx="12" cy="12" r="1"></circle>
|
|
967
|
+
<circle cx="19" cy="12" r="1"></circle>
|
|
968
|
+
<circle cx="5" cy="12" r="1"></circle>
|
|
969
|
+
</svg>
|
|
970
|
+
</button>
|
|
971
|
+
|
|
972
|
+
<div class="toolbar-overflow-menu" id="toolbarOverflowMenu">
|
|
973
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`hidden`})} id="fileHistoryBtn" aria-label="Open file history" title="View file history">
|
|
974
|
+
<svg 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">
|
|
975
|
+
<path d="M3 12a9 9 0 1 0 3-6.7"></path>
|
|
976
|
+
<path d="M3 4v5h5"></path>
|
|
977
|
+
<path d="M12 7v5l3 3"></path>
|
|
978
|
+
</svg>
|
|
979
|
+
<span class="ui-toolbar-button-label" id="fileHistoryBtnLabel">History</span>
|
|
980
|
+
</button>
|
|
981
|
+
|
|
982
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`ui-toolbar-button--name`})} id="editNameBtn" aria-label="Set name. Change display name" title="Change display name">
|
|
983
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
984
|
+
<path d="M12 20h9"></path>
|
|
985
|
+
<path d="M16.5 3.5a2.12 2.12 0 1 1 3 3L7 19l-4 1 1-4Z"></path>
|
|
986
|
+
</svg>
|
|
987
|
+
<span class="ui-toolbar-button-label ui-toolbar-button-text" id="currentUserName">Set name</span>
|
|
988
|
+
</button>
|
|
989
|
+
|
|
990
|
+
<button class=${U({variant:`ghost`,toolbar:!0})} id="shareBtn" aria-label="Share. Copy link" title="Share link">
|
|
991
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
992
|
+
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
|
|
993
|
+
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
|
|
994
|
+
</svg>
|
|
995
|
+
<span class="ui-toolbar-button-label">Share</span>
|
|
996
|
+
</button>
|
|
997
|
+
|
|
998
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`toolbar-search-files-btn`})} id="searchFilesBtn" aria-label="Search files" title="Search files">
|
|
999
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1000
|
+
<circle cx="11" cy="11" r="7"></circle>
|
|
1001
|
+
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
1002
|
+
</svg>
|
|
1003
|
+
<span class="ui-toolbar-button-label">Search files</span>
|
|
1004
|
+
</button>
|
|
1005
|
+
|
|
1006
|
+
<details class="toolbar-overflow-group hidden" id="exportMenuGroup">
|
|
1007
|
+
<summary class=${U({variant:`ghost`,toolbar:!0,extra:`toolbar-overflow-group-toggle`})} aria-label="Export options" title="Export">
|
|
1008
|
+
<svg 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">
|
|
1009
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
|
|
1010
|
+
<polyline points="14 2 14 8 20 8"></polyline>
|
|
1011
|
+
<path d="M12 18v-6"></path>
|
|
1012
|
+
<path d="m9 15 3 3 3-3"></path>
|
|
1013
|
+
</svg>
|
|
1014
|
+
<span class="ui-toolbar-button-label">Export</span>
|
|
1015
|
+
</summary>
|
|
1016
|
+
<div class="toolbar-overflow-submenu">
|
|
1017
|
+
<button class=${U({variant:`ghost`,toolbar:!0})} id="exportDocxBtn" aria-label="Export DOCX" title="Export DOCX">
|
|
1018
|
+
<svg 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">
|
|
1019
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
|
|
1020
|
+
<polyline points="14 2 14 8 20 8"></polyline>
|
|
1021
|
+
<path d="M8 13h2l1.2 2 1.6-4 1.2 2H18"></path>
|
|
1022
|
+
</svg>
|
|
1023
|
+
<span class="ui-toolbar-button-label">Export DOCX</span>
|
|
1024
|
+
</button>
|
|
1025
|
+
<button class=${U({variant:`ghost`,toolbar:!0})} id="exportPdfBtn" aria-label="Print or save PDF" title="Print / Save PDF">
|
|
1026
|
+
<svg 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">
|
|
1027
|
+
<path d="M6 9V2h12v7"></path>
|
|
1028
|
+
<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
|
|
1029
|
+
<rect x="6" y="14" width="12" height="8"></rect>
|
|
1030
|
+
</svg>
|
|
1031
|
+
<span class="ui-toolbar-button-label">Print / Save PDF</span>
|
|
1032
|
+
</button>
|
|
1033
|
+
</div>
|
|
1034
|
+
</details>
|
|
1035
|
+
|
|
1036
|
+
<button class=${U({variant:`ghost`,toolbar:!0,extra:`toolbar-theme-button`})} id="themeToggleBtn" data-theme-toggle aria-label="Toggle theme" title="Toggle theme">
|
|
1037
|
+
<span class="toolbar-theme-icon" data-theme-toggle-icon aria-hidden="true">
|
|
1038
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1039
|
+
<circle cx="12" cy="12" r="5"></circle>
|
|
1040
|
+
<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"></path>
|
|
1041
|
+
</svg>
|
|
1042
|
+
</span>
|
|
1043
|
+
<span class="ui-toolbar-button-label">Theme</span>
|
|
1044
|
+
<span class=${bl({tone:`muted`,extra:`toolbar-theme-state`})} data-theme-toggle-state>Dark</span>
|
|
1045
|
+
</button>
|
|
1046
|
+
</div>
|
|
1047
|
+
</div>
|
|
1048
|
+
</header>
|
|
1049
|
+
|
|
1050
|
+
<div id="emptyState" class="empty-state">
|
|
1051
|
+
<div class="empty-state-content">
|
|
1052
|
+
<div class="empty-state-logo" aria-hidden="true">
|
|
1053
|
+
<svg width="48" height="48" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1054
|
+
<rect x="6" y="8" width="28" height="38" rx="4" stroke="var(--color-primary)" stroke-width="2" fill="var(--color-primary)" fill-opacity="0.12"></rect>
|
|
1055
|
+
<rect x="22" y="10" width="28" height="38" rx="4" stroke="var(--color-primary)" stroke-width="2" fill="var(--color-primary)" fill-opacity="0.25"></rect>
|
|
1056
|
+
<path d="M14 20l4 10 1.5-4 4-1.5L14 20z" fill="var(--color-primary)" opacity="0.7"></path>
|
|
1057
|
+
<path d="M38 28l-4-10-1.5 4-4 1.5L38 28z" fill="var(--color-primary)"></path>
|
|
1058
|
+
</svg>
|
|
1059
|
+
</div>
|
|
1060
|
+
<h2 class="empty-state-title">Welcome to CollabMD</h2>
|
|
1061
|
+
<p class="empty-state-desc">Open a file from the sidebar, or get started quickly:</p>
|
|
1062
|
+
<div class="empty-state-actions">
|
|
1063
|
+
<button class=${U({variant:`secondary`,extra:`empty-state-btn`})} id="emptyStateNewFileBtn">
|
|
1064
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1065
|
+
<line x1="12" y1="5" x2="12" y2="19"></line>
|
|
1066
|
+
<line x1="5" y1="12" x2="19" y2="12"></line>
|
|
1067
|
+
</svg>
|
|
1068
|
+
Create
|
|
1069
|
+
</button>
|
|
1070
|
+
<button class=${U({variant:`secondary`,extra:`empty-state-btn`})} id="emptyStateSearchBtn">
|
|
1071
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1072
|
+
<circle cx="11" cy="11" r="8"></circle>
|
|
1073
|
+
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
1074
|
+
</svg>
|
|
1075
|
+
Search Everything
|
|
1076
|
+
<kbd class="empty-state-kbd">⌘K</kbd>
|
|
1077
|
+
</button>
|
|
1078
|
+
</div>
|
|
1079
|
+
</div>
|
|
1080
|
+
</div>
|
|
1081
|
+
|
|
1082
|
+
<div id="editor-page" class="editor-page hidden">
|
|
1083
|
+
<div class="editor-layout" id="editorLayout" data-view="split">
|
|
1084
|
+
<div class="editor-pane" id="editorPane">
|
|
1085
|
+
<div class="pane-header">
|
|
1086
|
+
<div class="pane-header-meta">
|
|
1087
|
+
<span class="pane-label">Editor</span>
|
|
1088
|
+
<span class="pane-label-meta" id="lineInfo">Ln 1, Col 1</span>
|
|
1089
|
+
</div>
|
|
1090
|
+
<div class="pane-header-actions">
|
|
1091
|
+
<button class=${U({variant:`ghost`,size:`compact`,toggle:!0,extra:`mobile-editor-find-btn`})} id="editorFindBtn" aria-label="Find in file" title="Find in file">
|
|
1092
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1093
|
+
<circle cx="11" cy="11" r="7"></circle>
|
|
1094
|
+
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
1095
|
+
</svg>
|
|
1096
|
+
<span class="ui-action-label">Find</span>
|
|
1097
|
+
</button>
|
|
1098
|
+
<button class=${U({variant:`ghost`,size:`compact`,toggle:!0,extra:`hidden`})} id="commentSelectionBtn" aria-label="Comment current line or selection" title="Comment current line or selection">
|
|
1099
|
+
<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">
|
|
1100
|
+
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
1101
|
+
</svg>
|
|
1102
|
+
<span class="ui-action-label">Comment</span>
|
|
1103
|
+
</button>
|
|
1104
|
+
<button class=${U({variant:`ghost`,size:`compact`,toggle:!0})} id="toggleWrapBtn" aria-label="Disable line wrap" title="Disable line wrap">
|
|
1105
|
+
<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">
|
|
1106
|
+
<path d="M3 6h14a4 4 0 1 1 0 8H9"></path>
|
|
1107
|
+
<path d="m9 10-4 4 4 4"></path>
|
|
1108
|
+
<path d="M3 18h7"></path>
|
|
1109
|
+
</svg>
|
|
1110
|
+
<span id="wrapToggleLabel">Wrap on</span>
|
|
1111
|
+
</button>
|
|
1112
|
+
</div>
|
|
1113
|
+
</div>
|
|
1114
|
+
<div id="markdownToolbar" class="markdown-toolbar hidden" role="toolbar" aria-label="Markdown formatting"></div>
|
|
1115
|
+
<div id="editorContainer" class="editor-container">
|
|
1116
|
+
<div class="editor-loading" id="editorLoading">
|
|
1117
|
+
<div class="skeleton-line skeleton-line--title skeleton-line--break"></div>
|
|
1118
|
+
<div class="skeleton-line skeleton-line--full"></div>
|
|
1119
|
+
<div class="skeleton-line skeleton-line--ninety"></div>
|
|
1120
|
+
<div class="skeleton-line skeleton-line--ninety-five"></div>
|
|
1121
|
+
<div class="skeleton-line skeleton-line--eighty skeleton-line--break"></div>
|
|
1122
|
+
<div class="skeleton-line skeleton-line--full"></div>
|
|
1123
|
+
<div class="skeleton-line skeleton-line--eighty-five"></div>
|
|
1124
|
+
</div>
|
|
1125
|
+
</div>
|
|
1126
|
+
</div>
|
|
1127
|
+
|
|
1128
|
+
<div class="resizer" id="resizer" role="separator" aria-orientation="vertical" tabindex="0" aria-label="Resize editor and preview" aria-controls="editorPane previewPane" aria-valuemin="20" aria-valuemax="80" aria-valuenow="50"></div>
|
|
1129
|
+
|
|
1130
|
+
<div class="preview-pane" id="previewPane">
|
|
1131
|
+
<div class="pane-header">
|
|
1132
|
+
<span class="pane-label">Preview</span>
|
|
1133
|
+
<div class="pane-header-actions">
|
|
1134
|
+
<div id="backlinksHeaderPanel" class="backlinks-panel backlinks-panel-header hidden" data-backlinks-variant="header">
|
|
1135
|
+
<button type="button" class="backlinks-header" aria-expanded="false">
|
|
1136
|
+
<svg class="backlinks-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
1137
|
+
<polyline points="9 18 15 12 9 6"></polyline>
|
|
1138
|
+
</svg>
|
|
1139
|
+
<span class="backlinks-toggle">0 Linked Mentions</span>
|
|
1140
|
+
<span class="backlinks-count"></span>
|
|
1141
|
+
</button>
|
|
1142
|
+
<div class="backlinks-body" aria-hidden="true" inert>
|
|
1143
|
+
<div class="backlinks-list"></div>
|
|
1144
|
+
</div>
|
|
1145
|
+
</div>
|
|
1146
|
+
<button class=${U({variant:`ghost`,size:`compact`,toggle:!0,extra:`hidden`})} id="commentsToggle" aria-label="Toggle comments" title="Toggle comments">
|
|
1147
|
+
<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">
|
|
1148
|
+
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
1149
|
+
</svg>
|
|
1150
|
+
<span class="ui-action-label">Comments</span>
|
|
1151
|
+
</button>
|
|
1152
|
+
<button class=${U({variant:`ghost`,size:`compact`,toggle:!0})} id="outlineToggle" aria-label="Toggle outline" title="Toggle outline">
|
|
1153
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1154
|
+
<line x1="3" y1="6" x2="21" y2="6"></line>
|
|
1155
|
+
<line x1="3" y1="12" x2="15" y2="12"></line>
|
|
1156
|
+
<line x1="3" y1="18" x2="18" y2="18"></line>
|
|
1157
|
+
</svg>
|
|
1158
|
+
</button>
|
|
1159
|
+
</div>
|
|
1160
|
+
</div>
|
|
1161
|
+
<div class="preview-body">
|
|
1162
|
+
<div id="previewContainer" class="preview-container">
|
|
1163
|
+
<div id="previewContent" class="preview-content"></div>
|
|
1164
|
+
<div id="backlinksInlinePanel" class="backlinks-panel backlinks-panel-inline hidden">
|
|
1165
|
+
<button type="button" class="backlinks-header" aria-expanded="false">
|
|
1166
|
+
<svg class="backlinks-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
1167
|
+
<polyline points="9 18 15 12 9 6"></polyline>
|
|
1168
|
+
</svg>
|
|
1169
|
+
<span class="backlinks-toggle">0 Linked Mentions</span>
|
|
1170
|
+
<span class="backlinks-count"></span>
|
|
1171
|
+
</button>
|
|
1172
|
+
<div class="backlinks-body" aria-hidden="true" inert>
|
|
1173
|
+
<div class="backlinks-list"></div>
|
|
1174
|
+
</div>
|
|
1175
|
+
</div>
|
|
1176
|
+
</div>
|
|
1177
|
+
<div id="backlinksPanel" class="backlinks-panel-layer hidden">
|
|
1178
|
+
<div class="backlinks-panel backlinks-panel-dock" data-backlinks-variant="dock">
|
|
1179
|
+
<button type="button" class="backlinks-header" aria-expanded="false">
|
|
1180
|
+
<svg class="backlinks-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
1181
|
+
<polyline points="9 18 15 12 9 6"></polyline>
|
|
1182
|
+
</svg>
|
|
1183
|
+
<span class="backlinks-toggle">0 Linked Mentions</span>
|
|
1184
|
+
<span class="backlinks-count"></span>
|
|
1185
|
+
</button>
|
|
1186
|
+
<div class="backlinks-body" aria-hidden="true" inert>
|
|
1187
|
+
<div class="backlinks-list"></div>
|
|
1188
|
+
</div>
|
|
1189
|
+
</div>
|
|
1190
|
+
</div>
|
|
1191
|
+
<aside id="commentsDrawer" class="comments-drawer hidden" aria-label="Comments">
|
|
1192
|
+
<div class="comments-drawer-header">
|
|
1193
|
+
<span class="comments-drawer-title">Comments</span>
|
|
1194
|
+
</div>
|
|
1195
|
+
<div id="commentsDrawerEmpty" class="comments-drawer-empty">
|
|
1196
|
+
Add a comment from the editor or the preview bubbles.
|
|
1197
|
+
</div>
|
|
1198
|
+
<div id="commentsDrawerList" class="comments-drawer-list"></div>
|
|
1199
|
+
</aside>
|
|
1200
|
+
<aside id="outlinePanel" class="outline-panel hidden" aria-label="Document outline">
|
|
1201
|
+
<div class="outline-header">
|
|
1202
|
+
<span class="outline-title">Outline</span>
|
|
1203
|
+
</div>
|
|
1204
|
+
<nav id="outlineNav" class="outline-nav"></nav>
|
|
1205
|
+
</aside>
|
|
1206
|
+
</div>
|
|
1207
|
+
</div>
|
|
1208
|
+
</div>
|
|
1209
|
+
</div>
|
|
1210
|
+
|
|
1211
|
+
<div id="diff-page" class="diff-page hidden">
|
|
1212
|
+
<div class="diff-toolbar">
|
|
1213
|
+
<div class="diff-toolbar-left">
|
|
1214
|
+
<div class="diff-file-nav">
|
|
1215
|
+
<button class=${qr({action:!0})} id="diffPrevBtn" type="button" disabled aria-label="Previous changed file">
|
|
1216
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1217
|
+
<polyline points="15 18 9 12 15 6"></polyline>
|
|
1218
|
+
</svg>
|
|
1219
|
+
</button>
|
|
1220
|
+
<span class="diff-file-indicator" id="diffFileIndicator">0 / 0 files</span>
|
|
1221
|
+
<button class=${qr({action:!0})} id="diffNextBtn" type="button" disabled aria-label="Next changed file">
|
|
1222
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1223
|
+
<polyline points="9 18 15 12 9 6"></polyline>
|
|
1224
|
+
</svg>
|
|
1225
|
+
</button>
|
|
1226
|
+
</div>
|
|
1227
|
+
<div class="diff-toolbar-actions">
|
|
1228
|
+
<button class=${U({variant:`secondary`,action:!0,surface:!0,wide:!0,hidden:!0,extra:`diff-back-btn`})} id="diffBackToHistoryBtn" type="button">
|
|
1229
|
+
Back to History
|
|
1230
|
+
</button>
|
|
1231
|
+
<div class="diff-toolbar-actions-group diff-toolbar-actions-group-git" id="diffGitActionsGroup" role="group" aria-label="Git file actions">
|
|
1232
|
+
<button class=${U({variant:`secondary`,action:!0,surface:!0,wide:!0})} id="diffPrimaryActionBtn" type="button" disabled>
|
|
1233
|
+
Stage
|
|
1234
|
+
</button>
|
|
1235
|
+
<button class=${U({variant:`primary`,action:!0,wide:!0})} id="diffCommitBtn" type="button" disabled>
|
|
1236
|
+
Commit Staged
|
|
1237
|
+
</button>
|
|
1238
|
+
</div>
|
|
1239
|
+
<span class="diff-toolbar-actions-divider" id="diffToolbarDivider" aria-hidden="true"></span>
|
|
1240
|
+
<div class="diff-toolbar-actions-group" id="diffEditorActionsGroup" role="group" aria-label="Navigation actions">
|
|
1241
|
+
<button class=${U({variant:`secondary`,action:!0,surface:!0,wide:!0,extra:`diff-open-editor-btn`})} id="diffOpenEditorBtn" type="button" disabled>
|
|
1242
|
+
Open in Editor
|
|
1243
|
+
</button>
|
|
1244
|
+
</div>
|
|
1245
|
+
</div>
|
|
1246
|
+
</div>
|
|
1247
|
+
<div class="diff-toolbar-right">
|
|
1248
|
+
<div class="diff-stats" id="diffStats">
|
|
1249
|
+
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+0</span>
|
|
1250
|
+
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-0</span>
|
|
1251
|
+
</div>
|
|
1252
|
+
<div class=${Jr({hidden:!0,extra:`diff-layout-toggle`})} id="diffLayoutToggle" role="group" aria-label="Commit diff layout">
|
|
1253
|
+
<button class=${G({extra:`view-btn diff-layout-btn`})} data-diff-layout="stacked" type="button">Stacked</button>
|
|
1254
|
+
<button class=${G({active:!0,extra:`view-btn diff-layout-btn`})} data-diff-layout="focused" type="button">Focused</button>
|
|
1255
|
+
</div>
|
|
1256
|
+
<div class=${Jr({extra:`diff-mode-toggle`})} role="group" aria-label="Diff view mode">
|
|
1257
|
+
<button class=${G({active:!0,extra:`view-btn diff-mode-btn`})} data-diff-mode="unified" type="button">Unified</button>
|
|
1258
|
+
<button class=${G({extra:`view-btn diff-mode-btn`})} data-diff-mode="split" type="button">Split</button>
|
|
1259
|
+
</div>
|
|
1260
|
+
</div>
|
|
1261
|
+
</div>
|
|
1262
|
+
<div class="diff-scroll" id="diffScroll">
|
|
1263
|
+
<div class="diff-content" id="diffContent"></div>
|
|
1264
|
+
</div>
|
|
1265
|
+
</div>
|
|
1266
|
+
</main>
|
|
1267
|
+
</div>
|
|
1268
|
+
|
|
1269
|
+
<dialog class="app-dialog" id="displayNameDialog">
|
|
1270
|
+
<form class="app-dialog-form" id="displayNameForm" method="dialog">
|
|
1271
|
+
<div class="app-dialog-header">
|
|
1272
|
+
<h2 class="app-dialog-title" id="displayNameTitle">Update display name</h2>
|
|
1273
|
+
<p class="app-dialog-copy" id="displayNameCopy">Your name will be visible to everyone editing this vault.</p>
|
|
1274
|
+
</div>
|
|
1275
|
+
<label class="app-dialog-field" for="displayNameInput">
|
|
1276
|
+
<span class="app-dialog-label">Name</span>
|
|
1277
|
+
<input type="text" class=${W()} id="displayNameInput" name="displayName" maxlength="24" autocomplete="nickname" spellcheck="false" required>
|
|
1278
|
+
</label>
|
|
1279
|
+
<div class="app-dialog-actions">
|
|
1280
|
+
<button type="button" class=${U({variant:`secondary`})} id="displayNameCancel">Cancel</button>
|
|
1281
|
+
<button type="submit" class=${U({variant:`primary`})} id="displayNameSubmit">Save name</button>
|
|
1282
|
+
</div>
|
|
1283
|
+
</form>
|
|
1284
|
+
</dialog>
|
|
1285
|
+
|
|
1286
|
+
<dialog class="app-dialog" id="fileActionDialog">
|
|
1287
|
+
<form class="app-dialog-form" id="fileActionForm" method="dialog">
|
|
1288
|
+
<div class="app-dialog-header">
|
|
1289
|
+
<h2 class="app-dialog-title" id="fileActionTitle">Create file</h2>
|
|
1290
|
+
<p class="app-dialog-copy" id="fileActionCopy">Add a new file to the vault.</p>
|
|
1291
|
+
</div>
|
|
1292
|
+
<label class="app-dialog-field" id="fileActionField" for="fileActionInput">
|
|
1293
|
+
<span class="app-dialog-label" id="fileActionLabel">Path</span>
|
|
1294
|
+
<input type="text" class=${W()} id="fileActionInput" name="fileActionValue" autocomplete="off" spellcheck="false" required>
|
|
1295
|
+
<span class="app-dialog-hint" id="fileActionHint" hidden></span>
|
|
1296
|
+
</label>
|
|
1297
|
+
<p class="app-dialog-note" id="fileActionNote" hidden></p>
|
|
1298
|
+
<div class="app-dialog-actions">
|
|
1299
|
+
<button type="button" class=${U({variant:`secondary`})} id="fileActionCancel">Cancel</button>
|
|
1300
|
+
<button type="submit" class=${U({variant:`primary`})} id="fileActionSubmit">Create</button>
|
|
1301
|
+
</div>
|
|
1302
|
+
</form>
|
|
1303
|
+
</dialog>
|
|
1304
|
+
|
|
1305
|
+
<dialog class="app-dialog" id="gitCommitDialog">
|
|
1306
|
+
<form class="app-dialog-form" id="gitCommitForm" method="dialog">
|
|
1307
|
+
<div class="app-dialog-header">
|
|
1308
|
+
<h2 class="app-dialog-title" id="gitCommitTitle">Commit staged changes</h2>
|
|
1309
|
+
<p class="app-dialog-copy" id="gitCommitCopy">All staged changes will be included.</p>
|
|
1310
|
+
</div>
|
|
1311
|
+
<label class="app-dialog-field" for="gitCommitInput">
|
|
1312
|
+
<span class="app-dialog-label">Commit message</span>
|
|
1313
|
+
<input type="text" class=${W()} id="gitCommitInput" name="gitCommitMessage" autocomplete="off" spellcheck="true" required>
|
|
1314
|
+
</label>
|
|
1315
|
+
<div class="app-dialog-actions">
|
|
1316
|
+
<button type="button" class=${U({variant:`secondary`})} id="gitCommitCancel">Cancel</button>
|
|
1317
|
+
<button type="submit" class=${U({variant:`primary`})} id="gitCommitSubmit">Commit staged changes</button>
|
|
1318
|
+
</div>
|
|
1319
|
+
</form>
|
|
1320
|
+
</dialog>
|
|
1321
|
+
|
|
1322
|
+
<dialog class="app-dialog" id="gitResetDialog">
|
|
1323
|
+
<form class="app-dialog-form" method="dialog">
|
|
1324
|
+
<div class="app-dialog-header">
|
|
1325
|
+
<h2 class="app-dialog-title" id="gitResetTitle">Reset file</h2>
|
|
1326
|
+
<p class="app-dialog-copy" id="gitResetCopy">Restore this file from the current checked-out branch. If that branch does not contain the file, it will be deleted locally.</p>
|
|
1327
|
+
</div>
|
|
1328
|
+
<div class="app-dialog-field">
|
|
1329
|
+
<label class="app-dialog-label" for="gitResetFileName">File</label>
|
|
1330
|
+
<input class=${W({extra:`app-dialog-input`})} id="gitResetFileName" type="text" readonly>
|
|
1331
|
+
</div>
|
|
1332
|
+
<div class="app-dialog-note is-danger">
|
|
1333
|
+
Local file content and staged changes for this path will be discarded.
|
|
1334
|
+
</div>
|
|
1335
|
+
<div class="app-dialog-actions">
|
|
1336
|
+
<button class=${U({variant:`secondary`})} id="gitResetCancel" type="button">Cancel</button>
|
|
1337
|
+
<button class=${U({variant:`danger`})} id="gitResetSubmit" type="button">Reset File</button>
|
|
1338
|
+
</div>
|
|
1339
|
+
</form>
|
|
1340
|
+
</dialog>
|
|
1341
|
+
|
|
1342
|
+
<div class="tab-lock-overlay hidden" id="tabLockOverlay" role="dialog" aria-modal="true" aria-labelledby="tabLockTitle">
|
|
1343
|
+
<div class="tab-lock-card">
|
|
1344
|
+
<span class="tab-lock-kicker">Single active tab</span>
|
|
1345
|
+
<h2 class="tab-lock-title" id="tabLockTitle">This vault is active in another tab</h2>
|
|
1346
|
+
<p class="tab-lock-copy" id="tabLockCopy">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.</p>
|
|
1347
|
+
<div class="tab-lock-actions">
|
|
1348
|
+
<button type="button" class=${U({variant:`primary`,size:`lg`})} id="tabLockTakeoverBtn">Take over here</button>
|
|
1349
|
+
</div>
|
|
1350
|
+
</div>
|
|
1351
|
+
</div>
|
|
1352
|
+
|
|
1353
|
+
<div class="toast-container" id="toastContainer"></div>
|
|
1354
|
+
|
|
1355
|
+
<div class="qs-overlay" id="quickSwitcher">
|
|
1356
|
+
<div class="qs-modal">
|
|
1357
|
+
<div class="qs-input-wrap">
|
|
1358
|
+
<svg class="qs-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1359
|
+
<circle cx="11" cy="11" r="8"></circle>
|
|
1360
|
+
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
1361
|
+
</svg>
|
|
1362
|
+
<input type="text" class="qs-input" id="quickSwitcherInput" placeholder="Search files..." autocomplete="off" spellcheck="false">
|
|
1363
|
+
<kbd class="qs-kbd">esc</kbd>
|
|
1364
|
+
</div>
|
|
1365
|
+
<div class="qs-results" id="quickSwitcherResults"></div>
|
|
1366
|
+
<div class="qs-hint" id="quickSwitcherHint">Type to search files</div>
|
|
1367
|
+
</div>
|
|
1368
|
+
</div>
|
|
1369
|
+
`}function Sl(e=document){let t=e.getElementById(`appRoot`);if(!t)throw Error(`App shell root element #appRoot is missing.`);return yl(xl(),t),t}var Cl=class{updateChatMessages(...e){return F.updateChatMessages.apply(this,e)}toggleChatPanel(...e){return F.toggleChatPanel.apply(this,e)}openChatPanel(...e){return F.openChatPanel.apply(this,e)}closeChatPanel(...e){return F.closeChatPanel.apply(this,e)}handleChatSubmit(...e){return F.handleChatSubmit.apply(this,e)}renderChat(...e){return F.renderChat.apply(this,e)}createChatMessageElement(...e){return F.createChatMessageElement.apply(this,e)}scrollChatToBottom(...e){return F.scrollChatToBottom.apply(this,e)}formatChatTimestamp(...e){return F.formatChatTimestamp.apply(this,e)}getChatMessageFileLabel(...e){return F.getChatMessageFileLabel.apply(this,e)}formatChatToastMessage(...e){return F.formatChatToastMessage.apply(this,e)}syncChatToggleButton(...e){return F.syncChatToggleButton.apply(this,e)}syncChatNotificationButton(...e){return F.syncChatNotificationButton.apply(this,e)}handleChatNotificationToggle(...e){return F.handleChatNotificationToggle.apply(this,e)}maybeNotifyChatMessage(...e){return F.maybeNotifyChatMessage.apply(this,e)}maybeShowBrowserChatNotification(...e){return F.maybeShowBrowserChatNotification.apply(this,e)}getCommentFileKind(...e){return tt.getCommentFileKind.apply(this,e)}syncCommentChrome(...e){return tt.syncCommentChrome.apply(this,e)}handleCommentSelectionChange(...e){return tt.handleCommentSelectionChange.apply(this,e)}handleCommentThreadsChange(...e){return tt.handleCommentThreadsChange.apply(this,e)}handleCommentEditorContentChange(...e){return tt.handleCommentEditorContentChange.apply(this,e)}refreshCommentUiLayout(...e){return tt.refreshCommentUiLayout.apply(this,e)}initializeExportBridge(...e){return gt.initializeExportBridge.apply(this,e)}handleExportRequest(...e){return gt.handleExportRequest.apply(this,e)}formatPullBackupToast(...e){return I.formatPullBackupToast.apply(this,e)}setGitOperationStatus(...e){return I.setGitOperationStatus.apply(this,e)}runGitActionWithStatus(...e){return I.runGitActionWithStatus.apply(this,e)}handleGitDiffSelection(...e){return I.handleGitDiffSelection.apply(this,e)}handleGitCommitSelection(...e){return I.handleGitCommitSelection.apply(this,e)}handleGitHistorySelection(...e){return I.handleGitHistorySelection.apply(this,e)}handleGitFileHistorySelection(...e){return I.handleGitFileHistorySelection.apply(this,e)}handleGitFilePreviewSelection(...e){return I.handleGitFilePreviewSelection.apply(this,e)}handleGitRepoChange(...e){return I.handleGitRepoChange.apply(this,e)}syncFileHistoryButton(...e){return I.syncFileHistoryButton.apply(this,e)}syncMainChrome(...e){return I.syncMainChrome.apply(this,e)}showGitDiff(...e){return I.showGitDiff.apply(this,e)}showGitCommit(...e){return I.showGitCommit.apply(this,e)}showGitHistory(...e){return I.showGitHistory.apply(this,e)}showGitFileHistory(...e){return I.showGitFileHistory.apply(this,e)}showGitFilePreview(...e){return I.showGitFilePreview.apply(this,e)}postGitAction(...e){return I.postGitAction.apply(this,e)}refreshWorkspaceAfterGitAction(...e){return I.refreshWorkspaceAfterGitAction.apply(this,e)}refreshGitAfterAction(...e){return I.refreshGitAfterAction.apply(this,e)}finalizeGitAction(...e){return I.finalizeGitAction.apply(this,e)}handleWorkspaceChangeForCurrentFile(...e){return I.handleWorkspaceChangeForCurrentFile.apply(this,e)}handleIncomingWorkspaceEvent(...e){return I.handleIncomingWorkspaceEvent.apply(this,e)}stageGitFile(...e){return I.stageGitFile.apply(this,e)}unstageGitFile(...e){return I.unstageGitFile.apply(this,e)}pushGitBranch(...e){return I.pushGitBranch.apply(this,e)}pullGitBranch(...e){return I.pullGitBranch.apply(this,e)}openGitResetDialog(...e){return I.openGitResetDialog.apply(this,e)}handleGitResetSubmit(...e){return I.handleGitResetSubmit.apply(this,e)}openGitCommitDialog(...e){return I.openGitCommitDialog.apply(this,e)}handleGitCommitSubmit(...e){return I.handleGitCommitSubmit.apply(this,e)}updateGlobalUsers(...e){return L.updateGlobalUsers.apply(this,e)}updateFileAwareness(...e){return L.updateFileAwareness.apply(this,e)}renderPresence(...e){return L.renderPresence.apply(this,e)}renderAvatars(...e){return L.renderAvatars.apply(this,e)}toggleFollowUser(...e){return L.toggleFollowUser.apply(this,e)}stopFollowingUser(...e){return L.stopFollowingUser.apply(this,e)}syncFollowedUser(...e){return L.syncFollowedUser.apply(this,e)}followUserCursor(...e){return L.followUserCursor.apply(this,e)}followExcalidrawUser(...e){return L.followExcalidrawUser.apply(this,e)}resolveFileClientId(...e){return L.resolveFileClientId.apply(this,e)}bindEvents(...e){return B.bindEvents.apply(this,e)}clearInitialFileBootstrap(...e){return B.clearInitialFileBootstrap.apply(this,e)}closeToolbarOverflowMenu(...e){return B.closeToolbarOverflowMenu.apply(this,e)}getStoredLineWrapping(...e){return B.getStoredLineWrapping.apply(this,e)}handleConnectionChange(...e){return B.handleConnectionChange.apply(this,e)}handleDocumentKeydown(...e){return B.handleDocumentKeydown.apply(this,e)}handleDocumentPointerDown(...e){return B.handleDocumentPointerDown.apply(this,e)}handlePreviewContentClick(...e){return B.handlePreviewContentClick.apply(this,e)}handleThemeChange(...e){return B.handleThemeChange.apply(this,e)}hideEditorLoading(...e){return B.hideEditorLoading.apply(this,e)}initialize(...e){return B.initialize.apply(this,e)}initializeVisualViewportBinding(...e){return B.initializeVisualViewportBinding.apply(this,e)}initializeVersionMonitoring(...e){return B.initializeVersionMonitoring.apply(this,e)}promptForVersionReload(...e){return B.promptForVersionReload.apply(this,e)}scheduleBacklinkRefresh(...e){return B.scheduleBacklinkRefresh.apply(this,e)}setToolbarOverflowOpen(...e){return B.setToolbarOverflowOpen.apply(this,e)}showEditorLoadError(...e){return B.showEditorLoadError.apply(this,e)}showEditorLoading(...e){return B.showEditorLoading.apply(this,e)}syncVisualViewportBounds(...e){return B.syncVisualViewportBounds.apply(this,e)}syncToolbarOverflowVisibility(...e){return B.syncToolbarOverflowVisibility.apply(this,e)}syncWrapToggle(...e){return B.syncWrapToggle.apply(this,e)}toggleToolbarOverflowMenu(...e){return B.toggleToolbarOverflowMenu.apply(this,e)}toggleLineWrapping(...e){return B.toggleLineWrapping.apply(this,e)}applySidebarVisibility(...e){return B.applySidebarVisibility.apply(this,e)}closeSidebarOnMobile(...e){return B.closeSidebarOnMobile.apply(this,e)}isMobileViewport(...e){return B.isMobileViewport.apply(this,e)}restoreSidebarState(...e){return B.restoreSidebarState.apply(this,e)}setSidebarTab(...e){return B.setSidebarTab.apply(this,e)}setSidebarVisibility(...e){return B.setSidebarVisibility.apply(this,e)}toggleSidebar(...e){return B.toggleSidebar.apply(this,e)}getCurrentUser(...e){return B.getCurrentUser.apply(this,e)}getCurrentUserName(...e){return B.getCurrentUserName.apply(this,e)}getStoredUserName(...e){return B.getStoredUserName.apply(this,e)}handleDisplayNameSubmit(...e){return B.handleDisplayNameSubmit.apply(this,e)}isIdentityManagedByAuth(...e){return B.isIdentityManagedByAuth.apply(this,e)}openDisplayNameDialog(...e){return B.openDisplayNameDialog.apply(this,e)}promptForDisplayNameIfNeeded(...e){return B.promptForDisplayNameIfNeeded.apply(this,e)}syncCurrentUserName(...e){return B.syncCurrentUserName.apply(this,e)}syncIdentityManagementUi(...e){return B.syncIdentityManagementUi.apply(this,e)}applyMarkdownToolbarAction(...e){return B.applyMarkdownToolbarAction.apply(this,e)}copyCurrentLink(...e){return B.copyCurrentLink.apply(this,e)}closeMarkdownBlockMenu(...e){return B.closeMarkdownBlockMenu.apply(this,e)}getActiveMarkdownBlockAction(...e){return B.getActiveMarkdownBlockAction.apply(this,e)}getMarkdownBlockMenuPopover(...e){return B.getMarkdownBlockMenuPopover.apply(this,e)}handleEditorImageInsert(...e){return B.handleEditorImageInsert.apply(this,e)}handleMarkdownToolbarClick(...e){return B.handleMarkdownToolbarClick.apply(this,e)}handleMarkdownToolbarDocumentPointerDown(...e){return B.handleMarkdownToolbarDocumentPointerDown.apply(this,e)}handleMarkdownToolbarKeydown(...e){return B.handleMarkdownToolbarKeydown.apply(this,e)}handleToolbarImageInsert(...e){return B.handleToolbarImageInsert.apply(this,e)}isMarkdownBlockMenuOpen(...e){return B.isMarkdownBlockMenuOpen.apply(this,e)}openMarkdownBlockMenu(...e){return B.openMarkdownBlockMenu.apply(this,e)}positionMarkdownBlockMenu(...e){return B.positionMarkdownBlockMenu.apply(this,e)}renderMarkdownBlockMenuPopover(...e){return B.renderMarkdownBlockMenuPopover.apply(this,e)}pickImageFile(...e){return B.pickImageFile.apply(this,e)}renderMarkdownToolbar(...e){return B.renderMarkdownToolbar.apply(this,e)}runEditorCommand(...e){return B.runEditorCommand.apply(this,e)}setActiveMarkdownBlockAction(...e){return B.setActiveMarkdownBlockAction.apply(this,e)}syncMarkdownToolbarBlockUi(...e){return B.syncMarkdownToolbarBlockUi.apply(this,e)}toggleMarkdownBlockMenu(...e){return B.toggleMarkdownBlockMenu.apply(this,e)}handleTabActivated(...e){return B.handleTabActivated.apply(this,e)}handleTabBlocked(...e){return B.handleTabBlocked.apply(this,e)}handleTabTakeover(...e){return B.handleTabTakeover.apply(this,e)}hideTabLockOverlay(...e){return B.hideTabLockOverlay.apply(this,e)}showTabLockOverlay(...e){return B.showTabLockOverlay.apply(this,e)}isExcalidrawFile(...e){return V.isExcalidrawFile.apply(this,e)}isBaseFile(...e){return V.isBaseFile.apply(this,e)}isDrawioFile(...e){return V.isDrawioFile.apply(this,e)}isImageFile(...e){return V.isImageFile.apply(this,e)}isMermaidFile(...e){return V.isMermaidFile.apply(this,e)}isPlantUmlFile(...e){return V.isPlantUmlFile.apply(this,e)}createDiagramPreviewDocument(...e){return V.createDiagramPreviewDocument.apply(this,e)}getPreviewSource(...e){return V.getPreviewSource.apply(this,e)}getStaticPreviewDocument(...e){return V.getStaticPreviewDocument.apply(this,e)}setStaticPreviewDocument(...e){return V.setStaticPreviewDocument.apply(this,e)}clearStaticPreviewDocument(...e){return V.clearStaticPreviewDocument.apply(this,e)}supportsFileHistory(...e){return V.supportsFileHistory.apply(this,e)}getDisplayName(...e){return V.getDisplayName.apply(this,e)}resetPreviewMode(...e){return V.resetPreviewMode.apply(this,e)}syncFileChrome(...e){return V.syncFileChrome.apply(this,e)}handleLayoutViewRequest(...e){return V.handleLayoutViewRequest.apply(this,e)}renderExcalidrawFilePreview(...e){return V.renderExcalidrawFilePreview.apply(this,e)}renderDrawioFilePreview(...e){return V.renderDrawioFilePreview.apply(this,e)}renderImageFilePreview(...e){return V.renderImageFilePreview.apply(this,e)}renderBaseFilePreview(...e){return V.renderBaseFilePreview.apply(this,e)}renderTextFilePreview(...e){return V.renderTextFilePreview.apply(this,e)}createResizeHandler(...e){return V.createResizeHandler.apply(this,e)}initializePreviewLayoutObserver(...e){return V.initializePreviewLayoutObserver.apply(this,e)}schedulePreviewLayoutSync(...e){return V.schedulePreviewLayoutSync.apply(this,e)}handleEditorScrollActivityChange(...e){return V.handleEditorScrollActivityChange.apply(this,e)}handleHashChange(...e){return V.handleHashChange.apply(this,e)}showEmptyState(...e){return V.showEmptyState.apply(this,e)}showDiffState(...e){return V.showDiffState.apply(this,e)}openFile(...e){return V.openFile.apply(this,e)}cleanupSession(...e){return V.cleanupSession.apply(this,e)}handleWikiLinkClick(...e){return V.handleWikiLinkClick.apply(this,e)}normalizeNewWikiFilePath(...e){return V.normalizeNewWikiFilePath.apply(this,e)}createAndOpenFile(...e){return V.createAndOpenFile.apply(this,e)}handleFileSelection(...e){return V.handleFileSelection.apply(this,e)}constructor(){Sl(document),this.elements=et(document),this.runtimeConfig=T(),this.stateStore=new $e,this.navigation=new gr,this.preferences=new vr({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new _r,this.backlinksApiClient=Sr,this.gitApiClient=Tr,this.plantUmlApiClient=Er,this.vaultApiClient=S,this._session=null,this._hasPromptedForDisplayName=!1,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.chatNotificationsEnabled=this.preferences.getChatNotificationsEnabled(),this.chatNotificationPermission=this.notifications.getPermission(),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 xr({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new hr({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Wr({onTreeChange:(e,t={})=>{let n=this.fileExplorerReady;this.fileExplorer.setTree(e,t),this.fileExplorerReady=!0,!n&&this.isTabActive&&this.handleHashChange()},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new Cc(this.elements.toastContainer),this.chatToastController=new Cc(this.elements.chatToastContainer),this.fileExplorer=new Es({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController}),this.gitPanel=new ic({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 oc({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 kc({previewElement:this.elements.previewContent}),this.basesPreview=new ia({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 Ic({previewElement:this.elements.previewContent}),this.previewRenderer=new Ie({getContent:()=>this.getPreviewSource(),getFileList:()=>this.fileExplorer.flatDocumentFiles,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.videoEmbed.syncLayout(),this.basesPreview.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.reconcileEmbeds(this.elements.previewContent,{isLargeDocument:t.isLargeDocument}),this.excalidrawEmbed.syncLayout(),this.scrollSyncController.setLargeDocumentMode(t.isLargeDocument),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onBeforeRenderCommit:()=>{this.videoEmbed.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit()},onPreviewLayoutChange:()=>{this.scrollSyncController.invalidatePreviewBlocks(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onRenderComplete:()=>{this.videoEmbed.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.plantUmlApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent}),this.themeController=new Sc({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new ac({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new yc({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.backlinksPanel=new Gr({headerPanelElement:this.elements.backlinksHeaderPanel,inlinePanelElement:this.elements.backlinksInlinePanel,loadBacklinks:(e,t={})=>this.backlinksApiClient.readBacklinks(e,t),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),panelElement:this.elements.backlinksPanel}),this.excalidrawEmbed=new rs({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 Go({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}),this.commentUi=new Lo({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.session?.createCommentThread({anchor:e,body:t}),onNavigateToLine:e=>{this.scrollSyncController.suspendSync(250),this.session?.scrollToLine(e,.2)},onReplyToThread:(e,t)=>this.session?.replyToCommentThread(e,t),onToggleReaction:(e,t,n)=>this.session?.toggleCommentReaction(e,t,n),onResolveThread:e=>this.session?.deleteCommentThread(e)}),this.workspacePreviewController=new qe({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),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),layoutController:this.layoutController,outlineController:this.outlineController,previewRenderer:this.previewRenderer,schedulePreviewLayoutSync:e=>this.schedulePreviewLayoutSync(e),scrollSyncController:this.scrollSyncController,videoEmbed:this.videoEmbed}),this.wikiLinkFileController=new Ke({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitDiffView=new Ks({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}),this.fileHistoryView=new Ps({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 Pr({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new Qe({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,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(),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),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(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:()=>{this.session=null,this.commentUi.attachSession(null),this.layoutController.reset(),this.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})=>{if(this.handleCommentEditorContentChange(),e){this.renderBaseFilePreview(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()},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.renderDrawioFilePreview(e),onRenderBasePreview:e=>this.renderBaseFilePreview(e),onRenderExcalidrawPreview:e=>this.renderExcalidrawFilePreview(e),onRenderImagePreview:e=>this.renderImageFilePreview(e),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.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.resetPreviewMode(),renderPresence:()=>this.renderPresence(),scrollContainerForSession:e=>e.getScrollContainer(),shouldUseDrawioPreview:()=>!!this.runtimeConfig.drawioBaseUrl,showEditorLoading:()=>this.showEditorLoading(),stateStore:this.stateStore}),this.workspaceRouteController=new ze({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,renderAvatars:()=>this.renderAvatars(),renderPresence:()=>this.renderPresence(),resetPreviewMode:()=>this.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),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}),this.chatNotificationPermission!==`granted`&&(this.chatNotificationsEnabled=!1)}get session(){return this._session}set session(e){this._session=e}get currentFilePath(){return this.stateStore.get(`currentFilePath`)}set currentFilePath(e){this.stateStore.set(`currentFilePath`,e)}get currentDrawioMode(){return this.stateStore.get(`currentDrawioMode`)}set currentDrawioMode(e){this.stateStore.set(`currentDrawioMode`,e??null)}get globalUsers(){return this.stateStore.get(`globalUsers`)}set globalUsers(e){this.stateStore.set(`globalUsers`,e)}get connectionState(){return this.stateStore.get(`connectionState`)}set connectionState(e){this.stateStore.set(`connectionState`,e)}get sessionLoadToken(){return this.stateStore.get(`sessionLoadToken`)}set sessionLoadToken(e){this.stateStore.set(`sessionLoadToken`,e)}get connectionHelpShown(){return this.stateStore.get(`connectionHelpShown`)}set connectionHelpShown(e){this.stateStore.set(`connectionHelpShown`,e)}get chatMessages(){return this.stateStore.get(`chatMessages`)}set chatMessages(e){this.stateStore.set(`chatMessages`,e)}get chatMessageIds(){return this.stateStore.get(`chatMessageIds`)}set chatMessageIds(e){this.stateStore.set(`chatMessageIds`,e)}get chatUnreadCount(){return this.stateStore.get(`chatUnreadCount`)}set chatUnreadCount(e){this.stateStore.set(`chatUnreadCount`,e)}get chatIsOpen(){return this.stateStore.get(`chatIsOpen`)}set chatIsOpen(e){this.stateStore.set(`chatIsOpen`,e)}get chatInitialSyncComplete(){return this.stateStore.get(`chatInitialSyncComplete`)}set chatInitialSyncComplete(e){this.stateStore.set(`chatInitialSyncComplete`,e)}get isTabActive(){return this.stateStore.get(`isTabActive`)}set isTabActive(e){this.stateStore.set(`isTabActive`,e)}get fileExplorerReady(){return this.stateStore.get(`fileExplorerReady`)}set fileExplorerReady(e){this.stateStore.set(`fileExplorerReady`,e)}get gitRepoAvailable(){return this.stateStore.get(`gitRepoAvailable`)}set gitRepoAvailable(e){this.stateStore.set(`gitRepoAvailable`,e)}get activeSidebarTab(){return this.stateStore.get(`activeSidebarTab`)}set activeSidebarTab(e){this.stateStore.set(`activeSidebarTab`,e)}get followedUserClientId(){return this.stateStore.get(`followedUserClientId`)}set followedUserClientId(e){this.stateStore.set(`followedUserClientId`,e)}get followedCursorSignature(){return this.stateStore.get(`followedCursorSignature`)}set followedCursorSignature(e){this.stateStore.set(`followedCursorSignature`,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-CLOuvy37.js`).then(e=>e.EditorSession),__vite__mapDeps([27,1,28,29,30,31,32,33,34,35,36,37,38,39,26]),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-B1erSgJ1.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([40,25,26]),import.meta.url)}async ensureQuickSwitcher(){return Le(this)}async toggleQuickSwitcher(){return Re(this)}};async function wl(){await te(),new Cl().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{wl()},{once:!0}):wl();
|