@templatical/editor 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/README.md +1 -1
  2. package/dist/{AiChatSidebar-DxPHFNoT.js → AiChatSidebar-CdjTb9ej.js} +14 -14
  3. package/dist/{AiFeatureMenu-C8GVqu1d.js → AiFeatureMenu-DKm7VYCs.js} +7 -7
  4. package/dist/{BlockIssueBadge-BShkuJis.js → BlockIssueBadge-BdpJwim0.js} +5 -5
  5. package/dist/{BlockPreviewCanvas-tzAtDkXH.js → BlockPreviewCanvas-D_sowkf0.js} +8 -8
  6. package/dist/CloudHeaderExtras-CI8RR9hG.js +55 -0
  7. package/dist/{CloudPanels-Dgw7tb4R.js → CloudPanels-1hwFiJ0G.js} +39 -68
  8. package/dist/CollaborationNotices-BWpKzueF.js +73 -0
  9. package/dist/CollaboratorBar-D87phJsw.js +123 -0
  10. package/dist/{CommentsPanel-DiWzYtnZ.js → CommentsPanel-BUvUzO3T.js} +2 -2
  11. package/dist/{CommentsSidebar-BOqj16Al.js → CommentsSidebar-J65znlrH.js} +14 -14
  12. package/dist/{CountdownBlock-zx39Dyby.js → CountdownBlock-DPQXWRvU.js} +4 -4
  13. package/dist/{CountdownToolbar-C4y3Ft7H.js → CountdownToolbar-CLMIwfK7.js} +7 -7
  14. package/dist/{DesignReferenceSidebar-BWAi3eQQ.js → DesignReferenceSidebar-BTwCFgz8.js} +13 -13
  15. package/dist/{IssuesPanel-C-x3I012.js → IssuesPanel-DeeVsfG7.js} +8 -8
  16. package/dist/{LoadingTrack-6XsqodoY.js → LoadingTrack-BXOptf5g.js} +1 -1
  17. package/dist/{LogicTagInsertButton-B1_Wy0AN.js → LogicTagInsertButton-CR5E4jSG.js} +17 -17
  18. package/dist/{MediaEditModal-ByOvznRC.js → MediaEditModal-C_wxoUMG.js} +3 -3
  19. package/dist/{MediaPanels-9mDBv4aL.js → MediaPanels-BVXDkqtH.js} +2 -2
  20. package/dist/{MergeTagInput-fOewuF27.js → MergeTagInput-BEw_r0PJ.js} +3 -3
  21. package/dist/{MergeTagModeToggle-BXamLcv7.js → MergeTagModeToggle-CJTpFmVd.js} +7 -7
  22. package/dist/{ParagraphEditor-BVjOwwHx.js → ParagraphEditor-zLV44z-R.js} +19 -19
  23. package/dist/{RestoreVersionDialog-BEKXx9xk.js → RestoreVersionDialog-BaDpy3cL.js} +6 -6
  24. package/dist/{RichTextEditorContent-D7kp7iig.js → RichTextEditorContent-CsvniFlI.js} +9 -9
  25. package/dist/{SaveBlockDialog-SJu0lecx.js → SaveBlockDialog-DzWURF_e.js} +12 -12
  26. package/dist/{SavedBlocksBrowserModal-DbmIS5uK.js → SavedBlocksBrowserModal-B8DCFW7t.js} +14 -14
  27. package/dist/{SavedBlocksPanels-Dr5Fxx9Z.js → SavedBlocksPanels-B3Af8ns2.js} +2 -2
  28. package/dist/{SavedBlocksPickBar-DnEWBZJy.js → SavedBlocksPickBar-Dj11-Lqp.js} +5 -5
  29. package/dist/{TemplateScoringPanel-ynbGl-sr.js → TemplateScoringPanel-Ba9sgvjS.js} +16 -16
  30. package/dist/{TemplateSettings-Bi01S3H3.js → TemplateSettings-Cu5X9DgA.js} +11 -11
  31. package/dist/{TestEmailModal-CbRY8HQx.js → TestEmailModal-BeRYV3eg.js} +14 -14
  32. package/dist/{TestEmailPanel-NAOmt3xi.js → TestEmailPanel-B8c3fQi2.js} +2 -2
  33. package/dist/{TitleEditor-Cc3DHbuN.js → TitleEditor-CvpNUoAp.js} +11 -11
  34. package/dist/{ToggleSwitch-Ozc7YU38.js → ToggleSwitch-DHweVJOr.js} +2 -2
  35. package/dist/{Toolbar-B-2lO0I8.js → Toolbar-BadDSkkF.js} +426 -429
  36. package/dist/{TplModal-Bz4-IZ9R.js → TplModal-BZgi9Tes.js} +5 -5
  37. package/dist/{VersionHistoryMenu-CjV1d1zk.js → VersionHistoryMenu-BRlcQ8wX.js} +10 -10
  38. package/dist/{VersionHistoryPanels-BtwxrKJn.js → VersionHistoryPanels-DGkllN3a.js} +2 -2
  39. package/dist/{VersionPreviewBanner-BLAei1kj.js → VersionPreviewBanner-F-811aps.js} +4 -4
  40. package/dist/{WrapperBlock-D0qgNqjD.js → WrapperBlock-DiiaxpMb.js} +5 -5
  41. package/dist/{blockTypeIcons-CEDZytqP.js → blockTypeIcons-CayLluou.js} +2 -2
  42. package/dist/bundle-stats.json +7 -7
  43. package/dist/{ca-CbNzJM3I.js → ca-DSJwJ5ov.js} +23 -1
  44. package/dist/cdn/chunks/{AiChatSidebar-Dk0rJBQN.js → AiChatSidebar-yXJ85Zcg.js} +8 -8
  45. package/dist/cdn/chunks/{AiChatSidebar-Dk0rJBQN.js.map → AiChatSidebar-yXJ85Zcg.js.map} +1 -1
  46. package/dist/cdn/chunks/{AiFeatureMenu-B7b0w8ZS.js → AiFeatureMenu-4ydjrhsQ.js} +6 -6
  47. package/dist/cdn/chunks/{AiFeatureMenu-B7b0w8ZS.js.map → AiFeatureMenu-4ydjrhsQ.js.map} +1 -1
  48. package/dist/cdn/chunks/{BlockIssueBadge-C7sdnkrF.js → BlockIssueBadge-D1VBS_6x.js} +5 -5
  49. package/dist/cdn/chunks/{BlockIssueBadge-C7sdnkrF.js.map → BlockIssueBadge-D1VBS_6x.js.map} +1 -1
  50. package/dist/cdn/chunks/{BlockPreviewCanvas-vK5tBazr.js → BlockPreviewCanvas-m2tWRyWv.js} +8 -8
  51. package/dist/cdn/chunks/{BlockPreviewCanvas-vK5tBazr.js.map → BlockPreviewCanvas-m2tWRyWv.js.map} +1 -1
  52. package/dist/cdn/chunks/{CloudHeaderExtras-B4fhuwc_.js → CloudHeaderExtras-DEkRww7n.js} +16 -20
  53. package/dist/cdn/chunks/CloudHeaderExtras-DEkRww7n.js.map +1 -0
  54. package/dist/cdn/chunks/{CloudPanels-awqHfJqC.js → CloudPanels-XufhBZYF.js} +38 -67
  55. package/dist/cdn/chunks/CloudPanels-XufhBZYF.js.map +1 -0
  56. package/dist/cdn/chunks/CollaborationNotices-CBvKEj1Q.js +75 -0
  57. package/dist/cdn/chunks/CollaborationNotices-CBvKEj1Q.js.map +1 -0
  58. package/dist/cdn/chunks/CollaboratorBar-DWW54Bn_.js +72 -0
  59. package/dist/cdn/chunks/CollaboratorBar-DWW54Bn_.js.map +1 -0
  60. package/dist/cdn/chunks/{CommentsPanel-CbzxwsyI.js → CommentsPanel-R8YLLO3v.js} +3 -3
  61. package/dist/cdn/chunks/{CommentsPanel-CbzxwsyI.js.map → CommentsPanel-R8YLLO3v.js.map} +1 -1
  62. package/dist/cdn/chunks/{CommentsSidebar-DWPHZuQm.js → CommentsSidebar-96NZHVq3.js} +5 -5
  63. package/dist/cdn/chunks/{CommentsSidebar-DWPHZuQm.js.map → CommentsSidebar-96NZHVq3.js.map} +1 -1
  64. package/dist/cdn/chunks/{CountdownBlock-Dasj191h.js → CountdownBlock-DB4JNdqh.js} +5 -5
  65. package/dist/cdn/chunks/{CountdownBlock-Dasj191h.js.map → CountdownBlock-DB4JNdqh.js.map} +1 -1
  66. package/dist/cdn/chunks/{CountdownToolbar-Cqg8FUH-.js → CountdownToolbar-tmiTPEXm.js} +8 -8
  67. package/dist/cdn/chunks/{CountdownToolbar-Cqg8FUH-.js.map → CountdownToolbar-tmiTPEXm.js.map} +1 -1
  68. package/dist/cdn/chunks/{DesignReferenceSidebar-BW9cHnA9.js → DesignReferenceSidebar-D14IIu_P.js} +39 -39
  69. package/dist/cdn/chunks/{DesignReferenceSidebar-BW9cHnA9.js.map → DesignReferenceSidebar-D14IIu_P.js.map} +1 -1
  70. package/dist/cdn/chunks/{IssuesPanel-cXf9ywA4.js → IssuesPanel-BoPiCLGc.js} +8 -8
  71. package/dist/cdn/chunks/{IssuesPanel-cXf9ywA4.js.map → IssuesPanel-BoPiCLGc.js.map} +1 -1
  72. package/dist/cdn/chunks/{LoadingTrack-DbH97JR9.js → LoadingTrack-YU44CM8X.js} +2 -2
  73. package/dist/cdn/chunks/{LoadingTrack-DbH97JR9.js.map → LoadingTrack-YU44CM8X.js.map} +1 -1
  74. package/dist/cdn/chunks/{LogicTagInsertButton-BMB9vShs.js → LogicTagInsertButton-BJ2t2vxC.js} +20 -20
  75. package/dist/cdn/chunks/{LogicTagInsertButton-BMB9vShs.js.map → LogicTagInsertButton-BJ2t2vxC.js.map} +1 -1
  76. package/dist/cdn/chunks/{MediaEditModal-zXfcArr4.js → MediaEditModal-DD0SZ-S3.js} +3 -3
  77. package/dist/cdn/chunks/{MediaEditModal-zXfcArr4.js.map → MediaEditModal-DD0SZ-S3.js.map} +1 -1
  78. package/dist/cdn/chunks/{MediaPanels-Cp4XB_dH.js → MediaPanels-CkdJ_kGp.js} +3 -3
  79. package/dist/cdn/chunks/{MediaPanels-Cp4XB_dH.js.map → MediaPanels-CkdJ_kGp.js.map} +1 -1
  80. package/dist/cdn/chunks/{MergeTagInput-DLqrA9co.js → MergeTagInput-7wXX71DH.js} +4 -4
  81. package/dist/cdn/chunks/{MergeTagInput-DLqrA9co.js.map → MergeTagInput-7wXX71DH.js.map} +1 -1
  82. package/dist/cdn/chunks/{MergeTagModeToggle-BRiJzzn5.js → MergeTagModeToggle-r9vHH4u_.js} +6 -6
  83. package/dist/cdn/chunks/{MergeTagModeToggle-BRiJzzn5.js.map → MergeTagModeToggle-r9vHH4u_.js.map} +1 -1
  84. package/dist/cdn/chunks/{ParagraphEditor-D4aq9eeC.js → ParagraphEditor-CJQjRHXV.js} +29 -29
  85. package/dist/cdn/chunks/{ParagraphEditor-D4aq9eeC.js.map → ParagraphEditor-CJQjRHXV.js.map} +1 -1
  86. package/dist/cdn/chunks/{RestoreVersionDialog-BgR6RXSb.js → RestoreVersionDialog-C5cxBRKi.js} +6 -6
  87. package/dist/cdn/chunks/{RestoreVersionDialog-BgR6RXSb.js.map → RestoreVersionDialog-C5cxBRKi.js.map} +1 -1
  88. package/dist/cdn/chunks/{RichTextEditorContent-C4DMAn0g.js → RichTextEditorContent-BfE7Bkge.js} +8 -8
  89. package/dist/cdn/chunks/{RichTextEditorContent-C4DMAn0g.js.map → RichTextEditorContent-BfE7Bkge.js.map} +1 -1
  90. package/dist/cdn/chunks/{SaveBlockDialog-BaIsQd09.js → SaveBlockDialog-BKbjUnPM.js} +10 -10
  91. package/dist/cdn/chunks/{SaveBlockDialog-BaIsQd09.js.map → SaveBlockDialog-BKbjUnPM.js.map} +1 -1
  92. package/dist/cdn/chunks/{SavedBlocksBrowserModal-CtnB58p_.js → SavedBlocksBrowserModal-BMtyUrUP.js} +10 -10
  93. package/dist/cdn/chunks/{SavedBlocksBrowserModal-CtnB58p_.js.map → SavedBlocksBrowserModal-BMtyUrUP.js.map} +1 -1
  94. package/dist/cdn/chunks/{SavedBlocksPanels-BhEOMzEQ.js → SavedBlocksPanels-s_gxi1im.js} +3 -3
  95. package/dist/cdn/chunks/{SavedBlocksPanels-BhEOMzEQ.js.map → SavedBlocksPanels-s_gxi1im.js.map} +1 -1
  96. package/dist/cdn/chunks/{SavedBlocksPickBar-CcdqTEIp.js → SavedBlocksPickBar-B8WHk5mI.js} +6 -6
  97. package/dist/cdn/chunks/{SavedBlocksPickBar-CcdqTEIp.js.map → SavedBlocksPickBar-B8WHk5mI.js.map} +1 -1
  98. package/dist/cdn/chunks/{TemplateScoringPanel-BrWqJCSP.js → TemplateScoringPanel-BBPnHILC.js} +6 -6
  99. package/dist/cdn/chunks/{TemplateScoringPanel-BrWqJCSP.js.map → TemplateScoringPanel-BBPnHILC.js.map} +1 -1
  100. package/dist/cdn/chunks/{TemplateSettings-BkkWTDHD.js → TemplateSettings-CtrzzQWl.js} +10 -10
  101. package/dist/cdn/chunks/{TemplateSettings-BkkWTDHD.js.map → TemplateSettings-CtrzzQWl.js.map} +1 -1
  102. package/dist/cdn/chunks/{TestEmailModal-V5mwHsUV.js → TestEmailModal-DuZKYMWD.js} +13 -13
  103. package/dist/cdn/chunks/{TestEmailModal-V5mwHsUV.js.map → TestEmailModal-DuZKYMWD.js.map} +1 -1
  104. package/dist/cdn/chunks/{TestEmailPanel-DxrKuctP.js → TestEmailPanel-DERaCdpG.js} +3 -3
  105. package/dist/cdn/chunks/{TestEmailPanel-DxrKuctP.js.map → TestEmailPanel-DERaCdpG.js.map} +1 -1
  106. package/dist/cdn/chunks/{TitleEditor-CsZiG3TT.js → TitleEditor-CEgxjtUX.js} +14 -14
  107. package/dist/cdn/chunks/{TitleEditor-CsZiG3TT.js.map → TitleEditor-CEgxjtUX.js.map} +1 -1
  108. package/dist/cdn/chunks/{ToggleSwitch-BB-bQADJ.js → ToggleSwitch-DGQ7iRc-.js} +3 -3
  109. package/dist/cdn/chunks/{ToggleSwitch-BB-bQADJ.js.map → ToggleSwitch-DGQ7iRc-.js.map} +1 -1
  110. package/dist/cdn/chunks/{Toolbar-C_x2TfFk.js → Toolbar-GFIZQHzw.js} +440 -443
  111. package/dist/cdn/chunks/Toolbar-GFIZQHzw.js.map +1 -0
  112. package/dist/cdn/chunks/{TplModal-DC_eodTV.js → TplModal-DDrbWJcE.js} +5 -5
  113. package/dist/cdn/chunks/{TplModal-DC_eodTV.js.map → TplModal-DDrbWJcE.js.map} +1 -1
  114. package/dist/cdn/chunks/{VersionHistoryMenu-DXnM5Df2.js → VersionHistoryMenu-MlxsUmuT.js} +6 -6
  115. package/dist/cdn/chunks/{VersionHistoryMenu-DXnM5Df2.js.map → VersionHistoryMenu-MlxsUmuT.js.map} +1 -1
  116. package/dist/cdn/chunks/{VersionHistoryPanels-DXSqmaLS.js → VersionHistoryPanels-DVOV8QLv.js} +3 -3
  117. package/dist/cdn/chunks/{VersionHistoryPanels-DXSqmaLS.js.map → VersionHistoryPanels-DVOV8QLv.js.map} +1 -1
  118. package/dist/cdn/chunks/{VersionPreviewBanner-DKyN6BhO.js → VersionPreviewBanner-BQwRKc6S.js} +5 -5
  119. package/dist/cdn/chunks/{VersionPreviewBanner-DKyN6BhO.js.map → VersionPreviewBanner-BQwRKc6S.js.map} +1 -1
  120. package/dist/cdn/chunks/{WrapperBlock-gG_Bleug.js → WrapperBlock-CFuP4R0c.js} +6 -6
  121. package/dist/cdn/chunks/{WrapperBlock-gG_Bleug.js.map → WrapperBlock-CFuP4R0c.js.map} +1 -1
  122. package/dist/cdn/chunks/{blockTypeIcons-HrMJDfVg.js → blockTypeIcons-BnAd8qsP.js} +2 -2
  123. package/dist/cdn/chunks/{blockTypeIcons-HrMJDfVg.js.map → blockTypeIcons-BnAd8qsP.js.map} +1 -1
  124. package/dist/cdn/chunks/{ca-CbNzJM3I.js → ca-DSJwJ5ov.js} +24 -2
  125. package/dist/cdn/chunks/ca-DSJwJ5ov.js.map +1 -0
  126. package/dist/{cloud-B5xwm_4X.js → cdn/chunks/cloud-CI_fgDyy.js} +116 -293
  127. package/dist/cdn/chunks/cloud-CI_fgDyy.js.map +1 -0
  128. package/dist/cdn/chunks/{createCloudRuntime-Vd0N4elZ.js → createCloudRuntime-DiYCJ21w.js} +127 -169
  129. package/dist/cdn/chunks/createCloudRuntime-DiYCJ21w.js.map +1 -0
  130. package/dist/{de-DMquBpZM.js → cdn/chunks/de-CBE6O79z.js} +25 -1
  131. package/dist/cdn/chunks/de-CBE6O79z.js.map +1 -0
  132. package/dist/{de-mMY5yQJu.js → cdn/chunks/de-D_atmUVB.js} +2 -4
  133. package/dist/cdn/chunks/{de-mMY5yQJu.js.map → de-D_atmUVB.js.map} +1 -1
  134. package/dist/cdn/chunks/{dist-MNQYSEWU.js → dist-DdwjXLme.js} +3 -3
  135. package/dist/cdn/chunks/{dist-MNQYSEWU.js.map → dist-DdwjXLme.js.map} +1 -1
  136. package/dist/cdn/chunks/{dist-CjL6JHML.js → dist-Doy3r07H.js} +2 -2
  137. package/dist/cdn/chunks/{dist-CjL6JHML.js.map → dist-Doy3r07H.js.map} +1 -1
  138. package/dist/cdn/chunks/{draggable-DrsNwZuB.js → draggable-akeQH_JP.js} +1682 -1683
  139. package/dist/cdn/chunks/draggable-akeQH_JP.js.map +1 -0
  140. package/dist/cdn/chunks/{editor-modal-vEEmZ8Tu.js → editor-modal-HJBy9kLj.js} +88 -88
  141. package/dist/cdn/chunks/{editor-modal-vEEmZ8Tu.js.map → editor-modal-HJBy9kLj.js.map} +1 -1
  142. package/dist/cdn/chunks/{en-C8Mp71sO.js → en-CDexnk0p.js} +24 -2
  143. package/dist/cdn/chunks/en-CDexnk0p.js.map +1 -0
  144. package/dist/{en-ChVeGQBY.js → cdn/chunks/en-DhJLnaBx.js} +2 -4
  145. package/dist/cdn/chunks/en-DhJLnaBx.js.map +1 -0
  146. package/dist/cdn/chunks/en-Ve-PWSXu.js +1 -0
  147. package/dist/{es-Byq4tthI.js → cdn/chunks/es-BE42B6uN.js} +25 -1
  148. package/dist/cdn/chunks/es-BE42B6uN.js.map +1 -0
  149. package/dist/cdn/chunks/{extensions-hJ9VqzDc.js → extensions-koOuDeZS.js} +23 -23
  150. package/dist/cdn/chunks/{extensions-hJ9VqzDc.js.map → extensions-koOuDeZS.js.map} +1 -1
  151. package/dist/{fr-B3j35HEw.js → cdn/chunks/fr-DlJFPDQR.js} +25 -1
  152. package/dist/cdn/chunks/fr-DlJFPDQR.js.map +1 -0
  153. package/dist/cdn/chunks/{icons-aTYwH5-g.js → icons-CjlNV8xD.js} +46 -46
  154. package/dist/cdn/chunks/{icons-aTYwH5-g.js.map → icons-CjlNV8xD.js.map} +1 -1
  155. package/dist/{ja-D7txAuGS.js → cdn/chunks/ja-CUT8gkNI.js} +25 -1
  156. package/dist/cdn/chunks/ja-CUT8gkNI.js.map +1 -0
  157. package/dist/cdn/chunks/{keys-HI-INbkz.js → keys-UAWhQ3zW.js} +2 -2
  158. package/dist/cdn/chunks/{keys-HI-INbkz.js.map → keys-UAWhQ3zW.js.map} +1 -1
  159. package/dist/{nl-ClJ3BY3F.js → cdn/chunks/nl-bXWqqRyS.js} +25 -1
  160. package/dist/cdn/chunks/nl-bXWqqRyS.js.map +1 -0
  161. package/dist/cdn/chunks/{preRenderCustomBlocks-ByfuSjtL.js → preRenderCustomBlocks-DqKbdTJ8.js} +5 -5
  162. package/dist/cdn/chunks/{preRenderCustomBlocks-ByfuSjtL.js.map → preRenderCustomBlocks-DqKbdTJ8.js.map} +1 -1
  163. package/dist/cdn/chunks/{pt-BR-DibcXcmv.js → pt-BR-2_H4-wlb.js} +24 -2
  164. package/dist/cdn/chunks/pt-BR-2_H4-wlb.js.map +1 -0
  165. package/dist/{pt-BR-CoCwRUi0.js → cdn/chunks/pt-BR-BphMoUTw.js} +2 -4
  166. package/dist/cdn/chunks/{pt-BR-CoCwRUi0.js.map → pt-BR-BphMoUTw.js.map} +1 -1
  167. package/dist/cdn/chunks/{pusher-C8DeiO2X.js → pusher-Cs4GGEtd.js} +2 -2
  168. package/dist/cdn/chunks/pusher-Cs4GGEtd.js.map +1 -0
  169. package/dist/cdn/chunks/{rolldown-runtime-B0aSnxlc.js → rolldown-runtime-Y_bBpyJl.js} +1 -1
  170. package/dist/cdn/chunks/socialIcons-CkZSYpoG.js +2091 -0
  171. package/dist/cdn/chunks/socialIcons-CkZSYpoG.js.map +1 -0
  172. package/dist/cdn/chunks/{src-DlFlC9Tt.js → src-B1e5SSYP.js} +84 -84
  173. package/dist/cdn/chunks/{src-DlFlC9Tt.js.map → src-B1e5SSYP.js.map} +1 -1
  174. package/dist/cdn/chunks/{src-dZ4D_tuP.js → src-B77z1iw4.js} +117 -117
  175. package/dist/cdn/chunks/src-B77z1iw4.js.map +1 -0
  176. package/dist/cdn/chunks/{src-DYCDeBDM.js → src-CvLTYGdO.js} +549 -315
  177. package/dist/cdn/chunks/src-CvLTYGdO.js.map +1 -0
  178. package/dist/cdn/chunks/{styleConstants-D1Jz-TFU.js → styleConstants-v1dNKgJf.js} +2 -4
  179. package/dist/cdn/chunks/{styleConstants-D1Jz-TFU.js.map → styleConstants-v1dNKgJf.js.map} +1 -1
  180. package/dist/cdn/chunks/timeouts-o5Y9BuqI.js +6 -0
  181. package/dist/cdn/chunks/timeouts-o5Y9BuqI.js.map +1 -0
  182. package/dist/cdn/chunks/{tiptap-BPigZk5G.js → tiptap-B1RfWFzB.js} +3 -3
  183. package/dist/cdn/chunks/tiptap-B1RfWFzB.js.map +1 -0
  184. package/dist/cdn/chunks/{useAliveFlag-DCB96vzR.js → useAliveFlag-PuXh83UK.js} +2 -2
  185. package/dist/cdn/chunks/{useAliveFlag-DCB96vzR.js.map → useAliveFlag-PuXh83UK.js.map} +1 -1
  186. package/dist/cdn/chunks/{useCloudI18n-BBF4waXO.js → useCloudI18n-kp07GQmk.js} +3 -3
  187. package/dist/cdn/chunks/{useCloudI18n-BBF4waXO.js.map → useCloudI18n-kp07GQmk.js.map} +1 -1
  188. package/dist/cdn/chunks/{useEditorCore-Bb2UcB20.js → useEditorCore-DpCFvHg_.js} +440 -419
  189. package/dist/cdn/chunks/useEditorCore-DpCFvHg_.js.map +1 -0
  190. package/dist/cdn/chunks/useEditorRoot-5SBqm90x.js +10 -0
  191. package/dist/cdn/chunks/{useEditorRoot-CTc6O8al.js.map → useEditorRoot-5SBqm90x.js.map} +1 -1
  192. package/dist/cdn/chunks/{useI18n-DUlyyIJJ.js → useI18n-DEqtEgOs.js} +3 -3
  193. package/dist/cdn/chunks/{useI18n-DUlyyIJJ.js.map → useI18n-DEqtEgOs.js.map} +1 -1
  194. package/dist/cdn/chunks/{useLogicTag-HsyUCQtl.js → useLogicTag-X8bc5qNl.js} +4 -4
  195. package/dist/cdn/chunks/{useLogicTag-HsyUCQtl.js.map → useLogicTag-X8bc5qNl.js.map} +1 -1
  196. package/dist/cdn/chunks/{useMergeTag-Dg9pE85U.js → useMergeTag-DFoOexIQ.js} +6 -6
  197. package/dist/cdn/chunks/{useMergeTag-Dg9pE85U.js.map → useMergeTag-DFoOexIQ.js.map} +1 -1
  198. package/dist/cdn/chunks/{usePopoverPosition-IbaW6-Ao.js → usePopoverPosition-Cz9-XiXR.js} +3 -3
  199. package/dist/cdn/chunks/{usePopoverPosition-IbaW6-Ao.js.map → usePopoverPosition-Cz9-XiXR.js.map} +1 -1
  200. package/dist/cdn/chunks/{useScrollToBlock-uUa601I4.js → useScrollToBlock-MNzurEZV.js} +3 -3
  201. package/dist/cdn/chunks/{useScrollToBlock-uUa601I4.js.map → useScrollToBlock-MNzurEZV.js.map} +1 -1
  202. package/dist/cdn/chunks/{withCurrentFont-oLcATrQ8.js → withCurrentFont-D-f61ghC.js} +2 -2
  203. package/dist/cdn/chunks/{withCurrentFont-oLcATrQ8.js.map → withCurrentFont-D-f61ghC.js.map} +1 -1
  204. package/dist/cdn/editor.css +1 -1
  205. package/dist/cdn/editor.js +1319 -1066
  206. package/dist/cdn/editor.js.map +1 -1
  207. package/dist/{check-ClwqRMgv.js → check-DQQzkmIC.js} +1 -1
  208. package/dist/{chevron-down-te6qn-zE.js → chevron-down-CIF4bdon.js} +1 -1
  209. package/dist/{chevron-right-W2hbH1FM.js → chevron-right-Cg7Xu-ev.js} +1 -1
  210. package/dist/{chevron-up-Bf5Zo7o4.js → chevron-up-Csu7ISD-.js} +1 -1
  211. package/dist/{circle-alert-CIEGV5DN.js → circle-alert-YUvIJAgY.js} +1 -1
  212. package/dist/{clock-Y4cx0gkJ.js → clock-CnSIGKQW.js} +1 -1
  213. package/dist/{cdn/chunks/cloud-BHClP3e2.js → cloud-YUYDtdHt.js} +308 -569
  214. package/dist/{copy-BEcsAlfB.js → copy-CUC43md_.js} +1 -1
  215. package/dist/{createCloudRuntime-zNPkF6T9.js → createCloudRuntime-BMDRjL0k.js} +126 -168
  216. package/dist/{createLucideIcon-CYHXK9hn.js → createLucideIcon-BcP1sjdp.js} +6 -6
  217. package/dist/{cdn/chunks/de-DMquBpZM.js → de-CBE6O79z.js} +23 -3
  218. package/dist/{cdn/chunks/de-mMY5yQJu.js → de-D_atmUVB.js} +0 -6
  219. package/dist/{dist-CUWI-IvA.js → dist-Bv_GBr2l.js} +1 -1
  220. package/dist/{dist-DAAJogrx.js → dist-CCqn-RqE.js} +2 -2
  221. package/dist/{dist-DuufrR8O.js → dist-CNqjHA8e.js} +2 -2
  222. package/dist/{dist-tsmnQugO.js → dist-DBG3nh3k.js} +503 -273
  223. package/dist/{editor-modal-AlVLkU91.js → editor-modal--7_9A6j-.js} +20 -20
  224. package/dist/en-BHCMzqib.js +1 -0
  225. package/dist/{en-C8Mp71sO.js → en-CDexnk0p.js} +23 -1
  226. package/dist/{cdn/chunks/en-ChVeGQBY.js → en-DhJLnaBx.js} +0 -6
  227. package/dist/{cdn/chunks/es-Byq4tthI.js → es-BE42B6uN.js} +23 -3
  228. package/dist/{extensions-pjO8VGkM.js → extensions-zwsZlWjH.js} +23 -23
  229. package/dist/{eye-Ddnz8nnm.js → eye-B1bua-ck.js} +1 -1
  230. package/dist/{cdn/chunks/fr-B3j35HEw.js → fr-DlJFPDQR.js} +23 -3
  231. package/dist/{image-up-CM_HC0Dx.js → image-up-BqiO7KCO.js} +1 -1
  232. package/dist/index.d.ts +290 -35
  233. package/dist/{info-DXLmzoeY.js → info-x26nGOo2.js} +1 -1
  234. package/dist/{cdn/chunks/ja-D7txAuGS.js → ja-CUT8gkNI.js} +23 -3
  235. package/dist/{keys-BKFq19a2.js → keys-BymCnLHD.js} +1 -1
  236. package/dist/{link-Cel46wgo.js → link-CezhndyR.js} +1 -1
  237. package/dist/{list-Cl0GwiV9.js → list-DQqdptI0.js} +1 -1
  238. package/dist/{loader-circle-uAwpvfys.js → loader-circle-DCEeoYoi.js} +1 -1
  239. package/dist/{message-circle-DWU1pTM_.js → message-circle-BLGzfv_7.js} +1 -1
  240. package/dist/{cdn/chunks/nl-ClJ3BY3F.js → nl-bXWqqRyS.js} +23 -3
  241. package/dist/{package-CbyG_yU_.js → package-D_kEQCMU.js} +1 -1
  242. package/dist/{pencil-BzoDcwKu.js → pencil-Dct8zGLy.js} +1 -1
  243. package/dist/{plus-8cDvoCjZ.js → plus-BDd0gTEm.js} +1 -1
  244. package/dist/{preRenderCustomBlocks-DMP5RuHl.js → preRenderCustomBlocks-CtKJecE-.js} +3 -3
  245. package/dist/{pt-BR-DibcXcmv.js → pt-BR-2_H4-wlb.js} +23 -1
  246. package/dist/{cdn/chunks/pt-BR-CoCwRUi0.js → pt-BR-BphMoUTw.js} +0 -6
  247. package/dist/{refresh-cw-9WinWixo.js → refresh-cw-tGMRDxr8.js} +1 -1
  248. package/dist/{runtime-dom.esm-bundler-lFF-QG3j.js → runtime-dom.esm-bundler-DYn1z2Xf.js} +1 -1
  249. package/dist/{search-CqgGq1gG.js → search-Bm2cCQpe.js} +1 -1
  250. package/dist/{send-Ceo3c9Db.js → send-sVLaKZ7f.js} +1 -1
  251. package/dist/{shield-check-uDAwur5D.js → shield-check-YhsbXfQc.js} +1 -1
  252. package/dist/{smartphone-CcLaCpGK.js → smartphone-B2W81p02.js} +1 -1
  253. package/dist/socialIcons-Bwv-49EB.js +2167 -0
  254. package/dist/{sparkles-Do9XjAuT.js → sparkles-a1qkBZ8X.js} +1 -1
  255. package/dist/style.css +1 -1
  256. package/dist/{styleConstants-D1Jz-TFU.js → styleConstants-v1dNKgJf.js} +1 -3
  257. package/dist/templatical-editor.js +1409 -1156
  258. package/dist/{text-align-start-DvzC0HQA.js → text-align-start-CTuwQ5YW.js} +1 -1
  259. package/dist/timeouts-o5Y9BuqI.js +4 -0
  260. package/dist/{trash-vlINTx32.js → trash-I3D2peFQ.js} +1 -1
  261. package/dist/{triangle-alert-MRYSJ9T2.js → triangle-alert-CenxmLRE.js} +1 -1
  262. package/dist/{upload-CtNOI6J2.js → upload-uU2cK0Ce.js} +1 -1
  263. package/dist/{useAliveFlag-Dd06mRxe.js → useAliveFlag-BjP0Gxza.js} +1 -1
  264. package/dist/{useCloudI18n-Nwqo7pI_.js → useCloudI18n-CGVEZV3o.js} +2 -2
  265. package/dist/{useEditorCore-PvErWWsp.js → useEditorCore-DRbMRe8F.js} +806 -785
  266. package/dist/{useEditorRoot-BD3piYtD.js → useEditorRoot-BVm2-1N8.js} +2 -2
  267. package/dist/{useI18n-CxVEpurs.js → useI18n-CSh4gO5c.js} +2 -2
  268. package/dist/{useLogicTag-BHn67tDd.js → useLogicTag-zcI6BWIf.js} +3 -3
  269. package/dist/{useMergeTag-CRkm5Ig6.js → useMergeTag-C-iBLlp0.js} +5 -5
  270. package/dist/{usePopoverPosition-CwnH1o5g.js → usePopoverPosition-CMcsMBtK.js} +2 -2
  271. package/dist/{useScrollToBlock-CXmcHQQN.js → useScrollToBlock-CdCQK9QQ.js} +3 -3
  272. package/dist/{vue.runtime.esm-bundler-CAzmrXdD.js → vue.runtime.esm-bundler-DV0Wx4r_.js} +1079 -1080
  273. package/dist/{withCurrentFont-CxRGeHO3.js → withCurrentFont-D62njRLu.js} +1 -1
  274. package/dist/{x-Cd6SFw8r.js → x-KFQ4S-Kz.js} +1 -1
  275. package/package.json +12 -12
  276. package/dist/CloudHeaderExtras-CUSftQdm.js +0 -59
  277. package/dist/CollaboratorBar-5rfopCPx.js +0 -103
  278. package/dist/cdn/chunks/CloudHeaderExtras-B4fhuwc_.js.map +0 -1
  279. package/dist/cdn/chunks/CloudPanels-awqHfJqC.js.map +0 -1
  280. package/dist/cdn/chunks/CollaboratorBar-CS0ivqkr.js +0 -52
  281. package/dist/cdn/chunks/CollaboratorBar-CS0ivqkr.js.map +0 -1
  282. package/dist/cdn/chunks/Toolbar-C_x2TfFk.js.map +0 -1
  283. package/dist/cdn/chunks/ca-CbNzJM3I.js.map +0 -1
  284. package/dist/cdn/chunks/cloud-BHClP3e2.js.map +0 -1
  285. package/dist/cdn/chunks/createCloudRuntime-Vd0N4elZ.js.map +0 -1
  286. package/dist/cdn/chunks/de-DMquBpZM.js.map +0 -1
  287. package/dist/cdn/chunks/draggable-DrsNwZuB.js.map +0 -1
  288. package/dist/cdn/chunks/en-C8Mp71sO.js.map +0 -1
  289. package/dist/cdn/chunks/en-ChVeGQBY.js.map +0 -1
  290. package/dist/cdn/chunks/en-eWpiXyZu.js +0 -1
  291. package/dist/cdn/chunks/es-Byq4tthI.js.map +0 -1
  292. package/dist/cdn/chunks/fr-B3j35HEw.js.map +0 -1
  293. package/dist/cdn/chunks/ja-D7txAuGS.js.map +0 -1
  294. package/dist/cdn/chunks/nl-ClJ3BY3F.js.map +0 -1
  295. package/dist/cdn/chunks/pt-BR-DibcXcmv.js.map +0 -1
  296. package/dist/cdn/chunks/pusher-C8DeiO2X.js.map +0 -1
  297. package/dist/cdn/chunks/socialIcons-C_lnkpG6.js +0 -1279
  298. package/dist/cdn/chunks/socialIcons-C_lnkpG6.js.map +0 -1
  299. package/dist/cdn/chunks/src-DYCDeBDM.js.map +0 -1
  300. package/dist/cdn/chunks/src-dZ4D_tuP.js.map +0 -1
  301. package/dist/cdn/chunks/timeouts-Cv2jvusx.js +0 -6
  302. package/dist/cdn/chunks/timeouts-Cv2jvusx.js.map +0 -1
  303. package/dist/cdn/chunks/tiptap-BPigZk5G.js.map +0 -1
  304. package/dist/cdn/chunks/useEditorCore-Bb2UcB20.js.map +0 -1
  305. package/dist/cdn/chunks/useEditorRoot-CTc6O8al.js +0 -10
  306. package/dist/en-B0FUfNwz.js +0 -1
  307. package/dist/socialIcons-PTiwhLoC.js +0 -1359
  308. package/dist/timeouts-Cv2jvusx.js +0 -4
