@forsion/unit 2.13.3 → 2.13.5
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/main.mjs +135 -10
- package/package.json +1 -1
- package/release.json +5 -5
- package/web/assets/ArtificialView-BD1yHz1N.js +1 -0
- package/web/assets/AutomationBuilder-B09c-5Bi.js +1 -0
- package/web/assets/CalendarConfigView-Bd-ZDGPO.js +1 -0
- package/web/assets/CalendarSide-B0RVbOsg.js +1 -0
- package/web/assets/CalendarView-BHio-n_r.js +3 -0
- package/web/assets/CalendarView-t91KpUG7.css +1 -0
- package/web/assets/CapabilityMenu-DyHTEYLr.js +1 -0
- package/web/assets/Chrome-C7F6fdDp.js +1 -0
- package/web/assets/{CodeView-DRVh13k9.js → CodeView-BGOnrGhB.js} +3 -3
- package/web/assets/CtxMenuButtons-BYjrbUKS.js +1 -0
- package/web/assets/DashboardGridView-CR-R_qV8.js +25 -0
- package/web/assets/DashboardGridView-RoVFSkNO.css +1 -0
- package/web/assets/EventCard-QyYorE1_.js +1 -0
- package/web/assets/ExcalidrawCanvas-BgcFPMpU.css +1 -0
- package/web/assets/ExcalidrawCanvas-lwJCN6uB.js +1 -0
- package/web/assets/FloatingToc-DO7SH8Ku.js +1 -0
- package/web/assets/GitCloneDialog-CbW-RJak.js +1 -0
- package/web/assets/GitCloneDialog-DOxZk2K0.css +1 -0
- package/web/assets/HomepageView-Bx8FbWlY.css +1 -0
- package/web/assets/HomepageView-CHJEhf9c.js +4 -0
- package/web/assets/ImageStudioPanels-CgVf0wiq.js +3 -0
- package/web/assets/ImageStudioView-4WcX0_V4.js +1 -0
- package/web/assets/InlineAiPanel-CdIPINsA.js +1 -0
- package/web/assets/InlineAiPanel-DZZijfif.css +1 -0
- package/web/assets/InlineFiles-CAIyTk1n.js +1 -0
- package/web/assets/MarkdownBlock-Cqfk5DhC.css +1 -0
- package/web/assets/MarkdownBlock-DSItkLhu.js +58 -0
- package/web/assets/ModelPill--CU3XTIQ.js +2 -0
- package/web/assets/{ModelPill-CzdNh7Mt.css → ModelPill-BiUsuhy3.css} +1 -1
- package/web/assets/MuseLibraryView-16p1zsxz.css +1 -0
- package/web/assets/MuseLibraryView-PlS7HAlV.js +2 -0
- package/web/assets/MuseView-CvsO62Fo.js +7 -0
- package/web/assets/PageHistoryPanel-CDh7nm78.js +2 -0
- package/web/assets/{PdfAnnotator-CW0wPWRB.js → PdfAnnotator-DafvjP3U.js} +3 -3
- package/web/assets/PenRow-CEy-s6SF.js +1 -0
- package/web/assets/PluginToolCard-BmTRr5JT.css +1 -0
- package/web/assets/PluginToolCard-DCzLhsCA.js +2 -0
- package/web/assets/ProductView-AUqnTwmQ.js +1 -0
- package/web/assets/SettingsPage-B9mmkWaM.js +3 -0
- package/web/assets/StudioGuestSurface-OOhRA8nt.js +1 -0
- package/web/assets/TodoListView-BkgMe44I.js +1 -0
- package/web/assets/Tooltip-DOYi44eY.js +1 -0
- package/web/assets/UnifiedPage-CTmQpf2T.css +1 -0
- package/web/assets/UnifiedPage-s7-tDSwG.js +712 -0
- package/web/assets/ViewSelectionBar-WmSWMFsR.js +2 -0
- package/web/assets/appStore-DDOkzWDA.js +456 -0
- package/web/assets/appStore-iy8_Tmac.css +1 -0
- package/web/assets/arrow-up-right-BptN64d-.js +1 -0
- package/web/assets/{artificial-BzLFkChP.css → artificial-BubVxExB.css} +1 -1
- package/web/assets/astryxBridge-BL56QfEv.js +69 -0
- package/web/assets/astryxBridge-djzCiy4v.css +1 -0
- package/web/assets/automationListSource-B1jz6q0t.js +1 -0
- package/web/assets/boardSurface-CP4HNmcm.js +1 -0
- package/web/assets/calendarNavStore-DCi7VBmM.js +1 -0
- package/web/assets/canvasPrefs-ArsX3NFO.js +1 -0
- package/web/assets/chatBoxSurface-DRsDr-MT.js +1 -0
- package/web/assets/chevron-up-ChXNh14u.js +1 -0
- package/web/assets/{client-BqhpYbYL.js → client-fKy9CWk0.js} +1 -1
- package/web/assets/code-xml-DCCD9eCS.js +1 -0
- package/web/assets/{codeStudioStore-Dq5i8nbE.js → codeStudioStore-BgLfCDK2.js} +8 -8
- package/web/assets/codingNavigation-BrkLENBZ.css +1 -0
- package/web/assets/contextMenuSurface-BF593l2M.js +1 -0
- package/web/assets/copy-plus-ClKrSgM7.js +1 -0
- package/web/assets/create-DYmVT68X.js +14 -0
- package/web/assets/dashboardSurface-C6cbR3oG.js +1 -0
- package/web/assets/dbStore-BIG5Mfh2.js +1 -0
- package/web/assets/deskCapture-q-jRDIcc.js +1 -0
- package/web/assets/{diff2html-OoRdHZ_O.js → diff2html-Di8qIz6O.js} +2 -2
- package/web/assets/{docx-preview-B43XC8Cn.js → docx-preview-B-URZXdP.js} +1 -1
- package/web/assets/draft-CBSW5tHx.js +2 -0
- package/web/assets/drawingStore-CGvTqqYW.js +7 -0
- package/web/assets/file-down-Z913cCyQ.js +1 -0
- package/web/assets/floatingTocSurface-DGwTiqvU.js +1 -0
- package/web/assets/foldActions-DGIPTmE1.js +1 -0
- package/web/assets/folder-1OJQeDI1.js +1 -0
- package/web/assets/folder-minus-D_j1SwHu.js +1 -0
- package/web/assets/folder-plus-DP9sFr26.js +1 -0
- package/web/assets/gestures-ZhFAENNZ.js +1 -0
- package/web/assets/git-branch-BMajF2cu.js +1 -0
- package/web/assets/homeCardStatus-5R7XkxFL.js +1 -0
- package/web/assets/i18n-CAf4PT1o.css +1 -0
- package/web/assets/i18n.generated-DW_l6CkR.js +15 -0
- package/web/assets/imageStudio-CwG21Bat.css +1 -0
- package/web/assets/imageStudio-DC_syDtx.js +4 -0
- package/web/assets/index-B8A3nKeL.js +1 -0
- package/web/assets/{index-DDMXVG0h.js → index-BDZIQnEx.js} +2 -2
- package/web/assets/index-BYKR7EVg.js +1 -0
- package/web/assets/index-BeW45J9J.js +7 -0
- package/web/assets/index-BnJguNqI.js +1 -0
- package/web/assets/index-BniT-A2n.js +1 -0
- package/web/assets/index-C--E96Ul.js +1 -0
- package/web/assets/index-CI2esW1X.js +1 -0
- package/web/assets/index-CIKPZc3Q.js +1 -0
- package/web/assets/index-COzdD7mZ.js +13 -0
- package/web/assets/index-CPfmhZ3Z.js +1 -0
- package/web/assets/index-CVLDDD5Z.js +1 -0
- package/web/assets/index-CWXpOSI2.js +1 -0
- package/web/assets/index-Cg1FWM_p.js +1 -0
- package/web/assets/index-CmsN2Zm2.js +1 -0
- package/web/assets/index-CtCYv9bF.js +1 -0
- package/web/assets/index-CtRdzpNh.js +1 -0
- package/web/assets/index-D-ClOPbg.js +1 -0
- package/web/assets/{index-CobUnTcv.js → index-DfhEDV2T.js} +2 -2
- package/web/assets/index-Dr6YmrrT.js +1 -0
- package/web/assets/index-SpegRFQV.js +1 -0
- package/web/assets/index-bF04pF8q.js +3 -0
- package/web/assets/index-fDB1l4d-.js +3398 -0
- package/web/assets/index-jzlU5luC.js +1 -0
- package/web/assets/{index-D102FOuM.js → index-uhvJ8AiJ.js} +1 -1
- package/web/assets/{invitePage-BW0BH8Ac.js → invitePage-iOT1zBvp.js} +1 -1
- package/web/assets/{ipc-D7yENkjV.js → ipc-SAPDwyQ4.js} +1 -1
- package/web/assets/{jszip.min-UE5d5vPJ.js → jszip.min-B3n1FGCb.js} +1 -1
- package/web/assets/launchpad-C9U9hpWJ.css +1 -0
- package/web/assets/launchpad-CcmSwlJl.js +2 -0
- package/web/assets/layout-grid-oIyIGbc5.js +1 -0
- package/web/assets/linkFollow-uke1Xtit.js +8 -0
- package/web/assets/{listFold-CKxjyY5_.js → listFold-BeNv2v6M.js} +1 -1
- package/web/assets/lock-open-D2nMg0ga.js +1 -0
- package/web/assets/log-out-D70NCXC4.js +1 -0
- package/web/assets/magnet-Cqmm97W8.js +1 -0
- package/web/assets/main-B9aT0WXG.js +15 -0
- package/web/assets/main-BlVApHpj.css +1 -0
- package/web/assets/markdownEditorSurface-BiDH0__r.css +1 -0
- package/web/assets/markdownEditorSurface-zUzFity2.js +3 -0
- package/web/assets/mediaPlayer-DB4KUvua.js +1 -0
- package/web/assets/message-square-plus-BvUfAAZm.js +1 -0
- package/web/assets/{messages-4w1Khzm1.js → messages-GQUjmbwW.js} +1 -1
- package/web/assets/minimize-2-CMhzL6ZW.js +1 -0
- package/web/assets/mobileEntry-6u7TYC4s.css +1 -0
- package/web/assets/mobileEntry-BnHzrdoC.js +13 -0
- package/web/assets/modelPickerSurface-Dtz40Ae2.js +1 -0
- package/web/assets/nativeDownload-DsGyUSJ5.js +1 -0
- package/web/assets/nativeSheetMenu--iihXNVd.js +1 -0
- package/web/assets/pageStore-CyvNZEYX.js +13 -0
- package/web/assets/pageStore-ys8L4rjF.css +1 -0
- package/web/assets/{pageTree-CIXFRCLk.js → pageTree-Ci2qzrs1.js} +4 -4
- package/web/assets/pen-line-DC3lbEY1.js +1 -0
- package/web/assets/pen-tool-DD5_N4lZ.js +1 -0
- package/web/assets/pencil--sWwxHdP.js +1 -0
- package/web/assets/phoneList-BpLxxdq6.css +1 -0
- package/web/assets/phoneList-DKRMxQHf.js +1 -0
- package/web/assets/pluginChat-82zZt47Y.js +2 -0
- package/web/assets/react-b7FrqRQR.js +1 -0
- package/web/assets/recordSurface-vUX25Z8R.js +1 -0
- package/web/assets/redo-2-CqlqhWrI.js +1 -0
- package/web/assets/rotate-ccw-D8kni6Ni.js +1 -0
- package/web/assets/selectionActions-DIq0xDm8.js +2 -0
- package/web/assets/selectionBarSurface-B94e5JW_.js +1 -0
- package/web/assets/sessionTitle-Ctp4iNKu.js +1 -0
- package/web/assets/settingsPageSurface-C9TA3mJg.js +1 -0
- package/web/assets/sharePage-CY04XCAf.js +2 -0
- package/web/assets/{shareViewer-BzuSyJv_.js → shareViewer-DweNF8Ch.js} +2 -2
- package/web/assets/star-B0sZEmbj.js +1 -0
- package/web/assets/tableSurface-CSBYBw5P.js +1 -0
- package/web/assets/tanguProbe-B8Qv2vcm.js +6 -0
- package/web/assets/{terminalView-SAxITnRW.js → terminalView-BLGdmdl7.js} +3 -3
- package/web/assets/theme-CUWFlazV.css +1 -0
- package/web/assets/type-Dt7RNB9g.js +1 -0
- package/web/assets/undo-2-QimgpLBn.js +1 -0
- package/web/assets/{unitAccount-BPYRAa3m.js → unitAccount-DL3jfd84.js} +1 -1
- package/web/assets/{unitBridge-BNVzai6X.js → unitBridge-BSsCy1zP.js} +1 -1
- package/web/assets/{unitCloudTransport-iFweA1xk.js → unitCloudTransport-CI_6H0TU.js} +1 -1
- package/web/assets/unitOwnerAccess-CiQ7nD7E.js +1 -0
- package/web/assets/unitShim-Dl2ksNp-.js +5 -0
- package/web/assets/upload-Dy7svciS.js +1 -0
- package/web/assets/userSpaces-oMHIWgYe.js +1 -0
- package/web/assets/viewportLock-B0l1GU_k.css +1 -0
- package/web/assets/viewportLock-BZq5PTeN.js +738 -0
- package/web/assets/zoom-in-DDEtY_Go.js +1 -0
- package/web/excalidraw/excalidraw.js +4 -2
- package/web/index.html +12 -13
- package/web/assets/ArtificialView-DS97zlMg.js +0 -1
- package/web/assets/AutomationBuilder-BsJc8wuC.js +0 -1
- package/web/assets/CalendarConfigView-BN8mraSo.js +0 -1
- package/web/assets/CalendarView-D55PA1vn.js +0 -1
- package/web/assets/CapabilityMenu-BVrokPpT.js +0 -1
- package/web/assets/CheckboxInput-BuJ3HPm_.js +0 -1
- package/web/assets/Chrome-amTcZNE4.js +0 -1
- package/web/assets/DashboardGridView-D9s9pez_.css +0 -1
- package/web/assets/DashboardGridView-DlFyYfUh.js +0 -17
- package/web/assets/EventCard-DUrn2krw.js +0 -1
- package/web/assets/ExcalidrawCanvas-4uYrLYin.css +0 -1
- package/web/assets/ExcalidrawCanvas-TpbzBF-J.js +0 -1
- package/web/assets/FloatingToc-B1d4-5EL.js +0 -1
- package/web/assets/HomepageView-DnQ_5Obe.css +0 -1
- package/web/assets/HomepageView-nzKfbHM-.js +0 -1
- package/web/assets/ImageStudioPanels-B2PTq6Yb.js +0 -3
- package/web/assets/ImageStudioView-Cawr6pGW.js +0 -1
- package/web/assets/InlineFiles-DKPH5JHz.js +0 -1
- package/web/assets/MarkdownBlock--__nPQGh.css +0 -1
- package/web/assets/MarkdownBlock-BHpDy2qQ.js +0 -58
- package/web/assets/ModelPill-ChzAM3z1.js +0 -2
- package/web/assets/MuseLibraryView-DLuQ_jyV.js +0 -2
- package/web/assets/MuseView-CDDwV6SR.js +0 -6
- package/web/assets/PageHistoryPanel-BbdXpjJM.js +0 -2
- package/web/assets/PenRow-BY-MZLDQ.js +0 -1
- package/web/assets/ProductView-0ieVL3rY.js +0 -1
- package/web/assets/RightPanel-BRexwQ3W.js +0 -4
- package/web/assets/RunLocationPicker-BrDfOu8-.css +0 -1
- package/web/assets/RunLocationPicker-CadYiE7C.js +0 -43
- package/web/assets/SketchCard-BcXCdBAs.js +0 -641
- package/web/assets/StudioGuestSurface-ZJFKnNYF.js +0 -1
- package/web/assets/TodoListView-DuRdVFgB.js +0 -1
- package/web/assets/Tooltip-DtDUL18W.js +0 -1
- package/web/assets/UnifiedPage-CWXc_mo1.css +0 -1
- package/web/assets/UnifiedPage-D7JTfABH.js +0 -68
- package/web/assets/appStore-ClD7vq5L.css +0 -1
- package/web/assets/appStore-affnJoin.js +0 -3292
- package/web/assets/approvalText-Cy2UAUAQ.js +0 -2
- package/web/assets/arrow-up-right-R4P9Mmxz.js +0 -1
- package/web/assets/astryxBridge-CF_hpqC2.css +0 -1
- package/web/assets/astryxBridge-CT2wZJXs.js +0 -70
- package/web/assets/automationListSource-JVBMsMbC.js +0 -1
- package/web/assets/boardSurface-Ce0_vf9f.js +0 -1
- package/web/assets/book-open-CcXCToyx.js +0 -1
- package/web/assets/calendarNavStore-tQJRVpum.js +0 -1
- package/web/assets/canvasPrefs-CSuX9aLF.js +0 -1
- package/web/assets/chatBoxSurface-IG6Vu4Dz.js +0 -1
- package/web/assets/circle-question-mark-O8AhUz35.js +0 -1
- package/web/assets/circle-x-AV2ZWulM.js +0 -1
- package/web/assets/code-xml-DdR58F83.js +0 -1
- package/web/assets/codingNavigation-CxdCK78-.js +0 -53
- package/web/assets/codingNavigation-_tOR0ell.css +0 -1
- package/web/assets/create-BgJN5qsj.js +0 -14
- package/web/assets/dashboardSurface-BY-AFB-r.js +0 -1
- package/web/assets/deskCapture-BD2qD6NI.js +0 -1
- package/web/assets/emoji-BPdA62d7.js +0 -1
- package/web/assets/floatingTocSurface-BM2SYE_u.js +0 -1
- package/web/assets/foldActions-BcyvNVBs.js +0 -1
- package/web/assets/folder-CCZqnwRc.js +0 -1
- package/web/assets/folder-plus-BJKT1Pqg.js +0 -1
- package/web/assets/gestures-BwPbZDkU.js +0 -1
- package/web/assets/hack2gate-dark-Dx2RtDRI.jpg +0 -0
- package/web/assets/hack2gate-light-DRKq9tyS.jpg +0 -0
- package/web/assets/hand-DRu7IJdU.js +0 -1
- package/web/assets/hard-drive-CXNJUCXw.js +0 -1
- package/web/assets/i18n-BMo19xaR.css +0 -1
- package/web/assets/i18n.generated-DvY59Zq3.js +0 -15
- package/web/assets/imageStudio-Axwmd4GW.js +0 -2
- package/web/assets/imageStudio-DZ0qGU2s.css +0 -1
- package/web/assets/index-B1rE_NwA.js +0 -1
- package/web/assets/index-BFTY79aq.js +0 -1
- package/web/assets/index-BGEkZBs2.js +0 -1
- package/web/assets/index-BO2XJc36.js +0 -13
- package/web/assets/index-BYUntVIZ.js +0 -297
- package/web/assets/index-C65u4fXd.js +0 -1
- package/web/assets/index-C_Ohi-I3.js +0 -1
- package/web/assets/index-CkMhazev.js +0 -1
- package/web/assets/index-D3CYvMpl.js +0 -1
- package/web/assets/index-D78izbLA.js +0 -1
- package/web/assets/index-DY0M_dpd.js +0 -1
- package/web/assets/index-DcbZwhpE.js +0 -1
- package/web/assets/index-Dlkq7gkE.js +0 -1
- package/web/assets/index-HqmJW2np.js +0 -1
- package/web/assets/index-LxlyPm0_.js +0 -1
- package/web/assets/index-Uq4J2aoW.js +0 -1
- package/web/assets/index-WbVt2P8R.js +0 -3
- package/web/assets/index-XyjIhkPw.js +0 -1
- package/web/assets/index-Y2kzYlZq.js +0 -1
- package/web/assets/index-mB0EQkyZ.js +0 -1
- package/web/assets/index-pJh7JN7_.js +0 -1
- package/web/assets/index-taRxNsbp.js +0 -7
- package/web/assets/launchpad-C2c1MSVX.css +0 -1
- package/web/assets/layout-grid-Hs3eDA07.js +0 -1
- package/web/assets/linkFollow-Msu1XH9v.js +0 -8
- package/web/assets/list-tree-DmuRb-p9.js +0 -1
- package/web/assets/lock-kffGfeHt.js +0 -1
- package/web/assets/log-out-B5gEP0tF.js +0 -1
- package/web/assets/main-BiS_5wrB.css +0 -1
- package/web/assets/main-DIyFlyfK.js +0 -20
- package/web/assets/markdownEditorSurface-Bql20IAf.css +0 -1
- package/web/assets/markdownEditorSurface-Cx2rqFAY.js +0 -3
- package/web/assets/message-square-plus-DxBPIhPS.js +0 -1
- package/web/assets/minus-CfoZ4oxr.js +0 -1
- package/web/assets/mobileEntry-B8JwR53-.js +0 -13
- package/web/assets/mobileEntry-DS1vohuL.css +0 -1
- package/web/assets/nativeDownload-Udrv_tmU.js +0 -1
- package/web/assets/pageChrome-D-9npbUE.js +0 -1
- package/web/assets/pageChrome-eO9pb2fH.css +0 -1
- package/web/assets/pen-tool-D_Y9We9x.js +0 -1
- package/web/assets/pencil-DGiTRzW1.js +0 -1
- package/web/assets/phoneList-BQfCJwKF.css +0 -1
- package/web/assets/phoneList-DHUia6HT.js +0 -9
- package/web/assets/pluginChat-BXuJiMYi.js +0 -2
- package/web/assets/redo-2-QgiKEg9T.js +0 -1
- package/web/assets/rotate-ccw-BLoH5er1.js +0 -1
- package/web/assets/sharePage-DYYN5usb.js +0 -2
- package/web/assets/star-BmywYD3u.js +0 -1
- package/web/assets/tableSurface-21LDYY_G.js +0 -1
- package/web/assets/terminal-BlmA_Z1C.js +0 -1
- package/web/assets/theme-Dgqst5S9.css +0 -1
- package/web/assets/type-DmIL6FB-.js +0 -1
- package/web/assets/undo-2-yMeXc8Wi.js +0 -1
- package/web/assets/unitOwnerAccess-Bggl7bDP.js +0 -1
- package/web/assets/unitShim-BP2nBO_k.js +0 -5
- package/web/assets/upload-D20PZHXc.js +0 -1
- package/web/assets/userSpaces-CrLrKklx.js +0 -1
- package/web/assets/viewportLock-DO1lzA2N.css +0 -1
- package/web/assets/viewportLock-tlT6H_Hc.js +0 -629
- package/web/assets/workflow-Bd6xBHiT.js +0 -1
- package/web/assets/zoom-in-_TgFOpyv.js +0 -1
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-CW0wPWRB.js","./index-BYUntVIZ.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./appStore-affnJoin.js","./nativeDownload-Udrv_tmU.js","./ipc-D7yENkjV.js","./client-BqhpYbYL.js","./appStore-ClD7vq5L.css","./PdfAnnotator-C_kglLCA.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as gn,j as f,u as Zt,d as v,P as Cr,t as ke,bB as Du,bC as Lu,bD as Iu,bE as qs,b2 as Pu,a_ as bl,bF as Fu,b5 as Ou,bG as Zs,bH as _u,bI as Oc,bJ as Bu,bK as Ku,l as vl,bL as qu,bM as Or,bN as Hu,aG as Vu,aT as Wu,bO as Yu,bP as wl,n as Xu,bQ as Uu,m as hs,bR as Gu,bS as kl,aO as Cl,aS as Ju,bv as ia,J as Zu,ag as _c,V as Qu,_ as ed,bT as td,M as nd,bU as od,bV as rd,ab as sd,q as Sl,as as Bc,B as El,bW as Kc,bX as Hs,bY as qc,bZ as ad,b_ as Hc,ad as cd,b$ as hr,c0 as Vc,c1 as id,aw as ld,c2 as ud,ax as dd,c3 as fd,c4 as md}from"./index-BYUntVIZ.js";import{F as pd,c as Qs,d as hd,h as Ml,p as ks,e as ps,t as gd,f as yd,g as xd,i as bd,j as sc,l as zl,k as vd,m as Fa,n as wd,o as kd,q as Cd,r as Sd,v as la,w as ua,x as Ed,y as Vs,z as Oa,A as Md,B as Ws,C as zd,D as _a,E as Nl,G as Wc,H as Nd,I as $d,T as Ad,J as Td,K as jd,L as Rd,M as Dd,u as $l,N as Ld,O as Id,Q as Pd,R as Fd,S as Yc,U as Od,V as $s,W as _d,X as Bd,Y as Kd,Z as Al,_ as as,$ as qd,a0 as Hd,a1 as Vd,a2 as Wd,a3 as Yd,a4 as Xd,a5 as Ud,a6 as Gd,a7 as da,a8 as Jd,a9 as Zd,aa as Qd}from"./MarkdownBlock-BHpDy2qQ.js";import{G as Qt,ne as ef,at as tf,c6 as Tl,dm as bn,nf,cr as Kr,ng as Ht,ah as Ln,nh as Xc,ni as _o,nj as Ie,nk as Nr,nl as of,nm as rf,nn as sf,bq as jl,b as kn,fB as ac,no as Uc,j7 as af,ar as cf,aF as cc,np as lf,aK as ea,nq as uf,nr as df,ns as ff,nt as Tn,nu as Me,nv as zo,N as ic,I as mf,aN as Gc,lH as Sr,nw as Rl,cW as Ba,nx as Jc,ny as pf,gl as hf,nz as cr,nA as co,nB as gf,nC as yf,nD as xf,nE as bf,nF as Zc,nG as vf,fz as wf,fy as kf,nH as Cf,fj as Dl,nI as Qc,gm as Sf,nJ as Ef,lB as Mf,nK as Ll,nL as zf,nM as Nf,nN as $f,nO as Ka,nP as Af,nQ as ei,nR as Tf,nS as Ur,fV as qa,nT as ti,nU as As,d$ as jf,cP as Rf,kT as Df,kS as Lf,nV as sr,ai as Mr,P as If,nW as ni,nX as oi,g6 as ri,m7 as Pf,nY as Ff,nZ as Of,n_ as _f,n$ as Bf,o0 as si,mW as Kf,o1 as qf,o2 as ai,o3 as Hf,m6 as Vf,o4 as Wf,o5 as Yf,o6 as Xf,bK as Ha,eN as Uf,fA as Gf,o7 as Jf,fc as Zf,o8 as Qf,o9 as em,oa as tm,ob as nm,oc as om,od as rm,oe as sm,of as ci,og as am,oh as cm,oi as fa,oj as ii,ok as ma,dH as im,cL as lm,cq as um,iU as li,bV as dm,dF as fm,ol as ui,om as mm,on as pm,oo as di,op as hm,Z as gm,b6 as ym,oq as xm,or as bm,os as vm,ot as Lr,ou as xn,ov as wm,ow as km,ox as Va,fn as pa,oy as fi,m$ as Cm,i5 as Sm,oz as Em,oA as Mm}from"./appStore-affnJoin.js";import{c as zm}from"./client-BqhpYbYL.js";import{$ as Et,a as Il,b as lc}from"./index-Y2kzYlZq.js";import{N as Nm,S as $m,r as Am,a as Tm,C as jm,U as Rm,I as Dm}from"./pageChrome-D-9npbUE.js";import{h as Yr,l as Lm,f as Xr,a as mi,i as uc,b as _s,c as Im,d as gr,t as Ts,e as js,g as ha,s as Pm,j as Fm,k as Om}from"./listFold-CKxjyY5_.js";import{a as _m,b as Bm,c as pi,v as hi,i as Km}from"./linkFollow-Msu1XH9v.js";import{S as qm,b as Hm,a as Vm,F as Wm}from"./SketchCard-BcXCdBAs.js";import{A as gi}from"./arrow-up-right-R4P9Mmxz.js";import{c as Pl}from"./nativeDownload-Udrv_tmU.js";import{r as Gr,a as Ym,C as Xm}from"./Chrome-amTcZNE4.js";import{e as Um,h as Gm,a as yi,o as Jm,d as Zm,i as Qm,g as ep,j as tp,k as np,f as op,c as rp}from"./canvasPrefs-CSuX9aLF.js";import{H as sp}from"./hand-DRu7IJdU.js";import{T as ap,F as cp}from"./type-DmIL6FB-.js";import{M as ip}from"./minus-CfoZ4oxr.js";import{createFoldMemory as lp,remapFoldMemory as up}from"./foldActions-BcyvNVBs.js";import{L as dp}from"./lock-kffGfeHt.js";import{U as fp}from"./undo-2-yMeXc8Wi.js";import{C as mp}from"./code-xml-DdR58F83.js";import{M as pp}from"./message-square-plus-DxBPIhPS.js";const hp=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]],gp=Qt("align-center-vertical",hp);const yp=[["rect",{width:"13",height:"7",x:"3",y:"3",rx:"1",key:"11xb64"}],["path",{d:"m22 15-3-3 3-3",key:"26chmm"}],["rect",{width:"13",height:"7",x:"3",y:"14",rx:"1",key:"k6ky7n"}]],xp=Qt("between-horizontal-end",yp);const bp=[["rect",{width:"13",height:"7",x:"8",y:"3",rx:"1",key:"pkso9a"}],["path",{d:"m2 9 3 3-3 3",key:"1agib5"}],["rect",{width:"13",height:"7",x:"8",y:"14",rx:"1",key:"1q5fc1"}]],vp=Qt("between-horizontal-start",bp);const wp=[["rect",{width:"7",height:"13",x:"3",y:"3",rx:"1",key:"1fdu0f"}],["path",{d:"m9 22 3-3 3 3",key:"17z65a"}],["rect",{width:"7",height:"13",x:"14",y:"3",rx:"1",key:"1squn4"}]],kp=Qt("between-vertical-end",wp);const Cp=[["rect",{width:"7",height:"13",x:"3",y:"8",rx:"1",key:"1fjrkv"}],["path",{d:"m15 2-3 3-3-3",key:"1uh6eb"}],["rect",{width:"7",height:"13",x:"14",y:"8",rx:"1",key:"w3fjg8"}]],Sp=Qt("between-vertical-start",Cp);const Ep=[["path",{d:"m2 16 4.039-9.69a.5.5 0 0 1 .923 0L11 16",key:"d5nyq2"}],["path",{d:"M22 9v7",key:"pvm9v3"}],["path",{d:"M3.304 13h6.392",key:"1q3zxz"}],["circle",{cx:"18.5",cy:"12.5",r:"3.5",key:"z97x68"}]],Mp=Qt("case-sensitive",Ep);const zp=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],Np=Qt("chevrons-down",zp);const $p=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]],Ap=Qt("heading-1",$p);const Tp=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]],jp=Qt("heading-2",Tp);const Rp=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]],Dp=Qt("heading-3",Rp);const Lp=[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]],Ip=Qt("list-collapse",Lp);const Pp=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],Fp=Qt("list-ordered",Pp);const Op=[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]],_p=Qt("move-horizontal",Op);const Bp=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Kp=Qt("move-right",Bp);const qp=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Hp=Qt("move-left",qp);const Vp=[["path",{d:"M13 4v16",key:"8vvj80"}],["path",{d:"M17 4v16",key:"7dpous"}],["path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13",key:"sh4n9v"}]],xi=Qt("pilcrow",Vp);const Wp=[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]],Yp=Qt("regex",Wp);const Xp=[["path",{d:"M14 14a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1",key:"zg1ipl"}],["path",{d:"M14 4a1 1 0 0 1 1-1",key:"dhj8ez"}],["path",{d:"M15 10a1 1 0 0 1-1-1",key:"1mnyi5"}],["path",{d:"M19 14a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1",key:"txt6k4"}],["path",{d:"M21 4a1 1 0 0 0-1-1",key:"sfs9ap"}],["path",{d:"M21 9a1 1 0 0 1-1 1",key:"mp6qeo"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a2 2 0 0 1 2-2h2",key:"15xut4"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}]],Up=Qt("replace-all",Xp);const Gp=[["path",{d:"M14 4a1 1 0 0 1 1-1",key:"dhj8ez"}],["path",{d:"M15 10a1 1 0 0 1-1-1",key:"1mnyi5"}],["path",{d:"M21 4a1 1 0 0 0-1-1",key:"sfs9ap"}],["path",{d:"M21 9a1 1 0 0 1-1 1",key:"mp6qeo"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a2 2 0 0 1 2-2h2",key:"15xut4"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}]],Jp=Qt("replace",Gp);const Zp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Qp=Qt("rows-2",Zp);const eh=[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]],th=Qt("spline",eh);const nh=[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}]],Wa=Qt("sticky-note",nh);const oh=[["path",{d:"M17 5H3",key:"1cn7zz"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 19H8",key:"13qgcb"}],["path",{d:"M3 12v7",key:"1ri8j3"}]],rh=Qt("text-quote",oh);function sh(e,t){const n=e.trim().toLowerCase(),o=t.toLowerCase();if(!n)return 1;let r=0,s=0,i=-2,a=-1;for(let c=0;c<o.length&&s<n.length;c++)if(o[c]===n[s]){a<0&&(a=c);let d=1;c===i+1&&(d+=4),(c===0||/[\s/\-_.]/.test(o[c-1]))&&(d+=3),r+=d,i=c,s++}return s<n.length?null:(r-=a*.1,r-=o.length*.02,o===n&&(r+=10),r)}function ah(e,t,n){if(!e.trim())return t;const o=[];for(const r of t){const s=sh(e,n(r));s!=null&&o.push({item:r,score:s})}return o.sort((r,s)=>s.score-r.score),o.map(r=>r.item)}gn({"delassets.blockTitle":{zh:"引用块已删除",en:"Reference block deleted"},"delassets.noteTitle":{zh:"删除「{name}」",en:'Delete "{name}"'},"delassets.blockMsg":{zh:"这 {n} 个文件只被这条笔记引用,要一并从磁盘删除吗?",en:"These {n} files are only referenced by this note. Delete them from disk too?"},"delassets.noteMsg":{zh:"有 {n} 个附件只被这条笔记引用,要一并删除吗?",en:"{n} attachments are only referenced by this note. Delete them too?"},"delassets.more":{zh:"…还有 {n} 个",en:"…and {n} more"},"delassets.remember":{zh:"下次不再问(设置→笔记可改回)",en:"Don't ask again (change it back in Settings → Notes)"},"delassets.keepFiles":{zh:"保留文件",en:"Keep files"},"delassets.cancel":{zh:"取消",en:"Cancel"},"delassets.noteOnly":{zh:"只删笔记",en:"Delete note only"},"delassets.deleteAll":{zh:"一并删除",en:"Delete them too"}});const Ya="amadeus_delete_assets";function Gb(){try{const e=localStorage.getItem(Ya);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function ch(e){try{e===null?localStorage.removeItem(Ya):localStorage.setItem(Ya,e?"yes":"no")}catch{}}const gs=Pl(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function ih(e,t,n){return new Promise(o=>{gs.getState().req?.resolve(null),gs.getState().open({note:e,assets:t,block:n?.block,resolve:o})})}function Jb(){const e=gs(t=>t.req);return e?f.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:f.jsx(lh,{req:e},e.note)}):null}function lh({req:e}){const{t}=Zt(),[n,o]=v.useState(!1),r=i=>{gs.getState().req===e&&(n&&i!==null&&ch(i==="with"),gs.getState().clear(),e.resolve(i))};ef(()=>r(null));const s=e.assets.slice(0,6);return f.jsx("div",{className:"dialog-overlay",onMouseDown:()=>r(null),children:f.jsxs("div",{className:"dialog",onMouseDown:i=>i.stopPropagation(),children:[f.jsx("div",{className:"dialog-title",children:e.block?t("delassets.blockTitle"):t("delassets.noteTitle",{name:e.note})}),f.jsxs("div",{className:"dialog-msg",children:[e.block?t("delassets.blockMsg",{n:e.assets.length}):t("delassets.noteMsg",{n:e.assets.length}),f.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18,opacity:.8},children:[s.map(i=>f.jsx("li",{children:i},i)),e.assets.length>s.length&&f.jsx("li",{children:t("delassets.more",{n:e.assets.length-s.length})})]})]}),!e.block&&f.jsxs("label",{className:"inline-check",style:{display:"flex",gap:6,alignItems:"center",marginTop:10},children:[f.jsx("input",{type:"checkbox",checked:n,onChange:i=>o(i.target.checked)}),t("delassets.remember")]}),f.jsxs("div",{className:"dialog-actions",children:[e.block?f.jsx("button",{className:"dialog-btn",autoFocus:!0,onClick:()=>r("only"),children:t("delassets.keepFiles")}):f.jsxs(f.Fragment,{children:[f.jsx("button",{className:"dialog-btn",onClick:()=>r(null),children:t("delassets.cancel")}),f.jsx("button",{className:"dialog-btn",onClick:()=>r("only"),children:t("delassets.noteOnly")})]}),f.jsx("button",{className:"dialog-btn","data-danger":!0,autoFocus:!e.block,onClick:()=>r("with"),children:t("delassets.deleteAll")})]})]})})}gn({"settings.notes.aiSpaceLabel":{zh:"空行按空格唤起 AI",en:"Press Space on an empty line for AI"},"settings.notes.aiSpaceHint":{zh:"在空的段落里按空格打开 AI 写作面板;输入法组字中的空格不受影响。仅本机生效",en:"Space on an empty paragraph opens the AI writing panel. Spaces typed with an input method are not affected. This device only"}});const Xa="forsion.amadeus.aiSpaceTrigger";let cs=null;function uh(){if(cs===null)try{cs=localStorage.getItem(Xa)==="1"}catch{cs=!1}return cs}function Zb(e){cs=e;try{e?localStorage.setItem(Xa,"1"):localStorage.removeItem(Xa)}catch{}}gn({"find.placeholder":{zh:"在本页查找…",en:"Find in page…"},"find.prev":{zh:"上一个(Shift+Enter)",en:"Previous (Shift+Enter)"},"find.next":{zh:"下一个(Enter)",en:"Next (Enter)"},"find.close":{zh:"关闭(Esc)",en:"Close (Esc)"},"find.case":{zh:"区分大小写",en:"Match case"},"find.regex":{zh:"使用正则表达式",en:"Use regular expression"},"find.toggleReplace":{zh:"切换替换(⌘⌥F / Ctrl+Alt+F)",en:"Toggle replace (⌘⌥F / Ctrl+Alt+F)"},"find.replacePlaceholder":{zh:"替换为…",en:"Replace with…"},"find.replaceOne":{zh:"替换(Enter)",en:"Replace (Enter)"},"find.replaceAll":{zh:"全部替换(⌘/Ctrl+Enter)",en:"Replace all (⌘/Ctrl+Enter)"},"find.badRegex":{zh:"正则表达式无效",en:"Invalid regular expression"}});const Fl=typeof CSS<"u"&&"highlights"in CSS;let qt=[],ys=[];const St=Pl(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),xs=new Set,bi=()=>St.setState(e=>({providerVer:e.providerVer+1}));function vi(e){return xs.add(e),bi(),()=>{xs.delete(e),bi()}}function dc(e){const t=e.startContainer;for(const n of xs)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function wi(e,t,n){return!n||!t?e:e.replace(/\$(\$|&|<([^>]*)>|(\d{1,2}))/g,(o,r,s,i)=>{if(r==="$")return"$";if(r==="&")return t[0];if(s!==void 0)return t.groups?.[s]??"";if(i!==void 0){const a=Number(i);if(a>=1&&a<t.length)return t[a]??"";if(i.length===2&&Number(i[0])>=1&&Number(i[0])<t.length)return(t[Number(i[0])]??"")+i[1]}return o})}function Ol(e,t){const n=t.regex?e:e.trim();if(!n)return null;try{return new RegExp(t.regex?n:n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t.caseSensitive?"gm":"gim")}catch{return"bad"}}function dh(e){let t=null;const n=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textIndent","textTransform","textAlign","tabSize","whiteSpace","overflowWrap","wordBreak","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","direction"],o=()=>{if(!t)return;const r=getComputedStyle(e);for(const s of n)t.style[s]=r[s];Object.assign(t.style,{position:"absolute",left:`${e.offsetLeft}px`,top:`${e.offsetTop}px`,width:`${e.offsetWidth}px`,height:`${e.offsetHeight}px`,margin:"0",borderStyle:"solid",borderColor:"transparent",overflow:"hidden",color:"transparent",background:"transparent",pointerEvents:"none",whiteSpace:"pre-wrap"}),t.firstChild?.nodeValue!==e.value&&(t.textContent=e.value),t.scrollTop=e.scrollTop};return{el:e,owns:r=>!!t&&t.contains(r),attach:()=>{t=document.createElement("div"),t.className="amx-find-mirror",t.setAttribute("aria-hidden","true"),e.parentElement?.insertBefore(t,e.nextSibling),o();const r=new ResizeObserver(o);return r.observe(e),e.addEventListener("input",o),e.addEventListener("scroll",o),()=>{r.disconnect(),e.removeEventListener("input",o),e.removeEventListener("scroll",o),t?.remove(),t=null}},replace:r=>{const s=e.value,i=r.map(({range:L,text:M})=>({from:L.startOffset,to:L.endOffset,text:M,was:L.toString()})).filter(L=>s.slice(L.from,L.to)===L.was).sort((L,M)=>L.from-M.from);if(!i.length)return 0;const a=i[0].from,c=i[i.length-1].to;let d="",m=a;for(const L of i)d+=s.slice(m,L.from)+L.text,m=L.to;d+=s.slice(m,c);const g=document.activeElement;return e.focus(),e.setSelectionRange(a,c),(d?document.execCommand("insertText",!1,d):document.execCommand("delete"))||(e.setRangeText(d,a,c,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))),g?.focus(),o(),i.length},focusAt:r=>t?.contains(r.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(r.startOffset,r.endOffset),!0):!1}}function fh(){const e=document.activeElement;return(e instanceof Element?e.closest(".wb-view, .mb-view, .fs-overlay"):null)??document.querySelector(".dv-active-group .wb-view")??document.querySelector(".wb-view--main")??document.querySelector(".mb-view")??document.body}function mh(){const e=document.activeElement;let t="";if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&/^(text|search)$/.test(e.type)){if(e.closest(".amx-findbar"))return null;t=e.value.slice(e.selectionStart??0,e.selectionEnd??0)}else t=window.getSelection()?.toString()??"";return t.trim()&&!/[\r\n]/.test(t)&&t.length<=200?t:null}let bs=null;function ph(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){bs=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;bs={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function hh(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function gh(e){const t=bs;bs=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(dc(e)?.focusAt?.(e))return;const r=hh(e);if(r){r.focus({preventScroll:!0});const s=window.getSelection();s?.removeAllRanges(),s?.addRange(e);return}}if(t?.el.isConnected&&(t.el.focus({preventScroll:!0}),t.range&&t.range.startContainer.isConnected)){const o=window.getSelection();o?.removeAllRanges(),o?.addRange(t.range)}}}function Qb(e={}){if(!Fl)return;const t=mh();if(St.getState().open){St.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}ph(),St.setState({open:!0,root:fh(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function ga(e){const t=e==="keyboard"?qt[St.getState().active]??null:null;qt=[],ys=[],is(-1),St.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?gh(t):bs=null}const yh=/^(inline|contents|ruby)/;function xh(e,t){let n=e.parentElement;for(;n;){let o=t.get(n);if(o===void 0&&(o=yh.test(getComputedStyle(n).display),t.set(n,o)),!o)return n;n=n.parentElement}return null}function bh(e,t){if(ys=[],!t)return[];const n=new WeakMap,o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(d){const m=d.parentElement;if(!m||!d.nodeValue||m.closest(".amx-findbar"))return NodeFilter.FILTER_REJECT;const g=m.tagName;return g==="SCRIPT"||g==="STYLE"||g==="NOSCRIPT"||g==="TEXTAREA"||!m.checkVisibility()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let r="";const s=[];let i=null;for(let d=o.nextNode();d;d=o.nextNode()){const m=d,g=xh(m,n);s.length&&g!==i&&(r+=`
|
|
3
|
-
`),i=g,s.push({node:m,at:r.length}),r+=m.nodeValue??""}const a=[];let c=0;t.lastIndex=0;for(let d=t.exec(r);d;d=t.exec(r)){if(!d[0]){t.lastIndex++;continue}if(d[0].includes(`
|
|
4
|
-
`))continue;const m=d.index,g=m+d[0].length;for(;c>0&&s[c].at>m;)c--;for(;c+1<s.length&&s[c+1].at<=m;)c++;let C=c;for(;C+1<s.length&&s[C+1].at<g;)C++;const L=document.createRange();L.setStart(s[c].node,m-s[c].at),L.setEnd(s[C].node,Math.min(g-s[C].at,s[C].node.length)),a.push(L),ys.push(d)}return a}function ya(e){const t=St.getState(),n=Ol(t.query,t);return qt=bh(e,n==="bad"?null:n),St.setState({bad:n==="bad",replaceable:qt.filter(o=>dc(o)).length}),qt.length}function is(e){if(!Fl)return;const t=CSS.highlights;if(!qt.length){t.delete("amx-find"),t.delete("amx-find-active");return}t.set("amx-find",new Highlight(...qt));const n=qt[e],o=n?new Highlight(n):new Highlight;o.priority=1,t.set("amx-find-active",o)}function vh(e){for(let t=e;t&&t!==document.body;t=t.parentElement){if(!(t instanceof HTMLElement))continue;const n=getComputedStyle(t),o=/auto|scroll/.test(n.overflowY)&&t.scrollHeight>t.clientHeight+1,r=/auto|scroll/.test(n.overflowX)&&t.scrollWidth>t.clientWidth+1;if(o||r)return t}return null}function xa(e){const t=e.getBoundingClientRect();if(!t.width&&!t.height)return;const n=e.startContainer.parentElement;if(!n||!n.dispatchEvent(new CustomEvent("amx-reveal",{bubbles:!0,cancelable:!0,detail:{rect:t}})))return;const r=vh(n);if(!r)return;const s=r.getBoundingClientRect(),i=r.currentCSSZoom||1;(t.bottom>s.bottom||t.top<s.top)&&(r.scrollTop+=(t.top+t.height/2-(s.top+s.height/2))/i),(t.right>s.right||t.left<s.left)&&(r.scrollLeft+=(t.left+t.width/2-(s.left+s.width/2))/i)}function ev(){return St(t=>t.open)?f.jsx(wh,{}):null}function wh(){const{t:e}=Zt(),t=St(H=>H.query),n=St(H=>H.active),o=St(H=>H.total),r=St(H=>H.root),s=St(H=>H.caseSensitive),i=St(H=>H.regex),a=St(H=>H.bad),c=St(H=>H.replaceOpen),d=St(H=>H.replacement),m=St(H=>H.replaceable),g=St(H=>H.providerVer),[C,L]=v.useState({top:12,right:12}),M=v.useRef(null),k=!!r&&[...xs].some(H=>H.el.isConnected&&r.contains(H.el));v.useLayoutEffect(()=>{const H=()=>{const ne=r?.getBoundingClientRect();ne&&L({top:ne.top+8,right:Math.max(8,window.innerWidth-ne.right+8)})};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[r]),v.useLayoutEffect(()=>{if(!r)return;const H=[...xs].filter(ne=>ne.attach&&r.contains(ne.el)).map(ne=>ne.attach());return()=>H.forEach(ne=>ne())},[r,g]),v.useEffect(()=>{r&&(ya(r),St.setState({total:qt.length,active:0}),is(0),qt.length&&xa(qt[0]))},[r,t,s,i,g]),v.useEffect(()=>{if(!r)return;const H=()=>{r.isConnected||ga()};window.addEventListener("focusin",H);const ne=window.setInterval(H,1e3);return()=>{window.removeEventListener("focusin",H),window.clearInterval(ne)}},[r]),v.useEffect(()=>{if(!r||!t.trim())return;let H=0;const ne=new MutationObserver(()=>{window.clearTimeout(H),H=window.setTimeout(()=>{ya(r);const je=Math.min(St.getState().active,Math.max(0,qt.length-1));St.setState({total:qt.length,active:je}),is(je)},150)});return ne.observe(r,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(H),ne.disconnect()}},[r,t,s,i]);const z=H=>{if(!qt.length)return;const ne=(St.getState().active+H+qt.length)%qt.length;St.setState({active:ne}),is(ne),xa(qt[ne])},F=H=>{if(!r||!qt.length)return;const ne=St.getState(),je=H?qt.map((be,me)=>me):[ne.active],He=new Map;for(const be of je){const me=dc(qt[be]);if(!me)continue;const Ee=He.get(me)??[];Ee.push({range:qt[be],text:wi(ne.replacement,ys[be],ne.regex)}),He.set(me,Ee)}let p=0;for(const[be,me]of He)p+=be.replace(me);if(!p&&!H){z(1);return}const fe=ne.active,rt=H?"":wi(ne.replacement,ys[ne.active],ne.regex);ya(r);let ie=0;if(!H&&qt.length){const be=Ol(ne.query,ne),me=be&&be!=="bad"?(rt.match(new RegExp(be.source,be.flags))??[]).length:0;ie=(fe+me)%qt.length}St.setState({total:qt.length,active:ie}),is(ie),qt.length&&xa(qt[ie])},J=H=>H.key==="Escape"?(ga("keyboard"),!0):(H.metaKey||H.ctrlKey)&&H.altKey&&H.code==="KeyF"?(H.preventDefault(),k&&St.setState({replaceOpen:!St.getState().replaceOpen}),!0):!1,se=H=>{St.setState({[H]:!St.getState()[H]}),M.current?.focus()};return f.jsxs("div",{className:`amx-findbar${c&&k?" amx-findbar--replace":""}`,style:{top:C.top,right:C.right},children:[k&&f.jsx("button",{className:"amx-findbar-expand",onClick:()=>St.setState({replaceOpen:!c}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":c,children:c?f.jsx(tf,{size:14}):f.jsx(Tl,{size:14})}),f.jsxs("div",{className:"amx-findbar-rows",children:[f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{ref:M,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":a||void 0,title:a?e("find.badRegex"):void 0,onFocus:H=>H.currentTarget.select(),onChange:H=>St.setState({query:H.target.value}),onKeyDown:H=>{!J(H)&&H.key==="Enter"&&z(H.shiftKey?-1:1),H.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>se("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:f.jsx(Mp,{size:15})}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>se("regex"),"aria-pressed":i,title:e("find.regex"),"aria-label":e("find.regex"),children:f.jsx(Yp,{size:14})}),f.jsx("span",{className:"amx-findbar-count",children:o?`${n+1}/${o}`:t.trim()?"0":""}),f.jsx("button",{onClick:()=>z(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),f.jsx("button",{onClick:()=>z(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),f.jsx("button",{onClick:()=>ga("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),c&&k&&f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:d,onChange:H=>St.setState({replacement:H.target.value}),onKeyDown:H=>{!J(H)&&H.key==="Enter"&&F(H.metaKey||H.ctrlKey),H.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>F(!1),disabled:!m,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:f.jsx(Jp,{size:14})}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>F(!0),disabled:!m,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:f.jsx(Up,{size:14})})]})]})]})}gn({"unisave.conflict.toast":{zh:"「{name}」在你编辑时被别处改过。已保留你的版本,被覆盖的那一版另存为「{copy}」。",en:'"{name}" was changed elsewhere while you were editing. Your version was kept, and the overwritten version was saved as "{copy}".'},"unisave.conflict.agentToast":{zh:"Tangu 在你编辑时改了「{name}」。已保留你的版本,Tangu 的改动另存为「{copy}」。",en:'Tangu changed "{name}" while you were editing. Your version was kept, and Tangu’s changes were saved as "{copy}".'},"unisave.conflict.open":{zh:"打开副本",en:"Open copy"},"unisave.failed.toast":{zh:"「{name}」没能保存({reason}),正在自动重试。保存成功之前请不要关闭它。",en:'Couldn’t save "{name}" ({reason}). Retrying automatically — keep it open until it’s saved.'},"unisave.failed.unknown":{zh:"未知原因",en:"unknown reason"},"unisave.failed.bar":{zh:"未保存:写入失败,正在自动重试",en:"Unsaved: the write failed and is being retried"},"unisave.failed.retry":{zh:"立即重试",en:"Retry now"},"unisave.draft.bar":{zh:"这篇笔记有一份上次没保存成功的草稿({time})。",en:"This note has a draft that wasn’t saved last time ({time})."},"unisave.draft.hint":{zh:"恢复后会覆盖盘上当前内容;盘上那一版若是别处改过的,会先另存为冲突副本。",en:"Restoring replaces what’s on disk now. If that version was changed elsewhere, it is saved as a conflict copy first."},"unisave.draft.restore":{zh:"恢复草稿",en:"Restore draft"},"unisave.draft.discard":{zh:"丢弃",en:"Discard"},"unisave.gone.toast":{zh:"「{name}」已在别处被删除或移走,最后的改动没来得及保存,另存副本也没写成。可以把这篇的内容复制下来。",en:'"{name}" was deleted or moved elsewhere before your last changes were saved, and a backup copy couldn’t be written. You can copy its text.'},"unisave.renameCopy.toast":{zh:"「{name}」改名时已被别处改过,没有覆盖它。你改名期间打的字另存为「{copy}」。",en:'"{name}" was changed elsewhere while it was being renamed, so it wasn’t overwritten. What you typed during the rename was saved as "{copy}".'},"unisave.rescued.toast":{zh:"「{name}」已在别处被删除或移走。你还没保存的内容另存为「{copy}」。",en:'"{name}" was deleted or moved elsewhere. Your unsaved changes were saved as "{copy}".'},"unisave.gone.copy":{zh:"复制内容",en:"Copy text"},"unisave.gone.copied":{zh:"已复制到剪贴板",en:"Copied to clipboard"}});function ir(e){typeof window>"u"||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:e}))}const lr=e=>(e.split("/").pop()??e).replace(/\.md$/i,"");let ki=Promise.resolve();function ba(e,t,n=new Date){const o=ki.then(()=>Ci(e,t,n),()=>Ci(e,t,n));return ki=o.catch(()=>{}),o}async function Ci(e,t,n){const o=Du(e,n);for(let r=1;r<=50;r++){const s=Lu(o,r),i=await bn.readTextFile(s);if(i===t)return s;if(i!=null)continue;const a=await bn.writeTextFile(s,t,{create:!0});if(a&&a.ok===!1){if(a.current===t)return s;if(a.current!=null)continue;throw new Error("The conflict copy could not be created")}return s}throw new Error("Too many conflict copies in one minute")}function kh(e,t,n=!1){ir({level:"error",dedupeKey:`amx-conflict:${e}`,text:ke(n?"unisave.conflict.agentToast":"unisave.conflict.toast",{name:lr(e),copy:lr(t)}),action:{label:ke("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function _l(e){const n=(e instanceof Error?e.message:typeof e=="string"?e:"").replace(/^Error invoking remote method '[^']*':\s*/,"").replace(/^(?:[A-Za-z]*Error:\s*)+/,"").trim();return n?n.length>80?`${n.slice(0,79)}…`:n:ke("unisave.failed.unknown")}function va(e,t){ir({level:"warning",dedupeKey:`amx-savefail:${e}`,text:ke("unisave.failed.toast",{name:lr(e),reason:_l(t)})})}function Ch(e,t){ir({level:"error",dedupeKey:`amx-rescued:${t}`,text:ke("unisave.rescued.toast",{name:lr(e),copy:lr(t)}),action:{label:ke("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Sh(e,t){ir({level:"error",dedupeKey:`amx-renamecopy:${t}`,text:ke("unisave.renameCopy.toast",{name:lr(e),copy:lr(t)}),action:{label:ke("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Eh(e,t){ir({level:"error",dedupeKey:`amx-gone:${e}:${Cr(t)}`,text:ke("unisave.gone.toast",{name:lr(e)}),action:{label:ke("unisave.gone.copy"),run:()=>{navigator.clipboard?.writeText(t).then(()=>ir({text:ke("unisave.gone.copied")}),()=>{})}}})}const Si=[2e3,5e3,1e4,3e4,6e4],Bl=(e,t)=>`amadeus.unsavedDraft:${e??""}:${t}`,Ys=(e,t,n)=>Bl(e,t)+(n?`\0${n}`:"");function Po(e,t,n,o,r){try{const s={text:n,base:Cr(o),at:Date.now()};localStorage.setItem(Ys(e,t,r),JSON.stringify(s))}catch{}}function ls(e,t){if(!e)return null;const n=JSON.parse(e);return typeof n.text=="string"&&typeof n.base=="string"?{text:n.text,base:n.base,at:Number(n.at)||0,slot:t}:null}function Mh(e,t,n,o=()=>!0){try{const r=Ys(e,t);if(n){const a=ls(localStorage.getItem(Ys(e,t,n)),n);if(a)return a;const c=o(null)?null:ls(localStorage.getItem(r),null);if(c)return c}else{const a=ls(localStorage.getItem(r),null);if(a)return a}const s=Bl(e,t)+"\0";let i=null;for(let a=0;a<localStorage.length;a++){const c=localStorage.key(a);if(!c||!c.startsWith(s))continue;const d=c.slice(s.length);if(d===n||o(d))continue;const m=ls(localStorage.getItem(c),d);m&&(!i||m.at>i.at)&&(i=m)}return i}catch{return null}}function Jr(e,t,n,o){try{const r=Ys(e,t,o);if(n!=null){const s=ls(localStorage.getItem(r),o??null);if(!s||s.text!==n)return}localStorage.removeItem(r)}catch{}}function zh(){return typeof navigator<"u"&&/\bElectron\//.test(navigator.userAgent)}function br(e){const t=Iu(e);return t.length===e.length&&e.startsWith(qs)?{fmText:qs,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function $n(e,t){return e+t}function wa(e,t){const n=ws(e);return n.trim()&&!Nh(n)?e:br(Fu(e,t)).fmText}function Nh(e){try{const t=Zs(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function $h(e,t){const n=Ah(e,t);if(n!==null)return Ga(e,n);const{bom:o}=vs(e),r=Ja(e),s=t.replace(/\n+$/,"");if(!r.length&&!s.trim())return o;const i=o+["---",...r,...s.trim()?[s]:[],"---",""].join(`
|
|
5
|
-
`);return Ua(s)?Ga(e,i):i}function Ah(e,t){const n=ws(e),o=t.replace(/(?:\r?\n)+$/,"");if(!n||!o.trim())return null;if(o===n)return e;const r=e.indexOf(n),s=r+n.length;if(r<=0||e[r-1]!==`
|
|
6
|
-
`||!/^\r?\n/.test(e.slice(s))||e.indexOf(n,r+1)>=0)return null;const i=e.slice(0,r)+o+e.slice(s);return ws(i)===o&&Ja(i).join(`
|
|
7
|
-
`)===Ja(e).join(`
|
|
8
|
-
`)?i:null}function Ua(e){try{return Zs(e),!0}catch{return!1}}function Ga(e,t){if(t===e)return t;const n=vs(t).inner;if(n==null||Ua(n))return t;const o=vs(e).inner;return o==null||!Ua(o)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const Th=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function vs(e){const t=e.startsWith(qs)?qs:"",n=Th.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function fc(e){const{inner:t}=vs(e);return t==null?null:t?_u(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function Ja(e){return(fc(e)??[]).filter(t=>Ou.test(t[0])).flat()}const jh=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function us(e,t,n){const{bom:o}=vs(e),r=fc(e)??[],s=r.filter(c=>!jh.test(c[0])).flat(),a=[...nf(t,n).flatMap(c=>{const d=Dh.exec(c)?.[1],m=d?ql(r,d):null;return m&&m.length>1&&Hl(m,d)===(d==="layout"?t:n)?m:[c]}),...s];return a.length?Ga(e,o+["---",...a,"---",""].join(`
|
|
9
|
-
`)):o}function Rh(e){const t=yo(e),n=ln(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:us(e,t,n)}function yo(e){return Kl(e,"layout")}function ln(e){return Kl(e,"canvas")}const Dh=/^amadeus_(layout|canvas):/;function Kl(e,t){const n=fc(e),o=n&&ql(n,t);return o?Hl(o,t):null}function ql(e,t){const n=new RegExp(`^["']?amadeus_${t}["']?\\s*:`);let o=null;for(const r of e)n.test(r[0])&&(o=r);return o}function Hl(e,t){if(e.length===1){const o=new RegExp(`^["']?amadeus_${t}["']?\\s*:\\s*(.+)$`).exec(e[0]);return o?o[1].trim():null}const n=e.join(`
|
|
10
|
-
`);try{const o=Zs(n),r=o&&typeof o=="object"&&!Array.isArray(o)?Object.values(o)[0]:void 0;if(r&&typeof r=="object")return JSON.stringify(r);if(typeof r=="string")return r}catch{}return n}function Lh(e){return e?Pu(bl(e)):{}}function ws(e){return e?bl(e):""}const Ih=80;function Ph(){return Et(()=>{if(!Kr())return new Ht({});const e=Math.round(Ih*Ln(document.body));return new Ht({props:{scrollThreshold:{top:0,left:0,right:0,bottom:e},scrollMargin:{top:5,left:5,right:5,bottom:e}}})})}function Xs(e){const t=[];return e.descendants((n,o)=>{if(n.type.name!=="heading")return!0;const r=Number(n.attrs?.level),s=Number.isFinite(r)?Math.min(6,Math.max(1,r)):1,i=n.textContent.trim();return i&&t.push({level:s,text:i,pos:o}),!1}),t}function Ei(e,t=0,n=e.content.size){return e.textBetween(t,n,`
|
|
11
|
-
`,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function Fh(e){let t=null,n={chars:0,words:0};return()=>{const o=e();if(!o)return null;o.state.doc!==t&&(t=o.state.doc,n=Xc(Ei(t)));const{from:r,to:s,empty:i}=o.state.selection;return{all:n,sel:i?null:Xc(Ei(o.state.doc,r,s))}}}function Oh(){return[Et(()=>new Ht({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Oc()}))};return t(),{update:(n,o)=>{(n.state.doc!==o.doc||!n.state.selection.eq(o.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Oc()}}}}))]}function _h(e){const t=(o,r,s)=>{const i=o.selection;return!(i instanceof Ie)||!i.empty||!s||Nr.atStart(o.doc).$from.start()!==i.$from.start()||!s.endOfTextblock("up")?!1:e()},n=o=>{const r=o.selection;if(!(r instanceof Ie)||!r.empty)return!1;const s=r.$from;return s.depth!==1||s.index(0)!==0||s.parentOffset!==0||s.parent.type.name!=="paragraph"?!1:e()};return[Et(()=>_o({ArrowUp:t,ArrowLeft:n}))]}function Mi(e,t){const n=e.content.size;return e.textBetween(Math.max(0,t-12),Math.min(n,t+12),`
|
|
12
|
-
`,"")}function Bh(e){return[Et(()=>new Ht({view:t=>{try{localStorage.getItem("amx_probe")&&(window.__amxView=t)}catch{}let n=!0,o=null;const r=()=>{o=null;const{vaultRoot:i,path:a}=e.where(),c=t.state.selection;rf(i,a,{a:c.anchor,h:c.head,t:Mi(t.state.doc,c.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:i,path:a}=e.where(),c=of(i,a),d=t.state.doc;let m=null;if(c&&c.a<=d.content.size&&c.h<=d.content.size&&Mi(d,c.h)===c.t){try{m=Ie.between(d.resolve(c.a),d.resolve(c.h))}catch{m=null}m&&(m.anchor!==c.a||m.head!==c.h)&&(m=null)}m&&t.dispatch(t.state.tr.setSelection(m).setMeta("addToHistory",!1)),e.focus()&&t.focus()});const s=()=>{o&&(clearTimeout(o),r(),sf())};return window.addEventListener("pagehide",s),{update:(i,a)=>{i.state.selection.eq(a.selection)&&i.state.doc===a.doc||(o&&clearTimeout(o),o=setTimeout(r,300))},destroy:()=>{n=!1,window.removeEventListener("pagehide",s),o&&(clearTimeout(o),r())}}}}))]}gn({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const Kh="amx-modeseg-slot";function qh({on:e,toggle:t}){const{t:n}=Zt();return f.jsxs("div",{className:"t2s-vaultseg amx-modeseg",role:"tablist","aria-label":n("canvasseg.aria"),children:[f.jsx("div",{className:"t2s-vaultseg-thumb","data-side":e?"canvas":"doc"}),f.jsx("button",{type:"button",role:"tab","aria-selected":!e,className:e?"":"on",onMouseDown:o=>o.preventDefault(),onClick:()=>{e&&t()},children:n("canvasseg.doc")}),f.jsx("button",{type:"button",role:"tab","aria-selected":e,className:e?"on":"",onMouseDown:o=>o.preventDefault(),onClick:()=>{e||t()},children:n("canvasseg.canvas")})]})}function Hh({anchor:e,on:t,toggle:n}){const[o,r]=v.useState(null);return v.useEffect(()=>{const s=e?.closest(".amx-pane")??e?.ownerDocument?.body;if(!s)return;const i=()=>r(s.querySelector(`.${Kh}`));i();const a=new MutationObserver(i);return a.observe(s,{childList:!0,subtree:!0}),()=>a.disconnect()},[e]),o?jl.createPortal(f.jsx(qh,{on:t,toggle:n}),o):null}gn({"amprops.add":{zh:"添加属性",en:"Add property"},"amprops.addLabel":{zh:"写入笔记 frontmatter 的键名",en:"Key name written to the note frontmatter"},"amprops.reservedKey":{zh:"amadeus_* 是保留键",en:"amadeus_* keys are reserved"},"amprops.pluginManaged":{zh:"该键由插件管理",en:"This key is managed by a plugin"},"amprops.chipRaw":{zh:"属性(原文)",en:"Properties (raw)"},"amprops.chipCount":{zh:"属性 {n}",en:"Properties {n}"},"amprops.empty":{zh:"还没有属性。",en:"No properties yet."},"amprops.delete":{zh:"删除属性",en:"Delete property"},"amprops.pluginKeysWarn":{zh:"⚠️ 本文件含插件数据键({keys}),修复 YAML 时请勿改动那几行。",en:"⚠️ This file contains plugin data keys ({keys}) — leave those lines untouched while fixing the YAML."},"amprops.nestedHint":{zh:"嵌套结构请在源码模式编辑",en:"Edit nested values in source mode"},"amprops.chipsPlaceholder":{zh:"回车添加…",en:"Press Enter to add…"},"amprops.conflict":{zh:"此处已在别处改为「{v}」。失焦后以你的输入为准,按 Esc 放弃你的输入。",en:'Changed elsewhere to "{v}". Leaving the field keeps your input; press Esc to discard it.'},"amprops.conflictRaw":{zh:"这段已在别处被改动。失焦后以你的输入为准;撤销你的改动再失焦则采用别处的版本。",en:"Changed elsewhere. Leaving the field keeps your input; undo your edits first to take the other version."},"amprops.keyPlaceholder":{zh:"属性名",en:"Property name"},"amprops.type":{zh:"属性类型",en:"Property type"},"amprops.type.text":{zh:"文本",en:"Text"},"amprops.type.number":{zh:"数字",en:"Number"},"amprops.type.checkbox":{zh:"勾选",en:"Checkbox"},"amprops.type.date":{zh:"日期",en:"Date"},"amprops.type.list":{zh:"列表",en:"List"},"amprops.addConfirm":{zh:"添加",en:"Add"},"amprops.addCancel":{zh:"取消",en:"Cancel"},"amprops.linksHint":{zh:"点链接跳转,点空白处编辑",en:"Click a link to open it; click elsewhere to edit"}});const Vh=["text","number","checkbox","date","list"];function Wh(e,t=new Date){switch(e){case"number":return 0;case"checkbox":return!1;case"date":return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;case"list":return[];default:return""}}const Yh=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",Vl=e=>/\[\[[^\]\n]+\]\]/.test(e);function ka(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=Zs(e);if(t&&typeof t=="object"&&!Array.isArray(t))return{ok:!0,entries:Object.entries(t).map(([n,o])=>({key:n,value:o}))}}catch{}return{ok:!1,entries:[]}}const Wl=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function Ca(e,t,n,o=r=>r){if(e===null)return null;const r=o(e);return r===o(t)||r===o(n)?null:r}const Yl=v.createContext(null);function mc(e,t,{escDiscards:n="conflict",norm:o=s=>s,enterCommits:r=!1}={}){const[s,i]=v.useState(null),[a,c]=v.useState(e),d=v.useRef({draft:s,base:a,current:e,norm:o,commit:t});d.current.current=e,d.current.norm=o,d.current.commit=t;const m=k=>{d.current.draft=k,i(k)},g=k=>{d.current.base=k,c(k)},C=v.useContext(Yl);v.useLayoutEffect(()=>{if(!C)return;const k=()=>{const z=d.current,F=Ca(z.draft,z.base,z.current,z.norm);F!==null&&(g(F),z.commit(F))};return C.add(k),()=>{C.delete(k),k()}},[C]);const L=s!==null&&e!==a&&Ca(s,a,e,o)!==null;return{shown:s??e,conflict:L,change:k=>{d.current.draft===null&&g(d.current.current),m(k)},settle:()=>{const k=d.current,z=Ca(k.draft,k.base,k.current,k.norm);return m(null),z},onKeyDown:k=>{if(!(k.nativeEvent.isComposing||k.keyCode===229)){if(k.key==="Enter"&&r){k.preventDefault(),k.currentTarget.blur();return}k.key!=="Escape"||n==="never"||!L||(k.preventDefault(),k.stopPropagation(),m(null))}}}}function Xh({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:o}={}){const{t:r}=Zt(),s=kn(Ee=>Ee.activePage),i=kn(Ee=>Ee.vaultRoot),a=kn(Ee=>Ee.manifest?.fmExtra??""),c=ac(),d=e!==void 0,m=d?e:a,g=v.useRef(m);g.current=m;const[C,L]=v.useState(()=>Uc(i)??!1);v.useEffect(()=>{L(Uc(i)??!1)},[i]);const M=Ee=>{L(Be=>{const pe=typeof Ee=="function"?Ee(Be):Ee;return lf(i,pe),pe})},[k,z]=v.useState(!1),[F,J]=v.useState(null),se=v.useRef(null),H=o??s??void 0,ne=Ee=>{const Be=vl(Ee);Be&&c.getState().openWikiLink(Be,H)},je=v.useMemo(()=>ka(m),[m]),He=v.useMemo(()=>{const Ee=!d&&s?af(s):void 0;return new Set(Ee?.fmKeys??[])},[d,s]),p=v.useMemo(()=>je.entries.map((Ee,Be)=>({...Ee,idx:Be})).filter(Ee=>!He.has(Ee.key)),[je,He]);if(v.useEffect(()=>{if(!F)return;const Be=[...se.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(pe=>pe.dataset.key===F)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");Be&&(Be.focus(),Be.classList.contains("amx-prop-links")&&Be.click(),J(null))},[F,je]),!d&&!s)return null;const fe=Ee=>{t?t(Ee):c.getState().setFmExtra(Ee)},rt=Ee=>{Ee!==null&&fe(Ee)},ie=(Ee,Be)=>rt(qu(g.current,{[Ee]:Be})),be=(Ee,Be)=>{const pe=Ee.trim();return pe?/^amadeus_/.test(pe)?(window.alert(r("amprops.reservedKey")),!1):He.has(pe)?(window.alert(r("amprops.pluginManaged")),!1):(ka(g.current).entries.some(Ne=>Ne.key===pe)||ie(pe,Wh(Be)),J(pe),!0):!1},me=je.ok?p.length:null;return f.jsxs("div",{className:`amx-props${me===0&&!C?" is-empty":""}`,ref:se,children:[f.jsxs("div",{className:"amx-props-bar",children:[f.jsxs("button",{className:"amx-props-chip",onClick:()=>M(Ee=>!Ee),children:[me===null?r("amprops.chipRaw"):r("amprops.chipCount",{n:me}),C?" ▾":" ▸"]}),!n&&f.jsx("button",{className:"amx-props-add",title:r("amprops.add"),onClick:()=>{M(!0),je.ok&&z(!0)},children:f.jsx(cf,{size:12})})]}),C&&(je.ok?f.jsxs("div",{className:"amx-props-rows",children:[p.length===0&&!k&&f.jsx("div",{className:"amx-props-empty",children:r("amprops.empty")}),p.map(Ee=>n?f.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[f.jsx("span",{className:"amx-prop-key",children:Ee.key}),f.jsx(Jh,{value:Ee.value})]},`${s}:${Ee.idx}:${Ee.key}`):f.jsxs("div",{className:"amx-prop-row","data-key":Ee.key,children:[f.jsx(Gh,{name:Ee.key,onRename:Be=>{const pe=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(Be)||He.has(Be)||ka(g.current).entries.some(Ne=>Ne.key!==Ee.key&&Ne.key===Be);!Be||pe||rt(Bu(g.current,Ee.key,Be))}}),f.jsx(eg,{value:Ee.value,onCommit:Be=>ie(Ee.key,Be),onOpenLink:ne}),f.jsx("button",{className:"amx-prop-del",title:r("amprops.delete"),onClick:()=>ie(Ee.key,void 0),children:f.jsx(cc,{size:12})})]},`${s}:${Ee.key}`)),k&&!n&&f.jsx(Zh,{onAdd:(Ee,Be)=>{be(Ee,Be)&&z(!1)},onCancel:()=>z(!1)})]}):f.jsxs(f.Fragment,{children:[He.size>0&&f.jsx("div",{className:"amx-props-empty",children:r("amprops.pluginKeysWarn",{keys:[...He].join(", ")})}),f.jsx(Uh,{text:m,readOnly:n,onCommit:fe})]}))]})}function Uh({text:e,readOnly:t,onCommit:n}){const{t:o}=Zt(),r=i=>{t||n(i)},s=mc(e,r,{escDiscards:"never"});return f.jsx("textarea",{className:`amx-props-raw${s.conflict?" amx-prop-conflict":""}`,value:s.shown,spellCheck:!1,readOnly:t,title:s.conflict?o("amprops.conflictRaw"):void 0,onChange:i=>{t||s.change(i.target.value)},onBlur:()=>{const i=s.settle();i!==null&&r(i)}})}function Gh({name:e,onRename:t}){const n=mc(e,t,{norm:o=>o.trim(),enterCommits:!0});return f.jsx("input",{className:"amx-prop-key",value:n.shown,onChange:o=>n.change(o.target.value),onKeyDown:n.onKeyDown,onBlur:()=>{const o=n.settle();o!==null&&t(o)}})}function Jh({value:e}){return typeof e=="boolean"?f.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):Wl(e)?f.jsx("span",{className:"amx-prop-chips",children:e.map((t,n)=>f.jsx("span",{className:"amx-chip",children:String(t??"")},n))}):e==null?f.jsx("span",{className:"amx-prop-input"}):typeof e=="object"?f.jsx("span",{className:"amx-prop-input",children:JSON.stringify(e)}):f.jsx("span",{className:"amx-prop-input",children:String(e)})}function Zh({onAdd:e,onCancel:t}){const{t:n}=Zt(),[o,r]=v.useState(""),[s,i]=v.useState("text"),[a,c]=v.useState(!1),d=a?s:Yh(o);return f.jsxs("div",{className:"amx-prop-row amx-prop-new",children:[f.jsx("input",{className:"amx-prop-key",autoFocus:!0,value:o,placeholder:n("amprops.keyPlaceholder"),"aria-label":n("amprops.addLabel"),onChange:m=>r(m.target.value),onKeyDown:m=>{m.nativeEvent.isComposing||m.keyCode===229||(m.key==="Enter"?(m.preventDefault(),e(o,d)):m.key==="Escape"&&(m.preventDefault(),t()))}}),f.jsx("select",{className:"amx-prop-type","aria-label":n("amprops.type"),value:d,onChange:m=>{i(m.target.value),c(!0)},onKeyDown:m=>{m.key==="Escape"&&(m.preventDefault(),t())},children:Vh.map(m=>f.jsx("option",{value:m,children:n(`amprops.type.${m}`)},m))}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addConfirm"),"aria-label":n("amprops.addConfirm"),onClick:()=>e(o,d),children:f.jsx(ea,{size:12})}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addCancel"),"aria-label":n("amprops.addCancel"),onClick:t,children:f.jsx(cc,{size:12})})]})}function Xl({text:e,onOpenLink:t}){const n=[],o=/\[\[([^\]\n]+)\]\]/g;let r=0,s;for(;s=o.exec(e);){s.index>r&&n.push(e.slice(r,s.index));const i=s[1],a=i.indexOf("|");n.push(f.jsx("span",{className:"amx-prop-link",onMouseDown:c=>{c.preventDefault(),c.stopPropagation(),t(i)},onClick:c=>c.stopPropagation(),children:a>=0?i.slice(a+1):i},s.index)),r=s.index+s[0].length}return r<e.length&&n.push(e.slice(r)),f.jsx(f.Fragment,{children:n})}function Qh({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Zt(),[r,s]=v.useState(!1);return r?f.jsx(Za,{current:e,autoFocus:!0,onCommit:t,onDone:()=>s(!1)}):f.jsx("div",{className:"amx-prop-input amx-prop-links",tabIndex:0,title:o("amprops.linksHint"),onClick:()=>s(!0),onKeyDown:i=>{i.key==="Enter"&&!i.nativeEvent.isComposing&&(i.preventDefault(),s(!0))},children:f.jsx(Xl,{text:e,onOpenLink:n})})}function eg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Zt();return typeof e=="boolean"?f.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:r=>t(r.target.checked)}):Wl(e)?f.jsx(ng,{items:e.map(r=>String(r??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?f.jsx(Za,{current:String(e),norm:r=>r.trim(),onCommit:r=>{const s=Number(r);t(r!==""&&!Number.isNaN(s)?s:r)}}):typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?f.jsx(tg,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
|
|
13
|
-
`)&&Vl(e)?f.jsx(Qh,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?f.jsx(Za,{current:e??"",multiline:typeof e=="string"&&e.includes(`
|
|
14
|
-
`),onCommit:t}):f.jsx("span",{className:"amx-prop-nested",title:o("amprops.nestedHint"),children:Ku(e).trimEnd()})}function Za({current:e,norm:t,multiline:n=!1,autoFocus:o,onCommit:r,onDone:s}){const{t:i}=Zt(),a=mc(e,r,{norm:t,enterCommits:!n}),c={className:`amx-prop-input${n?" amx-prop-multiline":""}${a.conflict?" amx-prop-conflict":""}`,value:a.shown,title:a.conflict?i("amprops.conflict",{v:e}):void 0,autoFocus:o,onKeyDown:a.onKeyDown,onBlur:()=>{const d=a.settle();d!==null&&r(d),s?.()}};return n?f.jsx("textarea",{...c,rows:Math.min(8,a.shown.replace(/\n$/,"").split(`
|
|
15
|
-
`).length),spellCheck:!1,onChange:d=>a.change(d.target.value)}):f.jsx("input",{...c,onChange:d=>a.change(d.target.value)})}function tg({value:e,onCommit:t}){const[n,o]=v.useState(!1);return f.jsx("input",{type:"date",className:"amx-prop-input",value:n?"":e,onChange:r=>{const s=r.target.value;o(!s),s&&s!==e&&t(s)},onBlur:()=>o(!1)})}function ng({items:e,onCommit:t,onOpenLink:n}){const{t:o}=Zt(),[r,s]=v.useState(""),i=()=>{const c=r.trim();s(""),c&&!e.includes(c)&&t([...e,c])},a=c=>{c.nativeEvent.isComposing||c.keyCode===229||(c.key==="Enter"||c.key===","?(c.preventDefault(),i()):c.key==="Backspace"&&!r&&e.length&&t(e.slice(0,-1)))};return f.jsxs("div",{className:"amx-prop-chips",children:[e.map((c,d)=>f.jsxs("span",{className:"amx-chip",children:[n&&Vl(c)?f.jsx(Xl,{text:c,onOpenLink:n}):c,f.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((m,g)=>g!==d)),children:f.jsx(cc,{size:10})})]},`${d}:${c}`)),f.jsx("input",{value:r,placeholder:e.length?"":o("amprops.chipsPlaceholder"),onChange:c=>s(c.target.value),onKeyDown:a,onBlur:i})]})}const og=new Set(["bullet","ordered","task"]);function rg(e){if(!e)return null;switch(e.type.name){case"paragraph":return"text";case"heading":return e.attrs.level>=1&&e.attrs.level<=3?`h${e.attrs.level}`:null;case"bullet_list":return e.firstChild?.attrs.checked!=null?"task":"bullet";case"ordered_list":return"ordered";case"code_block":return"code";case"amadeusCanvasCard":return"card";case"blockquote":{const t=e.firstChild?.isTextblock?e.firstChild.textContent:"";return/^\[!fold\]/i.test(t)?"fold":/^\[![\w-]+\]/.test(t)?"callout":"quote"}default:return null}}function Ul(e,t,n,o){if(o.kind!=="quote"&&o.kind!=="fold"){const a=e.state.tr,c=a.doc.content.size;e.state.doc.nodesBetween(t,n,(d,m)=>d.type.name==="blockquote"?(Jl(a,a.mapping.map(m)),!1):!d.isTextblock),a.docChanged&&(e.dispatch(a),n+=a.doc.content.size-c)}const r=[];e.state.doc.nodesBetween(t,n,(a,c)=>a.isTextblock?(r.push(c+1),!1):!0);const s=e.state.doc.content.size;let i=!1;for(const a of r.reverse())e.dispatch(e.state.tr.setSelection(Ie.near(e.state.doc.resolve(a)))),Qs(e,o,null)&&(i=!0);return i&&og.has(o.kind)&&sg(e,t,n+(e.state.doc.content.size-s)),i}function sg(e,t,n){const{doc:o}=e.state,r=o.resolve(t),s=r.parent,i=[];let a=r.start();for(let d=0;d<r.index();d++)a+=s.child(d).nodeSize;for(let d=r.index();d<s.childCount-1;d++){const m=s.child(d);if(a+=m.nodeSize,a>=n)break;const g=s.child(d+1);m.type===g.type&&/_list$/.test(m.type.name)&&i.push(a)}if(!i.length)return;const c=e.state.tr;for(const d of i.reverse())ff(c.doc,d)&&c.join(d);c.docChanged&&e.dispatch(c)}function Qa(e,t,n){const{state:o}=e,r=o.schema.nodes.code_block;if(!r)return!1;const s=o.doc.resolve(t),i=o.doc.resolve(n);if(s.parent!==i.parent||!s.parent.canReplaceWith(s.index(),i.index(),r))return!1;const a=o.doc.textBetween(t,n,`
|
|
16
|
-
`,`
|
|
17
|
-
`).replace(/^\n+|\n+$/g,""),c=o.tr.replaceWith(t,n,r.create(null,a?o.schema.text(a):void 0));return c.setSelection(Ie.near(c.doc.resolve(t+1))),e.dispatch(c.scrollIntoView()),!0}const ag=/^\[![\w-]+\]/;function zi(e,t,n,o){const r=e.state.schema.nodes.blockquote;if(!r)return!1;let s;const i=e.state.doc.nodeAt(t);if(i?.type===r&&t+i.nodeSize===n)s=t;else if(o){const d=e.state.doc.resolve(t).blockRange(e.state.doc.resolve(n)),m=d&&df(d,r);if(!d||!m)return!1;e.dispatch(e.state.tr.wrap(d,m)),s=t}else{if(e.dispatch(e.state.tr.setSelection(Ie.near(e.state.doc.resolve(t+1)))),!Qs(e,{kind:"quote"},null))return!1;const d=e.state.selection.$from;let m=d.depth;for(;m>0&&d.node(m).type!==r;)m--;if(m<1)return!1;s=d.before(m)}const a=e.state.doc.nodeAt(s),c=a?.firstChild;return!a||a.type!==r||!c?.isTextblock||ag.test(c.textContent)?!!a:(e.dispatch(e.state.tr.insertText(c.content.size?"[!note] ":"[!note]",s+2)),!0)}const Gl=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function Jl(e,t){const n=e.doc.nodeAt(t),o=n?.firstChild,r=n?.type.name==="blockquote"&&o?.isTextblock?Gl.exec(o.textContent):null;return!n||!o||!r?!1:(o.content.size===r[0].length&&n.childCount>1?e.delete(t+1,t+1+o.nodeSize):e.delete(t+2,t+2+r[0].length),!0)}function Ni(e,t,n,o){const r=e.state.doc.nodeAt(t),s=r?.firstChild,i=r?.type.name==="blockquote"&&t+r.nodeSize===n&&s?.isTextblock?Gl.exec(s.textContent):null;if(!r||!s||!i)return null;const a=e.state.tr;if(o!=="code"&&o.kind==="fold"){if(/^\[!fold\]/i.test(s.textContent))return!0;const C=i[0].length-(/[ \u00a0]$/.test(i[0])?1:0);return a.replaceWith(t+2,t+2+C,e.state.schema.text(pd)),e.dispatch(a.scrollIntoView()),!0}if(Jl(a,t),o!=="code"&&o.kind==="quote")return a.setSelection(Ie.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),!0;const c=a.doc.nodeAt(t),d=c.content.size,m=a.doc.resolve(t+1).blockRange(a.doc.resolve(t+c.nodeSize-1)),g=m?uf(m):null;return!m||g==null?!1:(a.lift(m,g),a.setSelection(Ie.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),o==="code"?Qa(e,t,t+d):o.kind==="text"?!0:o.kind==="heading"?Qs(e,o,null):Ul(e,t,t+d,o))}function cg(e){const t=e.split(`\r
|
|
18
|
-
`).length-1;return t&&t===e.split(`
|
|
19
|
-
`).length-1&&t===e.split("\r").length-1?`\r
|
|
20
|
-
`:`
|
|
21
|
-
`}function qr(e){const t=cg(e);return{text:t===`\r
|
|
22
|
-
`?e.replace(/\r\n/g,`
|
|
23
|
-
`):e,eol:t}}function Oo(e,t){return t===`\r
|
|
24
|
-
`?e.replace(/\r?\n/g,`\r
|
|
25
|
-
`):e}function ds(e,t,n){let o=n,r;try{r=e.doc.resolve(t)}catch{return n}const s=r.parent;let i=t;for(let a=r.index();a<s.childCount&&i<o;a++){const c=s.child(a);if(c.type.name==="heading"){const d=Xr(e,i);d!=null&&d>o&&(o=d)}i+=c.nodeSize}return o}function _r(e,t,n){for(const o of[Yr,Lm]){const r=o.getState(e)?.folded;if(!r?.length)continue;const s=[];for(const i of r){const a=i>=n.from&&i<n.to;(!a||n.copy)&&s.push(t.mapping.map(i)),a&&!n.drop&&n.newStart!=null&&s.push(n.newStart+(i-n.from))}t.setMeta(o,{set:s})}}function Zr(e,t,n){const o=t.getMeta(Yr)?.set;if(!o?.length)return;const r=mi(e.doc,Yr.getState(e)?.folded??[]),s=d=>r.some(m=>d>=m.start&&d<m.after),i=n.to-n.from,a=t.mapping.invert(),c=o.filter(d=>mi(t.doc,[d]).every(m=>{const g=t.doc.resolve(m.start),C=g.parent;let L=m.start;for(let M=g.index();M<C.childCount&&L<m.after;M++){const k=L;L+=C.child(M).nodeSize;const z=k>=n.newStart&&k<n.newStart+i?n.from+(k-n.newStart):a.map(k);if(!s(z))return!1}return!0}));c.length!==o.length&&t.setMeta(Yr,{set:c})}gn({"blocklinks.copyHeading":{zh:"复制标题链接",en:"Copy heading link"},"blocklinks.copyBlock":{zh:"复制块链接",en:"Copy block link"},"blocklinks.moveTo":{zh:"移动到…",en:"Move to…"},"blocklinks.copied":{zh:"已复制 {link}",en:"Copied {link}"},"blocklinks.copyFailed":{zh:"没能写入剪贴板",en:"Couldn't write to the clipboard"},"blocklinks.pickTitle":{zh:"移动到哪篇笔记",en:"Move to which note"},"blocklinks.pickPlaceholder":{zh:"输入笔记名…",en:"Type a note name…"},"blocklinks.noMatch":{zh:"没有匹配的笔记",en:"No matching notes"},"blocklinks.moved":{zh:"已移动到「{name}」末尾",en:'Moved to the end of "{name}"'},"blocklinks.moveFailed":{zh:"没能移动到「{name}」,原块没动",en:`Couldn't move to "{name}" — the blocks were left in place`},"blocklinks.moveConflict":{zh:"「{name}」刚被别处改过,没有移动,请重试",en:'"{name}" was just changed elsewhere — nothing was moved, try again'},"blocklinks.targetUnsaved":{zh:"已追加到「{name}」,但它还没存上,原块先保留在这里",en:`Added to "{name}", but it hasn't been saved yet, so the blocks were kept here too`},"blocklinks.keptSource":{zh:"已追加到「{name}」,但这几块期间被改过,没有从本篇删掉",en:'Added to "{name}", but these blocks changed meanwhile, so they were kept here too'}});const Bo=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},pc=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),Qr=e=>e.split("/").slice(0,-1).join("/");function ig(e,t,n){if(t===n)return e;const o=[!1,!0].map(r=>[Ai(t,r),Ai(n,r)]);return Uu(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(s,i,a,c,d)=>{if(/^[/<]/.test(c)||!$i(c))return s;const m=c.indexOf("#"),g=m<0?c:c.slice(0,m);let C=!1;try{decodeURIComponent(g)}catch{C=!0}const[L,M]=o[+C],k=Gu(M,kl(Cl(L,g)));if(C&&k.includes(" "))return s;const z=k.replace(/ /g,"");return`${i}[${a}](${!z.includes("/")||!$i(z)?"./":""}${z}${m<0?"":c.slice(m)}${d})`}))}const $i=e=>/^(?:note|file)$/.test(Ml(e)),Ai=(e,t)=>e.split("/").map(n=>{const o=t?n.replace(/%/g,""):n;return Ti(o)===o?n:` ${Ti(n)}`}).join("/"),Ti=e=>e.replace(/[\s%#?&|"'`[\]*:<>()\u0000-\u001f\u007f-\u009f]/g,t=>Array.from(new TextEncoder().encode(t),n=>`%${n.toString(16).toUpperCase().padStart(2,"0")}`).join(""));function lg(e){let t=null;for(const n of e.split(`
|
|
26
|
-
`)){const o=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(n);o&&(t?o[1][0]===t[0]&&o[1].length>=t.length&&!o[2].trim()&&(t=null):t=o[1])}return t!=null||e.lastIndexOf("<!--")>e.lastIndexOf("-->")}function ug(e,t){const{text:n,eol:o}=qr(e),r=n?n.endsWith(`
|
|
27
|
-
|
|
28
|
-
`)?"":n.endsWith(`
|
|
29
|
-
`)?`
|
|
30
|
-
`:`
|
|
31
|
-
|
|
32
|
-
`:"";return Oo(`${n}${r}${t}
|
|
33
|
-
`,o)}function dg(e,t){const n=pc(e);return hs(n,t)===e?n:e.replace(/\.md$/i,"")}function fg(e,t,n){const o=dg(t,n);if(e.type.name==="heading"){const s=hd(e.textContent);return s?{kind:"heading",link:`[[${o}#${s}]]`}:null}const r=wl(e.textContent);return r?{kind:"block",link:`[[${o}#^${r}]]`}:null}function mg(e){const t=navigator.clipboard?.writeText(e);if(!t){Bo(ke("blocklinks.copyFailed"));return}t.then(()=>Bo(ke("blocklinks.copied",{link:e})),()=>Bo(ke("blocklinks.copyFailed")))}function pg(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function hg(e){const{view:t,from:n,to:o,source:r,target:s}=e,i=pc(s);if(s===r)return!1;const a=t.state.doc.slice(n,o).content,c=e.serialize(a);if(!c?.trim())return Bo(ke("blocklinks.moveFailed",{name:i})),!1;let d=ig(Or(c,Qr(s)).trim(),Qr(r),Qr(s));e.pages&&Qr(r)!==Qr(s)&&(d=Hu(d,r,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(Vu(s)){if(!Wu(s,d,"end"))throw new Error("insert refused");try{await Yu(s,!0)}catch{return Bo(ke("blocklinks.targetUnsaved",{name:i})),!1}}else{const g=await bn.readTextFile(s);if(g==null)throw new Error("missing");if(lg(qr(g).text))throw new Error("unsafe tail");const C=await bn.writeTextFile(s,ug(g,d),{base:Cr(g)});if(C&&!C.ok)return Bo(ke("blocklinks.moveConflict",{name:i})),!1}}catch{return Bo(ke("blocklinks.moveFailed",{name:i})),!1}if(t.isDestroyed||o>t.state.doc.content.size||!t.state.doc.slice(n,o).content.eq(a))return Bo(ke("blocklinks.keptSource",{name:i})),!0;const m=t.state.tr.delete(n,o);return _r(t.state,m,{from:n,to:o,drop:!0}),t.dispatch(m.scrollIntoView()),Bo(ke("blocklinks.moved",{name:i})),!0}function Zl({pages:e,exclude:t,onPick:n,onClose:o}){const{t:r}=Zt(),[s,i]=v.useState(""),[a,c]=v.useState(0),d=ah(s,e.filter(m=>m!==t&&/\.md$/i.test(m)),Xu).slice(0,30);return v.useEffect(()=>{c(0)},[s]),jl.createPortal(f.jsx("div",{className:"cmd-overlay",onMouseDown:o,children:f.jsxs("div",{className:"cmd-panel",role:"dialog","aria-label":r("blocklinks.pickTitle"),"data-testid":"note-picker",onMouseDown:m=>m.stopPropagation(),children:[f.jsx("input",{className:"cmd-input",autoFocus:!0,placeholder:r("blocklinks.pickPlaceholder"),"aria-label":r("blocklinks.pickTitle"),value:s,onChange:m=>i(m.target.value),onKeyDown:m=>{m.key==="ArrowDown"?(m.preventDefault(),c(g=>Math.min(g+1,d.length-1))):m.key==="ArrowUp"?(m.preventDefault(),c(g=>Math.max(g-1,0))):m.key==="Enter"?(m.preventDefault(),d[a]&&n(d[a])):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),o())}}),f.jsxs("div",{className:"cmd-list",role:"listbox",children:[d.map((m,g)=>f.jsx("button",{className:"cmd-item",role:"option","aria-selected":g===a,"data-active":g===a||void 0,onMouseEnter:()=>c(g),onClick:()=>n(m),children:f.jsxs("span",{className:"cmd-row",children:[f.jsx("span",{className:"cmd-title",children:pc(m)}),f.jsx("span",{className:"cmd-path",children:m})]})},m)),!d.length&&f.jsx("div",{className:"cmd-empty",children:r("blocklinks.noMatch")})]})]})}),document.body)}function gg(e){return e.nodeType===1}function yg(e){return gg(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function xg(e){const t=[[-1,e.state.doc]],n=[];for(;t.length>0;){const[o,r]=t.pop();if(o>=0){const s=e.nodeDOM(o);if(s&&yg(s)){const{top:i,bottom:a,left:c,right:d}=s.getBoundingClientRect();n.push([o,[c,i,d,i]],[o+r.nodeSize,[c,a,d,a]])}}if(r.isBlock&&!r.isTextblock){let s=o+1;for(const i of r.children)t.push([s,i]),s+=i.nodeSize}}return n}function bg(e,t){let n=[],o,r;const s=()=>{const m=e.dom.getBoundingClientRect(),g=e.state.doc;return n&&o&&r&&m.width===r.width&&m.height===r.height&&m.x===r.x&&m.y===r.y&&o.eq(g)||(r=m,o=g,n=xg(e)),n},i=(m,g)=>{if(!e.editable||e.isDestroyed)return;const C=(k,z)=>{const[F,J]=k,[se,H]=z;return Ri(m,J)-Ri(m,H)||F-se};let L=s();L.sort(C),L=L.slice(0,8);const M=L.find(k=>t?.({view:e,pos:k[0],event:g})!==!1);if(!(M&&wg(e,M[0])))return M};let a,c;return(m,g)=>(a&&vg(a,m)||(a=m,c=i(m,g)),c)}function vg(e,t){return e[0]===t[0]&&e[1]===t[1]}function ji(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function Ri(e,t){return Math.min(ji(e,[t[0],t[1]]),ji(e,[t[2],t[3]]))}function wg(e,t){const n=e.dragging;if(!n)return;const{move:o}=n;if(!o)return;const r=e.state.selection;if(!(r instanceof Me))return;const{from:s,to:i}=r;return s<=t&&t<=i}function kg(e){let t;return new Ht({key:new Tn("prosemirror-drop-indicator"),view:n=>(t=bg(n,e.onDrag),Sg(n,t,e)),props:{handleDrop(n,o,r,s){if(!t)return!1;const i=t([o.clientX,o.clientY],o);if(!i)return!1;o.preventDefault();const a=i[0],c=n.state.tr;if(s){const{node:L}=n.dragging||{};L?L.replace(c):c.deleteSelection()}const d=c.mapping.map(a),m=r.openStart==0&&r.openEnd==0&&r.content.childCount==1,g=c.doc;if(m?c.replaceRangeWith(d,d,r.content.firstChild):c.replaceRange(d,d,r),c.doc.eq(g))return!0;const C=c.doc.resolve(d);if(m&&Me.isSelectable(r.content.firstChild)&&C.nodeAfter&&C.nodeAfter.sameMarkup(r.content.firstChild))c.setSelection(new Me(C));else{let L=c.mapping.map(a);c.mapping.maps[c.mapping.maps.length-1].forEach((M,k,z,F)=>L=F),c.setSelection(Cg(n,C,c.doc.resolve(L)))}return n.focus(),n.dispatch(c.setMeta("uiEvent","drop")),!0}}})}function Cg(e,t,n,o){return e.someProp("createSelectionBetween",r=>r(e,t,n))||Ie.between(t,n,o)}function Sg(e,t,n){const o=e.dom;let r,s,i,a=!1;const c=()=>{r&&clearTimeout(r),a=!1,r=setTimeout(()=>{a||n.onHide?.()},30)},d=g=>{a=!0;const{clientX:C,clientY:L}=g;if(s===C&&i===L)return;s=C,i=L;const M=t([C,L],g);if(M){const[k,[z,F,J,se]]=M,H={p1:{x:z,y:F},p2:{x:J,y:se}};n.onShow?.({view:e,pos:k,line:H})}else{c();return}};return o.addEventListener("dragover",d),o.addEventListener("dragend",c),o.addEventListener("drop",c),o.addEventListener("dragleave",c),{destroy:()=>{o.removeEventListener("dragover",d),o.removeEventListener("dragend",c),o.removeEventListener("drop",c),o.removeEventListener("dragleave",c)}}}gn({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function qo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function Di(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function Fo(e){return Array.isArray(e)?[...e]:[]}function Ql(e,t,n){return e.map(o=>qo(o)===t?{...o,...n}:o)}function Eg(e,t){const n=new Set,o=e.filter(r=>{const s=qo(r);return s&&t.has(s)?(n.add(s),!1):!0});return n.size?o.filter(r=>{if(!r||typeof r!="object"||r.type!=="connector")return!0;const s=r,i=Di(s.from),a=Di(s.to);return!(i&&n.has(i)||a&&n.has(a))}):o}function Li(e,t,n,o){return e.map(r=>{const s=qo(r);if(!s||!t.has(s))return r;const i=r;return typeof i.x!="number"||typeof i.y!="number"?r:{...i,x:Math.round(i.x+n),y:Math.round(i.y+o)}})}function fs(e,t){const n=new Set;for(const o of e){const r=qo(o);r&&n.add(r)}for(let o=1;;o++){const r=`${t}${o}`;if(!n.has(r))return r}}const he="m:",Mg={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},Ii={w:480,h:320};function eu(e,t,n){return{id:e,type:t==="text"?"text":"shape",...t==="text"?{}:{shape:t},x:Math.round(n.x),y:Math.round(n.y),w:Math.round(n.w),h:Math.round(n.h),...t==="text"?{text:ke("canvasedit.textDefault")}:{}}}function zg(e,t,n,o){const r=Mg[t];return eu(e,t,{x:n-r.w/2,y:o-r.h/2,w:r.w,h:r.h})}function ec(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function Ng(e,t,n){if(t===n)return e;const o=ec(t),r=ec(n);if(!o||!r)return e;const s=(a,c)=>{const d=c;return!!d&&d.ref===a.ref&&d.id===a.id};return e.some(a=>{if(!a||typeof a!="object"||a.type!=="connector")return!1;const c=a;return s(o,c.from)&&s(r,c.to)||s(o,c.to)&&s(r,c.from)})?e:[...e,{id:fs(e,"e"),type:"connector",from:o,to:r}]}const ms={fromEnd:"none",toEnd:"arrow"};function $g(e,t,n){let o=!1;const r=e.map(s=>{const i=qo(s);if(!i||!t.has(i)||s.type!=="connector")return s;const a=s;let c=null;for(const d of["fromEnd","toEnd"]){const m=n[d];if(m==null)continue;const g=m===ms[d];(g?!(d in a):a[d]===m)||(c??={...a},g?delete c[d]:c[d]=m)}return c?(o=!0,c):s});return o?r:e}const Ir=(e,t)=>{if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const n=e,o=t;return typeof n.ref=="string"||typeof o.ref=="string"?n.ref===o.ref:typeof n.id=="string"||typeof o.id=="string"?n.id===o.id:n.main===!0&&o.main===!0};function Ag(e,t,n,o){const r=ec(o);if(!r)return e;const s=e.find(c=>qo(c)===t);if(!s||s.type!=="connector")return e;const i=n==="from"?s.to:s.from;return Ir(r,s[n])||Ir(r,i)||e.some(c=>{if(qo(c)===t||!c||typeof c!="object"||c.type!=="connector")return!1;const d=c;return Ir(r,d.from)&&Ir(i,d.to)||Ir(r,d.to)&&Ir(i,d.from)})?e:Ql(e,t,{[n]:r})}function Tg(e,t,n,o){return e.map(r=>{if(qo(r)!==t)return r;const s={...r};return o?s[n]=o:delete s[n],s})}function Kt(e){const t=Object.create(null);if(!e||typeof e!="object"||Array.isArray(e))return t;for(const n of Object.keys(e))t[n]=e[n];return t}function Br(e,t,n){if(!t||!n||t===n)return e;let o=n;const r=new Set([t]);for(;typeof o=="string"&&o;){if(r.has(o))return e;r.add(o),o=e[o]}const s=Kt(e);return s[t]=n,s}function jg(e,t){if(!t.size)return e;const n=Object.create(null);for(const o of Object.keys(e)){if(t.has(o))continue;let r=e[o];const s=new Set;for(;typeof r=="string"&&t.has(r)&&!s.has(r);)s.add(r),r=e[r];typeof r!="string"||!r||t.has(r)||r===o||(n[o]=r)}return n}const vr=(e,t)=>Object.keys(e).filter(n=>e[n]===t).sort();function tu(e,t,n,o){if(!t||!n||t===n)return!1;const r=new Set([t]);let s=e[t];for(;typeof s=="string"&&s&&!r.has(s)&&(!o||o.has(s));){if(s===n)return!0;r.add(s),s=e[s]}return!1}function Rg(e,t,n,o=6){let r=0;const s=new Set([t]);let i=e[t];for(;typeof i=="string"&&i&&n.has(i)&&!s.has(i)&&r<o;)r++,s.add(i),i=e[i];return r}function Us(e,t,n){const o=new Set(e.map(s=>s.anchor));let r=t+1;for(;r<e.length&&e[r].idx===e[r-1].idx+1&&tu(n,e[r].anchor,e[t].anchor,o);)r++;return r}function Dg(e,t,n,o,r,s){return{id:e,type:"frame",x:Math.round(t),y:Math.round(n),w:Math.round(o),h:Math.round(r)}}const Lg=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function ta(e){return typeof e!="string"||!Lg.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function Ig(e,t,n){let o=!1;const r=e.map(s=>{const i=qo(s);if(!i||!t.has(i))return s;const a=s;if(n?a.color===n:!("color"in a))return s;o=!0;const c={...a};return n?c.color=n:delete c.color,c});return o?r:e}const hc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function Sa(e){if(!e)return null;try{const n=JSON.parse(e);if(!n||n.v!==4||!Array.isArray(n.rows))return null;for(const o of n.rows){if(!o||!Array.isArray(o.columns)||o.columns.length<1||o.tail!=null&&(typeof o.tail!="string"||!/^[A-Za-z0-9_-]+$/.test(o.tail)))return null;for(const r of o.columns)if(!r||!Array.isArray(r.refs)||r.refs.length<1||!r.refs.every(s=>typeof s=="string"&&/^[A-Za-z0-9_-]+$/.test(s))||typeof r.width!="number"||!Number.isFinite(r.width)||r.width<=0)return null}return n}catch{return null}}function No(e){const t=new Set;for(e.descendants(n=>{if(n.type.name==="amadeusColumnCell"&&n.attrs.anchor&&t.add(String(n.attrs.anchor)),n.type.name==="amadeusColumnRow"&&n.attrs.tail&&t.add(String(n.attrs.tail)),n.type.name==="amadeusCanvasCard"&&n.attrs.anchor&&t.add(String(n.attrs.anchor)),n.type.name==="html"){const o=hc.exec(String(n.attrs.value??"").trim());o&&t.add(o[1])}});;){const n="c"+Math.random().toString(36).slice(2,6);if(!t.has(n))return n}}function es(e,t){const n=[],o=[];return t.forEach(r=>{if(r.type.name==="amadeusCanvasCard"){let s=No(e);for(;n.includes(s);)s=No(e);n.push(s),o.push(r.type.create({...r.attrs,anchor:s},r.content,r.marks))}else o.push(r)}),n.length?{content:zo.fromArray(o),minted:n}:{content:t,minted:n}}const Pg=lc("amadeusColumnRow",()=>({content:"amadeusColumnCell+",group:"block",defining:!0,isolating:!0,selectable:!1,attrs:{tail:{default:""}},parseDOM:[{tag:"div[data-amx-colrow]",getAttrs:e=>({tail:e.dataset.tail??""})}],toDOM:e=>["div",{"data-amx-colrow":"","data-tail":String(e.attrs.tail),class:"amx-ucolrow"},0],parseMarkdown:{match:({type:e})=>e==="amadeusColumnRow",runner:(e,t,n)=>{e.openNode(n,{tail:t.tail??""}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusColumnRow",runner:(e,t)=>{t.forEach(n=>{e.addNode("html",void 0,`<!-- a ${n.attrs.anchor} -->`),n.childCount===1&&n.firstChild.type.name==="paragraph"&&n.firstChild.content.size===0||e.next(n.content)}),t.attrs.tail&&e.addNode("html",void 0,`<!-- a ${t.attrs.tail} -->`)}}})),Fg=lc("amadeusColumnCell",()=>({content:"block+",defining:!0,isolating:!0,selectable:!1,attrs:{anchor:{default:""},width:{default:1}},parseDOM:[{tag:"div[data-amx-colcell]",getAttrs:e=>{const t=Number(e.dataset.width);return{anchor:e.dataset.anchor??"",width:Number.isFinite(t)&&t>0?t:1}}}],toDOM:e=>["div",{"data-amx-colcell":"","data-anchor":String(e.attrs.anchor),"data-width":String(e.attrs.width),class:"amx-ucolcell",style:`flex-grow:${Number(e.attrs.width)||1}`},0],parseMarkdown:{match:({type:e})=>e==="amadeusColumnCell",runner:(e,t,n)=>{e.openNode(n,{anchor:t.anchor??"",width:t.width??1}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusColumnCell",runner:(e,t)=>{e.next(t.content)}}}));function Og(e,t,n){if(!t?.rows?.length)return;const o=Array.isArray(e?.children)?e.children:[];if(o.length&&!o.some(d=>d?.position))return;const r=d=>{let m=null;if(d?.type==="html"&&typeof d.value=="string")m=d.value;else if(d?.type==="paragraph"&&Array.isArray(d.children)&&d.children.length===1){const C=d.children[0];C?.type==="html"&&typeof C.value=="string"&&(m=C.value)}if(m==null)return null;const g=hc.exec(m.trim());return g?g[1]:null},s=[];if(o.forEach((d,m)=>{const g=r(d);g&&s.push({id:g,idx:m})}),!s.length)return;const i=new Map;s.forEach((d,m)=>{i.has(d.id)?i.set(d.id,-1):i.set(d.id,m)});const a=new Set,c=[];for(const d of t.rows){if(d.columns.length<2)continue;const m=d.columns.flatMap(F=>F.refs);if(!m.length)continue;const g=m.map(F=>i.get(F)??-1);if(g.some(F=>F<0||a.has(F))||new Set(g).size!==g.length||!g.every((F,J)=>J===0||F===g[J-1]+1))continue;const C=g[g.length-1],L=d.tail!=null&&C+1<s.length&&s[C+1].id===d.tail&&!a.has(C+1)?C+1:null,M=L!=null?s[L].idx:C+1<s.length?s[C+1].idx:o.length,k=[];let z=!0;d.columns.forEach((F,J)=>{const se=i.get(F.refs[0]),H=s[se].idx+1,ne=J+1<d.columns.length?i.get(d.columns[J+1].refs[0]):null,je=ne!=null?s[ne].idx:M;if(je<H){z=!1;return}const He=o.slice(H,je);k.push({type:"amadeusColumnCell",anchor:F.refs[0],width:F.width||1,children:He.length?He:[{type:"paragraph",children:[]}]})}),!(!z||k.length<2)&&(g.forEach(F=>a.add(F)),L!=null&&a.add(L),c.push({from:s[g[0]].idx,to:L!=null?s[L].idx+1:M,node:{type:"amadeusColumnRow",tail:L!=null?d.tail:"",children:k}}))}c.sort((d,m)=>m.from-d.from);for(const d of c)o.splice(d.from,d.to-d.from,d.node);c.length&&n?.()}function _g(e,t){return[Il("amadeusColumnsFold",()=>()=>n=>{Og(n,e(),t)})].flat()}function Bg(e){const t=[String(e.attrs.anchor)];return e.forEach(n=>{if(n.type.name!=="paragraph"||n.childCount!==1)return;const o=n.firstChild;if(o.type.name!=="html")return;const r=hc.exec(String(o.attrs.value??"").trim());r&&t.push(r[1])}),t}function Kg(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const o=[];n.forEach(r=>{o.push({refs:Bg(r),width:Number(r.attrs.width)||1})}),o.length>=2&&t.push({columns:o,...n.attrs.tail?{tail:String(n.attrs.tail)}:{}})}),t.length?JSON.stringify({v:4,rows:t}):null}const gc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function Gs(e,t){const{paragraph:n,html:o}=e.nodes;return t&&n&&o?[n.create(null,o.create({value:`<!-- a ${t} -->`}))]:[]}function yc(e,t,n,o=!1){const r=[];for(const s of t)r.push(...Gs(e,String(s.attrs.anchor))),o&&gc(s)||s.forEach(i=>r.push(i));return r.push(...Gs(e,n)),r}const qg=Et(()=>new Ht({key:new Tn("AMX_COLUMNS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(c=>c.docChanged))return null;const o=e.some(c=>(c.getMeta("uiEvent")==="drop"||c.getMeta("amxColumns"))&&!c.getMeta("amxColumnsKeepEmpty")),{paragraph:r}=n.schema.nodes,s=c=>Gs(n.schema,c),i=[];if(n.doc.descendants((c,d,m)=>{if(c.type.name==="amadeusColumnRow"&&m?.type.name==="amadeusColumnCell"){const g=[];return c.forEach(C=>C.forEach(L=>g.push(L))),i.push({from:d,to:d+c.nodeSize,content:g.length?g:[r.create()]}),!1}return!0}),n.doc.forEach((c,d)=>{if(c.type.name!=="amadeusColumnRow")return;const m=[];c.forEach(z=>m.push(z));const g=o?m.filter(z=>!gc(z)):m,C=g.some(z=>!z.attrs.anchor);if(g.length===m.length&&g.length>=2&&!C)return;const L=new Set;n.doc.descendants(z=>{z.type.name==="amadeusColumnCell"&&z.attrs.anchor&&L.add(String(z.attrs.anchor)),z.type.name==="amadeusColumnRow"&&z.attrs.tail&&L.add(String(z.attrs.tail))});const M=z=>{if(z.attrs.anchor)return z;let F="c"+Math.random().toString(36).slice(2,6);for(;L.has(F);)F="c"+Math.random().toString(36).slice(2,6);return L.add(F),z.type.create({...z.attrs,anchor:F},z.content)},k=m.filter(z=>!g.includes(z)).flatMap(z=>s(String(z.attrs.anchor)));if(g.length>=2)i.push({from:d,to:d+c.nodeSize,content:[c.type.create(c.attrs,g.map(M)),...k]});else{const z=[...k,...yc(n.schema,g,String(c.attrs.tail??""))];i.push({from:d,to:d+c.nodeSize,content:z.length?z:[r.create()]})}}),!i.length)return null;let a=n.tr;for(const c of i.sort((d,m)=>m.from-d.from))a=a.replaceWith(c.from,c.to,c.content);return a}}));function Hg(e,t,n,o=!1){const{state:r}=e,s=r.selection;if(!(s instanceof Me))return!1;const i=s.node;if(i.type.name==="amadeusColumnRow"||i.type.name==="amadeusColumnCell"||i.type.name==="amadeusCanvasCard"||r.doc.nodeAt(t)?.type.name==="amadeusCanvasCard"||t>=s.from&&t<s.to)return!1;const a=r.schema.nodes.amadeusColumnRow,c=r.schema.nodes.amadeusColumnCell;if(!a||!c)return!1;const d=i.type.name==="list_item"?s.$from.parent.type.create(s.$from.parent.attrs,i):i,m=r.doc.resolve(t);let g=null;if(m.depth>0){let F=-1;for(let J=m.depth;J>=1;J--)if(m.node(J).type===a){F=J;break}if(F<0||F!==1)return!1;g={rowPos:m.before(F),cellIndex:m.index(F)}}const C=new Set,L=()=>{let F=No(r.doc);for(;C.has(F);)F=No(r.doc);return C.add(F),F},M=L(),k=L();let z=r.tr;if(o||(z=z.delete(s.from,s.to)),g){const F=z.mapping.map(g.rowPos),J=z.doc.nodeAt(F);if(!J||J.type!==a)return!1;const se=n==="left"?g.cellIndex:g.cellIndex+1;let H=F+1;for(let ne=0;ne<Math.min(se,J.childCount);ne++)H+=J.child(ne).nodeSize;z=z.insert(H,c.create({anchor:k,width:1},d))}else{const F=z.mapping.map(t),J=z.doc.nodeAt(F);if(!J)return!1;const se=n==="left"?[c.create({anchor:k,width:1},d),c.create({anchor:M,width:1},J)]:[c.create({anchor:M,width:1},J),c.create({anchor:k,width:1},d)];z=z.replaceWith(F,F+J.nodeSize,a.create({tail:L()},se))}return z.setMeta("amxColumns",!0),e.dispatch(z.scrollIntoView()),!0}function Vg(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Me))return!1;const s=r.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell")return!1;const i=o.doc.nodeAt(t);if(!i||i.type.name!=="amadeusColumnRow"||!n&&r.from===t+i.nodeSize)return!1;const a=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s;let c=o.tr;return n||(c=c.delete(r.from,r.to)),c=c.insert(c.mapping.map(t+i.nodeSize),a),c.setMeta("amxColumns",!0),e.dispatch(c.scrollIntoView()),!0}function Wg(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Me))return!1;const s=r.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell"||s.type.name==="amadeusCanvasCard")return!1;const i=o.doc.resolve(t),a=i.parent;if(a.type.name!=="amadeusColumnCell")return!1;if(!n&&t>=r.from&&t<=r.to)return!0;const c=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s,d=a.childCount===1&&a.firstChild.type.name==="paragraph"&&a.firstChild.content.size===0;let m=o.tr;return n||(m=m.delete(r.from,r.to)),d?m=m.replaceWith(m.mapping.map(i.start()),m.mapping.map(i.end()),c):m=m.insert(m.mapping.map(t),c),m.setMeta("amxColumns",!0),e.dispatch(m.scrollIntoView()),!0}function nu(e,t,n,o){if(o.type.name==="amadeusCanvasCard")return!1;const{state:r}=e;if(r.doc.resolve(t).depth!==0)return!1;const s=r.schema.nodes.amadeusColumnRow,i=r.schema.nodes.amadeusColumnCell,a=r.schema.nodes.paragraph;if(!s||!i||!a)return!1;const c=new Set,d=()=>{let C=No(r.doc);for(;c.has(C);)C=No(r.doc);return c.add(C),C},m=s.create({tail:d()},[i.create({anchor:d(),width:1},o),i.create({anchor:d(),width:1},a.create())]);let g=r.tr.replaceWith(t,n,m);return g=g.setSelection(Ie.near(g.doc.resolve(t+m.nodeSize-3))),g.setMeta("amxColumns",!0),g.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(g.scrollIntoView()),!0}function ou(e,t,n,o=!1){const r=e.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnCell"||!(o||gc(r)))return null;const s=e.doc.resolve(t),i=s.parent;if(i.type.name!=="amadeusColumnRow")return null;const a=s.before(),c=s.after(),d=s.index(),m=[];i.forEach((J,se,H)=>{H!==d&&m.push(J)});const g=Gs(e.schema,String(r.attrs.anchor));if(m.length>=2){const J=e.tr.delete(t,t+r.nodeSize);return g.length&&J.insert(J.mapping.map(c),g),J.setSelection(Nr.near(J.doc.resolve(Math.min(t,J.doc.content.size)),n)),J.scrollIntoView()}const C=[...yc(e.schema,m,String(i.attrs.tail??"")),...g],L=e.tr.replaceWith(a,c,C),M=m[0],k=n<0?d>0:d>=m.length,z=k?M?.lastChild:M?.firstChild;let F=a;for(const J of C){if(J===z){L.setSelection(Nr.near(L.doc.resolve(k?F+J.nodeSize-1:F+1),k?-1:1));break}F+=J.nodeSize}return L.scrollIntoView()}function Yg(e,t){const{state:n}=e,o=n.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnRow")return!1;const r=[];o.forEach(g=>r.push(g));const s=yc(n.schema,r,String(o.attrs.tail??""),!0),i=s.length?s:[n.schema.nodes.paragraph.create()],a=n.selection;let c=null;n.doc.nodesBetween(t,t+o.nodeSize,(g,C,L)=>c||L?.type.name!=="amadeusColumnCell"?!c:(a.from>=C&&a.from<C+g.nodeSize&&(c={node:g,off:a.from-C,nodeSel:a instanceof Me&&a.from===C}),!1));const d=n.tr.replaceWith(t,t+o.nodeSize,i);let m=t;for(const g of i){const C=c;if(C&&g===C.node){d.setSelection(C.nodeSel?Me.create(d.doc,m):Nr.near(d.doc.resolve(m+C.off)));break}m+=g.nodeSize}return e.dispatch(d.scrollIntoView()),!0}const Xg=[Pg,Fg,qg].flat();gn({"docagent.instructions":{zh:"本页指令",en:"Page instructions"},"docagent.instructionsScope":{zh:"仅用于维护本页",en:"Applies to this page only"},"docagent.instructionsNested":{zh:"移到页面顶层后生效",en:"Move to the page top level to apply"},"docagent.instructionsPlaceholder":{zh:"写下维护本页时应遵循的要求…",en:"Describe how this page should be maintained…"},"docagent.task":{zh:"交办 Agent",en:"Agent task"},"docagent.prompt":{zh:"提示模板",en:"Prompt template"},"docagent.promptPlaceholder":{zh:"描述要让 Agent 完成的工作…",en:"Describe the work for the agent…"},"docagent.promptLabel":{zh:"任务内容",en:"Task prompt"},"docagent.agent":{zh:"选择 Agent",en:"Select agent"},"docagent.defaultAgent":{zh:"默认 Agent",en:"Default agent"},"docagent.assign":{zh:"交办",en:"Assign task"},"docagent.usePrompt":{zh:"使用提示",en:"Use prompt"},"docagent.open":{zh:"查看会话",en:"Open session"},"docagent.starting":{zh:"正在交办…",en:"Starting…"},"docagent.ready":{zh:"待交办",en:"Ready to assign"},"docagent.linked":{zh:"已关联会话",en:"Session linked"},"docagent.running":{zh:"处理中",en:"Working"},"docagent.waiting":{zh:"等待你回应",en:"Waiting for you"},"docagent.done":{zh:"本轮已完成",en:"Turn completed"},"docagent.failed":{zh:"执行遇到问题",en:"Run needs attention"},"docagent.startFailed":{zh:"交办失败,请重试",en:"Could not start. Please try again."},"docagent.noSession":{zh:"会话尚未关联,请重试",en:"No session was linked. Please try again."},"docagent.unavailable":{zh:"当前环境无法创建会话",en:"Sessions cannot be started in this environment"},"docagent.empty":{zh:"尚未填写内容",en:"No content yet"}});function Ug(e){return e.kind==="instructions"?f.jsx(Gg,{...e},e.pagePath):f.jsx(Jg,{...e},`${e.kind}:${e.pagePath}:${ks(e.src)?.id??"source"}`)}function Gg({src:e,readOnly:t=!1,activeInstructions:n=!0,onChange:o}){const{t:r}=Zt(),[s,i]=v.useState(e);return v.useEffect(()=>{i(e)},[e]),f.jsxs("section",{className:"am-doc-agent am-doc-agent-instructions","data-document-agent":"instructions","data-active":n,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(qm,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:r("docagent.instructions")}),f.jsx("span",{className:"am-doc-agent-hint",children:r(n?"docagent.instructionsScope":"docagent.instructionsNested")})]}),t?f.jsx("div",{className:"am-doc-agent-content",children:e||r("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":r("docagent.instructions"),rows:3,placeholder:r("docagent.instructionsPlaceholder"),value:s,onKeyDown:a=>a.stopPropagation(),onChange:a=>{i(a.target.value),o(a.target.value)}})]})}function Jg({kind:e,src:t,pagePath:n,readOnly:o=!1,onChange:r,onStart:s,onOpen:i}){const{t:a}=Zt(),c=v.useMemo(()=>ks(t),[t]),[d,m]=v.useState(c),[g,C]=v.useState(!1),[L,M]=v.useState(null),[k,z]=v.useState(null),[F,J]=v.useState("idle"),se=v.useRef(!1),H=v.useRef(!1),ne=Sr(),je=e==="task"?typeof ne?.submitDocumentTask=="function"&&ne.hostExecution?.()!==!1:typeof ne?.startChat=="function",[He,p]=v.useState(()=>ne?.agents?.()??[]),fe=e==="task"?c?.sessionId||(k?.id===c?.id?k?.sessionId:void 0):void 0,rt=o||g||!!fe;v.useEffect(()=>(se.current=!0,()=>{se.current=!1}),[]),v.useEffect(()=>{m(c),M(null)},[c]),v.useEffect(()=>{const pe=()=>{p(ne?.agents?.()??[])};return pe(),ne?.subscribeAgents?ne.subscribeAgents(pe):ne?.subscribe(pe)},[ne]),v.useEffect(()=>{if(J(fe?ne?.agentStatus?.(fe).phase??"idle":"idle"),!!fe)return ne?.subscribeAgentStatus?.(pe=>{pe.sessionId===fe&&J(pe.phase)},fe)},[ne,fe]);const ie=async()=>{if(!(o||!je||H.current||!d||!d.prompt.trim()||fe)){H.current=!0,C(!0),M(null);try{r(ps(d));const pe=await s(d,e==="prompt"?"prompt":"task");if(e==="task"&&!pe.sessionId)throw new Error(a("docagent.noSession"));se.current&&e==="task"&&pe.sessionId&&z({id:d.id,sessionId:pe.sessionId})}catch(pe){se.current&&M(pe instanceof Error?pe.message:a("docagent.startFailed"))}finally{H.current=!1,se.current&&C(!1)}}};if(!c||!d)return f.jsx("pre",{className:"am-doc-agent-source",children:f.jsx("code",{children:t})});const be=fe?F==="waiting"?"docagent.waiting":F==="done"?"docagent.done":F==="error"?"docagent.failed":F==="idle"?"docagent.linked":"docagent.running":"docagent.ready",me=g||!!fe&&["thinking","speaking","tool"].includes(F),Ee=e==="prompt"?ic:mf,Be=d.agent&&!He.some(pe=>pe.slug===d.agent);return f.jsxs("section",{className:"am-doc-agent","data-document-agent":e,"data-document-agent-id":d.id,"data-page-path":n,"aria-busy":g,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(Ee,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:a(e==="prompt"?"docagent.prompt":"docagent.task")}),e==="task"&&f.jsxs("span",{className:"am-doc-agent-status",role:"status","aria-live":"polite","data-phase":F,children:[me?f.jsx(Gc,{size:12,className:"am-doc-agent-spin","aria-hidden":"true"}):F==="done"?f.jsx(ea,{size:12,"aria-hidden":"true"}):null,a(g?"docagent.starting":be)]})]}),o||fe?f.jsx("div",{className:"am-doc-agent-content",children:d.prompt||a("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":a("docagent.promptLabel"),rows:3,placeholder:a("docagent.promptPlaceholder"),value:d.prompt,disabled:g,onKeyDown:pe=>pe.stopPropagation(),onChange:pe=>{const Ne={...d,prompt:pe.target.value};m(Ne),r(ps(Ne))}}),f.jsxs("div",{className:"am-doc-agent-footer",children:[rt?f.jsx("span",{className:"am-doc-agent-assignee",children:He.find(pe=>pe.slug===d.agent)?.name||d.agent||a("docagent.defaultAgent")}):f.jsxs("select",{className:"am-doc-agent-select","aria-label":a("docagent.agent"),value:d.agent??"",onKeyDown:pe=>pe.stopPropagation(),onChange:pe=>{const Ne={...d,agent:pe.target.value||void 0};m(Ne),r(ps(Ne))},children:[f.jsx("option",{value:"",children:a("docagent.defaultAgent")}),Be&&f.jsx("option",{value:d.agent,children:d.agent}),He.map(pe=>f.jsx("option",{value:pe.slug,children:pe.name},pe.slug))]}),fe?i&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",onClick:()=>i(fe),children:[f.jsx(gi,{size:14,"aria-hidden":"true"}),a("docagent.open")]}):!o&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",disabled:g||!je||!d.prompt.trim(),title:je?void 0:a("docagent.unavailable"),onMouseDown:pe=>pe.preventDefault(),onClick:()=>{ie()},children:[g?f.jsx(Gc,{size:14,className:"am-doc-agent-spin","aria-hidden":"true"}):f.jsx(gi,{size:14,"aria-hidden":"true"}),a(g?"docagent.starting":e==="prompt"?"docagent.usePrompt":"docagent.assign")]})]}),!o&&!fe&&!je&&f.jsx("div",{className:"am-doc-agent-hint",children:a("docagent.unavailable")}),L&&f.jsx("div",{className:"am-doc-agent-error",role:"alert",children:L})]})}function tc(e){const t=[];return e.forEach(n=>{if(n.type.name==="code_block"&&n.attrs.language==="forsion-instructions"){const o=n.textContent.trim();o&&t.push(o)}}),t.join(`
|
|
34
|
-
|
|
35
|
-
`).slice(0,12e3)}function ru(e,t){return e.trim()?`Page maintenance instructions for ${JSON.stringify(t)} (apply only when working on this page; the current user request takes precedence; do not grant permissions or inherit into other pages):
|
|
36
|
-
${e.slice(0,12e3)}
|
|
37
|
-
End of page maintenance instructions.`:""}gn({"uembed.openInTab":{zh:"在 Forsion 标签页中打开",en:"Open in a Forsion tab"},"uembed.openWithSystem":{zh:"用系统默认程序打开",en:"Open with the system default app"},"uembed.openPdfInTab":{zh:"在 Forsion 标签页中打开",en:"Open in a Forsion tab"},"uembed.open":{zh:"打开 ↗",en:"Open ↗"},"uembed.startAt":{zh:"起播时刻",en:"Start time"},"uembed.badAnchor":{zh:"锚点无效 · 从 0 秒起播",en:"Invalid anchor · playing from 0:00"},"uembed.badAnchorTip":{zh:"只认 #t=95 / #t=01:35 / #t=1:02:30(MM 与 SS 须两位)",en:"Only #t=95 / #t=01:35 / #t=1:02:30 are recognized (MM and SS must be two digits)"},"uembed.collapse":{zh:"收起",en:"Collapse"},"uembed.expand":{zh:"展开",en:"Expand"},"uembed.loadingPdf":{zh:"加载 PDF…",en:"Loading PDF…"},"uembed.crossNote":{zh:"跨笔记嵌入(只读)",en:"Cross-note embed (read-only)"},"uembed.badge":{zh:"↪ 嵌入",en:"↪ Embed"},"uembed.editAtSource":{zh:"去源头编辑",en:"Edit at the source"},"uembed.resolving":{zh:"解析中…",en:"Resolving…"},"uembed.embedMissing":{zh:"嵌入丢失:",en:"Embed missing: "},"uembed.create":{zh:"创建",en:"Create"},"uembed.createTip":{zh:"新建笔记「{name}」",en:"Create the note “{name}”"}});function su(){const[,e]=v.useState(0);return v.useEffect(()=>El(()=>e(t=>t+1)),[]),ke}const Zg=hf(()=>ed(()=>import("./PdfAnnotator-CW0wPWRB.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),tr=()=>{},au=/^!\[\[([^\]\n]+)\]\]$/,Qg=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,ey=/\.[a-z0-9]{1,8}$/i,ty=/\.db$/i,ny=/\.pdf$/i,oy=/^https?:\/\/\S+$/i;function rr(e){if(e.type.name==="code_block"){const g={"forsion-instructions":"instructions","forsion-task":"task","forsion-prompt":"prompt"}[e.attrs.language];return g&&(g==="instructions"||ks(e.textContent))?{k:"document-agent",type:g,src:e.textContent}:e.attrs.language===Hm?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!Rl(cu(e.textContent))?null:{k:"button",src:e.textContent}}if(e.type.name!=="paragraph")return null;const t=e.textContent.trim(),n=au.exec(t);if(!n)return oy.test(t)?{k:"bookmark",url:t}:null;const o=n[1],[r,s]=o.split("|"),i=r.trim();if(Qg.test(i))return null;const a=Ju(o);if(a)return{k:"web",url:a,w:ia(o)};if(!i.includes("#")&&ty.test(i))return{k:"db",name:i,view:s?.trim()||null};if(!i.includes("#")&&Zu(i))return{k:"draw",target:i};const c=Ba.getState().embedRenderers;if(Jc(c,o.trim()))return{k:"plugin",target:o.trim()};const d=i.includes("#")?_c(i)?.target??null:i;if(d&&Jc(c,d))return{k:"plugin",target:d};if(pf(i))return{k:"note",target:o};const m=_c(i);return m?{k:"file",name:m.target,fileKind:Qu.test(m.target)?"video":"audio",loc:m.loc,badAnchor:i.includes("#")&&!m.loc,w:ia(o)}:!i.includes("#")&&ey.test(i)?{k:"file",name:i,fileKind:ny.test(i)?"pdf":"other",w:ia(o)}:{k:"note",target:o}}function ry({name:e,fileKind:t,pagePath:n,loc:o,badAnchor:r,insertAfter:s}){const i=su(),a=kn(L=>L.files),c=kn(L=>L.openWikiLink),[d,m]=v.useState(!0),g=t==="pdf"?Dl(e,a,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!Qc()?f.jsxs("div",{className:"embed-file",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e})]}):f.jsxs("button",{className:"embed-file",onClick:()=>{/\.[a-z0-9]+\.md$/i.test(e)?c(e,n):bn.openAttachment(n,e)},title:/\.[a-z0-9]+\.md$/i.test(e)?i("uembed.openInTab"):i("uembed.openWithSystem"),children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e}),f.jsx("span",{className:"embed-file-open",children:i("uembed.open")})]});const C=Sl(e);return f.jsxs("div",{className:"embed-media",children:[f.jsxs("div",{className:"embed-media-head",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:t==="pdf"?"📕":t==="video"?"🎬":"🎵"}),f.jsx("span",{className:"embed-file-name",children:e}),o&&f.jsxs("span",{className:"embed-media-at",title:i("uembed.startAt"),children:["@",Bc(o.at),o.to?`–${Bc(o.to)}`:""]}),r&&f.jsx("span",{className:"embed-media-warn",title:i("uembed.badAnchorTip"),children:i("uembed.badAnchor")}),f.jsx("button",{className:"embed-media-btn",onClick:()=>m(L=>!L),children:i(d?"uembed.collapse":"uembed.expand")}),(t==="pdf"||Qc())&&f.jsx("button",{className:"embed-media-btn",title:i(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?c(e,n):bn.openAttachment(n,e)},children:i("uembed.open")})]}),d&&t==="pdf"&&(g?f.jsx("div",{className:"embed-pdf embed-pdf-live",children:f.jsx(v.Suspense,{fallback:f.jsx("div",{className:"embed-pdf-loading",children:i("uembed.loadingPdf")}),children:f.jsx(Zg,{pdfPath:g,embed:!0})})}):f.jsx("iframe",{className:"embed-pdf",src:C,title:e})),d&&(t==="video"||t==="audio")&&f.jsx(Sf,{kind:t,url:C,name:e,pagePath:n,loc:o??null,insertAfter:s})]})}function sy({target:e,pagePath:t,readOnly:n}){const o=su(),r=kn(F=>F.openWikiLink),s=kn(F=>F.loadPage),i=kn(F=>F.pages),a=kn(F=>F.linkGraphVersion),[c,d]=v.useState("loading"),{note:m,subpath:g}=rd(e),C=g?`${m}#${g}`:m;v.useEffect(()=>{let F=!0;return d("loading"),Promise.resolve(C?bn.resolveEmbed?.(C,t)??null:null).then(J=>{F&&d(J)}).catch(()=>{F&&d(null)}),()=>{F=!1}},[C,t,a]);const L=!n&&c===null&&!!m&&!hs(m,i,t),M=()=>{kn.getState().openWikiLink(m,t),kn.getState().pendingWikiCreate?.name===m&&kn.getState().confirmWikiCreate()},z=(c&&c!=="loading"?Cf(c.type):void 0)?.Editor;return f.jsxs("div",{className:"embed-body",children:[f.jsxs("div",{className:"embed-head",children:[f.jsx("span",{className:"embed-badge",title:o("uembed.crossNote"),children:o("uembed.badge")}),c&&c!=="loading"&&f.jsxs("button",{className:"embed-src",onClick:()=>{s(c.owner)},title:o("uembed.editAtSource"),children:[sd(c.owner)," ↗"]})]}),c==="loading"?f.jsx("div",{className:"embed-loading",children:o("uembed.resolving")}):c&&z?f.jsx(z,{blockId:"uembed",content:c.content,pagePath:c.owner,readOnly:!0,onChange:tr,onInsertAfter:tr,onDeleteEmpty:tr,onMergePrev:tr,onArrowOut:tr,onMoveDir:tr,focusPlace:null,onFocused:tr,requestSelfFocus:tr,onOpenWiki:(F,J)=>r(F,c.owner,J),getPageNames:()=>i}):f.jsxs("div",{className:"embed-missing",children:[o("uembed.embedMissing"),f.jsx("code",{children:e}),L&&f.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:o("uembed.createTip",{name:m}),onClick:M,children:o("uembed.create")})]})]})}function ay({kind:e,pagePath:t,replaceText:n,insertAfter:o,startTask:r,readOnly:s=!1}){const i=s?()=>{}:n;switch(e.k){case"document-agent":return f.jsx(Ug,{kind:e.type,src:e.src,pagePath:t,readOnly:s,activeInstructions:e.activeInstructions,onChange:i,onStart:r,onOpen:a=>Sr()?.openDocumentTask?.(a)});case"db":return f.jsx(kf,{target:e.name,pagePath:t,initialView:e.view??void 0,readOnly:s,onViewChange:a=>i(a?`![[${e.name}|${a}]]`:`![[${e.name}]]`)});case"draw":return f.jsx(wf,{target:e.target,pagePath:t,readOnly:s});case"plugin":return f.jsx(vf,{target:e.target,pagePath:t});case"file":return f.jsx(ry,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:s?()=>{}:o});case"note":return f.jsx(sy,{target:e.target,pagePath:t,readOnly:s});case"bookmark":return s?f.jsx(Zc,{url:e.url}):f.jsx(Zc,{url:e.url,onChangeUrl:a=>n(a),onEmbed:()=>n(`![[${od(e.url)}]]`)});case"web":return f.jsx(bf,{url:e.url,toCard:()=>i(e.url)});case"button":{const a=Rl(cu(e.src));return a?f.jsx(yf,{spec:a,readOnly:s,onChange:c=>i(cy(xf(c)))}):f.jsx("span",{})}case"sketch":return f.jsx(Vm,{items:[{callId:"note-sketch",html:e.src}]})}}function cu(e){return"```forsion-button\n"+e+"\n```"}function cy(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const Pi=(e,t)=>e.k==="db"?`db:${e.name}`:e.k==="document-agent"?`document-agent:${e.type}:${e.type==="instructions"?"":ks(e.src)?.id}`:`${e.k}:${t}`;function iy(e,t,n){let o=!0;return e.mapping.maps.forEach((r,s)=>{const i=e.mapping.slice(s+1);r.forEach((a,c,d,m)=>{(i.map(d,-1)<t||i.map(m,1)>n)&&(o=!1)})}),o}function ly(e){return[Et(()=>{const n=new Tn("UNIFIED_EMBED_LAYER"),o=new Map,r=new Set,s=(a,c,d,m,g=null)=>{const C=[],L=new Map,M=(k,z)=>{const F=rr(k);if(!F)return;F.k==="document-agent"&&(F.activeInstructions=a.resolve(z).depth===0);const J=Pi(F,k.textContent),se=L.get(J)??0;if(L.set(J,se+1),m===z&&d>z&&c<z+k.nodeSize||g===z)return;const H=`${J}#${se}`,ne=o.get(H),je=F.k==="document-agent"?`${F.activeInstructions}:${k.textContent}`:k.textContent;ne&&ne.text!==je&&(ne.text=je,ne.render(F)),C.push(co.inline(z+1,z+k.nodeSize-1,{class:"wikilink-src-hidden"})),C.push(co.node(z,z+k.nodeSize,{class:"unified-embed-host"})),C.push(co.widget(z+1,He=>{const p=o.get(H);if(p)return p.refs++,p.dom;const fe=document.createElement("div");fe.className="unified-embed",fe.contentEditable="false";const rt=Ne=>{let Ue=0,U=null;return Ne.state.doc.descendants((ce,$e)=>{if(U)return!1;const A=rr(ce);return A&&Pi(A,ce.textContent)===J?Ue===se?(U={at:$e,size:ce.nodeSize},!1):(Ue++,!1):!0}),U};fe.addEventListener("mousedown",Ne=>{if(Ne.button!==0)return;const Ue=Ne.target;if(Ue!==fe&&Ue.parentElement!==fe||Ue.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const U=i;if(!U)return;const ce=rt(U);ce&&(Ne.preventDefault(),Ne.stopPropagation(),U.dispatch(U.state.tr.setSelection(Me.create(U.state.doc,ce.at))),U.focus())});const ie=Ne=>{const Ue=i;if(!Ue)return;const U=rt(Ue);U&&Ue.dispatch(Ue.state.tr.insertText(Ne,U.at+1,U.at+U.size-1))},be=F.k==="web"||F.k==="file"&&F.fileKind!=="other",me=F.k==="web"||F.k==="file"?F.w:void 0;me&&(fe.style.width=`${me}px`);const Ee=document.createElement("div");if(Ee.className="unified-embed-body",fe.appendChild(Ee),be){const Ne=au.exec(k.textContent.trim())?.[1];Ne!==void 0&&gf(fe,fe,Ue=>ie(`![[${td(Ne,Ue)}]]`))}const Be=zm.createRoot(Ee),pe=Ne=>Be.render(f.jsx(nd,{children:f.jsx(ay,{kind:Ne,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:Ue=>{const U=i;if(!U)return;const ce=rt(U);if(!ce)return;const $e=U.state.schema.nodes.paragraph;if(!$e)return;const A=Ue.split(/\n{2,}/).map(Z=>$e.create(null,Z?U.state.schema.text(Z):null));U.dispatch(U.state.tr.insert(ce.at+ce.size,A))},startTask:async(Ue,U)=>{const ce=Sr(),$e=kn.getState().vaultRoot,A=i,Z=A&&rt(A);if(!Z)throw new Error(ke("documentTask.sourceGone"));const le={from:Z.at,to:Z.at+Z.size,deleted:!1};r.add(le);try{const ve=()=>{if(le.deleted||e.readOnly||!i||i!==A||e.alive?.()===!1||kn.getState().vaultRoot!==$e)return null;const it=i.state.doc.nodeAt(le.from);if(!it||le.from+it.nodeSize!==le.to)return null;const mt=rr(it);if(mt?.k!=="document-agent"||mt.type!==U)return null;const ct=it?ks(it.textContent):null;return ct?.id===Ue.id&&ct.prompt===Ue.prompt&&ct.agent===Ue.agent?ct:null};if(!ve()||!e.flush)throw new Error(ke("documentTask.sourceGone"));if(await e.flush(),!ve()||!i)throw new Error(ke("documentTask.sourceGone"));const Qe=ru(tc(i.state.doc),e.path),Ke=`${Ue.prompt.trim()}
|
|
38
|
-
|
|
39
|
-
Source note: ${JSON.stringify(e.path)}. Read the source note before editing it.
|
|
40
|
-
${Qe}`;if(U==="prompt"){const it=await ce?.startChat?.({agent:Ue.agent,prompt:Ke,send:!1,...ce?.hostExecution?.()&&$e?{cwd:$e}:{},alive:()=>!!ve()});if(!it?.ok)throw new Error(it?.error||ke("docagent.unavailable"));return{}}const $t=ve()?.sessionId;if($t)return{sessionId:$t};if(!$e||!ce?.submitDocumentTask)throw new Error(ke("docagent.unavailable"));const st=await ce.submitDocumentTask({key:`${$e}
|
|
41
|
-
${e.path}
|
|
42
|
-
${Ue.id}`,agent:Ue.agent,prompt:Ke,vaultRoot:$e,alive:()=>!!ve(),onCreated:async it=>{const mt=ve();if(!mt||mt.sessionId&&mt.sessionId!==it)throw new Error(ke("documentTask.sourceGone"));const ct=i;if(ct.dispatch(ct.state.tr.insertText(ps({...mt,sessionId:it}),le.from+1,le.to-1)),await e.flush(),ve()?.sessionId!==it)throw new Error(ke("documentTask.sourceGone"))}});if(!st.ok)throw new Error(st.error||ke("docagent.startFailed"));return{sessionId:st.sessionId}}finally{r.delete(le)}},replaceText:ie})}));return pe(F),_m(fe,He,()=>{const Ne=i;if(!Ne)return;const Ue=rt(Ne);if(!Ue)return;const U=Ne.state.tr.setSelection(Ie.near(Ne.state.doc.resolve(Ue.at+1)));U.setMeta(n,{sourcePos:Ue.at}),Ne.dispatch(U),Ne.focus()}),fe.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),o.set(H,{root:Be,dom:fe,text:je,render:pe,refs:1}),fe},{key:H,side:-1,ignoreSelection:!0,stopEvent:He=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(He.type),destroy:()=>{const He=o.get(H);He&&(He.refs--,!(He.refs>0)&&queueMicrotask(()=>{He.refs>0||o.get(H)!==He||(o.delete(H),He.root.unmount())}))}}))};return a.descendants((k,z)=>(M(k,z),!0)),cr.create(a,C)};let i=null;return new Ht({key:n,view:a=>(i=a,{destroy:()=>{for(const c of r)c.deleted=!0;i=null,queueMicrotask(()=>{if(!i){for(const[,c]of o)c.root.unmount();o.clear()}})}}),state:{init:(a,c)=>({decos:s(c.doc,c.selection.from,c.selection.to,null),sourcePos:null,pendingPos:null}),apply:(a,c,d,m)=>{for(const M of r)for(const k of a.mapping.maps){if(M.deleted)break;const z=k.mapResult(M.from,1),F=k.mapResult(M.to,-1);(z.deleted||F.deleted||z.pos>=F.pos)&&(M.deleted=!0),M.from=z.pos,M.to=F.pos}const g=a.getMeta(n);let C=c.sourcePos;if(C!=null&&a.docChanged&&(C=a.mapping.map(C)),g&&typeof g.sourcePos=="number")C=g.sourcePos;else if(C!=null&&a.selectionSet){const M=m.doc.nodeAt(C);(!M||m.selection.to<=C||m.selection.from>=C+M.nodeSize)&&(C=null)}let L=c.pendingPos;if(L!=null&&a.docChanged&&(L=a.mapping.map(L,-1)),g?.commit)L=null;else if(a.docChanged&&m.selection.empty&&!/^(paste|drop)$/.test(String(a.getMeta("uiEvent")??""))){const M=m.selection.$head,k=M.depth>0?M.before():-1;k>=0&&M.parent.type.name==="paragraph"&&rr(M.parent)?.k==="bookmark"&&iy(a,k+1,k+M.parent.nodeSize-1)&&(L=k)}if(L!=null){const M=m.doc.nodeAt(L),{from:k,to:z}=m.selection;(!M||M.type.name!=="paragraph"||z<L+1||k>L+M.nodeSize-1)&&(L=null)}return!a.docChanged&&!a.selectionSet&&!g&&L===c.pendingPos?{sourcePos:C,pendingPos:L,decos:c.decos.map(a.mapping,a.doc)}:{sourcePos:C,pendingPos:L,decos:s(m.doc,m.selection.from,m.selection.to,C,L)}}},props:{decorations(a){return n.getState(a)?.decos??null},handleDOMEvents:{blur:a=>(n.getState(a.state)?.pendingPos!=null&&a.dispatch(a.state.tr.setMeta(n,{commit:!0})),!1)}}})})].flat()}const uy=[Et(()=>_o({Enter:xd,"Shift-Enter":yd,"Mod-Enter":gd}))].flat();function na(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function xc(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:rr(e)!=null}function dy(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:rr(e)!=null}function Ho(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="list_item")return t;return null}function Cs(e,t){return _s(e,t)!=null?!0:Im(e).some(n=>t>n.start&&t<n.after)}function fy(e){let t=0;for(let n=e.depth;n>=1;n--)e.node(n).type.name==="list_item"&&t++;return t}function iu(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="blockquote")return t;return null}function Hr(...e){return(t,n,o)=>e.some(r=>r(t,n,o))}const my=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0||n.parent.type.name!=="heading")return!1;const r=n.before(n.depth);if(Xr(e,r)==null)return!1;const s=e.schema.nodes.paragraph;if(!s)return!1;const i=e.tr.split(n.pos,1,[{type:s}]);return i.setMeta(Yr,{toggle:r}),t?.(i.scrollIntoView()),!0},lu=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.type.name!=="heading")return!1;const r=e.schema.nodes.paragraph;if(!r)return!1;if(n.parentOffset===0){const i=n.before(n.depth),a=e.tr.insert(i,r.create());return a.setSelection(Ie.near(a.doc.resolve(i+1))),t?.(a.scrollIntoView()),!0}const s=e.tr.split(n.pos,1,[{type:r}]);return t?.(s.scrollIntoView()),!0},py=(e,t)=>{const n=e.selection;if(!(n instanceof Me)||!n.node.isTextblock||rr(n.node)!=null)return!1;const o=e.tr.setSelection(Ie.near(e.doc.resolve(n.to-1),-1));return t?.(o.scrollIntoView()),!0},hy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||!n||!t)return!1;const s=kd(o);return!s||!Cd(o.parent.type.name,s)?!1:Sd(n,s)},gy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.content.size!==0||Ho(n)==null)return!1;const r=e.schema.nodes.list_item;return r?zl(r)(e,t):!1},yy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=Ho(n);if(r==null||r!==n.depth-1||n.node(r).childCount<2||!uc(e,n.before(r)))return!1;const i=e.schema.nodes.list_item,a=e.schema.nodes.paragraph;if(!i||!a)return!1;const c=e.doc.slice(n.pos,n.end()).content,d=i.createAndFill(null,a.create(null,c));if(!d)return!1;let m=e.tr.delete(n.pos,n.end());const g=m.mapping.map(n.after(r));return m=m.insert(g,d),m.setSelection(Ie.near(m.doc.resolve(g+2))),t?.(m.scrollIntoView()),!0},xy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0)return!1;const r=Ho(n);if(r==null||r!==n.depth-1)return!1;const s=n.node(r);if(s.childCount<2||uc(e,n.before(r)))return!1;const i=s.child(1);if(!/_list$/.test(i.type.name))return!1;const a=e.schema.nodes.list_item,c=e.schema.nodes.paragraph;if(!a||!c)return!1;const d=n.pos,m=n.end(),g=e.doc.slice(d,m).content,C=n.before(r)+1+s.child(0).nodeSize+1,L=a.createAndFill(null,c.create(null,g));if(!L)return!1;let M=e.tr.delete(d,m);const k=M.mapping.map(C);return M=M.insert(k,L),M.setSelection(Ie.near(M.doc.resolve(k+2))),t?.(M.scrollIntoView()),!0},by=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=sc(n);if(!r||n.parentOffset!==n.parent.content.size)return!1;const s=e.tr.split(n.pos,1,[{type:n.parent.type,attrs:{...n.parent.attrs,indent:r}}]);return t?.(s.scrollIntoView()),!0},vy=(e,t,n)=>{const{$from:o,empty:r}=e.selection,s=Ho(o);if(s==null||o.node(s).attrs.checked!==!0)return!1;const i=e.schema.nodes.list_item;if(!i)return!1;if(r&&s===o.depth-1&&o.index(s)===0&&o.parentOffset===0&&o.parent.content.size>0){const g=i.createAndFill({...o.node(s).attrs,checked:!1});if(!g)return!1;if(!t)return!0;t(e.tr.insert(o.before(s),g).scrollIntoView());const C=n?n.root.getSelection?.():null;if(C&&C.rangeCount){const L=C.getRangeAt(0);C.removeAllRanges(),C.addRange(L)}return!0}if(!t)return Fa(i)(e);let a=null;if(!Fa(i)(e,g=>{a=g}))return!1;const c=a;if(!c)return!1;const d=c.selection.$from,m=Ho(d);return m!=null&&d.node(m).attrs.checked===!0&&c.setNodeMarkup(d.before(m),void 0,{...d.node(m).attrs,checked:!1}),t(c),!0},wy=e=>{const t=[];for(let n=0;;){const o=e.indexOf("$$",n);if(o<0)break;if(e[o+2]==="$"){n=o+3;continue}const r=e.indexOf("$$",o+2);if(r<0)break;t.push([o,r+2]),n=r+2}return t},uu=(e,t)=>{const{$from:n,$to:o}=e.selection;if(!n.sameParent(o)||!n.parent.isTextblock||n.parent.type.spec.code)return!1;const r=e.schema.nodes.hardbreak;if(!r||!n.parent.textContent.includes("$$"))return!1;const s=n.parentOffset,i=o.parentOffset;return wy(Bm(n.parent)).some(([a,c])=>s>=a+2&&i<=c-2)?(t?.(e.tr.replaceSelectionWith(r.create({isInline:!0}),!1).scrollIntoView()),!0):!1},ky=Hr(my,lu,py,uu,hy,gy,yy,xy,vy,by),Cy=(e,t)=>{const{$from:n}=e.selection,o=Ho(n),r=iu(n);if(o!=null&&(r==null||o>r)&&n.node(o).attrs.checked!=null){const m=vd(e,n.pos);return m?(t?.(m.scrollIntoView()),!0):!1}if(r!=null){const m=e.schema.nodes.hardbreak;return m?(t?.(e.tr.replaceSelectionWith(m.create(),!1).scrollIntoView()),!0):!1}const s=e.schema.nodes.list_item;if(s&&Ho(n)!=null)return Fa(s)(e,t);const i=e.schema.nodes.paragraph,a=na(n);if(!i||a<1)return!1;const c=n.after(a),d=e.tr.insert(c,i.create());return d.setSelection(Ie.near(d.doc.resolve(c+1))),t?.(d.scrollIntoView()),!0},Sy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0||n.parent.type.name!=="heading"||n.parent.content.size===0)return!1;const r=e.schema.nodes.paragraph;return r?(t?.(e.tr.setBlockType(n.start(),n.end(),r)),!0):!1},Ey=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=iu(n);if(r==null)return!1;if(n.index(r)===0){const C=n.before(r),L=e.doc.nodeAt(C);return!L||!Me.isSelectable(L)?!1:(t?.(e.tr.setSelection(Me.create(e.doc,C))),!0)}const i=n.before(r+1),a=n.after(r+1),c=n.after(r),d=e.doc.nodeAt(i);if(!d)return!1;let m=e.tr.delete(i,a);const g=m.mapping.map(c);return m=m.insert(g,d),m.setSelection(Ie.near(m.doc.resolve(g+1))),t?.(m.scrollIntoView()),!0},My=(e,t,n)=>{const{$from:o,empty:r}=e.selection;return!r||o.parentOffset!==0||!n||Ho(o)==null?!1:wd(n)},zy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=na(n);if(r<1||r!==n.depth)return!1;const s=n.before(r),a=e.doc.resolve(s).nodeBefore;if(!xc(a)||!a)return!1;const c=s-a.nodeSize;let d=e.tr;n.parent.content.size===0&&(d=d.delete(s,n.after(r)));const m=d.doc.nodeAt(c);return!m||!Me.isSelectable(m)||Cs(e,c)?!1:(d=d.setSelection(Me.create(d.doc,c)),t?.(d.scrollIntoView()),!0)},Ny=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=sc(n);if(!r)return!1;const s=n.before(n.depth);return t?.(e.tr.setNodeMarkup(s,void 0,{...n.parent.attrs,indent:r-1}).scrollIntoView()),!0},nc=e=>(t,n)=>{const{$from:o,empty:r}=t.selection;if(!r||o.depth<2||o.node(-1).type.name!=="amadeusColumnCell")return!1;const s=ou(t,o.before(-1),e);return s?(n?.(s),!0):!1},$y=Hr(nc(-1),Sy,Ey,My,Ny,zy),Ay=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||o.parentOffset!==0)return!1;if(sc(o)){const a=o.before(o.depth);return t?.(e.tr.setNodeMarkup(a,void 0,{...o.parent.attrs,indent:0}).scrollIntoView()),!0}const i=e.schema.nodes.list_item;if(!i||Ho(o)==null)return!1;if(!t||!n)return!0;for(let a=0;a<32&&!(fy(n.state.selection.$from)<=1||!zl(i)(n.state,c=>n.dispatch(c)));a++);return!0},Fi=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.type.name!=="heading"||n.parentOffset!==n.parent.content.size)return!1;const r=n.before(n.depth);return Xr(e,r)==null?!1:(t?.(e.tr.setMeta(Yr,{toggle:r})),!0)},Oi=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==n.parent.content.size)return!1;const r=na(n);if(r<1)return!1;const s=n.after(r),i=e.doc.resolve(s).nodeAfter;return!i||!xc(i)||!Me.isSelectable(i)||Cs(e,s)?!1:(t?.(e.tr.setSelection(Me.create(e.doc,s)).scrollIntoView()),!0)},Ty=/^\[![\w-]+\]/,_i=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||!n.parent.isTextblock||n.parentOffset!==n.parent.content.size||n.parent.type.name==="code_block"||n.depth<1)return!1;const r=M=>{for(let k=M.depth;k>0;k--)if(M.node(k).type.name==="table")return!0;return!1};if(r(n))return!1;const s=n.after(),i=Nr.findFrom(e.doc.resolve(s),1,!0);if(!(i instanceof Ie))return!1;const a=i.$from;if(a.parentOffset!==0||!a.parent.isTextblock||a.parent.type.name==="code_block"||r(a)||a.depth===n.depth&&a.before()===s||Cs(e,a.pos))return!1;const c=M=>{for(let k=M.depth;k>0;k--)if(M.node(k).type.spec.isolating)return M.before(k);return-1};if(c(n)!==c(a))return!1;let d=!1;if(e.doc.nodesBetween(s,a.before(),(M,k)=>(k>=s&&k+M.nodeSize<=a.before()&&(M.isLeaf||M.isTextblock)&&(d=!0),!d)),d)return!1;const m=a.depth>=2&&a.node(-1).type.name==="blockquote"&&a.index(-1)===0?a.before(-1):null;if(m!=null&&Ty.test(a.parent.textContent)){const M=e.doc.nodeAt(m);return!M||!Me.isSelectable(M)?!1:(t?.(e.tr.setSelection(Me.create(e.doc,m)).scrollIntoView()),!0)}const g=n.parent.textContent+a.parent.textContent,C=e.tr.delete(n.pos,a.pos),L=C.doc.resolve(C.mapping.map(n.pos));return!L.parent.isTextblock||L.parent.textContent!==g||C.doc.textContent!==e.doc.textContent?!1:(t?.(C.setSelection(Ie.create(C.doc,L.pos)).scrollIntoView()),!0)};function Bi(e){return(t,n,o)=>{const r=t.selection;if(!r.empty||!o||!o.endOfTextblock(e))return!1;const s=r.$from,i=na(s);if(i<1)return!1;const a=e==="down"?s.after(i):s.before(i),c=e==="down"?t.doc.resolve(a).nodeAfter:t.doc.resolve(a).nodeBefore;if(!dy(c)||!c)return!1;const d=e==="down"?a:a-c.nodeSize,m=t.doc.nodeAt(d);return!m||!Me.isSelectable(m)||Cs(t,d)?!1:(n?.(t.tr.setSelection(Me.create(t.doc,d)).scrollIntoView()),!0)}}function Ki(e){return(t,n,o)=>{const{$from:r,empty:s}=t.selection;if(!s||r.parent.type.name!=="code_block"||r.depth<1)return!1;const i=o?o.root.getSelection?.():null;if(o&&i?.anchorNode&&o.dom.contains(i.anchorNode))try{if(o.posAtDOM(i.anchorNode,i.anchorOffset)!==r.pos)return!1}catch{return!1}if(e==="down"?!o?.endOfTextblock("down"):r.parentOffset!==r.parent.content.size)return!1;const a=r.node(-1);if(r.index(-1)!==a.childCount-1)return!1;const c=t.schema.nodes.paragraph,d=r.after();if(!c||!a.canReplaceWith(r.index(-1)+1,r.index(-1)+1,c))return!1;if(!n)return!0;const m=t.tr.insert(d,c.create());return n(m.setSelection(Ie.create(m.doc,d+1)).scrollIntoView()),!0}}const jy=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
|
|
43
|
-
`).scrollIntoView()),!0);function qi(e){return(t,n)=>{const o=t.doc,r=e==="up"?o.firstChild:o.lastChild;if(!r)return!1;const s=e==="up"?0:o.content.size-r.nodeSize;return rr(r)!=null?!Me.isSelectable(r)||Cs(t,s)?!1:(n?.(t.tr.setSelection(Me.create(o,s)).scrollIntoView()),!0):r.type.name==="code_block"?(n?.(t.tr.setSelection(Ie.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):!1}}const Ry={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},Dy=Et(e=>new Ht({props:{handleTextInput:(t,n,o,r)=>{const s=Ry[r];if(!s||n===o)return!1;const i=t.state.selection;if(!(i instanceof Ie)||i.empty||!i.$from.sameParent(i.$to)||i.$from.parent.type.name==="code_block")return!1;if(r==="`"&&t.state.schema.marks.inlineCode)return e.get(Ef).call(bd.key);const a=t.state.tr.insertText(s,o).insertText(r,n);return a.setSelection(Ie.create(a.doc,n+1,o+1)),t.dispatch(a.scrollIntoView()),!0}}}));function Ea(e){const t=e.selection;if(!(t instanceof Me)||!t.node.isBlock)return null;const n=t.node,o=e.tr;if(n.type.name==="code_block")return o.setSelection(Ie.create(o.doc,t.to-1));if(n.type.name==="table"){const i=Nr.near(o.doc.resolve(t.from+1),1);return!(i instanceof Ie)||i.from>=t.to?null:o.setSelection(Ie.create(o.doc,i.$from.end()))}if(!xc(n)&&!n.isLeaf){const i=Nr.near(o.doc.resolve(t.to-1),-1);if(i instanceof Ie&&i.from>t.from&&i.to<t.to)return o.setSelection(i)}const r=e.schema.nodes.paragraph,s=t.$to;return!r||!s.parent.canReplaceWith(s.index(),s.index(),r)?null:(o.insert(t.to,r.create()),o.setSelection(Ie.create(o.doc,t.to+1)))}const Ly=Et(()=>new Ht({props:{handleDOMEvents:{keydown:(e,t)=>{if(!e.editable||t.metaKey||t.ctrlKey||!(t.key.length===1||t.key==="Process"||t.keyCode===229))return!1;const o=Ea(e.state);return o&&e.dispatch(o.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=Ea(e.state);return t&&e.dispatch(t),!1},beforeinput:(e,t)=>{const n=t;if(!e.editable||n.inputType!=="insertText"||!n.data)return!1;const o=Ea(e.state);if(!o)return!1;n.preventDefault();const{from:r,to:s}=o.selection;return e.dispatch(o.insertText(n.data,r,s).scrollIntoView()),!0}}}})),Hi=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Iy=[uy,Ly,Dy,Et(()=>_o({Enter:ky,"Shift-Enter":Hr(lu,jy,uu),"Mod-Enter":Cy,Backspace:$y,"Mod-Backspace":Ay,Delete:Hr(nc(1),Fi,Oi,_i),...Hi?{"Ctrl-d":Hr(nc(1),Fi,Oi,_i)}:{},ArrowUp:Bi("up"),ArrowDown:Hr(Ki("down"),Bi("down")),ArrowRight:Ki("right"),...Hi?{"Meta-ArrowUp":qi("up"),"Meta-ArrowDown":qi("down")}:{}}))].flat();gn({"blocklayer.dragHandle":{zh:"点击打开菜单,按住拖动",en:"Click for menu, hold to drag"},"blocklayer.addBelow":{zh:"在下方插入块(按住 Alt 点击插到上方)",en:"Add block below (Alt-click to add above)"},"blocklayer.cardGrab":{zh:"选中所在卡片,按住拖动整卡",en:"Select card, hold to drag it"},"blocklayer.expandChildren":{zh:"展开子项",en:"Expand children"},"blocklayer.foldChildren":{zh:"折叠子项",en:"Collapse children"},"blocklayer.expandSection":{zh:"展开小节",en:"Expand section"},"blocklayer.foldSection":{zh:"折叠小节",en:"Collapse section"},"blocklayer.phParagraph":{zh:"输入 '/' 唤起命令",en:"Type '/' for commands"},"blocklayer.phHeading":{zh:"标题 {n}",en:"Heading {n}"}});function Py(e,t,n,o){const{schema:r}=e,s=r.nodes.paragraph;if(!s)return null;const i=s.create(null,r.text("/"));let a=null;t.type.name==="list_item"?a=n:/_list$/.test(t.type.name)&&t.firstChild?.type.name==="list_item"&&(a=n+1);const c=a==null?null:e.doc.nodeAt(a);if(c&&a!=null){const m={...c.attrs,...c.attrs.checked!=null?{checked:!1}:{}},g=c.type.createAndFill(m,i);if(g){const C=o?a:a+c.nodeSize;return{at:C,node:g,caret:C+3}}}const d=o?n:n+t.nodeSize;return{at:d,node:i,caret:d+2}}function Pr(e){const t=e.offsetWidth;if(t<=0)return Ln(e);const n=Ln(e),o=e.getBoundingClientRect().width/t;return Math.abs(o-n)<.01?n:o}function Vi(e){return e.transform!=="none"||e.perspective!=="none"||e.filter!=="none"||e.backdropFilter&&e.backdropFilter!=="none"||e.containerType&&e.containerType!=="normal"||/\b(layout|paint|strict|content)\b/.test(e.contain??"")||e.contentVisibility==="auto"||e.contentVisibility==="hidden"?!0:/\b(transform|perspective|filter|backdrop-filter|contain)\b/.test(e.willChange??"")}function Fr(e){const t=n=>{const o=n.getBoundingClientRect(),r=getComputedStyle(n);return{x:o.left+(Number.parseFloat(r.borderLeftWidth)||0),y:o.top+(Number.parseFloat(r.borderTopWidth)||0)}};if(getComputedStyle(e).position==="absolute"){let n=e.offsetParent;for(let o=e.parentElement;!n&&o;o=o.parentElement){const r=getComputedStyle(o);(r.position!=="static"||Vi(r))&&(n=o)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(Vi(getComputedStyle(n)))return t(n);return{x:0,y:0}}const Ma=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||Nf(o=>o.type.name==="table"||o.type.name==="blockquote")(e))};function ts(e,t){try{const n=e.posAtCoords({left:t.x,top:t.y})?.inside;if(n==null||n<0)return null;let o=e.state.doc.resolve(n),r=e.state.doc.nodeAt(n),s=e.nodeDOM(n);const i=a=>{const c=o.depth>=1&&o.index(o.depth)===0&&!["amadeusColumnCell","amadeusCanvasCard"].includes(o.node(o.depth).type.name);if(!(a||c)||o.depth<1)return;const d=o.before(o.depth);r=e.state.doc.nodeAt(d),s=e.nodeDOM(d),o=e.state.doc.resolve(d),Ma(o,r)||i(!0)};if(i(!Ma(o,r)),!r||!Ma(o,r)||!(s instanceof HTMLElement))return null;if(o.depth>=1&&o.node(o.depth).type.name==="amadeusCanvasCard"){const a=o.before(o.depth),c=e.nodeDOM(a);if(c instanceof HTMLElement){const d=c.firstElementChild?.getBoundingClientRect(),m=c.lastElementChild?.getBoundingClientRect();if(d&&t.y<d.top||m&&t.y>m.bottom){const g=e.state.doc.nodeAt(a);if(g)return{node:g,pos:a,el:c}}}}return{node:r,pos:o.pos,el:s}}catch{return null}}function Wi(e){const{$from:t}=e.selection;for(let n=t.depth;n>=1;n--)if(t.node(n).type.name==="blockquote")return t.before(n);for(let n=t.depth;n>=1;n--){const o=t.node(n);if(Me.isSelectable(o)&&!(o.type.name==="paragraph"&&n>1))return t.before(n)}return null}function Fy(e){for(let t=e.parentElement;t;t=t.parentElement)if(/(auto|scroll)/.test(getComputedStyle(t).overflowY)&&t.scrollHeight>t.clientHeight)return t;return null}function Oy(e){let t=null,n=null;const o=new Tn("amx-block-selection-mode");let r=null,s=null;const i=y=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(y.dom.parentElement??document.body).appendChild(s)),s),a=(y,E,I)=>{const D=i(y),K=Pr(y.dom),X=Fr(D),oe=E.getBoundingClientRect(),G=(I==="left"?oe.left-6:oe.right+3)-X.x;D.style.display="block",D.style.height=`${oe.height/K}px`,D.style.transform=`translate(${Math.round(G/K)}px, ${Math.round((oe.top-X.y)/K)}px)`},c=()=>{s&&(s.style.display="none")},d=28,m=y=>/Mac/i.test(navigator.platform)?y.altKey:y.ctrlKey,g=y=>{const E=y.state.selection;if(!(E instanceof Ie)||E.empty||E.$from.sameParent(E.$to))return null;const I=X=>{let oe=X.depth;for(;oe>=1&&!["doc","amadeusColumnCell"].includes(X.node(oe-1).type.name);)oe--;return oe},D=I(E.$from),K=I(E.$to);return D<1||K<1||E.$from.node(D-1)!==E.$to.node(K-1)?null:{from:E.$from.before(D),to:E.$to.after(K)}},C=(y,E,I)=>{if(I.type.name!=="paragraph")return null;const D=y.state.doc.resolve(E),K=D.parent;if(!["doc","amadeusColumnCell"].includes(K.type.name))return null;const X=Number(I.attrs.indent??0),oe=D.index();let G=E+I.nodeSize,ee=0;for(let q=oe+1;q<K.childCount;q++){const ze=K.child(q);if(ze.type.name!=="paragraph"||Number(ze.attrs.indent??0)<=X)break;G+=ze.nodeSize,ee++}return ee?{from:E,to:G}:null};let L=null;const M=(y,E,I,D,K)=>{_r(y,E,{from:I.from,to:I.to,newStart:D,copy:K}),Zr(y,E,{from:I.from,to:I.to,newStart:D}),L===I.from&&E.doc.nodeAt(D)?.type.name==="heading"&&(E.setSelection(Me.create(E.doc,D)),L=null)},k=(y,E)=>{const{state:I}=y,D=I.doc.content.size,K=g(y);if(K){if(!E&&K.to===D)return!0;let q=I.doc.slice(K.from,K.to).content;if(E){const Oe=es(I.doc,q);q=Oe.content,Oe.minted.length&&e.onCardsMinted?.(Oe.minted)}let ze=I.tr;E||(ze=ze.delete(K.from,K.to));const Pe=ze.mapping.map(D);return ze=ze.insert(Pe,q),M(I,ze,K,Pe,E),ze.setMeta("amxColumns",!0),y.dispatch(ze.scrollIntoView()),!0}const X=I.selection;if(!(X instanceof Me))return!1;if(!E&&X.to===D)return!0;const oe=X.node,G=oe.type.name==="list_item"?X.$from.parent.type.create(X.$from.parent.attrs,oe):oe;let ee=I.tr;return E||(ee=ee.delete(X.from,X.to)),ee=ee.insert(ee.mapping.map(D),G),ee.setMeta("amxColumns",!0),y.dispatch(ee.scrollIntoView()),!0},z=(y,E,I)=>{const D=g(y);if(!D)return!1;const K=le(y,E.clientY);if(!K)return!1;const X=K.el.getBoundingClientRect(),oe=E.clientY>X.top+X.height/2?K.pos+K.node.nodeSize:K.pos;if(oe>=D.from&&oe<=D.to)return!0;let G=y.state.doc.slice(D.from,D.to).content;if(I){const ze=es(y.state.doc,G);G=ze.content,ze.minted.length&&e.onCardsMinted?.(ze.minted)}$t(y,oe);let ee=y.state.tr;I||(ee=ee.delete(D.from,D.to));const q=ee.mapping.map(oe);return ee=ee.insert(q,G),M(y.state,ee,D,q,I),ee.setMeta("amxColumns",!0),y.dispatch(ee.scrollIntoView()),!0},F=(y,E,I)=>{const{state:D}=y,K=D.selection;if(!(K instanceof Me))return!1;const X=D.doc.nodeAt(E);if(!X||X.type.name!=="list_item"||E>=K.from&&E<K.to)return!1;const oe=D.schema.nodes.list_item,G=D.schema.nodes.bullet_list;if(!oe||!G)return!1;const ee=K.node;if(ee.type.name==="amadeusColumnRow"||ee.type.name==="amadeusColumnCell")return!1;const q=ee.type.name==="list_item"?ee:oe.createAndFill(null,ee);if(!q)return!1;const ze=X.child(X.childCount-1),Pe=X.childCount>1&&/_list$/.test(ze.type.name);let Oe=D.tr;I||(Oe=Oe.delete(K.from,K.to));const _e=Oe.mapping.map(E),qe=Oe.doc.nodeAt(_e);if(!qe||qe.type.name!=="list_item")return!1;const Xe=Pe?_e+qe.nodeSize-2:_e+qe.nodeSize-1;return Oe=Oe.insert(Xe,Pe?q:(ze.type.name.endsWith("_list")?ze.type:G).create(null,q)),Oe.setMeta("amxColumns",!0),y.dispatch(Oe.scrollIntoView()),!0},J=y=>!!y.dom.closest(".unified-body")?.classList.contains("amx-canvas"),se=(y,E,I,D)=>{let K=I;for(let X=0;X<E.childCount;X++){const oe=E.child(X),G=y.nodeDOM(K),ee=G instanceof HTMLElement?G.getBoundingClientRect():null;if(ee&&D.clientY<=ee.bottom)return D.clientY>ee.top+ee.height/2?K+oe.nodeSize:K;K+=oe.nodeSize}return K},H=(y,E)=>{const I=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;let K=0;for(let X=0;X<I.childCount;X++){const oe=I.child(X);if(oe.type===D)return K;const G=y.nodeDOM(K),ee=G instanceof HTMLElement?G.getBoundingClientRect():null;if(ee&&E.clientY<=ee.bottom)return E.clientY>ee.top+ee.height/2?K+oe.nodeSize:K;K+=oe.nodeSize}return K},ne=(y,E,I)=>{const D=y.state.selection;if(!(D instanceof Me))return!1;const K=y.state.schema.nodes.amadeusCanvasCard;if(!K)return!1;const X=E.target;if(!X||!y.dom.contains(X))return!1;if(D.node.type===K)return!0;const oe=X.closest?.(".amx-ucard");let G;if(oe){let q;try{q=y.posAtDOM(oe,0)-1}catch{return!1}const ze=y.state.doc.nodeAt(q);if(ze?.type!==K)return!1;G=se(y,ze,q+1,E)}else G=H(y,E);if(G>=D.from&&G<=D.to)return!0;let ee=y.state.tr;return I||(ee=ee.delete(D.from,D.to)),ee=ee.insert(ee.mapping.map(G),D.node),ee.setMeta("amxColumns",!0),y.dispatch(ee.scrollIntoView()),!0},je=y=>{const E=y.state.schema.nodes.amadeusCanvasCard,I=[];return E&&y.state.doc.forEach((D,K,X)=>{D.type===E&&I.push({anchor:String(D.attrs.anchor),idx:X,pos:K,size:D.nodeSize})}),I},He=(y,E)=>{const I=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;if(!D)return null;const K=e.canvasTree?.()??{},X=je(y),oe=new Map;for(let _e=0;_e<X.length;){const qe=Us(X,_e,K);oe.set(_e,qe),_e=qe}const G=_e=>{const qe=y.nodeDOM(_e);return qe instanceof HTMLElement?qe:null},ee=[];let q=0,ze=0,Pe=-1;for(let _e=0;_e<I.childCount;_e++){const qe=I.child(_e);if(q<Pe){qe.type===D&&ze++,q+=qe.nodeSize;continue}if(qe.type===D){const Xe=oe.get(ze);if(Xe!=null){const Ve=X[Xe-1];ee.push({from:q,to:Ve.pos+Ve.size,firstEl:G(q),lastEl:G(Ve.pos)})}ze++}else{let Xe=q+qe.nodeSize,Ve;if(qe.type.name==="heading"&&gr(y,q)==="folded"){const Ge=Xr(y.state,q);Ge!=null&&(Xe=Ge,Pe=Ge,Ve=q)}ee.push({from:q,to:Xe,firstEl:G(q),lastEl:G(q),foldPos:Ve})}q+=qe.nodeSize}let Oe=null;for(let _e=0;_e<ee.length;_e++){const qe=ee[_e];if(!qe.firstEl||!qe.lastEl)continue;const Xe=qe.firstEl.getBoundingClientRect().top,Ve=qe.lastEl.getBoundingClientRect().bottom;if(Oe={at:qe.to,lineEl:qe.lastEl,edge:"bottom",expandFold:qe.foldPos},E.clientY>Ve)continue;const Ge=_e>0?ee[_e-1]:null;return E.clientY<=(Xe+Ve)/2?{at:qe.from,lineEl:qe.firstEl,edge:"top",expandFold:Ge&&Ge.foldPos!=null&&Ge.to===qe.from?Ge.foldPos:void 0}:Oe}return Oe},p=(y,E)=>{const I=y.state.selection,D=y.state.schema.nodes.amadeusCanvasCard;if(!D||!(I instanceof Me)||I.node.type!==D)return null;const K=He(y,E);if(!K)return null;const X=e.canvasTree?.()??{},oe=je(y),G=oe.findIndex(ze=>ze.pos===I.from);if(G<0)return null;const ee=oe[Us(oe,G,X)-1],q={from:I.from,to:ee.pos+ee.size};return{drop:K,range:q,self:K.at>=q.from&&K.at<=q.to}},fe=(y,E,I)=>{const D=y.state.selection,K=y.state.schema.nodes.amadeusCanvasCard;if(!K||!(D instanceof Me)||D.node.type!==K)return!1;const X=p(y,E);if(!X||X.self)return!0;let oe=y.state.doc.slice(X.range.from,X.range.to).content;if(I){const ee=es(y.state.doc,oe);oe=ee.content,ee.minted.length&&e.onCardsMinted?.(ee.minted)}X.drop.expandFold!=null&&gr(y,X.drop.expandFold)==="folded"&&Ts(y,X.drop.expandFold);let G=y.state.tr;if(I||(G=G.delete(X.range.from,X.range.to)),G=G.insert(G.mapping.map(X.drop.at),oe),G.setMeta("amxColumns",!0),y.dispatch(G.scrollIntoView()),!I){const ee=String(D.node.attrs.anchor),ze=(e.canvasTree?.()??{})[ee];typeof ze=="string"&&je(y).some(Pe=>Pe.anchor===ze)&&e.onCardDetach?.([ee])}return!0};let rt=null,ie=null,be=null,me=null,Ee=!1,Be=!1,pe=null;const Ne=y=>(pe&&pe.isConnected||(pe=document.createElement("div"),pe.className="unified-drop-line",pe.style.display="none",pe.style.animation="none",(y.dom.parentElement??document.body).appendChild(pe)),pe),Ue=(y,E,I=0,D="bottom")=>{const K=Ne(y),X=Pr(y.dom),oe=Fr(K),G=E.getBoundingClientRect(),ee=D==="top"?G.top-6:G.bottom+6;K.style.display="block",K.style.width=`${Math.max(0,G.width-I)/X}px`,K.style.transform=`translate(${Math.round((G.left+I-oe.x)/X)}px, ${Math.round((ee-oe.y)/X)}px)`},U=()=>{pe&&(pe.style.display="none")},ce=(y,E)=>{const I=y.state.doc.resolve(E);if(I.depth===0)return y.state.doc.nodeAt(E)?.type.name!=="amadeusCanvasCard";for(let D=I.depth;D>=1;D--)if(I.node(D).type.name==="amadeusColumnRow")return D===1;return!1},$e=y=>y instanceof HTMLElement&&y.getClientRects().length>0,A=(y,E)=>{if(J(y))return null;const I=y.state.selection,D=I instanceof Me?{from:I.from,to:I.to}:g(y);if(!D)return null;const K=E.target instanceof Element?E.target.closest("blockquote"):null;if(!(K instanceof HTMLElement)||!y.dom.contains(K))return null;let X;try{X=y.posAtDOM(K,0)-1}catch{return null}const oe=y.state.doc.nodeAt(X);if(oe?.type.name!=="blockquote"||y.nodeDOM(X)!==K)return null;const G=y.state.doc.slice(D.from,D.to).content;let ee=!1;if(G.descendants(_e=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(_e.type.name)&&(ee=!0)}),ee)return null;const q=!!oe.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(oe.firstChild.textContent),ze=y.nodeDOM(X+1);if(q&&$e(ze)){const _e=ze.getBoundingClientRect();if(E.clientY<_e.top+_e.height/2)return null}let Pe=null;if(oe.forEach((_e,qe)=>{const Xe=X+1+qe,Ve=y.nodeDOM(Xe);if(!$e(Ve))return;const Ge=Ve.getBoundingClientRect(),Xt=E.clientY<Ge.top+Ge.height/2?"top":"bottom",Mt=Math.abs(E.clientY-(Xt==="top"?Ge.top:Ge.bottom));(!Pe||Mt<Pe.distance)&&(Pe={at:Xt==="top"?Xe:Xe+_e.nodeSize,lineEl:Ve,edge:Xt,distance:Mt})}),!Pe)return null;const Oe=Pe;return{...Oe,self:Oe.at>=D.from&&Oe.at<=D.to}},Z=(y,E,I)=>{const D=A(y,E);if(!D)return!1;if(D.self)return!0;const{state:K}=y,X=K.selection,oe=X instanceof Me?{from:X.from,to:X.to}:g(y);if(!oe)return!1;const G=X instanceof Me&&X.node.type.name==="list_item"?zo.from(X.$from.parent.type.create(X.$from.parent.attrs,X.node)):K.doc.slice(oe.from,oe.to).content,ee=I?K.tr:K.tr.delete(oe.from,oe.to),q=ee.mapping.map(D.at),ze=ee.doc.resolve(q);return ze.parent.type.name!=="blockquote"||!ze.parent.canReplace(ze.index(),ze.index(),G)?!1:(ee.insert(q,G),M(K,ee,oe,q,I),Vs(ee,q,q+G.size),ee.setSelection(G.childCount===1&&Me.isSelectable(G.firstChild)?Me.create(ee.doc,q):Ie.between(ee.doc.resolve(q),ee.doc.resolve(q+G.size))),ee.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),y.dispatch(ee.scrollIntoView()),y.focus(),!0)},le=(y,E)=>{const I=y.state.doc;let D=null,K=1/0;for(let X=0,oe=0;X<I.childCount;oe+=I.child(X).nodeSize,X++){const G=y.nodeDOM(oe);if(!$e(G))continue;const ee=G.getBoundingClientRect(),q=E<ee.top?ee.top-E:E>ee.bottom?E-ee.bottom:0;if(q===0)return{pos:oe,node:I.child(X),el:G};q<K&&(K=q,D={pos:oe,node:I.child(X),el:G})}return D},ve=(y,E)=>{const I=y.state.selection,D=m(E),K=X=>!D&&I instanceof Me&&X>=I.from&&X<=I.to;for(const X of y.dom.querySelectorAll(":scope > .amx-ucolrow")){const oe=X.getBoundingClientRect();if(!(E.clientY<oe.top||E.clientY>oe.bottom||E.clientX<oe.left||E.clientX>oe.right)){for(const G of Array.from(X.children)){if(!$e(G)||!("amxColcell"in G.dataset))continue;const ee=G.getBoundingClientRect();if(!(E.clientX<ee.left||E.clientX>ee.right))try{const q=y.posAtDOM(G,0)-1,ze=y.state.doc.nodeAt(q);if(ze?.type.name!=="amadeusColumnCell")return null;let Pe=q+1,Oe=null;for(let _e=0;_e<ze.childCount;_e++){const qe=ze.child(_e),Xe=y.nodeDOM(Pe);if($e(Xe)){const Ve=Xe.getBoundingClientRect();if(E.clientY<=Ve.bottom){if(E.clientY>=Ve.top&&(!qe.isTextblock&&!qe.isAtom||E.clientX<=Ve.left+d||E.clientX>=Ve.right-d))return null;const Ge=E.clientY<=Ve.top+Ve.height/2,Xt=Ge?Pe:Pe+qe.nodeSize;return{cellEl:G,lineEl:Xe,pos:Pe,edge:Ge?"top":"bottom",tail:!1,self:K(Xt)}}Oe=Xe}Pe+=qe.nodeSize}return Oe?{cellEl:G,lineEl:Oe,pos:q,edge:"bottom",tail:!0,self:K(q+ze.nodeSize-1)}:null}catch{return null}}return null}}return null},Qe=(y,E)=>{if(!E.cellEl.isConnected||!E.lineEl.isConnected)return null;try{if(E.tail){const K=y.posAtDOM(E.cellEl,0)-1,X=y.state.doc.nodeAt(K);return X?.type.name==="amadeusColumnCell"?K+X.nodeSize-1:null}const I=y.state.doc.nodeAt(E.pos);if(!I||y.nodeDOM(E.pos)!==E.lineEl)return null;const D=E.edge==="top"?E.pos:E.pos+I.nodeSize;return y.state.doc.resolve(D).parent.type.name==="amadeusColumnCell"?D:null}catch{return null}},Ke=(y,E)=>{try{const I=y.state.doc.resolve(E),D=I.parent;let K=I.start();for(let X=0;X<D.childCount&&K<E;X++){const oe=D.child(X);if(oe.type.name==="heading"&&gr(y,K)==="folded"){const G=Xr(y.state,K);if(G!=null&&E>K&&E<=G)return K}K+=oe.nodeSize}}catch{}return null},$t=(y,E)=>{for(let I=Ke(y,E),D=-1;I!=null&&I!==D;D=I,I=Ke(y,E))Ts(y,I)};let st=null;const it=()=>{st&&(st.style.display="none")};let mt=!1,ct=!1;const un=()=>{ct||(ct=!0,mt=!1,queueMicrotask(()=>{ct=!1,mt||it()}))},ut=Et(()=>new Ht({key:new Tn("UNIFIED_BLOCK_HANDLE"),view:y=>{t=y,pi.add(y);const E=y.dom.parentElement??document.body,I=E.closest(".unified-body")??E,D=T=>{for(const P of I.querySelectorAll(".amx-ucard.amx-droptarget"))P.classList.remove("amx-droptarget");T?.classList.add("amx-droptarget")},K=document.createElement("div");K.className="unified-gutter",K.dataset.show="false";const X=()=>{K.dataset.show="false",n=null},oe=T=>{if(!y.editable)return;n=T,Mt(T),Ze.style.display=Un(T)?"":"none";const P=Pr(y.dom),ue=Fr(K),ge=hi(T.el),Ae=ge.getBoundingClientRect(),Q=(T.el.tagName==="LI"&&/^(UL|OL)$/.test(T.el.parentElement?.tagName??"")?T.el.parentElement:null)?.getBoundingClientRect().left??Ae.left,Je=getComputedStyle(ge),ft=Number.parseFloat(Je.lineHeight)||24,kt=(Number.parseFloat(Je.paddingTop)||0)+Math.max(0,(ft-24)/2),Ut=Ae.height/P,zt=Math.max(24,Ut-16),Tt=zt>24?zt/2-4-kt:0;K.dataset.show="true",K.style.setProperty("--amx-block-h",`${Ut}px`),K.style.setProperty("--amx-block-grow-y",`${Tt}px`);const Kn=K.offsetWidth||52;K.style.top=`${(Ae.top-ue.y)/P+kt}px`;let pt=(Q-ue.x)/P-Kn-8;Kr()&&(pt=Math.max(pt,(2-ue.x)/P-G.offsetLeft)),K.style.left=`${pt}px`},G=document.createElement("button");G.type="button",G.className="drag-handle",G.textContent="⠿",G.draggable=!0,G.title=ke("blocklayer.dragHandle"),G.setAttribute("aria-label",G.title),G.addEventListener("click",T=>{T.stopPropagation();const P=G.getBoundingClientRect();if(T.detail===0&&t&&n){const ue=t.state.selection;ue instanceof Me&&ue.from<=n.pos&&n.pos+n.node.nodeSize<=ue.to||ee(t,n)}e.onMenu({x:P.left,y:P.bottom+4,keyboard:T.detail===0}),Kr()||t?.focus()}),K.addEventListener("mousedown",()=>{t&&n&&ee(t,n)});const ee=(T,P)=>{const ue=T.state.selection,ge=P.pos+1,Ae=P.pos+P.node.nodeSize-1;if(ue instanceof Ie&&!ue.empty&&!ue.$from.sameParent(ue.$to)&&ue.from<=ge&&ue.to>=Ae){T.focus();return}const Re=C(T,P.pos,P.node);if(Re){const Q=T.state.doc;T.dispatch(T.state.tr.setSelection(Ie.between(Q.resolve(Re.from+1),Q.resolve(Re.to-1))).setMeta(o,!0)),T.focus();return}Me.isSelectable(P.node)&&(T.dispatch(T.state.tr.setSelection(Me.create(T.state.doc,P.pos))),T.focus())};let q=null;const ze=()=>{const T=t,P=n;if(!T||!P)return;(!q||!q.isConnected)&&(q=document.createElement("div"),q.className="unified-press-rect",(T.dom.parentElement??document.body).appendChild(q));const ue=Pr(T.dom),ge=Fr(q),Ae=hi(P.el).getBoundingClientRect(),Re=g(T);let Q={left:Ae.left-ge.x,top:Ae.top-ge.y,right:Ae.right-ge.x,bottom:Ae.bottom-ge.y};if(Re)for(const Je of Array.from(T.dom.children)){if(!Je.classList.contains("amx-block-selected"))continue;const ft=Je.getBoundingClientRect();Q={left:Math.min(Q.left,ft.left-ge.x),top:Math.min(Q.top,ft.top-ge.y),right:Math.max(Q.right,ft.right-ge.x),bottom:Math.max(Q.bottom,ft.bottom-ge.y)}}Object.assign(q.style,{display:"block",transform:`translate(${Math.round((Q.left-4)/ue)}px, ${Math.round((Q.top-4)/ue)}px)`,width:`${(Q.right-Q.left+8)/ue}px`,height:`${(Q.bottom-Q.top+8)/ue}px`})},Pe=()=>{q&&(q.style.display="none")};K.addEventListener("mousedown",ze),window.addEventListener("mouseup",Pe);const Oe=(T,P,ue)=>{T.dom.dataset.dragging="true";let ge=T.state.selection;if(L=null,ge instanceof Me&&gr(T,ge.from)==="folded"){const Re=ge.from,Q=Xr(T.state,Re),Je=T.state.doc;if(Q!=null){T.dispatch(T.state.tr.setSelection(Ie.between(Je.resolve(Re+1),Je.resolve(Q-1))).setMeta(o,!0));const ft=g(T);ft&&ft.from===Re&&ft.to===Q?L=Re:T.dispatch(T.state.tr.setSelection(Me.create(T.state.doc,Re)))}L==null&&Ts(T,Re),ge=T.state.selection}ge instanceof Me&&js(T,ge.from)==="folded"&&ha(T,ge.from);const Ae=ge instanceof Ie&&!ge.empty&&!ge.$from.sameParent(ge.$to);if(P.dataTransfer&&(ge instanceof Me||Ae)){const Re=ge.content();P.dataTransfer.effectAllowed="copyMove";const{dom:Q,text:Je}=T.serializeForClipboard(Re);P.dataTransfer.clearData(),P.dataTransfer.setData("text/html",Q.innerHTML),P.dataTransfer.setData("text/plain",Je),ue&&P.dataTransfer.setDragImage(ue,0,0),T.dragging={slice:Re,move:!0}}};K.addEventListener("dragstart",T=>{t&&Oe(t,T,n?.el??null)});const _e=T=>{const P=t;if(!P||!(T.target instanceof Node)||!P.dom.contains(T.target)||!T.target.closest?.(".wiki-inline-img-wrap"))return;const ue=Km(T.target);let ge=-1;try{ue&&(ge=P.posAtDOM(ue,0)-1)}catch{}const Ae=ue?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),Re=Ae?ts(P,{x:Ae.left+Ae.width/2,y:Ae.top+Ae.height/2}):null;if(!ue||!T.dataTransfer||P.nodeDOM(ge)!==ue||!Re||ge<Re.pos||ge>=Re.pos+Re.node.nodeSize){T.preventDefault();return}T.stopPropagation(),ee(P,Re),Oe(P,T,null),T.target.addEventListener("dragend",qe,{once:!0})};I.addEventListener("dragstart",_e,!0);const qe=()=>{const T=t;if(T&&L!=null){const P=g(T);P&&P.from===L&&T.state.doc.nodeAt(L)?.type.name==="heading"&&T.dispatch(T.state.tr.setSelection(Me.create(T.state.doc,L))),L=null}Pe(),D(null),r=null,be=null,me=null,ie=null,Be=!1,Ee=!1,c(),U(),it(),T&&(T.dom.dataset.dragging="false",T.dragging=null)};K.addEventListener("dragend",qe);const Xe=document.createElement("button");Xe.type="button",Xe.className="block-add block-fold",Xe.textContent="▾",Xe.style.display="none";const Ve=T=>{const P=t;return P?js(P,T.pos)?T.pos:/_list$/.test(T.node.type.name)&&js(P,T.pos+1)?T.pos+1:null:null},Ge=T=>{const P=t;return P?gr(P,T.pos)?T.pos:!T.node.isTextblock&&T.node.childCount>0&&gr(P,T.pos+1)?T.pos+1:null:null},Xt=T=>!t||!T?null:Ge(T)!=null?"heading":Ve(T)!=null?"list":null,Mt=T=>{const P=t,ue=Xt(T),ge=T?Ve(T):null,Ae=T?Ge(T):null,Re=!P||!T||!ue?null:ue==="heading"?Ae==null?null:gr(P,Ae):ge==null?null:js(P,ge);Xe.style.display=Re?"":"none",Xe.textContent=Re==="folded"?"▸":"▾",Xe.title=ue==="list"?Re==="folded"?ke("blocklayer.expandChildren"):ke("blocklayer.foldChildren"):Re==="folded"?ke("blocklayer.expandSection"):ke("blocklayer.foldSection"),Xe.setAttribute("aria-label",Xe.title),Xe.setAttribute("aria-expanded",String(Re!=="folded"))};Xe.addEventListener("click",T=>{T.stopPropagation();const P=t,ue=n;if(!P||!ue)return;const ge=Xt(ue)==="list"?Ve(ue):null;if(ge!=null)ha(P,ge);else{const Ae=Ge(ue);if(Ae==null)return;Ts(P,Ae)}Mt(ue)});const wt=document.createElement("button");wt.type="button",wt.className="block-add",wt.textContent="+",wt.title=ke("blocklayer.addBelow"),wt.setAttribute("aria-label",wt.title),wt.addEventListener("click",T=>{T.stopPropagation();const P=t,ue=n;if(!P||!ue)return;const ge=Py(P.state,ue.node,ue.pos,T.altKey);if(!ge)return;P.focus();let Ae=P.state.tr.insert(ge.at,ge.node);Ae=Ae.setSelection(Ie.create(Ae.doc,ge.caret)).scrollIntoView(),Ed(P,ge.caret),P.dispatch(Ae),X()});const Ze=document.createElement("button");Ze.type="button",Ze.className="card-grab",Ze.textContent="❏",Ze.draggable=!0,Ze.title=ke("blocklayer.cardGrab"),Ze.setAttribute("aria-label",Ze.title),Ze.style.display="none";const Un=T=>{const P=t;if(!P||!T||T.node.type.name==="amadeusCanvasCard")return null;try{const ue=P.state.doc.resolve(T.pos);for(let ge=ue.depth;ge>=1;ge--){if(ue.node(ge).type.name!=="amadeusCanvasCard")continue;const Ae=ue.before(ge),Re=P.state.doc.nodeAt(Ae),Q=P.nodeDOM(Ae);return Re&&Q instanceof HTMLElement?{node:Re,pos:Ae,el:Q}:null}}catch{}return null};Ze.addEventListener("mousedown",T=>{const P=t,ue=Un(n);!P||!ue||(T.stopPropagation(),n=ue,P.dispatch(P.state.tr.setSelection(Me.create(P.state.doc,ue.pos))),P.focus(),ze())}),Ze.addEventListener("click",T=>{if(T.stopPropagation(),!n)return;const P=Ze.getBoundingClientRect();e.onMenu({x:P.left,y:P.bottom+4,keyboard:T.detail===0}),Kr()||t?.focus()}),K.append(Ze,G,wt,Xe);let jt=null,rn=null,lo=null;const Uo=()=>{const T=[];for(const P of Array.from(y.dom.children))if(P.classList.contains("amx-ucolrow"))for(const ue of Array.from(P.querySelectorAll(".amx-ucolcell")))T.push(...Array.from(ue.children));else T.push(P);return T},$r=(T,P,ue)=>{const ge=T.getBoundingClientRect();if(P<ge.left||P>ge.right||ue<ge.top||ue>ge.bottom)return!1;if(T.matches("hr, table, pre, .amx-ucard"))return!0;const Ae=Q=>P>=Q.left-2&&P<=Q.right+2&&ue>=Q.top-2&&ue<=Q.bottom+2;for(const Q of T.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if(Ae(Q.getBoundingClientRect()))return!0;const Re=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);for(let Q=Re.nextNode();Q;Q=Re.nextNode()){if(!Q.textContent?.length)continue;const Je=document.createRange();Je.selectNodeContents(Q);for(const ft of Je.getClientRects())if(Ae(ft))return!0}return!1},Fn=T=>{if(window.removeEventListener("mouseup",Go),T.button!==0||I.classList.contains("amx-canvas"))return;const P=T.target;if(!P||P.closest(".unified-gutter")||P.closest(".amx-embed")||P.closest("button, input, textarea, a")||!y.editable)return;if(T.pointerType==="touch")return To();const ue=Uo();if(ue.some(Re=>$r(Re,T.clientX,T.clientY)))return To();const ge=P.closest('li[data-item-type="task"]');if(ge&&T.clientX-ge.getBoundingClientRect().left<=2)return;if(ue.some(Re=>{const Q=Re.getBoundingClientRect();return T.clientX>=Q.left&&T.clientX<=Q.right&&T.clientY>=Q.top&&T.clientY<=Q.bottom})){lo={x:T.clientX,y:T.clientY},window.addEventListener("pointermove",Gn),window.addEventListener("pointerup",uo,{once:!0});return}T.preventDefault(),On(T.clientX,T.clientY)},On=(T,P)=>{rn={x:T,y:P},jt=document.createElement("div"),jt.className="amx-marquee",document.body.appendChild(jt),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",jo),window.addEventListener("pointerup",Jo,{once:!0})},wo=()=>{lo=null,window.removeEventListener("pointermove",Gn),window.removeEventListener("pointerup",uo)},To=()=>window.addEventListener("mouseup",Go,{once:!0}),uo=()=>{wo(),To()},Go=()=>{y.isDestroyed||y.domObserver?.flush?.()},Gn=T=>{const P=lo;!P||Math.abs(T.clientX-P.x)<=4&&Math.abs(T.clientY-P.y)<=4||(wo(),On(P.x,P.y),Jn=!0,window.addEventListener("dragstart",_n,!0),window.addEventListener("selectionchange",_n,!0),jo(T))};let Jn=!1;const _n=T=>{T.type==="dragstart"?T.preventDefault():T.stopImmediatePropagation()},Ar=()=>{if(!Jn)return;Jn=!1,window.removeEventListener("dragstart",_n,!0);let T=!1;const P=()=>{if(T)return;T=!0,window.removeEventListener("mouseup",ue,!0),clearTimeout(ge);const Ae=t;Ae&&!Ae.isDestroyed&&Ae.focus(),Jn||window.removeEventListener("selectionchange",_n,!0)},ue=()=>{setTimeout(P,0)},ge=setTimeout(P,300);window.addEventListener("mouseup",ue,{capture:!0,once:!0})},jo=T=>{if(!jt||!rn)return;const P=Math.min(rn.x,T.clientX),ue=Math.min(rn.y,T.clientY),ge=Math.abs(T.clientX-rn.x),Ae=Math.abs(T.clientY-rn.y);Object.assign(jt.style,{left:`${P}px`,top:`${ue}px`,width:`${ge}px`,height:`${Ae}px`});const Re=[],Q=[];for(const zt of Uo()){const Tt=zt.getBoundingClientRect();if(!(Tt.bottom<ue||Tt.top>ue+Ae||Tt.right<P||Tt.left>P+ge))try{Re.push(y.posAtDOM(zt,0)),Q.push(zt)}catch{}}if(!Re.length)return;const Je=y.state.doc;if(Q.length===1){const zt=Q[0];try{const Tt=Array.prototype.indexOf.call(zt.parentNode?.childNodes,zt),Kn=y.posAtDOM(zt.parentNode,Tt),pt=Je.nodeAt(Kn);if(pt&&Me.isSelectable(pt)){const Wn=Me.create(Je,Kn);Wn.eq(y.state.selection)||y.dispatch(y.state.tr.setSelection(Wn));return}}catch{}}const ft=Math.min(...Re),Bt=Q[Q.length-1];if(!Bt)return;let kt=ft;try{const zt=y.posAtDOM(Bt,0),Tt=y.state.doc.nodeAt(zt-1);kt=Tt?zt+Tt.content.size:zt}catch{}const Ut=Ie.between(Je.resolve(Math.min(ft,Je.content.size)),Je.resolve(Math.min(kt,Je.content.size)));(!Ut.eq(y.state.selection)||!o.getState(y.state))&&y.dispatch(y.state.tr.setSelection(Ut).setMeta(o,!0))},Jo=T=>{window.removeEventListener("pointermove",jo),Ar();const P=!!(T&&rn&&(Math.abs(T.clientX-rn.x)>4||Math.abs(T.clientY-rn.y)>4)),ue=rn;if(jt?.remove(),jt=null,rn=null,document.body.classList.remove("amx-marquee-active"),P){y.focus();return}if(!ue||!T)return;const ge=y.dom.getBoundingClientRect(),Ae=Math.min(Math.max(T.clientX,ge.left+8),ge.right-8),Re=y.posAtCoords({left:Ae,top:T.clientY});if(!Re)return;const Q=y.state.doc.resolve(Re.pos);if(!Q.parent.isTextblock)return;const Je=T.clientX<ge.left+ge.width/2?Q.start():Q.end();y.dispatch(y.state.tr.setSelection(Ie.near(y.state.doc.resolve(Je)))),y.focus()};I.addEventListener("pointerdown",Fn),E.appendChild(K);let ko=0,Bn=null;const Ro=T=>{if(K.contains(T.target)){Bn&&clearTimeout(Bn),Bn=null;return}const P=Date.now();if(P-ko<80){const{clientX:ue,clientY:ge}=T;Bn&&clearTimeout(Bn),Bn=setTimeout(()=>{Bn=null,ko=Date.now(),Co(ue,ge)},80);return}ko=P,Co(T.clientX,T.clientY)},Co=(T,P)=>{const ue={clientX:T,clientY:P};if(y.dom.dataset.dragging==="true")return;let ge=ts(y,{x:ue.clientX,y:ue.clientY});if(!ge){const Ae=y.dom.getBoundingClientRect();if(ue.clientY>=Ae.top&&ue.clientY<=Ae.bottom&&(ue.clientX<Ae.left+8||ue.clientX>Ae.right-8)){const Re=Math.min(Math.max(ue.clientX,Ae.left+8),Ae.right-8);ge=ts(y,{x:Re,y:ue.clientY})}}ge&&oe(ge)};I.addEventListener("mousemove",Ro,{passive:!0});const So=T=>{const P=T.relatedTarget;P&&(K.contains(P)||I.contains(P))||X()};I.addEventListener("mouseleave",So);const Tr=()=>{y.dom.dataset.dragging!=="true"&&X()};y.dom.addEventListener("keydown",Tr);const sn=T=>{const P=t;if(!P||!P.editable)return;const ue=P.state.selection,ge=ue instanceof Me?{from:ue.from,to:ue.to}:o.getState(P.state)?g(P):null;let Ae=!1;if(ge){const Re=ue instanceof Me?P.nodeDOM(ue.from):null,Q=P.posAtCoords({left:T.clientX,top:T.clientY});Ae=Re instanceof Node&&T.target instanceof Node&&Re.contains(T.target)||!!Q&&Q.pos>=ge.from&&Q.pos<=ge.to}if(!Ae){const Re=T.target instanceof Element?T.target:null,Q=Re?.closest('[contenteditable="false"]'),Je=!!Re&&(!!Q&&Q!==P.dom&&P.dom.contains(Q)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(Re.tagName)),ft=P.state.selection.empty?Re?.closest("td, th"):null;let Bt=null;if(ft&&P.dom.contains(ft)){const zt=P.state.doc.resolve(P.posAtDOM(ft,0));for(let Tt=zt.depth;Tt>0;Tt--)if(zt.node(Tt).type.spec.tableRole==="table"){Bt=zt.before(Tt);break}}if(!Je&&Bt==null)return;const kt=Bt??ts(P,{x:T.clientX,y:T.clientY})?.pos,Ut=kt==null?null:P.state.doc.nodeAt(kt);if(kt==null||!Ut||!Me.isSelectable(Ut))return;P.dispatch(P.state.tr.setSelection(Me.create(P.state.doc,kt)))}T.preventDefault(),P.focus(),e.onMenu({x:T.clientX,y:T.clientY})};y.dom.addEventListener("contextmenu",sn),K.addEventListener("contextmenu",T=>{const P=t;!P||!P.editable||!n||(T.preventDefault(),Kr()||P.focus(),e.onMenu({x:T.clientX,y:T.clientY}))});const to=()=>{y.dom.dataset.dragging!=="true"&&X()};window.addEventListener("scroll",to,{capture:!0,passive:!0});const At=T=>{if(y.dom.dataset.dragging!=="true")return;const P=Fy(y.dom);if(!P)return;const ue=P.getBoundingClientRect();T.clientY<ue.top+56?P.scrollTop-=14:T.clientY>ue.bottom-56&&(P.scrollTop+=14)};window.addEventListener("dragover",At);const an=T=>{const P=t,ue=T.dataTransfer?Array.from(T.dataTransfer.types):[];if(ue.includes("Files")||ue.includes(Mf)&&P&&!J(P)){if(!P)return;const Q=le(P,T.clientY);if(!Q)return;const Je=Q.el.getBoundingClientRect();rt={pos:Q.pos,el:Q.el,lower:T.clientY>Je.top+Je.height/2},Ue(P,Q.el);return}if(!P||P.dom.dataset.dragging!=="true")return;Ee&&U(),Ee=!1;{const Q=P.state.selection;if(!J(P)&&Q instanceof Me&&Q.node.type===P.state.schema.nodes.amadeusCanvasCard){Be=!1,r=null,ie=null,be=null,me=null,c();const Je=p(P,T);Je&&!Je.self?(Ue(P,Je.drop.lineEl,0,Je.drop.edge),T.preventDefault()):U();return}}const ge=A(P,T);if(ge){Ee=!0,r=null,ie=null,be=null,me=null,Be=!1,c(),it(),ge.self?U():Ue(P,ge.lineEl,0,ge.edge),T.preventDefault();return}if(Be=!1,me=null,!J(P)){const Je=P.state.selection instanceof Me||!!g(P),ft=P.dom.lastElementChild;if(Je&&$e(ft)){const Bt=ft.getBoundingClientRect(),kt=P.dom.getBoundingClientRect();if(T.clientY>Bt.bottom+2&&T.clientX>=kt.left&&T.clientX<=kt.right){Be=!0,r=null,ie=null,be=null,c(),Ue(P,ft),T.preventDefault();return}}}if(!(P.state.selection instanceof Me))return;if(J(P)){D(T.target?.closest?.(".amx-ucard")),be=null,U(),T.preventDefault();return}const Ae=ve(P,T);if(Ae){me={cellEl:Ae.cellEl,lineEl:Ae.lineEl,pos:Ae.pos,edge:Ae.edge,tail:Ae.tail,self:Ae.self},be=null,r=null,ie=null,c(),it(),Ae.self?U():Ue(P,Ae.lineEl,0,Ae.edge),T.preventDefault();return}let Re=null;for(const Q of P.dom.querySelectorAll(":scope > .amx-ucolrow")){const Je=Q.getBoundingClientRect();if(T.clientX<Je.left||T.clientX>Je.right||T.clientY<=Je.bottom+2)continue;const ft=Q.nextElementSibling;ft&&T.clientY>=ft.getBoundingClientRect().top-2||(Re=Q)}if(Re)try{const Q=P.posAtDOM(Re,0)-1;if(P.state.doc.nodeAt(Q)?.type.name==="amadeusColumnRow"){be={rowEl:Re},Ue(P,Re),T.preventDefault();return}}catch{}be=null,U()};I.addEventListener("dragover",an,!0);const fo=T=>{const P=T.relatedTarget;P&&I.contains(P)||(be=null,me=null,rt=null,ie=null,r=null,Ee=!1,c(),U(),it(),D(null))};I.addEventListener("dragleave",fo,!0);const mo=T=>{const P=t,ue=r,ge=be,Ae=me,Re=ie,Q=rt,Je=Be,ft=Ee;if(r=null,be=null,me=null,ie=null,rt=null,Be=!1,Ee=!1,c(),U(),it(),D(null),!P)return;if(Q){try{const Ut=P.nodeDOM(Q.pos)===Q.el?P.state.doc.nodeAt(Q.pos):null;if(Ut){$t(P,Q.pos+Ut.nodeSize);const zt=P.state.doc;P.dispatch(P.state.tr.setSelection(Ut.isAtom?Me.create(zt,Q.pos):Ie.near(zt.resolve(Q.lower?Q.pos+1+Ut.content.size:Q.pos+1),Q.lower?-1:1)))}}catch{}return}const Bt=m(T);let kt=J(P)?ne(P,T,Bt):fe(P,T,Bt);if(!kt)if(Je)kt=k(P,Bt);else if(ft)kt=Z(P,T,Bt);else if(g(P))kt=z(P,T,Bt);else if(Re)kt=F(P,Re.targetPos,Bt);else if(ge)try{ge.rowEl.isConnected&&(kt=Vg(P,P.posAtDOM(ge.rowEl,0)-1,Bt))}catch{kt=!1}else if(Ae){const Ut=Qe(P,Ae);Ut!=null&&(Ae.self||$t(P,Ut),kt=Wg(P,Ut,Bt))}else ue&&(kt=Hg(P,ue.targetPos,ue.side,Bt));kt&&(T.preventDefault(),T.stopPropagation(),P.dom.dataset.dragging="false",P.dragging=null)};I.addEventListener("drop",mo,!0);let Mn=null;const Vn=T=>{const P=t,ue=T.target;if(!P||!ue||!ue.classList?.contains("amx-ucolrow"))return;const ge=ue,Ae=[...ge.children].filter(pt=>pt instanceof HTMLElement&&"amxColcell"in pt.dataset);let Re=-1;for(let pt=0;pt<Ae.length-1;pt++)if(T.clientX>=Ae[pt].getBoundingClientRect().right-2&&T.clientX<=Ae[pt+1].getBoundingClientRect().left+2){Re=pt;break}if(Re<0)return;T.preventDefault();const Q=Ae[Re],Je=Ae[Re+1],ft=Q.getBoundingClientRect().left,Bt=Je.getBoundingClientRect().right-ft,kt=(Number(Q.dataset.width)||1)+(Number(Je.dataset.width)||1),Ut=pt=>Math.min(.85,Math.max(.15,(pt.clientX-ft)/Bt)),zt=pt=>{const Wn=Ut(pt);Q.style.flexGrow=String(kt*Wn),Je.style.flexGrow=String(kt*(1-Wn))},Tt=()=>{window.removeEventListener("pointermove",zt),window.removeEventListener("pointerup",Kn),window.removeEventListener("pointercancel",Tt),Mn=null},Kn=pt=>{Tt();const Wn=Ut(pt),dr=u=>Math.round(u*1e4)/1e4;try{const u=P.posAtDOM(ge,0)-1,S=P.state.doc.nodeAt(u);if(!S||S.type.name!=="amadeusColumnRow")return;let N=u+1,B=P.state.tr;for(let _=0;_<S.childCount;_++){const O=S.child(_);_===Re&&(B=B.setNodeMarkup(N,void 0,{...O.attrs,width:dr(kt*Wn)})),_===Re+1&&(B=B.setNodeMarkup(N,void 0,{...O.attrs,width:dr(kt*(1-Wn))})),N+=O.nodeSize}B.setMeta("amxColumns",!0),P.dispatch(B)}catch{}};window.addEventListener("pointermove",zt),window.addEventListener("pointerup",Kn),window.addEventListener("pointercancel",Tt),Mn=Tt};E.addEventListener("pointerdown",Vn);const no=El(()=>{G.title=ke("blocklayer.dragHandle"),wt.title=ke("blocklayer.addBelow"),Ze.title=ke("blocklayer.cardGrab");for(const T of[G,wt,Ze])T.setAttribute("aria-label",T.title)});return{update:T=>{const P=n;if(!P)return;let ue=!1;try{ue=P.pos<=T.state.doc.content.size&&T.state.doc.nodeAt(P.pos)===P.node}catch{}ue||X()},destroy:()=>{window.removeEventListener("mouseup",Pe),q?.remove(),q=null,Bn&&clearTimeout(Bn),Jo(),I.removeEventListener("pointerdown",Fn),I.removeEventListener("mousemove",Ro),y.dom.removeEventListener("keydown",Tr),y.dom.removeEventListener("contextmenu",sn),I.removeEventListener("dragover",an,!0),I.removeEventListener("dragleave",fo,!0),I.removeEventListener("drop",mo,!0),I.removeEventListener("dragstart",_e,!0),pi.delete(y),I.removeEventListener("mouseleave",So),E.removeEventListener("pointerdown",Vn),no(),Mn?.(),window.removeEventListener("scroll",to,{capture:!0}),window.removeEventListener("dragover",At),K.remove(),s?.remove(),s=null,pe?.remove(),pe=null,st?.remove(),st=null,r=null,be=null,me=null,Ee=!1,n=null,t===y&&(t=null)}}}})),Yn=Et(()=>{const y=I=>{if(st&&st.isConnected)return st;const D=document.createElement("div");return D.className="unified-drop-line",D.style.display="none",D.style.animation="none",(I.dom.parentElement??document.body).appendChild(D),st=D,D};return kg({onDrag:({view:I,event:D,pos:K})=>{if(un(),(D.dataTransfer?Array.from(D.dataTransfer.types):[]).includes("Files"))return!1;if(J(I))return c(),!1;if(!I.dragging||!(I.state.selection instanceof Me)||I.state.selection.node.type===I.state.schema.nodes.amadeusCanvasCard)return!1;if(be||Be||me||Ee)return r=null,ie=null,c(),!1;const oe=I.state.selection,G=ts(I,{x:D.clientX,y:D.clientY});if(G&&G.node.type.name==="list_item"&&!(G.pos>=oe.from&&G.pos<oe.to)){const q=G.el.getBoundingClientRect();if(D.clientX>q.left+24&&D.clientY>q.top+q.height/2)return ie={targetPos:G.pos,el:G.el},r=null,c(),Ue(I,G.el,24),!1}if(ie=null,G&&!(G.pos>=oe.from&&G.pos<oe.to)&&ce(I,G.pos)){const q=G.el.getBoundingClientRect(),ze=D.clientX<=q.left+d?"left":D.clientX>=q.right-d?"right":null;if(ze)return r={targetPos:G.pos,side:ze},a(I,G.el,ze),!1}r=null,c();const ee=I.state.doc.resolve(K);if(ee.parent.type.name==="amadeusColumnRow")return!1;for(let q=ee.depth;q>=1;q--){if(ee.node(q).type.name!=="amadeusColumnCell")continue;const ze=I.nodeDOM(ee.before(q));if(ze instanceof HTMLElement){const Pe=ze.getBoundingClientRect();if(D.clientX<Pe.left||D.clientX>Pe.right)return!1}break}return!0},onShow:({view:I,line:D})=>{mt=!0;const K=y(I),X=Pr(I.dom),oe=Fr(K),G=(D.p1.x-oe.x)/X,ee=(D.p2.x-oe.x)/X,q=(D.p1.y-oe.y)/X;K.style.display="block",K.style.width=`${Math.max(0,ee-G)}px`,K.style.transform=`translate(${Math.round(G)}px, ${Math.round(q-1.5)}px)`},onHide:it})}),vt=Et(()=>new Ht({key:new Tn("UNIFIED_DROP_GUARD"),props:{handleDrop:y=>y.dom.dataset.dragging==="true"&&!!y.dragging}})),lt=Et(()=>{let y=null,E=null;const I=()=>{y&&(y.style.display="none")};return new Ht({key:new Tn("AMX_GAP_INSERT"),view:D=>{const K=()=>(y&&y.isConnected||(y=document.createElement("div"),y.className="amx-gap-insert",y.innerHTML="<span>+</span>",y.addEventListener("mousedown",G=>{G.preventDefault(),G.stopPropagation()}),y.addEventListener("click",G=>{if(G.preventDefault(),G.stopPropagation(),!E)return;let ee=-1;D.state.doc.forEach((Pe,Oe)=>{ee<0&&Pe.type.name==="amadeusCanvasCard"&&String(Pe.attrs.anchor)===E&&(ee=Oe)});const q=D.state.schema.nodes.paragraph;if(ee<0||!q){I();return}let ze=D.state.tr.insert(ee,q.create());ze=ze.setSelection(Ie.create(ze.doc,ee+1)).scrollIntoView(),D.dispatch(ze),D.focus(),I()}),(D.dom.parentElement??document.body).appendChild(y)),y),X=G=>{if(J(D)||D.dragging){I();return}const ee=D.state.schema.nodes.amadeusCanvasCard;if(!ee){I();return}const q=D.state.doc;let ze=0,Pe=null,Oe=null;for(let Ge=0;Ge<q.childCount&&!Oe;Ge++){const Xt=q.child(Ge);if(Xt.type===ee){const Mt=D.nodeDOM(ze);if(Mt instanceof HTMLElement){if(Mt.classList.contains("amx-card-f0")&&!Mt.classList.contains("amx-card-f0-top")){Pe=Mt,ze+=Xt.nodeSize;continue}if(Pe){const wt=Pe.getBoundingClientRect(),Ze=Mt.getBoundingClientRect();G.clientY>=wt.bottom-3&&G.clientY<=Ze.top+3&&G.clientX>=Math.min(wt.left,Ze.left)&&G.clientX<=Math.max(wt.right,Ze.right)&&(Oe={top:wt.bottom,bottom:Ze.top,left:Math.min(wt.left,Ze.left),right:Math.max(wt.right,Ze.right),anchor:String(Xt.attrs.anchor)})}Pe=Mt}else Pe=null}else Pe=null;ze+=Xt.nodeSize}if(!Oe){I();return}const _e=K(),qe=Pr(D.dom),Xe=Fr(_e),Ve=(Oe.top+Oe.bottom)/2;_e.style.display="flex",_e.style.width=`${(Oe.right-Oe.left)/qe}px`,_e.style.transform=`translate(${Math.round((Oe.left-Xe.x)/qe)}px, ${Math.round((Ve-Xe.y)/qe-9)}px)`,E=Oe.anchor},oe=D.dom.parentElement??D.dom;return oe.addEventListener("mousemove",X),oe.addEventListener("mouseleave",I),{update:(G,ee)=>{G.state.doc.eq(ee.doc)||I()},destroy:()=>{oe.removeEventListener("mousemove",X),oe.removeEventListener("mouseleave",I),y?.remove(),y=null}}}})}),Ot={listFoldedAt:(y,E)=>uc(y,E),unfoldList:(y,E)=>ha(y,E)},on=Et(()=>_o({Tab:(y,E,I)=>la(y,E,I,Ot),"Shift-Tab":(y,E)=>ua(y,E)})),Yt=Et(()=>new Ht({props:{decorations:y=>{const E=y.selection;if(!E.empty)return null;const I=E.$from,D=I.parent;if(!D.isTextblock||D.content.size>0)return null;for(let X=I.depth;X>=1;X--)if(I.node(X).type.name==="blockquote")return null;const K=D.type.name==="paragraph"?ke("blocklayer.phParagraph"):D.type.name==="heading"?ke("blocklayer.phHeading",{n:D.attrs.level??1}):null;return K?cr.create(y.doc,[co.node(I.before(),I.after(),{class:"is-empty","data-placeholder":K})]):null}}})),Cn=["doc","amadeusColumnCell","bullet_list","ordered_list"],Qn=y=>{let E=y.depth;for(;E>=1&&!Cn.includes(y.node(E-1).type.name);)E--;return E},ur=y=>{const E=y.selection;if(E instanceof Me){if(!E.node.isBlock)return null;if(Cn.includes(E.$from.parent.type.name))return{from:E.from,to:E.to};const X=Qn(E.$from);return X<1?null:{from:E.$from.before(X),to:E.$from.after(X)}}const{$from:I,$to:D}=E;if(!I.sameParent(D)){let X=I.sharedDepth(D.pos);for(;X>0&&!Cn.includes(I.node(X).type.name);)X--;return{from:I.before(X+1),to:D.after(X+1)}}const K=Qn(I);return K<1?null:{from:I.before(K),to:I.after(K)}},en=y=>(E,I)=>{const D=ur(E);if(!D)return!1;const{from:K}=D,X=ds(E,D.from,D.to),oe=E.doc.resolve(K),G=oe.parent,ee=oe.index(),q=E.doc.resolve(X).index()-1,ze=G.child(ee),Pe=X>D.to&&ze.type.name==="heading"?Number(ze.attrs.level)||1:null;let Oe,_e;if(y<0){if(ee===0)return!0;_e=K,Oe=K-G.child(ee-1).nodeSize;let wt=null;if(Pe!=null)for(let Ze=ee-1,Un=K;Ze>=0;Ze--){const jt=G.child(Ze);if(Un-=jt.nodeSize,jt.type.name==="heading"&&(Number(jt.attrs.level)||1)<=Pe){wt=Un;break}}if(wt!=null)Oe=wt;else for(let Ze=_s(E,Oe+1);Ze!=null&&Ze<Oe;Ze=_s(E,Oe+1))Oe=Ze}else{if(q+1>=G.childCount)return!0;Oe=X;const wt=G.child(q+1);_e=X+wt.nodeSize,Pe!=null&&wt.type.name==="heading"&&(_e=Pm(E.doc,Oe)??_e)}if(!I)return!0;const qe=X-K,Xe=E.doc.slice(K,X).content,Ve=y<0?Oe:_e-qe,Ge=E.tr.delete(K,X).insert(Ve,Xe),Xt=Ve-K;_r(E,Ge,{from:K,to:X,newStart:Ve}),Zr(E,Ge,{from:K,to:X,newStart:Ve});const Mt=E.selection;return Mt instanceof Me?Ge.setSelection(Me.create(Ge.doc,Mt.from+Xt)):Ge.setSelection(Ie.create(Ge.doc,Mt.anchor+Xt,Mt.head+Xt)),o.getState(E)&&Ge.setMeta(o,!0),I(Ge.scrollIntoView()),!0},Xn=Et(()=>_o({"Mod-Alt-ArrowUp":en(-1),"Mod-Alt-ArrowDown":en(1),"Mod-Shift-ArrowUp":en(-1),"Mod-Shift-ArrowDown":en(1)})),Sn=(y,E,I)=>{const D=y.selection,K=I?g(I):null;if(K){if(!E)return!0;const Pe=ds(y,K.from,K.to),{content:Oe,minted:_e}=es(y.doc,y.doc.slice(K.from,Pe).content);_e.length&&e.onCardsMinted?.(_e);const qe=Pe-K.from,Xe=y.tr.insert(Pe,Oe);return _r(y,Xe,{from:K.from,to:Pe,newStart:Pe,copy:!0}),Zr(y,Xe,{from:K.from,to:Pe,newStart:Pe}),Xe.setSelection(Ie.create(Xe.doc,D.anchor+qe,D.head+qe)),o.getState(y)&&Xe.setMeta(o,!0),E(Xe.scrollIntoView()),!0}if(D instanceof Me){if(!D.node.isBlock)return!1;if(!E)return!0;const Pe=ds(y,D.from,D.to);if(Pe>D.to){const qe=y.tr.insert(Pe,y.doc.slice(D.from,Pe).content);return _r(y,qe,{from:D.from,to:Pe,newStart:Pe,copy:!0}),Zr(y,qe,{from:D.from,to:Pe,newStart:Pe}),qe.setSelection(Me.create(qe.doc,Pe)),E(qe.scrollIntoView()),!0}let Oe=D.node;if(Oe.type.name==="amadeusCanvasCard"){const{content:qe,minted:Xe}=es(y.doc,zo.from(Oe)),Ve=qe.firstChild??Oe;Oe=Ve.type.create({...Ve.attrs,x:Number(Ve.attrs.x)+40,y:Number(Ve.attrs.y)+40},Ve.content,Ve.marks),Xe.length&&e.onCardsMinted?.(Xe)}const _e=y.tr.insert(D.to,Oe);return _e.setSelection(Me.create(_e.doc,D.to)),E(_e.scrollIntoView()),!0}if(!(D instanceof Ie)||!D.$from.sameParent(D.$to))return!1;const{$from:X}=D;let oe=X.depth;for(;oe>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(X.node(oe-1).type.name);)oe--;if(oe<1)return!1;const G=X.before(oe),ee=ds(y,G,X.after(oe));if(!y.doc.nodeAt(G))return!1;if(!E)return!0;const q=ee-G,ze=y.tr.insert(ee,y.doc.slice(G,ee).content);return _r(y,ze,{from:G,to:ee,newStart:ee,copy:!0}),Zr(y,ze,{from:G,to:ee,newStart:ee}),ze.setSelection(Ie.create(ze.doc,D.anchor+q,D.head+q)),E(ze.scrollIntoView()),!0},eo=Et(()=>_o({"Mod-d":Sn})),$o=(y,E,I,D=!1)=>{const K=I?g(I):null;if(!K)return!1;const X=y.doc.resolve(K.from);if(y.doc.resolve(K.to).index()-X.index()<2)return!1;const G=y.selection;if(G.from>K.from+1||G.to<K.to-1)return!1;if(!E)return!0;const ee=y.doc.slice(K.from,K.to).content;return E(y.tr.delete(K.from,K.to).scrollIntoView()),D||e.onBlocksDeleted?.(ee),!0},Wo=(y,E)=>{const I=y.selection;if(!(I instanceof Me))return!1;if(!E)return!0;const D=zo.from(I.node);return E(y.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(D),!0},Yo=(y,E,I)=>$o(y,E,I)||Wo(y,E),vn=Et(()=>_o({Backspace:Yo,Delete:Yo})),En=Et(()=>new Ht({props:{handleDOMEvents:{cut:(y,E)=>{const I=E;if(!I.clipboardData||!$o(y.state,void 0,y,!0))return!1;const{dom:D,text:K}=y.serializeForClipboard(y.state.selection.content());return I.preventDefault(),I.clipboardData.clearData(),I.clipboardData.setData("text/html",D.innerHTML),I.clipboardData.setData("text/plain",K),$o(y.state,y.dispatch.bind(y),y,!0),!0}}}})),jn=Et(()=>_o({"Mod-a":(y,E)=>{const{$from:I}=y.selection,D=(oe,G)=>y.selection.from<=oe&&y.selection.to>=G,K=[];I.parent.isTextblock&&K.push([I.start(),I.end()]);let X=I.depth;for(;X>=1&&!["doc","amadeusColumnCell"].includes(I.node(X-1).type.name);)X--;X>=1&&K.push([I.start(X),I.end(X)]);for(const[oe,G]of K)if(!D(oe,G))return E?.(y.tr.setSelection(Ie.create(y.doc,oe,G))),!0;return E?.(y.tr.setSelection(new Ll(y.doc))),!0}})),xo=y=>{const E=y.selection;if(!(E instanceof Ie)||E.empty)return[];const I=!!o.getState(y);if(!I&&E.$from.sameParent(E.$to))return[];const D=[],K=oe=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(oe.type.name))return!0;if(oe.type.name!=="paragraph")return!1;const G=oe.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(G)||oe.childCount===1&&oe.firstChild?.type.name==="image"},X=(oe,G)=>{oe.forEach((ee,q)=>{const ze=G+q,Pe=ze+ee.nodeSize;if(!(Pe<=E.from||ze>=E.to)){if(ee.type.name==="amadeusColumnRow"){ee.forEach((Oe,_e)=>X(Oe,ze+1+_e+1));return}(I||K(ee))&&D.push([ze,Pe,I])}})};return X(y.doc,0),D},bo=Et(()=>new Ht({key:o,state:{init:()=>!1,apply:(y,E,I)=>y.getMeta(o)===!0?!0:y.docChanged||y.selectionSet&&!y.selection.eq(I.selection)?!1:E},props:{decorations:y=>{const E=xo(y);return E.length?cr.create(y.doc,E.map(([I,D,K])=>co.node(I,D,{class:K?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:y=>o.getState(y)&&xo(y).length?{"data-blocksel":"true"}:{}}})),ot=Et(()=>_o({Escape:(y,E)=>{const I=y.selection;if(I instanceof Me){const D=Ie.near(y.doc.resolve(I.from+1));return E?.(y.tr.setSelection(D)),!0}if(I instanceof Ie){const D=Wi(y);return D==null?!1:(E?.(y.tr.setSelection(Me.create(y.doc,D))),!0)}return!1}})),Lt=["doc","amadeusColumnCell"],vo=y=>{const E=y.selection;return E instanceof Me?E.node.isBlock:E instanceof Ie&&!E.empty&&!!o.getState(y)},io=(y,E)=>{const I=y.resolve(E);if(Lt.includes(I.parent.type.name)){const K=I.nodeAfter;return K?{from:E,to:E+K.nodeSize}:null}let D=I.depth;for(;D>=1&&!Lt.includes(I.node(D-1).type.name);)D--;return D>=1?{from:I.before(D),to:I.after(D)}:null},Xo=y=>{const E=y.selection,I=y.doc,D=io(I,E instanceof Me?E.from:E.anchor),K=E instanceof Me?D:io(I,E.head);return!D||!K||I.resolve(D.from).parent!==I.resolve(K.from).parent?null:{a:D,h:K}},Ao=(y,E,I)=>{const D=y.doc,K=E.from===I.from?D.nodeAt(E.from):null;if(K&&Me.isSelectable(K))return y.tr.setSelection(Me.create(D,E.from));const X=I.from>=E.from,oe=D.resolve(X?E.from+1:E.to-1),G=D.resolve(X?I.to-1:I.from+1);return y.tr.setSelection(Ie.between(oe,G)).setMeta(o,!0)},Hn=y=>(E,I)=>{if(!vo(E))return!1;const D=Xo(E);if(!D)return!1;const K=E.doc.resolve(D.h.from),X=K.parent;let oe=K.index()+y,G=y>0?D.h.to:D.h.from;for(;oe>=0&&oe<X.childCount;){const ee=X.child(oe).nodeSize,q=y>0?G:G-ee;if(_s(E,q+1)==null)return I?.(Ao(E,D.a,{from:q,to:q+ee}).scrollIntoView()),!0;G=y>0?G+ee:G-ee,oe+=y}return!0},Fe=y=>y.selection.$from.parent.type.name==="code_block";return{plugins:[Et(()=>new Ht({props:{handleKeyDown:zf({"Shift-ArrowDown":Hn(1),"Shift-ArrowUp":Hn(-1),"Mod-Alt-/":(y,E,I)=>{if(!I||!I.editable||!E)return!1;if(!vo(y)){const oe=Wi(y);if(oe==null)return!1;E(y.tr.setSelection(Me.create(y.doc,oe)))}const D=I.state,K=D.selection instanceof Me?I.nodeDOM(D.selection.from):null,X=K instanceof HTMLElement?K.getBoundingClientRect():I.coordsAtPos(D.selection.from);return e.onMenu({x:X.left,y:X.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(y,E,I)=>Fe(y)?!1:la(y,E,I,Ot),"Mod-[":(y,E)=>Fe(y)?!1:ua(y,E)}),handleDOMEvents:{mousedown:(y,E)=>{if(!E.shiftKey||E.button!==0||!y.editable||!vo(y.state))return!1;const I=y.posAtCoords({left:E.clientX,top:E.clientY}),D=Xo(y.state),K=I?io(y.state.doc,I.pos):null;return!D||!K||y.state.doc.resolve(K.from).parent!==y.state.doc.resolve(D.a.from).parent?!1:(E.preventDefault(),y.dispatch(Ao(y.state,D.a,K)),y.focus(),!0)}}}})),ut,Yn,vt,lt,bo,Yt,ot,on,jn,vn,En,Xn,eo,Iy].flat(),getView:()=>t,topRangeOf:g,duplicate:y=>Sn(y.state,y.dispatch.bind(y),y),indent:(y,E)=>E>0?la(y.state,y.dispatch.bind(y),y,Ot):ua(y.state,y.dispatch.bind(y))}}async function _y(e,t,n){const o=Kc(t);if(!o.length)return;const r=new Set(Kc(n).map(Hs)),s=o.filter(c=>!r.has(Hs(c)));if(!s.length)return;const a=(await bn.exclusiveAssets?.(e).catch(()=>[])??[]).filter(c=>s.some(d=>By(d,c)));a.length&&await ih(e,a,{block:!0})==="with"&&await $f(a)}function By(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),o=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?o===n||o.endsWith(`/${n}`)||o===kl(n):Hs(e)===Hs(t)}function Yi(e){const t=[],n=o=>{if(o.isText){t.push(o.text??"");for(const s of o.marks){const i=String(s.attrs?.href??"");s.type.name==="link"&&i&&t.push(`[](${qc(i)??i})`)}return}const r=String(o.attrs?.src??"");r&&t.push(`??r})`),o.forEach(n)};return e.forEach(n),t.join(`
|
|
44
|
-
`)}const Vo=1,Jt=400,Ko=720,Ky=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,qy=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,oa=/^[A-Za-z0-9_-]+$/,ao=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.round(e):t;function Pn(e){if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.v!==Vo||n.mode!=null&&n.mode!=="doc"&&n.mode!=="canvas")return null;const o=r=>typeof r=="number"&&Number.isFinite(r);if(n.main!=null&&(typeof n.main!="object"||!o(n.main.w)||n.main.w<=0||!o(n.main.x)||!o(n.main.y)||n.main.h!=null&&(!o(n.main.h)||n.main.h<0)))return null;if(n.cards!=null){if(!Array.isArray(n.cards))return null;for(const s of n.cards)if(!s||typeof s!="object"||typeof s.ref!="string"||!oa.test(s.ref)||!o(s.w)||s.w<=0||!o(s.x)||!o(s.y)||s.h!=null&&(!o(s.h)||s.h<0))return null;const r=n.cards.map(s=>s.ref);if(new Set(r).size!==r.length)return null}return n.elements!=null&&!Array.isArray(n.elements)?null:n}catch{return null}}function Hy(e){const t=new Set;for(const n of e?.rows??[]){for(const o of n.columns)for(const r of o.refs)t.add(r);n.tail&&t.add(n.tail)}return t}const Vy=lc("amadeusCanvasCard",()=>({content:"block+",group:"block",defining:!0,isolating:!0,selectable:!0,attrs:{anchor:{default:""},x:{default:0},y:{default:0},w:{default:Jt},h:{default:0},color:{default:""}},parseDOM:[{tag:"div[data-amx-card]",getAttrs:e=>{const t=e.dataset;return{anchor:t.anchor??"",x:ao(Number(t.x),0),y:ao(Number(t.y),0),w:ao(Number(t.w),Jt)||Jt,h:ao(Number(t.h),0),color:t.color??""}}}],toDOM:e=>{const t=ta(e.attrs.color);return["div",{"data-amx-card":"","data-anchor":String(e.attrs.anchor),"data-x":String(e.attrs.x),"data-y":String(e.attrs.y),"data-w":String(e.attrs.w),"data-h":String(e.attrs.h),"data-color":typeof e.attrs.color=="string"&&e.attrs.color?e.attrs.color:null,class:"amx-ucard",style:`--amx-x:${e.attrs.x}px;--amx-y:${e.attrs.y}px;--amx-w:${e.attrs.w}px;--amx-h:${Number(e.attrs.h)>0?`${e.attrs.h}px`:"auto"}${t?`;--amx-color:${t}`:""}`},0]},parseMarkdown:{match:({type:e})=>e==="amadeusCanvasCard",runner:(e,t,n)=>{const o=t;e.openNode(n,{anchor:o.anchor??"",x:o.x??0,y:o.y??0,w:o.w??Jt,h:o.h??0,color:o.color??""}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusCanvasCard",runner:(e,t)=>{e.addNode("html",void 0,`<!-- a ${t.attrs.anchor} -->`),t.childCount===1&&t.firstChild.type.name==="paragraph"&&t.firstChild.content.size===0||e.next(t.content),e.addNode("html",void 0,`<!-- /a ${t.attrs.anchor} -->`)}}}));function Wy(e,t,n,o){const r=t?.cards;if(!r?.length)return;const s=Array.isArray(e?.children)?e.children:[];if(s.length&&!s.some(M=>M?.position))return;const i=M=>{let k=null;if(M?.type==="html"&&typeof M.value=="string")k=M.value;else if(M?.type==="paragraph"&&Array.isArray(M.children)&&M.children.length===1){const F=M.children[0];F?.type==="html"&&typeof F.value=="string"&&(k=F.value)}if(k==null)return null;const z=Ky.exec(k.trim());return z?z[1]:null},a=M=>{let k=null;if(M?.type==="html"&&typeof M.value=="string")k=M.value;else if(M?.type==="paragraph"&&Array.isArray(M.children)&&M.children.length===1){const F=M.children[0];F?.type==="html"&&typeof F.value=="string"&&(k=F.value)}if(k==null)return null;const z=qy.exec(k.trim());return z?z[1]:null},c=new Map(r.map(M=>[M.ref,M])),d=du(t?.cardColors),m=[];if(s.forEach((M,k)=>{const z=i(M);z&&m.push({id:z,idx:k})}),!m.length)return;const g=new Map;m.forEach(M=>g.set(M.id,(g.get(M.id)??0)+1));const C=[];for(const M of m){if((g.get(M.id)??0)>1||n.has(M.id)||!c.has(M.id))continue;let k=s.length,z=-1;for(let F=M.idx+1;F<s.length;F++){if(i(s[F])){k=F;break}if(a(s[F])===M.id){k=F,z=F;break}}C.push({id:M.id,open:M.idx,end:k,closer:z})}if(!C.length)return;const L=[];for(const M of[...C].reverse()){const k=c.get(M.id),z=s.slice(M.open+1,M.end);s.splice(M.open,(M.closer>=0?M.closer+1:M.end)-M.open,{type:"amadeusCanvasCard",anchor:M.id,x:ao(k.x,0),y:ao(k.y,0),w:ao(k.w,Jt)||Jt,h:ao(k.h,0),color:d&&Object.prototype.hasOwnProperty.call(d,M.id)&&fu(d[M.id])?d[M.id]:typeof k.color=="string"?k.color:"",children:z.length?z:[{type:"paragraph",children:[]}]}),L.unshift(M.id)}o?.(L)}function Yy(e,t,n){return[Il("amadeusCanvasFold",()=>()=>o=>{Wy(o,e(),Hy(t()),n)})].flat()}function Xy(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);if(!oa.test(o))return;const r=ao(n.attrs.h,0);t.push({ref:o,x:ao(n.attrs.x,0),y:ao(n.attrs.y,0),w:ao(n.attrs.w,Jt)||Jt,...r>0?{h:r}:{}})}),t}function du(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const fu=e=>e!==""&&e!=null;function Xi(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);oa.test(o)&&fu(n.attrs.color)&&(t[o]=n.attrs.color)}),t}function Uy(e,t,n,o){const r=Xy(e),s=Pn(t);if(!s){if(t!=null)return t;if(!r.length)return null;const m=Xi(e);return JSON.stringify({v:Vo,mode:n??"canvas",main:{x:0,y:0,w:Ko},cards:r,...Object.keys(m).length?{cardColors:{...m}}:{}})}if(!(s.cards??[]).every(m=>o.has(m.ref)))return t;if(!r.length&&!s.elements?.length){const m=s.main;if(!m||m.x===0&&m.y===0&&m.w===Ko)return null}const i={...s,v:Vo,cards:r},a=Xi(e);Object.keys(a).length?i.cardColors={...a}:(i.cardColors===void 0||du(i.cardColors))&&delete i.cardColors,n&&(i.mode=n),i.main||(i.main={x:0,y:0,w:Ko}),i.elements?.length||delete i.elements;const c=Kt(i.tree),d=Object.keys(c);if(d.length){const m=new Set(r.map(L=>L.ref)),g=L=>typeof L=="string"&&oa.test(L)&&!m.has(L),C=new Set;for(const L of d)g(L)&&C.add(L),g(c[L])&&C.add(c[L]);if(C.size){const L=jg(c,C);Object.keys(L).length?i.tree=L:delete i.tree}}return JSON.stringify(i)}function Gy(e,t){const n=Pn(e);if(!n)return e??(t.length?JSON.stringify({v:Vo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],elements:t}):null);const o={...n,v:Vo,elements:t};return t.length||delete o.elements,JSON.stringify(o)}function Jy(e,t){const n={x:Math.round(t.x),y:Math.round(t.y),w:Math.round(t.w),...typeof t.h=="number"&&t.h>0?{h:Math.round(t.h)}:{}},o=Pn(e);return o?JSON.stringify({...o,v:Vo,main:n}):e??(!n.x&&!n.y&&n.w===Ko?null:JSON.stringify({v:Vo,mode:"canvas",main:n,cards:[]}))}function Zy(e,t){const n=Object.keys(t).length,o=Pn(e);if(!o)return e??(n?JSON.stringify({v:Vo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],tree:t}):null);const r={...o,v:Vo,tree:t};return n||delete r.tree,JSON.stringify(r)}const Qy=Et(()=>new Ht({key:new Tn("AMX_CANVAS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(c=>c.docChanged))return null;const o=n.schema.nodes.amadeusCanvasCard;if(!o)return null;const r=[],s=[],i=new Set;if(n.doc.forEach((c,d)=>{if(c.type!==o)return;const m=String(c.attrs.anchor);i.has(m)?s.push(d):i.add(m),c.forEach((g,C)=>{if(g.type.name!=="amadeusColumnRow")return;const L=d+1+C;r.push({from:L,to:L+g.nodeSize,node:g,before:d})})}),!r.length&&!s.length)return null;let a=n.tr;for(const c of s){const d=a.doc.nodeAt(c);d?.type===o&&(a=a.setNodeMarkup(c,void 0,{...d.attrs,anchor:No(a.doc)}))}for(const c of r)a=a.delete(a.mapping.map(c.from,1),a.mapping.map(c.to,-1)),a=a.insert(a.mapping.map(c.before),c.node);return a.steps.length?a:null}})),ex=Et(()=>new Ht({key:new Tn("AMX_CANVAS_PASTE_GUARD"),props:{transformPasted:(e,t)=>{if(t.dragging?.move)return e;const n=t.state.schema.nodes.amadeusCanvasCard;if(!n)return e;let o=!1;if(e.content.descendants(s=>s.type===n?(o=!0,!1):!0),!o)return e;const r=s=>{const i=[];return s.forEach(a=>{a.type===n?r(a.content).forEach(c=>i.push(c)):i.push(a.copy(r(a.content)))}),zo.fromArray(i)};return Ka.maxOpen(r(e.content))}}})),tx=Et(()=>new Ht({key:new Tn("AMX_CANVAS_INTEGRITY"),filterTransaction:(e,t)=>{if(!e.docChanged)return!0;const n=t.schema.nodes.amadeusCanvasCard;if(!n)return!0;let o=!0;return e.doc.descendants((r,s,i)=>!o||r.type!==n?o:i?.type.name!=="doc"?(o=!1,!1):!0),o}})),nx=[Vy,Qy,ex,tx].flat();function ox(e){return[Et(()=>new Ht({key:new Tn("AMX_CANVAS_SEL_CLAMP"),appendTransaction:(t,n,o)=>{if(!e())return null;const r=o.schema.nodes.amadeusCanvasCard;if(!r)return null;let s=-1;{let M=0;for(let k=0;k<o.doc.childCount;k++){const z=o.doc.child(k);if(z.type===r){s=M;break}M+=z.nodeSize}}if(s<0)return null;const i=M=>M.depth>=1&&M.node(1).type===r?M.index(0):-1,a=M=>{if(M<0)return{from:0,to:s};let k=0;for(let z=0;z<M;z++)k+=o.doc.child(z).nodeSize;return{from:k+1,to:k+o.doc.child(M).nodeSize-1}},c=M=>M.eq(o.selection)||i(o.doc.resolve(M.anchor))!==i(o.doc.resolve(M.head))?null:o.tr.setSelection(M),d=o.selection;if(d.empty||d instanceof Me)return null;if(d instanceof Ll){if(t.some(z=>z.docChanged))return null;const M=Math.max(0,Math.min(n.selection.head,o.doc.content.size)),k=a(i(o.doc.resolve(M)));return k.from>=k.to?null:c(Ie.between(o.doc.resolve(k.from),o.doc.resolve(k.to),-1))}if(!(d instanceof Ie))return null;const m=o.doc.resolve(d.anchor),g=i(m);if(g===i(o.doc.resolve(d.head)))return null;const C=a(g),L=Math.max(C.from,Math.min(C.to,d.head));return c(Ie.between(m,o.doc.resolve(L),d.head>=d.anchor?-1:1))}}))].flat()}function rx(){return[Et(()=>new Ht({key:new Tn("AMX_CARD_ACTIVE"),props:{decorations(e){const t=e.schema.nodes.amadeusCanvasCard;if(!t)return null;const n=e.selection;let o=-1,r=null;if(n instanceof Me){if(n.node.type===t)o=n.from,r=n.node;else if(n.$from.depth>=1){const s=n.$from.node(1);s.type===t&&(o=n.$from.before(1),r=s)}}else if(n.$head.depth>=1){const s=n.$head.node(1);s.type===t&&(o=n.$head.before(1),r=s)}return r?cr.create(e.doc,[co.node(o,o+r.nodeSize,{class:"amx-card-active"})]):null}}}))].flat()}const sx=6,ax=2;function cx(e){return[Et(()=>new Ht({key:new Tn("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const o=Kt(e()?.tree);if(!Object.keys(o).length)return null;const r=new Set,s=[];t.doc.forEach((c,d,m)=>{if(c.type!==n)return;const g=String(c.attrs.anchor);r.add(g),s.push({pos:d,size:c.nodeSize,anchor:g,idx:m})});const i=[];for(let c=0;c<s.length;c++){const d=Us(s,c,o);d>c+1&&i.push({start:c,end:d})}const a=[];for(let c=0;c<s.length;c++){const d=s[c],m=Rg(o,d.anchor,r,sx),g=i.filter(L=>L.start<=c&&c<L.end).slice(0,ax);if(!m&&!g.length)continue;const C=[];m>0&&C.push("amx-card-child",`amx-card-d${m}`),g.forEach((L,M)=>{C.push(`amx-card-f${M}`),L.start===c&&C.push(`amx-card-f${M}-top`),L.end-1===c&&C.push(`amx-card-f${M}-end`)}),a.push(co.node(d.pos,d.pos+d.size,{class:C.join(" ")}))}return a.length?cr.create(t.doc,a):null}}}))].flat()}const ix=200;function lx(e){return[Et(()=>new Ht({key:new Tn("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Oa(n)}),apply:(t,n,o,r)=>{const s=Oa(r);return t.docChanged&&s>n.depth&&!Md(t)&&(e.log.push("pm"),e.log.length>ix&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}gn({"canvasel.attach.count":{zh:"{n} 张",en:"{n} cards"},"canvasel.attach.child":{zh:"设为子节点",en:"Attach as child"},"canvasel.attach.sibling":{zh:"设为同级节点",en:"Attach as sibling"},"canvasel.add.child":{zh:"新建子卡片(Tab)",en:"New child card (Tab)"},"canvasel.add.sibling":{zh:"新建兄弟卡片(回车)",en:"New sibling card (Enter)"},"canvasel.link.drag":{zh:"拖出连线(落在卡片上 = 设为子节点,按住 Shift = 自由连线)",en:"Drag to connect (onto a card = make it a child; hold Shift for a free connector)"}});const Pt=e=>`c:${e}`,hn=e=>`e:${e}`,mu=e=>`t:${e}`,tt=e=>e.slice(2),Rs=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Vr=e=>typeof e=="string"&&e?e:null,za=e=>ta(e)?e:null,bc=e=>{const t=ta(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function Js(e){if(!e||typeof e!="object")return null;const t=e,n=Vr(t.ref);if(n)return{ref:n};const o=Vr(t.id);return o?{id:o}:t.main===!0?{main:!0}:null}const yr=e=>e.ref?Pt(e.ref):e.id?hn(e.id):e.main?he:null;function An(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const r=o,s=Vr(r.id);if(!s||n.has(s))continue;if(r.type==="connector"){const m=Js(r.from),g=Js(r.to);if(!m||!g)continue;n.add(s),t.push({kind:"connector",id:s,from:m,to:g,label:Vr(r.label),color:za(r.color),fromEnd:r.fromEnd==="arrow"?"arrow":"none",toEnd:r.toEnd==="none"?"none":"arrow"});continue}if(r.type!=="shape"&&r.type!=="text"&&r.type!=="frame")continue;const i=Rs(r.x),a=Rs(r.y),c=Rs(r.w),d=Rs(r.h);if(!(i==null||a==null||c==null||d==null||c<=0||d<=0)){if(n.add(s),r.type==="frame"){t.push({kind:"frame",id:s,x:i,y:a,w:c,h:d,title:Vr(r.title),color:za(r.color)});continue}t.push({kind:r.type==="text"?"text":"shape",id:s,x:i,y:a,w:c,h:d,shape:r.shape==="ellipse"?"ellipse":"rect",text:Vr(r.text),color:za(r.color)})}}return t}function Ui(e,t){const n=e.x+e.w/2,o=e.y+e.h/2,r=t.x+t.w/2-n,s=t.y+t.h/2-o;return Math.abs(r)*e.h>=Math.abs(s)*e.w?{x:r>=0?e.x+e.w:e.x,y:o}:{x:n,y:s>=0?e.y+e.h:e.y}}function vc(e,t){const n=Ui(e,t),o=Ui(t,e),r=Math.abs(o.x-n.x)>=Math.abs(o.y-n.y),s=Math.max(24,Math.abs(r?o.x-n.x:o.y-n.y)/2),i=Math.sign(o.x-n.x||1),a=Math.sign(o.y-n.y||1);return{p1:n,c1:r?{x:n.x+i*s,y:n.y}:{x:n.x,y:n.y+a*s},c2:r?{x:o.x-i*s,y:o.y}:{x:o.x,y:o.y-a*s},p2:o}}function ux(e,t){const{p1:n,c1:o,c2:r,p2:s}=vc(e,t),i=[n.x,o.x,r.x,s.x],a=[n.y,o.y,r.y,s.y],c=Math.min(...i),d=Math.min(...a);return{d:`M${n.x},${n.y} C${o.x},${o.y} ${r.x},${r.y} ${s.x},${s.y}`,mid:{x:(n.x+s.x)/2+(o.x+r.x-n.x-s.x)/8,y:(n.y+s.y)/2+(o.y+r.y-n.y-s.y)/8},tip:s,ang:Math.atan2(s.y-r.y,s.x-r.x),tail:n,tailAng:Math.atan2(n.y-o.y,n.x-o.x),box:{x:c,y:d,w:Math.max(1,Math.max(...i)-c),h:Math.max(1,Math.max(...a)-d)}}}function Ds(e,t,n,o=8){const{p1:r,c1:s,c2:i,p2:a}=vc(e,t);let c=r.x,d=r.y;for(let m=1;m<=24;m++){const g=m/24,C=1-g,L=C*C*C*r.x+3*C*C*g*s.x+3*C*g*g*i.x+g*g*g*a.x,M=C*C*C*r.y+3*C*C*g*s.y+3*C*g*g*i.y+g*g*g*a.y,k=L-c,z=M-d,F=k*k+z*z,J=F?Math.max(0,Math.min(1,((n.x-c)*k+(n.y-d)*z)/F)):0;if(Math.hypot(c+J*k-n.x,d+J*z-n.y)<=o)return!0;c=L,d=M}return!1}function pu(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[];for(const[n,o]of Object.entries(e))!n||typeof o!="string"||!o||o===n||t.push([n,o]);return t}function dx(e,t){const n=[...t].flatMap(a=>a===he?[he]:a.startsWith("c:")?[tt(a)]:[]),o=new Set(n),r=new Set;if(!n.length||!e.length)return{nodes:o,edgeChildren:r};const s=new Map,i=new Map;for(const[a,c]of e){s.set(a,c);const d=i.get(c);d?d.push(a):i.set(c,[a])}for(const a of n){const c=new Set;let d=a;for(;!c.has(d);){c.add(d),o.add(d);const C=s.get(d);if(!C)break;r.add(d),o.add(C),d=C}const m=[a],g=new Set;for(;m.length;){const C=m.shift();if(!g.has(C)){g.add(C);for(const L of i.get(C)??[])r.add(L),o.add(L),m.push(L)}}}return{nodes:o,edgeChildren:r}}const Gi=(e,t)=>e.x<t.x+t.w&&e.x+e.w>t.x&&e.y<t.y+t.h&&e.y+e.h>t.y;function mn(e){const t=new Map;if(!e)return t;for(const n of e.querySelectorAll(".amx-ucard[data-anchor]")){const o=n.dataset.anchor;o&&t.set(o,{x:n.offsetLeft,y:n.offsetTop,w:n.offsetWidth,h:n.offsetHeight})}return t}function pn(e){const t=e?.querySelector(".ProseMirror");return t?{x:t.offsetLeft,y:t.offsetTop,w:t.offsetWidth,h:t.offsetHeight}:null}function Ji(e,t=!1){const n=c=>!t||!c.closest(".amx-ucard"),o=c=>(c.innerText||c.textContent||"").split(/\r?\n/).map(d=>d.trim()).find(Boolean)??null,r=[...e.querySelectorAll("h1,h2,h3,h4,h5,h6")].filter(n).map(o).filter(c=>!!c),s=[...e.querySelectorAll("p,li,blockquote,pre")].filter(n).map(o).filter(c=>!!c),i=r[0]??s[0];if(!i)return null;const a=s.find((c,d)=>c!==i&&(r.length>0||d>0))??null;return{title:i,detail:a}}function fx(e,t){const n=e.classList.contains("amx-stage-overview");n&&e.classList.remove("amx-stage-overview");try{const o=[];for(const[a,c]of mn(e)){const d=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(a)}"]`),m=d?Ji(d):null;d&&m&&o.push({key:Pt(a),anchor:a,...m,h:c.h,autoHeight:Number(d.dataset.h)<=0})}const r=e.querySelector(".ProseMirror"),s=pn(e),i=r?Ji(r,!0):null;return s&&i&&o.push({key:he,anchor:he,...i,h:s.h,autoHeight:t}),o}finally{n&&e.classList.add("amx-stage-overview")}}function mx(e,t){return e.length===t.length&&e.every((n,o)=>{const r=t[o];return n.key===r?.key&&n.anchor===r.anchor&&n.title===r.title&&n.detail===r.detail&&n.h===r.h&&n.autoHeight===r.autoHeight})}const nr=24;function Er(e,t){const n=new Map;for(const o of e){if(o.kind==="connector")continue;let r={x:o.x,y:o.y,w:o.w,h:o.h};t?.move&&t.move.ids.has(hn(o.id))&&(r={...r,x:r.x+t.move.dx,y:r.y+t.move.dy}),t?.size&&t.size.id===o.id&&(r={x:r.x+t.size.dx,y:r.y+t.size.dy,w:Math.max(nr,r.w+t.size.dw),h:Math.max(nr,r.h+t.size.dh)}),n.set(o.id,r)}return n}function px({elements:e,hostRef:t,documentKey:n,sel:o,editing:r,tree:s,ghost:i,marquee:a,attach:c,overviewScale:d,mainAutoHeight:m=!0,preview:g,guides:C}){const{t:L}=Zt(),M=v.useMemo(()=>An(e),[e]),k=v.useMemo(()=>pu(s),[s]),z=v.useMemo(()=>dx(k,o),[k,o]),F=z.edgeChildren,[J,se]=v.useState(0),H=M.length+k.length,ne=[...o].filter(A=>A.startsWith("c:")).map(tt),je=o.has(he),He=H+ne.length+(je?1:0),p=d!=null&&d>0,[fe,rt]=v.useState({documentKey:"",items:[]});v.useEffect(()=>{const A=t.current;if(!A)return;let Z=0;const le=new ResizeObserver(()=>Ke()),ve=new Set,Qe=()=>{const st=new Set(A.querySelectorAll(".amx-ucard")),it=A.querySelector(".ProseMirror");it&&st.add(it);for(const mt of st)ve.has(mt)||(le.observe(mt,{box:"border-box"}),ve.add(mt));for(const mt of[...ve])st.has(mt)||(le.unobserve(mt),ve.delete(mt))},Ke=()=>{cancelAnimationFrame(Z),Z=requestAnimationFrame(()=>{Qe(),se(st=>st+1)})};Ke();const $t=new MutationObserver(Ke);return $t.observe(A,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),le.observe(A),()=>{cancelAnimationFrame(Z),$t.disconnect(),le.disconnect()}},[t]);const ie=v.useMemo(()=>mn(t.current),[t,n,fe.documentKey,J,He,i]),be=v.useMemo(()=>Er(M,i),[M,i]),me=pn(t.current);v.useLayoutEffect(()=>{if(!p)return;const A=t.current,Z=A?.querySelector(".ProseMirror");if(!A||!Z||Z.childElementCount===0)return;const le=fx(A,m);rt(ve=>ve.documentKey===n&&mx(ve.items,le)?ve:{documentKey:n,items:le})},[n,t,m,p,J]);const Ee=fe.documentKey===n?fe.items:[],Be=new Set([...ne,...je?[he]:[]]),pe=p?Ee.flatMap(A=>{if(Be.has(A.anchor))return[];const Z=A.anchor===he?me:ie.get(A.anchor);return Z?[{...A,box:Z}]:[]}):[],Ne=t.current?.dataset.amxDragscope,Ue=p&&Ne?Ee.flatMap(A=>{const Z=`.amx-stage[data-amx-dragscope="${CSS.escape(Ne)}"].amx-stage-overview`;if(Be.has(A.anchor))return[];if(A.anchor===he)return[`${Z} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...m?[`${Z} .ProseMirror:not(.unified-embed .ProseMirror){height:${A.h}px;}`]:[]];const le=`${Z} .amx-ucard[data-anchor="${CSS.escape(A.anchor)}"]`;return[`${le} > *{display:none!important;}`,...A.autoHeight?[`${le}[data-h="0"]{height:${A.h}px;}`]:[]]}).join(`
|
|
45
|
-
`):"",U=z.nodes.size>0&&Ne?(()=>{const A=`.amx-stage[data-amx-dragscope="${CSS.escape(Ne)}"]:not(.amx-stage-off)`,Z=[...ie.keys()].filter(ve=>!z.nodes.has(ve)).flatMap(ve=>[`${A} .amx-ucard[data-anchor="${CSS.escape(ve)}"]`,`${A} .amx-card-overview[data-card-label="${CSS.escape(ve)}"]`]),le=Z.length?[`${Z.join(`,
|
|
46
|
-
`)}{opacity:0.44;}`]:[];if(!z.nodes.has(he)){const ve=`${A} .ProseMirror:not(.unified-embed .ProseMirror)`;le.push(`${ve}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${ve}>:not(.amx-ucard){opacity:0.44;}`,`${A} .amx-card-overview[data-card-label="${CSS.escape(he)}"]{opacity:0.44;}`)}return le.push(`${A} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),le.join(`
|
|
47
|
-
`)})():"",ce=A=>A.ref!=null?ie.get(A.ref)??null:A.id!=null?be.get(A.id)??null:A.main?me:null,$e=A=>A===he?me:A.startsWith("c:")?ie.get(tt(A))??null:be.get(tt(A))??null;return f.jsxs("div",{className:"amx-el-layer",children:[Ue?f.jsx("style",{"data-amx-overview-rules":!0,children:Ue}):null,U?f.jsx("style",{"data-amx-related-focus-rules":!0,children:U}):null,M.filter(A=>A.kind==="frame").map(A=>f.jsx(xx,{el:A,box:be.get(A.id),sel:o.has(hn(A.id))},A.id)),M.filter(A=>A.kind!=="frame").map(A=>A.kind==="connector"?f.jsx(Ls,{el:A,a:ce(A.from),b:ce(A.to),sel:o.has(hn(A.id))},A.id):f.jsx(bx,{el:A,box:be.get(A.id),sel:o.has(hn(A.id))},A.id)),o.size===1&&[...o][0].startsWith("e:")&&be.has(tt([...o][0]))?f.jsxs(f.Fragment,{children:[f.jsx(gx,{id:tt([...o][0]),box:be.get(tt([...o][0]))}),f.jsx(Na,{node:[...o][0],box:be.get(tt([...o][0]))})]}):null,(()=>{const A=o.size===1?[...o][0]:null,Z=A?.startsWith("e:")?M.find($t=>$t.kind==="connector"&&$t.id===tt(A)):null,le=Z?ce(Z.from):null,ve=Z?ce(Z.to):null;if(!Z||!le||!ve)return null;const{p1:Qe,p2:Ke}=vc(le,ve);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":Z.id,style:{left:`${Qe.x}px`,top:`${Qe.y}px`}}),f.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":Z.id,style:{left:`${Ke.x}px`,top:`${Ke.y}px`}})]})})(),k.map(([A,Z])=>{const le=Z===he?me:ie.get(Z),ve=ie.get(A),Qe=Z===he?{main:!0}:{ref:Z};return le&&ve?f.jsx(Ls,{el:{kind:"connector",id:`t:${A}`,from:Qe,to:{ref:A},label:null},a:le,b:ve,sel:o.has(mu(A)),related:F.has(A),tree:!0},`t:${A}`):null}),ne.map(A=>{const Z=ie.get(A);return Z?f.jsx("div",{className:`amx-el-selbox${r===A?" is-editing":""}`,"data-anchor":A,style:{left:`${Z.x}px`,top:`${Z.y}px`,width:`${Z.w}px`,height:`${Z.h}px`},children:o.size===1&&r!==A?f.jsxs(f.Fragment,{children:[f.jsx(Zi,{anchor:A}),f.jsx(Qi,{node:A}),f.jsx(Na,{node:Pt(A)})]}):null},`sel:${A}`):null}),je&&me?f.jsx("div",{className:`amx-el-selbox${r===he?" is-editing":""}`,"data-main-sel":!0,style:{left:`${me.x}px`,top:`${me.y}px`,width:`${me.w}px`,height:`${me.h}px`},children:o.size===1&&r!==he?f.jsxs(f.Fragment,{children:[f.jsx(Zi,{anchor:he}),f.jsx(Qi,{node:he}),f.jsx(Na,{node:he})]}):null}):null,pe.map(A=>{const Z=A.box.h*d,le=Z<44?"title":Z<60?"summary":"full",ve=le==="title"?Math.max(8,Math.min(12,(Z-3)/1.2)):12;return f.jsxs("div",{className:"amx-card-overview","data-card-label":A.anchor,"data-overview-density":le,style:{left:`${A.box.x}px`,top:`${A.box.y}px`,width:`${A.box.w}px`,height:`${A.box.h}px`,"--amx-overview-inv":String(1/d),"--amx-overview-title-screen":`${ve}px`},children:[f.jsx("span",{className:"amx-card-overview-title",children:A.title}),A.detail?f.jsx("span",{className:"amx-card-overview-detail",children:A.detail}):null]},`overview:${A.key}`)}),g?(()=>{const A=$e(g.from);if(!A)return null;const Z=g.over?$e(g.over):null,le=Z??{x:g.x,y:g.y,w:1,h:1};return f.jsxs(f.Fragment,{children:[f.jsx(Ls,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:A,b:le,sel:!1,preview:!0}),f.jsx("div",{className:"amx-conn-target",style:{left:`${A.x}px`,top:`${A.y}px`,width:`${A.w}px`,height:`${A.h}px`}}),Z?f.jsx("div",{className:"amx-conn-target",style:{left:`${Z.x}px`,top:`${Z.y}px`,width:`${Z.w}px`,height:`${Z.h}px`}}):null]})})():null,c?(()=>{const A=c.node===he?me:ie.get(c.node),Z=ie.get(c.source);if(!A)return null;const le=3,ve=22,Qe=c.side==="n"||c.side==="s",Ke=c.side==="w"?A.x:c.side==="e"?A.x+A.w:A.x+A.w/2,$t=c.side==="n"?A.y:c.side==="s"?A.y+A.h:A.y+A.h/2;return f.jsxs(f.Fragment,{children:[Z?f.jsx(Ls,{el:{kind:"connector",id:"~attach",from:{ref:c.source},to:c.node===he?{main:!0}:{ref:c.node},label:null},a:Z,b:A,sel:!1,preview:!0}):null,f.jsx("div",{className:`amx-el-attach-target is-${c.rel}`,style:{left:`${A.x}px`,top:`${A.y}px`,width:`${A.w}px`,height:`${A.h}px`}}),f.jsx("div",{className:`amx-el-attach is-${c.rel}`,"data-attach":c.side,style:{left:`${c.side==="e"?A.x+A.w-le:c.side==="w"?A.x:A.x+(A.w-ve)/2}px`,top:`${c.side==="s"?A.y+A.h-le:c.side==="n"?A.y:A.y+(A.h-ve)/2}px`,width:`${Qe?ve:le}px`,height:`${Qe?le:ve}px`}}),f.jsxs("div",{className:`amx-el-attach-label is-${c.rel}`,style:{left:`${Ke}px`,top:`${$t}px`},children:[c.count&&c.count>1?`${L("canvasel.attach.count",{n:c.count})} · `:"",c.rel==="child"?L("canvasel.attach.child"):L("canvasel.attach.sibling")]})]})})():null,C?.map((A,Z)=>f.jsx("div",{className:`amx-el-guide is-${A.dir}`,style:{left:`${A.x}px`,top:`${A.y}px`,width:`${A.w}px`,height:`${A.h}px`}},`guide:${Z}`)),a?f.jsx("div",{className:"amx-el-marquee",style:{left:`${a.x}px`,top:`${a.y}px`,width:`${a.w}px`,height:`${a.h}px`}}):null]})}const hu=["nw","ne","sw","se"],hx=["n","e","s","w",...hu];function Zi({anchor:e}){return f.jsx(f.Fragment,{children:hx.map(t=>f.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function gx({id:e,box:t}){return f.jsx(f.Fragment,{children:hu.map(n=>f.jsx("div",{className:`amx-el-grip is-free is-${n}`,"data-grip":e,"data-corner":n,style:{left:`${(n[1]==="e"?t.x+t.w:t.x)-5}px`,top:`${(n[0]==="s"?t.y+t.h:t.y)-5}px`}},n))})}function Qi({node:e}){const{t}=Zt();return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-el-add is-child","data-add":"child","data-node":e,title:t("canvasel.add.child"),children:"+"}),f.jsx("div",{className:"amx-el-add is-sibling","data-add":"sibling","data-node":e,title:t("canvasel.add.sibling"),children:"+"})]})}const yx=["n","e","s","w"];function Na({node:e,box:t}){const{t:n}=Zt(),o=r=>t?{left:`${r==="w"?t.x:r==="e"?t.x+t.w:t.x+t.w/2}px`,top:`${r==="n"?t.y:r==="s"?t.y+t.h:t.y+t.h/2}px`}:void 0;return f.jsx(f.Fragment,{children:yx.map(r=>f.jsx("div",{className:`amx-link-dot is-${r}${t?" is-free":""}`,"data-link-from":e,title:n("canvasel.link.drag"),style:o(r)},r))})}function xx({el:e,box:t,sel:n}){const o=bc(e.color);return f.jsx("div",{className:`amx-el-frame${n?" is-sel":""}`,"data-color":o["data-color"],style:{left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,...o.style},children:f.jsx("div",{className:"amx-el-frame-bar","data-el":e.id,children:e.title??"Frame"})})}function bx({el:e,box:t,sel:n}){const o=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",r=bc(e.color);return f.jsx("div",{className:`amx-el-shape ${o}${n?" is-sel":""}`,"data-el":e.id,"data-color":r["data-color"],style:{left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,...r.style},children:e.text})}function Ls({el:e,a:t,b:n,sel:o,related:r,tree:s,preview:i}){if(!t||!n)return null;const a=ux(t,n),c=14,d={x:a.box.x-c,y:a.box.y-c,w:a.box.w+c*2,h:a.box.h+c*2},m=9,g=4.5,C=(z,F)=>{const J=Math.cos(F),se=Math.sin(F);return[`${z.x},${z.y}`,`${z.x-m*J+g*se},${z.y-m*se-g*J}`,`${z.x-m*J-g*se},${z.y-m*se+g*J}`].join(" ")},L=!s&&e.toEnd!=="none",M=!s&&e.fromEnd==="arrow",k=bc(e.color);return f.jsxs(f.Fragment,{children:[f.jsxs("svg",{className:`amx-el-conn${o?" is-sel":""}${r?" is-related":""}${s?" is-tree":""}${i?" is-preview":""}`,"data-el":e.id,"data-color":k["data-color"],style:{left:`${d.x}px`,top:`${d.y}px`,width:`${d.w}px`,height:`${d.h}px`,...k.style},viewBox:`${d.x} ${d.y} ${d.w} ${d.h}`,children:[r?f.jsx("path",{className:"amx-el-conn-halo",d:a.d}):null,f.jsx("path",{className:"amx-el-conn-core",d:a.d}),L?f.jsx("polygon",{points:C(a.tip,a.ang)}):null,M?f.jsx("polygon",{points:C(a.tail,a.tailAng)}):null]}),e.label?f.jsx("div",{className:`amx-el-label${o?" is-sel":""}`,"data-color":k["data-color"],style:{left:`${a.mid.x}px`,top:`${a.mid.y}px`,...k.style},children:e.label}):null]})}const Is=e=>typeof e=="number"&&Number.isFinite(e)?e:null,ns=e=>typeof e=="string"&&e?e:null,$a=e=>ta(e)?e:null,el=e=>e==="none"||e==="arrow"?e:null,os=e=>({x:Math.round(e.x),y:Math.round(e.y),width:Math.max(1,Math.round(e.w)),height:Math.max(1,Math.round(e.h))});function vx(e){const t=/^!\[\[([^\]\n]+)\]\]$/.exec(e.trim());return t?t[1]:null}function tl(e,t){const n=t.x+t.w/2-(e.x+e.w/2),o=t.y+t.h/2-(e.y+e.h/2);return Math.abs(n)*e.h>=Math.abs(o)*e.w?n>=0?"right":"left":o>=0?"bottom":"top"}function wx(e){const t=[],n=[],o=[],r=new Map,s=e.pages?[...e.pages].sort():[],i=Array.isArray(e.elements)?e.elements:[],a=new Set,c=[];for(const k of i){if(!k||typeof k!="object"||Array.isArray(k))continue;const z=k,F=ns(z.id);if(!F||a.has(F))continue;if(z.type==="connector"){a.add(F),c.push(z);continue}if(z.type!=="shape"&&z.type!=="text"&&z.type!=="frame")continue;const J=Is(z.x),se=Is(z.y),H=Is(z.w),ne=Is(z.h);if(J==null||se==null||H==null||ne==null||H<=0||ne<=0)continue;a.add(F);const je=`el-${F}`,He={x:J,y:se,w:H,h:ne};r.set(je,He);const p=$a(z.color);if(z.type==="frame"){const fe=ns(z.title);t.push({id:je,type:"group",...os(He),...fe?{label:fe}:{},...p?{color:p}:{}})}else n.push({id:je,type:"text",...os(He),text:typeof z.text=="string"?z.text:"",...p?{color:p}:{}})}for(const k of e.cards){const z=`card-${k.ref}`;r.set(z,k);const F=$a(k.color),J=vx(k.md),se=J&&s.length?hs(vl(J),s,e.sourcePath):null;if(J&&se){const H=J.split("|")[0],ne=H.indexOf("#"),je=ne>=0?H.slice(ne).trim():"";o.push({id:z,type:"file",...os(k),file:se,...je.length>1?{subpath:je}:{},...F?{color:F}:{}})}else o.push({id:z,type:"text",...os(k),text:k.md,...F?{color:F}:{}})}const d=[],m=k=>{if(!k||typeof k!="object")return null;const z=k,F=ns(z.ref)?`card-${z.ref}`:ns(z.id)?`el-${z.id}`:z.main===!0?"main":null;return F&&(r.has(F)||F==="main")?F:null};e.main&&r.set("main",e.main);let g=!1;const C=k=>{const z=r.get(k.fromNode),F=r.get(k.toNode);!z||!F||((k.fromNode==="main"||k.toNode==="main")&&(g=!0),d.push({...k,fromSide:tl(z,F),toSide:tl(F,z)}))};for(const k of c){const z=m(k.from),F=m(k.to);if(!z||!F||z===F)continue;const J=el(k.fromEnd),se=el(k.toEnd),H=ns(k.label),ne=$a(k.color);C({id:`edge-${k.id}`,fromNode:z,toNode:F,...J?{fromEnd:J}:{},...se?{toEnd:se}:{},...H?{label:H}:{},...ne?{color:ne}:{}})}const L=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const k of Object.keys(L)){const z=L[k];if(typeof z!="string"||!z||z===k)continue;const F=z==="m:"?"main":`card-${z}`,J=`card-${k}`;r.has(J)&&C({id:`tree-${k}`,fromNode:F,toNode:J,toEnd:"none"})}const M=[...t,...n];return e.main&&(e.main.md.trim()||g)&&M.push({id:"main",type:"text",...os(e.main),text:e.main.md}),M.push(...o),{nodes:M,edges:d}}const kx=e=>`${JSON.stringify(e,null," ")}
|
|
48
|
-
`;function Cx(e,t=1){const n=e.lastIndexOf("/"),o=n>=0?e.slice(0,n+1):"",r=e.slice(n+1).replace(/\.md$/i,"");return`${o}${r}${t>1?` ${t}`:""}.canvas`}async function Sx(e,t,n){for(let o=1;o<=50;o++){const r=Cx(t,o);if(await e.readTextFile(r).catch(()=>null)!=null)continue;const s=await e.writeTextFile(r,n,{create:!0});if(s&&s.ok===!1){if(s.current!=null)continue;throw new Error(`Could not create ${r}`)}return r}throw new Error("Too many exported canvases with the same name")}gn({"canvasstage.textTitle.connector":{zh:"连线标签",en:"Connector label"},"canvasstage.textTitle.frame":{zh:"Frame 标题",en:"Frame title"},"canvasstage.textTitle.element":{zh:"元素文字",en:"Element text"},"canvasstage.upload.fileN":{zh:"文件{n}",en:"File {n}"},"canvasstage.upload.uploading":{zh:"上传中 {name}",en:"Uploading {name}"},"canvasstage.toast.needEdit":{zh:"双击卡片(或选中后按空格)进入编辑模式,才能勾选待办、点开双链",en:"Double-click a card (or select it and press Space) to edit — then you can tick to-dos and open backlinks"},"canvasstage.toolbar.label":{zh:"画布工具",en:"Canvas tools"},"canvasstage.tool.select":{zh:"选择 (Esc)",en:"Select (Esc)"},"canvasstage.tool.pan":{zh:"抓手(或按住空格 / Alt 拖)",en:"Pan (or hold Space or Alt and drag)"},"canvasstage.tool.card":{zh:"新建卡片(双击空白同)",en:"New card (or double-click empty space)"},"canvasstage.tool.frame":{zh:"Frame:拖出范围(或点一下取默认大小)",en:"Frame: drag to size (or click for the default size)"},"canvasstage.tool.conn":{zh:"箭头:依次点父节点、子节点(Shift 或形状=自由连线)",en:"Arrow: click the parent, then the child (Shift or a shape = free connector)"},"canvasstage.shape.rect":{zh:"矩形",en:"Rectangle"},"canvasstage.shape.ellipse":{zh:"椭圆",en:"Ellipse"},"canvasstage.shape.text":{zh:"文本",en:"Text"},"canvasstage.conn.hint":{zh:"再点一个对象:卡片/正文 = 收它作子节点(按住 Shift = 改画自由连线),形状 = 自由连线;Esc 取消",en:"Now click another object: a card or the body text becomes a child node (hold Shift to draw a free connector instead), a shape gets a free connector. Esc cancels."},"canvasstage.overview.label":{zh:"低倍率简略显示",en:"Low-zoom overview"},"canvasstage.overview.off":{zh:"关闭低倍率简略显示",en:"Turn off low-zoom overview"},"canvasstage.overview.on":{zh:"开启低倍率简略显示",en:"Turn on low-zoom overview"},"canvasstage.guides.label":{zh:"对齐参考线",en:"Alignment guides"},"canvasstage.guides.off":{zh:"关闭对齐参考线",en:"Turn off alignment guides"},"canvasstage.guides.on":{zh:"开启对齐参考线",en:"Turn on alignment guides"},"canvasstage.menu.editText":{zh:"编辑文字",en:"Edit text"},"canvasstage.menu.connectTo":{zh:"连线到…",en:"Connect to…"},"canvasstage.menu.copy":{zh:"复制",en:"Copy"},"canvasstage.menu.duplicate":{zh:"重复",en:"Duplicate"},"canvasstage.menu.arrange":{zh:"一键整理",en:"Auto-arrange"},"canvasstage.menu.groupFrame":{zh:"成组为 Frame",en:"Group into a frame"},"canvasstage.menu.unwrap":{zh:"收回文档",en:"Unwrap into document"},"canvasstage.menu.delete":{zh:"删除",en:"Delete"},"canvasstage.menu.newCard":{zh:"新建卡片",en:"New card"},"canvasstage.menu.addNote":{zh:"添加笔记…",en:"Add note…"},"canvasstage.menu.fit":{zh:"适应内容",en:"Fit to content"},"canvasstage.menu.exportCanvas":{zh:"导出为 JSON Canvas",en:"Export as JSON Canvas"},"canvasstage.export.done":{zh:"已导出 JSON Canvas:{path}",en:"Exported JSON Canvas: {path}"},"canvasstage.export.failed":{zh:"导出 JSON Canvas 失败:{e}",en:"JSON Canvas export failed: {e}"},"canvasstage.color.label":{zh:"颜色",en:"Color"},"canvasstage.color.none":{zh:"无颜色",en:"No color"},"canvasstage.color.red":{zh:"红色",en:"Red"},"canvasstage.color.orange":{zh:"橙色",en:"Orange"},"canvasstage.color.yellow":{zh:"黄色",en:"Yellow"},"canvasstage.color.green":{zh:"绿色",en:"Green"},"canvasstage.color.cyan":{zh:"青色",en:"Cyan"},"canvasstage.color.purple":{zh:"紫色",en:"Purple"},"canvasstage.color.custom":{zh:"自定义颜色…",en:"Custom color…"},"canvasstage.ends.label":{zh:"箭头",en:"Arrows"},"canvasstage.ends.end":{zh:"箭头指向终点",en:"Arrow at end"},"canvasstage.ends.start":{zh:"箭头指向起点",en:"Arrow at start"},"canvasstage.ends.both":{zh:"双向箭头",en:"Arrows at both ends"},"canvasstage.ends.none":{zh:"无箭头",en:"No arrows"}});const Ex=[{v:"",nameKey:"canvasstage.color.none"},{v:"1",nameKey:"canvasstage.color.red"},{v:"2",nameKey:"canvasstage.color.orange"},{v:"3",nameKey:"canvasstage.color.yellow"},{v:"4",nameKey:"canvasstage.color.green"},{v:"5",nameKey:"canvasstage.color.cyan"},{v:"6",nameKey:"canvasstage.color.purple"}],nl=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:f.jsx(Kp,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:f.jsx(Hp,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:f.jsx(_p,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:f.jsx(ip,{size:13})}],Mx=2,Bs=168,gu=72,Aa=320,ol=12,rs=".amx-el-shape, .amx-el-frame-bar",rl="button, a[href], input, select, textarea",zx='li[data-item-type="task"], .wikilink';function Nx(e,t){const n=e.closest(zx);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Ta=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",ja=e=>ke(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),Ps=e=>[...Er(An(e).filter(t=>t.kind!=="frame"),null).values()],sl=50,Ra=new Set(["rect","ellipse","frame"]),ss={rect:"rect",ellipse:"ellipse",text:"text"};let $x=0;const al=(e,t,n,o,r,s=Bs)=>Hf(e,t,n,o,r,s,gu);function wc(e){const t=[];return e.forEach((n,o,r)=>{n.type.name==="amadeusCanvasCard"&&t.push({anchor:String(n.attrs.anchor),pos:o,idx:r,node:n})}),t}function In(e){return wc(e.state.doc)}const oc=(e,t,n)=>Us(e,t,n);function yu(e,t,n){const o=wc(e),r=o.findIndex(i=>i.anchor===n);if(r<0)return e.content.size;const s=o[oc(o,r,t)-1];return s.pos+s.node.nodeSize}function cl(e,t,n,o){const r=wc(e.doc),s=r.findIndex(C=>C.anchor===n);if(s<0)return e;const i=oc(r,s,t),a=r[s].pos,c=r[i-1],d=c.pos+c.node.nodeSize;let m;if(o){const C=r.findIndex(k=>k.anchor===o);if(C<0||C>=s&&C<i)return e;const L=oc(r,C,t);if(s>C&&s<L)return e;const M=r[L-1];m=M.pos+M.node.nodeSize}else if(m=e.doc.content.size,d===m)return e;const g=zo.fromArray(r.slice(s,i).map(C=>C.node));return e.delete(a,d).insert(m>d?m-(d-a):m,g)}function or(e,t){e.dispatch(Ws(t).setMeta("amxCanvas",!0))}function xr(e,t,n=!0){const o=In(e);let r=e.state.tr,s=!1;for(const i of o){const a=t.get(i.anchor);a&&(r=r.setNodeMarkup(i.pos,void 0,{...i.node.attrs,...a}),s=!0)}s&&(n?or(e,r):e.dispatch(r.setMeta("amxCanvas",!0).setMeta("addToHistory",!1)))}function Ax(e,t,n,o){const r=In(e).find(a=>a.anchor===t),s=e.state.schema.nodes.paragraph;if(!r||!s||o!=null&&r.node.textContent!==o)return!1;const i=s.create(null,n?e.state.schema.text(n):void 0);return e.dispatch(e.state.tr.replaceWith(r.pos+1,r.pos+r.node.nodeSize-1,i).setMeta("amxCanvas",!0)),!0}function il(e){if(!e?.childCount)return;const t=[];return e.forEach(n=>{n.type.name==="amadeusCanvasCard"?n.content.forEach(o=>t.push(o)):t.push(n)}),t.length?zo.fromArray(t):void 0}function ll(e,t=!1){return e.kind==="note"?`${t?"":"!"}[[${e.path.replace(/\.md$/i,"")}]]`:e.kind==="session"?`[[session:${e.id}|${e.title}]]`:e.path}const ul="application/x-amx-canvas";let Da=null;function Tx(e){if(!e)return null;try{const t=JSON.parse(e);if(typeof t?.token!="string"||!Array.isArray(t.mds))return null;const n=t.mds.filter(s=>typeof s=="string"),o={token:t.token,mds:n},r=s=>typeof s=="number"&&Number.isFinite(s);if(Array.isArray(t.cards)&&t.cards.length===n.length&&n.length===t.mds.length){const s=t.cards.flatMap(i=>{const a=i;return!a||typeof a.ref!="string"||!r(a.x)||!r(a.y)||!r(a.w)||a.w<=0?[]:[{ref:a.ref,x:a.x,y:a.y,w:a.w,h:r(a.h)&&a.h>0?a.h:0,...typeof a.color=="string"?{color:a.color}:{}}]});s.length===n.length&&(o.cards=s)}return Array.isArray(t.els)&&(o.els=t.els.filter(s=>!!s&&typeof s=="object"&&!Array.isArray(s))),Array.isArray(t.tree)&&(o.tree=t.tree.filter(s=>Array.isArray(s)&&typeof s[0]=="string"&&typeof s[1]=="string")),o}catch{return null}}const La=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),dl=(e,t)=>e.x<t.x+t.w&&e.x+e.w>t.x&&e.y<t.y+t.h&&e.y+e.h>t.y;function jx({hostRef:e,vp:t,elements:n,ghost:o,onCenter:r}){const[,s]=v.useState(0);v.useEffect(()=>{const g=e.current;if(!g)return;let C=0;const L=new Set,M=new ResizeObserver(()=>z()),k=()=>{const J=new Set(g.querySelectorAll(".amx-ucard")),se=g.querySelector(".ProseMirror");se&&J.add(se);for(const H of J)L.has(H)||(M.observe(H,{box:"border-box"}),L.add(H));for(const H of[...L])J.has(H)||(M.unobserve(H),L.delete(H))},z=()=>{cancelAnimationFrame(C),C=requestAnimationFrame(()=>{k(),s(J=>J+1)})},F=new MutationObserver(z);return F.observe(g,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),M.observe(g),z(),()=>{cancelAnimationFrame(C),F.disconnect(),M.disconnect()}},[e]);const i=e.current;if(!i)return null;const a=[];for(const[g,C]of mn(i))a.push({key:Pt(g),kind:"card",box:C});const c=pn(i);c&&a.push({key:he,kind:"main",box:c});const d=An(n),m=Er(d,o);for(const g of d){if(g.kind==="connector")continue;const C=m.get(g.id);C&&a.push({key:hn(g.id),kind:g.kind==="frame"?"frame":"shape",box:C})}return f.jsx(Xm,{hostRef:e,vp:t,items:a,onCenter:r})}function Rx({path:e,vaultRoot:t=null,active:n,getView:o,main:r,mainStored:s,elements:i,tree:a,onElements:c,onTree:d,onMain:m,timeline:g,histStepRef:C,onCommit:L,saveFile:M,parseMd:k,serializeMd:z,onBlocksDeleted:F,revealSelection:J=0,readOnly:se=!1,notePages:H,exportRef:ne,storedMd:je,children:He}){const p=v.useRef(null),{t:fe}=Zt(),rt=Af(t,e),[ie,be]=v.useState(()=>ei(rt)??{x:0,y:0,z:1}),me=v.useRef(ie);me.current=ie;const[Ee,Be]=v.useState(Um),[pe,Ne]=v.useState(Gm),[Ue,U]=v.useState(yi);v.useEffect(()=>Jm(()=>U(yi())),[]);const[ce,$e]=v.useState(Zm),A=v.useRef(ce);A.current=ce;const[Z,le]=v.useState(Qm),ve=v.useRef(Z);ve.current=Z;const[Qe,Ke]=v.useState(null),$t=v.useCallback(u=>{A.current=u,$e(u),ep(u)},[]),[st,it]=v.useState("select"),mt=v.useRef("select"),ct=v.useRef(se);ct.current=se;const un=v.useCallback(u=>{mt.current=u,it(u)},[]),[ut,Yn]=v.useState([]),vt=v.useRef([]),lt=v.useCallback(u=>{const S=typeof u=="function"?u(vt.current):u;vt.current=S,Yn(S)},[]),[Ot,on]=v.useState(null),Yt=v.useRef(null),Cn=v.useCallback(u=>{Yt.current=u,on(u)},[]),[Qn,ur]=v.useState(null),en=v.useRef(null),Xn=v.useCallback(u=>{en.current=u,ur(u)},[]),Sn=v.useRef({held:!1,used:!1}),[eo,$o]=v.useState(!1);v.useEffect(()=>{const u=p.current;if(!Qn||!u)return;const S=u.dataset.amxDragscope;if(!S)return;const N=document.createElement("style");return N.textContent=Qn===he?`.amx-stage[data-amx-dragscope="${S}"] .ProseMirror{cursor:text;}`:`.amx-stage[data-amx-dragscope="${S}"] .amx-ucard[data-anchor="${CSS.escape(Qn)}"]{cursor:text;}`,document.head.appendChild(N),()=>N.remove()},[Qn]);const Wo=v.useRef(0),[Yo,vn]=v.useState(null),[En,jn]=v.useState(null),[xo,bo]=v.useState(null),[ot,Lt]=v.useState(null),[vo,io]=v.useState(null),[Xo,Ao]=v.useState(!1),Hn=v.useRef(0),Fe=v.useCallback(()=>{cancelAnimationFrame(Hn.current),Hn.current=0,Ao(!1)},[]);v.useEffect(()=>()=>cancelAnimationFrame(Hn.current),[]);const Vt=v.useRef({raf:0,animations:[]}),y=v.useCallback(()=>{cancelAnimationFrame(Vt.current.raf),Vt.current.raf=0;const u=Vt.current.animations.splice(0);for(const S of u)S.cancel()},[]),E=v.useCallback(u=>{const S=p.current;y(),!(!S||!u.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Vt.current.raf=requestAnimationFrame(()=>{Vt.current.raf=0;let N=0;const B=_=>{Vt.current.animations.push(_);const O=()=>{Vt.current.animations=Vt.current.animations.filter(V=>V!==_)};_.addEventListener("finish",O,{once:!0}),_.addEventListener("cancel",O,{once:!0})};for(const _ of u){const O=S.querySelector(`.amx-ucard[data-anchor="${CSS.escape(_.anchor)}"]`),V=Math.hypot(_.x,_.y);if(!O||V<1)continue;const te=Math.min(126,Math.max(0,_.depth-1)*42),l=Math.round(Math.max(420,Math.min(620,360+V*.34)));N=Math.max(N,te+l);const h=O.animate([{transform:`translate(${-_.x}px, ${-_.y}px) scale(0.988)`,opacity:.94,boxShadow:"0 8px 24px rgb(0 0 0 / 18%)",offset:0,easing:"cubic-bezier(0.16, 0.82, 0.24, 1)"},{transform:`translate(${_.x*.035}px, ${_.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-_.x*.008}px, ${-_.y*.008}px) scale(0.999)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:l,delay:te,fill:"backwards"});h.id="amx-card-arrange",B(h)}if(N>0)for(const _ of S.querySelectorAll(".amx-el-conn, .amx-el-label")){const O=_.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:N,fill:"backwards"});O.id="amx-card-arrange-line",B(O)}}))},[y]),I=v.useCallback((u,S)=>{const N=p.current,B=Math.hypot(S.x,S.y);y(),!(!N||B<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Vt.current.raf=requestAnimationFrame(()=>{Vt.current.raf=0;const _=l=>{Vt.current.animations.push(l);const h=()=>{Vt.current.animations=Vt.current.animations.filter(x=>x!==l)};l.addEventListener("finish",h,{once:!0}),l.addEventListener("cancel",h,{once:!0})},O=Math.round(Math.max(400,Math.min(520,350+B*.42))),V=N.querySelector(`.amx-ucard[data-anchor="${CSS.escape(u)}"]`);if(V){const l=V.animate([{transform:`translate(${-S.x}px, ${-S.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"ease-in"},{transform:`translate(${-S.x*.54}px, ${-S.y*.54}px) scale(1.007)`,opacity:.97,boxShadow:"0 8px 24px rgb(0 0 0 / 19%)",offset:.22,easing:"cubic-bezier(0.16, 0.82, 0.24, 1)"},{transform:`translate(${S.x*.05}px, ${S.y*.05}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-S.x*.012}px, ${-S.y*.012}px) scale(1.001)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:O,fill:"none"});l.id="amx-card-attach",_(l)}const te=N.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${u}`)}"]`);if(te){const l=te.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:O,fill:"backwards"});l.id="amx-card-attach-line",_(l)}}))},[y]);v.useEffect(()=>y,[y]);const[D,K]=v.useState(null),[X,oe]=v.useState(null);v.useEffect(()=>{Ot||K(null)},[Ot]);const G=new Set(ut),ee=v.useRef(!ei(rt));v.useEffect(()=>{n&&Tf(rt,ie)},[rt,ie,n]),v.useLayoutEffect(()=>{const u=p.current;!n||!Qn||!u||!document.activeElement||!u.contains(document.activeElement)||Yf()},[n,Qn,ie]);const q=v.useRef({getView:o,onCommit:L,onElements:c,onTree:d,onMain:m,timeline:g,elements:i,tree:a,main:r,mainStored:s,saveFile:M,parseMd:k,serializeMd:z,onBlocksDeleted:F,notePages:H,path:e,storedMd:je});q.current={getView:o,onCommit:L,onElements:c,onTree:d,onMain:m,timeline:g,elements:i,tree:a,main:r,mainStored:s,saveFile:M,parseMd:k,serializeMd:z,onBlocksDeleted:F,notePages:H,path:e,storedMd:je};const ze=An(i),Pe=u=>{if(!u)return null;const S={x:u.x,y:u.y,w:u.w,...typeof u.h=="number"&&u.h>0?{h:u.h}:{}};return S.x!==0||S.y!==0||S.w!==Ko||(S.h??0)>0?S:null},Oe=()=>{const u=q.current;return{e:Fo(u.elements),t:Kt(u.tree),m:Pe(u.mainStored?u.main:null)}},_e=v.useRef(null),qe=v.useRef({past:[],future:[]}),Xe=()=>qe.current;v.useEffect(()=>{const u=Oe(),S=JSON.stringify(u);if(!(_e.current!==null&&S===_e.current)){if(_e.current!==null)try{const N=JSON.parse(_e.current),B=(O,V)=>{let te=N.t[O];const l=new Set([O]);for(;typeof te=="string"&&te&&!l.has(te);){if(te===V)return!0;l.add(te),te=N.t[te]}return!1};if(JSON.stringify(u.e)===JSON.stringify(N.e)&&JSON.stringify(u.m)===JSON.stringify(N.m)&&Object.keys(u.t).length<=Object.keys(N.t).length&&Object.keys(u.t).every(O=>typeof N.t[O]<"u"&&(JSON.stringify(u.t[O])===JSON.stringify(N.t[O])||B(O,u.t[O])))){_e.current=S;return}}catch{}_e.current=S,qe.current={past:[],future:[]},q.current.timeline.log.length=0,q.current.timeline.future.length=0}},[e,i,a,r,s]);const Ve=v.useCallback((u,S)=>{const N=q.current,B=Oe(),_=JSON.stringify(B),O=JSON.stringify({e:u.e??B.e,t:u.t??B.t,m:u.m?Pe(u.m):B.m});if(O!==_){if(S?.snap!==!1){const V=Xe();V.past.push(_),V.past.length>sl&&V.past.shift(),V.future.length=0,N.timeline.log.push("fm"),N.timeline.future.length=0;const te=N.getView();te&&te.dispatch(Ws(te.state.tr))}_e.current=O,u.e&&N.onElements(u.e),u.t&&N.onTree(u.t),u.m&&N.onMain(u.m)}},[e]),Ge=v.useCallback(u=>{const S=Fo(q.current.elements),N=u(S);N!==S&&Ve({e:N})},[Ve]),Xt=v.useCallback(u=>{const S=Xe(),N=u==="undo"?S.past:S.future,B=u==="undo"?S.future:S.past,_=N.pop();if(_==null)return!1;const O=q.current;B.push(JSON.stringify(Oe()));const V=JSON.parse(_);return _e.current=_,O.onElements(V.e),O.onTree(V.t),O.onMain(V.m??{x:0,y:0,w:Ko}),!0},[e]),Mt=v.useCallback(()=>{const u=Xe();u.past.push(JSON.stringify(Oe())),u.past.length>sl&&u.past.shift(),u.future.length=0;const S=q.current.timeline;S.log.push("fm"),S.future.length=0},[e]),wt=v.useCallback(u=>{const S=Kt(q.current.tree);return u.some(N=>typeof S[N]<"u"||Object.keys(S).some(B=>S[B]===N))},[]),Ze=v.useCallback(()=>{const u=q.current.timeline,S=u.log.length;if(S<2)return;const N=u.log[S-2],B=u.log[S-1];(N==="pm"&&B==="fm"||N==="fm"&&B==="pm")&&u.log.splice(S-2,2,"pair")},[]),Un=v.useCallback(u=>{const S=q.current.timeline,N=u==="undo"?S.log:S.future,B=u==="undo"?S.future:S.log,_=()=>{const te=q.current.getView();return!!te&&(u==="undo"?Oa(te.state):zd(te.state))>0},O=()=>(u==="undo"?Xe().past:Xe().future).length>0,V=()=>{const te=q.current.getView();return!!te&&(u==="undo"?_a:Nl)(te.state,te.dispatch)};for(;N.length;){const te=N[N.length-1];if(N.pop(),te==="pair"){if(!_()||!O())continue;return Xt(u),V(),B.push(te),!0}if(te==="fm"){if(Xt(u))return B.push(te),!0;continue}if(V())return B.push("pm"),!0}return V()},[Xt]);v.useEffect(()=>{if(C)return C.current=Un,()=>{C.current===Un&&(C.current=null)}},[C,Un]);const jt=v.useCallback((u,S)=>{const N=p.current,B=N?.getBoundingClientRect(),{x:_,y:O,z:V}=me.current;if(!N||!B)return{x:0,y:0};const te=Ln(N)||1;return{x:((u-B.left)/te-_)/V,y:((S-B.top)/te-O)/V}},[]),rn=v.useCallback(()=>{Fe();const u=p.current,S=o();if(!u||!S)return;const N=[...u.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),S.dom].map(de=>de.getBoundingClientRect());if(!N.length)return;const{x:B,y:_,z:O}=me.current,V=u.getBoundingClientRect(),te=Ln(u)||1,l=(de,R)=>(de/te-R)/O,h=Math.min(...N.map(de=>l(de.left-V.left,B))),x=Math.min(...N.map(de=>l(de.top-V.top,_))),w=Math.max(...N.map(de=>l(de.right-V.left,B))),$=Math.max(...N.map(de=>l(de.bottom-V.top,_))),Y=w-h,ae=$-x;if(Y<=0||ae<=0)return;const ye=48,W=Math.max(Ur,Math.min(1,Math.min((V.width/te-ye*2)/Y,(V.height/te-ye*2)/ae)));be({z:W,x:(V.width/te-Y*W)/2-h*W,y:(V.height/te-ae*W)/2-x*W})},[o,Fe]),lo=v.useCallback(u=>{Fe();const S=p.current;if(!S)return;const{x:N,y:B,z:_}=me.current,O=Math.max(Ur,Math.min(As,_*u));if(O===_)return;const V=Ln(S)||1,te=S.getBoundingClientRect().width/V/2,l=S.getBoundingClientRect().height/V/2;be({z:O,x:te-(te-N)*O/_,y:l-(l-B)*O/_})},[Fe]),Uo=v.useCallback((u,S)=>{Fe();const N=p.current;if(!N)return;const B=Ln(N)||1,_=N.getBoundingClientRect(),O=me.current.z;be({z:O,x:_.width/B/2-u*O,y:_.height/B/2-S*O})},[Fe]);v.useEffect(()=>{const u=p.current;if(!se||!u)return;const S=()=>{const N=q.current.getView(),B=document.getSelection();if(!N||!B||B.isCollapsed||!B.rangeCount)return;const _=B.getRangeAt(0),O=l=>N.dom.contains(l.nodeType===3?l.parentNode:l),V=O(_.startContainer),te=O(_.endContainer);if(!(!V&&!te))try{const l=N.state.doc,h=V?N.posAtDOM(_.startContainer,_.startOffset):0,x=te?N.posAtDOM(_.endContainer,_.endOffset):l.content.size,w=Ie.between(l.resolve(Math.min(h,x)),l.resolve(Math.max(h,x)));w.eq(N.state.selection)||N.dispatch(N.state.tr.setSelection(w))}catch{}};return u.addEventListener("copy",S,!0),()=>u.removeEventListener("copy",S,!0)},[se]),v.useEffect(()=>{const u=p.current;if(!n||!u)return;const S=N=>{const B=N.detail?.rect;if(!B)return;const _=jt(B.left+B.width/2,B.top+B.height/2);Uo(_.x,_.y),N.preventDefault()};return u.addEventListener("amx-reveal",S),()=>u.removeEventListener("amx-reveal",S)},[n,jt,Uo]);const $r=v.useRef(rn);$r.current=rn,v.useEffect(()=>{if(!n||!ee.current)return;ee.current=!1;const u=setTimeout(()=>$r.current(),220);return()=>clearTimeout(u)},[n]),v.useEffect(()=>{n||(lt([]),un("select"),Cn(null),Lt(null),io(null),Xn(null))},[n]),v.useEffect(()=>{if(!ot)return;const u=S=>{S.target?.closest?.(".ctx-menu")||Lt(null)};return window.addEventListener("pointerdown",u,!0),window.addEventListener("contextmenu",u,!0),()=>{window.removeEventListener("pointerdown",u,!0),window.removeEventListener("contextmenu",u,!0)}},[ot]);const Fn=v.useCallback(u=>{const S=new Map;for(const[B,_]of mn(p.current))S.set(Pt(B),_);for(const[B,_]of Er(An(q.current.elements),u))S.set(hn(B),_);const N=pn(p.current);return N&&S.set(he,N),S},[]),On=v.useRef(!1);v.useEffect(()=>()=>{On.current=!0},[]);const wo=v.useCallback(async(u,S,N)=>{const B=An(q.current.elements).find(V=>V.id===u);if(!B)return;const _=(B.kind==="connector"?B.label:B.kind==="frame"?B.title:B.text)??"",O=await qa(N,_);O==null||On.current||An(q.current.elements).some(V=>V.id===u)&&Ge(V=>Tg(V,u,S,O.trim()))},[Ge]),To=v.useCallback((u,S)=>{const N=q.current,B=N.getView(),_=new Set(u.filter(h=>h.startsWith("c:")).map(tt));let O=!1;if(B&&_.size){const h=S??"",x=new Map;for(const w of In(B))_.has(w.anchor)&&String(w.node.attrs.color??"")!==h&&x.set(w.anchor,{color:h});x.size&&(xr(B,x),N.onCommit(),O=!0)}const V=new Set(u.filter(h=>h.startsWith("e:")).map(tt));if(!V.size)return;const te=Fo(q.current.elements),l=Ig(te,V,S);l!==te&&(Ve({e:l}),O&&Ze())},[Ve,Ze]),uo=v.useCallback((u,S,N,B,_)=>{const O=q.current.getView(),V=O?.state.schema.nodes.amadeusCanvasCard,te=O?.state.schema.nodes.paragraph;if(!O||!V||!te)return null;const l=No(O.state.doc),h={x:u,y:S,w:Jt,h:80},x=[...mn(p.current).values(),...Ps(q.current.elements)],w=pn(p.current);w&&x.push(w);const $=Gr([h],x),Y=u+$.x,ae=S+$.y,ye=_?.childCount?_:te.create(null,B?O.state.schema.text(B):void 0),W=V.createAndFill({anchor:l,x:Math.round(Y),y:Math.round(ae),w:Jt,h:0},ye);if(!W)return null;const de=N?yu(O.state.doc,Kt(q.current.tree),N):O.state.doc.content.size;return or(O,O.state.tr.insert(de,W)),q.current.onCommit(l),lt([Pt(l)]),!B&&!_?.childCount&&Q.current.enterNodeEdit(Pt(l)),l},[Fn]),Go=v.useCallback((u,S)=>{const N=q.current.saveFile;N&&u.forEach((B,_)=>{const O=B.name||ke("canvasstage.upload.fileN",{n:_+1}),V=ke("canvasstage.upload.uploading",{name:O}),te=Q.current.addCardAt(S.x-Jt/2+_*24,S.y-24+_*24,void 0,V);te&&N(B).then(l=>{const h=q.current.getView(),x=h?In(h).find(w=>w.anchor===te&&w.node.textContent===V)??In(h).find(w=>w.node.textContent===V):null;!h||!x||(l?(Ax(h,x.anchor,l,V),q.current.onCommit()):Q.current.removeSel([Pt(x.anchor)]))})})},[]),Gn=v.useCallback((u,S,N=0)=>{const B=u.trim();if(!B)return null;const _=q.current.parseMd?.(B)??null;return Q.current.addCardAt(S.x-Jt/2+N*24,S.y-24+N*24,void 0,B,il(_))},[]),Jn=v.useCallback(u=>{const S=Kt(q.current.tree),N=u(S);return N===S?!1:(Ve({t:N}),!0)},[Ve]),_n=v.useCallback(u=>u===he?pn(p.current):mn(p.current).get(u)??null,[]),Ar=v.useCallback((u,S,N,B,_=0)=>{const O=_n(u);if(!O)return null;const V=Kt(q.current.tree),te=V[u],l=S==="child"?u:typeof te=="string"&&te?te:"",h=(l?vr(V,l):[u]).map(_n).filter(Boolean),x=80,w=32,Y=S==="child"?N==="w"?O.x-B-x:O.x+O.w+x:h.length?Math.min(...h.map(R=>R.x)):O.x,ae=h.length?Math.min(...h.map(R=>R.y))-w-_:O.y,ye=h.length?Math.max(...h.map(R=>R.y+R.h))+w:O.y,W=N==="n"?ae:ye,de=S==="child"?vr(V,u).length?W:O.y:W;return{parent:l,x:Math.round(Y),y:Math.round(de)}},[_n]),jo=v.useCallback((u,S,N,B=80)=>{const _=_n(u);if(!_)return null;const O=Kt(q.current.tree),V=O[u],te=S==="child"?u:typeof V=="string"&&V?V:"",l=S==="child"?_:te?_n(te):_;if(!l)return null;const h=q.current.getView(),x=h?In(h).map(Se=>Se.anchor):[],$=(te?vr(O,te):S==="child"?vr(O,u):x.filter(Se=>typeof O[Se]!="string"||!O[Se])).map(Se=>_n(Se)).filter(Boolean),Y=l.x+l.w/2,ae=[...mn(p.current).values(),...Ps(q.current.elements)],ye=pn(p.current);ye&&ae.push(ye);const W=80,de=32;let R=null;for(const Se of[1,-1]){const we=$.filter(cn=>(cn.x+cn.w/2-Y)*Se>0),We=Se>0?l.x+l.w+W:l.x-W-N,Rt=we.length?Math.max(...we.map(cn=>cn.y+cn.h))+de:l.y,_t=Gr([{x:We,y:Rt,w:N,h:B}],ae,{x:Se,y:0}),wn=Math.hypot(_t.x,_t.y)*100+we.length*32+(Se<0?6:0);(!R||wn<R.score)&&(R={x:We+_t.x,y:Rt+_t.y,score:wn})}return R?{parent:te,x:Math.round(R.x),y:Math.round(R.y)}:null},[Fn,_n]),Jo=v.useCallback((u,S)=>{const N=jo(u,S,Jt);if(!N)return;const B=uo(N.x,N.y,N.parent||void 0);B&&N.parent&&Jn(_=>Br(_,B,N.parent))&&Ze()},[jo,uo,Jn,Ze]),ko=v.useCallback((u,S)=>{const N=[...new Set(typeof u=="string"?[u]:u)],B=new Set(N),_=mn(p.current),O=N[0],V=O?_.get(O):null;if(!V||!O)return null;const te=Ar(S.node,S.rel,S.side,V.w,V.h);if(!te)return null;const l=Kt(q.current.tree),h=N.filter(Se=>!(typeof l[Se]=="string"&&B.has(l[Se])));if(!h.length||h.includes(te.parent))return null;const x=N.flatMap(Se=>{const we=_.get(Se);return we?[{anchor:Se,box:we}]:[]});if(!x.length)return null;const w=te.x-V.x,$=te.y-V.y,Y=x.map(({box:Se})=>({...Se,x:Se.x+w,y:Se.y+$})),ae=[..._].filter(([Se])=>!B.has(Se)).map(([,Se])=>Se),ye=pn(p.current);ye&&ae.push(ye),ae.push(...Ps(q.current.elements));const W=Gr(Y,ae,{x:w,y:$}),de=w+W.x,R=$+W.y;return{sources:N,sourceSet:B,boxes:_,primary:O,roots:h,moving:x,slot:te,dx:de,dy:R}},[Ar]),Bn=v.useCallback((u,S)=>{const N=[...new Set(typeof u=="string"?[u]:u)],B=N[0];if(!B)return null;const _=new Set(N),O=48,V=ye=>Math.min(38,Math.max(18,ye*.32)),te=Kt(q.current.tree),l=ye=>{let W=ye;const de=new Set;for(;typeof W=="string"&&W&&!de.has(W);){if(_.has(W))return!0;de.add(W),W=te[W]}return!1},x=[...mn(p.current)].filter(([ye])=>!_.has(ye)&&!l(ye)),w=pn(p.current);w&&x.push([he,w]);let $=null;for(const[ye,W]of x){if(S.x<W.x-O||S.x>W.x+W.w+O||S.y<W.y-O||S.y>W.y+W.h+O)continue;const de=V(W.w),R=V(W.h),Se=18,we=[["e",Math.abs(W.x+W.w-S.x),S.x>W.x+W.w?O:de,S.y>=W.y-Se&&S.y<=W.y+W.h+Se],["w",Math.abs(S.x-W.x),S.x<W.x?O:de,S.y>=W.y-Se&&S.y<=W.y+W.h+Se],["s",Math.abs(W.y+W.h-S.y),S.y>W.y+W.h?O:R,S.x>=W.x-Se&&S.x<=W.x+W.w+Se],["n",Math.abs(S.y-W.y),S.y<W.y?O:R,S.x>=W.x-Se&&S.x<=W.x+W.w+Se]];for(const[We,Rt,Ct,_t]of we){if(!_t||Rt>Ct)continue;const wn=Rt/Math.max(1,Ct);(!$||wn<$.score)&&($={node:ye,side:We,rel:We==="e"||We==="w"?"child":"sibling",score:wn})}}if(!$)return null;const Y={node:$.node,side:$.side,rel:$.rel};return ko(N,Y)?{source:B,count:N.length,...Y}:null},[ko]),Ro=v.useCallback((u,S)=>{const N=q.current.getView(),B=ko(u,S);if(!N||!B)return!1;const{sources:_,sourceSet:O,boxes:V,primary:te,roots:l,moving:h,slot:x,dx:w,dy:$}=B,Y=Kt(q.current.tree);let ae=Kt(Y);for(const de of l)if(delete ae[de],x.parent){const R=Br(ae,de,x.parent);if(R===ae)return!1;ae=R}let ye=N.state.tr;for(const de of In(N)){const R=V.get(de.anchor);O.has(de.anchor)&&R&&(ye=ye.setNodeMarkup(de.pos,void 0,{...de.node.attrs,x:Math.round(R.x+w),y:Math.round(R.y+$)}))}const W=l.filter(de=>(typeof Y[de]=="string"?Y[de]:"")!==x.parent);for(const de of W)ye=cl(ye,ae,de,x.parent);return or(N,ye),q.current.onCommit(),W.length&&Jn(R=>{let Se=Kt(R);for(const we of l)delete Se[we],x.parent&&(Se=Br(Se,we,x.parent));return Se})&&Ze(),_.length===1?I(te,{x:w,y:$}):E(h.map(({anchor:de})=>({anchor:de,x:w,y:$,depth:l.includes(de)?1:2}))),lt(_.map(Pt)),!0},[ko,Jn,Ze,E,I]),Co=v.useCallback((u,S)=>{const N=Kt(q.current.tree);if(N[u]===S)return;const B=Br(N,u,S);if(B===N)return;const _=q.current.getView();let O=!1;if(_){const V=cl(_.state.tr,B,u,S);V.steps.length&&(or(_,V),O=!0)}Ve({t:B}),O&&Ze()},[Ve,Ze]),So=v.useCallback((u,S,N)=>{const B=V=>V===he?he:V.startsWith("c:")?tt(V):null,_=B(u),O=B(S);_&&O&&O!==he&&!N?Co(O,_):Ge(V=>Ng(V,u,S))},[Co,Ge]),Tr=v.useCallback((u,S,N)=>{Ge(B=>$g(B,new Set(u),{fromEnd:S,toEnd:N}))},[Ge]),sn=v.useCallback(async()=>{const u=q.current.getView(),S=p.current;if(!u||!S||!n)return;const N=q.current.storedMd,B=x=>N?.(x.content)?.trim()||x.textBetween(0,x.content.size,`
|
|
49
|
-
|
|
50
|
-
`),_=mn(S),O=In(u).map(x=>{const w=x.node.attrs,$=_.get(x.anchor)??{x:Number(w.x)||0,y:Number(w.y)||0,w:Number(w.w)||Jt,h:Number(w.h)||80};return{ref:x.anchor,...$,color:w.color,md:B(x.node)}}),V=[];u.state.doc.forEach(x=>{x.type.name!=="amadeusCanvasCard"&&V.push(x)});const te=pn(S),l=V.length?N?.(zo.fromArray(V))?.trim()??"":"",h=wx({cards:O,main:te?{...te,md:l}:null,elements:q.current.elements,tree:q.current.tree,pages:q.current.notePages?.(),sourcePath:e});try{const x=await Sx(bn,e,kx(h));ir({text:ke("canvasstage.export.done",{path:x}),level:"success"})}catch(x){ir({text:ke("canvasstage.export.failed",{e:_l(x)}),level:"error"})}},[n,e]);v.useEffect(()=>{if(!ne||!n||se)return;const u=()=>{sn()};return ne.current=u,()=>{ne.current===u&&(ne.current=null)}},[ne,n,se,sn]);const to=v.useCallback((u,S,N,B)=>{let _="";Ge(O=>(_=fs(O,"s"),[...O,B?eu(_,u,B):zg(_,u,S,N)])),_&<([hn(_)])},[Ge]),At=v.useCallback((u,S,N=480,B=320)=>{let _="";Ge(O=>(_=fs(O,"f"),[...O,Dg(_,u,S,N,B)])),_&<([hn(_)])},[Ge]),an=v.useCallback(u=>{const S=Fn(null),N=u.map(V=>S.get(V)).filter(V=>!!V);if(!N.length)return;const B=32,_=Math.min(...N.map(V=>V.x))-B,O=Math.min(...N.map(V=>V.y))-B;At(_,O,Math.max(...N.map(V=>V.x+V.w))+B-_,Math.max(...N.map(V=>V.y+V.h))+B-O)},[Fn,At]),fo=v.useCallback(u=>{const S=An(q.current.elements),N=u.filter(O=>O.startsWith("e:")).map(O=>S.find(V=>V.id===tt(O))).filter(O=>O?.kind==="frame");if(!N.length)return u;const B=Fn(null),_=new Set(u);for(const O of N)for(const[V,te]of B)_.has(V)||te.x>=O.x&&te.y>=O.y&&te.x+te.w<=O.x+O.w&&te.y+te.h<=O.y+O.h&&_.add(V);return[..._]},[Fn]),mo=v.useCallback((u,S)=>{const N=u.filter(h=>h.startsWith("e:")).map(tt),B=u.filter(h=>h.startsWith("c:")).map(tt),_=u.filter(h=>h.startsWith("t:")).map(tt),O=B.length?q.current.getView():null,V=new Set(B),te=O?In(O).filter(h=>V.has(h.anchor)).sort((h,x)=>x.pos-h.pos):[],l=te.length>0&&(N.length>0||_.length>0||wt(B));if(l&&Mt(),_.length){const h=Kt(q.current.tree),x=Kt(h);let w=!1;for(const $ of _)typeof x[$]<"u"&&(delete x[$],w=!0);w&&Ve({t:x},l?{snap:!1}:void 0)}if(N.length){const h=Fo(q.current.elements),x=Eg(h,new Set(N));x!==h&&Ve({e:x},l?{snap:!1}:void 0)}if(O&&te.length){let h=O.state.tr;for(const x of te)h=h.delete(x.pos,x.pos+x.node.nodeSize);or(O,h),S?.assets!==!1&&q.current.onBlocksDeleted?.(zo.from(te.map(x=>x.node).reverse())),q.current.onCommit(),l&&Ze()}lt([])},[Ve,Mt,wt,Ze]),Mn=v.useCallback(u=>{const S=q.current.getView(),N=new Set(fo(u).filter(W=>W!==he&&!W.startsWith("t:"))),B=new Set([...N].filter(W=>W.startsWith("c:")).map(tt)),_=S?In(S).filter(W=>B.has(W.anchor)):[],O=new Set(_.map(W=>W.anchor)),V=Fo(q.current.elements),te=W=>{const de=W&&typeof W=="object"?W.id:null;return typeof de=="string"&&de?de:null},l=W=>!!W&&typeof W=="object"&&W.type==="connector",h=V.filter(W=>!l(W)&&N.has(hn(te(W)??""))),x=new Set(h.map(te)),w=W=>{const de=Js(W);return!!de&&(de.ref?O.has(de.ref):de.id?x.has(de.id):!1)},$=V.filter(W=>l(W)&&te(W)&&w(W.from)&&w(W.to)),Y=Kt(q.current.tree),ae=[...O].flatMap(W=>typeof Y[W]=="string"&&O.has(Y[W])?[[W,Y[W]]]:[]);if(!_.length&&!h.length&&!$.length)return null;const ye=[...h,...$];return{cards:_,els:ye,tree:ae,keys:[..._.map(W=>Pt(W.anchor)),...ye.map(W=>hn(te(W)))]}},[fo]),Vn=v.useCallback((u,S,N,B,_)=>{const O=q.current,V=O.getView(),te=V?.state.schema.nodes.amadeusCanvasCard,l=V?.state.schema.nodes.paragraph;if(!V||!te||!l)return;const h=new Map,x=[];let w=V.state.tr;for(const we of u){const We=No(w.doc),Rt=Math.round(we.x+B),Ct=Math.round(we.y+_);let _t=null;if(we.node&&we.node.type===te)_t=te.create({...we.node.attrs,anchor:We,x:Rt,y:Ct},we.node.content);else{const wn=il(we.md?.trim()?O.parseMd?.(we.md.trim())??null:null)??l.create(null,we.md?.trim()?V.state.schema.text(we.md.trim()):void 0);_t=te.createAndFill({anchor:We,x:Rt,y:Ct,w:Math.round(we.w)||Jt,h:Math.round(we.h)||0,color:typeof we.color=="string"?we.color:""},wn)}_t&&(w=w.insert(w.doc.content.size,_t),h.set(we.ref,We),x.push(We))}const $=x.length>0;$&&(or(V,w),x.forEach(we=>O.onCommit(we)));const Y=Fo(q.current.elements),ae=new Map,ye=[],W=we=>we.type==="frame"?"f":we.type==="connector"?"e":"s",de=[];for(const we of S){const We=we;if(typeof We.id!="string"||!We.id)continue;if(We.type==="connector"){de.push(We);continue}const Rt=fs(Y,W(We));ae.set(We.id,Rt),Y.push({...We,id:Rt,...typeof We.x=="number"?{x:Math.round(We.x+B)}:{},...typeof We.y=="number"?{y:Math.round(We.y+_)}:{}}),ye.push(Rt)}const R=we=>{const We=Js(we);if(!We)return null;const Rt=we;if(We.ref){const Ct=h.get(We.ref);return Ct?{...Rt,ref:Ct}:null}if(We.id){const Ct=ae.get(We.id);return Ct?{...Rt,id:Ct}:null}return null};for(const we of de){const We=R(we.from),Rt=R(we.to);if(!We||!Rt)continue;const Ct=fs(Y,"e");Y.push({...we,id:Ct,from:We,to:Rt}),ye.push(Ct)}let Se=null;for(const[we,We]of N){const Rt=h.get(we),Ct=h.get(We);if(!Rt||!Ct)continue;const _t=Br(Se??Kt(q.current.tree),Rt,Ct);_t!==Se&&(Se=_t)}(ye.length||Se)&&(Ve({...ye.length?{e:Y}:{},...Se?{t:Se}:{}}),$&&Ze()),lt([...x.map(Pt),...ye.map(hn)])},[Ve,Ze]),no=v.useCallback((u,S)=>{u.clearData();const N=Mn(S);if(!N)return Da=null,u.setData("text/plain",""),null;const B=q.current.serializeMd,_=N.cards.map(h=>B?.(h.node.content)?.trim()||h.node.textBetween(0,h.node.content.size,`
|
|
51
|
-
|
|
52
|
-
`)),O=N.els.flatMap(h=>{const x=h,w=x.type==="connector"?x.label:x.type==="frame"?x.title:x.text;return typeof w=="string"&&w.trim()?[w.trim()]:[]});u.setData("text/plain",[..._,...O].join(`
|
|
53
|
-
|
|
54
|
-
`));const V=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,te=N.cards.map(h=>{const x=h.node.attrs;return{ref:h.anchor,x:Number(x.x)||0,y:Number(x.y)||0,w:Number(x.w)||Jt,h:Number(x.h)||0,...typeof x.color=="string"&&x.color?{color:x.color}:{}}}),l={token:V,mds:_,cards:te,...N.els.length?{els:N.els}:{},...N.tree.length?{tree:N.tree}:{}};try{u.setData(ul,JSON.stringify(l))}catch{}return Da={token:V,nodes:N.cards.map(h=>h.node)},Wo.current=0,N},[Mn]),T=v.useCallback((u,S)=>{const N=q.current.getView();if(!N)return!1;const B=Da,_=!!B&&B.token===u.token&&(B.nodes.length===0||B.nodes[0].type===N.state.schema.nodes.amadeusCanvasCard);let O;if(_&&B)O=B.nodes.map(h=>({ref:String(h.attrs.anchor),x:Number(h.attrs.x)||0,y:Number(h.attrs.y)||0,w:Number(h.attrs.w)||Jt,h:Number(h.attrs.h)||0,node:h}));else if(u.cards)O=u.cards.map((h,x)=>({...h,md:u.mds[x]}));else{const h=u.mds.filter(x=>x.trim());return h.length?(h.forEach((x,w)=>Q.current.addCardMd(x,S,w)),!0):!1}const V=u.els??[],te=O.map(h=>h.x),l=O.map(h=>h.y);for(const h of V){const x=h;typeof x.x=="number"&&typeof x.y=="number"&&(te.push(x.x),l.push(x.y))}return te.length?(Vn(O,V,u.tree??[],S.x-Math.min(...te),S.y-Math.min(...l)),!0):!1},[Vn]),P=v.useCallback(u=>{const S=Mn(u);S&&Vn(S.cards.map(N=>({ref:N.anchor,x:Number(N.node.attrs.x)||0,y:Number(N.node.attrs.y)||0,w:Number(N.node.attrs.w)||Jt,h:Number(N.node.attrs.h)||0,node:N.node})),S.els,S.tree,ti,ti)},[Mn,Vn]),ue=v.useCallback(u=>{const S=N=>{N.clipboardData&&(N.preventDefault(),N.stopImmediatePropagation(),no(N.clipboardData,u))};document.addEventListener("copy",S,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",S,{capture:!0})}p.current?.focus({preventScroll:!0})},[no]),ge=v.useCallback((u,S)=>{const N=q.current.getView();if(!N||u!==he&&!u.startsWith("c:"))return;let B=null,_=null;if(u===he)N.state.doc.forEach((O,V)=>{B==null&&O.type.name!=="amadeusCanvasCard"&&(B=Math.min(N.state.doc.content.size,V+O.nodeSize-1))}),_=O=>{const V=N.state.doc.resolve(O);for(let te=V.depth;te>0;te--)if(V.node(te).type.name==="amadeusCanvasCard")return!1;return!0};else{const O=In(N).find(V=>V.anchor===tt(u));O&&(B=Math.min(N.state.doc.content.size,O.pos+O.node.nodeSize-1),_=V=>V>O.pos&&V<O.pos+O.node.nodeSize)}if(B!=null){if(S){const O=N.posAtCoords({left:S.x,top:S.y});O&&_?.(O.pos)&&(B=O.pos)}try{N.dispatch(Ws(N.state.tr.setSelection(Ie.near(N.state.doc.resolve(B),-1))))}catch{}Xn(u===he?he:tt(u)),N.focus()}},[]),Ae=v.useCallback((u,S=!1)=>{const N=p.current;if(!N)return;const B=u===he?pn(N):u.startsWith("c:")?mn(N).get(tt(u))??null:null;if(!B)return;const _=Ln(N)||1,O=N.getBoundingClientRect(),V=O.width/_,te=O.height/_,l=Math.max(Ur,Math.min(1.5,As,V*.62/Math.max(1,B.w),te*.72/Math.max(1,B.h))),h={z:l,x:V/2-(B.x+B.w/2)*l,y:te/2-(B.y+B.h/2)*l},x={...me.current};if(Fe(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)me.current=h,be(h);else{const w=Math.hypot(h.x-x.x,h.y-x.y),$=Math.round(Math.max(460,Math.min(560,420+w*.12+Math.abs(h.z-x.z)*120))),Y=performance.now();Ao(!0);const ae=ye=>{const W=Math.min(1,(ye-Y)/$),de=W>=1?1:1-Math.exp(-8*W)*(Math.cos(6*W)+8/6*Math.sin(6*W)),R={x:x.x+(h.x-x.x)*de,y:x.y+(h.y-x.y)*de,z:x.z+(h.z-x.z)*de};me.current=R,be(R),W<1?Hn.current=requestAnimationFrame(ae):(Hn.current=0,Ao(!1))};Hn.current=requestAnimationFrame(ae)}S||(Xn(null),lt([u]),N.focus({preventScroll:!0}))},[Fe]),Re=v.useCallback(u=>{const S=p.current,N=q.current.getView();if(!S||!N)return!1;const B=Kt(q.current.tree),_=mn(S),O=new Set(_.keys()),V=at=>vr(B,at).filter(et=>O.has(et)).sort((et,Dt)=>(_.get(et)?.y??0)-(_.get(Dt)?.y??0)),te=[],l=new Map,h=new Set([u]),x=(at,et)=>{for(const Dt of V(at))h.has(Dt)||(h.add(Dt),te.push(Dt),l.set(Dt,et+1),x(Dt,et+1))};if(x(u,0),!te.length)return!1;const w=u===he?pn(S):_.get(u);if(!w)return!1;const $=96,Y=32,ae=new Map,ye=at=>{const et=at===u?w:_.get(at);if(!et)return 0;const Dt=V(at).filter(Rn=>Rn!==u&&h.has(Rn)),yn=Dt.reduce((Rn,dn)=>Rn+ye(dn),0)+Math.max(0,Dt.length-1)*Y,It=Math.max(et.h,yn);return ae.set(at,It),It};ye(u);const W=V(u).filter(at=>at!==u&&h.has(at)),de=at=>{const et=new Map,Dt=(yn,It,Rn)=>{const dn=V(yn).filter(Gt=>Gt!==u&&h.has(Gt));if(!dn.length)return;const dt=dn.reduce((Gt,zn)=>Gt+(ae.get(zn)??ye(zn)),0)+(dn.length-1)*Y;let fn=It.y+It.h/2-dt/2;for(const Gt of dn){const zn=_.get(Gt);if(!zn)continue;const fr=ae.get(Gt)??zn.h,Do={x:Rn>0?It.x+It.w+$:It.x-$-zn.w,y:fn+(fr-zn.h)/2,w:zn.w,h:zn.h};et.set(Gt,Do),Dt(Gt,Do,Rn),fn+=fr+Y}};for(const yn of[1,-1]){const It=W.filter(dt=>at.get(dt)===yn),Rn=It.reduce((dt,fn)=>dt+(ae.get(fn)??ye(fn)),0)+Math.max(0,It.length-1)*Y;let dn=w.y+w.h/2-Rn/2;for(const dt of It){const fn=_.get(dt);if(!fn)continue;const Gt=ae.get(dt)??fn.h,zn={x:yn>0?w.x+w.w+$:w.x-$-fn.w,y:dn+(Gt-fn.h)/2,w:fn.w,h:fn.h};et.set(dt,zn),Dt(dt,zn,yn),dn+=Gt+Y}}return et},R=[],Se=new Set,we=at=>{const et=at.join(",");Se.has(et)||(Se.add(et),R.push(new Map(W.map((Dt,yn)=>[Dt,at[yn]]))))};if(W.length<=9)for(let at=0;at<2**W.length;at++)we(W.map((et,Dt)=>at&1<<Dt?-1:1));else we(W.map((at,et)=>et%2?-1:1)),we(W.map((at,et)=>et<Math.ceil(W.length/2)?1:-1)),we(W.map(()=>1)),we(W.map(()=>-1));we(W.map(at=>(_.get(at)?.x??w.x)<w.x?-1:1));const We=Fn(null),Rt=new Set(te.map(Pt)),Ct=[...We].filter(([at])=>!Rt.has(at)).map(([,at])=>La(at,24));let _t=null;for(const at of R){const et=W.filter(dt=>at.get(dt)===-1).length;if(W.length>1&&(et===0||et===W.length))continue;const Dt=de(at),yn=[...Dt.values()],It=Math.min(...yn.map(dt=>dt.y)),Rn=Math.max(...yn.map(dt=>dt.y+dt.h)),dn=new Set([0]);for(let dt=1;dt<=20;dt++)dn.add(dt*72),dn.add(-dt*72);for(const dt of Ct)dn.add(Math.ceil(dt.y+dt.h+12-It)),dn.add(Math.floor(dt.y-12-Rn));Ct.length&&(dn.add(Math.ceil(Math.max(...Ct.map(dt=>dt.y+dt.h))+12-It)),dn.add(Math.floor(Math.min(...Ct.map(dt=>dt.y))-12-Rn)));for(const dt of[...dn].sort((fn,Gt)=>Math.abs(fn)-Math.abs(Gt))){const fn=new Map([...Dt].map(([Zn,oo])=>[Zn,{...oo,y:oo.y+dt}]));let Gt=0;for(const Zn of fn.values())for(const oo of Ct)dl(La(Zn,12),oo)&&Gt++;const zn=Zn=>{const oo=W.filter(po=>at.get(po)===Zn).map(po=>ae.get(po)??0);return oo.reduce((po,Zo)=>po+Zo,0)+Math.max(0,oo.length-1)*Y},fr=zn(1),Do=zn(-1),Ss=[...fn].reduce((Zn,[oo,po])=>{const Zo=_.get(oo);return Zn+(Zo?Math.hypot(po.x-Zo.x,po.y-Zo.y):0)},0),Wt=Gt*1e6+Math.abs(dt)+Math.max(fr,Do)*.18+Math.abs(fr-Do)*.04+Ss*.002+et*2;(!_t||Wt<_t.score)&&(_t={plan:fn,score:Wt})}}if(!_t)return!1;const wn=new Map([..._t.plan].map(([at,et])=>[at,{x:Math.round(et.x),y:Math.round(et.y)}])),cn=[...wn].flatMap(([at,et])=>{const Dt=_.get(at);return Dt?[{anchor:at,x:et.x-Dt.x,y:et.y-Dt.y,depth:l.get(at)??1}]:[]});return xr(N,wn),E(cn),q.current.onCommit(),S.focus({preventScroll:!0}),!0},[Fn,E]);v.useEffect(()=>{const u=p.current;!n||!u||document.activeElement&&u.contains(document.activeElement)||u.focus({preventScroll:!0})},[n]);const Q=v.useRef({mutate:Ge,writeFm:Ve,mergePair:Ze,pushFmCheckpoint:Mt,treeTouches:wt,removeSel:mo,editText:wo,boxesNow:Fn,fit:rn,zoomBy:lo,addCardAt:uo,addShapeAt:to,addFrame:At,addRelated:Jo,attachHit:Bn,applyAttach:Ro,setNodeParent:Co,expandFrames:fo,enterNodeEdit:ge,focusNode:Ae,arrangeChildren:Re,stopArrangeMotion:y,stopFocusMotion:Fe,dropFilesAt:Go,addCardMd:Gn,writeClip:no,pastePayload:T,linkNodes:So});Q.current={mutate:Ge,writeFm:Ve,mergePair:Ze,pushFmCheckpoint:Mt,treeTouches:wt,removeSel:mo,editText:wo,boxesNow:Fn,fit:rn,zoomBy:lo,addCardAt:uo,addShapeAt:to,addFrame:At,addRelated:Jo,attachHit:Bn,applyAttach:Ro,setNodeParent:Co,expandFrames:fo,enterNodeEdit:ge,focusNode:Ae,arrangeChildren:Re,stopArrangeMotion:y,stopFocusMotion:Fe,dropFilesAt:Go,addCardMd:Gn,writeClip:no,pastePayload:T,linkNodes:So},v.useEffect(()=>{const u=p.current;if(!n||!u||typeof ResizeObserver>"u")return;const S=new Set,N=new WeakMap;let B=0,_=!1;const O=()=>{if(B=0,_)return;const x=en.current,w=q.current.getView();if(!x||!w)return;const $=mn(u),Y=x===he?pn(u):$.get(x);if(!Y)return;const ae=[...$].filter(([R,Se])=>R!==x&&dl(La(Y,18),Se));if(!ae.length)return;const ye=new Map($),W=new Map,de=[];for(const[R,Se]of ae){const we=[...ye].filter(([wn])=>wn!==R).map(([,wn])=>wn),We=pn(u);We&&x!==he&&we.push(We),we.push(...Ps(q.current.elements));const Rt={x:Se.x+Se.w/2-(Y.x+Y.w/2),y:Se.y+Se.h/2-(Y.y+Y.h/2)},Ct=Gr([Se],we,Rt);if(!Ct.x&&!Ct.y)continue;const _t={...Se,x:Se.x+Ct.x,y:Se.y+Ct.y};ye.set(R,_t),W.set(R,{x:Math.round(_t.x),y:Math.round(_t.y)}),de.push({anchor:R,x:Ct.x,y:Ct.y,depth:1})}W.size&&(_=!0,xr(w,W,!1),E(de),q.current.onCommit(),requestAnimationFrame(()=>{_=!1}))},V=()=>{window.clearTimeout(B),B=window.setTimeout(O,90)},te=new ResizeObserver(x=>{for(const w of x){const $=w.target,Y={w:$.offsetWidth,h:$.offsetHeight},ae=N.get($);if(N.set($,Y),ae&&(ae.w!==Y.w||ae.h!==Y.h)){const ye=$.classList.contains("amx-ucard")?$.dataset.anchor:he;ye&&ye===en.current&&V()}}}),l=()=>{const x=new Set(u.querySelectorAll(".amx-ucard")),w=u.querySelector(".ProseMirror");w&&x.add(w);for(const $ of x)S.has($)||(S.add($),N.set($,{w:$.offsetWidth,h:$.offsetHeight}),te.observe($,{box:"border-box"}));for(const $ of[...S])x.has($)||(S.delete($),te.unobserve($))};l();const h=new MutationObserver(l);return h.observe(u,{subtree:!0,childList:!0}),()=>{window.clearTimeout(B),h.disconnect(),te.disconnect()}},[n,e,E]),v.useEffect(()=>{if(!n||J<=0)return;ee.current=!1;let u=0;const S=requestAnimationFrame(()=>{u=requestAnimationFrame(()=>{const N=q.current.getView();if(!N)return;const{$from:B}=N.state.selection;let _=he;for(let O=B.depth;O>0;O--){const V=B.node(O);if(V.type.name==="amadeusCanvasCard"){_=Pt(String(V.attrs.anchor));break}}lt([_]),Xn(_===he?he:tt(_)),Q.current.focusNode(_,!0),N.focus()})});return()=>{cancelAnimationFrame(S),cancelAnimationFrame(u)}},[n,J]),v.useEffect(()=>{const u=p.current;if(!u||!n)return;const S=()=>q.current.getView(),N=b=>q.current.onCommit(b),B=()=>u.focus({preventScroll:!0}),_=`s${++$x}`;u.dataset.amxDragscope=_;const O=document.createElement("style");document.head.appendChild(O);let V=[],te=0;const l=(b,j=!1)=>`left:${b.x}px!important;top:${b.y}px!important;${j&&"w"in b&&"h"in b?`width:${b.w}px!important;height:${b.h}px!important;`:""}`,h=`.amx-stage[data-amx-dragscope="${_}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,x=(b,j)=>{const re=[];for(const Ce of b){const xe=CSS.escape(Ce.anchor);re.push(`.amx-stage[data-amx-dragscope="${_}"] .amx-ucard[data-anchor="${xe}"]{${Ce.decl}}`),re.push(`.amx-stage[data-amx-dragscope="${_}"] .amx-el-selbox[data-anchor="${xe}"]{${l(Ce.selection)}}`)}j&&re.push(`.amx-stage[data-amx-dragscope="${_}"] .amx-el-selbox[data-main-sel]{${l(j)}}`),re.push(h),O.textContent=re.join(`
|
|
55
|
-
`)},w=(b,j,re)=>{const Ce=b===he?`.amx-stage[data-amx-dragscope="${_}"] .ProseMirror:not(.unified-embed .ProseMirror){${j}}`:`.amx-stage[data-amx-dragscope="${_}"] .amx-ucard[data-anchor="${CSS.escape(b)}"]{${j}}`,xe=b===he?`.amx-stage[data-amx-dragscope="${_}"] .amx-el-selbox[data-main-sel]{${l(re,!0)}}`:`.amx-stage[data-amx-dragscope="${_}"] .amx-el-selbox[data-anchor="${CSS.escape(b)}"]{${l(re,!0)}}`;O.textContent=`${Ce}
|
|
56
|
-
${xe}
|
|
57
|
-
${h}`},$="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",Y=()=>{O.textContent=""},ae=()=>{cancelAnimationFrame(te),te=0;for(const b of V)b.cancel();V=[]},ye=(b,j,re,Ce="amx-card-repel")=>{const xe=Math.hypot(re.x,re.y);if(xe<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;ae();const Le=Math.round(Math.max(340,Math.min(480,320+xe*.55))),De=[{transform:`translate(${-re.x}px, ${-re.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"cubic-bezier(0.16, 0.84, 0.24, 1)"},{transform:`translate(${re.x*.06}px, ${re.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-re.x*.015}px, ${-re.y*.015}px) scale(1.001)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}];te=requestAnimationFrame(()=>{te=0;const nt=b.map(ht=>u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(ht)}"]`)).filter(ht=>!!ht);if(j){const ht=u.querySelector(".ProseMirror");ht&&nt.push(ht)}for(const ht of nt){const Te=ht.animate(De,{duration:Le,fill:"none"});Te.id=Ce,V.push(Te);const Ye=()=>{V=V.filter(gt=>gt!==Te)};Te.addEventListener("finish",Ye,{once:!0}),Te.addEventListener("cancel",Ye,{once:!0})}})},W=(b,j,re)=>{Math.max(Math.abs(j.x-re.x),Math.abs(j.y-re.y),Math.abs(j.w-re.w),Math.abs(j.h-re.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(ae(),te=requestAnimationFrame(()=>{te=0;const xe=b===he?u.querySelector(".ProseMirror"):u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(b)}"]`);if(!xe)return;const Le=b===he?{marginLeft:`${j.x}px`,marginTop:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`},De=b===he?{marginLeft:`${re.x}px`,marginTop:`${re.y}px`,width:`${re.w}px`,height:`${re.h}px`}:{left:`${re.x}px`,top:`${re.y}px`,width:`${re.w}px`,height:`${re.h}px`},nt=xe.animate([Le,De],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});nt.id="amx-card-snap",V.push(nt);const ht=()=>{V=V.filter(Te=>Te!==nt)};nt.addEventListener("finish",ht,{once:!0}),nt.addEventListener("cancel",ht,{once:!0})}))},de=b=>{if(b.target?.closest?.(".amx-stage-minimap"))return;Q.current.stopFocusMotion(),b.preventDefault();const{x:j,y:re,z:Ce}=me.current,xe=Ln(u)||1;if(b.metaKey||b.ctrlKey){const Le=b.ctrlKey&&!b.metaKey?Mx:1,De=Math.max(Ur,Math.min(As,Ce*Math.exp(-b.deltaY*Le/300))),nt=u.getBoundingClientRect(),ht=(b.clientX-nt.left)/xe,Te=(b.clientY-nt.top)/xe;be({z:De,x:ht-(ht-j)*De/Ce,y:Te-(Te-re)*De/Ce})}else{const Le=b.shiftKey&&!b.deltaX?b.deltaY:b.deltaX,De=b.shiftKey?0:b.deltaY;be({z:Ce,x:j-Le/xe,y:re-De/xe})}};u.addEventListener("wheel",de,{passive:!1});let R=null,Se=-1;const we=b=>{Se=b;try{u.setPointerCapture(b)}catch{}},We=b=>{try{u.hasPointerCapture(b)&&u.releasePointerCapture(b)}catch{}},Rt=()=>Wf/(me.current.z*(Ln(u)||1)),Ct=(b,j,re)=>{const Ce=[];for(const[Le,De]of mn(u))b.has(Le)||Ce.push(De);const xe=j?null:pn(u);xe&&Ce.push(xe);for(const[Le,De]of Er(An(q.current.elements),null))re.has(Le)||Ce.push(De);return Ce},_t=(b,j)=>{const re=document.elementFromPoint(b,j);if(!re||!u.contains(re))return null;const Ce=re.closest(rs);if(Ce?.dataset.el)return hn(Ce.dataset.el);const xe=re.closest("[data-card-grip]");if(xe?.dataset.cardGrip)return xe.dataset.cardGrip===he?he:Pt(xe.dataset.cardGrip);const Le=re.closest(".amx-ucard");return Le?.dataset.anchor?Pt(Le.dataset.anchor):re.closest(".ProseMirror")?he:null},wn=b=>b===u||b.classList.contains("amx-stage-inner")||b.classList.contains("amx-el-layer"),cn=new Map;let at=null,et=null,Dt=0,yn=null,It=ni;const Rn=()=>{Zn();const b=R;R=null,b&&b.kind!=="pan"&&Qo(b)},dn=()=>{const[b,j]=[...cn.keys()],re=cn.get(b),Ce=cn.get(j);if(!re||!Ce)return null;const xe=Ln(u)||1,Le=u.getBoundingClientRect();return{x:((re.x+Ce.x)/2-Le.left)/xe,y:((re.y+Ce.y)/2-Le.top)/xe,d:Math.hypot(re.x-Ce.x,re.y-Ce.y)/xe,ids:`${b}/${j}`}},dt=()=>{const b=dn();if(!b)return;const{x:j,y:re,z:Ce}=me.current;et={d0:Math.max(1,b.d),z0:Ce,sx:(b.x-j)/Ce,sy:(b.y-re)/Ce,ids:b.ids}},fn=()=>{const b=dn();if(!b||!et)return;if(b.ids!==et.ids){dt();return}const j=Math.max(Ur,Math.min(As,et.z0*b.d/et.d0));be({z:j,x:b.x-et.sx*j,y:b.y-et.sy*j})},Gt=()=>{Dt&&window.clearTimeout(Dt),Dt=0,yn=null},zn=b=>{const j=b.target,{clientX:re,clientY:Ce}=b;yn={x:re,y:Ce},Dt=window.setTimeout(()=>{Dt=0,yn=null,Nc(j,re,Ce)==="open"&&Rn()},Of)},fr=b=>{const j=S(),re=j?In(j).map(De=>De.anchor):[],Ce=new Set([...re,he]),xe=Kt(q.current.tree);return[b===he?he:Pt(b),...re.filter(De=>tu(xe,De,b,Ce)).map(Pt)]},Do=(b,j)=>{const re=vt.current;if(j.shiftKey||j.metaKey||j.ctrlKey){const Ce=j.shiftKey&&(b===he||b.startsWith("c:"))?fr(b===he?he:tt(b)):[b],xe=re.includes(b)?re.filter(Le=>!Ce.includes(Le)):[...re,...Ce.filter(Le=>!re.includes(Le))];return lt(xe),xe.includes(b)?xe:null}return re.includes(b)?re:(lt([b]),[b])},Ss=b=>{Lt(null);const j=b.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(ae(),Q.current.stopArrangeMotion(),Q.current.stopFocusMotion(),b.pointerType==="touch"){if(cn.set(b.pointerId,{x:b.clientX,y:b.clientY}),Gt(),cn.size>=2){b.preventDefault(),Rn(),dt();return}zn(b)}if(et)return;It=b.pointerType==="touch"?oi/(me.current.z*(Ln(u)||1)):ni;const re=b.button===1;if(b.button!==0&&!re)return;const Ce=mt.current,xe=jt(b.clientX,b.clientY);if(ct.current){if(j.closest(`${rl}, .wikilink`))return;const bt=performance.now(),Nt=at;if(at=b.pointerType==="mouse"?{t:bt,x:b.clientX,y:b.clientY}:null,Nt&&bt-Nt.t<500&&Math.hypot(b.clientX-Nt.x,b.clientY-Nt.y)<6&&j.closest(".ProseMirror"))return;b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:me.current.x,vy:me.current.y},we(b.pointerId);return}const Le=en.current,De=Sn.current.held;De&&(Sn.current.used=!0);const nt=Ce==="pan"||b.altKey||re||De,ht=Ce!=="select"&&!nt,Te=Le===he?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(Le??"")}"]`);if(Le&&!nt&&(ht||!Te)&&Xn(null),nt){b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:me.current.x,vy:me.current.y},we(b.pointerId);return}if(Ra.has(Ce)){b.preventDefault(),R={kind:"create",tool:Ce,x0:xe.x,y0:xe.y,x1:xe.x,y1:xe.y},we(b.pointerId);return}if(b.pointerType==="touch"&&(Ce==="card"||ss[Ce])){b.preventDefault(),R={kind:"create",tool:Ce,x0:xe.x,y0:xe.y,x1:xe.x,y1:xe.y},we(b.pointerId);return}if(ss[Ce]){b.preventDefault(),Q.current.addShapeAt(ss[Ce],xe.x,xe.y),un("select"),B();return}if(Ce==="card"){b.preventDefault();const bt=Q.current.addCardAt(xe.x-Jt/2,xe.y-24);un("select"),bt||B();return}const Ye=j.closest("[data-grip]"),gt=j.closest("[data-card-grip][data-card-edge]"),Ft=j.closest(rs),yt=j.closest(".amx-ucard"),Nn=j.closest(".ProseMirror"),ho=!yt&&!Ft&&!!Nn&&j===Nn,Eo=!yt&&!Ft&&!!Nn&&j!==Nn,mr=!!yt&&j===yt,Dn=yt?.dataset.anchor??null;if(Ce==="select"&>?.dataset.cardGrip&>.dataset.cardEdge){const bt=gt.dataset.cardGrip,Nt=bt===he,tn=Nt?pn(u):mn(u).get(bt),nn=Nt?null:S(),qn=nn?In(nn).find(ro=>ro.anchor===bt):null;tn&&(Nt||qn)&&(b.preventDefault(),B(),lt([Nt?he:Pt(bt)]),R={kind:"card-size",key:bt,edge:gt.dataset.cardEdge,b0:tn,h0:Nt?Number(q.current.main.h)||0:Number(qn.node.attrs.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:tn},we(b.pointerId));return}const pr=Ce==="select"?j.closest("[data-link-from]"):null;if(pr?.dataset.linkFrom){b.preventDefault(),B(),R={kind:"link",from:pr.dataset.linkFrom,x0:xe.x,y0:xe.y},we(b.pointerId);return}const er=Ce==="select"?j.closest("[data-conn-end]"):null;if(er?.dataset.connEnd&&er.dataset.el){const bt=An(q.current.elements).find(nn=>nn.id===er.dataset.el),Nt=er.dataset.connEnd==="from"?"from":"to",tn=bt?.kind==="connector"?yr(Nt==="from"?bt.to:bt.from):null;b.preventDefault(),B(),bt&&tn&&(R={kind:"reconnect",id:bt.id,end:Nt,fixed:tn,x0:xe.x,y0:xe.y},we(b.pointerId));return}const Rr=j.closest(rl)?Dn??(Nn?he:null):null;if(Ce==="select"&&Rr){Xn(Rr);return}const Dr=yt&&Dn?Dn:Eo?he:null;Ce==="select"&&Dr&&en.current!==Dr&&Nx(j,b.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("canvasstage.toast.needEdit")}}));const xt=b.pointerType==="touch"&&Ce==="select"?Ft?.dataset.el?hn(Ft.dataset.el):Dn?Pt(Dn):!yt&&Nn?he:null:null;if(xt&&!vt.current.includes(xt)&&en.current!==(Dn??he)){b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:me.current.x,vy:me.current.y,tapKey:xt},we(b.pointerId);return}if(yt&&Dn&&!mr&&Ce==="select"){if(en.current===Dn)return;b.preventDefault(),B();const bt=b.shiftKey||b.metaKey||b.ctrlKey,Nt=Pt(Dn),tn=Do(Nt,b);if(!tn)return;const nn=tn,qn=[];for(const ro of nn){if(!ro.startsWith("c:"))continue;const go=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(ro))}"]`);go&&qn.push({anchor:tt(ro),ox:Number(go.dataset.x)||0,oy:Number(go.dataset.y)||0})}R={kind:"move",cards:qn,ids:new Set(nn),hit:Nt,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:bt},we(b.pointerId);return}if(Eo&&Ce==="select"){if(en.current===he)return;b.preventDefault(),B();const bt=b.shiftKey||b.metaKey||b.ctrlKey,Nt=Do(he,b);if(!Nt)return;const tn=Nt,nn=[];for(const qn of tn){if(!qn.startsWith("c:"))continue;const ro=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(qn))}"]`);ro&&nn.push({anchor:tt(qn),ox:Number(ro.dataset.x)||0,oy:Number(ro.dataset.y)||0})}R={kind:"move",cards:nn,ids:new Set(tn),hit:he,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:{x:q.current.main.x,y:q.current.main.y},mainEl:Nn,additive:bt},we(b.pointerId);return}const Mo=Ft?.dataset.el?hn(Ft.dataset.el):Dn?Pt(Dn):ho?he:null;if(Ce==="conn"){b.preventDefault(),B();const bt=Mo??(!yt&&!Ft&&j.closest(".ProseMirror")?he:null);if(!bt){Cn(null);return}const Nt=Yt.current;Nt?(Q.current.linkNodes(Nt,bt,b.shiftKey),Cn(null),un("select")):Cn(bt);return}const zs=j.closest("[data-add]");if(zs?.dataset.add&&zs.dataset.node){b.preventDefault(),B(),Q.current.addRelated(zs.dataset.node,zs.dataset.add==="child"?"child":"sibling");return}if(Ye?.dataset.grip){b.preventDefault();const bt=Er(An(q.current.elements),null).get(Ye.dataset.grip);if(!bt)return;R={kind:"size",id:Ye.dataset.grip,corner:Ye.dataset.corner??"se",b0:bt,dx:0,dy:0,dw:0,dh:0},we(b.pointerId);return}if(Mo){b.preventDefault(),B();const bt=b.shiftKey||b.metaKey||b.ctrlKey,Nt=Do(Mo,b);if(!Nt)return;const tn=Nt;if(mr&&tn.length===1&&yt.dataset.anchor){const go=yt.getBoundingClientRect(),Io=ol*me.current.z*(Ln(u)||1);if(b.clientX>=go.right-Io){const ca=mn(u).get(yt.dataset.anchor),Fc=In(S()).find(Ru=>Ru.anchor===yt.dataset.anchor);if(!ca||!Fc)return;R={kind:"card-size",key:yt.dataset.anchor,edge:"e",b0:ca,h0:Number(Fc.node.attrs.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:ca},we(b.pointerId);return}}if(Mo===he&&tn.length===1&&Nn){const go=Nn.getBoundingClientRect();if(b.clientX>go.right-ol*me.current.z*(Ln(u)||1)){const Io=pn(u);if(!Io)return;R={kind:"card-size",key:he,edge:"e",b0:Io,h0:Number(q.current.main.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:Io},we(b.pointerId);return}}const nn=Q.current.expandFrames(tn),qn=[];for(const go of nn){if(!go.startsWith("c:"))continue;const Io=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(go))}"]`);Io&&qn.push({anchor:tt(go),ox:Number(Io.dataset.x)||0,oy:Number(Io.dataset.y)||0})}const ro=nn.includes(he);R={kind:"move",cards:qn,ids:new Set(nn),hit:Mo,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:ro?{x:q.current.main.x,y:q.current.main.y}:null,mainEl:ro?u.querySelector(".ProseMirror"):null,additive:bt,growSel:nn.length>Nt.length?[...nn]:void 0},we(b.pointerId);return}if(!wn(j))return;const Ns=Q.current.boxesNow(null),sa=An(q.current.elements).find(bt=>{if(bt.kind!=="connector")return!1;const Nt=yr(bt.from),tn=yr(bt.to),nn=Nt?Ns.get(Nt):null,qn=tn?Ns.get(tn):null;return!!nn&&!!qn&&Ds(nn,qn,xe,8/me.current.z)}),Pc=sa?null:pu(q.current.tree).find(([bt,Nt])=>{const tn=Ns.get(Pt(bt)),nn=Ns.get(Nt===he?he:Pt(Nt));return!!tn&&!!nn&&Ds(nn,tn,xe,8/me.current.z)});if(b.preventDefault(),B(),sa){lt([hn(sa.id)]);return}if(Pc){lt([mu(Pc[0])]);return}const aa=b.shiftKey||b.metaKey||b.ctrlKey,ju=aa?[...vt.current]:[];if(aa||lt([]),b.pointerType==="touch"){R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:me.current.x,vy:me.current.y},we(b.pointerId);return}R={kind:"marquee",x0:xe.x,y0:xe.y,additive:aa,base:ju},we(b.pointerId)},Wt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Zn=()=>{Wt.raf&&cancelAnimationFrame(Wt.raf),Wt.raf=0},oo=()=>{const b=u.getBoundingClientRect();return{left:Math.max(b.left,0),top:Math.max(b.top,0),right:Math.min(b.right,window.innerWidth),bottom:Math.min(b.bottom,window.innerHeight)}},po=b=>ct.current||et?!1:R?R.kind!=="pan"&&R.live===!0:mt.current==="conn"&&!!Yt.current&&!b?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),Zo=b=>{Wt.raf=0;const j=document.elementFromPoint(Wt.x,Wt.y);if(!po(j))return;const{vx:re,vy:Ce}=ai(oo(),Wt.x,Wt.y);if(!re&&!Ce)return;const xe=Math.min(.05,Math.max(0,(b-Wt.t)/1e3));Wt.t=b;const Le=Ln(u)||1,De={...me.current,x:me.current.x-re*xe/Le,y:me.current.y-Ce*xe/Le};me.current=De,be(De),Ec({clientX:Wt.x,clientY:Wt.y,pointerId:Wt.id,pointerType:Wt.type,target:j??u}),Wt.raf=requestAnimationFrame(Zo)},$u=b=>{if(R&&Se!==b.pointerId)return;Wt.x=b.clientX,Wt.y=b.clientY,Wt.id=b.pointerId,Wt.type=b.pointerType;const{vx:j,vy:re}=po(b.target)?ai(oo(),b.clientX,b.clientY):{vx:0,vy:0};if(!j&&!re){Zn();return}Wt.raf||(Wt.t=performance.now(),Wt.raf=requestAnimationFrame(Zo))},Cc=()=>{R||Zn()},Sc=b=>{Ec(b),$u(b)},Ec=b=>{if(b.pointerType==="touch"&&(cn.has(b.pointerId)&&cn.set(b.pointerId,{x:b.clientX,y:b.clientY}),yn&&Math.hypot(b.clientX-yn.x,b.clientY-yn.y)>_f&&Gt()),et){fn();return}if(R&&Se!==b.pointerId)return;if(!R&&mt.current==="conn"&&Yt.current){const Te=b.target,Ye=Te.closest?.(rs),gt=Te.closest?.(".amx-ucard");let Ft=Ye?.dataset.el?hn(Ye.dataset.el):gt?.dataset.anchor?Pt(gt.dataset.anchor):!gt&&Te.closest?.(".ProseMirror")?he:null;Ft===Yt.current&&(Ft=null);const yt=jt(b.clientX,b.clientY);K({x:yt.x,y:yt.y,over:Ft});return}if(!R)return;const j=Ln(u)||1;if(R.kind==="pan"){be({...me.current,x:R.vx+(b.clientX-R.x0)/j,y:R.vy+(b.clientY-R.y0)/j});return}const re=jt(b.clientX,b.clientY);if(R.kind==="link"||R.kind==="reconnect"){(Math.abs(re.x-R.x0)>It||Math.abs(re.y-R.y0)>It)&&(R.live=!0);const Te=R.kind==="link"?R.from:R.fixed,Ye=_t(b.clientX,b.clientY);oe({from:Te,x:re.x,y:re.y,over:Ye===Te?null:Ye});return}if(R.kind==="card-size"){R.dx=re.x-R.x0,R.dy=re.y-R.y0;const Te=R.key===he;let Ye=al(R.b0,R.edge,R.dx,R.dy,!1,Te?Aa:Bs);if((Math.abs(Ye.x-R.b0.x)>It||Math.abs(Ye.y-R.b0.y)>It||Math.abs(Ye.w-R.b0.w)>It||Math.abs(Ye.h-R.b0.h)>It)&&(R.live=!0),R.gx=!1,R.gy=!1,ve.current&&R.live){R.others||(R.others=Ct(new Set(Te?[]:[R.key]),Te,new Set));const gt=Bf(Ye,R.edge,R.others,Rt(),Te?Aa:Bs,gu);Ye=gt.box,R.gx=gt.guides.v.length>0,R.gy=gt.guides.h.length>0,Ke(R.gx||R.gy?si(Ye,R.others,gt.guides,1/me.current.z):null)}else Ke(null);R.next=Ye,w(R.key,Te?`margin-left:${Ye.x}px;margin-top:${Ye.y}px;width:${Ye.w}px;height:${Ye.h}px;${$}`:`left:${Ye.x}px;top:${Ye.y}px;width:${Ye.w}px;height:${Ye.h}px;${$}`,Ye),vn({move:{ids:new Set([Te?he:Pt(R.key)]),dx:0,dy:0},size:null});return}if(R.kind==="size"){const Te=R.b0,Ye=R.corner.includes("e"),gt=R.corner.includes("s"),Ft=Math.max(nr,Math.round(Ye?re.x-Te.x:Te.x+Te.w-re.x)),yt=Math.max(nr,Math.round(gt?re.y-Te.y:Te.y+Te.h-re.y));R.dx=Ye?0:Te.w-Ft,R.dy=gt?0:Te.h-yt,R.dw=Ft-Te.w,R.dh=yt-Te.h,(Math.abs(R.dw)>It||Math.abs(R.dh)>It)&&(R.live=!0),vn({move:null,size:{id:R.id,dx:R.dx,dy:R.dy,dw:R.dw,dh:R.dh}});return}if(R.kind==="create"){R.x1=re.x,R.y1=re.y,(Math.abs(R.x1-R.x0)>It||Math.abs(R.y1-R.y0)>It)&&(R.live=!0),Ra.has(R.tool)&&jn({x:Math.min(R.x0,re.x),y:Math.min(R.y0,re.y),w:Math.abs(re.x-R.x0),h:Math.abs(re.y-R.y0)});return}if(R.kind==="marquee"){R.live=!0;const Te={x:Math.min(R.x0,re.x),y:Math.min(R.y0,re.y),w:Math.abs(re.x-R.x0),h:Math.abs(re.y-R.y0)};jn(Te);const Ye=[];for(const[gt,Ft]of Q.current.boxesNow(null))Gi(Te,Ft)&&Ye.push(gt);lt(R.additive?[...new Set([...R.base,...Ye])]:Ye);return}if(R.dx=Math.round(re.x-R.x0),R.dy=Math.round(re.y-R.y0),(Math.abs(R.dx)>It||Math.abs(R.dy)>It)&&(R.live=!0),!R.align){const Te=new Set(R.cards.map(ho=>ho.anchor)),Ye=new Set([...R.ids].filter(ho=>ho.startsWith("e:")).map(tt)),gt=mn(u),Ft=Er(An(q.current.elements),null),yt=[];for(const ho of Te){const Eo=gt.get(ho);Eo&&yt.push(Eo)}const Nn=R.mainStart?pn(u):null;Nn&&yt.push(Nn);for(const ho of Ye){const Eo=Ft.get(ho);Eo&&yt.push(Eo)}R.align={base:Kf(yt),others:Ct(Te,!!R.mainStart,Ye)}}R.gx=!1,R.gy=!1;const Ce=R.align.base;if(ve.current&&R.live&&Ce){const Te=qf({...Ce,x:Ce.x+R.dx,y:Ce.y+R.dy},R.align.others,Rt());R.dx+=Math.round(Te.dx),R.dy+=Math.round(Te.dy),R.gx=Te.guides.v.length>0,R.gy=Te.guides.h.length>0,Ke(R.gx||R.gy?si({...Ce,x:Ce.x+R.dx,y:Ce.y+R.dy},R.align.others,Te.guides,1/me.current.z):null)}else Ke(null);R.live&&R.kind==="move"&&R.growSel&&(lt(R.growSel),R.growSel=void 0);const{dx:xe,dy:Le}=R;x(R.cards.map(Te=>({anchor:Te.anchor,decl:`left:${Te.ox+xe}px;top:${Te.oy+Le}px;${$}`,selection:{x:Te.ox+xe,y:Te.oy+Le}})),R.mainStart?{x:R.mainStart.x+xe,y:R.mainStart.y+Le}:void 0),R.mainStart&&R.mainEl&&(R.mainEl.style.marginLeft=`${R.mainStart.x+R.dx}px`,R.mainEl.style.marginTop=`${R.mainStart.y+R.dy}px`),vn({move:{ids:R.ids,dx:R.dx,dy:R.dy},size:null});const De=tt(R.hit),nt=!R.mainStart&&R.cards.length>0&&R.ids.size===R.cards.length?R.cards.map(Te=>Te.anchor).sort((Te,Ye)=>+(Ye===De)-+(Te===De)):[],ht=nt.length&&R.live?Q.current.attachHit(nt,re):null;bo(ht)},Qo=b=>{Y(),b.kind==="move"&&b.mainEl&&(b.mainEl.style.marginLeft="",b.mainEl.style.marginTop=""),vn(null),jn(null),bo(null),Ke(null),oe(null)},Mc=b=>{if(b.pointerType==="touch"&&(cn.delete(b.pointerId),Gt(),et)){cn.size===0&&(et=null),We(b.pointerId),R=null;return}if(R&&Se!==b.pointerId){We(b.pointerId);return}Zn();const j=R;if(R=null,We(b.pointerId),!j)return;if(j.kind==="pan"){j.tapKey&&Math.hypot(b.clientX-j.x0,b.clientY-j.y0)<oi&<([j.tapKey]);return}if(j.kind==="link"||j.kind==="reconnect"){if(Qo(j),!j.live)return;const Le=j.kind==="link"?j.from:j.fixed,De=_t(b.clientX,b.clientY);if(!De||De===Le)return;j.kind==="reconnect"?Q.current.mutate(nt=>Ag(nt,j.id,j.end,De)):Q.current.linkNodes(Le,De,b.shiftKey);return}if(j.kind==="create"){const Le=Math.abs(j.x1-j.x0),De=Math.abs(j.y1-j.y0),nt=Ra.has(j.tool)&&Le>=nr&&De>=nr?{x:Math.min(j.x0,j.x1),y:Math.min(j.y0,j.y1),w:Le,h:De}:null;let ht=null;j.tool==="frame"?nt?Q.current.addFrame(nt.x,nt.y,nt.w,nt.h):Q.current.addFrame(j.x0-Ii.w/2,j.y0-Ii.h/2):j.tool==="card"?ht=Q.current.addCardAt(j.x0-Jt/2,j.y0-24):ss[j.tool]&&Q.current.addShapeAt(ss[j.tool],j.x0,j.y0,nt??void 0),un("select"),ht||B(),Qo(j);return}if(!j.live){j.kind==="move"&&j.ids.size>1&&!j.additive&<([j.hit]),Qo(j);return}const re=S();if(j.kind==="marquee"){const Le=jt(b.clientX,b.clientY),De={x:Math.min(j.x0,Le.x),y:Math.min(j.y0,Le.y),w:Math.abs(Le.x-j.x0),h:Math.abs(Le.y-j.y0)},nt=[];for(const[ht,Te]of Q.current.boxesNow(null))Gi(De,Te)&&nt.push(ht);lt(j.additive?[...new Set([...j.base,...nt])]:nt),Qo(j);return}if(!re){Qo(j);return}let Ce=null,xe=null;if(j.kind==="card-size"){const Le=j.key===he;let De=A.current?al(j.b0,j.edge,j.dx,j.dy,!0,Le?Aa:Bs):j.next;j.gx&&(De={...De,x:j.next.x,w:j.next.w}),j.gy&&(De={...De,y:j.next.y,h:j.next.h});const nt=j.edge.includes("n")||j.edge.includes("s");Le?Q.current.writeFm({m:{...q.current.main,x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),...nt?{h:Math.round(De.h)}:{}}}):xr(re,new Map([[j.key,{x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),h:nt?Math.round(De.h):j.h0}]])),A.current&&(xe={key:j.key,from:j.next,to:De})}else if(j.kind==="size"){const Le=An(q.current.elements).find(De=>De.id===j.id);Le&&Le.kind!=="connector"&&Q.current.mutate(De=>Ql(De,j.id,{x:Math.round(Le.x+j.dx),y:Math.round(Le.y+j.dy),w:Math.max(nr,Math.round(Le.w+j.dw)),h:Math.max(nr,Math.round(Le.h+j.dh))}))}else{const Le=!j.mainStart&&j.cards.length>0&&j.ids.size===j.cards.length?j.cards.map(xt=>xt.anchor).sort((xt,Mo)=>+(Mo===tt(j.hit))-+(xt===tt(j.hit))):[],De=Le.length?Q.current.attachHit(Le,jt(b.clientX,b.clientY)):null;if(Le.length&&De&&Q.current.applyAttach(Le,De)){Qo(j);return}const nt=mn(u),ht=[];for(const xt of j.cards){const Mo=nt.get(xt.anchor);Mo&&ht.push(Mo)}if(j.mainStart){const xt=pn(u);xt&&ht.push(xt)}const Te=new Set(j.cards.map(xt=>xt.anchor)),Ye=[...nt].filter(([xt])=>!Te.has(xt)).map(([,xt])=>xt);if(!j.mainStart){const xt=pn(u);xt&&Ye.push(xt)}const gt=(j.hit.startsWith("c:")?j.cards.find(xt=>xt.anchor===tt(j.hit)):null)??j.cards[0]??(j.mainStart?{ox:j.mainStart.x,oy:j.mainStart.y}:null),Ft=j.gx?j.dx:A.current&>?ri(gt.ox+j.dx)-gt.ox:j.dx,yt=j.gy?j.dy:A.current&>?ri(gt.oy+j.dy)-gt.oy:j.dy,Nn=Ft-j.dx,ho=yt-j.dy,Eo=ht.map(xt=>({...xt,x:xt.x+Nn,y:xt.y+ho})),mr=Gr(Eo,Ye,{x:Ft,y:yt}),Dn=Ft+mr.x,pr=yt+mr.y,er={x:Dn-j.dx,y:pr-j.dy};(er.x||er.y)&&(Ce={anchors:j.cards.map(xt=>xt.anchor),main:!!j.mainStart,push:er,repel:!!(mr.x||mr.y)}),j.cards.length&&xr(re,new Map(j.cards.map(xt=>[xt.anchor,{x:Math.round(xt.ox+Dn),y:Math.round(xt.oy+pr)}])));const Rr=new Set([...j.ids].filter(xt=>xt.startsWith("e:")).map(tt)),Dr=j.mainStart?{...q.current.main,x:Math.round(j.mainStart.x+Dn),y:Math.round(j.mainStart.y+pr)}:void 0;(Rr.size||Dr)&&(Q.current.writeFm({...Rr.size?{e:Li(Fo(q.current.elements),Rr,Dn,pr)}:{},...Dr?{m:Dr}:{}}),j.cards.length&&Q.current.mergePair())}Qo(j),xe&&W(xe.key,xe.from,xe.to),Ce&&ye(Ce.anchors,Ce.main,Ce.push,Ce.repel?"amx-card-repel":"amx-card-snap"),N()},zc=b=>{if(ct.current)return;const j=document.elementFromPoint(b.clientX,b.clientY)??b.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const re=j.closest(".amx-ucard"),Ce=!re&&!!j.closest(".ProseMirror"),xe=re?.dataset.anchor?Pt(re.dataset.anchor):Ce?he:null;if(xe){if(en.current===(xe===he?he:tt(xe)))return;b.preventDefault(),b.stopPropagation(),Q.current.enterNodeEdit(xe,{x:b.clientX,y:b.clientY}),rp()&&Q.current.focusNode(xe,!0);return}const Le=j.closest(rs);if(Le?.dataset.el){b.preventDefault(),b.stopPropagation();const Te=An(q.current.elements).find(Ye=>Ye.id===Le.dataset.el);Te&&Q.current.editText(Te.id,Ta(Te),ja(Te));return}if(!wn(j))return;const De=jt(b.clientX,b.clientY),nt=Q.current.boxesNow(null),ht=An(q.current.elements).find(Te=>{if(Te.kind!=="connector")return!1;const Ye=yr(Te.from),gt=yr(Te.to),Ft=Ye?nt.get(Ye):null,yt=gt?nt.get(gt):null;return!!Ft&&!!yt&&Ds(Ft,yt,De,8/me.current.z)});b.preventDefault(),ht?Q.current.editText(ht.id,"label",ke("canvasstage.textTitle.connector")):Q.current.addCardAt(De.x-Jt/2,De.y-24)},Nc=(b,j,re)=>{if(ct.current||b.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const Ce=b.closest(rs),xe=b.closest(".amx-ucard"),Le=!xe&&!Ce&&!!b.closest(".ProseMirror");if(xe?.dataset.anchor&&en.current===xe.dataset.anchor||Le&&en.current===he)return"native";let De=Ce?.dataset.el?hn(Ce.dataset.el):xe?.dataset.anchor?Pt(xe.dataset.anchor):Le?he:null;if(!De&&!wn(b))return"skip";if(!De){const nt=jt(j,re),ht=Q.current.boxesNow(null),Te=An(q.current.elements).find(Ye=>{if(Ye.kind!=="connector")return!1;const gt=yr(Ye.from),Ft=yr(Ye.to),yt=gt?ht.get(gt):null,Nn=Ft?ht.get(Ft):null;return!!yt&&!!Nn&&Ds(yt,Nn,nt,8/me.current.z)});Te&&(De=hn(Te.id))}return De&&!vt.current.includes(De)&<([De]),Lt({x:j,y:re,key:De,at:jt(j,re)}),"open"},$c=b=>{const j=Nc(b.target,b.clientX,b.clientY);j!=="skip"&&(b.stopPropagation(),j==="open"&&b.preventDefault())},Au=b=>{const j=b.target,re=en.current;return!re||!j?!1:re===he?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(re)}"]`)};let ra=!1;const Ac=b=>{b.target?.closest?.(".ProseMirror")&&(ra=!0)},jr=()=>{ra=!1},Tc=b=>{const j=b.dataTransfer,re=j?Array.from(j.types):[];return ra||S()?.dragging?null:q.current.saveFile&&re.includes("Files")?"files":Vf(j)?"refs":Au(b)?null:re.includes("text/uri-list")||re.includes("text/plain")?"text":null},jc=b=>{if(ct.current)return;const j=S();if(Tc(b)){b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="copy"),u.classList.add("amx-dropzone");return}!j?.dragging||b.target?.closest?.(".ProseMirror")||(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"),u.classList.add("amx-dropzone"))},Lo=()=>u.classList.remove("amx-dropzone"),Rc=b=>{u.contains(b.relatedTarget)||Lo()},Dc=b=>{if(Lo(),ct.current){b.preventDefault();return}const j=S(),re=Tc(b);if(re){b.preventDefault(),b.stopPropagation();const Le=jt(b.clientX,b.clientY),De=Array.from(b.dataTransfer?.files??[]);if(re==="files"&&De.length){Q.current.dropFilesAt(De,Le);return}if(re==="refs"){const ht=q.current.path;Pf(b.dataTransfer).forEach((Te,Ye)=>Q.current.addCardMd(ll(Te,b.altKey||Te.kind==="note"&&Te.path===ht),Le,Ye));return}const nt=b.dataTransfer?.getData("text/uri-list")||b.dataTransfer?.getData("text/plain")||"";Q.current.addCardMd(nt,Le);return}if(!j?.dragging||b.target?.closest?.(".ProseMirror"))return;b.preventDefault(),b.stopPropagation();const Ce=jt(b.clientX,b.clientY),xe=j.state.selection;if(xe instanceof Me&&xe.node.type.name==="amadeusCanvasCard")xr(j,new Map([[String(xe.node.attrs.anchor),{x:Math.round(Ce.x),y:Math.round(Ce.y)}]])),N();else{const Le=xu(j,Math.round(Ce.x),Math.round(Ce.y));Le&&N(Le)}j.dragging=null,j.dom.dataset.dragging="false"},Tu=()=>{const b=u.getBoundingClientRect();return jt(b.left+b.width/2,b.top+b.height/2)},Es=b=>{if(en.current||!b.clipboardData||!S())return;const j=vt.current;if(!j.length)return;b.preventDefault();const re=Q.current.writeClip(b.clipboardData,j);b.type==="cut"&&re&&Q.current.removeSel(re.keys,{assets:!1})},Lc=b=>{if(ct.current||en.current||!b.clipboardData)return;const j=Array.from(b.clipboardData.files??[]),re=b.clipboardData.getData("text/plain")??"",Ce=Tx(b.clipboardData.getData(ul));if(!j.length&&!re.trim()&&!Ce)return;b.preventDefault();const xe=Wo.current++,Le=Tu(),De={x:Le.x+xe*24,y:Le.y+xe*24};if(j.length){Q.current.dropFilesAt(j,De);return}Ce&&Q.current.pastePayload(Ce,De)||re.trim()&&Q.current.addCardMd(re,De)},Ms=b=>{b.pointerType==="touch"&&(cn.delete(b.pointerId),Gt(),et&&cn.size===0&&(et=null))};window.addEventListener("pointerup",Ms,!0),window.addEventListener("pointercancel",Ms,!0);const Ic=b=>{b.pointerType==="touch"&&(cn.delete(b.pointerId),Gt(),et&&cn.size===0&&(et=null)),We(b.pointerId),!(R&&Se!==b.pointerId)&&Rn()};return u.addEventListener("pointerdown",Ss),u.addEventListener("pointermove",Sc),u.addEventListener("pointerleave",Cc),u.addEventListener("pointerup",Mc),u.addEventListener("pointercancel",Ic),u.addEventListener("dblclick",zc),u.addEventListener("contextmenu",$c,!0),u.addEventListener("dragover",jc),u.addEventListener("dragleave",Rc),u.addEventListener("drop",Dc),u.addEventListener("dragstart",Ac),window.addEventListener("dragend",Lo),window.addEventListener("drop",Lo),window.addEventListener("blur",Lo),window.addEventListener("dragend",jr),window.addEventListener("drop",jr),window.addEventListener("blur",jr),u.addEventListener("copy",Es,!0),u.addEventListener("cut",Es,!0),u.addEventListener("paste",Lc,!0),()=>{window.removeEventListener("pointerup",Ms,!0),window.removeEventListener("pointercancel",Ms,!0),Gt(),O.remove(),ae(),delete u.dataset.amxDragscope,u.removeEventListener("wheel",de),u.removeEventListener("pointerdown",Ss),u.removeEventListener("pointermove",Sc),u.removeEventListener("pointerleave",Cc),Zn(),u.removeEventListener("pointerup",Mc),u.removeEventListener("pointercancel",Ic),u.removeEventListener("dblclick",zc),u.removeEventListener("contextmenu",$c,!0),u.removeEventListener("dragover",jc),u.removeEventListener("dragleave",Rc),u.removeEventListener("drop",Dc),u.removeEventListener("dragstart",Ac),window.removeEventListener("dragend",Lo),window.removeEventListener("drop",Lo),window.removeEventListener("blur",Lo),window.removeEventListener("dragend",jr),window.removeEventListener("drop",jr),window.removeEventListener("blur",jr),Lo(),u.removeEventListener("copy",Es,!0),u.removeEventListener("cut",Es,!0),u.removeEventListener("paste",Lc,!0)}},[n,jt]),v.useEffect(()=>{if(!n)return;const u=()=>{Sn.current={held:!1,used:!1},$o(!1)},S=N=>{if(N.code!=="Space"||!Sn.current.held)return;const{used:B}=Sn.current;u(),N.preventDefault();const _=p.current,O=N.target;if(B||ct.current||!_||!O||!_.contains(O)||O.closest(".ProseMirror"))return;const V=vt.current;V.length===1&&(V[0].startsWith("c:")||V[0]===he)&&Q.current.enterNodeEdit(V[0])};return window.addEventListener("keyup",S,!0),window.addEventListener("blur",u),()=>{window.removeEventListener("keyup",S,!0),window.removeEventListener("blur",u),u()}},[n]);const Je=u=>{if(!n||se||u.nativeEvent.isComposing)return;const S=u.target;if((u.metaKey||u.ctrlKey)&&(u.key==="z"||u.key==="Z")){if(S.tagName==="INPUT"||S.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Un(u.shiftKey?"redo":"undo");return}if((u.metaKey||u.ctrlKey)&&!u.shiftKey&&!u.altKey&&(u.key==="y"||u.key==="Y")){if(S.tagName==="INPUT"||S.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Un("redo");return}if(u.key!=="Escape")return;const N=en.current;!N||!S.closest(".ProseMirror")||(u.preventDefault(),u.stopPropagation(),Xn(null),lt([N===he?he:Pt(N)]),p.current?.focus({preventScroll:!0}))},ft=u=>{if(!n)return;const S=u.target;if(S.closest(".ProseMirror")||S.tagName==="INPUT"||S.tagName==="TEXTAREA")return;const N=u.metaKey||u.ctrlKey;if(!u.altKey&&(N?u.key==="="||u.key==="+"||u.key==="-"||u.key==="0":u.shiftKey&&u.code==="Digit1")){u.preventDefault(),N?u.key==="0"?lo(1/me.current.z):lo(u.key==="-"?1/1.2:1.2):rn();return}if(!se){if(N&&(u.key==="a"||u.key==="A")){u.preventDefault(),lt([...mn(p.current).keys()].map(Pt).concat(ze.filter(B=>B.kind!=="connector").map(B=>hn(B.id)),[he]));return}if(N&&!u.shiftKey&&!u.altKey&&(u.key==="d"||u.key==="D")){u.preventDefault(),ut.length&&P(ut);return}if(u.key==="Escape"){u.preventDefault(),ot?Lt(null):Ot?Cn(null):st!=="select"?un("select"):lt([]);return}if(u.code==="Space"&&!N&&!u.target?.closest?.("button")){u.preventDefault(),!u.repeat&&!Sn.current.held&&(Sn.current={held:!0,used:!1},$o(!0));return}if(ut.length){if(u.key==="Delete"||u.key==="Backspace"){u.preventDefault(),mo(ut);return}if((u.key==="Enter"||u.key==="F2")&&ut.length===1&&ut[0].startsWith("e:")){u.preventDefault();const B=ze.find(_=>_.id===tt(ut[0]));B&&wo(B.id,Ta(B),ja(B));return}if((u.key==="Tab"||u.key==="Enter")&&ut.length===1&&(ut[0].startsWith("c:")||ut[0]===he)){u.preventDefault(),Jo(ut[0]===he?he:tt(ut[0]),u.key==="Tab"?"child":"sibling");return}if(u.key.startsWith("Arrow")){u.preventDefault();const B=Ff(A.current,u.shiftKey),_=u.key==="ArrowLeft"?-B:u.key==="ArrowRight"?B:0,O=u.key==="ArrowUp"?-B:u.key==="ArrowDown"?B:0;if(!_&&!O)return;const V=o(),te=fo(ut),l=te.filter(w=>w.startsWith("c:")).map(tt);if(V&&l.length){const w=mn(p.current);xr(V,new Map(l.map($=>{const Y=w.get($);return[$,{x:Math.round((Y?.x??0)+_),y:Math.round((Y?.y??0)+O)}]}))),L()}const h=new Set(te.filter(w=>w.startsWith("e:")).map(tt)),x=te.includes(he)?{...r,x:Math.round(r.x+_),y:Math.round(r.y+O)}:void 0;(h.size||x)&&(Ve({...h.size?{e:Li(Fo(i),h,_,O)}:{},...x?{m:x}:{}}),l.length&&Ze())}}}},Bt=[{id:"select",icon:f.jsx(jf,{size:14}),title:fe("canvasstage.tool.select")},{id:"pan",icon:f.jsx(sp,{size:14}),title:fe("canvasstage.tool.pan")},{id:"card",icon:f.jsx(Wa,{size:14}),title:fe("canvasstage.tool.card")},{id:"rect",icon:f.jsx(Rf,{size:14}),title:fe("canvasstage.shape.rect")},{id:"ellipse",icon:f.jsx(Df,{size:14}),title:fe("canvasstage.shape.ellipse")},{id:"text",icon:f.jsx(ap,{size:14}),title:fe("canvasstage.shape.text")},{id:"frame",icon:f.jsx(cp,{size:14}),title:fe("canvasstage.tool.frame")},{id:"conn",icon:f.jsx(th,{size:14}),title:fe("canvasstage.tool.conn")}],kt=Lf(ie),zt=(ot?.key?.startsWith("e:")?ze.find(u=>u.id===tt(ot.key))??null:null)?.kind==="connector",Tt=ot?.key?(ut.length?ut:[ot.key]).filter(u=>u.startsWith("c:")||u.startsWith("e:")):[],Kn=(()=>{if(!Tt.length)return null;const u=ot?o():null,S=Fo(i),N=_=>{if(_.startsWith("c:"))return String((u?In(u).find(V=>V.anchor===tt(_))?.node.attrs.color:"")??"");const O=S.find(V=>!!V&&typeof V=="object"&&V.id===tt(_));return typeof O?.color=="string"?O.color:""},B=N(Tt[0]);return Tt.every(_=>N(_)===B)?B:null})(),pt=Kn&&Kn.startsWith("#")?Kn:null,Wn=zt?(ut.length?ut:[ot.key]).filter(u=>u.startsWith("e:")).map(tt).filter(u=>ze.some(S=>S.kind==="connector"&&S.id===u)):[],dr=(()=>{const u=Wn.map(S=>{const N=ze.find(O=>O.kind==="connector"&&O.id===S),B=N?.kind==="connector"?N.fromEnd??ms.fromEnd:ms.fromEnd,_=N?.kind==="connector"?N.toEnd??ms.toEnd:ms.toEnd;return nl.find(O=>O.from===B&&O.to===_)?.id??null});return u.length&&u.every(S=>S===u[0])?u[0]:null})();return f.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${se?"pan":st}`:""}${se?" amx-stage-ro":""}${n&&eo?" amx-space-pan":""}${Xo?" amx-vp-focus":""}${n&&pe&&ie.z<=Ue?" amx-stage-overview":""}`,ref:p,tabIndex:-1,onKeyDownCapture:Je,onKeyDown:ft,children:[n?f.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:kt}):null,f.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${ie.x}px, ${ie.y}px) scale(${ie.z})`,"--amx-main-x":`${r.x}px`,"--amx-main-y":`${r.y}px`,"--amx-main-w":`${r.w}px`,"--amx-main-h":typeof r.h=="number"&&r.h>0?`${r.h}px`:"auto"}:void 0,children:[n?f.jsx(px,{elements:i,hostRef:p,documentKey:e,sel:G,editing:Qn,tree:a,ghost:Yo,marquee:En,attach:xo,overviewScale:pe&&ie.z<=Ue?ie.z:null,mainAutoHeight:!(typeof r.h=="number"&&r.h>0),preview:X??(Ot&&D?{from:Ot,x:D.x,y:D.y,over:D.over}:null),guides:Qe}):null,He]}),n&&Ee?f.jsx(jx,{hostRef:p,vp:ie,elements:i,ghost:Yo,onCenter:Uo}):null,n&&!se?f.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":fe("canvasstage.toolbar.label"),children:Bt.map(u=>f.jsx("button",{type:"button",title:u.title,className:st===u.id?"on":"","aria-pressed":st===u.id,onClick:()=>{un(u.id),Cn(null),p.current?.focus({preventScroll:!0})},children:u.icon},u.id))}):null,n&&Ot?f.jsx("div",{className:"amx-stage-hint",children:fe("canvasstage.conn.hint")}):null,n?f.jsx(Ym,{zoom:ie.z,onZoomBy:lo,onFit:rn,snap:ce,onSnap:u=>{$t(u),p.current?.focus({preventScroll:!0})},mini:Ee,onMini:u=>{Be(u),op(u),p.current?.focus({preventScroll:!0})},extra:f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:Z?"is-on":"","aria-pressed":Z,"aria-label":fe("canvasstage.guides.label"),title:fe(Z?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const u=!Z;ve.current=u,le(u),tp(u),p.current?.focus({preventScroll:!0})},children:f.jsx(gp,{size:12})}),f.jsx("button",{type:"button",className:pe?"is-on":"","aria-pressed":pe,"aria-label":fe("canvasstage.overview.label"),title:fe(pe?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const u=!pe;Ne(u),np(u),p.current?.focus({preventScroll:!0})},children:f.jsx(Ip,{size:12})})]})}):null,n&&ot?f.jsx(sr,{children:f.jsx(Mr,{className:"ctx-menu amx-canvas-menu",x:ot.x,y:ot.y,onClick:u=>u.stopPropagation(),children:ot.key?f.jsxs(f.Fragment,{children:[Tt.length>0&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"amx-color-row",role:"group","aria-label":fe("canvasstage.color.label"),children:[Ex.map(u=>f.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":u.v||"none",title:fe(u.nameKey),"aria-label":fe(u.nameKey),"aria-pressed":Kn===u.v,style:u.v?{"--amx-swatch":`var(--amx-cv-${u.v})`}:void 0,onClick:()=>{const S=Tt;Lt(null),To(S,u.v||null)}},u.v||"none")),f.jsxs("label",{className:"amx-color-swatch is-custom",title:fe("canvasstage.color.custom"),"data-active":pt?"":void 0,style:pt?{"--amx-swatch":pt}:void 0,children:[pt?null:f.jsx(If,{size:11}),f.jsx("input",{type:"color","aria-label":fe("canvasstage.color.custom"),defaultValue:pt??"#7b5ce5",ref:u=>{if(!u)return;const S=Tt;u.onchange=()=>{Lt(null),To(S,u.value)}}})]})]}),f.jsx("div",{className:"ctx-separator"})]}),zt&&Wn.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":fe("canvasstage.ends.label"),children:nl.map(u=>f.jsx("button",{type:"button",className:"amx-end-btn","data-ends":u.id,title:fe(u.nameKey),"aria-label":fe(u.nameKey),"aria-pressed":dr===u.id,onClick:()=>{const S=Wn;Lt(null),Tr(S,u.from,u.to),p.current?.focus({preventScroll:!0})},children:u.icon},u.id))}),f.jsx("div",{className:"ctx-separator"})]}),ot.key.startsWith("e:")&&f.jsx("button",{onClick:()=>{const u=ze.find(S=>S.id===tt(ot.key));Lt(null),u&&wo(u.id,Ta(u),ja(u))},children:fe("canvasstage.menu.editText")}),ot.key!==he&&!zt&&f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=ut.length?ut:[ot.key];Lt(null),ue(u)},children:fe("canvasstage.menu.copy")}),f.jsx("button",{onClick:()=>{const u=ut.length?ut:[ot.key];Lt(null),P(u),p.current?.focus({preventScroll:!0})},children:fe("canvasstage.menu.duplicate")})]}),!zt&&f.jsx("button",{onClick:()=>{Cn(ot.key),un("conn"),Lt(null)},children:fe("canvasstage.menu.connectTo")}),(ot.key===he||ot.key.startsWith("c:"))&&vr(Kt(a),ot.key===he?he:tt(ot.key)).length>0&&f.jsx("button",{onClick:()=>{const u=ot.key===he?he:tt(ot.key);Lt(null),Re(u)},children:fe("canvasstage.menu.arrange")}),!zt&&f.jsx("button",{onClick:()=>{const u=ut.length?ut:[ot.key];Lt(null),an(u)},children:fe("canvasstage.menu.groupFrame")}),ot.key.startsWith("c:")&&f.jsx("button",{onClick:()=>{const u=tt(ot.key);Lt(null);const S=o();if(!S)return;const N=wt([u]);N&&Mt(),bu(S,u),lt([]),L(),N&&Ze()},children:fe("canvasstage.menu.unwrap")}),ot.key!==he&&f.jsx("button",{className:"danger",onClick:()=>{const u=ut.length?ut:[ot.key];Lt(null),mo(u)},children:fe("canvasstage.menu.delete")})]}):f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),uo(u.x-Jt/2,u.y-24)},children:fe("canvasstage.menu.newCard")}),H&&f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),io(u)},children:fe("canvasstage.menu.addNote")}),f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),to("rect",u.x,u.y)},children:fe("canvasstage.shape.rect")}),f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),to("ellipse",u.x,u.y)},children:fe("canvasstage.shape.ellipse")}),f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),to("text",u.x,u.y)},children:fe("canvasstage.shape.text")}),f.jsx("button",{onClick:()=>{const u=ot.at;Lt(null),At(u.x,u.y)},children:"Frame"}),f.jsx("button",{onClick:()=>{Lt(null),rn()},children:fe("canvasstage.menu.fit")}),f.jsx("div",{className:"ctx-separator"}),f.jsx("button",{onClick:()=>{Lt(null),sn()},children:fe("canvasstage.menu.exportCanvas")})]})})}):null,n&&!se&&vo&&H?f.jsx(Zl,{pages:H(),exclude:e,onClose:()=>{io(null),p.current?.focus({preventScroll:!0})},onPick:u=>{const S=vo;io(null),p.current?.focus({preventScroll:!0}),Gn(ll({kind:"note",path:u}),S)}}):null]})}function xu(e,t,n,o){const r=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(r instanceof Me))return null;const i=r.node;if(!i.isBlock||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(i.type.name))return null;const a=e.state.doc.resolve(r.from);for(let L=a.depth;L>=1;L--)if(a.node(L).type.name==="amadeusColumnCell")return null;const c=No(e.state.doc),d=s.createAndFill({anchor:c,x:t,y:n,w:Jt,h:0},i);if(!d)return null;const m=a.depth>=1?a.node(a.depth):null,g=e.state.schema.nodes.paragraph;let C=m?.type.name==="amadeusCanvasCard"&&m.childCount===1&&g?e.state.tr.replaceWith(r.from,r.to,g.create()):e.state.tr.delete(r.from,r.to);return C=C.insert(o?yu(C.doc,o.tree,o.parent):C.doc.content.size,d),or(e,C.scrollIntoView()),c}function bu(e,t){const o=In(e).find(m=>m.anchor===t);if(!o)return;const{paragraph:r,html:s}=e.state.schema.nodes,i=[];o.node.forEach(m=>i.push(m));const c=[...t&&r&&s?[r.create(null,s.create({value:`<!-- a ${t} -->`}))]:[],...i.length?i:[r.create()]],d=e.state.tr.delete(o.pos,o.pos+o.node.nodeSize);or(e,d.insert(o.pos,c).scrollIntoView())}const Dx={heading:["id"]};function kc(e,t){if(e.type!==t.type)return!1;const n=Dx[e.type.name];if(!n)return e.sameMarkup(t);const o={...t.attrs};for(const r of n)o[r]=e.attrs[r];return e.hasMarkup(t.type,o,t.marks)}function Wr(e,t){if(e===t)return!0;if(!kc(e,t))return!1;if(e.isText)return e.text===t.text;if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Wr(e.child(n),t.child(n)))return!1;return!0}function vu(e,t,n){for(let o=0;;o++){if(o===e.childCount||o===t.childCount)return e.childCount===t.childCount?null:n;const r=e.child(o),s=t.child(o);if(r===s){n+=r.nodeSize;continue}if(!kc(r,s))return n;if(r.isText&&r.text!==s.text){const i=r.text??"",a=s.text??"";for(let c=0;i[c]===a[c];c++)n++;return n}if(r.content.size||s.content.size){const i=vu(r.content,s.content,n+1);if(i!=null)return i}n+=r.nodeSize}}function wu(e,t,n,o){for(let r=e.childCount,s=t.childCount;;){if(r===0||s===0)return r===s?null:{a:n,b:o};const i=e.child(--r),a=t.child(--s),c=i.nodeSize;if(i===a){n-=c,o-=c;continue}if(!kc(i,a))return{a:n,b:o};if(i.isText&&i.text!==a.text){const d=i.text??"",m=a.text??"";let g=0;const C=Math.min(d.length,m.length);for(;g<C&&d[d.length-g-1]===m[m.length-g-1];)g++,n--,o--;return{a:n,b:o}}if(i.content.size||a.content.size){const d=wu(i.content,a.content,n-1,o-1);if(d)return d}n-=c,o-=c}}const Lx=25e4;function Ix(e,t){const n=e.childCount,o=t.childCount;let r=0;for(;r<n&&r<o&&Wr(e.child(r),t.child(r));)r++;let s=0;for(;s<n-r&&s<o-r&&Wr(e.child(n-1-s),t.child(o-1-s));)s++;const i=r,a=n-s,c=r,d=o-s,m=a-i,g=d-c;if(m===0&&g===0)return[];if(m===0||g===0||m*g>Lx)return[[i,a,c,d]];const C=g+1,L=new Uint32Array((m+1)*C);for(let se=m-1;se>=0;se--)for(let H=g-1;H>=0;H--)L[se*C+H]=Wr(e.child(i+se),t.child(c+H))?L[(se+1)*C+H+1]+1:Math.max(L[(se+1)*C+H],L[se*C+H+1]);const M=[];let k=0,z=0,F=0,J=0;for(;k<m&&z<g;)Wr(e.child(i+k),t.child(c+z))&&L[k*C+z]===L[(k+1)*C+z+1]+1?((F<k||J<z)&&M.push([i+F,i+k,c+J,c+z]),k++,z++,F=k,J=z):L[(k+1)*C+z]>=L[k*C+z+1]?k++:z++;return(F<m||J<g)&&M.push([i+F,a,c+J,d]),M}const Fs=(e,t)=>{let n=0;for(let o=0;o<t;o++)n+=e.child(o).nodeSize;return n};function Px(e,t){const n=[];for(const[o,r,s,i]of Ix(e,t)){const a=Fs(e,o),c=Fs(t,s),d=e.content.cut(a,Fs(e,r)),m=t.content.cut(c,Fs(t,i)),g=vu(d,m,a);if(g==null)continue;const C=wu(d,m,a+d.size,c+m.size);let L=C?C.a:a+d.size,M=C?C.b:c+m.size;const k=c-a;L<g&&(M+=g-L,L=g),M-k<g&&(L+=g-(M-k),M=g+k),n.push({from:g,to:L,slice:t.slice(g+k,M)})}return n}function Fx(e,t,n){const o=Px(e.doc,t);if(!o.length)return null;const r=e.selection,s=e.tr;for(let i=o.length-1;i>=0;i--){const a=o[i];s.replace(a.from,a.to,a.slice)}if(n)for(const i of o)n.push({from:s.mapping.map(i.from,-1),to:s.mapping.map(i.to,1),old:e.doc.slice(i.from,i.to),oldFrom:i.from,oldTo:i.to});if(r instanceof Ie){const i=d=>{for(const m of o)if(d>m.from&&d<m.to){const g=s.mapping.map(m.from,-1);return Math.min(g+(d-m.from),g+m.slice.size,s.doc.content.size)}return null},a=i(r.head),c=i(r.anchor);if(a!=null||c!=null){const d=a??s.mapping.map(r.head),m=c??s.mapping.map(r.anchor);try{s.setSelection(Ie.between(s.doc.resolve(m),s.doc.resolve(d)))}catch{}}}return s.setMeta("addToHistory",!1)}const so=new Tn("amAgentChanges");let fl=0;function ku(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Wr(e.child(n),t.child(n)))return!1;return!0}function Ox(e,t,n,o){const r=[...e.map(a=>({a:a.from,b:a.to,e:a})),...t.map(a=>({a:a.oldFrom,b:a.oldTo,c:a}))].sort((a,c)=>a.a-c.a||a.b-c.b),s=[];for(const a of r){const c=s[s.length-1],d=c?Math.max(...c.map(m=>m.b)):-1;c&&a.a<=d&&(a.c||c.some(m=>m.c))?c.push(a):s.push([a])}const i=[];for(const a of s){const c=a.filter(se=>se.e).map(se=>se.e),d=a.filter(se=>se.c).map(se=>se.c);if(!d.length){for(const se of c){const H=o.mapping.map(se.from,1);i.push({...se,from:H,to:Math.max(H,o.mapping.map(se.to,-1))})}continue}if(!c.length&&d.length===1){const se=d[0];i.push({id:++fl,from:se.from,to:se.to,old:se.old,after:o.doc.slice(se.from,se.to).content});continue}const m=Math.min(...a.map(se=>se.a)),g=Math.max(...a.map(se=>se.b)),C=c.filter(se=>ku(n.slice(se.from,se.to).content,se.after)),L=c.reduce((se,H)=>se+(H.locked??0)+(C.includes(H)?0:1),0),M=new Xf(n);for(const se of[...C].sort((H,ne)=>ne.from-H.from))M.replace(se.from,se.to,se.old);const k=M.mapping.map(m,-1),z=M.mapping.map(g,1),F=o.mapping.map(m,-1),J=o.mapping.map(g,1);i.push({id:++fl,from:F,to:J,old:M.doc.slice(k,z),after:o.doc.slice(F,J).content,...L?{locked:L}:{}})}return i.sort((a,c)=>a.from-c.from)}function _x(e,t){if(!t.changes.length)return null;const n=[],o=e.doc.content.size;for(const r of t.changes){const s=`am-agent-change${t.current===r.id?" is-current":""}`,i=Math.min(r.from,o),a=Math.min(r.to,o);a>i?(n.push(co.inline(i,a,{class:s,"data-agent-change":String(r.id)})),e.doc.nodesBetween(i,a,(c,d)=>(c.isBlock&&c.isLeaf&&d>=i&&d+c.nodeSize<=a&&n.push(co.node(d,d+c.nodeSize,{class:`${s} am-agent-change-block`})),!c.isTextblock))):n.push(co.widget(i,()=>{const c=document.createElement("span");return c.className=`am-agent-del${t.current===r.id?" is-current":""}`,c.setAttribute("data-agent-change",String(r.id)),c},{side:-1,key:`am-agent-del-${r.id}-${t.current===r.id?1:0}`,ignoreSelection:!0}))}return cr.create(e.doc,n)}function Bx(e){return[Et(()=>Kx(e))].flat()}function Kx(e){return new Ht({key:so,state:{init:()=>({changes:[],current:null}),apply(t,n){const o=t.getMeta(so);if(o&&"clear"in o)return{changes:[],current:null};if(o&&"add"in o){const s=Ox(n.changes,o.add,o.before,t);return{changes:s,current:s.some(i=>i.id===n.current)?n.current:null}}let r=n;return t.docChanged&&n.changes.length&&(r={...n,changes:n.changes.map(s=>{const i=t.mapping.map(s.from,1);return{...s,from:i,to:Math.max(i,t.mapping.map(s.to,-1))}})}),o&&"current"in o&&(r={...r,current:o.current}),r}},props:{decorations(t){const n=so.getState(t);return n?_x(t,n):null}},view:t=>{const n=so.getState(t.state);return n&&e.current(n),{update(o,r){const s=so.getState(o.state);s&&s!==so.getState(r)&&e.current(s)}}}})}function qx(e,t,n){return n.length?e.setMeta(so,{add:n,before:t}):e}function Hx(e){const t=so.getState(e.state);if(!t?.changes.length)return{reverted:0,skipped:0};const n=e.state.tr;let o=0,r=0;for(const s of[...t.changes].sort((i,a)=>a.from-i.from)){if(!ku(e.state.doc.slice(s.from,s.to).content,s.after)){r+=1+(s.locked??0);continue}n.replace(s.from,s.to,s.old),o++,r+=s.locked??0}return e.dispatch(n.setMeta(so,{clear:!0}).scrollIntoView()),{reverted:o,skipped:r}}function Vx(e){e.dispatch(e.state.tr.setMeta(so,{clear:!0}))}function Wx(e){const t=so.getState(e.state);if(!t?.changes.length)return null;const n=t.changes.findIndex(r=>r.id===t.current),o=t.changes[(n+1)%t.changes.length];return e.dispatch(e.state.tr.setMeta(so,{current:o.id})),o}gn({"agentchg.summary":{zh:"Tangu 修改了 {n} 处",en:"Tangu changes: {n}"},"agentchg.review":{zh:"逐处查看",en:"Review"},"agentchg.next":{zh:"下一处 {i}/{n}",en:"Next {i}/{n}"},"agentchg.revert":{zh:"全部撤回",en:"Revert all"},"agentchg.keep":{zh:"保留",en:"Keep"},"agentchg.label":{zh:"Tangu 对这篇笔记的改动",en:"Tangu's changes to this note"},"agentchg.skipped":{zh:"有 {n} 处你已改过,保留了你的版本,没有撤回",en:"Skipped {n} you had already edited; your version was kept"},"agentchg.live":{zh:"Tangu 正在修改这篇笔记",en:"Tangu is editing this note"},"agentchg.liveHint":{zh:"可以接着写;改动撞上时保留你的版本,Tangu 的另存为副本",en:"Keep writing — if edits overlap, yours are kept and Tangu’s are saved as a copy"}});function Yx(){const{t:e}=Zt();return f.jsxs("div",{className:"am-agent-capsule is-live",role:"status","aria-live":"polite","data-testid":"agent-live-capsule",children:[f.jsx("span",{className:"amx-pending-insert-spin","aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:e("agentchg.live")}),f.jsx("span",{className:"am-agent-capsule-hint",children:e("agentchg.liveHint")})]})}function Xx({count:e,index:t,onReview:n,onRevert:o,onKeep:r}){const{t:s}=Zt();return f.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[f.jsx(ic,{size:14,"aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:s("agentchg.summary",{n:String(e)})}),f.jsx("span",{className:"am-agent-capsule-sep","aria-hidden":!0}),f.jsx("button",{type:"button",className:"btn sm","data-act":"review",onClick:n,children:t?s("agentchg.next",{i:String(t),n:String(e)}):s("agentchg.review")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"revert",onClick:o,children:s("agentchg.revert")}),f.jsx("button",{type:"button",className:"btn sm primary","data-act":"keep",onClick:r,children:s("agentchg.keep")})]})}gn({"inlineai.action.improve":{zh:"润色",en:"Improve writing"},"inlineai.action.fix":{zh:"修正拼写与语法",en:"Fix spelling and grammar"},"inlineai.action.shorter":{zh:"精简",en:"Make shorter"},"inlineai.action.longer":{zh:"扩写",en:"Make longer"},"inlineai.action.summarize":{zh:"总结",en:"Summarize"},"inlineai.action.translate":{zh:"翻译",en:"Translate"},"inlineai.action.continue":{zh:"续写",en:"Continue writing"},"inlineai.action.custom":{zh:"自定义指令…",en:"Custom instruction…"},"inlineai.label":{zh:"AI 写作",en:"AI writing"},"inlineai.placeholder":{zh:"告诉 Tangu 要写什么,留空则续写",en:"Tell Tangu what to write, or leave empty to continue"},"inlineai.placeholderSel":{zh:"告诉 Tangu 怎么改选中的文字",en:"Tell Tangu how to change the selection"},"inlineai.send":{zh:"生成",en:"Generate"},"inlineai.generating":{zh:"正在生成…",en:"Generating…"},"inlineai.stop":{zh:"停止",en:"Stop"},"inlineai.replace":{zh:"替换",en:"Replace"},"inlineai.insertBelow":{zh:"插入下方",en:"Insert below"},"inlineai.insert":{zh:"插入",en:"Insert"},"inlineai.discard":{zh:"丢弃",en:"Discard"},"inlineai.retry":{zh:"重试",en:"Try again"},"inlineai.hint":{zh:"预览:确认后才写入笔记",en:"Preview: nothing is written until you confirm"},"inlineai.toolText":{zh:"模型写出了工具调用的样子,但这里什么都没有执行",en:"The model wrote something that looks like a tool call, but nothing was run"},"inlineai.errEmptyResult":{zh:"没有生成任何内容",en:"Nothing was generated"},"inlineai.unavailable":{zh:"这里用不了正文 AI",en:"In-note AI is not available here"},"inlineai.targetChanged":{zh:"选中的文字在生成期间被改过,结果已插入到下方",en:"The selection changed while generating, so the result was inserted below it"}});function Ux({x:e,y:t,anchorTop:n,title:o,hasSelection:r,askFirst:s,run:i,onApply:a,onClose:c,editorEl:d}){const{t:m}=Zt(),[g,C]=v.useState(s?"ask":"running"),[L,M]=v.useState(""),[k,z]=v.useState(""),[F,J]=v.useState(""),[se,H]=v.useState(!1),ne=v.useRef(null),je=v.useRef(""),He=v.useRef(void 0),p=v.useRef(null),fe=v.useRef(null),rt=v.useRef(d);rt.current=d;const ie=pe=>{ne.current?.abort();const Ne=new AbortController;ne.current=Ne,He.current=pe,je.current="",z(""),J(""),H(!1),C("running"),i(pe,Ue=>{Ne.signal.aborted||(je.current+=Ue,z(je.current))},Ne.signal).then(Ue=>{if(Ne.signal.aborted)return;const U=String(Ue.text??"");z(U),H(!!Ue.toolCallText),U.trim()?C("done"):(J(m("inlineai.errEmptyResult")),C("error"))}).catch(Ue=>{Ne.signal.aborted||(J(String(Ue?.message||Ue)),C("error"))})},be=()=>{ne.current?.abort(),je.current.trim()?(z(je.current),C("done")):s?C("ask"):c()};v.useEffect(()=>(s?requestAnimationFrame(()=>p.current?.focus()):ie(void 0),()=>ne.current?.abort()),[]);const me=r?"replace":"insert",Ee=pe=>{const Ne=document.activeElement;return!Ne||Ne===document.body||Ne===document.documentElement?!0:fe.current?.contains(Ne)?!pe||Ne===fe.current:!!rt.current?.contains(Ne)},Be=v.useRef({phase:g,text:k,primary:me});return Be.current={phase:g,text:k,primary:me},v.useEffect(()=>{const pe=Ne=>{Ne.isComposing||Ne.keyCode===229||(Ne.key==="Escape"&&Ee(!1)?(Ne.preventDefault(),Ne.stopPropagation(),c()):Ne.key==="Enter"&&!Ne.shiftKey&&!Ne.metaKey&&!Ne.ctrlKey&&!Ne.altKey&&Be.current.phase==="done"&&Ee(!0)&&(Ne.preventDefault(),Ne.stopPropagation(),a(Be.current.primary,Be.current.text)))};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[c,a]),f.jsxs(Mr,{innerRef:pe=>{fe.current=pe},className:"ui-popover am-ai-panel",x:e,y:t,anchorTop:n,prefer:"below",role:"dialog","aria-label":m("inlineai.label"),"data-testid":"inline-ai-panel","data-phase":g,children:[f.jsxs("div",{className:"am-ai-head",children:[f.jsx(ic,{size:14,"aria-hidden":!0}),f.jsx("span",{className:"am-ai-title",children:o}),g!=="ask"&&f.jsx("span",{className:"am-ai-hint",children:m(g==="running"?"inlineai.generating":"inlineai.hint")})]}),g==="ask"&&f.jsxs("div",{className:"am-ai-ask",children:[f.jsx("textarea",{ref:p,className:"am-ai-input",rows:2,value:L,placeholder:m(r?"inlineai.placeholderSel":"inlineai.placeholder"),onChange:pe=>M(pe.target.value),onKeyDown:pe=>{if(pe.key!=="Enter"||pe.shiftKey||pe.nativeEvent.isComposing||pe.keyCode===229)return;pe.preventDefault(),pe.stopPropagation();const Ne=L.trim();!Ne&&r||ie(Ne||void 0)}}),f.jsxs("div",{className:"am-ai-actions",children:[f.jsx("button",{type:"button",className:"btn sm primary","data-act":"send",disabled:r&&!L.trim(),onClick:()=>ie(L.trim()||void 0),children:m("inlineai.send")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:c,children:m("inlineai.discard")})]})]}),g!=="ask"&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"am-ai-preview","data-testid":"inline-ai-preview",children:k||(g==="running"?"…":"")}),g==="error"&&f.jsx("div",{className:"am-ai-error",role:"alert",children:F}),se&&g==="done"&&f.jsx("div",{className:"am-ai-error",children:m("inlineai.toolText")}),f.jsxs("div",{className:"am-ai-actions",children:[g==="running"&&f.jsx("button",{type:"button",className:"btn sm","data-act":"stop",onClick:be,children:m("inlineai.stop")}),g==="done"&&r&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"btn sm primary","data-act":"replace",onClick:()=>a("replace",k),children:m("inlineai.replace")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"below",onClick:()=>a("below",k),children:m("inlineai.insertBelow")})]}),g==="done"&&!r&&f.jsx("button",{type:"button",className:"btn sm primary","data-act":"insert",onClick:()=>a("insert",k),children:m("inlineai.insert")}),(g==="done"||g==="error")&&f.jsx("button",{type:"button",className:"btn sm","data-act":"retry",onClick:()=>ie(He.current),children:m("inlineai.retry")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:c,children:m("inlineai.discard")})]})]})]})}gn({"pendins.busy":{zh:"「{label}」进行中…",en:'"{label}" in progress…'},"pendins.cancel":{zh:"取消",en:"Cancel"},"pendins.lost":{zh:"「{label}」的结果没有插入:原来的位置已被删除。",en:'"{label}" wasn’t inserted: its original position was deleted.'},"pendins.sourceMode":{zh:"「{label}」的结果没有插入:你正在源码模式里编辑。切回可视模式后可以重新执行。",en:'"{label}" wasn’t inserted because you’re editing in source mode. Switch back to visual mode and run it again.'}});const zr=new Tn("UNIFIED_PENDING_INSERT");function Gx(e){const t=document.createElement("span");if(t.className="amx-pending-insert",t.dataset.pendingInsert=e.id,t.contentEditable="false",!e.visible)return t.dataset.hidden="",t;t.setAttribute("role","status");const n=document.createElement("span");n.className="amx-pending-insert-spin",n.setAttribute("aria-hidden","true");const o=document.createElement("span");o.textContent=ke("pendins.busy",{label:e.label});const r=document.createElement("button");return r.type="button",r.className="btn sm",r.textContent=ke("pendins.cancel"),r.addEventListener("mousedown",s=>s.preventDefault()),r.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,o,r),t}function Jx(){return[Et(()=>new Ht({key:zr,state:{init:()=>cr.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const o=e.getMeta(zr);return o&&"add"in o?n=n.add(e.doc,[co.widget(o.add.pos,()=>Gx(o.add),{id:o.add.id,key:`pending:${o.add.id}`,side:-1,ignoreSelection:!0,stopEvent:()=>!0})]):o&&"remove"in o&&(n=n.remove(n.find(void 0,void 0,r=>r.id===o.remove))),n}},props:{decorations:e=>zr.getState(e)}}))]}function Cu(e,t){const o=zr.getState(e)?.find(void 0,void 0,r=>r.id===t)[0];return o?o.from:null}let Zx=0;function Qx(e,t,n=!0){const o=`p${Date.now().toString(36)}${(Zx++).toString(36)}`;let r=!1;const s=()=>{r=!0,Su(e,o)};return e.dispatch(e.state.tr.setMeta(zr,{add:{id:o,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:o,label:t,cancelled:()=>r}}function Su(e,t){e.isDestroyed||Cu(e.state,t)==null||e.dispatch(e.state.tr.setMeta(zr,{remove:t}))}function eb(e,t,n){const o=Cu(e.state,t);if(o==null)return!1;let r=e.state.tr.setMeta(zr,{remove:t});if(!n?.size)return e.dispatch(r),!0;const s=e.state.doc.resolve(o);let i=s.depth;for(;i>=1&&!["doc","amadeusColumnCell","blockquote"].includes(s.node(i-1).type.name);)i--;const a=e.state.selection;let c,d,m;if(i<1)c=o,r=r.insert(o,n),d=o+n.size,m=e.hasFocus()&&a.empty&&a.head===o;else{const g=s.before(i),C=s.after(i),L=s.node(i).textContent.trim()==="";m=e.hasFocus()&&a.from>=g&&a.to<=C,c=L?g:C,r=L?r.replaceWith(g,C,n):r.insert(C,n),d=c+n.size}return Vs(r,c,d),m&&(r=r.setSelection(Ie.near(r.doc.resolve(Math.min(d,r.doc.content.size)),-1)).scrollIntoView()),e.dispatch(r),!0}function ml(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:ke("pendins.sourceMode",{label:e})}}))}function tb(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("pendins.lost",{label:e})}}))}function Eu(e,t,n){return JSON.stringify(e.slice(t,n).content.toJSON()??[],(o,r)=>{if(r&&typeof r=="object"&&!Array.isArray(r)&&r.type==="heading"&&r.attrs){const{id:s,...i}=r.attrs;return{...r,attrs:i}}return r})}const ar=new Tn("amInlineAi");function nb(e){const t=e.state.selection;if(!(t instanceof Ie)||!t.empty)return!1;const n=t.$from;if(n.parent.type.name!=="paragraph"||n.parent.content.size!==0)return!1;const o=n.depth>=1?n.node(n.depth-1).type.name:"";return o==="doc"||o==="amadeusColumnCell"||o==="amadeusCanvasCard"}function ob(e){return new Ht({key:ar,state:{init:()=>null,apply(t,n){const o=t.getMeta(ar);if(o&&"clear"in o)return null;if(o&&"set"in o)return o.set;if(!n||!t.docChanged)return n;const r=t.mapping.map(n.from,1);return{...n,from:r,to:Math.max(r,t.mapping.map(n.to,-1))}}},props:{decorations(t){const n=ar.getState(t);return!n||n.to<=n.from?null:cr.create(t.doc,[co.inline(n.from,Math.min(n.to,t.doc.content.size),{class:"am-ai-target"})])},handleKeyDown(t,n){return n.key!==" "||n.isComposing||n.keyCode===229||t.composing||n.metaKey||n.ctrlKey||n.altKey||n.shiftKey||!e.spaceTrigger()||!nb(t)?!1:(e.onSpace(t),!0)}}})}function rb(e){return[Et(()=>ob({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function sb(e,t,n){const o={from:t,to:n,text:e.state.doc.textBetween(t,n,`
|
|
58
|
-
`,""),sig:Eu(e.state.doc,t,n)},r=e.state.tr.setMeta(ar,{set:o});return n>t&&r.setSelection(Ie.create(r.doc,n)),e.dispatch(r),o}function pl(e){const t=ar.getState(e.state);if(!t)return;const n=e.state.tr.setMeta(ar,{clear:!0});if(t.to>t.from&&t.to<=n.doc.content.size)try{n.setSelection(Ie.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function hl(e){return ar.getState(e.state)??null}function ab(e,t,n){const o=e.content.size,r=e.textBetween(Math.max(0,t-8e3),t,`
|
|
59
|
-
`,"").slice(-2e3),s=e.textBetween(n,Math.min(o,n+4e3),`
|
|
60
|
-
`,"").slice(0,1e3);return{before:r,after:s}}function cb(e){const t=e.replace(/[\s\p{P}\p{S}\d]/gu,"");return t?(t.match(/[-ヿ㐀-鿿豈-]/g)||[]).length/t.length>.3?"English":"Chinese (Simplified)":"English"}function ib(e,t){const n=e.resolve(t);let o=n.depth;for(;o>=1&&!["doc","amadeusColumnCell"].includes(n.node(o-1).type.name);)o--;return o<1?null:{from:n.before(o),to:n.after(o),blank:n.node(o).textContent.trim()===""}}function lb(e,t,n,o){if(!n.childCount)return null;const{doc:r}=e.state,s=r.content.size,i=Math.min(t.from,s),a=Math.min(Math.max(t.to,i),s);let c=o;c==="replace"&&Eu(r,i,a)!==t.sig&&(c="below");let d=e.state.tr,m;if(c==="replace"){const g=n.childCount===1&&!!n.firstChild?.isTextblock&&r.resolve(i).sameParent(r.resolve(a));d=d.replaceRange(i,a,g?new Ka(n,1,1):new Ka(n,0,0)),m=d.mapping.map(a,1)}else{const g=ib(r,c==="below"?a:i);if(!g)return null;c==="insert"&&g.blank?(d=d.replaceWith(g.from,g.to,n),m=g.from+n.size):(d=d.insert(g.to,n),m=g.to+n.size)}return d=d.setSelection(Ie.near(d.doc.resolve(Math.min(m,d.doc.content.size)),-1)),e.dispatch(d.setMeta(ar,{clear:!0}).scrollIntoView()),c}gn({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const ub=2e4;function db(e,t){let n=null;for(const o of Xs(e)){if(o.pos>t)break;n=o.text}return n}function fb(e,t,n,o){const r=e.textBetween(t,n,`
|
|
61
|
-
`,"").trim().slice(0,ub);if(!r)return"";const s=db(e,t),i=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return o?`${r}
|
|
62
|
-
— [[${o}${i}]]`:r}function Mu(e,t){const n=e.resolve(t);let o=n.depth;for(;o>=1&&!["doc","amadeusColumnCell"].includes(n.node(o-1).type.name);)o--;return o>=1?n.after(o):null}function mb(e,t,n){if(e.resolve(t).depth!==0)return Mu(e,t+1)??e.content.size;let o=e.content.size,r=!1;return e.forEach((s,i)=>{if(o!==e.content.size)return;if(i===t){r=!0;return}if(!r||s.type.name!=="heading")return;(Number(s.attrs.level)||1)<=n&&(o=i)}),o}function pb(e,t){if(!t)return null;const n=Xs(e),o=t.heading?n.findIndex(c=>c.text===t.heading.trim()):-1,r=o>=0?n[o]:null,s=r?r.pos:0,i=r?mb(e,r.pos,r.level):e.content.size,a=(t.text??"").split(`
|
|
63
|
-
`).map(c=>c.trim()).filter(Boolean);if(a.length){const c=[];e.nodesBetween(s,i,(m,g)=>m.isTextblock?(g>=s&&c.push({pos:g,text:m.textContent}),!1):!0);const d=c.findIndex(m=>m.text.includes(a[0]));if(d>=0){const m=a[a.length-1],g=c.findIndex((L,M)=>M>=d&&L.text.includes(m)),C=Mu(e,c[g>=0?g:d].pos+1);if(C!=null)return C}}return r?i:null}gn({"linkcard.text":{zh:"文字",en:"Text"},"linkcard.link":{zh:"链接",en:"Link"},"linkcard.copy":{zh:"复制链接",en:"Copy link"},"linkcard.unlink":{zh:"移除链接",en:"Remove link"},"linkcard.fnEmpty":{zh:"脚注还是空的",en:"This footnote is empty"},"linkcard.fnMissing":{zh:"找不到这条脚注的定义",en:"Footnote definition not found"}});const gl=500,Ia=250,yl='a[href], sup[data-type="footnote_reference"]';function zu(e,t,n){const o=e.resolve(Math.max(0,Math.min(t,e.content.size)));if(!o.parent.isTextblock)return null;const r=o.start(),s=[];o.parent.forEach((g,C)=>s.push({node:g,from:r+C,to:r+C+g.nodeSize}));const i=g=>!!n.isInSet(g.node.marks);let a=s.findIndex(g=>i(g)&&t>=g.from&&t<g.to);if(a<0&&(a=s.findIndex(g=>i(g)&&t>=g.from&&t<=g.to)),a<0)return null;const c=n.isInSet(s[a].node.marks);let d=a,m=a;for(;d>0&&c.isInSet(s[d-1].node.marks);)d--;for(;m<s.length-1&&c.isInSet(s[m+1].node.marks);)m++;return{from:s[d].from,to:s[m].to,mark:c}}function hb(e,t){const n=e.state.schema.marks.link;if(!n)return null;let o;try{o=e.posAtDOM(t,0)}catch{return null}const r=zu(e.state.doc,o,n);return r&&r.from<r.to?{from:r.from,to:r.to}:null}function gb({getView:e,onOpenNote:t}){const{t:n}=Zt(),[o,r]=v.useState(null),[s,i]=v.useState(null),[a,c]=v.useState(null),d=v.useRef(null),m=v.useRef(null);v.useEffect(()=>{const M=()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),d.current=null,m.current=null},k=J=>{const se=e()?.dom.closest(".unified-body");return!!se&&J.closest(".unified-body")===se},z=J=>{const H=J.target?.closest?.(yl);if(!H||!k(H))return;if(m.current&&(clearTimeout(m.current),m.current=null),d.current&&clearTimeout(d.current),H.tagName==="SUP"){d.current=setTimeout(()=>{const je=e(),He=H.getBoundingClientRect();r(null),i({num:H.textContent??"",text:je?Nd(je.state.doc,H.getAttribute("data-label")??""):null,x:He.left,y:He.bottom+6})},gl);return}const ne=H;d.current=setTimeout(()=>{const je=e();i(null);const He=ne.getBoundingClientRect(),p=je?hb(je,ne):null;r({href:ne.getAttribute("href")??"",text:p&&je?je.state.doc.textBetween(p.from,p.to):ne.textContent??"",from:p?.from??-1,to:p?.to??-1,x:He.left,y:He.bottom+6})},gl)},F=J=>{!J.target?.closest?.(yl)||J.relatedTarget?.closest?.(".amx-linkcard")||(d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{r(null),i(null)},Ia))};return document.addEventListener("mouseover",z,!0),document.addEventListener("mouseout",F,!0),()=>{document.removeEventListener("mouseover",z,!0),document.removeEventListener("mouseout",F,!0),M()}},[e]),v.useEffect(()=>{if(!o&&!s||a)return;const M=()=>{r(null),i(null)};return document.addEventListener("scroll",M,!0),()=>document.removeEventListener("scroll",M,!0)},[o,s,a]);const g=(M,k,z,F,J)=>{const se=e(),H=se?.state.schema.marks.link;if(!se||!H)return;const{doc:ne}=se.state;if(k>ne.content.size||M>=k)return;const je=zu(ne,M,H);if(!je||je.from!==M||je.to!==k||je.mark.attrs.href!==z)return;const He=ne.textBetween(M,k),p=rt=>H.create({...je.mark.attrs,href:rt,..."ref"in je.mark.attrs?{ref:null}:{}});let fe=se.state.tr;if(F==="")fe=fe.delete(M,k);else if(F!==null&&F!==He){let rt=null;ne.nodesBetween(M,k,be=>be.isInline?(rt=rt===null?be.marks:rt.filter(me=>me.isInSet(be.marks)),!1):!0);const ie=(rt??[]).filter(be=>be.type!==H);fe=fe.replaceWith(M,k,se.state.schema.text(F,J?p(J).addToSet(ie):ie)),fe.setSelection(Ie.near(fe.doc.resolve(M+F.length)))}else if(J){if(J===je.mark.attrs.href){se.focus();return}fe=fe.removeMark(M,k,je.mark).addMark(M,k,p(J))}else fe=fe.removeMark(M,k,je.mark);se.dispatch(fe.scrollIntoView()),se.focus()};if(a){const M=!!Wc(a.href)&&!!a.text.trim(),k=()=>{c(null),r(null),e()?.focus()};return f.jsxs(sr,{children:[f.jsx("div",{className:"amx-linkedit-backdrop",onMouseDown:()=>c(null),role:"presentation"}),f.jsx(Mr,{className:"amx-linkedit",x:window.innerWidth/2,y:Math.round(window.innerHeight*.3),center:!0,children:f.jsxs("form",{className:"amx-linkedit-form",onSubmit:z=>{z.preventDefault();const F=Wc(a.href);!F||!a.text.trim()||(g(a.from,a.to,a.wasHref,a.text,F),c(null),r(null))},onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),k())},children:[f.jsxs("label",{children:[n("linkcard.text"),f.jsx("input",{autoFocus:!0,value:a.text,onChange:z=>c({...a,text:z.target.value}),onFocus:z=>z.currentTarget.select()})]}),f.jsxs("label",{children:[n("linkcard.link"),f.jsx("input",{value:a.href,onChange:z=>c({...a,href:z.target.value})})]}),f.jsxs("div",{className:"amx-linkedit-row",children:[f.jsx("button",{type:"button",onClick:k,children:n("common.cancel")}),f.jsx("button",{type:"submit",className:"primary",disabled:!M,children:n("common.save")})]})]})})]})}if(s)return f.jsx(sr,{children:f.jsxs(Mr,{className:"amx-linkcard amx-fncard",x:s.x,y:s.y,onMouseEnter:()=>{m.current&&clearTimeout(m.current),m.current=null},onMouseLeave:()=>{m.current=setTimeout(()=>i(null),Ia)},children:[f.jsx("span",{className:"amx-fncard-num",children:s.num}),f.jsx("span",{className:`amx-fncard-text${s.text?"":" muted"}`,children:s.text==null?n("linkcard.fnMissing"):s.text||n("linkcard.fnEmpty")})]})});if(!o)return null;let C=o.href;try{C=new URL(o.href).host||o.href}catch{}const L=o.from>=0&&(e()?.editable??!0);return f.jsx(sr,{children:f.jsxs(Mr,{className:"amx-linkcard",x:o.x,y:o.y,onMouseEnter:()=>{m.current&&clearTimeout(m.current),m.current=null},onMouseLeave:()=>{m.current=setTimeout(()=>r(null),Ia)},children:[f.jsx("button",{className:"amx-linkcard-host",title:o.href,onClick:()=>{t&&Ml(o.href)==="note"?(r(null),t(o.href)):window.open(o.href,"_blank","noopener")},children:C}),f.jsx("span",{className:"amx-linkcard-sep"}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(o.href)},children:n("linkcard.copy")}),L&&f.jsx("button",{onClick:()=>c({from:o.from,to:o.to,text:o.text,href:o.href,wasHref:o.href}),children:n("common.edit")}),L&&f.jsx("button",{onClick:()=>{g(o.from,o.to,o.href,null,null),r(null)},children:n("linkcard.unlink")}),L&&f.jsx("button",{className:"danger",onClick:()=>{g(o.from,o.to,o.href,"",null),r(null)},children:n("common.delete")})]})})}gn({"unipage.table.label":{zh:"表格",en:"Table"},"unipage.table.rowAbove":{zh:"在上方插入行",en:"Insert row above"},"unipage.table.rowBelow":{zh:"在下方插入行",en:"Insert row below"},"unipage.table.colLeft":{zh:"在左侧插入列",en:"Insert column left"},"unipage.table.colRight":{zh:"在右侧插入列",en:"Insert column right"},"unipage.table.deleteRow":{zh:"删除行",en:"Delete row"},"unipage.table.deleteCol":{zh:"删除列",en:"Delete column"},"unipage.table.alignLeft":{zh:"左对齐",en:"Align left"},"unipage.table.alignCenter":{zh:"居中",en:"Align center"},"unipage.table.alignRight":{zh:"右对齐",en:"Align right"}});function rc(e){const t=e?.state.selection;return t instanceof Me&&t.node.type.spec.tableRole==="table"}function yb(e,t,n){if(!e||!rc(e))return null;const o=document.elementFromPoint(t,n)?.closest?.("td,th");if(!o||!e.dom.contains(o))return null;try{return Dd(e.state.doc,e.posAtDOM(o,0))}catch{return null}}const xb=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:vp},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:xp},{op:"colLeft",key:"unipage.table.colLeft",Icon:Sp},{op:"colRight",key:"unipage.table.colRight",Icon:kp},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Ha},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Ha}],bb=[{align:"left",key:"unipage.table.alignLeft",Icon:Uf},{align:"center",key:"unipage.table.alignCenter",Icon:Ad},{align:"right",key:"unipage.table.alignRight",Icon:Td}];function vb({view:e,cell:t,onDone:n}){const{t:o}=Zt(),r=e.state.selection;if(!(r instanceof Me)||r.node.type.spec.tableRole!=="table")return null;const s=$d(e.state.doc,r.from,t);if(!s)return null;const i=a=>{n();const c=a();c&&e.dispatch(c),e.focus()};return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"ubm-sep",role:"separator"}),f.jsx("div",{className:"ubm-label",role:"presentation",children:o("unipage.table.label")}),xb.filter(a=>s.ops.includes(a.op)).map(({op:a,key:c,Icon:d})=>f.jsxs("button",{"data-table-op":a,role:"menuitem",tabIndex:-1,onClick:()=>i(()=>jd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",o(c)]},a)),s.align&&bb.map(({align:a,key:c,Icon:d})=>f.jsxs("button",{"data-table-align":a,"aria-checked":s.align===a,role:"menuitemcheckbox",tabIndex:-1,onClick:()=>i(()=>Rd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",o(c),s.align===a&&f.jsx(ea,{size:13,className:"ubm-check"})]},a))]})}function wb(e,t){return{el:e,owns:n=>{const o=t();if(!o||!o.dom.contains(n))return!1;for(let r=n.nodeType===1?n:n.parentElement;r&&r!==o.dom;r=r.parentElement)if(r.contentEditable==="false"||r.classList.contains("ProseMirror"))return!1;return!0},replace:n=>{const o=t();if(!o||!o.editable)return 0;const r=[];for(const{range:i,text:a}of n){let c,d;try{c=o.posAtDOM(i.startContainer,i.startOffset),d=o.posAtDOM(i.endContainer,i.endOffset)}catch{continue}d<=c||o.state.doc.textBetween(c,d,`
|
|
64
|
-
`,"")!==i.toString()||r.push({from:c,to:d,text:a})}if(!r.length)return 0;r.sort((i,a)=>a.from-i.from);const s=o.state.tr;for(const i of r)i.text?s.insertText(i.text,i.from,i.to):s.delete(i.from,i.to);return o.dispatch(s),r.length}}}gn({"unipage.upload.uploading":{zh:"上传中 {name}",en:"Uploading {name}"},"unipage.upload.fileN":{zh:"文件{n}",en:"File {n}"},"unipage.toast.insertPointLost":{zh:"文件已创建,但原插入位置已失效(笔记已切换)",en:"The file was created, but the original insertion point is gone (the note was switched)."},"unipage.plugin.notString":{zh:"run() 必须返回字符串,实际是 {type}",en:"run() must return a string, but returned {type}"},"unipage.plugin.tooLong":{zh:"run() 返回内容过长",en:"run() returned too much content"},"unipage.plugin.controlChars":{zh:"run() 返回内容含控制字符",en:"run() returned content containing control characters"},"unipage.plugin.failed":{zh:"「{label}」失败:{err}",en:'"{label}" failed: {err}'},"unipage.toast.columnTopLevelOnly":{zh:"分栏只能对顶层块使用,请先把这一块拖出当前列/列表",en:"Columns only work on top-level blocks — move this block out of its current column or list first."},"unipage.file.drawing":{zh:"画板",en:"Whiteboard"},"unipage.file.noteView":{zh:"笔记视图",en:"Note view"},"unipage.file.noteViewN":{zh:"笔记视图 {n}",en:"Note view {n}"},"unipage.file.untitledView":{zh:"未命名视图",en:"Untitled view"},"unipage.bookmark.title":{zh:"插入书签",en:"Insert bookmark"},"unipage.bookmark.label":{zh:"粘贴链接地址(https:// 开头);YouTube 链接会直接内嵌播放器。",en:"Paste a link starting with https:// — YouTube links turn into an embedded player."},"unipage.embed.title":{zh:"嵌入块引用",en:"Embed a block reference"},"unipage.embed.label":{zh:"形如 笔记名#标题 或 笔记名#^块ID(块菜单「复制标题链接」「复制块链接」可得);也可只填笔记名嵌整篇首块。",en:'Looks like NoteName#Heading or NoteName#^blockId — the block menu items "Copy heading link" and "Copy block link" give you one. A note name on its own embeds the first block of that note.'},"unipage.embed.confirm":{zh:"嵌入",en:"Embed"},"unipage.title.iconAction":{zh:"更换/移除页面图标",en:"Change or remove the page icon"},"unipage.title.addIcon":{zh:"添加图标",en:"Add icon"},"unipage.title.addCover":{zh:"添加封面",en:"Add cover"},"unipage.toast.canvasElementsFailed":{zh:"画布改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Canvas changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.canvasTreeFailed":{zh:"层级改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Hierarchy changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.canvasMainFailed":{zh:"主卡改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Main card changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.cardUnavailable":{zh:"当前块不能转换为卡片;请先移出列表或分栏",en:"This block cannot be turned into a card — move it out of the list or columns first."},"unipage.toast.cardMade":{zh:"已转换为卡片 —— 右上角切到画布模式查看",en:"Turned into a card — switch to canvas mode at the top right to see it."},"unipage.menu.turnInto":{zh:"转换为",en:"Turn into"},"unipage.toast.renameDetachedFailed":{zh:"没能把笔记改名为「{name}」(可能已有同名笔记),保留了原名",en:"Couldn’t rename the note to “{name}” (the name may be taken). The old name was kept."},"unipage.menu.text":{zh:"正文",en:"Text"},"unipage.menu.h1":{zh:"标题 1",en:"Heading 1"},"unipage.menu.h2":{zh:"标题 2",en:"Heading 2"},"unipage.menu.h3":{zh:"标题 3",en:"Heading 3"},"unipage.menu.bullet":{zh:"无序列表",en:"Bulleted list"},"unipage.menu.ordered":{zh:"有序列表",en:"Numbered list"},"unipage.menu.task":{zh:"待办",en:"To-do list"},"unipage.menu.quote":{zh:"引用",en:"Quote"},"unipage.menu.fold":{zh:"折叠",en:"Toggle"},"unipage.menu.callout":{zh:"标注",en:"Callout"},"unipage.menu.code":{zh:"代码块",en:"Code block"},"unipage.menu.card":{zh:"卡片",en:"Card"},"unipage.menu.toNewColumn":{zh:"移到新列",en:"Move to new column"},"unipage.menu.unsplit":{zh:"取消分栏",en:"Unsplit columns"},"unipage.menu.aria":{zh:"块操作",en:"Block actions"},"unipage.menu.stale":{zh:"笔记在菜单打开期间变了,请重新打开块菜单",en:"The note changed while the menu was open — open the block menu again"},"unipage.menu.toNewColumnMulti":{zh:"选中多块时不能移到新列,请只选一块",en:"Select a single block to move it to a new column"},"unipage.menu.backToDoc":{zh:"收回文档",en:"Return to document"},"unipage.menu.duplicate":{zh:"复制块",en:"Duplicate block"},"unipage.menu.delete":{zh:"删除",en:"Delete"},"unipage.lock.bar":{zh:"页面已锁定,防止误改。",en:"This page is locked to prevent accidental edits."},"unipage.lock.unlock":{zh:"解锁",en:"Unlock"}});const kb=800;let Os=null,Pa=null;const Cb={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function Nu(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:o}=await Va(),{base:r}=await bn.saveAttachment(e,t.name||"file",n,o);return`![[${r}]]`}catch{return null}}let wr=null;function kr(){wr&&(clearTimeout(wr.timer),clearTimeout(wr.arm),wr.off(),wr.el.remove(),wr=null)}function Ks(e){if(kr(),e.width<1||e.height<1)return;const t=document.createElement("div");t.className="am-citeflash",t.style.cssText="position:fixed;pointer-events:none;z-index:60;left:0;top:0",document.body.appendChild(t);const n=t.currentCSSZoom||1;t.style.left=`${(e.left-4)/n}px`,t.style.top=`${(e.top-2)/n}px`,t.style.width=`${(e.width+8)/n}px`,t.style.height=`${(e.height+4)/n}px`;const o=()=>{window.removeEventListener("scroll",kr,!0),window.removeEventListener("wheel",kr,!0)},r=window.setTimeout(()=>{window.addEventListener("scroll",kr,!0),window.addEventListener("wheel",kr,!0)},300);wr={el:t,timer:window.setTimeout(kr,1400),arm:r,off:o}}function Sb(e,t,n=!1,o=!1){const r=[],s=Fx(e.state,t,n?r:void 0);s&&(o&&s.setMeta("addToHistory",!0),e.dispatch(n?qx(s,e.state.doc,r):s))}function Eb({path:e,pageDir:t,body:n,onChange:o,onFinalFlush:r,skipFinalFlush:s,hidden:i,apiRef:a,probe:c,extraPlugins:d,focusPlace:m,onFocused:g,onCard:C,readOnly:L=!1,onAskTangu:M,aiMenu:k,onAiPrompt:z}){const[,F]=Od(),J=ac(),se=v.useRef(null),[H,ne]=v.useState(!1),je=v.useRef({onFinalFlush:r,skipFinalFlush:s});je.current={onFinalFlush:r,skipFinalFlush:s};const He=v.useRef(C);He.current=C;const p=v.useRef(z);p.current=z,v.useEffect(()=>(a.current={applySlashItem:U=>Ne.current(U),applyBody:(U,ce,$e)=>{let A=!1;return F()?.action(Z=>{const le=Z.get(xn),ve=Z.get(Lr)(hr(U,t));ve&&(Sb(le,ve,ce,$e),Bd(le.state.doc,ve),A=!0,c&&(c.reconciled=(c.reconciled??0)+1))}),A},serializeNow:()=>{let U=null;return F()?.action(ce=>{const $e=ce.get(xn);U=Or($s(ce,$e.state.doc),t)}),U},canonical:U=>{let ce=null;return F()?.action($e=>{const A=$e.get(Lr)(hr(U,t));A&&(ce=Or($s($e,A),t))}),ce},insertFiles:U=>{rt(U)},insertMarkdown:(U,ce,$e)=>ie(U,ce,$e),parseMd:U=>{let ce=null;return F()?.action($e=>{const A=$e.get(Lr)(hr(U,t));ce=A?.childCount?A.content:null}),ce},serializeMd:U=>{let ce=null;try{F()?.action($e=>{const Z=$e.get(xn).state.schema.topNodeType.createAndFill(void 0,U);Z&&(ce=_d($e.get(wm)(Z)))})}catch{return null}return ce},serializeStored:U=>{let ce=null;try{F()?.action($e=>{const A=$e.get(xn).state.schema.topNodeType.createAndFill(void 0,U);A&&(ce=Or($s($e,A),t))})}catch{return null}return ce},focusStart:()=>{F()?.action(U=>{const ce=U.get(xn);ce.dispatch(ce.state.tr.setSelection(Ie.atStart(ce.state.doc))),ce.focus()})},focusEnd:()=>{F()?.action(U=>{const ce=U.get(xn);ce.dispatch(ce.state.tr.setSelection(Ie.atEnd(ce.state.doc))),ce.focus()})},focusTail:()=>{F()?.action(U=>{const ce=U.get(xn),{doc:$e,schema:A}=ce.state,Z=A.nodes.paragraph,le=Ke=>!!Ke&&Ke.type===Z&&Ke.content.size===0,ve=$e.lastChild;let Qe=ce.state.tr;le(ve)||(Qe=Qe.insert($e.content.size,Z.create())),ce.dispatch(Qe.setSelection(Ie.atEnd(Qe.doc)).scrollIntoView()),ce.focus()})},hasFocus:()=>{let U=!1;return F()?.action(ce=>{U=ce.get(xn).hasFocus()}),U},revealSelection:()=>{F()?.action(U=>{const ce=U.get(xn);ce.dispatch(ce.state.tr.scrollIntoView()),ce.focus()})},serializePrefix:U=>{let ce=null;try{F()?.action($e=>{const A=$e.get(xn);ce=Or($s($e,A.state.doc.cut(0,Math.min(U,A.state.doc.content.size))),t)})}catch{return null}return ce},posAfterPrefix:U=>{let ce=null;try{F()?.action($e=>{const A=$e.get(Lr)(hr(U,t));A&&(ce=Ie.atEnd(A).head)})}catch{return null}return ce}},()=>{if(!je.current.skipFinalFlush()){const U=a.current?.serializeNow()??null;U!=null&&je.current.onFinalFlush(U)}a.current=null}),[F,t]);const fe=async U=>{try{const ce=new Uint8Array(await U.arrayBuffer()),{opts:$e}=await Va(),{pageRel:A}=await bn.saveAttachment(e,U.name||"pasted.png",ce,$e);return Sl(Cl(t,A),!0)}catch{return null}},rt=async U=>{if(!U.length)return;const ce=U.map((A,Z)=>`${ke("unipage.upload.uploading",{name:A.name||ke("unipage.upload.fileN",{n:Z+1})})}`);F()?.action(A=>{const Z=A.get(xn),le=Z.state.schema.nodes.paragraph;if(!le)return;const{$to:ve}=Z.state.selection;let Qe=ve.depth>=1?ve.after(1):ve.pos,Ke=Z.state.tr;for(const $t of ce){const st=le.create(null,Z.state.schema.text($t));Ke=Ke.insert(Qe,st),Qe+=st.nodeSize}Z.dispatch(Ke.scrollIntoView())});const $e=(A,Z)=>{F()?.action(le=>{const ve=le.get(xn);let Qe=-1,Ke=-1;if(ve.state.doc.descendants((mt,ct)=>Qe>=0||!mt.isTextblock||mt.textContent!==A?!0:(Qe=ct,Ke=ct+mt.nodeSize,!1)),Qe<0)return;const $t={from:Qe,to:Ke},st=ve.state.schema.nodes.paragraph,it=Z&&st?ve.state.tr.replaceWith($t.from,$t.to,st.create(null,ve.state.schema.text(Z))):ve.state.tr.delete($t.from,$t.to);ve.dispatch(it)})};for(let A=0;A<U.length;A++)$e(ce[A],await Nu(e,U[A]))},ie=(U,ce="cursor",$e)=>{let A=!1;return F()?.action(Z=>{const le=Z.get(xn),ve=Z.get(Lr)(hr(U,t));if(!ve?.childCount)return;const Qe=ve.content,Ke=!!$e?.quiet,$t=Ke?pb(le.state.doc,$e?.after):null;if(Ke&&$t==null&&$e?.caretless&&(ce="end"),ce!=="cursor"||$t!=null){const vt=$t??(ce==="start"?0:le.state.doc.content.size),lt=le.state.tr.insert(vt,Qe);Ke?be(le,lt,vt):le.dispatch(lt),A=!0;return}const{$from:st}=le.state.selection;let it=st.depth;for(;it>=1&&!["doc","amadeusColumnCell","blockquote"].includes(st.node(it-1).type.name);)it--;if(it<1)return;const mt=(vt,lt)=>{const Ot=Ie.near(vt.doc.resolve(Math.min(lt,vt.doc.content.size)),-1),on=$e?.caretBack??0;vt.setSelection(on&&Ot.$from.parentOffset>=on?Ie.create(vt.doc,Ot.from-on):Ot)};if(st.depth>it&&st.parent.isTextblock&&st.parent.content.size===0){const vt=le.state.tr,lt=on=>{const Yt=vt.doc.resolve(on),Cn=Yt.index(-1);return Yt.parent.isTextblock&&Yt.parent.content.size===0&&Yt.node(-1).canReplace(Cn,Cn+1,Qe)};let Ot=st.pos;if(!lt(Ot)){for(let on=vt.doc.resolve(Ot).depth;on>0;on--)if(vt.doc.resolve(Ot).node(on).type.name==="list_item"){Ot=Kd(vt,Ot,["list_item"]);break}}if(lt(Ot)){const on=vt.doc.resolve(Ot),Yt=on.before();vt.replaceWith(Yt,on.after(),Qe),Vs(vt,Yt,Yt+Qe.size),mt(vt,Yt+Qe.size),Ke?be(le,vt,Yt):(le.dispatch(vt.scrollIntoView()),le.focus()),A=!0;return}}const ct=st.before(it),un=st.after(it),ut=st.node(it).textContent.trim()==="",Yn=ut?le.state.tr.replaceWith(ct,un,Qe):le.state.tr.insert(un,Qe);Vs(Yn,ut?ct:un,(ut?ct:un)+Qe.size),mt(Yn,(ut?ct:un)+Qe.size),Ke?be(le,Yn,ut?ct:un):(le.dispatch(Yn.scrollIntoView()),le.focus()),A=!0}),A},be=(U,ce,$e)=>{U.dispatch(Ws(ce)),Al(U,Math.min($e+1,U.state.doc.content.size));const A=U.nodeDOM($e);if(!(A instanceof HTMLElement))return;const Z=A.getBoundingClientRect();(Z.top<0||Z.top>window.innerHeight-40)&&as(A),Ks(A.getBoundingClientRect())},me=(U,ce=!0)=>{let $e=null;return F()?.action(A=>{$e=Qx(A.get(xn),U,ce)}),$e},Ee=U=>{U&&F()?.action(ce=>Su(ce.get(xn),U.id))},Be=(U,ce,$e=!0)=>{if(ce?.cancelled())return;if(i?.()){Ee(ce),ml(ce?.label??"");return}const A=()=>{$e||!ce?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.insertPointLost")}})):tb(ce.label)};if(!a.current||!ce){A();return}let Z=!1;F()?.action(le=>{const ve=le.get(Lr)(hr(U,t));Z=eb(le.get(xn),ce.id,ve?.childCount?ve.content:null)}),Z||A()},pe=async(U,ce,$e,A=!1)=>{try{const{base:Z}=await bn.saveAttachment(e,U,ce,{mode:"vault",folder:pa(e)});Be(`![[${A?Z.replace(/\.md$/i,""):Z}]]`,$e),J.getState().syncFdChildren(e)}catch{Ee($e)}},Ne=v.useRef(()=>{}),Ue=U=>{const ce=se.current;if(!ce)return;const $e=U.run?void 0:Vd[U.scaffold];if($e){ce.transform($e)||Wd(U.label);return}ce.consume();const A=Yd;if(U.scaffold===A.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(U.scaffold===A.card){F()?.action(Z=>He.current(Z.get(xn)));return}if(U.scaffold===A.instructions||U.scaffold===A.agentTask||U.scaffold===A.prompt){const Z=U.scaffold===A.instructions?"instructions":U.scaffold===A.agentTask?"task":"prompt";ie(Xd(Z,Z==="instructions"?"":ps(Ud())));return}if(U.scaffold===A.ai){F()?.action(Z=>p.current?.(Z.get(xn)));return}if(U.run){const Z=me(U.label);(async()=>{try{const le=await U.run({pagePath:e,folder:pa(e)});if(le===""||le==null){Ee(Z);return}if(typeof le!="string")throw new Error(ke("unipage.plugin.notString",{type:typeof le}));if(le.length>8192)throw new Error(ke("unipage.plugin.tooLong"));if(Array.from(le).some(ve=>ve.charCodeAt(0)<32&&ve!==" "&&ve!==`
|
|
65
|
-
`))throw new Error(ke("unipage.plugin.controlChars"));Be(le,Z,!1),J.getState().syncFdChildren(e)}catch(le){if(Ee(Z),Z?.cancelled())return;console.error("[plugin] slash item failed",le),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.plugin.failed",{label:U.label,err:le instanceof Error?le.message:String(le)}),error:!0}}))}})();return}if(U.scaffold===A.image){const Z=document.createElement("input");Z.type="file",Z.accept="image/*",Z.onchange=()=>{const le=Z.files?.[0];if(!le)return;const ve=me(U.label);(async()=>{try{const Qe=new Uint8Array(await le.arrayBuffer()),{opts:Ke}=await Va(),{base:$t}=await bn.saveAttachment(e,le.name||"image.png",Qe,Ke);Be(`![[${$t}]]`,ve)}catch{Ee(ve)}})()},Z.click();return}if(U.scaffold===A.column){F()?.action(Z=>{const le=Z.get(xn),{$from:ve}=le.state.selection;if(ve.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.columnTopLevelOnly")}}));return}nu(le,ve.before(1),ve.after(1),ve.node(1)),le.focus()});return}if(U.scaffold===A.page){const Z=me(U.label);(async()=>{try{const le=J.getState(),ve=await le.createChildNote(e,ke("amadeus.default.note"));Be(`[[${ve.split("/").pop().replace(/\.md$/i,"")}]]`,Z),le.loadPage(ve)}catch{Ee(Z)}})();return}if(U.scaffold===A.database){const Z=ke("amadeus.default.database");pe(`${Z}.db`,new TextEncoder().encode(Vc(id(Z))),me(U.label));return}if(U.scaffold===A.drawing){pe(`${Gd(ke("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode(ld(dd)),me(U.label),!0);return}if(U.scaffold===A.noteview){const Z=me(U.label);(async()=>{const le=pa(e);let ve=null;for(let Ke=1;Ke<=20&&ve===null;Ke++)try{ve=await bn.createFolder(le,Ke===1?ke("unipage.file.noteView"):ke("unipage.file.noteViewN",{n:Ke}))}catch{}if(ve===null){Ee(Z);return}const Qe=ke("unipage.file.untitledView");await pe(`${Qe}.db`,new TextEncoder().encode(Vc(fd(Qe,ve))),Z)})();return}if(U.scaffold===A.linkdb){ne(!0);return}if(U.scaffold===A.bookmark){const Z=me(U.label,!1);qa(ke("unipage.bookmark.title"),"",{label:ke("unipage.bookmark.label")}).then(le=>{const ve=le?.trim();ve&&/^https?:\/\/\S+$/i.test(ve)?Be(ve,Z,!1):Ee(Z)});return}if(U.scaffold===A.embed){const Z=me(U.label,!1);(async()=>{let le="";try{const Ke=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());Ke&&(le=Ke[1].trim())}catch{}const Qe=(await qa(ke("unipage.embed.title"),le,{label:ke("unipage.embed.label"),confirmLabel:ke("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();Qe?Be(`![[${Qe}]]`,Z,!1):Ee(Z)})();return}ie(U.scaffold,"cursor",U.key==="math"?{caretBack:3}:void 0)};return Ne.current=Ue,f.jsxs(f.Fragment,{children:[f.jsx(qd,{initial:hr(n,t),onChange:U=>o(Or(U,t)),keys:Cb,saveImage:fe,saveFiles:rt,onOpenWiki:(U,ce)=>{J.getState().openWikiLink(U,e,ce)},getPageNames:()=>J.getState().pages,slashOpsRef:se,onSlashPick:Ue,getFiles:()=>km()?J.getState().files:[],isWikiResolved:U=>!!hs(U,J.getState().pages,e)||!!Dl(U,J.getState().files,e),wikiIcon:U=>{const ce=hs(U,J.getState().pages,e);return ce?J.getState().icons[ce]:void 0},focusPlace:m,onFocused:g,unified:!0,attachmentPagePath:e,extraPlugins:d,readOnly:L,onAskTangu:M,aiMenu:k}),H&&f.jsx(sr,{children:f.jsx(Hd,{onClose:()=>ne(!1),onPick:U=>{ne(!1),i?.()?ml(ke("mdblock.slash.linkdb")):ie(`![[${U}]]`)}})})]})}function xl(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function Mb(e){const t=e.selectionEnd;if(t>=e.value.length)return!0;const n=getComputedStyle(e),o=document.createElement("div");for(const c of["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","wordSpacing","lineHeight","textTransform","textIndent","tabSize","paddingLeft","paddingRight","borderLeftWidth","borderRightWidth","boxSizing","wordBreak","overflowWrap"])o.style[c]=n[c];Object.assign(o.style,{position:"absolute",visibility:"hidden",left:"-99999px",top:"0",width:`${e.offsetWidth}px`,whiteSpace:"pre-wrap",borderStyle:"solid",borderColor:"transparent"});const r=document.createElement("span"),s=document.createElement("span"),i=String.fromCodePoint(e.value.codePointAt(t)??32);r.textContent=i,s.textContent="",o.append(e.value.slice(0,t),r,e.value.slice(t+i.length),s),document.body.appendChild(o);const a=r.offsetTop>=s.offsetTop;return o.remove(),a}function zb({path:e,icon:t,cover:n,onSetIcon:o,onSetCover:r,onRename:s,onDetachedRename:i,onEnterBody:a,focusSignal:c,compact:d=!1,readOnly:m=!1}){const{t:g}=Zt(),C=$l(),L=(e.split("/").pop()??e).replace(/\.md$/i,""),M=Rm.test(L)?"":L,[k,z]=v.useState(M),[F,J]=v.useState(null),[se,H]=v.useState(null),ne=v.useRef(null),je=v.useRef(null),He=v.useRef(i);He.current=i,v.useEffect(()=>{z(M),je.current=null},[e]),v.useLayoutEffect(()=>()=>{const ie=je.current;je.current=null,ie!=null&&He.current(ie)},[]),v.useLayoutEffect(()=>{xl(ne.current)},[k]),v.useEffect(()=>{const ie=ne.current;if(!ie)return;let be=ie.clientWidth;const me=new ResizeObserver(()=>{ie.clientWidth!==be&&(be=ie.clientWidth,xl(ie))});return me.observe(ie),()=>me.disconnect()},[]),v.useEffect(()=>{if(!c)return;const ie=ne.current;if(ie){ie.focus();const be=ie.value.length;ie.setSelectionRange(be,be)}},[c]);const p=v.useRef(null),fe=v.useRef(!1),rt=()=>{const ie=p.current;if(p.current=null,je.current=null,fe.current){fe.current=!1,z(M);return}const be=k.trim();be&&be!==L?s(be,ie).then(me=>{me||z(M)}):z(M)};return m?f.jsxs("div",{className:"amx-title-wrap amx-title-ro",children:[t&&f.jsx("span",{className:"amx-title-bigicon","aria-hidden":!0,children:t}),f.jsx("div",{className:"amx-title-row",children:f.jsx("h1",{className:"amx-title-input amx-title-static",children:M||L})})]}):f.jsxs("div",{className:"amx-title-wrap",children:[!d&&t&&f.jsx("button",{className:"amx-title-bigicon",title:g("unipage.title.iconAction"),onClick:ie=>{const be=ie.currentTarget.getBoundingClientRect();J({x:be.left,y:be.bottom+6})},children:t}),!d&&(!t||!n)&&f.jsxs("div",{className:"amx-title-actions",children:[!t&&f.jsxs("button",{onClick:()=>o(Am()),children:[f.jsx($m,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addIcon")]}),!n&&f.jsxs("button",{onClick:ie=>{const be=ie.currentTarget.getBoundingClientRect();H({x:be.right,y:be.bottom+6})},children:[f.jsx(gm,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addCover")]})]}),f.jsx("div",{className:"amx-title-row",children:f.jsx("textarea",{ref:ne,className:"amx-title-input",rows:1,spellCheck:C,value:k,placeholder:"New Page",onChange:ie=>{const be=ie.target.value.replace(/[\r\n]+/g," ");je.current=be,z(be)},onBlur:rt,onKeyDown:ie=>{if(ie.nativeEvent.isComposing||ie.keyCode===229)return;const be=ie.currentTarget;if(ie.key==="Tab"){ie.preventDefault();return}const me=be.selectionStart===be.selectionEnd,Ee=me&&be.selectionEnd===be.value.length,Be=!ie.shiftKey&&!ie.altKey&&!ie.metaKey&&!ie.ctrlKey,pe=ie.key==="ArrowDown"&&Be&&me&&Mb(be);(ie.key==="Enter"||ie.key==="ArrowRight"&&Be&&Ee||pe)&&(ie.preventDefault(),p.current=ie.key==="Enter"?"enter":"move",be.blur(),a(ie.key==="Enter"?"enter":"move")),ie.key==="Escape"&&(je.current=null,fe.current=!0,z(M),be.blur())}})}),F&&f.jsx(Tm,{x:F.x,y:F.y,current:t,onPick:ie=>{o(ie),J(null)},onClose:()=>J(null)}),se&&f.jsx(jm,{page:e,x:se.x,y:se.y,onApply:ie=>r(ie),onClose:()=>H(null)})]})}function Nb({path:e,initial:t,diskRaw:n,probe:o,onRenamed:r,onCanvasMode:s,historyRef:i,filesRef:a,mdRef:c,onUnlock:d,compact:m=!1,readOnly:g=!1,hardBreaks:C=!1}){const L=e.split("/").slice(0,-1).join("/"),M=ac(),k=M.getState().vaultRoot,z=v.useContext(Gf),F=Jf(),J=z??F,se=Zf(l=>Qf(l,J)),H=g?"wysiwyg":se,{t:ne}=Zt(),je=$l(),He=v.useRef(null);if(!He.current){const l=qr(n??t),{fmText:h,body:x}=br(n==null?l.text:qr(t).text);He.current={fm:h,body:x,lastSaved:l.text,eol:l.eol,pending:!1,timer:null,reconcileBusy:0,unpreserved:null,preserved:new Set,failed:!1,retryTimer:null,retryN:0,stashed:null,writing:0,dead:!1,retired:!1,sawRows:!1,ownedCards:new Set,chain:Promise.resolve(),readOnly:g,slot:z,peerPatch:null}}const p=He.current,fe=v.useRef(0),rt=v.useRef(null),ie=v.useRef(()=>{rt.current?.()}).current,be=()=>{fe.current=performance.now(),fi(ie)},me=v.useRef(!1);v.useEffect(()=>{z!=null&&z===F&&be()},[z,F]);const[Ee]=v.useState(()=>new Set),Be=()=>{for(const l of[...Ee])l()},[pe,Ne]=v.useState(0),[Ue,U]=v.useState(0),ce=v.useRef(null),$e=v.useRef(H==="source"),A=v.useMemo(()=>({get current(){return $e.current?null:ce.current}}),[]);if($e.current!==(H==="source")){if(H==="source"){const l=ce.current?.serializeNow();l!=null&&(p.body=l)}$e.current=H==="source"}const Z=v.useRef(null),le=v.useRef(null),[ve,Qe]=v.useState(null),[Ke,$t]=v.useState(()=>{if(Kr())return!1;const l=em(k,e);return l?l==="canvas":Pn(ln(p.fm))?.mode==="canvas"}),[st,it]=v.useState(0),mt=v.useRef(!1),ct=v.useRef(Ke);ct.current=Ke;const un=v.useRef(!1),ut=ln(p.fm),Yn=v.useMemo(()=>Pn(ut),[ut]),vt=Yn?.main??{x:0,y:0,w:Ko},lt=()=>{const l=!Ke;if((A.current?.hasFocus()??!1)&&(l?it(x=>x+1):mt.current=!0),l){const x=le.current?.closest(".amx-pane");x&&ui(k,e,x.scrollTop)}ct.current=l,un.current=!0,mm(k,e,l?"canvas":"doc"),$t(l),ln(p.fm)!=null&&(At(),an())},Ot=v.useRef(lt);Ot.current=lt,rt.current=H==="source"?null:()=>Ot.current(),v.useEffect(()=>(fi(ie),()=>tm(ie)),[ie]);const on=v.useRef(l=>A.current?.applySlashItem(l)).current;v.useEffect(()=>(da(on),()=>{Jd()===on&&da(null)}),[on]),v.useEffect(()=>(s?.({on:Ke,toggle:()=>Ot.current(),...Ke&&H!=="source"&&!g?{exportCanvas:()=>Cn.current?.()}:{}}),()=>s?.(null)),[Ke,s,H,g]);const Yt=v.useRef(null),Cn=v.useRef(null);v.useEffect(()=>{if(!i)return;const l=w=>{if(p.readOnly)return!1;if(ct.current&&Yt.current)return Yt.current(w);const $=Vt();return!!$&&(w==="undo"?_a:Nl)($.state,$.dispatch)},x={undo:()=>l("undo"),redo:()=>l("redo"),indent:w=>{const $=Vt();return!p.readOnly&&!!$&&Fe.indent($,w)}};return i.current=x,()=>{i.current===x&&(i.current=null)}},[i]);const Qn=l=>{const h=ln(p.fm);if(h!=null&&Pn(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.canvasElementsFailed"),error:!0}}));return}p.fm=us(p.fm,yo(p.fm),Gy(h,l)),Ne(x=>x+1),Mn(),an()},ur=l=>{const h=ln(p.fm);if(h!=null&&Pn(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.canvasTreeFailed"),error:!0}}));return}p.fm=us(p.fm,yo(p.fm),Zy(h,l)),Ne(x=>x+1),Mn(),an()},en=l=>{const h=ln(p.fm);if(h!=null&&Pn(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.canvasMainFailed"),error:!0}}));return}p.fm=us(p.fm,yo(p.fm),Jy(h,l)),Ne(x=>x+1),Mn(),an()},Xn=v.useMemo(()=>({log:[],future:[]}),[e]),Sn=Ke&&H!=="source";v.useEffect(()=>{Qe(le.current)},[]),v.useEffect(()=>{const l=Z.current?.closest(".amx-pane");if(l)return l.classList.toggle("amx-canvas-pane",Sn),()=>l.classList.remove("amx-canvas-pane")},[Sn]),v.useEffect(()=>{if(Ke)return;const l=le.current?.closest(".amx-pane");if(!l)return;const h=nm(k,e);let x=!1,w=0;const $=performance.now()+1500,Y=()=>{if(l.scrollTop=h,l.scrollTop!==h&&performance.now()<$){w=requestAnimationFrame(Y);return}x=!0};w=requestAnimationFrame(Y);const ae=()=>{cancelAnimationFrame(w),x=!0},ye=()=>{x&&ui(k,e,l.scrollTop)};return l.addEventListener("scroll",ye,{passive:!0}),l.addEventListener("wheel",ae,{passive:!0}),l.addEventListener("pointerdown",ae),l.addEventListener("keydown",ae),()=>{cancelAnimationFrame(w),l.removeEventListener("scroll",ye),l.removeEventListener("wheel",ae),l.removeEventListener("pointerdown",ae),l.removeEventListener("keydown",ae)}},[Ke,e,k]),v.useEffect(()=>{if(Ke||!mt.current)return;mt.current=!1;let l=0;const h=requestAnimationFrame(()=>{l=requestAnimationFrame(()=>A.current?.revealSelection())});return()=>{cancelAnimationFrame(h),cancelAnimationFrame(l)}},[Ke]);const[eo,$o]=v.useState(()=>{const l=Os;return l?.path===e&&l.scope===z?(Os=null,Date.now()-l.at<1e4?l.req:null):null}),Wo=v.useRef(eo);Wo.current=eo;const Yo=v.useRef(null),[vn,En]=v.useState(null),[jn,xo]=v.useState(null),bo=v.useRef(0);v.useEffect(()=>{vn||(xo(null),clearTimeout(bo.current))},[vn]);const ot=(l,h)=>{if(clearTimeout(bo.current),jn&&!h)return;const x=l.closest(".unified-block-menu");if(!x)return;const w=x.getBoundingClientRect(),$=l.getBoundingClientRect(),Y=w.right+4+w.width>window.innerWidth-8;xo({x:Y?w.left-4-w.width:w.right+4,y:$.top-5,anchorTop:$.bottom+5,focus:h})},Lt=()=>{clearTimeout(bo.current),bo.current=window.setTimeout(()=>{document.querySelector(".unified-block-submenu")?.contains(document.activeElement)&&document.querySelector('.unified-block-menu [data-sub="turnInto"]')?.focus(),xo(null)},180)};v.useLayoutEffect(()=>{if(!jn?.focus)return;let l=0,h=0;const x=()=>{const w=document.querySelector(".unified-block-submenu button");w?.focus(),document.activeElement!==w&&++l<10&&(h=requestAnimationFrame(x))};return x(),()=>cancelAnimationFrame(h)},[jn]);const vo=v.useRef(null),[io,Xo]=v.useState(null),Ao=v.useRef(()=>{}),Hn=v.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),Fe=v.useMemo(()=>Oy({onMenu:l=>{const h=Fe.getView();vo.current=h?{doc:h.state.doc,sel:h.state.selection}:null,En({...l,cell:yb(h,l.x,l.y)})},onBlocksDeleted:l=>Ao.current(l),canvasTree:()=>Hn.current.tree(),onCardDetach:l=>Hn.current.detach(l),onCardsMinted:l=>Hn.current.minted(l)}),[]),Vt=()=>$e.current?null:Fe.getView(),[y]=v.useState(()=>Fh(Vt)),E=l=>{const h=Fe.getView();h&&_y(e,Yi(l),Yi(h.state.doc.content))};Ao.current=E,Hn.current={tree:()=>Kt(Pn(ln(p.fm))?.tree),detach:l=>{const h=Kt(Pn(ln(p.fm))?.tree);let x=!1;for(const w of l)w in h&&(delete h[w],x=!0);x&&ur(h)},minted:l=>{for(const h of l)p.ownedCards.add(h)}};const I=v.useRef({vaultRoot:k,path:e});I.current={vaultRoot:k,path:e};const D=v.useRef(!1),K=v.useRef(()=>{}),[X,oe]=v.useState({count:0,index:0}),G=v.useRef(()=>{}),ee=k?`${k.replace(/[\\/]+$/,"")}/${e}`:e,q=v.useSyncExternalStore(om,()=>!g&&rm(ee));G.current=l=>{const h=l.current==null?0:l.changes.findIndex(x=>x.id===l.current)+1;oe(x=>x.count===l.changes.length&&x.index===h?x:{count:l.changes.length,index:h})};const ze=v.useMemo(()=>[...Fe.plugins,...Xg,..._g(()=>Sa(yo(p.fm)),()=>{p.sawRows=!0}),...nx,...Yy(()=>Pn(ln(p.fm)),()=>Sa(yo(p.fm)),l=>{for(const h of l)p.ownedCards.add(h)}),...ly({path:e,readOnly:g,alive:()=>!p.dead&&!p.retired&&!p.readOnly&&!$e.current,flush:async()=>{if(p.dead||p.retired||p.readOnly||$e.current)throw new Error(ke("documentTask.sourceGone"));if(At(),Be(),p.timer&&(clearTimeout(p.timer),p.timer=null),await sn(!0),p.dead||p.retired||p.failed)throw new Error(ke("documentTask.sourceGone"))}}),Ph(),...Jx(),...ox(()=>ct.current),...lx(Xn),...rx(),...cx(()=>Pn(ln(p.fm))),...Bx(G),...rb({spaceTrigger:()=>uh()&&D.current,onSpace:K}),...Fm,...Om,...lp(()=>I.current),...Oh(),..._h(()=>Ut.current()),...Bh({where:()=>I.current,restore:()=>ft.current(),focus:()=>Bt.current()}),...C?Ld:[]],[Fe,e,g,C]);v.useEffect(()=>{if(!vn)return;const l=w=>{w.target?.closest?.(".ctx-menu")||En(null)},h=w=>{const $=document.querySelector(".unified-block-menu"),Y=document.querySelector(".unified-block-submenu"),ae=!!Y&&Y.contains(document.activeElement),ye=!!$&&$.contains(document.activeElement)||ae,W=$?.querySelector('[data-sub="turnInto"]');if(w.key==="Escape"){if(w.stopPropagation(),ae){xo(null),W?.focus();return}En(null),Fe.getView()?.focus();return}if(!$||w.isComposing)return;const de=!w.metaKey&&!w.ctrlKey&&!w.altKey&&!w.shiftKey;if(de&&ae&&w.key==="ArrowLeft"){w.preventDefault(),w.stopPropagation(),xo(null),W?.focus();return}if(de&&!ae&&w.key==="ArrowRight"&&W&&document.activeElement===W){w.preventDefault(),w.stopPropagation(),ot(W,!0);return}if(de&&["ArrowDown","ArrowUp","Home","End"].includes(w.key)){w.preventDefault(),w.stopPropagation();const R=[...(ae?Y:$).querySelectorAll('button:not([aria-disabled="true"])')],Se=R.indexOf(document.activeElement),we=R.length,We=w.key==="Home"?0:w.key==="End"?we-1:Se<0?w.key==="ArrowUp"?we-1:0:(Se+(w.key==="ArrowDown"?1:-1)+we)%we;R[We]?.focus();return}ye&&(w.key==="Enter"||w.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(w.key)||(En(null),ye&&(w.preventDefault(),Fe.getView()?.focus()))};let x=0;if(vn.keyboard){let w=0;const $=()=>{const Y=document.querySelector(".unified-block-menu");if(!Y){++w<10&&(x=requestAnimationFrame($));return}const ae=vn.focus==="turnInto"?Y.querySelector('[data-sub="turnInto"]'):null;if(ae){ot(ae,!0);return}Y.querySelector("button")?.focus()};x=requestAnimationFrame($)}return window.addEventListener("pointerdown",l,!0),window.addEventListener("contextmenu",l,!0),window.addEventListener("keydown",h,!0),()=>{cancelAnimationFrame(x),window.removeEventListener("pointerdown",l,!0),window.removeEventListener("contextmenu",l,!0),window.removeEventListener("keydown",h,!0)}},[vn]);const Pe=l=>{const h=vo.current;return vo.current=null,h?l.state.doc!==h.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.menu.stale")}})),!1):(l.state.selection.eq(h.sel)||l.dispatch(l.state.tr.setSelection(h.sel)),!0):!0},Oe=l=>{En(null);const h=Fe.getView();if(!h||!Pe(h))return;const x=h.state.selection;x instanceof Me&&(l(h,x),h.focus())},_e=(l,h)=>{En(null);const x=Fe.getView();if(!x||!Pe(x))return;const w=Fe.topRangeOf(x);w?l(x,w):x.state.selection instanceof Me&&h(x,x.state.selection),x.focus()},qe=l=>{const h=l.state.selection,x=Fe.topRangeOf(l)??(h instanceof Me?{from:h.from,to:h.to}:null);return x&&{from:x.from,to:ds(l.state,x.from,x.to)}},Xe=!g&&!!Sr()?.askInChat,Ve=(l,h,x)=>{const w=fb(l.state.doc,h,x,e);w&&Sr()?.askInChat?.([ru(tc(l.state.doc),e),w].filter(Boolean).join(`
|
|
66
|
-
|
|
67
|
-
`).slice(0,2e4))},Ge=!g&&!!Sr()?.complete;D.current=Ge;const Xt=Ba(l=>l.selectionActions),[Mt,wt]=v.useState(null),Un=[...["improve","fix","shorter","longer","summarize","translate","continue","custom"].map(l=>({id:l,label:ne(`inlineai.action.${l}`)})),...Xt.map(l=>({id:`plugin:${l.pluginId}:${l.item.id}`,label:l.item.title,plugin:!0}))],jt=(l,h)=>{if(!Ge)return;const x=l.state.selection,w=h==="prompt",$=w?x.head:x.from,Y=w?x.head:x.to;if(!w&&Y<=$)return;sb(l,$,Y);const ae=l.coordsAtPos($),ye=l.coordsAtPos(Y),W=h.startsWith("plugin:")?h.slice(7):void 0,de=W||w?w?"prompt":"custom":h,R=W?Xt.find(Se=>`${Se.pluginId}:${Se.item.id}`===W)?.item.title??ne("inlineai.label"):ne(w?"inlineai.label":`inlineai.action.${h}`);wt({key:Date.now(),x:ae.left,y:ye.bottom+6,top:ae.top-6,title:R,hasSelection:!w,askFirst:w||h==="custom",action:de,plugin:W})};K.current=l=>jt(l,"prompt");const rn=l=>async(h,x,w)=>{const $=Fe.getView(),Y=$?hl($):null;if(!$||!Y)throw new Error(ke("unipage.toast.insertPointLost"));const ae=Y.to>Y.from?A.current?.serializeMd($.state.doc.slice(Y.from,Y.to).content)??Y.text:"";if(l.plugin){const Se=Ba.getState().selectionActions.find(We=>`${We.pluginId}:${We.item.id}`===l.plugin);if(!Se)throw new Error(ke("unipage.toast.insertPointLost"));const we=await Se.item.run({text:Y.text,markdown:ae,pagePath:e});if(we==null||we==="")return{text:""};if(typeof we!="string")throw new Error(ke("unipage.plugin.notString",{type:typeof we}));if(Array.from(we).some(We=>We.charCodeAt(0)<32&&We!==" "&&We!==`
|
|
68
|
-
`))throw new Error(ke("unipage.plugin.controlChars"));return{text:we}}const ye=Sr();if(!ye?.complete)throw new Error(ke("inlineai.unavailable"));const{before:W,after:de}=ab($.state.doc,Y.from,Y.to),R=l.action==="prompt"?h?"custom":"continue":l.action;return ye.complete({action:R,...h?{instruction:h}:{},...ae?{selection:ae}:{},...W?{before:W}:{},...de?{after:de}:{},title:e.split("/").pop().replace(/\.md$/i,""),pagePath:e,pageInstructions:tc($.state.doc),...R==="translate"?{language:cb(Y.text)}:{}},{signal:w,onDelta:x})},lo=()=>{wt(null);const l=Fe.getView();l&&(pl(l),l.focus())},Uo=(l,h)=>{const x=Fe.getView(),w=x?hl(x):null,$=A.current?.parseMd(h);if(wt(null),!x||!w||!$){x&&pl(x),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.insertPointLost")}}));return}const Y=lb(x,w,$,l);x.focus(),At(),an(),l==="replace"&&Y==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("inlineai.targetChanged")}}))},$r=()=>{const l=Fe.getView();if(!l)return;const h=Wx(l),x=h?Z.current?.querySelector(`[data-agent-change="${h.id}"]`):null;x instanceof HTMLElement&&as(x,48)},Fn=()=>{const l=Fe.getView();if(!l)return;const{skipped:h}=Hx(l);At(),an(),h&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("agentchg.skipped",{n:String(h)})}}))},On=(l,h)=>{let x=!0;_e((w,$)=>{x=Ul(w,$.from,$.to,l)},(w,$)=>{const Y=Ni(w,$.from,$.to,l);if(Y!=null){x=Y;return}$.node.type.spec.code&&Qd(w,$.from,l)||(w.dispatch(w.state.tr.setSelection(Ie.near(w.state.doc.resolve($.from+1)))),x=Qs(w,l,null))}),x||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("mdblock.turn.failed",{kind:h})}}))},wo=(l,h)=>{let x=!0;_e((w,$)=>{x=l==="code"?Qa(w,$.from,$.to):zi(w,$.from,$.to,!0)},(w,$)=>{x=l==="code"?Ni(w,$.from,$.to,"code")??Qa(w,$.from,$.to):zi(w,$.from,$.to,!1)}),x||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("mdblock.turn.failed",{kind:h})}}))},To=()=>{const l=Fe.getView();if(!l)return[];const h=[];if(!rc(l)){const w=($,Y,ae,ye)=>{const W=ne(ae);h.push({k:$,icon:Y,label:W,run:()=>ye(W)})};w("text",xi,"unipage.menu.text",$=>On({kind:"text"},$)),w("h1",Ap,"unipage.menu.h1",$=>On({kind:"heading",level:1},$)),w("h2",jp,"unipage.menu.h2",$=>On({kind:"heading",level:2},$)),w("h3",Dp,"unipage.menu.h3",$=>On({kind:"heading",level:3},$)),w("bullet",Cm,"unipage.menu.bullet",$=>On({kind:"bullet"},$)),w("ordered",Fp,"unipage.menu.ordered",$=>On({kind:"ordered"},$)),w("task",Sm,"unipage.menu.task",$=>On({kind:"task"},$)),w("quote",rh,"unipage.menu.quote",$=>On({kind:"quote"},$)),w("callout",Dm,"unipage.menu.callout",$=>wo("callout",$)),w("fold",Np,"unipage.menu.fold",$=>On({kind:"fold"},$)),w("code",mp,"unipage.menu.code",$=>wo("code",$))}const x=l.state.selection;if(x instanceof Me&&!["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(x.node.type.name)){const w=l.state.doc.resolve(x.from);let $=!1;for(let Y=w.depth;Y>=1;Y--)w.node(Y).type.name==="amadeusColumnCell"&&($=!0);$||h.push({k:"card",icon:Wa,label:ne("unipage.menu.card"),run:()=>Oe(Y=>{Go(Y)})})}return h},uo=()=>{const l=Fe.getView();if(!l||Fe.topRangeOf(l))return null;const h=l.state.selection;return h instanceof Me?h.node.type.name==="list_item"?h.node.attrs.checked!=null?"task":h.$from.parent.type.name==="ordered_list"?"ordered":"bullet":rg(h.node):null},Go=l=>{const h=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.cardUnavailable")}})),!1);if(!(l.state.selection instanceof Me)){const{$from:Se}=l.state.selection;for(let We=Se.depth;We>=1;We--)if(Se.node(We).type.name==="list_item")return h();let we=Se.depth;for(;we>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(Se.node(we-1).type.name);)we--;if(we<1)return!1;l.dispatch(l.state.tr.setSelection(Me.create(l.state.doc,Se.before(we))))}const x=l.state.selection,w=l.state.doc.resolve(x.from),$=w.depth>=1?w.node(w.depth):null,Y=$?.type.name==="amadeusCanvasCard"?String($.attrs.anchor):"",ae=Kt(Pn(ln(p.fm))?.tree);let ye=0;l.state.doc.forEach(Se=>{Se.type.name==="amadeusCanvasCard"&&ye++});const W=Y?(Number($.attrs.x)||0)+(Number($.attrs.w)||Jt)+80:vt.x+vt.w+80,de=Y?(Number($.attrs.y)||0)+vr(ae,Y).length*72:vt.y+ye*72,R=xu(l,Math.round(W),Math.round(de),Y?{parent:Y,tree:ae}:void 0);return R?(p.ownedCards.add(R),At(),an(),Y&&ur(Br(Kt(Pn(ln(p.fm))?.tree),R,Y)),!ct.current&&!Y&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.cardMade")}})),!0):h()},Gn=()=>{const l=br(p.lastSaved);if(l.fmText!==p.fm&&(p.peerPatch==null||wa(l.fmText,p.peerPatch)!==p.fm))return!1;if(l.body===p.body)return!0;if(yo(p.fm)!=null||ln(p.fm)!=null)return!1;const h=A.current?.canonical(l.body);return h!=null&&h===p.body},Jn=v.useRef(null),_n=()=>{Jn.current?.()},[Ar,jo]=v.useState(!1),Jo=async l=>{const h=Cr(l);if(p.preserved.has(h))return;const x=await ba(e,Oo(l,p.eol));p.preserved.add(h),kh(e,x,!p.readOnly&&di(ee,l)),M.getState().refreshPages()},ko=async l=>{const h=await ba(e,Oo(l,p.eol));Ch(e,h),M.getState().refreshPages()},Bn=()=>{if(p.gone==null||p.readOnly)return;At();const l=$n(p.fm,p.body);l!==p.gone&&(p.gone=l,Ro(l))},Ro=async l=>{try{await ko(l)}catch{Po(k,e,l,p.lastSaved,p.slot),Eh(e,l)}},Co=l=>{if(p.retired||(p.stashed=$n(p.fm,p.body),Po(k,e,p.stashed,p.lastSaved,p.slot)),p.failed||(p.failed=!0,jo(!0),va(e,l)),p.retryTimer||p.dead||p.retired)return;const h=Si[Math.min(p.retryN,Si.length-1)];p.retryN++,p.retryTimer=setTimeout(()=>{p.retryTimer=null,!(p.dead||p.retired||!p.pending)&&(p.reconcileBusy||sn())},h)},So=l=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),p.retryN=0,p.failed&&(p.failed=!1,jo(!1)),p.stashed!=null&&(l==null||p.stashed===l||$n(p.fm,p.body)===l)&&(Jr(k,e,p.stashed,p.slot),p.stashed=null)},Tr=l=>{p.peerPatch=null,So(l),ud(e,p)},sn=(l=!1)=>{if(p.readOnly)return Promise.resolve();const h=async()=>{let $=0;for(;!p.retired;){const Y=$n(p.fm,p.body);if(Y===p.lastSaved){p.pending=!1,So();return}let ae;try{p.unpreserved!=null&&p.unpreserved!==Y&&await Jo(p.unpreserved),p.unpreserved=null,ae=await bn.writeTextFile(e,Oo(Y,p.eol),{base:Cr(Oo(p.lastSaved,p.eol))})}catch(ye){if(p.pending=!0,Co(ye),l)throw ye;return}if(ae&&ae.ok===!1&&ae.current==null){p.retired||(p.retired=!0,p.pending=!1,At(),p.gone=$n(p.fm,p.body),await Ro(p.gone));return}if(ae&&ae.ok===!1&&ae.current!=null){const ye=qr(ae.current);p.eol=ye.eol;const W=ye.text;if(W===Y){p.lastSaved=Y;continue}if(++$>3){const de=new Error("The note kept changing on disk while saving");if(p.pending=!0,Co(de),l)throw de;return}if(Gn()){p.pending=!1,_n();return}p.unpreserved=W,p.lastSaved=W;continue}if(p.lastSaved=Y,M.getState().bumpLinkGraph(),$n(p.fm,p.body)===Y&&(p.pending=!1),Tr(Y),!l)return}},x=async()=>{p.writing++;try{await h()}finally{p.writing--}},w=p.chain.then(x,x);return p.chain=w.catch(()=>{}),w},to=()=>{const l=Vt();if(!l)return;const h=yo(p.fm),x=Kg(l.state.doc);let w=h;x!=null?(w=x,p.sawRows=!0):p.sawRows&&h!=null&&Sa(h)!=null&&(w=null);const $=Uy(l.state.doc,ln(p.fm),un.current?ct.current?"canvas":"doc":null,p.ownedCards),Y=ln(p.fm);p.fm=us(p.fm,w,$),ln(p.fm)!==Y&&Ne(ae=>ae+1)},At=()=>{const l=A.current?.serializeNow();l!=null&&(p.body=l,to())},an=()=>{p.dead||p.retired||g||!p.writing&&$n(p.fm,p.body)===p.lastSaved||(p.pending=!0,p.timer&&clearTimeout(p.timer),p.timer=setTimeout(()=>{p.timer=null,!p.reconcileBusy&&sn()},kb))},[fo,mo]=v.useState(null),Mn=()=>{mo(l=>l==null?l:$n(p.fm,p.body))},Vn=(l,h=!0)=>{g||(p.fm=wa(p.fm,l),Ne(x=>x+1),Mn(),h?(p.pending=!0,sn().then(()=>{const x=kn.getState();x.refreshPages(),x.refreshIcons()})):an())};v.useEffect(()=>{sm(document)},[]);const[no,T]=v.useState(null);v.useEffect(()=>{const l=h=>{const x=document.elementFromPoint(h.clientX,h.clientY)??h.target,w=x?.tagName==="IMG"?x:null;if(!w||!w.closest(".unified-body"))return;const $=w.currentSrc||w.src;$&&(h.preventDefault(),h.stopPropagation(),T($))};return document.addEventListener("dblclick",l,!0),()=>document.removeEventListener("dblclick",l,!0)},[]),ci(!!no,()=>T(null)),ci(!!vn&&!g,()=>En(null)),v.useEffect(()=>{if(!no)return;const l=h=>{h.key==="Escape"&&T(null)};return window.addEventListener("keydown",l,!0),()=>window.removeEventListener("keydown",l,!0)},[no]),v.useEffect(()=>{const l=async()=>{p.reconcileBusy++;try{await pm(),await p.chain;const x=await bn.readTextFile(e);if(x==null||p.dead||p.retired)return;const w=qr(x);p.eol=w.eol;const $=w.text;if($===p.lastSaved&&!p.pending)return;if(p.pending&&At(),p.pending&&!Gn()){$!==p.lastSaved&&$!==$n(p.fm,p.body)&&(p.unpreserved=$),p.lastSaved=$;return}const{fmText:Y,body:ae}=br($),ye=yo(Y)!==yo(p.fm)||ln(Y)!==ln(p.fm);if(p.fm=Y,p.peerPatch=null,Ne(W=>W+1),ae!==p.body){p.ownedCards.clear();const W=!p.readOnly&&di(ee,x);(A.current??($e.current?ce.current:null))?.applyBody(ae,W)?p.body=ae:(p.body=ae,U(de=>de+1))}else ye&&(p.ownedCards.clear(),U(W=>W+1));p.lastSaved=$,p.pending=!1,So(),Mn()}finally{p.reconcileBusy--,p.reconcileBusy===0&&p.pending&&sn()}};Jn.current=()=>{l()};const h=bn.onExternalChange?.(x=>{x===e&&l()});return l(),()=>{Jn.current=null,h?.()}},[e]),v.useEffect(()=>{const l=()=>{if(At(),Be(),p.timer&&clearTimeout(p.timer),p.timer=null,p.readOnly)return;if(p.retired){p.gone!=null&&Bn(),p.stashed!=null&&Jr(k,e,p.stashed,p.slot),p.stashed=null;return}const x=$n(p.fm,p.body);if(!p.writing&&x===p.lastSaved){So();return}if(!p.writing&&Gn()){p.pending=!1;return}p.stashed=x,Po(k,e,x,p.lastSaved,p.slot),sn()},h=x=>{l(),p.failed&&p.pending&&!zh()&&(x.preventDefault(),x.returnValue="")};return window.addEventListener("beforeunload",h),()=>{p.dead=!0,window.removeEventListener("beforeunload",h),l();const x=Yo.current,w=Fe.getView();x&&w&&(x.doc=w.state.doc.toJSON(),x.anchor=w.state.selection.anchor,x.head=w.state.selection.head)}},[e]),v.useEffect(()=>{const l=()=>{!p.failed||!p.pending||p.dead||p.retired||typeof document<"u"&&document.visibilityState==="hidden"||(p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),!p.reconcileBusy&&sn())};return window.addEventListener("online",l),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("online",l),window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}},[e]),v.useEffect(()=>{const l=ye=>{if(p.readOnly||p.retired||p.dead)return!1;At(),ye&&Be();const W=$n(p.fm,p.body);return!p.writing&&(W===p.lastSaved||Gn())?!1:(p.pending=!0,p.stashed=W,Po(k,e,W,p.lastSaved,p.slot),!0)},h=ye=>{l(ye)&&(p.timer&&(clearTimeout(p.timer),p.timer=null),!p.reconcileBusy&&sn())},x=()=>{document.visibilityState==="hidden"&&h(!0)},w=()=>h(!0);let $=0,Y=null;const ae=()=>{const ye=$+1e3-Date.now();if(ye>0){l(!1),Y||(Y=setTimeout(()=>{Y=null,$=Date.now(),h(!1)},ye));return}$=Date.now(),h(!1)};return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",w),document.addEventListener("freeze",w),document.addEventListener("pause",w),window.addEventListener("blur",ae),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",w),document.removeEventListener("freeze",w),document.removeEventListener("pause",w),window.removeEventListener("blur",ae),Y&&clearTimeout(Y)}},[e]);const P=l=>p.readOnly||p.retired||p.dead||!A.current?!1:(A.current.insertFiles(l),!0);v.useEffect(()=>{if(!a)return;const l=h=>P(h);return a.current=l,()=>{a.current===l&&(a.current=null)}},[a]),v.useEffect(()=>{if(!c)return;const l=h=>p.readOnly||p.retired||p.dead?!1:A.current?.insertMarkdown(h,"cursor")??!1;return c.current=l,()=>{c.current===l&&(c.current=null)}},[c]),v.useLayoutEffect(()=>ad({path:e,owner:p,peerWrote:()=>_n(),scope:z,lastActive:()=>fe.current,dirty:()=>p.readOnly||p.retired||p.dead?!1:(At(),$n(p.fm,p.body)!==p.lastSaved&&!Gn()),flush:(l=!1)=>p.readOnly?Promise.resolve():(At(),Be(),p.timer&&(clearTimeout(p.timer),p.timer=null),sn(l)),insertFiles:l=>P(l),patchFm:(l,h=!1)=>p.readOnly||p.retired||p.dead?null:h?(p.fm=wa(p.fm,l),p.peerPatch={...p.peerPatch??{},...l},Ne(x=>x+1),Mn(),Promise.resolve()):(Vn(l),p.chain),fmNow:()=>ws(p.fm),insertMarkdown:(l,h)=>p.retired||p.readOnly?!1:A.current?.insertMarkdown(l,h)??!1,insertReply:g?void 0:(l,h)=>{if(p.retired||p.dead||p.readOnly||!A.current?.insertMarkdown(l,"cursor",{quiet:!0,after:h,caretless:!me.current}))return null;const x=Vt()?.state.doc,w=Xn,$={n:w.log.length,top:w.log[w.log.length-1],future:w.future.length};return{undo:()=>{const Y=Vt();return!Y||!x||Y.state.doc!==x||p.retired||p.dead||$.top!=="pm"||w.log.length!==$.n||w.log[w.log.length-1]!=="pm"||w.future.length!==$.future?!1:ct.current&&Yt.current?Yt.current("undo"):_a(Y.state,Y.dispatch)}}},bodyNow:()=>p.body,statsNow:()=>y(),headings:()=>{const l=Vt();return l?Xs(l.state.doc):[]},revealHeading:(l,h,x)=>{const w=Vt();if(!w)return;const $=Xs(w.state.doc),Y=$[l]?.text===h?$[l]:$.find(ye=>ye.text===h);if(!Y)return;w.focus(),w.dispatch(w.state.tr.setSelection(Ie.near(w.state.tr.doc.resolve(Y.pos+1))));const ae=w.nodeDOM(Y.pos);ae instanceof HTMLElement&&(as(ae),x&&Ks(ae.getBoundingClientRect()))},revealBlock:(l,h)=>{const x=Vt();if(!x)return!1;const w=[];x.state.doc.descendants((ye,W,de)=>ye.isTextblock?(w.push({pos:W,text:ye.textContent,parent:de}),!1):!0);let $=w.findIndex(ye=>wl(ye.text)===l);if($<0)return!1;md(w[$].text)&&$>0&&w[$-1].parent===w[$].parent&&($-=1);const Y=w[$].pos;x.focus(),x.dispatch(x.state.tr.setSelection(Ie.near(x.state.tr.doc.resolve(Y+1))));const ae=x.nodeDOM(Y);return ae instanceof HTMLElement&&(as(ae),h&&Ks(ae.getBoundingClientRect())),!0},focusBody:()=>{if(p.readOnly||p.retired||p.dead)return!0;const l=Fe.getView();return l?(l.hasFocus()||l.focus(),!0):!1},revealText:(l,h)=>{const x=Vt();if(!x)return!1;const w=Zd(x.state.doc,l,!!h?.tag);if(!w)return!1;Al(x,w.from),x.focus(),x.dispatch(x.state.tr.setSelection(Ie.create(x.state.doc,w.from,w.to)));let $=x.nodeDOM(w.block);for(;$ instanceof HTMLElement&&$!==x.dom;){const Y=$.getBoundingClientRect();if(Y.width||Y.height)break;$=$.parentElement}return!($ instanceof HTMLElement)||$===x.dom||(as($),h?.flash&&Ks($.getBoundingClientRect())),!0},retire:l=>{if(kr(),!p.retired&&!p.readOnly&&!p.dead){At();const h=$n(p.fm,p.body);h!==p.lastSaved&&!Gn()&&(l?Po(k,l,h,p.lastSaved,p.slot):(M.getState().vaultRoot??null)!==(k??null)?Po(k,e,h,p.lastSaved,p.slot):Ro(h))}else p.retired&&p.gone!=null&&Bn();p.retired=!0,p.timer&&(clearTimeout(p.timer),p.timer=null),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}}),[e]);const[ue,ge]=v.useState(()=>{if(g)return null;const l=x=>x==null?Hc(e,null):hm(x)||Hc(e,x),h=Mh(k,e,p.slot,l);return h?h.text===p.lastSaved||h.text===(n??t)?(Jr(k,e,void 0,h.slot),null):h:null}),Ae=()=>{ue&&Jr(k,e,void 0,ue.slot),ge(null)},Re=()=>{const l=ue;if(ge(null),!l||g||p.retired)return;(l.slot??null)!==p.slot&&(Jr(k,e,l.text,l.slot),Po(k,e,l.text,p.lastSaved,p.slot)),At();const h=p.lastSaved,x=$n(p.fm,p.body),w=x!==h?x:Cr(h)!==l.base?h:null;w!=null&&w!==l.text&&(p.unpreserved=w);const{fmText:$,body:Y}=br(l.text);p.fm=$,Ne(ae=>ae+1),Y!==p.body&&(p.ownedCards.clear(),p.body=Y,(A.current??($e.current?ce.current:null))?.applyBody(Y)||U(ae=>ae+1)),Mn(),p.pending=!0,p.stashed=l.text,sn()};v.useEffect(()=>{o&&(o.scheduleState=()=>({pending:p.pending,lastSaved:p.lastSaved}),o.flush=()=>(At(),p.timer&&clearTimeout(p.timer),p.timer=null,sn()),o.fmState=()=>({fm:p.fm,body:p.body}),o.setFm=l=>Vn(l,!1),o.view=()=>Fe.getView(),o.serializeNow=()=>A.current?.serializeNow()??null)},[o]);const[Q,Je]=v.useState(0);v.useEffect(()=>{am(e)&&Je(l=>l+1)},[e]);const ft=v.useRef(()=>!1);ft.current=()=>!g&&!m&&!ct.current&&Wo.current==null&&Q===0;const Bt=v.useRef(()=>!1);Bt.current=()=>{const l=Pa;if(!l||l.scope!==z||Date.now()-l.at>5e3)return!1;Pa=null;const h=document.activeElement;return(!h||h===document.body)&&(z==null||z===Em())};const kt=v.useRef(null);v.useLayoutEffect(()=>()=>{const l=document.activeElement;l&&l!==document.body&&(Z.current?.contains(l)||kt.current?.contains(l))&&(Pa={scope:z,at:Date.now()})},[]);const Ut=v.useRef(()=>!1);Ut.current=()=>Sn||g?!1:(Je(l=>l+1),!0);const zt=l=>{const h=Fe.getView();if(!h)return;let x=h.state.tr;if(p.body===l.body)try{const Y=h.state.schema.nodeFromJSON(l.doc);Y.eq(x.doc)||(x=x.replaceWith(0,x.doc.content.size,Y.content))}catch{}const w=x.doc.content.size,$=Y=>x.doc.resolve(Math.max(0,Math.min(Y,w)));try{x=x.setSelection(Ie.between($(l.anchor),$(l.head)))}catch{}h.dispatch(x.setMeta("addToHistory",!1).scrollIntoView())},Tt=async(l,h=null,x=!1)=>{if(g||x&&p.retired)return!1;const w=k;try{if(At(),await sn(),await ym(),x&&(await p.chain,p.retired||kn.getState().vaultRoot!==w))return!1;const $=await bn.renamePageFile(e,l);if($!==e){xm(k,e,$),up(k,e,$),p.retired=!0,At();const Y=$n(p.fm,p.body),ae=p.body;if(Y!==p.lastSaved)try{const de=await bn.writeTextFile($,Oo(Y,p.eol),{base:Cr(Oo(p.lastSaved,p.eol))});if(de&&de.ok===!1&&de.current!==Oo(Y,p.eol))try{Sh($,await ba($,Oo(Y,p.eol))),kn.getState().refreshPages()}catch(R){Po(k,$,Y,p.lastSaved,p.slot),va($,R)}}catch(de){Po(k,$,Y,p.lastSaved,p.slot),va($,de)}const ye=Wo.current,W=Fe.getView();if(!x&&h&&ye!=null&&typeof ye!="object")Os={path:$,scope:z,req:ye,at:Date.now()};else if(!x&&W?.hasFocus()){const de={place:"restore",body:ae,doc:W.state.doc.toJSON(),anchor:W.state.selection.anchor,head:W.state.selection.head};Yo.current=de,Os={path:$,scope:z,req:de,at:Date.now()}}cd(e,"file",$),bm(e,$,"file"),await vm(e,$),kn.getState().refreshPages(),x||r?.($)}return!0}catch{return x&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.toast.renameDetachedFailed",{name:l})}})),!1}},Kn=v.useRef("");v.useEffect(()=>{const l=JSON.stringify(Pn(ln(p.fm))?.tree??null);if(l===Kn.current)return;Kn.current=l;const h=Fe.getView();h&&h.updateState(h.state)},[pe,Fe]);const pt=Lh(p.fm),Wn=typeof pt.icon=="string"&&pt.icon.trim()?pt.icon.trim():null,dr=typeof pt.cover=="string"&&pt.cover.trim()?pt.cover.trim():null,u=pt.cover_y,S=typeof u=="number"?u:typeof u=="string"?parseFloat(u):NaN,N=Number.isFinite(S)?Math.max(0,Math.min(100,S)):50,B=v.useMemo(()=>H==="source"?$n(p.fm,p.body):"",[H,pe]),_=v.useRef(null),O=()=>`${yo(p.fm)??""}\0${ln(p.fm)??""}`;v.useEffect(()=>{if(!g)return cm(J,l=>{const h=fa(le.current),x=ma(h);if(l==="source"){At();const ae=Fe.getView(),ye=$n(p.fm,p.body);let W=p.fm.length,de=0,R=!1;if(ae){const{head:Se,$head:we}=ae.state.selection;R=ae.hasFocus();try{de=ae.coordsAtPos(Se).top-x}catch{}const We=we.parent.isTextblock?we.parent.textBetween(Math.max(0,we.parentOffset-16),we.parentOffset,void 0,""):"",Rt=ce.current?.serializePrefix(Se);W=Mm(ye,p.fm.length+(Rt?.trimEnd().length??0),We)}_.current={to:l,offset:W,y:de,focused:R,bodyAtEnter:p.body,struct:O()};return}const w=te.current;if(!w)return;const $=w.selectionStart??0;let Y=0;try{Y=ii(w,$)-x}catch{}_.current={..._.current??{},to:l,offset:$,bodyOff:$-br(w.value).fmText.length,y:Y,focused:document.activeElement===w}})},[J,g]);const V=v.useRef(H);v.useLayoutEffect(()=>{const l=V.current;if(V.current=H,l===H)return;const h=_.current,x=fa(le.current);if(H==="source"){an();const de=te.current;if(!de||h?.to!=="source")return;const R=x.scrollTop;de.style.height="auto",de.style.height=`${de.scrollHeight}px`,x.scrollTop=R;const Se=Math.min(h.offset,de.value.length);de.setSelectionRange(Se,Se),h.focused&&de.focus({preventScroll:!0}),x.scrollTop+=ii(de,Se)-ma(x)-h.y;return}_.current=null,mo(null);const w=ce.current,$=Fe.getView();if(!w||!$||!h||h.struct!==O()){p.ownedCards.clear(),U(de=>de+1);return}if(p.body!==h.bodyAtEnter&&w.applyBody(p.body,!1,!0),h.to!=="wysiwyg"||h.bodyOff==null)return;const Y=Fe.getView();if(!Y)return;const ae=Y.state.doc.content.size,ye=h.bodyOff<=0?0:w.posAfterPrefix(p.body.slice(0,h.bodyOff))??0,W=Ie.near(Y.state.doc.resolve(Math.max(0,Math.min(ye,ae))),-1);Y.dispatch(Y.state.tr.setSelection(W).setMeta("addToHistory",!1)),h.focused&&Y.focus();try{x.scrollTop+=Y.coordsAtPos(W.head).top-ma(x)-h.y}catch{}},[H]);const te=v.useRef(null);return v.useEffect(()=>{const l=te.current;if(H==="source"&&l){const h=fa(l),x=h.scrollTop;l.style.height="auto",l.style.height=`${l.scrollHeight}px`,h.scrollTop=x}},[H,fo,B]),v.useEffect(()=>{if(g)return;if(H==="source"){const h=te.current;return h?vi(dh(h)):void 0}const l=Z.current;return l?vi(wb(l,()=>Fe.getView())):void 0},[g,H,Fe]),f.jsxs(f.Fragment,{children:[f.jsx("span",{ref:le,className:"amx-seg-anchor","aria-hidden":!0}),H==="source"?null:f.jsx(Hh,{anchor:ve,on:Ke,toggle:()=>Ot.current()}),Sn||m?null:f.jsx(Nm,{page:e,cover:dr,coverY:N,readOnly:g,onSetCover:l=>Vn({cover:l??void 0,...l?{}:{cover_y:void 0}}),onSetCoverY:l=>Vn({cover_y:l})}),Sn?null:f.jsxs("div",{ref:kt,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:be,onPointerDownCapture:be,children:[f.jsx(zb,{compact:m,path:e,icon:Wn,cover:dr,readOnly:g,onSetIcon:l=>Vn({icon:l??void 0}),onSetCover:l=>Vn({cover:l}),onRename:Tt,onDetachedRename:l=>{const h=l.trim();h&&h!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&Tt(h,null,!0)},onEnterBody:l=>$o(l==="enter"?"body-enter":"start"),focusSignal:Q}),!m&&f.jsx(Yl.Provider,{value:Ee,children:f.jsx(Xh,{fmExtra:ws(p.fm),readOnly:g,notePath:e,onCommit:l=>{p.fm=$h(p.fm,l),Ne(h=>h+1),Mn(),p.pending=!0,sn()}})}),g&&d&&f.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[f.jsx(dp,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:ne("unipage.lock.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:d,children:ne("unipage.lock.unlock")})]}),!g&&Ar&&f.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[f.jsx(im,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:ne("unisave.failed.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:()=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),sn()},children:ne("unisave.failed.retry")})]}),!g&&ue&&f.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[f.jsx(lm,{size:15}),f.jsxs("div",{className:"mk-notice-body",children:[f.jsx("span",{children:ne("unisave.draft.bar",{time:um(ue.at)})}),f.jsx("small",{children:ne("unisave.draft.hint")})]}),f.jsx("button",{type:"button",className:"btn sm primary",onClick:Re,children:ne("unisave.draft.restore")}),f.jsx("button",{type:"button",className:"btn sm",onClick:Ae,children:ne("unisave.draft.discard")})]})]}),H==="source"?f.jsx("textarea",{ref:te,className:"amx-source",value:fo??B,spellCheck:je,onFocus:be,onChange:l=>{const h=l.target.value;mo(h);const{fmText:x,body:w}=br(h);p.fm=Rh(x),p.body=w,an()}}):null,f.jsxs("div",{ref:Z,className:`page-view unified-body${Ke?" amx-canvas":""}${Sn?" amx-canvas-full":""}`,style:H==="source"?{display:"none"}:void 0,"aria-hidden":H==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{be(),me.current=!0,da(on)},onPointerDownCapture:be,children:[f.jsx(Rx,{path:e,vaultRoot:k,active:Ke&&H!=="source",readOnly:g,revealSelection:st,getView:()=>Fe.getView(),main:vt,mainStored:Yn?.main!=null,elements:Yn?.elements,tree:Yn?.tree,onElements:Qn,onTree:ur,onMain:en,timeline:Xn,histStepRef:Yt,exportRef:Cn,saveFile:l=>Nu(e,l),parseMd:l=>A.current?.parseMd(l)??null,serializeMd:l=>A.current?.serializeMd(l)??null,storedMd:l=>A.current?.serializeStored(l)??null,onBlocksDeleted:E,notePages:()=>M.getState().pages,onCommit:l=>{l&&p.ownedCards.add(l),At(),an()},children:f.jsx(Id,{children:f.jsx(Eb,{path:e,pageDir:L,body:p.body,onChange:l=>{$e.current||(p.body=l,to(),an())},onFinalFlush:l=>{p.body=l,to(),an(),Ne(h=>h+1)},skipFinalFlush:()=>p.reconcileBusy>0||$e.current,hidden:()=>$e.current,apiRef:ce,probe:o,extraPlugins:ze,focusPlace:eo!=null&&typeof eo=="object"?"start":eo,onFocused:()=>{eo!=null&&typeof eo=="object"&&zt(eo),$o(null)},onCard:Go,readOnly:g,onAskTangu:Xe?l=>Ve(l,l.state.selection.from,l.state.selection.to):void 0,aiMenu:Ge?{items:Un,onPick:(l,h)=>jt(h,l)}:void 0,onAiPrompt:Ge?l=>jt(l,"prompt"):void 0})},`${e}:${Ue}${g?":ro":""}`)}),!Ke&&!g&&f.jsx("div",{className:"page-tail",onClick:()=>A.current?.focusTail()}),q&&f.jsx(Yx,{}),!g&&X.count>0&&f.jsx(Xx,{count:X.count,index:X.index,onReview:$r,onRevert:Fn,onKeep:()=>{const l=Fe.getView();l&&Vx(l)}})]}),f.jsx(gb,{getView:()=>Fe.getView(),onOpenNote:l=>{M.getState().openWikiLink(Pd(l,e,M.getState().pages),e)}}),no&&f.jsx(sr,{children:f.jsx("div",{className:"amx-lightbox",onClick:()=>T(null),role:"presentation",children:f.jsx("img",{src:no,alt:""})})}),Mt&&Ge&&f.jsx(sr,{children:f.jsx(Ux,{x:Mt.x,y:Mt.y,anchorTop:Mt.top,title:Mt.title,hasSelection:Mt.hasSelection,askFirst:Mt.askFirst,run:rn(Mt),onApply:Uo,onClose:lo,editorEl:Z.current},Mt.key)}),io&&!g&&f.jsx(Zl,{pages:M.getState().pages,exclude:e,onClose:()=>{Xo(null),Fe.getView()?.focus()},onPick:l=>{const h=io;Xo(null);const x=Fe.getView();if(x){if(x.state.doc!==h.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.menu.stale")}}));return}hg({view:x,from:h.from,to:h.to,source:e,target:l,pages:[...M.getState().pages].sort(),serialize:w=>A.current?.serializeMd(w)??null}).then(w=>{w&&(At(),an())}),x.focus()}}}),vn&&!g&&f.jsxs(sr,{children:[f.jsxs(Mr,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":ne("unipage.menu.aria"),x:vn.x,y:vn.y,onClick:l=>l.stopPropagation(),onMouseOver:l=>{jn&&!l.target.closest("[data-sub]")&&Lt()},children:[Xe&&f.jsxs(f.Fragment,{children:[f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{En(null);const l=Fe.getView();if(!l||!Pe(l))return;const h=Fe.topRangeOf(l),x=l.state.selection;h?Ve(l,h.from,h.to):x instanceof Me&&Ve(l,x.from,x.to)},children:[f.jsx(pp,{size:13})," ",ne("unipage.menu.askTangu")]}),f.jsx("div",{className:"ubm-sep",role:"separator"})]}),(()=>{const l=To();if(!l.length)return null;const h=uo(),x=l.find($=>$.k===h)??(h==="card"?{icon:Wa,label:ne("unipage.menu.card")}:void 0),w=x?.icon??xi;return f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-sub":"turnInto","aria-haspopup":"menu","aria-expanded":!!jn,className:jn?"is-open":void 0,onMouseEnter:$=>ot($.currentTarget,!1),onClick:$=>ot($.currentTarget,!0),children:[f.jsx(w,{size:13})," ",ne("unipage.menu.turnInto"),f.jsxs("span",{className:"ubm-sub-tail",children:[x?.label,f.jsx(Tl,{size:13})]})]})})(),rc(Fe.getView())&&f.jsx(vb,{view:Fe.getView(),cell:vn.cell??null,onDone:()=>En(null)}),f.jsx("div",{className:"ubm-sep",role:"separator"}),Fe.getView()&&Fe.topRangeOf(Fe.getView())?f.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:ne("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:ke("unipage.menu.toNewColumnMulti")}}))},children:[f.jsx(li,{size:13})," ",ne("unipage.menu.toNewColumn")]}):Fe.getView()&&Fd(Fe.getView().state.selection)&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>Oe((l,h)=>{nu(l,h.from,h.to,h.node)}),children:[f.jsx(li,{size:13})," ",ne("unipage.menu.toNewColumn")]}),Fe.getView()&&Yc(Fe.getView().state.selection)!=null&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{En(null);const l=Fe.getView();if(!l||!Pe(l))return;const h=Yc(l.state.selection);h!=null&&Yg(l,h),l.focus()},children:[f.jsx(Qp,{size:13})," ",ne("unipage.menu.unsplit")]}),Fe.getView()?.state.selection instanceof Me&&Fe.getView().state.selection.node.type.name==="amadeusCanvasCard"&&f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>Oe((l,h)=>{h.node.type.name==="amadeusCanvasCard"&&(bu(l,String(h.node.attrs.anchor)),At(),an())}),children:[f.jsx(fp,{size:13})," ",ne("unipage.menu.backToDoc")]}),f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{En(null);const l=Fe.getView();!l||!Pe(l)||(Fe.duplicate(l)&&(At(),an()),l.focus())},children:[f.jsx(dm,{size:13})," ",ne("unipage.menu.duplicate")]}),(()=>{const l=Fe.getView();if(!l)return null;const h=l.state.selection,x=qe(l),w=h instanceof Me?fg(h.node,e,M.getState().pages):null,$=!!x&&pg(l.state.doc.slice(x.from,x.to).content);return f.jsxs(f.Fragment,{children:[w&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{En(null),mg(w.link),Fe.getView()?.focus()},children:[f.jsx(fm,{size:13})," ",ne(w.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),$&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{En(null);const Y=Fe.getView();if(!Y||!Pe(Y))return;const ae=qe(Y);ae&&Xo({doc:Y.state.doc,...ae})},children:[f.jsx(Wm,{size:13})," ",ne("blocklinks.moveTo")]})]})})(),f.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>_e((l,h)=>{const x=l.state.doc.slice(h.from,h.to).content;l.dispatch(l.state.tr.delete(h.from,h.to).scrollIntoView()),E(x)},(l,h)=>{const x=zo.from(h.node),w=h.$from.parent,$=w.type.name==="amadeusColumnCell"&&w.childCount===1?ou(l.state,h.$from.before(),-1,!0):null;l.dispatch($??l.state.tr.deleteSelection().scrollIntoView()),E(x)}),children:[f.jsx(Ha,{size:13})," ",ne("unipage.menu.delete")]})]}),jn&&(()=>{const l=uo();return f.jsx(Mr,{className:"ctx-menu unified-block-submenu",role:"menu","aria-label":ne("unipage.menu.turnInto"),x:jn.x,y:jn.y,anchorTop:jn.anchorTop,onClick:h=>h.stopPropagation(),onMouseEnter:()=>clearTimeout(bo.current),children:To().map(({k:h,icon:x,label:w,run:$})=>f.jsxs("button",{role:"menuitemradio","aria-checked":h===l,tabIndex:-1,"data-kind":h,onClick:$,children:[f.jsx(x,{size:13})," ",w,h===l&&f.jsx(ea,{size:13,className:"ubm-check"})]},h))})})()]})]})}const tv=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:Nb},Symbol.toStringTag,{value:"Module"}));export{Xh as A,Np as C,Jb as D,ev as F,_p as M,Kh as S,Nb as U,uh as a,ch as b,Fl as c,Gb as d,_l as e,ah as f,ir as g,br as h,ih as i,tv as j,Qb as o,Zb as s};
|