@@ -1 +0,0 @@
1
- {"version":3,"file":"socialIcons-C_lnkpG6.js","names":["computed","DEFAULT_KEY","computed","computed","computed","computed","_openBlock","_createElementBlock","_normalizeClass","_normalizeStyle","_Fragment","_createVNode","_unref","_createTextVNode","_toDisplayString","_sfc_main","computed","computed","watch$1","inject","getCurrentScope","openBlock","ref","defineComponent","computed","reactive","onScopeDispose","readonly","unref","createVNode","normalizeClass","computed$1","createElementBlock","normalizeStyle","watch","toValue","Fragment","toDisplayString","createTextVNode","cloneBlock","assertNoWrapperInContent","assertNoSlotInContent","generateId","toBorderCss","resolveHero","applyLayout","safeClone","createDefaultTemplateContent","isSection","SOCIAL_ICON_GLYPHS","isWrapper","containsMergeTag","createBlock","SYNTAX_PRESETS","SdkError","useDropZone","ON_REQUEST_MEDIA_KEY","MERGE_TAG_SYNTAX_KEY","CAN_DROP_MEDIA_KEY","IMAGE_URL_RESOLVER_KEY","NATURAL_SIZE_TIMEOUT_MS","useI18n","DEFAULT_RESOLVED_COLORS","resolveColorsConfig","LoaderCircle","Upload","useAliveFlag","wrapReportedError","error","notifyHandler","getColumnCount","layout","useEditor","seedContent","options","state","revision","touch","content","value","selectedBlock","findBlockById","block","blocks","id","column","found","collectBlockIds","ids","child","findBlockParent","i","parent","colIdx","result","isBlockLocked","blockId","findBlockLocation","index","b","setContent","newContent","markDirty","selectBlock","setViewport","viewport","setDarkMode","darkMode","setUiTheme","theme","setPreviewMode","previewMode","updateBlock","updates","updateSettings","addBlock","candidate","targetSectionId","section","columnIndex","targetArray","removeBlock","removed","removedIds","moveBlock","oldIndex","newIndex","refuse","action","reason","notify","run","requireProvider","templates","setName","create","provider","providerCreate","created","input","revisionAtRequest","load","loaded","templateId","save","providerSave","current","patch","saved","localName","hasTemplate","MAX_STACK_SIZE","DEBOUNCE_MS","NAVIGATE_IDLE_MS","useHistory","undoStack","redoStack","isNavigating","navigatingTimeoutId","pendingDebounce","canUndo","canRedo","cloneContent","pushToUndoStack","snapshot","maxSize","flushPendingDebounce","record","isRemoteOperation","recordDebounced","setNavigating","undo","redo","clear","destroy","useBlockActions","createAndAddBlock","defaults","type","duplicateBlock","cloned","sourceLocation","deleteBlock","updateBlockProperty","key","DEFAULT_AUTO_SAVE_DEBOUNCE_MS","useAutoSave","timeoutId","paused","isEnabled","enabled","pause","cancel","resume","flush","isDirty","onChange","scheduleOnChange","debounce","stopWatch","useConditionPreview","hiddenBlockIds","hasHiddenBlocks","isHidden","toggleBlock","editor","reset","useDataSourceFetch","isFetching","fetchError","hasDataSource","needsFetch","fetch","def","merged","useHistoryInterceptor","originalAddBlock","originalRemoveBlock","originalMoveBlock","originalUpdateBlock","originalUpdateSettings","history","useSavedBlocks","savedBlocks","isLoading","categories","seen","category","a","canCreate","canUpdate","canDelete","canUpdateBlock","canDeleteBlock","params","update","providerUpdate","local","updated","remove","providerDelete","DEFAULT_KEY$1","createLocalStorageSavedBlocksProvider","storageKey","getStorage","readAll","raw","parsed","writeAll","all","search","now","next","DEFAULT_KEY","PAGE_SIZE","createLocalStorageMediaProvider","assets","readFileAsDataURL","reader","resolve","reject","file","filtered","filename","asset","alt","offset","items","page","nextOffset","url","useVersionHistory","versions","nextCursor","isRestoring","fetched","canRestore","requireTemplateId","getTemplateId","peekContent","version","resolveContent","known","meta","restore","providerRestore","restored","versionId","useComments","comments","isSubmitting","canResolve","totalCount","sum","thread","unresolvedCount","commentCountByBlock","map","requireUser","user","getUser","find","commentId","reply","isOwn","comment","report","wrapped","replaceAt","list","sameComment","upsert","changed","replies","at","drop","existing","parentId","r","c","setResolved","providerSetResolved","resolved","applyRemoteCreate","applyRemoteUpdate","applyRemoteDelete","useCommentListener","subscribe","unsubscribe","stop","change","createImageUrlResolver","cache","inFlight","get","src","has","lookup","useResolvedImageSrc","resolver","srcRef","timer","clearTimer","initial","immediate","readCachedImageUrl","hasMergeTagBackground","bg","syntax","getBackgroundLookupUrl","useResolvedBackgroundUrl","display","readCachedBackgroundUrl","getBlockTypeLabel","translations","blockType","getBlockLabel","customBlockDefinitions","d","customType","resolveFieldColors","own","field","presetsInherited","editorResolved","isSize","toNaturalSize","width","height","naturalSizeOf","naturalSizeFields","size","loadNaturalSize","done","image","measureNaturalSize","MediaDropOverlay_default","props","__props","SIZES","sizing","t","IMAGE_MIME_PREFIX","useImageDrop","target","images","files","onFiles","isOverDropZone","useMediaDropField","onRequestMedia","canDropMedia","aliveFlag","openMediaBrowser","apply","isUploading","dropEnabled","blocked","uploadDroppedFiles","showOverlay","isOver","getEmailFrameWidth","settings","EMAIL_FRAME_WIDTH_TRANSITION","COLUMN_PERCENTS","horizontalInset","whole","drawn","side","padding","border","insideBand","blockRoom","columnContent","bandedBlocks","documentOf","imageRoom","doc","sectionBox","bandWidth","percents","sectionBandWidth","sectionId","matchImageBoxWidth","hero","socialIcons","socialIconSizeMap","socialPlatformOptions"],"sources":["../../../../core/src/error-reporting.ts","../../../../core/src/editor.ts","../../../../core/src/history.ts","../../../../core/src/block-actions.ts","../../../../core/src/auto-save.ts","../../../../core/src/condition-preview.ts","../../../../core/src/data-source-fetch.ts","../../../../core/src/history-interceptor.ts","../../../../core/src/saved-blocks.ts","../../../../core/src/saved-blocks-local.ts","../../../../core/src/media-local.ts","../../../../core/src/version-history.ts","../../../../core/src/comments.ts","../../../src/composables/useImageUrlResolver.ts","../../../src/utils/blockTypeLabels.ts","../../../src/utils/resolveFieldColors.ts","../../../src/utils/imageNaturalSize.ts","../../../src/components/MediaDropOverlay.vue","../../../src/components/MediaDropOverlay.vue","../../../src/composables/useImageDrop.ts","../../../src/composables/useMediaDropField.ts","../../../src/utils/emailFrameWidth.ts","../../../src/utils/imageRoom.ts","../../../src/constants/socialIcons.ts"],"sourcesContent":["/**\n * Turn a thrown value into an `Error`.\n *\n * A `catch` clause's binding is `unknown` — a provider or a consumer's event\n * handler can throw a string, an object, or anything else. `onError` callbacks\n * across this package are typed to take an `Error`, so this is what makes that\n * contract honest at the one place values actually cross it.\n */\nexport function wrapReportedError(error: unknown): Error {\n return error instanceof Error\n ? error\n : new Error(String(error), { cause: error });\n}\n\n/**\n * Run a consumer's event handler without letting it fail the operation it\n * followed.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the caller has already succeeded by the time this runs. `onError` is taken\n * as a parameter rather than read from a shared reporter, so every feature\n * module keeps its own `options.onError` wiring and this stays reusable by\n * any module with the same fire-and-forget event shape.\n */\nexport function notifyHandler(\n onError: ((error: Error) => void) | undefined,\n run: () => void,\n): void {\n try {\n run();\n } catch (error) {\n onError?.(wrapReportedError(error));\n }\n}\n","import type {\n Block,\n ColumnLayout,\n Template,\n TemplateContent,\n TemplateDefaults,\n TemplatePatch,\n TemplateSaveTrigger,\n TemplateSettings,\n TemplatesProvider,\n UiTheme,\n ViewportSize,\n} from \"@templatical/types\";\nimport {\n assertNoSlotInContent,\n assertNoWrapperInContent,\n createDefaultTemplateContent,\n SdkError,\n} from \"@templatical/types\";\nimport { notifyHandler } from \"./error-reporting\";\n\nfunction getColumnCount(layout: ColumnLayout): number {\n if (layout === \"1\") return 1;\n if (layout === \"3\") return 3;\n return 2;\n}\nimport {\n computed,\n reactive,\n readonly,\n type DeepReadonly,\n type Ref,\n} from \"@vue/reactivity\";\n\nexport interface EditorState {\n /**\n * The template currently being edited, as the store last returned it — `null`\n * until `create()` or `load()` resolves, and always `null` without a\n * {@link TemplatesProvider}.\n *\n * Carries identity and name only for practical purposes: its `content` is the\n * store's copy from the last round-trip, whereas `state.content` is what the\n * user is editing.\n */\n template: Template | null;\n content: TemplateContent;\n selectedBlockId: string | null;\n viewport: ViewportSize;\n darkMode: boolean;\n previewMode: boolean;\n isDirty: boolean;\n /** True for the duration of a `save()` call. */\n isSaving: boolean;\n /** True for the duration of a `create()` or `load()` call. */\n isLoading: boolean;\n uiTheme: UiTheme;\n}\n\nexport interface UseEditorOptions {\n content: TemplateContent;\n defaultFontFamily?: string;\n templateDefaults?: TemplateDefaults;\n lockedBlocks?: Ref<Map<string, unknown>>;\n /**\n * Storage backend for the template's save/load lifecycle. Omit it and\n * `create()` / `load()` / `save()` reject — the editor keeps working as a\n * purely local editing surface.\n */\n templates?: TemplatesProvider;\n /**\n * Called with any error a provider call rejects with, before the rejection is\n * re-thrown to the caller.\n */\n onError?: (error: Error) => void;\n}\n\nexport interface UseEditorReturn {\n state: DeepReadonly<EditorState>;\n content: Ref<TemplateContent>;\n selectedBlock: Ref<Block | null>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n selectBlock: (blockId: string | null) => void;\n setViewport: (viewport: ViewportSize) => void;\n setDarkMode: (darkMode: boolean) => void;\n setPreviewMode: (previewMode: boolean) => void;\n setUiTheme: (theme: UiTheme) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n isBlockLocked: (blockId: string) => boolean;\n markDirty: () => void;\n findBlockLocation: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n /**\n * Rename the loaded template locally and mark the editor dirty. The new name\n * reaches the store on the next `save()`, in the same patch as the content —\n * a rename is an ordinary unsaved change, not a side channel.\n *\n * This method only stages it. The editor's inline rename field commits by\n * calling `setName()` and then saving immediately, because a rename reads as a\n * discrete action rather than an edit to be batched — so in the editor the\n * \"next `save()`\" is usually the one it triggers itself. A headless caller\n * decides its own moment.\n *\n * No-op when no template is loaded: there is nothing to name.\n */\n setName: (name: string) => void;\n /**\n * Persist the current content as a new template. `input.content`, when given,\n * replaces the editor's content first — so `create({ content })` both loads\n * and stores in one step.\n */\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n /** Fetch a template and make it the editor's content. */\n load: (templateId: string) => Promise<Template>;\n /**\n * Persist the loaded template's name + content as a patch.\n *\n * `trigger` is passed through to `TemplatesOptions.onSaved`. It defaults to\n * `\"api\"`, which is the honest answer for a direct call — the editor package\n * passes the value matching whichever affordance fired.\n */\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n /** Whether a template has been created or loaded. */\n hasTemplate: () => boolean;\n}\n\nexport function useEditor(options: UseEditorOptions): UseEditorReturn {\n const seedContent =\n options.content ??\n createDefaultTemplateContent(\n options.defaultFontFamily,\n options.templateDefaults,\n );\n // Layout-only; authored content must not contain slot or wrapper.\n assertNoSlotInContent(seedContent);\n assertNoWrapperInContent(seedContent);\n\n const state = reactive<EditorState>({\n template: null,\n content: seedContent,\n selectedBlockId: null,\n viewport: \"desktop\",\n darkMode: false,\n previewMode: false,\n isDirty: false,\n isSaving: false,\n isLoading: false,\n uiTheme: \"auto\",\n });\n\n /**\n * Bumped by every content mutation. `save()` captures it before awaiting the\n * provider and only clears `isDirty` if it is unchanged afterwards, so an edit\n * made while a save is in flight is not reported as persisted — which would\n * also make autosave skip it, since that decides dirtiness at debounce time.\n */\n let revision = 0;\n\n function touch(): void {\n state.isDirty = true;\n revision++;\n }\n\n const content = computed({\n get: () => state.content,\n set: (value: TemplateContent) => {\n state.content = value;\n touch();\n },\n });\n\n const selectedBlock = computed(() => {\n if (!state.selectedBlockId) return null;\n return findBlockById(state.content.blocks, state.selectedBlockId);\n });\n\n function findBlockById(blocks: Block[], id: string): Block | null {\n for (const block of blocks) {\n if (block.id === id) return block;\n if (block.type === \"section\") {\n for (const column of block.children) {\n const found = findBlockById(column, id);\n if (found) return found;\n }\n }\n }\n return null;\n }\n\n function collectBlockIds(block: Block, ids: Set<string>): void {\n ids.add(block.id);\n if (block.type === \"section\") {\n for (const column of block.children) {\n for (const child of column) {\n collectBlockIds(child, ids);\n }\n }\n }\n }\n\n function findBlockParent(\n blocks: Block[],\n id: string,\n parent: {\n blocks: Block[];\n sectionId?: string;\n columnIndex?: number;\n } = { blocks },\n ): { blocks: Block[]; sectionId?: string; columnIndex?: number } | null {\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (block.id === id) return parent;\n if (block.type === \"section\") {\n for (let colIdx = 0; colIdx < block.children.length; colIdx++) {\n const result = findBlockParent(block.children[colIdx], id, {\n blocks: block.children[colIdx],\n sectionId: block.id,\n columnIndex: colIdx,\n });\n if (result) return result;\n }\n }\n }\n return null;\n }\n\n function isBlockLocked(blockId: string): boolean {\n return options.lockedBlocks?.value.has(blockId) ?? false;\n }\n\n function findBlockLocation(blockId: string): {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null {\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return null;\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index === -1) return null;\n return {\n targetSectionId: parent.sectionId,\n columnIndex: parent.columnIndex,\n index,\n };\n }\n\n // TODO(collab): the lock checks in addBlock/moveBlock/removeBlock/updateBlock\n // are shallow — they only consider the directly-targeted block id. A section\n // can still be removed, moved, or have its `children` array rewritten while a\n // peer is editing one of its descendants, which silently disrupts that peer's\n // edit. Add a `hasLockedDescendant(blockId)` helper and gate section-level\n // operations on it (and on the parent of each affected child) so cascades\n // through the tree are also blocked.\n\n function setContent(newContent: TemplateContent, markDirty = true): void {\n assertNoSlotInContent(newContent);\n assertNoWrapperInContent(newContent);\n state.content = newContent;\n if (markDirty) {\n touch();\n }\n }\n\n function selectBlock(blockId: string | null): void {\n if (blockId && isBlockLocked(blockId)) {\n return;\n }\n state.selectedBlockId = blockId;\n }\n\n function setViewport(viewport: ViewportSize): void {\n state.viewport = viewport;\n }\n\n function setDarkMode(darkMode: boolean): void {\n state.darkMode = darkMode;\n }\n\n function setUiTheme(theme: UiTheme): void {\n state.uiTheme = theme;\n }\n\n function setPreviewMode(previewMode: boolean): void {\n state.previewMode = previewMode;\n if (previewMode) {\n state.selectedBlockId = null;\n }\n }\n\n function updateBlock(blockId: string, updates: Partial<Block>): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const block = findBlockById(state.content.blocks, blockId);\n if (block) {\n Object.assign(block, updates);\n touch();\n }\n }\n\n function updateSettings(updates: Partial<TemplateSettings>): void {\n state.content.settings = { ...state.content.settings, ...updates };\n touch();\n }\n\n function addBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex = 0,\n index?: number,\n ): void {\n const candidate = {\n settings: state.content.settings,\n blocks: [block],\n };\n assertNoSlotInContent(candidate);\n assertNoWrapperInContent(candidate);\n // Sections cannot be nested inside a column — MJML forbids `mj-section`\n // inside `mj-column`, so the renderer drops them on export (issue #292).\n // Reject the nest up front rather than lose the content silently later.\n if (targetSectionId && block.type === \"section\") {\n return;\n }\n if (targetSectionId) {\n if (isBlockLocked(targetSectionId)) {\n return;\n }\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (section && section.type === \"section\") {\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n const targetArray = section.children[columnIndex];\n if (index !== undefined && index < targetArray.length) {\n targetArray.splice(index, 0, block);\n } else {\n targetArray.push(block);\n }\n }\n } else {\n if (index !== undefined && index < state.content.blocks.length) {\n state.content.blocks.splice(index, 0, block);\n } else {\n state.content.blocks.push(block);\n }\n }\n touch();\n }\n\n function removeBlock(blockId: string): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const parent = findBlockParent(state.content.blocks, blockId);\n if (parent) {\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index !== -1) {\n const [removed] = parent.blocks.splice(index, 1);\n if (state.selectedBlockId) {\n const removedIds = new Set<string>();\n collectBlockIds(removed, removedIds);\n if (removedIds.has(state.selectedBlockId)) {\n state.selectedBlockId = null;\n }\n }\n touch();\n }\n }\n }\n\n function moveBlock(\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex = 0,\n ): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && isBlockLocked(targetSectionId)) {\n return;\n }\n\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return;\n\n const oldIndex = parent.blocks.findIndex((b) => b.id === blockId);\n if (oldIndex === -1) return;\n\n // Sections cannot be nested inside a column (issue #292) — refuse to move\n // a section into a section column; MJML would drop it on export.\n if (targetSectionId && parent.blocks[oldIndex].type === \"section\") {\n return;\n }\n\n // Resolve target before mutating the source — otherwise an invalid\n // targetSectionId leaves the block spliced-out and unrecoverable.\n let targetArray: Block[];\n if (targetSectionId) {\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (!section || section.type !== \"section\") return;\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n targetArray = section.children[columnIndex];\n } else {\n targetArray = state.content.blocks;\n }\n\n const [block] = parent.blocks.splice(oldIndex, 1);\n targetArray.splice(newIndex, 0, block);\n\n touch();\n }\n\n function markDirty(): void {\n touch();\n }\n\n // -------------------------------------------------------------------------\n // Template lifecycle (over an optional TemplatesProvider)\n // -------------------------------------------------------------------------\n\n /**\n * A refused call throws rather than resolving, because a resolved promise\n * would read as \"saved\" to whoever awaited it.\n *\n * The message names the provider key the consumer set, not an internal\n * capability flag: neither `EditorCapabilities` nor its injection key is\n * exported, so neither a core nor an editor consumer can read one. Note the\n * editor hides its own save controls when `save` is withheld but has no\n * create affordance to hide at all, so `create()` is reachable by definition.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(`[Templatical] Templates: ${action} ${reason}`);\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for something that landed.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n function requireProvider(action: string): TemplatesProvider {\n const { templates } = options;\n if (!templates) {\n refuse(\n action,\n \"needs a templates provider. Pass one as `init({ templates })` to enable saving and loading.\",\n );\n }\n return templates;\n }\n\n function setName(name: string): void {\n if (!state.template) return;\n state.template = { ...state.template, name };\n touch();\n }\n\n async function create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template> {\n const provider = requireProvider(\"create()\");\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\n \"create()\",\n \"is disabled by the provider — its `create` is `false`.\",\n );\n }\n\n let created: Template;\n state.isLoading = true;\n try {\n if (input?.content) {\n state.content = input.content;\n }\n // Omit `name` entirely when unset rather than sending `undefined` — a\n // provider serialising the input to JSON would otherwise receive a key it\n // never asked for.\n const revisionAtRequest = revision;\n created = await providerCreate(\n input?.name !== undefined\n ? { name: input.name, content: state.content }\n : { content: state.content },\n );\n state.template = created;\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n // Below the `finally` on purpose: `isLoading` is cleared there, so a handler\n // must not observe the editor still loading. Unreachable on failure — the\n // catch rethrows.\n notify(() => provider.onCreated?.(created));\n return created;\n }\n\n async function load(templateId: string): Promise<Template> {\n const provider = requireProvider(\"load()\");\n\n let loaded: Template;\n state.isLoading = true;\n try {\n loaded = await provider.load(templateId);\n assertNoSlotInContent(loaded.content);\n assertNoWrapperInContent(loaded.content);\n state.template = loaded;\n state.content = loaded.content;\n state.isDirty = false;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n // Below the `finally` on purpose: `isLoading` is cleared there, so a handler\n // must not observe the editor still loading. Unreachable on failure — the\n // catch rethrows.\n notify(() => provider.onLoaded?.(loaded));\n return loaded;\n }\n\n async function save(trigger: TemplateSaveTrigger = \"api\"): Promise<Template> {\n const provider = requireProvider(\"save()\");\n const { save: providerSave } = provider;\n if (typeof providerSave !== \"function\") {\n refuse(\"save()\", \"is disabled by the provider — its `save` is `false`.\");\n }\n const current = state.template;\n if (!current) {\n refuse(\n \"save()\",\n \"has no template loaded. Call create() or load() first.\",\n );\n }\n\n // The name rides the same patch as the content: a rename is an ordinary\n // unsaved change, so one round-trip persists both.\n const patch: TemplatePatch =\n current.name !== undefined\n ? { name: current.name, content: state.content }\n : { content: state.content };\n\n let saved: Template;\n state.isSaving = true;\n try {\n const revisionAtRequest = revision;\n saved = await providerSave(current.id, patch);\n // Adopt the response only while it still describes what is open. A\n // `load()` that landed mid-flight has already replaced the template, so\n // the response is stale.\n if (state.template?.id === current.id) {\n // The patch was built before the await, so a rename that landed during\n // it is absent from the response. Taking the response's name verbatim\n // reverts what the user typed — and because the next save reads the\n // name back off `state.template`, it would then persist the stale one,\n // losing the rename outright rather than merely on screen.\n const localName = state.template.name;\n state.template =\n localName !== current.name ? { ...saved, name: localName } : saved;\n }\n // Deliberately conditional. An edit landing while the request was in\n // flight is not persisted by it, and clearing the flag would both claim it\n // was and make autosave — which checks dirtiness at debounce time — skip\n // the follow-up save.\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isSaving = false;\n }\n // Below the `finally` on purpose: `isSaving` is cleared there, and a handler\n // that navigates must observe a settled editor or the consumer's own dirty\n // guard blocks their navigation. Unreachable on failure — the catch rethrows.\n notify(() => provider.onSaved?.(saved, { trigger }));\n return saved;\n }\n\n function hasTemplate(): boolean {\n return state.template?.id !== undefined;\n }\n\n return {\n state: readonly(state),\n content,\n selectedBlock,\n isBlockLocked,\n setContent,\n selectBlock,\n setViewport,\n setDarkMode,\n setUiTheme,\n setPreviewMode,\n updateBlock,\n updateSettings,\n addBlock,\n removeBlock,\n moveBlock,\n markDirty,\n findBlockLocation,\n setName,\n create,\n load,\n save,\n hasTemplate,\n };\n}\n","import { safeClone, type TemplateContent } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"@vue/reactivity\";\n\nexport interface UseHistoryOptions {\n content: Ref<TemplateContent>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n isRemoteOperation?: () => boolean;\n maxSize?: number;\n}\n\nexport interface UseHistoryReturn {\n canUndo: ComputedRef<boolean>;\n canRedo: ComputedRef<boolean>;\n isNavigating: Ref<boolean>;\n undo: () => void;\n redo: () => void;\n record: () => void;\n recordDebounced: (blockId: string) => void;\n clear: () => void;\n destroy: () => void;\n}\n\ninterface DebouncedSnapshot {\n blockId: string;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nconst MAX_STACK_SIZE = 50;\nconst DEBOUNCE_MS = 300;\nconst NAVIGATE_IDLE_MS = 1500;\n\nexport function useHistory(options: UseHistoryOptions): UseHistoryReturn {\n const {\n content,\n setContent,\n isRemoteOperation,\n maxSize = MAX_STACK_SIZE,\n } = options;\n\n const undoStack = ref<TemplateContent[]>([]);\n const redoStack = ref<TemplateContent[]>([]);\n const isNavigating = ref(false);\n let navigatingTimeoutId: ReturnType<typeof setTimeout> | null = null;\n let pendingDebounce: DebouncedSnapshot | null = null;\n\n const canUndo = computed(() => undoStack.value.length > 0);\n const canRedo = computed(() => redoStack.value.length > 0);\n\n function cloneContent(): TemplateContent {\n // Cycle-safe deep clone (see `safeClone`). A naked JSON.stringify throws\n // `Converting circular structure to JSON` if a DOM element with a Sortable\n // expando back-ref ever sneaks into block data via a drag handler — which\n // would freeze the undo stack, since every subsequent mutation calls\n // `record()`. safeClone drops the back-ref instead of throwing.\n return safeClone(content.value);\n }\n\n function pushToUndoStack(snapshot: TemplateContent): void {\n undoStack.value.push(snapshot);\n if (undoStack.value.length > maxSize) {\n undoStack.value.splice(0, undoStack.value.length - maxSize);\n }\n }\n\n function flushPendingDebounce(): void {\n if (pendingDebounce) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce = null;\n }\n }\n\n function record(): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n flushPendingDebounce();\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n }\n\n function recordDebounced(blockId: string): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n if (pendingDebounce && pendingDebounce.blockId === blockId) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce.timeoutId = setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS);\n return;\n }\n\n flushPendingDebounce();\n\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n\n pendingDebounce = {\n blockId,\n timeoutId: setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS),\n };\n }\n\n function setNavigating(): void {\n isNavigating.value = true;\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n }\n navigatingTimeoutId = setTimeout(() => {\n isNavigating.value = false;\n navigatingTimeoutId = null;\n }, NAVIGATE_IDLE_MS);\n }\n\n function undo(): void {\n if (undoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = undoStack.value.pop()!;\n redoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function redo(): void {\n if (redoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = redoStack.value.pop()!;\n undoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function clear(): void {\n undoStack.value = [];\n redoStack.value = [];\n flushPendingDebounce();\n }\n\n function destroy(): void {\n clear();\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n navigatingTimeoutId = null;\n }\n }\n\n return {\n canUndo,\n canRedo,\n isNavigating,\n undo,\n redo,\n record,\n recordDebounced,\n clear,\n destroy,\n };\n}\n","import type { Block, BlockDefaults, BlockType } from \"@templatical/types\";\nimport { cloneBlock, createBlock } from \"@templatical/types\";\n\nexport interface UseBlockActionsOptions {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n selectBlock: (blockId: string | null) => void;\n /** Locate a block in the tree — used by `duplicateBlock` to insert the\n * clone right after the source instead of appending to the end. */\n findBlockLocation?: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n /**\n * Defaults merged onto every block `createAndAddBlock` creates.\n *\n * A **getter** is re-read on each insert; a plain object is captured once.\n * The editor passes a getter because half of these defaults track the\n * template's own `settings.locale`, which the author can change mid-session\n * — a snapshot would pin every later insert to the value at mount.\n */\n blockDefaults?: BlockDefaults | (() => BlockDefaults);\n}\n\nexport interface UseBlockActionsReturn {\n createAndAddBlock: (\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n duplicateBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n deleteBlock: (blockId: string) => void;\n updateBlockProperty: <K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ) => void;\n}\n\nexport function useBlockActions(\n options: UseBlockActionsOptions,\n): UseBlockActionsReturn {\n const { addBlock, removeBlock, updateBlock, selectBlock, findBlockLocation } =\n options;\n\n function createAndAddBlock(\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const defaults =\n typeof options.blockDefaults === \"function\"\n ? options.blockDefaults()\n : options.blockDefaults;\n const block = createBlock(type, defaults);\n addBlock(block, targetSectionId, columnIndex);\n selectBlock(block.id);\n return block;\n }\n\n function duplicateBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const cloned = cloneBlock(block);\n\n // Insert directly after the source block. Explicit target args win;\n // otherwise, resolve the source's location and bump index by 1. Falls\n // back to appending at the end if location is unknown.\n if (targetSectionId !== undefined || columnIndex !== undefined) {\n addBlock(cloned, targetSectionId, columnIndex);\n } else {\n const sourceLocation = findBlockLocation?.(block.id) ?? null;\n if (sourceLocation) {\n addBlock(\n cloned,\n sourceLocation.targetSectionId,\n sourceLocation.columnIndex,\n sourceLocation.index + 1,\n );\n } else {\n addBlock(cloned, targetSectionId, columnIndex);\n }\n }\n selectBlock(cloned.id);\n return cloned;\n }\n\n function deleteBlock(blockId: string): void {\n removeBlock(blockId);\n }\n\n function updateBlockProperty<K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ): void {\n updateBlock(blockId, { [key]: value } as Partial<Block>);\n }\n\n return {\n createAndAddBlock,\n duplicateBlock,\n deleteBlock,\n updateBlockProperty,\n };\n}\n","import type { TemplateContent } from \"@templatical/types\";\nimport { watch, type Ref } from \"@vue/reactivity\";\n\nexport interface UseAutoSaveOptions {\n content: Ref<TemplateContent>;\n isDirty: () => boolean;\n onChange: (content: TemplateContent) => void;\n debounce?: number;\n enabled?: boolean | (() => boolean);\n}\n\nexport interface UseAutoSaveReturn {\n flush: () => void;\n cancel: () => void;\n pause: () => void;\n resume: () => void;\n destroy: () => void;\n}\n\n/**\n * Trailing debounce, in ms, measured from the *last* content mutation.\n *\n * Typing is not debounced upstream — TipTap's `onUpdate` calls `updateBlock` per\n * keystroke — so this is the only thing between a keypress and a whole-document\n * write. 1000 was too eager: ordinary prose pauses for a second constantly\n * (word choice, re-reading, reaching for the mouse), so a single paragraph could\n * produce dozens of full-content saves. 2000 roughly halves that while still\n * landing well before a user wonders whether their work was kept.\n *\n * **The single default for both entry points.** Cloud imports this constant\n * rather than declaring its own — a second copy for one setting drifts silently,\n * since nothing links the two.\n */\nexport const DEFAULT_AUTO_SAVE_DEBOUNCE_MS = 2000;\n\nexport function useAutoSave(options: UseAutoSaveOptions): UseAutoSaveReturn {\n const {\n content,\n isDirty,\n onChange,\n debounce = DEFAULT_AUTO_SAVE_DEBOUNCE_MS,\n enabled = true,\n } = options;\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let paused = false;\n\n function isEnabled(): boolean {\n return typeof enabled === \"function\" ? enabled() : enabled;\n }\n\n function pause(): void {\n paused = true;\n cancel();\n }\n\n function resume(): void {\n paused = false;\n }\n\n function cancel(): void {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n }\n\n function flush(): void {\n cancel();\n if (isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }\n\n function scheduleOnChange(): void {\n if (!isEnabled() || paused) return;\n\n cancel();\n timeoutId = setTimeout(() => {\n timeoutId = null;\n if (isEnabled() && !paused && isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }, debounce);\n }\n\n // `watch` from `@vue/reactivity` has no scheduler, so this callback runs\n // *synchronously inside the mutation* — before the editor's trailing\n // `state.isDirty = true`, and `isDirty` sits outside the watched `content`\n // subtree so setting it never re-triggers. An `isDirty()` guard here would\n // therefore drop the first edit after every dirty-flag reset (issue #522).\n // Dirtiness is decided at debounce time instead, where the flag is settled;\n // `scheduleOnChange` still checks `enabled`/`paused` up front.\n const stopWatch = watch(\n content,\n () => {\n scheduleOnChange();\n },\n { deep: true },\n );\n\n function destroy(): void {\n stopWatch();\n cancel();\n }\n\n return {\n flush,\n cancel,\n pause,\n resume,\n destroy,\n };\n}\n","import { computed, reactive, type ComputedRef } from \"@vue/reactivity\";\n\nexport interface UseConditionPreviewReturn {\n isHidden: (blockId: string) => boolean;\n toggleBlock: (blockId: string) => void;\n reset: () => void;\n hasHiddenBlocks: ComputedRef<boolean>;\n}\n\n/**\n * The slice of an editor this needs — deliberately structural, so both the OSS\n * and the Cloud `useEditor` satisfy it without either having to grow toward the\n * other.\n */\nexport interface ConditionPreviewEditor {\n state: { readonly selectedBlockId: string | null };\n selectBlock: (blockId: string | null) => void;\n}\n\nexport function useConditionPreview(\n editor: ConditionPreviewEditor,\n): UseConditionPreviewReturn {\n const hiddenBlockIds = reactive(new Set<string>());\n\n const hasHiddenBlocks = computed(() => hiddenBlockIds.size > 0);\n\n function isHidden(blockId: string): boolean {\n return hiddenBlockIds.has(blockId);\n }\n\n function toggleBlock(blockId: string): void {\n if (hiddenBlockIds.has(blockId)) {\n hiddenBlockIds.delete(blockId);\n } else {\n hiddenBlockIds.add(blockId);\n\n if (editor.state.selectedBlockId === blockId) {\n editor.selectBlock(null);\n }\n }\n }\n\n function reset(): void {\n hiddenBlockIds.clear();\n }\n\n return {\n isHidden,\n toggleBlock,\n reset,\n hasHiddenBlocks,\n };\n}\n","import type { CustomBlock, CustomBlockDefinition } from \"@templatical/types\";\nimport type { ComputedRef, Ref } from \"@vue/reactivity\";\nimport { computed, ref } from \"@vue/reactivity\";\n\nexport function useDataSourceFetch(options: {\n definition: ComputedRef<CustomBlockDefinition | undefined>;\n block: ComputedRef<CustomBlock>;\n onUpdate: (fieldValues: Record<string, unknown>, fetched: boolean) => void;\n}): {\n isFetching: Ref<boolean>;\n fetchError: Ref<boolean>;\n fetch: () => Promise<void>;\n hasDataSource: ComputedRef<boolean>;\n needsFetch: ComputedRef<boolean>;\n} {\n const isFetching = ref(false);\n const fetchError = ref(false);\n\n const hasDataSource = computed(() => !!options.definition.value?.dataSource);\n\n const needsFetch = computed(\n () => hasDataSource.value && !options.block.value.dataSourceFetched,\n );\n\n async function fetch(): Promise<void> {\n const def = options.definition.value;\n if (!def?.dataSource) {\n return;\n }\n\n isFetching.value = true;\n fetchError.value = false;\n\n try {\n const result = await def.dataSource.onFetch({\n fieldValues: { ...options.block.value.fieldValues },\n blockId: options.block.value.id,\n });\n\n if (result == null) {\n return;\n }\n\n const merged = { ...options.block.value.fieldValues };\n for (const key of Object.keys(merged)) {\n if (key in result) {\n merged[key] = result[key];\n }\n }\n\n options.onUpdate(merged, true);\n } catch (error) {\n console.warn(\"[Templatical] Data source fetch error:\", error);\n fetchError.value = true;\n } finally {\n isFetching.value = false;\n }\n }\n\n return {\n isFetching,\n fetchError,\n fetch,\n hasDataSource,\n needsFetch,\n };\n}\n","import type { Block, TemplateSettings } from \"@templatical/types\";\nimport type { UseHistoryReturn } from \"./history\";\n\n/**\n * The mutable slice of an editor this wraps — structural, so the OSS and Cloud\n * `useEditor` returns both satisfy it without either having to grow toward the\n * other. Not `Readonly`: the whole point is to replace these members in place.\n */\nexport interface HistoryInterceptorEditor {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n isBlockLocked: (blockId: string) => boolean;\n}\n\n/**\n * Wraps editor mutation methods to record history snapshots before each\n * operation. Mutates the editor object in place.\n *\n * Must be applied **after** any collaboration broadcast wrapping so the\n * call chain is: history.record() → broadcast → original mutation.\n */\nexport function useHistoryInterceptor(\n editor: HistoryInterceptorEditor,\n history: UseHistoryReturn,\n): void {\n const originalAddBlock = editor.addBlock;\n const originalRemoveBlock = editor.removeBlock;\n const originalMoveBlock = editor.moveBlock;\n const originalUpdateBlock = editor.updateBlock;\n const originalUpdateSettings = editor.updateSettings;\n\n // Skip recording when the underlying op is a no-op (e.g., a peer-locked\n // block or section), otherwise the undo stack fills with snapshots that\n // are identical to current state and undo silently does nothing.\n editor.addBlock = (block, targetSectionId?, columnIndex?, index?) => {\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalAddBlock(block, targetSectionId, columnIndex, index);\n };\n\n editor.removeBlock = (blockId) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.record();\n originalRemoveBlock(blockId);\n };\n\n editor.moveBlock = (blockId, newIndex, targetSectionId?, columnIndex?) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalMoveBlock(blockId, newIndex, targetSectionId, columnIndex);\n };\n\n editor.updateBlock = (blockId, updates) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.recordDebounced(blockId);\n originalUpdateBlock(blockId, updates);\n };\n\n editor.updateSettings = (updates) => {\n history.record();\n originalUpdateSettings(updates);\n };\n}\n","import type {\n Block,\n SavedBlock,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { notifyHandler } from \"./error-reporting\";\n\nexport interface UseSavedBlocksOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ savedBlocks })`, or\n * by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: SavedBlocksProvider;\n onError?: (error: Error) => void;\n}\n\nexport interface UseSavedBlocksReturn {\n /** In-memory mirror of the provider's list, kept in sync after each call. */\n savedBlocks: Ref<SavedBlock[]>;\n isLoading: Ref<boolean>;\n /**\n * Distinct categories across the loaded entries, alphabetically sorted.\n *\n * Derived rather than stored: a category exists exactly as long as an entry\n * carries it. Sorting here is not a violation of \"the editor never re-sorts\"\n * — that rule protects the provider's ordering of *entries*, whereas these\n * are strings with no given order.\n */\n categories: ComputedRef<string[]>;\n /**\n * Whether the provider supplied each mutation at all — `false` on the\n * provider means the capability does not exist for this user, and the UI\n * hides the corresponding affordance entirely.\n *\n * Constant for the provider's lifetime, but exposed as computed refs so\n * consumers can bind them the same way as everything else here.\n */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n /**\n * Whether a *particular* entry may be edited / deleted: the capability must\n * exist AND the entry must not opt out via `canUpdate` / `canDelete`.\n *\n * Use these rather than reading the flags directly, so every surface asks the\n * question the same way and the \"absent means allowed\" default lives in one\n * place.\n */\n canUpdateBlock: (block: SavedBlock) => boolean;\n canDeleteBlock: (block: SavedBlock) => boolean;\n /**\n * Re-read from the provider. The editor always calls this bare and filters\n * in memory; `params` exists for headless callers that want the provider to\n * filter instead (see {@link SavedBlocksListParams}).\n */\n load: (params?: SavedBlocksListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n name: string,\n content: Block[],\n category?: string,\n ) => Promise<SavedBlock>;\n /** Rejects when `update` is disabled or the entry opts out of editing. */\n update: (id: string, patch: SavedBlockPatch) => Promise<SavedBlock>;\n /** Rejects when `delete` is disabled or the entry opts out of deletion. */\n remove: (id: string) => Promise<void>;\n}\n\n/**\n * Reactive state over a {@link SavedBlocksProvider}.\n *\n * Owns the list, the loading flag, and the local mutations that keep the list\n * consistent after each successful call, so a provider only has to implement\n * four promise-returning methods. Errors are reported through `onError` and\n * re-thrown, leaving the local list untouched on failure.\n */\nexport function useSavedBlocks(\n options: UseSavedBlocksOptions,\n): UseSavedBlocksReturn {\n const { provider } = options;\n\n const savedBlocks = ref<SavedBlock[]>([]);\n const isLoading = ref(false);\n\n const categories = computed(() => {\n const seen = new Set<string>();\n for (const block of savedBlocks.value) {\n const category = block.category?.trim();\n if (category) seen.add(category);\n }\n return [...seen].sort((a, b) => a.localeCompare(b));\n });\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n\n /** Absent flag means allowed — the flags exist only to forbid. */\n function canUpdateBlock(block: SavedBlock): boolean {\n return canUpdate.value && block.canUpdate !== false;\n }\n\n function canDeleteBlock(block: SavedBlock): boolean {\n return canDelete.value && block.canDelete !== false;\n }\n\n /**\n * The UI hides disabled actions, so reaching one of these means a programmatic\n * caller went around it. Fail loudly rather than silently no-op: a resolved\n * promise would read as \"saved\" to whoever awaited it.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(\n `[Templatical] Saved blocks: ${action} is ${reason}. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a saved block that was created.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n async function load(params?: SavedBlocksListParams): Promise<void> {\n isLoading.value = true;\n try {\n savedBlocks.value = await provider.list(params);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(\n name: string,\n content: Block[],\n category?: string,\n ): Promise<SavedBlock> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\"create\", \"disabled by the provider\");\n }\n try {\n // Omit the key entirely when unset, rather than sending `undefined` —\n // a provider serialising the input to JSON would otherwise be handed an\n // explicit null-ish field it never asked for.\n const created = await providerCreate(\n category ? { name, content, category } : { name, content },\n );\n savedBlocks.value = [created, ...savedBlocks.value];\n notify(() => provider.onCreated?.(created));\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function update(\n id: string,\n patch: SavedBlockPatch,\n ): Promise<SavedBlock> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") {\n refuse(\"update\", \"disabled by the provider\");\n }\n // An id absent from the local list isn't refused — a headless caller may\n // legitimately patch something it never loaded. Only a loaded entry that\n // explicitly opted out is blocked.\n const local = savedBlocks.value.find((b) => b.id === id);\n if (local && local.canUpdate === false) {\n refuse(\"update\", `not permitted for entry \"${id}\"`);\n }\n try {\n const updated = await providerUpdate(id, patch);\n savedBlocks.value = savedBlocks.value.map((b) =>\n b.id === id ? updated : b,\n );\n notify(() => provider.onUpdated?.(updated));\n return updated;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function remove(id: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") {\n refuse(\"delete\", \"disabled by the provider\");\n }\n // Captured before the delete resolves: `onDeleted` carries the removed\n // entry itself, and there is nothing left to read once the list is\n // filtered.\n const removed = savedBlocks.value.find((b) => b.id === id) ?? null;\n if (removed && removed.canDelete === false) {\n refuse(\"delete\", `not permitted for entry \"${id}\"`);\n }\n try {\n await providerDelete(id);\n savedBlocks.value = savedBlocks.value.filter((b) => b.id !== id);\n if (removed) {\n notify(() => provider.onDeleted?.(removed));\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n return {\n savedBlocks,\n isLoading,\n categories,\n canCreate,\n canUpdate,\n canDelete,\n canUpdateBlock,\n canDeleteBlock,\n load,\n create,\n update,\n remove,\n };\n}\n","import type {\n SavedBlock,\n SavedBlockInput,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { generateId } from \"@templatical/types\";\n\nexport interface LocalStorageSavedBlocksOptions {\n /**\n * `localStorage` key holding the serialized array.\n *\n * @default \"templatical:saved-blocks\"\n */\n key?: string;\n}\n\nconst DEFAULT_KEY = \"templatical:saved-blocks\";\n\n/**\n * Browser-local {@link SavedBlocksProvider} backed by `localStorage`.\n *\n * Opt-in: pass it explicitly as `init({ savedBlocks: createLocalStorageSavedBlocksProvider() })`.\n * The editor never falls back to it, so consumers without a provider keep the\n * feature — and its UI — entirely off.\n *\n * Intended for demos, prototypes, and single-device use. Entries live in one\n * browser profile only: they don't sync across devices or users, and clearing\n * site data removes them. Back saved blocks with your own API for anything\n * that needs to outlive a browser profile.\n */\nexport function createLocalStorageSavedBlocksProvider(\n options: LocalStorageSavedBlocksOptions = {},\n): SavedBlocksProvider {\n const storageKey = options.key ?? DEFAULT_KEY;\n\n function getStorage(): Storage {\n // Core targets a neutral platform, so `localStorage` isn't guaranteed —\n // fail with an actionable message rather than a bare ReferenceError.\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"[Templatical] createLocalStorageSavedBlocksProvider requires a browser environment with localStorage. Supply your own SavedBlocksProvider for server-side or non-browser use.\",\n );\n }\n return localStorage;\n }\n\n function readAll(): SavedBlock[] {\n const raw = getStorage().getItem(storageKey);\n if (!raw) return [];\n try {\n const parsed: unknown = JSON.parse(raw);\n // Tolerate a corrupted or hand-edited value rather than breaking the\n // editor: treat anything that isn't an array as \"no saved blocks\".\n return Array.isArray(parsed) ? (parsed as SavedBlock[]) : [];\n } catch {\n return [];\n }\n }\n\n function writeAll(blocks: SavedBlock[]): void {\n getStorage().setItem(storageKey, JSON.stringify(blocks));\n }\n\n // Every method is `async` so a synchronous failure (a missing\n // `localStorage`, a quota error from `setItem`) surfaces as a rejected\n // promise rather than a sync throw — callers of a `Promise`-returning\n // contract must be able to rely on `.catch()`.\n return {\n // The editor calls this bare and filters in memory; the params are honored\n // for headless callers that would rather the provider did the work.\n async list(params?: SavedBlocksListParams): Promise<SavedBlock[]> {\n const all = readAll();\n const search = params?.search?.trim().toLowerCase();\n const category = params?.category?.trim();\n return all.filter((b) => {\n if (search && !b.name.toLowerCase().includes(search)) return false;\n if (category && b.category !== category) return false;\n return true;\n });\n },\n\n // All three mutations are enabled: a browser-local store has no notion of\n // permissions, so there is nothing to forbid.\n async create(input: SavedBlockInput): Promise<SavedBlock> {\n const now = new Date().toISOString();\n const created: SavedBlock = {\n id: generateId(),\n name: input.name,\n content: input.content,\n ...(input.category ? { category: input.category } : {}),\n createdAt: now,\n updatedAt: now,\n };\n // Newest-first, matching the order the composable applies locally after\n // a create — so a reload preserves what the user just saw.\n writeAll([created, ...readAll()]);\n return created;\n },\n\n async update(id: string, patch: SavedBlockPatch): Promise<SavedBlock> {\n const all = readAll();\n const index = all.findIndex((b) => b.id === id);\n // Mirrors a REST 404 so provider behavior is consistent across adapters.\n if (index === -1) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n const updated: SavedBlock = {\n ...all[index],\n ...patch,\n updatedAt: new Date().toISOString(),\n };\n const next = [...all];\n next[index] = updated;\n writeAll(next);\n return updated;\n },\n\n async delete(id: string): Promise<void> {\n const all = readAll();\n if (!all.some((b) => b.id === id)) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n writeAll(all.filter((b) => b.id !== id));\n },\n };\n}\n","import type {\n MediaAsset,\n MediaAssetPatch,\n MediaCreateInput,\n MediaListPage,\n MediaListParams,\n MediaProvider,\n} from \"@templatical/types\";\nimport { generateId } from \"@templatical/types\";\n\nexport interface LocalStorageMediaProviderOptions {\n /**\n * `localStorage` key holding the serialized array.\n *\n * @default \"templatical:media\"\n */\n key?: string;\n}\n\nconst DEFAULT_KEY = \"templatical:media\";\nconst PAGE_SIZE = 50;\n\n/**\n * Browser-local {@link MediaProvider} backed by `localStorage`.\n *\n * Opt-in: pass it explicitly as `init({ media: createLocalStorageMediaProvider() })`.\n * The editor never falls back to it, so consumers without a provider keep\n * image fields URL-only.\n *\n * `create` stores the file as a data URL. That is a demo-sized persistence\n * model — `localStorage` quotas are typically ~5 MB, and a few large\n * images will fill it. Back a real gallery with your own API.\n *\n * Folders, replace, import, usage, frequently-used and quota are `false`:\n * this adapter is a flat list of assets.\n */\nexport function createLocalStorageMediaProvider(\n options: LocalStorageMediaProviderOptions = {},\n): MediaProvider {\n const storageKey = options.key ?? DEFAULT_KEY;\n\n function getStorage(): Storage {\n // Core targets a neutral platform, so `localStorage` isn't guaranteed —\n // fail with an actionable message rather than a bare ReferenceError.\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"[Templatical] createLocalStorageMediaProvider requires a browser environment with localStorage. Supply your own MediaProvider for server-side or non-browser use.\",\n );\n }\n return localStorage;\n }\n\n function readAll(): MediaAsset[] {\n const raw = getStorage().getItem(storageKey);\n if (!raw) return [];\n try {\n const parsed: unknown = JSON.parse(raw);\n // Tolerate a corrupted or hand-edited value rather than breaking the\n // editor: treat anything that isn't an array as \"no assets\".\n return Array.isArray(parsed) ? (parsed as MediaAsset[]) : [];\n } catch {\n return [];\n }\n }\n\n function writeAll(assets: MediaAsset[]): void {\n getStorage().setItem(storageKey, JSON.stringify(assets));\n }\n\n function readFileAsDataURL(file: File): Promise<string> {\n if (typeof FileReader === \"undefined\") {\n return Promise.reject(\n new Error(\n \"[Templatical] createLocalStorageMediaProvider requires a browser environment with FileReader.\",\n ),\n );\n }\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n if (typeof reader.result !== \"string\") {\n reject(new Error(\"[Templatical] Failed to read file as a data URL.\"));\n return;\n }\n resolve(reader.result);\n };\n reader.onerror = () => {\n reject(\n reader.error ??\n new Error(\"[Templatical] Failed to read file as a data URL.\"),\n );\n };\n reader.readAsDataURL(file);\n });\n }\n\n // Every method is `async` so a synchronous failure (a missing\n // `localStorage`, a quota error from `setItem`) surfaces as a rejected\n // promise rather than a sync throw — callers of a `Promise`-returning\n // contract must be able to rely on `.catch()`.\n return {\n async list(params?: MediaListParams): Promise<MediaListPage> {\n const all = readAll();\n const search = params?.search?.trim().toLowerCase();\n const filtered = search\n ? all.filter((asset) => {\n const filename = asset.filename?.toLowerCase() ?? \"\";\n const alt = asset.alt?.toLowerCase() ?? \"\";\n return filename.includes(search) || alt.includes(search);\n })\n : all;\n const parsed = params?.cursor ? Number.parseInt(params.cursor, 10) : 0;\n const offset = Number.isFinite(parsed) && parsed > 0 ? parsed : 0;\n const items = filtered.slice(offset, offset + PAGE_SIZE);\n const page: MediaListPage = { items };\n const nextOffset = offset + items.length;\n if (nextOffset < filtered.length) {\n page.nextCursor = String(nextOffset);\n }\n return page;\n },\n\n async create(input: MediaCreateInput): Promise<MediaAsset> {\n const url = await readFileAsDataURL(input.file);\n const now = new Date().toISOString();\n const created: MediaAsset = {\n id: generateId(),\n url,\n filename: input.filename || input.file.name,\n createdAt: now,\n updatedAt: now,\n size: input.file.size,\n };\n if (input.alt !== undefined) created.alt = input.alt;\n if (input.file.type) created.mimeType = input.file.type;\n if (input.folderId !== undefined) created.folderId = input.folderId;\n // Newest-first, matching the order the composable applies locally after\n // a create — so a reload preserves what the user just saw.\n writeAll([created, ...readAll()]);\n return created;\n },\n\n async update(id: string, patch: MediaAssetPatch): Promise<MediaAsset> {\n const all = readAll();\n const index = all.findIndex((asset) => asset.id === id);\n // Mirrors a REST 404 so provider behavior is consistent across adapters.\n if (index === -1) {\n throw new Error(`[Templatical] Media asset not found: ${id}`);\n }\n const current = all[index];\n const updated: MediaAsset = {\n ...current,\n ...patch,\n id: current.id,\n url: current.url,\n updatedAt: new Date().toISOString(),\n };\n const next = [...all];\n next[index] = updated;\n writeAll(next);\n return updated;\n },\n\n async delete(ids: string[]): Promise<void> {\n const all = readAll();\n for (const id of ids) {\n if (!all.some((asset) => asset.id === id)) {\n throw new Error(`[Templatical] Media asset not found: ${id}`);\n }\n }\n const remove = new Set(ids);\n writeAll(all.filter((asset) => !remove.has(asset.id)));\n },\n\n folders: false,\n replace: false,\n importFromUrl: false,\n checkUsage: false,\n frequentlyUsed: false,\n storage: false,\n };\n}\n","import type {\n Template,\n TemplateContent,\n TemplateVersion,\n VersionHistoryListParams,\n VersionHistoryProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { notifyHandler } from \"./error-reporting\";\n\nexport interface UseVersionHistoryOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ versionHistory })`,\n * or by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: VersionHistoryProvider;\n /**\n * Which template's history this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n onError?: (error: Error) => void;\n}\n\nexport interface UseVersionHistoryReturn {\n /** The provider's list, in the provider's order. Never re-sorted. */\n versions: Ref<TemplateVersion[]>;\n isLoading: Ref<boolean>;\n isRestoring: Ref<boolean>;\n /**\n * Cursor for the page after the one currently held, or `undefined` when the\n * provider signalled there is no more. The editor loads one page and ignores\n * this; it is here so a headless caller can page without reaching past the\n * composable.\n */\n nextCursor: Ref<string | undefined>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canRestore: ComputedRef<boolean>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: VersionHistoryListParams) => Promise<void>;\n /**\n * The version's content **if it is already in hand** — the provider's\n * `content` hint, or a previous `get` this composable cached. `null` means a\n * round-trip is required.\n *\n * Callers that must not block (scrubbing through history swaps the canvas in\n * the same tick) check this first and only await {@link resolveContent} when\n * it comes back null.\n */\n peekContent: (version: TemplateVersion) => TemplateContent | null;\n /**\n * `version.content ?? await provider.get(...)`, cached per version id, so a\n * lazily-loaded version costs one round-trip on its first visit and nothing\n * afterwards.\n */\n resolveContent: (version: TemplateVersion) => Promise<TemplateContent>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n content: TemplateContent,\n meta?: { label?: string },\n ) => Promise<TemplateVersion>;\n /** Rejects with an {@link SdkError} when the provider disabled `restore`. */\n restore: (versionId: string) => Promise<Template>;\n}\n\n/**\n * Reactive state over a {@link VersionHistoryProvider}.\n *\n * Owns the list, the loading flags and the per-version content cache that keeps\n * scrubbing synchronous. Errors are reported through `onError` and re-thrown,\n * leaving the list untouched on failure.\n *\n * It deliberately does **not** create versions of its own accord. The editor\n * never records a version on a save — whoever implements `TemplatesProvider.save`\n * decides that, because they are the side that pays for the storage.\n */\nexport function useVersionHistory(\n options: UseVersionHistoryOptions,\n): UseVersionHistoryReturn {\n const { provider, getTemplateId } = options;\n\n const versions = ref<TemplateVersion[]>([]);\n const isLoading = ref(false);\n const nextCursor = ref<string | undefined>(undefined);\n const isRestoring = ref(false);\n\n /**\n * Content fetched through `get`, keyed by version id. A version that carried\n * a `content` hint never lands here — the hint is read straight off the entry,\n * so a provider that eager-loads pays no second copy.\n */\n const fetched = new Map<string, TemplateContent>();\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canRestore = computed(() => typeof provider.restore === \"function\");\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op: a resolved promise reads as \"done\".\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Version history: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Version history: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a version that was recorded or restored.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n async function load(params?: VersionHistoryListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n const page = await provider.list(templateId, params);\n versions.value = page.versions;\n nextCursor.value = page.nextCursor;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n function peekContent(version: TemplateVersion): TemplateContent | null {\n return version.content ?? fetched.get(version.id) ?? null;\n }\n\n async function resolveContent(\n version: TemplateVersion,\n ): Promise<TemplateContent> {\n const known = peekContent(version);\n if (known) return known;\n\n const templateId = requireTemplateId(\"get\");\n try {\n const content = await provider.get(templateId, version.id);\n fetched.set(version.id, content);\n return content;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function create(\n content: TemplateContent,\n meta?: { label?: string },\n ): Promise<TemplateVersion> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n try {\n const created = await providerCreate(templateId, content, meta);\n versions.value = [created, ...versions.value];\n notify(() => provider.onCreated?.(created));\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function restore(versionId: string): Promise<Template> {\n const { restore: providerRestore } = provider;\n if (typeof providerRestore !== \"function\") refuse(\"restore\");\n const templateId = requireTemplateId(\"restore\");\n\n let restored: Template;\n isRestoring.value = true;\n try {\n restored = await providerRestore(templateId, versionId);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isRestoring.value = false;\n }\n // Below the `finally` on purpose: `isRestoring` is cleared there, so a\n // handler must not observe the composable still reporting itself\n // mid-restore. Unreachable on failure — the catch rethrows.\n notify(() => provider.onRestored?.(restored));\n return restored;\n }\n\n return {\n nextCursor,\n versions,\n isLoading,\n isRestoring,\n canCreate,\n canRestore,\n load,\n peekContent,\n resolveContent,\n create,\n restore,\n };\n}\n","import type {\n Comment,\n CommentAuthor,\n CommentChange,\n CommentInput,\n CommentPatch,\n CommentsListParams,\n CommentsProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport {\n computed,\n onScopeDispose,\n ref,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport { notifyHandler, wrapReportedError } from \"./error-reporting\";\n\nexport interface UseCommentsOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ comments })`, or by\n * Cloud's own adapter — this composable is transport-agnostic and never talks\n * to a network itself.\n */\n provider: CommentsProvider;\n /**\n * Which template's conversation this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n /**\n * Who is commenting, read at call time. `null` means the editor has no\n * identity, and every mutation refuses — an unattributable comment is worse\n * than no comment feature.\n */\n getUser: () => CommentAuthor | null;\n onError?: (error: Error) => void;\n}\n\nexport interface UseCommentsReturn {\n /** Thread roots in the provider's order. Never re-sorted. */\n comments: Ref<Comment[]>;\n isLoading: Ref<boolean>;\n isSubmitting: Ref<boolean>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n canResolve: ComputedRef<boolean>;\n /** Roots plus replies. */\n totalCount: ComputedRef<number>;\n /** Unresolved roots — the badge on the trigger. */\n unresolvedCount: ComputedRef<number>;\n /** Comments per anchored block id, roots plus their replies. */\n commentCountByBlock: ComputedRef<Map<string, number>>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: CommentsListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when `create` is disabled or there is no user. */\n create: (input: CommentInput) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `update` is disabled or there is no user. */\n update: (commentId: string, patch: CommentPatch) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `delete` is disabled or there is no user. */\n remove: (commentId: string) => Promise<void>;\n /** Rejects with an {@link SdkError} when `setResolved` is disabled or there is no user. */\n setResolved: (commentId: string, resolved: boolean) => Promise<Comment>;\n /** Look one up by id, root or reply. `null` when it isn't loaded. */\n find: (commentId: string) => Comment | null;\n /** Whether this comment was written by the current user. */\n isOwn: (comment: Comment) => boolean;\n /**\n * Apply a change that arrived from {@link CommentsProvider.subscribe}. Public\n * so a consumer driving this headlessly can push their own transport into it.\n */\n applyRemoteCreate: (comment: Comment) => void;\n applyRemoteUpdate: (comment: Comment) => void;\n applyRemoteDelete: (commentId: string, parentId?: string | null) => void;\n}\n\n/**\n * Reactive state over a {@link CommentsProvider}.\n *\n * Owns the thread list, the loading flags, the local mutations that keep the list\n * consistent, and the derived counts the chrome renders. Errors are reported\n * through `onError` and **re-thrown**, leaving the list untouched on failure —\n * the same discipline as `useSavedBlocks` and `useVersionHistory`.\n *\n * Mutations **reject** when the provider withheld them rather than resolving to\n * `null`: a resolved promise reads as \"saved\" to whoever awaited it. Ask through\n * `canCreate` / `canUpdate` / `canDelete` / `canResolve` first — which is what the\n * editor's own UI does, hiding each action rather than disabling it.\n */\nexport function useComments(options: UseCommentsOptions): UseCommentsReturn {\n const { provider, getTemplateId, getUser } = options;\n\n const comments = ref<Comment[]>([]);\n const isLoading = ref(false);\n const isSubmitting = ref(false);\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n const canResolve = computed(() => typeof provider.setResolved === \"function\");\n\n const totalCount = computed(() =>\n comments.value.reduce(\n (sum, thread) => sum + 1 + (thread.replies?.length ?? 0),\n 0,\n ),\n );\n\n const unresolvedCount = computed(\n () => comments.value.filter((thread) => !thread.resolvedAt).length,\n );\n\n const commentCountByBlock = computed(() => {\n const map = new Map<string, number>();\n for (const thread of comments.value) {\n if (!thread.blockId) continue;\n map.set(\n thread.blockId,\n (map.get(thread.blockId) ?? 0) + 1 + (thread.replies?.length ?? 0),\n );\n }\n return map;\n });\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op.\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function requireUser(action: string): CommentAuthor {\n const user = getUser();\n if (!user) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs to know who is commenting. Pass init({ user: { id, name } }) — an unattributed comment is not written.`,\n );\n }\n return user;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Comments: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n function find(commentId: string): Comment | null {\n for (const thread of comments.value) {\n if (thread.id === commentId) return thread;\n for (const reply of thread.replies ?? []) {\n if (reply.id === commentId) return reply;\n }\n }\n return null;\n }\n\n function isOwn(comment: Comment): boolean {\n const user = getUser();\n return user !== null && comment.author.id === user.id;\n }\n\n function report(error: unknown): never {\n const wrapped = wrapReportedError(error);\n options.onError?.(wrapped);\n throw wrapped;\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a comment that was created.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n function replaceAt<T>(list: T[], index: number, next: T): T[] {\n return [...list.slice(0, index), next, ...list.slice(index + 1)];\n }\n\n /**\n * Key-order sensitive: identical fields serialized in a different order\n * compare unequal, so an echo whose transport frame orders keys\n * differently than the mutation response it echoes would not be\n * suppressed. Accepted rather than a defect — not worth a deep-equal\n * dependency for it.\n */\n function sameComment(a: Comment | undefined, b: Comment): boolean {\n return a !== undefined && JSON.stringify(a) === JSON.stringify(b);\n }\n\n /**\n * Insert a comment, replacing an entry with the same id rather than\n * duplicating it, and report whether the list actually changed.\n *\n * The **remote** apply paths (`applyRemoteCreate` / `applyRemoteUpdate`)\n * emit their event only when this returns `true`. A transport's own\n * broadcast can come back to the sender — `CommentsProvider.subscribe`'s\n * contract permits it — and emitting unconditionally fires the handler\n * twice for one comment. The comparison below runs against the **merged**\n * result, never the raw payload: the root branch keeps already-loaded\n * `replies` when an update payload carries none, so comparing the payload\n * directly would report a change for an echo that altered nothing.\n * Deleting the `sameComment` check as a redundant no-op reinstates the\n * double-fire.\n */\n function upsert(comment: Comment): boolean {\n if (comment.parentId) {\n let changed = false;\n const next = comments.value.map((thread) => {\n if (thread.id !== comment.parentId) return thread;\n const replies = thread.replies ?? [];\n const at = replies.findIndex((reply) => reply.id === comment.id);\n if (at !== -1 && sameComment(replies[at], comment)) return thread;\n changed = true;\n return {\n ...thread,\n replies:\n at === -1 ? [...replies, comment] : replaceAt(replies, at, comment),\n };\n });\n // Assigned only when something actually changed: `.map()` always returns\n // a new array, and reassigning `comments.value` for a no-op echo would\n // still invalidate every computed reading it (`commentCountByBlock`\n // returns a new `Map` on each recompute) for nothing.\n if (changed) comments.value = next;\n return changed;\n }\n\n const at = comments.value.findIndex((thread) => thread.id === comment.id);\n if (at === -1) {\n comments.value = [...comments.value, comment];\n return true;\n }\n // A root arriving again keeps the replies already loaded: the update payload\n // for a body edit carries none, and dropping them would empty the thread.\n const next: Comment = {\n ...comment,\n replies: comment.replies ?? comments.value[at].replies,\n };\n if (sameComment(comments.value[at], next)) return false;\n comments.value = replaceAt(comments.value, at, next);\n return true;\n }\n\n function drop(commentId: string, parentId?: string | null): Comment | null {\n const existing = find(commentId);\n // `parentId` from the caller wins so a delete can be applied without the\n // comment being loaded — the subscribe path, on a thread never opened.\n const parent = parentId ?? existing?.parentId ?? null;\n\n if (parent) {\n comments.value = comments.value.map((thread) =>\n thread.id === parent\n ? {\n ...thread,\n replies: (thread.replies ?? []).filter((r) => r.id !== commentId),\n }\n : thread,\n );\n } else {\n comments.value = comments.value.filter((c) => c.id !== commentId);\n }\n return existing;\n }\n\n async function load(params?: CommentsListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n comments.value = await provider.list(templateId, params);\n } catch (error) {\n report(error);\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(input: CommentInput): Promise<Comment> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n requireUser(\"create\");\n isSubmitting.value = true;\n try {\n const created = await providerCreate(templateId, input);\n upsert(created);\n notify(() => provider.onCreated?.(created, { origin: \"local\" }));\n return created;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function update(\n commentId: string,\n patch: CommentPatch,\n ): Promise<Comment> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") refuse(\"update\");\n const templateId = requireTemplateId(\"update\");\n requireUser(\"update\");\n isSubmitting.value = true;\n try {\n const updated = await providerUpdate(templateId, commentId, patch);\n upsert(updated);\n notify(() => provider.onUpdated?.(updated, { origin: \"local\" }));\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function remove(commentId: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") refuse(\"delete\");\n const templateId = requireTemplateId(\"delete\");\n requireUser(\"delete\");\n // Snapshotted before the request: the event carries what was deleted, and\n // there is nothing to read afterwards.\n const existing = find(commentId);\n isSubmitting.value = true;\n try {\n await providerDelete(templateId, commentId);\n drop(commentId);\n if (existing) {\n notify(() => provider.onDeleted?.(existing, { origin: \"local\" }));\n }\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function setResolved(\n commentId: string,\n resolved: boolean,\n ): Promise<Comment> {\n const { setResolved: providerSetResolved } = provider;\n if (typeof providerSetResolved !== \"function\") refuse(\"setResolved\");\n const templateId = requireTemplateId(\"setResolved\");\n requireUser(\"setResolved\");\n isSubmitting.value = true;\n try {\n const updated = await providerSetResolved(\n templateId,\n commentId,\n resolved,\n );\n upsert(updated);\n // The stored result decides which event fires, not the requested state: a\n // store may refuse to reopen, and the consumer should hear what happened.\n notify(() =>\n (updated.resolvedAt ? provider.onResolved : provider.onUnresolved)?.(\n updated,\n { origin: \"local\" },\n ),\n );\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n function applyRemoteCreate(comment: Comment): void {\n // A reply whose parent thread isn't loaded reports nothing: `upsert`\n // finds no matching thread to attach it to, so the list doesn't change.\n if (upsert(comment)) {\n notify(() => provider.onCreated?.(comment, { origin: \"remote\" }));\n }\n }\n\n function applyRemoteUpdate(comment: Comment): void {\n if (!upsert(comment)) return;\n notify(() =>\n (comment.resolvedAt\n ? provider.onResolved\n : // An unresolve and a body edit are both \"not resolved\"; only a payload\n // that used to be resolved is an unresolve, and the transport doesn't\n // say. `updated` is the honest answer for a plain change.\n provider.onUpdated)?.(comment, { origin: \"remote\" }),\n );\n }\n\n function applyRemoteDelete(\n commentId: string,\n parentId?: string | null,\n ): void {\n const existing = drop(commentId, parentId);\n if (existing) {\n notify(() => provider.onDeleted?.(existing, { origin: \"remote\" }));\n }\n }\n\n return {\n comments,\n isLoading,\n isSubmitting,\n canCreate,\n canUpdate,\n canDelete,\n canResolve,\n totalCount,\n unresolvedCount,\n commentCountByBlock,\n load,\n create,\n update,\n remove,\n setResolved,\n find,\n isOwn,\n applyRemoteCreate,\n applyRemoteUpdate,\n applyRemoteDelete,\n };\n}\n\nexport interface UseCommentListenerOptions {\n comments: UseCommentsReturn;\n provider: CommentsProvider;\n getTemplateId: () => string | null;\n}\n\n/**\n * Wire {@link CommentsProvider.subscribe} into the three `applyRemote*` paths.\n *\n * A no-op when the provider has no `subscribe` — realtime is optional, and\n * comments without it work exactly the same except that a colleague's comment\n * only appears on the next read. Nothing here knows about a transport: Cloud's\n * Pusher channel lives inside `createCloudCommentsProvider`, and an SSE or\n * long-poll implementation is the same three lines on the consumer's side.\n *\n * Re-subscribes when the template id changes, and unsubscribes on scope dispose —\n * so a session that loads a second template does not keep receiving the first\n * one's comments.\n */\nexport function useCommentListener(options: UseCommentListenerOptions): void {\n const { comments, provider, getTemplateId } = options;\n const { subscribe } = provider;\n if (typeof subscribe !== \"function\") return;\n\n let unsubscribe: (() => void) | null = null;\n\n function stop(): void {\n unsubscribe?.();\n unsubscribe = null;\n }\n\n watch(\n () => getTemplateId(),\n (templateId) => {\n stop();\n if (!templateId) return;\n unsubscribe = subscribe(templateId, (change: CommentChange) => {\n switch (change.type) {\n case \"created\":\n comments.applyRemoteCreate(change.comment);\n break;\n case \"updated\":\n comments.applyRemoteUpdate(change.comment);\n break;\n case \"deleted\":\n comments.applyRemoteDelete(change.commentId, change.parentId);\n break;\n }\n });\n },\n { immediate: true },\n );\n\n onScopeDispose(stop);\n}\n","import {\n SYNTAX_PRESETS,\n containsMergeTag,\n type BackgroundImage,\n type SyntaxPreset,\n} from \"@templatical/types\";\nimport {\n computed,\n getCurrentScope,\n inject,\n onScopeDispose,\n reactive,\n watch,\n type ComputedRef,\n} from \"vue\";\nimport { IMAGE_URL_RESOLVER_KEY, MERGE_TAG_SYNTAX_KEY } from \"../keys\";\nimport { RESOLVE_IMAGE_DEBOUNCE_MS } from \"../constants/timeouts\";\n\n/**\n * Display-only resolver for image `src` values (`config.resolveImageUrl`,\n * #415). Maps a canonical src (e.g. a plain file name like `logo.png`) to a\n * URL the canvas can actually display (e.g. an ephemeral `blob:` URL).\n * Returning `null` (or the input value) means \"use the src as-is\". The\n * resolved value never enters the content model or the MJML export.\n */\nexport type ResolveImageUrl = (\n src: string,\n) => string | null | Promise<string | null>;\n\n/**\n * Per-editor cache around the host's `resolveImageUrl` callback. Each src is\n * resolved at most once for the editor's lifetime — repeated lookups (same\n * image in several blocks, re-mounts while scrolling) hit the cache, and a\n * failed lookup caches `null` so the host service is never hammered with\n * retries for the same value.\n */\nexport interface ImageUrlResolver {\n /**\n * Cached result for a src: the resolved URL, `null` for \"use as-is\"\n * (also the failure fallback), or `undefined` when the src was never\n * looked up or the lookup is still in flight.\n */\n get(src: string): string | null | undefined;\n /** True when the src is cached or a lookup for it is in flight. */\n has(src: string): boolean;\n /** Start a lookup unless the src is already cached or in flight. */\n lookup(src: string): void;\n}\n\nexport function createImageUrlResolver(\n resolve: ResolveImageUrl,\n): ImageUrlResolver {\n // Reactive so `useResolvedImageSrc`'s computed re-evaluates when an async\n // lookup settles into the cache.\n const cache = reactive(new Map<string, string | null>());\n const inFlight = new Set<string>();\n\n function get(src: string): string | null | undefined {\n return cache.get(src);\n }\n\n function has(src: string): boolean {\n return cache.has(src) || inFlight.has(src);\n }\n\n function lookup(src: string): void {\n if (has(src)) return;\n\n let result: string | null | Promise<string | null>;\n try {\n result = resolve(src);\n } catch {\n cache.set(src, null);\n return;\n }\n\n if (result === null || typeof result === \"string\") {\n cache.set(src, result);\n return;\n }\n\n inFlight.add(src);\n Promise.resolve(result)\n .then(\n (value) => {\n // Normalize a misbehaving resolver (undefined, non-string) to null.\n cache.set(src, typeof value === \"string\" ? value : null);\n },\n () => {\n cache.set(src, null);\n },\n )\n .finally(() => inFlight.delete(src));\n }\n\n return { get, has, lookup };\n}\n\n/**\n * Component-facing display value for an image src. Passes the src through\n * unchanged when no `resolveImageUrl` is configured. With a resolver, the\n * returned computed shows the resolved preview URL once available and the\n * canonical src otherwise (while pending, or when the resolver opted out\n * with `null`).\n *\n * Lookup cadence: the initial src resolves immediately (template load),\n * subsequent changes are debounced by `RESOLVE_IMAGE_DEBOUNCE_MS` so typing\n * in the src input never sends partial values (`lo`, `logo.p`, …) to the\n * host resolver. Already-cached values apply instantly either way.\n *\n * Pass `undefined` from the getter to opt a value out of resolution\n * entirely (e.g. a merge-tag src, which is never displayable).\n */\nexport function useResolvedImageSrc(\n src: () => string | undefined,\n): ComputedRef<string | undefined> {\n const resolver = inject(IMAGE_URL_RESOLVER_KEY, null);\n const srcRef = computed(src);\n if (!resolver) return srcRef;\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n function clearTimer(): void {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n }\n if (getCurrentScope()) {\n onScopeDispose(clearTimer);\n }\n\n let initial = true;\n watch(\n srcRef,\n (value) => {\n clearTimer();\n const immediate = initial;\n initial = false;\n if (!value || resolver.has(value)) return;\n if (immediate) {\n resolver.lookup(value);\n return;\n }\n timer = setTimeout(() => {\n timer = undefined;\n resolver.lookup(value);\n }, RESOLVE_IMAGE_DEBOUNCE_MS);\n },\n { immediate: true },\n );\n\n return computed(() => {\n const value = srcRef.value;\n if (!value) return value;\n const resolved = resolver.get(value);\n return typeof resolved === \"string\" && resolved.length > 0\n ? resolved\n : value;\n });\n}\n\n/**\n * Synchronous cache read for surfaces that render blocks in a loop and can't\n * hold a per-item `useResolvedImageSrc` (block previews). Returns the resolved\n * URL when the canvas has already looked this src up, otherwise the src\n * itself. Never starts a lookup.\n */\nexport function readCachedImageUrl(\n resolver: ImageUrlResolver | null,\n src: string | undefined,\n): string | undefined {\n if (!resolver || !src) return src;\n const resolved = resolver.get(src);\n return typeof resolved === \"string\" && resolved.length > 0 ? resolved : src;\n}\n\n/**\n * Whether a background image's URL holds a merge tag. Such a URL is never\n * displayable — painting it makes the browser request the literal token — so,\n * like an image block's merge-tag `src`, the canvas neither resolves nor paints\n * it and the fallback colour shows instead.\n */\nexport function hasMergeTagBackground(\n bg: BackgroundImage | undefined,\n syntax: SyntaxPreset,\n): boolean {\n return typeof bg?.url === \"string\" && containsMergeTag(bg.url, syntax);\n}\n\n/**\n * The URL to look up for a background image: its own, or `undefined` when\n * there is nothing displayable to resolve (no image, a blank URL, a merge tag).\n */\nexport function getBackgroundLookupUrl(\n bg: BackgroundImage | undefined,\n syntax: SyntaxPreset,\n): string | undefined {\n const url = bg?.url;\n if (typeof url !== \"string\" || url.trim() === \"\") return undefined;\n return containsMergeTag(url, syntax) ? undefined : url;\n}\n\n/**\n * Display value for a background image in the shape the canvas style helpers\n * take as `backgroundImageUrl`: the resolved URL, `null` for a merge-tag URL\n * (paint nothing, start no lookup), `undefined` when there is no image.\n * Same lookup cadence as {@link useResolvedImageSrc}.\n */\nexport function useResolvedBackgroundUrl(\n bg: () => BackgroundImage | undefined,\n): ComputedRef<string | null | undefined> {\n const syntax = inject(MERGE_TAG_SYNTAX_KEY, SYNTAX_PRESETS.liquid);\n const display = useResolvedImageSrc(() =>\n getBackgroundLookupUrl(bg(), syntax),\n );\n return computed(() =>\n hasMergeTagBackground(bg(), syntax) ? null : display.value,\n );\n}\n\n/**\n * {@link readCachedImageUrl} for a background image, in the same shape as\n * {@link useResolvedBackgroundUrl}: cache-only, never starts a lookup.\n */\nexport function readCachedBackgroundUrl(\n resolver: ImageUrlResolver | null,\n bg: BackgroundImage | undefined,\n syntax: SyntaxPreset,\n): string | null | undefined {\n if (hasMergeTagBackground(bg, syntax)) return null;\n return readCachedImageUrl(resolver, getBackgroundLookupUrl(bg, syntax));\n}\n","import type { Translations } from \"../i18n\";\nimport type {\n Block,\n CustomBlock,\n CustomBlockDefinition,\n} from \"@templatical/types\";\n\n/**\n * Returns the i18n label for a built-in block type.\n * Falls back to the raw type string for unknown types.\n */\nexport function getBlockTypeLabel(\n blockType: string,\n translations: Translations,\n): string {\n const labels = translations.blocks as Record<string, string>;\n return labels[blockType] ?? blockType;\n}\n\n/**\n * Display label for a block *instance*, which is what user-facing copy wants:\n * built-ins resolve to their i18n label, custom blocks to the consumer's own\n * name for them (\"Featured Article\"), not the literal type `\"custom\"`.\n *\n * `blocks` carries no `custom` key on purpose — one generic \"Custom\" would make\n * two different custom blocks indistinguishable in a list. The name comes from\n * the definition instead; it is consumer-supplied and therefore NOT localized,\n * which is already how the toolbar and the sidebar palette present it.\n *\n * Falls back to `customType` (the slug) when no definition matches — an\n * instance whose definition was never registered — mirroring `Toolbar.vue`.\n * Pass the array injected under `CUSTOM_BLOCK_DEFINITIONS_KEY`; omitting it\n * degrades to that same slug fallback rather than throwing.\n */\nexport function getBlockLabel(\n block: Block,\n translations: Translations,\n customBlockDefinitions: readonly CustomBlockDefinition[] = [],\n): string {\n if (block.type !== \"custom\") {\n return getBlockTypeLabel(block.type, translations);\n }\n const { customType } = block as CustomBlock;\n const definition = customBlockDefinitions.find((d) => d.type === customType);\n return definition?.name ?? customType;\n}\n","import type { CustomBlockColorField } from \"@templatical/types\";\nimport {\n DEFAULT_RESOLVED_COLORS,\n resolveColorsConfig,\n type ResolvedColors,\n} from \"./resolveColorsConfig\";\n\n/**\n * The palette one custom-block color field renders, plus the audit signals a\n * consumer needs to warn about a field config that could not be honoured.\n *\n * Pure — this util never logs. The warnings live at the definition-registration\n * site (`useEditorCore`, via `collectColorFieldIssues`), the same resolver /\n * consumer split `resolveColorsConfig` and `resolvePaletteBlocks` use.\n */\nexport interface ResolvedFieldColors {\n /** The preset grid this field's picker renders. */\n presets: string[];\n /** Whether the wheel + hex input are offered alongside the grid. */\n allowCustom: boolean;\n /**\n * Entries of the FIELD's own `presets` dropped as invalid hex. Never includes\n * anything inherited from the editor palette — those were already validated\n * (and already warned about) at the editor level, so they are not re-reported.\n */\n invalidPresets: string[];\n /** The field declared `presets: []` — an empty list cannot narrow anything. */\n emptyPresets: boolean;\n /**\n * The field contributed no usable presets (unset, empty, or all-invalid), so\n * {@link ResolvedFieldColors.presets} is the editor's palette.\n */\n presetsInherited: boolean;\n /**\n * The field asked for `allowCustom: true` while the editor is locked. A field\n * may only narrow, so the request is dropped and the field stays locked.\n */\n allowCustomIgnored: boolean;\n}\n\n/**\n * Resolve a custom-block color field's own `presets` / `allowCustom` against\n * the already-resolved editor-wide palette. A field narrows the author's\n * freedom, not the palette: it can lock this field or give it its own presets,\n * but never unlock what the editor locked — and its `presets` *replace* the\n * editor grid rather than intersecting it (a locked field may list colors\n * outside it):\n *\n * - `allowCustom` — locked stays locked. `editorResolved.allowCustom === false`\n * wins outright, so an explicit field `allowCustom: true` under a locked\n * editor is ignored (flagged via `allowCustomIgnored`). Otherwise the field's\n * value applies, falling back to the editor's.\n * - `presets` — the field's entries are validated by {@link resolveColorsConfig}\n * (against the unconfigured baseline, so the hex rule lives in exactly one\n * place and inheritance is decided here rather than by that util's generic\n * per-property precedence). A non-empty valid list replaces the editor's;\n * unset, `[]`, or all-invalid all inherit the editor's palette. This is why\n * `[]` cannot mean \"no chips\" — an empty grid on a locked field would leave\n * the picker with nothing to pick.\n *\n * One residual case is left to `ColorPicker`'s own guard rather than forced\n * here: a field locking itself (`allowCustom: false`) when neither it nor the\n * editor has presets resolves to `{ presets: [], allowCustom: false }`, and the\n * picker's `showFreeform = allowCustom || !hasPresets` still renders the wheel,\n * so the field is never left unable to set a color.\n */\nexport function resolveFieldColors(\n field: Pick<CustomBlockColorField, \"presets\" | \"allowCustom\">,\n editorResolved: ResolvedColors,\n): ResolvedFieldColors {\n // Validate the field's own presets through the shared resolver, against the\n // unconfigured baseline — NOT against `editorResolved`, whose per-property\n // precedence would inherit before we can tell \"field said nothing\" apart\n // from \"field said something unusable\".\n const own = resolveColorsConfig(\n { presets: field.presets },\n DEFAULT_RESOLVED_COLORS,\n );\n\n const presetsInherited = own.presets.length === 0;\n\n const requestedAllowCustom = field.allowCustom ?? editorResolved.allowCustom;\n\n return {\n presets: presetsInherited ? editorResolved.presets : own.presets,\n allowCustom:\n editorResolved.allowCustom === false ? false : requestedAllowCustom,\n invalidPresets: own.invalidPresets,\n emptyPresets: field.presets !== undefined && field.presets.length === 0,\n presetsInherited,\n allowCustomIgnored:\n field.allowCustom === true && editorResolved.allowCustom === false,\n };\n}\n","import type { ImageBlock } from \"@templatical/types\";\nimport { NATURAL_SIZE_TIMEOUT_MS } from \"../constants/timeouts\";\n\nexport interface NaturalSize {\n width: number;\n height: number;\n}\n\nfunction isSize(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n\n/**\n * A width and height as a natural size, or `null` unless both are positive\n * numbers: one without the other says nothing about the ratio.\n */\nexport function toNaturalSize(\n width: unknown,\n height: unknown,\n): NaturalSize | null {\n return isSize(width) && isSize(height) ? { width, height } : null;\n}\n\n/** The size of the file an image block shows, when the block stores one. */\nexport function naturalSizeOf(\n block: Pick<ImageBlock, \"naturalWidth\" | \"naturalHeight\">,\n): NaturalSize | null {\n return toNaturalSize(block.naturalWidth, block.naturalHeight);\n}\n\n/**\n * The block fields for a natural size: both set, or both cleared. Written in\n * the same update as `src`, so a size from the previous file never outlives it.\n */\nexport function naturalSizeFields(\n size: NaturalSize | null,\n): Pick<ImageBlock, \"naturalWidth\" | \"naturalHeight\"> {\n return size\n ? { naturalWidth: size.width, naturalHeight: size.height }\n : { naturalWidth: undefined, naturalHeight: undefined };\n}\n\n/**\n * Load `url` in an `Image` and pass its natural size to `done`, or `null` when\n * it fails to load or reports no size (a broken image reads 0 × 0). Only the\n * size is read, never the pixels, so a cross-origin image needs no CORS\n * headers. The returned function stops listening; `done` is then never called.\n */\nexport function loadNaturalSize(\n url: string,\n done: (size: NaturalSize | null) => void,\n): () => void {\n if (typeof Image === \"undefined\") {\n done(null);\n return () => {};\n }\n const image = new Image();\n const stop = (): void => {\n image.onload = null;\n image.onerror = null;\n };\n image.onload = () => {\n stop();\n done(toNaturalSize(image.naturalWidth, image.naturalHeight));\n };\n image.onerror = () => {\n stop();\n done(null);\n };\n image.src = url;\n return stop;\n}\n\n/**\n * The natural size of the image at `url` (`loadNaturalSize`), or `null` once\n * `NATURAL_SIZE_TIMEOUT_MS` passes without a load, so a stalled image never\n * leaves a measurement pending.\n */\nexport function measureNaturalSize(url: string): Promise<NaturalSize | null> {\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n stop();\n resolve(null);\n }, NATURAL_SIZE_TIMEOUT_MS);\n const stop = loadNaturalSize(url, (size) => {\n clearTimeout(timer);\n resolve(size);\n });\n });\n}\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { LoaderCircle, Upload } from \"@lucide/vue\";\nimport { computed } from \"vue\";\n\nconst props = withDefaults(\n defineProps<{\n uploading: boolean;\n size?: \"field\" | \"canvas\";\n }>(),\n {\n size: \"field\",\n },\n);\n\nconst { t } = useI18n();\n\n// The canvas overlay covers a whole image block, so it draws larger and lets\n// a little more of the image show through than a sidebar field's.\nconst SIZES = {\n field: { gap: \"tpl:gap-1.5\", icon: 18, veil: \"90%\" },\n canvas: { gap: \"tpl:gap-2\", icon: 20, veil: \"85%\" },\n} as const;\n\nconst sizing = computed(() => SIZES[props.size]);\n</script>\n\n<template>\n <div\n class=\"tpl:pointer-events-none tpl:absolute tpl:inset-0 tpl:z-10 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded tpl:border-2 tpl:border-dashed tpl:text-xs tpl:font-medium tpl:border-[var(--tpl-primary)] tpl:text-[var(--tpl-primary)]\"\n :class=\"sizing.gap\"\n :style=\"{\n backgroundColor: `color-mix(in srgb, var(--tpl-bg) ${sizing.veil}, transparent)`,\n }\"\n >\n <template v-if=\"uploading\">\n <LoaderCircle class=\"tpl-spinner\" :size=\"sizing.icon\" :stroke-width=\"2\" />\n {{ t.image.uploading }}\n </template>\n <template v-else>\n <Upload :size=\"sizing.icon\" :stroke-width=\"1.5\" />\n {{ t.image.dropToUpload }}\n </template>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { LoaderCircle, Upload } from \"@lucide/vue\";\nimport { computed } from \"vue\";\n\nconst props = withDefaults(\n defineProps<{\n uploading: boolean;\n size?: \"field\" | \"canvas\";\n }>(),\n {\n size: \"field\",\n },\n);\n\nconst { t } = useI18n();\n\n// The canvas overlay covers a whole image block, so it draws larger and lets\n// a little more of the image show through than a sidebar field's.\nconst SIZES = {\n field: { gap: \"tpl:gap-1.5\", icon: 18, veil: \"90%\" },\n canvas: { gap: \"tpl:gap-2\", icon: 20, veil: \"85%\" },\n} as const;\n\nconst sizing = computed(() => SIZES[props.size]);\n</script>\n\n<template>\n <div\n class=\"tpl:pointer-events-none tpl:absolute tpl:inset-0 tpl:z-10 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded tpl:border-2 tpl:border-dashed tpl:text-xs tpl:font-medium tpl:border-[var(--tpl-primary)] tpl:text-[var(--tpl-primary)]\"\n :class=\"sizing.gap\"\n :style=\"{\n backgroundColor: `color-mix(in srgb, var(--tpl-bg) ${sizing.veil}, transparent)`,\n }\"\n >\n <template v-if=\"uploading\">\n <LoaderCircle class=\"tpl-spinner\" :size=\"sizing.icon\" :stroke-width=\"2\" />\n {{ t.image.uploading }}\n </template>\n <template v-else>\n <Upload :size=\"sizing.icon\" :stroke-width=\"1.5\" />\n {{ t.image.dropToUpload }}\n </template>\n </div>\n</template>\n","import {\n computed,\n toValue,\n type ComputedRef,\n type MaybeRefOrGetter,\n} from \"vue\";\nimport { useDropZone } from \"@vueuse/core\";\n\nexport interface UseImageDropOptions {\n /** The drop target element (a template ref). */\n target: MaybeRefOrGetter<HTMLElement | null | undefined>;\n /**\n * Called with the dropped image file(s). The editor acts on a single file\n * per drop (`files[0]`), but the array shape is kept for forward-compat.\n */\n onFiles: (files: File[]) => void;\n /**\n * Gate the zone. While falsy the drop is inert: no highlight, dropped files\n * are ignored. `useMediaDropField` passes `canDropMedia && !isUploading`\n * so a read-only library (`create: false`) renders no affordance, a\n * missing media handler does the same, and a second drop can't race an\n * in-flight upload.\n */\n enabled?: MaybeRefOrGetter<boolean>;\n}\n\nexport interface UseImageDropReturn {\n /** True while an image drag hovers the (enabled) target — drive the highlight. */\n isOver: ComputedRef<boolean>;\n}\n\nconst IMAGE_MIME_PREFIX = \"image/\";\n\n/**\n * Drag-and-drop image upload onto an image block/field (#229). Wraps\n * `useDropZone`; filters dropped files to image MIME types client-side (the\n * authoritative size/type check stays server/plan-config side) and forwards\n * the first image to `onFiles`. The caller hands the file to `onRequestMedia`,\n * which uploads it and returns a `MediaResult` — identical to the Browse Media\n * path, only the input differs.\n *\n * `preventDefaultForUnhandled` keeps the browser from navigating to the dropped\n * file even for a non-image drop on the zone; the editor-root guard covers\n * drops that land outside any zone.\n */\nexport function useImageDrop(options: UseImageDropOptions): UseImageDropReturn {\n const { target, onFiles, enabled } = options;\n\n const isEnabled = (): boolean =>\n enabled === undefined ? true : toValue(enabled);\n\n const { isOverDropZone } = useDropZone(target, {\n preventDefaultForUnhandled: true,\n onDrop: (files) => {\n if (!isEnabled()) return;\n const images = (files ?? []).filter((file) =>\n file.type.startsWith(IMAGE_MIME_PREFIX),\n );\n if (images.length > 0) onFiles([images[0]]);\n },\n });\n\n const isOver = computed(() => isEnabled() && isOverDropZone.value);\n\n return { isOver };\n}\n","import {\n computed,\n inject,\n ref,\n toValue,\n type ComputedRef,\n type MaybeRefOrGetter,\n type Ref,\n} from \"vue\";\nimport type { MediaResult } from \"@templatical/types\";\nimport { CAN_DROP_MEDIA_KEY, ON_REQUEST_MEDIA_KEY } from \"../keys\";\nimport { useAliveFlag } from \"./useAliveFlag\";\nimport { useImageDrop } from \"./useImageDrop\";\n\nexport interface UseMediaDropFieldOptions {\n /** The drop target element (a template ref). */\n target: MaybeRefOrGetter<HTMLElement | null | undefined>;\n /**\n * Turns drop off for this field on top of the media gates, e.g. for a\n * merge-tag value (a deliberate dynamic value a drop must never clobber) or\n * a read-only field. Browse is unaffected.\n */\n blocked?: MaybeRefOrGetter<boolean>;\n /**\n * Writes a picked or uploaded image into the field. Not called when the\n * request is cancelled or the component has unmounted while it ran.\n */\n apply: (result: MediaResult) => void;\n}\n\nexport interface UseMediaDropFieldReturn {\n /** Whether the host handles media requests, so Browse can render. */\n canBrowse: boolean;\n /** Whether a drop would be accepted right now. */\n dropEnabled: ComputedRef<boolean>;\n /** True while a dropped image uploads. */\n isUploading: Readonly<Ref<boolean>>;\n /** Whether the drag-over or uploading overlay shows. */\n showOverlay: ComputedRef<boolean>;\n /** Opens the host's media browser and applies the picked image. */\n openMediaBrowser: () => Promise<void>;\n}\n\n/**\n * Browse and drag-and-drop upload for an image URL field (#229). Both go\n * through the injected `onRequestMedia`: Browse asks it to pick an image, a\n * drop hands it the file to upload, and either way the returned `MediaResult`\n * goes to `apply`.\n *\n * Browse and drop are gated separately: a read-only provider still opens the\n * library, but `canDropMedia` is false so the zone does not highlight. Drop is\n * also off while an upload runs, so a second drop can't race it, and while\n * `blocked` holds.\n */\nexport function useMediaDropField(\n options: UseMediaDropFieldOptions,\n): UseMediaDropFieldReturn {\n const { target, blocked, apply } = options;\n const onRequestMedia = inject(ON_REQUEST_MEDIA_KEY, null);\n const canDropMedia = inject(CAN_DROP_MEDIA_KEY, null);\n const aliveFlag = useAliveFlag();\n\n async function openMediaBrowser(): Promise<void> {\n const result = await onRequestMedia?.({ accept: [\"images\"] });\n if (!aliveFlag.alive) return;\n if (result) apply(result);\n }\n\n const isUploading = ref(false);\n const dropEnabled = computed(\n () =>\n (canDropMedia?.value ?? !!onRequestMedia) &&\n !isUploading.value &&\n !toValue(blocked),\n );\n\n async function uploadDroppedFiles(files: File[]): Promise<void> {\n if (!onRequestMedia) return;\n isUploading.value = true;\n try {\n const result = await onRequestMedia({ accept: [\"images\"], files });\n if (!aliveFlag.alive) return;\n if (result) apply(result);\n } finally {\n if (aliveFlag.alive) isUploading.value = false;\n }\n }\n\n const { isOver } = useImageDrop({\n target,\n enabled: dropEnabled,\n onFiles: uploadDroppedFiles,\n });\n\n // Uploading counts on its own: drop is off while an upload runs, so gating\n // it on `dropEnabled` would hide the uploading state.\n const showOverlay = computed(\n () => (dropEnabled.value && isOver.value) || isUploading.value,\n );\n\n return {\n canBrowse: !!onRequestMedia,\n dropEnabled,\n isUploading,\n showOverlay,\n openMediaBrowser,\n };\n}\n","import type { TemplateSettings, ViewportSize } from \"@templatical/types\";\n\n/**\n * Width a mobile preview renders at. Not the template's own width — a phone\n * viewport is narrower than any sensible email body, so every viewport-aware\n * surface clamps to this.\n */\nexport const MOBILE_EMAIL_WIDTH = 375;\n\n/**\n * Fallback body width when no template settings are available — headless mounts\n * and tests. Matches `createDefaultTemplateContent`'s default.\n */\nexport const DEFAULT_EMAIL_WIDTH = 600;\n\n/**\n * The width an email body lays itself out against, for a given viewport.\n *\n * **The single source of truth for every surface that renders blocks**: the\n * canvas, the preview canvas, and the save dialog's scaled preview rows. They\n * have to agree — `SavedBlockPreviewRow` divides by this number to compute its\n * `transform: scale()`, so if it and the canvas disagreed the rows would be\n * scaled by the wrong factor and overflow or under-fill their frame. Sharing one\n * function makes that agreement structural instead of three constants that happen\n * to match today.\n *\n * Pass the *current* template's settings even when previewing content from\n * elsewhere (a saved block stores only `Block[]`): the current settings are what\n * the content will actually be rendered at.\n */\nexport function getEmailFrameWidth(\n settings: TemplateSettings | undefined,\n viewport: ViewportSize = \"desktop\",\n): number {\n if (viewport === \"mobile\") return MOBILE_EMAIL_WIDTH;\n return settings?.width ?? DEFAULT_EMAIL_WIDTH;\n}\n\n/**\n * Band of email background shown on each side of the content column.\n *\n * A surface that renders blocks at exactly the body width has nowhere for\n * `settings.backgroundColor` to show: a full-width section's own background\n * covers every pixel of it, so the body colour reads as unset even though the\n * sent email paints it across the whole client viewport. The gutter is what\n * makes it visible, mirroring how `mj-body background-color` renders beside the\n * centred content.\n *\n * Fixed rather than \"fill the container\" so the band never overwhelms the\n * content on a wide monitor. `Canvas.vue` adds it to both sides of a fixed\n * stage; `BlockPreviewCanvas` treats it as the cap on a fluid one, because a\n * fixed 792px stage overflows every dialog it lives in.\n */\nexport const EMAIL_GUTTER = 96;\n\n/**\n * How a viewport switch animates the frame.\n *\n * Lives here rather than being written out per call site so every surface that\n * switches viewport eases identically — the canvas's toggle and the test-email\n * dialog's should feel like the same control, not two similar ones. The slight\n * overshoot in the curve is deliberate and matches the editor's other viewport\n * transitions.\n *\n * Only `width` transitions: block content re-flows for the new viewport in the\n * same frame, exactly as it does on the canvas, so animating height as well would\n * lag the reflow behind the frame.\n */\nexport const EMAIL_FRAME_WIDTH_TRANSITION =\n \"width 300ms cubic-bezier(0.34, 1.56, 0.64, 1)\";\n","import type {\n Block,\n BorderValue,\n ColumnLayout,\n SpacingValue,\n TemplateContent,\n} from \"@templatical/types\";\nimport {\n applyLayout,\n isSection,\n isWrapper,\n resolveHero,\n toBorderCss,\n} from \"@templatical/types\";\nimport { getEmailFrameWidth } from \"./emailFrameWidth\";\n\n/**\n * Column percentages per layout, exactly as the renderer's\n * `getWidthPercentages` emits them. MJML sizes a column from the emitted\n * string, so 33.33% of 600 is 199, not a third. The parity test in\n * `tests/imageRoom.test.ts` holds this table to the renderer's.\n */\nconst COLUMN_PERCENTS: Record<ColumnLayout, number[]> = {\n \"1\": [100],\n \"2\": [50, 50],\n \"3\": [33.33, 33.33, 33.34],\n \"1-2\": [33.33, 66.67],\n \"2-1\": [66.67, 33.33],\n};\n\n/**\n * Side padding plus drawn side borders: what MJML takes off a box's content,\n * each side read as a whole pixel as MJML's `parseInt` reads it.\n */\nfunction horizontalInset(\n padding: SpacingValue | undefined,\n border?: BorderValue,\n): number {\n const whole = (value: number | undefined) => Math.trunc(value ?? 0);\n const drawn = (side: BorderValue[\"left\"] | undefined) =>\n toBorderCss(side) === null ? 0 : Math.trunc(side!.width);\n return (\n whole(padding?.left) +\n whole(padding?.right) +\n drawn(border?.left) +\n drawn(border?.right)\n );\n}\n\n/** What an `mj-wrapper` band leaves its content: floored, less its side padding. */\nfunction insideBand(width: number, padding: SpacingValue | undefined): number {\n return Math.floor(width) - horizontalInset(padding);\n}\n\nfunction blockRoom(block: Block, columnContent: number): number {\n const border = \"border\" in block ? (block.border as BorderValue) : undefined;\n return (\n Math.floor(columnContent) - horizontalInset(block.styles.padding, border)\n );\n}\n\n/**\n * Each section and top-level leaf in `blocks`, with the width the bands around\n * it leave it: every layout wrapper's and the section's own `wrapper`'s side\n * padding taken off, floored at each band as the renderer's `insideWrapper`\n * does.\n */\nfunction* bandedBlocks(\n blocks: Block[],\n width: number,\n): Generator<{ block: Block; bandWidth: number }> {\n for (const block of blocks) {\n if (isWrapper(block)) {\n yield* bandedBlocks(\n block.children,\n insideBand(width, block.styles.padding),\n );\n continue;\n }\n const bandWidth =\n isSection(block) && block.wrapper\n ? insideBand(width, block.wrapper.padding)\n : width;\n yield { block, bandWidth };\n }\n}\n\n/**\n * The content with the layout shell (`init({ layout })`) applied, as the\n * export does; a layout that fails to apply is ignored.\n */\nfunction documentOf(\n content: TemplateContent,\n layout: TemplateContent | undefined,\n): TemplateContent {\n if (!layout) return content;\n try {\n return applyLayout(layout, content);\n } catch {\n return content;\n }\n}\n\n/**\n * The px an image can span on desktop: what MJML gives its column's content,\n * less the image's own side padding and drawn side borders. It mirrors the\n * renderer's `RenderContext.contentWidth` and `fluidOnMobileAttr`, so a width\n * at or above it renders as `\"full\"` does. A hero's content takes the box\n * less the hero's padding only: the hero hides its section's border. `null`\n * when the block is not in the content.\n */\nexport function imageRoom(\n content: TemplateContent,\n blockId: string,\n layout?: TemplateContent,\n): number | null {\n const doc = documentOf(content, layout);\n for (const { block, bandWidth } of bandedBlocks(\n doc.blocks,\n doc.settings.width,\n )) {\n if (isSection(block)) {\n const border = resolveHero(block)?.applied ? undefined : block.border;\n const sectionBox =\n Math.floor(bandWidth) - horizontalInset(block.styles.padding, border);\n const percents = COLUMN_PERCENTS[block.columns] ?? [100];\n for (let index = 0; index < block.children.length; index++) {\n const column = Math.floor(\n (sectionBox * (percents[index] ?? 100)) / 100,\n );\n const child = block.children[index].find((c) => c.id === blockId);\n if (child) return blockRoom(child, column);\n }\n continue;\n }\n\n // A top-level leaf renders in a default section with no padding.\n if (block.id === blockId) return blockRoom(block, bandWidth);\n }\n return null;\n}\n\n/**\n * The width the bands around a top-level section leave it, which is the box\n * MJML draws a hero at and Outlook paints its image across: the body width\n * less the side padding of every layout wrapper and of the section's own\n * `wrapper`, floored at each band. `null` when the section is not in the\n * content.\n */\nexport function sectionBandWidth(\n content: TemplateContent,\n sectionId: string,\n layout?: TemplateContent,\n): number | null {\n const doc = documentOf(content, layout);\n for (const { block, bandWidth } of bandedBlocks(\n doc.blocks,\n doc.settings.width,\n )) {\n if (block.id === sectionId) return Math.floor(bandWidth);\n }\n return null;\n}\n\n/**\n * The desktop box width a \"match image\" hero's height follows on every\n * viewport, as the renderer's fixed height does: the band width it is drawn\n * at (`sectionBandWidth`), or the body width for a section outside `content`.\n * `undefined` for any block that isn't an applied \"match image\" hero.\n */\nexport function matchImageBoxWidth(\n block: Block,\n content: TemplateContent | undefined,\n layout?: TemplateContent,\n): number | undefined {\n if (!isSection(block)) return undefined;\n const hero = resolveHero(block);\n if (!hero?.applied || hero.height !== \"image\") return undefined;\n const banded = content ? sectionBandWidth(content, block.id, layout) : null;\n return banded ?? getEmailFrameWidth(content?.settings);\n}\n","import { SOCIAL_ICON_GLYPHS, type SocialPlatform } from \"@templatical/types\";\n\n/**\n * Icon glyph (SVG path + brand color) per platform. Re-exported from the\n * shared kernel in `@templatical/types` so the editor's inline SVG and the\n * renderer's PNG rasterizer never drift. Platform display labels are NOT here\n * — they come from i18n (`t.social.platforms[platform]`).\n */\nexport const socialIcons = SOCIAL_ICON_GLYPHS;\n\nexport const socialIconSizeMap: Record<\"small\" | \"medium\" | \"large\", number> = {\n small: 24,\n medium: 32,\n large: 48,\n};\n\nexport const socialPlatformOptions: SocialPlatform[] = [\n \"facebook\",\n \"twitter\",\n \"instagram\",\n \"linkedin\",\n \"youtube\",\n \"tiktok\",\n \"pinterest\",\n \"email\",\n \"website\",\n \"whatsapp\",\n \"telegram\",\n \"discord\",\n \"snapchat\",\n \"reddit\",\n \"github\",\n \"dribbble\",\n \"behance\",\n];\n"],"mappings":";;;;;;;;;;AAQA,SAAgBmE,EAAkB,GAAuB;CACvD,OAAOC,aAAiB,QACpBA,IACI,MAAM,OAAOA,CAAK,GAAG,EAAE,OAAOA,EAAM,CAAC;AAC/C;AAYA,SAAgBC,EACd,GACA,GACM;CACN,IAAI;EACF,EAAI;CACN,SAASD,GAAO;EACd,IAAUD,EAAkBC,CAAK,CAAC;CACpC;AACF;;;ACZA,SAASE,EAAe,GAA8B;CAGpD,OAFIC,MAAW,MAAY,IACvBA,MAAW,MAAY,IACpB;AACT;AAwHA,SAAgBC,GAAU,GAA4C;CACpE,IAAMC,IACJC,EAAQ,WACR3B,EACE2B,EAAQ,mBACRA,EAAQ,gBACV;CAGF,AADAjC,EAAsBgC,CAAW,GACjCjC,EAAyBiC,CAAW;CAEpC,IAAME,IAAQlD,EAAsB;EAClC,UAAU;EACV,SAASgD;EACT,iBAAiB;EACjB,UAAU;EACV,UAAU;EACV,aAAa;EACb,SAAS;EACT,UAAU;EACV,WAAW;EACX,SAAS;CACX,CAAC,GAQGG,IAAW;CAEf,SAASC,IAAc;EAErB,AADA,EAAM,UAAU,IAChB;CACF;CAEA,IAAMC,IAAUtD,EAAS;EACvB,WAAWmD,EAAM;EACjB,MAAM,MAA2B;GAE/B,AADA,EAAM,UAAUI,GAChBF,EAAM;EACR;CACF,CAAC,GAEKG,IAAgBxD,QACfmD,EAAM,kBACJM,EAAcN,EAAM,QAAQ,QAAQA,EAAM,eAAe,IAD7B,IAEpC;CAED,SAASM,EAAc,GAAiB,GAA0B;EAChE,KAAK,IAAMC,KAASC,GAAQ;GAC1B,IAAID,EAAM,OAAOE,GAAI,OAAOF;GAC5B,IAAIA,EAAM,SAAS,WACjB,KAAK,IAAMG,KAAUH,EAAM,UAAU;IAC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