@templatical/editor 0.52.1 → 0.54.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 (397) hide show
  1. package/README.md +1 -1
  2. package/dist/AiAltTextPopover-NMJqQKvD.js +106 -0
  3. package/dist/{AiAltTextReview-9ySsXOTU.js → AiAltTextReview-Ci4zHwRc.js} +68 -66
  4. package/dist/AiChatPanel-C8SeEJRP.js +561 -0
  5. package/dist/{AiPanels-DqT4PgQ0.js → AiPanels-CR6zphjP.js} +6 -6
  6. package/dist/{AiRewriteMenu-28agTycW.js → AiRewriteMenu-CIHUnPud.js} +76 -105
  7. package/dist/BlockIssueBadge-DaPTq1RE.js +33 -0
  8. package/dist/BlockPreviewCanvas-B70RSavL.js +140 -0
  9. package/dist/{CloudHeaderExtras-QI82yF54.js → CloudHeaderExtras-XpjJjn3o.js} +4 -4
  10. package/dist/{CloudPanels-BKJaLkUN.js → CloudPanels-VpSQiLLL.js} +53 -53
  11. package/dist/CollaborationNotices-Cnx0XHzZ.js +65 -0
  12. package/dist/{CollaboratorBar-CXQqN3VP.js → CollaboratorBar-BaBoNhwB.js} +24 -24
  13. package/dist/CommentsPanel-Ck3QmqiC.js +16 -0
  14. package/dist/CommentsSidebar-CHknhOar.js +526 -0
  15. package/dist/{CountdownBlock-CU2yTWtF.js → CountdownBlock-BMezkFbJ.js} +15 -15
  16. package/dist/CountdownToolbar-CM4XNEuO.js +258 -0
  17. package/dist/IssuesPanel-1wGV0wiy.js +371 -0
  18. package/dist/LanguageMenu-d2GlX67r.js +403 -0
  19. package/dist/{LoadingTrack-DM4g6j7b.js → LoadingTrack-BG8cg9xi.js} +2 -2
  20. package/dist/LocaleNotices-WzsYtBRs.js +46 -0
  21. package/dist/LogicTagInsertButton-DgTJ6Lvx.js +1096 -0
  22. package/dist/{MediaEditModal-Dy08GEwE.js → MediaEditModal-C3U9Mi31.js} +451 -451
  23. package/dist/{MediaPanels-BgEp7iCp.js → MediaPanels-CGmk9ufe.js} +4 -4
  24. package/dist/{MergeTagInput-B9dtUthD.js → MergeTagInput-B_51YcQO.js} +30 -30
  25. package/dist/{MergeTagModeToggle-DxujhYJ4.js → MergeTagModeToggle-D3Q2z317.js} +49 -49
  26. package/dist/MergeTagTextarea-DZz1L9DE.js +126 -0
  27. package/dist/ParagraphEditor-CI68PYDL.js +825 -0
  28. package/dist/{RestoreVersionDialog-C4s_JYCx.js → RestoreVersionDialog-DcuhpOIz.js} +23 -23
  29. package/dist/{RichTextEditorContent-o6HmE8GR.js → RichTextEditorContent-Dstovi0m.js} +47 -47
  30. package/dist/{SaveBlockDialog-CWLrly6l.js → SaveBlockDialog-vuwvoi-d.js} +86 -86
  31. package/dist/{cdn/chunks/SavedBlocksBrowserModal-BPYcRoGa.js → SavedBlocksBrowserModal-DUJm0dOv.js} +135 -132
  32. package/dist/{SavedBlocksPanels-BE1N9rNZ.js → SavedBlocksPanels-BiMXQ5lY.js} +9 -9
  33. package/dist/{SavedBlocksPickBar-Dwl94xhP.js → SavedBlocksPickBar-CAstZfG7.js} +15 -15
  34. package/dist/TemplateSettings-Baar78_s.js +294 -0
  35. package/dist/TestEmailModal-Bl_GHdrN.js +212 -0
  36. package/dist/{TestEmailPanel-DaFjP9QK.js → TestEmailPanel-CpTBF7B5.js} +4 -4
  37. package/dist/TitleEditor-DkbEDAZB.js +202 -0
  38. package/dist/ToggleSwitch-R3wCCYE6.js +43 -0
  39. package/dist/Toolbar-bOZ_eq7X.js +3711 -0
  40. package/dist/{TplModal-DLMssVlt.js → TplModal-wk2gLa7_.js} +17 -17
  41. package/dist/{VersionHistoryMenu-BkbYUs0Q.js → VersionHistoryMenu-BnP0EyLl.js} +39 -39
  42. package/dist/{VersionHistoryPanels-DP7HaYWv.js → VersionHistoryPanels-Cq2rFKIX.js} +5 -5
  43. package/dist/VersionPreviewBanner-BPP939cD.js +37 -0
  44. package/dist/WrapperBlock-cWT_nZgQ.js +44 -0
  45. package/dist/{blockTypeIcons-BHjlPnPf.js → blockTypeIcons-BUyPZ7Su.js} +7 -7
  46. package/dist/bundle-stats.json +8 -8
  47. package/dist/{cdn/chunks/ca-CD-Kt1qz.js → ca-DOuIxWRv.js} +114 -2
  48. package/dist/cdn/chunks/AiAltTextPopover-Cnc_kUmb.js +107 -0
  49. package/dist/cdn/chunks/AiAltTextPopover-Cnc_kUmb.js.map +1 -0
  50. package/dist/cdn/chunks/{AiAltTextReview-BGLLSKLm.js → AiAltTextReview-DPeSY-7r.js} +70 -68
  51. package/dist/cdn/chunks/AiAltTextReview-DPeSY-7r.js.map +1 -0
  52. package/dist/cdn/chunks/AiChatPanel-By8Uo1nH.js +487 -0
  53. package/dist/cdn/chunks/AiChatPanel-By8Uo1nH.js.map +1 -0
  54. package/dist/cdn/chunks/{AiPanels-0wBarZSH.js → AiPanels-BblCSkQy.js} +11 -11
  55. package/dist/cdn/chunks/{AiPanels-0wBarZSH.js.map → AiPanels-BblCSkQy.js.map} +1 -1
  56. package/dist/cdn/chunks/{AiRewriteMenu-qf-cfEpy.js → AiRewriteMenu-C4btyN4W.js} +79 -79
  57. package/dist/cdn/chunks/AiRewriteMenu-C4btyN4W.js.map +1 -0
  58. package/dist/cdn/chunks/BlockIssueBadge-D3Plo_wt.js +34 -0
  59. package/dist/cdn/chunks/BlockIssueBadge-D3Plo_wt.js.map +1 -0
  60. package/dist/cdn/chunks/BlockPreviewCanvas-CTKmBPsq.js +142 -0
  61. package/dist/cdn/chunks/{BlockPreviewCanvas-DGBh6mqe.js.map → BlockPreviewCanvas-CTKmBPsq.js.map} +1 -1
  62. package/dist/cdn/chunks/{CloudHeaderExtras-BMNK_F9p.js → CloudHeaderExtras-BtqdN777.js} +4 -4
  63. package/dist/cdn/chunks/{CloudHeaderExtras-BMNK_F9p.js.map → CloudHeaderExtras-BtqdN777.js.map} +1 -1
  64. package/dist/cdn/chunks/{CloudPanels-JMWIoVWh.js → CloudPanels-COU26R83.js} +45 -45
  65. package/dist/cdn/chunks/{CloudPanels-JMWIoVWh.js.map → CloudPanels-COU26R83.js.map} +1 -1
  66. package/dist/cdn/chunks/CollaborationNotices-DraFUhyo.js +67 -0
  67. package/dist/cdn/chunks/CollaborationNotices-DraFUhyo.js.map +1 -0
  68. package/dist/cdn/chunks/{CollaboratorBar-CXByAoUz.js → CollaboratorBar-0OEH3hrj.js} +17 -17
  69. package/dist/cdn/chunks/{CollaboratorBar-CXByAoUz.js.map → CollaboratorBar-0OEH3hrj.js.map} +1 -1
  70. package/dist/cdn/chunks/CommentsPanel-tZZswofV.js +18 -0
  71. package/dist/cdn/chunks/{CommentsPanel-DoJnKLXI.js.map → CommentsPanel-tZZswofV.js.map} +1 -1
  72. package/dist/cdn/chunks/CommentsSidebar-7Hfl3Hdj.js +496 -0
  73. package/dist/cdn/chunks/CommentsSidebar-7Hfl3Hdj.js.map +1 -0
  74. package/dist/cdn/chunks/{CountdownBlock-BqRw147R.js → CountdownBlock-CjMhMhnv.js} +22 -22
  75. package/dist/cdn/chunks/{CountdownBlock-BqRw147R.js.map → CountdownBlock-CjMhMhnv.js.map} +1 -1
  76. package/dist/cdn/chunks/CountdownToolbar-CNgsNL5-.js +260 -0
  77. package/dist/cdn/chunks/CountdownToolbar-CNgsNL5-.js.map +1 -0
  78. package/dist/cdn/chunks/{IssuesPanel-C7LfxaAY.js → IssuesPanel-Duic0mIs.js} +133 -121
  79. package/dist/cdn/chunks/IssuesPanel-Duic0mIs.js.map +1 -0
  80. package/dist/cdn/chunks/LanguageMenu-B1Aue_lf.js +359 -0
  81. package/dist/cdn/chunks/LanguageMenu-B1Aue_lf.js.map +1 -0
  82. package/dist/cdn/chunks/{LoadingTrack-CZuLTazv.js → LoadingTrack-DUYcDHOV.js} +2 -2
  83. package/dist/cdn/chunks/{LoadingTrack-CZuLTazv.js.map → LoadingTrack-DUYcDHOV.js.map} +1 -1
  84. package/dist/cdn/chunks/LocaleNotices-8J2DRWeg.js +47 -0
  85. package/dist/cdn/chunks/LocaleNotices-8J2DRWeg.js.map +1 -0
  86. package/dist/{LogicTagInsertButton-CfscnwCn.js → cdn/chunks/LogicTagInsertButton-Bhvi0nWz.js} +422 -449
  87. package/dist/cdn/chunks/LogicTagInsertButton-Bhvi0nWz.js.map +1 -0
  88. package/dist/cdn/chunks/{MediaEditModal-Cpcod6_U.js → MediaEditModal-Dz972UFx.js} +421 -421
  89. package/dist/cdn/chunks/MediaEditModal-Dz972UFx.js.map +1 -0
  90. package/dist/cdn/chunks/{MediaPanels-BIdcW_1f.js → MediaPanels-C6Hqtp1H.js} +5 -5
  91. package/dist/cdn/chunks/{MediaPanels-BIdcW_1f.js.map → MediaPanels-C6Hqtp1H.js.map} +1 -1
  92. package/dist/cdn/chunks/{MergeTagInput-BvWg8o5E.js → MergeTagInput-CrhZm-AW.js} +28 -28
  93. package/dist/cdn/chunks/{MergeTagInput-BvWg8o5E.js.map → MergeTagInput-CrhZm-AW.js.map} +1 -1
  94. package/dist/cdn/chunks/{MergeTagModeToggle-BgKEVUtV.js → MergeTagModeToggle-CWVtXLYa.js} +52 -52
  95. package/dist/cdn/chunks/MergeTagModeToggle-CWVtXLYa.js.map +1 -0
  96. package/dist/cdn/chunks/MergeTagTextarea-hTIBwX0F.js +128 -0
  97. package/dist/cdn/chunks/MergeTagTextarea-hTIBwX0F.js.map +1 -0
  98. package/dist/cdn/chunks/ParagraphEditor-B2UU1Q5I.js +660 -0
  99. package/dist/cdn/chunks/ParagraphEditor-B2UU1Q5I.js.map +1 -0
  100. package/dist/cdn/chunks/{RestoreVersionDialog-CjOdD2xj.js → RestoreVersionDialog-C1Y5Ewo_.js} +22 -22
  101. package/dist/cdn/chunks/{RestoreVersionDialog-CjOdD2xj.js.map → RestoreVersionDialog-C1Y5Ewo_.js.map} +1 -1
  102. package/dist/cdn/chunks/{RichTextEditorContent-DNjR_sNN.js → RichTextEditorContent-up4AqL7D.js} +44 -44
  103. package/dist/cdn/chunks/{RichTextEditorContent-DNjR_sNN.js.map → RichTextEditorContent-up4AqL7D.js.map} +1 -1
  104. package/dist/cdn/chunks/{SaveBlockDialog-CUhpawq0.js → SaveBlockDialog-B9lwEP_T.js} +77 -77
  105. package/dist/cdn/chunks/{SaveBlockDialog-CUhpawq0.js.map → SaveBlockDialog-B9lwEP_T.js.map} +1 -1
  106. package/dist/{SavedBlocksBrowserModal-CE8n4EBS.js → cdn/chunks/SavedBlocksBrowserModal-fAeHUyxb.js} +103 -106
  107. package/dist/cdn/chunks/{SavedBlocksBrowserModal-BPYcRoGa.js.map → SavedBlocksBrowserModal-fAeHUyxb.js.map} +1 -1
  108. package/dist/cdn/chunks/{SavedBlocksPanels-C6--Bc81.js → SavedBlocksPanels-DRDTLDyZ.js} +9 -9
  109. package/dist/cdn/chunks/{SavedBlocksPanels-C6--Bc81.js.map → SavedBlocksPanels-DRDTLDyZ.js.map} +1 -1
  110. package/dist/cdn/chunks/{SavedBlocksPickBar-DUavxpbU.js → SavedBlocksPickBar-B6b5z-o3.js} +16 -16
  111. package/dist/cdn/chunks/{SavedBlocksPickBar-DUavxpbU.js.map → SavedBlocksPickBar-B6b5z-o3.js.map} +1 -1
  112. package/dist/cdn/chunks/TemplateSettings-CWUpUKJb.js +266 -0
  113. package/dist/cdn/chunks/TemplateSettings-CWUpUKJb.js.map +1 -0
  114. package/dist/cdn/chunks/TestEmailModal-DQxnW5Q5.js +212 -0
  115. package/dist/cdn/chunks/TestEmailModal-DQxnW5Q5.js.map +1 -0
  116. package/dist/cdn/chunks/{TestEmailPanel-CcUpEpAn.js → TestEmailPanel-BcO_-16H.js} +5 -5
  117. package/dist/cdn/chunks/{TestEmailPanel-CcUpEpAn.js.map → TestEmailPanel-BcO_-16H.js.map} +1 -1
  118. package/dist/cdn/chunks/TitleEditor-pmycpmTd.js +202 -0
  119. package/dist/cdn/chunks/TitleEditor-pmycpmTd.js.map +1 -0
  120. package/dist/cdn/chunks/ToggleSwitch-BSkySwA1.js +45 -0
  121. package/dist/cdn/chunks/ToggleSwitch-BSkySwA1.js.map +1 -0
  122. package/dist/cdn/chunks/Toolbar-BlWVQRcA.js +3626 -0
  123. package/dist/cdn/chunks/Toolbar-BlWVQRcA.js.map +1 -0
  124. package/dist/cdn/chunks/{TplModal-CFPDgbwQ.js → TplModal-ClSSGX7a.js} +20 -20
  125. package/dist/cdn/chunks/{TplModal-CFPDgbwQ.js.map → TplModal-ClSSGX7a.js.map} +1 -1
  126. package/dist/cdn/chunks/{VersionHistoryMenu-BYlLRvRJ.js → VersionHistoryMenu-CZury5gU.js} +33 -33
  127. package/dist/cdn/chunks/{VersionHistoryMenu-BYlLRvRJ.js.map → VersionHistoryMenu-CZury5gU.js.map} +1 -1
  128. package/dist/cdn/chunks/{VersionHistoryPanels-C6SOVoiT.js → VersionHistoryPanels-B8GPBKMq.js} +6 -6
  129. package/dist/cdn/chunks/{VersionHistoryPanels-C6SOVoiT.js.map → VersionHistoryPanels-B8GPBKMq.js.map} +1 -1
  130. package/dist/cdn/chunks/VersionPreviewBanner-C4Ji8nu4.js +39 -0
  131. package/dist/cdn/chunks/VersionPreviewBanner-C4Ji8nu4.js.map +1 -0
  132. package/dist/cdn/chunks/WrapperBlock-BoUflYwY.js +46 -0
  133. package/dist/cdn/chunks/WrapperBlock-BoUflYwY.js.map +1 -0
  134. package/dist/cdn/chunks/{blockTypeIcons-D7FW7Ypo.js → blockTypeIcons-Cc6RJ27V.js} +5 -5
  135. package/dist/cdn/chunks/{blockTypeIcons-D7FW7Ypo.js.map → blockTypeIcons-Cc6RJ27V.js.map} +1 -1
  136. package/dist/{ca-CD-Kt1qz.js → cdn/chunks/ca-DOuIxWRv.js} +116 -0
  137. package/dist/cdn/chunks/ca-DOuIxWRv.js.map +1 -0
  138. package/dist/cdn/chunks/composables-C1KU4ZHw.js +3039 -0
  139. package/dist/cdn/chunks/composables-C1KU4ZHw.js.map +1 -0
  140. package/dist/cdn/chunks/{createCloudRuntime-Cth2JCEh.js → createCloudRuntime-C2Zs5F1O.js} +75 -73
  141. package/dist/cdn/chunks/createCloudRuntime-C2Zs5F1O.js.map +1 -0
  142. package/dist/{de-CeFJ6wbM.js → cdn/chunks/de-DaOUfYBX.js} +116 -0
  143. package/dist/cdn/chunks/de-DaOUfYBX.js.map +1 -0
  144. package/dist/cdn/chunks/{dist-8ym3y-pH.js → dist-BzXULHvI.js} +48 -48
  145. package/dist/cdn/chunks/{dist-8ym3y-pH.js.map → dist-BzXULHvI.js.map} +1 -1
  146. package/dist/cdn/chunks/{dist-BMzNabtD.js → dist-DqGgijFI.js} +114 -114
  147. package/dist/cdn/chunks/{dist-BMzNabtD.js.map → dist-DqGgijFI.js.map} +1 -1
  148. package/dist/cdn/chunks/{draggable-Du8AUMFT.js → draggable-DepKdldn.js} +1491 -1486
  149. package/dist/cdn/chunks/draggable-DepKdldn.js.map +1 -0
  150. package/dist/cdn/chunks/{editor-modal-CyCe560f.js → editor-modal-erQEOHZN.js} +781 -781
  151. package/dist/cdn/chunks/{editor-modal-CyCe560f.js.map → editor-modal-erQEOHZN.js.map} +1 -1
  152. package/dist/cdn/chunks/en-B6tLGRHq.js +1 -0
  153. package/dist/{en-D14i5nFh.js → cdn/chunks/en-C0pHHMiR.js} +116 -0
  154. package/dist/cdn/chunks/en-C0pHHMiR.js.map +1 -0
  155. package/dist/{es-zDacbMhs.js → cdn/chunks/es-CxyEKr6n.js} +116 -0
  156. package/dist/cdn/chunks/es-CxyEKr6n.js.map +1 -0
  157. package/dist/cdn/chunks/{extensions-CFF2KWy-.js → extensions-DcMKZpzh.js} +59 -59
  158. package/dist/cdn/chunks/{extensions-CFF2KWy-.js.map → extensions-DcMKZpzh.js.map} +1 -1
  159. package/dist/{fr-CSgYtjOd.js → cdn/chunks/fr-CYbamiI6.js} +116 -0
  160. package/dist/cdn/chunks/fr-CYbamiI6.js.map +1 -0
  161. package/dist/cdn/chunks/{icons-okSPsLOa.js → icons-Da9GKjPx.js} +188 -147
  162. package/dist/cdn/chunks/icons-Da9GKjPx.js.map +1 -0
  163. package/dist/{ja-B7H3ID8O.js → cdn/chunks/ja-DfaIAoGI.js} +116 -0
  164. package/dist/cdn/chunks/ja-DfaIAoGI.js.map +1 -0
  165. package/dist/cdn/chunks/keys-CoQtCqNv.js +11 -0
  166. package/dist/cdn/chunks/keys-CoQtCqNv.js.map +1 -0
  167. package/dist/cdn/chunks/languageName-DEEOhDWI.js +12 -0
  168. package/dist/cdn/chunks/languageName-DEEOhDWI.js.map +1 -0
  169. package/dist/{nl-176ySmc5.js → cdn/chunks/nl-DkrB-VKZ.js} +116 -0
  170. package/dist/cdn/chunks/nl-DkrB-VKZ.js.map +1 -0
  171. package/dist/cdn/chunks/normalizeMergeTagMarkup-cC32Ox6A.js +290 -0
  172. package/dist/cdn/chunks/normalizeMergeTagMarkup-cC32Ox6A.js.map +1 -0
  173. package/dist/cdn/chunks/noticeTones-D7BPu-Le.js +16 -0
  174. package/dist/cdn/chunks/noticeTones-D7BPu-Le.js.map +1 -0
  175. package/dist/cdn/chunks/plural-CyxrJXL1.js +17 -0
  176. package/dist/cdn/chunks/plural-CyxrJXL1.js.map +1 -0
  177. package/dist/{preRenderCustomBlocks--_xc0XK3.js → cdn/chunks/preRenderCustomBlocks-f7GEKdvw.js} +5 -3
  178. package/dist/cdn/chunks/{preRenderCustomBlocks-BcXIz7oJ.js.map → preRenderCustomBlocks-f7GEKdvw.js.map} +1 -1
  179. package/dist/{pt-BR-dDlTwX18.js → cdn/chunks/pt-BR-CY5Ye7eP.js} +116 -0
  180. package/dist/cdn/chunks/pt-BR-CY5Ye7eP.js.map +1 -0
  181. package/dist/cdn/chunks/sanitizeHtml-WTfz9lZd.js +61 -0
  182. package/dist/cdn/chunks/sanitizeHtml-WTfz9lZd.js.map +1 -0
  183. package/dist/cdn/chunks/socialIcons-DeCYorUT.js +2638 -0
  184. package/dist/cdn/chunks/socialIcons-DeCYorUT.js.map +1 -0
  185. package/dist/cdn/chunks/{src-DEd87i_U.js → src-A_cKeTM_.js} +618 -461
  186. package/dist/cdn/chunks/src-A_cKeTM_.js.map +1 -0
  187. package/dist/cdn/chunks/src-BQUv2CYU.js +2606 -0
  188. package/dist/cdn/chunks/src-BQUv2CYU.js.map +1 -0
  189. package/dist/cdn/chunks/src-BWX_xVxO.js +671 -0
  190. package/dist/cdn/chunks/src-BWX_xVxO.js.map +1 -0
  191. package/dist/{styleConstants-B8xVRiwX.js → cdn/chunks/styleConstants-CgiNKdnc.js} +7 -5
  192. package/dist/cdn/chunks/styleConstants-CgiNKdnc.js.map +1 -0
  193. package/dist/cdn/chunks/templateSettingsFields-cjlP-jdw.js.map +1 -1
  194. package/dist/cdn/chunks/{tiptap-CbiTlECY.js → tiptap-Dipw_zOQ.js} +40 -40
  195. package/dist/cdn/chunks/{tiptap-CbiTlECY.js.map → tiptap-Dipw_zOQ.js.map} +1 -1
  196. package/dist/cdn/chunks/{useCloudI18n-DY8_-ETE.js → useCloudI18n-Cc5NZqiI.js} +3 -3
  197. package/dist/cdn/chunks/{useCloudI18n-DY8_-ETE.js.map → useCloudI18n-Cc5NZqiI.js.map} +1 -1
  198. package/dist/cdn/chunks/useEditorRoot-D_LuZ_hE.js +9 -0
  199. package/dist/cdn/chunks/{useEditorRoot-vjZJwKrV.js.map → useEditorRoot-D_LuZ_hE.js.map} +1 -1
  200. package/dist/cdn/chunks/{useI18n-D8pY4LTq.js → useI18n-BnJYydPv.js} +3 -3
  201. package/dist/cdn/chunks/{useI18n-D8pY4LTq.js.map → useI18n-BnJYydPv.js.map} +1 -1
  202. package/dist/cdn/chunks/useLocalizedDisplay-aGfnO90D.js +33 -0
  203. package/dist/cdn/chunks/useLocalizedDisplay-aGfnO90D.js.map +1 -0
  204. package/dist/cdn/chunks/{useLogicTag-DBJDtpKA.js → useLogicTag-DtYe8HIq.js} +5 -5
  205. package/dist/cdn/chunks/{useLogicTag-DBJDtpKA.js.map → useLogicTag-DtYe8HIq.js.map} +1 -1
  206. package/dist/cdn/chunks/{useMergeTag-B-aG--s1.js → useMergeTag-B8ULmsnp.js} +6 -6
  207. package/dist/cdn/chunks/{useMergeTag-B-aG--s1.js.map → useMergeTag-B8ULmsnp.js.map} +1 -1
  208. package/dist/cdn/chunks/usePopoverPosition-BWAXWeBv.js +78 -0
  209. package/dist/cdn/chunks/usePopoverPosition-BWAXWeBv.js.map +1 -0
  210. package/dist/cdn/chunks/{useScrollToBlock-vjQ0fe-L.js → useScrollToBlock-Ct1AwLD-.js} +5 -5
  211. package/dist/cdn/chunks/useScrollToBlock-Ct1AwLD-.js.map +1 -0
  212. package/dist/cdn/chunks/{withCurrentFont-hZTvYBHO.js → withCurrentFont-MK8ga9q9.js} +2 -2
  213. package/dist/cdn/chunks/{withCurrentFont-hZTvYBHO.js.map → withCurrentFont-MK8ga9q9.js.map} +1 -1
  214. package/dist/cdn/editor.css +1 -1
  215. package/dist/cdn/editor.js +2189 -1495
  216. package/dist/cdn/editor.js.map +1 -1
  217. package/dist/{check-BZ8o0eet.js → check-XMnOOIEC.js} +1 -1
  218. package/dist/{chevron-down-DfAAfILv.js → chevron-down-DmamTEWQ.js} +1 -1
  219. package/dist/{chevron-right-Bk4mGdr7.js → chevron-right-BEFXOH27.js} +1 -1
  220. package/dist/{chevron-up-MhUf_azW.js → chevron-up-Dw7woXj8.js} +1 -1
  221. package/dist/{circle-alert-CShJwVFv.js → circle-alert-BTKC9vkq.js} +1 -1
  222. package/dist/{clock-CTfD6OCt.js → clock-BVT5u2uG.js} +1 -1
  223. package/dist/composables-CMIrGXJ1.js +4517 -0
  224. package/dist/{createCloudRuntime-DCgO4A1r.js → createCloudRuntime-DGV5a5Af.js} +54 -52
  225. package/dist/{createLucideIcon-CvhTA2KG.js → createLucideIcon-CgDE3xAR.js} +16 -16
  226. package/dist/{cdn/chunks/de-CeFJ6wbM.js → de-DaOUfYBX.js} +114 -2
  227. package/dist/{dist-ByCWA2Tv.js → dist-0alKVRc_.js} +101 -101
  228. package/dist/{dist-Cy8I5scI.js → dist-54VCNoC0.js} +2 -2
  229. package/dist/dist-6DU0me3E.js +4 -0
  230. package/dist/{dist-p3wymUDt.js → dist-B8dY8drK.js} +2 -2
  231. package/dist/{dist-Dd5MU2Ev.js → dist-B9a7iVye.js} +2 -2
  232. package/dist/{dist-V7W1UhVr.js → dist-BWflWcpW.js} +2 -2
  233. package/dist/{dist-D6fZec6r.js → dist-C3hu_C3w.js} +2 -2
  234. package/dist/{dist-CVy-7PHQ.js → dist-CX7skkvG.js} +48 -48
  235. package/dist/dist-CcOn7WCo.js +4 -0
  236. package/dist/dist-Cdkm20M6.js +2542 -0
  237. package/dist/{dist-BS5uKktL.js → dist-ChOb5XHW.js} +2 -2
  238. package/dist/{dist-BF5zEHop.js → dist-DZ3X-uB8.js} +2 -2
  239. package/dist/{dist-CWSG7Kj0.js → dist-D_XrUEET.js} +5 -5
  240. package/dist/{dist-txQLT2sF.js → dist-TAv500j6.js} +2 -2
  241. package/dist/{dist-D6cMdrfG.js → dist-fqSers8_.js} +55 -55
  242. package/dist/{editor-modal-zaZHcmlO.js → editor-modal-BeX6otLk.js} +953 -952
  243. package/dist/{cdn/chunks/en-D14i5nFh.js → en-C0pHHMiR.js} +114 -2
  244. package/dist/en-Do0SU6tR.js +1 -0
  245. package/dist/{cdn/chunks/es-zDacbMhs.js → es-CxyEKr6n.js} +114 -2
  246. package/dist/{extensions-fo_c-vqf.js → extensions-BJ184osp.js} +173 -173
  247. package/dist/{eye-7W4t5e0Q.js → eye-ByMgHeA_.js} +1 -1
  248. package/dist/{cdn/chunks/fr-CSgYtjOd.js → fr-CYbamiI6.js} +114 -2
  249. package/dist/{image-BDiRFzSd.js → image-Ch8tR35K.js} +1 -1
  250. package/dist/index.d.ts +182 -14
  251. package/dist/{info-Cxi3-Kh9.js → info-DzSD-Wpk.js} +1 -1
  252. package/dist/{cdn/chunks/ja-B7H3ID8O.js → ja-DfaIAoGI.js} +114 -2
  253. package/dist/keys-BCqskl51.js +9 -0
  254. package/dist/languageName-DEEOhDWI.js +10 -0
  255. package/dist/{link-ju_2Cmir.js → link-oDn9AR2w.js} +1 -1
  256. package/dist/{list-DYZJf0aZ.js → list-C5t07dp8.js} +1 -1
  257. package/dist/{loader-circle-BZRD0a4I.js → loader-circle-k6xvKgUB.js} +1 -1
  258. package/dist/{message-circle-DuEw4Zfx.js → message-circle-C23R6OJR.js} +1 -1
  259. package/dist/{cdn/chunks/nl-176ySmc5.js → nl-DkrB-VKZ.js} +114 -2
  260. package/dist/normalizeMergeTagMarkup-CUCo7B5X.js +288 -0
  261. package/dist/noticeTones-D7BPu-Le.js +14 -0
  262. package/dist/{package-CePMr2kK.js → package-C90eQ7NU.js} +1 -1
  263. package/dist/{pencil-D3aFCL7c.js → pencil-BK7GrQuA.js} +1 -1
  264. package/dist/plural-CyxrJXL1.js +15 -0
  265. package/dist/plus-Cr0Mis63.js +13 -0
  266. package/dist/{cdn/chunks/preRenderCustomBlocks-BcXIz7oJ.js → preRenderCustomBlocks-Bs3N9no-.js} +4 -6
  267. package/dist/{cdn/chunks/pt-BR-dDlTwX18.js → pt-BR-CY5Ye7eP.js} +114 -2
  268. package/dist/{refresh-cw-xnro7_Sk.js → refresh-cw-_ZLOIEvA.js} +2 -12
  269. package/dist/rotate-ccw-CB5wsHwv.js +13 -0
  270. package/dist/{runtime-dom.esm-bundler-BURR-bj5.js → runtime-dom.esm-bundler-DlHp8xgy.js} +154 -154
  271. package/dist/sanitizeHtml-2rjV0r-6.js +962 -0
  272. package/dist/{search-CDrstRBv.js → search-BmrQNox8.js} +1 -1
  273. package/dist/{send-DROkPOaX.js → send-blAsIBBg.js} +1 -1
  274. package/dist/{smartphone-Bx6u_tjn.js → smartphone-BPpWYrwV.js} +1 -1
  275. package/dist/socialIcons-TFiOkpoU.js +2705 -0
  276. package/dist/{sparkles-CdaTtvoz.js → sparkles-OqIxrNp-.js} +1 -1
  277. package/dist/{square-BbCROH_f.js → square-BP-V7iT-.js} +1 -1
  278. package/dist/style.css +1 -1
  279. package/dist/{cdn/chunks/styleConstants-B8xVRiwX.js → styleConstants-CgiNKdnc.js} +5 -7
  280. package/dist/templatical-editor.js +2438 -1752
  281. package/dist/{text-align-start-CGacJ9Vw.js → text-align-start-4mwX2o-F.js} +13 -13
  282. package/dist/{trash-DxCd7zIy.js → trash-B99WixTA.js} +1 -1
  283. package/dist/{triangle-alert-7_oaitpf.js → triangle-alert-CHMiDkHa.js} +1 -1
  284. package/dist/{upload-DuFEOi_0.js → upload-Cp8o-hrN.js} +1 -1
  285. package/dist/{useCloudI18n-DEMmUKuO.js → useCloudI18n-Dh2iydo1.js} +4 -4
  286. package/dist/useEditorRoot-DY3mgcHm.js +7 -0
  287. package/dist/{useI18n-BBrHTdu8.js → useI18n-CgtvtF4C.js} +4 -4
  288. package/dist/useLocalizedDisplay-DNNwDRxL.js +31 -0
  289. package/dist/{useLogicTag-ZPC39rfH.js → useLogicTag-BXXXQQmi.js} +4 -4
  290. package/dist/{useMergeTag-BQ4qqWpQ.js → useMergeTag-C9Okr87y.js} +5 -5
  291. package/dist/usePopoverPosition-VDQjyX_A.js +76 -0
  292. package/dist/{useScrollToBlock-BSyAV4pk.js → useScrollToBlock-B35ObCGK.js} +5 -5
  293. package/dist/{vue.runtime.esm-bundler-CnEeTfhs.js → vue.runtime.esm-bundler-BJXc_Mri.js} +1373 -1368
  294. package/dist/withCurrentFont-DJiQqZzL.js +18 -0
  295. package/dist/{x-BpfG7v9g.js → x-BIBStNMS.js} +1 -1
  296. package/package.json +21 -21
  297. package/dist/AiAltTextPopover-DawbUywc.js +0 -105
  298. package/dist/AiChatPanel-CupPhmsN.js +0 -548
  299. package/dist/BlockIssueBadge-BxpDy3u-.js +0 -33
  300. package/dist/BlockPreviewCanvas-B-4bmJ3t.js +0 -140
  301. package/dist/CollaborationNotices-CTw4JThq.js +0 -75
  302. package/dist/CommentsPanel-DwwFuh1h.js +0 -16
  303. package/dist/CommentsSidebar-9ZfiC2DO.js +0 -500
  304. package/dist/CountdownToolbar-BqoYzf_6.js +0 -197
  305. package/dist/IssuesPanel-4ykrf1ax.js +0 -359
  306. package/dist/MergeTagTextarea-CPFEjJZd.js +0 -69
  307. package/dist/ParagraphEditor-CWXfurGh.js +0 -796
  308. package/dist/TemplateSettings-CS0f1Ues.js +0 -236
  309. package/dist/TestEmailModal-DBD0X5nV.js +0 -209
  310. package/dist/TitleEditor-DSqtle77.js +0 -198
  311. package/dist/ToggleSwitch-JykPyD_8.js +0 -36
  312. package/dist/Toolbar-BZPFfKrf.js +0 -3145
  313. package/dist/VersionPreviewBanner-DECaBwLq.js +0 -37
  314. package/dist/WrapperBlock-BsJv_Fiw.js +0 -44
  315. package/dist/cdn/chunks/AiAltTextPopover-SEEjkd-I.js +0 -106
  316. package/dist/cdn/chunks/AiAltTextPopover-SEEjkd-I.js.map +0 -1
  317. package/dist/cdn/chunks/AiAltTextReview-BGLLSKLm.js.map +0 -1
  318. package/dist/cdn/chunks/AiChatPanel-DKDAaBNi.js +0 -474
  319. package/dist/cdn/chunks/AiChatPanel-DKDAaBNi.js.map +0 -1
  320. package/dist/cdn/chunks/AiRewriteMenu-qf-cfEpy.js.map +0 -1
  321. package/dist/cdn/chunks/BlockIssueBadge-jdf91-nk.js +0 -34
  322. package/dist/cdn/chunks/BlockIssueBadge-jdf91-nk.js.map +0 -1
  323. package/dist/cdn/chunks/BlockPreviewCanvas-DGBh6mqe.js +0 -142
  324. package/dist/cdn/chunks/CollaborationNotices-Bsf1rGW9.js +0 -77
  325. package/dist/cdn/chunks/CollaborationNotices-Bsf1rGW9.js.map +0 -1
  326. package/dist/cdn/chunks/CommentsPanel-DoJnKLXI.js +0 -18
  327. package/dist/cdn/chunks/CommentsSidebar-CUtgvdBC.js +0 -470
  328. package/dist/cdn/chunks/CommentsSidebar-CUtgvdBC.js.map +0 -1
  329. package/dist/cdn/chunks/CountdownToolbar-xobieKoU.js +0 -199
  330. package/dist/cdn/chunks/CountdownToolbar-xobieKoU.js.map +0 -1
  331. package/dist/cdn/chunks/IssuesPanel-C7LfxaAY.js.map +0 -1
  332. package/dist/cdn/chunks/LogicTagInsertButton-BIi05UQu.js +0 -1051
  333. package/dist/cdn/chunks/LogicTagInsertButton-BIi05UQu.js.map +0 -1
  334. package/dist/cdn/chunks/MediaEditModal-Cpcod6_U.js.map +0 -1
  335. package/dist/cdn/chunks/MergeTagModeToggle-BgKEVUtV.js.map +0 -1
  336. package/dist/cdn/chunks/MergeTagTextarea-tBz8McZf.js +0 -71
  337. package/dist/cdn/chunks/MergeTagTextarea-tBz8McZf.js.map +0 -1
  338. package/dist/cdn/chunks/ParagraphEditor-B3Rj_cWF.js +0 -631
  339. package/dist/cdn/chunks/ParagraphEditor-B3Rj_cWF.js.map +0 -1
  340. package/dist/cdn/chunks/TemplateSettings-CKtI-dof.js +0 -208
  341. package/dist/cdn/chunks/TemplateSettings-CKtI-dof.js.map +0 -1
  342. package/dist/cdn/chunks/TestEmailModal-CDQTgESD.js +0 -209
  343. package/dist/cdn/chunks/TestEmailModal-CDQTgESD.js.map +0 -1
  344. package/dist/cdn/chunks/TitleEditor-Cob7RLyK.js +0 -198
  345. package/dist/cdn/chunks/TitleEditor-Cob7RLyK.js.map +0 -1
  346. package/dist/cdn/chunks/ToggleSwitch-J7Vwhvha.js +0 -38
  347. package/dist/cdn/chunks/ToggleSwitch-J7Vwhvha.js.map +0 -1
  348. package/dist/cdn/chunks/Toolbar-CdpsvNOR.js +0 -3061
  349. package/dist/cdn/chunks/Toolbar-CdpsvNOR.js.map +0 -1
  350. package/dist/cdn/chunks/VersionPreviewBanner-Dvg0ZfAW.js +0 -39
  351. package/dist/cdn/chunks/VersionPreviewBanner-Dvg0ZfAW.js.map +0 -1
  352. package/dist/cdn/chunks/WrapperBlock-C7Md56IT.js +0 -46
  353. package/dist/cdn/chunks/WrapperBlock-C7Md56IT.js.map +0 -1
  354. package/dist/cdn/chunks/ca-CD-Kt1qz.js.map +0 -1
  355. package/dist/cdn/chunks/createCloudRuntime-Cth2JCEh.js.map +0 -1
  356. package/dist/cdn/chunks/de-CeFJ6wbM.js.map +0 -1
  357. package/dist/cdn/chunks/draggable-Du8AUMFT.js.map +0 -1
  358. package/dist/cdn/chunks/en-D14i5nFh.js.map +0 -1
  359. package/dist/cdn/chunks/en-TIqv4ag3.js +0 -1
  360. package/dist/cdn/chunks/es-zDacbMhs.js.map +0 -1
  361. package/dist/cdn/chunks/fr-CSgYtjOd.js.map +0 -1
  362. package/dist/cdn/chunks/icons-okSPsLOa.js.map +0 -1
  363. package/dist/cdn/chunks/ja-B7H3ID8O.js.map +0 -1
  364. package/dist/cdn/chunks/keys-CUj6UA38.js +0 -11
  365. package/dist/cdn/chunks/keys-CUj6UA38.js.map +0 -1
  366. package/dist/cdn/chunks/nl-176ySmc5.js.map +0 -1
  367. package/dist/cdn/chunks/normalizeMergeTagMarkup-C_KlfSW4.js +0 -198
  368. package/dist/cdn/chunks/normalizeMergeTagMarkup-C_KlfSW4.js.map +0 -1
  369. package/dist/cdn/chunks/pt-BR-dDlTwX18.js.map +0 -1
  370. package/dist/cdn/chunks/sanitizeHtml-CN85EDrO.js +0 -72
  371. package/dist/cdn/chunks/sanitizeHtml-CN85EDrO.js.map +0 -1
  372. package/dist/cdn/chunks/socialIcons-jsTDmkbb.js +0 -2008
  373. package/dist/cdn/chunks/socialIcons-jsTDmkbb.js.map +0 -1
  374. package/dist/cdn/chunks/src-C7bkofBL.js +0 -647
  375. package/dist/cdn/chunks/src-C7bkofBL.js.map +0 -1
  376. package/dist/cdn/chunks/src-DEd87i_U.js.map +0 -1
  377. package/dist/cdn/chunks/src-DwWrYnUj.js +0 -1404
  378. package/dist/cdn/chunks/src-DwWrYnUj.js.map +0 -1
  379. package/dist/cdn/chunks/styleConstants-B8xVRiwX.js.map +0 -1
  380. package/dist/cdn/chunks/useEditorCore-BrY66C2y.js +0 -2582
  381. package/dist/cdn/chunks/useEditorCore-BrY66C2y.js.map +0 -1
  382. package/dist/cdn/chunks/useEditorRoot-vjZJwKrV.js +0 -9
  383. package/dist/cdn/chunks/usePopoverPosition-DSMtmu2W.js +0 -70
  384. package/dist/cdn/chunks/usePopoverPosition-DSMtmu2W.js.map +0 -1
  385. package/dist/cdn/chunks/useScrollToBlock-vjQ0fe-L.js.map +0 -1
  386. package/dist/dist-CKi_npZM.js +0 -1344
  387. package/dist/dist-DyFArF_G.js +0 -4
  388. package/dist/dist-pA3ooG6N.js +0 -4
  389. package/dist/en-Db76vJbY.js +0 -1
  390. package/dist/keys-BgRERHzu.js +0 -9
  391. package/dist/normalizeMergeTagMarkup-CELnOlgK.js +0 -196
  392. package/dist/sanitizeHtml-BzfzpYJY.js +0 -942
  393. package/dist/socialIcons-D7MGsg0d.js +0 -2075
  394. package/dist/useEditorCore-BSo2sSID.js +0 -4059
  395. package/dist/useEditorRoot-BMcoCLBx.js +0 -7
  396. package/dist/usePopoverPosition-DV1PxL66.js +0 -68
  397. package/dist/withCurrentFont-B22FXAF5.js +0 -18
@@ -1 +1 @@
1
- {"version":3,"file":"editor.js","names":["toError","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","SectionBlock","TitleBlock","ParagraphBlock","ImageBlock","ButtonBlock","DividerBlock","SpacerBlock","HtmlBlock","SocialIconsBlock","MenuBlock","TableBlock","VideoBlock","CustomBlock","WrapperBlock","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createElementVNode","_normalizeClass","_toDisplayString","_Fragment","_renderList","_createCommentVNode","_withDirectives","_createVNode","VueDraggable","_withCtx","_createTextVNode","_createBlock","_resolveDynamicComponent","BlockWrapper","_vShow","_sfc_main","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","createBlock","_openBlock","_createElementBlock","_unref","_normalizeStyle","_createElementVNode","_createVNode","_toDisplayString","_createCommentVNode","VueDraggable","_withCtx","_Fragment","_renderList","_createBlock","_resolveDynamicComponent","CustomBlockIcon","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_useModel","_openBlock","_createElementBlock","_unref","_normalizeClass","_createElementVNode","_normalizeStyle","_createVNode","_toDisplayString","_createCommentVNode","_createBlock","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_createElementVNode","_createVNode","_unref","_toDisplayString","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeClass","_createElementVNode","_toDisplayString","_unref","_createStaticVNode","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createVNode","_Transition","_withCtx","_createBlock","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createVNode","_Transition","_withCtx","_createBlock","_sfc_main","_hoisted_1","_hoisted_2","_withDirectives","_openBlock","_createElementBlock","_unref","_normalizeClass","_withKeys","_withModifiers","_vModelText","_toDisplayString","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_openBlock","_createElementBlock","_createVNode","_unref","_createTextVNode","_toDisplayString","_createElementVNode","_createCommentVNode","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_unref","_normalizeClass","_normalizeStyle","_withModifiers","_createVNode","_createTextVNode","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_openBlock","_createElementBlock","_createElementVNode","_normalizeClass","_createBlock","TemplateNameField","_createCommentVNode","TemplateTimestamp","_unref","_renderSlot","_createVNode","ViewportToggle","DarkModeToggle","PreviewToggle","TemplateSaveStatus","_normalizeStyle","_createTextVNode","_toDisplayString","AiHeaderMenu","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","listId","_openBlock","_createBlock","TplModal","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createVNode","_withDirectives","_withKeys","_withModifiers","_vModelText","_createElementBlock","_Fragment","_renderList","_createCommentVNode","_normalizeClass","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_openBlock","_createBlock","TplModal","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createVNode","_withDirectives","_withKeys","_withModifiers","_vModelText","_createElementBlock","_Fragment","_renderList","_normalizeClass","LogicTagBadge","_createCommentVNode","_sfc_main","_openBlock","_createElementBlock","_normalizeClass","_unref","_normalizeStyle","_withModifiers","_createVNode","CustomBlockStylesheets","_createElementVNode","EditorHeader","_createSlots","_withCtx","_withDirectives","Sidebar","_vShow","_Transition","MergeTagModeToggle","_createCommentVNode","_createTextVNode","_toDisplayString","Canvas","_createBlock","EditorFooter","RightSidebar","MergeTagPickerModal","LogicTagPickerModal","SmallScreenNotice","_sfc_main","editorStylesInline","Editor","nextTick","useModel","defineComponent","inject","provide","withDirectives","renderList","getCurrentScope","renderSlot","onMounted","onUnmounted","mergeModels","openBlock","defineAsyncComponent","h","watch","withCtx","onScopeDispose","createElementBlock","createTextVNode","withKeys","normalizeStyle","ref","toDisplayString","createCommentVNode","createBlock","withModifiers","createBaseVNode","Transition","shallowRef","vModelText","computed","createApp","toRaw","vShow","unref","lo","Fragment","normalizeClass","createSlots","createVNode","createStaticVNode","resolveDynamicComponent","resolveContentDirection","assertNoWrapperInContent","OperationError","createParagraphBlock","createCustomBlock","validateLayout","cloneBlock","applyLayout","safeClone","createBlock$1","invertOperations","applyOperationsInPlace","createSlotBlock","createWrapperBlock","CollaborationConflict","createDefaultTemplateContent","getLogicMergeTagKeyword","layoutWrapsSlot","assertNoSlotInContent","SYNTAX_PRESETS","isSlot","isLogicMergeTagValue","SdkError","isWrapper","useSavedBlocks","useVersionHistory","useComments","createLocalStorageMediaProvider","useCommentListener","getEmailFrameWidth","toNaturalSize","useCollaboration","createLocalStorageSavedBlocksProvider","EMAIL_FRAME_WIDTH_TRANSITION","getBlockTypeLabel","useEditor","useTimeoutFn","refDebounced","useIntervalFn","useEventListener","resolveBlockComponent","CustomBlockIcon_default","isLocaleSupported","loadCloudTranslations","loadTranslations","getSupportedCloudLocales","getSupportedLocales","getDocumentStyle","isCloudLocaleSupported","useSmallScreenNotice","SocialIconsBlock_default","useFonts","createHeroSection","ParagraphBlock_default","MenuBlock_default","CustomBlock_default","DividerBlock_default","SpacerBlock_default","getBaseLocale","TitleBlock_default","HtmlBlock_default","VideoBlock_default","SectionBlock_default","ImageBlock_default","TableBlock_default","HERO_PALETTE_TYPE","useEditorCore","BlockWrapper_default","ButtonBlock_default","requireInject","MERGE_TAG_PICKER_KEY","LOGIC_TAG_PICKER_KEY","SIZE_CHECK_KEY","THEME_STYLES_KEY","TEMPLATE_LINT_KEY","MERGE_TAG_SAMPLE_MODE_KEY","MERGE_TAG_SHOW_RAW_VALUE_KEY","MERGE_TAG_SYNTAX_KEY","USE_MERGE_TAG_SAMPLES_KEY","SAVED_BLOCKS_KEY","PREVIEW_RESOLUTION_KEY","UI_LOCALE_KEY","UI_THEME_KEY","CONDITION_PREVIEW_KEY","EDITOR_KEY","CAPABILITIES_KEY","CUSTOM_BLOCK_STYLESHEETS_KEY","BLOCK_DEFAULTS_KEY","CUSTOM_BLOCK_DEFINITIONS_KEY","TEMPLATE_SETTINGS_FIELDS_KEY","APPLIES_CONDITION_FILTER_KEY","BLOCK_REGISTRY_KEY","AI_FEATURE_KEY","FONTS_MANAGER_KEY","PALETTE_BLOCKS_KEY","logger","useI18n","ALL_TEMPLATE_SETTINGS_FIELDS","Monitor","Settings","Check","Sparkles","Eye","SquarePlus","RotateCcw","CircleAlert","Search","EyeOff","Save","Moon","Package","LoaderCircle","ListChecks","LayoutTemplate","Send","MessageCircle","PanelTop","X","ImageUp","Sun","ChevronDown","_plugin_vue_export_helper_default","withNormalizedContentWrites","normalizeRemoteOperations","normalizeContentForConfig","withNormalizedTemplateLoads","normalizeBlockForConfig","AI_MISSING_PROVIDER_MESSAGE","formatAbsoluteDateTime","aiImageSnapshot","aiImageContext","effectiveAltMaxLength","AI_ALT_TEXT_RULES","AI_FIXABLE_RULES","useScrollToBlock","warningBtnCompactClass","secondaryBtnCompactClass","inputClass","primaryBtnCompactClass","WrapperBlock_default","blockTypeIcons","ViewportToggle_default","MergeTagModeToggle_default","formatRelativeTime","TplModal_default","preRenderCustomBlocks","LANGUAGE_TAG","resolveTemplateDefaults","tag","config","seeded","COLLABORATION_NOTICE_MS","AGENT_HIGHLIGHT_MS","RESYNC_SUMMARY","summarizeAgentEdit","blockIds","settings","templateUpdated","op","ops","useCollaborationFeature","notices","nextNoticeId","dismissTimers","armDismiss","running","id","dismissNotice","show","notice","onNotice","agentRun","highlights","highlightTimers","highlightSequence","highlight","sequence","next","blockId","rest","noteAgent","actor","isAi","core","summary","client","key","now","run","counts","view","options","content","change","timer","people","members","myUserId","member","byPerson","history","holders","holder","useCommentsFeature","headless","editor","isOpen","filterBlockId","hasTemplate","unresolvedCount","isAvailable","available","attached","open","toggle","close","openForBlock","AI_SETTLE_TIMEOUT_MS","AI_BROADCAST_GRACE_MS","isAbort","error","asError","sum","message","total","batch","hasBlock","blocks","block","column","refusalOf","useAiFeature","conversation","provider","localSessionId","panel","memory","destroyed","authorVersion","applyingAi","createSession","saved","memoryFor","templateId","currentSession","has","feature","scopeOf","isCurrent","scope","sessionRef","select","empty","value","messages","isTemplateEmpty","isLoadingHistory","isRunning","failure","keptYourVersion","failedPrompt","failedAttachments","importQueue","invalidateHistory","enqueue","job","result","skipped","pump","check","abortable","abort","stopped","reject","signal","promise","reloadCurrent","valid","recoverStopped","canKeepReload","expectedAuthorVersion","found","later","ms","report","outline","collaboration","settle","resolve","requestBase","selectedBlockId","applyOps","normalized","inverse","turn","selected","followRevision","revision","patch","item","changes","replayAvailability","recovery","eligible","record","emptyOutcome","runTurn","userKey","operationCount","text","interrupted","refusal","outcome","completed","reconciling","update","rememberRecovery","reconcileLateApplied","observed","readHistory","handlers","chunk","userText","attachments","file","call","controller","previousKey","caught","kind","recovered","replay","remote","direction","answer","toItem","mergeHistory","list","previous","items","old","matches","persisted","reconciled","row","token","force","loadConversation","pending","newChat","bootstrap","stop","startImport","files","stopSession","abandon","watchers","dirty","draftAltText","altText","abandonDraft","context","applyAltTexts","entries","expect","start","chat","base","fixFinding","finding","rewrite","input","onText","unwatch","AI_MERGE_TAG_LIMITS","truncate","points","max","mergeTagSyntaxName","name","preset","syntax","toAiMergeTags","out","tags","toError$1","dropFileError","maxFileSize","mimeTypes","accept","category","useMediaFeature","isModalOpen","getTemplateId","canDrop","onRequestMedia","toMediaResult","asset","rejected","onError","err","size","useSavedBlocksFeature","isSaveDialogOpen","isBrowserOpen","picking","pickedIds","isPicking","pickedCount","startPicking","togglePick","isPicked","cancelPicking","confirmPicking","refresh","closeSaveDialog","previewMode","openBrowser","closeBrowser","insert","i","cloned","position","insertIndex","count","SAVED_STATUS_MS","useTemplatesFeature","status","errorMessage","startSavedStatusClear","stopSavedStatusClear","canCreate","canSave","timestamp","template","isSaving","reportSuccess","reportFailure","save","trigger","create","load","shouldApply","queuedAutoSave","runSave","requestAutoSave","cannotSave","requestSave","gate","rename","trimmed","newName","event","tryLoadRenderer","toMjmlForInstance","renderer","stylesheetResolver","instance","fonts","layout","customType","SUCCESS_DISMISS_MS","toError","useTestEmailFeature","isSending","justSent","dismissTimer","warnedAboutRenderer","clearDismissTimer","allowedRecipients","defaultRecipient","preferred","allowed","resolveMjml","notifySent","payload","send","recipient","mjml","wrapped","useVersionHistoryFeature","previewingVersion","contentBeforePreview","isConfirmingRestore","isSavingBeforeRestore","versions","isLoading","isRestoring","canRestore","isPreviewing","canSaveBeforeRestore","isConfirmBusy","navigate","known","version","autoSave","requestRestore","confirmRestore","saveAndRestore","before","saver","previewed","discardAndRestore","cancelRestoreConfirm","conditionPreview","applyRestored","cancelPreview","resolveAutoSave","defaultEnabled","resolveLintOptions","resolveInsertPosition","findBlockLocation","blockType","parent","isBlockLocked","insertBlockAtSelection","targetSectionId","columnIndex","index","withCollaborativeSave","storedNames","remember","current","getTemplate","_hoisted_1$15","_hoisted_2$9","_hoisted_3$8","_hoisted_4$7","_hoisted_5$6","_hoisted_6$6","_hoisted_7$6","_hoisted_8$4","_hoisted_9$3","_hoisted_10$3","_hoisted_11$3","_hoisted_12$3","Canvas_default","__emit","blockComponentMap","props","__props","emit","fontsManager","blockRegistry","caps","mergeTagSampleMode","previewResolution","canChat","canImport","importInput","pickImport","importPicked","appliesConditionFilter","viewportWidth","stageWidth","canvasStyle","contentLang","contentDir","isEmptyCanvas","dragEnterDepth","isDragOverEmpty","handleEmptyDragEnter","handleEmptyDragLeave","handleEmptyDrop","handleCanvasClick","getBlockComponent","isLockedByOther","handleBlockSelect","savedBlocks","isPickedBlock","handleFetchData","t","n","_cache","$event","updates","CustomBlockStylesheets_default","stylesheets","css","resolvePaletteBlocks","paletteBlocks","candidates","byType","c","unknown","seen","entry","candidate","_hoisted_1$14","_hoisted_2$8","_hoisted_3$7","_hoisted_4$6","_hoisted_5$5","_hoisted_6$5","_hoisted_7$5","PALETTE_DRAG_TOLERANCE_PX","Sidebar_default","customBlockDefinitions","blockDefaults","scrollToBlock","showSavedBlocksSection","isExpanded","isDragging","railEl","suppressPaletteClick","suppressPaletteClickTimer","hasKeyboardFocusInRail","handleSidebarLeave","handleDragChoose","handleDragUnchoose","handleDragStart","handleRailFocusOut","clearFallbackClickSwallow","handleDragEnd","builtInBlockTypeOrder","builtInBlockTypes","types","type","customBlockItems","def","candidateBlockTypes","resolvedPalette","blockTypes","warnedPaletteEntries","createBlockFromItem","definition","d","insertBlockFromItem","handlePaletteClick","handlePaletteKeydown","format","_hoisted_1$13","_hoisted_2$7","_hoisted_3$6","_hoisted_4$5","_hoisted_5$4","_hoisted_6$4","_hoisted_7$4","_hoisted_8$3","_hoisted_9$2","_hoisted_10$2","_hoisted_11$2","_hoisted_12$2","_hoisted_13$2","_hoisted_14$2","_hoisted_15$2","_hoisted_16$2","RightSidebar_default","\"tab\"","\"tabModifiers\"","Toolbar","TemplateSettingsPanel","IssuesPanel","activeTab","lint","lintAvailable","issueCount","allowedSettingsFields","settingsEnabled","tabClass","tab","tabStyle","newBlock","_hoisted_1$12","_hoisted_2$6","_hoisted_3$5","_hoisted_4$4","SmallScreenNotice_default","_hoisted_1$11","EditorFooter_default","_hoisted_1$10","DarkModeToggle_default","_hoisted_1$9","PreviewToggle_default","_hoisted_1$8","_hoisted_2$5","TemplateNameField_default","isEditing","draft","inputEl","startEditing","commit","cancel","_hoisted_1$7","TemplateTimestamp_default","uiLocale","tick","label","relative","isJustNow","absolute","_hoisted_1$6","_hoisted_2$4","_hoisted_3$4","TemplateSaveStatus_default","_hoisted_1$5","AiHeaderMenu_default","isActive","_hoisted_1$4","_hoisted_2$3","_hoisted_3$3","_hoisted_4$3","_hoisted_5$3","_hoisted_6$3","_hoisted_7$3","_hoisted_8$2","EditorHeader_default","VersionHistoryMenu","CollaboratorBar","_ctx","_hoisted_1$3","_hoisted_2$2","_hoisted_3$2","_hoisted_4$2","_hoisted_5$2","_hoisted_6$2","_hoisted_7$2","_hoisted_8$1","_hoisted_9$1","_hoisted_10$1","_hoisted_11$1","_hoisted_12$1","_hoisted_13$1","_hoisted_14$1","_hoisted_15$1","_hoisted_16$1","_hoisted_17$1","_hoisted_18","listId$1","MergeTagPickerModal_default","picker","themeStyles","tplUiTheme","showRawValue","isChanging","modalTitle","rowTitle","rawSearch","search","searchInputRef","searchActive","highlightedIndex","hasGroups","collapsedGroups","isCollapsed","group","toggleGroup","filteredTags","query","groupOrder","otherLabel","order","rows","buckets","tagIndex","groupKey","visibleTags","preselectPending","preselectCurrent","target","setHighlight","selectTag","moveHighlight","delta","scrollHighlightIntoView","listRef","headerRefs","setHeaderRef","el","container","jumpToGroup","targetScrollTop","child","onKeydown","activeOptionId","optionId","isEmptyConfig","isNoResults","showPillRow","rowIndex","_hoisted_1$2","LogicTagBadge_default","isLogic","keyword","\"border\"","\"color\"","_hoisted_1$1","_hoisted_2$1","_hoisted_3$1","_hoisted_4$1","_hoisted_5$1","_hoisted_6$1","_hoisted_7$1","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","listId","LogicTagPickerModal_default","haystackParts","filteredPairs","pair","filteredEntries","bucket","map","built","idx","pushEntry","groupEntries","visibleItems","selectItem","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","Editor_default","__expose","liveMergeTags","normalizedTemplates","templatesProvider","cloudAttachment","templates","isDirty","rootEl","SavedBlocksPanels","mediaFeature","MediaPanels","testEmail","TestEmailPanel","comments","CommentsPanel","AiPanels","ai","CollaborationNotices","CloudPanels","CloudHeaderExtras","VersionHistoryPanels","autoSaveEnabled","isAutoSaving","autoSaveOptions","capabilities","rightSidebarTab","cloudReady","versionHistory","rightPanelOpen","bodyInsetClass","showSmallScreenNotice","templateLifecycle","copy","theme","\"transition\"","IMPORT_RULE","stripStylesheetImports","resolveRenderFonts","source","buildRenderPayload","raw","createRenderMethods","toMjml","providerToMjml","toHtml","providerToHtml","compileMjml","usesLocalRenderer","canRenderHtml","_virtual_editor_css_default","cachedEditorStyleSheet","getEditorStyleSheet","sheet","attachDevStyleMirror","resolveMountTarget","shadowDom","shadowRoot","host","ossEntries","lastOssContainer","lastClaimToken","containerClaims","claimContainer","unmountOssContainer","onlyApp","prepareLayoutAndContent","init","prepared","mountEditor","translations","createEditorInstance","mount","editorRef","app","render","initCloud","claim","cloudTranslations","bootstrapCloud","providers","runtime","unmount"],"sources":["../../src/utils/resolveTemplateDefaults.ts","../../src/composables/useCollaborationFeature.ts","../../src/composables/useCommentsFeature.ts","../../src/composables/useAiFeature.ts","../../src/utils/aiMergeTags.ts","../../src/composables/useMediaFeature.ts","../../src/composables/useSavedBlocksFeature.ts","../../src/composables/useTemplatesFeature.ts","../../src/utils/toMjml.ts","../../src/composables/useTestEmailFeature.ts","../../src/composables/useVersionHistoryFeature.ts","../../src/types/auto-save.ts","../../src/utils/resolveLintOptions.ts","../../src/utils/resolveInsertPosition.ts","../../src/utils/insertBlockAtSelection.ts","../../src/utils/withCollaborativeSave.ts","../../src/components/Canvas.vue","../../src/components/Canvas.vue","../../src/components/CustomBlockStylesheets.vue","../../src/components/CustomBlockStylesheets.vue","../../src/utils/resolvePaletteBlocks.ts","../../src/components/Sidebar.vue","../../src/components/Sidebar.vue","../../src/components/RightSidebar.vue","../../src/components/RightSidebar.vue","../../src/components/SmallScreenNotice.vue","../../src/components/SmallScreenNotice.vue","../../src/components/EditorFooter.vue","../../src/components/EditorFooter.vue","../../src/components/DarkModeToggle.vue","../../src/components/DarkModeToggle.vue","../../src/components/PreviewToggle.vue","../../src/components/PreviewToggle.vue","../../src/components/TemplateNameField.vue","../../src/components/TemplateNameField.vue","../../src/components/TemplateTimestamp.vue","../../src/components/TemplateTimestamp.vue","../../src/components/TemplateSaveStatus.vue","../../src/components/TemplateSaveStatus.vue","../../src/components/ai/AiHeaderMenu.vue","../../src/components/ai/AiHeaderMenu.vue","../../src/components/EditorHeader.vue","../../src/components/EditorHeader.vue","../../src/components/MergeTagPickerModal.vue","../../src/components/MergeTagPickerModal.vue","../../src/components/LogicTagBadge.vue","../../src/components/LogicTagBadge.vue","../../src/components/LogicTagPickerModal.vue","../../src/components/LogicTagPickerModal.vue","../../src/Editor.vue","../../src/Editor.vue","../../src/utils/stripStylesheetImports.ts","../../src/utils/renderProvider.ts","../../src/index.ts"],"sourcesContent":["import type { TemplateDefaults } from \"@templatical/types\";\n\n/**\n * A well-formed BCP-47-ish language tag: 2–3 letter primary subtag, then\n * hyphen-separated alphanumeric subtags (`de`, `en-GB`, `pt-BR`, `zh-Hant-TW`).\n *\n * Deliberately a shape check, not a registry check — an unknown-but-well-formed\n * tag is the author's business, whereas a *malformed* one must not reach\n * `<mjml lang=\"…\">`, which the renderer stamps from this value.\n */\nconst LANGUAGE_TAG = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i;\n\n/**\n * The template defaults a new, contentless template starts from — the\n * consumer's `templateDefaults`, with the editor's `locale` filled in as the\n * content language when they did not set one.\n *\n * Without this a fresh template rendered `<mjml lang=\"en\">` regardless of the\n * editor's language, so German copy announced itself as English to every screen\n * reader that opened the delivered email. This only decides the *starting*\n * value: the author can change it afterwards, since Template Settings exposes\n * it as \"Content language\" — **unless** the consumer excluded `locale` from\n * `templateSettings.fields`, in which case that card is gone and this seed is\n * the only thing that sets a blank template's content language.\n *\n * Three details are load-bearing:\n *\n * - **The consumer wins.** `templateDefaults.locale` is spread last, so\n * `init({ locale: \"de\", templateDefaults: { locale: \"en\" } })` means a\n * German UI authoring English emails, which is a real setup.\n * - **The region is kept**, unlike `loadTranslations`, which strips it to pick\n * a bundle. `en-GB` and `pt-BR` are meaningfully not `en`/`pt` to a screen\n * reader, and `<html lang>` is exactly where that distinction belongs.\n * - **A malformed tag yields nothing** rather than a guess, leaving\n * `createDefaultTemplateContent` to apply its own English fallback. Emitting\n * it would put unvalidated config text straight into a `lang` attribute.\n *\n * Returns `undefined` when it has nothing to contribute, so the call site can\n * pass it through without inventing an empty object.\n */\nexport function resolveTemplateDefaults(config: {\n locale?: string;\n templateDefaults?: TemplateDefaults;\n}): TemplateDefaults | undefined {\n const tag = config.locale?.trim().replace(/_/g, \"-\");\n const seeded = tag && LANGUAGE_TAG.test(tag) ? { locale: tag } : undefined;\n\n if (!seeded && !config.templateDefaults) return undefined;\n\n return { ...seeded, ...config.templateDefaults };\n}\n","import {\n computed,\n getCurrentScope,\n onScopeDispose,\n ref,\n shallowRef,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport {\n useCollaboration,\n type CollaborationEditor,\n type CollaborationNotice,\n type UseCollaborationReturn,\n type UseHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n BlockLock,\n BlockLockHolder,\n CollaborationActor,\n CollaborationConflictCode,\n CollaborationProvider,\n CollaborationRemoteChange,\n EditorUser,\n MergeTagsConfig,\n Operation,\n Template,\n} from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\nimport { normalizeRemoteOperations } from \"../utils/normalizeMergeTagMarkup\";\n\n/** How long a notice stays up. */\nexport const COLLABORATION_NOTICE_MS = 5000;\n/** An agent's batches closer together than this share one notice. */\nexport const AGENT_EDIT_MERGE_MS = 2000;\n/** How long the blocks an agent changed stay outlined. */\nexport const AGENT_HIGHLIGHT_MS = 2000;\n\n/** One person in the collaborator bar: a user's sessions, or one guest. */\nexport interface CollaborationPerson {\n key: string;\n type: \"user\" | \"guest\";\n /** The member's name; the bar shows its own word for a guest. */\n name: string;\n avatarUrl?: string;\n color: string;\n}\n\n/** `Omit` for each member of a union. */\ntype OmitEach<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/** A notice the editor shows, in words the components translate. */\nexport type CollaborationNoticeView =\n | { id: number; kind: \"selectionRefused\"; name: string; isGuest: boolean }\n | {\n id: number;\n kind: \"editRefused\";\n code: CollaborationConflictCode;\n name?: string;\n isGuest?: boolean;\n }\n | { id: number; kind: \"undoSkipped\" }\n | {\n id: number;\n kind: \"replaceRefused\";\n holders: { name: string; isGuest: boolean }[];\n }\n | {\n id: number;\n kind: \"agentEdited\";\n /** The agent's name, or `null` when the backend sent none. */\n client: string | null;\n /** The user the agent acts for. */\n name: string;\n /** Distinct blocks the agent added, moved, deleted or updated. */\n blocks: number;\n /** The agent changed the template settings. */\n settings: boolean;\n /** The agent updated the whole template: a replace, a restore or a re-sync. */\n templateUpdated: boolean;\n }\n | {\n id: number;\n /** An AI changed the template for a user (`actor.type: \"ai\"`): Cloud, or a BYO backend honouring `origin: \"ai\"`. */\n kind: \"aiEdited\";\n /** The user who asked the AI. */\n name: string;\n blocks: number;\n settings: boolean;\n /** The AI built or replaced the whole template, or a re-sync came in. */\n templateUpdated: boolean;\n };\n\n/** What one batch from an agent changed. */\nexport interface AgentEditSummary {\n /** The blocks its ops name: an added block's id, every other block op's `blockId`. */\n blockIds: string[];\n /** It has an `updateSettings`. */\n settings: boolean;\n /** It has a `setContent`, or it is a re-sync. */\n templateUpdated: boolean;\n}\n\n/** What a re-sync says: the template changed as a whole, and no blocks are named. */\nconst RESYNC_SUMMARY: AgentEditSummary = {\n blockIds: [],\n settings: false,\n templateUpdated: true,\n};\n\n/**\n * Read an agent's batch for its notice: the distinct blocks it names, and\n * whether it changed the settings or updated the whole template.\n */\nexport function summarizeAgentEdit(\n ops: readonly Operation[],\n): AgentEditSummary {\n const blockIds = new Set<string>();\n let settings = false;\n let templateUpdated = false;\n for (const op of ops) {\n if (op.op === \"addBlock\") {\n if (typeof op.block?.id === \"string\") blockIds.add(op.block.id);\n } else if (op.op === \"updateSettings\") {\n settings = true;\n } else if (op.op === \"setContent\") {\n templateUpdated = true;\n } else {\n blockIds.add(op.blockId);\n }\n }\n return { blockIds: [...blockIds], settings, templateUpdated };\n}\n\nexport interface UseCollaborationFeatureOptions {\n provider: CollaborationProvider;\n /** The templates provider's `load`, for a re-sync. */\n loadTemplate: (templateId: string) => Promise<Template>;\n /** `init({ user })`: the editor's own sessions are left out of the bar by it too. */\n user?: EditorUser;\n /**\n * `init({ mergeTags })`: another session's batch has its tokens turned into\n * tags with it as it arrives, the way loaded content does.\n */\n mergeTags?: MergeTagsConfig;\n onRemoteChange?: (change: CollaborationRemoteChange) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseCollaborationFeatureReturn {\n core: UseCollaborationReturn;\n /** Others' locks, read by `useEditor` before the controller attaches. */\n locks: UseCollaborationReturn[\"locks\"];\n /** Wire the controller to the editor; call once, after `useEditor()`. */\n attach: (editor: CollaborationEditor) => void;\n /** Undo and redo by inverse batches, in place of the snapshot history. */\n history: UseHistoryReturn;\n /** Everyone else, one entry per person; empty without presence. */\n people: ComputedRef<CollaborationPerson[]>;\n /** Presence is live: the bar shows. */\n isLive: ComputedRef<boolean>;\n connection: UseCollaborationReturn[\"connection\"];\n notices: Ref<CollaborationNoticeView[]>;\n dismissNotice: (id: number) => void;\n /** Say a whole-template replace was refused, naming who holds locks. */\n reportReplaceRefused: (holders: readonly BlockLockHolder[]) => void;\n /**\n * Outline blocks for AGENT_HIGHLIGHT_MS, with no notice: the editor that\n * asked an AI shows its own turn's changes this way (D26).\n */\n outline: (blockIds: readonly string[]) => void;\n capability: NonNullable<EditorCapabilities[\"collaboration\"]>;\n}\n\n/** One agent's, or the AI's, run of batches and re-syncs while they share a notice. */\ninterface AgentRun {\n /** The actor type, the user it acts for and, for an agent, its own name. */\n key: string;\n noticeId: number;\n lastAt: number;\n blockIds: Set<string>;\n settings: boolean;\n templateUpdated: boolean;\n}\n\n/**\n * Shared glue for collaboration: the controller from `@templatical/core`, the\n * history it replaces, the people the bar shows and the notices — an AI\n * agent's and an AI's edits included, with the outline on the blocks\n * they changed.\n *\n * Built before `useEditor()`, because the editor reads others' locks from it;\n * `attach` wires it to the editor right after.\n */\nexport function useCollaborationFeature(\n options: UseCollaborationFeatureOptions,\n): UseCollaborationFeatureReturn {\n const notices = ref<CollaborationNoticeView[]>([]);\n let nextNoticeId = 1;\n const dismissTimers = new Map<number, ReturnType<typeof setTimeout>>();\n\n /** Start, or restart, a notice's countdown to dismissal. */\n function armDismiss(id: number): void {\n const running = dismissTimers.get(id);\n if (running) clearTimeout(running);\n dismissTimers.set(\n id,\n setTimeout(() => dismissNotice(id), COLLABORATION_NOTICE_MS),\n );\n }\n\n function show(notice: OmitEach<CollaborationNoticeView, \"id\">): number {\n const id = nextNoticeId++;\n // One at a time: a newer notice replaces the one on screen.\n notices.value = [{ ...notice, id }];\n armDismiss(id);\n return id;\n }\n\n function dismissNotice(id: number): void {\n const running = dismissTimers.get(id);\n if (running) {\n clearTimeout(running);\n dismissTimers.delete(id);\n }\n notices.value = notices.value.filter((notice) => notice.id !== id);\n }\n\n function onNotice(notice: CollaborationNotice): void {\n if (notice.type === \"selectionRefused\") {\n show({\n kind: \"selectionRefused\",\n name: notice.holder.name,\n isGuest: notice.holder.type === \"guest\",\n });\n } else if (notice.type === \"editRefused\") {\n show({\n kind: \"editRefused\",\n code: notice.code,\n ...(notice.holder\n ? {\n name: notice.holder.name,\n isGuest: notice.holder.type === \"guest\",\n }\n : {}),\n });\n } else {\n show({ kind: \"undoSkipped\" });\n }\n }\n\n // --- Agents' edits ---------------------------------------------------------\n\n let agentRun: AgentRun | null = null;\n const highlights = shallowRef<ReadonlyMap<string, number>>(new Map());\n const highlightTimers = new Map<string, ReturnType<typeof setTimeout>>();\n let highlightSequence = 0;\n\n /** Outline `blockIds` for AGENT_HIGHLIGHT_MS, under one new number. */\n function highlight(blockIds: readonly string[]): void {\n if (blockIds.length === 0) return;\n const sequence = ++highlightSequence;\n const next = new Map(highlights.value);\n for (const blockId of blockIds) {\n next.set(blockId, sequence);\n const running = highlightTimers.get(blockId);\n if (running) clearTimeout(running);\n highlightTimers.set(\n blockId,\n setTimeout(() => {\n highlightTimers.delete(blockId);\n const rest = new Map(highlights.value);\n rest.delete(blockId);\n highlights.value = rest;\n }, AGENT_HIGHLIGHT_MS),\n );\n }\n highlights.value = next;\n }\n\n /**\n * An agent's or the AI's batch or re-sync: a notice naming who acted and\n * for whom, and an outline on the blocks a batch changed. Batches and\n * re-syncs from one of them within AGENT_EDIT_MERGE_MS of each other update\n * one notice while it is the one on screen, counting each block once — so\n * the batch a re-sync's catch-up brings lands in the re-sync's notice. The\n * editor that asked the AI only outlines its batches (D26).\n */\n function noteAgent(\n actor: CollaborationActor,\n summary: AgentEditSummary,\n ): void {\n if (actor.type !== \"mcp\" && actor.type !== \"ai\") return;\n const isAi = actor.type === \"ai\";\n // The editor that asked the AI outlines the change but shows no notice:\n // its chat already says \"Applied N changes\" (D26).\n if (isAi && actor.sessionId === core.sessionId) {\n if (!summary.templateUpdated) highlight(summary.blockIds);\n return;\n }\n const client =\n !isAi && typeof actor.client === \"string\" && actor.client.trim() !== \"\"\n ? actor.client\n : null;\n const key = `${actor.type}\\n${actor.id ?? \"\"}\\n${client ?? \"\"}`;\n const now = Date.now();\n\n let run = agentRun;\n if (\n !run ||\n run.key !== key ||\n now - run.lastAt > AGENT_EDIT_MERGE_MS ||\n notices.value.at(-1)?.id !== run.noticeId\n ) {\n run = {\n key,\n noticeId: 0,\n lastAt: now,\n blockIds: new Set(),\n settings: false,\n templateUpdated: false,\n };\n }\n for (const blockId of summary.blockIds) run.blockIds.add(blockId);\n run.settings ||= summary.settings;\n run.templateUpdated ||= summary.templateUpdated;\n run.lastAt = now;\n\n const counts = {\n blocks: run.blockIds.size,\n settings: run.settings,\n templateUpdated: run.templateUpdated,\n };\n const view: OmitEach<CollaborationNoticeView, \"id\"> = isAi\n ? { kind: \"aiEdited\", name: actor.name, ...counts }\n : { kind: \"agentEdited\", client, name: actor.name, ...counts };\n if (run === agentRun) {\n notices.value = [{ ...view, id: run.noticeId }];\n armDismiss(run.noticeId);\n } else {\n run.noticeId = show(view);\n agentRun = run;\n }\n if (!summary.templateUpdated) highlight(summary.blockIds);\n }\n\n const core = useCollaboration({\n provider: options.provider,\n loadTemplate: options.loadTemplate,\n normalizeRemoteOperations: (ops, content) =>\n normalizeRemoteOperations(ops, content, options.mergeTags),\n // The consumer's callback runs whatever happens to the notice: an\n // integrator's `onRemoteChange` must not depend on the editor's chrome.\n onRemoteChange: (change) => {\n try {\n noteAgent(change.actor, summarizeAgentEdit(change.ops));\n } finally {\n options.onRemoteChange?.(change);\n }\n },\n // An agent's replace or restore, an AI's built template, or a batch too\n // large to broadcast reaches live editors only as a re-sync: the template\n // changed as a whole.\n onRemoteResync: ({ actor }) => noteAgent(actor, RESYNC_SUMMARY),\n onNotice,\n onError: options.onError,\n });\n\n if (getCurrentScope()) {\n onScopeDispose(() => {\n for (const timer of dismissTimers.values()) clearTimeout(timer);\n for (const timer of highlightTimers.values()) clearTimeout(timer);\n dismissTimers.clear();\n highlightTimers.clear();\n });\n }\n\n const people = computed<CollaborationPerson[]>(() => {\n const members = core.members.value;\n const self = members.find((member) => member.sessionId === core.sessionId);\n const myUserId = self?.userId ?? options.user?.id ?? null;\n const byPerson = new Map<string, CollaborationPerson>();\n for (const member of members) {\n if (member.sessionId === core.sessionId) continue;\n if (member.userId !== null && member.userId === myUserId) continue;\n const key =\n member.userId !== null\n ? `user:${member.userId}`\n : `guest:${member.sessionId}`;\n if (byPerson.has(key)) continue;\n byPerson.set(key, {\n key,\n type: member.type,\n name: member.name,\n ...(member.avatarUrl ? { avatarUrl: member.avatarUrl } : {}),\n color: member.color,\n });\n }\n return [...byPerson.values()];\n });\n\n const history: UseHistoryReturn = {\n canUndo: core.canUndo,\n canRedo: core.canRedo,\n isNavigating: ref(false),\n undo: core.undo,\n redo: core.redo,\n // The controller captures every change by diffing; nothing to record.\n record: () => {},\n recordDebounced: () => {},\n clear: core.clearHistory,\n destroy: () => {},\n };\n\n return {\n core,\n locks: core.locks,\n attach: core.attach,\n history,\n people,\n isLive: computed(() => core.members.value.length > 0),\n connection: core.connection,\n notices,\n dismissNotice,\n reportReplaceRefused: (holders) =>\n show({\n kind: \"replaceRefused\",\n holders: [\n ...new Map(\n holders.map((holder) => [\n holder.type === \"guest\" ? `guest:${holder.sessionId}` : holder.id,\n { name: holder.name, isGuest: holder.type === \"guest\" },\n ]),\n ).values(),\n ],\n }),\n outline: highlight,\n capability: {\n lockOf: (blockId: string): BlockLock | null =>\n core.locks.value.get(blockId) ?? null,\n agentHighlightOf: (blockId: string): number | null =>\n highlights.value.get(blockId) ?? null,\n },\n };\n}\n","import { computed, ref, watch, type ComputedRef, type Ref } from \"vue\";\nimport { useComments, useCommentListener } from \"@templatical/core\";\nimport type { UseCommentsReturn } from \"@templatical/core\";\nimport type { CommentsProvider, EditorUser } from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — OSS and Cloud alike. */\ninterface CommentsEditor {\n state: {\n readonly template?: { id: string } | null;\n };\n}\n\nexport interface UseCommentsFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: CommentsProvider;\n editor: CommentsEditor;\n /**\n * Who is commenting (`init({ user })`). **Without one the feature reports\n * itself unavailable** — see {@link isAvailable}.\n */\n user?: EditorUser | null;\n /**\n * The panel's open state. Cloud passes its own; otherwise a local ref is\n * used. The open-source AI feature reads this state to keep comments and\n * AI panels mutually exclusive in their shared 360px gutter.\n */\n isOpen?: Ref<boolean>;\n onError?: (error: Error) => void;\n /**\n * Extra gate on top of a provider and a user being present — Cloud adds its\n * `commenting` plan entitlement and \"the template must be saved\". Read\n * reactively, so a Cloud entitlement that resolves after setup still lights the\n * feature up.\n */\n isAvailable?: () => boolean;\n /**\n * Whether a block id exists in the **stored** template. Cloud supplies this: a\n * comment is anchored server-side, so filtering to a block that only exists on\n * the canvas has nothing to show. Absent means \"assume it does\", which is right\n * for a store that accepts any anchor.\n */\n isBlockSaved?: (blockId: string) => boolean;\n}\n\nexport interface UseCommentsFeatureReturn {\n headless: UseCommentsReturn;\n\n isOpen: Ref<boolean>;\n isAvailable: ComputedRef<boolean>;\n /** True once a template exists — comments are keyed to one. */\n hasTemplate: ComputedRef<boolean>;\n unresolvedCount: ComputedRef<number>;\n\n /**\n * The block the panel should filter to, or `null` for no block filter. Owned\n * here rather than in the panel because a block's comment indicator sets it\n * *before* the lazy panel exists.\n */\n filterBlockId: Ref<string | null>;\n\n /** Toggle the panel. A no-op while unavailable. */\n toggle: () => void;\n close: () => void;\n /** Open the panel filtered to one block — what the canvas indicator calls. */\n openForBlock: (blockId: string) => void;\n\n capability: NonNullable<EditorCapabilities[\"comments\"]>;\n}\n\n/**\n * Shared glue for comments: the reactive thread list, the panel's open and filter\n * state, and the capability the shared chrome gates on.\n *\n * Both entry points construct this — OSS from `init({ comments })`, Cloud from\n * `createCloudCommentsProvider` — so the two run identical logic over different\n * transports. Nothing here is auth- or plan-aware; callers decide availability.\n *\n * **Nothing is fetched at mount.** The list is read when the panel opens, matching\n * saved blocks: a review panel nobody opens should cost no round-trip, and the\n * unresolved badge is worth less than a request on every editor boot.\n */\nexport function useCommentsFeature(\n options: UseCommentsFeatureOptions,\n): UseCommentsFeatureReturn {\n const { provider, editor } = options;\n\n const headless = useComments({\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n // Read through a getter, never destructured: Cloud fills `user` from the JWT\n // and a consumer may swap it, and the same lesson as `allowedRecipients`\n // applies — a snapshot at setup pins the answer forever.\n getUser: () => options.user ?? null,\n onError: options.onError,\n });\n\n // Provider-driven realtime, or nothing at all when the provider has no\n // `subscribe`. It is deliberately wired here rather than inside `useComments`:\n // the subscription is a lifecycle concern (it follows the template and must be\n // torn down), and `useComments` is state.\n useCommentListener({\n comments: headless,\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n });\n\n const isOpen = options.isOpen ?? ref(false);\n const filterBlockId = ref<string | null>(null);\n\n const hasTemplate = computed(() => !!editor.state.template?.id);\n const unresolvedCount = headless.unresolvedCount;\n\n const isAvailable = computed(() => {\n // No identity ⇒ unavailable, never anonymous. Every comment carries an author\n // and an unattributable one is worse than no comment feature.\n if (!options.user) return false;\n return options.isAvailable?.() ?? true;\n });\n\n // A panel left open when the feature goes away — a Cloud plan fetch that\n // withholds `commenting`, or a consumer clearing `user` — would sit there with\n // no trigger to close it.\n watch(isAvailable, (available) => {\n if (!available) isOpen.value = false;\n });\n\n // Load as soon as there is a template, not just when the panel opens. Unlike\n // saved blocks or version history — whose lists are read only by the surface\n // that fetches them — two indicators *outside* this panel derive from the whole\n // list: `unresolvedCount` feeds the header badge, and `commentCountByBlock`\n // feeds the per-block canvas markers. Deferring the fetch left both at zero, so\n // a template arriving with existing comments showed no sign of them anywhere\n // until the user happened to click Comments, and the badge then popped into\n // existence — the same \"reads 0, then pops\" failure that cost the saved-blocks\n // rail its count.\n //\n // Loading the lot up front is already the design's assumption: `comments.list`\n // is deliberately unpaginated precisely because those two aggregates are\n // computed over every thread.\n watch(\n [isAvailable, hasTemplate],\n ([available, attached]) => {\n if (!available || !attached) return;\n void headless.load().catch(() => {\n /* reported through onError */\n });\n },\n { immediate: true },\n );\n\n // Every open re-reads. History and comments both grow elsewhere, so a list\n // fetched once goes stale silently; only a *first* open has nothing to show\n // meanwhile, which the panel distinguishes for its skeleton.\n watch(isOpen, (open) => {\n if (!open || !hasTemplate.value) return;\n void headless.load().catch(() => {\n /* reported through onError */\n });\n });\n\n function toggle(): void {\n if (!isAvailable.value) return;\n isOpen.value = !isOpen.value;\n }\n\n function close(): void {\n isOpen.value = false;\n }\n\n function openForBlock(blockId: string): void {\n if (!isAvailable.value) return;\n filterBlockId.value = blockId;\n // Assigning `true` to an already-true ref fires no watcher, so an indicator\n // clicked while the panel is open must refresh explicitly — otherwise moving\n // between blocks shows a list read before the last change.\n if (isOpen.value) {\n if (hasTemplate.value) {\n void headless.load().catch(() => {\n /* reported through onError */\n });\n }\n return;\n }\n isOpen.value = true;\n }\n\n return {\n headless,\n\n isOpen,\n isAvailable,\n hasTemplate,\n unresolvedCount,\n\n filterBlockId,\n\n toggle,\n close,\n openForBlock,\n\n capability: {\n getBlockCount: (blockId: string) =>\n headless.commentCountByBlock.value.get(blockId) ?? 0,\n openForBlock,\n // Absent means \"any anchor is fine\", which is the right default for a store\n // that accepts one. Cloud supplies the real check because it renders from\n // the saved template.\n isBlockSaved: (blockId: string) =>\n options.isBlockSaved?.(blockId) ?? true,\n isAvailable,\n unresolvedCount,\n canCreate: headless.canCreate,\n canUpdate: headless.canUpdate,\n canDelete: headless.canDelete,\n canResolve: headless.canResolve,\n },\n };\n}\n","import {\n computed,\n ref,\n shallowRef,\n toRaw,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport type { UseHistoryReturn } from \"@templatical/core\";\nimport type {\n AiChatMessage,\n AiFeatureName,\n AiFixFinding,\n AiMergeTags,\n AiMessageKind,\n AiOperationsResult,\n AiProvider,\n AiRequestBase,\n AiRewriteRequest,\n AiTurnHandlers,\n AiTurnResult,\n Block,\n Operation,\n TemplateContent,\n} from \"@templatical/types\";\nimport {\n applyOperationsInPlace,\n CollaborationConflict,\n invertOperations,\n OperationError,\n safeClone,\n SdkError,\n} from \"@templatical/types\";\nimport {\n AI_MISSING_PROVIDER_MESSAGE,\n type AiErrorContext,\n} from \"../utils/aiErrors\";\nimport {\n aiImageContext,\n aiImageSnapshot,\n type AiImageSnapshot,\n} from \"../utils/aiImageContext\";\nimport { DEFAULT_ALT_MAX_LENGTH } from \"../utils/aiFixableRules\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\nimport {\n AGENT_HIGHLIGHT_MS,\n summarizeAgentEdit,\n type UseCollaborationFeatureReturn,\n} from \"./useCollaborationFeature\";\n\n/** How long a turn waits for this editor's unsent edits to reach the backend. */\nexport const AI_SETTLE_TIMEOUT_MS = 3000;\n/** How long a live channel gets to deliver a server-applied batch before a catch-up. */\nexport const AI_BROADCAST_GRACE_MS = 1000;\nexport { AI_MISSING_PROVIDER_MESSAGE } from \"../utils/aiErrors\";\n/** UTF-8 bytes of serialized content, matching the wire's AI_LIMITS. */\nexport const AI_CONTENT_MAX_BYTES = 200_000;\n\nexport type AiPanel = \"chat\";\nexport type { AiErrorContext } from \"../utils/aiErrors\";\n\nexport interface AiFailure {\n error: Error;\n context: AiErrorContext;\n}\n\n/** One row of the chat (D16). */\nexport interface AiChatItem {\n id: string;\n role: \"user\" | \"assistant\";\n kind: AiMessageKind;\n text: string;\n attachments: { name: string; kind: \"image\" | \"pdf\" }[];\n /** Operations this turn changed, client- and server-applied together. */\n operationCount: number;\n undone: boolean;\n /** Undo is available for this not-undone message. */\n canUndo: boolean;\n /** Redo is available for this undone message. */\n canRedo: boolean;\n createdAt: string;\n status: \"streaming\" | \"done\" | \"failed\";\n /** Why the turn, or its last Undo or Redo, failed. */\n failure?: AiFailure;\n}\n\nexport interface AiTurnOutcome {\n /** The assistant item's id, `null` when the turn left no message. */\n messageId: string | null;\n operationCount: number;\n text: string;\n failed: boolean;\n}\n\n/** The slice of the editor the feature reads and writes. */\nexport interface AiFeatureEditor {\n state: {\n readonly template?: { readonly id: string } | null;\n readonly selectedBlockId: string | null;\n readonly isLoading?: boolean;\n readonly isDirty?: boolean;\n readonly isSaving?: boolean;\n };\n /** Committed create/load version from core; metadata edits leave it alone. */\n loadVersion?: Readonly<Ref<number>>;\n content: Ref<TemplateContent>;\n selectBlock: (blockId: string | null) => void;\n markDirty: () => void;\n}\n\nexport interface UseAiFeatureOptions {\n provider: AiProvider;\n editor: AiFeatureEditor;\n collaboration: Pick<UseCollaborationFeatureReturn, \"core\" | \"outline\"> | null;\n /** The snapshot history; read at call time (core is built after this). */\n history: () => Pick<UseHistoryReturn, \"record\">;\n /** Reload after a server-applied turn; check the guard before committing. */\n reload:\n | ((templateId: string, shouldApply?: () => boolean) => Promise<unknown>)\n | null;\n mergeTags: () => AiMergeTags;\n /** Bare merge tags to tags, as for remote batches (D8). */\n normalize: (\n ops: readonly Operation[],\n content: TemplateContent,\n ) => Operation[];\n /** The comments panel's state: AI panels and comments are exclusive (D18). */\n commentsOpen: Ref<boolean> | null;\n altMaxLength?: () => number;\n onError?: (error: Error) => void;\n}\n\ninterface TurnRecord {\n /** Undoes the turn: each batch's inverse, the last batch's first. */\n inverse: Operation[];\n /** Redoes it after an Undo: the inverse of the Undo batch. */\n redo: Operation[] | null;\n serverApplied: boolean;\n batchIds: Set<string>;\n}\n\ninterface Memory {\n generation: number;\n items: AiChatItem[];\n records: Map<string, TurnRecord>;\n storedIds: Set<string>;\n recoveries: Map<\n string,\n { item: AiChatItem; user?: AiChatItem; record: TurnRecord }\n >;\n}\n\nconst isAbort = (error: unknown): boolean =>\n error instanceof Error && error.name === \"AbortError\";\nconst asError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\nconst sum = (message: AiChatMessage) =>\n message.batches.reduce((total, batch) => total + batch.operationCount, 0);\n\nfunction hasBlock(blocks: readonly Block[], blockId: string): boolean {\n return blocks.some(\n (block) =>\n block.id === blockId ||\n (block.type === \"section\" &&\n Array.isArray((block as { children?: unknown }).children) &&\n (block as unknown as { children: Block[][] }).children.some(\n (column) => Array.isArray(column) && hasBlock(column, blockId),\n )),\n );\n}\n\nfunction refusalOf(error: OperationError): AiOperationsResult {\n return {\n applied: false,\n code: error.code,\n opIndex: error.opIndex,\n message: error.message,\n };\n}\n\nexport interface UseAiFeatureReturn {\n capability: NonNullable<EditorCapabilities[\"ai\"]>;\n panel: Ref<AiPanel | null>;\n open: (panel: AiPanel) => void;\n close: () => void;\n has: (feature: AiFeatureName) => boolean;\n /** The loaded template's id: AI works on it, and panels reset when it changes. */\n templateId: ComputedRef<string | null>;\n /** Changes on every committed load, including same-id reloads. */\n templateSession: ComputedRef<number | string | null>;\n /** Opaque identity; AI reconciliation keeps it, external committed loads replace it. */\n sessionIdentity: ComputedRef<object | null>;\n isAvailable: ComputedRef<boolean>;\n hasConversation: boolean;\n canClear: boolean;\n messages: Ref<AiChatItem[]>;\n isLoadingHistory: Ref<boolean>;\n /** True while any AI operation owns the serialized lane. */\n busy: Ref<boolean>;\n /** Alias of busy, retained for existing panels. */\n isRunning: Ref<boolean>;\n failure: Ref<AiFailure | null>;\n keptYourVersion: Ref<boolean>;\n reloadTemplate: () => Promise<void>;\n failedPrompt: Ref<string | null>;\n failedAttachments: Ref<File[]>;\n importQueue: Ref<File[]>;\n isTemplateEmpty: ComputedRef<boolean>;\n send: (message: string, attachments?: File[]) => Promise<AiTurnOutcome>;\n startImport: (files: File[]) => void;\n fix: (finding: AiFixFinding) => Promise<AiTurnOutcome>;\n stop: () => void;\n newChat: () => Promise<void>;\n undoMessage: (id: string) => Promise<void>;\n redoMessage: (id: string) => Promise<void>;\n rewrite: (\n input: Pick<\n AiRewriteRequest,\n \"html\" | \"preset\" | \"language\" | \"instruction\"\n >,\n onText: (text: string) => void,\n signal: AbortSignal,\n ) => Promise<{ html: string }>;\n draftAltText: (blockId: string, signal?: AbortSignal) => Promise<string>;\n applyAltTexts: (\n entries: Array<{\n blockId: string;\n alt: string;\n decorative: boolean;\n expect?: AiImageSnapshot;\n }>,\n ) => Promise<void>;\n destroy: () => void;\n}\n\n/**\n * The editor's side of `init({ ai })` (A1 §3): the capability its entry points\n * read, the request each call carries, the edits a turn hands over (applied\n * through the collaboration controller or through the engine and the snapshot\n * history, one undo step per turn), server-applied batches followed or\n * reloaded, the chat in `conversation` or in memory, and every failure to\n * `onError`. Built before `useEditorCore`; reads core through getters.\n */\nexport function useAiFeature(options: UseAiFeatureOptions): UseAiFeatureReturn {\n const { provider, editor, collaboration } = options;\n const conversation = provider.conversation ?? null;\n const localSessionId = crypto.randomUUID();\n\n const panel = ref<AiPanel | null>(null);\n const memory = new Map<string, Memory>();\n let destroyed = false;\n let authorVersion = 0;\n let applyingAi = false;\n type LaneKind =\n \"turn\" | \"replay\" | \"clear\" | \"history\" | \"read\" | \"reconcile\";\n interface Session {\n id: string;\n memory: Memory;\n generation: number;\n messages: Ref<AiChatItem[]>;\n isLoadingHistory: Ref<boolean>;\n busy: Ref<boolean>;\n keptYourVersion: Ref<boolean>;\n failure: Ref<AiFailure | null>;\n failedPrompt: Ref<string | null>;\n failedAttachments: Ref<File[]>;\n importQueue: Ref<File[]>;\n loaded: boolean;\n historyGeneration: number;\n pendingHistory: { generation: number; promise: Promise<void> } | null;\n active: Job | null;\n queue: Job[];\n lifetime: AbortController;\n committingReload: boolean;\n lastRecordedTurn: string | null;\n timers: Set<ReturnType<typeof setTimeout>>;\n highlights: Ref<ReadonlyMap<string, number>>;\n highlightSequence: number;\n }\n interface Job {\n kind: LaneKind;\n scope: Session;\n controller: AbortController;\n authorVersion: number;\n execute: () => Promise<void>;\n }\n\n function createSession(id: string): Session {\n const saved = memoryFor(id);\n return {\n id,\n memory: saved,\n generation: ++saved.generation,\n messages: ref(saved.items),\n isLoadingHistory: ref(false),\n busy: ref(false),\n keptYourVersion: ref(false),\n failure: ref(null),\n failedPrompt: ref(null),\n failedAttachments: shallowRef([]),\n importQueue: shallowRef([]),\n loaded: false,\n historyGeneration: 0,\n pendingHistory: null,\n active: null,\n queue: [],\n lifetime: new AbortController(),\n committingReload: false,\n lastRecordedTurn: null,\n timers: new Set(),\n highlights: shallowRef(new Map()),\n highlightSequence: 0,\n };\n }\n\n const templateId = computed(() => editor.state.template?.id ?? null);\n const currentSession = shallowRef<Session | null>(\n templateId.value === null ? null : createSession(templateId.value),\n );\n const isAvailable = computed(\n () =>\n currentSession.value !== null && !destroyed && templateId.value !== null,\n );\n const has = (feature: AiFeatureName): boolean =>\n feature === \"chatAttachments\"\n ? isAvailable.value &&\n provider.chatAttachments === true &&\n typeof provider.chat === \"function\"\n : typeof provider[feature] === \"function\";\n const scopeOf = (): Session | null =>\n destroyed ? null : currentSession.value;\n const isCurrent = (scope: Session): boolean =>\n !destroyed &&\n currentSession.value === scope &&\n !scope.lifetime.signal.aborted &&\n templateId.value === scope.id;\n\n // Stable public refs follow the current session, never an obsolete job's refs.\n function sessionRef<T>(select: (scope: Session) => Ref<T>, empty: T): Ref<T> {\n return computed({\n get: () =>\n currentSession.value ? select(currentSession.value).value : empty,\n set: (value) => {\n const scope = scopeOf();\n if (scope) select(scope).value = value;\n },\n });\n }\n const messages = sessionRef((scope) => scope.messages, []);\n const isTemplateEmpty = computed(\n () => editor.content.value.blocks.length === 0,\n );\n const isLoadingHistory = sessionRef((scope) => scope.isLoadingHistory, false);\n const isRunning = sessionRef((scope) => scope.busy, false);\n const failure = sessionRef((scope) => scope.failure, null);\n const keptYourVersion = sessionRef((scope) => scope.keptYourVersion, false);\n const failedPrompt = sessionRef((scope) => scope.failedPrompt, null);\n const failedAttachments = sessionRef((scope) => scope.failedAttachments, []);\n const importQueue = sessionRef((scope) => scope.importQueue, []);\n\n function invalidateHistory(scope: Session): void {\n scope.historyGeneration++;\n scope.pendingHistory = null;\n scope.loaded = false;\n scope.isLoadingHistory.value = false;\n }\n\n function enqueue<T>(\n kind: LaneKind,\n scope: Session,\n run: (job: Job) => Promise<T>,\n skipped: () => T | Promise<T>,\n ): Promise<T> {\n if (!isCurrent(scope)) return Promise.resolve().then(skipped);\n return new Promise<T>((resolve, reject) => {\n const job: Job = {\n kind,\n scope,\n controller: new AbortController(),\n authorVersion: 0,\n execute: async () => {\n job.authorVersion = authorVersion;\n let result: T;\n try {\n result = await (job.controller.signal.aborted || !isCurrent(scope)\n ? skipped()\n : run(job));\n } catch (error) {\n reject(error);\n return;\n } finally {\n scope.active = null;\n scope.busy.value = false;\n pump(scope);\n }\n resolve(result);\n },\n };\n scope.queue.push(job);\n pump(scope);\n });\n }\n\n function pump(scope: Session): void {\n if (scope.active) return;\n const job = scope.queue.shift();\n if (!job) return;\n scope.active = job;\n // Abandoned queues drain their skipped results without reviving busy state.\n if (isCurrent(scope)) scope.busy.value = true;\n void job.execute();\n }\n\n function check(job: Job): void {\n job.controller.signal.throwIfAborted();\n if (!isCurrent(job.scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n }\n\n async function abortable<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n ): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n const stopped = new Promise<never>((_, reject) => {\n abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n });\n try {\n return await Promise.race([promise, stopped]);\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n }\n\n async function reloadCurrent(\n job: Job,\n recoverStopped = false,\n expectedAuthorVersion = job.authorVersion,\n ): Promise<void> {\n const { scope } = job;\n const valid = () =>\n scope.active === job &&\n isCurrent(scope) &&\n (recoverStopped || !job.controller.signal.aborted);\n const canKeepReload = () => {\n if (!valid()) return false;\n if (expectedAuthorVersion !== authorVersion) {\n scope.keptYourVersion.value = true;\n return false;\n }\n return true;\n };\n if (!options.reload || !canKeepReload()) return;\n try {\n await abortable(\n options.reload(scope.id, () => {\n if (!canKeepReload()) return false;\n scope.keptYourVersion.value = false;\n scope.committingReload = true;\n return true;\n }),\n scope.lifetime.signal,\n );\n } finally {\n scope.committingReload = false;\n }\n }\n\n function memoryFor(id: string): Memory {\n let found = memory.get(id);\n if (!found) {\n found = {\n generation: 0,\n items: [],\n records: new Map(),\n storedIds: new Set(),\n recoveries: new Map(),\n };\n memory.set(id, found);\n }\n return found;\n }\n\n function later(scope: Session, run: () => void, ms: number): void {\n const timer = setTimeout(() => {\n scope.timers.delete(timer);\n run();\n }, ms);\n scope.timers.add(timer);\n }\n\n function report(error: unknown): void {\n if (!isAbort(error)) options.onError?.(asError(error));\n }\n\n // --- The asker's outline (D42) ---------------------------------------------\n\n function outline(scope: Session, blockIds: readonly string[]): void {\n if (blockIds.length === 0) return;\n if (collaboration) {\n collaboration.outline(blockIds);\n return;\n }\n const sequence = ++scope.highlightSequence;\n const next = new Map(scope.highlights.value);\n for (const id of blockIds) next.set(id, sequence);\n scope.highlights.value = next;\n later(\n scope,\n () => {\n const rest = new Map(scope.highlights.value);\n for (const id of blockIds)\n if (rest.get(id) === sequence) rest.delete(id);\n scope.highlights.value = rest;\n },\n AGENT_HIGHLIGHT_MS,\n );\n }\n\n // --- Requests (D12) --------------------------------------------------------\n\n async function settle(scope: Session): Promise<void> {\n if (!collaboration) return;\n await Promise.race([\n collaboration.core.settle().catch(() => {}),\n new Promise<void>((resolve) =>\n later(scope, resolve, AI_SETTLE_TIMEOUT_MS),\n ),\n ]);\n }\n\n function requestBase(id: string): AiRequestBase {\n const content = safeClone(toRaw(editor.content.value));\n if (\n new TextEncoder().encode(JSON.stringify(content)).length >\n AI_CONTENT_MAX_BYTES\n )\n throw new SdkError(\n \"This template is too large for AI.\",\n 413,\n \"content_too_large\",\n );\n return {\n templateId: id,\n content,\n revision: collaboration ? collaboration.core.revision.value : null,\n sessionId: collaboration ? collaboration.core.sessionId : localSessionId,\n mergeTags: options.mergeTags(),\n };\n }\n\n function selectedBlockId(): string | null {\n const id = editor.state.selectedBlockId;\n if (!id) return null;\n if (collaboration)\n return collaboration.core.hasConfirmedBlock(id) ? id : null;\n return hasBlock(editor.content.value.blocks, id) ? id : null;\n }\n\n // --- Applying edits (D6, D7, D8) ---------------------------------------------\n\n function applyOps(\n ops: Operation[],\n turn: string,\n scope: Session,\n ): AiOperationsResult {\n const normalized = options.normalize(ops, toRaw(editor.content.value));\n const summary = summarizeAgentEdit(normalized);\n if (collaboration) {\n const result = collaboration.core.applyOperations(normalized, {\n origin: \"ai\",\n turn,\n });\n if (!result.applied) return refusalOf(result.error);\n if (!summary.templateUpdated) outline(scope, summary.blockIds);\n return { applied: true, inverse: result.inverse };\n }\n let inverse: Operation[];\n try {\n // Also the check: it throws the engine's refusal for ops that don't apply.\n inverse = invertOperations(toRaw(editor.content.value), normalized);\n } catch (error) {\n if (error instanceof OperationError) return refusalOf(error);\n throw error;\n }\n if (scope.lastRecordedTurn !== turn) {\n options.history().record();\n scope.lastRecordedTurn = turn;\n }\n applyingAi = true;\n try {\n applyOperationsInPlace(editor.content.value, safeClone(normalized));\n editor.markDirty();\n } finally {\n applyingAi = false;\n }\n const selected = editor.state.selectedBlockId;\n if (selected && !hasBlock(editor.content.value.blocks, selected)) {\n editor.selectBlock(null);\n }\n if (!summary.templateUpdated) outline(scope, summary.blockIds);\n return { applied: true, inverse };\n }\n\n function followRevision(revision: number, scope: Session): void {\n if (!collaboration || !isCurrent(scope)) return;\n const core = collaboration.core;\n if (core.revision.value >= revision) return;\n if (core.connection.value !== \"connected\") {\n void core.catchUp();\n return;\n }\n later(\n scope,\n () => {\n if (isCurrent(scope) && core.revision.value < revision)\n void core.catchUp();\n },\n AI_BROADCAST_GRACE_MS,\n );\n }\n\n // --- Turns (D15, D16) --------------------------------------------------------\n\n function patch(\n scope: Session,\n key: string,\n changes: Partial<AiChatItem>,\n ): void {\n const saved = scope.memory;\n saved.items = saved.items.map((item) => {\n if (item.id !== key) return item;\n const next = { ...item, ...changes };\n return { ...next, ...replayAvailability(next, saved) };\n });\n for (const recovery of saved.recoveries.values()) {\n if (recovery.item.id === key) {\n recovery.item =\n saved.items.find((item) => item.id === (changes.id ?? key)) ??\n recovery.item;\n }\n }\n scope.messages.value = saved.items;\n }\n\n function replayAvailability(\n item: AiChatItem,\n saved: Memory,\n ): Pick<AiChatItem, \"canUndo\" | \"canRedo\"> {\n const eligible = item.role === \"assistant\" && item.operationCount > 0;\n if (saved.storedIds.has(item.id)) {\n return {\n canUndo:\n eligible && !item.undone && typeof conversation?.undo === \"function\",\n canRedo:\n eligible && item.undone && typeof conversation?.redo === \"function\",\n };\n }\n const record = saved.records.get(item.id);\n return {\n canUndo:\n eligible &&\n !item.undone &&\n !record?.serverApplied &&\n (record?.inverse.length ?? 0) > 0,\n canRedo:\n eligible &&\n item.undone &&\n !record?.serverApplied &&\n (record?.redo?.length ?? 0) > 0,\n };\n }\n\n const emptyOutcome = (): AiTurnOutcome => ({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n\n function runTurn(\n kind: AiMessageKind,\n userText: string,\n call: (\n base: AiRequestBase,\n handlers: AiTurnHandlers,\n signal: AbortSignal,\n ) => Promise<AiTurnResult>,\n attachments: File[] = [],\n ): Promise<AiTurnOutcome> {\n const scope = scopeOf();\n if (\n !scope ||\n scope.active?.kind === \"turn\" ||\n scope.queue.some((job) => job.kind === \"turn\")\n )\n return Promise.resolve(emptyOutcome());\n return enqueue(\n \"turn\",\n scope,\n async (job) => {\n const { controller } = job;\n const saved = scope.memory;\n const turn = crypto.randomUUID();\n const userKey = crypto.randomUUID();\n let key: string = crypto.randomUUID();\n let operationCount = 0;\n let text = \"\";\n let interrupted = false;\n let refusal: SdkError | null = null;\n const record: TurnRecord = {\n inverse: [],\n redo: null,\n serverApplied: false,\n batchIds: new Set(),\n };\n let outcome: AiTurnOutcome;\n let completed = false;\n let reconciling = false;\n const update = (changes: Partial<AiChatItem>) =>\n patch(scope, key, changes);\n const rememberRecovery = () => {\n const item = saved.items.find((item) => item.id === key);\n if (conversation && item)\n saved.recoveries.set(turn, {\n item,\n user: saved.items.find((item) => item.id === userKey),\n record,\n });\n };\n const reconcileLateApplied = () => {\n if (\n reconciling ||\n (!conversation && (collaboration || !options.reload))\n )\n return;\n reconciling = true;\n // Stop cancels provider work immediately. Received server facts still\n // enter the lane and reload only the session that requested the turn.\n void enqueue(\n \"reconcile\",\n scope,\n async (recovery) => {\n try {\n let observed: number;\n do {\n observed = operationCount;\n if (!collaboration && options.reload)\n await reloadCurrent(recovery, true, job.authorVersion);\n if (conversation) await readHistory(recovery, true, true);\n } while (isCurrent(scope) && observed !== operationCount);\n } catch (error) {\n if (isCurrent(scope)) report(error);\n } finally {\n reconciling = false;\n }\n },\n () => {\n reconciling = false;\n },\n );\n };\n const handlers: AiTurnHandlers = {\n onText: (chunk) => {\n check(job);\n text += chunk;\n update({ text });\n },\n onOperations: async (ops) => {\n check(job);\n const result = applyOps(ops, turn, scope);\n if (result.applied) {\n record.inverse = [...result.inverse, ...record.inverse];\n operationCount += ops.length;\n update({ operationCount });\n }\n return result;\n },\n onApplied: (batch) => {\n // An applied batch is a fact, including one received during Stop.\n if (!isCurrent(scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n if (!collaboration && !options.reload) {\n refusal ??= new SdkError(\n AI_MISSING_PROVIDER_MESSAGE,\n 502,\n \"ai_provider_error\",\n );\n throw refusal;\n }\n record.serverApplied = true;\n record.batchIds.add(batch.batchId);\n operationCount += batch.operationCount;\n update({ operationCount });\n followRevision(batch.revision, scope);\n if (completed) {\n rememberRecovery();\n reconcileLateApplied();\n }\n },\n };\n try {\n try {\n await readHistory(job);\n check(job);\n scope.failure.value = null;\n scope.failedPrompt.value = null;\n scope.failedAttachments.value = [];\n const now = new Date().toISOString();\n saved.records.set(key, record);\n saved.items = [\n ...saved.items,\n {\n id: userKey,\n role: \"user\",\n kind,\n text: userText,\n attachments: attachments.map((file) => ({\n name: file.name,\n kind: file.type === \"application/pdf\" ? \"pdf\" : \"image\",\n })),\n operationCount: 0,\n undone: false,\n canUndo: false,\n canRedo: false,\n createdAt: now,\n status: \"done\",\n },\n {\n id: key,\n role: \"assistant\",\n kind,\n text: \"\",\n attachments: [],\n operationCount: 0,\n undone: false,\n canUndo: false,\n canRedo: false,\n createdAt: now,\n status: \"streaming\",\n },\n ];\n scope.messages.value = saved.items;\n await abortable(settle(scope), job.controller.signal);\n check(job);\n const result = await abortable(\n call(requestBase(scope.id), handlers, controller.signal),\n controller.signal,\n );\n check(job);\n if (refusal) throw refusal;\n if (result.text !== \"\") text = result.text;\n if (result.messageId !== null && conversation) {\n const previousKey = key;\n key = result.messageId;\n saved.storedIds.add(key);\n saved.records.delete(previousKey);\n saved.records.set(key, record);\n patch(scope, previousKey, { id: key });\n }\n update({ text, status: \"done\" });\n outcome = { messageId: key, operationCount, text, failed: false };\n } catch (caught) {\n const error = refusal ?? caught;\n interrupted = controller.signal.aborted || isAbort(error);\n if (!interrupted) report(error);\n if (operationCount === 0 && (!interrupted || text === \"\")) {\n saved.items = saved.items.filter(\n (item) => item.id !== key && item.id !== userKey,\n );\n if (isCurrent(scope)) {\n scope.messages.value = saved.items;\n if (!interrupted) {\n if (kind === \"chat\") {\n scope.failedPrompt.value = userText;\n scope.failedAttachments.value = attachments;\n }\n scope.failure.value = {\n error: asError(error),\n context: \"turn\",\n };\n }\n }\n outcome = {\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: !interrupted,\n };\n } else {\n update({\n status: interrupted ? \"done\" : \"failed\",\n failure: interrupted\n ? undefined\n : { error: asError(error), context: \"turn\" },\n });\n outcome = {\n messageId: key,\n operationCount,\n text,\n failed: !interrupted,\n };\n }\n }\n\n // Recovery belongs to the turn, even after Stop. Switching templates\n // still discards it; a user Stop retains the changes already applied.\n if (\n conversation &&\n outcome.messageId !== null &&\n operationCount > 0 &&\n (outcome.failed || interrupted)\n ) {\n rememberRecovery();\n }\n let observed: number;\n do {\n observed = operationCount;\n if (\n record.serverApplied &&\n !collaboration &&\n options.reload &&\n isCurrent(scope)\n ) {\n await reloadCurrent(job, true).catch((error) => {\n if (isCurrent(scope)) report(error);\n });\n }\n if (\n conversation &&\n saved.recoveries.has(turn) &&\n isCurrent(scope)\n ) {\n await readHistory(job, true, true);\n const recovered = saved.recoveries.get(turn);\n if (recovered) {\n outcome.messageId = recovered.item.id;\n outcome.text = recovered.item.text;\n }\n }\n } while (\n isCurrent(scope) &&\n record.serverApplied &&\n observed !== operationCount\n );\n outcome.operationCount = operationCount;\n // Stop may arrive during the final reload, after the provider-call\n // catch. Applied edits and recovery remain, but the turn did not finish.\n if (interrupted || controller.signal.aborted) outcome.failed = true;\n return outcome;\n } finally {\n completed = true;\n scope.messages.value = saved.items;\n }\n },\n emptyOutcome,\n );\n }\n\n // --- Undo and Redo of a message (D13, D14) ------------------------------------\n\n function replay(id: string, direction: \"undo\" | \"redo\"): Promise<void> {\n const scope = scopeOf();\n if (!scope || scope.busy.value) return Promise.resolve();\n return enqueue(\n \"replay\",\n scope,\n async (job) => {\n const saved = scope.memory;\n const item = saved.items.find((item) => item.id === id);\n if (!item) return;\n const remote = conversation?.[direction];\n const record = saved.records.get(id);\n try {\n check(job);\n if (saved.storedIds.has(id)) {\n if (typeof remote !== \"function\") {\n throw new SdkError(\n `This AI backend does not support ${direction}.`,\n 403,\n \"feature_unavailable\",\n );\n }\n if (item.undone !== (direction === \"redo\")) return;\n const answer = await abortable(\n remote(scope.id, id, {\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n }),\n scope.lifetime.signal,\n );\n if (!isCurrent(scope)) return;\n if (\"operations\" in answer) {\n if (job.controller.signal.aborted) return;\n const result = applyOps(\n answer.operations,\n `${direction}:${id}:${crypto.randomUUID()}`,\n scope,\n );\n if (result.applied) {\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n }\n try {\n await abortable(\n conversation!.settleReplay(scope.id, id, {\n replayId: answer.replayId,\n direction,\n applied: result.applied,\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n }),\n scope.lifetime.signal,\n );\n } catch (error) {\n if (!isCurrent(scope)) return;\n report(error);\n patch(scope, id, {\n failure: { error: asError(error), context: direction },\n });\n }\n if (!isCurrent(scope)) return;\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n return;\n } else {\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n if (collaboration) followRevision(answer.applied.revision, scope);\n else if (options.reload) await reloadCurrent(job, true);\n else\n throw new SdkError(\n AI_MISSING_PROVIDER_MESSAGE,\n 502,\n \"ai_provider_error\",\n );\n return;\n }\n } else {\n if (item.undone !== (direction === \"redo\")) return;\n const ops = direction === \"undo\" ? record?.inverse : record?.redo;\n if (!record || record.serverApplied || !ops || ops.length === 0)\n return;\n const result = applyOps(\n ops,\n `${direction}:${id}:${crypto.randomUUID()}`,\n scope,\n );\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n if (direction === \"undo\") record.redo = result.inverse;\n else record.inverse = result.inverse;\n }\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n } catch (error) {\n if (!isCurrent(scope) || isAbort(error)) return;\n report(error);\n patch(scope, id, {\n failure: { error: asError(error), context: direction },\n });\n }\n },\n () => {},\n );\n }\n\n // --- History (D14) -----------------------------------------------------------\n\n function toItem(message: AiChatMessage, saved: Memory): AiChatItem {\n const item: AiChatItem = {\n id: message.id,\n role: message.role,\n kind: message.kind,\n text: message.text,\n attachments: message.attachments ?? [],\n operationCount: sum(message),\n undone: message.undone,\n canUndo: false,\n canRedo: false,\n createdAt: message.createdAt,\n status: \"done\",\n };\n return { ...item, ...replayAvailability(item, saved) };\n }\n\n function mergeHistory(list: AiChatMessage[], saved: Memory): AiChatItem[] {\n for (const message of list) saved.storedIds.add(message.id);\n const previous = new Map(saved.items.map((item) => [item.id, item]));\n let items = list.map((message) => {\n const item = toItem(message, saved);\n const old = previous.get(item.id);\n return old?.status === \"failed\"\n ? { ...item, status: old.status, failure: old.failure }\n : item;\n });\n for (const recovery of saved.recoveries.values()) {\n const { item, record } = recovery;\n // Only persisted identity can associate a local failure with a stored\n // message. Other sessions may append messages of the same kind at any time.\n const matches = list.filter(\n (message) =>\n message.role === \"assistant\" &&\n message.kind === item.kind &&\n (message.id === item.id ||\n (record.batchIds.size > 0 &&\n [...record.batchIds].every((id) =>\n message.batches.some((batch) => batch.batchId === id),\n ))),\n );\n const persisted = matches.length === 1 ? matches[0] : undefined;\n if (persisted) {\n saved.records.delete(item.id);\n saved.records.set(persisted.id, record);\n const reconciled = {\n ...toItem(persisted, saved),\n status: item.status,\n failure: item.failure,\n };\n recovery.item = reconciled;\n items = items.map((row) =>\n row.id === persisted.id ? reconciled : row,\n );\n } else {\n if (recovery.user && !items.some((row) => row.id === recovery.user!.id))\n items.push(recovery.user);\n items.push({ ...item, ...replayAvailability(item, saved) });\n }\n }\n return items;\n }\n\n async function readHistory(\n job: Job,\n force = false,\n recoverStopped = false,\n token = job.scope.historyGeneration,\n ): Promise<void> {\n const { scope } = job;\n if (\n !isCurrent(scope) ||\n token !== scope.historyGeneration ||\n (!recoverStopped && job.controller.signal.aborted)\n )\n return;\n if (!force && scope.loaded) return;\n const saved = scope.memory;\n if (!conversation) {\n scope.messages.value = saved.items;\n scope.loaded = true;\n return;\n }\n scope.isLoadingHistory.value = true;\n scope.loaded = false;\n try {\n const request = conversation.list(scope.id).then((list) => {\n if (\n destroyed ||\n saved.generation !== scope.generation ||\n token !== scope.historyGeneration ||\n (!recoverStopped &&\n (!isCurrent(scope) || job.controller.signal.aborted))\n )\n return;\n // A late recovery can reconcile remembered A, but only A's session refs\n // are published. The public refs may already belong to B or a new A.\n saved.items = mergeHistory(list, saved);\n scope.messages.value = saved.items;\n scope.loaded = true;\n if (scope.failure.value?.context === \"history\")\n scope.failure.value = null;\n });\n await abortable(\n request,\n recoverStopped ? scope.lifetime.signal : job.controller.signal,\n );\n } catch (error) {\n if (\n !isCurrent(scope) ||\n token !== scope.historyGeneration ||\n isAbort(error)\n )\n return;\n report(error);\n scope.failure.value = { error: asError(error), context: \"history\" };\n } finally {\n if (token === scope.historyGeneration)\n scope.isLoadingHistory.value = false;\n }\n }\n\n function loadConversation(scope = scopeOf()): Promise<void> {\n if (!scope || !isCurrent(scope)) return Promise.resolve();\n if (scope.pendingHistory?.generation === scope.historyGeneration)\n return scope.pendingHistory.promise;\n if (scope.loaded) return Promise.resolve();\n const token = scope.historyGeneration;\n const pending = { generation: token, promise: Promise.resolve() };\n const promise = enqueue(\n \"history\",\n scope,\n (job) => readHistory(job, false, false, token),\n () => {},\n );\n pending.promise = promise.finally(() => {\n if (scope.pendingHistory === pending) scope.pendingHistory = null;\n });\n scope.pendingHistory = pending;\n return pending.promise;\n }\n\n function newChat(): Promise<void> {\n const scope = scopeOf();\n if (\n !scope ||\n (conversation && typeof conversation.clear !== \"function\") ||\n (scope.active &&\n scope.active.kind !== \"history\" &&\n scope.active.kind !== \"read\") ||\n scope.queue.some((job) => job.kind !== \"history\" && job.kind !== \"read\")\n )\n return Promise.resolve();\n invalidateHistory(scope);\n scope.active?.controller.abort();\n return enqueue(\n \"clear\",\n scope,\n async () => {\n try {\n if (conversation && typeof conversation.clear === \"function\")\n await conversation.clear(scope.id);\n // A returning session owns a newer generation of this shared memory.\n // Its turns and replay records must survive this abandoned clear.\n if (scope.memory.generation !== scope.generation) return;\n // The backend cleared this template even if another session is current.\n memory.delete(scope.id);\n scope.memory.items = [];\n scope.memory.records.clear();\n scope.memory.storedIds.clear();\n scope.memory.recoveries.clear();\n invalidateHistory(scope);\n scope.messages.value = [];\n scope.loaded = true;\n scope.failure.value = null;\n scope.failedPrompt.value = null;\n scope.failedAttachments.value = [];\n if (isCurrent(scope)) memory.set(scope.id, scope.memory);\n } catch (error) {\n if (!isCurrent(scope)) return;\n report(error);\n scope.failure.value = { error: asError(error), context: \"history\" };\n }\n },\n () => {},\n );\n }\n\n // --- Panels (D17, D18) -------------------------------------------------------------\n\n function bootstrap(scope: Session): void {\n if (!isCurrent(scope)) return;\n void loadConversation(scope);\n }\n\n function open(next: AiPanel): void {\n const scope = scopeOf();\n if (!scope || !isCurrent(scope)) return;\n if (panel.value !== next && scope.busy.value) stop();\n panel.value = next;\n if (options.commentsOpen) options.commentsOpen.value = false;\n if (next === \"chat\") bootstrap(scope);\n }\n\n function startImport(files: File[]): void {\n if (files.length === 0 || !has(\"chatAttachments\")) return;\n importQueue.value = [...files];\n open(\"chat\");\n }\n\n function stopSession(scope: Session): void {\n scope.active?.controller.abort();\n for (const job of scope.queue) {\n if (job.kind !== \"reconcile\") job.controller.abort();\n }\n }\n\n function abandon(scope: Session): void {\n scope.lifetime.abort();\n stopSession(scope);\n scope.busy.value = false;\n scope.isLoadingHistory.value = false;\n for (const timer of scope.timers) clearTimeout(timer);\n scope.timers.clear();\n }\n\n function stop(): void {\n const scope = scopeOf();\n if (scope) stopSession(scope);\n }\n\n function close(): void {\n stop();\n panel.value = null;\n }\n\n const watchers: (() => void)[] = [\n watch(\n () => editor.state.isDirty,\n (dirty, previous) => {\n // Core clears dirty during save only when that successful request covers\n // the current mutation revision. A failed or superseded save stays dirty.\n if (previous === true && dirty === false && editor.state.isSaving)\n keptYourVersion.value = false;\n },\n { flush: \"sync\" },\n ),\n watch(\n editor.content,\n () => {\n if (!applyingAi && !currentSession.value?.committingReload)\n authorVersion++;\n },\n { deep: true, flush: \"sync\" },\n ),\n ];\n if (options.commentsOpen) {\n watchers.push(\n watch(options.commentsOpen, (isOpen) => {\n if (isOpen) close();\n }),\n );\n }\n\n watchers.push(\n watch(\n () => editor.loadVersion?.value ?? templateId.value,\n () => {\n if (destroyed) return;\n const previous = currentSession.value;\n if (previous?.committingReload && isCurrent(previous)) {\n previous.committingReload = false;\n return;\n }\n if (previous) abandon(previous);\n const id = templateId.value;\n const next = id === null ? null : createSession(id);\n currentSession.value = next;\n if (next && panel.value === \"chat\") bootstrap(next);\n },\n { flush: \"sync\" },\n ),\n );\n\n async function draftAltText(\n blockId: string,\n signal?: AbortSignal,\n ): Promise<string> {\n const scope = scopeOf();\n const altText = provider.altText;\n const controller = new AbortController();\n const abort = () => controller.abort(signal?.reason);\n const abandonDraft = () => controller.abort();\n try {\n signal?.throwIfAborted();\n if (!scope || typeof altText !== \"function\")\n throw new SdkError(\n \"This AI feature isn't available.\",\n 403,\n \"feature_unavailable\",\n );\n const context = aiImageContext(editor.content.value, blockId);\n if (!context)\n throw new SdkError(\n \"The image is no longer available.\",\n 409,\n \"block_missing\",\n );\n signal?.addEventListener(\"abort\", abort, { once: true });\n scope.lifetime.signal.addEventListener(\"abort\", abandonDraft, {\n once: true,\n });\n const { url, ...rest } = context;\n const answer = await abortable(\n altText(\n {\n templateId: scope.id,\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n blockId,\n image: { url },\n ...rest,\n locale: editor.content.value.settings.locale,\n maxLength: options.altMaxLength?.() ?? DEFAULT_ALT_MAX_LENGTH,\n },\n controller.signal,\n ),\n controller.signal,\n );\n controller.signal.throwIfAborted();\n if (!isCurrent(scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n return answer.alt;\n } catch (error) {\n report(error);\n throw error;\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n scope?.lifetime.signal.removeEventListener(\"abort\", abandonDraft);\n }\n }\n\n function applyAltTexts(\n entries: Array<{\n blockId: string;\n alt: string;\n decorative: boolean;\n expect?: AiImageSnapshot;\n }>,\n ): Promise<void> {\n const scope = scopeOf();\n if (!scope || entries.length === 0) return Promise.resolve();\n const ops: Operation[] = entries.map(\n ({ blockId, alt, decorative, expect }) => ({\n op: \"updateBlock\",\n blockId,\n expect: {\n ...(expect ??\n aiImageSnapshot(editor.content.value, blockId) ?? {\n src: null,\n alt: null,\n decorative: null,\n }),\n },\n set: { alt, decorative },\n }),\n );\n return enqueue(\n \"replay\",\n scope,\n async (job) => {\n try {\n check(job);\n const turn = crypto.randomUUID();\n for (let start = 0; start < ops.length; start += 100) {\n check(job);\n const result = applyOps(ops.slice(start, start + 100), turn, scope);\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n }\n } catch (error) {\n report(error);\n throw error;\n }\n },\n () => {},\n );\n }\n\n // --- The features ------------------------------------------------------------------\n\n return {\n capability: {\n isFeatureEnabled: (feature) => isAvailable.value && has(feature),\n open,\n startImport,\n highlightOf: (blockId) =>\n currentSession.value?.highlights.value.get(blockId) ?? null,\n },\n panel,\n open,\n close,\n has,\n templateId,\n sessionIdentity: computed(() => currentSession.value),\n templateSession: computed(\n () => editor.loadVersion?.value ?? templateId.value,\n ),\n isAvailable,\n hasConversation: conversation !== null,\n canClear: conversation === null || typeof conversation.clear === \"function\",\n messages,\n isLoadingHistory,\n isRunning,\n busy: isRunning,\n failure,\n keptYourVersion,\n reloadTemplate: () => {\n const scope = scopeOf();\n return scope\n ? enqueue(\n \"reconcile\",\n scope,\n (job) => reloadCurrent(job),\n () => {},\n )\n : Promise.resolve();\n },\n failedPrompt,\n failedAttachments,\n importQueue,\n startImport,\n isTemplateEmpty,\n send: (message, attachments = []) => {\n const chat = provider.chat;\n return typeof chat === \"function\"\n ? runTurn(\n \"chat\",\n message,\n (base, handlers, signal) =>\n chat(\n {\n ...base,\n message,\n selectedBlockId: selectedBlockId(),\n attachments: attachments.map((file) => ({\n file,\n name: file.name,\n kind: file.type === \"application/pdf\" ? \"pdf\" : \"image\",\n })),\n },\n handlers,\n signal,\n ),\n attachments,\n )\n : Promise.resolve({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n },\n fix: (finding) => {\n const fixFinding = provider.fixFinding;\n return typeof fixFinding === \"function\"\n ? runTurn(\"fix\", `Fix: ${finding.message}`, (base, handlers, signal) =>\n fixFinding({ ...base, finding }, handlers, signal),\n )\n : Promise.resolve({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n },\n stop,\n newChat,\n undoMessage: (id) => replay(id, \"undo\"),\n redoMessage: (id) => replay(id, \"redo\"),\n rewrite: (input, onText, signal) => {\n const scope = scopeOf();\n const rewrite = provider.rewrite;\n if (!scope || typeof rewrite !== \"function\")\n return Promise.reject(new Error(\"Rewrite isn't available.\"));\n return enqueue(\n \"read\",\n scope,\n async (job) => {\n const abort = () => job.controller.abort(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n signal.throwIfAborted();\n check(job);\n return await abortable(\n rewrite(\n { ...requestBase(scope.id), ...input },\n {\n onText: (text) => {\n check(job);\n onText(text);\n },\n },\n job.controller.signal,\n ),\n job.controller.signal,\n );\n } catch (error) {\n report(error);\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n },\n () => {\n throw new DOMException(\"Rewrite stopped.\", \"AbortError\");\n },\n );\n },\n draftAltText,\n applyAltTexts,\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n const scope = currentSession.value;\n if (scope) abandon(scope);\n currentSession.value = null;\n for (const unwatch of watchers) unwatch();\n watchers.length = 0;\n },\n };\n}\n","import type {\n AiMergeTag,\n AiMergeTagSyntax,\n AiMergeTags,\n MergeTag,\n SyntaxPreset,\n SyntaxPresetName,\n} from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\n\n/** The wire's caps on merge tags, in code points (S7 Y5, S8 X4). */\nexport const AI_MERGE_TAG_LIMITS = {\n tags: 500,\n value: 200,\n label: 100,\n group: 100,\n description: 200,\n} as const;\n\n/** `text` cut to `max` code points, so a surrogate pair is never split. */\nfunction truncate(text: string, max: number): string {\n const points = Array.from(text);\n return points.length > max ? points.slice(0, max).join(\"\") : text;\n}\n\n/** The built-in preset whose patterns the syntax carries, or `custom`. */\nexport function mergeTagSyntaxName(syntax: SyntaxPreset): AiMergeTagSyntax {\n for (const name of Object.keys(SYNTAX_PRESETS) as SyntaxPresetName[]) {\n const preset = SYNTAX_PRESETS[name];\n if (\n preset.value.source === syntax.value.source &&\n preset.logic.source === syntax.logic.source\n ) {\n return name;\n }\n }\n return \"custom\";\n}\n\n/**\n * The editor's merge tags as an AI request carries them, within the caps:\n * at most 500 in order; a value that is empty or over 200 code points is left\n * out (a cut value names another tag); label, group and description are cut;\n * an empty label falls back to the value; `sample` never travels. The syntax\n * travels even when no tag is declared (`tags: []`).\n */\nexport function toAiMergeTags(\n tags: readonly MergeTag[],\n syntax: SyntaxPreset,\n): AiMergeTags {\n const out: AiMergeTag[] = [];\n for (const tag of tags) {\n if (out.length === AI_MERGE_TAG_LIMITS.tags) break;\n const value = typeof tag?.value === \"string\" ? tag.value : \"\";\n if (value === \"\" || Array.from(value).length > AI_MERGE_TAG_LIMITS.value)\n continue;\n const label =\n typeof tag.label === \"string\" && tag.label !== \"\" ? tag.label : value;\n out.push({\n value,\n label: truncate(label, AI_MERGE_TAG_LIMITS.label),\n ...(typeof tag.group === \"string\" && tag.group !== \"\"\n ? { group: truncate(tag.group, AI_MERGE_TAG_LIMITS.group) }\n : {}),\n ...(typeof tag.description === \"string\" && tag.description !== \"\"\n ? {\n description: truncate(\n tag.description,\n AI_MERGE_TAG_LIMITS.description,\n ),\n }\n : {}),\n });\n }\n return { syntax: mergeTagSyntaxName(syntax), tags: out };\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport type {\n MediaAsset,\n MediaCategory,\n MediaProvider,\n MediaRequestContext,\n MediaResult,\n} from \"@templatical/types\";\nimport type { OnRequestMedia } from \"../index\";\nimport { toNaturalSize } from \"../utils/imageNaturalSize\";\n\nexport interface UseMediaFeatureOptions {\n /** Storage backend. Absent with a callback-only config (a host widget). */\n provider?: MediaProvider;\n /**\n * UI override. Wins over {@link provider} when both are set — the host\n * brought a widget, so the built-in modal never opens.\n */\n onRequestMedia?: OnRequestMedia;\n /**\n * Current template id, read at request time. Passed on `create` when a\n * template is loaded; omitted on a blank canvas. Media is not gated on it.\n */\n getTemplateId?: () => string | undefined;\n onError?: (error: Error) => void;\n}\n\nexport interface UseMediaFeatureReturn {\n /**\n * What `useEditorCore` provides as `ON_REQUEST_MEDIA_KEY`. Null when\n * neither a provider nor a callback is configured, which is what keeps\n * image fields URL-only.\n */\n requestMedia: OnRequestMedia | null;\n /**\n * What `useEditorCore` provides as `CAN_DROP_MEDIA_KEY`. True when a\n * host callback is set (it receives `files`) or when `provider.create`\n * is a function. False for a read-only library (`create: false`) so\n * the drop zone does not highlight while Browse still works.\n */\n canDrop: ComputedRef<boolean>;\n isModalOpen: Ref<boolean>;\n accept: Ref<MediaCategory[] | undefined>;\n close: () => void;\n select: (asset: MediaAsset) => void;\n templateId: ComputedRef<string | undefined>;\n onError?: (error: Error) => void;\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\n/**\n * Client pre-check for a dropped file. Matches the modal's `isAcceptedFile`:\n * omitted `maxFileSize` / `mimeTypes` are no cap; an explicit `0` or `{}`\n * is a stated floor. `accept` narrows the mime list when the drop named\n * categories (image fields pass `[\"images\"]`).\n *\n * Reads `maxFileSize` / `mimeTypes` off the provider at call time — Cloud\n * implements them as getters over plan config that arrives after setup.\n */\nfunction dropFileError(\n provider: MediaProvider,\n file: File,\n accept?: MediaCategory[],\n): Error | null {\n const maxFileSize = provider.maxFileSize ?? Number.POSITIVE_INFINITY;\n if (file.size > maxFileSize) {\n return new Error(\n `Image is too large (${file.size} bytes). Maximum allowed is ${maxFileSize} bytes.`,\n );\n }\n\n const mimeTypes = provider.mimeTypes;\n if (!mimeTypes) return null;\n\n const categories =\n accept && accept.length > 0\n ? accept\n : (Object.keys(mimeTypes) as MediaCategory[]);\n const allowed = categories.some(\n (category) => mimeTypes[category]?.includes(file.type) ?? false,\n );\n if (allowed) return null;\n\n return new Error(`Unsupported image type: ${file.type || \"unknown\"}.`);\n}\n\n/**\n * Synthesizes the function image fields inject as `ON_REQUEST_MEDIA_KEY`.\n *\n * `onRequestMedia` is the UI override (a host widget) and wins when both\n * are set. Otherwise a configured `media` provider opens the lazy library\n * modal, except on drop: a `create` function uploads the file without\n * opening, and `create: false` refuses the drop. Size/type after the\n * drop zone's `image/` filter is `MediaOptions`, read live on each drop.\n */\nexport function useMediaFeature(\n options: UseMediaFeatureOptions,\n): UseMediaFeatureReturn {\n const { provider, onRequestMedia, getTemplateId, onError } = options;\n\n const isModalOpen = ref(false);\n const accept = ref<MediaCategory[] | undefined>(undefined);\n const templateId = computed(() => getTemplateId?.());\n // Callback present ⇒ drop goes to the host widget. Otherwise only a\n // `create` function uploads; `create: false` is a read-only library.\n const canDrop = computed(\n () => !!onRequestMedia || typeof provider?.create === \"function\",\n );\n\n let pending: ((result: MediaResult | null) => void) | null = null;\n\n function settle(result: MediaResult | null): void {\n isModalOpen.value = false;\n pending?.(result);\n pending = null;\n }\n\n function select(asset: MediaAsset): void {\n settle(toMediaResult(asset));\n }\n\n function close(): void {\n settle(null);\n }\n\n onScopeDispose(() => {\n if (pending) settle(null);\n });\n\n const requestMedia: OnRequestMedia | null =\n onRequestMedia || provider\n ? async (context?: MediaRequestContext): Promise<MediaResult | null> => {\n if (onRequestMedia) {\n return onRequestMedia(context);\n }\n\n if (!provider) return null;\n\n if (context?.files?.length) {\n if (typeof provider.create !== \"function\") {\n return null;\n }\n const file = context.files[0];\n const rejected = dropFileError(provider, file, context.accept);\n if (rejected) {\n onError?.(rejected);\n return null;\n }\n const id = getTemplateId?.();\n try {\n const asset = await provider.create({\n file,\n ...(id ? { templateId: id } : {}),\n });\n try {\n provider.onCreated?.(asset);\n } catch (err) {\n onError?.(toError(err));\n }\n return toMediaResult(asset);\n } catch (err) {\n onError?.(toError(err));\n return null;\n }\n }\n\n if (pending) {\n pending(null);\n pending = null;\n }\n accept.value = context?.accept;\n isModalOpen.value = true;\n return new Promise<MediaResult | null>((resolve) => {\n pending = resolve;\n });\n }\n : null;\n\n return {\n requestMedia,\n canDrop,\n isModalOpen,\n accept,\n close,\n select,\n templateId,\n onError,\n };\n}\n\n/**\n * What an image field receives for a library asset: its URL and alt, plus the\n * file's size when the store knows both dimensions, for the image block's\n * aspect-ratio lock.\n */\nfunction toMediaResult(asset: MediaAsset): MediaResult {\n const size = toNaturalSize(asset.width, asset.height);\n return {\n url: asset.url,\n alt: asset.alt,\n ...(size ? { width: size.width, height: size.height } : {}),\n };\n}\n","import { computed, provide, ref, watch, type ComputedRef, type Ref } from \"vue\";\nimport { useSavedBlocks, type UseSavedBlocksReturn } from \"@templatical/core\";\nimport type {\n Block,\n SavedBlock,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { cloneBlock } from \"@templatical/types\";\nimport { SAVED_BLOCKS_KEY } from \"../keys\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — satisfied by OSS and Cloud alike. */\ninterface SavedBlocksEditor {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n /** Read reactively to cancel a pick session when preview mode turns on. */\n state: { previewMode: boolean };\n}\n\nexport interface UseSavedBlocksFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: SavedBlocksProvider;\n editor: SavedBlocksEditor;\n onError?: (error: Error) => void;\n /**\n * Whether the feature may be used. Read reactively, so Cloud can defer to a\n * plan entitlement that only resolves after its async config fetch. Omit for\n * always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseSavedBlocksFeatureReturn {\n headless: UseSavedBlocksReturn;\n\n // --- Pick session ---\n isPicking: ComputedRef<boolean>;\n pickedIds: Ref<Set<string>>;\n pickedCount: ComputedRef<number>;\n startPicking: (blockId: string) => void;\n togglePick: (blockId: string) => void;\n isPicked: (blockId: string) => boolean;\n confirmPicking: () => void;\n cancelPicking: () => void;\n\n // --- Dialogs ---\n isSaveDialogOpen: Ref<boolean>;\n closeSaveDialog: () => void;\n isBrowserOpen: Ref<boolean>;\n openBrowser: () => void;\n closeBrowser: () => void;\n\n /** Insert a saved block's content into the canvas, with fresh block IDs. */\n insert: (saved: SavedBlock, insertIndex: number | undefined) => void;\n /** Re-read the list from the provider (used after a successful save). */\n refresh: () => void;\n /** Capability object handed to `useEditorCore` so shared UI can light up. */\n capability: NonNullable<EditorCapabilities[\"savedBlocks\"]>;\n count: ComputedRef<number>;\n isAvailable: ComputedRef<boolean>;\n}\n\n/**\n * Shared glue for the saved-blocks feature: reactive list, the canvas pick\n * session, the insert operation, and the capability object the shared UI gates\n * on.\n *\n * Both `Editor.vue` (OSS) and `useCloudInitialization` (Cloud) call this with\n * their own provider, so the two entry points run identical logic over\n * different transports. Nothing here is auth- or plan-aware — callers decide\n * whether the feature is available *before* constructing it.\n *\n * **The pick session is deliberately local to this feature.** Choosing which\n * blocks to save happens on the canvas (the user's mental model is spatial),\n * but it does NOT touch `EditorState.selectedBlockId`: keeping it a transient\n * mode avoids a breaking core-state change, leaves Cloud's single-block\n * selection broadcast and block locking untouched, and steers clear of\n * Sortable multi-drag. Promote it to real multi-select only if a second\n * consumer needs it.\n *\n * Must be called from `setup()`: it `provide()`s the headless instance under\n * {@link SAVED_BLOCKS_KEY} for the dialogs to inject.\n */\nexport function useSavedBlocksFeature(\n options: UseSavedBlocksFeatureOptions,\n): UseSavedBlocksFeatureReturn {\n const { provider, editor } = options;\n\n const headless = useSavedBlocks({ provider, onError: options.onError });\n\n const isSaveDialogOpen = ref(false);\n const isBrowserOpen = ref(false);\n\n // --- Pick session ---\n const picking = ref(false);\n const pickedIds = ref<Set<string>>(new Set());\n const isPicking = computed(() => picking.value);\n const pickedCount = computed(() => pickedIds.value.size);\n\n function startPicking(blockId: string): void {\n // Nothing to pick *for* when the provider withheld `create` — the dialog at\n // the end of the session would have no way to persist. The bookmark action\n // is already hidden; this covers programmatic callers.\n if (!headless.canCreate.value) return;\n // Preview mode has no block chrome to pick with, and its click handlers are\n // suppressed — a session there could never be completed or cancelled.\n if (editor.state.previewMode) return;\n pickedIds.value = new Set([blockId]);\n picking.value = true;\n }\n\n function togglePick(blockId: string): void {\n if (!picking.value) return;\n const next = new Set(pickedIds.value);\n if (next.has(blockId)) {\n next.delete(blockId);\n } else {\n next.add(blockId);\n }\n pickedIds.value = next;\n }\n\n function isPicked(blockId: string): boolean {\n return pickedIds.value.has(blockId);\n }\n\n function cancelPicking(): void {\n picking.value = false;\n pickedIds.value = new Set();\n }\n\n function confirmPicking(): void {\n if (pickedCount.value === 0) return;\n // Leave pick mode but keep the set — the dialog reads it to know what it's\n // saving. `closeSaveDialog` is what clears it.\n picking.value = false;\n isSaveDialogOpen.value = true;\n // The dialog offers the categories already in use as suggestions, and those\n // are derived from the loaded list — without this they'd be empty for anyone\n // who saves without ever opening the browser, and the derived-category model\n // would drift into near-duplicates.\n refresh();\n }\n\n function closeSaveDialog(): void {\n isSaveDialogOpen.value = false;\n pickedIds.value = new Set();\n }\n\n // A session can't survive entering preview mode: the canvas stops responding\n // to selection there, so the bar would be the only way out.\n watch(\n () => editor.state.previewMode,\n (previewMode) => {\n if (previewMode && picking.value) cancelPicking();\n },\n );\n\n function openBrowser(): void {\n isBrowserOpen.value = true;\n refresh();\n }\n\n function closeBrowser(): void {\n isBrowserOpen.value = false;\n }\n\n function insert(saved: SavedBlock, insertIndex: number | undefined): void {\n for (let i = 0; i < saved.content.length; i++) {\n // cloneBlock regenerates ids (recursively for section children) so the\n // inserted copy never collides with the stored one, or with blocks\n // already on the canvas from a previous insert of the same entry.\n const cloned = cloneBlock(saved.content[i]);\n const position = insertIndex !== undefined ? insertIndex + i : undefined;\n editor.addBlock(cloned, undefined, undefined, position);\n }\n isBrowserOpen.value = false;\n }\n\n function refresh(): void {\n // Fire-and-forget: `useSavedBlocks` already routes failures to `onError`,\n // and a stale list is not worth blocking the dialog's close on.\n void headless.load().catch(() => {});\n }\n\n const count = computed(() => headless.savedBlocks.value.length);\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n\n /**\n * Nothing is fetched at mount — the list loads when the browser or the save\n * dialog opens. So a consumer's `list()` latency can neither delay the editor\n * nor shift the sidebar: the rail entry is gated purely on availability,\n * never on whether anything happens to be saved.\n *\n * True only while there is *nothing to show*, which is what makes the browser\n * skeleton appear on a first open and stay away on a reopen — the previous\n * results render immediately while the refetch lands underneath. Without that\n * distinction the empty state would read \"No saved blocks yet\" for however\n * long the request takes, which is false rather than merely unhelpful.\n *\n * The browser modal derives that condition itself from the injected composable\n * — it is the only surface that displays the list, so there is no reason to\n * widen the capability with it.\n */\n\n provide(SAVED_BLOCKS_KEY, headless);\n\n return {\n headless,\n\n isPicking,\n pickedIds,\n pickedCount,\n startPicking,\n togglePick,\n isPicked,\n confirmPicking,\n cancelPicking,\n\n isSaveDialogOpen,\n closeSaveDialog,\n isBrowserOpen,\n openBrowser,\n closeBrowser,\n\n insert,\n refresh,\n capability: {\n startPicking,\n togglePick,\n isPicked,\n isPicking,\n confirmPicking,\n cancelPicking,\n openBrowser,\n count,\n isAvailable,\n canCreate: headless.canCreate,\n canUpdate: headless.canUpdate,\n canDelete: headless.canDelete,\n },\n count,\n isAvailable,\n };\n}\n","import { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { useEventListener, useTimeoutFn } from \"@vueuse/core\";\nimport type {\n Template,\n TemplateContent,\n TemplateSaveTrigger,\n TemplatesProvider,\n} from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** How long the header shows \"Saved\" before falling back to the dirty state. */\nconst SAVED_STATUS_MS = 3000;\n\n/** Minimal slice of the editor this feature needs. */\ninterface TemplatesEditor {\n state: {\n readonly template: {\n id: string;\n name?: string;\n createdAt?: string;\n updatedAt?: string;\n } | null;\n readonly isDirty: boolean;\n readonly isSaving: boolean;\n };\n setName: (name: string) => void;\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n load: (templateId: string, shouldApply?: () => boolean) => Promise<Template>;\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n hasTemplate: () => boolean;\n}\n\n/**\n * A veto over saving, supplied by whoever configured the editor.\n *\n * The one implementation is Cloud's lint save-gate: with the server policy\n * `accessibility.blockOnError` on and error-severity issues present, a manual\n * save opens a confirmation and an autosave simply does not fire. The shape is\n * generic because the header's Save must be *routable* through a gate — without\n * that, unifying the two headers would have silently dropped `blockOnError`.\n */\nexport interface SaveGate {\n /**\n * Manual save (header button, Cmd+S). Runs the save, or defers it and raises a\n * confirmation. Resolves to whether it ran.\n */\n tryRunSave: (run: () => Promise<unknown> | unknown) => Promise<boolean>;\n /**\n * Autosave. Runs the save only when the gate would not block, and does nothing\n * at all otherwise — no prompt on a debounce timer, and no write that would\n * demote the policy to a manual-save-only speed bump.\n */\n runUnlessBlocked: (run: () => Promise<unknown> | unknown) => Promise<boolean>;\n}\n\nexport interface UseTemplatesFeatureOptions {\n /** Storage backend — consumer-supplied via `init({ templates })`. */\n provider: TemplatesProvider;\n editor: TemplatesEditor;\n /**\n * Warn on tab close while there are unsaved changes. Defaults to on; pass\n * `false` to own that guard yourself.\n */\n guardUnsavedChanges?: boolean;\n /**\n * Extra gate on top of the provider being present. Read reactively, so a\n * future adapter can defer to an entitlement that resolves after setup. Omit\n * for always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n /**\n * Optional veto over every save this feature performs. Read through a getter\n * rather than passed by value because Cloud builds its gate from\n * `core.templateLint`, which only exists after `useEditorCore()` — i.e. after\n * this composable is constructed.\n */\n getSaveGate?: () => SaveGate | null;\n}\n\nexport interface UseTemplatesFeatureReturn {\n /** Persist the loaded template. Rejects — see {@link requestSave} for UI. */\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n /** Persist the current content as a new template. Rejects on failure. */\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n /** Fetch a template. Passed straight through; saving status is untouched. */\n load: (templateId: string, shouldApply?: () => boolean) => Promise<Template>;\n /**\n * Fire-and-forget save for the header button and Cmd+S: the outcome is already\n * reported through {@link status}, so nothing is left for a caller to handle.\n * A no-op while a save is running, without a template, or when the provider\n * withheld `save`.\n */\n requestSave: (trigger?: TemplateSaveTrigger) => void;\n /**\n * The autosave path. Identical to {@link requestSave} except that a configured\n * gate is consulted with `runUnlessBlocked` instead of `tryRunSave`, so a\n * blocked autosave is skipped silently rather than raising a prompt while the\n * user is typing. The template stays dirty and the header keeps saying so.\n */\n requestAutoSave: () => void;\n /**\n * Commit an inline rename and persist it. Empty (or whitespace-only) names and\n * no-change commits are ignored, so a stray blur can neither clear the name\n * nor trigger a pointless round-trip.\n */\n rename: (name: string) => void;\n /** The loaded template's name, or `undefined` when unnamed / not loaded. */\n name: ComputedRef<string | undefined>;\n /**\n * The stored template's write time and which field it came from, or `null`\n * when the provider supplies neither timestamp.\n */\n timestamp: ComputedRef<{\n iso: string;\n kind: \"updatedAt\" | \"createdAt\";\n } | null>;\n hasTemplate: ComputedRef<boolean>;\n isSaving: ComputedRef<boolean>;\n /**\n * What the header's status indicator shows. `\"saved\"` decays back to `\"idle\"`\n * after a few seconds; `\"error\"` stays until the next attempt, since a failure\n * the user never saw is worse than a stale badge.\n */\n status: Ref<\"idle\" | \"saved\" | \"error\">;\n /** The provider's own message for the last failure. Rendered in a tooltip. */\n errorMessage: Ref<string>;\n canCreate: ComputedRef<boolean>;\n canSave: ComputedRef<boolean>;\n isAvailable: ComputedRef<boolean>;\n capability: NonNullable<EditorCapabilities[\"templates\"]>;\n}\n\n/**\n * Shared glue for the templates feature: the save-status the header renders, the\n * inline rename, the unsaved-changes guard, and the capability shared chrome\n * gates on.\n *\n * Persistence itself lives in `@templatical/core`'s `useEditor`, over the\n * consumer's {@link TemplatesProvider} — this composable owns only what is\n * *about the UI*. It is constructed exactly when a provider is configured, so\n * an editor without one downloads it but never runs it.\n */\nexport function useTemplatesFeature(\n options: UseTemplatesFeatureOptions,\n): UseTemplatesFeatureReturn {\n const { provider, editor } = options;\n\n const status = ref<\"idle\" | \"saved\" | \"error\">(\"idle\");\n const errorMessage = ref(\"\");\n\n const { start: startSavedStatusClear, stop: stopSavedStatusClear } =\n useTimeoutFn(\n () => {\n status.value = \"idle\";\n },\n SAVED_STATUS_MS,\n { immediate: false },\n );\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canSave = computed(() => typeof provider.save === \"function\");\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n\n const name = computed(() => editor.state.template?.name);\n // Prefers `updatedAt`; `createdAt` is the fallback for a store that records\n // only creation. Carries which one won, because labelling a never-updated\n // template \"Updated\" would be a claim the store never made.\n const timestamp = computed<{\n iso: string;\n kind: \"updatedAt\" | \"createdAt\";\n } | null>(() => {\n const template = editor.state.template;\n if (template?.updatedAt)\n return { iso: template.updatedAt, kind: \"updatedAt\" };\n if (template?.createdAt)\n return { iso: template.createdAt, kind: \"createdAt\" };\n return null;\n });\n const hasTemplate = computed(() => editor.state.template !== null);\n const isSaving = computed(() => editor.state.isSaving);\n\n function reportSuccess(): void {\n errorMessage.value = \"\";\n status.value = \"saved\";\n // Restart rather than stack: two saves inside the window would otherwise\n // clear the badge on the first timer, mid-way through the second's window.\n stopSavedStatusClear();\n startSavedStatusClear();\n }\n\n function reportFailure(error: unknown): void {\n stopSavedStatusClear();\n status.value = \"error\";\n errorMessage.value =\n error instanceof Error && error.message ? error.message : \"Save failed\";\n }\n\n async function save(trigger?: TemplateSaveTrigger): Promise<Template> {\n try {\n const template = await editor.save(trigger);\n reportSuccess();\n return template;\n } catch (error) {\n reportFailure(error);\n throw error;\n }\n }\n\n async function create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template> {\n try {\n const template = await editor.create(input);\n // Deliberately no \"saved\" badge. The badge acknowledges a save the user\n // asked for — an explicit `save()` or an autosave tick — and attaching a\n // template is neither. It also matched nothing: `load()` attaches without\n // announcing, so a new template flashed green where an existing one stayed\n // silent, for the same action. What a fresh template *has* is a\n // `createdAt`, which the header renders as its write time.\n //\n // The state is still reset, because a failure must not outlive the success\n // that followed it: a create that fails and is then retried would\n // otherwise leave \"Save failed\" on screen for a template that saved fine.\n stopSavedStatusClear();\n status.value = \"idle\";\n errorMessage.value = \"\";\n return template;\n } catch (error) {\n reportFailure(error);\n throw error;\n }\n }\n\n function load(\n templateId: string,\n shouldApply?: () => boolean,\n ): Promise<Template> {\n // The badge describes one template, so it cannot outlive the switch to\n // another: a save that failed seconds ago would otherwise show \"Save failed\"\n // over freshly loaded content, and a green \"Saved\" still inside its decay\n // window would claim the incoming template had just been written. Reset up\n // front rather than on success — a load that fails still means the old\n // status no longer describes what the user is looking at, and if the old\n // template stays attached with edits, `isDirty` puts \"Unsaved\" back.\n stopSavedStatusClear();\n status.value = \"idle\";\n errorMessage.value = \"\";\n // Deliberately not wrapped beyond that: a failed *load* is not a failed\n // save, and flashing \"Save failed\" for it would be a lie. Core already\n // routes it to `onError` and rejects to the caller.\n return shouldApply\n ? editor.load(templateId, shouldApply)\n : editor.load(templateId);\n }\n\n /**\n * An autosave tick that arrived while a save was in flight. `useAutoSave`'s\n * timer fires once and clears itself, and only a further content mutation\n * arms a new one — so dropping such a tick left autosave silent until the\n * user happened to type again.\n */\n let queuedAutoSave = false;\n\n /** Shared by both request paths — the outcome is reported through `status`. */\n function runSave(trigger: TemplateSaveTrigger): Promise<void> {\n return save(trigger).then(\n () => {\n if (!queuedAutoSave) return;\n queuedAutoSave = false;\n // Only what the finished save could not have covered.\n if (editor.state.isDirty) requestAutoSave();\n },\n () => {\n // Deliberately no retry on failure: the status indicator already shows\n // \"Save failed\", so autosave has not gone *silent*, and re-firing into a\n // failing endpoint would only double the traffic. The next content\n // change arms a fresh tick.\n queuedAutoSave = false;\n },\n );\n }\n\n /** True when there is nothing a save could do, whatever the gate says. */\n function cannotSave(): boolean {\n // The UI hides the button in each of these cases; this covers Cmd+S and\n // programmatic callers, where a refusal would surface as an error badge for\n // something the user never asked for.\n return !canSave.value || !hasTemplate.value || isSaving.value;\n }\n\n function requestSave(trigger: TemplateSaveTrigger = \"manual\"): void {\n if (cannotSave()) return;\n const gate = options.getSaveGate?.();\n if (gate) {\n void gate.tryRunSave(() => runSave(trigger));\n return;\n }\n void runSave(trigger);\n }\n\n function requestAutoSave(): void {\n // Split the transient condition out of `cannotSave()`: a save already in\n // flight is a \"later\", not a \"never\". Overlapping PATCHes of the whole\n // document must still never happen, so the tick is queued rather than run.\n if (!canSave.value || !hasTemplate.value) return;\n if (isSaving.value) {\n queuedAutoSave = true;\n return;\n }\n const gate = options.getSaveGate?.();\n if (gate) {\n void gate.runUnlessBlocked(() => runSave(\"autosave\"));\n return;\n }\n void runSave(\"autosave\");\n }\n\n function rename(newName: string): void {\n const trimmed = newName.trim();\n // An empty name is rejected rather than stored: the header would then have\n // nothing to render, and \"\" is far more likely a slip than an intent.\n if (!trimmed) return;\n if (trimmed === editor.state.template?.name) return;\n editor.setName(trimmed);\n requestSave(\"rename\");\n }\n\n // Tab close with unsaved work. Gated on a provider being configured — the\n // editor otherwise has no idea whether the consumer already persisted the\n // change, so it would be warning about nothing. Note this cannot cover SPA\n // route changes; `onDirtyChange` is what consumers guard their router with.\n if (options.guardUnsavedChanges !== false) {\n useEventListener(window, \"beforeunload\", (event: BeforeUnloadEvent) => {\n if (!editor.state.isDirty) return;\n event.preventDefault();\n // Some engines still show the prompt only when `returnValue` is set.\n event.returnValue = \"\";\n });\n }\n\n const capability: NonNullable<EditorCapabilities[\"templates\"]> = {\n save: requestSave,\n rename,\n name,\n timestamp,\n hasTemplate,\n isSaving,\n status,\n errorMessage,\n canCreate,\n canSave,\n isAvailable,\n };\n\n return {\n save,\n create,\n load,\n requestSave,\n requestAutoSave,\n rename,\n name,\n timestamp,\n hasTemplate,\n isSaving,\n status,\n errorMessage,\n canCreate,\n canSave,\n isAvailable,\n capability,\n };\n}\n","import type { CustomBlock, TemplateContent } from \"@templatical/types\";\nimport type { RenderFonts } from \"./renderProvider\";\n\n/**\n * Minimal slice of the editor surface needed by `toMjmlForInstance`.\n * Decoupled from the full `TemplaticalEditor` type so this helper can be\n * tested in isolation with a stub object.\n */\nexport interface ToMjmlSource {\n getContent(): TemplateContent;\n renderCustomBlock(block: CustomBlock): Promise<string>;\n /**\n * Optional. The fonts the editor is rendering with, forwarded to the renderer's\n * `customFonts` / `defaultFallbackFont`. Without it a template using a custom\n * face exports with no `<mj-font>` declaration and no fallback stack — i.e. the\n * mail client silently substitutes. Provided by both editors, and by anything\n * that has a fonts manager; a source that omits it produces byte-identical\n * MJML to one whose template uses no custom face.\n */\n getFonts?: () => RenderFonts;\n /**\n * Optional. Look up the definition-level CSS for a custom block type.\n * Returns `undefined` when the definition is unknown or has no\n * `stylesheet`. Wired to the renderer's `getCustomBlockStylesheet` option\n * so authored responsive/hover/font CSS lands in `<mj-head>` deduped per\n * definition. Omitting it is optional-by-design: the resolver is simply not\n * passed through, so no `<mj-head>` stylesheet is emitted.\n */\n getCustomBlockStylesheet?: (customType: string) => string | undefined;\n /**\n * Optional. Base URL for the social-icon PNGs, forwarded to the renderer’s\n * `socialIconsBaseUrl`. Omitting it leaves the renderer on its version-pinned\n * jsDelivr default, so output matches today’s `toMjml()` for the same template.\n */\n socialIconsBaseUrl?: string;\n /**\n * Optional. Embedder shell forwarded to the renderer's `layout` option only\n * when defined, so `toMjml()` composes and a source that omits it produces\n * today's unshelled MJML. Never written into `getContent()`.\n */\n getLayout?: () => TemplateContent | undefined;\n}\n\n/**\n * Lazy-load `@templatical/renderer` and render the editor's current content\n * to MJML, wiring the editor's own custom block resolver into the renderer's\n * `renderCustomBlock` callback.\n *\n * The renderer is an optional peer dependency (small, MIT-licensed). It is\n * only loaded when an export is actually requested. Consumers that don't\n * need MJML export at all (e.g., embedding the editor in an app where the\n * backend handles export) can omit the install entirely; calling `toMjml()`\n * in that case throws a clear error naming the missing package.\n *\n * The dynamic import is cached by the module system, so subsequent calls\n * skip the import overhead.\n */\n/**\n * Resolve `@templatical/renderer`, or `null` when it isn't installed.\n *\n * The single `import(\"@templatical/renderer\")` site in the package, so callers\n * can choose their own failure behaviour without duplicating the dynamic import\n * or matching on an error message. {@link toMjmlForInstance} throws when this\n * returns `null`; the test-email path degrades to JSON-only and warns once,\n * because there the renderer is opt-in and a missing install must not break\n * sending.\n *\n * Cheap to call repeatedly — the module system caches the import, so a second\n * call after a successful first one costs nothing.\n */\nexport async function tryLoadRenderer(): Promise<\n typeof import(\"@templatical/renderer\") | null\n> {\n try {\n return await import(\"@templatical/renderer\");\n } catch {\n return null;\n }\n}\n\nexport async function toMjmlForInstance(\n instance: ToMjmlSource,\n): Promise<string> {\n const renderer = await tryLoadRenderer();\n if (!renderer) {\n throw new Error(\n \"[Templatical] toMjml() requires the @templatical/renderer package. Please install it.\",\n );\n }\n const stylesheetResolver = instance.getCustomBlockStylesheet;\n const fonts = instance.getFonts?.();\n const layout = instance.getLayout?.();\n return renderer.renderToMjml(instance.getContent(), {\n renderCustomBlock: instance.renderCustomBlock,\n // Only pass through when the source actually provides a resolver, so a\n // caller that doesn't care about stylesheets sees an options shape (and MJML\n // output) with no stylesheet key at all rather than an explicit `undefined`.\n ...(stylesheetResolver\n ? {\n getCustomBlockStylesheet: (customType: string) =>\n stylesheetResolver(customType),\n }\n : {}),\n ...(fonts\n ? {\n customFonts: fonts.customFonts,\n defaultFallbackFont: fonts.defaultFallback,\n }\n : {}),\n ...(instance.socialIconsBaseUrl\n ? { socialIconsBaseUrl: instance.socialIconsBaseUrl }\n : {}),\n ...(layout ? { layout } : {}),\n });\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport type {\n TemplateContent,\n TestEmailPayload,\n TestEmailProvider,\n} from \"@templatical/types\";\nimport { logger } from \"../utils/logger\";\nimport { tryLoadRenderer } from \"../utils/toMjml\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** How long the dialog shows its success confirmation before closing itself. */\nconst SUCCESS_DISMISS_MS = 1200;\n\n/**\n * Why a send failed.\n *\n * Split by origin so the dialog knows whether it may render the text directly.\n * A provider's message is already user-presentable and is passed through\n * verbatim; an editor-generated refusal carries no text, because only the\n * component has the active locale.\n */\nexport type TestEmailError =\n { kind: \"provider\"; message: string } | { kind: \"recipientNotAllowed\" };\n\n/**\n * Turn a thrown value into an `Error`. A `catch` clause's binding is\n * `unknown` — a rejected `send` and a throwing `onSent` handler both need a\n * real `Error` to report, and both paths below share this.\n */\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nexport interface UseTestEmailFeatureOptions {\n /** Sending backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: TestEmailProvider;\n /** The template to send. Read at send time, never snapshotted. */\n getContent: () => TemplateContent;\n /**\n * Render the current template to MJML. Supplied by the entry point, which\n * already owns the `ToMjmlSource` for `editor.toMjml()`, so this composable\n * never learns about custom-block resolvers or stylesheets.\n *\n * Only ever called when the provider set `includeMjml`.\n */\n renderMjml?: () => Promise<string>;\n /**\n * Whether {@link renderMjml} reaches the bundled `@templatical/renderer`.\n * Omitted means yes, which is what a caller with no `render` provider wants.\n *\n * Gates the degradation below: a missing optional peer explains a failed\n * render only on the local path. A consumer whose backend renders has no\n * reason to install `@templatical/renderer` at all, so reading their backend's\n * error as an absent package would both swallow it and advise an install that\n * changes nothing.\n */\n usesLocalRenderer?: () => boolean;\n onError?: (error: Error) => void;\n /**\n * Extra gate on top of the provider being present — Cloud adds its plan\n * entitlement and \"template must be saved\" here. Read reactively.\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseTestEmailFeatureReturn {\n isModalOpen: Ref<boolean>;\n open: () => void;\n close: () => void;\n isSending: Ref<boolean>;\n /** True for a moment after a successful send, while the dialog confirms. */\n justSent: Ref<boolean>;\n error: Ref<TestEmailError | null>;\n send: (recipient: string) => Promise<void>;\n /**\n * The provider's allowlist, or `undefined` when unrestricted.\n *\n * A computed rather than a snapshot: Cloud exposes `allowedRecipients` as a\n * getter over a value that arrives with its JWT, so reading it once at setup\n * would freeze it at `[]` forever.\n */\n allowedRecipients: ComputedRef<string[] | undefined>;\n defaultRecipient: ComputedRef<string | undefined>;\n isAvailable: ComputedRef<boolean>;\n capability: NonNullable<EditorCapabilities[\"testEmail\"]>;\n}\n\nexport function useTestEmailFeature(\n options: UseTestEmailFeatureOptions,\n): UseTestEmailFeatureReturn {\n const { provider } = options;\n\n const isModalOpen = ref(false);\n const isSending = ref(false);\n const justSent = ref(false);\n const error = ref<TestEmailError | null>(null);\n\n let dismissTimer: ReturnType<typeof setTimeout> | null = null;\n /** One warning per editor instance, not per send — a retry shouldn't re-log. */\n let warnedAboutRenderer = false;\n\n function clearDismissTimer(): void {\n if (dismissTimer !== null) {\n clearTimeout(dismissTimer);\n dismissTimer = null;\n }\n }\n\n // The timer outlives a fast unmount otherwise, and fires into dead refs.\n onScopeDispose(clearDismissTimer);\n\n // IMPORTANT: read `provider.allowedRecipients` *inside* the computed. Cloud's\n // adapter implements it as a getter over a reactive source that starts empty\n // and fills once auth resolves — destructuring it at setup would pin it to\n // `[]`, which (see `isAvailable`) hides the trigger permanently.\n const allowedRecipients = computed(() => provider.allowedRecipients);\n\n const defaultRecipient = computed(() => {\n const preferred = provider.defaultRecipient;\n if (preferred === undefined) return undefined;\n const allowed = allowedRecipients.value;\n // A default outside the allowlist is ignored rather than smuggled in.\n if (allowed && !allowed.includes(preferred)) return undefined;\n return preferred;\n });\n\n const isAvailable = computed(() => {\n // An explicitly empty allowlist means nobody may be sent to, so the feature\n // is unusable and must not advertise itself. Distinct from `undefined`,\n // which means \"unrestricted\".\n if (allowedRecipients.value?.length === 0) return false;\n return options.isAvailable?.() ?? true;\n });\n\n function open(): void {\n if (!isAvailable.value) return;\n // Clear both, or a reopen shows the previous attempt's error or a stale tick\n // of the success state.\n error.value = null;\n justSent.value = false;\n clearDismissTimer();\n isModalOpen.value = true;\n }\n\n function close(): void {\n clearDismissTimer();\n isModalOpen.value = false;\n justSent.value = false;\n }\n\n /**\n * Build `payload.mjml` when the provider opted in.\n *\n * Returns `undefined` for the two non-fatal cases (not opted in; opted in but\n * the renderer isn't installed) and **throws** when rendering itself fails —\n * that means the render is broken, and silently sending JSON-only would hide\n * a real defect indefinitely.\n */\n async function resolveMjml(): Promise<string | undefined> {\n if (!provider.includeMjml || !options.renderMjml) return undefined;\n\n try {\n return await options.renderMjml();\n } catch (err) {\n // Probe only on the failure path, so the happy path pays nothing — and\n // only when the bundled renderer is what ran, since a `render` provider's\n // failure can never be explained by the package being absent.\n const couldBeMissingRenderer = options.usesLocalRenderer?.() ?? true;\n if (couldBeMissingRenderer && (await tryLoadRenderer()) === null) {\n if (!warnedAboutRenderer) {\n warnedAboutRenderer = true;\n logger.warn(\n \"testEmail.includeMjml is set but @templatical/renderer is not installed — \" +\n \"sending the template as JSON only. Install it to receive `payload.mjml`.\",\n );\n }\n return undefined;\n }\n throw err;\n }\n }\n\n /**\n * Report a completed send to the provider's `onSent`, guarded so a throw\n * cannot reach `send`'s own try/catch — by the time this runs, `send` has\n * already succeeded and the dialog is already showing success.\n *\n * Mirrors `@templatical/core`'s `notifyHandler`, which this composable\n * cannot import: `error-reporting.ts` is not part of `@templatical/core`'s\n * package exports.\n */\n function notifySent(payload: TestEmailPayload): void {\n try {\n // Read off `provider` at call time, never destructured — the same\n // discipline `allowedRecipients`/`defaultRecipient` apply above, so a\n // handler that arrives or changes after setup is never missed.\n provider.onSent?.(payload);\n } catch (err) {\n options.onError?.(toError(err));\n }\n }\n\n async function send(recipient: string): Promise<void> {\n if (isSending.value) return;\n\n const allowed = allowedRecipients.value;\n if (allowed && !allowed.includes(recipient)) {\n // Unreachable through the picker, reachable by a programmatic open or a\n // tampered field. Refusing keeps a guarantee worth having: the editor\n // never calls `send` with an address outside a configured allowlist.\n error.value = { kind: \"recipientNotAllowed\" };\n return;\n }\n\n isSending.value = true;\n error.value = null;\n\n try {\n const mjml = await resolveMjml();\n const payload: TestEmailPayload = {\n recipient,\n content: options.getContent(),\n ...(mjml !== undefined ? { mjml } : {}),\n ...(allowed !== undefined ? { allowedRecipients: allowed } : {}),\n };\n await provider.send(payload);\n\n justSent.value = true;\n dismissTimer = setTimeout(close, SUCCESS_DISMISS_MS);\n notifySent(payload);\n } catch (err) {\n const wrapped = toError(err);\n error.value = { kind: \"provider\", message: wrapped.message };\n options.onError?.(wrapped);\n // Deliberately not re-thrown: the dialog surfaces `error` and stays open\n // for a retry, and nothing awaits this beyond the click handler.\n } finally {\n isSending.value = false;\n }\n }\n\n const capability: NonNullable<EditorCapabilities[\"testEmail\"]> = {\n open,\n isAvailable,\n };\n\n return {\n isModalOpen,\n open,\n close,\n isSending,\n justSent,\n error,\n send,\n allowedRecipients,\n defaultRecipient,\n isAvailable,\n capability,\n };\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport {\n useVersionHistory,\n type UseVersionHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n UseAutoSaveReturn,\n UseConditionPreviewReturn,\n UseHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n BlockLockHolder,\n TemplateContent,\n TemplateVersion,\n VersionHistoryProvider,\n} from \"@templatical/types\";\nimport { safeClone } from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — OSS and Cloud alike. */\ninterface VersionHistoryEditor {\n state: {\n readonly template?: { id: string } | null;\n readonly isDirty: boolean;\n };\n content: Ref<TemplateContent>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n}\n\n/**\n * How the restore confirmation persists unsaved work instead of only warning\n * about it.\n *\n * Both members are read at confirmation time rather than captured at setup, so\n * a late-bound save (Cloud's, which only exists once its lifecycle composable\n * is constructed) and a save that comes and goes (Cloud's lint gate) are both\n * expressible.\n */\nexport interface SaveBeforeRestore {\n /** Whether persisting is possible *right now*. */\n canSave: () => boolean;\n /** Persist the template. Rejects on failure; the confirmation stays up. */\n save: () => Promise<unknown>;\n}\n\n/**\n * What a version preview and a restore need from collaboration. A previewed\n * version is not an edit, so collaboration stops reading the canvas while one\n * is on it; a restore replaces the template on the backend, which this editor\n * then fetches like every other editor.\n */\nexport interface VersionHistoryCollaboration {\n suspend: () => void;\n resume: () => void;\n catchUp: () => Promise<void>;\n reportReplaceRefused: (holders: readonly BlockLockHolder[]) => void;\n}\n\nexport interface UseVersionHistoryFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: VersionHistoryProvider;\n editor: VersionHistoryEditor;\n /**\n * Lets the restore confirmation offer \"save first\". Omit it — or supply one\n * whose `canSave` is false, which is what a `save: false` templates provider\n * amounts to — and the confirmation degrades to a plain \"these will be lost\",\n * because there is then nowhere to put them.\n */\n saveBeforeRestore?: SaveBeforeRestore | null;\n history: UseHistoryReturn;\n conditionPreview: UseConditionPreviewReturn;\n /** Paused for the duration of a preview, so previewed content is never saved. */\n autoSave: UseAutoSaveReturn | null;\n /** Set with a collaboration provider. */\n collaboration?: VersionHistoryCollaboration | null;\n onError?: (error: Error) => void;\n /**\n * Whether the feature may be used. Read reactively, so Cloud can defer to a\n * plan entitlement that resolves after its async config fetch. Omit for\n * always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseVersionHistoryFeatureReturn {\n headless: UseVersionHistoryReturn;\n\n versions: ComputedRef<TemplateVersion[]>;\n isLoading: ComputedRef<boolean>;\n isRestoring: ComputedRef<boolean>;\n canCreate: ComputedRef<boolean>;\n canRestore: ComputedRef<boolean>;\n /** True once a template exists — there is no history before that. */\n hasTemplate: ComputedRef<boolean>;\n isAvailable: ComputedRef<boolean>;\n\n /** The version currently on the canvas, or `null` when editing normally. */\n previewingVersion: Ref<TemplateVersion | null>;\n isPreviewing: ComputedRef<boolean>;\n\n /** True while the unsaved-changes confirmation is up. */\n isConfirmingRestore: Ref<boolean>;\n /** Whether that confirmation may offer \"save first\" rather than only warn. */\n canSaveBeforeRestore: ComputedRef<boolean>;\n /**\n * True from the moment a confirmation action is taken until it settles —\n * covering the save as well as the restore, so a second click can't fire a\n * second save while the first is still in flight.\n */\n isConfirmBusy: ComputedRef<boolean>;\n\n /** Re-read the list. Called when the history control opens. */\n refresh: () => void;\n /**\n * Show a version on the canvas. **Synchronous once the preview is open and the\n * version's content is already in hand**, which is what keeps scrubbing\n * instant — see {@link TemplateVersion.content}.\n */\n navigate: (version: TemplateVersion) => Promise<void>;\n /**\n * What the banner's Restore button calls. Restores straight away when there is\n * nothing to lose; opens the confirmation when there are unsaved changes,\n * because {@link confirmRestore} discards the pre-preview backup and that work\n * would then exist nowhere.\n */\n requestRestore: () => Promise<void>;\n /** Confirmation's primary action: persist the unsaved work, then restore. */\n saveAndRestore: () => Promise<void>;\n /** Confirmation's destructive action: restore, losing the unsaved work. */\n discardAndRestore: () => Promise<void>;\n /** Dismiss the confirmation, staying in the preview with nothing restored. */\n cancelRestoreConfirm: () => void;\n /** Make the previewed version current. Rejects if the provider's restore does. */\n confirmRestore: () => Promise<void>;\n /** Leave the preview and put the pre-preview content back. */\n cancelPreview: () => void;\n\n capability: NonNullable<EditorCapabilities[\"versionHistory\"]>;\n}\n\n/**\n * Shared glue for version history: the reactive list, the preview-before-restore\n * flow, and the capability the shared chrome gates on.\n *\n * Both `Editor.vue` (OSS) and `useCloudInitialization` (Cloud) call this with\n * their own provider, so the two entry points run identical logic over different\n * transports. Nothing here is auth- or plan-aware — callers decide whether the\n * feature is available *before* constructing it.\n */\nexport function useVersionHistoryFeature(\n options: UseVersionHistoryFeatureOptions,\n): UseVersionHistoryFeatureReturn {\n const { provider, editor, history, conditionPreview, autoSave } = options;\n const collaboration = options.collaboration ?? null;\n\n const headless = useVersionHistory({\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n onError: options.onError,\n });\n\n const previewingVersion = ref<TemplateVersion | null>(null);\n const contentBeforePreview = ref<TemplateContent | null>(null);\n const isConfirmingRestore = ref(false);\n const isSavingBeforeRestore = ref(false);\n\n // Async functions must guard against post-unmount execution after every\n // `await` so we don't write to dead refs or fire side effects\n // (autoSave.pause, setContent) on a torn-down component.\n let destroyed = false;\n onScopeDispose(() => {\n destroyed = true;\n });\n\n const versions = computed(() => headless.versions.value);\n const isLoading = computed(() => headless.isLoading.value);\n const isRestoring = computed(() => headless.isRestoring.value);\n const canCreate = headless.canCreate;\n const canRestore = headless.canRestore;\n const hasTemplate = computed(() => !!editor.state.template?.id);\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n const isPreviewing = computed(() => previewingVersion.value !== null);\n const canSaveBeforeRestore = computed(\n () => options.saveBeforeRestore?.canSave() === true,\n );\n const isConfirmBusy = computed(\n () => isSavingBeforeRestore.value || isRestoring.value,\n );\n\n function refresh(): void {\n if (!hasTemplate.value) return;\n // Fire-and-forget: `useVersionHistory` already routes failures to `onError`,\n // and a stale list is not worth blocking the dropdown's open on.\n void headless.load().catch(() => {});\n }\n\n async function navigate(version: TemplateVersion): Promise<void> {\n if (destroyed) return;\n\n // A pending confirmation names the version it was raised for, so moving to\n // another one must retract it. Unreachable while the dialog is modal, but a\n // programmatic scrub reaches it today and an inline confirmation would.\n isConfirmingRestore.value = false;\n\n // Already previewing: this is a scrub. Take the synchronous path whenever\n // the content is in hand — a provider that hydrates its list (Cloud does)\n // never awaits here, and the canvas swaps in the same tick.\n if (previewingVersion.value) {\n const known = headless.peekContent(version);\n if (known) {\n previewingVersion.value = version;\n editor.setContent(known, false);\n return;\n }\n const content = await headless.resolveContent(version);\n if (destroyed) return;\n previewingVersion.value = version;\n editor.setContent(content, false);\n return;\n }\n\n // Entering the preview. Resolve first: a failed fetch must leave the user\n // editing, not stranded in a preview of nothing.\n const content = await headless.resolveContent(version);\n if (destroyed) return;\n\n // Opening a preview records nothing. The editor never authors a version —\n // whoever implements `TemplatesProvider.save` decides that. The unsaved work\n // that a confirmed restore would discard is protected at the confirmation\n // instead (see `requestRestore`), which is both where the loss happens and\n // the one place the user can be asked about it.\n //\n // `safeClone`, not `structuredClone`: what arrives here is a Vue reactive\n // proxy over the editor's content, and the structured-clone algorithm\n // refuses a proxy outright. It is also the repo's one deep-clone for\n // content, so a Sortable back-ref that leaked into block data is dropped\n // rather than thrown on.\n contentBeforePreview.value = safeClone(editor.content.value);\n\n autoSave?.pause();\n collaboration?.suspend();\n previewingVersion.value = version;\n editor.setContent(content, false);\n }\n\n async function requestRestore(): Promise<void> {\n if (!previewingVersion.value) return;\n\n // `setContent(…, false)` is what puts a version on the canvas, so `isDirty`\n // still describes the user's own work rather than the preview.\n if (editor.state.isDirty) {\n isConfirmingRestore.value = true;\n return;\n }\n await confirmRestore();\n }\n\n async function saveAndRestore(): Promise<void> {\n const version = previewingVersion.value;\n const before = contentBeforePreview.value;\n const saver = options.saveBeforeRestore;\n // The UI hides this action in each of these cases; a programmatic caller\n // gets a no-op rather than a save of the previewed version.\n if (!version || !before || !saver?.canSave()) return;\n if (isConfirmBusy.value) return;\n\n // The canvas is showing the *previewed* version and a save persists whatever\n // the editor holds, so put the user's work back before saving — otherwise\n // \"save first\" would save the very version they are about to restore.\n editor.setContent(before, false);\n isSavingBeforeRestore.value = true;\n try {\n await saver.save();\n } catch {\n // Already reported by whoever owns the save (status badge, `onError`).\n // Put the preview back so the banner and the canvas agree again, and leave\n // the confirmation up: nothing was saved and nothing was restored.\n if (destroyed) return;\n const previewed = headless.peekContent(version);\n if (previewed) editor.setContent(previewed, false);\n return;\n } finally {\n if (!destroyed) isSavingBeforeRestore.value = false;\n }\n if (destroyed) return;\n await confirmRestore();\n }\n\n async function discardAndRestore(): Promise<void> {\n // The dialog disables its buttons while busy; this covers a programmatic\n // caller, for whom a second restore mid-flight would append twice.\n if (isConfirmBusy.value) return;\n await confirmRestore();\n }\n\n function cancelRestoreConfirm(): void {\n isConfirmingRestore.value = false;\n }\n\n async function confirmRestore(): Promise<void> {\n if (!previewingVersion.value) return;\n\n try {\n const template = await headless.restore(previewingVersion.value.id);\n if (destroyed) return;\n if (collaboration) {\n // The backend replaced the content; fetch it like every other editor\n // does. `resume()` below puts it on the canvas.\n await collaboration.catchUp();\n if (destroyed) return;\n history.clear();\n conditionPreview.reset();\n } else {\n applyRestored(template.content);\n }\n // History is append-only: the restore added an entry, so the list the\n // dropdown shows is stale until it is re-read.\n await headless.load();\n if (destroyed) return;\n } catch (error) {\n // The canvas is still showing the previewed version (set in `navigate`),\n // so roll back to the pre-preview content before the `finally` discards\n // the backup — otherwise the user is silently left editing an un-restored\n // version with the banner gone, and the next autosave persists it.\n if (!destroyed && contentBeforePreview.value) {\n editor.setContent(contentBeforePreview.value, false);\n }\n const refusal = error as { code?: unknown; holders?: unknown };\n if (collaboration && refusal?.code === \"locked_by_others\") {\n collaboration.reportReplaceRefused(\n Array.isArray(refusal.holders)\n ? (refusal.holders as BlockLockHolder[])\n : [],\n );\n }\n throw error;\n } finally {\n if (!destroyed) {\n previewingVersion.value = null;\n contentBeforePreview.value = null;\n isConfirmingRestore.value = false;\n autoSave?.resume();\n collaboration?.resume();\n }\n }\n }\n\n function applyRestored(content: TemplateContent): void {\n editor.setContent(content, false);\n history.clear();\n conditionPreview.reset();\n }\n\n function cancelPreview(): void {\n if (!previewingVersion.value || !contentBeforePreview.value) return;\n\n editor.setContent(contentBeforePreview.value, false);\n\n previewingVersion.value = null;\n contentBeforePreview.value = null;\n isConfirmingRestore.value = false;\n\n autoSave?.resume();\n collaboration?.resume();\n }\n\n return {\n headless,\n\n versions,\n isLoading,\n isRestoring,\n canCreate,\n canRestore,\n hasTemplate,\n isAvailable,\n\n previewingVersion,\n isPreviewing,\n isConfirmingRestore,\n canSaveBeforeRestore,\n isConfirmBusy,\n\n refresh,\n navigate,\n requestRestore,\n saveAndRestore,\n discardAndRestore,\n cancelRestoreConfirm,\n confirmRestore,\n cancelPreview,\n\n capability: {\n refresh,\n isPreviewing,\n hasTemplate,\n isAvailable,\n canCreate,\n canRestore,\n },\n };\n}\n","/**\n * Whether the editor saves automatically after the user stops editing.\n *\n * The cadence is `changeDebounce` at the config root rather than a member here,\n * because one `useAutoSave` instance drives both the save and the `onChange`\n * notification — and `onChange` works with no templates provider, so a\n * provider-less consumer still needs to set it. `autoSave: false` with a\n * `changeDebounce` is therefore a real setting, not a dead one: it means notify\n * at that cadence and persist nothing.\n */\nexport type AutoSaveConfig = boolean;\n\n/**\n * Normalise an {@link AutoSaveConfig}.\n *\n * The one call site is `Editor.vue`'s `autoSaveEnabled`, which always passes\n * `false` as `defaultEnabled` — a consumer without a `templates` provider has\n * nothing to save to. `initCloud()` inlines its own default instead of\n * calling this (`config.templates?.autoSave ?? true`, in `index.ts`), since\n * Cloud always has a store to save to.\n */\nexport function resolveAutoSave(\n value: AutoSaveConfig | undefined,\n defaultEnabled: boolean,\n): boolean {\n return value ?? defaultEnabled;\n}\n","import type { LintOptions } from \"@templatical/quality\";\n\n/**\n * Build the `LintOptions` object the editor passes to the lint composable.\n *\n * In editor / cloud-editor mode the linter locale is forced to match the\n * editor UI locale — `lint.locale` set by the consumer is ignored.\n * Headless callers (`lintAccessibility(...)` / `lintStructure(...)` directly)\n * keep full control.\n */\nexport function resolveLintOptions(config: {\n locale?: string;\n lint?: LintOptions;\n}): LintOptions {\n return {\n ...config.lint,\n locale: config.locale,\n };\n}\n","/**\n * Where a palette insert should land, expressed as the trailing arguments of\n * `editor.addBlock(block, targetSectionId?, columnIndex?, index?)`.\n *\n * An empty object means \"append at the end\" — every field absent, so spreading\n * it into `addBlock` passes `undefined` for all three and takes the push path.\n */\nexport interface InsertPosition {\n targetSectionId?: string;\n columnIndex?: number;\n index?: number;\n}\n\nexport interface ResolveInsertPositionOptions {\n /**\n * The type of block about to be inserted. Only `\"section\"` changes the\n * outcome — custom types (`custom:*`) behave like any other leaf block.\n */\n blockType: string;\n selectedBlockId: string | null;\n findBlockLocation: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n isBlockLocked: (blockId: string) => boolean;\n}\n\n/**\n * Resolve the insert position for a palette click: directly below the selected\n * block, falling back to appending at the end.\n *\n * Every fallback here exists because `addBlock` refuses the alternative\n * *silently*. Returning a position it rejects would turn the click into a\n * complete no-op — worse for the user than landing at the bottom, which is the\n * behaviour this whole function replaces. So the rule is: only ever return a\n * position `addBlock` will accept.\n *\n * Mirrors `duplicateBlock` in `@templatical/core` (resolve the reference\n * block's location, bump the index by one, append when it can't be resolved) so\n * click-to-insert and duplicate place blocks by the same rule.\n */\nexport function resolveInsertPosition(\n options: ResolveInsertPositionOptions,\n): InsertPosition {\n const { blockType, selectedBlockId, findBlockLocation, isBlockLocked } =\n options;\n\n if (!selectedBlockId) return {};\n\n // A selection can outlive its block — a collaborator removes it, an undo\n // drops it — so an unresolvable id means append, never a guessed index.\n const selected = findBlockLocation(selectedBlockId);\n if (!selected) return {};\n\n if (selected.targetSectionId === undefined) {\n return { index: selected.index + 1 };\n }\n\n if (blockType === \"section\") {\n // MJML forbids `mj-section` inside `mj-column`, so `addBlock` rejects the\n // nest outright. Land beside the section the selection sits in instead —\n // the nearest position that accepts a section at all. Sections never nest,\n // so the parent's own location is always top-level.\n const parent = findBlockLocation(selected.targetSectionId);\n if (!parent || parent.targetSectionId !== undefined) return {};\n return { index: parent.index + 1 };\n }\n\n // `addBlock` bails when the target section is locked, so a locked parent\n // means the column is unavailable — append rather than lose the block.\n if (isBlockLocked(selected.targetSectionId)) return {};\n\n return {\n targetSectionId: selected.targetSectionId,\n columnIndex: selected.columnIndex,\n index: selected.index + 1,\n };\n}\n","import type { Block } from \"@templatical/types\";\nimport {\n resolveInsertPosition,\n type ResolveInsertPositionOptions,\n} from \"./resolveInsertPosition\";\n\n/** The slice of the core editor a click-to-insert needs. */\nexport interface InsertBlockTarget {\n state: { selectedBlockId: string | null };\n findBlockLocation: ResolveInsertPositionOptions[\"findBlockLocation\"];\n isBlockLocked: ResolveInsertPositionOptions[\"isBlockLocked\"];\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n selectBlock: (blockId: string | null) => void;\n}\n\n/**\n * Insert a block the way a palette click does: below the selection, by the\n * rules in `resolveInsertPosition`, then select it. Shared by the sidebar and\n * the public `insertBlock()`, so the two can never place a block differently.\n *\n * Returns whether the block landed. `addBlock` refuses silently, and selecting\n * an id it never added would leave a selection the next insert resolves\n * against.\n */\nexport function insertBlockAtSelection(\n editor: InsertBlockTarget,\n block: Block,\n): boolean {\n const { targetSectionId, columnIndex, index } = resolveInsertPosition({\n blockType: block.type,\n selectedBlockId: editor.state.selectedBlockId,\n findBlockLocation: editor.findBlockLocation,\n isBlockLocked: editor.isBlockLocked,\n });\n editor.addBlock(block, targetSectionId, columnIndex, index);\n if (!editor.findBlockLocation(block.id)) return false;\n editor.selectBlock(block.id);\n return true;\n}\n","import type {\n Template,\n TemplatePatch,\n TemplatesProvider,\n} from \"@templatical/types\";\n\n/** What the save needs from collaboration: a way to wait for the batches. */\nexport interface SettlingCollaboration {\n settle: () => Promise<void>;\n}\n\n/**\n * A templates provider whose `save` persists content through collaboration.\n *\n * With a collaboration provider, every edit already reaches the backend as an\n * operation, and the backend's copy is the shared one. Saving the whole\n * content as well would write over other people's edits, so `save` waits for\n * this editor's batches to be confirmed and passes on only a rename. A save\n * with nothing to rename makes no call and answers with what is open.\n *\n * @param getTemplate What is open: the loaded template with the content on\n * the canvas.\n */\nexport function withCollaborativeSave(\n provider: TemplatesProvider,\n collaboration: SettlingCollaboration,\n getTemplate: () => Template | null,\n): TemplatesProvider {\n const { save, create } = provider;\n if (typeof save !== \"function\") return provider;\n\n // The name the store last confirmed, per template id.\n const storedNames = new Map<string, string | undefined>();\n const remember = (template: Template): Template => {\n storedNames.set(template.id, template.name);\n return template;\n };\n\n return {\n ...provider,\n load: async (id) => remember(await provider.load(id)),\n create:\n typeof create === \"function\"\n ? async (input) => remember(await create(input))\n : false,\n save: async (id: string, patch: TemplatePatch): Promise<Template> => {\n await collaboration.settle();\n const renamed =\n patch.name !== undefined && patch.name !== storedNames.get(id);\n if (renamed) return remember(await save(id, { name: patch.name }));\n const current = getTemplate();\n // Another template was opened while the batches settled: answer with\n // the stored one, which core then ignores as stale.\n return current && current.id === id\n ? current\n : remember(await provider.load(id));\n },\n };\n}\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type {\n Block,\n CustomBlock as CustomBlockType,\n TemplateContent,\n ViewportSize,\n} from \"@templatical/types\";\nimport { resolveContentDirection } from \"@templatical/types\";\nimport { ImageUp, Sparkles, SquarePlus } from \"@lucide/vue\";\nimport { computed, inject, provide, ref, type Component } from \"vue\";\nimport {\n EDITOR_KEY,\n APPLIES_CONDITION_FILTER_KEY,\n CONDITION_PREVIEW_KEY,\n BLOCK_REGISTRY_KEY,\n CAPABILITIES_KEY,\n FONTS_MANAGER_KEY,\n MERGE_TAG_SAMPLE_MODE_KEY,\n PREVIEW_RESOLUTION_KEY,\n USE_MERGE_TAG_SAMPLES_KEY,\n requireInject,\n} from \"../keys\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport {\n getDocumentStyle,\n resolveBlockComponent,\n} from \"../utils/blockComponentResolver\";\nimport {\n EMAIL_FRAME_WIDTH_TRANSITION,\n EMAIL_GUTTER,\n getEmailFrameWidth,\n} from \"../utils/emailFrameWidth\";\n\nimport BlockWrapper from \"./blocks/BlockWrapper.vue\";\nimport SectionBlock from \"./blocks/SectionBlock.vue\";\nimport TitleBlock from \"./blocks/TitleBlock.vue\";\nimport ParagraphBlock from \"./blocks/ParagraphBlock.vue\";\nimport ImageBlock from \"./blocks/ImageBlock.vue\";\nimport ButtonBlock from \"./blocks/ButtonBlock.vue\";\nimport DividerBlock from \"./blocks/DividerBlock.vue\";\nimport SpacerBlock from \"./blocks/SpacerBlock.vue\";\nimport HtmlBlock from \"./blocks/HtmlBlock.vue\";\nimport SocialIconsBlock from \"./blocks/SocialIconsBlock.vue\";\nimport MenuBlock from \"./blocks/MenuBlock.vue\";\nimport TableBlock from \"./blocks/TableBlock.vue\";\nimport CustomBlock from \"./blocks/CustomBlock.vue\";\nimport VideoBlock from \"./blocks/VideoBlock.vue\";\nimport WrapperBlock from \"./blocks/WrapperBlock.vue\";\n\n// `countdown` is deliberately absent: it resolves from the block registry, which\n// `useEditorCore` populates with a lazy `defineAsyncComponent` so OSS bundles\n// don't carry a Cloud-only block. `resolveBlockComponent` checks the registry\n// first, so a static entry here would never be reached — but its static import\n// would still pull the module into the eager graph and defeat the laziness.\n// The other fallback maps (SectionBlock, BlockPreviewCanvas,\n// PreviewSectionBlock) omit it for the same reason.\nconst blockComponentMap: Record<string, Component> = {\n section: SectionBlock,\n title: TitleBlock,\n paragraph: ParagraphBlock,\n image: ImageBlock,\n button: ButtonBlock,\n divider: DividerBlock,\n spacer: SpacerBlock,\n html: HtmlBlock,\n social: SocialIconsBlock,\n menu: MenuBlock,\n table: TableBlock,\n video: VideoBlock,\n custom: CustomBlock,\n wrapper: WrapperBlock,\n};\n\nconst props = defineProps<{\n viewport: ViewportSize;\n content: TemplateContent;\n selectedBlockId: string | null;\n darkMode: boolean;\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"select-block\", blockId: string | null): void;\n}>();\n\nconst { t } = useI18n();\n\nconst editor = requireInject(EDITOR_KEY, \"Canvas\");\nconst fontsManager = requireInject(FONTS_MANAGER_KEY, \"Canvas\");\nconst conditionPreview = inject(CONDITION_PREVIEW_KEY, null);\nconst blockRegistry = inject(BLOCK_REGISTRY_KEY, null);\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n/**\n * Merge-tag samples render on this canvas **only while preview mode is on**.\n * The `previewMode &&` is the load-bearing half: the canvas is the editing\n * surface, and substituted text in a block a user is about to edit would be\n * text they never wrote. Preview mode is already fully non-editing (clicks and\n * dragging are blocked above), so it is the one state where swapping the\n * displayed value is safe.\n */\nconst mergeTagSampleMode = inject(MERGE_TAG_SAMPLE_MODE_KEY, null);\n// Null in headless mounts and when no resolver is configured.\nconst previewResolution = inject(PREVIEW_RESOLUTION_KEY, null);\nprovide(\n USE_MERGE_TAG_SAMPLES_KEY,\n computed(\n () =>\n props.previewMode &&\n (mergeTagSampleMode?.value ?? false) &&\n // A configured resolver owns what the preview shows. Substituting samples\n // underneath it would mix invented values with real ones, and on the\n // failure path would contradict the note saying the *unresolved* template\n // is showing.\n !previewResolution?.isConfigured,\n ),\n);\n\nconst canChat = computed(() => caps.ai?.isFeatureEnabled(\"chat\") ?? false);\nconst canImport = computed(\n () =>\n canChat.value && (caps.ai?.isFeatureEnabled(\"chatAttachments\") ?? false),\n);\nconst importInput = ref<HTMLInputElement | null>(null);\nfunction pickImport(): void {\n importInput.value?.click();\n}\nfunction importPicked(event: Event): void {\n const input = event.target as HTMLInputElement;\n const files = Array.from(input.files ?? []);\n input.value = \"\";\n if (files.length) caps.ai?.startImport(files);\n}\n\n/**\n * Whether the hand-toggled display-condition filter applies here. Owned by\n * `useEditorCore` and injected rather than re-derived — see the key's comment.\n */\nconst appliesConditionFilter = inject(APPLIES_CONDITION_FILTER_KEY, null);\n\nconst blocks = computed({\n get: () => props.content.blocks,\n set: (value: Block[]) => {\n editor.setContent({\n ...props.content,\n blocks: value,\n });\n },\n});\n\n// Shared with the preview canvas and the save dialog's scaled rows, so all\n// three lay out against the same width.\nconst viewportWidth = computed(() =>\n getEmailFrameWidth(props.content.settings, props.viewport),\n);\n\n// The \"stage\" represents the email body: the content column plus a gutter of\n// email background on each side (#230 — without it a full-width section's own\n// background hides the global one entirely). Mirrors how `mj-body\n// background-color` renders in the gutters around the centered content when\n// the email is sent. The neutral work area beyond the stage is preserved so\n// editor chrome stays legible.\n//\n// `EMAIL_GUTTER` comes from the shared helper rather than a local constant: the\n// preview surfaces show the same band, and two copies drift into two different\n// answers for how much of the body background an email is supposed to show.\nconst stageWidth = computed(() => viewportWidth.value + EMAIL_GUTTER * 2);\n\n// Canvas dark mode preview: simulates how the email will appear in recipients'\n// dark-themed email clients. Uses CSS filter inversion — independent of the\n// editor UI theme (light/dark/auto) which is controlled via uiTheme config.\n// The email bg lives on the `.tpl-canvas-bg` sibling layer (so it can be\n// inverted by `filter` without trapping block chrome in a stacking context);\n// the `.tpl-canvas` itself stays transparent so the bg layer shows through.\n// Shared with every other surface that renders blocks (the saved-block\n// previews), so a block looks the same wherever it is drawn.\nconst canvasStyle = computed(() =>\n getDocumentStyle(props.content.settings, fontsManager.resolveFontFamily),\n);\n// The email's own language, for the browser's spellchecker and hyphenation.\n// Without it the canvas inherits the HOST page's `lang`, so German copy is\n// spellchecked by English rules — every word underlined. `settings.locale`,\n// never `config.locale`: the chrome's language says nothing about the content's,\n// and an author writing English in a German editor must not have their copy\n// declared German. Undefined rather than `\"\"`, which would explicitly declare\n// \"unknown language\" and suppress spellcheck outright.\nconst contentLang = computed(\n () => props.content.settings?.locale?.trim() || undefined,\n);\n// Always a real token: an empty `dir` inherits the host page and the email\n// stage would follow chrome instead of `settings.direction`. Flex `row` on\n// sections follows this inline axis, so column 0 lands on the start edge\n// with no extra reverse class (which would also ship in every LTR stylesheet).\nconst contentDir = computed(() =>\n resolveContentDirection(props.content.settings),\n);\n\n// Empty canvas: the whole dashed placeholder IS the Sortable drop zone.\n// `isEmptyCanvas` toggles the styling + the inline empty-state content.\nconst isEmptyCanvas = computed(\n () => blocks.value.length === 0 && !props.previewMode,\n);\n\n// Highlight the empty drop zone while a block is being dragged over it.\n// Uses a counter to handle dragenter/leave bubbling from descendants —\n// raw event toggling would flicker as the pointer moves between children.\nconst dragEnterDepth = ref(0);\nconst isDragOverEmpty = computed(\n () => isEmptyCanvas.value && dragEnterDepth.value > 0,\n);\n\nfunction handleEmptyDragEnter(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value += 1;\n}\n\nfunction handleEmptyDragLeave(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value = Math.max(0, dragEnterDepth.value - 1);\n}\n\nfunction handleEmptyDrop(): void {\n dragEnterDepth.value = 0;\n}\n\nfunction handleCanvasClick(event: MouseEvent): void {\n if (props.previewMode) {\n return;\n }\n // During a pick session, a stray background click must not clear anything —\n // the session is left only via the bar's Save/Cancel or Escape. Deselecting\n // here would also be meaningless, since picking doesn't touch selection.\n if (caps.savedBlocks?.isPicking.value) {\n return;\n }\n if (event.target === event.currentTarget) {\n emit(\"select-block\", null);\n }\n}\n\nfunction getBlockComponent(block: Block): Component | null {\n return resolveBlockComponent(block, blockRegistry, blockComponentMap);\n}\n\nfunction isLockedByOther(blockId: string): boolean {\n return caps.collaboration?.lockOf(blockId) != null;\n}\n\n/**\n * A click on a block either toggles its pick (while a saved-blocks pick\n * session is running) or selects it. Preview mode and collaborator locks are\n * checked first, so a locked block can be neither selected nor picked.\n */\nfunction handleBlockSelect(blockId: string): void {\n if (props.previewMode || isLockedByOther(blockId)) return;\n const savedBlocks = caps.savedBlocks;\n if (savedBlocks?.isPicking.value) {\n savedBlocks.togglePick(blockId);\n return;\n }\n emit(\"select-block\", blockId);\n}\n\nfunction isPickedBlock(blockId: string): boolean {\n return caps.savedBlocks?.isPicked(blockId) ?? false;\n}\n\n/** True while a pick session runs — swaps block chrome into picking behaviour. */\nconst isPicking = computed(() => caps.savedBlocks?.isPicking.value === true);\n\nfunction handleFetchData(\n block: Block,\n payload: {\n fieldValues: Record<string, unknown>;\n dataSourceFetched: boolean;\n },\n): void {\n if (block.type !== \"custom\") {\n return;\n }\n\n editor.updateBlock(block.id, {\n fieldValues: payload.fieldValues,\n dataSourceFetched: payload.dataSourceFetched,\n } as Partial<CustomBlockType>);\n}\n</script>\n\n<template>\n <!-- STAGE — the email body. Sized to the content column plus a gutter of\n email background on each side, so the global background stays visible\n around full-width sections, mirroring how `mj-body background-color`\n renders in the gutters when sent (#230). The neutral work area beyond\n the stage is preserved so the canvas still reads as a floating card and\n editor chrome stays legible.\n\n Auto margins centre it in the pane. The max-width keeps the pane's\n clearance on each side by shrinking the gutters first, and min-content\n stops it at the email column: past that the margins fall to zero and\n the pane scrolls from the column's left edge instead of clipping it. -->\n <div\n class=\"tpl-canvas-stage tpl:relative tpl:mx-auto tpl:flex tpl:justify-center tpl:rounded-lg\"\n :style=\"{\n width: `${stageWidth}px`,\n maxWidth: 'calc(100% - 4 * var(--tpl-base-size))',\n minWidth: 'min-content',\n boxShadow: darkMode ? 'none' : 'var(--tpl-shadow-xl)',\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <!-- Background layer — holds the email bg and the dark-preview filter,\n spanning the full stage (content + gutters). Filter on this leaf\n layer (no descendants) does not create a containing block / stacking\n context that would trap block chrome (action bar, indicators) inside\n the wrapper. The filter has its own transition so the canvas fades\n smoothly between modes. -->\n <div\n class=\"tpl-canvas-bg tpl:absolute tpl:inset-0 tpl:rounded-lg tpl:pointer-events-none\"\n :style=\"{\n backgroundColor: content.settings.backgroundColor,\n ...(darkMode ? { filter: 'invert(1) hue-rotate(180deg)' } : {}),\n transition: 'filter 300ms ease',\n }\"\n />\n <!-- CONTENT COLUMN — the email content at its true width, centered in the\n stage. A full-width section fills this column but not the surrounding\n gutters, so the global background remains visible beside it. -->\n <div\n data-testid=\"canvas-wrapper\"\n role=\"region\"\n :aria-label=\"t.landmarks.canvas\"\n class=\"tpl-canvas-wrapper tpl:relative\"\n :style=\"{\n width: `${viewportWidth}px`,\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <div\n class=\"tpl-canvas tpl:relative tpl:rounded-lg\"\n :lang=\"contentLang\"\n :dir=\"contentDir\"\n :class=\"{\n 'tpl-canvas--dark-mode': darkMode,\n 'tpl-preview-mode': previewMode,\n }\"\n :style=\"canvasStyle\"\n @click=\"handleCanvasClick\"\n >\n <!-- Preview resolution. The skeleton shows only on a *first* resolve —\n `isInitialResolve` — so switching recipient or reopening keeps the\n last good preview on screen instead of flashing over it. -->\n <div\n v-if=\"previewResolution?.isInitialResolve.value\"\n role=\"status\"\n aria-busy=\"true\"\n data-testid=\"preview-resolution-loading\"\n class=\"tpl:flex tpl:flex-col tpl:gap-3 tpl:p-6\"\n >\n <span class=\"tpl:sr-only\">{{ t.previewResolution.resolving }}</span>\n <div\n v-for=\"n in 3\"\n :key=\"n\"\n aria-hidden=\"true\"\n class=\"tpl-pulse tpl:h-16 tpl:rounded-md tpl:bg-[var(--tpl-bg-hover)]\"\n ></div>\n </div>\n\n <!-- Resolution failed: the unresolved template still renders below, so\n the preview degrades rather than disappearing. -->\n <p\n v-else-if=\"previewResolution?.hasFailed.value\"\n role=\"status\"\n data-testid=\"preview-resolution-failed\"\n class=\"tpl:mx-6 tpl:mt-4 tpl:rounded-md tpl:px-3 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)] tpl:bg-[var(--tpl-bg-hover)]\"\n >\n {{ t.previewResolution.failed }}\n </p>\n\n <!-- `draggable` names what to leave out, the empty-state content, not\n the canvas's own item class: Sortable indexes a cross-list drop in\n the receiving list with the sending list's `draggable`, and a\n canvas-only class matches nothing in a section column, which\n would drop every canvas block at the column's top. The `>` keeps\n hit-testing on the canvas's direct children. -->\n <VueDraggable\n v-show=\"!previewResolution?.isInitialResolve.value\"\n v-model=\"blocks\"\n group=\"blocks\"\n :animation=\"150\"\n ghost-class=\"tpl-ghost\"\n drag-class=\"tpl-dragging\"\n handle=\".tpl-block-btn\"\n :invert-swap=\"true\"\n :inverted-swap-threshold=\"0.65\"\n :disabled=\"previewMode\"\n :draggable=\"'>:not(.tpl-canvas-empty-content)'\"\n :force-fallback=\"true\"\n :class=\"[\n 'tpl-canvas-blocks',\n isEmptyCanvas\n ? 'tpl-canvas-empty tpl:m-6 tpl:flex tpl:min-h-[400px] tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded-xl tpl:border-2 tpl:border-dashed tpl:px-10 tpl:py-12 tpl:text-center tpl:bg-[var(--tpl-bg-elevated)] tpl:font-[var(--tpl-font-family)] tpl:transition-colors'\n : '',\n isEmptyCanvas && isDragOverEmpty\n ? 'tpl-canvas-empty--drag-over tpl:border-[var(--tpl-primary-hover)] tpl:bg-[var(--tpl-primary-light)]'\n : '',\n isEmptyCanvas && !isDragOverEmpty\n ? 'tpl:border-[var(--tpl-primary)]'\n : '',\n ]\"\n @dragenter=\"handleEmptyDragEnter\"\n @dragleave=\"handleEmptyDragLeave\"\n @drop=\"handleEmptyDrop\"\n >\n <!-- Empty-state content: rendered INSIDE the draggable so the whole\n dashed box is the drop zone, but excluded from sortable items by\n the `draggable` selector above. -->\n <div\n v-if=\"isEmptyCanvas\"\n class=\"tpl-canvas-empty-content tpl:flex tpl:flex-col tpl:items-center\"\n >\n <div\n class=\"tpl-canvas-empty-icon tpl:mb-4 tpl:text-[var(--tpl-primary)]\"\n >\n <SquarePlus :size=\"48\" :stroke-width=\"1\" />\n </div>\n <p\n class=\"tpl-canvas-empty-title tpl:m-0 tpl:mb-2 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-primary)]\"\n >\n {{ t.canvas.noBlocks }}\n </p>\n <p\n class=\"tpl-canvas-empty-text tpl:m-0 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.canvas.dragHint }}\n </p>\n <p\n v-if=\"canChat\"\n class=\"tpl:m-0 tpl:mt-2 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.chatHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-chat\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"caps.ai?.open('chat')\"\n >\n <Sparkles :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.menu.chat }}\n </button>\n {{ t.ai.canvas.chatHintSuffix }}\n </p>\n <p\n v-if=\"canImport\"\n class=\"tpl:m-0 tpl:mt-4 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.importHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-import\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"pickImport\"\n >\n <ImageUp :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.import.menu }}\n </button>\n <input\n ref=\"importInput\"\n type=\"file\"\n multiple\n accept=\"image/png,image/jpeg,image/webp,image/gif,application/pdf\"\n hidden\n @change=\"importPicked\"\n />\n </p>\n </div>\n <div\n v-for=\"block in blocks\"\n :key=\"block.id\"\n class=\"tpl-block-item\"\n v-show=\"\n appliesConditionFilter === false ||\n !conditionPreview?.isHidden(block.id)\n \"\n >\n <div class=\"tpl:relative\">\n <component\n v-if=\"block.type === 'wrapper'\"\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n />\n <BlockWrapper\n v-else\n :block=\"block\"\n :is-selected=\"\n !previewMode &&\n !isPicking &&\n selectedBlockId === block.id &&\n !isLockedByOther(block.id)\n \"\n :picked=\"isPickedBlock(block.id)\"\n :viewport=\"viewport\"\n :preview-mode=\"previewMode\"\n @select=\"handleBlockSelect(block.id)\"\n >\n <component\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n @fetch-data=\"handleFetchData(block, $event)\"\n @update=\"\n (updates: Partial<Block>) =>\n editor.updateBlock(block.id, updates)\n \"\n />\n </BlockWrapper>\n </div>\n </div>\n </VueDraggable>\n </div>\n </div>\n </div>\n</template>\n\n<style scoped>\n/* Dark-mode preview: invert only the outermost `.tpl-email-surface` — a\n block's box, a section's wrapper frame, or a layout band. Surfaces nest\n (child blocks inside a section, a box inside its frame, the whole email\n inside a band), and a filter at every level would compound and cancel\n out, so `:not(...)` keeps the inversion single-pass. Block chrome (action\n bar, indicators, overlays) lives outside every surface and is therefore\n never filtered — no counter-filter / toggle flicker. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface:not(.tpl-email-surface *)) {\n filter: invert(1) hue-rotate(180deg);\n}\n:deep(.tpl-email-surface) {\n transition: filter 300ms ease;\n}\n\n/* Counter-invert images so they look normal inside the inverted email\n surface (canonical CSS-filter dark-mode trick). */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface img) {\n filter: invert(1) hue-rotate(180deg);\n}\n\n/* Background photos get the same counter-invert. A filter on the host would\n also hit the content painted over it, so the photo moves to a `::before`\n beneath that content, painted from `--tpl-block-bg-layer`\n (`getBackgroundImageStyle`). Every host is a surface or sits inside one, so\n every host is under exactly one inversion. `isolation` keeps the\n `z-index: -1` layer above the host's background colour wherever the host\n isn't the filtered surface itself. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image),\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image) {\n position: relative;\n isolation: isolate;\n background-image: none !important;\n}\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image)::before,\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image)::before {\n content: \"\";\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n pointer-events: none;\n background: var(--tpl-block-bg-layer, none);\n filter: invert(1) hue-rotate(180deg);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type {\n Block,\n CustomBlock as CustomBlockType,\n TemplateContent,\n ViewportSize,\n} from \"@templatical/types\";\nimport { resolveContentDirection } from \"@templatical/types\";\nimport { ImageUp, Sparkles, SquarePlus } from \"@lucide/vue\";\nimport { computed, inject, provide, ref, type Component } from \"vue\";\nimport {\n EDITOR_KEY,\n APPLIES_CONDITION_FILTER_KEY,\n CONDITION_PREVIEW_KEY,\n BLOCK_REGISTRY_KEY,\n CAPABILITIES_KEY,\n FONTS_MANAGER_KEY,\n MERGE_TAG_SAMPLE_MODE_KEY,\n PREVIEW_RESOLUTION_KEY,\n USE_MERGE_TAG_SAMPLES_KEY,\n requireInject,\n} from \"../keys\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport {\n getDocumentStyle,\n resolveBlockComponent,\n} from \"../utils/blockComponentResolver\";\nimport {\n EMAIL_FRAME_WIDTH_TRANSITION,\n EMAIL_GUTTER,\n getEmailFrameWidth,\n} from \"../utils/emailFrameWidth\";\n\nimport BlockWrapper from \"./blocks/BlockWrapper.vue\";\nimport SectionBlock from \"./blocks/SectionBlock.vue\";\nimport TitleBlock from \"./blocks/TitleBlock.vue\";\nimport ParagraphBlock from \"./blocks/ParagraphBlock.vue\";\nimport ImageBlock from \"./blocks/ImageBlock.vue\";\nimport ButtonBlock from \"./blocks/ButtonBlock.vue\";\nimport DividerBlock from \"./blocks/DividerBlock.vue\";\nimport SpacerBlock from \"./blocks/SpacerBlock.vue\";\nimport HtmlBlock from \"./blocks/HtmlBlock.vue\";\nimport SocialIconsBlock from \"./blocks/SocialIconsBlock.vue\";\nimport MenuBlock from \"./blocks/MenuBlock.vue\";\nimport TableBlock from \"./blocks/TableBlock.vue\";\nimport CustomBlock from \"./blocks/CustomBlock.vue\";\nimport VideoBlock from \"./blocks/VideoBlock.vue\";\nimport WrapperBlock from \"./blocks/WrapperBlock.vue\";\n\n// `countdown` is deliberately absent: it resolves from the block registry, which\n// `useEditorCore` populates with a lazy `defineAsyncComponent` so OSS bundles\n// don't carry a Cloud-only block. `resolveBlockComponent` checks the registry\n// first, so a static entry here would never be reached — but its static import\n// would still pull the module into the eager graph and defeat the laziness.\n// The other fallback maps (SectionBlock, BlockPreviewCanvas,\n// PreviewSectionBlock) omit it for the same reason.\nconst blockComponentMap: Record<string, Component> = {\n section: SectionBlock,\n title: TitleBlock,\n paragraph: ParagraphBlock,\n image: ImageBlock,\n button: ButtonBlock,\n divider: DividerBlock,\n spacer: SpacerBlock,\n html: HtmlBlock,\n social: SocialIconsBlock,\n menu: MenuBlock,\n table: TableBlock,\n video: VideoBlock,\n custom: CustomBlock,\n wrapper: WrapperBlock,\n};\n\nconst props = defineProps<{\n viewport: ViewportSize;\n content: TemplateContent;\n selectedBlockId: string | null;\n darkMode: boolean;\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"select-block\", blockId: string | null): void;\n}>();\n\nconst { t } = useI18n();\n\nconst editor = requireInject(EDITOR_KEY, \"Canvas\");\nconst fontsManager = requireInject(FONTS_MANAGER_KEY, \"Canvas\");\nconst conditionPreview = inject(CONDITION_PREVIEW_KEY, null);\nconst blockRegistry = inject(BLOCK_REGISTRY_KEY, null);\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n/**\n * Merge-tag samples render on this canvas **only while preview mode is on**.\n * The `previewMode &&` is the load-bearing half: the canvas is the editing\n * surface, and substituted text in a block a user is about to edit would be\n * text they never wrote. Preview mode is already fully non-editing (clicks and\n * dragging are blocked above), so it is the one state where swapping the\n * displayed value is safe.\n */\nconst mergeTagSampleMode = inject(MERGE_TAG_SAMPLE_MODE_KEY, null);\n// Null in headless mounts and when no resolver is configured.\nconst previewResolution = inject(PREVIEW_RESOLUTION_KEY, null);\nprovide(\n USE_MERGE_TAG_SAMPLES_KEY,\n computed(\n () =>\n props.previewMode &&\n (mergeTagSampleMode?.value ?? false) &&\n // A configured resolver owns what the preview shows. Substituting samples\n // underneath it would mix invented values with real ones, and on the\n // failure path would contradict the note saying the *unresolved* template\n // is showing.\n !previewResolution?.isConfigured,\n ),\n);\n\nconst canChat = computed(() => caps.ai?.isFeatureEnabled(\"chat\") ?? false);\nconst canImport = computed(\n () =>\n canChat.value && (caps.ai?.isFeatureEnabled(\"chatAttachments\") ?? false),\n);\nconst importInput = ref<HTMLInputElement | null>(null);\nfunction pickImport(): void {\n importInput.value?.click();\n}\nfunction importPicked(event: Event): void {\n const input = event.target as HTMLInputElement;\n const files = Array.from(input.files ?? []);\n input.value = \"\";\n if (files.length) caps.ai?.startImport(files);\n}\n\n/**\n * Whether the hand-toggled display-condition filter applies here. Owned by\n * `useEditorCore` and injected rather than re-derived — see the key's comment.\n */\nconst appliesConditionFilter = inject(APPLIES_CONDITION_FILTER_KEY, null);\n\nconst blocks = computed({\n get: () => props.content.blocks,\n set: (value: Block[]) => {\n editor.setContent({\n ...props.content,\n blocks: value,\n });\n },\n});\n\n// Shared with the preview canvas and the save dialog's scaled rows, so all\n// three lay out against the same width.\nconst viewportWidth = computed(() =>\n getEmailFrameWidth(props.content.settings, props.viewport),\n);\n\n// The \"stage\" represents the email body: the content column plus a gutter of\n// email background on each side (#230 — without it a full-width section's own\n// background hides the global one entirely). Mirrors how `mj-body\n// background-color` renders in the gutters around the centered content when\n// the email is sent. The neutral work area beyond the stage is preserved so\n// editor chrome stays legible.\n//\n// `EMAIL_GUTTER` comes from the shared helper rather than a local constant: the\n// preview surfaces show the same band, and two copies drift into two different\n// answers for how much of the body background an email is supposed to show.\nconst stageWidth = computed(() => viewportWidth.value + EMAIL_GUTTER * 2);\n\n// Canvas dark mode preview: simulates how the email will appear in recipients'\n// dark-themed email clients. Uses CSS filter inversion — independent of the\n// editor UI theme (light/dark/auto) which is controlled via uiTheme config.\n// The email bg lives on the `.tpl-canvas-bg` sibling layer (so it can be\n// inverted by `filter` without trapping block chrome in a stacking context);\n// the `.tpl-canvas` itself stays transparent so the bg layer shows through.\n// Shared with every other surface that renders blocks (the saved-block\n// previews), so a block looks the same wherever it is drawn.\nconst canvasStyle = computed(() =>\n getDocumentStyle(props.content.settings, fontsManager.resolveFontFamily),\n);\n// The email's own language, for the browser's spellchecker and hyphenation.\n// Without it the canvas inherits the HOST page's `lang`, so German copy is\n// spellchecked by English rules — every word underlined. `settings.locale`,\n// never `config.locale`: the chrome's language says nothing about the content's,\n// and an author writing English in a German editor must not have their copy\n// declared German. Undefined rather than `\"\"`, which would explicitly declare\n// \"unknown language\" and suppress spellcheck outright.\nconst contentLang = computed(\n () => props.content.settings?.locale?.trim() || undefined,\n);\n// Always a real token: an empty `dir` inherits the host page and the email\n// stage would follow chrome instead of `settings.direction`. Flex `row` on\n// sections follows this inline axis, so column 0 lands on the start edge\n// with no extra reverse class (which would also ship in every LTR stylesheet).\nconst contentDir = computed(() =>\n resolveContentDirection(props.content.settings),\n);\n\n// Empty canvas: the whole dashed placeholder IS the Sortable drop zone.\n// `isEmptyCanvas` toggles the styling + the inline empty-state content.\nconst isEmptyCanvas = computed(\n () => blocks.value.length === 0 && !props.previewMode,\n);\n\n// Highlight the empty drop zone while a block is being dragged over it.\n// Uses a counter to handle dragenter/leave bubbling from descendants —\n// raw event toggling would flicker as the pointer moves between children.\nconst dragEnterDepth = ref(0);\nconst isDragOverEmpty = computed(\n () => isEmptyCanvas.value && dragEnterDepth.value > 0,\n);\n\nfunction handleEmptyDragEnter(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value += 1;\n}\n\nfunction handleEmptyDragLeave(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value = Math.max(0, dragEnterDepth.value - 1);\n}\n\nfunction handleEmptyDrop(): void {\n dragEnterDepth.value = 0;\n}\n\nfunction handleCanvasClick(event: MouseEvent): void {\n if (props.previewMode) {\n return;\n }\n // During a pick session, a stray background click must not clear anything —\n // the session is left only via the bar's Save/Cancel or Escape. Deselecting\n // here would also be meaningless, since picking doesn't touch selection.\n if (caps.savedBlocks?.isPicking.value) {\n return;\n }\n if (event.target === event.currentTarget) {\n emit(\"select-block\", null);\n }\n}\n\nfunction getBlockComponent(block: Block): Component | null {\n return resolveBlockComponent(block, blockRegistry, blockComponentMap);\n}\n\nfunction isLockedByOther(blockId: string): boolean {\n return caps.collaboration?.lockOf(blockId) != null;\n}\n\n/**\n * A click on a block either toggles its pick (while a saved-blocks pick\n * session is running) or selects it. Preview mode and collaborator locks are\n * checked first, so a locked block can be neither selected nor picked.\n */\nfunction handleBlockSelect(blockId: string): void {\n if (props.previewMode || isLockedByOther(blockId)) return;\n const savedBlocks = caps.savedBlocks;\n if (savedBlocks?.isPicking.value) {\n savedBlocks.togglePick(blockId);\n return;\n }\n emit(\"select-block\", blockId);\n}\n\nfunction isPickedBlock(blockId: string): boolean {\n return caps.savedBlocks?.isPicked(blockId) ?? false;\n}\n\n/** True while a pick session runs — swaps block chrome into picking behaviour. */\nconst isPicking = computed(() => caps.savedBlocks?.isPicking.value === true);\n\nfunction handleFetchData(\n block: Block,\n payload: {\n fieldValues: Record<string, unknown>;\n dataSourceFetched: boolean;\n },\n): void {\n if (block.type !== \"custom\") {\n return;\n }\n\n editor.updateBlock(block.id, {\n fieldValues: payload.fieldValues,\n dataSourceFetched: payload.dataSourceFetched,\n } as Partial<CustomBlockType>);\n}\n</script>\n\n<template>\n <!-- STAGE — the email body. Sized to the content column plus a gutter of\n email background on each side, so the global background stays visible\n around full-width sections, mirroring how `mj-body background-color`\n renders in the gutters when sent (#230). The neutral work area beyond\n the stage is preserved so the canvas still reads as a floating card and\n editor chrome stays legible.\n\n Auto margins centre it in the pane. The max-width keeps the pane's\n clearance on each side by shrinking the gutters first, and min-content\n stops it at the email column: past that the margins fall to zero and\n the pane scrolls from the column's left edge instead of clipping it. -->\n <div\n class=\"tpl-canvas-stage tpl:relative tpl:mx-auto tpl:flex tpl:justify-center tpl:rounded-lg\"\n :style=\"{\n width: `${stageWidth}px`,\n maxWidth: 'calc(100% - 4 * var(--tpl-base-size))',\n minWidth: 'min-content',\n boxShadow: darkMode ? 'none' : 'var(--tpl-shadow-xl)',\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <!-- Background layer — holds the email bg and the dark-preview filter,\n spanning the full stage (content + gutters). Filter on this leaf\n layer (no descendants) does not create a containing block / stacking\n context that would trap block chrome (action bar, indicators) inside\n the wrapper. The filter has its own transition so the canvas fades\n smoothly between modes. -->\n <div\n class=\"tpl-canvas-bg tpl:absolute tpl:inset-0 tpl:rounded-lg tpl:pointer-events-none\"\n :style=\"{\n backgroundColor: content.settings.backgroundColor,\n ...(darkMode ? { filter: 'invert(1) hue-rotate(180deg)' } : {}),\n transition: 'filter 300ms ease',\n }\"\n />\n <!-- CONTENT COLUMN — the email content at its true width, centered in the\n stage. A full-width section fills this column but not the surrounding\n gutters, so the global background remains visible beside it. -->\n <div\n data-testid=\"canvas-wrapper\"\n role=\"region\"\n :aria-label=\"t.landmarks.canvas\"\n class=\"tpl-canvas-wrapper tpl:relative\"\n :style=\"{\n width: `${viewportWidth}px`,\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <div\n class=\"tpl-canvas tpl:relative tpl:rounded-lg\"\n :lang=\"contentLang\"\n :dir=\"contentDir\"\n :class=\"{\n 'tpl-canvas--dark-mode': darkMode,\n 'tpl-preview-mode': previewMode,\n }\"\n :style=\"canvasStyle\"\n @click=\"handleCanvasClick\"\n >\n <!-- Preview resolution. The skeleton shows only on a *first* resolve —\n `isInitialResolve` — so switching recipient or reopening keeps the\n last good preview on screen instead of flashing over it. -->\n <div\n v-if=\"previewResolution?.isInitialResolve.value\"\n role=\"status\"\n aria-busy=\"true\"\n data-testid=\"preview-resolution-loading\"\n class=\"tpl:flex tpl:flex-col tpl:gap-3 tpl:p-6\"\n >\n <span class=\"tpl:sr-only\">{{ t.previewResolution.resolving }}</span>\n <div\n v-for=\"n in 3\"\n :key=\"n\"\n aria-hidden=\"true\"\n class=\"tpl-pulse tpl:h-16 tpl:rounded-md tpl:bg-[var(--tpl-bg-hover)]\"\n ></div>\n </div>\n\n <!-- Resolution failed: the unresolved template still renders below, so\n the preview degrades rather than disappearing. -->\n <p\n v-else-if=\"previewResolution?.hasFailed.value\"\n role=\"status\"\n data-testid=\"preview-resolution-failed\"\n class=\"tpl:mx-6 tpl:mt-4 tpl:rounded-md tpl:px-3 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)] tpl:bg-[var(--tpl-bg-hover)]\"\n >\n {{ t.previewResolution.failed }}\n </p>\n\n <!-- `draggable` names what to leave out, the empty-state content, not\n the canvas's own item class: Sortable indexes a cross-list drop in\n the receiving list with the sending list's `draggable`, and a\n canvas-only class matches nothing in a section column, which\n would drop every canvas block at the column's top. The `>` keeps\n hit-testing on the canvas's direct children. -->\n <VueDraggable\n v-show=\"!previewResolution?.isInitialResolve.value\"\n v-model=\"blocks\"\n group=\"blocks\"\n :animation=\"150\"\n ghost-class=\"tpl-ghost\"\n drag-class=\"tpl-dragging\"\n handle=\".tpl-block-btn\"\n :invert-swap=\"true\"\n :inverted-swap-threshold=\"0.65\"\n :disabled=\"previewMode\"\n :draggable=\"'>:not(.tpl-canvas-empty-content)'\"\n :force-fallback=\"true\"\n :class=\"[\n 'tpl-canvas-blocks',\n isEmptyCanvas\n ? 'tpl-canvas-empty tpl:m-6 tpl:flex tpl:min-h-[400px] tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded-xl tpl:border-2 tpl:border-dashed tpl:px-10 tpl:py-12 tpl:text-center tpl:bg-[var(--tpl-bg-elevated)] tpl:font-[var(--tpl-font-family)] tpl:transition-colors'\n : '',\n isEmptyCanvas && isDragOverEmpty\n ? 'tpl-canvas-empty--drag-over tpl:border-[var(--tpl-primary-hover)] tpl:bg-[var(--tpl-primary-light)]'\n : '',\n isEmptyCanvas && !isDragOverEmpty\n ? 'tpl:border-[var(--tpl-primary)]'\n : '',\n ]\"\n @dragenter=\"handleEmptyDragEnter\"\n @dragleave=\"handleEmptyDragLeave\"\n @drop=\"handleEmptyDrop\"\n >\n <!-- Empty-state content: rendered INSIDE the draggable so the whole\n dashed box is the drop zone, but excluded from sortable items by\n the `draggable` selector above. -->\n <div\n v-if=\"isEmptyCanvas\"\n class=\"tpl-canvas-empty-content tpl:flex tpl:flex-col tpl:items-center\"\n >\n <div\n class=\"tpl-canvas-empty-icon tpl:mb-4 tpl:text-[var(--tpl-primary)]\"\n >\n <SquarePlus :size=\"48\" :stroke-width=\"1\" />\n </div>\n <p\n class=\"tpl-canvas-empty-title tpl:m-0 tpl:mb-2 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-primary)]\"\n >\n {{ t.canvas.noBlocks }}\n </p>\n <p\n class=\"tpl-canvas-empty-text tpl:m-0 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.canvas.dragHint }}\n </p>\n <p\n v-if=\"canChat\"\n class=\"tpl:m-0 tpl:mt-2 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.chatHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-chat\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"caps.ai?.open('chat')\"\n >\n <Sparkles :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.menu.chat }}\n </button>\n {{ t.ai.canvas.chatHintSuffix }}\n </p>\n <p\n v-if=\"canImport\"\n class=\"tpl:m-0 tpl:mt-4 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.importHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-import\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"pickImport\"\n >\n <ImageUp :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.import.menu }}\n </button>\n <input\n ref=\"importInput\"\n type=\"file\"\n multiple\n accept=\"image/png,image/jpeg,image/webp,image/gif,application/pdf\"\n hidden\n @change=\"importPicked\"\n />\n </p>\n </div>\n <div\n v-for=\"block in blocks\"\n :key=\"block.id\"\n class=\"tpl-block-item\"\n v-show=\"\n appliesConditionFilter === false ||\n !conditionPreview?.isHidden(block.id)\n \"\n >\n <div class=\"tpl:relative\">\n <component\n v-if=\"block.type === 'wrapper'\"\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n />\n <BlockWrapper\n v-else\n :block=\"block\"\n :is-selected=\"\n !previewMode &&\n !isPicking &&\n selectedBlockId === block.id &&\n !isLockedByOther(block.id)\n \"\n :picked=\"isPickedBlock(block.id)\"\n :viewport=\"viewport\"\n :preview-mode=\"previewMode\"\n @select=\"handleBlockSelect(block.id)\"\n >\n <component\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n @fetch-data=\"handleFetchData(block, $event)\"\n @update=\"\n (updates: Partial<Block>) =>\n editor.updateBlock(block.id, updates)\n \"\n />\n </BlockWrapper>\n </div>\n </div>\n </VueDraggable>\n </div>\n </div>\n </div>\n</template>\n\n<style scoped>\n/* Dark-mode preview: invert only the outermost `.tpl-email-surface` — a\n block's box, a section's wrapper frame, or a layout band. Surfaces nest\n (child blocks inside a section, a box inside its frame, the whole email\n inside a band), and a filter at every level would compound and cancel\n out, so `:not(...)` keeps the inversion single-pass. Block chrome (action\n bar, indicators, overlays) lives outside every surface and is therefore\n never filtered — no counter-filter / toggle flicker. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface:not(.tpl-email-surface *)) {\n filter: invert(1) hue-rotate(180deg);\n}\n:deep(.tpl-email-surface) {\n transition: filter 300ms ease;\n}\n\n/* Counter-invert images so they look normal inside the inverted email\n surface (canonical CSS-filter dark-mode trick). */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface img) {\n filter: invert(1) hue-rotate(180deg);\n}\n\n/* Background photos get the same counter-invert. A filter on the host would\n also hit the content painted over it, so the photo moves to a `::before`\n beneath that content, painted from `--tpl-block-bg-layer`\n (`getBackgroundImageStyle`). Every host is a surface or sits inside one, so\n every host is under exactly one inversion. `isolation` keeps the\n `z-index: -1` layer above the host's background colour wherever the host\n isn't the filtered surface itself. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image),\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image) {\n position: relative;\n isolation: isolate;\n background-image: none !important;\n}\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image)::before,\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image)::before {\n content: \"\";\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n pointer-events: none;\n background: var(--tpl-block-bg-layer, none);\n filter: invert(1) hue-rotate(180deg);\n}\n</style>\n","<script lang=\"ts\">\nimport { defineComponent, h, inject, type ComputedRef } from \"vue\";\nimport { CUSTOM_BLOCK_STYLESHEETS_KEY } from \"../keys\";\n\n/**\n * Renders one `<style>` tag per unique custom-block definition stylesheet\n * currently in use by the editor's content. Mounted near the top of\n * `Editor.vue`'s root template so the rules sit early in the document order\n * and apply to the canvas.\n *\n * In shadow-DOM mode (`shadowDom: true`, default) the styles scope to the\n * editor's shadow root. In light-DOM mode they leak globally, matching the\n * existing behavior of the editor's published `dist/style.css` in that mode\n * — no new global-leak vector.\n *\n * Why a render function instead of `<template>`: Vue's template compiler\n * treats `<style>` inside `<template>` as a side-effect tag and refuses to\n * emit it in strict client-render compilation paths (notably the one used\n * by `vue-tsc` and Vitest's Vue plugin). The render function below\n * bypasses the template compiler entirely and produces the same DOM at\n * runtime — and `innerHTML` on a `<style>` element sets the CSS rules\n * directly, no escape/parse pass between authoring and the cssom.\n */\nexport default defineComponent({\n name: \"CustomBlockStylesheets\",\n setup() {\n const stylesheets = inject<ComputedRef<string[]> | null>(\n CUSTOM_BLOCK_STYLESHEETS_KEY,\n null,\n );\n\n return () => {\n if (!stylesheets) return null;\n return stylesheets.value.map((css, i) =>\n h(\"style\", {\n key: i,\n \"data-tpl-custom-block-stylesheet\": \"\",\n innerHTML: css,\n }),\n );\n };\n },\n});\n</script>\n","<script lang=\"ts\">\nimport { defineComponent, h, inject, type ComputedRef } from \"vue\";\nimport { CUSTOM_BLOCK_STYLESHEETS_KEY } from \"../keys\";\n\n/**\n * Renders one `<style>` tag per unique custom-block definition stylesheet\n * currently in use by the editor's content. Mounted near the top of\n * `Editor.vue`'s root template so the rules sit early in the document order\n * and apply to the canvas.\n *\n * In shadow-DOM mode (`shadowDom: true`, default) the styles scope to the\n * editor's shadow root. In light-DOM mode they leak globally, matching the\n * existing behavior of the editor's published `dist/style.css` in that mode\n * — no new global-leak vector.\n *\n * Why a render function instead of `<template>`: Vue's template compiler\n * treats `<style>` inside `<template>` as a side-effect tag and refuses to\n * emit it in strict client-render compilation paths (notably the one used\n * by `vue-tsc` and Vitest's Vue plugin). The render function below\n * bypasses the template compiler entirely and produces the same DOM at\n * runtime — and `innerHTML` on a `<style>` element sets the CSS rules\n * directly, no escape/parse pass between authoring and the cssom.\n */\nexport default defineComponent({\n name: \"CustomBlockStylesheets\",\n setup() {\n const stylesheets = inject<ComputedRef<string[]> | null>(\n CUSTOM_BLOCK_STYLESHEETS_KEY,\n null,\n );\n\n return () => {\n if (!stylesheets) return null;\n return stylesheets.value.map((css, i) =>\n h(\"style\", {\n key: i,\n \"data-tpl-custom-block-stylesheet\": \"\",\n innerHTML: css,\n }),\n );\n };\n },\n});\n</script>\n","/**\n * Filters and reorders a candidate list of block-palette items against a\n * consumer-supplied `paletteBlocks` allowlist.\n *\n * Each `paletteBlocks` entry is a block-type key that must match a candidate's\n * `type`: a bare built-in type (e.g. `\"image\"`) or a prefixed custom type\n * (e.g. `\"custom:qrcode\"`). `\"hero\"` is a shortcut, not a block type: it\n * inserts a one-column section in hero mode with starter content. The\n * result's `items` contains exactly the candidates named in `paletteBlocks`, in\n * that order. Entries with no matching candidate (a typo, an unregistered\n * custom block, or a plan-gated built-in like `countdown` outside Cloud) are\n * collected into `unknown` so the caller can warn and skip. A type listed more\n * than once is rendered once.\n *\n * When `paletteBlocks` is `undefined` or empty the candidates are returned\n * unchanged (the default full palette). An empty allowlist is treated as \"not\n * configured\" rather than \"hide everything\", since a zero-block palette is\n * almost always a mistake.\n */\nexport function resolvePaletteBlocks<T extends { type: string }>(\n candidates: T[],\n paletteBlocks: string[] | undefined,\n): { items: T[]; unknown: string[] } {\n if (!paletteBlocks || paletteBlocks.length === 0) {\n return { items: candidates, unknown: [] };\n }\n\n const byType = new Map(candidates.map((c) => [c.type, c]));\n const items: T[] = [];\n const unknown: string[] = [];\n const seen = new Set<string>();\n\n for (const entry of paletteBlocks) {\n if (seen.has(entry)) continue;\n seen.add(entry);\n\n const candidate = byType.get(entry);\n if (candidate) {\n items.push(candidate);\n } else {\n unknown.push(entry);\n }\n }\n\n return { items, unknown };\n}\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type { Block, BlockType } from \"@templatical/types\";\nimport { createBlock, createCustomBlock } from \"@templatical/types\";\nimport { Package } from \"@lucide/vue\";\nimport { computed, inject, onScopeDispose, ref, watch } from \"vue\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport CustomBlockIcon from \"./CustomBlockIcon.vue\";\nimport { blockTypeIcons } from \"../utils/blockTypeIcons\";\nimport { getBlockTypeLabel } from \"../utils/blockTypeLabels\";\nimport { createHeroSection, HERO_PALETTE_TYPE } from \"../utils/heroShortcut\";\nimport { resolvePaletteBlocks } from \"../utils/resolvePaletteBlocks\";\nimport { insertBlockAtSelection } from \"../utils/insertBlockAtSelection\";\nimport { useScrollToBlock } from \"../composables/useScrollToBlock\";\nimport { logger } from \"../utils/logger\";\nimport {\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n PALETTE_BLOCKS_KEY,\n BLOCK_DEFAULTS_KEY,\n CAPABILITIES_KEY,\n EDITOR_KEY,\n} from \"../keys\";\n\ninterface BlockTypeItem {\n type: BlockType | string;\n label: string;\n isCustom?: boolean;\n icon?: string;\n}\n\nconst { t, format } = useI18n();\nconst customBlockDefinitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst paletteBlocks = inject(PALETTE_BLOCKS_KEY, undefined);\nconst blockDefaults = inject(BLOCK_DEFAULTS_KEY, undefined);\nconst editor = inject(EDITOR_KEY, null);\nconst scrollToBlock = useScrollToBlock();\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n// Availability only — deliberately NOT `count > 0`. Gating on the loaded count\n// meant the entry appeared only once the consumer's `list()` resolved, so a slow\n// endpoint shifted the rail mid-session and an empty library hid the feature\n// entirely. The list is now fetched when the browser opens instead.\nconst showSavedBlocksSection = computed(\n () => caps.savedBlocks?.isAvailable.value === true,\n);\n\nconst isExpanded = ref(false);\nconst isDragging = ref(false);\nconst railEl = ref<HTMLElement | null>(null);\n\n// Sortable's default is 0, and the `fallbackTolerance &&` guard treats 0 as\n// \"no threshold\", so any pointer movement starts a force-fallback drag. The\n// palette button is also the click-to-insert control, and a drag that jitters\n// onto the canvas then clicks it inserts a second block (#817). 3–5px is\n// Sortable's own range for clickable items. 4 matches the e2e nudge in\n// `pointerDriveFromPalette` (`startX + 4`): Sortable starts the drag when\n// movement is not strictly below this value, so that nudge still counts.\nconst PALETTE_DRAG_TOLERANCE_PX = 4;\n\n// `start` means a drag actually began. A stationary click emits `choose` +\n// `unchoose` and never `start`, so this must not key off `isDragging` — that\n// flag flips at pointerdown. Cleared on a macrotask after `end`: `end` runs\n// inside mouseup, and the click is dispatched later in that same turn, after\n// microtasks. `nextTick` / `queueMicrotask` would drop the flag first and the\n// duplicate would land. `unchoose` fires before `end` on a completed drag, so\n// clearing there has the same hole.\nlet suppressPaletteClick = false;\nlet suppressPaletteClickTimer = 0;\n\nonScopeDispose(() => {\n window.clearTimeout(suppressPaletteClickTimer);\n});\n\n// `:focus-visible`, never `:focus`: a mouse click leaves the clicked palette\n// button focused, so a plain `:focus` test would pin the rail open from the\n// first click-to-insert onward — the very symptom this rail already had for\n// another reason (#568). Keyboard focus does keep it open, because collapsing\n// hides the label of the entry the user has focused.\nfunction hasKeyboardFocusInRail(): boolean {\n try {\n return railEl.value?.querySelector(\":focus-visible\") != null;\n } catch {\n // Firefox <85 / Safari <15.4 — reachable on the `shadowDom: false` tier,\n // whose browser floor predates the selector — throw on it. Reading that\n // as \"no keyboard focus\" keeps the collapse working there.\n return false;\n }\n}\n\nfunction handleSidebarLeave(): void {\n // Don't collapse while a Sortable drag is in progress. If the sidebar\n // shrinks (200px → 48px) DURING the drag's threshold-to-dragStarted\n // window, `dragEl.getBoundingClientRect()` returns a mid-transition\n // rect when Sortable's `_appendGhost` runs — the fallback ghost gets\n // stamped with that wrong rect and ends up visibly offset from the\n // cursor for the rest of the drag. Cleared on drag-end.\n if (isDragging.value) return;\n if (hasKeyboardFocusInRail()) return;\n isExpanded.value = false;\n}\n\nfunction handleDragChoose(): void {\n // `choose` fires synchronously inside Sortable's `_onTapStart` at\n // pointerdown, BEFORE any pointermove or mouseleave. `start` would be\n // too late — it fires only after the threshold-move dispatches\n // `_dragStarted`, by which time mouseleave may already have flipped\n // `isExpanded` and the sidebar may be mid-collapse.\n isDragging.value = true;\n}\n\nfunction handleDragUnchoose(): void {\n // `end` is not the counterpart of `choose` — Sortable gates it on\n // `Sortable.active`, which only `_dragStarted` sets, so a click on a palette\n // entry emits `choose` + `unchoose` and no `end` at all. Clearing the guard\n // only in `handleDragEnd` therefore latches it true on the first click and\n // `handleSidebarLeave` bails forever after: the rail stays expanded until\n // some later drag happens to complete (#568). `unchoose` fires on every\n // release, at drop time — long after `_appendGhost` captured its rect — so\n // it cannot re-open the race `handleDragChoose` guards.\n isDragging.value = false;\n}\n\nfunction handleDragStart(): void {\n // Click suppression only. The rail-width guard stays on `choose`: `start`\n // is after `_dragStarted`, which is too late to stop the collapse race.\n suppressPaletteClick = true;\n window.clearTimeout(suppressPaletteClickTimer);\n}\n\nfunction handleRailFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget;\n if (next instanceof Node && railEl.value?.contains(next)) return;\n // Inserting selects the new block and moves focus off the palette button.\n // The pointer is often still on the rail. Collapsing here shrinks the\n // label strip out from under it, and the next press opens the rail\n // instead of inserting (#818).\n if (railEl.value?.matches(\":hover\")) return;\n isExpanded.value = false;\n}\n\nfunction clearFallbackClickSwallow(): void {\n // A fallback drag sets Sortable's ignoreNextClick. Sortable clears it by\n // swallowing the next click. A slip that stays on the palette cancels\n // mouseup, so that click is never dispatched and the author's next press\n // is the one swallowed. This click is aimed at the document, not a palette\n // button, so it spends the swallow without inserting. The button's own\n // click stays suppressed until the macrotask in handleDragEnd.\n railEl.value?.ownerDocument.dispatchEvent(\n new MouseEvent(\"click\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n }),\n );\n}\n\nfunction handleDragEnd(): void {\n isDragging.value = false;\n // A canvas drop ends outside the rail, and `mouseleave` never fires for\n // that path: `handleSidebarLeave` bailed while `isDragging` was true.\n // Collapse only then. A press that slipped into a fallback drag and\n // released still on the palette must leave the rail open (#818), including\n // when focusout already collapsed it earlier in this same pointerup.\n // `:hover` matches the rail while the pointer is over a button inside it.\n // The fallback ghost has `pointer-events: none`, so it does not take the hit.\n if (railEl.value?.matches(\":hover\")) {\n isExpanded.value = true;\n clearFallbackClickSwallow();\n } else {\n isExpanded.value = false;\n }\n window.clearTimeout(suppressPaletteClickTimer);\n suppressPaletteClickTimer = window.setTimeout(() => {\n suppressPaletteClick = false;\n }, 0);\n}\n\nconst builtInBlockTypeOrder: string[] = [\n \"section\",\n HERO_PALETTE_TYPE,\n \"image\",\n \"title\",\n \"paragraph\",\n \"button\",\n \"divider\",\n \"video\",\n \"social\",\n \"menu\",\n \"table\",\n \"spacer\",\n \"html\",\n];\n\nconst builtInBlockTypes = computed<BlockTypeItem[]>(() => {\n const types: BlockTypeItem[] = builtInBlockTypeOrder.map((type) => ({\n type,\n label: getBlockTypeLabel(type, t),\n }));\n\n // Countdown requires Templatical Cloud for server-side GIF rendering\n if (caps.plan) {\n types.splice(-1, 0, {\n type: \"countdown\",\n label: getBlockTypeLabel(\"countdown\", t),\n });\n }\n\n return types;\n});\n\nconst customBlockItems = computed<BlockTypeItem[]>(() => {\n return customBlockDefinitions.map((def) => ({\n type: `custom:${def.type}`,\n label: def.name,\n isCustom: true,\n icon: def.icon,\n }));\n});\n\nconst candidateBlockTypes = computed<BlockTypeItem[]>(() => [\n ...builtInBlockTypes.value,\n ...customBlockItems.value,\n]);\n\n// Apply the consumer's `paletteBlocks` allowlist + order when provided; otherwise show\n// the full default palette. Filtering only affects the palette — the block\n// registry stays complete, so existing content using a hidden type still renders.\nconst resolvedPalette = computed(() =>\n resolvePaletteBlocks(candidateBlockTypes.value, paletteBlocks),\n);\n\nconst blockTypes = computed<BlockTypeItem[]>(() => resolvedPalette.value.items);\n\n// Warn once per unknown `paletteBlocks` entry (a typo, an unregistered custom block, or\n// `countdown` outside a Cloud plan). Done in a watcher rather than inside the\n// computed so recomputes don't repeat the warning.\nconst warnedPaletteEntries = new Set<string>();\nwatch(\n () => resolvedPalette.value.unknown,\n (unknown) => {\n for (const entry of unknown) {\n if (warnedPaletteEntries.has(entry)) continue;\n warnedPaletteEntries.add(entry);\n logger.warn(\n `config.paletteBlocks: \"${entry}\" is not a built-in or registered custom block ` +\n `(use the \"custom:\" prefix for custom blocks) — skipping it in the palette.`,\n );\n }\n },\n { immediate: true },\n);\n\nfunction createBlockFromItem(item: BlockTypeItem): Block {\n if (item.isCustom) {\n const customType = item.type.replace(\"custom:\", \"\");\n const definition = customBlockDefinitions.find(\n (d) => d.type === customType,\n );\n if (definition) {\n return createCustomBlock(definition);\n }\n }\n\n // A shortcut, not a block type: a hero-mode section with starter content.\n if (item.type === HERO_PALETTE_TYPE) {\n return createHeroSection(blockDefaults?.value, t.blockDefaults.paragraph);\n }\n\n // `.value` at insert time, never destructured at setup: the recipient-facing\n // half of these defaults tracks the template's own content language, which\n // the author can change while the palette is mounted.\n return createBlock(item.type as BlockType, blockDefaults?.value);\n}\n\nfunction insertBlockFromItem(item: BlockTypeItem): void {\n if (!editor) return;\n const block = createBlockFromItem(item);\n // Land below the selection, not at the end: on a template taller than the\n // viewport an appended block is below the fold, and the canvas does not\n // follow on its own, so the click reads as a no-op (issue #568).\n // Selecting is not visible by itself, and the append fallback still lands\n // off-screen — the canvas has to follow either way.\n if (insertBlockAtSelection(editor, block)) scrollToBlock(block.id);\n}\n\nfunction handlePaletteClick(item: BlockTypeItem): void {\n // The drag element is this button. Sortable moves it into the canvas drop\n // slot and clears `ignoreNextClick` inside `_onDragOver` once the pointer\n // enters that list, so the click after mouseup still reaches this handler\n // and inserts a second block (#817).\n if (suppressPaletteClick) return;\n insertBlockFromItem(item);\n}\n\nfunction handlePaletteKeydown(event: KeyboardEvent, item: BlockTypeItem): void {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n insertBlockFromItem(item);\n }\n}\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 48px the canvas body leaves\n for the collapsed rail (`left-12`). -->\n <aside\n ref=\"railEl\"\n :aria-label=\"t.sidebarNav.palette\"\n class=\"tpl-sidebar-rail tpl:absolute tpl:top-14 tpl:bottom-0 tpl:left-0 tpl:z-40 tpl:box-border tpl:flex tpl:flex-col tpl:overflow-hidden\"\n :style=\"{\n width: isExpanded ? '200px' : '48px',\n backgroundColor: 'var(--tpl-bg-elevated)',\n borderRight: '1px solid var(--tpl-border)',\n boxShadow: isExpanded ? 'var(--tpl-shadow-lg)' : 'none',\n transition:\n 'width 200ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 200ms cubic-bezier(0.16, 1, 0.3, 1)',\n }\"\n @mouseenter=\"isExpanded = true\"\n @mouseleave=\"handleSidebarLeave\"\n @focusin=\"isExpanded = true\"\n @focusout=\"handleRailFocusOut\"\n >\n <!-- Saved blocks browser trigger. Needs the feature to be available (a\n provider configured, and in Cloud the plan to allow it). -->\n <div\n v-if=\"showSavedBlocksSection\"\n class=\"tpl:border-b tpl:px-1 tpl:pb-1 tpl:border-[var(--tpl-border)]\"\n >\n <button\n type=\"button\"\n :aria-label=\"t.sidebarNav.browseSavedBlocks\"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)]\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"caps.savedBlocks?.openBrowser()\"\n >\n <Package :size=\"20\" :stroke-width=\"1.5\" class=\"tpl:shrink-0\" />\n <!-- No `flex-1`: the rail inherits `text-align: center`, so a label\n stretched to fill the row centres its glyphs and sits visibly\n further right than the palette labels below it. Shrink-to-fit\n matches them exactly. -->\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ t.savedBlocks.title }}\n </span>\n </button>\n </div>\n <!-- The palette is the rail's scroll region: `flex-1` makes it fill the\n height left by the (optional) modules trigger, `min-h-0` lets it\n shrink below its content so `overflow-y-auto` engages. Without this\n the rail's `overflow-hidden` clips items below the fold on short\n viewports with no way to reach them (#231). -->\n <VueDraggable\n :model-value=\"blockTypes\"\n :group=\"{ name: 'blocks', pull: 'clone', put: false }\"\n :clone=\"createBlockFromItem\"\n :sort=\"false\"\n :animation=\"150\"\n :force-fallback=\"true\"\n :fallback-tolerance=\"PALETTE_DRAG_TOLERANCE_PX\"\n class=\"tpl:flex tpl:min-h-0 tpl:flex-1 tpl:flex-col tpl:gap-0.5 tpl:overflow-y-auto tpl:p-1\"\n @choose=\"handleDragChoose\"\n @start=\"handleDragStart\"\n @unchoose=\"handleDragUnchoose\"\n @end=\"handleDragEnd\"\n >\n <button\n v-for=\"blockType in blockTypes\"\n :key=\"blockType.type\"\n type=\"button\"\n :data-palette-type=\"blockType.type\"\n :aria-label=\"\n format(t.sidebarNav.insertBlock, { block: blockType.label })\n \"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:shrink-0 tpl:cursor-grab tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)] tpl:active:cursor-grabbing\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"handlePaletteClick(blockType)\"\n @keydown=\"handlePaletteKeydown($event, blockType)\"\n >\n <div\n class=\"tpl:flex tpl:shrink-0 tpl:items-center tpl:justify-center tpl:transition-transform tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:scale-105\"\n >\n <component\n :is=\"blockTypeIcons[blockType.type]\"\n v-if=\"blockTypeIcons[blockType.type]\"\n :size=\"20\"\n :stroke-width=\"1.5\"\n />\n <CustomBlockIcon\n v-else-if=\"blockType.isCustom\"\n :icon=\"blockType.icon\"\n :size=\"20\"\n />\n </div>\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ blockType.label }}\n </span>\n </button>\n </VueDraggable>\n </aside>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type { Block, BlockType } from \"@templatical/types\";\nimport { createBlock, createCustomBlock } from \"@templatical/types\";\nimport { Package } from \"@lucide/vue\";\nimport { computed, inject, onScopeDispose, ref, watch } from \"vue\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport CustomBlockIcon from \"./CustomBlockIcon.vue\";\nimport { blockTypeIcons } from \"../utils/blockTypeIcons\";\nimport { getBlockTypeLabel } from \"../utils/blockTypeLabels\";\nimport { createHeroSection, HERO_PALETTE_TYPE } from \"../utils/heroShortcut\";\nimport { resolvePaletteBlocks } from \"../utils/resolvePaletteBlocks\";\nimport { insertBlockAtSelection } from \"../utils/insertBlockAtSelection\";\nimport { useScrollToBlock } from \"../composables/useScrollToBlock\";\nimport { logger } from \"../utils/logger\";\nimport {\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n PALETTE_BLOCKS_KEY,\n BLOCK_DEFAULTS_KEY,\n CAPABILITIES_KEY,\n EDITOR_KEY,\n} from \"../keys\";\n\ninterface BlockTypeItem {\n type: BlockType | string;\n label: string;\n isCustom?: boolean;\n icon?: string;\n}\n\nconst { t, format } = useI18n();\nconst customBlockDefinitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst paletteBlocks = inject(PALETTE_BLOCKS_KEY, undefined);\nconst blockDefaults = inject(BLOCK_DEFAULTS_KEY, undefined);\nconst editor = inject(EDITOR_KEY, null);\nconst scrollToBlock = useScrollToBlock();\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n// Availability only — deliberately NOT `count > 0`. Gating on the loaded count\n// meant the entry appeared only once the consumer's `list()` resolved, so a slow\n// endpoint shifted the rail mid-session and an empty library hid the feature\n// entirely. The list is now fetched when the browser opens instead.\nconst showSavedBlocksSection = computed(\n () => caps.savedBlocks?.isAvailable.value === true,\n);\n\nconst isExpanded = ref(false);\nconst isDragging = ref(false);\nconst railEl = ref<HTMLElement | null>(null);\n\n// Sortable's default is 0, and the `fallbackTolerance &&` guard treats 0 as\n// \"no threshold\", so any pointer movement starts a force-fallback drag. The\n// palette button is also the click-to-insert control, and a drag that jitters\n// onto the canvas then clicks it inserts a second block (#817). 3–5px is\n// Sortable's own range for clickable items. 4 matches the e2e nudge in\n// `pointerDriveFromPalette` (`startX + 4`): Sortable starts the drag when\n// movement is not strictly below this value, so that nudge still counts.\nconst PALETTE_DRAG_TOLERANCE_PX = 4;\n\n// `start` means a drag actually began. A stationary click emits `choose` +\n// `unchoose` and never `start`, so this must not key off `isDragging` — that\n// flag flips at pointerdown. Cleared on a macrotask after `end`: `end` runs\n// inside mouseup, and the click is dispatched later in that same turn, after\n// microtasks. `nextTick` / `queueMicrotask` would drop the flag first and the\n// duplicate would land. `unchoose` fires before `end` on a completed drag, so\n// clearing there has the same hole.\nlet suppressPaletteClick = false;\nlet suppressPaletteClickTimer = 0;\n\nonScopeDispose(() => {\n window.clearTimeout(suppressPaletteClickTimer);\n});\n\n// `:focus-visible`, never `:focus`: a mouse click leaves the clicked palette\n// button focused, so a plain `:focus` test would pin the rail open from the\n// first click-to-insert onward — the very symptom this rail already had for\n// another reason (#568). Keyboard focus does keep it open, because collapsing\n// hides the label of the entry the user has focused.\nfunction hasKeyboardFocusInRail(): boolean {\n try {\n return railEl.value?.querySelector(\":focus-visible\") != null;\n } catch {\n // Firefox <85 / Safari <15.4 — reachable on the `shadowDom: false` tier,\n // whose browser floor predates the selector — throw on it. Reading that\n // as \"no keyboard focus\" keeps the collapse working there.\n return false;\n }\n}\n\nfunction handleSidebarLeave(): void {\n // Don't collapse while a Sortable drag is in progress. If the sidebar\n // shrinks (200px → 48px) DURING the drag's threshold-to-dragStarted\n // window, `dragEl.getBoundingClientRect()` returns a mid-transition\n // rect when Sortable's `_appendGhost` runs — the fallback ghost gets\n // stamped with that wrong rect and ends up visibly offset from the\n // cursor for the rest of the drag. Cleared on drag-end.\n if (isDragging.value) return;\n if (hasKeyboardFocusInRail()) return;\n isExpanded.value = false;\n}\n\nfunction handleDragChoose(): void {\n // `choose` fires synchronously inside Sortable's `_onTapStart` at\n // pointerdown, BEFORE any pointermove or mouseleave. `start` would be\n // too late — it fires only after the threshold-move dispatches\n // `_dragStarted`, by which time mouseleave may already have flipped\n // `isExpanded` and the sidebar may be mid-collapse.\n isDragging.value = true;\n}\n\nfunction handleDragUnchoose(): void {\n // `end` is not the counterpart of `choose` — Sortable gates it on\n // `Sortable.active`, which only `_dragStarted` sets, so a click on a palette\n // entry emits `choose` + `unchoose` and no `end` at all. Clearing the guard\n // only in `handleDragEnd` therefore latches it true on the first click and\n // `handleSidebarLeave` bails forever after: the rail stays expanded until\n // some later drag happens to complete (#568). `unchoose` fires on every\n // release, at drop time — long after `_appendGhost` captured its rect — so\n // it cannot re-open the race `handleDragChoose` guards.\n isDragging.value = false;\n}\n\nfunction handleDragStart(): void {\n // Click suppression only. The rail-width guard stays on `choose`: `start`\n // is after `_dragStarted`, which is too late to stop the collapse race.\n suppressPaletteClick = true;\n window.clearTimeout(suppressPaletteClickTimer);\n}\n\nfunction handleRailFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget;\n if (next instanceof Node && railEl.value?.contains(next)) return;\n // Inserting selects the new block and moves focus off the palette button.\n // The pointer is often still on the rail. Collapsing here shrinks the\n // label strip out from under it, and the next press opens the rail\n // instead of inserting (#818).\n if (railEl.value?.matches(\":hover\")) return;\n isExpanded.value = false;\n}\n\nfunction clearFallbackClickSwallow(): void {\n // A fallback drag sets Sortable's ignoreNextClick. Sortable clears it by\n // swallowing the next click. A slip that stays on the palette cancels\n // mouseup, so that click is never dispatched and the author's next press\n // is the one swallowed. This click is aimed at the document, not a palette\n // button, so it spends the swallow without inserting. The button's own\n // click stays suppressed until the macrotask in handleDragEnd.\n railEl.value?.ownerDocument.dispatchEvent(\n new MouseEvent(\"click\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n }),\n );\n}\n\nfunction handleDragEnd(): void {\n isDragging.value = false;\n // A canvas drop ends outside the rail, and `mouseleave` never fires for\n // that path: `handleSidebarLeave` bailed while `isDragging` was true.\n // Collapse only then. A press that slipped into a fallback drag and\n // released still on the palette must leave the rail open (#818), including\n // when focusout already collapsed it earlier in this same pointerup.\n // `:hover` matches the rail while the pointer is over a button inside it.\n // The fallback ghost has `pointer-events: none`, so it does not take the hit.\n if (railEl.value?.matches(\":hover\")) {\n isExpanded.value = true;\n clearFallbackClickSwallow();\n } else {\n isExpanded.value = false;\n }\n window.clearTimeout(suppressPaletteClickTimer);\n suppressPaletteClickTimer = window.setTimeout(() => {\n suppressPaletteClick = false;\n }, 0);\n}\n\nconst builtInBlockTypeOrder: string[] = [\n \"section\",\n HERO_PALETTE_TYPE,\n \"image\",\n \"title\",\n \"paragraph\",\n \"button\",\n \"divider\",\n \"video\",\n \"social\",\n \"menu\",\n \"table\",\n \"spacer\",\n \"html\",\n];\n\nconst builtInBlockTypes = computed<BlockTypeItem[]>(() => {\n const types: BlockTypeItem[] = builtInBlockTypeOrder.map((type) => ({\n type,\n label: getBlockTypeLabel(type, t),\n }));\n\n // Countdown requires Templatical Cloud for server-side GIF rendering\n if (caps.plan) {\n types.splice(-1, 0, {\n type: \"countdown\",\n label: getBlockTypeLabel(\"countdown\", t),\n });\n }\n\n return types;\n});\n\nconst customBlockItems = computed<BlockTypeItem[]>(() => {\n return customBlockDefinitions.map((def) => ({\n type: `custom:${def.type}`,\n label: def.name,\n isCustom: true,\n icon: def.icon,\n }));\n});\n\nconst candidateBlockTypes = computed<BlockTypeItem[]>(() => [\n ...builtInBlockTypes.value,\n ...customBlockItems.value,\n]);\n\n// Apply the consumer's `paletteBlocks` allowlist + order when provided; otherwise show\n// the full default palette. Filtering only affects the palette — the block\n// registry stays complete, so existing content using a hidden type still renders.\nconst resolvedPalette = computed(() =>\n resolvePaletteBlocks(candidateBlockTypes.value, paletteBlocks),\n);\n\nconst blockTypes = computed<BlockTypeItem[]>(() => resolvedPalette.value.items);\n\n// Warn once per unknown `paletteBlocks` entry (a typo, an unregistered custom block, or\n// `countdown` outside a Cloud plan). Done in a watcher rather than inside the\n// computed so recomputes don't repeat the warning.\nconst warnedPaletteEntries = new Set<string>();\nwatch(\n () => resolvedPalette.value.unknown,\n (unknown) => {\n for (const entry of unknown) {\n if (warnedPaletteEntries.has(entry)) continue;\n warnedPaletteEntries.add(entry);\n logger.warn(\n `config.paletteBlocks: \"${entry}\" is not a built-in or registered custom block ` +\n `(use the \"custom:\" prefix for custom blocks) — skipping it in the palette.`,\n );\n }\n },\n { immediate: true },\n);\n\nfunction createBlockFromItem(item: BlockTypeItem): Block {\n if (item.isCustom) {\n const customType = item.type.replace(\"custom:\", \"\");\n const definition = customBlockDefinitions.find(\n (d) => d.type === customType,\n );\n if (definition) {\n return createCustomBlock(definition);\n }\n }\n\n // A shortcut, not a block type: a hero-mode section with starter content.\n if (item.type === HERO_PALETTE_TYPE) {\n return createHeroSection(blockDefaults?.value, t.blockDefaults.paragraph);\n }\n\n // `.value` at insert time, never destructured at setup: the recipient-facing\n // half of these defaults tracks the template's own content language, which\n // the author can change while the palette is mounted.\n return createBlock(item.type as BlockType, blockDefaults?.value);\n}\n\nfunction insertBlockFromItem(item: BlockTypeItem): void {\n if (!editor) return;\n const block = createBlockFromItem(item);\n // Land below the selection, not at the end: on a template taller than the\n // viewport an appended block is below the fold, and the canvas does not\n // follow on its own, so the click reads as a no-op (issue #568).\n // Selecting is not visible by itself, and the append fallback still lands\n // off-screen — the canvas has to follow either way.\n if (insertBlockAtSelection(editor, block)) scrollToBlock(block.id);\n}\n\nfunction handlePaletteClick(item: BlockTypeItem): void {\n // The drag element is this button. Sortable moves it into the canvas drop\n // slot and clears `ignoreNextClick` inside `_onDragOver` once the pointer\n // enters that list, so the click after mouseup still reaches this handler\n // and inserts a second block (#817).\n if (suppressPaletteClick) return;\n insertBlockFromItem(item);\n}\n\nfunction handlePaletteKeydown(event: KeyboardEvent, item: BlockTypeItem): void {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n insertBlockFromItem(item);\n }\n}\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 48px the canvas body leaves\n for the collapsed rail (`left-12`). -->\n <aside\n ref=\"railEl\"\n :aria-label=\"t.sidebarNav.palette\"\n class=\"tpl-sidebar-rail tpl:absolute tpl:top-14 tpl:bottom-0 tpl:left-0 tpl:z-40 tpl:box-border tpl:flex tpl:flex-col tpl:overflow-hidden\"\n :style=\"{\n width: isExpanded ? '200px' : '48px',\n backgroundColor: 'var(--tpl-bg-elevated)',\n borderRight: '1px solid var(--tpl-border)',\n boxShadow: isExpanded ? 'var(--tpl-shadow-lg)' : 'none',\n transition:\n 'width 200ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 200ms cubic-bezier(0.16, 1, 0.3, 1)',\n }\"\n @mouseenter=\"isExpanded = true\"\n @mouseleave=\"handleSidebarLeave\"\n @focusin=\"isExpanded = true\"\n @focusout=\"handleRailFocusOut\"\n >\n <!-- Saved blocks browser trigger. Needs the feature to be available (a\n provider configured, and in Cloud the plan to allow it). -->\n <div\n v-if=\"showSavedBlocksSection\"\n class=\"tpl:border-b tpl:px-1 tpl:pb-1 tpl:border-[var(--tpl-border)]\"\n >\n <button\n type=\"button\"\n :aria-label=\"t.sidebarNav.browseSavedBlocks\"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)]\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"caps.savedBlocks?.openBrowser()\"\n >\n <Package :size=\"20\" :stroke-width=\"1.5\" class=\"tpl:shrink-0\" />\n <!-- No `flex-1`: the rail inherits `text-align: center`, so a label\n stretched to fill the row centres its glyphs and sits visibly\n further right than the palette labels below it. Shrink-to-fit\n matches them exactly. -->\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ t.savedBlocks.title }}\n </span>\n </button>\n </div>\n <!-- The palette is the rail's scroll region: `flex-1` makes it fill the\n height left by the (optional) modules trigger, `min-h-0` lets it\n shrink below its content so `overflow-y-auto` engages. Without this\n the rail's `overflow-hidden` clips items below the fold on short\n viewports with no way to reach them (#231). -->\n <VueDraggable\n :model-value=\"blockTypes\"\n :group=\"{ name: 'blocks', pull: 'clone', put: false }\"\n :clone=\"createBlockFromItem\"\n :sort=\"false\"\n :animation=\"150\"\n :force-fallback=\"true\"\n :fallback-tolerance=\"PALETTE_DRAG_TOLERANCE_PX\"\n class=\"tpl:flex tpl:min-h-0 tpl:flex-1 tpl:flex-col tpl:gap-0.5 tpl:overflow-y-auto tpl:p-1\"\n @choose=\"handleDragChoose\"\n @start=\"handleDragStart\"\n @unchoose=\"handleDragUnchoose\"\n @end=\"handleDragEnd\"\n >\n <button\n v-for=\"blockType in blockTypes\"\n :key=\"blockType.type\"\n type=\"button\"\n :data-palette-type=\"blockType.type\"\n :aria-label=\"\n format(t.sidebarNav.insertBlock, { block: blockType.label })\n \"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:shrink-0 tpl:cursor-grab tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)] tpl:active:cursor-grabbing\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"handlePaletteClick(blockType)\"\n @keydown=\"handlePaletteKeydown($event, blockType)\"\n >\n <div\n class=\"tpl:flex tpl:shrink-0 tpl:items-center tpl:justify-center tpl:transition-transform tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:scale-105\"\n >\n <component\n :is=\"blockTypeIcons[blockType.type]\"\n v-if=\"blockTypeIcons[blockType.type]\"\n :size=\"20\"\n :stroke-width=\"1.5\"\n />\n <CustomBlockIcon\n v-else-if=\"blockType.isCustom\"\n :icon=\"blockType.icon\"\n :size=\"20\"\n />\n </div>\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ blockType.label }}\n </span>\n </button>\n </VueDraggable>\n </aside>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Toolbar and Template Settings are `defineAsyncComponent` behind the\n * `v-if`s that already gate them (a selected block, the Settings tab).\n * `defineAsyncComponent` fetches on first render, so a static import here\n * would pull ColorPicker, MergeTagInput, and every per-type toolbar into\n * the eager graph for every session. IssuesPanel in this file is the same\n * contract. Guarded by `tests/rightSidebarLazy.test.ts` and the\n * properties-panel cases in `cdn-chunk-granularity.test.ts` /\n * `bundle-topology.test.ts`.\n */\nimport { useI18n } from \"../composables/useI18n\";\nimport { TEMPLATE_LINT_KEY, TEMPLATE_SETTINGS_FIELDS_KEY } from \"../keys\";\nimport { ALL_TEMPLATE_SETTINGS_FIELDS } from \"../utils/templateSettingsFields\";\nimport type { Block, TemplateSettings } from \"@templatical/types\";\nimport { ListChecks, LayoutTemplate, PanelTop, Settings } from \"@lucide/vue\";\nimport { computed, defineAsyncComponent, inject, watch } from \"vue\";\n\nconst Toolbar = defineAsyncComponent(() => import(\"./Toolbar.vue\"));\nconst TemplateSettingsPanel = defineAsyncComponent(\n () => import(\"./TemplateSettings.vue\"),\n);\nconst IssuesPanel = defineAsyncComponent(\n () => import(\"./sidebar/IssuesPanel.vue\"),\n);\n\nconst props = defineProps<{\n selectedBlock: Block | null;\n settings: TemplateSettings;\n shiftedLeft?: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"update-block\", updates: Partial<Block>): void;\n (e: \"delete-block\"): void;\n (e: \"duplicate-block\"): void;\n (e: \"update-settings\", settings: Partial<TemplateSettings>): void;\n}>();\n\nconst { t } = useI18n();\n\nexport type RightSidebarTab = \"content\" | \"settings\" | \"issues\";\ntype Tab = RightSidebarTab;\n\n// `v-model:tab`: `Editor.vue` owns the tab. Without a parent binding it is local state.\nconst activeTab = defineModel<Tab>(\"tab\", { default: \"content\" });\n\nconst lint = inject(TEMPLATE_LINT_KEY, null);\n// `@templatical/quality` is an optional peer imported at mount. The tab renders\n// from the start, so apps that install it never see the tab pop in, and goes\n// once the import fails: without the package the panel has nothing to show.\nconst lintAvailable = computed(() => lint !== null && !lint.unavailable.value);\nconst issueCount = computed(() => lint?.issues.value.length ?? 0);\n\n// The tab follows the panel: with every setting excluded there is nothing for\n// it to open, and a tab onto an empty panel reads as a bug. Defaults to every\n// field, since the key is absent for a consumer who configured nothing.\nconst allowedSettingsFields = inject(\n TEMPLATE_SETTINGS_FIELDS_KEY,\n new Set(ALL_TEMPLATE_SETTINGS_FIELDS),\n);\nconst settingsEnabled = computed(() => allowedSettingsFields.size > 0);\n\nfunction tabClass(tab: Tab): string {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return \"tpl:flex-1 tpl:text-[var(--tpl-primary)]\";\n }\n return \"tpl:shrink-0 tpl:text-[var(--tpl-text-muted)] tpl:hover:text-[var(--tpl-text)]\";\n}\n\nfunction tabStyle(tab: Tab): Record<string, string> {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return {\n backgroundColor: \"var(--tpl-bg)\",\n // `-sm` is the step the shadow vocabulary assigns to a lifted control;\n // `-md` is dialog and side-panel depth, which overstates a 32px tab.\n boxShadow: \"var(--tpl-shadow-sm)\",\n };\n }\n return { backgroundColor: \"transparent\" };\n}\n\nwatch(\n () => props.selectedBlock,\n (newBlock) => {\n if (newBlock) {\n activeTab.value = \"content\";\n }\n },\n);\n\n// The Issues tab can be picked while the quality import is in flight; when\n// that import then fails, the sidebar would otherwise show no panel at all.\nwatch(lintAvailable, (available) => {\n if (!available && activeTab.value === \"issues\") {\n activeTab.value = \"content\";\n }\n});\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 320px the canvas body leaves\n for this rail (`right-[320px]`); outside it, the rail covers the body's\n last pixel column, where the block toolbar's drag grip sits. -->\n <aside\n :aria-label=\"t.landmarks.rightSidebar\"\n class=\"tpl-right-sidebar tpl:absolute tpl:top-14 tpl:bottom-0 tpl:z-40 tpl:flex tpl:box-border tpl:w-[320px] tpl:flex-col tpl:bg-[var(--tpl-bg-elevated)] tpl:transition-all tpl:duration-200 tpl:border-l tpl:border-[var(--tpl-border)]\"\n :class=\"shiftedLeft ? 'tpl:right-[360px]' : 'tpl:right-0'\"\n >\n <div\n role=\"tablist\"\n class=\"tpl:relative tpl:flex tpl:gap-1 tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-active)] tpl:p-1.5\"\n >\n <button\n id=\"tpl-tab-content\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'content'\"\n aria-controls=\"tpl-tabpanel-content\"\n :aria-label=\"t.sidebar.content\"\n :title=\"t.sidebar.content\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('content')\"\n :style=\"tabStyle('content')\"\n @click=\"activeTab = 'content'\"\n >\n <PanelTop :size=\"14\" :stroke-width=\"2\" />\n <span v-if=\"activeTab === 'content'\">{{ t.sidebar.content }}</span>\n </button>\n <button\n v-if=\"settingsEnabled\"\n id=\"tpl-tab-settings\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'settings'\"\n aria-controls=\"tpl-tabpanel-settings\"\n :aria-label=\"t.sidebar.settings\"\n :title=\"t.sidebar.settings\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('settings')\"\n :style=\"tabStyle('settings')\"\n @click=\"activeTab = 'settings'\"\n >\n <Settings :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'settings'\">{{ t.sidebar.settings }}</span>\n </button>\n <button\n v-if=\"lintAvailable\"\n id=\"tpl-tab-issues\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'issues'\"\n aria-controls=\"tpl-tabpanel-issues\"\n :aria-label=\"t.issues.panelTabLabel\"\n :title=\"t.issues.panelTabLabel\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('issues')\"\n :style=\"tabStyle('issues')\"\n @click=\"activeTab = 'issues'\"\n >\n <ListChecks :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'issues'\">\n {{ t.issues.panelTabLabel }}\n </span>\n <span\n v-if=\"issueCount > 0\"\n class=\"tpl:ml-1 tpl:rounded-full tpl:bg-[var(--tpl-bg-hover)] tpl:px-1.5 tpl:text-[10px]\"\n >\n {{ issueCount }}\n </span>\n </button>\n </div>\n\n <div\n v-if=\"activeTab === 'content'\"\n id=\"tpl-tabpanel-content\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-content\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <Toolbar\n v-if=\"selectedBlock\"\n :block=\"selectedBlock\"\n @update=\"emit('update-block', $event)\"\n @delete=\"emit('delete-block')\"\n @duplicate=\"emit('duplicate-block')\"\n />\n <div\n v-else\n class=\"tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:px-6 tpl:py-10 tpl:text-center tpl:text-[var(--tpl-text-muted)]\"\n >\n <div class=\"tpl:mb-4 tpl:text-[var(--tpl-text-dim)]\">\n <LayoutTemplate :size=\"40\" :stroke-width=\"1.5\" />\n </div>\n <h3\n class=\"tpl:m-0 tpl:mb-2 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.sidebar.noSelection }}\n </h3>\n <p class=\"tpl:m-0 tpl:text-sm tpl:leading-normal\">\n {{ t.sidebar.noSelectionHint }}\n </p>\n </div>\n </div>\n\n <div\n v-if=\"activeTab === 'settings' && settingsEnabled\"\n id=\"tpl-tabpanel-settings\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-settings\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <TemplateSettingsPanel\n :settings=\"settings\"\n @update=\"emit('update-settings', $event)\"\n />\n </div>\n\n <div\n v-if=\"activeTab === 'issues' && lintAvailable\"\n id=\"tpl-tabpanel-issues\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-issues\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <IssuesPanel />\n </div>\n </aside>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Toolbar and Template Settings are `defineAsyncComponent` behind the\n * `v-if`s that already gate them (a selected block, the Settings tab).\n * `defineAsyncComponent` fetches on first render, so a static import here\n * would pull ColorPicker, MergeTagInput, and every per-type toolbar into\n * the eager graph for every session. IssuesPanel in this file is the same\n * contract. Guarded by `tests/rightSidebarLazy.test.ts` and the\n * properties-panel cases in `cdn-chunk-granularity.test.ts` /\n * `bundle-topology.test.ts`.\n */\nimport { useI18n } from \"../composables/useI18n\";\nimport { TEMPLATE_LINT_KEY, TEMPLATE_SETTINGS_FIELDS_KEY } from \"../keys\";\nimport { ALL_TEMPLATE_SETTINGS_FIELDS } from \"../utils/templateSettingsFields\";\nimport type { Block, TemplateSettings } from \"@templatical/types\";\nimport { ListChecks, LayoutTemplate, PanelTop, Settings } from \"@lucide/vue\";\nimport { computed, defineAsyncComponent, inject, watch } from \"vue\";\n\nconst Toolbar = defineAsyncComponent(() => import(\"./Toolbar.vue\"));\nconst TemplateSettingsPanel = defineAsyncComponent(\n () => import(\"./TemplateSettings.vue\"),\n);\nconst IssuesPanel = defineAsyncComponent(\n () => import(\"./sidebar/IssuesPanel.vue\"),\n);\n\nconst props = defineProps<{\n selectedBlock: Block | null;\n settings: TemplateSettings;\n shiftedLeft?: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"update-block\", updates: Partial<Block>): void;\n (e: \"delete-block\"): void;\n (e: \"duplicate-block\"): void;\n (e: \"update-settings\", settings: Partial<TemplateSettings>): void;\n}>();\n\nconst { t } = useI18n();\n\nexport type RightSidebarTab = \"content\" | \"settings\" | \"issues\";\ntype Tab = RightSidebarTab;\n\n// `v-model:tab`: `Editor.vue` owns the tab. Without a parent binding it is local state.\nconst activeTab = defineModel<Tab>(\"tab\", { default: \"content\" });\n\nconst lint = inject(TEMPLATE_LINT_KEY, null);\n// `@templatical/quality` is an optional peer imported at mount. The tab renders\n// from the start, so apps that install it never see the tab pop in, and goes\n// once the import fails: without the package the panel has nothing to show.\nconst lintAvailable = computed(() => lint !== null && !lint.unavailable.value);\nconst issueCount = computed(() => lint?.issues.value.length ?? 0);\n\n// The tab follows the panel: with every setting excluded there is nothing for\n// it to open, and a tab onto an empty panel reads as a bug. Defaults to every\n// field, since the key is absent for a consumer who configured nothing.\nconst allowedSettingsFields = inject(\n TEMPLATE_SETTINGS_FIELDS_KEY,\n new Set(ALL_TEMPLATE_SETTINGS_FIELDS),\n);\nconst settingsEnabled = computed(() => allowedSettingsFields.size > 0);\n\nfunction tabClass(tab: Tab): string {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return \"tpl:flex-1 tpl:text-[var(--tpl-primary)]\";\n }\n return \"tpl:shrink-0 tpl:text-[var(--tpl-text-muted)] tpl:hover:text-[var(--tpl-text)]\";\n}\n\nfunction tabStyle(tab: Tab): Record<string, string> {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return {\n backgroundColor: \"var(--tpl-bg)\",\n // `-sm` is the step the shadow vocabulary assigns to a lifted control;\n // `-md` is dialog and side-panel depth, which overstates a 32px tab.\n boxShadow: \"var(--tpl-shadow-sm)\",\n };\n }\n return { backgroundColor: \"transparent\" };\n}\n\nwatch(\n () => props.selectedBlock,\n (newBlock) => {\n if (newBlock) {\n activeTab.value = \"content\";\n }\n },\n);\n\n// The Issues tab can be picked while the quality import is in flight; when\n// that import then fails, the sidebar would otherwise show no panel at all.\nwatch(lintAvailable, (available) => {\n if (!available && activeTab.value === \"issues\") {\n activeTab.value = \"content\";\n }\n});\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 320px the canvas body leaves\n for this rail (`right-[320px]`); outside it, the rail covers the body's\n last pixel column, where the block toolbar's drag grip sits. -->\n <aside\n :aria-label=\"t.landmarks.rightSidebar\"\n class=\"tpl-right-sidebar tpl:absolute tpl:top-14 tpl:bottom-0 tpl:z-40 tpl:flex tpl:box-border tpl:w-[320px] tpl:flex-col tpl:bg-[var(--tpl-bg-elevated)] tpl:transition-all tpl:duration-200 tpl:border-l tpl:border-[var(--tpl-border)]\"\n :class=\"shiftedLeft ? 'tpl:right-[360px]' : 'tpl:right-0'\"\n >\n <div\n role=\"tablist\"\n class=\"tpl:relative tpl:flex tpl:gap-1 tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-active)] tpl:p-1.5\"\n >\n <button\n id=\"tpl-tab-content\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'content'\"\n aria-controls=\"tpl-tabpanel-content\"\n :aria-label=\"t.sidebar.content\"\n :title=\"t.sidebar.content\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('content')\"\n :style=\"tabStyle('content')\"\n @click=\"activeTab = 'content'\"\n >\n <PanelTop :size=\"14\" :stroke-width=\"2\" />\n <span v-if=\"activeTab === 'content'\">{{ t.sidebar.content }}</span>\n </button>\n <button\n v-if=\"settingsEnabled\"\n id=\"tpl-tab-settings\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'settings'\"\n aria-controls=\"tpl-tabpanel-settings\"\n :aria-label=\"t.sidebar.settings\"\n :title=\"t.sidebar.settings\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('settings')\"\n :style=\"tabStyle('settings')\"\n @click=\"activeTab = 'settings'\"\n >\n <Settings :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'settings'\">{{ t.sidebar.settings }}</span>\n </button>\n <button\n v-if=\"lintAvailable\"\n id=\"tpl-tab-issues\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'issues'\"\n aria-controls=\"tpl-tabpanel-issues\"\n :aria-label=\"t.issues.panelTabLabel\"\n :title=\"t.issues.panelTabLabel\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('issues')\"\n :style=\"tabStyle('issues')\"\n @click=\"activeTab = 'issues'\"\n >\n <ListChecks :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'issues'\">\n {{ t.issues.panelTabLabel }}\n </span>\n <span\n v-if=\"issueCount > 0\"\n class=\"tpl:ml-1 tpl:rounded-full tpl:bg-[var(--tpl-bg-hover)] tpl:px-1.5 tpl:text-[10px]\"\n >\n {{ issueCount }}\n </span>\n </button>\n </div>\n\n <div\n v-if=\"activeTab === 'content'\"\n id=\"tpl-tabpanel-content\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-content\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <Toolbar\n v-if=\"selectedBlock\"\n :block=\"selectedBlock\"\n @update=\"emit('update-block', $event)\"\n @delete=\"emit('delete-block')\"\n @duplicate=\"emit('duplicate-block')\"\n />\n <div\n v-else\n class=\"tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:px-6 tpl:py-10 tpl:text-center tpl:text-[var(--tpl-text-muted)]\"\n >\n <div class=\"tpl:mb-4 tpl:text-[var(--tpl-text-dim)]\">\n <LayoutTemplate :size=\"40\" :stroke-width=\"1.5\" />\n </div>\n <h3\n class=\"tpl:m-0 tpl:mb-2 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.sidebar.noSelection }}\n </h3>\n <p class=\"tpl:m-0 tpl:text-sm tpl:leading-normal\">\n {{ t.sidebar.noSelectionHint }}\n </p>\n </div>\n </div>\n\n <div\n v-if=\"activeTab === 'settings' && settingsEnabled\"\n id=\"tpl-tabpanel-settings\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-settings\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <TemplateSettingsPanel\n :settings=\"settings\"\n @update=\"emit('update-settings', $event)\"\n />\n </div>\n\n <div\n v-if=\"activeTab === 'issues' && lintAvailable\"\n id=\"tpl-tabpanel-issues\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-issues\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <IssuesPanel />\n </div>\n </aside>\n</template>\n","<script setup lang=\"ts\">\nimport { Monitor } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\n// Full-cover gate shown below the usable-width breakpoint (issue #235).\n// Rendered as the last child of `.tpl` and given a literal z-index above all\n// chrome (header z-50, sidebars z-40) AND `.tpl-popover-root` (z 10000), so the\n// opaque overlay covers everything including any open popover/modal.\n//\n// The z-index is a LITERAL rather than a token or a Tailwind utility, for two\n// separate reasons: a `var()` token would live on `:root`, unreachable from\n// inside the shadow root; and this notice must outrank `.tpl-popover-root`\n// (10000), which is itself a literal. Named z layers no longer exist — Tailwind\n// derives z utilities from `--z-index-*`, so a named one emits nothing (guarded\n// in `tests/design-system-conformance.test.ts`). Deliberately NOT written as a\n// class-like name in prose: that guard scans source text and cannot tell a\n// comment from a class attribute.\nconst { t } = useI18n();\n</script>\n\n<template>\n <div\n class=\"tpl-small-screen-notice tpl:absolute tpl:inset-0 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:gap-4 tpl:px-6 tpl:py-10 tpl:text-center tpl:bg-[var(--tpl-bg)] tpl:text-[var(--tpl-text-muted)]\"\n style=\"z-index: 10001\"\n role=\"status\"\n data-testid=\"small-screen-notice\"\n >\n <div class=\"tpl:text-[var(--tpl-text-dim)]\">\n <Monitor :size=\"48\" :stroke-width=\"1.5\" />\n </div>\n <h2\n class=\"tpl:m-0 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.smallScreen.title }}\n </h2>\n <p class=\"tpl:m-0 tpl:max-w-sm tpl:text-sm tpl:leading-normal\">\n {{ t.smallScreen.message }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Monitor } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\n// Full-cover gate shown below the usable-width breakpoint (issue #235).\n// Rendered as the last child of `.tpl` and given a literal z-index above all\n// chrome (header z-50, sidebars z-40) AND `.tpl-popover-root` (z 10000), so the\n// opaque overlay covers everything including any open popover/modal.\n//\n// The z-index is a LITERAL rather than a token or a Tailwind utility, for two\n// separate reasons: a `var()` token would live on `:root`, unreachable from\n// inside the shadow root; and this notice must outrank `.tpl-popover-root`\n// (10000), which is itself a literal. Named z layers no longer exist — Tailwind\n// derives z utilities from `--z-index-*`, so a named one emits nothing (guarded\n// in `tests/design-system-conformance.test.ts`). Deliberately NOT written as a\n// class-like name in prose: that guard scans source text and cannot tell a\n// comment from a class attribute.\nconst { t } = useI18n();\n</script>\n\n<template>\n <div\n class=\"tpl-small-screen-notice tpl:absolute tpl:inset-0 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:gap-4 tpl:px-6 tpl:py-10 tpl:text-center tpl:bg-[var(--tpl-bg)] tpl:text-[var(--tpl-text-muted)]\"\n style=\"z-index: 10001\"\n role=\"status\"\n data-testid=\"small-screen-notice\"\n >\n <div class=\"tpl:text-[var(--tpl-text-dim)]\">\n <Monitor :size=\"48\" :stroke-width=\"1.5\" />\n </div>\n <h2\n class=\"tpl:m-0 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.smallScreen.title }}\n </h2>\n <p class=\"tpl:m-0 tpl:max-w-sm tpl:text-sm tpl:leading-normal\">\n {{ t.smallScreen.message }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n /** Positioning classes for the footer (left/right offsets). */\n positionClass?: string | string[];\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <footer\n class=\"tpl:pointer-events-none tpl:absolute tpl:bottom-0 tpl:z-50 tpl:flex tpl:h-8 tpl:items-center tpl:justify-end tpl:pr-4 tpl:text-[10px] tpl:opacity-90 tpl:transition-all tpl:duration-300 tpl:text-[var(--tpl-text-dim)]\"\n :class=\"positionClass\"\n >\n <div\n class=\"tpl:pointer-events-auto tpl:flex tpl:items-center tpl:gap-1.5 tpl:rounded-tl-lg tpl:p-1\"\n style=\"\n background-color: color-mix(\n in srgb,\n var(--tpl-canvas-bg) 85%,\n transparent\n );\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n \"\n >\n <span>{{ t.footer.poweredBy }}</span>\n <a\n href=\"https://templatical.com\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-1 tpl:font-medium tpl:transition-colors tpl:hover:opacity-80 tpl:text-[var(--tpl-text-muted)]\"\n style=\"text-decoration: none\"\n >\n <!-- An inline mark, not an image loaded from templatical.com: the docs promise init() makes no requests to Templatical, and editorFooter.test.ts holds that. -->\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">\n <rect\n x=\"10\"\n y=\"1\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(85% 0.08 55)\"\n transform=\"rotate(8 19 12)\"\n />\n <rect\n x=\"6\"\n y=\"2\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(77% 0.12 55)\"\n transform=\"rotate(-4 15 13)\"\n />\n <rect\n x=\"2\"\n y=\"4\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(70% 0.16 55)\"\n />\n <rect\n x=\"6\"\n y=\"9\"\n width=\"10\"\n height=\"1.8\"\n rx=\"0.9\"\n fill=\"white\"\n opacity=\"0.9\"\n />\n <rect\n x=\"6\"\n y=\"13.5\"\n width=\"7\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"17\"\n width=\"9\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"20.5\"\n width=\"5\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.4\"\n />\n </svg>\n Templatical\n </a>\n </div>\n </footer>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n /** Positioning classes for the footer (left/right offsets). */\n positionClass?: string | string[];\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <footer\n class=\"tpl:pointer-events-none tpl:absolute tpl:bottom-0 tpl:z-50 tpl:flex tpl:h-8 tpl:items-center tpl:justify-end tpl:pr-4 tpl:text-[10px] tpl:opacity-90 tpl:transition-all tpl:duration-300 tpl:text-[var(--tpl-text-dim)]\"\n :class=\"positionClass\"\n >\n <div\n class=\"tpl:pointer-events-auto tpl:flex tpl:items-center tpl:gap-1.5 tpl:rounded-tl-lg tpl:p-1\"\n style=\"\n background-color: color-mix(\n in srgb,\n var(--tpl-canvas-bg) 85%,\n transparent\n );\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n \"\n >\n <span>{{ t.footer.poweredBy }}</span>\n <a\n href=\"https://templatical.com\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-1 tpl:font-medium tpl:transition-colors tpl:hover:opacity-80 tpl:text-[var(--tpl-text-muted)]\"\n style=\"text-decoration: none\"\n >\n <!-- An inline mark, not an image loaded from templatical.com: the docs promise init() makes no requests to Templatical, and editorFooter.test.ts holds that. -->\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">\n <rect\n x=\"10\"\n y=\"1\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(85% 0.08 55)\"\n transform=\"rotate(8 19 12)\"\n />\n <rect\n x=\"6\"\n y=\"2\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(77% 0.12 55)\"\n transform=\"rotate(-4 15 13)\"\n />\n <rect\n x=\"2\"\n y=\"4\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(70% 0.16 55)\"\n />\n <rect\n x=\"6\"\n y=\"9\"\n width=\"10\"\n height=\"1.8\"\n rx=\"0.9\"\n fill=\"white\"\n opacity=\"0.9\"\n />\n <rect\n x=\"6\"\n y=\"13.5\"\n width=\"7\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"17\"\n width=\"9\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"20.5\"\n width=\"5\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.4\"\n />\n </svg>\n Templatical\n </a>\n </div>\n </footer>\n</template>\n","<!--\n Canvas Dark Mode Preview Toggle\n\n This toggle simulates how the email template will look when the recipient's\n email client uses dark mode (e.g. Gmail, Outlook, Apple Mail in dark theme).\n It applies a CSS filter (invert + hue-rotate) to the canvas area only.\n\n This is NOT the editor UI theme toggle. The editor UI theme (light/dark/auto)\n is controlled externally via the `uiTheme` config option or `editor.setTheme()`.\n-->\n<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Moon, Sun } from \"@lucide/vue\";\n\ndefineProps<{\n darkMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", darkMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-dark-mode-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: darkMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: darkMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :title=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :aria-pressed=\"darkMode\"\n @click=\"emit('change', !darkMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Moon v-if=\"darkMode\" key=\"moon\" :size=\"18\" :stroke-width=\"1.5\" />\n <Sun v-else key=\"sun\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-dark-mode-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-dark-mode-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<!--\n Canvas Dark Mode Preview Toggle\n\n This toggle simulates how the email template will look when the recipient's\n email client uses dark mode (e.g. Gmail, Outlook, Apple Mail in dark theme).\n It applies a CSS filter (invert + hue-rotate) to the canvas area only.\n\n This is NOT the editor UI theme toggle. The editor UI theme (light/dark/auto)\n is controlled externally via the `uiTheme` config option or `editor.setTheme()`.\n-->\n<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Moon, Sun } from \"@lucide/vue\";\n\ndefineProps<{\n darkMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", darkMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-dark-mode-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: darkMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: darkMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :title=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :aria-pressed=\"darkMode\"\n @click=\"emit('change', !darkMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Moon v-if=\"darkMode\" key=\"moon\" :size=\"18\" :stroke-width=\"1.5\" />\n <Sun v-else key=\"sun\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-dark-mode-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-dark-mode-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Eye, EyeOff } from \"@lucide/vue\";\n\ndefineProps<{\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", previewMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-preview-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: previewMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: previewMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :title=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :aria-pressed=\"previewMode\"\n @click=\"emit('change', !previewMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Eye v-if=\"previewMode\" key=\"eye\" :size=\"18\" :stroke-width=\"1.5\" />\n <EyeOff v-else key=\"eye-off\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-preview-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-preview-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Eye, EyeOff } from \"@lucide/vue\";\n\ndefineProps<{\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", previewMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-preview-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: previewMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: previewMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :title=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :aria-pressed=\"previewMode\"\n @click=\"emit('change', !previewMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Eye v-if=\"previewMode\" key=\"eye\" :size=\"18\" :stroke-width=\"1.5\" />\n <EyeOff v-else key=\"eye-off\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-preview-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-preview-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { nextTick, ref } from \"vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { inputClass } from \"../constants/styleConstants\";\n\nconst props = defineProps<{\n /** The loaded template's name. Undefined renders the \"Untitled\" placeholder. */\n name?: string;\n /**\n * Whether the name may be changed. False when the provider withheld `save`:\n * there would be nowhere for the new name to go, so it renders as plain text.\n */\n editable: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"commit\", name: string): void;\n}>();\n\nconst { t } = useI18n();\n\nconst isEditing = ref(false);\nconst draft = ref(\"\");\nconst inputEl = ref<HTMLInputElement | null>(null);\n\nasync function startEditing(): Promise<void> {\n if (!props.editable) return;\n draft.value = props.name ?? \"\";\n isEditing.value = true;\n await nextTick();\n inputEl.value?.focus();\n inputEl.value?.select();\n}\n\nfunction commit(): void {\n // Escape already left edit mode, and removing the input fires `blur` — which\n // would otherwise commit the very draft the user just cancelled.\n if (!isEditing.value) return;\n isEditing.value = false;\n const next = draft.value.trim();\n // An empty name is rejected by reverting: the header would have nothing to\n // render, and a cleared field is far more likely a slip than an intent.\n if (!next || next === props.name) return;\n emit(\"commit\", next);\n}\n\nfunction cancel(): void {\n isEditing.value = false;\n}\n</script>\n\n<template>\n <input\n v-if=\"isEditing\"\n ref=\"inputEl\"\n v-model=\"draft\"\n type=\"text\"\n data-testid=\"template-name-input\"\n :aria-label=\"t.header.templateName\"\n :class=\"[\n inputClass,\n 'tpl:h-8 tpl:max-w-[260px] tpl:text-sm tpl:font-medium',\n ]\"\n @keydown.enter.prevent=\"commit\"\n @keydown.esc.prevent=\"cancel\"\n @blur=\"commit\"\n />\n <button\n v-else-if=\"editable\"\n type=\"button\"\n data-testid=\"template-name\"\n :title=\"t.header.rename\"\n :aria-label=\"t.header.rename\"\n class=\"tpl:max-w-[260px] tpl:cursor-pointer tpl:truncate tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-transparent tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:border-[var(--tpl-border)] tpl:hover:bg-[var(--tpl-bg-hover)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n @click=\"startEditing\"\n >\n {{ name || t.header.untitled }}\n </button>\n <span\n v-else\n data-testid=\"template-name\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n >\n {{ name || t.header.untitled }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { nextTick, ref } from \"vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { inputClass } from \"../constants/styleConstants\";\n\nconst props = defineProps<{\n /** The loaded template's name. Undefined renders the \"Untitled\" placeholder. */\n name?: string;\n /**\n * Whether the name may be changed. False when the provider withheld `save`:\n * there would be nowhere for the new name to go, so it renders as plain text.\n */\n editable: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"commit\", name: string): void;\n}>();\n\nconst { t } = useI18n();\n\nconst isEditing = ref(false);\nconst draft = ref(\"\");\nconst inputEl = ref<HTMLInputElement | null>(null);\n\nasync function startEditing(): Promise<void> {\n if (!props.editable) return;\n draft.value = props.name ?? \"\";\n isEditing.value = true;\n await nextTick();\n inputEl.value?.focus();\n inputEl.value?.select();\n}\n\nfunction commit(): void {\n // Escape already left edit mode, and removing the input fires `blur` — which\n // would otherwise commit the very draft the user just cancelled.\n if (!isEditing.value) return;\n isEditing.value = false;\n const next = draft.value.trim();\n // An empty name is rejected by reverting: the header would have nothing to\n // render, and a cleared field is far more likely a slip than an intent.\n if (!next || next === props.name) return;\n emit(\"commit\", next);\n}\n\nfunction cancel(): void {\n isEditing.value = false;\n}\n</script>\n\n<template>\n <input\n v-if=\"isEditing\"\n ref=\"inputEl\"\n v-model=\"draft\"\n type=\"text\"\n data-testid=\"template-name-input\"\n :aria-label=\"t.header.templateName\"\n :class=\"[\n inputClass,\n 'tpl:h-8 tpl:max-w-[260px] tpl:text-sm tpl:font-medium',\n ]\"\n @keydown.enter.prevent=\"commit\"\n @keydown.esc.prevent=\"cancel\"\n @blur=\"commit\"\n />\n <button\n v-else-if=\"editable\"\n type=\"button\"\n data-testid=\"template-name\"\n :title=\"t.header.rename\"\n :aria-label=\"t.header.rename\"\n class=\"tpl:max-w-[260px] tpl:cursor-pointer tpl:truncate tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-transparent tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:border-[var(--tpl-border)] tpl:hover:bg-[var(--tpl-bg-hover)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n @click=\"startEditing\"\n >\n {{ name || t.header.untitled }}\n </button>\n <span\n v-else\n data-testid=\"template-name\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n >\n {{ name || t.header.untitled }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, ref } from \"vue\";\nimport { useIntervalFn } from \"@vueuse/core\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { UI_LOCALE_KEY } from \"../keys\";\nimport { formatAbsoluteDateTime } from \"../utils/formatAbsoluteDateTime\";\nimport { formatRelativeTime } from \"../utils/formatRelativeTime\";\n\nconst props = defineProps<{\n /** ISO 8601 timestamp, straight from the store. */\n iso: string;\n /** Which field it came from — decides the \"Updated\"/\"Created\" wording. */\n kind: \"updatedAt\" | \"createdAt\";\n}>();\n\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined);\n\n// The header stays open for as long as the session does, so a label computed\n// once would sit at \"Just now\" for hours. A minute is the formatter's smallest\n// bucket, so nothing finer would show anyway.\nconst tick = ref(0);\nuseIntervalFn(() => {\n tick.value += 1;\n}, 60000);\n\nconst label = computed(() => {\n // Depended on for its side effect: `formatRelativeTime` reads the clock\n // itself, so the tick is the only thing that can invalidate this.\n void tick.value;\n const relative = formatRelativeTime(props.iso, t.time, format);\n // Null covers a value that does not parse and one further into the future\n // than clock skew explains. Falling back to an absolute date would put a\n // number where the eye expects chrome, so the line is dropped instead.\n if (relative === null) return \"\";\n // The shared buckets are phrased to stand alone, so the smallest one is\n // capitalised (\"Just now\") and reads wrong inside \"Updated {time}\". Matched\n // against the label rather than re-deriving a one-minute threshold, so what\n // counts as \"just now\" stays `formatRelativeTime`'s decision alone.\n const isJustNow = relative === t.time.justNow;\n if (props.kind === \"updatedAt\") {\n return isJustNow\n ? t.header.updatedJustNow\n : format(t.header.updatedAt, { time: relative });\n }\n return isJustNow\n ? t.header.createdJustNow\n : format(t.header.createdAt, { time: relative });\n});\n\n/**\n * Full date for the tooltip — built by `Intl`, so it needs no i18n keys, but it\n * does need the editor's locale: `toLocaleString()` with no argument formats in\n * the BROWSER's, which put an English month name directly under German chrome.\n */\nconst absolute = computed(() => formatAbsoluteDateTime(props.iso, uiLocale));\n</script>\n\n<template>\n <!-- `px-2` aligns the line under the name field's text, which carries the same\n padding for its hover affordance. Present whether or not the name renders,\n so the left column reads the same in both. -->\n <span\n v-if=\"label\"\n data-testid=\"template-timestamp\"\n :title=\"absolute\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:text-xs tpl:leading-tight tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ label }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, ref } from \"vue\";\nimport { useIntervalFn } from \"@vueuse/core\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { UI_LOCALE_KEY } from \"../keys\";\nimport { formatAbsoluteDateTime } from \"../utils/formatAbsoluteDateTime\";\nimport { formatRelativeTime } from \"../utils/formatRelativeTime\";\n\nconst props = defineProps<{\n /** ISO 8601 timestamp, straight from the store. */\n iso: string;\n /** Which field it came from — decides the \"Updated\"/\"Created\" wording. */\n kind: \"updatedAt\" | \"createdAt\";\n}>();\n\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined);\n\n// The header stays open for as long as the session does, so a label computed\n// once would sit at \"Just now\" for hours. A minute is the formatter's smallest\n// bucket, so nothing finer would show anyway.\nconst tick = ref(0);\nuseIntervalFn(() => {\n tick.value += 1;\n}, 60000);\n\nconst label = computed(() => {\n // Depended on for its side effect: `formatRelativeTime` reads the clock\n // itself, so the tick is the only thing that can invalidate this.\n void tick.value;\n const relative = formatRelativeTime(props.iso, t.time, format);\n // Null covers a value that does not parse and one further into the future\n // than clock skew explains. Falling back to an absolute date would put a\n // number where the eye expects chrome, so the line is dropped instead.\n if (relative === null) return \"\";\n // The shared buckets are phrased to stand alone, so the smallest one is\n // capitalised (\"Just now\") and reads wrong inside \"Updated {time}\". Matched\n // against the label rather than re-deriving a one-minute threshold, so what\n // counts as \"just now\" stays `formatRelativeTime`'s decision alone.\n const isJustNow = relative === t.time.justNow;\n if (props.kind === \"updatedAt\") {\n return isJustNow\n ? t.header.updatedJustNow\n : format(t.header.updatedAt, { time: relative });\n }\n return isJustNow\n ? t.header.createdJustNow\n : format(t.header.createdAt, { time: relative });\n});\n\n/**\n * Full date for the tooltip — built by `Intl`, so it needs no i18n keys, but it\n * does need the editor's locale: `toLocaleString()` with no argument formats in\n * the BROWSER's, which put an English month name directly under German chrome.\n */\nconst absolute = computed(() => formatAbsoluteDateTime(props.iso, uiLocale));\n</script>\n\n<template>\n <!-- `px-2` aligns the line under the name field's text, which carries the same\n padding for its hover affordance. Present whether or not the name renders,\n so the left column reads the same in both. -->\n <span\n v-if=\"label\"\n data-testid=\"template-timestamp\"\n :title=\"absolute\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:text-xs tpl:leading-tight tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ label }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { Check, CircleAlert } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n status: \"idle\" | \"saved\" | \"error\";\n /** The provider's failure message, shown in a tooltip on the error state. */\n errorMessage: string;\n isDirty: boolean;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <!-- Three mutually exclusive states, in priority order: a failure outranks\n everything (it needs acknowledging), a fresh success outranks the dirty\n flag, and \"unsaved\" is the resting state once either decays. Rendered\n only when a templates provider can actually save — without one the editor\n never learns that a save completed, so this would read \"unsaved\" forever. -->\n <div\n v-if=\"status === 'error'\"\n aria-live=\"assertive\"\n data-testid=\"save-status-error\"\n class=\"tpl-tooltip tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-danger)]\"\n :data-tooltip=\"errorMessage\"\n >\n <CircleAlert :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saveFailed }}\n </div>\n <div\n v-else-if=\"status === 'saved'\"\n aria-live=\"polite\"\n data-testid=\"save-status-saved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-success)]\"\n >\n <Check :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saved }}\n </div>\n <div\n v-else-if=\"isDirty\"\n aria-live=\"polite\"\n data-testid=\"save-status-unsaved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <span\n class=\"tpl-pulse tpl:size-1.5 tpl:rounded-full tpl:bg-[var(--tpl-primary)]\"\n ></span>\n {{ t.header.unsaved }}\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Check, CircleAlert } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n status: \"idle\" | \"saved\" | \"error\";\n /** The provider's failure message, shown in a tooltip on the error state. */\n errorMessage: string;\n isDirty: boolean;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <!-- Three mutually exclusive states, in priority order: a failure outranks\n everything (it needs acknowledging), a fresh success outranks the dirty\n flag, and \"unsaved\" is the resting state once either decays. Rendered\n only when a templates provider can actually save — without one the editor\n never learns that a save completed, so this would read \"unsaved\" forever. -->\n <div\n v-if=\"status === 'error'\"\n aria-live=\"assertive\"\n data-testid=\"save-status-error\"\n class=\"tpl-tooltip tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-danger)]\"\n :data-tooltip=\"errorMessage\"\n >\n <CircleAlert :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saveFailed }}\n </div>\n <div\n v-else-if=\"status === 'saved'\"\n aria-live=\"polite\"\n data-testid=\"save-status-saved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-success)]\"\n >\n <Check :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saved }}\n </div>\n <div\n v-else-if=\"isDirty\"\n aria-live=\"polite\"\n data-testid=\"save-status-unsaved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <span\n class=\"tpl-pulse tpl:size-1.5 tpl:rounded-full tpl:bg-[var(--tpl-primary)]\"\n ></span>\n {{ t.header.unsaved }}\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Sparkles } from \"@lucide/vue\";\nimport { computed } from \"vue\";\nimport type { UseAiFeatureReturn } from \"../../composables/useAiFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { secondaryBtnCompactClass } from \"../../constants/styleConstants\";\n\nconst props = defineProps<{\n feature: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n >;\n}>();\n\nconst { t } = useI18n();\nconst isActive = computed(() => props.feature.panel.value === \"chat\");\n\nfunction toggle(): void {\n if (isActive.value) props.feature.close();\n else props.feature.open(\"chat\");\n}\n</script>\n\n<template>\n <!-- The header's shared compact recipe, like Comments and test email, so the\n row keeps one height, size and weight and Save stays its only amber\n surface. The amber is on the icon alone: `--tpl-primary-hover` is 3.64:1\n on `--tpl-bg`, clearing the 3:1 non-text floor that `--tpl-primary`\n (2.76:1) misses. Open, it takes the Comments button's open fill. -->\n <button\n v-if=\"feature.isAvailable.value && feature.has('chat')\"\n type=\"button\"\n data-testid=\"ai-menu-trigger\"\n :aria-pressed=\"isActive\"\n :aria-label=\"t.ai.menu.chat\"\n :title=\"t.ai.menu.chat\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n isActive\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click.stop=\"toggle\"\n >\n <Sparkles\n :size=\"16\"\n :stroke-width=\"2\"\n class=\"tpl:text-[var(--tpl-primary-hover)]\"\n aria-hidden=\"true\"\n />\n {{ t.ai.menu.button }}\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { Sparkles } from \"@lucide/vue\";\nimport { computed } from \"vue\";\nimport type { UseAiFeatureReturn } from \"../../composables/useAiFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { secondaryBtnCompactClass } from \"../../constants/styleConstants\";\n\nconst props = defineProps<{\n feature: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n >;\n}>();\n\nconst { t } = useI18n();\nconst isActive = computed(() => props.feature.panel.value === \"chat\");\n\nfunction toggle(): void {\n if (isActive.value) props.feature.close();\n else props.feature.open(\"chat\");\n}\n</script>\n\n<template>\n <!-- The header's shared compact recipe, like Comments and test email, so the\n row keeps one height, size and weight and Save stays its only amber\n surface. The amber is on the icon alone: `--tpl-primary-hover` is 3.64:1\n on `--tpl-bg`, clearing the 3:1 non-text floor that `--tpl-primary`\n (2.76:1) misses. Open, it takes the Comments button's open fill. -->\n <button\n v-if=\"feature.isAvailable.value && feature.has('chat')\"\n type=\"button\"\n data-testid=\"ai-menu-trigger\"\n :aria-pressed=\"isActive\"\n :aria-label=\"t.ai.menu.chat\"\n :title=\"t.ai.menu.chat\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n isActive\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click.stop=\"toggle\"\n >\n <Sparkles\n :size=\"16\"\n :stroke-width=\"2\"\n class=\"tpl:text-[var(--tpl-primary-hover)]\"\n aria-hidden=\"true\"\n />\n {{ t.ai.menu.button }}\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { defineAsyncComponent } from \"vue\";\nimport { LoaderCircle, MessageCircle, Save, Send } from \"@lucide/vue\";\n\nimport type {\n BaseEditorReturn,\n UseEditorCoreReturn,\n} from \"../composables/useEditorCore\";\nimport type { UseAiFeatureReturn } from \"../composables/useAiFeature\";\nimport type { UseCollaborationFeatureReturn } from \"../composables/useCollaborationFeature\";\nimport type { UseCommentsFeatureReturn } from \"../composables/useCommentsFeature\";\nimport type { UseTemplatesFeatureReturn } from \"../composables/useTemplatesFeature\";\nimport type { UseTestEmailFeatureReturn } from \"../composables/useTestEmailFeature\";\nimport type { UseVersionHistoryFeatureReturn } from \"../composables/useVersionHistoryFeature\";\nimport {\n primaryBtnCompactClass,\n secondaryBtnCompactClass,\n} from \"../constants/styleConstants\";\n\nimport ViewportToggle from \"./ViewportToggle.vue\";\nimport DarkModeToggle from \"./DarkModeToggle.vue\";\nimport PreviewToggle from \"./PreviewToggle.vue\";\nimport TemplateNameField from \"./TemplateNameField.vue\";\nimport TemplateTimestamp from \"./TemplateTimestamp.vue\";\nimport TemplateSaveStatus from \"./TemplateSaveStatus.vue\";\n// Eager, unlike the panels it opens: lazy, it rendered one chunk fetch after\n// the rest of the header. The AI panels stay lazy in `Editor.vue`, so an editor\n// without an `ai` provider downloads only this button.\nimport AiHeaderMenu from \"./ai/AiHeaderMenu.vue\";\n\n// Lazy: an editor with no `versionHistory` provider never downloads the control.\nconst VersionHistoryMenu = defineAsyncComponent(\n () => import(\"./VersionHistoryMenu.vue\"),\n);\n// Lazy: an editor with no collaboration provider never downloads it.\nconst CollaboratorBar = defineAsyncComponent(\n () => import(\"./collaboration/CollaboratorBar.vue\"),\n);\n\n/**\n * The editor's one header. Both entry points render this — `initCloud()` adds its\n * own controls through the `left-extras` / `right-extras` slots rather than\n * through a second header component, which is what keeps the two layouts from\n * drifting apart again (they already had: only Cloud carried `min-w-[200px]`, so\n * the OSS centre column was never actually centred).\n *\n * The two slots are in the anchored columns on purpose. There is deliberately no\n * centre slot: that track's width must stay constant, and a slot is the one\n * thing a guard test cannot stop someone filling. See the centre column's own\n * comment for why width changes there move the Preview button.\n *\n * Everything here is capability-driven, so the same markup covers \"no providers\n * configured at all\" and a fully-wired Cloud session. Nothing in this file knows\n * that Cloud exists.\n */\ndefineProps<{\n editor: BaseEditorReturn;\n core: UseEditorCoreReturn;\n /** Null when no `TemplatesProvider` is configured — no name, save or status. */\n templates: UseTemplatesFeatureReturn | null;\n /**\n * Whether to render the inline name field, from `config.templates?.nameField`.\n * False hides it whether or not the provider can save — a consumer whose\n * store has no name column, or whose own chrome owns the name.\n */\n showTemplateName: boolean;\n testEmail: UseTestEmailFeatureReturn | null;\n versionHistory: UseVersionHistoryFeatureReturn | null;\n /** Null when no `CommentsProvider` (or no `user`) is configured. */\n comments: UseCommentsFeatureReturn | null;\n /** Null when no `CollaborationProvider` is configured. */\n collaboration: UseCollaborationFeatureReturn | null;\n /** Null when no `AiProvider` is configured. */\n ai: UseAiFeatureReturn | null;\n}>();\n</script>\n\n<template>\n <!-- Opaque, and `--tpl-shadow-sm` because that is the step the shadow\n vocabulary assigns to sticky chrome. `.tpl-body` starts at this header's\n own height, so nothing ever passes beneath it: a translucent fill has an\n identical surface behind it and a backdrop blur has nothing to blur,\n which costs a compositing layer to render exactly `--tpl-bg`. -->\n <header\n class=\"tpl-header tpl:absolute tpl:top-0 tpl:right-0 tpl:left-0 tpl:z-50 tpl:grid tpl:h-14 tpl:grid-cols-[1fr_auto_1fr] tpl:items-center tpl:px-4 tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-sm)] tpl:border-b tpl:border-[var(--tpl-border)]\"\n >\n <!-- Left: the template's identity — the inline-editable name, and under it\n when the store dates its writes. Stacking the two needs 6px of bottom\n padding: the name is a button, so it carries border + `py-1` + half its\n leading above its text, while the timestamp carries nothing below its\n own. Centring the boxes therefore puts all of that lead at the top and\n reads as a misaligned pair. Only when both render — either alone is\n already centred on its own box. `min-w-[200px]` matches the right column\n so the centre controls are actually centred. Nothing renders before a\n template exists; there is neither a name nor a write time yet. The stack\n is gated as a whole so an empty one cannot add a `gap-2.5` before the\n cloud extras. -->\n <div\n class=\"tpl-header-left tpl:flex tpl:min-w-[200px] tpl:items-center tpl:gap-2.5\"\n >\n <div\n v-if=\"\n templates?.isAvailable.value &&\n templates.hasTemplate.value &&\n (showTemplateName || templates.timestamp.value)\n \"\n class=\"tpl:flex tpl:min-w-0 tpl:flex-col tpl:items-start\"\n :class=\"{\n 'tpl:pb-1.5': showTemplateName && templates.timestamp.value !== null,\n }\"\n >\n <TemplateNameField\n v-if=\"showTemplateName\"\n :name=\"templates.name.value\"\n :editable=\"templates.canSave.value\"\n @commit=\"templates.rename\"\n />\n <TemplateTimestamp\n v-if=\"templates.timestamp.value\"\n :iso=\"templates.timestamp.value.iso\"\n :kind=\"templates.timestamp.value.kind\"\n />\n </div>\n <!-- Version history — the third piece of \"which template, and which\n version of it\", after the name and the write time. It sits here and\n not in the right column because that column's content already\n overflows its track: `justify-end` packs to the right edge, so an\n extra control there spills *leftward* over the centre track and\n swallows clicks meant for the Preview button. Measured — it covered\n it with the menu's own back-arrow. This column packs from the left\n and has the room.\n\n Needs a template as well as a provider: a version belongs to a\n template id, so before one is loaded there is nothing to list. -->\n <VersionHistoryMenu\n v-if=\"\n versionHistory?.isAvailable.value && versionHistory.hasTemplate.value\n \"\n :versions=\"versionHistory.versions.value\"\n :is-loading=\"versionHistory.isLoading.value\"\n :is-restoring=\"versionHistory.isRestoring.value\"\n :previewing-id=\"versionHistory.previewingVersion.value?.id ?? null\"\n @open=\"versionHistory.refresh()\"\n @navigate=\"versionHistory.navigate($event)\"\n />\n <!-- Who else has the template open. Here, never in the centre track:\n the bar changes width as people come and go, and the centre must\n not (#574). This column packs from the left and moves nothing. -->\n <CollaboratorBar\n v-if=\"collaboration?.isLive.value\"\n :people=\"collaboration.people.value\"\n :connection=\"collaboration.connection.value\"\n />\n <slot name=\"left-extras\" />\n </div>\n\n <!-- Center: the three \"how am I viewing the canvas\" controls, and nothing\n else — ever.\n\n The grid is `1fr auto 1fr`, so this track is exactly max-content wide\n and the equal `fr` columns centre it. Any width change therefore\n redistributes symmetrically about the header's centre and moves every\n sibling by half the delta, whichever side of the change it sits on.\n DOM order buys nothing. So a conditional control here drags the Preview\n button out from under the cursor — 114.5px when the sample/label toggle\n used to live here, and repeatedly in Cloud as collaborators came and\n went (#574).\n\n Hence the rule: nothing in this track may be conditional. No `v-if`, no\n `v-show`, no slot. Conditional controls go in the edge-anchored `fr`\n columns, which grow away from their anchored edge; preview-only ones go\n on the preview surface, where `Editor.vue` floats them over the canvas.\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div\n class=\"tpl-header-center tpl:flex tpl:items-center tpl:justify-center tpl:gap-10\"\n >\n <ViewportToggle\n :viewport=\"editor.state.viewport\"\n @change=\"editor.setViewport\"\n />\n <DarkModeToggle\n :dark-mode=\"editor.state.darkMode\"\n @change=\"editor.setDarkMode\"\n />\n <PreviewToggle\n :preview-mode=\"editor.state.previewMode\"\n @change=\"editor.setPreviewMode\"\n />\n </div>\n\n <!-- Right: save status → Comments → AI → [cloud extras] → test email → Save.\n Save is last: it is the primary action. `justify-end` anchors the row to\n the right edge, so a control appearing at its start extends the row\n leftward and moves nothing already in it — but note the row is already\n at the edge of its track at common widths, so anything added here\n overflows onto the centre rather than fitting. -->\n <div\n class=\"tpl-header-right tpl:flex tpl:min-w-[200px] tpl:items-center tpl:justify-end tpl:gap-3\"\n >\n <!-- Gated on a provider that can actually save. Without one the editor\n never learns that a save completed, so the badge could only ever read\n \"unsaved\" — worse than showing nothing. -->\n <TemplateSaveStatus\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n :status=\"templates.status.value\"\n :error-message=\"templates.errorMessage.value\"\n :is-dirty=\"editor.state.isDirty\"\n />\n\n <!-- Comments. Needs a template as well as a provider — a comment is keyed\n to a template id, so before one is loaded there is nothing to attach a\n thread to. Shared chrome, because comments are a shared\n provider-backed feature rather than a Cloud one. -->\n <button\n v-if=\"comments?.isAvailable.value && comments.hasTemplate.value\"\n type=\"button\"\n data-testid=\"comments-trigger\"\n :aria-label=\"\n comments.unresolvedCount.value > 0\n ? `${core.t.comments.button} (${comments.unresolvedCount.value})`\n : core.t.comments.button\n \"\n :aria-expanded=\"comments.isOpen.value\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n comments.isOpen.value\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click=\"comments.toggle()\"\n >\n <MessageCircle :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.comments.button }}\n <span\n v-if=\"comments.unresolvedCount.value > 0 && !comments.isOpen.value\"\n class=\"tpl:inline-flex tpl:size-4.5 tpl:items-center tpl:justify-center tpl:rounded-full tpl:text-[10px] tpl:font-semibold tpl:bg-[var(--tpl-primary)] tpl:text-[var(--tpl-on-primary)]\"\n >\n {{ comments.unresolvedCount.value }}\n </span>\n </button>\n\n <!-- AI: after Comments, before test email, as Cloud's AI button sat. -->\n <AiHeaderMenu v-if=\"ai\" :feature=\"ai\" />\n\n <slot name=\"right-extras\" />\n\n <!-- The shared recipe, like every control in this row. Shared rather than\n hand-rolled so all three keep one height — a bespoke string is how\n this button came to sit 4px shorter than its neighbours. -->\n <button\n v-if=\"testEmail?.isAvailable.value\"\n type=\"button\"\n data-testid=\"test-email-trigger\"\n :aria-label=\"core.t.testEmail.title\"\n :title=\"core.t.testEmail.title\"\n :disabled=\"testEmail.isSending.value\"\n :class=\"secondaryBtnCompactClass\"\n @click=\"testEmail.open()\"\n >\n <Send v-if=\"!testEmail.isSending.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle v-else class=\"tpl-spinner\" :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.testEmail.button }}\n </button>\n\n <!-- Save is the editor's one primary, and it only takes that treatment\n while there is something to save. Amber announces intent or selection,\n so a Save that looks identical dirty or clean announces nothing — and\n it would be the loudest element in chrome that exists to recede behind\n the canvas. Gated on `hasTemplate` too, or a disabled button would\n light up before there is anywhere to save to.\n\n Amber with the paper colour on it is 2.80:1 in light mode. That is\n accepted rather than overlooked: every amber surface and accent in the\n editor shares this pairing, and correcting this one control alone would\n make it read as a different kind of thing. The Amber-Accent Exception\n in DESIGN.md records the decision and its limits — chief among them\n that amber must never be the only carrier of a state, which is why the\n `TemplateSaveStatus` badge says \"Unsaved\" in words beside it.\n\n The light lift is the same condition, and it is Flat-At-Rest applied\n rather than bent: a surface paints no shadow until something happens to\n it, and unsaved work is that something. It sits inline rather than in\n the recipe because the recipe is shared, and a primary button at rest\n elsewhere should still be flat.\n\n Hidden entirely when the provider withheld `save` — the read-only\n equivalent of the saved-blocks permission discipline: loading a\n template and editing it locally still works, there is simply nothing\n to persist. Disabled (with a reason in the tooltip) until a template\n exists, since `save()` patches an id. -->\n <button\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n type=\"button\"\n data-testid=\"template-save\"\n :class=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? primaryBtnCompactClass\n : secondaryBtnCompactClass\n \"\n :style=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? { boxShadow: 'var(--tpl-shadow-sm)' }\n : undefined\n \"\n :disabled=\"templates.isSaving.value || !templates.hasTemplate.value\"\n :title=\"\n templates.hasTemplate.value\n ? core.t.header.save\n : core.t.header.saveNoTemplate\n \"\n @click=\"templates.requestSave()\"\n >\n <Save v-if=\"!templates.isSaving.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle v-else class=\"tpl-spinner\" :size=\"16\" :stroke-width=\"2\" />\n {{\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n }}\n </button>\n </div>\n </header>\n</template>\n","<script setup lang=\"ts\">\nimport { defineAsyncComponent } from \"vue\";\nimport { LoaderCircle, MessageCircle, Save, Send } from \"@lucide/vue\";\n\nimport type {\n BaseEditorReturn,\n UseEditorCoreReturn,\n} from \"../composables/useEditorCore\";\nimport type { UseAiFeatureReturn } from \"../composables/useAiFeature\";\nimport type { UseCollaborationFeatureReturn } from \"../composables/useCollaborationFeature\";\nimport type { UseCommentsFeatureReturn } from \"../composables/useCommentsFeature\";\nimport type { UseTemplatesFeatureReturn } from \"../composables/useTemplatesFeature\";\nimport type { UseTestEmailFeatureReturn } from \"../composables/useTestEmailFeature\";\nimport type { UseVersionHistoryFeatureReturn } from \"../composables/useVersionHistoryFeature\";\nimport {\n primaryBtnCompactClass,\n secondaryBtnCompactClass,\n} from \"../constants/styleConstants\";\n\nimport ViewportToggle from \"./ViewportToggle.vue\";\nimport DarkModeToggle from \"./DarkModeToggle.vue\";\nimport PreviewToggle from \"./PreviewToggle.vue\";\nimport TemplateNameField from \"./TemplateNameField.vue\";\nimport TemplateTimestamp from \"./TemplateTimestamp.vue\";\nimport TemplateSaveStatus from \"./TemplateSaveStatus.vue\";\n// Eager, unlike the panels it opens: lazy, it rendered one chunk fetch after\n// the rest of the header. The AI panels stay lazy in `Editor.vue`, so an editor\n// without an `ai` provider downloads only this button.\nimport AiHeaderMenu from \"./ai/AiHeaderMenu.vue\";\n\n// Lazy: an editor with no `versionHistory` provider never downloads the control.\nconst VersionHistoryMenu = defineAsyncComponent(\n () => import(\"./VersionHistoryMenu.vue\"),\n);\n// Lazy: an editor with no collaboration provider never downloads it.\nconst CollaboratorBar = defineAsyncComponent(\n () => import(\"./collaboration/CollaboratorBar.vue\"),\n);\n\n/**\n * The editor's one header. Both entry points render this — `initCloud()` adds its\n * own controls through the `left-extras` / `right-extras` slots rather than\n * through a second header component, which is what keeps the two layouts from\n * drifting apart again (they already had: only Cloud carried `min-w-[200px]`, so\n * the OSS centre column was never actually centred).\n *\n * The two slots are in the anchored columns on purpose. There is deliberately no\n * centre slot: that track's width must stay constant, and a slot is the one\n * thing a guard test cannot stop someone filling. See the centre column's own\n * comment for why width changes there move the Preview button.\n *\n * Everything here is capability-driven, so the same markup covers \"no providers\n * configured at all\" and a fully-wired Cloud session. Nothing in this file knows\n * that Cloud exists.\n */\ndefineProps<{\n editor: BaseEditorReturn;\n core: UseEditorCoreReturn;\n /** Null when no `TemplatesProvider` is configured — no name, save or status. */\n templates: UseTemplatesFeatureReturn | null;\n /**\n * Whether to render the inline name field, from `config.templates?.nameField`.\n * False hides it whether or not the provider can save — a consumer whose\n * store has no name column, or whose own chrome owns the name.\n */\n showTemplateName: boolean;\n testEmail: UseTestEmailFeatureReturn | null;\n versionHistory: UseVersionHistoryFeatureReturn | null;\n /** Null when no `CommentsProvider` (or no `user`) is configured. */\n comments: UseCommentsFeatureReturn | null;\n /** Null when no `CollaborationProvider` is configured. */\n collaboration: UseCollaborationFeatureReturn | null;\n /** Null when no `AiProvider` is configured. */\n ai: UseAiFeatureReturn | null;\n}>();\n</script>\n\n<template>\n <!-- Opaque, and `--tpl-shadow-sm` because that is the step the shadow\n vocabulary assigns to sticky chrome. `.tpl-body` starts at this header's\n own height, so nothing ever passes beneath it: a translucent fill has an\n identical surface behind it and a backdrop blur has nothing to blur,\n which costs a compositing layer to render exactly `--tpl-bg`. -->\n <header\n class=\"tpl-header tpl:absolute tpl:top-0 tpl:right-0 tpl:left-0 tpl:z-50 tpl:grid tpl:h-14 tpl:grid-cols-[1fr_auto_1fr] tpl:items-center tpl:px-4 tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-sm)] tpl:border-b tpl:border-[var(--tpl-border)]\"\n >\n <!-- Left: the template's identity — the inline-editable name, and under it\n when the store dates its writes. Stacking the two needs 6px of bottom\n padding: the name is a button, so it carries border + `py-1` + half its\n leading above its text, while the timestamp carries nothing below its\n own. Centring the boxes therefore puts all of that lead at the top and\n reads as a misaligned pair. Only when both render — either alone is\n already centred on its own box. `min-w-[200px]` matches the right column\n so the centre controls are actually centred. Nothing renders before a\n template exists; there is neither a name nor a write time yet. The stack\n is gated as a whole so an empty one cannot add a `gap-2.5` before the\n cloud extras. -->\n <div\n class=\"tpl-header-left tpl:flex tpl:min-w-[200px] tpl:items-center tpl:gap-2.5\"\n >\n <div\n v-if=\"\n templates?.isAvailable.value &&\n templates.hasTemplate.value &&\n (showTemplateName || templates.timestamp.value)\n \"\n class=\"tpl:flex tpl:min-w-0 tpl:flex-col tpl:items-start\"\n :class=\"{\n 'tpl:pb-1.5': showTemplateName && templates.timestamp.value !== null,\n }\"\n >\n <TemplateNameField\n v-if=\"showTemplateName\"\n :name=\"templates.name.value\"\n :editable=\"templates.canSave.value\"\n @commit=\"templates.rename\"\n />\n <TemplateTimestamp\n v-if=\"templates.timestamp.value\"\n :iso=\"templates.timestamp.value.iso\"\n :kind=\"templates.timestamp.value.kind\"\n />\n </div>\n <!-- Version history — the third piece of \"which template, and which\n version of it\", after the name and the write time. It sits here and\n not in the right column because that column's content already\n overflows its track: `justify-end` packs to the right edge, so an\n extra control there spills *leftward* over the centre track and\n swallows clicks meant for the Preview button. Measured — it covered\n it with the menu's own back-arrow. This column packs from the left\n and has the room.\n\n Needs a template as well as a provider: a version belongs to a\n template id, so before one is loaded there is nothing to list. -->\n <VersionHistoryMenu\n v-if=\"\n versionHistory?.isAvailable.value && versionHistory.hasTemplate.value\n \"\n :versions=\"versionHistory.versions.value\"\n :is-loading=\"versionHistory.isLoading.value\"\n :is-restoring=\"versionHistory.isRestoring.value\"\n :previewing-id=\"versionHistory.previewingVersion.value?.id ?? null\"\n @open=\"versionHistory.refresh()\"\n @navigate=\"versionHistory.navigate($event)\"\n />\n <!-- Who else has the template open. Here, never in the centre track:\n the bar changes width as people come and go, and the centre must\n not (#574). This column packs from the left and moves nothing. -->\n <CollaboratorBar\n v-if=\"collaboration?.isLive.value\"\n :people=\"collaboration.people.value\"\n :connection=\"collaboration.connection.value\"\n />\n <slot name=\"left-extras\" />\n </div>\n\n <!-- Center: the three \"how am I viewing the canvas\" controls, and nothing\n else — ever.\n\n The grid is `1fr auto 1fr`, so this track is exactly max-content wide\n and the equal `fr` columns centre it. Any width change therefore\n redistributes symmetrically about the header's centre and moves every\n sibling by half the delta, whichever side of the change it sits on.\n DOM order buys nothing. So a conditional control here drags the Preview\n button out from under the cursor — 114.5px when the sample/label toggle\n used to live here, and repeatedly in Cloud as collaborators came and\n went (#574).\n\n Hence the rule: nothing in this track may be conditional. No `v-if`, no\n `v-show`, no slot. Conditional controls go in the edge-anchored `fr`\n columns, which grow away from their anchored edge; preview-only ones go\n on the preview surface, where `Editor.vue` floats them over the canvas.\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div\n class=\"tpl-header-center tpl:flex tpl:items-center tpl:justify-center tpl:gap-10\"\n >\n <ViewportToggle\n :viewport=\"editor.state.viewport\"\n @change=\"editor.setViewport\"\n />\n <DarkModeToggle\n :dark-mode=\"editor.state.darkMode\"\n @change=\"editor.setDarkMode\"\n />\n <PreviewToggle\n :preview-mode=\"editor.state.previewMode\"\n @change=\"editor.setPreviewMode\"\n />\n </div>\n\n <!-- Right: save status → Comments → AI → [cloud extras] → test email → Save.\n Save is last: it is the primary action. `justify-end` anchors the row to\n the right edge, so a control appearing at its start extends the row\n leftward and moves nothing already in it — but note the row is already\n at the edge of its track at common widths, so anything added here\n overflows onto the centre rather than fitting. -->\n <div\n class=\"tpl-header-right tpl:flex tpl:min-w-[200px] tpl:items-center tpl:justify-end tpl:gap-3\"\n >\n <!-- Gated on a provider that can actually save. Without one the editor\n never learns that a save completed, so the badge could only ever read\n \"unsaved\" — worse than showing nothing. -->\n <TemplateSaveStatus\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n :status=\"templates.status.value\"\n :error-message=\"templates.errorMessage.value\"\n :is-dirty=\"editor.state.isDirty\"\n />\n\n <!-- Comments. Needs a template as well as a provider — a comment is keyed\n to a template id, so before one is loaded there is nothing to attach a\n thread to. Shared chrome, because comments are a shared\n provider-backed feature rather than a Cloud one. -->\n <button\n v-if=\"comments?.isAvailable.value && comments.hasTemplate.value\"\n type=\"button\"\n data-testid=\"comments-trigger\"\n :aria-label=\"\n comments.unresolvedCount.value > 0\n ? `${core.t.comments.button} (${comments.unresolvedCount.value})`\n : core.t.comments.button\n \"\n :aria-expanded=\"comments.isOpen.value\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n comments.isOpen.value\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click=\"comments.toggle()\"\n >\n <MessageCircle :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.comments.button }}\n <span\n v-if=\"comments.unresolvedCount.value > 0 && !comments.isOpen.value\"\n class=\"tpl:inline-flex tpl:size-4.5 tpl:items-center tpl:justify-center tpl:rounded-full tpl:text-[10px] tpl:font-semibold tpl:bg-[var(--tpl-primary)] tpl:text-[var(--tpl-on-primary)]\"\n >\n {{ comments.unresolvedCount.value }}\n </span>\n </button>\n\n <!-- AI: after Comments, before test email, as Cloud's AI button sat. -->\n <AiHeaderMenu v-if=\"ai\" :feature=\"ai\" />\n\n <slot name=\"right-extras\" />\n\n <!-- The shared recipe, like every control in this row. Shared rather than\n hand-rolled so all three keep one height — a bespoke string is how\n this button came to sit 4px shorter than its neighbours. -->\n <button\n v-if=\"testEmail?.isAvailable.value\"\n type=\"button\"\n data-testid=\"test-email-trigger\"\n :aria-label=\"core.t.testEmail.title\"\n :title=\"core.t.testEmail.title\"\n :disabled=\"testEmail.isSending.value\"\n :class=\"secondaryBtnCompactClass\"\n @click=\"testEmail.open()\"\n >\n <Send v-if=\"!testEmail.isSending.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle v-else class=\"tpl-spinner\" :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.testEmail.button }}\n </button>\n\n <!-- Save is the editor's one primary, and it only takes that treatment\n while there is something to save. Amber announces intent or selection,\n so a Save that looks identical dirty or clean announces nothing — and\n it would be the loudest element in chrome that exists to recede behind\n the canvas. Gated on `hasTemplate` too, or a disabled button would\n light up before there is anywhere to save to.\n\n Amber with the paper colour on it is 2.80:1 in light mode. That is\n accepted rather than overlooked: every amber surface and accent in the\n editor shares this pairing, and correcting this one control alone would\n make it read as a different kind of thing. The Amber-Accent Exception\n in DESIGN.md records the decision and its limits — chief among them\n that amber must never be the only carrier of a state, which is why the\n `TemplateSaveStatus` badge says \"Unsaved\" in words beside it.\n\n The light lift is the same condition, and it is Flat-At-Rest applied\n rather than bent: a surface paints no shadow until something happens to\n it, and unsaved work is that something. It sits inline rather than in\n the recipe because the recipe is shared, and a primary button at rest\n elsewhere should still be flat.\n\n Hidden entirely when the provider withheld `save` — the read-only\n equivalent of the saved-blocks permission discipline: loading a\n template and editing it locally still works, there is simply nothing\n to persist. Disabled (with a reason in the tooltip) until a template\n exists, since `save()` patches an id. -->\n <button\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n type=\"button\"\n data-testid=\"template-save\"\n :class=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? primaryBtnCompactClass\n : secondaryBtnCompactClass\n \"\n :style=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? { boxShadow: 'var(--tpl-shadow-sm)' }\n : undefined\n \"\n :disabled=\"templates.isSaving.value || !templates.hasTemplate.value\"\n :title=\"\n templates.hasTemplate.value\n ? core.t.header.save\n : core.t.header.saveNoTemplate\n \"\n @click=\"templates.requestSave()\"\n >\n <Save v-if=\"!templates.isSaving.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle v-else class=\"tpl-spinner\" :size=\"16\" :stroke-width=\"2\" />\n {{\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n }}\n </button>\n </div>\n </header>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n inject,\n nextTick,\n ref,\n watch,\n type ComponentPublicInstance,\n} from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { ChevronDown, Search, X } from \"@lucide/vue\";\nimport type { MergeTag } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n MERGE_TAG_PICKER_KEY,\n MERGE_TAG_SHOW_RAW_VALUE_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\n\n// Picker singleton — provided by useEditorCore. We require it explicitly so\n// the modal is unmountable only in a non-editor context (which we don't\n// support). `requireInject` throws a clear message rather than letting a\n// silent inject default mask the misuse.\nconst picker = requireInject(MERGE_TAG_PICKER_KEY, \"MergeTagPickerModal\");\nconst { t, format } = useI18n();\n\n// Theming — same pattern as every other OSS panel (ParagraphToolbar,\n// RichTextLinkDialog). The panel carries the `tpl` token class, so it must\n// re-establish the theme locally: `data-tpl-theme` selects the dark token\n// block, and the inline `themeStyles` apply the consumer's `theme` config\n// overrides. Without these the base `.tpl` rule shadows both with light\n// defaults and the picker ignores dark mode + custom theme colors.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\nconst showRawValue = inject(MERGE_TAG_SHOW_RAW_VALUE_KEY, true);\n\n// Replacing an existing tag rather than inserting a new one. Drives the title\n// and which row starts highlighted.\nconst isChanging = computed(() => picker.current.value !== null);\n\nconst modalTitle = computed(() =>\n isChanging.value ? t.mergeTag.picker.changeTitle : t.mergeTag.picker.title,\n);\n\n/**\n * A row's native tooltip. The description alone when the consumer hid raw\n * tokens — the picker is a list of labels, so leaking the token here would\n * defeat `showRawValue` on the one surface that exists to choose tags.\n */\nfunction rowTitle(tag: MergeTag): string | undefined {\n if (!showRawValue) return tag.description || undefined;\n return tag.description ? `${tag.value} — ${tag.description}` : tag.value;\n}\n\n// --- Search ---\nconst rawSearch = ref(\"\");\n// 200ms debounce keeps filtering responsive at 1000+ tags. The raw value\n// drives the input element (so typing feels instant); the filter reads\n// the debounced copy.\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-merge-tag-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\n// --- Highlight (keyboard nav state) ---\nconst highlightedIndex = ref(0);\n\n// --- Grouping mode ---\n// Active only when at least one tag carries `group`. When inactive, the\n// list renders flat with no headers (not even \"Other\"). The plan locks\n// this down in \"Decisions locked in\" #7.\nconst hasGroups = computed(() =>\n picker.tags.value.some((tag) => Boolean(tag.group)),\n);\n\n// --- Collapsed groups (by label) ---\n// Reset on every modal open so each session starts with all groups\n// visible. Persistence across opens would surprise users who expanded\n// in a previous edit; the cost of re-collapsing is one click.\nconst collapsedGroups = ref<Set<string>>(new Set());\nfunction isCollapsed(group: string): boolean {\n return collapsedGroups.value.has(group);\n}\nfunction toggleGroup(group: string): void {\n const next = new Set(collapsedGroups.value);\n if (next.has(group)) next.delete(group);\n else next.add(group);\n collapsedGroups.value = next;\n // Re-anchor highlight to the first visible tag — index of a\n // previously-highlighted item may now point elsewhere after the\n // collapse rearranges visibleTags.\n highlightedIndex.value = 0;\n}\n\n// --- Filtered tags ---\n// Case-insensitive substring match against label, value, description.\n// Insertion order is preserved (per decision #9).\nconst filteredTags = computed<MergeTag[]>(() => {\n const query = search.value.trim().toLowerCase();\n if (!query) return picker.tags.value;\n return picker.tags.value.filter((tag) => {\n const haystack = [tag.label, tag.value, tag.description ?? \"\"]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(query);\n });\n});\n\n// --- Group order (insertion order of first appearance) ---\n// Computed against the *full* tags list (not the filtered one) so the\n// pill row stays stable as the user types. The pills represent the\n// configured groupings; filter just adjusts which items are shown.\nconst groupOrder = computed<string[]>(() => {\n if (!hasGroups.value) return [];\n const otherLabel = t.mergeTag.picker.otherGroup;\n const seen = new Set<string>();\n const order: string[] = [];\n for (const tag of picker.tags.value) {\n const key = tag.group ?? otherLabel;\n if (seen.has(key)) continue;\n seen.add(key);\n order.push(key);\n }\n return order;\n});\n\n// --- Rendered rows (header + tag entries) ---\n// Headers are only emitted in grouped mode AND only when there is no\n// active search query (per decisions #6 + #7). Flat-list mode and\n// search-active mode both render a header-less sequence.\n//\n// Collapsed groups still emit their header row (so the header stays\n// clickable), but skip their tag rows entirely — those tags are then\n// absent from `visibleTags` and the highlight skips over them.\ntype Row =\n | { kind: \"header\"; group: string; count: number }\n | { kind: \"tag\"; tag: MergeTag; index: number };\n\nconst rows = computed<Row[]>(() => {\n const tags = filteredTags.value;\n if (!hasGroups.value || searchActive.value) {\n return tags.map((tag, index) => ({ kind: \"tag\", tag, index }));\n }\n\n // Grouped mode: bucket by `group`, ungrouped → \"Other\".\n const otherLabel = t.mergeTag.picker.otherGroup;\n const buckets = new Map<string, MergeTag[]>();\n // Insertion order over the first appearance of each group label.\n const order: string[] = [];\n for (const tag of tags) {\n const key = tag.group ?? otherLabel;\n if (!buckets.has(key)) {\n buckets.set(key, []);\n order.push(key);\n }\n buckets.get(key)!.push(tag);\n }\n\n const result: Row[] = [];\n let tagIndex = 0;\n for (const groupKey of order) {\n const items = buckets.get(groupKey)!;\n result.push({ kind: \"header\", group: groupKey, count: items.length });\n if (collapsedGroups.value.has(groupKey)) continue;\n for (const tag of items) {\n result.push({ kind: \"tag\", tag, index: tagIndex });\n tagIndex++;\n }\n }\n return result;\n});\n\n// Flat list of tag-rows only — used for highlight bookkeeping. Keyboard\n// nav skips headers, so the highlight index addresses this list directly.\nconst visibleTags = computed(() =>\n rows.value.flatMap((row) => (row.kind === \"tag\" ? [row.tag] : [])),\n);\n\n/**\n * Whether the highlight is still waiting to land on the tag being replaced.\n *\n * `search` is debounced, so right after `open()` it can still hold the previous\n * session's query and the row we want may not be in `visibleTags` yet. The flag\n * keeps trying as the list settles, and any deliberate move by the user clears\n * it so a late debounce can't yank the highlight back.\n */\nlet preselectPending = false;\n\nfunction preselectCurrent(candidates: MergeTag[]): boolean {\n const target = picker.current.value;\n if (!target) return false;\n const index = candidates.findIndex((tag) => tag.value === target.value);\n if (index === -1) return false;\n highlightedIndex.value = index;\n return true;\n}\n\nfunction setHighlight(index: number): void {\n preselectPending = false;\n highlightedIndex.value = index;\n}\n\n// --- Lifecycle: focus search + reset state when modal opens ---\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (!isOpen) {\n preselectPending = false;\n return;\n }\n {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n collapsedGroups.value = new Set();\n preselectPending = !preselectCurrent(visibleTags.value);\n // Search input is mounted as part of the same render cycle the\n // modal opens; nextTick guarantees the ref is bound before focus.\n nextTick(() => {\n searchInputRef.value?.focus();\n });\n }\n },\n);\n\n// Keep the highlight inside the visible-tags bounds whenever the\n// filtered list shrinks (e.g. user typed a more specific query).\nwatch(visibleTags, (next) => {\n if (preselectPending && preselectCurrent(next)) {\n preselectPending = false;\n return;\n }\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\n// --- Actions ---\nfunction selectTag(tag: MergeTag): void {\n picker.resolve(tag);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleTags.value.length === 0) return;\n preselectPending = false;\n const next = highlightedIndex.value + delta;\n // Stop at edges (don't wrap) — feels more predictable in a long list.\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleTags.value.length - 1, next),\n );\n scrollHighlightIntoView();\n}\n\nconst listRef = ref<HTMLElement | null>(null);\n// One ref per group header so the pill row can `scrollIntoView` precisely.\n// Bound by callback-ref in the template; cleared (set to null) when Vue\n// unmounts the header during re-render.\nconst headerRefs = ref<Record<string, HTMLElement | null>>({});\n// Vue's callback-ref type widens to Element | ComponentPublicInstance | null\n// because the same ref shape works for both DOM elements and components.\n// Headers are always native buttons, so coerce to HTMLElement once here.\nfunction setHeaderRef(\n group: string,\n el: Element | ComponentPublicInstance | null,\n): void {\n headerRefs.value[group] = (el as HTMLElement | null) ?? null;\n}\n\nfunction scrollHighlightIntoView(): void {\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n const el = container.querySelector<HTMLElement>(\n `[data-merge-tag-index=\"${highlightedIndex.value}\"]`,\n );\n el?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction jumpToGroup(group: string): void {\n // Expand the group if it was collapsed — otherwise scrolling reveals\n // only the header, which is confusing for a \"jump to\" affordance.\n if (collapsedGroups.value.has(group)) {\n const next = new Set(collapsedGroups.value);\n next.delete(group);\n collapsedGroups.value = next;\n }\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n // Sum the height of every child rendered BEFORE the target header.\n // Avoids two browser quirks:\n // - `scrollIntoView({ block: \"start\" })` short-circuits when the\n // element is currently sticky-pinned at top.\n // - `offsetTop` historically misreported on sticky elements in some\n // Chromium versions; offsetHeight on each in-flow child is stable.\n // Each child is a top-level DOM row (header button or tag button),\n // and there are at most a few dozen, so the linear scan is cheap.\n let targetScrollTop = 0;\n let found = false;\n for (const child of Array.from(container.children) as HTMLElement[]) {\n if (\n child.dataset.testid === \"merge-tag-picker-group-header\" &&\n child.dataset.groupName === group\n ) {\n found = true;\n break;\n }\n targetScrollTop += child.offsetHeight;\n }\n if (!found) return;\n container.scrollTo({ top: targetScrollTop, behavior: \"smooth\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const tag = visibleTags.value[highlightedIndex.value];\n if (tag) selectTag(tag);\n }\n // Esc is forwarded by TplModal via its own keydown→close path.\n}\n\nfunction activeOptionId(): string | undefined {\n if (visibleTags.value.length === 0) return undefined;\n return `${listId}-opt-${highlightedIndex.value}`;\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\n\n// --- Empty states ---\n// Distinguish two cases so the messaging is honest:\n// - the consumer configured zero tags (defensive — button shouldn't even\n// render in that case but a programmatic open() should still degrade)\n// - the active search matched nothing\n//\n// `filteredTags` (NOT `visibleTags`) is the correct signal for \"no\n// results\" — visibleTags also excludes tags inside collapsed groups, so\n// collapsing every group would otherwise falsely trigger the empty\n// state and hide the headers the user wants to see.\nconst isEmptyConfig = computed(() => picker.tags.value.length === 0);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && filteredTags.value.length === 0,\n);\n\n// --- Pill row visibility ---\n// Pills jump-link to group headers; they only make sense when there are\n// at least 2 groups AND the user isn't currently searching (search\n// collapses the grouped view to a flat list, so the pills' targets\n// disappear).\nconst showPillRow = computed(\n () => hasGroups.value && groupOrder.value.length > 1 && !searchActive.value,\n);\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"merge-tag-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <!-- Header -->\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ modalTitle }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.mergeTag.picker.close\"\n data-testid=\"merge-tag-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <!-- Search -->\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.mergeTag.picker.searchPlaceholder\"\n :aria-label=\"t.mergeTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"merge-tag-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <!-- Group pills — visible only when grouping is active and the\n user isn't searching. Click a pill to jump (and expand) the\n matching group. Horizontally scrollable so a long group list\n degrades gracefully. -->\n <div\n v-if=\"showPillRow\"\n class=\"tpl:flex tpl:gap-1.5 tpl:overflow-x-auto tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2\"\n data-testid=\"merge-tag-picker-group-pills\"\n >\n <button\n v-for=\"group in groupOrder\"\n :key=\"group\"\n type=\"button\"\n class=\"tpl:flex tpl:flex-shrink-0 tpl:cursor-pointer tpl:items-center tpl:rounded-full tpl:border tpl:border-[var(--tpl-border)] tpl:bg-transparent tpl:px-2.5 tpl:py-0.5 tpl:text-[10px] tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n data-testid=\"merge-tag-picker-group-pill\"\n :data-group-name=\"group\"\n @click=\"jumpToGroup(group)\"\n >\n {{ group }}\n </button>\n </div>\n\n <!-- Body / list -->\n <!-- `position: relative` makes this the offsetParent for the sticky\n group headers below, so `header.offsetTop` reliably reports each\n header's natural in-flow position. jumpToGroup() depends on this\n — see the comment in jumpToGroup() for why scrollIntoView isn't\n sufficient. -->\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"modalTitle\"\n data-testid=\"merge-tag-picker-list\"\n >\n <template v-if=\"isEmptyConfig\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.empty }}\n </div>\n </template>\n <template v-else-if=\"isNoResults\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.noResults }}\n </div>\n </template>\n <template v-else>\n <template v-for=\"(row, rowIndex) in rows\" :key=\"rowIndex\">\n <button\n v-if=\"row.kind === 'header'\"\n :ref=\"(el) => setHeaderRef(row.group, el)\"\n type=\"button\"\n :aria-expanded=\"!isCollapsed(row.group)\"\n :aria-controls=\"listId\"\n class=\"tpl:sticky tpl:top-0 tpl:z-10 tpl:flex tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-1.5 tpl:border-none tpl:bg-[var(--tpl-bg-elevated)] tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-left tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)]\"\n data-testid=\"merge-tag-picker-group-header\"\n :data-group-name=\"row.group\"\n :data-group-collapsed=\"isCollapsed(row.group) ? 'true' : 'false'\"\n @click=\"toggleGroup(row.group)\"\n >\n <ChevronDown\n :size=\"12\"\n :stroke-width=\"2\"\n class=\"tpl:transition-transform\"\n :class=\"isCollapsed(row.group) ? 'tpl:-rotate-90' : ''\"\n />\n <span>{{ row.group }}</span>\n <span class=\"tpl:ml-1 tpl:font-normal\">\n ({{\n format(t.mergeTag.picker.groupCount, { count: row.count })\n }})\n </span>\n </button>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-merge-tag-index=\"row.index\"\n :data-merge-tag-value=\"row.tag.value\"\n :aria-current=\"\n row.tag.value === picker.current.value?.value\n ? 'true'\n : undefined\n \"\n :title=\"rowTitle(row.tag)\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"merge-tag-picker-item\"\n @mousemove=\"setHighlight(row.index)\"\n @click=\"selectTag(row.tag)\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.tag.label\n }}</span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.value }}\n </span>\n <span\n v-if=\"row.tag.description\"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.description }}\n </span>\n <!-- What the previews will render in Sample mode, so an author\n knows before inserting. Shown only when configured. -->\n <span\n v-if=\"row.tag.sample !== undefined\"\n data-testid=\"merge-tag-picker-sample\"\n class=\"tpl:line-clamp-1 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n format(t.mergeTag.picker.sample, { sample: row.tag.sample })\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n inject,\n nextTick,\n ref,\n watch,\n type ComponentPublicInstance,\n} from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { ChevronDown, Search, X } from \"@lucide/vue\";\nimport type { MergeTag } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n MERGE_TAG_PICKER_KEY,\n MERGE_TAG_SHOW_RAW_VALUE_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\n\n// Picker singleton — provided by useEditorCore. We require it explicitly so\n// the modal is unmountable only in a non-editor context (which we don't\n// support). `requireInject` throws a clear message rather than letting a\n// silent inject default mask the misuse.\nconst picker = requireInject(MERGE_TAG_PICKER_KEY, \"MergeTagPickerModal\");\nconst { t, format } = useI18n();\n\n// Theming — same pattern as every other OSS panel (ParagraphToolbar,\n// RichTextLinkDialog). The panel carries the `tpl` token class, so it must\n// re-establish the theme locally: `data-tpl-theme` selects the dark token\n// block, and the inline `themeStyles` apply the consumer's `theme` config\n// overrides. Without these the base `.tpl` rule shadows both with light\n// defaults and the picker ignores dark mode + custom theme colors.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\nconst showRawValue = inject(MERGE_TAG_SHOW_RAW_VALUE_KEY, true);\n\n// Replacing an existing tag rather than inserting a new one. Drives the title\n// and which row starts highlighted.\nconst isChanging = computed(() => picker.current.value !== null);\n\nconst modalTitle = computed(() =>\n isChanging.value ? t.mergeTag.picker.changeTitle : t.mergeTag.picker.title,\n);\n\n/**\n * A row's native tooltip. The description alone when the consumer hid raw\n * tokens — the picker is a list of labels, so leaking the token here would\n * defeat `showRawValue` on the one surface that exists to choose tags.\n */\nfunction rowTitle(tag: MergeTag): string | undefined {\n if (!showRawValue) return tag.description || undefined;\n return tag.description ? `${tag.value} — ${tag.description}` : tag.value;\n}\n\n// --- Search ---\nconst rawSearch = ref(\"\");\n// 200ms debounce keeps filtering responsive at 1000+ tags. The raw value\n// drives the input element (so typing feels instant); the filter reads\n// the debounced copy.\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-merge-tag-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\n// --- Highlight (keyboard nav state) ---\nconst highlightedIndex = ref(0);\n\n// --- Grouping mode ---\n// Active only when at least one tag carries `group`. When inactive, the\n// list renders flat with no headers (not even \"Other\"). The plan locks\n// this down in \"Decisions locked in\" #7.\nconst hasGroups = computed(() =>\n picker.tags.value.some((tag) => Boolean(tag.group)),\n);\n\n// --- Collapsed groups (by label) ---\n// Reset on every modal open so each session starts with all groups\n// visible. Persistence across opens would surprise users who expanded\n// in a previous edit; the cost of re-collapsing is one click.\nconst collapsedGroups = ref<Set<string>>(new Set());\nfunction isCollapsed(group: string): boolean {\n return collapsedGroups.value.has(group);\n}\nfunction toggleGroup(group: string): void {\n const next = new Set(collapsedGroups.value);\n if (next.has(group)) next.delete(group);\n else next.add(group);\n collapsedGroups.value = next;\n // Re-anchor highlight to the first visible tag — index of a\n // previously-highlighted item may now point elsewhere after the\n // collapse rearranges visibleTags.\n highlightedIndex.value = 0;\n}\n\n// --- Filtered tags ---\n// Case-insensitive substring match against label, value, description.\n// Insertion order is preserved (per decision #9).\nconst filteredTags = computed<MergeTag[]>(() => {\n const query = search.value.trim().toLowerCase();\n if (!query) return picker.tags.value;\n return picker.tags.value.filter((tag) => {\n const haystack = [tag.label, tag.value, tag.description ?? \"\"]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(query);\n });\n});\n\n// --- Group order (insertion order of first appearance) ---\n// Computed against the *full* tags list (not the filtered one) so the\n// pill row stays stable as the user types. The pills represent the\n// configured groupings; filter just adjusts which items are shown.\nconst groupOrder = computed<string[]>(() => {\n if (!hasGroups.value) return [];\n const otherLabel = t.mergeTag.picker.otherGroup;\n const seen = new Set<string>();\n const order: string[] = [];\n for (const tag of picker.tags.value) {\n const key = tag.group ?? otherLabel;\n if (seen.has(key)) continue;\n seen.add(key);\n order.push(key);\n }\n return order;\n});\n\n// --- Rendered rows (header + tag entries) ---\n// Headers are only emitted in grouped mode AND only when there is no\n// active search query (per decisions #6 + #7). Flat-list mode and\n// search-active mode both render a header-less sequence.\n//\n// Collapsed groups still emit their header row (so the header stays\n// clickable), but skip their tag rows entirely — those tags are then\n// absent from `visibleTags` and the highlight skips over them.\ntype Row =\n | { kind: \"header\"; group: string; count: number }\n | { kind: \"tag\"; tag: MergeTag; index: number };\n\nconst rows = computed<Row[]>(() => {\n const tags = filteredTags.value;\n if (!hasGroups.value || searchActive.value) {\n return tags.map((tag, index) => ({ kind: \"tag\", tag, index }));\n }\n\n // Grouped mode: bucket by `group`, ungrouped → \"Other\".\n const otherLabel = t.mergeTag.picker.otherGroup;\n const buckets = new Map<string, MergeTag[]>();\n // Insertion order over the first appearance of each group label.\n const order: string[] = [];\n for (const tag of tags) {\n const key = tag.group ?? otherLabel;\n if (!buckets.has(key)) {\n buckets.set(key, []);\n order.push(key);\n }\n buckets.get(key)!.push(tag);\n }\n\n const result: Row[] = [];\n let tagIndex = 0;\n for (const groupKey of order) {\n const items = buckets.get(groupKey)!;\n result.push({ kind: \"header\", group: groupKey, count: items.length });\n if (collapsedGroups.value.has(groupKey)) continue;\n for (const tag of items) {\n result.push({ kind: \"tag\", tag, index: tagIndex });\n tagIndex++;\n }\n }\n return result;\n});\n\n// Flat list of tag-rows only — used for highlight bookkeeping. Keyboard\n// nav skips headers, so the highlight index addresses this list directly.\nconst visibleTags = computed(() =>\n rows.value.flatMap((row) => (row.kind === \"tag\" ? [row.tag] : [])),\n);\n\n/**\n * Whether the highlight is still waiting to land on the tag being replaced.\n *\n * `search` is debounced, so right after `open()` it can still hold the previous\n * session's query and the row we want may not be in `visibleTags` yet. The flag\n * keeps trying as the list settles, and any deliberate move by the user clears\n * it so a late debounce can't yank the highlight back.\n */\nlet preselectPending = false;\n\nfunction preselectCurrent(candidates: MergeTag[]): boolean {\n const target = picker.current.value;\n if (!target) return false;\n const index = candidates.findIndex((tag) => tag.value === target.value);\n if (index === -1) return false;\n highlightedIndex.value = index;\n return true;\n}\n\nfunction setHighlight(index: number): void {\n preselectPending = false;\n highlightedIndex.value = index;\n}\n\n// --- Lifecycle: focus search + reset state when modal opens ---\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (!isOpen) {\n preselectPending = false;\n return;\n }\n {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n collapsedGroups.value = new Set();\n preselectPending = !preselectCurrent(visibleTags.value);\n // Search input is mounted as part of the same render cycle the\n // modal opens; nextTick guarantees the ref is bound before focus.\n nextTick(() => {\n searchInputRef.value?.focus();\n });\n }\n },\n);\n\n// Keep the highlight inside the visible-tags bounds whenever the\n// filtered list shrinks (e.g. user typed a more specific query).\nwatch(visibleTags, (next) => {\n if (preselectPending && preselectCurrent(next)) {\n preselectPending = false;\n return;\n }\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\n// --- Actions ---\nfunction selectTag(tag: MergeTag): void {\n picker.resolve(tag);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleTags.value.length === 0) return;\n preselectPending = false;\n const next = highlightedIndex.value + delta;\n // Stop at edges (don't wrap) — feels more predictable in a long list.\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleTags.value.length - 1, next),\n );\n scrollHighlightIntoView();\n}\n\nconst listRef = ref<HTMLElement | null>(null);\n// One ref per group header so the pill row can `scrollIntoView` precisely.\n// Bound by callback-ref in the template; cleared (set to null) when Vue\n// unmounts the header during re-render.\nconst headerRefs = ref<Record<string, HTMLElement | null>>({});\n// Vue's callback-ref type widens to Element | ComponentPublicInstance | null\n// because the same ref shape works for both DOM elements and components.\n// Headers are always native buttons, so coerce to HTMLElement once here.\nfunction setHeaderRef(\n group: string,\n el: Element | ComponentPublicInstance | null,\n): void {\n headerRefs.value[group] = (el as HTMLElement | null) ?? null;\n}\n\nfunction scrollHighlightIntoView(): void {\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n const el = container.querySelector<HTMLElement>(\n `[data-merge-tag-index=\"${highlightedIndex.value}\"]`,\n );\n el?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction jumpToGroup(group: string): void {\n // Expand the group if it was collapsed — otherwise scrolling reveals\n // only the header, which is confusing for a \"jump to\" affordance.\n if (collapsedGroups.value.has(group)) {\n const next = new Set(collapsedGroups.value);\n next.delete(group);\n collapsedGroups.value = next;\n }\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n // Sum the height of every child rendered BEFORE the target header.\n // Avoids two browser quirks:\n // - `scrollIntoView({ block: \"start\" })` short-circuits when the\n // element is currently sticky-pinned at top.\n // - `offsetTop` historically misreported on sticky elements in some\n // Chromium versions; offsetHeight on each in-flow child is stable.\n // Each child is a top-level DOM row (header button or tag button),\n // and there are at most a few dozen, so the linear scan is cheap.\n let targetScrollTop = 0;\n let found = false;\n for (const child of Array.from(container.children) as HTMLElement[]) {\n if (\n child.dataset.testid === \"merge-tag-picker-group-header\" &&\n child.dataset.groupName === group\n ) {\n found = true;\n break;\n }\n targetScrollTop += child.offsetHeight;\n }\n if (!found) return;\n container.scrollTo({ top: targetScrollTop, behavior: \"smooth\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const tag = visibleTags.value[highlightedIndex.value];\n if (tag) selectTag(tag);\n }\n // Esc is forwarded by TplModal via its own keydown→close path.\n}\n\nfunction activeOptionId(): string | undefined {\n if (visibleTags.value.length === 0) return undefined;\n return `${listId}-opt-${highlightedIndex.value}`;\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\n\n// --- Empty states ---\n// Distinguish two cases so the messaging is honest:\n// - the consumer configured zero tags (defensive — button shouldn't even\n// render in that case but a programmatic open() should still degrade)\n// - the active search matched nothing\n//\n// `filteredTags` (NOT `visibleTags`) is the correct signal for \"no\n// results\" — visibleTags also excludes tags inside collapsed groups, so\n// collapsing every group would otherwise falsely trigger the empty\n// state and hide the headers the user wants to see.\nconst isEmptyConfig = computed(() => picker.tags.value.length === 0);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && filteredTags.value.length === 0,\n);\n\n// --- Pill row visibility ---\n// Pills jump-link to group headers; they only make sense when there are\n// at least 2 groups AND the user isn't currently searching (search\n// collapses the grouped view to a flat list, so the pills' targets\n// disappear).\nconst showPillRow = computed(\n () => hasGroups.value && groupOrder.value.length > 1 && !searchActive.value,\n);\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"merge-tag-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <!-- Header -->\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ modalTitle }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.mergeTag.picker.close\"\n data-testid=\"merge-tag-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <!-- Search -->\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.mergeTag.picker.searchPlaceholder\"\n :aria-label=\"t.mergeTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"merge-tag-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <!-- Group pills — visible only when grouping is active and the\n user isn't searching. Click a pill to jump (and expand) the\n matching group. Horizontally scrollable so a long group list\n degrades gracefully. -->\n <div\n v-if=\"showPillRow\"\n class=\"tpl:flex tpl:gap-1.5 tpl:overflow-x-auto tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2\"\n data-testid=\"merge-tag-picker-group-pills\"\n >\n <button\n v-for=\"group in groupOrder\"\n :key=\"group\"\n type=\"button\"\n class=\"tpl:flex tpl:flex-shrink-0 tpl:cursor-pointer tpl:items-center tpl:rounded-full tpl:border tpl:border-[var(--tpl-border)] tpl:bg-transparent tpl:px-2.5 tpl:py-0.5 tpl:text-[10px] tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n data-testid=\"merge-tag-picker-group-pill\"\n :data-group-name=\"group\"\n @click=\"jumpToGroup(group)\"\n >\n {{ group }}\n </button>\n </div>\n\n <!-- Body / list -->\n <!-- `position: relative` makes this the offsetParent for the sticky\n group headers below, so `header.offsetTop` reliably reports each\n header's natural in-flow position. jumpToGroup() depends on this\n — see the comment in jumpToGroup() for why scrollIntoView isn't\n sufficient. -->\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"modalTitle\"\n data-testid=\"merge-tag-picker-list\"\n >\n <template v-if=\"isEmptyConfig\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.empty }}\n </div>\n </template>\n <template v-else-if=\"isNoResults\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.noResults }}\n </div>\n </template>\n <template v-else>\n <template v-for=\"(row, rowIndex) in rows\" :key=\"rowIndex\">\n <button\n v-if=\"row.kind === 'header'\"\n :ref=\"(el) => setHeaderRef(row.group, el)\"\n type=\"button\"\n :aria-expanded=\"!isCollapsed(row.group)\"\n :aria-controls=\"listId\"\n class=\"tpl:sticky tpl:top-0 tpl:z-10 tpl:flex tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-1.5 tpl:border-none tpl:bg-[var(--tpl-bg-elevated)] tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-left tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)]\"\n data-testid=\"merge-tag-picker-group-header\"\n :data-group-name=\"row.group\"\n :data-group-collapsed=\"isCollapsed(row.group) ? 'true' : 'false'\"\n @click=\"toggleGroup(row.group)\"\n >\n <ChevronDown\n :size=\"12\"\n :stroke-width=\"2\"\n class=\"tpl:transition-transform\"\n :class=\"isCollapsed(row.group) ? 'tpl:-rotate-90' : ''\"\n />\n <span>{{ row.group }}</span>\n <span class=\"tpl:ml-1 tpl:font-normal\">\n ({{\n format(t.mergeTag.picker.groupCount, { count: row.count })\n }})\n </span>\n </button>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-merge-tag-index=\"row.index\"\n :data-merge-tag-value=\"row.tag.value\"\n :aria-current=\"\n row.tag.value === picker.current.value?.value\n ? 'true'\n : undefined\n \"\n :title=\"rowTitle(row.tag)\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"merge-tag-picker-item\"\n @mousemove=\"setHighlight(row.index)\"\n @click=\"selectTag(row.tag)\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.tag.label\n }}</span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.value }}\n </span>\n <span\n v-if=\"row.tag.description\"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.description }}\n </span>\n <!-- What the previews will render in Sample mode, so an author\n knows before inserting. Shown only when configured. -->\n <span\n v-if=\"row.tag.sample !== undefined\"\n data-testid=\"merge-tag-picker-sample\"\n class=\"tpl:line-clamp-1 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n format(t.mergeTag.picker.sample, { sample: row.tag.sample })\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n getLogicMergeTagKeyword,\n isLogicMergeTagValue,\n type SyntaxPreset,\n} from \"@templatical/types\";\nimport { computed } from \"vue\";\n\n// Small outlined keyword chip (IF, ENDIF, FOR…) shown next to a tag in the\n// merge tag picker and the typing-autocomplete list. It marks a configured\n// tag whose `value` is a logic tag rather than a data tag, so authors can\n// tell at a glance which entries insert control flow. The visual mirrors the\n// on-canvas logic badge (outlined, primary color) for consistency. Renders\n// nothing when the value isn't logic-shaped, so callers can drop it into any\n// row unconditionally.\nconst props = defineProps<{ value: string; syntax: SyntaxPreset }>();\n\nconst isLogic = computed(() => isLogicMergeTagValue(props.value, props.syntax));\nconst keyword = computed(() =>\n getLogicMergeTagKeyword(props.value, props.syntax),\n);\n</script>\n\n<template>\n <span\n v-if=\"isLogic\"\n class=\"tpl:inline-flex tpl:flex-shrink-0 tpl:items-center tpl:rounded tpl:px-1.5 tpl:py-0.5 tpl:text-[10px] tpl:leading-none tpl:font-bold tpl:tracking-wide tpl:uppercase\"\n style=\"\n border: 1.5px solid\n color-mix(in srgb, var(--tpl-primary) 50%, transparent);\n color: var(--tpl-primary);\n \"\n data-testid=\"merge-tag-logic-badge\"\n :data-logic-keyword=\"keyword\"\n >\n {{ keyword }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport {\n getLogicMergeTagKeyword,\n isLogicMergeTagValue,\n type SyntaxPreset,\n} from \"@templatical/types\";\nimport { computed } from \"vue\";\n\n// Small outlined keyword chip (IF, ENDIF, FOR…) shown next to a tag in the\n// merge tag picker and the typing-autocomplete list. It marks a configured\n// tag whose `value` is a logic tag rather than a data tag, so authors can\n// tell at a glance which entries insert control flow. The visual mirrors the\n// on-canvas logic badge (outlined, primary color) for consistency. Renders\n// nothing when the value isn't logic-shaped, so callers can drop it into any\n// row unconditionally.\nconst props = defineProps<{ value: string; syntax: SyntaxPreset }>();\n\nconst isLogic = computed(() => isLogicMergeTagValue(props.value, props.syntax));\nconst keyword = computed(() =>\n getLogicMergeTagKeyword(props.value, props.syntax),\n);\n</script>\n\n<template>\n <span\n v-if=\"isLogic\"\n class=\"tpl:inline-flex tpl:flex-shrink-0 tpl:items-center tpl:rounded tpl:px-1.5 tpl:py-0.5 tpl:text-[10px] tpl:leading-none tpl:font-bold tpl:tracking-wide tpl:uppercase\"\n style=\"\n border: 1.5px solid\n color-mix(in srgb, var(--tpl-primary) 50%, transparent);\n color: var(--tpl-primary);\n \"\n data-testid=\"merge-tag-logic-badge\"\n :data-logic-keyword=\"keyword\"\n >\n {{ keyword }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { Search, X } from \"@lucide/vue\";\nimport type { LogicPair, LogicTag, SyntaxPreset } from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport LogicTagBadge from \"./LogicTagBadge.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n LOGIC_TAG_PICKER_KEY,\n MERGE_TAG_SYNTAX_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\nimport type { LogicTagPickerResult } from \"../composables/useLogicTagPicker\";\n\n// Picker singleton — provided by useEditorCore. Required explicitly so the\n// modal only functions inside an editor context.\nconst picker = requireInject(LOGIC_TAG_PICKER_KEY, \"LogicTagPickerModal\");\nconst { t } = useI18n();\nconst syntax = inject<SyntaxPreset>(\n MERGE_TAG_SYNTAX_KEY,\n SYNTAX_PRESETS.liquid,\n);\n\n// Theming — same pattern as MergeTagPickerModal: re-establish the theme\n// locally so the `.tpl` token root resolves dark mode + consumer overrides.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\n\nconst rawSearch = ref(\"\");\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-logic-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\nconst highlightedIndex = ref(0);\n\nfunction matches(haystackParts: (string | undefined)[]): boolean {\n const query = search.value.trim().toLowerCase();\n if (!query) return true;\n return haystackParts.filter(Boolean).join(\" \").toLowerCase().includes(query);\n}\n\nconst filteredTags = computed<LogicTag[]>(() =>\n picker.tags.value.filter((tag) =>\n matches([tag.label, tag.value, tag.description]),\n ),\n);\nconst filteredPairs = computed<LogicPair[]>(() =>\n picker.pairs.value.filter((pair) =>\n matches([pair.label, pair.before, pair.after, pair.description]),\n ),\n);\n\n// Tags and pairs share one grouped list: a `group` section holds both its\n// standalone tags and its open/close pairs, so a group used by both (e.g.\n// \"Conditions\") renders once instead of appearing separately for each kind.\n// The badge shape — one pill for a tag, two for a pair — signals\n// insert-vs-wrap per row.\ntype Entry =\n | { kind: \"tag\"; tag: LogicTag; group?: string }\n | { kind: \"pair\"; pair: LogicPair; group?: string };\n\n// Pairs first, then standalone tags, so within a shared group the wrapping\n// constructs (e.g. If VIP) sort ahead of single tokens (e.g. Else). Group\n// order follows first appearance across this combined sequence.\nconst filteredEntries = computed<Entry[]>(() => [\n ...filteredPairs.value.map((pair): Entry => ({\n kind: \"pair\",\n pair,\n group: pair.group,\n })),\n ...filteredTags.value.map((tag): Entry => ({\n kind: \"tag\",\n tag,\n group: tag.group,\n })),\n]);\n\nconst hasGroups = computed(\n () =>\n picker.tags.value.some((tag) => Boolean(tag.group)) ||\n picker.pairs.value.some((pair) => Boolean(pair.group)),\n);\n\n// Rows drive rendering; `items` is the parallel flat list of selectable\n// entries in render order, so `highlightedIndex` (keyboard nav) maps 1:1.\ntype Row =\n | { kind: \"header\"; label: string }\n | { kind: \"tag\"; tag: LogicTag; index: number }\n | { kind: \"pair\"; pair: LogicPair; index: number };\n\nfunction bucket(entries: Entry[]): [string, Entry[]][] {\n const otherLabel = t.logicTag.picker.otherGroup;\n const map = new Map<string, Entry[]>();\n const order: string[] = [];\n for (const entry of entries) {\n const key = entry.group ?? otherLabel;\n if (!map.has(key)) {\n map.set(key, []);\n order.push(key);\n }\n map.get(key)!.push(entry);\n }\n return order.map((key) => [key, map.get(key)!]);\n}\n\nconst built = computed(() => {\n const rows: Row[] = [];\n const items: LogicTagPickerResult[] = [];\n let idx = 0;\n\n const pushEntry = (entry: Entry): void => {\n if (entry.kind === \"tag\") {\n rows.push({ kind: \"tag\", tag: entry.tag, index: idx });\n items.push(entry.tag);\n } else {\n rows.push({ kind: \"pair\", pair: entry.pair, index: idx });\n items.push(entry.pair);\n }\n idx++;\n };\n\n const entries = filteredEntries.value;\n if (searchActive.value || !hasGroups.value) {\n // Flat list: search flattens groups (matches the merge-tag picker), and\n // an ungrouped config has no headers to render.\n for (const entry of entries) pushEntry(entry);\n } else {\n for (const [group, groupEntries] of bucket(entries)) {\n rows.push({ kind: \"header\", label: group });\n for (const entry of groupEntries) pushEntry(entry);\n }\n }\n\n return { rows, items };\n});\n\nconst visibleItems = computed(() => built.value.items);\n\nconst isEmptyConfig = computed(\n () => picker.tags.value.length === 0 && picker.pairs.value.length === 0,\n);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && visibleItems.value.length === 0,\n);\n\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (isOpen) {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n nextTick(() => searchInputRef.value?.focus());\n }\n },\n);\n\nwatch(visibleItems, (next) => {\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\nconst listRef = ref<HTMLElement | null>(null);\n\nfunction selectItem(item: LogicTagPickerResult): void {\n picker.resolve(item);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleItems.value.length === 0) return;\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleItems.value.length - 1, highlightedIndex.value + delta),\n );\n nextTick(() => {\n listRef.value\n ?.querySelector<HTMLElement>(\n `[data-logic-index=\"${highlightedIndex.value}\"]`,\n )\n ?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const item = visibleItems.value[highlightedIndex.value];\n if (item) selectItem(item);\n }\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\nfunction activeOptionId(): string | undefined {\n return visibleItems.value.length === 0\n ? undefined\n : `${listId}-opt-${highlightedIndex.value}`;\n}\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"logic-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.logicTag.picker.title }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.logicTag.picker.close\"\n data-testid=\"logic-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.logicTag.picker.searchPlaceholder\"\n :aria-label=\"t.logicTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"logic-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"t.logicTag.picker.title\"\n data-testid=\"logic-picker-list\"\n >\n <div\n v-if=\"isEmptyConfig\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.empty }}\n </div>\n <div\n v-else-if=\"isNoResults\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.noResults }}\n </div>\n <template v-else>\n <template v-for=\"(row, rowIndex) in built.rows\" :key=\"rowIndex\">\n <div\n v-if=\"row.kind === 'header'\"\n class=\"tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-header\"\n :data-group-name=\"row.label\"\n >\n {{ row.label }}\n </div>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-logic-index=\"row.index\"\n :data-logic-kind=\"row.kind\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"logic-picker-item\"\n @mousemove=\"highlightedIndex = row.index\"\n @click=\"selectItem(row.kind === 'tag' ? row.tag : row.pair)\"\n >\n <span\n class=\"tpl:flex tpl:w-full tpl:items-center tpl:justify-between tpl:gap-2\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.kind === \"tag\" ? row.tag.label : row.pair.label\n }}</span>\n <span\n v-if=\"row.kind === 'tag'\"\n class=\"tpl:flex tpl:items-center\"\n >\n <LogicTagBadge :value=\"row.tag.value\" :syntax=\"syntax\" />\n </span>\n <span v-else class=\"tpl:flex tpl:items-center tpl:gap-1\">\n <LogicTagBadge :value=\"row.pair.before\" :syntax=\"syntax\" />\n <span class=\"tpl:text-[var(--tpl-text-dim)]\">…</span>\n <LogicTagBadge :value=\"row.pair.after\" :syntax=\"syntax\" />\n </span>\n </span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.value\n : `${row.pair.before} … ${row.pair.after}`\n }}\n </span>\n <span\n v-if=\"\n (row.kind === 'tag'\n ? row.tag.description\n : row.pair.description) as string | undefined\n \"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.description\n : row.pair.description\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { Search, X } from \"@lucide/vue\";\nimport type { LogicPair, LogicTag, SyntaxPreset } from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport LogicTagBadge from \"./LogicTagBadge.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n LOGIC_TAG_PICKER_KEY,\n MERGE_TAG_SYNTAX_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\nimport type { LogicTagPickerResult } from \"../composables/useLogicTagPicker\";\n\n// Picker singleton — provided by useEditorCore. Required explicitly so the\n// modal only functions inside an editor context.\nconst picker = requireInject(LOGIC_TAG_PICKER_KEY, \"LogicTagPickerModal\");\nconst { t } = useI18n();\nconst syntax = inject<SyntaxPreset>(\n MERGE_TAG_SYNTAX_KEY,\n SYNTAX_PRESETS.liquid,\n);\n\n// Theming — same pattern as MergeTagPickerModal: re-establish the theme\n// locally so the `.tpl` token root resolves dark mode + consumer overrides.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\n\nconst rawSearch = ref(\"\");\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-logic-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\nconst highlightedIndex = ref(0);\n\nfunction matches(haystackParts: (string | undefined)[]): boolean {\n const query = search.value.trim().toLowerCase();\n if (!query) return true;\n return haystackParts.filter(Boolean).join(\" \").toLowerCase().includes(query);\n}\n\nconst filteredTags = computed<LogicTag[]>(() =>\n picker.tags.value.filter((tag) =>\n matches([tag.label, tag.value, tag.description]),\n ),\n);\nconst filteredPairs = computed<LogicPair[]>(() =>\n picker.pairs.value.filter((pair) =>\n matches([pair.label, pair.before, pair.after, pair.description]),\n ),\n);\n\n// Tags and pairs share one grouped list: a `group` section holds both its\n// standalone tags and its open/close pairs, so a group used by both (e.g.\n// \"Conditions\") renders once instead of appearing separately for each kind.\n// The badge shape — one pill for a tag, two for a pair — signals\n// insert-vs-wrap per row.\ntype Entry =\n | { kind: \"tag\"; tag: LogicTag; group?: string }\n | { kind: \"pair\"; pair: LogicPair; group?: string };\n\n// Pairs first, then standalone tags, so within a shared group the wrapping\n// constructs (e.g. If VIP) sort ahead of single tokens (e.g. Else). Group\n// order follows first appearance across this combined sequence.\nconst filteredEntries = computed<Entry[]>(() => [\n ...filteredPairs.value.map((pair): Entry => ({\n kind: \"pair\",\n pair,\n group: pair.group,\n })),\n ...filteredTags.value.map((tag): Entry => ({\n kind: \"tag\",\n tag,\n group: tag.group,\n })),\n]);\n\nconst hasGroups = computed(\n () =>\n picker.tags.value.some((tag) => Boolean(tag.group)) ||\n picker.pairs.value.some((pair) => Boolean(pair.group)),\n);\n\n// Rows drive rendering; `items` is the parallel flat list of selectable\n// entries in render order, so `highlightedIndex` (keyboard nav) maps 1:1.\ntype Row =\n | { kind: \"header\"; label: string }\n | { kind: \"tag\"; tag: LogicTag; index: number }\n | { kind: \"pair\"; pair: LogicPair; index: number };\n\nfunction bucket(entries: Entry[]): [string, Entry[]][] {\n const otherLabel = t.logicTag.picker.otherGroup;\n const map = new Map<string, Entry[]>();\n const order: string[] = [];\n for (const entry of entries) {\n const key = entry.group ?? otherLabel;\n if (!map.has(key)) {\n map.set(key, []);\n order.push(key);\n }\n map.get(key)!.push(entry);\n }\n return order.map((key) => [key, map.get(key)!]);\n}\n\nconst built = computed(() => {\n const rows: Row[] = [];\n const items: LogicTagPickerResult[] = [];\n let idx = 0;\n\n const pushEntry = (entry: Entry): void => {\n if (entry.kind === \"tag\") {\n rows.push({ kind: \"tag\", tag: entry.tag, index: idx });\n items.push(entry.tag);\n } else {\n rows.push({ kind: \"pair\", pair: entry.pair, index: idx });\n items.push(entry.pair);\n }\n idx++;\n };\n\n const entries = filteredEntries.value;\n if (searchActive.value || !hasGroups.value) {\n // Flat list: search flattens groups (matches the merge-tag picker), and\n // an ungrouped config has no headers to render.\n for (const entry of entries) pushEntry(entry);\n } else {\n for (const [group, groupEntries] of bucket(entries)) {\n rows.push({ kind: \"header\", label: group });\n for (const entry of groupEntries) pushEntry(entry);\n }\n }\n\n return { rows, items };\n});\n\nconst visibleItems = computed(() => built.value.items);\n\nconst isEmptyConfig = computed(\n () => picker.tags.value.length === 0 && picker.pairs.value.length === 0,\n);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && visibleItems.value.length === 0,\n);\n\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (isOpen) {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n nextTick(() => searchInputRef.value?.focus());\n }\n },\n);\n\nwatch(visibleItems, (next) => {\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\nconst listRef = ref<HTMLElement | null>(null);\n\nfunction selectItem(item: LogicTagPickerResult): void {\n picker.resolve(item);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleItems.value.length === 0) return;\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleItems.value.length - 1, highlightedIndex.value + delta),\n );\n nextTick(() => {\n listRef.value\n ?.querySelector<HTMLElement>(\n `[data-logic-index=\"${highlightedIndex.value}\"]`,\n )\n ?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const item = visibleItems.value[highlightedIndex.value];\n if (item) selectItem(item);\n }\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\nfunction activeOptionId(): string | undefined {\n return visibleItems.value.length === 0\n ? undefined\n : `${listId}-opt-${highlightedIndex.value}`;\n}\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"logic-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.logicTag.picker.title }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.logicTag.picker.close\"\n data-testid=\"logic-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.logicTag.picker.searchPlaceholder\"\n :aria-label=\"t.logicTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"logic-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"t.logicTag.picker.title\"\n data-testid=\"logic-picker-list\"\n >\n <div\n v-if=\"isEmptyConfig\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.empty }}\n </div>\n <div\n v-else-if=\"isNoResults\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.noResults }}\n </div>\n <template v-else>\n <template v-for=\"(row, rowIndex) in built.rows\" :key=\"rowIndex\">\n <div\n v-if=\"row.kind === 'header'\"\n class=\"tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-header\"\n :data-group-name=\"row.label\"\n >\n {{ row.label }}\n </div>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-logic-index=\"row.index\"\n :data-logic-kind=\"row.kind\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"logic-picker-item\"\n @mousemove=\"highlightedIndex = row.index\"\n @click=\"selectItem(row.kind === 'tag' ? row.tag : row.pair)\"\n >\n <span\n class=\"tpl:flex tpl:w-full tpl:items-center tpl:justify-between tpl:gap-2\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.kind === \"tag\" ? row.tag.label : row.pair.label\n }}</span>\n <span\n v-if=\"row.kind === 'tag'\"\n class=\"tpl:flex tpl:items-center\"\n >\n <LogicTagBadge :value=\"row.tag.value\" :syntax=\"syntax\" />\n </span>\n <span v-else class=\"tpl:flex tpl:items-center tpl:gap-1\">\n <LogicTagBadge :value=\"row.pair.before\" :syntax=\"syntax\" />\n <span class=\"tpl:text-[var(--tpl-text-dim)]\">…</span>\n <LogicTagBadge :value=\"row.pair.after\" :syntax=\"syntax\" />\n </span>\n </span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.value\n : `${row.pair.before} … ${row.pair.after}`\n }}\n </span>\n <span\n v-if=\"\n (row.kind === 'tag'\n ? row.tag.description\n : row.pair.description) as string | undefined\n \"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.description\n : row.pair.description\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n defineAsyncComponent,\n onMounted,\n onUnmounted,\n provide,\n ref,\n toRaw,\n watch,\n} from \"vue\";\nimport type { TemplaticalEditorConfig } from \"./index\";\nimport { useEditor } from \"@templatical/core\";\nimport type {\n Block,\n MergeTagsConfig,\n Template,\n TemplateContent,\n UiTheme,\n} from \"@templatical/types\";\nimport { cloneBlock, safeClone } from \"@templatical/types\";\n// Type-only, so no cloud module is statically reachable from the OSS entry —\n// see `cloud/runtime.ts` for why the seam is shaped this way.\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport { useEditorCore } from \"./composables/useEditorCore\";\nimport { useCollaborationFeature } from \"./composables/useCollaborationFeature\";\nimport { useCommentsFeature } from \"./composables/useCommentsFeature\";\nimport { useAiFeature } from \"./composables/useAiFeature\";\nimport { toAiMergeTags } from \"./utils/aiMergeTags\";\nimport { useMediaFeature } from \"./composables/useMediaFeature\";\nimport { useSavedBlocksFeature } from \"./composables/useSavedBlocksFeature\";\nimport { useTemplatesFeature } from \"./composables/useTemplatesFeature\";\nimport { useTestEmailFeature } from \"./composables/useTestEmailFeature\";\nimport { useVersionHistoryFeature } from \"./composables/useVersionHistoryFeature\";\nimport { useSmallScreenNotice } from \"./composables/useSmallScreenNotice\";\nimport { useScrollToBlock } from \"./composables/useScrollToBlock\";\nimport { resolveAutoSave } from \"./types/auto-save\";\nimport { effectiveAltMaxLength } from \"./utils/aiFixableRules\";\nimport { resolveLintOptions } from \"./utils/resolveLintOptions\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\nimport { insertBlockAtSelection } from \"./utils/insertBlockAtSelection\";\nimport { withCollaborativeSave } from \"./utils/withCollaborativeSave\";\nimport { logger } from \"./utils/logger\";\nimport {\n normalizeRemoteOperations,\n withNormalizedContentWrites,\n withNormalizedTemplateLoads,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport type { Translations } from \"./i18n\";\nimport type { EditorCapabilities } from \"./types/editor-capabilities\";\nimport type { UseFontsReturn } from \"./composables/useFonts\";\nimport { AI_FEATURE_KEY, SIZE_CHECK_KEY } from \"./keys\";\n\nimport { RotateCcw } from \"@lucide/vue\";\nimport { warningBtnCompactClass } from \"./constants/styleConstants\";\nimport Canvas from \"./components/Canvas.vue\";\nimport CustomBlockStylesheets from \"./components/CustomBlockStylesheets.vue\";\nimport Sidebar from \"./components/Sidebar.vue\";\nimport RightSidebar from \"./components/RightSidebar.vue\";\nimport type { RightSidebarTab } from \"./components/RightSidebar.vue\";\nimport SmallScreenNotice from \"./components/SmallScreenNotice.vue\";\nimport EditorFooter from \"./components/EditorFooter.vue\";\nimport EditorHeader from \"./components/EditorHeader.vue\";\nimport MergeTagModeToggle from \"./components/MergeTagModeToggle.vue\";\nimport MergeTagPickerModal from \"./components/MergeTagPickerModal.vue\";\nimport LogicTagPickerModal from \"./components/LogicTagPickerModal.vue\";\nimport \"./styles/index.css\";\n\nconst props = defineProps<{\n config: TemplaticalEditorConfig;\n translations: Translations;\n fontsManager: UseFontsReturn;\n /**\n * Shadow root the editor is mounted into. Supplied by `init()` when\n * `shadowDom: true`; undefined in light-DOM mode. Passed through to\n * `useEditorCore` so shadow-DOM-aware composables can resolve the\n * effective root via `EDITOR_ROOT_KEY`.\n */\n shadowRoot?: ShadowRoot;\n /**\n * Cloud's adapter wiring, supplied only by `initCloud()`.\n *\n * There is **one** editor component. Cloud is a set of providers on\n * `config` plus this runtime, which exists purely for the handful of\n * composables that must run at a specific point inside this `setup()` —\n * collaboration before the history interceptor, the lint save-gate after\n * `useEditorCore`. Everything else it contributes arrives through the\n * ordinary config keys an OSS consumer would fill in themselves.\n */\n cloud?: CloudRuntime;\n /**\n * Render the current template to MJML, for `testEmail`'s `includeMjml` option.\n *\n * Supplied by the entry point, which owns the resolution ladder behind\n * `editor.toMjml()` — a consumer's `render.toMjml` first, the bundled renderer\n * otherwise. Rendering here instead would attach a message the send pipeline\n * never produces, which is the one thing a test email exists to rule out.\n *\n * Absent means no MJML: a directly-mounted editor has no entry point to ask.\n */\n renderMjml?: () => Promise<string>;\n renderHtml?: () => Promise<string>;\n canRenderHtml?: () => boolean;\n /** Whether {@link renderMjml} reaches the bundled `@templatical/renderer`. */\n usesLocalRenderer?: () => boolean;\n}>();\n\nprovide(SIZE_CHECK_KEY, {\n renderHtml: () =>\n props.renderHtml?.() ??\n Promise.reject(new Error(\"HTML rendering is unavailable\")),\n canRenderHtml: () => props.canRenderHtml?.() ?? false,\n cloud: !!props.cloud,\n options: props.config.lint ?? {},\n});\n\n// The fourth place consumer content enters (the other three are the entry\n// points in `index.ts`: the mount seed, `setContent` and `create`). A template\n// fetched from the store never passes through the public API — core assigns it\n// to state itself — so the provider is wrapped here, on its way in. Wrapping\n// rather than normalizing after the load resolves is what keeps the load from\n// registering as an edit: core is handed content that is already correct.\n// These getters run when content arrives, after core exists. setMergeTags()\n// replaces core's list, so every incoming path must read that list at call time.\nconst liveMergeTags: MergeTagsConfig = {\n get tags() {\n return core.mergeTags.value;\n },\n get syntax() {\n return core.mergeTagSyntax;\n },\n};\nconst normalizedTemplates = props.config.templates\n ? withNormalizedTemplateLoads(props.config.templates, liveMergeTags)\n : undefined;\n\n// --- Collaboration (opt-in: a collaboration provider and a templates provider) ---\n// Built before `useEditor()`, which reads others' locks from it, and attached\n// right after. A template id is what a session joins, so without a templates\n// provider there is nothing to collaborate on.\nif (props.config.collaboration && !normalizedTemplates) {\n logger.warn(\n \"config.collaboration needs config.templates: collaboration runs on a \" +\n \"loaded template, and only a templates provider loads one. \" +\n \"Collaboration is off.\",\n );\n}\nconst collaboration =\n props.config.collaboration && normalizedTemplates\n ? useCollaborationFeature({\n provider: props.config.collaboration,\n loadTemplate: (id) => normalizedTemplates.load(id),\n user: props.config.user,\n // The same source the load normalizer reads, so a tag arriving in a\n // batch looks the way a loaded one does.\n mergeTags: liveMergeTags,\n onRemoteChange: props.config.onRemoteChange,\n onError: props.config.onError,\n })\n : null;\n\n// With collaboration, content is saved as operations; `save` only renames.\n// A save answers with what is open: the loaded template with the canvas's\n// content, which the backend holds once `settle()` has resolved.\nconst templatesProvider =\n normalizedTemplates && collaboration\n ? withCollaborativeSave(normalizedTemplates, collaboration.core, () => {\n const template = editor.state.template;\n return template\n ? {\n ...(toRaw(template) as Template),\n content: safeClone(toRaw(editor.content.value)),\n }\n : null;\n })\n : normalizedTemplates;\n\n// --- Core editor state ---\nconst editor = useEditor({\n content: props.config.content!,\n // Seeds a *new* template's body font when no `content` was supplied. Only the\n // deleted Cloud core passed this, so `init({ fonts: { defaultFont } })` never\n // reached a blank template.\n defaultFontFamily: props.config.fonts?.defaultFont,\n // Not `props.config.templateDefaults` raw: the editor's own `locale` seeds\n // the template's content language when the consumer left it unset, so a\n // German editor stops producing `<mjml lang=\"en\">` on a fresh template.\n templateDefaults: resolveTemplateDefaults(props.config),\n templates: templatesProvider,\n onError: props.config.onError,\n // Blocks other collaborators hold: they can't be selected here.\n lockedBlocks: collaboration?.locks,\n});\n\ncollaboration?.attach(editor);\n\nconst cloudAttachment = props.cloud ? props.cloud.attach({ editor }) : null;\n\n// --- Templates (opt-in: only when a storage provider is configured) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header's name field, status indicator and save button — and what\n// makes Cmd+S mean \"persist now\".\nconst templates = templatesProvider\n ? useTemplatesFeature({\n provider: templatesProvider,\n editor,\n guardUnsavedChanges: props.config.templates?.unsavedChangesGuard,\n // Cloud's lint save-gate, when there is one. Read through a getter\n // because the gate needs `core.templateLint`, which does not exist yet.\n // Without this the collapse would have silently dropped the server's\n // `accessibility.blockOnError` policy.\n getSaveGate: props.cloud ? () => props.cloud!.getSaveGate() : undefined,\n })\n : null;\n\n// Reported to the consumer regardless of whether a provider is configured: a\n// `beforeunload` guard cannot cover SPA route changes, so an embedder needs this\n// to guard their own router — including when they persist via `onChange`.\nif (props.config.onDirtyChange) {\n watch(\n () => editor.state.isDirty,\n (isDirty) => props.config.onDirtyChange!(isDirty),\n );\n}\n\n// Outer `.tpl` ref — passed to `useEditorCore` so the active-editor\n// tracker can route keyboard shortcuts when two editors share a page.\nconst rootEl = ref<HTMLElement | null>(null);\n\n// --- Saved blocks (opt-in: only when a storage provider is configured) ---\n// Instantiated before `useEditorCore` so its capability can be passed in,\n// which is what lights up the shared save button and sidebar rail.\nconst savedBlocks = props.config.savedBlocks\n ? useSavedBlocksFeature({\n provider: props.config.savedBlocks,\n editor,\n onError: props.config.onError,\n // Cloud's store is plan-gated; a consumer's own store never is.\n isAvailable: props.cloud\n ? () => props.cloud!.isSavedBlocksAvailable()\n : undefined,\n })\n : null;\n\n// Lazily loaded so a consumer without a provider downloads none of the\n// saved-blocks UI. Rendered only when the feature is active.\nconst SavedBlocksPanels = defineAsyncComponent(\n () => import(\"./components/SavedBlocksPanels.vue\"),\n);\n\n// --- Media (opt-in: a provider and/or an `onRequestMedia` override) ---\n// Instantiated before `useEditorCore` so the synthesized function is what\n// gets provided as `ON_REQUEST_MEDIA_KEY`. The modal mounts only on the\n// provider path — a callback-only config never downloads it.\nconst mediaFeature =\n props.config.media || props.config.onRequestMedia\n ? useMediaFeature({\n provider: props.config.media,\n onRequestMedia: props.config.onRequestMedia,\n getTemplateId: () => editor.state.template?.id,\n onError: props.config.onError,\n })\n : null;\n\nconst MediaPanels = defineAsyncComponent(\n () => import(\"./components/MediaPanels.vue\"),\n);\n\n// --- Test email (opt-in: only when a sending provider is configured) ---\n// Created before `useEditorCore` so its capability can be passed in, same as\n// saved blocks.\nconst testEmail = props.config.testEmail\n ? useTestEmailFeature({\n provider: props.config.testEmail,\n getContent: () => editor.content.value,\n renderMjml: props.renderMjml,\n usesLocalRenderer: props.usesLocalRenderer,\n onError: props.config.onError,\n // Cloud folds in the plan feature and \"the template must be saved\", both\n // constraints of *its* sending path rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isTestEmailAvailable()\n : undefined,\n })\n : null;\n\nconst TestEmailPanel = defineAsyncComponent(\n () => import(\"./components/TestEmailPanel.vue\"),\n);\n\n// --- Comments (opt-in: only with a storage provider *and* a `user`) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header trigger and the per-block comment indicators.\n//\n// No `user` means no provider call at all — an unattributable comment is worse\n// than no comment feature, so `isAvailable` stays false and nothing renders.\nconst comments = props.config.comments\n ? useCommentsFeature({\n provider: props.config.comments,\n editor,\n user: props.config.user,\n // Cloud supplies its comments state; the open-source AI feature keeps\n // comments and AI panels exclusive in their shared 360px gutter.\n isOpen: cloudAttachment?.panelState.commentsOpen,\n onError: props.config.onError,\n // Cloud folds in the `commenting` plan feature and \"the template must be\n // saved\", both constraints of *its* store rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isCommentsAvailable()\n : undefined,\n // Cloud anchors a comment to a block in the saved template; a consumer's\n // store accepts whatever anchor it is given.\n isBlockSaved: props.cloud\n ? (blockId: string) => props.cloud!.isBlockSaved(blockId)\n : undefined,\n })\n : null;\n\nconst CommentsPanel = defineAsyncComponent(\n () => import(\"./components/CommentsPanel.vue\"),\n);\n\n// The AI panels: lazy, mounted only with an `ai` provider; each panel is its\n// own chunk inside.\nconst AiPanels = defineAsyncComponent(\n () => import(\"./components/ai/AiPanels.vue\"),\n);\n\n// --- AI (opt-in: an `ai` provider) ---\n// Built before `useEditorCore` so its capability is in the object core\n// provides. It reads core (the history and the merge tags) through\n// getters, at call time. Its panels are lazy (`AiPanels`); the header button\n// is not, so it renders with the rest of the header (`EditorHeader`).\nconst ai = props.config.ai\n ? useAiFeature({\n provider: props.config.ai,\n editor,\n collaboration,\n history: () => core.history,\n reload: templates\n ? (id, shouldApply) => templates.load(id, shouldApply)\n : null,\n altMaxLength: () =>\n effectiveAltMaxLength(resolveLintOptions(props.config)),\n mergeTags: () => toAiMergeTags(core.mergeTags.value, core.mergeTagSyntax),\n normalize: (ops, content) =>\n normalizeRemoteOperations(ops, content, liveMergeTags),\n commentsOpen: comments?.isOpen ?? null,\n onError: props.config.onError,\n })\n : null;\nif (ai) provide(AI_FEATURE_KEY, ai);\n\n// Lazy: an editor without a collaboration provider never downloads it.\nconst CollaborationNotices = defineAsyncComponent(\n () => import(\"./components/collaboration/CollaborationNotices.vue\"),\n);\n\n// --- Cloud chrome (opt-in: only under `initCloud()`) ---\n// One lazy wrapper for every panel, overlay and modal Cloud adds, plus one for\n// its header controls. Same discipline as `SavedBlocksPanels` / `TestEmailPanel`:\n// an OSS consumer never downloads any of it.\nconst CloudPanels = defineAsyncComponent(\n () => import(\"./cloud/components/CloudPanels.vue\"),\n);\nconst CloudHeaderExtras = defineAsyncComponent(\n () => import(\"./cloud/components/CloudHeaderExtras.vue\"),\n);\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// The header control lives in `EditorHeader`; this is the preview banner, which\n// renders outside the header. Both are lazy.\nconst VersionHistoryPanels = defineAsyncComponent(\n () => import(\"./components/VersionHistoryPanels.vue\"),\n);\n\n// --- Auto-save ---\n// One debounced tick drives everything a consumer can ask for on a content\n// change: the `onChange` notification, and, when `templates.autoSave` is on,\n// the save itself. Sharing a single `useAutoSave` instance keeps the two in\n// step and inherits the pause-during-undo/redo behaviour `useEditorCore` wires\n// up around it. `config.changeDebounce` sets the cadence for both.\nconst autoSaveEnabled = resolveAutoSave(\n props.config.templates?.autoSave,\n false,\n);\nconst isAutoSaving = autoSaveEnabled && templates !== null;\n// The one way autosave can still be inert once a provider exists is its\n// `save` being `false` — a read-only store — which `requestAutoSave()` below\n// already no-ops per tick for; this warning is the only signal the consumer\n// gets. `templates !== null` is redundant with `autoSaveEnabled` at runtime\n// (the provider that enables autosave is the same provider that makes\n// `templates` non-null) but stays as an explicit conjunct so TypeScript can\n// narrow `templates.canSave.value` below without a non-null assertion.\nif (autoSaveEnabled && templates !== null && !templates.canSave.value) {\n logger.warn(\n \"config.templates.autoSave is on but this provider's save is false — \" +\n \"there is nothing to persist to. Give it a real save function, or \" +\n \"use `onChange` to persist the content yourself.\",\n );\n}\n// `changeDebounce` alone does not enable autosave — only `templates.autoSave`\n// does. A config with `changeDebounce` set, a provider present, `autoSave`\n// left unset, and no `onChange` has nothing consuming the timer at all,\n// which reads as intentional `onChange`-only pacing but is easy to reach by\n// mistake. Warn on exactly that combination; `autoSave: false` is a stated\n// decision and must stay silent.\nif (\n props.config.changeDebounce !== undefined &&\n templates !== null &&\n props.config.templates?.autoSave === undefined &&\n !props.config.onChange\n) {\n logger.warn(\n \"config.changeDebounce is set but nothing will use it — \" +\n \"config.templates.autoSave is unset and there is no onChange either, \" +\n \"so the timer has no consumer. Set config.templates.autoSave, or add \" +\n \"onChange, so the debounce takes effect.\",\n );\n}\n\nconst autoSaveOptions =\n props.config.onChange || isAutoSaving\n ? {\n onChange: () => {\n props.config.onChange?.(\n JSON.parse(JSON.stringify(editor.state.content)),\n );\n // `requestAutoSave()` already no-ops without a saveable template, so a\n // read-only provider costs one predicate per tick and nothing else.\n // It is the *ungated* request only in the sense that it never raises a\n // prompt: Cloud's lint gate still refuses it, which is what keeps\n // `accessibility.blockOnError` a policy rather than a manual-save\n // speed bump.\n if (isAutoSaving) templates!.requestAutoSave();\n },\n ...(props.config.changeDebounce !== undefined\n ? { debounce: props.config.changeDebounce }\n : {}),\n }\n : null;\n\n// --- Shared editor core (composables, provides, plugins, keyboard) ---\n// A named object rather than an inline literal: `useVersionHistoryFeature` can\n// only be built after core (it needs history/conditionPreview/autoSave), so its\n// capability is assigned in below, into the very object core provided.\nconst capabilities: EditorCapabilities = {\n ...(savedBlocks ? { savedBlocks: savedBlocks.capability } : {}),\n ...(templates ? { templates: templates.capability } : {}),\n ...(testEmail ? { testEmail: testEmail.capability } : {}),\n ...(comments ? { comments: comments.capability } : {}),\n ...(collaboration ? { collaboration: collaboration.capability } : {}),\n ...(ai ? { ai: ai.capability } : {}),\n};\n\nconst core = useEditorCore({\n editor,\n containerEl: rootEl,\n config: {\n uiTheme: props.config.uiTheme,\n theme: props.config.theme,\n blockDefaults: props.config.blockDefaults,\n templateDefaults: props.config.templateDefaults,\n customBlocks: props.config.customBlocks,\n paletteBlocks: props.config.paletteBlocks,\n htmlBlockPreview: props.config.htmlBlockPreview,\n layout: props.config.layout,\n sectionWrapper: props.config.sectionWrapper,\n colors: props.config.colors,\n templateSettings: props.config.templateSettings,\n mergeTags: props.config.mergeTags,\n logicTags: props.config.logicTags,\n displayConditions: props.config.displayConditions,\n // The synthesized Browse/drop handler. Null when neither a provider nor a\n // callback is configured, which is what keeps image fields URL-only.\n onRequestMedia: mediaFeature?.requestMedia ?? null,\n // Distinct from Browse: a read-only provider still opens the library.\n canDropMedia: mediaFeature?.canDrop ?? null,\n resolvePreview: props.config.resolvePreview,\n resolveImageUrl: props.config.resolveImageUrl,\n lint: resolveLintOptions(props.config),\n // For Intl-built labels (dates), which would otherwise format in the\n // BROWSER's locale and disagree with the translated chrome beside them.\n locale: props.config.locale,\n },\n translations: props.translations,\n fontsManager: props.fontsManager,\n autoSaveOptions,\n capabilities,\n editorRoot: props.shadowRoot,\n history: collaboration?.history,\n});\n\nconst rightSidebarTab = ref<RightSidebarTab>(\"content\");\n\n// Cloud's setup-time wiring that needs `core`: the lint save-gate (reads\n// `core.templateLint`) and the capability entries Cloud contributes — mutated\n// into the very object `useEditorCore` provided, so injecting components see\n// them on first render.\nconst cloudReady =\n props.cloud && cloudAttachment\n ? props.cloud.ready({ core, capabilities })\n : null;\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// Constructed *after* `useEditorCore` because it drives `history` /\n// `conditionPreview` / `autoSave`, which core owns. Its capability is therefore\n// assigned into the object above rather than passed in — same object reference\n// core provided, mutated during setup, so injecting components see it on their\n// first render.\nconst versionHistory = props.config.versionHistory\n ? useVersionHistoryFeature({\n provider: props.config.versionHistory,\n // The fifth content-in path. A stored version holds whatever was written\n // to it, so it can carry bare tokens like any other loaded content, and\n // previewing one would put them on a canvas where every other tag is a\n // chip. Wrapped at `setContent` rather than at the provider, because\n // version content also arrives off the hydrated list and out of the\n // `fetched` cache without touching `get()`.\n editor: withNormalizedContentWrites(editor, liveMergeTags),\n history: core.history,\n conditionPreview: core.conditionPreview,\n autoSave: core.autoSave,\n // A version on the canvas is a preview, not an edit: collaboration stops\n // reading the canvas for it, and a restore re-syncs from the backend.\n collaboration: collaboration\n ? {\n suspend: collaboration.core.suspend,\n resume: collaboration.core.resume,\n catchUp: collaboration.core.catchUp,\n reportReplaceRefused: collaboration.reportReplaceRefused,\n }\n : null,\n // Lets the restore confirmation offer to persist unsaved work instead of\n // only warning about it. Without a templates provider — or with one whose\n // `save` is `false` — there is nowhere to put that work, and the\n // confirmation says so rather than offering an action that can't happen.\n // Cloud additionally refuses while the lint gate would block: stacking a\n // second modal on the confirmation would be worse than saying there is\n // currently nowhere to put the work.\n saveBeforeRestore: templates\n ? {\n canSave: () =>\n templates.canSave.value &&\n !(props.cloud?.getSaveGate()?.shouldBlock.value ?? false),\n save: () => templates.save(\"restore\"),\n }\n : null,\n onError: props.config.onError,\n })\n : null;\n\nif (versionHistory) capabilities.versionHistory = versionHistory.capability;\n\n/**\n * Left/right insets for the canvas body and the footer, which must always agree.\n *\n * Comments and the open-source AI panels widen the right gutter while open.\n */\n/**\n * Whether a 360px feature panel occupies the right-hand gutter.\n *\n * Comments and the open-source AI panels share this gutter; the AI feature\n * keeps their open states mutually exclusive. Cloud also supplies its panel\n * state, which shares the comments ref.\n *\n * Two things read this, and **both must**: the canvas/footer insets below, and\n * `RightSidebar`'s `shifted-left` — the properties panel sits at `right-0` too, so\n * a panel opening over it would swallow every click meant for the panel.\n */\nconst rightPanelOpen = computed(\n () =>\n comments?.isOpen.value === true ||\n (ai !== null && ai.panel.value !== null) ||\n cloudAttachment?.panelState.rightPanelOpen.value === true,\n);\n\nconst bodyInsetClass = computed(() => {\n if (editor.state.previewMode) return \"tpl:left-0 tpl:right-0\";\n return rightPanelOpen.value\n ? \"tpl:left-12 tpl:right-[680px]\"\n : \"tpl:left-12 tpl:right-[320px]\";\n});\n\n// --- Small-screen gate (#235) ---\n// Below ~768px the three-pane chrome can't lay out usably; show a notice\n// instead. Opt out with `config.smallScreenNotice: false`.\nconst { showNotice: showSmallScreenNotice } = useSmallScreenNotice(\n () => props.config.smallScreenNotice,\n);\n\n// --- Lifecycle ---\nonMounted(async () => {\n await props.fontsManager.loadCustomFonts();\n});\n\nonUnmounted(() => {\n props.fontsManager.cleanupFontLinks();\n ai?.destroy();\n props.cloud?.destroy();\n core.destroy();\n});\n\n// --- Public API (accessed via template ref from init()) ---\n// The lifecycle trio comes from the templates feature when one exists, so a\n// programmatic save also drives the header's status. Without a provider it comes\n// straight from core, whose own methods reject with the actionable error.\nconst templateLifecycle = templates ?? editor;\n\nconst scrollToBlock = useScrollToBlock(core.editorRoot);\n\ndefineExpose({\n getContent: () => editor.content.value,\n setContent: (content: TemplateContent) => editor.setContent(content),\n insertBlock: (block: Block): string | null => {\n // The palette is hidden in preview mode, and preview has no selection.\n if (editor.state.previewMode) {\n logger.warn(\"insertBlock() does nothing in preview mode.\");\n return null;\n }\n // A copy with fresh ids throughout, so inserting the same library item\n // twice never puts two blocks, rows or items on the canvas with one id.\n const copy = cloneBlock(block);\n if (!insertBlockAtSelection(editor, copy)) return null;\n scrollToBlock(copy.id);\n return copy.id;\n },\n setTheme: (theme: UiTheme) => editor.setUiTheme(theme),\n setMergeTags: core.setMergeTags,\n isDirty: () => editor.state.isDirty,\n create: templateLifecycle.create,\n load: templateLifecycle.load,\n save: templateLifecycle.save,\n renderCustomBlock: core.registry.renderCustomBlock,\n getCustomBlockStylesheet: (customType: string) =>\n core.registry.getDefinition(customType)?.stylesheet,\n});\n</script>\n\n<template>\n <!-- @dragover/@drop.prevent: a file dropped outside an image drop zone would\n otherwise make the browser navigate to the file:// URL and destroy the\n editor session. Image zones (useImageDrop) handle their own drops; this\n only neutralizes the default action everywhere else (#229). -->\n <div\n ref=\"rootEl\"\n class=\"tpl tpl:relative tpl:h-full\"\n :class=\"{ 'tpl:dark': editor.state.darkMode }\"\n :data-tpl-theme=\"core.resolvedTheme.value\"\n :style=\"core.themeStyles.value\"\n @dragover.prevent\n @drop.prevent\n >\n <!-- Reactive `<style>` tags for custom-block definition stylesheets in\n use. Sits at the top so its rules apply to the canvas below. -->\n <CustomBlockStylesheets />\n <!-- Chrome wrapper — the clip belongs here, never on the root and never\n around `.tpl-popover-root`. Safari paints a `position: fixed`\n descendant clipped to an ancestor's `overflow: hidden` box while still\n resolving its layout against the viewport, so a dialog teleported\n under a clipping ancestor is cut off wherever it extends past the\n container, and its backdrop dims only the container's own area\n (#633). Keeping the clip on this element bounds the header, rails,\n canvas and footer without reaching the popover root, and this box is\n identical to the root's, so everything anchored `absolute` inside\n lands exactly where it would against the root. Locked by\n `tests/popover-root-clip-scope.test.ts`. -->\n <div class=\"tpl:absolute tpl:inset-0 tpl:overflow-hidden\">\n <!-- One header for both entry points. Cloud's own controls arrive through\n the three slots; everything else here is capability-gated, so the same\n markup covers \"no providers at all\" and a fully-wired Cloud session. -->\n <EditorHeader\n :editor=\"editor\"\n :core=\"core\"\n :templates=\"templates\"\n :show-template-name=\"config.templates?.nameField !== false\"\n :test-email=\"testEmail\"\n :version-history=\"versionHistory\"\n :comments=\"comments\"\n :collaboration=\"collaboration\"\n :ai=\"ai\"\n >\n <template v-if=\"cloudAttachment\" #left-extras>\n <CloudHeaderExtras part=\"left\" :cloud=\"cloudAttachment\" />\n </template>\n <template v-if=\"cloudAttachment\" #right-extras>\n <CloudHeaderExtras part=\"right\" :cloud=\"cloudAttachment\" />\n </template>\n </EditorHeader>\n\n <!-- Left sidebar — absolute, below header -->\n <Sidebar v-show=\"!editor.state.previewMode\" />\n\n <!-- Canvas area — absolute, fills remaining space -->\n <div\n class=\"tpl-body tpl:absolute tpl:bottom-0 tpl:overflow-auto tpl:bg-[var(--tpl-canvas-bg)]\"\n style=\"transition: all 300ms cubic-bezier(0.34, 1.56, 0.64, 1)\"\n :class=\"[\n bodyInsetClass,\n versionHistory?.isPreviewing.value ? 'tpl:top-[104px]' : 'tpl:top-14',\n ]\"\n >\n <!-- Preview chrome, floated over the canvas.\n\n A zero-height sticky layer holding one absolutely-positioned,\n canvas-centred **column**. Zero height means the layer contributes no\n space of its own, so nothing here can push the canvas around — which\n is what lets the merge-tag toggle live over the preview instead of in\n the header, whose centre track re-centres on every width change and\n so dragged the Preview button 114.5px sideways each time the toggle\n appeared (#574).\n\n A column rather than two fixed offsets. Both pills are reachable at\n once — the restore pill needs hidden blocks, the toggle needs preview\n mode without a `resolvePreview`, and nothing makes those exclusive —\n so they have to stack. Doing that with a hardcoded second offset put\n the restore pill 48px down even when it rendered alone, which in\n editing mode (where the toggle never shows) dropped it onto the first\n block's content. Flow solves what the offset got wrong: whichever\n pills render sit tight under the header, in order.\n\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div class=\"tpl-preview-overlay tpl:sticky tpl:top-0 tpl:z-40 tpl:h-0\">\n <div\n class=\"tpl:absolute tpl:left-1/2 tpl:top-2 tpl:flex tpl:-translate-x-1/2 tpl:flex-col tpl:items-center tpl:gap-2\"\n >\n <!-- Sample / Label. Preview mode only: merge tags are never\n substituted on the editing canvas, so the choice would have no\n effect there. A configured `resolvePreview` supersedes samples\n entirely.\n\n The wrapper carries only the shadow that lifts the control off\n the canvas — no `backdrop-filter`, because the toggle's own\n `--tpl-bg-hover` fill is opaque and covers this box exactly, so a\n blur would composite a layer to show nothing. -->\n <Transition name=\"tpl-preview-pill\">\n <div\n v-if=\"\n editor.state.previewMode &&\n !core.previewResolution.supersedesSamples.value\n \"\n data-testid=\"merge-tag-mode-toggle-anchor\"\n class=\"tpl:rounded-[var(--tpl-radius-sm)] tpl:shadow-[var(--tpl-shadow-md)]\"\n >\n <MergeTagModeToggle\n :sample-mode=\"core.mergeTagSampleMode.value\"\n @change=\"core.mergeTagSampleMode.value = $event\"\n />\n </div>\n </Transition>\n <!-- Show all hidden blocks. The shared warning recipe, not a bespoke\n string: it has to read as the Sample/Label switch's sibling,\n since the two stack here, and a hand-rolled pill is how this one\n came to sit 8px shorter with a different radius and a 1.85:1\n label. `warningBtnCompactClass` carries why the amber is on the\n border rather than the text. -->\n <Transition name=\"tpl-preview-pill\">\n <button\n v-if=\"\n core.conditionPreview.hasHiddenBlocks.value &&\n core.appliesConditionFilter.value\n \"\n type=\"button\"\n :class=\"warningBtnCompactClass\"\n class=\"tpl:shadow-[var(--tpl-shadow-md)]\"\n data-testid=\"restore-hidden-blocks\"\n @click=\"core.conditionPreview.reset()\"\n >\n <RotateCcw :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.blockSettings.restoreHiddenBlocks }}\n </button>\n </Transition>\n </div>\n </div>\n <!-- No justify-center and no inline padding: the stage centres\n itself with auto margins and keeps its own clearance\n (Canvas.vue). A flex-centred child that overflows sticks out on\n both sides, and the left side can never be scrolled to. -->\n <main class=\"tpl-main tpl:flex tpl:py-8\">\n <Canvas\n :viewport=\"editor.state.viewport\"\n :content=\"core.previewResolution.content.value\"\n :selected-block-id=\"editor.state.selectedBlockId\"\n :dark-mode=\"editor.state.darkMode\"\n :preview-mode=\"editor.state.previewMode\"\n @select-block=\"editor.selectBlock\"\n />\n </main>\n </div>\n\n <EditorFooter\n v-if=\"config.branding !== false\"\n :position-class=\"[bodyInsetClass]\"\n />\n\n <!-- Keyboard reorder announcement region (visually hidden, screen-reader live) -->\n <div\n class=\"tpl-sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n :aria-label=\"core.t.landmarks.reorderAnnouncements\"\n >\n {{ core.keyboardReorder.announcement.value }}\n </div>\n\n <!-- Right sidebar — persisted with v-show -->\n <RightSidebar\n v-show=\"!editor.state.previewMode\"\n v-model:tab=\"rightSidebarTab\"\n :selected-block=\"editor.selectedBlock.value\"\n :settings=\"editor.content.value.settings\"\n :shifted-left=\"rightPanelOpen\"\n @update-block=\"\n (updates) =>\n editor.updateBlock(editor.state.selectedBlockId!, updates)\n \"\n @delete-block=\"\n () => {\n if (editor.state.selectedBlockId) {\n core.blockActions.deleteBlock(editor.state.selectedBlockId);\n }\n }\n \"\n @duplicate-block=\"\n () => {\n if (editor.selectedBlock.value) {\n core.blockActions.duplicateBlock(editor.selectedBlock.value);\n }\n }\n \"\n @update-settings=\"(updates) => editor.updateSettings(updates)\"\n />\n </div>\n\n <!-- Popover mount — Teleport target for toolbars, link dialog, modals.\n Every popup mounts here rather than at the page's `<body>`, so it\n renders inside the editor's effective DOM root and keeps the shadow\n root's adopted stylesheet; a body-level teleport leaves the shadow\n tree and renders unstyled. It also has to stay a child of `.tpl`, which\n declares `--tpl-base-size` and the colour tokens — `@theme inline`\n rebases the whole Tailwind length scale onto that variable, so a\n popup hoisted out would lose the sizing scale as well as the palette.\n Enforced by the `no-teleport-to-body` ESLint rule and\n `tests/global-refs-audit.test.ts`. -->\n <div\n :ref=\"(el) => (core.popoverRoot.value = el as HTMLElement | null)\"\n class=\"tpl-popover-root\"\n />\n\n <!-- Built-in merge tag picker modal. Reads picker state via injection;\n renders nothing until `picker.isOpen` flips true. -->\n <MergeTagPickerModal />\n\n <!-- Built-in logic picker modal (standalone logic feature). -->\n <LogicTagPickerModal />\n\n <!-- Saved blocks dialogs. Only mounted when a provider is configured;\n each dialog's chunk loads on first open. -->\n <SavedBlocksPanels\n v-if=\"savedBlocks?.isAvailable.value\"\n :feature=\"savedBlocks\"\n />\n\n <!-- Media library modal. Only mounted when a storage provider is\n configured; the modal's chunk loads on first Browse. A callback-only\n `onRequestMedia` never mounts this — the host brought a widget. -->\n <MediaPanels\n v-if=\"config.media && mediaFeature\"\n :feature=\"mediaFeature\"\n :provider=\"config.media\"\n :locale=\"config.locale\"\n :ui-theme=\"core.resolvedTheme.value\"\n :popover-target=\"core.popoverRoot.value\"\n />\n\n <TestEmailPanel v-if=\"testEmail?.isAvailable.value\" :feature=\"testEmail\" />\n\n <!-- The comments sidebar. Only mounted when a provider and a `user` are\n configured; the sidebar's own chunk loads the first time it opens. -->\n <CommentsPanel v-if=\"comments?.isAvailable.value\" :feature=\"comments\" />\n\n <!-- The AI chat panel shares the right gutter with\n comments, one at a time (D18). -->\n <AiPanels v-if=\"ai\" :feature=\"ai\" />\n\n <!-- Collaboration notices: a refused selection or edit, a skipped undo,\n a refused replace, reconnecting. -->\n <CollaborationNotices v-if=\"collaboration\" :feature=\"collaboration\" />\n\n <!-- Version-history chrome outside the header (the preview banner). Only\n mounted when a provider is configured; the banner's chunk loads the\n first time a version is previewed. -->\n <VersionHistoryPanels\n v-if=\"versionHistory?.isAvailable.value\"\n :feature=\"versionHistory\"\n />\n\n <!-- Cloud sidebars, modals and overlays. One lazy wrapper, mounted only\n under `initCloud()`; an OSS consumer downloads none of it. -->\n <CloudPanels\n v-if=\"cloud && cloudAttachment && cloudReady\"\n :editor=\"editor\"\n :core=\"core\"\n :runtime=\"cloud\"\n :cloud=\"cloudAttachment\"\n :ready=\"cloudReady\"\n />\n\n <!-- Small-screen gate (#235). Last child + a literal z-index above the\n chrome and `.tpl-popover-root`, so the opaque notice covers everything\n below the breakpoint. -->\n <SmallScreenNotice v-if=\"showSmallScreenNotice\" />\n </div>\n</template>\n\n<style scoped>\n.tpl-preview-pill-enter-active {\n transition:\n opacity 200ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 200ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-preview-pill-leave-active {\n transition:\n opacity 150ms ease-in,\n transform 150ms ease-in;\n}\n\n.tpl-preview-pill-enter-from,\n.tpl-preview-pill-leave-to {\n opacity: 0;\n transform: translateY(-8px) scale(0.9);\n}\n\n.tpl-preview-pill-enter-to,\n.tpl-preview-pill-leave-from {\n opacity: 1;\n transform: translateY(0) scale(1);\n}\n</style>\n","<script setup lang=\"ts\">\nimport {\n computed,\n defineAsyncComponent,\n onMounted,\n onUnmounted,\n provide,\n ref,\n toRaw,\n watch,\n} from \"vue\";\nimport type { TemplaticalEditorConfig } from \"./index\";\nimport { useEditor } from \"@templatical/core\";\nimport type {\n Block,\n MergeTagsConfig,\n Template,\n TemplateContent,\n UiTheme,\n} from \"@templatical/types\";\nimport { cloneBlock, safeClone } from \"@templatical/types\";\n// Type-only, so no cloud module is statically reachable from the OSS entry —\n// see `cloud/runtime.ts` for why the seam is shaped this way.\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport { useEditorCore } from \"./composables/useEditorCore\";\nimport { useCollaborationFeature } from \"./composables/useCollaborationFeature\";\nimport { useCommentsFeature } from \"./composables/useCommentsFeature\";\nimport { useAiFeature } from \"./composables/useAiFeature\";\nimport { toAiMergeTags } from \"./utils/aiMergeTags\";\nimport { useMediaFeature } from \"./composables/useMediaFeature\";\nimport { useSavedBlocksFeature } from \"./composables/useSavedBlocksFeature\";\nimport { useTemplatesFeature } from \"./composables/useTemplatesFeature\";\nimport { useTestEmailFeature } from \"./composables/useTestEmailFeature\";\nimport { useVersionHistoryFeature } from \"./composables/useVersionHistoryFeature\";\nimport { useSmallScreenNotice } from \"./composables/useSmallScreenNotice\";\nimport { useScrollToBlock } from \"./composables/useScrollToBlock\";\nimport { resolveAutoSave } from \"./types/auto-save\";\nimport { effectiveAltMaxLength } from \"./utils/aiFixableRules\";\nimport { resolveLintOptions } from \"./utils/resolveLintOptions\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\nimport { insertBlockAtSelection } from \"./utils/insertBlockAtSelection\";\nimport { withCollaborativeSave } from \"./utils/withCollaborativeSave\";\nimport { logger } from \"./utils/logger\";\nimport {\n normalizeRemoteOperations,\n withNormalizedContentWrites,\n withNormalizedTemplateLoads,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport type { Translations } from \"./i18n\";\nimport type { EditorCapabilities } from \"./types/editor-capabilities\";\nimport type { UseFontsReturn } from \"./composables/useFonts\";\nimport { AI_FEATURE_KEY, SIZE_CHECK_KEY } from \"./keys\";\n\nimport { RotateCcw } from \"@lucide/vue\";\nimport { warningBtnCompactClass } from \"./constants/styleConstants\";\nimport Canvas from \"./components/Canvas.vue\";\nimport CustomBlockStylesheets from \"./components/CustomBlockStylesheets.vue\";\nimport Sidebar from \"./components/Sidebar.vue\";\nimport RightSidebar from \"./components/RightSidebar.vue\";\nimport type { RightSidebarTab } from \"./components/RightSidebar.vue\";\nimport SmallScreenNotice from \"./components/SmallScreenNotice.vue\";\nimport EditorFooter from \"./components/EditorFooter.vue\";\nimport EditorHeader from \"./components/EditorHeader.vue\";\nimport MergeTagModeToggle from \"./components/MergeTagModeToggle.vue\";\nimport MergeTagPickerModal from \"./components/MergeTagPickerModal.vue\";\nimport LogicTagPickerModal from \"./components/LogicTagPickerModal.vue\";\nimport \"./styles/index.css\";\n\nconst props = defineProps<{\n config: TemplaticalEditorConfig;\n translations: Translations;\n fontsManager: UseFontsReturn;\n /**\n * Shadow root the editor is mounted into. Supplied by `init()` when\n * `shadowDom: true`; undefined in light-DOM mode. Passed through to\n * `useEditorCore` so shadow-DOM-aware composables can resolve the\n * effective root via `EDITOR_ROOT_KEY`.\n */\n shadowRoot?: ShadowRoot;\n /**\n * Cloud's adapter wiring, supplied only by `initCloud()`.\n *\n * There is **one** editor component. Cloud is a set of providers on\n * `config` plus this runtime, which exists purely for the handful of\n * composables that must run at a specific point inside this `setup()` —\n * collaboration before the history interceptor, the lint save-gate after\n * `useEditorCore`. Everything else it contributes arrives through the\n * ordinary config keys an OSS consumer would fill in themselves.\n */\n cloud?: CloudRuntime;\n /**\n * Render the current template to MJML, for `testEmail`'s `includeMjml` option.\n *\n * Supplied by the entry point, which owns the resolution ladder behind\n * `editor.toMjml()` — a consumer's `render.toMjml` first, the bundled renderer\n * otherwise. Rendering here instead would attach a message the send pipeline\n * never produces, which is the one thing a test email exists to rule out.\n *\n * Absent means no MJML: a directly-mounted editor has no entry point to ask.\n */\n renderMjml?: () => Promise<string>;\n renderHtml?: () => Promise<string>;\n canRenderHtml?: () => boolean;\n /** Whether {@link renderMjml} reaches the bundled `@templatical/renderer`. */\n usesLocalRenderer?: () => boolean;\n}>();\n\nprovide(SIZE_CHECK_KEY, {\n renderHtml: () =>\n props.renderHtml?.() ??\n Promise.reject(new Error(\"HTML rendering is unavailable\")),\n canRenderHtml: () => props.canRenderHtml?.() ?? false,\n cloud: !!props.cloud,\n options: props.config.lint ?? {},\n});\n\n// The fourth place consumer content enters (the other three are the entry\n// points in `index.ts`: the mount seed, `setContent` and `create`). A template\n// fetched from the store never passes through the public API — core assigns it\n// to state itself — so the provider is wrapped here, on its way in. Wrapping\n// rather than normalizing after the load resolves is what keeps the load from\n// registering as an edit: core is handed content that is already correct.\n// These getters run when content arrives, after core exists. setMergeTags()\n// replaces core's list, so every incoming path must read that list at call time.\nconst liveMergeTags: MergeTagsConfig = {\n get tags() {\n return core.mergeTags.value;\n },\n get syntax() {\n return core.mergeTagSyntax;\n },\n};\nconst normalizedTemplates = props.config.templates\n ? withNormalizedTemplateLoads(props.config.templates, liveMergeTags)\n : undefined;\n\n// --- Collaboration (opt-in: a collaboration provider and a templates provider) ---\n// Built before `useEditor()`, which reads others' locks from it, and attached\n// right after. A template id is what a session joins, so without a templates\n// provider there is nothing to collaborate on.\nif (props.config.collaboration && !normalizedTemplates) {\n logger.warn(\n \"config.collaboration needs config.templates: collaboration runs on a \" +\n \"loaded template, and only a templates provider loads one. \" +\n \"Collaboration is off.\",\n );\n}\nconst collaboration =\n props.config.collaboration && normalizedTemplates\n ? useCollaborationFeature({\n provider: props.config.collaboration,\n loadTemplate: (id) => normalizedTemplates.load(id),\n user: props.config.user,\n // The same source the load normalizer reads, so a tag arriving in a\n // batch looks the way a loaded one does.\n mergeTags: liveMergeTags,\n onRemoteChange: props.config.onRemoteChange,\n onError: props.config.onError,\n })\n : null;\n\n// With collaboration, content is saved as operations; `save` only renames.\n// A save answers with what is open: the loaded template with the canvas's\n// content, which the backend holds once `settle()` has resolved.\nconst templatesProvider =\n normalizedTemplates && collaboration\n ? withCollaborativeSave(normalizedTemplates, collaboration.core, () => {\n const template = editor.state.template;\n return template\n ? {\n ...(toRaw(template) as Template),\n content: safeClone(toRaw(editor.content.value)),\n }\n : null;\n })\n : normalizedTemplates;\n\n// --- Core editor state ---\nconst editor = useEditor({\n content: props.config.content!,\n // Seeds a *new* template's body font when no `content` was supplied. Only the\n // deleted Cloud core passed this, so `init({ fonts: { defaultFont } })` never\n // reached a blank template.\n defaultFontFamily: props.config.fonts?.defaultFont,\n // Not `props.config.templateDefaults` raw: the editor's own `locale` seeds\n // the template's content language when the consumer left it unset, so a\n // German editor stops producing `<mjml lang=\"en\">` on a fresh template.\n templateDefaults: resolveTemplateDefaults(props.config),\n templates: templatesProvider,\n onError: props.config.onError,\n // Blocks other collaborators hold: they can't be selected here.\n lockedBlocks: collaboration?.locks,\n});\n\ncollaboration?.attach(editor);\n\nconst cloudAttachment = props.cloud ? props.cloud.attach({ editor }) : null;\n\n// --- Templates (opt-in: only when a storage provider is configured) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header's name field, status indicator and save button — and what\n// makes Cmd+S mean \"persist now\".\nconst templates = templatesProvider\n ? useTemplatesFeature({\n provider: templatesProvider,\n editor,\n guardUnsavedChanges: props.config.templates?.unsavedChangesGuard,\n // Cloud's lint save-gate, when there is one. Read through a getter\n // because the gate needs `core.templateLint`, which does not exist yet.\n // Without this the collapse would have silently dropped the server's\n // `accessibility.blockOnError` policy.\n getSaveGate: props.cloud ? () => props.cloud!.getSaveGate() : undefined,\n })\n : null;\n\n// Reported to the consumer regardless of whether a provider is configured: a\n// `beforeunload` guard cannot cover SPA route changes, so an embedder needs this\n// to guard their own router — including when they persist via `onChange`.\nif (props.config.onDirtyChange) {\n watch(\n () => editor.state.isDirty,\n (isDirty) => props.config.onDirtyChange!(isDirty),\n );\n}\n\n// Outer `.tpl` ref — passed to `useEditorCore` so the active-editor\n// tracker can route keyboard shortcuts when two editors share a page.\nconst rootEl = ref<HTMLElement | null>(null);\n\n// --- Saved blocks (opt-in: only when a storage provider is configured) ---\n// Instantiated before `useEditorCore` so its capability can be passed in,\n// which is what lights up the shared save button and sidebar rail.\nconst savedBlocks = props.config.savedBlocks\n ? useSavedBlocksFeature({\n provider: props.config.savedBlocks,\n editor,\n onError: props.config.onError,\n // Cloud's store is plan-gated; a consumer's own store never is.\n isAvailable: props.cloud\n ? () => props.cloud!.isSavedBlocksAvailable()\n : undefined,\n })\n : null;\n\n// Lazily loaded so a consumer without a provider downloads none of the\n// saved-blocks UI. Rendered only when the feature is active.\nconst SavedBlocksPanels = defineAsyncComponent(\n () => import(\"./components/SavedBlocksPanels.vue\"),\n);\n\n// --- Media (opt-in: a provider and/or an `onRequestMedia` override) ---\n// Instantiated before `useEditorCore` so the synthesized function is what\n// gets provided as `ON_REQUEST_MEDIA_KEY`. The modal mounts only on the\n// provider path — a callback-only config never downloads it.\nconst mediaFeature =\n props.config.media || props.config.onRequestMedia\n ? useMediaFeature({\n provider: props.config.media,\n onRequestMedia: props.config.onRequestMedia,\n getTemplateId: () => editor.state.template?.id,\n onError: props.config.onError,\n })\n : null;\n\nconst MediaPanels = defineAsyncComponent(\n () => import(\"./components/MediaPanels.vue\"),\n);\n\n// --- Test email (opt-in: only when a sending provider is configured) ---\n// Created before `useEditorCore` so its capability can be passed in, same as\n// saved blocks.\nconst testEmail = props.config.testEmail\n ? useTestEmailFeature({\n provider: props.config.testEmail,\n getContent: () => editor.content.value,\n renderMjml: props.renderMjml,\n usesLocalRenderer: props.usesLocalRenderer,\n onError: props.config.onError,\n // Cloud folds in the plan feature and \"the template must be saved\", both\n // constraints of *its* sending path rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isTestEmailAvailable()\n : undefined,\n })\n : null;\n\nconst TestEmailPanel = defineAsyncComponent(\n () => import(\"./components/TestEmailPanel.vue\"),\n);\n\n// --- Comments (opt-in: only with a storage provider *and* a `user`) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header trigger and the per-block comment indicators.\n//\n// No `user` means no provider call at all — an unattributable comment is worse\n// than no comment feature, so `isAvailable` stays false and nothing renders.\nconst comments = props.config.comments\n ? useCommentsFeature({\n provider: props.config.comments,\n editor,\n user: props.config.user,\n // Cloud supplies its comments state; the open-source AI feature keeps\n // comments and AI panels exclusive in their shared 360px gutter.\n isOpen: cloudAttachment?.panelState.commentsOpen,\n onError: props.config.onError,\n // Cloud folds in the `commenting` plan feature and \"the template must be\n // saved\", both constraints of *its* store rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isCommentsAvailable()\n : undefined,\n // Cloud anchors a comment to a block in the saved template; a consumer's\n // store accepts whatever anchor it is given.\n isBlockSaved: props.cloud\n ? (blockId: string) => props.cloud!.isBlockSaved(blockId)\n : undefined,\n })\n : null;\n\nconst CommentsPanel = defineAsyncComponent(\n () => import(\"./components/CommentsPanel.vue\"),\n);\n\n// The AI panels: lazy, mounted only with an `ai` provider; each panel is its\n// own chunk inside.\nconst AiPanels = defineAsyncComponent(\n () => import(\"./components/ai/AiPanels.vue\"),\n);\n\n// --- AI (opt-in: an `ai` provider) ---\n// Built before `useEditorCore` so its capability is in the object core\n// provides. It reads core (the history and the merge tags) through\n// getters, at call time. Its panels are lazy (`AiPanels`); the header button\n// is not, so it renders with the rest of the header (`EditorHeader`).\nconst ai = props.config.ai\n ? useAiFeature({\n provider: props.config.ai,\n editor,\n collaboration,\n history: () => core.history,\n reload: templates\n ? (id, shouldApply) => templates.load(id, shouldApply)\n : null,\n altMaxLength: () =>\n effectiveAltMaxLength(resolveLintOptions(props.config)),\n mergeTags: () => toAiMergeTags(core.mergeTags.value, core.mergeTagSyntax),\n normalize: (ops, content) =>\n normalizeRemoteOperations(ops, content, liveMergeTags),\n commentsOpen: comments?.isOpen ?? null,\n onError: props.config.onError,\n })\n : null;\nif (ai) provide(AI_FEATURE_KEY, ai);\n\n// Lazy: an editor without a collaboration provider never downloads it.\nconst CollaborationNotices = defineAsyncComponent(\n () => import(\"./components/collaboration/CollaborationNotices.vue\"),\n);\n\n// --- Cloud chrome (opt-in: only under `initCloud()`) ---\n// One lazy wrapper for every panel, overlay and modal Cloud adds, plus one for\n// its header controls. Same discipline as `SavedBlocksPanels` / `TestEmailPanel`:\n// an OSS consumer never downloads any of it.\nconst CloudPanels = defineAsyncComponent(\n () => import(\"./cloud/components/CloudPanels.vue\"),\n);\nconst CloudHeaderExtras = defineAsyncComponent(\n () => import(\"./cloud/components/CloudHeaderExtras.vue\"),\n);\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// The header control lives in `EditorHeader`; this is the preview banner, which\n// renders outside the header. Both are lazy.\nconst VersionHistoryPanels = defineAsyncComponent(\n () => import(\"./components/VersionHistoryPanels.vue\"),\n);\n\n// --- Auto-save ---\n// One debounced tick drives everything a consumer can ask for on a content\n// change: the `onChange` notification, and, when `templates.autoSave` is on,\n// the save itself. Sharing a single `useAutoSave` instance keeps the two in\n// step and inherits the pause-during-undo/redo behaviour `useEditorCore` wires\n// up around it. `config.changeDebounce` sets the cadence for both.\nconst autoSaveEnabled = resolveAutoSave(\n props.config.templates?.autoSave,\n false,\n);\nconst isAutoSaving = autoSaveEnabled && templates !== null;\n// The one way autosave can still be inert once a provider exists is its\n// `save` being `false` — a read-only store — which `requestAutoSave()` below\n// already no-ops per tick for; this warning is the only signal the consumer\n// gets. `templates !== null` is redundant with `autoSaveEnabled` at runtime\n// (the provider that enables autosave is the same provider that makes\n// `templates` non-null) but stays as an explicit conjunct so TypeScript can\n// narrow `templates.canSave.value` below without a non-null assertion.\nif (autoSaveEnabled && templates !== null && !templates.canSave.value) {\n logger.warn(\n \"config.templates.autoSave is on but this provider's save is false — \" +\n \"there is nothing to persist to. Give it a real save function, or \" +\n \"use `onChange` to persist the content yourself.\",\n );\n}\n// `changeDebounce` alone does not enable autosave — only `templates.autoSave`\n// does. A config with `changeDebounce` set, a provider present, `autoSave`\n// left unset, and no `onChange` has nothing consuming the timer at all,\n// which reads as intentional `onChange`-only pacing but is easy to reach by\n// mistake. Warn on exactly that combination; `autoSave: false` is a stated\n// decision and must stay silent.\nif (\n props.config.changeDebounce !== undefined &&\n templates !== null &&\n props.config.templates?.autoSave === undefined &&\n !props.config.onChange\n) {\n logger.warn(\n \"config.changeDebounce is set but nothing will use it — \" +\n \"config.templates.autoSave is unset and there is no onChange either, \" +\n \"so the timer has no consumer. Set config.templates.autoSave, or add \" +\n \"onChange, so the debounce takes effect.\",\n );\n}\n\nconst autoSaveOptions =\n props.config.onChange || isAutoSaving\n ? {\n onChange: () => {\n props.config.onChange?.(\n JSON.parse(JSON.stringify(editor.state.content)),\n );\n // `requestAutoSave()` already no-ops without a saveable template, so a\n // read-only provider costs one predicate per tick and nothing else.\n // It is the *ungated* request only in the sense that it never raises a\n // prompt: Cloud's lint gate still refuses it, which is what keeps\n // `accessibility.blockOnError` a policy rather than a manual-save\n // speed bump.\n if (isAutoSaving) templates!.requestAutoSave();\n },\n ...(props.config.changeDebounce !== undefined\n ? { debounce: props.config.changeDebounce }\n : {}),\n }\n : null;\n\n// --- Shared editor core (composables, provides, plugins, keyboard) ---\n// A named object rather than an inline literal: `useVersionHistoryFeature` can\n// only be built after core (it needs history/conditionPreview/autoSave), so its\n// capability is assigned in below, into the very object core provided.\nconst capabilities: EditorCapabilities = {\n ...(savedBlocks ? { savedBlocks: savedBlocks.capability } : {}),\n ...(templates ? { templates: templates.capability } : {}),\n ...(testEmail ? { testEmail: testEmail.capability } : {}),\n ...(comments ? { comments: comments.capability } : {}),\n ...(collaboration ? { collaboration: collaboration.capability } : {}),\n ...(ai ? { ai: ai.capability } : {}),\n};\n\nconst core = useEditorCore({\n editor,\n containerEl: rootEl,\n config: {\n uiTheme: props.config.uiTheme,\n theme: props.config.theme,\n blockDefaults: props.config.blockDefaults,\n templateDefaults: props.config.templateDefaults,\n customBlocks: props.config.customBlocks,\n paletteBlocks: props.config.paletteBlocks,\n htmlBlockPreview: props.config.htmlBlockPreview,\n layout: props.config.layout,\n sectionWrapper: props.config.sectionWrapper,\n colors: props.config.colors,\n templateSettings: props.config.templateSettings,\n mergeTags: props.config.mergeTags,\n logicTags: props.config.logicTags,\n displayConditions: props.config.displayConditions,\n // The synthesized Browse/drop handler. Null when neither a provider nor a\n // callback is configured, which is what keeps image fields URL-only.\n onRequestMedia: mediaFeature?.requestMedia ?? null,\n // Distinct from Browse: a read-only provider still opens the library.\n canDropMedia: mediaFeature?.canDrop ?? null,\n resolvePreview: props.config.resolvePreview,\n resolveImageUrl: props.config.resolveImageUrl,\n lint: resolveLintOptions(props.config),\n // For Intl-built labels (dates), which would otherwise format in the\n // BROWSER's locale and disagree with the translated chrome beside them.\n locale: props.config.locale,\n },\n translations: props.translations,\n fontsManager: props.fontsManager,\n autoSaveOptions,\n capabilities,\n editorRoot: props.shadowRoot,\n history: collaboration?.history,\n});\n\nconst rightSidebarTab = ref<RightSidebarTab>(\"content\");\n\n// Cloud's setup-time wiring that needs `core`: the lint save-gate (reads\n// `core.templateLint`) and the capability entries Cloud contributes — mutated\n// into the very object `useEditorCore` provided, so injecting components see\n// them on first render.\nconst cloudReady =\n props.cloud && cloudAttachment\n ? props.cloud.ready({ core, capabilities })\n : null;\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// Constructed *after* `useEditorCore` because it drives `history` /\n// `conditionPreview` / `autoSave`, which core owns. Its capability is therefore\n// assigned into the object above rather than passed in — same object reference\n// core provided, mutated during setup, so injecting components see it on their\n// first render.\nconst versionHistory = props.config.versionHistory\n ? useVersionHistoryFeature({\n provider: props.config.versionHistory,\n // The fifth content-in path. A stored version holds whatever was written\n // to it, so it can carry bare tokens like any other loaded content, and\n // previewing one would put them on a canvas where every other tag is a\n // chip. Wrapped at `setContent` rather than at the provider, because\n // version content also arrives off the hydrated list and out of the\n // `fetched` cache without touching `get()`.\n editor: withNormalizedContentWrites(editor, liveMergeTags),\n history: core.history,\n conditionPreview: core.conditionPreview,\n autoSave: core.autoSave,\n // A version on the canvas is a preview, not an edit: collaboration stops\n // reading the canvas for it, and a restore re-syncs from the backend.\n collaboration: collaboration\n ? {\n suspend: collaboration.core.suspend,\n resume: collaboration.core.resume,\n catchUp: collaboration.core.catchUp,\n reportReplaceRefused: collaboration.reportReplaceRefused,\n }\n : null,\n // Lets the restore confirmation offer to persist unsaved work instead of\n // only warning about it. Without a templates provider — or with one whose\n // `save` is `false` — there is nowhere to put that work, and the\n // confirmation says so rather than offering an action that can't happen.\n // Cloud additionally refuses while the lint gate would block: stacking a\n // second modal on the confirmation would be worse than saying there is\n // currently nowhere to put the work.\n saveBeforeRestore: templates\n ? {\n canSave: () =>\n templates.canSave.value &&\n !(props.cloud?.getSaveGate()?.shouldBlock.value ?? false),\n save: () => templates.save(\"restore\"),\n }\n : null,\n onError: props.config.onError,\n })\n : null;\n\nif (versionHistory) capabilities.versionHistory = versionHistory.capability;\n\n/**\n * Left/right insets for the canvas body and the footer, which must always agree.\n *\n * Comments and the open-source AI panels widen the right gutter while open.\n */\n/**\n * Whether a 360px feature panel occupies the right-hand gutter.\n *\n * Comments and the open-source AI panels share this gutter; the AI feature\n * keeps their open states mutually exclusive. Cloud also supplies its panel\n * state, which shares the comments ref.\n *\n * Two things read this, and **both must**: the canvas/footer insets below, and\n * `RightSidebar`'s `shifted-left` — the properties panel sits at `right-0` too, so\n * a panel opening over it would swallow every click meant for the panel.\n */\nconst rightPanelOpen = computed(\n () =>\n comments?.isOpen.value === true ||\n (ai !== null && ai.panel.value !== null) ||\n cloudAttachment?.panelState.rightPanelOpen.value === true,\n);\n\nconst bodyInsetClass = computed(() => {\n if (editor.state.previewMode) return \"tpl:left-0 tpl:right-0\";\n return rightPanelOpen.value\n ? \"tpl:left-12 tpl:right-[680px]\"\n : \"tpl:left-12 tpl:right-[320px]\";\n});\n\n// --- Small-screen gate (#235) ---\n// Below ~768px the three-pane chrome can't lay out usably; show a notice\n// instead. Opt out with `config.smallScreenNotice: false`.\nconst { showNotice: showSmallScreenNotice } = useSmallScreenNotice(\n () => props.config.smallScreenNotice,\n);\n\n// --- Lifecycle ---\nonMounted(async () => {\n await props.fontsManager.loadCustomFonts();\n});\n\nonUnmounted(() => {\n props.fontsManager.cleanupFontLinks();\n ai?.destroy();\n props.cloud?.destroy();\n core.destroy();\n});\n\n// --- Public API (accessed via template ref from init()) ---\n// The lifecycle trio comes from the templates feature when one exists, so a\n// programmatic save also drives the header's status. Without a provider it comes\n// straight from core, whose own methods reject with the actionable error.\nconst templateLifecycle = templates ?? editor;\n\nconst scrollToBlock = useScrollToBlock(core.editorRoot);\n\ndefineExpose({\n getContent: () => editor.content.value,\n setContent: (content: TemplateContent) => editor.setContent(content),\n insertBlock: (block: Block): string | null => {\n // The palette is hidden in preview mode, and preview has no selection.\n if (editor.state.previewMode) {\n logger.warn(\"insertBlock() does nothing in preview mode.\");\n return null;\n }\n // A copy with fresh ids throughout, so inserting the same library item\n // twice never puts two blocks, rows or items on the canvas with one id.\n const copy = cloneBlock(block);\n if (!insertBlockAtSelection(editor, copy)) return null;\n scrollToBlock(copy.id);\n return copy.id;\n },\n setTheme: (theme: UiTheme) => editor.setUiTheme(theme),\n setMergeTags: core.setMergeTags,\n isDirty: () => editor.state.isDirty,\n create: templateLifecycle.create,\n load: templateLifecycle.load,\n save: templateLifecycle.save,\n renderCustomBlock: core.registry.renderCustomBlock,\n getCustomBlockStylesheet: (customType: string) =>\n core.registry.getDefinition(customType)?.stylesheet,\n});\n</script>\n\n<template>\n <!-- @dragover/@drop.prevent: a file dropped outside an image drop zone would\n otherwise make the browser navigate to the file:// URL and destroy the\n editor session. Image zones (useImageDrop) handle their own drops; this\n only neutralizes the default action everywhere else (#229). -->\n <div\n ref=\"rootEl\"\n class=\"tpl tpl:relative tpl:h-full\"\n :class=\"{ 'tpl:dark': editor.state.darkMode }\"\n :data-tpl-theme=\"core.resolvedTheme.value\"\n :style=\"core.themeStyles.value\"\n @dragover.prevent\n @drop.prevent\n >\n <!-- Reactive `<style>` tags for custom-block definition stylesheets in\n use. Sits at the top so its rules apply to the canvas below. -->\n <CustomBlockStylesheets />\n <!-- Chrome wrapper — the clip belongs here, never on the root and never\n around `.tpl-popover-root`. Safari paints a `position: fixed`\n descendant clipped to an ancestor's `overflow: hidden` box while still\n resolving its layout against the viewport, so a dialog teleported\n under a clipping ancestor is cut off wherever it extends past the\n container, and its backdrop dims only the container's own area\n (#633). Keeping the clip on this element bounds the header, rails,\n canvas and footer without reaching the popover root, and this box is\n identical to the root's, so everything anchored `absolute` inside\n lands exactly where it would against the root. Locked by\n `tests/popover-root-clip-scope.test.ts`. -->\n <div class=\"tpl:absolute tpl:inset-0 tpl:overflow-hidden\">\n <!-- One header for both entry points. Cloud's own controls arrive through\n the three slots; everything else here is capability-gated, so the same\n markup covers \"no providers at all\" and a fully-wired Cloud session. -->\n <EditorHeader\n :editor=\"editor\"\n :core=\"core\"\n :templates=\"templates\"\n :show-template-name=\"config.templates?.nameField !== false\"\n :test-email=\"testEmail\"\n :version-history=\"versionHistory\"\n :comments=\"comments\"\n :collaboration=\"collaboration\"\n :ai=\"ai\"\n >\n <template v-if=\"cloudAttachment\" #left-extras>\n <CloudHeaderExtras part=\"left\" :cloud=\"cloudAttachment\" />\n </template>\n <template v-if=\"cloudAttachment\" #right-extras>\n <CloudHeaderExtras part=\"right\" :cloud=\"cloudAttachment\" />\n </template>\n </EditorHeader>\n\n <!-- Left sidebar — absolute, below header -->\n <Sidebar v-show=\"!editor.state.previewMode\" />\n\n <!-- Canvas area — absolute, fills remaining space -->\n <div\n class=\"tpl-body tpl:absolute tpl:bottom-0 tpl:overflow-auto tpl:bg-[var(--tpl-canvas-bg)]\"\n style=\"transition: all 300ms cubic-bezier(0.34, 1.56, 0.64, 1)\"\n :class=\"[\n bodyInsetClass,\n versionHistory?.isPreviewing.value ? 'tpl:top-[104px]' : 'tpl:top-14',\n ]\"\n >\n <!-- Preview chrome, floated over the canvas.\n\n A zero-height sticky layer holding one absolutely-positioned,\n canvas-centred **column**. Zero height means the layer contributes no\n space of its own, so nothing here can push the canvas around — which\n is what lets the merge-tag toggle live over the preview instead of in\n the header, whose centre track re-centres on every width change and\n so dragged the Preview button 114.5px sideways each time the toggle\n appeared (#574).\n\n A column rather than two fixed offsets. Both pills are reachable at\n once — the restore pill needs hidden blocks, the toggle needs preview\n mode without a `resolvePreview`, and nothing makes those exclusive —\n so they have to stack. Doing that with a hardcoded second offset put\n the restore pill 48px down even when it rendered alone, which in\n editing mode (where the toggle never shows) dropped it onto the first\n block's content. Flow solves what the offset got wrong: whichever\n pills render sit tight under the header, in order.\n\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div class=\"tpl-preview-overlay tpl:sticky tpl:top-0 tpl:z-40 tpl:h-0\">\n <div\n class=\"tpl:absolute tpl:left-1/2 tpl:top-2 tpl:flex tpl:-translate-x-1/2 tpl:flex-col tpl:items-center tpl:gap-2\"\n >\n <!-- Sample / Label. Preview mode only: merge tags are never\n substituted on the editing canvas, so the choice would have no\n effect there. A configured `resolvePreview` supersedes samples\n entirely.\n\n The wrapper carries only the shadow that lifts the control off\n the canvas — no `backdrop-filter`, because the toggle's own\n `--tpl-bg-hover` fill is opaque and covers this box exactly, so a\n blur would composite a layer to show nothing. -->\n <Transition name=\"tpl-preview-pill\">\n <div\n v-if=\"\n editor.state.previewMode &&\n !core.previewResolution.supersedesSamples.value\n \"\n data-testid=\"merge-tag-mode-toggle-anchor\"\n class=\"tpl:rounded-[var(--tpl-radius-sm)] tpl:shadow-[var(--tpl-shadow-md)]\"\n >\n <MergeTagModeToggle\n :sample-mode=\"core.mergeTagSampleMode.value\"\n @change=\"core.mergeTagSampleMode.value = $event\"\n />\n </div>\n </Transition>\n <!-- Show all hidden blocks. The shared warning recipe, not a bespoke\n string: it has to read as the Sample/Label switch's sibling,\n since the two stack here, and a hand-rolled pill is how this one\n came to sit 8px shorter with a different radius and a 1.85:1\n label. `warningBtnCompactClass` carries why the amber is on the\n border rather than the text. -->\n <Transition name=\"tpl-preview-pill\">\n <button\n v-if=\"\n core.conditionPreview.hasHiddenBlocks.value &&\n core.appliesConditionFilter.value\n \"\n type=\"button\"\n :class=\"warningBtnCompactClass\"\n class=\"tpl:shadow-[var(--tpl-shadow-md)]\"\n data-testid=\"restore-hidden-blocks\"\n @click=\"core.conditionPreview.reset()\"\n >\n <RotateCcw :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.blockSettings.restoreHiddenBlocks }}\n </button>\n </Transition>\n </div>\n </div>\n <!-- No justify-center and no inline padding: the stage centres\n itself with auto margins and keeps its own clearance\n (Canvas.vue). A flex-centred child that overflows sticks out on\n both sides, and the left side can never be scrolled to. -->\n <main class=\"tpl-main tpl:flex tpl:py-8\">\n <Canvas\n :viewport=\"editor.state.viewport\"\n :content=\"core.previewResolution.content.value\"\n :selected-block-id=\"editor.state.selectedBlockId\"\n :dark-mode=\"editor.state.darkMode\"\n :preview-mode=\"editor.state.previewMode\"\n @select-block=\"editor.selectBlock\"\n />\n </main>\n </div>\n\n <EditorFooter\n v-if=\"config.branding !== false\"\n :position-class=\"[bodyInsetClass]\"\n />\n\n <!-- Keyboard reorder announcement region (visually hidden, screen-reader live) -->\n <div\n class=\"tpl-sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n :aria-label=\"core.t.landmarks.reorderAnnouncements\"\n >\n {{ core.keyboardReorder.announcement.value }}\n </div>\n\n <!-- Right sidebar — persisted with v-show -->\n <RightSidebar\n v-show=\"!editor.state.previewMode\"\n v-model:tab=\"rightSidebarTab\"\n :selected-block=\"editor.selectedBlock.value\"\n :settings=\"editor.content.value.settings\"\n :shifted-left=\"rightPanelOpen\"\n @update-block=\"\n (updates) =>\n editor.updateBlock(editor.state.selectedBlockId!, updates)\n \"\n @delete-block=\"\n () => {\n if (editor.state.selectedBlockId) {\n core.blockActions.deleteBlock(editor.state.selectedBlockId);\n }\n }\n \"\n @duplicate-block=\"\n () => {\n if (editor.selectedBlock.value) {\n core.blockActions.duplicateBlock(editor.selectedBlock.value);\n }\n }\n \"\n @update-settings=\"(updates) => editor.updateSettings(updates)\"\n />\n </div>\n\n <!-- Popover mount — Teleport target for toolbars, link dialog, modals.\n Every popup mounts here rather than at the page's `<body>`, so it\n renders inside the editor's effective DOM root and keeps the shadow\n root's adopted stylesheet; a body-level teleport leaves the shadow\n tree and renders unstyled. It also has to stay a child of `.tpl`, which\n declares `--tpl-base-size` and the colour tokens — `@theme inline`\n rebases the whole Tailwind length scale onto that variable, so a\n popup hoisted out would lose the sizing scale as well as the palette.\n Enforced by the `no-teleport-to-body` ESLint rule and\n `tests/global-refs-audit.test.ts`. -->\n <div\n :ref=\"(el) => (core.popoverRoot.value = el as HTMLElement | null)\"\n class=\"tpl-popover-root\"\n />\n\n <!-- Built-in merge tag picker modal. Reads picker state via injection;\n renders nothing until `picker.isOpen` flips true. -->\n <MergeTagPickerModal />\n\n <!-- Built-in logic picker modal (standalone logic feature). -->\n <LogicTagPickerModal />\n\n <!-- Saved blocks dialogs. Only mounted when a provider is configured;\n each dialog's chunk loads on first open. -->\n <SavedBlocksPanels\n v-if=\"savedBlocks?.isAvailable.value\"\n :feature=\"savedBlocks\"\n />\n\n <!-- Media library modal. Only mounted when a storage provider is\n configured; the modal's chunk loads on first Browse. A callback-only\n `onRequestMedia` never mounts this — the host brought a widget. -->\n <MediaPanels\n v-if=\"config.media && mediaFeature\"\n :feature=\"mediaFeature\"\n :provider=\"config.media\"\n :locale=\"config.locale\"\n :ui-theme=\"core.resolvedTheme.value\"\n :popover-target=\"core.popoverRoot.value\"\n />\n\n <TestEmailPanel v-if=\"testEmail?.isAvailable.value\" :feature=\"testEmail\" />\n\n <!-- The comments sidebar. Only mounted when a provider and a `user` are\n configured; the sidebar's own chunk loads the first time it opens. -->\n <CommentsPanel v-if=\"comments?.isAvailable.value\" :feature=\"comments\" />\n\n <!-- The AI chat panel shares the right gutter with\n comments, one at a time (D18). -->\n <AiPanels v-if=\"ai\" :feature=\"ai\" />\n\n <!-- Collaboration notices: a refused selection or edit, a skipped undo,\n a refused replace, reconnecting. -->\n <CollaborationNotices v-if=\"collaboration\" :feature=\"collaboration\" />\n\n <!-- Version-history chrome outside the header (the preview banner). Only\n mounted when a provider is configured; the banner's chunk loads the\n first time a version is previewed. -->\n <VersionHistoryPanels\n v-if=\"versionHistory?.isAvailable.value\"\n :feature=\"versionHistory\"\n />\n\n <!-- Cloud sidebars, modals and overlays. One lazy wrapper, mounted only\n under `initCloud()`; an OSS consumer downloads none of it. -->\n <CloudPanels\n v-if=\"cloud && cloudAttachment && cloudReady\"\n :editor=\"editor\"\n :core=\"core\"\n :runtime=\"cloud\"\n :cloud=\"cloudAttachment\"\n :ready=\"cloudReady\"\n />\n\n <!-- Small-screen gate (#235). Last child + a literal z-index above the\n chrome and `.tpl-popover-root`, so the opaque notice covers everything\n below the breakpoint. -->\n <SmallScreenNotice v-if=\"showSmallScreenNotice\" />\n </div>\n</template>\n\n<style scoped>\n.tpl-preview-pill-enter-active {\n transition:\n opacity 200ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 200ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-preview-pill-leave-active {\n transition:\n opacity 150ms ease-in,\n transform 150ms ease-in;\n}\n\n.tpl-preview-pill-enter-from,\n.tpl-preview-pill-leave-to {\n opacity: 0;\n transform: translateY(-8px) scale(0.9);\n}\n\n.tpl-preview-pill-enter-to,\n.tpl-preview-pill-leave-from {\n opacity: 1;\n transform: translateY(0) scale(1);\n}\n</style>\n","/**\n * An `@import` rule. The URL alternatives are quote-aware because a URL can\n * carry `;` (Google Fonts' `wght@400;500`), which would otherwise end the\n * match mid-URL and leave the rest of it behind in the CSS.\n */\nconst IMPORT_RULE =\n /@import\\s*(?:url\\(\\s*(?:\"[^\"]*\"|'[^']*'|[^)]*)\\s*\\)|\"[^\"]*\"|'[^']*')[^;]*;/g;\n\n/**\n * Removes every `@import` rule from CSS headed for a constructed stylesheet.\n * A constructed sheet cannot hold one: `replaceSync` drops it and logs a\n * warning on the host page.\n */\nexport function stripStylesheetImports(css: string): string {\n return css.replace(IMPORT_RULE, \"\");\n}\n","import type {\n CustomBlock,\n CustomFont,\n RenderPayload,\n RenderProvider,\n TemplateContent,\n} from \"@templatical/types\";\nimport {\n applyLayout,\n assertNoSlotInContent,\n assertNoWrapperInContent,\n safeClone,\n} from \"@templatical/types\";\nimport { preRenderCustomBlocks } from \"./preRenderCustomBlocks\";\n\n/** The fonts half of a {@link RenderPayload}, as the editor resolves it. */\nexport interface RenderFonts {\n customFonts: CustomFont[];\n defaultFallback: string;\n}\n\n/** Minimal slice of the fonts manager the payload needs. */\nexport interface RenderFontsSource {\n customFonts: { value: CustomFont[] };\n defaultFallback: { value: string };\n}\n\n/**\n * The fonts the editor is *actually* rendering with.\n *\n * The canvas's font set and the payload's are the same set *by construction*\n * rather than by agreement: nothing can switch custom faces off for a plan, so\n * there is no second source of truth to keep in step.\n */\nexport function resolveRenderFonts(source: RenderFontsSource): RenderFonts {\n return {\n customFonts: source.customFonts.value,\n defaultFallback: source.defaultFallback.value,\n };\n}\n\n/** What {@link buildRenderPayload} needs from an editor instance. */\nexport interface RenderPayloadSource {\n getContent: () => TemplateContent;\n renderCustomBlock: (block: CustomBlock) => Promise<string>;\n getCustomBlockStylesheet: (customType: string) => string | undefined;\n getFonts: () => RenderFonts;\n /**\n * Optional. Embedder shell spliced onto the payload's `content` so a BYO\n * `render.toMjml` cannot drop the chrome by treating payload content as\n * today's template. Omitting it (or returning undefined) leaves the\n * unshelled clone. Never written back into `getContent()`.\n */\n getLayout?: () => TemplateContent | undefined;\n}\n\n/**\n * Assemble the render-complete payload a {@link RenderProvider} is promised.\n *\n * \"Render-complete\" is the deal that lets the provider win over the bundled\n * renderer: local rendering sees custom blocks and fonts natively, a backend\n * doesn't, so the editor resolves both up front instead of each backend\n * rediscovering the problem.\n *\n * The content is a **defensive copy** (`safeClone`, same as `getContent()`, since\n * a drag inside a section can leave a Sortable expando cycle reachable from live\n * content). When `getLayout` returns a shell, that copy is composed (`applyLayout`)\n * so a BYO `render.toMjml` cannot drop the chrome by reading payload content as\n * today's template. Pre-rendering writes `renderedHtml` and\n * `renderedStylesheet` onto blocks, and doing that to the live tree would mark\n * the editor dirty and make an export mutate the document.\n */\nexport async function buildRenderPayload(\n source: RenderPayloadSource,\n): Promise<RenderPayload> {\n const raw = safeClone(source.getContent());\n const layout = source.getLayout?.();\n const content = layout ? applyLayout(layout, raw) : raw;\n if (!layout) {\n assertNoSlotInContent(content);\n assertNoWrapperInContent(content);\n }\n await preRenderCustomBlocks(content, {\n renderCustomBlock: source.renderCustomBlock,\n getCustomBlockStylesheet: source.getCustomBlockStylesheet,\n });\n\n return { content, fonts: source.getFonts() };\n}\n\n/** What {@link createRenderMethods} needs to resolve each method. */\nexport interface RenderMethodsSource {\n /** The consumer's backend, when `render` was configured. */\n provider?: RenderProvider | null;\n buildPayload: () => Promise<RenderPayload>;\n /**\n * Render MJML with the bundled `@templatical/renderer`. Expected to reject with\n * the \"install @templatical/renderer\" error when the optional peer is absent —\n * that rejection *is* the `toMjml()` chain's final `throw`.\n */\n renderLocalMjml: () => Promise<string>;\n}\n\nexport interface RenderMethods {\n toMjml(): Promise<string>;\n toHtml(): Promise<string>;\n /** Whether the provider can produce sending-ready HTML without guessing. */\n canRenderHtml(): boolean;\n /**\n * Whether {@link toMjml} would reach the bundled `@templatical/renderer` —\n * false once the provider implements `toMjml` and owns the render itself.\n *\n * Exists so a caller can tell what a rejected render *could* have been caused\n * by. A missing optional peer is a plausible reading only on the local path;\n * on the provider path it never is, and acting on it would swallow the\n * backend's own error. The test-email dialog's `includeMjml` degradation is\n * the one consumer.\n *\n * Resolved per call, like the two render methods, so a provider completed\n * after construction answers for what would happen now.\n */\n usesLocalRenderer(): boolean;\n}\n\n/**\n * `editor.toMjml()` / `editor.toHtml()`, resolved **per method rather than per\n * provider** — a provider that implements one of the three methods is not thereby\n * claiming the others.\n *\n * | Call | Order |\n * |---|---|\n * | `toMjml()` | `provider.toMjml` → the bundled renderer → throw |\n * | `toHtml()` | `provider.toHtml` → `toMjml()` + `provider.compileMjml` → throw |\n *\n * `toHtml()` composes through `toMjml()` rather than forcing the local renderer,\n * so a provider whose MJML is authoritative (Cloud's is — it renders block types\n * a browser cannot) is not silently bypassed on the way to HTML. When the provider\n * only supplies `compileMjml`, that resolves to local MJML anyway, which is the\n * cheap tier working exactly as intended.\n *\n * **There is no local HTML path, ever.** The SDK deliberately does not bundle an\n * MJML compiler, so the last step is a rejection with instructions rather than a\n * guess.\n */\nexport function createRenderMethods(\n source: RenderMethodsSource,\n): RenderMethods {\n async function toMjml(): Promise<string> {\n const provider = source.provider;\n // Bound rather than narrowed in place: the call sits behind an `await`, and a\n // bound reference cannot be re-read as undefined afterwards.\n const providerToMjml = provider?.toMjml?.bind(provider);\n if (providerToMjml) {\n return providerToMjml(await source.buildPayload());\n }\n return source.renderLocalMjml();\n }\n\n async function toHtml(): Promise<string> {\n const provider = source.provider;\n\n const providerToHtml = provider?.toHtml?.bind(provider);\n if (providerToHtml) {\n return providerToHtml(await source.buildPayload());\n }\n\n const compileMjml = provider?.compileMjml?.bind(provider);\n if (compileMjml) {\n return compileMjml(await toMjml());\n }\n\n throw new Error(\n \"[Templatical] toHtml() requires a `render` provider implementing either \" +\n \"`toHtml` or `compileMjml`. The SDK does not bundle an MJML compiler, so \" +\n \"there is no local HTML path — point `compileMjml` at any mjml2html \" +\n \"endpoint (a hosted service, a container, or a CLI shell-out).\",\n );\n }\n\n function usesLocalRenderer(): boolean {\n return typeof source.provider?.toMjml !== \"function\";\n }\n\n function canRenderHtml(): boolean {\n return (\n typeof source.provider?.toHtml === \"function\" ||\n typeof source.provider?.compileMjml === \"function\"\n );\n }\n\n return { toMjml, toHtml, canRenderHtml, usesLocalRenderer };\n}\n","// eslint-disable-next-line @typescript-eslint/triple-slash-reference -- ambient-module declaration must be loaded for cross-package typecheck (workspace path alias resolves to source)\n/// <reference path=\"./virtual-modules.d.ts\" />\nimport { createApp, h, ref, type App, type Ref } from \"vue\";\nimport { DEFAULT_AUTO_SAVE_DEBOUNCE_MS } from \"@templatical/core\";\nimport type {\n AiProvider,\n Block,\n BlockDefaults,\n CollaborationProvider,\n CollaborationRemoteChange,\n ColorsConfig,\n CommentsProvider,\n CustomBlock,\n CustomBlockDefinition,\n DisplayConditionsConfig,\n EditorUser,\n FontsConfig,\n LogicTagsConfig,\n MediaProvider,\n MediaRequestContext,\n MediaResult,\n MergeTag,\n MergeTagsConfig,\n RenderProvider,\n SavedBlocksProvider,\n TestEmailProvider,\n Template,\n TemplateContent,\n TemplateDefaults,\n TemplateSettingsConfig,\n TemplatesProvider,\n ThemeOverrides,\n VersionHistoryProvider,\n UiTheme,\n ResolvePreview,\n} from \"@templatical/types\";\nimport {\n assertNoSlotInContent,\n assertNoWrapperInContent,\n createDefaultTemplateContent,\n safeClone,\n validateLayout,\n} from \"@templatical/types\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\n\nimport Editor from \"./Editor.vue\";\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport type { TemplaticalCloudEditorConfig } from \"./cloud/cloudConfig\";\nimport type { ResolveImageUrl } from \"./composables/useImageUrlResolver\";\nimport {\n getSupportedLocales,\n isLocaleSupported,\n loadTranslations,\n loadCloudTranslations,\n} from \"./i18n\";\nimport { logger } from \"./utils/logger\";\nimport { useFonts, type UseFontsReturn } from \"./composables\";\nimport { stripStylesheetImports } from \"./utils/stripStylesheetImports\";\nimport { toMjmlForInstance } from \"./utils/toMjml\";\nimport {\n normalizeBlockForConfig,\n normalizeContentForConfig,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport {\n buildRenderPayload,\n createRenderMethods,\n resolveRenderFonts,\n type RenderMethods,\n} from \"./utils/renderProvider\";\nimport type { HtmlBlockPreviewConfig } from \"./utils/resolveHtmlBlockPreview\";\n// Compiled-CSS-as-string for shadow root adoption. The `virtual:editor-css`\n// module is owned by `scripts/inline-style-css-plugin.ts` — at build time it\n// captures every emitted CSS asset (Tailwind utilities + every `.vue` SFC\n// `<style>` block + `styles/index.css` rules) and replaces this import's\n// runtime value with the full library CSS string. In dev/test the plugin\n// returns `styles/index.css` source as a fallback.\n//\n// Separate concern from the side-effecting `import \"./styles/index.css\"` in\n// `Editor.vue`, which injects styles into `document.head` for light-DOM mode and\n// survives untouched.\n//\n// `ownedStyleRoots` tells the dev style mirror which `document.head` styles are\n// the editor's when a host app compiles it from source (see\n// `attachDevStyleMirror`).\n//\n// Ambient declaration for `virtual:editor-css` lives in `virtual-modules.d.ts`\n// referenced at the top of this file via triple-slash so it's visible to any\n// consumer typechecking through the workspace path alias.\nimport editorStylesInline, { ownedStyleRoots } from \"virtual:editor-css\";\n\n// ---------------------------------------------------------------------------\n// OSS config + return types\n// ---------------------------------------------------------------------------\n\nexport interface TemplaticalEditorConfig {\n /**\n * Where to mount the editor — a CSS selector or an `HTMLElement`.\n *\n * Layout caveat: do NOT apply `transform`, `filter`, `perspective`, or\n * `will-change` to an ancestor of this element. Each establishes a CSS\n * containing block for `position: fixed`, which offsets the editor's\n * floating UI (color pickers, rich-text toolbars) and its drag ghost away\n * from their anchor — even when the transform's computed value is `none`\n * (an active/animated transform still promotes the element). For a\n * scroll/entrance effect on a wrapper, animate `opacity` instead of\n * `transform`.\n */\n container: string | HTMLElement;\n content?: TemplateContent;\n\n /**\n * Embedder-owned email shell, applied as an overlay at preview and at\n * `toMjml()` / `toHtml()`. Never written into `getContent()`, save, history,\n * or the editing canvas.\n *\n * A Templatical JSON document with exactly one `slot` — top-level (header /\n * footer / mat) or inside a layout `wrapper` (the card around author\n * sections). Build it with `createSlotBlock()` / `createWrapperBlock()`.\n *\n * See the [Layout](https://docs.templatical.com/guide/layout) guide.\n */\n layout?: TemplateContent;\n\n /**\n * Whether the section toolbar offers Add wrapper. Defaults to on\n * (`!== false`). Set `false` to hide the control, including where a\n * wrapper is legal (sibling-slot layout, or no layout).\n *\n * Presentation only: hiding never strips `section.wrapper` from content\n * and does not refuse `updateBlock`. A section that already has a wrapper\n * still shows the panel so it can be turned off.\n *\n * Independent of {@link layout}. A sibling-slot layout still wants the\n * control; hiding is this flag, not inferred from a layout being set.\n */\n sectionWrapper?: boolean;\n\n /**\n * Mount the editor inside a Shadow DOM (open mode) for CSS isolation\n * from the host page. Defaults to `true` — host stylesheets cannot\n * cascade past the shadow boundary into editor elements (`p`, `a`,\n * `input`, etc.), and editor utility classes never collide with host\n * class names.\n *\n * Set to `false` to mount in light DOM. Opt out when:\n * - Your host integration uses `document.querySelector` to reach\n * editor internals (with shadow DOM, use `container.shadowRoot\n * .querySelector(...)` instead).\n * - You need to support Firefox <101 or Safari <16.4, which lack the\n * `adoptedStyleSheets` API the shadow path relies on.\n *\n * Light-mode consumers should keep this set to `false` explicitly so\n * future SDK changes don't silently flip the default again.\n *\n * @default true\n */\n shadowDom?: boolean;\n\n onChange?: (content: TemplateContent) => void;\n onError?: (error: Error) => void;\n\n /**\n * Called whenever the editor's unsaved-changes state flips — `true` on the\n * first edit after a save, `false` once a save completes.\n *\n * Works with or without a `templates` provider, because the editor's own\n * `beforeunload` guard cannot cover SPA route changes: an embedded editor's\n * consumer has to guard their router themselves, and this is what they guard\n * it with.\n */\n onDirtyChange?: (isDirty: boolean) => void;\n\n /**\n * Storage backend for **the template itself** — the save/load lifecycle around\n * whatever is on the canvas.\n *\n * The editor owns the header's name field, save button and save-status\n * indicator, the Cmd+S shortcut, autosave and the unsaved-changes guard; you\n * own persistence. Three methods:\n *\n * ```ts\n * const editor = await init({\n * container,\n * templates: {\n * load: (id) => fetch(`/api/templates/${id}`).then((r) => r.json()),\n * create: (input) =>\n * fetch(\"/api/templates\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(input),\n * }).then((r) => r.json()),\n * save: (id, patch) =>\n * fetch(`/api/templates/${id}`, {\n * method: \"PATCH\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(patch),\n * }).then((r) => r.json()),\n * },\n * });\n *\n * await editor.load(\"tpl_123\");\n * ```\n *\n * Autosave (`templates.autoSave`), the unsaved-changes guard\n * (`templates.unsavedChangesGuard`) and the header's inline name field\n * (`templates.nameField`) are configured on this same object — grouped here\n * because none of the three mean anything without somewhere to save to.\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * name field, no save button, no status indicator — and `create()` / `load()` /\n * `save()` reject with an explanatory error. Persist the content yourself from\n * `onChange` instead; Cmd+S then flushes that notification immediately rather\n * than waiting out the debounce.\n *\n * Opening a template is deliberately imperative: there is no `templateId`\n * config key and no in-editor template browser, because choosing which\n * template to open belongs to your application.\n */\n templates?: TemplatesProvider;\n\n /**\n * Rendering backend — how the template becomes MJML, and how MJML becomes the\n * HTML you send.\n *\n * Separate from `templates` on purpose: saving and rendering run at different\n * frequencies (autosave would compile MJML on every debounce tick) and fail in\n * different ways. Every method is optional, and `editor.toMjml()` /\n * `editor.toHtml()` resolve each one independently:\n *\n * | Call | Order |\n * |---|---|\n * | `toMjml()` | `render.toMjml` → the bundled `@templatical/renderer` → throw |\n * | `toHtml()` | `render.toHtml` → `toMjml()`'s result + `render.compileMjml` → throw |\n *\n * **Omitted by default**, in which case `toMjml()` renders locally and\n * `toHtml()` rejects — the SDK deliberately bundles no MJML compiler, so there\n * is no local HTML path. One endpoint is enough to close that gap:\n *\n * ```ts\n * init({\n * container,\n * render: {\n * compileMjml: (mjml) =>\n * fetch(\"/api/mjml\", { method: \"POST\", body: mjml }).then((r) => r.text()),\n * },\n * });\n * ```\n *\n * Provider methods receive a **render-complete** payload: custom blocks already\n * resolved to `renderedHtml`, and the editor's effective fonts. Both are things\n * a backend cannot reconstruct from the template JSON alone.\n */\n render?: RenderProvider;\n\n /**\n * Storage backend for the template's **version history** — the past states a\n * user can browse, preview and restore.\n *\n * The editor owns the header's history control, the preview banner and the\n * restore flow; you own the storage. `list` and `get` are the operations;\n * `create` and `restore` can each be turned off by passing `false` instead of\n * a function.\n *\n * ```ts\n * init({\n * container,\n * versionHistory: {\n * list: (templateId) =>\n * fetch(`/api/templates/${templateId}/versions`).then((r) => r.json()),\n * get: (templateId, versionId) =>\n * fetch(`/api/templates/${templateId}/versions/${versionId}`)\n * .then((r) => r.json())\n * .then((v) => v.content),\n * create: false,\n * restore: (templateId, versionId) =>\n * fetch(`/api/templates/${templateId}/versions/${versionId}/restore`, {\n * method: \"POST\",\n * }).then((r) => r.json()),\n * },\n * });\n * ```\n *\n * **Omitted by default** — the control does not render and none of its UI is\n * downloaded. It also stays hidden until a template is loaded, since a version\n * belongs to a template id.\n *\n * **The editor never records a version by itself.** Whichever\n * `TemplatesProvider.save` you supply decides whether a save also records one,\n * so throttling and retention stay with the side that pays for the storage.\n */\n versionHistory?: VersionHistoryProvider;\n\n /**\n * How long the editor waits after the last edit before it fires `onChange`\n * and, when `templates.autoSave` is on, saves.\n *\n * One timer drives both, so they cannot drift apart. Set it with no templates\n * provider to pace `onChange` alone.\n *\n * @default 2000\n */\n changeDebounce?: number;\n\n /**\n * Storage backend for the **media library** — the picker behind Browse on\n * image fields, video thumbnails, and custom-block image fields.\n *\n * The editor owns the modal, grid, crop and insertion; you own persistence.\n * `list` is required; every other method is `false | fn`. All mutations\n * `false` is a read-only library: browse, search and pick still work.\n *\n * Implement the methods of `MediaProvider` against your own API, or use\n * the bundled browser-local provider for demos and prototypes:\n *\n * ```ts\n * import { init, createLocalStorageMediaProvider } from \"@templatical/editor\";\n *\n * init({ container, media: createLocalStorageMediaProvider() });\n * ```\n *\n * **Omitted by default.** Image fields stay URL-only. `onRequestMedia` is\n * the UI override (a host widget) and wins when both are set.\n */\n media?: MediaProvider;\n\n onRequestMedia?: OnRequestMedia;\n\n /**\n * Resolves the template for preview surfaces — typically evaluating logic\n * tags (`{% if %}` … `{% endif %}`) against real data on your backend.\n *\n * Called when a preview opens and when the test-email recipient changes,\n * debounced. Display-only: the result never reaches `getContent()`, a send or\n * an export. Rejecting is safe — the preview falls back to the unresolved\n * template and says so.\n *\n * Supersedes `MergeTag.sample` when configured: real data beats example data,\n * so the Sample/Label switch stops rendering.\n */\n resolvePreview?: ResolvePreview;\n\n /**\n * Display-only resolver for image `src` values. The canvas calls this to\n * obtain a preview URL for a src the user entered; the content model (and\n * `toMjml()` output) always keeps the canonical value. Return `null` — or\n * the input value — to use the src as-is.\n *\n * Use this when templates reference images by a value that isn't directly\n * displayable, e.g. plain file names resolved to ephemeral `blob:` URLs\n * from local storage:\n *\n * ```ts\n * resolveImageUrl: async (src) => {\n * const file = await fileStore.lookup(src);\n * return file ? URL.createObjectURL(file) : null;\n * }\n * ```\n *\n * The resolver is called once per committed src value (typing in the src\n * input is debounced, so partial values never reach it) and results are\n * cached per src for the editor's lifetime — including failures, which\n * fall back to displaying the src verbatim. Note the caching applies to\n * transient failures too: a src that failed to resolve stays unresolved\n * until the editor is re-initialized (a re-resolve hook may be added\n * later). Applies to image srcs, design-time placeholder previews, explicit\n * video thumbnails, and section and wrapper background images;\n * auto-derived provider thumbnails (YouTube/Vimeo) are already real URLs and\n * are never resolved, and a background image whose URL holds a merge tag is\n * neither resolved nor painted.\n */\n resolveImageUrl?: ResolveImageUrl;\n\n mergeTags?: MergeTagsConfig;\n /**\n * Standalone logic tags — control-flow tokens (`{% else %}`) and open/close\n * pairs (`{% if %}` … `{% endif %}`) inserted from a dedicated \"Insert logic\"\n * button. Separate from `mergeTags`; typed/pasted logic is highlighted\n * regardless of this config.\n */\n logicTags?: LogicTagsConfig;\n displayConditions?: DisplayConditionsConfig;\n customBlocks?: CustomBlockDefinition[];\n\n /**\n * Allowlist + order for the block palette. When non-empty, only the listed\n * block types appear in the sidebar palette, in exactly this order —\n * unlisted built-ins (e.g. `video`, `table`) are hidden. When omitted or\n * empty (`[]`), the full default palette is shown: an empty allowlist means\n * \"not configured\", not \"hide every block\".\n *\n * Reference built-in blocks by their bare type (`'section'`, `'image'`, …)\n * and custom blocks by their `custom:`-prefixed type (`'custom:qrcode'`),\n * so they can be interleaved freely:\n *\n * ```ts\n * paletteBlocks: ['section', 'title', 'image', 'custom:qrcode', 'button']\n * ```\n *\n * `'hero'` is a shortcut, not a block type: it inserts a one-column section\n * in hero mode with starter content.\n *\n * Unknown entries — a typo, an unregistered custom block, or `countdown`\n * outside a Cloud plan — are logged with a warning and skipped. Filtering\n * the palette never affects rendering: existing content using a hidden\n * block type still renders correctly.\n */\n paletteBlocks?: string[];\n\n /**\n * Render each HTML block's raw content as a live preview in the editor\n * canvas instead of the static placeholder card. **Off by default.**\n *\n * ```ts\n * htmlBlockPreview: true // shorthand for { enabled: true }\n * htmlBlockPreview: { enabled: true }\n * ```\n *\n * The content is rendered verbatim inside a sandboxed `<iframe>`\n * (`sandbox=\"allow-same-origin\"`, **no** `allow-scripts`): scripts and\n * inline event handlers never execute and styles can't bleed into the rest\n * of the editor. This is a preview-only setting — the MJML/HTML export path\n * renders HTML blocks regardless of it.\n *\n * @default false\n */\n htmlBlockPreview?: HtmlBlockPreviewConfig;\n\n fonts?: FontsConfig;\n\n /**\n * Base URL for the social-icon PNGs the renderer references in exported MJML\n * (the `<mj-image>` src for each Social block icon). Forwarded to\n * `@templatical/renderer`’s `socialIconsBaseUrl`; when omitted the renderer\n * uses its version-pinned jsDelivr default. Set it to self-host the icons\n * from your own origin. Trailing slash optional.\n *\n * Applies to the local `toMjml()` / `toHtml()` (via `compileMjml`) path only.\n * A `render.toMjml` provider wins over the bundled renderer and never sees\n * this — pass the URL to your own `renderToMjml` there. The editing canvas is\n * unaffected either way (it draws icons as inline SVG).\n */\n socialIconsBaseUrl?: string;\n\n /**\n * Editor-wide color-picker palette. `presets` appear as a clickable grid in\n * every color picker popover (block toolbars, template settings, rich-text\n * color, custom-block color fields) — clicking one applies it, and the preset\n * matching the current value is marked selected.\n *\n * ```ts\n * colors: {\n * presets: ['#0b5cff', '#111827', '#6b7280', '#ffffff'],\n * allowCustom: false, // lock authors to the presets above\n * }\n * ```\n *\n * `allowCustom` defaults to `true`. Set it to `false` (together with\n * `presets`) to hide the wheel and hex input so authors can only pick from the\n * palette — useful when embedding the editor as a white-label / brand-kit\n * tool. `allowCustom: false` is ignored, with a warning, when no `presets` are\n * configured, since that would leave the picker with no way to set a color.\n */\n colors?: ColorsConfig;\n\n /**\n * Which template settings the Settings panel exposes — an allowlist over the\n * members of `TemplateSettings`.\n *\n * ```ts\n * // Layout and Appearance only: no Language card, no Preheader card.\n * templateSettings: { fields: ['width', 'backgroundColor', 'fontFamily'] }\n *\n * templateSettings: { fields: false } // no Settings tab at all\n * ```\n *\n * **Omitted by default**, in which case every setting is editable. The list\n * only narrows: a card renders while at least one of its settings survives,\n * and the tab itself stops rendering once none do. It never reorders —\n * settings sit in fixed cards, so unlike {@link paletteBlocks} there is no\n * order to express.\n *\n * Presentation only, and not a security boundary. Hiding a setting never\n * changes its value: whatever the loaded content carries keeps rendering and\n * keeps round-tripping through `getContent()`. Set the ones you hide from the\n * content you hand the editor — `init({ content })`, or the `templates`\n * provider's own `load`, which is the seam for \"this template's locale comes\n * from my application, not from the author\".\n *\n * Sibling restrictions live on their own keys: {@link paletteBlocks} for the\n * block palette, `fonts.builtIns` for the font picker, `colors.allowCustom`\n * for free-form colors, and `templates.nameField` for the header's name.\n */\n templateSettings?: TemplateSettingsConfig;\n\n /**\n * Storage backend for **saved blocks** — reusable groups of blocks a user\n * saves from the canvas and re-inserts into other templates.\n *\n * The editor owns the UI (a save action on each block, a searchable browser\n * with preview, insert-at-position, rename, delete); you own persistence.\n * Implement the four methods of `SavedBlocksProvider` against your own API,\n * or use the bundled browser-local provider for demos and prototypes:\n *\n * ```ts\n * import { init, createLocalStorageSavedBlocksProvider } from \"@templatical/editor\";\n *\n * init({ container, savedBlocks: createLocalStorageSavedBlocksProvider() });\n * ```\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * save action, no sidebar entry, and none of its UI code is downloaded.\n *\n * Not to be confused with `customBlocks`, which registers developer-defined\n * block *types* with their own templates and field schemas.\n */\n savedBlocks?: SavedBlocksProvider;\n\n /**\n * Sending backend for **test emails** — letting a user mail themselves the\n * template they're editing.\n *\n * The editor owns the trigger, the dialog, recipient validation and the\n * sending/success/error states; you own delivery. One method is enough:\n *\n * ```ts\n * init({\n * container,\n * testEmail: {\n * send: ({ recipient, content }) =>\n * fetch(\"/api/test-email\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ recipient, content }),\n * }).then((r) => {\n * if (!r.ok) throw new Error(\"Could not send the test email\");\n * }),\n * },\n * });\n * ```\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * button, and none of its UI code is downloaded.\n *\n * `allowedRecipients` restricts the picker but is **not** a security boundary:\n * it lives in the user's browser. Validate the recipient on your server.\n */\n testEmail?: TestEmailProvider;\n\n /**\n * Storage backend for **comments** — the review conversation on a template.\n *\n * The editor owns the panel, the threading, the resolve flow, the per-block\n * indicators and the jump-to-block affordance; you own persistence. Five\n * methods, each mutation turn-off-able by passing `false`:\n *\n * ```ts\n * init({\n * container,\n * user: { id: \"u_7\", name: \"Ada\" },\n * comments: {\n * list: (templateId) =>\n * fetch(`/api/templates/${templateId}/comments`).then((r) => r.json()),\n * create: (templateId, input) =>\n * fetch(`/api/templates/${templateId}/comments`, {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(input),\n * }).then((r) => r.json()),\n * update: (templateId, commentId, patch) =>\n * fetch(`/api/templates/${templateId}/comments/${commentId}`, {\n * method: \"PATCH\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(patch),\n * }).then((r) => r.json()),\n * delete: async (templateId, commentId) => {\n * await fetch(`/api/templates/${templateId}/comments/${commentId}`, {\n * method: \"DELETE\",\n * });\n * },\n * setResolved: (templateId, commentId, resolved) =>\n * fetch(`/api/templates/${templateId}/comments/${commentId}/resolve`, {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ resolved }),\n * }).then((r) => r.json()),\n * },\n * });\n * ```\n *\n * **Requires {@link user}** — with no identity the feature reports itself\n * unavailable and nothing renders, rather than writing anonymous comments.\n *\n * **Omitted by default**, and the panel also stays hidden until a template is\n * loaded, since a comment belongs to a template id.\n *\n * The same object also carries outward events — `onCreated`, `onUpdated`,\n * `onDeleted`, `onResolved`, `onUnresolved` — each called with the comment and\n * whether the change was made locally or arrived through `subscribe`. That's\n * the hook for a \"3 new comments\" badge outside the editor.\n *\n * Realtime is an optional `subscribe` on the provider, not a prerequisite:\n * without it comments work identically, you simply see a colleague's on the next\n * read rather than immediately.\n */\n comments?: CommentsProvider;\n\n /**\n * Real-time collaboration over your backend: ordered operations, presence and\n * block locks.\n *\n * ```ts\n * const editor = await init({\n * container,\n * templates,\n * collaboration: {\n * join: (templateId, session, handlers) => myRealtime.join(templateId, session, handlers),\n * submit: (templateId, batch) => post(`/api/templates/${templateId}/operations`, batch),\n * operationsAfter: (templateId, revision) =>\n * get(`/api/templates/${templateId}/operations?after=${revision}`),\n * acquireLock: (templateId, blockId) => post(`/api/templates/${templateId}/locks`, { blockId }),\n * renewLock: (templateId, blockId) => put(`/api/templates/${templateId}/locks/${blockId}`),\n * releaseLock: (templateId, blockId) => del(`/api/templates/${templateId}/locks/${blockId}`),\n * },\n * });\n * await editor.load(\"tpl_123\");\n * ```\n *\n * **Needs `templates`**: a session joins a loaded template, and `load` must\n * return the template's `revision`. With a collaboration provider, every edit\n * reaches your backend as an operation through `submit`, so `templates.save`\n * receives only renames, and undo and redo send inverse operations that your\n * backend can refuse. Selecting a block takes its lock; the three lock methods\n * are optional together. Apply operations on your server with\n * `applyOperations` from `@templatical/types`.\n *\n * **Omitted by default.** See the Collaboration page under Connect your backend.\n */\n collaboration?: CollaborationProvider;\n\n /**\n * A batch of edits from another session landed on the canvas: who made it\n * (`actor`) and the operations. Not called for this editor's own edits, and\n * not for a re-sync that reloads the whole template.\n */\n onRemoteChange?: (change: CollaborationRemoteChange) => void;\n\n /**\n * Your AI backend: a chat that edits the template with Undo, rewrite in the\n * paragraph toolbar, static localized chat starters and\n * chat attachments. One member per feature; `false` leaves it out and the\n * editor hides its entry point:\n *\n * ```ts\n * import { createHttpAiProvider } from \"@templatical/ai-kit/client\";\n *\n * const editor = await init({\n * container,\n * templates,\n * ai: createHttpAiProvider({ baseUrl: \"/api/ai\" }),\n * });\n * await editor.load(\"tpl_123\");\n * ```\n *\n * **Needs a loaded template**: every AI request names it, so the entry\n * points show once `create()` or `load()` has resolved. With\n * `collaboration`, the AI's edits travel as this user's batches marked\n * `origin: \"ai\"`; without it they apply here. Either way a turn is one\n * Cmd/Ctrl+Z. Failures reach `onError`.\n *\n * **Omitted by default.** See AI under Connect your backend.\n */\n ai?: AiProvider;\n\n /**\n * Who is using the editor — needed by any feature that attributes work to a\n * person: {@link comments}, and the collaborator bar, which leaves this user's\n * own sessions out. It is a top-level key rather than part of either provider.\n *\n * ```ts\n * init({ container, user: { id: \"u_7\", name: \"Ada Lovelace\" } });\n * ```\n *\n * Not a security boundary — it identifies the user to the editor's UI, in the\n * user's own browser. Attribute writes server-side from the session your backend\n * already trusts.\n */\n user?: EditorUser;\n\n blockDefaults?: BlockDefaults;\n templateDefaults?: TemplateDefaults;\n\n theme?: ThemeOverrides;\n uiTheme?: UiTheme;\n locale?: string;\n\n /**\n * Show the \"Powered by Templatical\" footer. Defaults to `true`.\n * Set to `false` to hide the footer (no attribution required by the license).\n */\n branding?: boolean;\n\n /**\n * Show a \"use a larger screen\" notice instead of the editor chrome on\n * viewports narrower than ~768px. Defaults to `true`.\n *\n * The drag-and-drop editor is a desktop-class tool — the block palette,\n * canvas, and properties panel can't lay out usably on a phone, and touch\n * dragging is impractical. Rather than render a broken, cramped layout, the\n * editor shows a clear message below the breakpoint.\n *\n * Set to `false` if you handle small screens yourself (e.g. you embed the\n * editor in a deliberately narrow desktop pane). The check is viewport-based,\n * so it targets actual small devices, not narrow containers on a wide screen.\n *\n * @default true\n */\n smallScreenNotice?: boolean;\n\n /**\n * Template linter (`@templatical/quality`) configuration. Runs every\n * linter exported by the package (accessibility + structure).\n *\n * - When unset, the linter loads on demand once the user opens the panel.\n * - When `disabled: true`, the optional peer is never imported (saves the\n * chunk download) and the sidebar tab + inline badges are suppressed.\n * - `rules`/`thresholds` follow the shape exported by `@templatical/quality`.\n */\n lint?: import(\"@templatical/quality\").LintOptions;\n}\n\n/** Function type for media browser requests, used by both OSS and Cloud editors. */\nexport type OnRequestMedia = (\n context?: MediaRequestContext,\n) => Promise<MediaResult | null>;\n\ninterface TemplaticalEditorBase {\n getContent(): TemplateContent;\n setContent(content: TemplateContent): void;\n /**\n * Insert a block where a click on a palette item would put it: below the\n * selected block, in the same column when the selection is inside a section\n * (a section lands after that section instead), or at the end when nothing\n * usable is selected. The new block is selected and scrolled into view, so\n * repeated calls stack in order.\n *\n * The block is inserted as given: the editor defaults a palette block is\n * built with (`blockDefaults`, localized placeholder text, RTL alignment)\n * aren't applied, so insert ready-made content rather than fresh factory\n * blocks.\n *\n * Inserts a copy with fresh ids, so the same block can be inserted twice.\n * Bare merge tags are converted the same way `setContent` converts them.\n * Returns the inserted copy's id, or `null` once the instance is unmounted\n * or replaced by a later `init()` on its container, in preview mode (with a\n * warning), or when the block could not be placed. A slot or wrapper block\n * throws, as it does in `setContent`.\n */\n insertBlock(block: Block): string | null;\n setTheme(theme: UiTheme): void;\n /**\n * Replace the configured merge tags after `init()`.\n *\n * Everything that renders a tag reads the same list, so a replacement\n * repaints the canvas, the sidebar fields and the built-in picker together.\n * Use it when tags are minted or renamed while the editor is open — mutating\n * the array you passed to `init()` is not a supported substitute and will\n * not repaint anything already on screen.\n *\n * Type-ahead autocomplete is the one exception: whether it is active is\n * decided when a block opens for editing, so going from no tags to some\n * enables it for the next block opened, not one already being edited.\n */\n setMergeTags(tags: MergeTag[]): void;\n /**\n * Tear this editor down. It unmounts only this instance: once a later\n * `init()` on the same container has replaced it, or kept it from mounting,\n * calling `unmount()` here does nothing, so a stale handle never removes the\n * editor that replaced it. Calling it again after the teardown is also a\n * no-op.\n */\n unmount(): void;\n /**\n * Render the current template to MJML.\n *\n * Resolves `render.toMjml` first when a `render` provider supplies it, then the\n * bundled `@templatical/renderer` (which resolves custom blocks through the\n * editor's own registry). Rejects with a clear error when neither is available —\n * i.e. no provider method *and* the optional `@templatical/renderer` peer isn't\n * installed.\n */\n toMjml(): Promise<string>;\n /**\n * Render the current template to sending-ready HTML.\n *\n * Resolves `render.toHtml` first, then `toMjml()`'s output through\n * `render.compileMjml`. **Requires one of the two** — the SDK bundles no MJML\n * compiler, so with no `render` provider this always rejects, and the error says\n * which method to add.\n */\n toHtml(): Promise<string>;\n}\n\nexport interface TemplaticalEditor extends TemplaticalEditorBase {\n /**\n * Persist the current content as a new template through the configured\n * `templates` provider, and make the result the editor's template.\n *\n * `input.content`, when given, replaces the editor's content first. Always\n * present on the type; rejects with an explanatory error when no provider is\n * configured or when the provider set `create: false` — the same convention as\n * {@link toMjml}.\n */\n create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template>;\n /** Load a template by id and make it the editor's content. */\n load(templateId: string): Promise<Template>;\n /**\n * Persist the loaded template — name and content, as one patch. Rejects when\n * no provider is configured, when the provider set `save: false`, or when no\n * template has been created or loaded yet.\n */\n save(): Promise<Template>;\n /**\n * Whether there are edits the editor knows aren't persisted. Cleared by a\n * successful `save()` / `create()` / `load()`.\n *\n * Read it in a router guard; `onDirtyChange` is the push-based counterpart.\n */\n isDirty(): boolean;\n /**\n * Render a single custom block to its HTML representation, using the\n * registered custom block definition's template and the block's current\n * field values. `toMjml()` wires this into the renderer automatically.\n * Headless callers with definitions pass them as `customBlocks` to\n * `@templatical/renderer`.\n */\n renderCustomBlock(block: CustomBlock): Promise<string>;\n /**\n * Look up the definition-level `stylesheet` for a registered custom block\n * type. Returns the raw CSS string, or `undefined` when the type is unknown\n * or the definition has no stylesheet. `toMjml()` wires this into the\n * renderer automatically. Headless callers pass their definitions as\n * `customBlocks` to `@templatical/renderer`.\n */\n getCustomBlockStylesheet(customType: string): string | undefined;\n}\n\n/**\n * `initCloud()` returns the **same** editor `init()` does.\n *\n * That is the point rather than a tidy-up: Cloud is a set of provider\n * implementations behind the same interfaces a consumer would implement, so if\n * the two entry points still returned different shapes, the claim would be\n * false. It also means moving between them is a config change and never a\n * rewrite of the calling code.\n *\n * Three cloud-only members went with the convergence: `create()` takes\n * `init()`'s `{ name?, content? }` input object now, rather than a bare\n * `TemplateContent`; `setThemeOverrides` is gone (`config.theme` is applied\n * at init on both entry points, and the entitlement that gated changing it\n * later is gone); and `sendTestEmail` is gone (the shared dialog is the\n * supported path).\n */\nexport type TemplaticalCloudEditor = TemplaticalEditor;\n\n// ---------------------------------------------------------------------------\n// Shadow root helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Module-cached `CSSStyleSheet` built once from the inline editor CSS string.\n * `adoptedStyleSheets` accepts the same sheet object across multiple shadow\n * roots — sharing one sheet costs zero per-instance memory, regardless of\n * how many editors mount.\n */\nlet cachedEditorStyleSheet: CSSStyleSheet | null = null;\n\nfunction getEditorStyleSheet(): CSSStyleSheet {\n if (cachedEditorStyleSheet === null) {\n const sheet = new CSSStyleSheet();\n // The one `@import` in the editor's CSS loads Geist. The document-level\n // stylesheet (`style.css`, or `editor.css` from the CDN) imports it too,\n // and font faces loaded there reach the shadow tree, so stripping it\n // here loses nothing and keeps `replaceSync` from warning.\n sheet.replaceSync(stripStylesheetImports(editorStylesInline));\n cachedEditorStyleSheet = sheet;\n }\n return cachedEditorStyleSheet;\n}\n\ninterface MountTarget {\n target: Element;\n shadowRoot: ShadowRoot | null;\n /**\n * Disposer for any dev-mode side effects attached to the shadow root\n * (currently: the document.head `<style>` mirror's MutationObserver).\n * Always safe to call — no-op when no side effects were registered.\n */\n cleanup: () => void;\n}\n\n/**\n * Whether the dev mirror copies one `document.head` style. Vite tags each\n * style it injects with `data-vite-dev-id`, the source path, so with\n * `ownedStyleRoots` set only the editor's styles and the third-party CSS it\n * imports pass. An untagged style was injected at runtime (TipTap's\n * `<style data-tiptap-style>`) and stays mirrored: in production it never\n * reaches the shadow root, and that gap is #869, which waits on an upstream\n * TipTap fix.\n */\nfunction isMirroredStyle(el: HTMLStyleElement): boolean {\n if (!ownedStyleRoots) return true;\n const devId = el.getAttribute(\"data-vite-dev-id\");\n if (devId === null) return true;\n const path = devId.replace(/\\\\/g, \"/\");\n return (\n ownedStyleRoots.some((root) => path.startsWith(root)) ||\n path.includes(\"/node_modules/\")\n );\n}\n\n/**\n * Dev-only: mirror every `<style>` tag in `document.head` into the\n * shadow root's `adoptedStyleSheets`, and observe `document.head` so\n * Vite's HMR-injected style updates flow through to the shadow root\n * automatically.\n *\n * Background: Vite dev injects each `.vue` `<style scoped>` block as a\n * separate `<style>` element in `document.head` via HMR. Those don't\n * cross the shadow boundary, so a shadow-mounted editor in dev would\n * render with only the bundled `styles/index.css` rules — every SFC\n * scoped style (block selection outlines, sidebar layout, etc.) missing.\n *\n * In production builds, `inline-style-css-plugin.ts` captures every\n * emitted CSS asset at `generateBundle` time and inlines the full\n * library CSS as a single string adopted by the shadow root. This\n * dev-only mirror does the same thing at runtime by observing whatever\n * Vite ends up injecting.\n *\n * The dead-code-elimination on `import.meta.env.DEV` ensures the\n * observer + filter logic is stripped from production bundles entirely.\n *\n * Caveats:\n * - A host app that compiles the editor from source has its own styles\n * in `document.head` too. It passes `ownedRoots` to the CSS plugin,\n * and then only the editor's styles are mirrored (`isMirroredStyle`).\n * Without that option, the host's page-level styles are adopted as\n * well. That's harmless when consumers install the editor from npm\n * dist (the dev branch is dead-coded out).\n * - A constructed sheet cannot hold `@import`: `replaceSync` drops each\n * such rule and logs a warning, so they are stripped before the call.\n */\nfunction attachDevStyleMirror(shadowRoot: ShadowRoot): () => void {\n if (!import.meta.env?.DEV) return () => {};\n\n function buildSheets(): CSSStyleSheet[] {\n const sheets: CSSStyleSheet[] = [];\n // shadow-ok: dev-only HMR style mirror (production path is plugin-driven via adoptedStyleSheets)\n document.head.querySelectorAll(\"style\").forEach((el) => {\n if (!isMirroredStyle(el)) return;\n const text = el.textContent;\n if (!text) return;\n try {\n const sheet = new CSSStyleSheet();\n // These are document styles, so the document has loaded their\n // imports already.\n sheet.replaceSync(stripStylesheetImports(text));\n sheets.push(sheet);\n } catch {\n // Skip a style the CSSOM refuses to parse.\n }\n });\n return sheets;\n }\n\n function refresh(): void {\n // Keep the editor's primary (bundled) sheet first so its declarations\n // are the cascade fallback; dev sheets adopted after may override them\n // — same precedence model as production where everything ends up in\n // one stylesheet anyway.\n shadowRoot.adoptedStyleSheets = [getEditorStyleSheet(), ...buildSheets()];\n }\n\n refresh();\n\n const observer = new MutationObserver(() => refresh());\n // childList catches new/removed <style> tags; characterData + subtree\n // catches Vite HMR mutating an existing style's textContent in place.\n // shadow-ok: dev-only HMR style mirror observer\n observer.observe(document.head, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n\n return () => observer.disconnect();\n}\n\n/**\n * Resolve where Vue should mount: directly on the consumer's container\n * (light-DOM mode) or on a fresh `<div>` inside a newly-attached open\n * shadow root (shadow mode). In shadow mode, also attaches the editor's\n * cached `CSSStyleSheet` to the root so chrome renders with the right\n * styles inside the boundary, plus a dev-only mirror that observes\n * `document.head` (see `attachDevStyleMirror`).\n *\n * Idempotent: a second call on the same container reuses any existing\n * shadow root, clearing its contents so a prior mount's stale DOM doesn't\n * accumulate.\n */\nfunction resolveMountTarget(\n container: Element,\n shadowDom: boolean | undefined,\n): MountTarget {\n if (!shadowDom) {\n return { target: container, shadowRoot: null, cleanup: () => {} };\n }\n\n const shadowRoot =\n container.shadowRoot ?? container.attachShadow({ mode: \"open\" });\n\n // Adopt the editor stylesheet. Idempotent — repeated assignment of the\n // same sheet is fine. Dev mirror (below) will overwrite this with the\n // primary sheet + mirrored sheets, then keep them in sync.\n shadowRoot.adoptedStyleSheets = [getEditorStyleSheet()];\n\n // Clear stale content from a prior mount (re-init on same container).\n while (shadowRoot.firstChild) {\n shadowRoot.removeChild(shadowRoot.firstChild);\n }\n\n const host = document.createElement(\"div\");\n host.className = \"tpl-editor-host\";\n // Match the container's layout. Without an explicit size the host is a\n // default block element (height: auto) and the editor's `tpl:h-full`\n // template root collapses to content height because the height-100% chain\n // breaks at the shadow boundary. `width: 100%` is redundant for block\n // elements but harmless and explicit.\n host.style.cssText = \"display:block;height:100%;width:100%;\";\n shadowRoot.appendChild(host);\n\n const cleanup = attachDevStyleMirror(shadowRoot);\n\n return { target: host, shadowRoot, cleanup };\n}\n\n// ---------------------------------------------------------------------------\n// OSS init — sync\n// ---------------------------------------------------------------------------\n\ninterface OssEntry {\n app: App;\n editorRef: Ref<InstanceType<typeof Editor> | null>;\n /** Tear down dev-mode side effects (style mirror observer, etc.). */\n cleanup: () => void;\n}\n\n// Per-container registry so two `init()` calls with different containers\n// produce independent editor instances (multi-instance support). Re-init\n// on the same container still auto-unmounts the previous instance.\nconst ossEntries = new Map<Element, OssEntry>();\n\n// \"Last init'd\" container preserves the legacy single-instance behavior\n// of the top-level `unmount()` export — the playground (and other one-\n// editor consumers) calls bare `unmount()` and expects it to tear down\n// whatever was most recently mounted.\nlet lastOssContainer: Element | null = null;\n\n// Which call may take a container over. Every `init()` / `initCloud()` whose\n// `layout` and `content` pass `prepareLayoutAndContent` claims its container\n// before its first await, and mounts only if its claim is still the latest once\n// its awaits settle. Calls on one container settle in whatever\n// order their awaits finish (under React StrictMode's dev double effect, the\n// cancelled first call can settle after the second one mounted), so the order\n// the calls were made in decides which editor the container keeps. A WeakMap,\n// so a container that leaves the page takes its claim with it.\nlet lastClaimToken = 0;\nconst containerClaims = new WeakMap<Element, number>();\n\ninterface ContainerClaim {\n container: Element;\n token: number;\n}\n\n/**\n * Resolve the configured container and claim it for this call. Runs before\n * the first await of `init()` and `initCloud()`, so claims follow call order.\n */\nfunction claimContainer(target: string | HTMLElement): ContainerClaim {\n const container =\n typeof target === \"string\" ? document.querySelector(target) : target;\n\n if (!container) {\n throw new Error(`[Templatical] Container element not found: ${target}`);\n }\n\n const token = ++lastClaimToken;\n containerClaims.set(container, token);\n return { container, token };\n}\n\n// Tears down whatever app the container holds, or with `onlyApp` just that app:\n// an instance unmounts only itself. A StrictMode double-mount can call a\n// superseded instance's `unmount()` after its replacement mounted on the same\n// container, and a container-scoped teardown there removes the replacement and\n// leaves a blank editor. `mountEditor`'s auto-unmount and the top-level\n// `unmount()` export pass no `onlyApp`: they mean \"whatever this container\n// holds now\".\nfunction unmountOssContainer(container: Element, onlyApp?: App): void {\n const entry = ossEntries.get(container);\n if (!entry) return;\n if (onlyApp && entry.app !== onlyApp) return;\n entry.cleanup();\n entry.app.unmount();\n ossEntries.delete(container);\n if (lastOssContainer === container) {\n lastOssContainer = null;\n }\n}\n\n/**\n * Normalize the merge tags in `layout` and `content`, then refuse an illegal\n * tree. `init()` and `initCloud()` run this when they are called, before they\n * claim the container. A call that throws here rejects at once: it supersedes\n * no earlier call, and the container and the editor it shows stay exactly as\n * they were.\n *\n * Merge tags reach us in one of two shapes, and only one of them behaves like\n * a tag. Anything typed or pasted is already a `<span data-merge-tag>`, since\n * `MergeTagNode`'s input rules convert it on the spot; content that arrived\n * any other way — a consumer's stored JSON, an `@templatical/import-*`\n * conversion — still holds bare `{{tokens}}` that render as plain text.\n * Normalizing here, before the seed reaches `Editor.vue`, means core is\n * handed content that is already correct and never observes a mutation, so\n * nothing is marked dirty and no autosave tick fires for a load.\n *\n * This is one of four places content enters. The other three:\n * `instance.setContent` and `instance.create` below, and the `templates`\n * provider's `load`, wrapped in `Editor.vue` where it reaches core.\n * Overlay chrome is not seed content: merge tags in the shell, then refuse\n * an illegal tree.\n */\nfunction prepareLayoutAndContent(\n config: Pick<TemplaticalEditorConfig, \"layout\" | \"content\" | \"mergeTags\">,\n): void {\n if (config.layout) {\n config.layout = normalizeContentForConfig(config.layout, config.mergeTags);\n validateLayout(config.layout);\n }\n if (config.content) {\n config.content = normalizeContentForConfig(\n config.content,\n config.mergeTags,\n );\n assertNoSlotInContent(config.content);\n assertNoWrapperInContent(config.content);\n }\n}\n\nexport async function init(\n config: TemplaticalEditorConfig,\n): Promise<TemplaticalEditor> {\n // A copy, as `initCloud()` makes: the editor never writes to the caller's\n // config, which may be frozen. A key reassigned on that object after this call\n // does not reach the editor.\n const prepared = { ...config };\n prepareLayoutAndContent(prepared);\n return mountEditor(prepared, claimContainer(prepared.container));\n}\n\n/**\n * The one mount path. `init()` calls it with no runtime; `initCloud()` calls it\n * with Cloud's, having already resolved auth, the plan and every adapter. Both\n * prepare `layout` and `content` and claim the container when they are called,\n * before this runs.\n */\nasync function mountEditor(\n config: TemplaticalEditorConfig,\n { container, token }: ContainerClaim,\n cloud?: CloudRuntime,\n): Promise<TemplaticalEditor> {\n // An unusable `locale` fell back to English in silence, so a typo — \"gr\" for\n // Greek (the country code, not the language code \"el\"), or \"english\" — was\n // indistinguishable from the option being ignored. Regions and stray\n // whitespace are NOT typos: they resolve to a base language by design.\n // `paletteBlocks` and `colors` both warn on input they cannot use; this makes\n // the third config option behave the same. Deliberately NOT extended to the\n // cloud chunk, which ships fewer locales on purpose (`guide/i18n.md` tells\n // contributors not to translate it) — warning there would fire for every\n // fr/es/nl/ca consumer, who did nothing wrong.\n if (config.locale !== undefined && !isLocaleSupported(config.locale)) {\n logger.warn(\n `config.locale: \"${config.locale}\" has no translations — falling back ` +\n `to English. Supported: ${getSupportedLocales().sort().join(\", \")}.`,\n );\n }\n\n // Load translations before mounting so child components can use useI18n synchronously\n const translations = await loadTranslations(config.locale ?? \"en\");\n\n // Create fonts manager to pass to Editor\n const fontsManager = useFonts(config.fonts);\n\n // A later `init()` or `initCloud()` on this container was made while this\n // one awaited, so the container is that call's. Mounting here would replace\n // its editor whenever this call settles last: under React StrictMode, with a\n // cancelled effect's editor, which that effect then unmounts, leaving the\n // container empty. So this call leaves the container alone and resolves\n // never mounted, like an instance a later `init()` replaced: its\n // `unmount()` is a no-op.\n if (containerClaims.get(container) !== token) {\n return createEditorInstance({\n config,\n editorRef: ref(null),\n fontsManager,\n unmount: () => {},\n }).instance;\n }\n\n // Auto-unmount any prior instance on the SAME container *after* awaits\n // — checking before the await would let two concurrent init() calls\n // both pass the guard and orphan the first-mounted app on this\n // container.\n unmountOssContainer(container);\n\n const mount = resolveMountTarget(container, config.shadowDom ?? true);\n const editorRef: Ref<InstanceType<typeof Editor> | null> = ref(null);\n\n const app = createApp({\n setup() {\n return () =>\n h(Editor, {\n config,\n translations,\n fontsManager,\n shadowRoot: mount.shadowRoot ?? undefined,\n cloud,\n // The test-email dialog's `includeMjml` payload comes off the same\n // ladder as `editor.toMjml()`, so a consumer's `render.toMjml` is what\n // a test carries when they configured one. `render` is declared below\n // and read at send time, never during this render.\n renderMjml: () => render.toMjml(),\n renderHtml: () => render.toHtml(),\n canRenderHtml: () => render.canRenderHtml(),\n usesLocalRenderer: () => render.usesLocalRenderer(),\n ref: editorRef,\n });\n },\n });\n\n app.mount(mount.target);\n\n ossEntries.set(container, { app, editorRef, cleanup: mount.cleanup });\n lastOssContainer = container;\n\n const { instance, render } = createEditorInstance({\n config,\n editorRef,\n fontsManager,\n // This instance's own app: once a later `init()` replaced it on the\n // container, this call must leave the replacement mounted.\n unmount: () => unmountOssContainer(container, app),\n });\n\n return instance;\n}\n\n/**\n * The object `init()` and `initCloud()` resolve with. It reaches the editor\n * through `editorRef`, which is `null` before the editor mounts and after it\n * unmounts, and for good on a call a later one superseded; every method\n * answers either way.\n */\nfunction createEditorInstance({\n config,\n editorRef,\n fontsManager,\n unmount,\n}: {\n config: TemplaticalEditorConfig;\n editorRef: Ref<InstanceType<typeof Editor> | null>;\n fontsManager: UseFontsReturn;\n unmount: () => void;\n}): { instance: TemplaticalEditor; render: RenderMethods } {\n const instance: TemplaticalEditor = {\n getContent() {\n // safeClone (not a naked JSON.stringify): a drag inside a section can\n // leave a Sortable expando cycle reachable from live content, which a\n // plain stringify chokes on (#203). The clone drops the back-ref.\n if (editorRef.value) {\n return safeClone(editorRef.value.getContent());\n }\n // Same defaults the mounted editor would have used, `locale` included:\n // a caller reading content before mount must not get a different\n // template than the one about to render.\n return safeClone(\n config.content ??\n createDefaultTemplateContent(\n config.fonts?.defaultFont,\n resolveTemplateDefaults(config),\n ),\n );\n },\n setContent(content: TemplateContent) {\n // Normalized once and used for both writes: `getContent()` falls back to\n // `config.content` before mount, so a raw write-back here would hand back\n // different content than the mounted editor holds.\n const normalized = normalizeContentForConfig(content, config.mergeTags);\n if (editorRef.value) {\n editorRef.value.setContent(normalized);\n }\n config.content = normalized;\n },\n insertBlock(block: Block) {\n // Before the mount and preview checks, so the mistake surfaces on every\n // path, not only once core's `addBlock` is reached. The asserts read\n // only `blocks`.\n const candidate = { blocks: [block] } as TemplateContent;\n assertNoSlotInContent(candidate);\n assertNoWrapperInContent(candidate);\n if (!editorRef.value) return null;\n // Consumer content arriving in, so it is normalized like `setContent`.\n return editorRef.value.insertBlock(\n normalizeBlockForConfig(block, config.mergeTags),\n );\n },\n setTheme(theme: UiTheme) {\n if (editorRef.value) {\n editorRef.value.setTheme(theme);\n }\n },\n setMergeTags(tags: MergeTag[]) {\n if (editorRef.value) {\n editorRef.value.setMergeTags(tags);\n return;\n }\n // Called before mount: fold it into the config the editor is about to\n // read, so the call is never silently lost.\n config.mergeTags = { ...config.mergeTags, tags };\n },\n unmount,\n create(input?: { name?: string; content?: TemplateContent }) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n // Supplied content becomes editor state before the provider is called,\n // so it is consumer content arriving in and gets the same treatment as\n // `setContent`. A contentless create is forwarded as-is — core then\n // persists the state it already holds, which is normalized already.\n return editorRef.value.create(\n input?.content\n ? {\n ...input,\n content: normalizeContentForConfig(\n input.content,\n config.mergeTags,\n ),\n }\n : input,\n );\n },\n load(templateId: string) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.load(templateId);\n },\n save() {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.save();\n },\n isDirty() {\n // Pre-mount there is nothing the editor could have changed, so the honest\n // answer is \"no unsaved edits\" rather than a throw.\n return editorRef.value?.isDirty() ?? false;\n },\n renderCustomBlock(block: CustomBlock) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.renderCustomBlock(block);\n },\n getCustomBlockStylesheet(customType: string) {\n // Pre-mount: registry is empty, so no definition has a stylesheet to\n // resolve. Returning undefined here matches the \"unknown type\" branch\n // and keeps the renderer's `getCustomBlockStylesheet` resolver total.\n if (!editorRef.value) {\n return undefined;\n }\n return editorRef.value.getCustomBlockStylesheet(customType);\n },\n toMjml: () => render.toMjml(),\n toHtml: () => render.toHtml(),\n };\n\n // Both methods resolve per call, so a provider added later in the config — or a\n // provider that implements only one method — behaves the same as one that\n // implements all three. `instance` is captured lazily, which is what lets the\n // payload builder read the editor's live content.\n const render = createRenderMethods({\n provider: config.render,\n buildPayload: () =>\n buildRenderPayload({\n getContent: () => instance.getContent(),\n renderCustomBlock: (block: CustomBlock) =>\n instance.renderCustomBlock(block),\n getCustomBlockStylesheet: (customType: string) =>\n instance.getCustomBlockStylesheet(customType),\n getFonts: () => resolveRenderFonts(fontsManager),\n getLayout: () => config.layout,\n }),\n renderLocalMjml: () =>\n toMjmlForInstance({\n getContent: () => instance.getContent(),\n renderCustomBlock: (block: CustomBlock) =>\n instance.renderCustomBlock(block),\n getCustomBlockStylesheet: (customType: string) =>\n instance.getCustomBlockStylesheet(customType),\n getFonts: () => resolveRenderFonts(fontsManager),\n socialIconsBaseUrl: config.socialIconsBaseUrl,\n getLayout: () => config.layout,\n }),\n });\n\n return { instance, render };\n}\n\n// ---------------------------------------------------------------------------\n// Cloud init — a thin adapter-wiring wrapper over init()\n// ---------------------------------------------------------------------------\n\n/**\n * Mount the editor against Templatical Cloud.\n *\n * **This is `init()` with Cloud's adapters filled in**, and deliberately nothing\n * more. Templates, rendering and version history are providers, so Cloud's entry\n * point is adapter wiring rather than a second editor:\n *\n * 1. Build the auth manager and complete the handshake.\n * 2. Health-check the API, and fetch the plan config.\n * 3. Build Cloud's adapters over that auth manager.\n * 4. Delegate to `init()`.\n *\n * A failure in steps 1–2 **rejects**, rather than mounting an editor that shows\n * an error overlay. That is the one place the wrapper is genuinely not `init()`:\n * `init()` cannot fail after it mounts, and OSS should not grow the ability. A\n * session that dies *later* — an auth refresh that cannot renew the token — does\n * still surface as an overlay, because by then there is an editor to cover.\n *\n * `templates`, `comments` and `versionHistory` are all keyed to a template\n * id Cloud issued, which also anchors the server-side export — a store Cloud\n * never issued ids for would degrade all of them silently. Cloud therefore\n * keeps each key's storage, but each key is still accepted, for its\n * configuration and events:\n * `templates.load`/`create`/`save`,\n * `comments.list`/`create`/`update`/`delete`/`setResolved`, and\n * `versionHistory.list`/`get`/`create`/`restore` are ignored with a warning\n * naming them, while `templates`' `autoSave`, `unsavedChangesGuard`,\n * `nameField`, `onSaved`, `onCreated`, `onLoaded`, `comments`' `onCreated`,\n * `onUpdated`, `onDeleted`, `onResolved`, `onUnresolved`, and\n * `versionHistory`'s `onCreated`, `onRestored` are all honoured.\n *\n * `render` is not a key here at all, unlike `init()` — Cloud renders\n * server-side for test email, sends and exports, so a supplied renderer\n * would change only what you preview and export, never what Cloud delivers.\n * `resolvePreview` is the same key with the same type on both entry points,\n * so upgrading an OSS integration is a deletion. `savedBlocks`, `testEmail`\n * and `media` are the same key on both entry points too, but Cloud widens\n * each type to also accept an events-only shape — `boolean |\n * SavedBlocksOptions | SavedBlocksProvider`, `Pick<TestEmailOptions,\n * \"onSent\" | \"defaultRecipient\"> | TestEmailProvider`, and\n * `false | MediaOptions | MediaProvider` — so upgrading is still a\n * deletion: drop the key to adopt Cloud's store or sender, or leave it\n * exactly as it is to keep your own.\n *\n * `user` is not a key either: Cloud signs comment writes against the auth token's\n * `user` claim, so it fills `init({ user })` from there rather than letting a\n * browser name someone else.\n */\nexport async function initCloud(\n config: TemplaticalCloudEditorConfig,\n): Promise<TemplaticalCloudEditor> {\n // Checked before the claim and the bootstrap, so an illegal `layout` or\n // `content` rejects without touching the container or making any request.\n // The three keys are copied first, so the caller's config is never written.\n const prepared = {\n layout: config.layout,\n content: config.content,\n mergeTags: config.mergeTags,\n };\n prepareLayoutAndContent(prepared);\n\n // Claimed before the bootstrap's requests go out, so a later call on this\n // container wins even when this call's bootstrap answers last, and a\n // selector that matches nothing rejects without making any request.\n const claim = claimContainer(config.container);\n\n // Dynamic imports — every cloud module is tree-shaken from the OSS bundle, and\n // an OSS consumer who never calls this downloads none of it.\n const [{ bootstrapCloud }, cloudTranslations] = await Promise.all([\n import(\"./cloud/createCloudRuntime\"),\n loadCloudTranslations(config.locale ?? \"en\"),\n ]);\n\n const { runtime, providers, user } = await bootstrapCloud({\n config,\n cloudTranslations,\n });\n\n return mountEditor(\n {\n container: config.container,\n content: prepared.content,\n layout: prepared.layout,\n sectionWrapper: config.sectionWrapper,\n shadowDom: config.shadowDom,\n locale: config.locale,\n uiTheme: config.uiTheme,\n theme: config.theme,\n branding: config.branding,\n smallScreenNotice: config.smallScreenNotice,\n blockDefaults: config.blockDefaults,\n templateDefaults: config.templateDefaults,\n customBlocks: config.customBlocks,\n paletteBlocks: config.paletteBlocks,\n htmlBlockPreview: config.htmlBlockPreview,\n colors: config.colors,\n templateSettings: config.templateSettings,\n fonts: config.fonts,\n mergeTags: config.mergeTags,\n logicTags: config.logicTags,\n displayConditions: config.displayConditions,\n resolvePreview: config.resolvePreview,\n lint: config.lint,\n onChange: config.onChange,\n onError: config.onError,\n onDirtyChange: config.onDirtyChange,\n // Cloud's adapters, behind the very keys a consumer would fill in\n // themselves. `savedBlocks` is absent when the consumer passed `false`.\n // `templates` spreads Cloud's own provider first so its load/create/save\n // always win over a consumer's config. Autosave defaults on here, unlike\n // `init()`, because Cloud always has a store to save to; the debounce\n // falls back to the same shared constant `useAutoSave` already defaults\n // to, made explicit so a consumer's own `changeDebounce` reaches it.\n templates: {\n ...providers.templates,\n autoSave: config.templates?.autoSave ?? true,\n unsavedChangesGuard: config.templates?.unsavedChangesGuard,\n nameField: config.templates?.nameField,\n },\n changeDebounce: config.changeDebounce ?? DEFAULT_AUTO_SAVE_DEBOUNCE_MS,\n render: providers.render,\n versionHistory: providers.versionHistory,\n savedBlocks: providers.savedBlocks,\n testEmail: providers.testEmail,\n comments: providers.comments,\n media: providers.media,\n onRequestMedia: config.onRequestMedia,\n // From the JWT. Undefined when the project's token carries no `user` claim,\n // which leaves comments unavailable rather than anonymous.\n user,\n },\n claim,\n runtime,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Unmount helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Unmount the most-recently-created OSS editor. Single-instance legacy\n * API — callers managing multiple editors should use `instance.unmount()`\n * from each returned object, which tears down only that instance.\n */\nexport function unmount(): void {\n if (lastOssContainer) {\n unmountOssContainer(lastOssContainer);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports\n// ---------------------------------------------------------------------------\n\nexport type { TemplaticalCloudEditorConfig } from \"./cloud/cloudConfig\";\nexport type {\n BlockDefaults,\n TemplateContent,\n TemplateDefaults,\n ThemeOverrides,\n UiTheme,\n MergeTagsConfig,\n LogicTagsConfig,\n LogicTag,\n LogicPair,\n DisplayConditionsConfig,\n CustomBlockDefinition,\n ViewportSize,\n ColorsConfig,\n CustomFont,\n FontsConfig,\n RenderPayload,\n RenderProvider,\n SavedBlock,\n SavedBlocksListParams,\n SavedBlocksOptions,\n SavedBlocksProvider,\n Template,\n TemplatePatch,\n TemplatesOptions,\n TemplateSaveTrigger,\n TemplateSettingsConfig,\n TemplatesProvider,\n TestEmailOptions,\n TestEmailPayload,\n TestEmailProvider,\n VersionHistoryOptions,\n CommentsOptions,\n CommentEventMeta,\n MediaAsset,\n MediaOptions,\n MediaProvider,\n MediaRequestContext,\n SdkErrorCode,\n BlockLock,\n BlockLockHolder,\n BlockParent,\n CollaborationActor,\n CollaborationConflictCode,\n CollaborationConnectionState,\n CollaborationHandlers,\n CollaborationJoin,\n CollaborationMember,\n CollaborationProvider,\n CollaborationRemoteChange,\n Operation,\n OperationBatch,\n OperationsAfterResult,\n RevisionedBatch,\n AiAppliedBatch,\n AiChatMessage,\n AiChatRequest,\n AiAltTextRequest,\n AiConversationProvider,\n AiChatAttachment,\n AiFeatureName,\n AiFixFinding,\n AiFixRequest,\n AiMergeTags,\n AiMessageBatch,\n AiOperationsResult,\n AiProvider,\n AiReplay,\n AiReplayContext,\n AiReplayOutcome,\n AiRequestBase,\n AiRewriteRequest,\n AiTurnHandlers,\n AiTurnResult,\n} from \"@templatical/types\";\n\n// Bundled browser-local saved-blocks / media providers. Re-exported here\n// (rather than leaving them to `@templatical/core`) because consumers\n// install only this package — core is bundled inline and isn't resolvable\n// on their side.\nexport { createLocalStorageSavedBlocksProvider } from \"@templatical/core\";\nexport type { LocalStorageSavedBlocksOptions } from \"@templatical/core\";\nexport { createLocalStorageMediaProvider } from \"@templatical/core\";\nexport type { LocalStorageMediaProviderOptions } from \"@templatical/core\";\n\nexport type { ResolveImageUrl } from \"./composables/useImageUrlResolver\";\nexport type { FontOption } from \"./composables/useFonts\";\nexport type { HtmlBlockPreviewConfig } from \"./utils/resolveHtmlBlockPreview\";\n\nexport {\n applyLayout,\n validateLayout,\n createSlotBlock,\n createWrapperBlock,\n createParagraphBlock,\n createDefaultTemplateContent,\n isSlot,\n isWrapper,\n layoutWrapsSlot,\n} from \"@templatical/types\";\n\nexport {\n getSupportedLocales,\n getSupportedCloudLocales,\n isLocaleSupported,\n isCloudLocaleSupported,\n getBaseLocale,\n} from \"./i18n\";\n\nexport { AI_FIXABLE_RULES, AI_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AAO,kBAAA;EACvB,QAAQmvB,EAAU;EAClB,gBAAgBA,EAAU;EAC1B,aAAaA,EAAU;EACvB,WAAWA,EAAU;EACrB,UAAUA,EAAU;EACpB,OAAOA,EAAU;EACjB,gBAAgBnvB,EAAO;EAGvB;CACF,GACAgvB,GACAI,CACF;AACF;AAWA,SAAgBC,KAAgB;CAC9B,AAAItB,MACFI,GAAoBJ,EAAgB;AAExC"}
1
+ {"version":3,"file":"editor.js","names":["_hoisted_1","_openBlock","_createElementBlock","_renderSlot","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_openBlock","_createElementBlock","_createElementVNode","_createVNode","_unref","_createTextVNode","_toDisplayString","_Fragment","_normalizeClass","_createCommentVNode","TplModal","_withCtx","_sfc_main","toError","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","SectionBlock","TitleBlock","ParagraphBlock","ImageBlock","ButtonBlock","DividerBlock","SpacerBlock","HtmlBlock","SocialIconsBlock","MenuBlock","TableBlock","VideoBlock","CustomBlock","WrapperBlock","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createElementVNode","_normalizeClass","_toDisplayString","_Fragment","_renderList","_createCommentVNode","_withDirectives","_createVNode","VueDraggable","_withCtx","_createTextVNode","_createBlock","_resolveDynamicComponent","BlockWrapper","_mergeProps","_vShow","_sfc_main","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","createBlock","_openBlock","_createElementBlock","_unref","_normalizeStyle","_createElementVNode","_createVNode","_toDisplayString","_createCommentVNode","VueDraggable","_withCtx","_Fragment","_renderList","_createBlock","_resolveDynamicComponent","CustomBlockIcon","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_useModel","_openBlock","_createElementBlock","_unref","_normalizeClass","_createElementVNode","_normalizeStyle","_createVNode","_toDisplayString","_createCommentVNode","_createBlock","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_createElementVNode","_createVNode","_unref","_toDisplayString","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeClass","_createElementVNode","_toDisplayString","_unref","_createStaticVNode","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createVNode","_Transition","_withCtx","_createBlock","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_normalizeStyle","_unref","_createVNode","_Transition","_withCtx","_createBlock","_sfc_main","_hoisted_1","_hoisted_2","_withDirectives","_openBlock","_createElementBlock","_unref","_normalizeClass","_withKeys","_withModifiers","_vModelText","_toDisplayString","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_openBlock","_createElementBlock","_createVNode","_unref","_createTextVNode","_toDisplayString","_createElementVNode","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_openBlock","_createElementBlock","_unref","_normalizeClass","_normalizeStyle","_withModifiers","_createVNode","_createElementVNode","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_openBlock","_createElementBlock","_createElementVNode","_unref","_normalizeClass","_createBlock","TemplateNameField","_createCommentVNode","TemplateTimestamp","_renderSlot","_createVNode","ViewportToggle","DarkModeToggle","PreviewToggle","TemplateSaveStatus","_normalizeStyle","_toDisplayString","AiHeaderMenu","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","listId","_openBlock","_createBlock","TplModal","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createVNode","_withDirectives","_withKeys","_withModifiers","_vModelText","_createElementBlock","_Fragment","_renderList","_createCommentVNode","_normalizeClass","_sfc_main","_hoisted_1","_openBlock","_createElementBlock","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_openBlock","_createBlock","TplModal","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createVNode","_withDirectives","_withKeys","_withModifiers","_vModelText","_createElementBlock","_Fragment","_renderList","_normalizeClass","LogicTagBadge","_createCommentVNode","_sfc_main","_openBlock","_createElementBlock","_normalizeClass","_unref","_normalizeStyle","_withModifiers","_createVNode","CustomBlockStylesheets","_createElementVNode","EditorHeader","_createSlots","_withCtx","_withDirectives","Sidebar","_vShow","_Transition","MergeTagModeToggle","_createCommentVNode","_createTextVNode","_toDisplayString","Canvas","_createBlock","EditorFooter","RightSidebar","LanguageBar","MergeTagPickerModal","LogicTagPickerModal","NoticeStack","SmallScreenNotice","_sfc_main","editorStylesInline","Editor","mergeProps","resolveDynamicComponent","defineComponent","h","openBlock","withCtx","watch","provide","withDirectives","renderList","onBeforeUnmount","onMounted","inject","onUnmounted","onScopeDispose","renderSlot","defineAsyncComponent","useModel","getCurrentScope","createElementBlock","withKeys","unref","normalizeClass","createCommentVNode","createBlock","toRaw","nextTick","mergeModels","withModifiers","createBaseVNode","toDisplayString","Transition","shallowReadonly","vModelText","computed","normalizeStyle","createApp","shallowRef","vShow","lo","ref","Fragment","createSlots","createVNode","createStaticVNode","deepEqual","assertNoWrapperInContent","invertOperations","createParagraphBlock","createCustomBlock","defaultLocaleGaps","validateLayout","cloneBlock","applyOperationsInPlace","applyLayout","isWrapper","createBlock$1","SdkError","defaultLocaleOf","isSlot","localeCoverage","createSlotBlock","createWrapperBlock","resolveLocale","resolveContentDirection","safeClone","applyLocaleStrings","getLogicMergeTagKeyword","layoutWrapsSlot","OperationError","assertNoSlotInContent","CollaborationConflict","createDefaultTemplateContent","SYNTAX_PRESETS","unmaskTags","localeStrings","isLogicMergeTagValue","isLocaleTag","createLocalStorageSavedBlocksProvider","useComments","useCommentListener","useCollaboration","mapLocalizedOperations","useVersionHistory","useEditor","toNaturalSize","getBlockTypeLabel","EMAIL_FRAME_WIDTH_TRANSITION","useSavedBlocks","createLocalStorageMediaProvider","getEmailFrameWidth","_plugin_vue_export_helper_default","Monitor","Settings","ChevronDown","Sparkles","Eye","SquarePlus","RotateCcw","CircleAlert","Search","EyeOff","Save","Moon","Check","Package","LoaderCircle","ListChecks","LayoutTemplate","Send","Languages","MessageCircle","PanelTop","X","ImageUp","Sun","TEMPLATE_SETTINGS_FIELDS_KEY","MERGE_TAG_SYNTAX_KEY","LOCALE_ACTIONS_KEY","PALETTE_BLOCKS_KEY","MERGE_TAG_PICKER_KEY","LOGIC_TAG_PICKER_KEY","LOCALIZATION_KEY","TEMPLATE_LINT_KEY","MERGE_TAG_SAMPLE_MODE_KEY","SAVED_BLOCKS_KEY","SIZE_CHECK_KEY","APPLIES_CONDITION_FILTER_KEY","USE_MERGE_TAG_SAMPLES_KEY","FONTS_MANAGER_KEY","BLOCK_DEFAULTS_KEY","CAPABILITIES_KEY","THEME_STYLES_KEY","CUSTOM_BLOCK_STYLESHEETS_KEY","CUSTOM_BLOCK_DEFINITIONS_KEY","UI_THEME_KEY","LOCALIZED_CONTENT_KEY","BLOCK_REGISTRY_KEY","CONDITION_PREVIEW_KEY","AI_FEATURE_KEY","TRANSLATION_FEATURE_KEY","requireInject","PREVIEW_RESOLUTION_KEY","UI_LOCALE_KEY","ACTIVE_LOCALE_COVERAGE_KEY","EDITOR_KEY","MERGE_TAG_SHOW_RAW_VALUE_KEY","useI18n","useLocalizedDisplay","useActiveLocaleCoverage","plural","languageName","secondaryBtnClass","warningBtnCompactClass","primaryBtnClass","inputClass","ghostBtnCompactClass","secondaryBtnCompactClass","primaryBtnCompactClass","useTimeoutFn","refDebounced","useIntervalFn","useEventListener","isCloudLocaleSupported","getBaseLocale","resolveBlockComponent","resolveLintOptions","loadCloudTranslations","loadTranslations","getSupportedCloudLocales","useFonts","DividerBlock_default","SpacerBlock_default","ButtonBlock_default","HERO_PALETTE_TYPE","BlockWrapper_default","updateBlockList","HtmlBlock_default","ImageBlock_default","TableBlock_default","isLocaleSupported","getSupportedLocales","createHeroSection","MenuBlock_default","useEditorCore","SocialIconsBlock_default","ParagraphBlock_default","VideoBlock_default","SectionBlock_default","useSmallScreenNotice","TitleBlock_default","CustomBlock_default","getDocumentStyle","CustomBlockIcon_default","logger","ALL_TEMPLATE_SETTINGS_FIELDS","sanitizeHtml","TplModal_default","withNormalizedContentWrites","normalizeRemoteOperations","normalizeContentForConfig","withNormalizedTemplateLoads","normalizeBlockForConfig","AI_MISSING_PROVIDER_MESSAGE","formatAbsoluteDateTime","aiImageSnapshot","aiImageContext","effectiveAltMaxLength","AI_ALT_TEXT_RULES","AI_FIXABLE_RULES","useScrollToBlock","WrapperBlock_default","blockTypeIcons","ViewportToggle_default","MergeTagModeToggle_default","formatRelativeTime","preRenderCustomBlocks","LANGUAGE_TAG","resolveTemplateDefaults","tag","config","seeded","_sfc_main","_hoisted_1$17","_sfc_render","_ctx","NoticeStack_default","_hoisted_1$16","_hoisted_2$11","_hoisted_3$9","_hoisted_4$8","_hoisted_5$7","_hoisted_6$7","_hoisted_7$7","_hoisted_8$5","_hoisted_9$5","_hoisted_10$5","_hoisted_11$5","_hoisted_12$4","_hoisted_13$3","_hoisted_14$3","_hoisted_15$3","_hoisted_16$3","_hoisted_17$2","seenTemplates","LanguageBar_default","props","__props","uiLocale","definitions","source","active","enabled","coverage","status","t","format","resultText","result","parts","structureVisible","seenMount","confirming","allAgain","allCount","confirmationTitle","closeConfirmation","startConfirmation","confirm","captured","templateId","createTextVNode","_cache","useLocaleActions","options","ops","editor","locale","error","translationError","shaped","styleValues","values","parsed","html","element","keepsStyles","allowed","translation","style","sanitizeTranslation","prefix","placeholders","protectedText","text","token","clean","index","abortable","abort","stopped","reject","signal","promise","useTranslationFeature","running","lastResult","disposed","isAvailable","counts","gapIds","strings","id","cancel","discard","translate","core","sourceLocale","syntax","doNotTranslate","extraction","scope","job","offset","limit","chunk","chars","field","answer","returned","value","tokens","restored","applied","rejection","blocks","collect","block","items","column","operations","operation","stored","path","locked","lock","count","COLLABORATION_NOTICE_MS","AGENT_HIGHLIGHT_MS","RESYNC_SUMMARY","summarizeAgentEdit","blockIds","settings","templateUpdated","op","useCollaborationFeature","notices","nextNoticeId","dismissTimers","armDismiss","dismissNotice","show","notice","onNotice","agentRun","highlights","highlightTimers","highlightSequence","highlight","sequence","next","blockId","rest","noteAgent","actor","isAi","summary","client","key","now","run","view","content","change","timer","people","members","myUserId","member","byPerson","history","holders","holder","locks","useCommentsFeature","headless","isOpen","filterBlockId","hasTemplate","unresolvedCount","available","attached","open","toggle","close","openForBlock","AI_SETTLE_TIMEOUT_MS","AI_BROADCAST_GRACE_MS","snapshotOf","isAbort","asError","sum","message","total","batch","hasBlock","refusalOf","useAiFeature","conversation","provider","localSessionId","panel","memory","destroyed","authorVersion","applyingAi","pendingJobs","stopAuthorWatch","ownerScope","createSession","saved","memoryFor","currentSession","localeVersion","stopLocaleWatch","checkLocale","version","has","feature","scopeOf","isCurrent","sessionRef","select","empty","messages","isTemplateEmpty","isLoadingHistory","isRunning","failure","keptYourVersion","failedPrompt","failedAttachments","importQueue","invalidateHistory","enqueue","skipped","watchAuthorEdits","pump","check","reloadCurrent","valid","recoverStopped","canKeepReload","expectedAuthorVersion","found","later","ms","report","outline","collaboration","settle","resolve","requestBase","raw","selectedBlockId","applySharedOps","normalized","inverse","turn","selected","applyModelOps","mapped","followRevision","revision","patch","item","changes","replayAvailability","recovery","eligible","record","emptyOutcome","runTurn","startingLocale","userKey","operationCount","interrupted","refusal","outcome","completed","reconciling","update","rememberRecovery","reconcileLateApplied","observed","readHistory","handlers","before","userText","attachments","file","call","controller","previousKey","caught","kind","recovered","replay","remote","direction","toItem","mergeHistory","list","previous","old","matches","persisted","reconciled","row","force","loadConversation","pending","newChat","bootstrap","stop","startImport","files","stopSession","abandon","idle","create","watchers","dirty","draftAltText","altText","abandonDraft","context","applyAltTexts","entries","expect","start","chat","base","fixFinding","finding","rewrite","input","onText","unwatch","AI_MERGE_TAG_LIMITS","truncate","points","max","mergeTagSyntaxName","name","preset","toAiMergeTags","out","tags","toError$1","dropFileError","maxFileSize","mimeTypes","accept","category","useMediaFeature","isModalOpen","getTemplateId","canDrop","onRequestMedia","toMediaResult","asset","rejected","onError","err","size","useSavedBlocksFeature","isSaveDialogOpen","isBrowserOpen","picking","pickedIds","isPicking","pickedCount","startPicking","togglePick","isPicked","cancelPicking","confirmPicking","refresh","closeSaveDialog","previewMode","openBrowser","closeBrowser","insert","i","cloned","position","insertIndex","SAVED_STATUS_MS","useTemplatesFeature","errorMessage","startSavedStatusClear","stopSavedStatusClear","canCreate","canSave","timestamp","template","isSaving","reportSuccess","reportFailure","save","trigger","load","shouldApply","queuedAutoSave","runSave","requestAutoSave","cannotSave","requestSave","gate","rename","trimmed","newName","event","tryLoadRenderer","toMjmlForInstance","renderer","stylesheetResolver","instance","fonts","layout","customType","SUCCESS_DISMISS_MS","toError","useTestEmailFeature","isSending","justSent","dismissTimer","warnedAboutRenderer","clearDismissTimer","allowedRecipients","defaultRecipient","preferred","resolveMjml","notifySent","payload","send","recipient","mjml","wrapped","useVersionHistoryFeature","previewingVersion","contentBeforePreview","isConfirmingRestore","isSavingBeforeRestore","versions","isLoading","isRestoring","canRestore","isPreviewing","canSaveBeforeRestore","isConfirmBusy","navigate","known","autoSave","requestRestore","confirmRestore","saveAndRestore","saver","previewed","discardAndRestore","cancelRestoreConfirm","conditionPreview","applyRestored","cancelPreview","resolveAutoSave","defaultEnabled","resolveInsertPosition","findBlockLocation","blockType","parent","isBlockLocked","insertBlockAtSelection","targetSectionId","columnIndex","withCollaborativeSave","storedNames","remember","current","getTemplate","_hoisted_1$15","_hoisted_2$10","_hoisted_3$8","_hoisted_4$7","_hoisted_5$6","_hoisted_6$6","_hoisted_7$6","_hoisted_8$4","_hoisted_9$4","_hoisted_10$4","_hoisted_11$4","_hoisted_12$3","Canvas_default","__emit","blockComponentMap","emit","displaySettings","fontsManager","blockRegistry","caps","mergeTagSampleMode","previewResolution","canChat","canImport","importInput","pickImport","importPicked","appliesConditionFilter","viewportWidth","stageWidth","canvasStyle","contentLang","contentDir","isEmptyCanvas","dragEnterDepth","isDragOverEmpty","handleEmptyDragEnter","handleEmptyDragLeave","handleEmptyDrop","handleCanvasClick","getBlockComponent","isLockedByOther","handleBlockSelect","savedBlocks","isPickedBlock","handleFetchData","n","$event","displayBlock","updates","CustomBlockStylesheets_default","stylesheets","css","resolvePaletteBlocks","paletteBlocks","candidates","byType","c","unknown","seen","entry","candidate","_hoisted_1$14","_hoisted_2$9","_hoisted_3$7","_hoisted_4$6","_hoisted_5$5","_hoisted_6$5","_hoisted_7$5","PALETTE_DRAG_TOLERANCE_PX","Sidebar_default","customBlockDefinitions","blockDefaults","scrollToBlock","showSavedBlocksSection","isExpanded","isDragging","railEl","suppressPaletteClick","suppressPaletteClickTimer","hasKeyboardFocusInRail","handleSidebarLeave","handleDragChoose","handleDragUnchoose","handleDragStart","handleRailFocusOut","clearFallbackClickSwallow","handleDragEnd","builtInBlockTypeOrder","builtInBlockTypes","types","type","customBlockItems","def","candidateBlockTypes","resolvedPalette","blockTypes","warnedPaletteEntries","createBlockFromItem","definition","d","insertBlockFromItem","handlePaletteClick","handlePaletteKeydown","_hoisted_1$13","_hoisted_2$8","_hoisted_3$6","_hoisted_4$5","_hoisted_5$4","_hoisted_6$4","_hoisted_7$4","_hoisted_8$3","_hoisted_9$3","_hoisted_10$3","_hoisted_11$3","_hoisted_12$2","_hoisted_13$2","_hoisted_14$2","_hoisted_15$2","_hoisted_16$2","RightSidebar_default","\"tab\"","\"tabModifiers\"","Toolbar","TemplateSettingsPanel","IssuesPanel","activeTab","lint","lintAvailable","issueCount","allowedSettingsFields","settingsEnabled","tabClass","tab","tabStyle","_hoisted_1$12","_hoisted_2$7","_hoisted_3$5","_hoisted_4$4","SmallScreenNotice_default","_hoisted_1$11","EditorFooter_default","pixels","decideHeaderFit","fullWidth","measurement","useHeaderFit","compact","resizeObserver","mutationObserver","mounted","contentDirty","scheduledFrame","metricProbe","probeWidth","probeHeight","headerGroups","groupsOverflow","track","group","bounds","control","measure","container","header","copy","attribute","child","groups","selector","identity","widths","decision","invalidateSize","invalidateContent","initialProbe","metricsChanged","width","height","_hoisted_1$10","DarkModeToggle_default","_hoisted_1$9","PreviewToggle_default","_hoisted_1$8","_hoisted_2$6","TemplateNameField_default","isEditing","draft","inputEl","startEditing","commit","_hoisted_1$7","TemplateTimestamp_default","tick","label","relative","isJustNow","absolute","_hoisted_1$6","_hoisted_2$5","_hoisted_3$4","TemplateSaveStatus_default","_hoisted_1$5","_hoisted_2$4","AiHeaderMenu_default","isActive","_hoisted_1$4","_hoisted_2$3","_hoisted_3$3","_hoisted_4$3","_hoisted_5$3","_hoisted_6$3","_hoisted_7$3","_hoisted_8$2","_hoisted_9$2","_hoisted_10$2","_hoisted_11$2","EditorHeader_default","VersionHistoryMenu","LanguageMenu","CollaboratorBar","containerElement","headerElement","_hoisted_1$3","_hoisted_2$2","_hoisted_3$2","_hoisted_4$2","_hoisted_5$2","_hoisted_6$2","_hoisted_7$2","_hoisted_8$1","_hoisted_9$1","_hoisted_10$1","_hoisted_11$1","_hoisted_12$1","_hoisted_13$1","_hoisted_14$1","_hoisted_15$1","_hoisted_16$1","_hoisted_17$1","_hoisted_18","listId$1","MergeTagPickerModal_default","picker","themeStyles","tplUiTheme","showRawValue","isChanging","modalTitle","rowTitle","rawSearch","search","searchInputRef","searchActive","highlightedIndex","hasGroups","collapsedGroups","isCollapsed","toggleGroup","filteredTags","query","groupOrder","otherLabel","order","rows","buckets","tagIndex","groupKey","visibleTags","preselectPending","preselectCurrent","target","setHighlight","selectTag","moveHighlight","delta","scrollHighlightIntoView","listRef","headerRefs","setHeaderRef","el","jumpToGroup","targetScrollTop","onKeydown","activeOptionId","optionId","isEmptyConfig","isNoResults","showPillRow","rowIndex","_hoisted_1$2","LogicTagBadge_default","isLogic","keyword","\"border\"","\"color\"","_hoisted_1$1","_hoisted_2$1","_hoisted_3$1","_hoisted_4$1","_hoisted_5$1","_hoisted_6$1","_hoisted_7$1","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","listId","LogicTagPickerModal_default","haystackParts","filteredPairs","pair","filteredEntries","bucket","map","built","idx","pushEntry","groupEntries","visibleItems","selectItem","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","Editor_default","__expose","liveMergeTags","normalizedTemplates","templatesProvider","structureNotice","localized","cloudAttachment","templates","isDirty","rootEl","SavedBlocksPanels","mediaFeature","MediaPanels","testEmail","TestEmailPanel","comments","CommentsPanel","AiPanels","ai","activeCoverage","localeNotice","localeActions","LocaleNotices","CollaborationNotices","CloudPanels","CloudHeaderExtras","VersionHistoryPanels","autoSaveEnabled","isAutoSaving","autoSaveOptions","capabilities","rightSidebarTab","cloudReady","versionHistory","rightPanelOpen","bodyInsetClass","topChrome","topChromeHeight","contentInsetStyle","topChromeObserver","showSmallScreenNotice","templateLifecycle","theme","\"transition\"","IMPORT_RULE","stripStylesheetImports","resolveRenderFonts","buildRenderPayload","createRenderMethods","toMjml","providerToMjml","toHtml","providerToHtml","compileMjml","usesLocalRenderer","canRenderHtml","_virtual_editor_css_default","cachedEditorStyleSheet","getEditorStyleSheet","sheet","attachDevStyleMirror","resolveMountTarget","shadowDom","shadowRoot","host","ossEntries","lastOssContainer","lastClaimToken","containerClaims","claimContainer","unmountOssContainer","onlyApp","prepareLayoutAndContent","init","prepared","terms","term","mountEditor","translations","createEditorInstance","mount","editorRef","app","render","initCloud","claim","cloudTranslations","bootstrapCloud","providers","runtime","unmount"],"sources":["../../src/utils/resolveTemplateDefaults.ts","../../src/components/NoticeStack.vue","../../src/components/localization/LanguageBar.vue","../../src/components/localization/LanguageBar.vue","../../src/composables/useLocaleActions.ts","../../src/composables/useTranslationFeature.ts","../../src/composables/useCollaborationFeature.ts","../../src/composables/useCommentsFeature.ts","../../src/composables/useAiFeature.ts","../../src/utils/aiMergeTags.ts","../../src/composables/useMediaFeature.ts","../../src/composables/useSavedBlocksFeature.ts","../../src/composables/useTemplatesFeature.ts","../../src/utils/toMjml.ts","../../src/composables/useTestEmailFeature.ts","../../src/composables/useVersionHistoryFeature.ts","../../src/types/auto-save.ts","../../src/utils/resolveInsertPosition.ts","../../src/utils/insertBlockAtSelection.ts","../../src/utils/withCollaborativeSave.ts","../../src/components/Canvas.vue","../../src/components/Canvas.vue","../../src/components/CustomBlockStylesheets.vue","../../src/components/CustomBlockStylesheets.vue","../../src/utils/resolvePaletteBlocks.ts","../../src/components/Sidebar.vue","../../src/components/Sidebar.vue","../../src/components/RightSidebar.vue","../../src/components/RightSidebar.vue","../../src/components/SmallScreenNotice.vue","../../src/components/SmallScreenNotice.vue","../../src/components/EditorFooter.vue","../../src/components/EditorFooter.vue","../../src/composables/useHeaderFit.ts","../../src/components/DarkModeToggle.vue","../../src/components/DarkModeToggle.vue","../../src/components/PreviewToggle.vue","../../src/components/PreviewToggle.vue","../../src/components/TemplateNameField.vue","../../src/components/TemplateNameField.vue","../../src/components/TemplateTimestamp.vue","../../src/components/TemplateTimestamp.vue","../../src/components/TemplateSaveStatus.vue","../../src/components/TemplateSaveStatus.vue","../../src/components/ai/AiHeaderMenu.vue","../../src/components/ai/AiHeaderMenu.vue","../../src/components/EditorHeader.vue","../../src/components/EditorHeader.vue","../../src/components/MergeTagPickerModal.vue","../../src/components/MergeTagPickerModal.vue","../../src/components/LogicTagBadge.vue","../../src/components/LogicTagBadge.vue","../../src/components/LogicTagPickerModal.vue","../../src/components/LogicTagPickerModal.vue","../../src/Editor.vue","../../src/Editor.vue","../../src/utils/stripStylesheetImports.ts","../../src/utils/renderProvider.ts","../../src/index.ts"],"sourcesContent":["import type { TemplateDefaults } from \"@templatical/types\";\n\n/**\n * A well-formed BCP-47-ish language tag: 2–3 letter primary subtag, then\n * hyphen-separated alphanumeric subtags (`de`, `en-GB`, `pt-BR`, `zh-Hant-TW`).\n *\n * Deliberately a shape check, not a registry check — an unknown-but-well-formed\n * tag is the author's business, whereas a *malformed* one must not reach\n * `<mjml lang=\"…\">`, which the renderer stamps from this value.\n */\nconst LANGUAGE_TAG = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i;\n\n/**\n * The template defaults a new, contentless template starts from — the\n * consumer's `templateDefaults`, with the editor's `locale` filled in as the\n * content language when they did not set one.\n *\n * Without this a fresh template rendered `<mjml lang=\"en\">` regardless of the\n * editor's language, so German copy announced itself as English to every screen\n * reader that opened the delivered email. This only decides the *starting*\n * value: the author can change it afterwards, since Template Settings exposes\n * it as \"Content language\" — **unless** the consumer excluded `locale` from\n * `templateSettings.fields`, in which case that card is gone and this seed is\n * the only thing that sets a blank template's content language.\n *\n * Three details are load-bearing:\n *\n * - **The consumer wins.** `templateDefaults.locale` is spread last, so\n * `init({ locale: \"de\", templateDefaults: { locale: \"en\" } })` means a\n * German UI authoring English emails, which is a real setup.\n * - **The region is kept**, unlike `loadTranslations`, which strips it to pick\n * a bundle. `en-GB` and `pt-BR` are meaningfully not `en`/`pt` to a screen\n * reader, and `<html lang>` is exactly where that distinction belongs.\n * - **A malformed tag yields nothing** rather than a guess, leaving\n * `createDefaultTemplateContent` to apply its own English fallback. Emitting\n * it would put unvalidated config text straight into a `lang` attribute.\n *\n * Returns `undefined` when it has nothing to contribute, so the call site can\n * pass it through without inventing an empty object.\n */\nexport function resolveTemplateDefaults(config: {\n locale?: string;\n templateDefaults?: TemplateDefaults;\n}): TemplateDefaults | undefined {\n const tag = config.locale?.trim().replace(/_/g, \"-\");\n const seeded = tag && LANGUAGE_TAG.test(tag) ? { locale: tag } : undefined;\n\n if (!seeded && !config.templateDefaults) return undefined;\n\n return { ...seeded, ...config.templateDefaults };\n}\n","<template>\n <div\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-16 tpl:left-1/2 tpl:z-[60] tpl:flex tpl:-translate-x-1/2 tpl:flex-col tpl:items-center tpl:gap-2\"\n >\n <slot />\n </div>\n</template>\n","<script lang=\"ts\">\nconst seenTemplates = new Set<string>();\n</script>\n<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { Languages, X } from \"@lucide/vue\";\nimport { defaultLocaleOf } from \"@templatical/types\";\nimport type { BaseEditorReturn } from \"../../composables/useEditorCore\";\nimport type { UseTranslationFeatureReturn } from \"../../composables/useTranslationFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { useActiveLocaleCoverage } from \"../../composables/useLocalizedDisplay\";\nimport {\n ACTIVE_LOCALE_COVERAGE_KEY,\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n UI_LOCALE_KEY,\n} from \"../../keys\";\nimport { plural } from \"../../i18n/plural\";\nimport { languageName } from \"../../utils/languageName\";\nimport {\n ghostBtnCompactClass,\n primaryBtnClass,\n primaryBtnCompactClass,\n secondaryBtnClass,\n} from \"../../constants/styleConstants\";\nimport TplModal from \"../TplModal.vue\";\n\nconst props = defineProps<{\n editor: BaseEditorReturn;\n locales: string[];\n feature: UseTranslationFeatureReturn | null;\n change: number;\n}>();\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined) ?? \"en\";\nconst definitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst source = computed(() => defaultLocaleOf(props.editor.content.value));\nconst active = computed(() => props.editor.activeLocale?.value ?? source.value);\nconst enabled = computed(() => props.locales.includes(active.value));\n// The editor shares one pass with the header trigger; a standalone bar\n// computes its own.\nconst coverage =\n inject(ACTIVE_LOCALE_COVERAGE_KEY, null) ??\n useActiveLocaleCoverage(props.editor, definitions);\nconst status = computed(() => {\n if (!enabled.value)\n return format(t.localization.languageReadOnly, {\n language: languageName(active.value),\n });\n if (!coverage.value?.missing.length && !coverage.value?.stale.length)\n return t.localization.complete;\n return format(t.localization.gapTooltip, {\n missing: coverage.value.missing.length,\n stale: coverage.value.stale.length,\n });\n});\nconst resultText = computed(() => {\n const result = props.feature?.lastResult.value;\n if (!result) return \"\";\n const parts = [\n plural(t.localization.translatedFields, result.translated, uiLocale),\n ];\n if (result.tagsChanged.length)\n parts.push(\n plural(\n t.localization.translationTagsChanged,\n result.tagsChanged.length,\n uiLocale,\n ),\n );\n if (result.skippedLocked.length)\n parts.push(\n plural(\n t.localization.translationSkippedLocked,\n result.skippedLocked.length,\n uiLocale,\n ),\n );\n if (result.missing.length)\n parts.push(\n plural(\n t.localization.translationMissing,\n result.missing.length,\n uiLocale,\n ),\n );\n if (result.tooLarge.length)\n parts.push(\n plural(\n t.localization.translationTooLarge,\n result.tooLarge.length,\n uiLocale,\n ),\n );\n if (result.error)\n parts.push(\n format(t.localization.translationError, {\n message: result.error.message,\n }),\n );\n return parts.join(\" \");\n});\n\nconst structureVisible = ref(false);\nlet seenMount = false;\nconst confirming = ref<{\n locale: string;\n templateId: string | null;\n loadVersion: number | undefined;\n} | null>(null);\nconst allAgain = ref<HTMLButtonElement | null>(null);\nconst allCount = computed(() => props.feature?.counts.value.all ?? 0);\nconst confirmationTitle = computed(() =>\n plural(t.localization.translationConfirmation, allCount.value, uiLocale),\n);\nfunction closeConfirmation() {\n confirming.value = null;\n void nextTick(() => allAgain.value?.focus());\n}\nfunction startConfirmation() {\n confirming.value = {\n locale: active.value,\n templateId: props.editor.state.template?.id ?? null,\n loadVersion: props.editor.loadVersion?.value,\n };\n}\nfunction confirm() {\n const captured = confirming.value;\n if (\n captured &&\n captured.locale === active.value &&\n captured.templateId === (props.editor.state.template?.id ?? null) &&\n captured.loadVersion === props.editor.loadVersion?.value &&\n enabled.value &&\n props.feature?.isAvailable.value &&\n !props.feature.running.value &&\n allCount.value > 0\n )\n void props.feature.translate({ only: \"all\" });\n closeConfirmation();\n}\nwatch(\n [\n () => props.editor.state.template?.id,\n () => props.editor.loadVersion?.value,\n ],\n () => {\n structureVisible.value = false;\n if (confirming.value) closeConfirmation();\n },\n { flush: \"sync\" },\n);\nwatch(active, () => {\n if (confirming.value) closeConfirmation();\n});\nwatch(\n () => props.change,\n () => {\n const templateId = props.editor.state.template?.id;\n if (templateId ? seenTemplates.has(templateId) : seenMount) return;\n if (templateId) seenTemplates.add(templateId);\n else seenMount = true;\n structureVisible.value = true;\n },\n);\n</script>\n\n<template>\n <div\n v-if=\"active !== source\"\n data-testid=\"language-bar\"\n class=\"tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-elevated)] tpl:px-4 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <div\n class=\"tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-between tpl:gap-x-6 tpl:gap-y-2\"\n >\n <!-- A 16-unit basis keeps the label and status on one line each; on a\n narrow editor the actions wrap to their own row instead. -->\n <div\n class=\"tpl:flex tpl:min-w-0 tpl:grow tpl:basis-64 tpl:flex-wrap tpl:items-center tpl:gap-x-3 tpl:gap-y-1\"\n >\n <span\n data-testid=\"language-bar-label\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-2 tpl:font-medium tpl:whitespace-nowrap tpl:text-[var(--tpl-text)]\"\n >\n <Languages :size=\"14\" aria-hidden=\"true\" class=\"tpl:shrink-0\" />\n {{\n format(t.localization.editingLanguage, {\n language: languageName(active),\n })\n }}\n </span>\n <span\n data-testid=\"language-bar-status\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n class=\"tpl:whitespace-nowrap\"\n >\n <template v-if=\"feature?.running.value\">{{\n format(t.localization.translating, feature.running.value)\n }}</template>\n <!-- A result can run to a provider's whole message, so it wraps. -->\n <span\n v-else-if=\"feature?.lastResult.value\"\n data-testid=\"translation-result\"\n class=\"tpl:whitespace-normal\"\n >{{ resultText }}</span\n >\n <template v-else>{{ status }}</template>\n </span>\n <button\n v-if=\"feature?.lastResult.value && !feature.running.value\"\n type=\"button\"\n data-testid=\"translation-dismiss\"\n :aria-label=\"t.localization.dismiss\"\n :class=\"ghostBtnCompactClass\"\n @click=\"feature.dismissResult()\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </div>\n <div class=\"tpl:flex tpl:flex-wrap tpl:items-center tpl:gap-2\">\n <button\n v-if=\"feature?.running.value\"\n type=\"button\"\n data-testid=\"translation-cancel\"\n :class=\"ghostBtnCompactClass\"\n @click=\"feature.cancel()\"\n >\n {{ t.localization.cancel }}\n </button>\n <template v-if=\"enabled && feature?.isAvailable.value\">\n <button\n v-if=\"feature.counts.value.gaps > 0\"\n type=\"button\"\n data-testid=\"translate-language\"\n :class=\"primaryBtnCompactClass\"\n :disabled=\"!!feature.running.value\"\n @click=\"feature.translate({ only: 'gaps' })\"\n >\n {{\n plural(\n t.localization.translateFields,\n feature.counts.value.gaps,\n uiLocale,\n )\n }}\n </button>\n <button\n ref=\"allAgain\"\n type=\"button\"\n data-testid=\"translate-all-again\"\n :class=\"ghostBtnCompactClass\"\n :disabled=\"!!feature.running.value || allCount === 0\"\n @click=\"startConfirmation\"\n >\n {{ t.localization.translateAllAgain }}\n </button>\n </template>\n <button\n type=\"button\"\n data-testid=\"language-back-default\"\n :class=\"ghostBtnCompactClass\"\n @click=\"editor.setActiveLocale?.(null)\"\n >\n {{\n format(t.localization.backToDefault, {\n default: languageName(source),\n })\n }}\n </button>\n </div>\n </div>\n <div\n v-if=\"structureVisible\"\n data-testid=\"structure-notice\"\n role=\"status\"\n class=\"tpl:mt-1 tpl:flex tpl:items-center tpl:gap-2\"\n >\n <span>{{ t.localization.structureNotice }}</span>\n <button\n type=\"button\"\n :aria-label=\"t.localization.dismiss\"\n :class=\"ghostBtnCompactClass\"\n @click=\"structureVisible = false\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </div>\n <TplModal :visible=\"confirming !== null\" @close=\"closeConfirmation\">\n <section\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-label=\"confirmationTitle\"\n class=\"tpl:w-96 tpl:max-w-full tpl:max-h-[90%] tpl:overflow-y-auto tpl:box-border tpl:rounded-[var(--tpl-radius)] tpl:bg-[var(--tpl-bg)] tpl:p-5 tpl:shadow-[var(--tpl-shadow-lg)]\"\n >\n <h3\n class=\"tpl:m-0 tpl:mb-4 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ confirmationTitle }}\n </h3>\n <p class=\"tpl:mb-4 tpl:text-sm tpl:text-[var(--tpl-text-muted)]\">\n {{\n format(t.localization.translationDescription, {\n language: languageName(confirming?.locale ?? active),\n })\n }}\n </p>\n <div class=\"tpl:flex tpl:flex-wrap tpl:justify-end tpl:gap-2\">\n <button\n type=\"button\"\n data-testid=\"translation-confirm-cancel\"\n :class=\"secondaryBtnClass\"\n @click=\"closeConfirmation\"\n >\n {{ t.localization.cancel }}\n </button>\n <button\n type=\"button\"\n data-testid=\"translation-confirm\"\n :class=\"primaryBtnClass\"\n :disabled=\"\n !!feature?.running.value ||\n !feature?.isAvailable.value ||\n allCount === 0\n \"\n @click=\"confirm\"\n >\n {{ plural(t.localization.translateAllFields, allCount, uiLocale) }}\n </button>\n </div>\n </section>\n </TplModal>\n </div>\n</template>\n","<script lang=\"ts\">\nconst seenTemplates = new Set<string>();\n</script>\n<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { Languages, X } from \"@lucide/vue\";\nimport { defaultLocaleOf } from \"@templatical/types\";\nimport type { BaseEditorReturn } from \"../../composables/useEditorCore\";\nimport type { UseTranslationFeatureReturn } from \"../../composables/useTranslationFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { useActiveLocaleCoverage } from \"../../composables/useLocalizedDisplay\";\nimport {\n ACTIVE_LOCALE_COVERAGE_KEY,\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n UI_LOCALE_KEY,\n} from \"../../keys\";\nimport { plural } from \"../../i18n/plural\";\nimport { languageName } from \"../../utils/languageName\";\nimport {\n ghostBtnCompactClass,\n primaryBtnClass,\n primaryBtnCompactClass,\n secondaryBtnClass,\n} from \"../../constants/styleConstants\";\nimport TplModal from \"../TplModal.vue\";\n\nconst props = defineProps<{\n editor: BaseEditorReturn;\n locales: string[];\n feature: UseTranslationFeatureReturn | null;\n change: number;\n}>();\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined) ?? \"en\";\nconst definitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst source = computed(() => defaultLocaleOf(props.editor.content.value));\nconst active = computed(() => props.editor.activeLocale?.value ?? source.value);\nconst enabled = computed(() => props.locales.includes(active.value));\n// The editor shares one pass with the header trigger; a standalone bar\n// computes its own.\nconst coverage =\n inject(ACTIVE_LOCALE_COVERAGE_KEY, null) ??\n useActiveLocaleCoverage(props.editor, definitions);\nconst status = computed(() => {\n if (!enabled.value)\n return format(t.localization.languageReadOnly, {\n language: languageName(active.value),\n });\n if (!coverage.value?.missing.length && !coverage.value?.stale.length)\n return t.localization.complete;\n return format(t.localization.gapTooltip, {\n missing: coverage.value.missing.length,\n stale: coverage.value.stale.length,\n });\n});\nconst resultText = computed(() => {\n const result = props.feature?.lastResult.value;\n if (!result) return \"\";\n const parts = [\n plural(t.localization.translatedFields, result.translated, uiLocale),\n ];\n if (result.tagsChanged.length)\n parts.push(\n plural(\n t.localization.translationTagsChanged,\n result.tagsChanged.length,\n uiLocale,\n ),\n );\n if (result.skippedLocked.length)\n parts.push(\n plural(\n t.localization.translationSkippedLocked,\n result.skippedLocked.length,\n uiLocale,\n ),\n );\n if (result.missing.length)\n parts.push(\n plural(\n t.localization.translationMissing,\n result.missing.length,\n uiLocale,\n ),\n );\n if (result.tooLarge.length)\n parts.push(\n plural(\n t.localization.translationTooLarge,\n result.tooLarge.length,\n uiLocale,\n ),\n );\n if (result.error)\n parts.push(\n format(t.localization.translationError, {\n message: result.error.message,\n }),\n );\n return parts.join(\" \");\n});\n\nconst structureVisible = ref(false);\nlet seenMount = false;\nconst confirming = ref<{\n locale: string;\n templateId: string | null;\n loadVersion: number | undefined;\n} | null>(null);\nconst allAgain = ref<HTMLButtonElement | null>(null);\nconst allCount = computed(() => props.feature?.counts.value.all ?? 0);\nconst confirmationTitle = computed(() =>\n plural(t.localization.translationConfirmation, allCount.value, uiLocale),\n);\nfunction closeConfirmation() {\n confirming.value = null;\n void nextTick(() => allAgain.value?.focus());\n}\nfunction startConfirmation() {\n confirming.value = {\n locale: active.value,\n templateId: props.editor.state.template?.id ?? null,\n loadVersion: props.editor.loadVersion?.value,\n };\n}\nfunction confirm() {\n const captured = confirming.value;\n if (\n captured &&\n captured.locale === active.value &&\n captured.templateId === (props.editor.state.template?.id ?? null) &&\n captured.loadVersion === props.editor.loadVersion?.value &&\n enabled.value &&\n props.feature?.isAvailable.value &&\n !props.feature.running.value &&\n allCount.value > 0\n )\n void props.feature.translate({ only: \"all\" });\n closeConfirmation();\n}\nwatch(\n [\n () => props.editor.state.template?.id,\n () => props.editor.loadVersion?.value,\n ],\n () => {\n structureVisible.value = false;\n if (confirming.value) closeConfirmation();\n },\n { flush: \"sync\" },\n);\nwatch(active, () => {\n if (confirming.value) closeConfirmation();\n});\nwatch(\n () => props.change,\n () => {\n const templateId = props.editor.state.template?.id;\n if (templateId ? seenTemplates.has(templateId) : seenMount) return;\n if (templateId) seenTemplates.add(templateId);\n else seenMount = true;\n structureVisible.value = true;\n },\n);\n</script>\n\n<template>\n <div\n v-if=\"active !== source\"\n data-testid=\"language-bar\"\n class=\"tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-elevated)] tpl:px-4 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <div\n class=\"tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-between tpl:gap-x-6 tpl:gap-y-2\"\n >\n <!-- A 16-unit basis keeps the label and status on one line each; on a\n narrow editor the actions wrap to their own row instead. -->\n <div\n class=\"tpl:flex tpl:min-w-0 tpl:grow tpl:basis-64 tpl:flex-wrap tpl:items-center tpl:gap-x-3 tpl:gap-y-1\"\n >\n <span\n data-testid=\"language-bar-label\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-2 tpl:font-medium tpl:whitespace-nowrap tpl:text-[var(--tpl-text)]\"\n >\n <Languages :size=\"14\" aria-hidden=\"true\" class=\"tpl:shrink-0\" />\n {{\n format(t.localization.editingLanguage, {\n language: languageName(active),\n })\n }}\n </span>\n <span\n data-testid=\"language-bar-status\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n class=\"tpl:whitespace-nowrap\"\n >\n <template v-if=\"feature?.running.value\">{{\n format(t.localization.translating, feature.running.value)\n }}</template>\n <!-- A result can run to a provider's whole message, so it wraps. -->\n <span\n v-else-if=\"feature?.lastResult.value\"\n data-testid=\"translation-result\"\n class=\"tpl:whitespace-normal\"\n >{{ resultText }}</span\n >\n <template v-else>{{ status }}</template>\n </span>\n <button\n v-if=\"feature?.lastResult.value && !feature.running.value\"\n type=\"button\"\n data-testid=\"translation-dismiss\"\n :aria-label=\"t.localization.dismiss\"\n :class=\"ghostBtnCompactClass\"\n @click=\"feature.dismissResult()\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </div>\n <div class=\"tpl:flex tpl:flex-wrap tpl:items-center tpl:gap-2\">\n <button\n v-if=\"feature?.running.value\"\n type=\"button\"\n data-testid=\"translation-cancel\"\n :class=\"ghostBtnCompactClass\"\n @click=\"feature.cancel()\"\n >\n {{ t.localization.cancel }}\n </button>\n <template v-if=\"enabled && feature?.isAvailable.value\">\n <button\n v-if=\"feature.counts.value.gaps > 0\"\n type=\"button\"\n data-testid=\"translate-language\"\n :class=\"primaryBtnCompactClass\"\n :disabled=\"!!feature.running.value\"\n @click=\"feature.translate({ only: 'gaps' })\"\n >\n {{\n plural(\n t.localization.translateFields,\n feature.counts.value.gaps,\n uiLocale,\n )\n }}\n </button>\n <button\n ref=\"allAgain\"\n type=\"button\"\n data-testid=\"translate-all-again\"\n :class=\"ghostBtnCompactClass\"\n :disabled=\"!!feature.running.value || allCount === 0\"\n @click=\"startConfirmation\"\n >\n {{ t.localization.translateAllAgain }}\n </button>\n </template>\n <button\n type=\"button\"\n data-testid=\"language-back-default\"\n :class=\"ghostBtnCompactClass\"\n @click=\"editor.setActiveLocale?.(null)\"\n >\n {{\n format(t.localization.backToDefault, {\n default: languageName(source),\n })\n }}\n </button>\n </div>\n </div>\n <div\n v-if=\"structureVisible\"\n data-testid=\"structure-notice\"\n role=\"status\"\n class=\"tpl:mt-1 tpl:flex tpl:items-center tpl:gap-2\"\n >\n <span>{{ t.localization.structureNotice }}</span>\n <button\n type=\"button\"\n :aria-label=\"t.localization.dismiss\"\n :class=\"ghostBtnCompactClass\"\n @click=\"structureVisible = false\"\n >\n <X :size=\"14\" aria-hidden=\"true\" />\n </button>\n </div>\n <TplModal :visible=\"confirming !== null\" @close=\"closeConfirmation\">\n <section\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-label=\"confirmationTitle\"\n class=\"tpl:w-96 tpl:max-w-full tpl:max-h-[90%] tpl:overflow-y-auto tpl:box-border tpl:rounded-[var(--tpl-radius)] tpl:bg-[var(--tpl-bg)] tpl:p-5 tpl:shadow-[var(--tpl-shadow-lg)]\"\n >\n <h3\n class=\"tpl:m-0 tpl:mb-4 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ confirmationTitle }}\n </h3>\n <p class=\"tpl:mb-4 tpl:text-sm tpl:text-[var(--tpl-text-muted)]\">\n {{\n format(t.localization.translationDescription, {\n language: languageName(confirming?.locale ?? active),\n })\n }}\n </p>\n <div class=\"tpl:flex tpl:flex-wrap tpl:justify-end tpl:gap-2\">\n <button\n type=\"button\"\n data-testid=\"translation-confirm-cancel\"\n :class=\"secondaryBtnClass\"\n @click=\"closeConfirmation\"\n >\n {{ t.localization.cancel }}\n </button>\n <button\n type=\"button\"\n data-testid=\"translation-confirm\"\n :class=\"primaryBtnClass\"\n :disabled=\"\n !!feature?.running.value ||\n !feature?.isAvailable.value ||\n allCount === 0\n \"\n @click=\"confirm\"\n >\n {{ plural(t.localization.translateAllFields, allCount, uiLocale) }}\n </button>\n </div>\n </section>\n </TplModal>\n </div>\n</template>\n","import type {\n UseCollaborationReturn,\n UseEditorReturn,\n UseHistoryReturn,\n} from \"@templatical/core\";\nimport {\n applyOperationsInPlace,\n invertOperations,\n OperationError,\n type Operation,\n} from \"@templatical/types\";\n\nexport interface UseLocaleActionsReturn {\n /** Applies `setDefaultLocale` as one undo step and moves the view to `locale`; returns the refusal, if any. */\n setDefaultLocale(\n locale: string,\n ): { applied: true } | { applied: false; error: OperationError };\n}\n\ninterface UseLocaleActionsOptions {\n editor: Pick<\n UseEditorReturn,\n | \"content\"\n | \"setActiveLocale\"\n | \"markDirty\"\n | \"createSetDefaultLocaleOperation\"\n >;\n history: () => Pick<UseHistoryReturn, \"record\">;\n collaboration?: {\n core: Pick<UseCollaborationReturn, \"applyOperations\">;\n } | null;\n}\n\nexport function useLocaleActions(\n options: UseLocaleActionsOptions,\n): UseLocaleActionsReturn {\n const { editor } = options;\n return {\n setDefaultLocale(locale) {\n let ops: Operation[];\n try {\n ops = [editor.createSetDefaultLocaleOperation(locale)];\n if (!options.collaboration) invertOperations(editor.content.value, ops);\n } catch (error) {\n if (error instanceof OperationError) return { applied: false, error };\n throw error;\n }\n if (options.collaboration) {\n const result = options.collaboration.core.applyOperations(ops, {});\n if (!result.applied) return result;\n } else {\n options.history().record();\n applyOperationsInPlace(editor.content.value, ops);\n editor.markDirty();\n }\n editor.setActiveLocale(locale);\n return { applied: true };\n },\n };\n}\n","import {\n computed,\n onScopeDispose,\n shallowReadonly,\n shallowRef,\n toRaw,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport type { UseEditorReturn, UseHistoryReturn } from \"@templatical/core\";\nimport {\n applyLocaleStrings,\n applyOperationsInPlace,\n defaultLocaleOf,\n invertOperations,\n localeCoverage,\n localeStrings,\n safeClone,\n SdkError,\n TRANSLATION_MAX_CHARS,\n TRANSLATION_MAX_FIELDS,\n unmaskTags,\n type Block,\n type CustomBlockDefinition,\n type LocaleCoverage,\n type LocaleString,\n type Operation,\n type SyntaxPreset,\n type TranslationErrorCode,\n type TranslationProvider,\n type TranslationResult,\n} from \"@templatical/types\";\nimport type { UseCollaborationFeatureReturn } from \"./useCollaborationFeature\";\nimport { sanitizeHtml } from \"../utils/sanitizeHtml\";\n\nexport interface TranslationRunResult {\n translated: number;\n tagsChanged: string[];\n skippedLocked: string[];\n missing: string[];\n /** A field over the per-call character cap: never sent, and the run stops there. */\n tooLarge: string[];\n error: { code: string; message: string } | null;\n cancelled: boolean;\n}\n\nexport interface UseTranslationFeatureReturn {\n isAvailable: ComputedRef<boolean>;\n counts: ComputedRef<{ gaps: number; all: number }>;\n running: Readonly<Ref<{ done: number; total: number } | null>>;\n lastResult: Readonly<Ref<TranslationRunResult | null>>;\n translate(scope: {\n only: \"gaps\" | \"all\";\n blockId?: string;\n }): Promise<TranslationRunResult>;\n cancel(): void;\n dismissResult(): void;\n}\n\ninterface UseTranslationFeatureOptions {\n provider: TranslationProvider;\n editor: Pick<\n UseEditorReturn,\n \"content\" | \"activeLocale\" | \"loadVersion\" | \"state\" | \"markDirty\"\n >;\n localization?: { locales: string[]; doNotTranslate?: string[] };\n definitions: () => readonly CustomBlockDefinition[];\n syntax: () => SyntaxPreset;\n history: () => Pick<UseHistoryReturn, \"record\">;\n collaboration?: Pick<UseCollaborationFeatureReturn, \"core\"> | null;\n /** The active view's coverage when the editor already computes it. */\n coverage?: () => LocaleCoverage | null;\n}\n\n/** Provider errors cross bundles and may be plain objects. */\nfunction translationError(error: unknown): {\n code: TranslationErrorCode;\n message?: string;\n statusCode?: number;\n} | null {\n if (typeof error !== \"object\" || error === null) return null;\n const shaped = error as {\n code?: unknown;\n message?: unknown;\n statusCode?: unknown;\n };\n if (\n (shaped.code !== \"rate_limited\" &&\n shaped.code !== \"limit_reached\" &&\n shaped.code !== \"content_too_large\" &&\n shaped.code !== \"translation_failed\") ||\n (shaped.statusCode !== undefined && typeof shaped.statusCode !== \"number\")\n )\n return null;\n return {\n code: shaped.code,\n ...(typeof shaped.message === \"string\" ? { message: shaped.message } : {}),\n ...(shaped.statusCode === undefined\n ? {}\n : { statusCode: shaped.statusCode }),\n };\n}\n\n/** Every `style` attribute value of an HTML fragment, as a browser reads it. */\nfunction styleValues(html: string): Set<string> {\n const values = new Set<string>();\n if (typeof DOMParser === \"undefined\") return values;\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n for (const element of parsed.querySelectorAll(\"[style]\"))\n values.add(element.getAttribute(\"style\") ?? \"\");\n return values;\n}\n\n/**\n * A translation may keep its default's inline styles, move them or drop them,\n * but not add or change one: a style can fetch a remote file or overlay the\n * email, and the sanitizer keeps `style`.\n */\nfunction keepsStyles(translation: string, source: string): boolean {\n const allowed = styleValues(source);\n return [...styleValues(translation)].every((style) => allowed.has(style));\n}\n\n/** Keep placeholder bytes out of the DOM parser, including in attributes. */\nfunction sanitizeTranslation(text: string): string {\n const prefix = `tpl-translation-${crypto.randomUUID()}-`;\n const placeholders: string[] = [];\n const protectedText = text.replace(\n /<x id=\"\\d+\"\\s*\\/>|<x id=\"\\d+\"><\\/x>|__x\\d+__/g,\n (token) => `${prefix}${placeholders.push(token)}-end`,\n );\n let clean = sanitizeHtml(protectedText);\n placeholders.forEach((token, index) => {\n clean = clean.replaceAll(`${prefix}${index + 1}-end`, token);\n });\n return clean;\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal) {\n signal.throwIfAborted();\n let abort!: () => void;\n const stopped = new Promise<never>((_, reject) => {\n abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n });\n try {\n return await Promise.race([promise, stopped]);\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n}\n\nexport function useTranslationFeature(\n options: UseTranslationFeatureOptions,\n): UseTranslationFeatureReturn {\n const { editor } = options;\n const running = shallowRef<{ done: number; total: number } | null>(null);\n const lastResult = shallowRef<TranslationRunResult | null>(null);\n let active: { controller: AbortController; discarded: boolean } | null = null;\n const disposed = shallowRef(false);\n const isAvailable = computed(() => {\n const locale = editor.activeLocale.value;\n return (\n !disposed.value &&\n !!locale &&\n locale !== defaultLocaleOf(editor.content.value) &&\n !!options.localization?.locales.includes(locale) &&\n !!editor.content.value.settings.locales?.includes(locale)\n );\n });\n // One extraction of every eligible field; the gaps among them come from the\n // coverage the editor already computes, so a change costs one coverage pass.\n const counts = computed(() => {\n if (!isAvailable.value) return { gaps: 0, all: 0 };\n const locale = editor.activeLocale.value!;\n const definitions = options.definitions();\n const coverage =\n options.coverage?.() ??\n localeCoverage(editor.content.value, locale, definitions);\n const gapIds = new Set([...coverage.missing, ...coverage.stale]);\n const { strings } = localeStrings(editor.content.value, locale, {\n definitions,\n syntax: options.syntax(),\n doNotTranslate: options.localization?.doNotTranslate,\n only: \"all\",\n });\n return {\n gaps: strings.filter(({ id }) => gapIds.has(id)).length,\n all: strings.length,\n };\n });\n function cancel() {\n active?.controller.abort();\n }\n function discard() {\n if (active) active.discarded = true;\n cancel();\n lastResult.value = null;\n }\n watch(\n editor.activeLocale,\n () => {\n cancel();\n lastResult.value = null;\n },\n { flush: \"sync\" },\n );\n watch(\n [editor.content, editor.loadVersion, () => editor.state.template?.id],\n discard,\n { flush: \"sync\" },\n );\n onScopeDispose(() => {\n disposed.value = true;\n discard();\n });\n\n async function translate(scope: {\n only: \"gaps\" | \"all\";\n blockId?: string;\n }): Promise<TranslationRunResult> {\n if (active)\n throw new SdkError(\n \"A translation is already running.\",\n 409,\n \"translation_running\",\n );\n if (!isAvailable.value)\n throw new SdkError(\n \"Translation isn't available in this language.\",\n 403,\n \"feature_unavailable\",\n );\n const core = options.collaboration?.core;\n core?.flush();\n const locale = editor.activeLocale.value!;\n const templateId = editor.state.template?.id ?? null;\n const sourceLocale = defaultLocaleOf(editor.content.value);\n const definitions = safeClone(toRaw([...options.definitions()]));\n const syntax = options.syntax();\n const doNotTranslate = options.localization?.doNotTranslate?.slice();\n const extraction = localeStrings(editor.content.value, locale, {\n ...scope,\n definitions,\n syntax,\n doNotTranslate,\n });\n const result: TranslationRunResult = {\n translated: 0,\n tagsChanged: [],\n skippedLocked: [],\n missing: [],\n tooLarge: [],\n error: null,\n cancelled: false,\n };\n const job = { controller: new AbortController(), discarded: false };\n active = job;\n lastResult.value = null;\n running.value = { done: 0, total: extraction.strings.length };\n const values: { id: string; text: string; sourceHash: string }[] = [];\n let offset = 0;\n let limit = TRANSLATION_MAX_FIELDS;\n try {\n while (offset < extraction.strings.length) {\n job.controller.signal.throwIfAborted();\n const chunk: LocaleString[] = [];\n let chars = 0;\n for (const field of extraction.strings.slice(offset, offset + limit)) {\n if (chars + field.source.length > TRANSLATION_MAX_CHARS) break;\n chunk.push(field);\n chars += field.source.length;\n }\n if (chunk.length === 0) {\n // The editor's own limit: the field is never sent, so no service\n // refused it. Fields returned so far still apply.\n result.tooLarge.push(extraction.strings[offset].id);\n break;\n }\n let answer: TranslationResult;\n try {\n answer = await abortable(\n options.provider.translate(\n {\n templateId,\n sourceLocale,\n targetLocale: locale,\n fields: chunk.map(({ id, source, format }) => ({\n id,\n text: source,\n format,\n })),\n },\n job.controller.signal,\n ),\n job.controller.signal,\n );\n job.controller.signal.throwIfAborted();\n } catch (error) {\n if (\n !job.controller.signal.aborted &&\n translationError(error)?.code === \"content_too_large\" &&\n chunk.length > 1\n ) {\n limit = Math.floor(chunk.length / 2);\n continue;\n }\n throw error;\n }\n for (const field of chunk) {\n const returned = answer.fields.find((value) => value.id === field.id);\n if (!returned) {\n result.missing.push(field.id);\n continue;\n }\n const tokens = extraction.tokens[field.id];\n const restored = unmaskTags(returned.text, tokens);\n if (\n restored === null ||\n (field.format === \"html\" &&\n !keepsStyles(restored, unmaskTags(field.source, tokens)!))\n ) {\n result.tagsChanged.push(field.id);\n continue;\n }\n values.push({\n id: field.id,\n text:\n field.format === \"html\"\n ? sanitizeTranslation(returned.text)\n : returned.text,\n sourceHash: field.sourceHash,\n });\n }\n offset += chunk.length;\n running.value = { done: offset, total: extraction.strings.length };\n }\n } catch (error) {\n if (\n job.controller.signal.aborted ||\n (error instanceof Error && error.name === \"AbortError\")\n )\n result.cancelled = true;\n else\n result.error = {\n code: translationError(error)?.code ?? \"translation_failed\",\n message:\n translationError(error)?.message ??\n (error instanceof Error ? error.message : String(error)),\n };\n }\n try {\n if (!job.discarded) {\n core?.flush();\n const applied = applyLocaleStrings(\n editor.content.value,\n locale,\n values,\n {\n definitions,\n syntax,\n doNotTranslate,\n tokens: extraction.tokens,\n },\n );\n for (const rejection of applied.rejected)\n if (rejection.reason === \"tags_changed\")\n result.tagsChanged.push(rejection.id);\n const blocks = new Map<string, Block>();\n const collect = (items: Block[]) => {\n for (const block of items) {\n blocks.set(block.id, block);\n if (block.type === \"section\")\n for (const column of block.children) collect(column);\n }\n };\n collect(editor.content.value.blocks);\n const changed = applied.operations\n .map((operation): Operation | null => {\n if (\n operation.op !== \"updateBlockLocale\" &&\n operation.op !== \"updateSettingsLocale\"\n )\n return operation;\n const stored =\n operation.op === \"updateSettingsLocale\"\n ? editor.content.value.settings.l10n?.[locale]?.text\n : blocks.get(operation.blockId)?.l10n?.[locale]?.text;\n const text = Object.fromEntries(\n Object.entries(operation.text ?? {}).filter(\n ([path, value]) =>\n value.value !== stored?.[path]?.value ||\n value.sourceHash !== stored?.[path]?.sourceHash,\n ),\n );\n return Object.keys(text).length ? { ...operation, text } : null;\n })\n .filter((operation): operation is Operation => operation !== null);\n const operations = changed.filter((operation) => {\n if (operation.op !== \"updateBlockLocale\" || !core) return true;\n const locked = core\n .locksOf(operation.blockId)\n .some(\n (lock) =>\n lock.holder.sessionId !== core.sessionId &&\n (lock.locale == null || lock.locale === locale),\n );\n if (locked)\n result.skippedLocked.push(\n ...Object.keys(operation.text ?? {}).map(\n (path) => `${operation.blockId}/${path}`,\n ),\n );\n return !locked;\n });\n if (operations.length) {\n // Validate before recording; the controller captures this ordinary\n // local mutation by diffing, with no new collaboration origin.\n invertOperations(toRaw(editor.content.value), operations);\n options.history().record();\n applyOperationsInPlace(editor.content.value, operations);\n editor.markDirty();\n core?.flush();\n result.translated = operations.reduce(\n (count, operation) =>\n count +\n (operation.op === \"updateBlockLocale\" ||\n operation.op === \"updateSettingsLocale\"\n ? Object.keys(operation.text ?? {}).length\n : 0),\n 0,\n );\n }\n if (editor.activeLocale.value === locale) lastResult.value = result;\n }\n } finally {\n active = null;\n running.value = null;\n }\n return result;\n }\n\n return {\n isAvailable,\n counts,\n running: shallowReadonly(running),\n lastResult: shallowReadonly(lastResult),\n translate,\n cancel,\n dismissResult: () => {\n lastResult.value = null;\n },\n };\n}\n","import {\n computed,\n getCurrentScope,\n onScopeDispose,\n ref,\n shallowRef,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport {\n useCollaboration,\n type CollaborationEditor,\n type CollaborationNotice,\n type UseCollaborationReturn,\n type UseHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n BlockLock,\n BlockLockHolder,\n CollaborationActor,\n CollaborationConflictCode,\n CollaborationProvider,\n CollaborationRemoteChange,\n EditorUser,\n MergeTagsConfig,\n Operation,\n Template,\n} from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\nimport { normalizeRemoteOperations } from \"../utils/normalizeMergeTagMarkup\";\n\n/** How long a notice stays up. */\nexport const COLLABORATION_NOTICE_MS = 5000;\n/** An agent's batches closer together than this share one notice. */\nexport const AGENT_EDIT_MERGE_MS = 2000;\n/** How long the blocks an agent changed stay outlined. */\nexport const AGENT_HIGHLIGHT_MS = 2000;\n\n/** One person in the collaborator bar: a user's sessions, or one guest. */\nexport interface CollaborationPerson {\n key: string;\n type: \"user\" | \"guest\";\n /** The member's name; the bar shows its own word for a guest. */\n name: string;\n avatarUrl?: string;\n color: string;\n}\n\n/** `Omit` for each member of a union. */\ntype OmitEach<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/** A notice the editor shows, in words the components translate. */\nexport type CollaborationNoticeView =\n | { id: number; kind: \"selectionRefused\"; name: string; isGuest: boolean }\n | {\n id: number;\n kind: \"editRefused\";\n code: CollaborationConflictCode;\n name?: string;\n isGuest?: boolean;\n }\n | { id: number; kind: \"undoSkipped\" }\n | {\n id: number;\n kind: \"replaceRefused\";\n holders: { name: string; isGuest: boolean }[];\n }\n | {\n id: number;\n kind: \"agentEdited\";\n /** The agent's name, or `null` when the backend sent none. */\n client: string | null;\n /** The user the agent acts for. */\n name: string;\n /** Distinct blocks the agent added, moved, deleted or updated. */\n blocks: number;\n /** The agent changed the template settings. */\n settings: boolean;\n /** The agent updated the whole template: a replace, a restore or a re-sync. */\n templateUpdated: boolean;\n }\n | {\n id: number;\n /** An AI changed the template for a user (`actor.type: \"ai\"`): Cloud, or a BYO backend honouring `origin: \"ai\"`. */\n kind: \"aiEdited\";\n /** The user who asked the AI. */\n name: string;\n blocks: number;\n settings: boolean;\n /** The AI built or replaced the whole template, or a re-sync came in. */\n templateUpdated: boolean;\n };\n\n/** What one batch from an agent changed. */\nexport interface AgentEditSummary {\n /** The blocks its ops name: an added block's id, every other block op's `blockId`. */\n blockIds: string[];\n /** It changes default or localized settings, or adds or removes a language. */\n settings: boolean;\n /** It has a `setContent`, or it is a re-sync. */\n templateUpdated: boolean;\n}\n\n/** What a re-sync says: the template changed as a whole, and no blocks are named. */\nconst RESYNC_SUMMARY: AgentEditSummary = {\n blockIds: [],\n settings: false,\n templateUpdated: true,\n};\n\n/**\n * Read an agent's batch for its notice: the distinct blocks it names, and\n * whether it changed the settings or updated the whole template.\n */\nexport function summarizeAgentEdit(\n ops: readonly Operation[],\n): AgentEditSummary {\n const blockIds = new Set<string>();\n let settings = false;\n let templateUpdated = false;\n for (const op of ops) {\n if (op.op === \"addBlock\") {\n if (typeof op.block?.id === \"string\") blockIds.add(op.block.id);\n } else if (\n op.op === \"updateSettings\" ||\n op.op === \"addLocale\" ||\n op.op === \"removeLocale\" ||\n op.op === \"updateSettingsLocale\"\n ) {\n settings = true;\n } else if (op.op === \"setContent\" || op.op === \"setDefaultLocale\") {\n templateUpdated = true;\n } else {\n blockIds.add(op.blockId);\n }\n }\n return { blockIds: [...blockIds], settings, templateUpdated };\n}\n\nexport interface UseCollaborationFeatureOptions {\n provider: CollaborationProvider;\n /** The templates provider's `load`, for a re-sync. */\n loadTemplate: (templateId: string) => Promise<Template>;\n /** `init({ user })`: the editor's own sessions are left out of the bar by it too. */\n user?: EditorUser;\n /**\n * `init({ mergeTags })`: another session's batch has its tokens turned into\n * tags with it as it arrives, the way loaded content does.\n */\n mergeTags?: MergeTagsConfig;\n onRemoteChange?: (change: CollaborationRemoteChange) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseCollaborationFeatureReturn {\n core: UseCollaborationReturn;\n /** Others' locks, read by `useEditor` before the controller attaches. */\n locks: UseCollaborationReturn[\"locks\"];\n /** Wire the controller to the editor; call once, after `useEditor()`. */\n attach: (editor: CollaborationEditor) => void;\n /** Undo and redo by inverse batches, in place of the snapshot history. */\n history: UseHistoryReturn;\n /** Everyone else, one entry per person; empty without presence. */\n people: ComputedRef<CollaborationPerson[]>;\n /** Presence is live: the bar shows. */\n isLive: ComputedRef<boolean>;\n connection: UseCollaborationReturn[\"connection\"];\n notices: Ref<CollaborationNoticeView[]>;\n dismissNotice: (id: number) => void;\n /** Say a whole-template replace was refused, naming who holds locks. */\n reportReplaceRefused: (holders: readonly BlockLockHolder[]) => void;\n /**\n * Outline blocks for AGENT_HIGHLIGHT_MS, with no notice: the editor that\n * asked an AI shows its own turn's changes this way (D26).\n */\n outline: (blockIds: readonly string[]) => void;\n capability: NonNullable<EditorCapabilities[\"collaboration\"]>;\n}\n\n/** One agent's, or the AI's, run of batches and re-syncs while they share a notice. */\ninterface AgentRun {\n /** The actor type, the user it acts for and, for an agent, its own name. */\n key: string;\n noticeId: number;\n lastAt: number;\n blockIds: Set<string>;\n settings: boolean;\n templateUpdated: boolean;\n}\n\n/**\n * Shared glue for collaboration: the controller from `@templatical/core`, the\n * history it replaces, the people the bar shows and the notices — an AI\n * agent's and an AI's edits included, with the outline on the blocks\n * they changed.\n *\n * Built before `useEditor()`, because the editor reads others' locks from it;\n * `attach` wires it to the editor right after.\n */\nexport function useCollaborationFeature(\n options: UseCollaborationFeatureOptions,\n): UseCollaborationFeatureReturn {\n const notices = ref<CollaborationNoticeView[]>([]);\n let nextNoticeId = 1;\n const dismissTimers = new Map<number, ReturnType<typeof setTimeout>>();\n\n /** Start, or restart, a notice's countdown to dismissal. */\n function armDismiss(id: number): void {\n const running = dismissTimers.get(id);\n if (running) clearTimeout(running);\n dismissTimers.set(\n id,\n setTimeout(() => dismissNotice(id), COLLABORATION_NOTICE_MS),\n );\n }\n\n function show(notice: OmitEach<CollaborationNoticeView, \"id\">): number {\n const id = nextNoticeId++;\n // One at a time: a newer notice replaces the one on screen.\n notices.value = [{ ...notice, id }];\n armDismiss(id);\n return id;\n }\n\n function dismissNotice(id: number): void {\n const running = dismissTimers.get(id);\n if (running) {\n clearTimeout(running);\n dismissTimers.delete(id);\n }\n notices.value = notices.value.filter((notice) => notice.id !== id);\n }\n\n function onNotice(notice: CollaborationNotice): void {\n if (notice.type === \"selectionRefused\") {\n show({\n kind: \"selectionRefused\",\n name: notice.holder.name,\n isGuest: notice.holder.type === \"guest\",\n });\n } else if (notice.type === \"editRefused\") {\n show({\n kind: \"editRefused\",\n code: notice.code,\n ...(notice.holder\n ? {\n name: notice.holder.name,\n isGuest: notice.holder.type === \"guest\",\n }\n : {}),\n });\n } else {\n show({ kind: \"undoSkipped\" });\n }\n }\n\n // --- Agents' edits ---------------------------------------------------------\n\n let agentRun: AgentRun | null = null;\n const highlights = shallowRef<ReadonlyMap<string, number>>(new Map());\n const highlightTimers = new Map<string, ReturnType<typeof setTimeout>>();\n let highlightSequence = 0;\n\n /** Outline `blockIds` for AGENT_HIGHLIGHT_MS, under one new number. */\n function highlight(blockIds: readonly string[]): void {\n if (blockIds.length === 0) return;\n const sequence = ++highlightSequence;\n const next = new Map(highlights.value);\n for (const blockId of blockIds) {\n next.set(blockId, sequence);\n const running = highlightTimers.get(blockId);\n if (running) clearTimeout(running);\n highlightTimers.set(\n blockId,\n setTimeout(() => {\n highlightTimers.delete(blockId);\n const rest = new Map(highlights.value);\n rest.delete(blockId);\n highlights.value = rest;\n }, AGENT_HIGHLIGHT_MS),\n );\n }\n highlights.value = next;\n }\n\n /**\n * An agent's or the AI's batch or re-sync: a notice naming who acted and\n * for whom, and an outline on the blocks a batch changed. Batches and\n * re-syncs from one of them within AGENT_EDIT_MERGE_MS of each other update\n * one notice while it is the one on screen, counting each block once — so\n * the batch a re-sync's catch-up brings lands in the re-sync's notice. The\n * editor that asked the AI only outlines its batches (D26).\n */\n function noteAgent(\n actor: CollaborationActor,\n summary: AgentEditSummary,\n ): void {\n if (actor.type !== \"mcp\" && actor.type !== \"ai\") return;\n const isAi = actor.type === \"ai\";\n // The editor that asked the AI outlines the change but shows no notice:\n // its chat already says \"Applied N changes\" (D26).\n if (isAi && actor.sessionId === core.sessionId) {\n if (!summary.templateUpdated) highlight(summary.blockIds);\n return;\n }\n const client =\n !isAi && typeof actor.client === \"string\" && actor.client.trim() !== \"\"\n ? actor.client\n : null;\n const key = `${actor.type}\\n${actor.id ?? \"\"}\\n${client ?? \"\"}`;\n const now = Date.now();\n\n let run = agentRun;\n if (\n !run ||\n run.key !== key ||\n now - run.lastAt > AGENT_EDIT_MERGE_MS ||\n notices.value.at(-1)?.id !== run.noticeId\n ) {\n run = {\n key,\n noticeId: 0,\n lastAt: now,\n blockIds: new Set(),\n settings: false,\n templateUpdated: false,\n };\n }\n for (const blockId of summary.blockIds) run.blockIds.add(blockId);\n run.settings ||= summary.settings;\n run.templateUpdated ||= summary.templateUpdated;\n run.lastAt = now;\n\n const counts = {\n blocks: run.blockIds.size,\n settings: run.settings,\n templateUpdated: run.templateUpdated,\n };\n const view: OmitEach<CollaborationNoticeView, \"id\"> = isAi\n ? { kind: \"aiEdited\", name: actor.name, ...counts }\n : { kind: \"agentEdited\", client, name: actor.name, ...counts };\n if (run === agentRun) {\n notices.value = [{ ...view, id: run.noticeId }];\n armDismiss(run.noticeId);\n } else {\n run.noticeId = show(view);\n agentRun = run;\n }\n if (!summary.templateUpdated) highlight(summary.blockIds);\n }\n\n const core = useCollaboration({\n provider: options.provider,\n loadTemplate: options.loadTemplate,\n normalizeRemoteOperations: (ops, content) =>\n normalizeRemoteOperations(ops, content, options.mergeTags),\n // The consumer's callback runs whatever happens to the notice: an\n // integrator's `onRemoteChange` must not depend on the editor's chrome.\n onRemoteChange: (change) => {\n try {\n noteAgent(change.actor, summarizeAgentEdit(change.ops));\n } finally {\n options.onRemoteChange?.(change);\n }\n },\n // An agent's replace or restore, an AI's built template, or a batch too\n // large to broadcast reaches live editors only as a re-sync: the template\n // changed as a whole.\n onRemoteResync: ({ actor }) => noteAgent(actor, RESYNC_SUMMARY),\n onNotice,\n onError: options.onError,\n });\n\n if (getCurrentScope()) {\n onScopeDispose(() => {\n for (const timer of dismissTimers.values()) clearTimeout(timer);\n for (const timer of highlightTimers.values()) clearTimeout(timer);\n dismissTimers.clear();\n highlightTimers.clear();\n });\n }\n\n const people = computed<CollaborationPerson[]>(() => {\n const members = core.members.value;\n const self = members.find((member) => member.sessionId === core.sessionId);\n const myUserId = self?.userId ?? options.user?.id ?? null;\n const byPerson = new Map<string, CollaborationPerson>();\n for (const member of members) {\n if (member.sessionId === core.sessionId) continue;\n if (member.userId !== null && member.userId === myUserId) continue;\n const key =\n member.userId !== null\n ? `user:${member.userId}`\n : `guest:${member.sessionId}`;\n if (byPerson.has(key)) continue;\n byPerson.set(key, {\n key,\n type: member.type,\n name: member.name,\n ...(member.avatarUrl ? { avatarUrl: member.avatarUrl } : {}),\n color: member.color,\n });\n }\n return [...byPerson.values()];\n });\n\n const history: UseHistoryReturn = {\n canUndo: core.canUndo,\n canRedo: core.canRedo,\n isNavigating: ref(false),\n undo: core.undo,\n redo: core.redo,\n // The controller captures every change by diffing; nothing to record.\n record: () => {},\n recordDebounced: () => {},\n clear: core.clearHistory,\n destroy: () => {},\n };\n\n return {\n core,\n locks: core.locks,\n attach: core.attach,\n history,\n people,\n isLive: computed(() => core.members.value.length > 0),\n connection: core.connection,\n notices,\n dismissNotice,\n reportReplaceRefused: (holders) =>\n show({\n kind: \"replaceRefused\",\n holders: [\n ...new Map(\n holders.map((holder) => [\n holder.type === \"guest\" ? `guest:${holder.sessionId}` : holder.id,\n { name: holder.name, isGuest: holder.type === \"guest\" },\n ]),\n ).values(),\n ],\n }),\n outline: highlight,\n capability: {\n lockOf: (\n blockId: string,\n locale = core.lockLocale.value,\n ): BlockLock | null => {\n const locks = core.locksOf(blockId);\n return (\n locks.find((lock) => lock.locale == null) ??\n locks.find((lock) => locale === null || lock.locale === locale) ??\n null\n );\n },\n agentHighlightOf: (blockId: string): number | null =>\n highlights.value.get(blockId) ?? null,\n },\n };\n}\n","import { computed, ref, watch, type ComputedRef, type Ref } from \"vue\";\nimport { useComments, useCommentListener } from \"@templatical/core\";\nimport type { UseCommentsReturn } from \"@templatical/core\";\nimport type { CommentsProvider, EditorUser } from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — OSS and Cloud alike. */\ninterface CommentsEditor {\n state: {\n readonly template?: { id: string } | null;\n };\n}\n\nexport interface UseCommentsFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: CommentsProvider;\n editor: CommentsEditor;\n /**\n * Who is commenting (`init({ user })`). **Without one the feature reports\n * itself unavailable** — see {@link isAvailable}.\n */\n user?: EditorUser | null;\n /**\n * The panel's open state. Cloud passes its own; otherwise a local ref is\n * used. The open-source AI feature reads this state to keep comments and\n * AI panels mutually exclusive in their shared 360px gutter.\n */\n isOpen?: Ref<boolean>;\n onError?: (error: Error) => void;\n /**\n * Extra gate on top of a provider and a user being present — Cloud adds its\n * `commenting` plan entitlement and \"the template must be saved\". Read\n * reactively, so a Cloud entitlement that resolves after setup still lights the\n * feature up.\n */\n isAvailable?: () => boolean;\n /**\n * Whether a block id exists in the **stored** template. Cloud supplies this: a\n * comment is anchored server-side, so filtering to a block that only exists on\n * the canvas has nothing to show. Absent means \"assume it does\", which is right\n * for a store that accepts any anchor.\n */\n isBlockSaved?: (blockId: string) => boolean;\n}\n\nexport interface UseCommentsFeatureReturn {\n headless: UseCommentsReturn;\n\n isOpen: Ref<boolean>;\n isAvailable: ComputedRef<boolean>;\n /** True once a template exists — comments are keyed to one. */\n hasTemplate: ComputedRef<boolean>;\n unresolvedCount: ComputedRef<number>;\n\n /**\n * The block the panel should filter to, or `null` for no block filter. Owned\n * here rather than in the panel because a block's comment indicator sets it\n * *before* the lazy panel exists.\n */\n filterBlockId: Ref<string | null>;\n\n /** Toggle the panel. A no-op while unavailable. */\n toggle: () => void;\n close: () => void;\n /** Open the panel filtered to one block — what the canvas indicator calls. */\n openForBlock: (blockId: string) => void;\n\n capability: NonNullable<EditorCapabilities[\"comments\"]>;\n}\n\n/**\n * Shared glue for comments: the reactive thread list, the panel's open and filter\n * state, and the capability the shared chrome gates on.\n *\n * Both entry points construct this — OSS from `init({ comments })`, Cloud from\n * `createCloudCommentsProvider` — so the two run identical logic over different\n * transports. Nothing here is auth- or plan-aware; callers decide availability.\n *\n * **Nothing is fetched at mount.** The list is read when the panel opens, matching\n * saved blocks: a review panel nobody opens should cost no round-trip, and the\n * unresolved badge is worth less than a request on every editor boot.\n */\nexport function useCommentsFeature(\n options: UseCommentsFeatureOptions,\n): UseCommentsFeatureReturn {\n const { provider, editor } = options;\n\n const headless = useComments({\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n // Read through a getter, never destructured: Cloud fills `user` from the JWT\n // and a consumer may swap it, and the same lesson as `allowedRecipients`\n // applies — a snapshot at setup pins the answer forever.\n getUser: () => options.user ?? null,\n onError: options.onError,\n });\n\n // Provider-driven realtime, or nothing at all when the provider has no\n // `subscribe`. It is deliberately wired here rather than inside `useComments`:\n // the subscription is a lifecycle concern (it follows the template and must be\n // torn down), and `useComments` is state.\n useCommentListener({\n comments: headless,\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n });\n\n const isOpen = options.isOpen ?? ref(false);\n const filterBlockId = ref<string | null>(null);\n\n const hasTemplate = computed(() => !!editor.state.template?.id);\n const unresolvedCount = headless.unresolvedCount;\n\n const isAvailable = computed(() => {\n // No identity ⇒ unavailable, never anonymous. Every comment carries an author\n // and an unattributable one is worse than no comment feature.\n if (!options.user) return false;\n return options.isAvailable?.() ?? true;\n });\n\n // A panel left open when the feature goes away — a Cloud plan fetch that\n // withholds `commenting`, or a consumer clearing `user` — would sit there with\n // no trigger to close it.\n watch(isAvailable, (available) => {\n if (!available) isOpen.value = false;\n });\n\n // Load as soon as there is a template, not just when the panel opens. Unlike\n // saved blocks or version history — whose lists are read only by the surface\n // that fetches them — two indicators *outside* this panel derive from the whole\n // list: `unresolvedCount` feeds the header badge, and `commentCountByBlock`\n // feeds the per-block canvas markers. Deferring the fetch left both at zero, so\n // a template arriving with existing comments showed no sign of them anywhere\n // until the user happened to click Comments, and the badge then popped into\n // existence — the same \"reads 0, then pops\" failure that cost the saved-blocks\n // rail its count.\n //\n // Loading the lot up front is already the design's assumption: `comments.list`\n // is deliberately unpaginated precisely because those two aggregates are\n // computed over every thread.\n watch(\n [isAvailable, hasTemplate],\n ([available, attached]) => {\n if (!available || !attached) return;\n void headless.load().catch(() => {\n /* reported through onError */\n });\n },\n { immediate: true },\n );\n\n // Every open re-reads. History and comments both grow elsewhere, so a list\n // fetched once goes stale silently; only a *first* open has nothing to show\n // meanwhile, which the panel distinguishes for its skeleton.\n watch(isOpen, (open) => {\n if (!open || !hasTemplate.value) return;\n void headless.load().catch(() => {\n /* reported through onError */\n });\n });\n\n function toggle(): void {\n if (!isAvailable.value) return;\n isOpen.value = !isOpen.value;\n }\n\n function close(): void {\n isOpen.value = false;\n }\n\n function openForBlock(blockId: string): void {\n if (!isAvailable.value) return;\n filterBlockId.value = blockId;\n // Assigning `true` to an already-true ref fires no watcher, so an indicator\n // clicked while the panel is open must refresh explicitly — otherwise moving\n // between blocks shows a list read before the last change.\n if (isOpen.value) {\n if (hasTemplate.value) {\n void headless.load().catch(() => {\n /* reported through onError */\n });\n }\n return;\n }\n isOpen.value = true;\n }\n\n return {\n headless,\n\n isOpen,\n isAvailable,\n hasTemplate,\n unresolvedCount,\n\n filterBlockId,\n\n toggle,\n close,\n openForBlock,\n\n capability: {\n getBlockCount: (blockId: string) =>\n headless.commentCountByBlock.value.get(blockId) ?? 0,\n openForBlock,\n // Absent means \"any anchor is fine\", which is the right default for a store\n // that accepts one. Cloud supplies the real check because it renders from\n // the saved template.\n isBlockSaved: (blockId: string) =>\n options.isBlockSaved?.(blockId) ?? true,\n isAvailable,\n unresolvedCount,\n canCreate: headless.canCreate,\n canUpdate: headless.canUpdate,\n canDelete: headless.canDelete,\n canResolve: headless.canResolve,\n },\n };\n}\n","import {\n computed,\n getCurrentScope,\n ref,\n shallowRef,\n toRaw,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport {\n mapLocalizedOperations,\n type UseHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n AiChatMessage,\n AiFeatureName,\n AiFixFinding,\n AiMergeTags,\n AiMessageKind,\n AiOperationsResult,\n AiProvider,\n AiRequestBase,\n AiRewriteRequest,\n AiTurnHandlers,\n AiTurnResult,\n Block,\n CustomBlockDefinition,\n Operation,\n TemplateContent,\n} from \"@templatical/types\";\nimport {\n defaultLocaleOf,\n resolveLocale,\n applyOperationsInPlace,\n CollaborationConflict,\n deepEqual,\n invertOperations,\n OperationError,\n safeClone,\n SdkError,\n} from \"@templatical/types\";\nimport {\n AI_MISSING_PROVIDER_MESSAGE,\n type AiErrorContext,\n} from \"../utils/aiErrors\";\nimport {\n aiImageContext,\n aiImageSnapshot,\n type AiImageSnapshot,\n} from \"../utils/aiImageContext\";\nimport { DEFAULT_ALT_MAX_LENGTH } from \"../utils/aiFixableRules\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\nimport {\n AGENT_HIGHLIGHT_MS,\n summarizeAgentEdit,\n type UseCollaborationFeatureReturn,\n} from \"./useCollaborationFeature\";\n\n/** How long a turn waits for this editor's unsent edits to reach the backend. */\nexport const AI_SETTLE_TIMEOUT_MS = 3000;\n/** How long a live channel gets to deliver a server-applied batch before a catch-up. */\nexport const AI_BROADCAST_GRACE_MS = 1000;\nexport { AI_MISSING_PROVIDER_MESSAGE } from \"../utils/aiErrors\";\n/** UTF-8 bytes of serialized content, matching the wire's AI_LIMITS. */\nexport const AI_CONTENT_MAX_BYTES = 200_000;\n\nexport type AiPanel = \"chat\";\nexport type { AiErrorContext } from \"../utils/aiErrors\";\n\nexport interface AiFailure {\n error: Error;\n context: AiErrorContext;\n}\n\n/** One row of the chat (D16). */\nexport interface AiChatItem {\n id: string;\n role: \"user\" | \"assistant\";\n kind: AiMessageKind;\n locale?: string | null;\n text: string;\n attachments: { name: string; kind: \"image\" | \"pdf\" }[];\n /** Operations this turn changed, client- and server-applied together. */\n operationCount: number;\n undone: boolean;\n /** Undo is available for this not-undone message. */\n canUndo: boolean;\n /** Redo is available for this undone message. */\n canRedo: boolean;\n createdAt: string;\n status: \"streaming\" | \"done\" | \"failed\";\n /** Why the turn, or its last Undo or Redo, failed. */\n failure?: AiFailure;\n}\n\nexport interface AiTurnOutcome {\n /** The assistant item's id, `null` when the turn left no message. */\n messageId: string | null;\n operationCount: number;\n text: string;\n failed: boolean;\n}\n\n/** The slice of the editor the feature reads and writes. */\nexport interface AiFeatureEditor {\n state: {\n readonly template?: { readonly id: string } | null;\n readonly selectedBlockId: string | null;\n readonly isLoading?: boolean;\n readonly isDirty?: boolean;\n readonly isSaving?: boolean;\n };\n /** Committed create/load version from core; metadata edits leave it alone. */\n loadVersion?: Readonly<Ref<number>>;\n content: Ref<TemplateContent>;\n activeLocale?: Ref<string | null>;\n selectBlock: (blockId: string | null) => void;\n markDirty: () => void;\n}\n\nexport interface UseAiFeatureOptions {\n provider: AiProvider;\n editor: AiFeatureEditor;\n collaboration: Pick<UseCollaborationFeatureReturn, \"core\" | \"outline\"> | null;\n /** The snapshot history; read at call time (core is built after this). */\n history: () => Pick<UseHistoryReturn, \"record\">;\n /** Reload after a server-applied turn; check the guard before committing. */\n reload:\n | ((templateId: string, shouldApply?: () => boolean) => Promise<unknown>)\n | null;\n mergeTags: () => AiMergeTags;\n /** Bare merge tags to tags, as for remote batches (D8). */\n normalize: (\n ops: readonly Operation[],\n content: TemplateContent,\n ) => Operation[];\n /** The comments panel's state: AI panels and comments are exclusive (D18). */\n commentsOpen: Ref<boolean> | null;\n localization?: { locales: string[] };\n customBlockDefinitions?: () => readonly CustomBlockDefinition[];\n onStructureChange?: () => void;\n altMaxLength?: () => number;\n onError?: (error: Error) => void;\n}\n\ninterface TurnRecord {\n /** Undoes the turn: each batch's inverse, the last batch's first. */\n inverse: Operation[];\n /** Redoes it after an Undo: the inverse of the Undo batch. */\n redo: Operation[] | null;\n serverApplied: boolean;\n batchIds: Set<string>;\n /**\n * Under collaboration, the content the turn's last batch, or its last Undo\n * or Redo, left; `null` once another change landed between its batches. A\n * whole-template snapshot in the inverse applies only on exactly this\n * content, so it can't overwrite an edit made since, including another\n * session's edit that a refusal of the turn kept.\n */\n view?: TemplateContent | null;\n}\n\n/** The current content, for a turn record's `view`. */\nfunction snapshotOf(content: TemplateContent): TemplateContent {\n return safeClone(toRaw(content));\n}\n\ninterface Memory {\n generation: number;\n items: AiChatItem[];\n records: Map<string, TurnRecord>;\n storedIds: Set<string>;\n recoveries: Map<\n string,\n { item: AiChatItem; user?: AiChatItem; record: TurnRecord }\n >;\n}\n\nconst isAbort = (error: unknown): boolean =>\n error instanceof Error && error.name === \"AbortError\";\nfunction asError(error: unknown): Error {\n if (error instanceof Error) return error;\n if (typeof error !== \"object\" || error === null)\n return new Error(String(error));\n const shaped = error as {\n message?: unknown;\n code?: unknown;\n statusCode?: unknown;\n details?: unknown;\n };\n return Object.assign(\n new Error(\n typeof shaped.message === \"string\" ? shaped.message : String(error),\n ),\n typeof shaped.code === \"string\" ? { code: shaped.code } : {},\n typeof shaped.statusCode === \"number\"\n ? { statusCode: shaped.statusCode }\n : {},\n shaped.details === undefined ? {} : { details: shaped.details },\n );\n}\nconst sum = (message: AiChatMessage) =>\n message.batches.reduce((total, batch) => total + batch.operationCount, 0);\n\nfunction hasBlock(blocks: readonly Block[], blockId: string): boolean {\n return blocks.some(\n (block) =>\n block.id === blockId ||\n (block.type === \"section\" &&\n Array.isArray((block as { children?: unknown }).children) &&\n (block as unknown as { children: Block[][] }).children.some(\n (column) => Array.isArray(column) && hasBlock(column, blockId),\n )),\n );\n}\n\nfunction refusalOf(error: OperationError): AiOperationsResult {\n return {\n applied: false,\n code: error.code,\n opIndex: error.opIndex,\n message: error.message,\n };\n}\n\nexport interface UseAiFeatureReturn {\n capability: NonNullable<EditorCapabilities[\"ai\"]>;\n panel: Ref<AiPanel | null>;\n open: (panel: AiPanel) => void;\n close: () => void;\n has: (feature: AiFeatureName) => boolean;\n /** The loaded template's id: AI works on it, and panels reset when it changes. */\n templateId: ComputedRef<string | null>;\n /** Changes on every committed load, including same-id reloads. */\n templateSession: ComputedRef<number | string | null>;\n /** Opaque identity; AI reconciliation keeps it, external committed loads replace it. */\n sessionIdentity: ComputedRef<object | null>;\n isAvailable: ComputedRef<boolean>;\n hasConversation: boolean;\n canClear: boolean;\n messages: Ref<AiChatItem[]>;\n isLoadingHistory: Ref<boolean>;\n /** True while any AI operation owns the serialized lane. */\n busy: Ref<boolean>;\n /** Alias of busy, retained for existing panels. */\n isRunning: Ref<boolean>;\n failure: Ref<AiFailure | null>;\n keptYourVersion: Ref<boolean>;\n reloadTemplate: () => Promise<void>;\n failedPrompt: Ref<string | null>;\n failedAttachments: Ref<File[]>;\n importQueue: Ref<File[]>;\n isTemplateEmpty: ComputedRef<boolean>;\n send: (message: string, attachments?: File[]) => Promise<AiTurnOutcome>;\n startImport: (files: File[]) => void;\n fix: (finding: AiFixFinding) => Promise<AiTurnOutcome>;\n stop: () => void;\n newChat: () => Promise<void>;\n undoMessage: (id: string) => Promise<void>;\n redoMessage: (id: string) => Promise<void>;\n rewrite: (\n input: Pick<\n AiRewriteRequest,\n \"html\" | \"preset\" | \"language\" | \"instruction\"\n >,\n onText: (text: string) => void,\n signal: AbortSignal,\n ) => Promise<{ html: string }>;\n draftAltText: (blockId: string, signal?: AbortSignal) => Promise<string>;\n applyAltTexts: (\n entries: Array<{\n blockId: string;\n alt: string;\n decorative: boolean;\n expect?: AiImageSnapshot;\n }>,\n ) => Promise<void>;\n destroy: () => void;\n}\n\n/**\n * The editor's side of `init({ ai })` (A1 §3): the capability its entry points\n * read, the request each call carries, the edits a turn hands over (applied\n * through the collaboration controller or through the engine and the snapshot\n * history, one undo step per turn), server-applied batches followed or\n * reloaded, the chat in `conversation` or in memory, and every failure to\n * `onError`. Built before `useEditorCore`; reads core through getters.\n */\nexport function useAiFeature(options: UseAiFeatureOptions): UseAiFeatureReturn {\n const { provider, editor, collaboration } = options;\n const conversation = provider.conversation ?? null;\n const localSessionId = crypto.randomUUID();\n\n const panel = ref<AiPanel | null>(null);\n const memory = new Map<string, Memory>();\n let destroyed = false;\n let authorVersion = 0;\n let applyingAi = false;\n let pendingJobs = 0;\n let stopAuthorWatch: (() => void) | null = null;\n // Watchers made later (from `enqueue` and a job's end) belong to this\n // composable, not to whichever component's setup queued the job.\n const ownerScope = getCurrentScope();\n type LaneKind =\n \"turn\" | \"replay\" | \"clear\" | \"history\" | \"read\" | \"reconcile\";\n interface Session {\n id: string;\n memory: Memory;\n generation: number;\n messages: Ref<AiChatItem[]>;\n isLoadingHistory: Ref<boolean>;\n busy: Ref<boolean>;\n keptYourVersion: Ref<boolean>;\n failure: Ref<AiFailure | null>;\n failedPrompt: Ref<string | null>;\n failedAttachments: Ref<File[]>;\n importQueue: Ref<File[]>;\n loaded: boolean;\n historyGeneration: number;\n pendingHistory: { generation: number; promise: Promise<void> } | null;\n active: Job | null;\n queue: Job[];\n lifetime: AbortController;\n committingReload: boolean;\n lastRecordedTurn: string | null;\n timers: Set<ReturnType<typeof setTimeout>>;\n highlights: Ref<ReadonlyMap<string, number>>;\n highlightSequence: number;\n }\n interface Job {\n kind: LaneKind;\n scope: Session;\n controller: AbortController;\n authorVersion: number;\n execute: () => Promise<void>;\n }\n\n function createSession(id: string): Session {\n const saved = memoryFor(id);\n return {\n id,\n memory: saved,\n generation: ++saved.generation,\n messages: ref(saved.items),\n isLoadingHistory: ref(false),\n busy: ref(false),\n keptYourVersion: ref(false),\n failure: ref(null),\n failedPrompt: ref(null),\n failedAttachments: shallowRef([]),\n importQueue: shallowRef([]),\n loaded: false,\n historyGeneration: 0,\n pendingHistory: null,\n active: null,\n queue: [],\n lifetime: new AbortController(),\n committingReload: false,\n lastRecordedTurn: null,\n timers: new Set(),\n highlights: shallowRef(new Map()),\n highlightSequence: 0,\n };\n }\n\n const templateId = computed(() => editor.state.template?.id ?? null);\n const currentSession = shallowRef<Session | null>(\n templateId.value === null ? null : createSession(templateId.value),\n );\n const isAvailable = computed(\n () =>\n currentSession.value !== null && !destroyed && templateId.value !== null,\n );\n let localeVersion = 0;\n const stopLocaleWatch = editor.activeLocale\n ? watch(\n editor.activeLocale,\n () => {\n localeVersion++;\n },\n { flush: \"sync\" },\n )\n : () => {};\n function checkLocale(version: number): void {\n if (version !== localeVersion)\n throw new DOMException(\"The language changed.\", \"AbortError\");\n }\n const has = (feature: AiFeatureName): boolean =>\n feature === \"chatAttachments\"\n ? isAvailable.value &&\n provider.chatAttachments === true &&\n typeof provider.chat === \"function\"\n : typeof provider[feature] === \"function\";\n const scopeOf = (): Session | null =>\n destroyed ? null : currentSession.value;\n const isCurrent = (scope: Session): boolean =>\n !destroyed &&\n currentSession.value === scope &&\n !scope.lifetime.signal.aborted &&\n templateId.value === scope.id;\n\n // Stable public refs follow the current session, never an obsolete job's refs.\n function sessionRef<T>(select: (scope: Session) => Ref<T>, empty: T): Ref<T> {\n return computed({\n get: () =>\n currentSession.value ? select(currentSession.value).value : empty,\n set: (value) => {\n const scope = scopeOf();\n if (scope) select(scope).value = value;\n },\n });\n }\n const messages = sessionRef((scope) => scope.messages, []);\n const isTemplateEmpty = computed(\n () => editor.content.value.blocks.length === 0,\n );\n const isLoadingHistory = sessionRef((scope) => scope.isLoadingHistory, false);\n const isRunning = sessionRef((scope) => scope.busy, false);\n const failure = sessionRef((scope) => scope.failure, null);\n const keptYourVersion = sessionRef((scope) => scope.keptYourVersion, false);\n const failedPrompt = sessionRef((scope) => scope.failedPrompt, null);\n const failedAttachments = sessionRef((scope) => scope.failedAttachments, []);\n const importQueue = sessionRef((scope) => scope.importQueue, []);\n\n function invalidateHistory(scope: Session): void {\n scope.historyGeneration++;\n scope.pendingHistory = null;\n scope.loaded = false;\n scope.isLoadingHistory.value = false;\n }\n\n function enqueue<T>(\n kind: LaneKind,\n scope: Session,\n run: (job: Job) => Promise<T>,\n skipped: () => T | Promise<T>,\n ): Promise<T> {\n if (!isCurrent(scope)) return Promise.resolve().then(skipped);\n return new Promise<T>((resolve, reject) => {\n const job: Job = {\n kind,\n scope,\n controller: new AbortController(),\n authorVersion: 0,\n execute: async () => {\n job.authorVersion = authorVersion;\n let result: T;\n try {\n result = await (job.controller.signal.aborted || !isCurrent(scope)\n ? skipped()\n : run(job));\n } catch (error) {\n reject(error);\n return;\n } finally {\n scope.active = null;\n scope.busy.value = false;\n if (--pendingJobs === 0) watchAuthorEdits();\n pump(scope);\n }\n resolve(result);\n },\n };\n scope.queue.push(job);\n if (pendingJobs++ === 0) watchAuthorEdits();\n pump(scope);\n });\n }\n\n function pump(scope: Session): void {\n if (scope.active) return;\n const job = scope.queue.shift();\n if (!job) return;\n scope.active = job;\n // Abandoned queues drain their skipped results without reviving busy state.\n if (isCurrent(scope)) scope.busy.value = true;\n void job.execute();\n }\n\n function check(job: Job): void {\n job.controller.signal.throwIfAborted();\n if (!isCurrent(job.scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n }\n\n async function abortable<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n ): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n const stopped = new Promise<never>((_, reject) => {\n abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n });\n try {\n return await Promise.race([promise, stopped]);\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n }\n\n async function reloadCurrent(\n job: Job,\n recoverStopped = false,\n expectedAuthorVersion = job.authorVersion,\n ): Promise<void> {\n const { scope } = job;\n const valid = () =>\n scope.active === job &&\n isCurrent(scope) &&\n (recoverStopped || !job.controller.signal.aborted);\n const canKeepReload = () => {\n if (!valid()) return false;\n if (expectedAuthorVersion !== authorVersion) {\n scope.keptYourVersion.value = true;\n return false;\n }\n return true;\n };\n if (!options.reload || !canKeepReload()) return;\n try {\n await abortable(\n options.reload(scope.id, () => {\n if (!canKeepReload()) return false;\n scope.keptYourVersion.value = false;\n scope.committingReload = true;\n return true;\n }),\n scope.lifetime.signal,\n );\n } finally {\n scope.committingReload = false;\n }\n }\n\n function memoryFor(id: string): Memory {\n let found = memory.get(id);\n if (!found) {\n found = {\n generation: 0,\n items: [],\n records: new Map(),\n storedIds: new Set(),\n recoveries: new Map(),\n };\n memory.set(id, found);\n }\n return found;\n }\n\n function later(scope: Session, run: () => void, ms: number): void {\n const timer = setTimeout(() => {\n scope.timers.delete(timer);\n run();\n }, ms);\n scope.timers.add(timer);\n }\n\n function report(error: unknown): void {\n if (!isAbort(error)) options.onError?.(asError(error));\n }\n\n // --- The asker's outline (D42) ---------------------------------------------\n\n function outline(scope: Session, blockIds: readonly string[]): void {\n if (blockIds.length === 0) return;\n if (collaboration) {\n collaboration.outline(blockIds);\n return;\n }\n const sequence = ++scope.highlightSequence;\n const next = new Map(scope.highlights.value);\n for (const id of blockIds) next.set(id, sequence);\n scope.highlights.value = next;\n later(\n scope,\n () => {\n const rest = new Map(scope.highlights.value);\n for (const id of blockIds)\n if (rest.get(id) === sequence) rest.delete(id);\n scope.highlights.value = rest;\n },\n AGENT_HIGHLIGHT_MS,\n );\n }\n\n // --- Requests (D12) --------------------------------------------------------\n\n async function settle(scope: Session): Promise<void> {\n if (!collaboration) return;\n await Promise.race([\n collaboration.core.settle().catch(() => {}),\n new Promise<void>((resolve) =>\n later(scope, resolve, AI_SETTLE_TIMEOUT_MS),\n ),\n ]);\n }\n\n function requestBase(id: string): AiRequestBase {\n const raw = toRaw(editor.content.value);\n const locale = editor.activeLocale?.value ?? null;\n const content = resolveLocale(raw, locale ?? defaultLocaleOf(raw));\n // Projection supplies an implicit English locale; older templates keep\n // their original settings shape at the AI boundary (LD11).\n if (locale === null && raw.settings.locale === undefined)\n delete (content.settings as Partial<TemplateContent[\"settings\"]>).locale;\n if (\n new TextEncoder().encode(JSON.stringify(content)).length >\n AI_CONTENT_MAX_BYTES\n )\n throw new SdkError(\n \"This template is too large for AI.\",\n 413,\n \"content_too_large\",\n );\n return {\n templateId: id,\n locale,\n content,\n revision: collaboration ? collaboration.core.revision.value : null,\n sessionId: collaboration ? collaboration.core.sessionId : localSessionId,\n mergeTags: options.mergeTags(),\n };\n }\n\n function selectedBlockId(): string | null {\n const id = editor.state.selectedBlockId;\n if (!id) return null;\n if (collaboration)\n return collaboration.core.hasConfirmedBlock(id) ? id : null;\n return hasBlock(editor.content.value.blocks, id) ? id : null;\n }\n\n // --- Applying edits (D6, D7, D8) ---------------------------------------------\n\n function applySharedOps(\n ops: Operation[],\n turn: string,\n scope: Session,\n ): AiOperationsResult {\n if (ops.length === 0) return { applied: true, inverse: [] };\n let normalized: Operation[];\n try {\n normalized = options.normalize(ops, toRaw(editor.content.value));\n } catch (error) {\n if (error instanceof OperationError) return refusalOf(error);\n throw error;\n }\n if (normalized.length === 0) return { applied: true, inverse: [] };\n const summary = summarizeAgentEdit(normalized);\n if (collaboration) {\n const result = collaboration.core.applyOperations(normalized, {\n origin: \"ai\",\n turn,\n });\n if (!result.applied) return refusalOf(result.error);\n if (!summary.templateUpdated) outline(scope, summary.blockIds);\n return { applied: true, inverse: result.inverse };\n }\n let inverse: Operation[];\n try {\n // Also the check: it throws the engine's refusal for ops that don't apply.\n inverse = invertOperations(toRaw(editor.content.value), normalized);\n } catch (error) {\n if (error instanceof OperationError) return refusalOf(error);\n throw error;\n }\n if (scope.lastRecordedTurn !== turn) {\n options.history().record();\n scope.lastRecordedTurn = turn;\n }\n applyingAi = true;\n try {\n applyOperationsInPlace(editor.content.value, safeClone(normalized));\n editor.markDirty();\n } finally {\n applyingAi = false;\n }\n const selected = editor.state.selectedBlockId;\n if (selected && !hasBlock(editor.content.value.blocks, selected)) {\n editor.selectBlock(null);\n }\n if (!summary.templateUpdated) outline(scope, summary.blockIds);\n return { applied: true, inverse };\n }\n\n function applyModelOps(\n ops: Operation[],\n turn: string,\n scope: Session,\n locale: string | null,\n ): AiOperationsResult {\n let mapped = ops;\n try {\n if (locale !== null) {\n if (\n options.localization &&\n !options.localization.locales.includes(locale)\n )\n throw new OperationError(\n \"invalid_operation\",\n 0,\n `Locale \"${locale}\" is not enabled.`,\n );\n mapped = mapLocalizedOperations(\n toRaw(editor.content.value),\n locale,\n ops,\n options.customBlockDefinitions?.(),\n );\n }\n } catch (error) {\n if (error instanceof OperationError) return refusalOf(error);\n throw error;\n }\n const result = applySharedOps(mapped, turn, scope);\n if (\n result.applied &&\n result.inverse.length > 0 &&\n locale !== null &&\n mapped.some((op) =>\n [\"addBlock\", \"moveBlock\", \"deleteBlock\", \"updateBlock\"].includes(op.op),\n )\n )\n options.onStructureChange?.();\n return result;\n }\n\n function followRevision(revision: number, scope: Session): void {\n if (!collaboration || !isCurrent(scope)) return;\n const core = collaboration.core;\n if (core.revision.value >= revision) return;\n if (core.connection.value !== \"connected\") {\n void core.catchUp();\n return;\n }\n later(\n scope,\n () => {\n if (isCurrent(scope) && core.revision.value < revision)\n void core.catchUp();\n },\n AI_BROADCAST_GRACE_MS,\n );\n }\n\n // --- Turns (D15, D16) --------------------------------------------------------\n\n function patch(\n scope: Session,\n key: string,\n changes: Partial<AiChatItem>,\n ): void {\n const saved = scope.memory;\n saved.items = saved.items.map((item) => {\n if (item.id !== key) return item;\n const next = { ...item, ...changes };\n return { ...next, ...replayAvailability(next, saved) };\n });\n for (const recovery of saved.recoveries.values()) {\n if (recovery.item.id === key) {\n recovery.item =\n saved.items.find((item) => item.id === (changes.id ?? key)) ??\n recovery.item;\n }\n }\n scope.messages.value = saved.items;\n }\n\n function replayAvailability(\n item: AiChatItem,\n saved: Memory,\n ): Pick<AiChatItem, \"canUndo\" | \"canRedo\"> {\n const eligible = item.role === \"assistant\" && item.operationCount > 0;\n if (saved.storedIds.has(item.id)) {\n return {\n canUndo:\n eligible && !item.undone && typeof conversation?.undo === \"function\",\n canRedo:\n eligible && item.undone && typeof conversation?.redo === \"function\",\n };\n }\n const record = saved.records.get(item.id);\n return {\n canUndo:\n eligible &&\n !item.undone &&\n !record?.serverApplied &&\n (record?.inverse.length ?? 0) > 0,\n canRedo:\n eligible &&\n item.undone &&\n !record?.serverApplied &&\n (record?.redo?.length ?? 0) > 0,\n };\n }\n\n const emptyOutcome = (): AiTurnOutcome => ({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n\n function runTurn(\n kind: AiMessageKind,\n userText: string,\n call: (\n base: AiRequestBase,\n handlers: AiTurnHandlers,\n signal: AbortSignal,\n ) => Promise<AiTurnResult>,\n attachments: File[] = [],\n ): Promise<AiTurnOutcome> {\n const startingLocale = localeVersion;\n const locale = editor.activeLocale?.value ?? null;\n const scope = scopeOf();\n if (\n !scope ||\n scope.active?.kind === \"turn\" ||\n scope.queue.some((job) => job.kind === \"turn\")\n )\n return Promise.resolve(emptyOutcome());\n return enqueue(\n \"turn\",\n scope,\n async (job) => {\n const { controller } = job;\n const saved = scope.memory;\n const turn = crypto.randomUUID();\n const userKey = crypto.randomUUID();\n let key: string = crypto.randomUUID();\n let operationCount = 0;\n let text = \"\";\n let interrupted = false;\n let refusal: SdkError | null = null;\n const record: TurnRecord = {\n inverse: [],\n redo: null,\n serverApplied: false,\n batchIds: new Set(),\n };\n let outcome: AiTurnOutcome;\n let completed = false;\n let reconciling = false;\n const update = (changes: Partial<AiChatItem>) =>\n patch(scope, key, changes);\n const rememberRecovery = () => {\n const item = saved.items.find((item) => item.id === key);\n if (conversation && item)\n saved.recoveries.set(turn, {\n item,\n user: saved.items.find((item) => item.id === userKey),\n record,\n });\n };\n const reconcileLateApplied = () => {\n if (\n reconciling ||\n (!conversation && (collaboration || !options.reload))\n )\n return;\n reconciling = true;\n // Stop cancels provider work immediately. Received server facts still\n // enter the lane and reload only the session that requested the turn.\n void enqueue(\n \"reconcile\",\n scope,\n async (recovery) => {\n try {\n let observed: number;\n do {\n observed = operationCount;\n if (!collaboration && options.reload)\n await reloadCurrent(recovery, true, job.authorVersion);\n if (conversation) await readHistory(recovery, true, true);\n } while (isCurrent(scope) && observed !== operationCount);\n } catch (error) {\n if (isCurrent(scope)) report(error);\n } finally {\n reconciling = false;\n }\n },\n () => {\n reconciling = false;\n },\n );\n };\n const handlers: AiTurnHandlers = {\n onText: (chunk) => {\n check(job);\n text += chunk;\n update({ text });\n },\n onOperations: async (ops) => {\n check(job);\n checkLocale(startingLocale);\n const before = collaboration\n ? snapshotOf(editor.content.value)\n : null;\n const result = applyModelOps(ops, turn, scope, locale);\n if (result.applied && result.inverse.length > 0) {\n record.inverse = [...result.inverse, ...record.inverse];\n if (collaboration)\n record.view =\n record.view === undefined ||\n (record.view !== null && deepEqual(record.view, before))\n ? snapshotOf(editor.content.value)\n : null;\n operationCount += ops.length;\n update({ operationCount });\n }\n return result;\n },\n onApplied: (batch) => {\n // An applied batch is a fact, including one received during Stop.\n if (!isCurrent(scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n if (!collaboration && !options.reload) {\n refusal ??= new SdkError(\n AI_MISSING_PROVIDER_MESSAGE,\n 502,\n \"ai_provider_error\",\n );\n throw refusal;\n }\n record.serverApplied = true;\n record.batchIds.add(batch.batchId);\n operationCount += batch.operationCount;\n update({ operationCount });\n followRevision(batch.revision, scope);\n if (completed) {\n rememberRecovery();\n reconcileLateApplied();\n }\n },\n };\n try {\n try {\n await readHistory(job);\n check(job);\n checkLocale(startingLocale);\n scope.failure.value = null;\n scope.failedPrompt.value = null;\n scope.failedAttachments.value = [];\n const now = new Date().toISOString();\n saved.records.set(key, record);\n saved.items = [\n ...saved.items,\n {\n id: userKey,\n role: \"user\",\n kind,\n locale,\n text: userText,\n attachments: attachments.map((file) => ({\n name: file.name,\n kind: file.type === \"application/pdf\" ? \"pdf\" : \"image\",\n })),\n operationCount: 0,\n undone: false,\n canUndo: false,\n canRedo: false,\n createdAt: now,\n status: \"done\",\n },\n {\n id: key,\n role: \"assistant\",\n kind,\n locale,\n text: \"\",\n attachments: [],\n operationCount: 0,\n undone: false,\n canUndo: false,\n canRedo: false,\n createdAt: now,\n status: \"streaming\",\n },\n ];\n scope.messages.value = saved.items;\n await abortable(settle(scope), job.controller.signal);\n check(job);\n checkLocale(startingLocale);\n const result = await abortable(\n call(requestBase(scope.id), handlers, controller.signal),\n controller.signal,\n );\n check(job);\n if (refusal) throw refusal;\n if (result.text !== \"\") text = result.text;\n if (result.messageId !== null && conversation) {\n const previousKey = key;\n key = result.messageId;\n saved.storedIds.add(key);\n saved.records.delete(previousKey);\n saved.records.set(key, record);\n patch(scope, previousKey, { id: key });\n }\n update({ text, status: \"done\" });\n outcome = { messageId: key, operationCount, text, failed: false };\n } catch (caught) {\n const error = refusal ?? caught;\n interrupted = controller.signal.aborted || isAbort(error);\n if (!interrupted) report(error);\n if (operationCount === 0 && (!interrupted || text === \"\")) {\n saved.items = saved.items.filter(\n (item) => item.id !== key && item.id !== userKey,\n );\n if (isCurrent(scope)) {\n scope.messages.value = saved.items;\n if (!interrupted) {\n if (kind === \"chat\") {\n scope.failedPrompt.value = userText;\n scope.failedAttachments.value = attachments;\n }\n scope.failure.value = {\n error: asError(error),\n context: \"turn\",\n };\n }\n }\n outcome = {\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: !interrupted,\n };\n } else {\n update({\n status: interrupted ? \"done\" : \"failed\",\n failure: interrupted\n ? undefined\n : { error: asError(error), context: \"turn\" },\n });\n outcome = {\n messageId: key,\n operationCount,\n text,\n failed: !interrupted,\n };\n }\n }\n\n // Recovery belongs to the turn, even after Stop. Switching templates\n // still discards it; a user Stop retains the changes already applied.\n if (\n conversation &&\n outcome.messageId !== null &&\n operationCount > 0 &&\n (outcome.failed || interrupted)\n ) {\n rememberRecovery();\n }\n let observed: number;\n do {\n observed = operationCount;\n if (\n record.serverApplied &&\n !collaboration &&\n options.reload &&\n isCurrent(scope)\n ) {\n await reloadCurrent(job, true).catch((error) => {\n if (isCurrent(scope)) report(error);\n });\n }\n if (\n conversation &&\n saved.recoveries.has(turn) &&\n isCurrent(scope)\n ) {\n await readHistory(job, true, true);\n const recovered = saved.recoveries.get(turn);\n if (recovered) {\n outcome.messageId = recovered.item.id;\n outcome.text = recovered.item.text;\n }\n }\n } while (\n isCurrent(scope) &&\n record.serverApplied &&\n observed !== operationCount\n );\n outcome.operationCount = operationCount;\n // Stop may arrive during the final reload, after the provider-call\n // catch. Applied edits and recovery remain, but the turn did not finish.\n if (interrupted || controller.signal.aborted) outcome.failed = true;\n return outcome;\n } finally {\n completed = true;\n scope.messages.value = saved.items;\n }\n },\n emptyOutcome,\n );\n }\n\n // --- Undo and Redo of a message (D13, D14) ------------------------------------\n\n function replay(id: string, direction: \"undo\" | \"redo\"): Promise<void> {\n const scope = scopeOf();\n if (!scope || scope.busy.value) return Promise.resolve();\n return enqueue(\n \"replay\",\n scope,\n async (job) => {\n const saved = scope.memory;\n const item = saved.items.find((item) => item.id === id);\n if (!item) return;\n const remote = conversation?.[direction];\n const record = saved.records.get(id);\n try {\n check(job);\n if (saved.storedIds.has(id)) {\n if (typeof remote !== \"function\") {\n throw new SdkError(\n `This AI backend does not support ${direction}.`,\n 403,\n \"feature_unavailable\",\n );\n }\n if (item.undone !== (direction === \"redo\")) return;\n const answer = await abortable(\n remote(scope.id, id, {\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n }),\n scope.lifetime.signal,\n );\n if (!isCurrent(scope)) return;\n if (\"operations\" in answer) {\n if (job.controller.signal.aborted) return;\n const result = applyModelOps(\n answer.operations,\n `${direction}:${id}:${crypto.randomUUID()}`,\n scope,\n item.locale ?? null,\n );\n if (result.applied) {\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n }\n try {\n await abortable(\n conversation!.settleReplay(scope.id, id, {\n replayId: answer.replayId,\n direction,\n applied: result.applied,\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n }),\n scope.lifetime.signal,\n );\n } catch (error) {\n if (!isCurrent(scope)) return;\n report(error);\n patch(scope, id, {\n failure: { error: asError(error), context: direction },\n });\n }\n if (!isCurrent(scope)) return;\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n return;\n } else {\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n if (collaboration) followRevision(answer.applied.revision, scope);\n else if (options.reload) await reloadCurrent(job, true);\n else\n throw new SdkError(\n AI_MISSING_PROVIDER_MESSAGE,\n 502,\n \"ai_provider_error\",\n );\n return;\n }\n } else {\n if (item.undone !== (direction === \"redo\")) return;\n const ops = direction === \"undo\" ? record?.inverse : record?.redo;\n if (!record || record.serverApplied || !ops || ops.length === 0)\n return;\n // A snapshot carries no guard of its own: it applies only on the\n // content the turn (or its last replay) left.\n if (\n collaboration &&\n ops.some((op) => op.op === \"setContent\") &&\n (!record.view ||\n !deepEqual(record.view, toRaw(editor.content.value)))\n )\n throw new CollaborationConflict(\n `The template changed since this message's changes, so ${direction === \"undo\" ? \"undoing\" : \"redoing\"} them would overwrite that.`,\n { code: \"precondition_failed\" },\n );\n const result = applySharedOps(\n ops,\n `${direction}:${id}:${crypto.randomUUID()}`,\n scope,\n );\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n if (direction === \"undo\") record.redo = result.inverse;\n else record.inverse = result.inverse;\n if (collaboration) record.view = snapshotOf(editor.content.value);\n }\n patch(scope, id, {\n undone: direction === \"undo\",\n failure: undefined,\n });\n } catch (error) {\n if (!isCurrent(scope) || isAbort(error)) return;\n report(error);\n patch(scope, id, {\n failure: { error: asError(error), context: direction },\n });\n }\n },\n () => {},\n );\n }\n\n // --- History (D14) -----------------------------------------------------------\n\n function toItem(message: AiChatMessage, saved: Memory): AiChatItem {\n const item: AiChatItem = {\n id: message.id,\n role: message.role,\n kind: message.kind,\n locale: message.locale,\n text: message.text,\n attachments: message.attachments ?? [],\n operationCount: sum(message),\n undone: message.undone,\n canUndo: false,\n canRedo: false,\n createdAt: message.createdAt,\n status: \"done\",\n };\n return { ...item, ...replayAvailability(item, saved) };\n }\n\n function mergeHistory(list: AiChatMessage[], saved: Memory): AiChatItem[] {\n for (const message of list) saved.storedIds.add(message.id);\n const previous = new Map(saved.items.map((item) => [item.id, item]));\n let items = list.map((message) => {\n const item = toItem(message, saved);\n const old = previous.get(item.id);\n return old?.status === \"failed\"\n ? { ...item, status: old.status, failure: old.failure }\n : item;\n });\n for (const recovery of saved.recoveries.values()) {\n const { item, record } = recovery;\n // Only persisted identity can associate a local failure with a stored\n // message. Other sessions may append messages of the same kind at any time.\n const matches = list.filter(\n (message) =>\n message.role === \"assistant\" &&\n message.kind === item.kind &&\n (message.id === item.id ||\n (record.batchIds.size > 0 &&\n [...record.batchIds].every((id) =>\n message.batches.some((batch) => batch.batchId === id),\n ))),\n );\n const persisted = matches.length === 1 ? matches[0] : undefined;\n if (persisted) {\n saved.records.delete(item.id);\n saved.records.set(persisted.id, record);\n const reconciled = {\n ...toItem(persisted, saved),\n status: item.status,\n failure: item.failure,\n };\n recovery.item = reconciled;\n items = items.map((row) =>\n row.id === persisted.id ? reconciled : row,\n );\n } else {\n if (recovery.user && !items.some((row) => row.id === recovery.user!.id))\n items.push(recovery.user);\n items.push({ ...item, ...replayAvailability(item, saved) });\n }\n }\n return items;\n }\n\n async function readHistory(\n job: Job,\n force = false,\n recoverStopped = false,\n token = job.scope.historyGeneration,\n ): Promise<void> {\n const { scope } = job;\n if (\n !isCurrent(scope) ||\n token !== scope.historyGeneration ||\n (!recoverStopped && job.controller.signal.aborted)\n )\n return;\n if (!force && scope.loaded) return;\n const saved = scope.memory;\n if (!conversation) {\n scope.messages.value = saved.items;\n scope.loaded = true;\n return;\n }\n scope.isLoadingHistory.value = true;\n scope.loaded = false;\n try {\n const request = conversation.list(scope.id).then((list) => {\n if (\n destroyed ||\n saved.generation !== scope.generation ||\n token !== scope.historyGeneration ||\n (!recoverStopped &&\n (!isCurrent(scope) || job.controller.signal.aborted))\n )\n return;\n // A late recovery can reconcile remembered A, but only A's session refs\n // are published. The public refs may already belong to B or a new A.\n saved.items = mergeHistory(list, saved);\n scope.messages.value = saved.items;\n scope.loaded = true;\n if (scope.failure.value?.context === \"history\")\n scope.failure.value = null;\n });\n await abortable(\n request,\n recoverStopped ? scope.lifetime.signal : job.controller.signal,\n );\n } catch (error) {\n if (\n !isCurrent(scope) ||\n token !== scope.historyGeneration ||\n isAbort(error)\n )\n return;\n report(error);\n scope.failure.value = { error: asError(error), context: \"history\" };\n } finally {\n if (token === scope.historyGeneration)\n scope.isLoadingHistory.value = false;\n }\n }\n\n function loadConversation(scope = scopeOf()): Promise<void> {\n if (!scope || !isCurrent(scope)) return Promise.resolve();\n if (scope.pendingHistory?.generation === scope.historyGeneration)\n return scope.pendingHistory.promise;\n if (scope.loaded) return Promise.resolve();\n const token = scope.historyGeneration;\n const pending = { generation: token, promise: Promise.resolve() };\n const promise = enqueue(\n \"history\",\n scope,\n (job) => readHistory(job, false, false, token),\n () => {},\n );\n pending.promise = promise.finally(() => {\n if (scope.pendingHistory === pending) scope.pendingHistory = null;\n });\n scope.pendingHistory = pending;\n return pending.promise;\n }\n\n function newChat(): Promise<void> {\n const scope = scopeOf();\n if (\n !scope ||\n (conversation && typeof conversation.clear !== \"function\") ||\n (scope.active &&\n scope.active.kind !== \"history\" &&\n scope.active.kind !== \"read\") ||\n scope.queue.some((job) => job.kind !== \"history\" && job.kind !== \"read\")\n )\n return Promise.resolve();\n invalidateHistory(scope);\n scope.active?.controller.abort();\n return enqueue(\n \"clear\",\n scope,\n async () => {\n try {\n if (conversation && typeof conversation.clear === \"function\")\n await conversation.clear(scope.id);\n // A returning session owns a newer generation of this shared memory.\n // Its turns and replay records must survive this abandoned clear.\n if (scope.memory.generation !== scope.generation) return;\n // The backend cleared this template even if another session is current.\n memory.delete(scope.id);\n scope.memory.items = [];\n scope.memory.records.clear();\n scope.memory.storedIds.clear();\n scope.memory.recoveries.clear();\n invalidateHistory(scope);\n scope.messages.value = [];\n scope.loaded = true;\n scope.failure.value = null;\n scope.failedPrompt.value = null;\n scope.failedAttachments.value = [];\n if (isCurrent(scope)) memory.set(scope.id, scope.memory);\n } catch (error) {\n if (!isCurrent(scope)) return;\n report(error);\n scope.failure.value = { error: asError(error), context: \"history\" };\n }\n },\n () => {},\n );\n }\n\n // --- Panels (D17, D18) -------------------------------------------------------------\n\n function bootstrap(scope: Session): void {\n if (!isCurrent(scope)) return;\n void loadConversation(scope);\n }\n\n function open(next: AiPanel): void {\n const scope = scopeOf();\n if (!scope || !isCurrent(scope)) return;\n if (panel.value !== next && scope.busy.value) stop();\n panel.value = next;\n if (options.commentsOpen) options.commentsOpen.value = false;\n if (next === \"chat\") bootstrap(scope);\n }\n\n function startImport(files: File[]): void {\n if (files.length === 0 || !has(\"chatAttachments\")) return;\n importQueue.value = [...files];\n open(\"chat\");\n }\n\n function stopSession(scope: Session): void {\n scope.active?.controller.abort();\n for (const job of scope.queue) {\n if (job.kind !== \"reconcile\") job.controller.abort();\n }\n }\n\n function abandon(scope: Session): void {\n scope.lifetime.abort();\n stopSession(scope);\n scope.busy.value = false;\n scope.isLoadingHistory.value = false;\n for (const timer of scope.timers) clearTimeout(timer);\n scope.timers.clear();\n }\n\n function stop(): void {\n const scope = scopeOf();\n if (scope) stopSession(scope);\n }\n\n function close(): void {\n stop();\n panel.value = null;\n }\n\n /**\n * Content changes outside an AI application are the author's. A job\n * snapshots `authorVersion` and compares it later (`reloadCurrent`), so\n * while a job is queued or running each change is checked as it happens.\n * Between jobs every change is the author's, and the first one is enough to\n * make an earlier snapshot differ (a late-applied batch reconciles against\n * its turn's snapshot), so an idle editor walks the content at most twice.\n */\n function watchAuthorEdits(): void {\n if (destroyed) return;\n stopAuthorWatch?.();\n const idle = pendingJobs === 0;\n const create = () =>\n watch(\n editor.content,\n () => {\n if (!applyingAi && !currentSession.value?.committingReload)\n authorVersion++;\n },\n { deep: true, flush: \"sync\", once: idle },\n );\n stopAuthorWatch = ownerScope?.active ? ownerScope.run(create)! : create();\n }\n watchAuthorEdits();\n\n const watchers: (() => void)[] = [\n () => stopAuthorWatch?.(),\n watch(\n () => editor.state.isDirty,\n (dirty, previous) => {\n // Core clears dirty during save only when that successful request covers\n // the current mutation revision. A failed or superseded save stays dirty.\n if (previous === true && dirty === false && editor.state.isSaving)\n keptYourVersion.value = false;\n },\n { flush: \"sync\" },\n ),\n ];\n if (options.commentsOpen) {\n watchers.push(\n watch(options.commentsOpen, (isOpen) => {\n if (isOpen) close();\n }),\n );\n }\n\n watchers.push(\n watch(\n () => editor.loadVersion?.value ?? templateId.value,\n () => {\n if (destroyed) return;\n const previous = currentSession.value;\n if (previous?.committingReload && isCurrent(previous)) {\n previous.committingReload = false;\n return;\n }\n if (previous) abandon(previous);\n const id = templateId.value;\n const next = id === null ? null : createSession(id);\n currentSession.value = next;\n if (next && panel.value === \"chat\") bootstrap(next);\n },\n { flush: \"sync\" },\n ),\n );\n\n async function draftAltText(\n blockId: string,\n signal?: AbortSignal,\n ): Promise<string> {\n const startingLocale = localeVersion;\n const scope = scopeOf();\n const altText = provider.altText;\n const controller = new AbortController();\n const abort = () => controller.abort(signal?.reason);\n const abandonDraft = () => controller.abort();\n try {\n signal?.throwIfAborted();\n if (!scope || typeof altText !== \"function\")\n throw new SdkError(\n \"This AI feature isn't available.\",\n 403,\n \"feature_unavailable\",\n );\n const raw = toRaw(editor.content.value);\n const locale = editor.activeLocale?.value ?? null;\n const content = resolveLocale(raw, locale ?? defaultLocaleOf(raw));\n const context = aiImageContext(content, blockId);\n if (!context)\n throw new SdkError(\n \"The image is no longer available.\",\n 409,\n \"block_missing\",\n );\n signal?.addEventListener(\"abort\", abort, { once: true });\n scope.lifetime.signal.addEventListener(\"abort\", abandonDraft, {\n once: true,\n });\n const { url, ...rest } = context;\n const answer = await abortable(\n altText(\n {\n templateId: scope.id,\n sessionId: collaboration\n ? collaboration.core.sessionId\n : localSessionId,\n blockId,\n image: { url },\n ...rest,\n locale: locale ?? raw.settings.locale,\n maxLength: options.altMaxLength?.() ?? DEFAULT_ALT_MAX_LENGTH,\n },\n controller.signal,\n ),\n controller.signal,\n );\n controller.signal.throwIfAborted();\n checkLocale(startingLocale);\n if (!isCurrent(scope))\n throw new DOMException(\"The template changed.\", \"AbortError\");\n return answer.alt;\n } catch (error) {\n report(error);\n throw error;\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n scope?.lifetime.signal.removeEventListener(\"abort\", abandonDraft);\n }\n }\n\n function applyAltTexts(\n entries: Array<{\n blockId: string;\n alt: string;\n decorative: boolean;\n expect?: AiImageSnapshot;\n }>,\n ): Promise<void> {\n const startingLocale = localeVersion;\n const scope = scopeOf();\n if (!scope || entries.length === 0) return Promise.resolve();\n const locale = editor.activeLocale?.value ?? null;\n const raw = toRaw(editor.content.value);\n const content = resolveLocale(raw, locale ?? defaultLocaleOf(raw));\n const ops: Operation[] = entries.map(\n ({ blockId, alt, decorative, expect }) => ({\n op: \"updateBlock\",\n blockId,\n expect: {\n ...(expect ??\n aiImageSnapshot(content, blockId) ?? {\n src: null,\n alt: null,\n decorative: null,\n }),\n },\n set: { alt, decorative },\n }),\n );\n return enqueue(\n \"replay\",\n scope,\n async (job) => {\n try {\n check(job);\n checkLocale(startingLocale);\n const turn = crypto.randomUUID();\n for (let start = 0; start < ops.length; start += 100) {\n check(job);\n const result = applyModelOps(\n ops.slice(start, start + 100),\n turn,\n scope,\n locale,\n );\n if (!result.applied)\n throw new CollaborationConflict(result.message, {\n code: result.code,\n opIndex: result.opIndex,\n });\n }\n } catch (error) {\n report(error);\n throw error;\n }\n },\n () => {},\n );\n }\n\n // --- The features ------------------------------------------------------------------\n\n return {\n capability: {\n isFeatureEnabled: (feature) => isAvailable.value && has(feature),\n open,\n startImport,\n highlightOf: (blockId) =>\n currentSession.value?.highlights.value.get(blockId) ?? null,\n },\n panel,\n open,\n close,\n has,\n templateId,\n sessionIdentity: computed(() => currentSession.value),\n templateSession: computed(\n () => editor.loadVersion?.value ?? templateId.value,\n ),\n isAvailable,\n hasConversation: conversation !== null,\n canClear: conversation === null || typeof conversation.clear === \"function\",\n messages,\n isLoadingHistory,\n isRunning,\n busy: isRunning,\n failure,\n keptYourVersion,\n reloadTemplate: () => {\n const scope = scopeOf();\n return scope\n ? enqueue(\n \"reconcile\",\n scope,\n (job) => reloadCurrent(job),\n () => {},\n )\n : Promise.resolve();\n },\n failedPrompt,\n failedAttachments,\n importQueue,\n startImport,\n isTemplateEmpty,\n send: (message, attachments = []) => {\n const chat = provider.chat;\n return typeof chat === \"function\"\n ? runTurn(\n \"chat\",\n message,\n (base, handlers, signal) =>\n chat(\n {\n ...base,\n message,\n selectedBlockId: selectedBlockId(),\n attachments: attachments.map((file) => ({\n file,\n name: file.name,\n kind: file.type === \"application/pdf\" ? \"pdf\" : \"image\",\n })),\n },\n handlers,\n signal,\n ),\n attachments,\n )\n : Promise.resolve({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n },\n fix: (finding) => {\n const fixFinding = provider.fixFinding;\n return typeof fixFinding === \"function\"\n ? runTurn(\"fix\", `Fix: ${finding.message}`, (base, handlers, signal) =>\n fixFinding({ ...base, finding }, handlers, signal),\n )\n : Promise.resolve({\n messageId: null,\n operationCount: 0,\n text: \"\",\n failed: true,\n });\n },\n stop,\n newChat,\n undoMessage: (id) => replay(id, \"undo\"),\n redoMessage: (id) => replay(id, \"redo\"),\n rewrite: (input, onText, signal) => {\n const startingLocale = localeVersion;\n const scope = scopeOf();\n const rewrite = provider.rewrite;\n if (!scope || typeof rewrite !== \"function\")\n return Promise.reject(new Error(\"Rewrite isn't available.\"));\n return enqueue(\n \"read\",\n scope,\n async (job) => {\n const abort = () => job.controller.abort(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n signal.throwIfAborted();\n check(job);\n checkLocale(startingLocale);\n const answer = await abortable(\n rewrite(\n { ...requestBase(scope.id), ...input },\n {\n onText: (text) => {\n check(job);\n checkLocale(startingLocale);\n onText(text);\n },\n },\n job.controller.signal,\n ),\n job.controller.signal,\n );\n checkLocale(startingLocale);\n return answer;\n } catch (error) {\n report(error);\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n },\n () => {\n throw new DOMException(\"Rewrite stopped.\", \"AbortError\");\n },\n );\n },\n draftAltText,\n applyAltTexts,\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n const scope = currentSession.value;\n if (scope) abandon(scope);\n currentSession.value = null;\n stopLocaleWatch();\n for (const unwatch of watchers) unwatch();\n watchers.length = 0;\n },\n };\n}\n","import type {\n AiMergeTag,\n AiMergeTagSyntax,\n AiMergeTags,\n MergeTag,\n SyntaxPreset,\n SyntaxPresetName,\n} from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\n\n/** The wire's caps on merge tags, in code points (S7 Y5, S8 X4). */\nexport const AI_MERGE_TAG_LIMITS = {\n tags: 500,\n value: 200,\n label: 100,\n group: 100,\n description: 200,\n} as const;\n\n/** `text` cut to `max` code points, so a surrogate pair is never split. */\nfunction truncate(text: string, max: number): string {\n const points = Array.from(text);\n return points.length > max ? points.slice(0, max).join(\"\") : text;\n}\n\n/** The built-in preset whose patterns the syntax carries, or `custom`. */\nexport function mergeTagSyntaxName(syntax: SyntaxPreset): AiMergeTagSyntax {\n for (const name of Object.keys(SYNTAX_PRESETS) as SyntaxPresetName[]) {\n const preset = SYNTAX_PRESETS[name];\n if (\n preset.value.source === syntax.value.source &&\n preset.logic.source === syntax.logic.source\n ) {\n return name;\n }\n }\n return \"custom\";\n}\n\n/**\n * The editor's merge tags as an AI request carries them, within the caps:\n * at most 500 in order; a value that is empty or over 200 code points is left\n * out (a cut value names another tag); label, group and description are cut;\n * an empty label falls back to the value; `sample` never travels. The syntax\n * travels even when no tag is declared (`tags: []`).\n */\nexport function toAiMergeTags(\n tags: readonly MergeTag[],\n syntax: SyntaxPreset,\n): AiMergeTags {\n const out: AiMergeTag[] = [];\n for (const tag of tags) {\n if (out.length === AI_MERGE_TAG_LIMITS.tags) break;\n const value = typeof tag?.value === \"string\" ? tag.value : \"\";\n if (value === \"\" || Array.from(value).length > AI_MERGE_TAG_LIMITS.value)\n continue;\n const label =\n typeof tag.label === \"string\" && tag.label !== \"\" ? tag.label : value;\n out.push({\n value,\n label: truncate(label, AI_MERGE_TAG_LIMITS.label),\n ...(typeof tag.group === \"string\" && tag.group !== \"\"\n ? { group: truncate(tag.group, AI_MERGE_TAG_LIMITS.group) }\n : {}),\n ...(typeof tag.description === \"string\" && tag.description !== \"\"\n ? {\n description: truncate(\n tag.description,\n AI_MERGE_TAG_LIMITS.description,\n ),\n }\n : {}),\n });\n }\n return { syntax: mergeTagSyntaxName(syntax), tags: out };\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport type {\n MediaAsset,\n MediaCategory,\n MediaProvider,\n MediaRequestContext,\n MediaResult,\n} from \"@templatical/types\";\nimport type { OnRequestMedia } from \"../index\";\nimport { toNaturalSize } from \"../utils/imageNaturalSize\";\n\nexport interface UseMediaFeatureOptions {\n /** Storage backend. Absent with a callback-only config (a host widget). */\n provider?: MediaProvider;\n /**\n * UI override. Wins over {@link provider} when both are set — the host\n * brought a widget, so the built-in modal never opens.\n */\n onRequestMedia?: OnRequestMedia;\n /**\n * Current template id, read at request time. Passed on `create` when a\n * template is loaded; omitted on a blank canvas. Media is not gated on it.\n */\n getTemplateId?: () => string | undefined;\n onError?: (error: Error) => void;\n}\n\nexport interface UseMediaFeatureReturn {\n /**\n * What `useEditorCore` provides as `ON_REQUEST_MEDIA_KEY`. Null when\n * neither a provider nor a callback is configured, which is what keeps\n * image fields URL-only.\n */\n requestMedia: OnRequestMedia | null;\n /**\n * What `useEditorCore` provides as `CAN_DROP_MEDIA_KEY`. True when a\n * host callback is set (it receives `files`) or when `provider.create`\n * is a function. False for a read-only library (`create: false`) so\n * the drop zone does not highlight while Browse still works.\n */\n canDrop: ComputedRef<boolean>;\n isModalOpen: Ref<boolean>;\n accept: Ref<MediaCategory[] | undefined>;\n close: () => void;\n select: (asset: MediaAsset) => void;\n templateId: ComputedRef<string | undefined>;\n onError?: (error: Error) => void;\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\n/**\n * Client pre-check for a dropped file. Matches the modal's `isAcceptedFile`:\n * omitted `maxFileSize` / `mimeTypes` are no cap; an explicit `0` or `{}`\n * is a stated floor. `accept` narrows the mime list when the drop named\n * categories (image fields pass `[\"images\"]`).\n *\n * Reads `maxFileSize` / `mimeTypes` off the provider at call time — Cloud\n * implements them as getters over plan config that arrives after setup.\n */\nfunction dropFileError(\n provider: MediaProvider,\n file: File,\n accept?: MediaCategory[],\n): Error | null {\n const maxFileSize = provider.maxFileSize ?? Number.POSITIVE_INFINITY;\n if (file.size > maxFileSize) {\n return new Error(\n `Image is too large (${file.size} bytes). Maximum allowed is ${maxFileSize} bytes.`,\n );\n }\n\n const mimeTypes = provider.mimeTypes;\n if (!mimeTypes) return null;\n\n const categories =\n accept && accept.length > 0\n ? accept\n : (Object.keys(mimeTypes) as MediaCategory[]);\n const allowed = categories.some(\n (category) => mimeTypes[category]?.includes(file.type) ?? false,\n );\n if (allowed) return null;\n\n return new Error(`Unsupported image type: ${file.type || \"unknown\"}.`);\n}\n\n/**\n * Synthesizes the function image fields inject as `ON_REQUEST_MEDIA_KEY`.\n *\n * `onRequestMedia` is the UI override (a host widget) and wins when both\n * are set. Otherwise a configured `media` provider opens the lazy library\n * modal, except on drop: a `create` function uploads the file without\n * opening, and `create: false` refuses the drop. Size/type after the\n * drop zone's `image/` filter is `MediaOptions`, read live on each drop.\n */\nexport function useMediaFeature(\n options: UseMediaFeatureOptions,\n): UseMediaFeatureReturn {\n const { provider, onRequestMedia, getTemplateId, onError } = options;\n\n const isModalOpen = ref(false);\n const accept = ref<MediaCategory[] | undefined>(undefined);\n const templateId = computed(() => getTemplateId?.());\n // Callback present ⇒ drop goes to the host widget. Otherwise only a\n // `create` function uploads; `create: false` is a read-only library.\n const canDrop = computed(\n () => !!onRequestMedia || typeof provider?.create === \"function\",\n );\n\n let pending: ((result: MediaResult | null) => void) | null = null;\n\n function settle(result: MediaResult | null): void {\n isModalOpen.value = false;\n pending?.(result);\n pending = null;\n }\n\n function select(asset: MediaAsset): void {\n settle(toMediaResult(asset));\n }\n\n function close(): void {\n settle(null);\n }\n\n onScopeDispose(() => {\n if (pending) settle(null);\n });\n\n const requestMedia: OnRequestMedia | null =\n onRequestMedia || provider\n ? async (context?: MediaRequestContext): Promise<MediaResult | null> => {\n if (onRequestMedia) {\n return onRequestMedia(context);\n }\n\n if (!provider) return null;\n\n if (context?.files?.length) {\n if (typeof provider.create !== \"function\") {\n return null;\n }\n const file = context.files[0];\n const rejected = dropFileError(provider, file, context.accept);\n if (rejected) {\n onError?.(rejected);\n return null;\n }\n const id = getTemplateId?.();\n try {\n const asset = await provider.create({\n file,\n ...(id ? { templateId: id } : {}),\n });\n try {\n provider.onCreated?.(asset);\n } catch (err) {\n onError?.(toError(err));\n }\n return toMediaResult(asset);\n } catch (err) {\n onError?.(toError(err));\n return null;\n }\n }\n\n if (pending) {\n pending(null);\n pending = null;\n }\n accept.value = context?.accept;\n isModalOpen.value = true;\n return new Promise<MediaResult | null>((resolve) => {\n pending = resolve;\n });\n }\n : null;\n\n return {\n requestMedia,\n canDrop,\n isModalOpen,\n accept,\n close,\n select,\n templateId,\n onError,\n };\n}\n\n/**\n * What an image field receives for a library asset: its URL and alt, plus the\n * file's size when the store knows both dimensions, for the image block's\n * aspect-ratio lock.\n */\nfunction toMediaResult(asset: MediaAsset): MediaResult {\n const size = toNaturalSize(asset.width, asset.height);\n return {\n url: asset.url,\n alt: asset.alt,\n ...(size ? { width: size.width, height: size.height } : {}),\n };\n}\n","import { computed, provide, ref, watch, type ComputedRef, type Ref } from \"vue\";\nimport { useSavedBlocks, type UseSavedBlocksReturn } from \"@templatical/core\";\nimport type {\n Block,\n SavedBlock,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { cloneBlock } from \"@templatical/types\";\nimport { SAVED_BLOCKS_KEY } from \"../keys\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — satisfied by OSS and Cloud alike. */\ninterface SavedBlocksEditor {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n /** Read reactively to cancel a pick session when preview mode turns on. */\n state: { previewMode: boolean };\n}\n\nexport interface UseSavedBlocksFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: SavedBlocksProvider;\n editor: SavedBlocksEditor;\n onError?: (error: Error) => void;\n /**\n * Whether the feature may be used. Read reactively, so Cloud can defer to a\n * plan entitlement that only resolves after its async config fetch. Omit for\n * always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseSavedBlocksFeatureReturn {\n headless: UseSavedBlocksReturn;\n\n // --- Pick session ---\n isPicking: ComputedRef<boolean>;\n pickedIds: Ref<Set<string>>;\n pickedCount: ComputedRef<number>;\n startPicking: (blockId: string) => void;\n togglePick: (blockId: string) => void;\n isPicked: (blockId: string) => boolean;\n confirmPicking: () => void;\n cancelPicking: () => void;\n\n // --- Dialogs ---\n isSaveDialogOpen: Ref<boolean>;\n closeSaveDialog: () => void;\n isBrowserOpen: Ref<boolean>;\n openBrowser: () => void;\n closeBrowser: () => void;\n\n /** Insert a saved block's content into the canvas, with fresh block IDs. */\n insert: (saved: SavedBlock, insertIndex: number | undefined) => void;\n /** Re-read the list from the provider (used after a successful save). */\n refresh: () => void;\n /** Capability object handed to `useEditorCore` so shared UI can light up. */\n capability: NonNullable<EditorCapabilities[\"savedBlocks\"]>;\n count: ComputedRef<number>;\n isAvailable: ComputedRef<boolean>;\n}\n\n/**\n * Shared glue for the saved-blocks feature: reactive list, the canvas pick\n * session, the insert operation, and the capability object the shared UI gates\n * on.\n *\n * Both `Editor.vue` (OSS) and `useCloudInitialization` (Cloud) call this with\n * their own provider, so the two entry points run identical logic over\n * different transports. Nothing here is auth- or plan-aware — callers decide\n * whether the feature is available *before* constructing it.\n *\n * **The pick session is deliberately local to this feature.** Choosing which\n * blocks to save happens on the canvas (the user's mental model is spatial),\n * but it does NOT touch `EditorState.selectedBlockId`: keeping it a transient\n * mode avoids a breaking core-state change, leaves Cloud's single-block\n * selection broadcast and block locking untouched, and steers clear of\n * Sortable multi-drag. Promote it to real multi-select only if a second\n * consumer needs it.\n *\n * Must be called from `setup()`: it `provide()`s the headless instance under\n * {@link SAVED_BLOCKS_KEY} for the dialogs to inject.\n */\nexport function useSavedBlocksFeature(\n options: UseSavedBlocksFeatureOptions,\n): UseSavedBlocksFeatureReturn {\n const { provider, editor } = options;\n\n const headless = useSavedBlocks({ provider, onError: options.onError });\n\n const isSaveDialogOpen = ref(false);\n const isBrowserOpen = ref(false);\n\n // --- Pick session ---\n const picking = ref(false);\n const pickedIds = ref<Set<string>>(new Set());\n const isPicking = computed(() => picking.value);\n const pickedCount = computed(() => pickedIds.value.size);\n\n function startPicking(blockId: string): void {\n // Nothing to pick *for* when the provider withheld `create` — the dialog at\n // the end of the session would have no way to persist. The bookmark action\n // is already hidden; this covers programmatic callers.\n if (!headless.canCreate.value) return;\n // Preview mode has no block chrome to pick with, and its click handlers are\n // suppressed — a session there could never be completed or cancelled.\n if (editor.state.previewMode) return;\n pickedIds.value = new Set([blockId]);\n picking.value = true;\n }\n\n function togglePick(blockId: string): void {\n if (!picking.value) return;\n const next = new Set(pickedIds.value);\n if (next.has(blockId)) {\n next.delete(blockId);\n } else {\n next.add(blockId);\n }\n pickedIds.value = next;\n }\n\n function isPicked(blockId: string): boolean {\n return pickedIds.value.has(blockId);\n }\n\n function cancelPicking(): void {\n picking.value = false;\n pickedIds.value = new Set();\n }\n\n function confirmPicking(): void {\n if (pickedCount.value === 0) return;\n // Leave pick mode but keep the set — the dialog reads it to know what it's\n // saving. `closeSaveDialog` is what clears it.\n picking.value = false;\n isSaveDialogOpen.value = true;\n // The dialog offers the categories already in use as suggestions, and those\n // are derived from the loaded list — without this they'd be empty for anyone\n // who saves without ever opening the browser, and the derived-category model\n // would drift into near-duplicates.\n refresh();\n }\n\n function closeSaveDialog(): void {\n isSaveDialogOpen.value = false;\n pickedIds.value = new Set();\n }\n\n // A session can't survive entering preview mode: the canvas stops responding\n // to selection there, so the bar would be the only way out.\n watch(\n () => editor.state.previewMode,\n (previewMode) => {\n if (previewMode && picking.value) cancelPicking();\n },\n );\n\n function openBrowser(): void {\n isBrowserOpen.value = true;\n refresh();\n }\n\n function closeBrowser(): void {\n isBrowserOpen.value = false;\n }\n\n function insert(saved: SavedBlock, insertIndex: number | undefined): void {\n for (let i = 0; i < saved.content.length; i++) {\n // cloneBlock regenerates ids (recursively for section children) so the\n // inserted copy never collides with the stored one, or with blocks\n // already on the canvas from a previous insert of the same entry.\n const cloned = cloneBlock(saved.content[i]);\n const position = insertIndex !== undefined ? insertIndex + i : undefined;\n editor.addBlock(cloned, undefined, undefined, position);\n }\n isBrowserOpen.value = false;\n }\n\n function refresh(): void {\n // Fire-and-forget: `useSavedBlocks` already routes failures to `onError`,\n // and a stale list is not worth blocking the dialog's close on.\n void headless.load().catch(() => {});\n }\n\n const count = computed(() => headless.savedBlocks.value.length);\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n\n /**\n * Nothing is fetched at mount — the list loads when the browser or the save\n * dialog opens. So a consumer's `list()` latency can neither delay the editor\n * nor shift the sidebar: the rail entry is gated purely on availability,\n * never on whether anything happens to be saved.\n *\n * True only while there is *nothing to show*, which is what makes the browser\n * skeleton appear on a first open and stay away on a reopen — the previous\n * results render immediately while the refetch lands underneath. Without that\n * distinction the empty state would read \"No saved blocks yet\" for however\n * long the request takes, which is false rather than merely unhelpful.\n *\n * The browser modal derives that condition itself from the injected composable\n * — it is the only surface that displays the list, so there is no reason to\n * widen the capability with it.\n */\n\n provide(SAVED_BLOCKS_KEY, headless);\n\n return {\n headless,\n\n isPicking,\n pickedIds,\n pickedCount,\n startPicking,\n togglePick,\n isPicked,\n confirmPicking,\n cancelPicking,\n\n isSaveDialogOpen,\n closeSaveDialog,\n isBrowserOpen,\n openBrowser,\n closeBrowser,\n\n insert,\n refresh,\n capability: {\n startPicking,\n togglePick,\n isPicked,\n isPicking,\n confirmPicking,\n cancelPicking,\n openBrowser,\n count,\n isAvailable,\n canCreate: headless.canCreate,\n canUpdate: headless.canUpdate,\n canDelete: headless.canDelete,\n },\n count,\n isAvailable,\n };\n}\n","import { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { useEventListener, useTimeoutFn } from \"@vueuse/core\";\nimport type {\n Template,\n TemplateContent,\n TemplateSaveTrigger,\n TemplatesProvider,\n} from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** How long the header shows \"Saved\" before falling back to the dirty state. */\nconst SAVED_STATUS_MS = 3000;\n\n/** Minimal slice of the editor this feature needs. */\ninterface TemplatesEditor {\n state: {\n readonly template: {\n id: string;\n name?: string;\n createdAt?: string;\n updatedAt?: string;\n } | null;\n readonly isDirty: boolean;\n readonly isSaving: boolean;\n };\n setName: (name: string) => void;\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n load: (templateId: string, shouldApply?: () => boolean) => Promise<Template>;\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n hasTemplate: () => boolean;\n}\n\n/**\n * A veto over saving, supplied by whoever configured the editor.\n *\n * The one implementation is Cloud's lint save-gate: with the server policy\n * `accessibility.blockOnError` on and error-severity issues present, a manual\n * save opens a confirmation and an autosave simply does not fire. The shape is\n * generic because the header's Save must be *routable* through a gate — without\n * that, unifying the two headers would have silently dropped `blockOnError`.\n */\nexport interface SaveGate {\n /**\n * Manual save (header button, Cmd+S). Runs the save, or defers it and raises a\n * confirmation. Resolves to whether it ran.\n */\n tryRunSave: (run: () => Promise<unknown> | unknown) => Promise<boolean>;\n /**\n * Autosave. Runs the save only when the gate would not block, and does nothing\n * at all otherwise — no prompt on a debounce timer, and no write that would\n * demote the policy to a manual-save-only speed bump.\n */\n runUnlessBlocked: (run: () => Promise<unknown> | unknown) => Promise<boolean>;\n}\n\nexport interface UseTemplatesFeatureOptions {\n /** Storage backend — consumer-supplied via `init({ templates })`. */\n provider: TemplatesProvider;\n editor: TemplatesEditor;\n /**\n * Warn on tab close while there are unsaved changes. Defaults to on; pass\n * `false` to own that guard yourself.\n */\n guardUnsavedChanges?: boolean;\n /**\n * Extra gate on top of the provider being present. Read reactively, so a\n * future adapter can defer to an entitlement that resolves after setup. Omit\n * for always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n /**\n * Optional veto over every save this feature performs. Read through a getter\n * rather than passed by value because Cloud builds its gate from\n * `core.templateLint`, which only exists after `useEditorCore()` — i.e. after\n * this composable is constructed.\n */\n getSaveGate?: () => SaveGate | null;\n}\n\nexport interface UseTemplatesFeatureReturn {\n /** Persist the loaded template. Rejects — see {@link requestSave} for UI. */\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n /** Persist the current content as a new template. Rejects on failure. */\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n /** Fetch a template. Passed straight through; saving status is untouched. */\n load: (templateId: string, shouldApply?: () => boolean) => Promise<Template>;\n /**\n * Fire-and-forget save for the header button and Cmd+S: the outcome is already\n * reported through {@link status}, so nothing is left for a caller to handle.\n * A no-op while a save is running, without a template, or when the provider\n * withheld `save`.\n */\n requestSave: (trigger?: TemplateSaveTrigger) => void;\n /**\n * The autosave path. Identical to {@link requestSave} except that a configured\n * gate is consulted with `runUnlessBlocked` instead of `tryRunSave`, so a\n * blocked autosave is skipped silently rather than raising a prompt while the\n * user is typing. The template stays dirty and the header keeps saying so.\n */\n requestAutoSave: () => void;\n /**\n * Commit an inline rename and persist it. Empty (or whitespace-only) names and\n * no-change commits are ignored, so a stray blur can neither clear the name\n * nor trigger a pointless round-trip.\n */\n rename: (name: string) => void;\n /** The loaded template's name, or `undefined` when unnamed / not loaded. */\n name: ComputedRef<string | undefined>;\n /**\n * The stored template's write time and which field it came from, or `null`\n * when the provider supplies neither timestamp.\n */\n timestamp: ComputedRef<{\n iso: string;\n kind: \"updatedAt\" | \"createdAt\";\n } | null>;\n hasTemplate: ComputedRef<boolean>;\n isSaving: ComputedRef<boolean>;\n /**\n * What the header's status indicator shows. `\"saved\"` decays back to `\"idle\"`\n * after a few seconds; `\"error\"` stays until the next attempt, since a failure\n * the user never saw is worse than a stale badge.\n */\n status: Ref<\"idle\" | \"saved\" | \"error\">;\n /** The provider's own message for the last failure. Rendered in a tooltip. */\n errorMessage: Ref<string>;\n canCreate: ComputedRef<boolean>;\n canSave: ComputedRef<boolean>;\n isAvailable: ComputedRef<boolean>;\n capability: NonNullable<EditorCapabilities[\"templates\"]>;\n}\n\n/**\n * Shared glue for the templates feature: the save-status the header renders, the\n * inline rename, the unsaved-changes guard, and the capability shared chrome\n * gates on.\n *\n * Persistence itself lives in `@templatical/core`'s `useEditor`, over the\n * consumer's {@link TemplatesProvider} — this composable owns only what is\n * *about the UI*. It is constructed exactly when a provider is configured, so\n * an editor without one downloads it but never runs it.\n */\nexport function useTemplatesFeature(\n options: UseTemplatesFeatureOptions,\n): UseTemplatesFeatureReturn {\n const { provider, editor } = options;\n\n const status = ref<\"idle\" | \"saved\" | \"error\">(\"idle\");\n const errorMessage = ref(\"\");\n\n const { start: startSavedStatusClear, stop: stopSavedStatusClear } =\n useTimeoutFn(\n () => {\n status.value = \"idle\";\n },\n SAVED_STATUS_MS,\n { immediate: false },\n );\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canSave = computed(() => typeof provider.save === \"function\");\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n\n const name = computed(() => editor.state.template?.name);\n // Prefers `updatedAt`; `createdAt` is the fallback for a store that records\n // only creation. Carries which one won, because labelling a never-updated\n // template \"Updated\" would be a claim the store never made.\n const timestamp = computed<{\n iso: string;\n kind: \"updatedAt\" | \"createdAt\";\n } | null>(() => {\n const template = editor.state.template;\n if (template?.updatedAt)\n return { iso: template.updatedAt, kind: \"updatedAt\" };\n if (template?.createdAt)\n return { iso: template.createdAt, kind: \"createdAt\" };\n return null;\n });\n const hasTemplate = computed(() => editor.state.template !== null);\n const isSaving = computed(() => editor.state.isSaving);\n\n function reportSuccess(): void {\n errorMessage.value = \"\";\n status.value = \"saved\";\n // Restart rather than stack: two saves inside the window would otherwise\n // clear the badge on the first timer, mid-way through the second's window.\n stopSavedStatusClear();\n startSavedStatusClear();\n }\n\n function reportFailure(error: unknown): void {\n stopSavedStatusClear();\n status.value = \"error\";\n errorMessage.value =\n error instanceof Error && error.message ? error.message : \"Save failed\";\n }\n\n async function save(trigger?: TemplateSaveTrigger): Promise<Template> {\n try {\n const template = await editor.save(trigger);\n reportSuccess();\n return template;\n } catch (error) {\n reportFailure(error);\n throw error;\n }\n }\n\n async function create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template> {\n try {\n const template = await editor.create(input);\n // Deliberately no \"saved\" badge. The badge acknowledges a save the user\n // asked for — an explicit `save()` or an autosave tick — and attaching a\n // template is neither. It also matched nothing: `load()` attaches without\n // announcing, so a new template flashed green where an existing one stayed\n // silent, for the same action. What a fresh template *has* is a\n // `createdAt`, which the header renders as its write time.\n //\n // The state is still reset, because a failure must not outlive the success\n // that followed it: a create that fails and is then retried would\n // otherwise leave \"Save failed\" on screen for a template that saved fine.\n stopSavedStatusClear();\n status.value = \"idle\";\n errorMessage.value = \"\";\n return template;\n } catch (error) {\n reportFailure(error);\n throw error;\n }\n }\n\n function load(\n templateId: string,\n shouldApply?: () => boolean,\n ): Promise<Template> {\n // The badge describes one template, so it cannot outlive the switch to\n // another: a save that failed seconds ago would otherwise show \"Save failed\"\n // over freshly loaded content, and a green \"Saved\" still inside its decay\n // window would claim the incoming template had just been written. Reset up\n // front rather than on success — a load that fails still means the old\n // status no longer describes what the user is looking at, and if the old\n // template stays attached with edits, `isDirty` puts \"Unsaved\" back.\n stopSavedStatusClear();\n status.value = \"idle\";\n errorMessage.value = \"\";\n // Deliberately not wrapped beyond that: a failed *load* is not a failed\n // save, and flashing \"Save failed\" for it would be a lie. Core already\n // routes it to `onError` and rejects to the caller.\n return shouldApply\n ? editor.load(templateId, shouldApply)\n : editor.load(templateId);\n }\n\n /**\n * An autosave tick that arrived while a save was in flight. `useAutoSave`'s\n * timer fires once and clears itself, and only a further content mutation\n * arms a new one — so dropping such a tick left autosave silent until the\n * user happened to type again.\n */\n let queuedAutoSave = false;\n\n /** Shared by both request paths — the outcome is reported through `status`. */\n function runSave(trigger: TemplateSaveTrigger): Promise<void> {\n return save(trigger).then(\n () => {\n if (!queuedAutoSave) return;\n queuedAutoSave = false;\n // Only what the finished save could not have covered.\n if (editor.state.isDirty) requestAutoSave();\n },\n () => {\n // Deliberately no retry on failure: the status indicator already shows\n // \"Save failed\", so autosave has not gone *silent*, and re-firing into a\n // failing endpoint would only double the traffic. The next content\n // change arms a fresh tick.\n queuedAutoSave = false;\n },\n );\n }\n\n /** True when there is nothing a save could do, whatever the gate says. */\n function cannotSave(): boolean {\n // The UI hides the button in each of these cases; this covers Cmd+S and\n // programmatic callers, where a refusal would surface as an error badge for\n // something the user never asked for.\n return !canSave.value || !hasTemplate.value || isSaving.value;\n }\n\n function requestSave(trigger: TemplateSaveTrigger = \"manual\"): void {\n if (cannotSave()) return;\n const gate = options.getSaveGate?.();\n if (gate) {\n void gate.tryRunSave(() => runSave(trigger));\n return;\n }\n void runSave(trigger);\n }\n\n function requestAutoSave(): void {\n // Split the transient condition out of `cannotSave()`: a save already in\n // flight is a \"later\", not a \"never\". Overlapping PATCHes of the whole\n // document must still never happen, so the tick is queued rather than run.\n if (!canSave.value || !hasTemplate.value) return;\n if (isSaving.value) {\n queuedAutoSave = true;\n return;\n }\n const gate = options.getSaveGate?.();\n if (gate) {\n void gate.runUnlessBlocked(() => runSave(\"autosave\"));\n return;\n }\n void runSave(\"autosave\");\n }\n\n function rename(newName: string): void {\n const trimmed = newName.trim();\n // An empty name is rejected rather than stored: the header would then have\n // nothing to render, and \"\" is far more likely a slip than an intent.\n if (!trimmed) return;\n if (trimmed === editor.state.template?.name) return;\n editor.setName(trimmed);\n requestSave(\"rename\");\n }\n\n // Tab close with unsaved work. Gated on a provider being configured — the\n // editor otherwise has no idea whether the consumer already persisted the\n // change, so it would be warning about nothing. Note this cannot cover SPA\n // route changes; `onDirtyChange` is what consumers guard their router with.\n if (options.guardUnsavedChanges !== false) {\n useEventListener(window, \"beforeunload\", (event: BeforeUnloadEvent) => {\n if (!editor.state.isDirty) return;\n event.preventDefault();\n // Some engines still show the prompt only when `returnValue` is set.\n event.returnValue = \"\";\n });\n }\n\n const capability: NonNullable<EditorCapabilities[\"templates\"]> = {\n save: requestSave,\n rename,\n name,\n timestamp,\n hasTemplate,\n isSaving,\n status,\n errorMessage,\n canCreate,\n canSave,\n isAvailable,\n };\n\n return {\n save,\n create,\n load,\n requestSave,\n requestAutoSave,\n rename,\n name,\n timestamp,\n hasTemplate,\n isSaving,\n status,\n errorMessage,\n canCreate,\n canSave,\n isAvailable,\n capability,\n };\n}\n","import type { CustomBlock, TemplateContent } from \"@templatical/types\";\nimport type { RenderFonts } from \"./renderProvider\";\n\n/**\n * Minimal slice of the editor surface needed by `toMjmlForInstance`.\n * Decoupled from the full `TemplaticalEditor` type so this helper can be\n * tested in isolation with a stub object.\n */\nexport interface ToMjmlSource {\n getContent(): TemplateContent;\n renderCustomBlock(block: CustomBlock): Promise<string>;\n /**\n * Optional. The fonts the editor is rendering with, forwarded to the renderer's\n * `customFonts` / `defaultFallbackFont`. Without it a template using a custom\n * face exports with no `<mj-font>` declaration and no fallback stack — i.e. the\n * mail client silently substitutes. Provided by both editors, and by anything\n * that has a fonts manager; a source that omits it produces byte-identical\n * MJML to one whose template uses no custom face.\n */\n getFonts?: () => RenderFonts;\n /**\n * Optional. Look up the definition-level CSS for a custom block type.\n * Returns `undefined` when the definition is unknown or has no\n * `stylesheet`. Wired to the renderer's `getCustomBlockStylesheet` option\n * so authored responsive/hover/font CSS lands in `<mj-head>` deduped per\n * definition. Omitting it is optional-by-design: the resolver is simply not\n * passed through, so no `<mj-head>` stylesheet is emitted.\n */\n getCustomBlockStylesheet?: (customType: string) => string | undefined;\n /**\n * Optional. Base URL for the social-icon PNGs, forwarded to the renderer’s\n * `socialIconsBaseUrl`. Omitting it leaves the renderer on its version-pinned\n * jsDelivr default, so output matches today’s `toMjml()` for the same template.\n */\n socialIconsBaseUrl?: string;\n /**\n * Optional. Embedder shell forwarded to the renderer's `layout` option only\n * when defined, so `toMjml()` composes and a source that omits it produces\n * today's unshelled MJML. Never written into `getContent()`.\n */\n getLayout?: () => TemplateContent | undefined;\n}\n\n/**\n * Lazy-load `@templatical/renderer` and render the editor's current content\n * to MJML, wiring the editor's own custom block resolver into the renderer's\n * `renderCustomBlock` callback.\n *\n * The renderer is an optional peer dependency (small, MIT-licensed). It is\n * only loaded when an export is actually requested. Consumers that don't\n * need MJML export at all (e.g., embedding the editor in an app where the\n * backend handles export) can omit the install entirely; calling `toMjml()`\n * in that case throws a clear error naming the missing package.\n *\n * The dynamic import is cached by the module system, so subsequent calls\n * skip the import overhead.\n */\n/**\n * Resolve `@templatical/renderer`, or `null` when it isn't installed.\n *\n * The single `import(\"@templatical/renderer\")` site in the package, so callers\n * can choose their own failure behaviour without duplicating the dynamic import\n * or matching on an error message. {@link toMjmlForInstance} throws when this\n * returns `null`; the test-email path degrades to JSON-only and warns once,\n * because there the renderer is opt-in and a missing install must not break\n * sending.\n *\n * Cheap to call repeatedly — the module system caches the import, so a second\n * call after a successful first one costs nothing.\n */\nexport async function tryLoadRenderer(): Promise<\n typeof import(\"@templatical/renderer\") | null\n> {\n try {\n return await import(\"@templatical/renderer\");\n } catch {\n return null;\n }\n}\n\nexport async function toMjmlForInstance(\n instance: ToMjmlSource,\n options?: { locale?: string },\n): Promise<string> {\n const renderer = await tryLoadRenderer();\n if (!renderer) {\n throw new Error(\n \"[Templatical] toMjml() requires the @templatical/renderer package. Please install it.\",\n );\n }\n const stylesheetResolver = instance.getCustomBlockStylesheet;\n const fonts = instance.getFonts?.();\n const layout = instance.getLayout?.();\n return renderer.renderToMjml(instance.getContent(), {\n ...(options?.locale !== undefined ? { locale: options.locale } : {}),\n renderCustomBlock: instance.renderCustomBlock,\n // Only pass through when the source actually provides a resolver, so a\n // caller that doesn't care about stylesheets sees an options shape (and MJML\n // output) with no stylesheet key at all rather than an explicit `undefined`.\n ...(stylesheetResolver\n ? {\n getCustomBlockStylesheet: (customType: string) =>\n stylesheetResolver(customType),\n }\n : {}),\n ...(fonts\n ? {\n customFonts: fonts.customFonts,\n defaultFallbackFont: fonts.defaultFallback,\n }\n : {}),\n ...(instance.socialIconsBaseUrl\n ? { socialIconsBaseUrl: instance.socialIconsBaseUrl }\n : {}),\n ...(layout ? { layout } : {}),\n });\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport type {\n TemplateContent,\n TestEmailPayload,\n TestEmailProvider,\n} from \"@templatical/types\";\nimport { logger } from \"../utils/logger\";\nimport { tryLoadRenderer } from \"../utils/toMjml\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** How long the dialog shows its success confirmation before closing itself. */\nconst SUCCESS_DISMISS_MS = 1200;\n\n/**\n * Why a send failed.\n *\n * Split by origin so the dialog knows whether it may render the text directly.\n * A provider's message is already user-presentable and is passed through\n * verbatim; an editor-generated refusal carries no text, because only the\n * component has the active locale.\n */\nexport type TestEmailError =\n { kind: \"provider\"; message: string } | { kind: \"recipientNotAllowed\" };\n\n/**\n * Turn a thrown value into an `Error`. A `catch` clause's binding is\n * `unknown` — a rejected `send` and a throwing `onSent` handler both need a\n * real `Error` to report, and both paths below share this.\n */\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nexport interface UseTestEmailFeatureOptions {\n /** Sending backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: TestEmailProvider;\n /** The template to send. Read at send time, never snapshotted. */\n getContent: () => TemplateContent;\n /**\n * Render the current template to MJML. Supplied by the entry point, which\n * already owns the `ToMjmlSource` for `editor.toMjml()`, so this composable\n * never learns about custom-block resolvers or stylesheets.\n *\n * Only ever called when the provider set `includeMjml`.\n */\n renderMjml?: () => Promise<string>;\n /**\n * Whether {@link renderMjml} reaches the bundled `@templatical/renderer`.\n * Omitted means yes, which is what a caller with no `render` provider wants.\n *\n * Gates the degradation below: a missing optional peer explains a failed\n * render only on the local path. A consumer whose backend renders has no\n * reason to install `@templatical/renderer` at all, so reading their backend's\n * error as an absent package would both swallow it and advise an install that\n * changes nothing.\n */\n usesLocalRenderer?: () => boolean;\n onError?: (error: Error) => void;\n /**\n * Extra gate on top of the provider being present — Cloud adds its plan\n * entitlement and \"template must be saved\" here. Read reactively.\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseTestEmailFeatureReturn {\n isModalOpen: Ref<boolean>;\n open: () => void;\n close: () => void;\n isSending: Ref<boolean>;\n /** True for a moment after a successful send, while the dialog confirms. */\n justSent: Ref<boolean>;\n error: Ref<TestEmailError | null>;\n send: (recipient: string) => Promise<void>;\n /**\n * The provider's allowlist, or `undefined` when unrestricted.\n *\n * A computed rather than a snapshot: Cloud exposes `allowedRecipients` as a\n * getter over a value that arrives with its JWT, so reading it once at setup\n * would freeze it at `[]` forever.\n */\n allowedRecipients: ComputedRef<string[] | undefined>;\n defaultRecipient: ComputedRef<string | undefined>;\n isAvailable: ComputedRef<boolean>;\n capability: NonNullable<EditorCapabilities[\"testEmail\"]>;\n}\n\nexport function useTestEmailFeature(\n options: UseTestEmailFeatureOptions,\n): UseTestEmailFeatureReturn {\n const { provider } = options;\n\n const isModalOpen = ref(false);\n const isSending = ref(false);\n const justSent = ref(false);\n const error = ref<TestEmailError | null>(null);\n\n let dismissTimer: ReturnType<typeof setTimeout> | null = null;\n /** One warning per editor instance, not per send — a retry shouldn't re-log. */\n let warnedAboutRenderer = false;\n\n function clearDismissTimer(): void {\n if (dismissTimer !== null) {\n clearTimeout(dismissTimer);\n dismissTimer = null;\n }\n }\n\n // The timer outlives a fast unmount otherwise, and fires into dead refs.\n onScopeDispose(clearDismissTimer);\n\n // IMPORTANT: read `provider.allowedRecipients` *inside* the computed. Cloud's\n // adapter implements it as a getter over a reactive source that starts empty\n // and fills once auth resolves — destructuring it at setup would pin it to\n // `[]`, which (see `isAvailable`) hides the trigger permanently.\n const allowedRecipients = computed(() => provider.allowedRecipients);\n\n const defaultRecipient = computed(() => {\n const preferred = provider.defaultRecipient;\n if (preferred === undefined) return undefined;\n const allowed = allowedRecipients.value;\n // A default outside the allowlist is ignored rather than smuggled in.\n if (allowed && !allowed.includes(preferred)) return undefined;\n return preferred;\n });\n\n const isAvailable = computed(() => {\n // An explicitly empty allowlist means nobody may be sent to, so the feature\n // is unusable and must not advertise itself. Distinct from `undefined`,\n // which means \"unrestricted\".\n if (allowedRecipients.value?.length === 0) return false;\n return options.isAvailable?.() ?? true;\n });\n\n function open(): void {\n if (!isAvailable.value) return;\n // Clear both, or a reopen shows the previous attempt's error or a stale tick\n // of the success state.\n error.value = null;\n justSent.value = false;\n clearDismissTimer();\n isModalOpen.value = true;\n }\n\n function close(): void {\n clearDismissTimer();\n isModalOpen.value = false;\n justSent.value = false;\n }\n\n /**\n * Build `payload.mjml` when the provider opted in.\n *\n * Returns `undefined` for the two non-fatal cases (not opted in; opted in but\n * the renderer isn't installed) and **throws** when rendering itself fails —\n * that means the render is broken, and silently sending JSON-only would hide\n * a real defect indefinitely.\n */\n async function resolveMjml(): Promise<string | undefined> {\n if (!provider.includeMjml || !options.renderMjml) return undefined;\n\n try {\n return await options.renderMjml();\n } catch (err) {\n // Probe only on the failure path, so the happy path pays nothing — and\n // only when the bundled renderer is what ran, since a `render` provider's\n // failure can never be explained by the package being absent.\n const couldBeMissingRenderer = options.usesLocalRenderer?.() ?? true;\n if (couldBeMissingRenderer && (await tryLoadRenderer()) === null) {\n if (!warnedAboutRenderer) {\n warnedAboutRenderer = true;\n logger.warn(\n \"testEmail.includeMjml is set but @templatical/renderer is not installed — \" +\n \"sending the template as JSON only. Install it to receive `payload.mjml`.\",\n );\n }\n return undefined;\n }\n throw err;\n }\n }\n\n /**\n * Report a completed send to the provider's `onSent`, guarded so a throw\n * cannot reach `send`'s own try/catch — by the time this runs, `send` has\n * already succeeded and the dialog is already showing success.\n *\n * Mirrors `@templatical/core`'s `notifyHandler`, which this composable\n * cannot import: `error-reporting.ts` is not part of `@templatical/core`'s\n * package exports.\n */\n function notifySent(payload: TestEmailPayload): void {\n try {\n // Read off `provider` at call time, never destructured — the same\n // discipline `allowedRecipients`/`defaultRecipient` apply above, so a\n // handler that arrives or changes after setup is never missed.\n provider.onSent?.(payload);\n } catch (err) {\n options.onError?.(toError(err));\n }\n }\n\n async function send(recipient: string): Promise<void> {\n if (isSending.value) return;\n\n const allowed = allowedRecipients.value;\n if (allowed && !allowed.includes(recipient)) {\n // Unreachable through the picker, reachable by a programmatic open or a\n // tampered field. Refusing keeps a guarantee worth having: the editor\n // never calls `send` with an address outside a configured allowlist.\n error.value = { kind: \"recipientNotAllowed\" };\n return;\n }\n\n isSending.value = true;\n error.value = null;\n\n try {\n const mjml = await resolveMjml();\n const payload: TestEmailPayload = {\n recipient,\n content: options.getContent(),\n ...(mjml !== undefined ? { mjml } : {}),\n ...(allowed !== undefined ? { allowedRecipients: allowed } : {}),\n };\n await provider.send(payload);\n\n justSent.value = true;\n dismissTimer = setTimeout(close, SUCCESS_DISMISS_MS);\n notifySent(payload);\n } catch (err) {\n const wrapped = toError(err);\n error.value = { kind: \"provider\", message: wrapped.message };\n options.onError?.(wrapped);\n // Deliberately not re-thrown: the dialog surfaces `error` and stays open\n // for a retry, and nothing awaits this beyond the click handler.\n } finally {\n isSending.value = false;\n }\n }\n\n const capability: NonNullable<EditorCapabilities[\"testEmail\"]> = {\n open,\n isAvailable,\n };\n\n return {\n isModalOpen,\n open,\n close,\n isSending,\n justSent,\n error,\n send,\n allowedRecipients,\n defaultRecipient,\n isAvailable,\n capability,\n };\n}\n","import { computed, onScopeDispose, ref, type ComputedRef, type Ref } from \"vue\";\nimport {\n useVersionHistory,\n type UseVersionHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n UseAutoSaveReturn,\n UseConditionPreviewReturn,\n UseHistoryReturn,\n} from \"@templatical/core\";\nimport type {\n BlockLockHolder,\n TemplateContent,\n TemplateVersion,\n VersionHistoryProvider,\n} from \"@templatical/types\";\nimport { safeClone } from \"@templatical/types\";\nimport type { EditorCapabilities } from \"../types/editor-capabilities\";\n\n/** Minimal slice of the editor this feature needs — OSS and Cloud alike. */\ninterface VersionHistoryEditor {\n state: {\n readonly template?: { id: string } | null;\n readonly isDirty: boolean;\n };\n content: Ref<TemplateContent>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n}\n\n/**\n * How the restore confirmation persists unsaved work instead of only warning\n * about it.\n *\n * Both members are read at confirmation time rather than captured at setup, so\n * a late-bound save (Cloud's, which only exists once its lifecycle composable\n * is constructed) and a save that comes and goes (Cloud's lint gate) are both\n * expressible.\n */\nexport interface SaveBeforeRestore {\n /** Whether persisting is possible *right now*. */\n canSave: () => boolean;\n /** Persist the template. Rejects on failure; the confirmation stays up. */\n save: () => Promise<unknown>;\n}\n\n/**\n * What a version preview and a restore need from collaboration. A previewed\n * version is not an edit, so collaboration stops reading the canvas while one\n * is on it; a restore replaces the template on the backend, which this editor\n * then fetches like every other editor.\n */\nexport interface VersionHistoryCollaboration {\n suspend: () => void;\n resume: () => void;\n catchUp: () => Promise<void>;\n reportReplaceRefused: (holders: readonly BlockLockHolder[]) => void;\n}\n\nexport interface UseVersionHistoryFeatureOptions {\n /** Storage backend — consumer-supplied in OSS, the Cloud adapter in Cloud. */\n provider: VersionHistoryProvider;\n editor: VersionHistoryEditor;\n /**\n * Lets the restore confirmation offer \"save first\". Omit it — or supply one\n * whose `canSave` is false, which is what a `save: false` templates provider\n * amounts to — and the confirmation degrades to a plain \"these will be lost\",\n * because there is then nowhere to put them.\n */\n saveBeforeRestore?: SaveBeforeRestore | null;\n history: UseHistoryReturn;\n conditionPreview: UseConditionPreviewReturn;\n /** Paused for the duration of a preview, so previewed content is never saved. */\n autoSave: UseAutoSaveReturn | null;\n /** Set with a collaboration provider. */\n collaboration?: VersionHistoryCollaboration | null;\n onError?: (error: Error) => void;\n /**\n * Whether the feature may be used. Read reactively, so Cloud can defer to a\n * plan entitlement that resolves after its async config fetch. Omit for\n * always-available (the OSS case: a configured provider is the whole gate).\n */\n isAvailable?: () => boolean;\n}\n\nexport interface UseVersionHistoryFeatureReturn {\n headless: UseVersionHistoryReturn;\n\n versions: ComputedRef<TemplateVersion[]>;\n isLoading: ComputedRef<boolean>;\n isRestoring: ComputedRef<boolean>;\n canCreate: ComputedRef<boolean>;\n canRestore: ComputedRef<boolean>;\n /** True once a template exists — there is no history before that. */\n hasTemplate: ComputedRef<boolean>;\n isAvailable: ComputedRef<boolean>;\n\n /** The version currently on the canvas, or `null` when editing normally. */\n previewingVersion: Ref<TemplateVersion | null>;\n isPreviewing: ComputedRef<boolean>;\n\n /** True while the unsaved-changes confirmation is up. */\n isConfirmingRestore: Ref<boolean>;\n /** Whether that confirmation may offer \"save first\" rather than only warn. */\n canSaveBeforeRestore: ComputedRef<boolean>;\n /**\n * True from the moment a confirmation action is taken until it settles —\n * covering the save as well as the restore, so a second click can't fire a\n * second save while the first is still in flight.\n */\n isConfirmBusy: ComputedRef<boolean>;\n\n /** Re-read the list. Called when the history control opens. */\n refresh: () => void;\n /**\n * Show a version on the canvas. **Synchronous once the preview is open and the\n * version's content is already in hand**, which is what keeps scrubbing\n * instant — see {@link TemplateVersion.content}.\n */\n navigate: (version: TemplateVersion) => Promise<void>;\n /**\n * What the banner's Restore button calls. Restores straight away when there is\n * nothing to lose; opens the confirmation when there are unsaved changes,\n * because {@link confirmRestore} discards the pre-preview backup and that work\n * would then exist nowhere.\n */\n requestRestore: () => Promise<void>;\n /** Confirmation's primary action: persist the unsaved work, then restore. */\n saveAndRestore: () => Promise<void>;\n /** Confirmation's destructive action: restore, losing the unsaved work. */\n discardAndRestore: () => Promise<void>;\n /** Dismiss the confirmation, staying in the preview with nothing restored. */\n cancelRestoreConfirm: () => void;\n /** Make the previewed version current. Rejects if the provider's restore does. */\n confirmRestore: () => Promise<void>;\n /** Leave the preview and put the pre-preview content back. */\n cancelPreview: () => void;\n\n capability: NonNullable<EditorCapabilities[\"versionHistory\"]>;\n}\n\n/**\n * Shared glue for version history: the reactive list, the preview-before-restore\n * flow, and the capability the shared chrome gates on.\n *\n * Both `Editor.vue` (OSS) and `useCloudInitialization` (Cloud) call this with\n * their own provider, so the two entry points run identical logic over different\n * transports. Nothing here is auth- or plan-aware — callers decide whether the\n * feature is available *before* constructing it.\n */\nexport function useVersionHistoryFeature(\n options: UseVersionHistoryFeatureOptions,\n): UseVersionHistoryFeatureReturn {\n const { provider, editor, history, conditionPreview, autoSave } = options;\n const collaboration = options.collaboration ?? null;\n\n const headless = useVersionHistory({\n provider,\n getTemplateId: () => editor.state.template?.id ?? null,\n onError: options.onError,\n });\n\n const previewingVersion = ref<TemplateVersion | null>(null);\n const contentBeforePreview = ref<TemplateContent | null>(null);\n const isConfirmingRestore = ref(false);\n const isSavingBeforeRestore = ref(false);\n\n // Async functions must guard against post-unmount execution after every\n // `await` so we don't write to dead refs or fire side effects\n // (autoSave.pause, setContent) on a torn-down component.\n let destroyed = false;\n onScopeDispose(() => {\n destroyed = true;\n });\n\n const versions = computed(() => headless.versions.value);\n const isLoading = computed(() => headless.isLoading.value);\n const isRestoring = computed(() => headless.isRestoring.value);\n const canCreate = headless.canCreate;\n const canRestore = headless.canRestore;\n const hasTemplate = computed(() => !!editor.state.template?.id);\n const isAvailable = computed(() => options.isAvailable?.() ?? true);\n const isPreviewing = computed(() => previewingVersion.value !== null);\n const canSaveBeforeRestore = computed(\n () => options.saveBeforeRestore?.canSave() === true,\n );\n const isConfirmBusy = computed(\n () => isSavingBeforeRestore.value || isRestoring.value,\n );\n\n function refresh(): void {\n if (!hasTemplate.value) return;\n // Fire-and-forget: `useVersionHistory` already routes failures to `onError`,\n // and a stale list is not worth blocking the dropdown's open on.\n void headless.load().catch(() => {});\n }\n\n async function navigate(version: TemplateVersion): Promise<void> {\n if (destroyed) return;\n\n // A pending confirmation names the version it was raised for, so moving to\n // another one must retract it. Unreachable while the dialog is modal, but a\n // programmatic scrub reaches it today and an inline confirmation would.\n isConfirmingRestore.value = false;\n\n // Already previewing: this is a scrub. Take the synchronous path whenever\n // the content is in hand — a provider that hydrates its list (Cloud does)\n // never awaits here, and the canvas swaps in the same tick.\n if (previewingVersion.value) {\n const known = headless.peekContent(version);\n if (known) {\n previewingVersion.value = version;\n editor.setContent(known, false);\n return;\n }\n const content = await headless.resolveContent(version);\n if (destroyed) return;\n previewingVersion.value = version;\n editor.setContent(content, false);\n return;\n }\n\n // Entering the preview. Resolve first: a failed fetch must leave the user\n // editing, not stranded in a preview of nothing.\n const content = await headless.resolveContent(version);\n if (destroyed) return;\n\n // Opening a preview records nothing. The editor never authors a version —\n // whoever implements `TemplatesProvider.save` decides that. The unsaved work\n // that a confirmed restore would discard is protected at the confirmation\n // instead (see `requestRestore`), which is both where the loss happens and\n // the one place the user can be asked about it.\n //\n // `safeClone`, not `structuredClone`: what arrives here is a Vue reactive\n // proxy over the editor's content, and the structured-clone algorithm\n // refuses a proxy outright. It is also the repo's one deep-clone for\n // content, so a Sortable back-ref that leaked into block data is dropped\n // rather than thrown on.\n contentBeforePreview.value = safeClone(editor.content.value);\n\n autoSave?.pause();\n collaboration?.suspend();\n previewingVersion.value = version;\n editor.setContent(content, false);\n }\n\n async function requestRestore(): Promise<void> {\n if (!previewingVersion.value) return;\n\n // `setContent(…, false)` is what puts a version on the canvas, so `isDirty`\n // still describes the user's own work rather than the preview.\n if (editor.state.isDirty) {\n isConfirmingRestore.value = true;\n return;\n }\n await confirmRestore();\n }\n\n async function saveAndRestore(): Promise<void> {\n const version = previewingVersion.value;\n const before = contentBeforePreview.value;\n const saver = options.saveBeforeRestore;\n // The UI hides this action in each of these cases; a programmatic caller\n // gets a no-op rather than a save of the previewed version.\n if (!version || !before || !saver?.canSave()) return;\n if (isConfirmBusy.value) return;\n\n // The canvas is showing the *previewed* version and a save persists whatever\n // the editor holds, so put the user's work back before saving — otherwise\n // \"save first\" would save the very version they are about to restore.\n editor.setContent(before, false);\n isSavingBeforeRestore.value = true;\n try {\n await saver.save();\n } catch {\n // Already reported by whoever owns the save (status badge, `onError`).\n // Put the preview back so the banner and the canvas agree again, and leave\n // the confirmation up: nothing was saved and nothing was restored.\n if (destroyed) return;\n const previewed = headless.peekContent(version);\n if (previewed) editor.setContent(previewed, false);\n return;\n } finally {\n if (!destroyed) isSavingBeforeRestore.value = false;\n }\n if (destroyed) return;\n await confirmRestore();\n }\n\n async function discardAndRestore(): Promise<void> {\n // The dialog disables its buttons while busy; this covers a programmatic\n // caller, for whom a second restore mid-flight would append twice.\n if (isConfirmBusy.value) return;\n await confirmRestore();\n }\n\n function cancelRestoreConfirm(): void {\n isConfirmingRestore.value = false;\n }\n\n async function confirmRestore(): Promise<void> {\n if (!previewingVersion.value) return;\n\n try {\n const template = await headless.restore(previewingVersion.value.id);\n if (destroyed) return;\n if (collaboration) {\n // The backend replaced the content; fetch it like every other editor\n // does. `resume()` below puts it on the canvas.\n await collaboration.catchUp();\n if (destroyed) return;\n history.clear();\n conditionPreview.reset();\n } else {\n applyRestored(template.content);\n }\n // History is append-only: the restore added an entry, so the list the\n // dropdown shows is stale until it is re-read.\n await headless.load();\n if (destroyed) return;\n } catch (error) {\n // The canvas is still showing the previewed version (set in `navigate`),\n // so roll back to the pre-preview content before the `finally` discards\n // the backup — otherwise the user is silently left editing an un-restored\n // version with the banner gone, and the next autosave persists it.\n if (!destroyed && contentBeforePreview.value) {\n editor.setContent(contentBeforePreview.value, false);\n }\n const refusal = error as { code?: unknown; holders?: unknown };\n if (collaboration && refusal?.code === \"locked_by_others\") {\n collaboration.reportReplaceRefused(\n Array.isArray(refusal.holders)\n ? (refusal.holders as BlockLockHolder[])\n : [],\n );\n }\n throw error;\n } finally {\n if (!destroyed) {\n previewingVersion.value = null;\n contentBeforePreview.value = null;\n isConfirmingRestore.value = false;\n autoSave?.resume();\n collaboration?.resume();\n }\n }\n }\n\n function applyRestored(content: TemplateContent): void {\n editor.setContent(content, false);\n history.clear();\n conditionPreview.reset();\n }\n\n function cancelPreview(): void {\n if (!previewingVersion.value || !contentBeforePreview.value) return;\n\n editor.setContent(contentBeforePreview.value, false);\n\n previewingVersion.value = null;\n contentBeforePreview.value = null;\n isConfirmingRestore.value = false;\n\n autoSave?.resume();\n collaboration?.resume();\n }\n\n return {\n headless,\n\n versions,\n isLoading,\n isRestoring,\n canCreate,\n canRestore,\n hasTemplate,\n isAvailable,\n\n previewingVersion,\n isPreviewing,\n isConfirmingRestore,\n canSaveBeforeRestore,\n isConfirmBusy,\n\n refresh,\n navigate,\n requestRestore,\n saveAndRestore,\n discardAndRestore,\n cancelRestoreConfirm,\n confirmRestore,\n cancelPreview,\n\n capability: {\n refresh,\n isPreviewing,\n hasTemplate,\n isAvailable,\n canCreate,\n canRestore,\n },\n };\n}\n","/**\n * Whether the editor saves automatically after the user stops editing.\n *\n * The cadence is `changeDebounce` at the config root rather than a member here,\n * because one `useAutoSave` instance drives both the save and the `onChange`\n * notification — and `onChange` works with no templates provider, so a\n * provider-less consumer still needs to set it. `autoSave: false` with a\n * `changeDebounce` is therefore a real setting, not a dead one: it means notify\n * at that cadence and persist nothing.\n */\nexport type AutoSaveConfig = boolean;\n\n/**\n * Normalise an {@link AutoSaveConfig}.\n *\n * The one call site is `Editor.vue`'s `autoSaveEnabled`, which always passes\n * `false` as `defaultEnabled` — a consumer without a `templates` provider has\n * nothing to save to. `initCloud()` inlines its own default instead of\n * calling this (`config.templates?.autoSave ?? true`, in `index.ts`), since\n * Cloud always has a store to save to.\n */\nexport function resolveAutoSave(\n value: AutoSaveConfig | undefined,\n defaultEnabled: boolean,\n): boolean {\n return value ?? defaultEnabled;\n}\n","/**\n * Where a palette insert should land, expressed as the trailing arguments of\n * `editor.addBlock(block, targetSectionId?, columnIndex?, index?)`.\n *\n * An empty object means \"append at the end\" — every field absent, so spreading\n * it into `addBlock` passes `undefined` for all three and takes the push path.\n */\nexport interface InsertPosition {\n targetSectionId?: string;\n columnIndex?: number;\n index?: number;\n}\n\nexport interface ResolveInsertPositionOptions {\n /**\n * The type of block about to be inserted. Only `\"section\"` changes the\n * outcome — custom types (`custom:*`) behave like any other leaf block.\n */\n blockType: string;\n selectedBlockId: string | null;\n findBlockLocation: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n isBlockLocked: (blockId: string) => boolean;\n}\n\n/**\n * Resolve the insert position for a palette click: directly below the selected\n * block, falling back to appending at the end.\n *\n * Every fallback here exists because `addBlock` refuses the alternative\n * *silently*. Returning a position it rejects would turn the click into a\n * complete no-op — worse for the user than landing at the bottom, which is the\n * behaviour this whole function replaces. So the rule is: only ever return a\n * position `addBlock` will accept.\n *\n * Mirrors `duplicateBlock` in `@templatical/core` (resolve the reference\n * block's location, bump the index by one, append when it can't be resolved) so\n * click-to-insert and duplicate place blocks by the same rule.\n */\nexport function resolveInsertPosition(\n options: ResolveInsertPositionOptions,\n): InsertPosition {\n const { blockType, selectedBlockId, findBlockLocation, isBlockLocked } =\n options;\n\n if (!selectedBlockId) return {};\n\n // A selection can outlive its block — a collaborator removes it, an undo\n // drops it — so an unresolvable id means append, never a guessed index.\n const selected = findBlockLocation(selectedBlockId);\n if (!selected) return {};\n\n if (selected.targetSectionId === undefined) {\n return { index: selected.index + 1 };\n }\n\n if (blockType === \"section\") {\n // MJML forbids `mj-section` inside `mj-column`, so `addBlock` rejects the\n // nest outright. Land beside the section the selection sits in instead —\n // the nearest position that accepts a section at all. Sections never nest,\n // so the parent's own location is always top-level.\n const parent = findBlockLocation(selected.targetSectionId);\n if (!parent || parent.targetSectionId !== undefined) return {};\n return { index: parent.index + 1 };\n }\n\n // `addBlock` bails when the target section is locked, so a locked parent\n // means the column is unavailable — append rather than lose the block.\n if (isBlockLocked(selected.targetSectionId)) return {};\n\n return {\n targetSectionId: selected.targetSectionId,\n columnIndex: selected.columnIndex,\n index: selected.index + 1,\n };\n}\n","import type { Block } from \"@templatical/types\";\nimport {\n resolveInsertPosition,\n type ResolveInsertPositionOptions,\n} from \"./resolveInsertPosition\";\n\n/** The slice of the core editor a click-to-insert needs. */\nexport interface InsertBlockTarget {\n state: { selectedBlockId: string | null };\n findBlockLocation: ResolveInsertPositionOptions[\"findBlockLocation\"];\n isBlockLocked: ResolveInsertPositionOptions[\"isBlockLocked\"];\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n selectBlock: (blockId: string | null) => void;\n}\n\n/**\n * Insert a block the way a palette click does: below the selection, by the\n * rules in `resolveInsertPosition`, then select it. Shared by the sidebar and\n * the public `insertBlock()`, so the two can never place a block differently.\n *\n * Returns whether the block landed. `addBlock` refuses silently, and selecting\n * an id it never added would leave a selection the next insert resolves\n * against.\n */\nexport function insertBlockAtSelection(\n editor: InsertBlockTarget,\n block: Block,\n): boolean {\n const { targetSectionId, columnIndex, index } = resolveInsertPosition({\n blockType: block.type,\n selectedBlockId: editor.state.selectedBlockId,\n findBlockLocation: editor.findBlockLocation,\n isBlockLocked: editor.isBlockLocked,\n });\n editor.addBlock(block, targetSectionId, columnIndex, index);\n if (!editor.findBlockLocation(block.id)) return false;\n editor.selectBlock(block.id);\n return true;\n}\n","import type {\n Template,\n TemplatePatch,\n TemplatesProvider,\n} from \"@templatical/types\";\n\n/** What the save needs from collaboration: a way to wait for the batches. */\nexport interface SettlingCollaboration {\n settle: () => Promise<void>;\n}\n\n/**\n * A templates provider whose `save` persists content through collaboration.\n *\n * With a collaboration provider, every edit already reaches the backend as an\n * operation, and the backend's copy is the shared one. Saving the whole\n * content as well would write over other people's edits, so `save` waits for\n * this editor's batches to be confirmed and passes on only a rename. A save\n * with nothing to rename makes no call and answers with what is open.\n *\n * @param getTemplate What is open: the loaded template with the content on\n * the canvas.\n */\nexport function withCollaborativeSave(\n provider: TemplatesProvider,\n collaboration: SettlingCollaboration,\n getTemplate: () => Template | null,\n): TemplatesProvider {\n const { save, create } = provider;\n if (typeof save !== \"function\") return provider;\n\n // The name the store last confirmed, per template id.\n const storedNames = new Map<string, string | undefined>();\n const remember = (template: Template): Template => {\n storedNames.set(template.id, template.name);\n return template;\n };\n\n return {\n ...provider,\n load: async (id) => remember(await provider.load(id)),\n create:\n typeof create === \"function\"\n ? async (input) => remember(await create(input))\n : false,\n save: async (id: string, patch: TemplatePatch): Promise<Template> => {\n await collaboration.settle();\n const renamed =\n patch.name !== undefined && patch.name !== storedNames.get(id);\n if (renamed) return remember(await save(id, { name: patch.name }));\n const current = getTemplate();\n // Another template was opened while the batches settled: answer with\n // the stored one, which core then ignores as stale.\n return current && current.id === id\n ? current\n : remember(await provider.load(id));\n },\n };\n}\n","<script setup lang=\"ts\">\nimport { updateBlockList } from \"../utils/updateBlockList\";\nimport { useLocalizedDisplay } from \"../composables/useLocalizedDisplay\";\nimport { useI18n } from \"../composables/useI18n\";\nimport type {\n Block,\n CustomBlock as CustomBlockType,\n TemplateContent,\n ViewportSize,\n} from \"@templatical/types\";\nimport { resolveContentDirection } from \"@templatical/types\";\nimport { ImageUp, Sparkles, SquarePlus } from \"@lucide/vue\";\nimport { computed, inject, provide, ref, type Component } from \"vue\";\nimport {\n EDITOR_KEY,\n APPLIES_CONDITION_FILTER_KEY,\n CONDITION_PREVIEW_KEY,\n BLOCK_REGISTRY_KEY,\n CAPABILITIES_KEY,\n FONTS_MANAGER_KEY,\n MERGE_TAG_SAMPLE_MODE_KEY,\n PREVIEW_RESOLUTION_KEY,\n USE_MERGE_TAG_SAMPLES_KEY,\n requireInject,\n} from \"../keys\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport {\n getDocumentStyle,\n resolveBlockComponent,\n} from \"../utils/blockComponentResolver\";\nimport {\n EMAIL_FRAME_WIDTH_TRANSITION,\n EMAIL_GUTTER,\n getEmailFrameWidth,\n} from \"../utils/emailFrameWidth\";\n\nimport BlockWrapper from \"./blocks/BlockWrapper.vue\";\nimport SectionBlock from \"./blocks/SectionBlock.vue\";\nimport TitleBlock from \"./blocks/TitleBlock.vue\";\nimport ParagraphBlock from \"./blocks/ParagraphBlock.vue\";\nimport ImageBlock from \"./blocks/ImageBlock.vue\";\nimport ButtonBlock from \"./blocks/ButtonBlock.vue\";\nimport DividerBlock from \"./blocks/DividerBlock.vue\";\nimport SpacerBlock from \"./blocks/SpacerBlock.vue\";\nimport HtmlBlock from \"./blocks/HtmlBlock.vue\";\nimport SocialIconsBlock from \"./blocks/SocialIconsBlock.vue\";\nimport MenuBlock from \"./blocks/MenuBlock.vue\";\nimport TableBlock from \"./blocks/TableBlock.vue\";\nimport CustomBlock from \"./blocks/CustomBlock.vue\";\nimport VideoBlock from \"./blocks/VideoBlock.vue\";\nimport WrapperBlock from \"./blocks/WrapperBlock.vue\";\n\n// `countdown` is deliberately absent: it resolves from the block registry, which\n// `useEditorCore` populates with a lazy `defineAsyncComponent` so OSS bundles\n// don't carry a Cloud-only block. `resolveBlockComponent` checks the registry\n// first, so a static entry here would never be reached — but its static import\n// would still pull the module into the eager graph and defeat the laziness.\n// The other fallback maps (SectionBlock, BlockPreviewCanvas,\n// PreviewSectionBlock) omit it for the same reason.\nconst blockComponentMap: Record<string, Component> = {\n section: SectionBlock,\n title: TitleBlock,\n paragraph: ParagraphBlock,\n image: ImageBlock,\n button: ButtonBlock,\n divider: DividerBlock,\n spacer: SpacerBlock,\n html: HtmlBlock,\n social: SocialIconsBlock,\n menu: MenuBlock,\n table: TableBlock,\n video: VideoBlock,\n custom: CustomBlock,\n wrapper: WrapperBlock,\n};\n\nconst props = defineProps<{\n viewport: ViewportSize;\n content: TemplateContent;\n selectedBlockId: string | null;\n darkMode: boolean;\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"select-block\", blockId: string | null): void;\n}>();\n\nconst { t } = useI18n();\n\nconst editor = requireInject(EDITOR_KEY, \"Canvas\");\nconst { displayBlock, settings: displaySettings } = useLocalizedDisplay({\n content: computed(() => props.content),\n activeLocale: computed(() =>\n props.previewMode ? null : (editor.activeLocale?.value ?? null),\n ),\n});\nconst fontsManager = requireInject(FONTS_MANAGER_KEY, \"Canvas\");\nconst conditionPreview = inject(CONDITION_PREVIEW_KEY, null);\nconst blockRegistry = inject(BLOCK_REGISTRY_KEY, null);\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n/**\n * Merge-tag samples render on this canvas **only while preview mode is on**.\n * The `previewMode &&` is the load-bearing half: the canvas is the editing\n * surface, and substituted text in a block a user is about to edit would be\n * text they never wrote. Preview mode is already fully non-editing (clicks and\n * dragging are blocked above), so it is the one state where swapping the\n * displayed value is safe.\n */\nconst mergeTagSampleMode = inject(MERGE_TAG_SAMPLE_MODE_KEY, null);\n// Null in headless mounts and when no resolver is configured.\nconst previewResolution = inject(PREVIEW_RESOLUTION_KEY, null);\nprovide(\n USE_MERGE_TAG_SAMPLES_KEY,\n computed(\n () =>\n props.previewMode &&\n (mergeTagSampleMode?.value ?? false) &&\n // A configured resolver owns what the preview shows. Substituting samples\n // underneath it would mix invented values with real ones, and on the\n // failure path would contradict the note saying the *unresolved* template\n // is showing.\n !previewResolution?.isConfigured,\n ),\n);\n\nconst canChat = computed(() => caps.ai?.isFeatureEnabled(\"chat\") ?? false);\nconst canImport = computed(\n () =>\n canChat.value && (caps.ai?.isFeatureEnabled(\"chatAttachments\") ?? false),\n);\nconst importInput = ref<HTMLInputElement | null>(null);\nfunction pickImport(): void {\n importInput.value?.click();\n}\nfunction importPicked(event: Event): void {\n const input = event.target as HTMLInputElement;\n const files = Array.from(input.files ?? []);\n input.value = \"\";\n if (files.length) caps.ai?.startImport(files);\n}\n\n/**\n * Whether the hand-toggled display-condition filter applies here. Owned by\n * `useEditorCore` and injected rather than re-derived — see the key's comment.\n */\nconst appliesConditionFilter = inject(APPLIES_CONDITION_FILTER_KEY, null);\n\nconst blocks = computed({\n get: () => props.content.blocks,\n set: (value: Block[]) => updateBlockList(editor, value),\n});\n\n// Shared with the preview canvas and the save dialog's scaled rows, so all\n// three lay out against the same width.\nconst viewportWidth = computed(() =>\n getEmailFrameWidth(displaySettings.value, props.viewport),\n);\n\n// The \"stage\" represents the email body: the content column plus a gutter of\n// email background on each side (#230 — without it a full-width section's own\n// background hides the global one entirely). Mirrors how `mj-body\n// background-color` renders in the gutters around the centered content when\n// the email is sent. The neutral work area beyond the stage is preserved so\n// editor chrome stays legible.\n//\n// `EMAIL_GUTTER` comes from the shared helper rather than a local constant: the\n// preview surfaces show the same band, and two copies drift into two different\n// answers for how much of the body background an email is supposed to show.\nconst stageWidth = computed(() => viewportWidth.value + EMAIL_GUTTER * 2);\n\n// Canvas dark mode preview: simulates how the email will appear in recipients'\n// dark-themed email clients. Uses CSS filter inversion — independent of the\n// editor UI theme (light/dark/auto) which is controlled via uiTheme config.\n// The email bg lives on the `.tpl-canvas-bg` sibling layer (so it can be\n// inverted by `filter` without trapping block chrome in a stacking context);\n// the `.tpl-canvas` itself stays transparent so the bg layer shows through.\n// Shared with every other surface that renders blocks (the saved-block\n// previews), so a block looks the same wherever it is drawn.\nconst canvasStyle = computed(() =>\n getDocumentStyle(displaySettings.value, fontsManager.resolveFontFamily),\n);\n// The email's own language, for the browser's spellchecker and hyphenation.\n// Without it the canvas inherits the HOST page's `lang`, so German copy is\n// spellchecked by English rules — every word underlined. `settings.locale`,\n// never `config.locale`: the chrome's language says nothing about the content's,\n// and an author writing English in a German editor must not have their copy\n// declared German. Undefined rather than `\"\"`, which would explicitly declare\n// \"unknown language\" and suppress spellcheck outright.\nconst contentLang = computed(\n () => displaySettings.value?.locale?.trim() || undefined,\n);\n// Always a real token: an empty `dir` inherits the host page and the email\n// stage would follow chrome instead of `settings.direction`. Flex `row` on\n// sections follows this inline axis, so column 0 lands on the start edge\n// with no extra reverse class (which would also ship in every LTR stylesheet).\nconst contentDir = computed(() =>\n resolveContentDirection(displaySettings.value),\n);\n\n// Empty canvas: the whole dashed placeholder IS the Sortable drop zone.\n// `isEmptyCanvas` toggles the styling + the inline empty-state content.\nconst isEmptyCanvas = computed(\n () => blocks.value.length === 0 && !props.previewMode,\n);\n\n// Highlight the empty drop zone while a block is being dragged over it.\n// Uses a counter to handle dragenter/leave bubbling from descendants —\n// raw event toggling would flicker as the pointer moves between children.\nconst dragEnterDepth = ref(0);\nconst isDragOverEmpty = computed(\n () => isEmptyCanvas.value && dragEnterDepth.value > 0,\n);\n\nfunction handleEmptyDragEnter(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value += 1;\n}\n\nfunction handleEmptyDragLeave(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value = Math.max(0, dragEnterDepth.value - 1);\n}\n\nfunction handleEmptyDrop(): void {\n dragEnterDepth.value = 0;\n}\n\nfunction handleCanvasClick(event: MouseEvent): void {\n if (props.previewMode) {\n return;\n }\n // During a pick session, a stray background click must not clear anything —\n // the session is left only via the bar's Save/Cancel or Escape. Deselecting\n // here would also be meaningless, since picking doesn't touch selection.\n if (caps.savedBlocks?.isPicking.value) {\n return;\n }\n if (event.target === event.currentTarget) {\n emit(\"select-block\", null);\n }\n}\n\nfunction getBlockComponent(block: Block): Component | null {\n return resolveBlockComponent(block, blockRegistry, blockComponentMap);\n}\n\n// An omitted locale checks the active language view.\nfunction isLockedByOther(blockId: string): boolean {\n return caps.collaboration?.lockOf(blockId) != null;\n}\n\n/**\n * A click on a block either toggles its pick (while a saved-blocks pick\n * session is running) or selects it. Preview mode and collaborator locks are\n * checked first, so a locked block can be neither selected nor picked.\n */\nfunction handleBlockSelect(blockId: string): void {\n if (props.previewMode || isLockedByOther(blockId)) return;\n const savedBlocks = caps.savedBlocks;\n if (savedBlocks?.isPicking.value) {\n savedBlocks.togglePick(blockId);\n return;\n }\n emit(\"select-block\", blockId);\n}\n\nfunction isPickedBlock(blockId: string): boolean {\n return caps.savedBlocks?.isPicked(blockId) ?? false;\n}\n\n/** True while a pick session runs — swaps block chrome into picking behaviour. */\nconst isPicking = computed(() => caps.savedBlocks?.isPicking.value === true);\n\nfunction handleFetchData(\n block: Block,\n payload: {\n fieldValues: Record<string, unknown>;\n dataSourceFetched: boolean;\n },\n): void {\n if (block.type !== \"custom\") {\n return;\n }\n\n editor.updateBlock(block.id, {\n fieldValues: payload.fieldValues,\n dataSourceFetched: payload.dataSourceFetched,\n } as Partial<CustomBlockType>);\n}\n</script>\n\n<template>\n <!-- STAGE — the email body. Sized to the content column plus a gutter of\n email background on each side, so the global background stays visible\n around full-width sections, mirroring how `mj-body background-color`\n renders in the gutters when sent (#230). The neutral work area beyond\n the stage is preserved so the canvas still reads as a floating card and\n editor chrome stays legible.\n\n Auto margins centre it in the pane. The max-width keeps the pane's\n clearance on each side by shrinking the gutters first, and min-content\n stops it at the email column: past that the margins fall to zero and\n the pane scrolls from the column's left edge instead of clipping it. -->\n <div\n class=\"tpl-canvas-stage tpl:relative tpl:mx-auto tpl:flex tpl:justify-center tpl:rounded-lg\"\n :style=\"{\n width: `${stageWidth}px`,\n maxWidth: 'calc(100% - 4 * var(--tpl-base-size))',\n minWidth: 'min-content',\n boxShadow: darkMode ? 'none' : 'var(--tpl-shadow-xl)',\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <!-- Background layer — holds the email bg and the dark-preview filter,\n spanning the full stage (content + gutters). Filter on this leaf\n layer (no descendants) does not create a containing block / stacking\n context that would trap block chrome (action bar, indicators) inside\n the wrapper. The filter has its own transition so the canvas fades\n smoothly between modes. -->\n <div\n class=\"tpl-canvas-bg tpl:absolute tpl:inset-0 tpl:rounded-lg tpl:pointer-events-none\"\n :style=\"{\n backgroundColor: displaySettings.backgroundColor,\n ...(darkMode ? { filter: 'invert(1) hue-rotate(180deg)' } : {}),\n transition: 'filter 300ms ease',\n }\"\n />\n <!-- CONTENT COLUMN — the email content at its true width, centered in the\n stage. A full-width section fills this column but not the surrounding\n gutters, so the global background remains visible beside it. -->\n <div\n data-testid=\"canvas-wrapper\"\n role=\"region\"\n :aria-label=\"t.landmarks.canvas\"\n class=\"tpl-canvas-wrapper tpl:relative\"\n :style=\"{\n width: `${viewportWidth}px`,\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <div\n class=\"tpl-canvas tpl:relative tpl:rounded-lg\"\n :lang=\"contentLang\"\n :dir=\"contentDir\"\n :class=\"{\n 'tpl-canvas--dark-mode': darkMode,\n 'tpl-preview-mode': previewMode,\n }\"\n :style=\"canvasStyle\"\n @click=\"handleCanvasClick\"\n >\n <!-- Preview resolution. The skeleton shows only on a *first* resolve —\n `isInitialResolve` — so switching recipient or reopening keeps the\n last good preview on screen instead of flashing over it. -->\n <div\n v-if=\"previewResolution?.isInitialResolve.value\"\n role=\"status\"\n aria-busy=\"true\"\n data-testid=\"preview-resolution-loading\"\n class=\"tpl:flex tpl:flex-col tpl:gap-3 tpl:p-6\"\n >\n <span class=\"tpl:sr-only\">{{ t.previewResolution.resolving }}</span>\n <div\n v-for=\"n in 3\"\n :key=\"n\"\n aria-hidden=\"true\"\n class=\"tpl-pulse tpl:h-16 tpl:rounded-md tpl:bg-[var(--tpl-bg-hover)]\"\n ></div>\n </div>\n\n <!-- Resolution failed: the unresolved template still renders below, so\n the preview degrades rather than disappearing. -->\n <p\n v-else-if=\"previewResolution?.hasFailed.value\"\n role=\"status\"\n data-testid=\"preview-resolution-failed\"\n class=\"tpl:mx-6 tpl:mt-4 tpl:rounded-md tpl:px-3 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)] tpl:bg-[var(--tpl-bg-hover)]\"\n >\n {{ t.previewResolution.failed }}\n </p>\n\n <!-- `draggable` names what to leave out, the empty-state content, not\n the canvas's own item class: Sortable indexes a cross-list drop in\n the receiving list with the sending list's `draggable`, and a\n canvas-only class matches nothing in a section column, which\n would drop every canvas block at the column's top. The `>` keeps\n hit-testing on the canvas's direct children. -->\n <VueDraggable\n v-show=\"!previewResolution?.isInitialResolve.value\"\n v-model=\"blocks\"\n group=\"blocks\"\n :animation=\"150\"\n ghost-class=\"tpl-ghost\"\n drag-class=\"tpl-dragging\"\n handle=\".tpl-block-btn\"\n :invert-swap=\"true\"\n :inverted-swap-threshold=\"0.65\"\n :disabled=\"previewMode\"\n :draggable=\"'>:not(.tpl-canvas-empty-content)'\"\n :force-fallback=\"true\"\n :class=\"[\n 'tpl-canvas-blocks',\n isEmptyCanvas\n ? 'tpl-canvas-empty tpl:m-6 tpl:flex tpl:min-h-[400px] tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded-xl tpl:border-2 tpl:border-dashed tpl:px-10 tpl:py-12 tpl:text-center tpl:bg-[var(--tpl-bg-elevated)] tpl:font-[var(--tpl-font-family)] tpl:transition-colors'\n : '',\n isEmptyCanvas && isDragOverEmpty\n ? 'tpl-canvas-empty--drag-over tpl:border-[var(--tpl-primary-hover)] tpl:bg-[var(--tpl-primary-light)]'\n : '',\n isEmptyCanvas && !isDragOverEmpty\n ? 'tpl:border-[var(--tpl-primary)]'\n : '',\n ]\"\n @update=\"\n (event) => updateBlockList(editor, blocks, undefined, 0, event)\n \"\n @dragenter=\"handleEmptyDragEnter\"\n @dragleave=\"handleEmptyDragLeave\"\n @drop=\"handleEmptyDrop\"\n >\n <!-- Empty-state content: rendered INSIDE the draggable so the whole\n dashed box is the drop zone, but excluded from sortable items by\n the `draggable` selector above. -->\n <div\n v-if=\"isEmptyCanvas\"\n class=\"tpl-canvas-empty-content tpl:flex tpl:flex-col tpl:items-center\"\n >\n <div\n class=\"tpl-canvas-empty-icon tpl:mb-4 tpl:text-[var(--tpl-primary)]\"\n >\n <SquarePlus :size=\"48\" :stroke-width=\"1\" />\n </div>\n <p\n class=\"tpl-canvas-empty-title tpl:m-0 tpl:mb-2 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-primary)]\"\n >\n {{ t.canvas.noBlocks }}\n </p>\n <p\n class=\"tpl-canvas-empty-text tpl:m-0 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.canvas.dragHint }}\n </p>\n <p\n v-if=\"canChat\"\n class=\"tpl:m-0 tpl:mt-2 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.chatHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-chat\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"caps.ai?.open('chat')\"\n >\n <Sparkles :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.menu.chat }}\n </button>\n {{ t.ai.canvas.chatHintSuffix }}\n </p>\n <p\n v-if=\"canImport\"\n class=\"tpl:m-0 tpl:mt-4 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.importHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-import\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"pickImport\"\n >\n <ImageUp :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.import.menu }}\n </button>\n <input\n ref=\"importInput\"\n type=\"file\"\n multiple\n accept=\"image/png,image/jpeg,image/webp,image/gif,application/pdf\"\n hidden\n @change=\"importPicked\"\n />\n </p>\n </div>\n <div\n v-for=\"block in blocks\"\n :key=\"block.id\"\n class=\"tpl-block-item\"\n v-show=\"\n appliesConditionFilter === false ||\n !conditionPreview?.isHidden(block.id)\n \"\n >\n <div class=\"tpl:relative\">\n <component\n v-if=\"block.type === 'wrapper'\"\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n />\n <BlockWrapper\n v-else\n :block=\"block\"\n :display-block=\"displayBlock(block)\"\n :is-selected=\"\n !previewMode &&\n !isPicking &&\n selectedBlockId === block.id &&\n !isLockedByOther(block.id)\n \"\n :picked=\"isPickedBlock(block.id)\"\n :viewport=\"viewport\"\n :preview-mode=\"previewMode\"\n @select=\"handleBlockSelect(block.id)\"\n >\n <component\n :is=\"getBlockComponent(block)\"\n :block=\"displayBlock(block)\"\n v-bind=\"\n block.type === 'section' ? { sourceBlock: block } : {}\n \"\n :viewport=\"viewport\"\n @fetch-data=\"handleFetchData(block, $event)\"\n @update=\"\n (updates: Partial<Block>) =>\n editor.updateBlock(block.id, updates)\n \"\n />\n </BlockWrapper>\n </div>\n </div>\n </VueDraggable>\n </div>\n </div>\n </div>\n</template>\n\n<style scoped>\n/* Dark-mode preview: invert only the outermost `.tpl-email-surface` — a\n block's box, a section's wrapper frame, or a layout band. Surfaces nest\n (child blocks inside a section, a box inside its frame, the whole email\n inside a band), and a filter at every level would compound and cancel\n out, so `:not(...)` keeps the inversion single-pass. Block chrome (action\n bar, indicators, overlays) lives outside every surface and is therefore\n never filtered — no counter-filter / toggle flicker. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface:not(.tpl-email-surface *)) {\n filter: invert(1) hue-rotate(180deg);\n}\n:deep(.tpl-email-surface) {\n transition: filter 300ms ease;\n}\n\n/* Counter-invert images so they look normal inside the inverted email\n surface (canonical CSS-filter dark-mode trick). */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface img) {\n filter: invert(1) hue-rotate(180deg);\n}\n\n/* Background photos get the same counter-invert. A filter on the host would\n also hit the content painted over it, so the photo moves to a `::before`\n beneath that content, painted from `--tpl-block-bg-layer`\n (`getBackgroundImageStyle`). Every host is a surface or sits inside one, so\n every host is under exactly one inversion. `isolation` keeps the\n `z-index: -1` layer above the host's background colour wherever the host\n isn't the filtered surface itself. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image),\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image) {\n position: relative;\n isolation: isolate;\n background-image: none !important;\n}\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image)::before,\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image)::before {\n content: \"\";\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n pointer-events: none;\n background: var(--tpl-block-bg-layer, none);\n filter: invert(1) hue-rotate(180deg);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { updateBlockList } from \"../utils/updateBlockList\";\nimport { useLocalizedDisplay } from \"../composables/useLocalizedDisplay\";\nimport { useI18n } from \"../composables/useI18n\";\nimport type {\n Block,\n CustomBlock as CustomBlockType,\n TemplateContent,\n ViewportSize,\n} from \"@templatical/types\";\nimport { resolveContentDirection } from \"@templatical/types\";\nimport { ImageUp, Sparkles, SquarePlus } from \"@lucide/vue\";\nimport { computed, inject, provide, ref, type Component } from \"vue\";\nimport {\n EDITOR_KEY,\n APPLIES_CONDITION_FILTER_KEY,\n CONDITION_PREVIEW_KEY,\n BLOCK_REGISTRY_KEY,\n CAPABILITIES_KEY,\n FONTS_MANAGER_KEY,\n MERGE_TAG_SAMPLE_MODE_KEY,\n PREVIEW_RESOLUTION_KEY,\n USE_MERGE_TAG_SAMPLES_KEY,\n requireInject,\n} from \"../keys\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport {\n getDocumentStyle,\n resolveBlockComponent,\n} from \"../utils/blockComponentResolver\";\nimport {\n EMAIL_FRAME_WIDTH_TRANSITION,\n EMAIL_GUTTER,\n getEmailFrameWidth,\n} from \"../utils/emailFrameWidth\";\n\nimport BlockWrapper from \"./blocks/BlockWrapper.vue\";\nimport SectionBlock from \"./blocks/SectionBlock.vue\";\nimport TitleBlock from \"./blocks/TitleBlock.vue\";\nimport ParagraphBlock from \"./blocks/ParagraphBlock.vue\";\nimport ImageBlock from \"./blocks/ImageBlock.vue\";\nimport ButtonBlock from \"./blocks/ButtonBlock.vue\";\nimport DividerBlock from \"./blocks/DividerBlock.vue\";\nimport SpacerBlock from \"./blocks/SpacerBlock.vue\";\nimport HtmlBlock from \"./blocks/HtmlBlock.vue\";\nimport SocialIconsBlock from \"./blocks/SocialIconsBlock.vue\";\nimport MenuBlock from \"./blocks/MenuBlock.vue\";\nimport TableBlock from \"./blocks/TableBlock.vue\";\nimport CustomBlock from \"./blocks/CustomBlock.vue\";\nimport VideoBlock from \"./blocks/VideoBlock.vue\";\nimport WrapperBlock from \"./blocks/WrapperBlock.vue\";\n\n// `countdown` is deliberately absent: it resolves from the block registry, which\n// `useEditorCore` populates with a lazy `defineAsyncComponent` so OSS bundles\n// don't carry a Cloud-only block. `resolveBlockComponent` checks the registry\n// first, so a static entry here would never be reached — but its static import\n// would still pull the module into the eager graph and defeat the laziness.\n// The other fallback maps (SectionBlock, BlockPreviewCanvas,\n// PreviewSectionBlock) omit it for the same reason.\nconst blockComponentMap: Record<string, Component> = {\n section: SectionBlock,\n title: TitleBlock,\n paragraph: ParagraphBlock,\n image: ImageBlock,\n button: ButtonBlock,\n divider: DividerBlock,\n spacer: SpacerBlock,\n html: HtmlBlock,\n social: SocialIconsBlock,\n menu: MenuBlock,\n table: TableBlock,\n video: VideoBlock,\n custom: CustomBlock,\n wrapper: WrapperBlock,\n};\n\nconst props = defineProps<{\n viewport: ViewportSize;\n content: TemplateContent;\n selectedBlockId: string | null;\n darkMode: boolean;\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"select-block\", blockId: string | null): void;\n}>();\n\nconst { t } = useI18n();\n\nconst editor = requireInject(EDITOR_KEY, \"Canvas\");\nconst { displayBlock, settings: displaySettings } = useLocalizedDisplay({\n content: computed(() => props.content),\n activeLocale: computed(() =>\n props.previewMode ? null : (editor.activeLocale?.value ?? null),\n ),\n});\nconst fontsManager = requireInject(FONTS_MANAGER_KEY, \"Canvas\");\nconst conditionPreview = inject(CONDITION_PREVIEW_KEY, null);\nconst blockRegistry = inject(BLOCK_REGISTRY_KEY, null);\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n/**\n * Merge-tag samples render on this canvas **only while preview mode is on**.\n * The `previewMode &&` is the load-bearing half: the canvas is the editing\n * surface, and substituted text in a block a user is about to edit would be\n * text they never wrote. Preview mode is already fully non-editing (clicks and\n * dragging are blocked above), so it is the one state where swapping the\n * displayed value is safe.\n */\nconst mergeTagSampleMode = inject(MERGE_TAG_SAMPLE_MODE_KEY, null);\n// Null in headless mounts and when no resolver is configured.\nconst previewResolution = inject(PREVIEW_RESOLUTION_KEY, null);\nprovide(\n USE_MERGE_TAG_SAMPLES_KEY,\n computed(\n () =>\n props.previewMode &&\n (mergeTagSampleMode?.value ?? false) &&\n // A configured resolver owns what the preview shows. Substituting samples\n // underneath it would mix invented values with real ones, and on the\n // failure path would contradict the note saying the *unresolved* template\n // is showing.\n !previewResolution?.isConfigured,\n ),\n);\n\nconst canChat = computed(() => caps.ai?.isFeatureEnabled(\"chat\") ?? false);\nconst canImport = computed(\n () =>\n canChat.value && (caps.ai?.isFeatureEnabled(\"chatAttachments\") ?? false),\n);\nconst importInput = ref<HTMLInputElement | null>(null);\nfunction pickImport(): void {\n importInput.value?.click();\n}\nfunction importPicked(event: Event): void {\n const input = event.target as HTMLInputElement;\n const files = Array.from(input.files ?? []);\n input.value = \"\";\n if (files.length) caps.ai?.startImport(files);\n}\n\n/**\n * Whether the hand-toggled display-condition filter applies here. Owned by\n * `useEditorCore` and injected rather than re-derived — see the key's comment.\n */\nconst appliesConditionFilter = inject(APPLIES_CONDITION_FILTER_KEY, null);\n\nconst blocks = computed({\n get: () => props.content.blocks,\n set: (value: Block[]) => updateBlockList(editor, value),\n});\n\n// Shared with the preview canvas and the save dialog's scaled rows, so all\n// three lay out against the same width.\nconst viewportWidth = computed(() =>\n getEmailFrameWidth(displaySettings.value, props.viewport),\n);\n\n// The \"stage\" represents the email body: the content column plus a gutter of\n// email background on each side (#230 — without it a full-width section's own\n// background hides the global one entirely). Mirrors how `mj-body\n// background-color` renders in the gutters around the centered content when\n// the email is sent. The neutral work area beyond the stage is preserved so\n// editor chrome stays legible.\n//\n// `EMAIL_GUTTER` comes from the shared helper rather than a local constant: the\n// preview surfaces show the same band, and two copies drift into two different\n// answers for how much of the body background an email is supposed to show.\nconst stageWidth = computed(() => viewportWidth.value + EMAIL_GUTTER * 2);\n\n// Canvas dark mode preview: simulates how the email will appear in recipients'\n// dark-themed email clients. Uses CSS filter inversion — independent of the\n// editor UI theme (light/dark/auto) which is controlled via uiTheme config.\n// The email bg lives on the `.tpl-canvas-bg` sibling layer (so it can be\n// inverted by `filter` without trapping block chrome in a stacking context);\n// the `.tpl-canvas` itself stays transparent so the bg layer shows through.\n// Shared with every other surface that renders blocks (the saved-block\n// previews), so a block looks the same wherever it is drawn.\nconst canvasStyle = computed(() =>\n getDocumentStyle(displaySettings.value, fontsManager.resolveFontFamily),\n);\n// The email's own language, for the browser's spellchecker and hyphenation.\n// Without it the canvas inherits the HOST page's `lang`, so German copy is\n// spellchecked by English rules — every word underlined. `settings.locale`,\n// never `config.locale`: the chrome's language says nothing about the content's,\n// and an author writing English in a German editor must not have their copy\n// declared German. Undefined rather than `\"\"`, which would explicitly declare\n// \"unknown language\" and suppress spellcheck outright.\nconst contentLang = computed(\n () => displaySettings.value?.locale?.trim() || undefined,\n);\n// Always a real token: an empty `dir` inherits the host page and the email\n// stage would follow chrome instead of `settings.direction`. Flex `row` on\n// sections follows this inline axis, so column 0 lands on the start edge\n// with no extra reverse class (which would also ship in every LTR stylesheet).\nconst contentDir = computed(() =>\n resolveContentDirection(displaySettings.value),\n);\n\n// Empty canvas: the whole dashed placeholder IS the Sortable drop zone.\n// `isEmptyCanvas` toggles the styling + the inline empty-state content.\nconst isEmptyCanvas = computed(\n () => blocks.value.length === 0 && !props.previewMode,\n);\n\n// Highlight the empty drop zone while a block is being dragged over it.\n// Uses a counter to handle dragenter/leave bubbling from descendants —\n// raw event toggling would flicker as the pointer moves between children.\nconst dragEnterDepth = ref(0);\nconst isDragOverEmpty = computed(\n () => isEmptyCanvas.value && dragEnterDepth.value > 0,\n);\n\nfunction handleEmptyDragEnter(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value += 1;\n}\n\nfunction handleEmptyDragLeave(): void {\n if (!isEmptyCanvas.value) return;\n dragEnterDepth.value = Math.max(0, dragEnterDepth.value - 1);\n}\n\nfunction handleEmptyDrop(): void {\n dragEnterDepth.value = 0;\n}\n\nfunction handleCanvasClick(event: MouseEvent): void {\n if (props.previewMode) {\n return;\n }\n // During a pick session, a stray background click must not clear anything —\n // the session is left only via the bar's Save/Cancel or Escape. Deselecting\n // here would also be meaningless, since picking doesn't touch selection.\n if (caps.savedBlocks?.isPicking.value) {\n return;\n }\n if (event.target === event.currentTarget) {\n emit(\"select-block\", null);\n }\n}\n\nfunction getBlockComponent(block: Block): Component | null {\n return resolveBlockComponent(block, blockRegistry, blockComponentMap);\n}\n\n// An omitted locale checks the active language view.\nfunction isLockedByOther(blockId: string): boolean {\n return caps.collaboration?.lockOf(blockId) != null;\n}\n\n/**\n * A click on a block either toggles its pick (while a saved-blocks pick\n * session is running) or selects it. Preview mode and collaborator locks are\n * checked first, so a locked block can be neither selected nor picked.\n */\nfunction handleBlockSelect(blockId: string): void {\n if (props.previewMode || isLockedByOther(blockId)) return;\n const savedBlocks = caps.savedBlocks;\n if (savedBlocks?.isPicking.value) {\n savedBlocks.togglePick(blockId);\n return;\n }\n emit(\"select-block\", blockId);\n}\n\nfunction isPickedBlock(blockId: string): boolean {\n return caps.savedBlocks?.isPicked(blockId) ?? false;\n}\n\n/** True while a pick session runs — swaps block chrome into picking behaviour. */\nconst isPicking = computed(() => caps.savedBlocks?.isPicking.value === true);\n\nfunction handleFetchData(\n block: Block,\n payload: {\n fieldValues: Record<string, unknown>;\n dataSourceFetched: boolean;\n },\n): void {\n if (block.type !== \"custom\") {\n return;\n }\n\n editor.updateBlock(block.id, {\n fieldValues: payload.fieldValues,\n dataSourceFetched: payload.dataSourceFetched,\n } as Partial<CustomBlockType>);\n}\n</script>\n\n<template>\n <!-- STAGE — the email body. Sized to the content column plus a gutter of\n email background on each side, so the global background stays visible\n around full-width sections, mirroring how `mj-body background-color`\n renders in the gutters when sent (#230). The neutral work area beyond\n the stage is preserved so the canvas still reads as a floating card and\n editor chrome stays legible.\n\n Auto margins centre it in the pane. The max-width keeps the pane's\n clearance on each side by shrinking the gutters first, and min-content\n stops it at the email column: past that the margins fall to zero and\n the pane scrolls from the column's left edge instead of clipping it. -->\n <div\n class=\"tpl-canvas-stage tpl:relative tpl:mx-auto tpl:flex tpl:justify-center tpl:rounded-lg\"\n :style=\"{\n width: `${stageWidth}px`,\n maxWidth: 'calc(100% - 4 * var(--tpl-base-size))',\n minWidth: 'min-content',\n boxShadow: darkMode ? 'none' : 'var(--tpl-shadow-xl)',\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <!-- Background layer — holds the email bg and the dark-preview filter,\n spanning the full stage (content + gutters). Filter on this leaf\n layer (no descendants) does not create a containing block / stacking\n context that would trap block chrome (action bar, indicators) inside\n the wrapper. The filter has its own transition so the canvas fades\n smoothly between modes. -->\n <div\n class=\"tpl-canvas-bg tpl:absolute tpl:inset-0 tpl:rounded-lg tpl:pointer-events-none\"\n :style=\"{\n backgroundColor: displaySettings.backgroundColor,\n ...(darkMode ? { filter: 'invert(1) hue-rotate(180deg)' } : {}),\n transition: 'filter 300ms ease',\n }\"\n />\n <!-- CONTENT COLUMN — the email content at its true width, centered in the\n stage. A full-width section fills this column but not the surrounding\n gutters, so the global background remains visible beside it. -->\n <div\n data-testid=\"canvas-wrapper\"\n role=\"region\"\n :aria-label=\"t.landmarks.canvas\"\n class=\"tpl-canvas-wrapper tpl:relative\"\n :style=\"{\n width: `${viewportWidth}px`,\n transition: EMAIL_FRAME_WIDTH_TRANSITION,\n }\"\n >\n <div\n class=\"tpl-canvas tpl:relative tpl:rounded-lg\"\n :lang=\"contentLang\"\n :dir=\"contentDir\"\n :class=\"{\n 'tpl-canvas--dark-mode': darkMode,\n 'tpl-preview-mode': previewMode,\n }\"\n :style=\"canvasStyle\"\n @click=\"handleCanvasClick\"\n >\n <!-- Preview resolution. The skeleton shows only on a *first* resolve —\n `isInitialResolve` — so switching recipient or reopening keeps the\n last good preview on screen instead of flashing over it. -->\n <div\n v-if=\"previewResolution?.isInitialResolve.value\"\n role=\"status\"\n aria-busy=\"true\"\n data-testid=\"preview-resolution-loading\"\n class=\"tpl:flex tpl:flex-col tpl:gap-3 tpl:p-6\"\n >\n <span class=\"tpl:sr-only\">{{ t.previewResolution.resolving }}</span>\n <div\n v-for=\"n in 3\"\n :key=\"n\"\n aria-hidden=\"true\"\n class=\"tpl-pulse tpl:h-16 tpl:rounded-md tpl:bg-[var(--tpl-bg-hover)]\"\n ></div>\n </div>\n\n <!-- Resolution failed: the unresolved template still renders below, so\n the preview degrades rather than disappearing. -->\n <p\n v-else-if=\"previewResolution?.hasFailed.value\"\n role=\"status\"\n data-testid=\"preview-resolution-failed\"\n class=\"tpl:mx-6 tpl:mt-4 tpl:rounded-md tpl:px-3 tpl:py-2 tpl:text-xs tpl:text-[var(--tpl-text-muted)] tpl:bg-[var(--tpl-bg-hover)]\"\n >\n {{ t.previewResolution.failed }}\n </p>\n\n <!-- `draggable` names what to leave out, the empty-state content, not\n the canvas's own item class: Sortable indexes a cross-list drop in\n the receiving list with the sending list's `draggable`, and a\n canvas-only class matches nothing in a section column, which\n would drop every canvas block at the column's top. The `>` keeps\n hit-testing on the canvas's direct children. -->\n <VueDraggable\n v-show=\"!previewResolution?.isInitialResolve.value\"\n v-model=\"blocks\"\n group=\"blocks\"\n :animation=\"150\"\n ghost-class=\"tpl-ghost\"\n drag-class=\"tpl-dragging\"\n handle=\".tpl-block-btn\"\n :invert-swap=\"true\"\n :inverted-swap-threshold=\"0.65\"\n :disabled=\"previewMode\"\n :draggable=\"'>:not(.tpl-canvas-empty-content)'\"\n :force-fallback=\"true\"\n :class=\"[\n 'tpl-canvas-blocks',\n isEmptyCanvas\n ? 'tpl-canvas-empty tpl:m-6 tpl:flex tpl:min-h-[400px] tpl:flex-col tpl:items-center tpl:justify-center tpl:rounded-xl tpl:border-2 tpl:border-dashed tpl:px-10 tpl:py-12 tpl:text-center tpl:bg-[var(--tpl-bg-elevated)] tpl:font-[var(--tpl-font-family)] tpl:transition-colors'\n : '',\n isEmptyCanvas && isDragOverEmpty\n ? 'tpl-canvas-empty--drag-over tpl:border-[var(--tpl-primary-hover)] tpl:bg-[var(--tpl-primary-light)]'\n : '',\n isEmptyCanvas && !isDragOverEmpty\n ? 'tpl:border-[var(--tpl-primary)]'\n : '',\n ]\"\n @update=\"\n (event) => updateBlockList(editor, blocks, undefined, 0, event)\n \"\n @dragenter=\"handleEmptyDragEnter\"\n @dragleave=\"handleEmptyDragLeave\"\n @drop=\"handleEmptyDrop\"\n >\n <!-- Empty-state content: rendered INSIDE the draggable so the whole\n dashed box is the drop zone, but excluded from sortable items by\n the `draggable` selector above. -->\n <div\n v-if=\"isEmptyCanvas\"\n class=\"tpl-canvas-empty-content tpl:flex tpl:flex-col tpl:items-center\"\n >\n <div\n class=\"tpl-canvas-empty-icon tpl:mb-4 tpl:text-[var(--tpl-primary)]\"\n >\n <SquarePlus :size=\"48\" :stroke-width=\"1\" />\n </div>\n <p\n class=\"tpl-canvas-empty-title tpl:m-0 tpl:mb-2 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-primary)]\"\n >\n {{ t.canvas.noBlocks }}\n </p>\n <p\n class=\"tpl-canvas-empty-text tpl:m-0 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.canvas.dragHint }}\n </p>\n <p\n v-if=\"canChat\"\n class=\"tpl:m-0 tpl:mt-2 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.chatHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-chat\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"caps.ai?.open('chat')\"\n >\n <Sparkles :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.menu.chat }}\n </button>\n {{ t.ai.canvas.chatHintSuffix }}\n </p>\n <p\n v-if=\"canImport\"\n class=\"tpl:m-0 tpl:mt-4 tpl:flex tpl:flex-wrap tpl:items-center tpl:justify-center tpl:gap-x-1 tpl:gap-y-0.5 tpl:text-sm tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ t.ai.canvas.importHint }}\n <button\n type=\"button\"\n data-testid=\"canvas-ai-import\"\n class=\"tpl:inline-flex tpl:shrink-0 tpl:cursor-pointer tpl:items-center tpl:gap-1 tpl:whitespace-nowrap tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-2 tpl:py-0.5 tpl:text-sm tpl:font-semibold tpl:transition-colors tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary-hover)]\"\n @click=\"pickImport\"\n >\n <ImageUp :size=\"14\" :stroke-width=\"2\" aria-hidden=\"true\" />\n {{ t.ai.import.menu }}\n </button>\n <input\n ref=\"importInput\"\n type=\"file\"\n multiple\n accept=\"image/png,image/jpeg,image/webp,image/gif,application/pdf\"\n hidden\n @change=\"importPicked\"\n />\n </p>\n </div>\n <div\n v-for=\"block in blocks\"\n :key=\"block.id\"\n class=\"tpl-block-item\"\n v-show=\"\n appliesConditionFilter === false ||\n !conditionPreview?.isHidden(block.id)\n \"\n >\n <div class=\"tpl:relative\">\n <component\n v-if=\"block.type === 'wrapper'\"\n :is=\"getBlockComponent(block)\"\n :block=\"block\"\n :viewport=\"viewport\"\n />\n <BlockWrapper\n v-else\n :block=\"block\"\n :display-block=\"displayBlock(block)\"\n :is-selected=\"\n !previewMode &&\n !isPicking &&\n selectedBlockId === block.id &&\n !isLockedByOther(block.id)\n \"\n :picked=\"isPickedBlock(block.id)\"\n :viewport=\"viewport\"\n :preview-mode=\"previewMode\"\n @select=\"handleBlockSelect(block.id)\"\n >\n <component\n :is=\"getBlockComponent(block)\"\n :block=\"displayBlock(block)\"\n v-bind=\"\n block.type === 'section' ? { sourceBlock: block } : {}\n \"\n :viewport=\"viewport\"\n @fetch-data=\"handleFetchData(block, $event)\"\n @update=\"\n (updates: Partial<Block>) =>\n editor.updateBlock(block.id, updates)\n \"\n />\n </BlockWrapper>\n </div>\n </div>\n </VueDraggable>\n </div>\n </div>\n </div>\n</template>\n\n<style scoped>\n/* Dark-mode preview: invert only the outermost `.tpl-email-surface` — a\n block's box, a section's wrapper frame, or a layout band. Surfaces nest\n (child blocks inside a section, a box inside its frame, the whole email\n inside a band), and a filter at every level would compound and cancel\n out, so `:not(...)` keeps the inversion single-pass. Block chrome (action\n bar, indicators, overlays) lives outside every surface and is therefore\n never filtered — no counter-filter / toggle flicker. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface:not(.tpl-email-surface *)) {\n filter: invert(1) hue-rotate(180deg);\n}\n:deep(.tpl-email-surface) {\n transition: filter 300ms ease;\n}\n\n/* Counter-invert images so they look normal inside the inverted email\n surface (canonical CSS-filter dark-mode trick). */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface img) {\n filter: invert(1) hue-rotate(180deg);\n}\n\n/* Background photos get the same counter-invert. A filter on the host would\n also hit the content painted over it, so the photo moves to a `::before`\n beneath that content, painted from `--tpl-block-bg-layer`\n (`getBackgroundImageStyle`). Every host is a surface or sits inside one, so\n every host is under exactly one inversion. `isolation` keeps the\n `z-index: -1` layer above the host's background colour wherever the host\n isn't the filtered surface itself. */\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image),\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image) {\n position: relative;\n isolation: isolate;\n background-image: none !important;\n}\n.tpl-canvas--dark-mode :deep(.tpl-email-surface.tpl-has-bg-image)::before,\n.tpl-canvas--dark-mode :deep(.tpl-email-surface .tpl-has-bg-image)::before {\n content: \"\";\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n pointer-events: none;\n background: var(--tpl-block-bg-layer, none);\n filter: invert(1) hue-rotate(180deg);\n}\n</style>\n","<script lang=\"ts\">\nimport { defineComponent, h, inject, type ComputedRef } from \"vue\";\nimport { CUSTOM_BLOCK_STYLESHEETS_KEY } from \"../keys\";\n\n/**\n * Renders one `<style>` tag per unique custom-block definition stylesheet\n * currently in use by the editor's content. Mounted near the top of\n * `Editor.vue`'s root template so the rules sit early in the document order\n * and apply to the canvas.\n *\n * In shadow-DOM mode (`shadowDom: true`, default) the styles scope to the\n * editor's shadow root. In light-DOM mode they leak globally, matching the\n * existing behavior of the editor's published `dist/style.css` in that mode\n * — no new global-leak vector.\n *\n * Why a render function instead of `<template>`: Vue's template compiler\n * treats `<style>` inside `<template>` as a side-effect tag and refuses to\n * emit it in strict client-render compilation paths (notably the one used\n * by `vue-tsc` and Vitest's Vue plugin). The render function below\n * bypasses the template compiler entirely and produces the same DOM at\n * runtime — and `innerHTML` on a `<style>` element sets the CSS rules\n * directly, no escape/parse pass between authoring and the cssom.\n */\nexport default defineComponent({\n name: \"CustomBlockStylesheets\",\n setup() {\n const stylesheets = inject<ComputedRef<string[]> | null>(\n CUSTOM_BLOCK_STYLESHEETS_KEY,\n null,\n );\n\n return () => {\n if (!stylesheets) return null;\n return stylesheets.value.map((css, i) =>\n h(\"style\", {\n key: i,\n \"data-tpl-custom-block-stylesheet\": \"\",\n innerHTML: css,\n }),\n );\n };\n },\n});\n</script>\n","<script lang=\"ts\">\nimport { defineComponent, h, inject, type ComputedRef } from \"vue\";\nimport { CUSTOM_BLOCK_STYLESHEETS_KEY } from \"../keys\";\n\n/**\n * Renders one `<style>` tag per unique custom-block definition stylesheet\n * currently in use by the editor's content. Mounted near the top of\n * `Editor.vue`'s root template so the rules sit early in the document order\n * and apply to the canvas.\n *\n * In shadow-DOM mode (`shadowDom: true`, default) the styles scope to the\n * editor's shadow root. In light-DOM mode they leak globally, matching the\n * existing behavior of the editor's published `dist/style.css` in that mode\n * — no new global-leak vector.\n *\n * Why a render function instead of `<template>`: Vue's template compiler\n * treats `<style>` inside `<template>` as a side-effect tag and refuses to\n * emit it in strict client-render compilation paths (notably the one used\n * by `vue-tsc` and Vitest's Vue plugin). The render function below\n * bypasses the template compiler entirely and produces the same DOM at\n * runtime — and `innerHTML` on a `<style>` element sets the CSS rules\n * directly, no escape/parse pass between authoring and the cssom.\n */\nexport default defineComponent({\n name: \"CustomBlockStylesheets\",\n setup() {\n const stylesheets = inject<ComputedRef<string[]> | null>(\n CUSTOM_BLOCK_STYLESHEETS_KEY,\n null,\n );\n\n return () => {\n if (!stylesheets) return null;\n return stylesheets.value.map((css, i) =>\n h(\"style\", {\n key: i,\n \"data-tpl-custom-block-stylesheet\": \"\",\n innerHTML: css,\n }),\n );\n };\n },\n});\n</script>\n","/**\n * Filters and reorders a candidate list of block-palette items against a\n * consumer-supplied `paletteBlocks` allowlist.\n *\n * Each `paletteBlocks` entry is a block-type key that must match a candidate's\n * `type`: a bare built-in type (e.g. `\"image\"`) or a prefixed custom type\n * (e.g. `\"custom:qrcode\"`). `\"hero\"` is a shortcut, not a block type: it\n * inserts a one-column section in hero mode with starter content. The\n * result's `items` contains exactly the candidates named in `paletteBlocks`, in\n * that order. Entries with no matching candidate (a typo, an unregistered\n * custom block, or a plan-gated built-in like `countdown` outside Cloud) are\n * collected into `unknown` so the caller can warn and skip. A type listed more\n * than once is rendered once.\n *\n * When `paletteBlocks` is `undefined` or empty the candidates are returned\n * unchanged (the default full palette). An empty allowlist is treated as \"not\n * configured\" rather than \"hide everything\", since a zero-block palette is\n * almost always a mistake.\n */\nexport function resolvePaletteBlocks<T extends { type: string }>(\n candidates: T[],\n paletteBlocks: string[] | undefined,\n): { items: T[]; unknown: string[] } {\n if (!paletteBlocks || paletteBlocks.length === 0) {\n return { items: candidates, unknown: [] };\n }\n\n const byType = new Map(candidates.map((c) => [c.type, c]));\n const items: T[] = [];\n const unknown: string[] = [];\n const seen = new Set<string>();\n\n for (const entry of paletteBlocks) {\n if (seen.has(entry)) continue;\n seen.add(entry);\n\n const candidate = byType.get(entry);\n if (candidate) {\n items.push(candidate);\n } else {\n unknown.push(entry);\n }\n }\n\n return { items, unknown };\n}\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type { Block, BlockType } from \"@templatical/types\";\nimport { createBlock, createCustomBlock } from \"@templatical/types\";\nimport { Package } from \"@lucide/vue\";\nimport { computed, inject, onScopeDispose, ref, watch } from \"vue\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport CustomBlockIcon from \"./CustomBlockIcon.vue\";\nimport { blockTypeIcons } from \"../utils/blockTypeIcons\";\nimport { getBlockTypeLabel } from \"../utils/blockTypeLabels\";\nimport { createHeroSection, HERO_PALETTE_TYPE } from \"../utils/heroShortcut\";\nimport { resolvePaletteBlocks } from \"../utils/resolvePaletteBlocks\";\nimport { insertBlockAtSelection } from \"../utils/insertBlockAtSelection\";\nimport { useScrollToBlock } from \"../composables/useScrollToBlock\";\nimport { logger } from \"../utils/logger\";\nimport {\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n PALETTE_BLOCKS_KEY,\n BLOCK_DEFAULTS_KEY,\n CAPABILITIES_KEY,\n EDITOR_KEY,\n} from \"../keys\";\n\ninterface BlockTypeItem {\n type: BlockType | string;\n label: string;\n isCustom?: boolean;\n icon?: string;\n}\n\nconst { t, format } = useI18n();\nconst customBlockDefinitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst paletteBlocks = inject(PALETTE_BLOCKS_KEY, undefined);\nconst blockDefaults = inject(BLOCK_DEFAULTS_KEY, undefined);\nconst editor = inject(EDITOR_KEY, null);\nconst scrollToBlock = useScrollToBlock();\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n// Availability only — deliberately NOT `count > 0`. Gating on the loaded count\n// meant the entry appeared only once the consumer's `list()` resolved, so a slow\n// endpoint shifted the rail mid-session and an empty library hid the feature\n// entirely. The list is now fetched when the browser opens instead.\nconst showSavedBlocksSection = computed(\n () => caps.savedBlocks?.isAvailable.value === true,\n);\n\nconst isExpanded = ref(false);\nconst isDragging = ref(false);\nconst railEl = ref<HTMLElement | null>(null);\n\n// Sortable's default is 0, and the `fallbackTolerance &&` guard treats 0 as\n// \"no threshold\", so any pointer movement starts a force-fallback drag. The\n// palette button is also the click-to-insert control, and a drag that jitters\n// onto the canvas then clicks it inserts a second block (#817). 3–5px is\n// Sortable's own range for clickable items. 4 matches the e2e nudge in\n// `pointerDriveFromPalette` (`startX + 4`): Sortable starts the drag when\n// movement is not strictly below this value, so that nudge still counts.\nconst PALETTE_DRAG_TOLERANCE_PX = 4;\n\n// `start` means a drag actually began. A stationary click emits `choose` +\n// `unchoose` and never `start`, so this must not key off `isDragging` — that\n// flag flips at pointerdown. Cleared on a macrotask after `end`: `end` runs\n// inside mouseup, and the click is dispatched later in that same turn, after\n// microtasks. `nextTick` / `queueMicrotask` would drop the flag first and the\n// duplicate would land. `unchoose` fires before `end` on a completed drag, so\n// clearing there has the same hole.\nlet suppressPaletteClick = false;\nlet suppressPaletteClickTimer = 0;\n\nonScopeDispose(() => {\n window.clearTimeout(suppressPaletteClickTimer);\n});\n\n// `:focus-visible`, never `:focus`: a mouse click leaves the clicked palette\n// button focused, so a plain `:focus` test would pin the rail open from the\n// first click-to-insert onward — the very symptom this rail already had for\n// another reason (#568). Keyboard focus does keep it open, because collapsing\n// hides the label of the entry the user has focused.\nfunction hasKeyboardFocusInRail(): boolean {\n try {\n return railEl.value?.querySelector(\":focus-visible\") != null;\n } catch {\n // Firefox <85 / Safari <15.4 — reachable on the `shadowDom: false` tier,\n // whose browser floor predates the selector — throw on it. Reading that\n // as \"no keyboard focus\" keeps the collapse working there.\n return false;\n }\n}\n\nfunction handleSidebarLeave(): void {\n // Don't collapse while a Sortable drag is in progress. If the sidebar\n // shrinks (200px → 48px) DURING the drag's threshold-to-dragStarted\n // window, `dragEl.getBoundingClientRect()` returns a mid-transition\n // rect when Sortable's `_appendGhost` runs — the fallback ghost gets\n // stamped with that wrong rect and ends up visibly offset from the\n // cursor for the rest of the drag. Cleared on drag-end.\n if (isDragging.value) return;\n if (hasKeyboardFocusInRail()) return;\n isExpanded.value = false;\n}\n\nfunction handleDragChoose(): void {\n // `choose` fires synchronously inside Sortable's `_onTapStart` at\n // pointerdown, BEFORE any pointermove or mouseleave. `start` would be\n // too late — it fires only after the threshold-move dispatches\n // `_dragStarted`, by which time mouseleave may already have flipped\n // `isExpanded` and the sidebar may be mid-collapse.\n isDragging.value = true;\n}\n\nfunction handleDragUnchoose(): void {\n // `end` is not the counterpart of `choose` — Sortable gates it on\n // `Sortable.active`, which only `_dragStarted` sets, so a click on a palette\n // entry emits `choose` + `unchoose` and no `end` at all. Clearing the guard\n // only in `handleDragEnd` therefore latches it true on the first click and\n // `handleSidebarLeave` bails forever after: the rail stays expanded until\n // some later drag happens to complete (#568). `unchoose` fires on every\n // release, at drop time — long after `_appendGhost` captured its rect — so\n // it cannot re-open the race `handleDragChoose` guards.\n isDragging.value = false;\n}\n\nfunction handleDragStart(): void {\n // Click suppression only. The rail-width guard stays on `choose`: `start`\n // is after `_dragStarted`, which is too late to stop the collapse race.\n suppressPaletteClick = true;\n window.clearTimeout(suppressPaletteClickTimer);\n}\n\nfunction handleRailFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget;\n if (next instanceof Node && railEl.value?.contains(next)) return;\n // Inserting selects the new block and moves focus off the palette button.\n // The pointer is often still on the rail. Collapsing here shrinks the\n // label strip out from under it, and the next press opens the rail\n // instead of inserting (#818).\n if (railEl.value?.matches(\":hover\")) return;\n isExpanded.value = false;\n}\n\nfunction clearFallbackClickSwallow(): void {\n // A fallback drag sets Sortable's ignoreNextClick. Sortable clears it by\n // swallowing the next click. A slip that stays on the palette cancels\n // mouseup, so that click is never dispatched and the author's next press\n // is the one swallowed. This click is aimed at the document, not a palette\n // button, so it spends the swallow without inserting. The button's own\n // click stays suppressed until the macrotask in handleDragEnd.\n railEl.value?.ownerDocument.dispatchEvent(\n new MouseEvent(\"click\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n }),\n );\n}\n\nfunction handleDragEnd(): void {\n isDragging.value = false;\n // A canvas drop ends outside the rail, and `mouseleave` never fires for\n // that path: `handleSidebarLeave` bailed while `isDragging` was true.\n // Collapse only then. A press that slipped into a fallback drag and\n // released still on the palette must leave the rail open (#818), including\n // when focusout already collapsed it earlier in this same pointerup.\n // `:hover` matches the rail while the pointer is over a button inside it.\n // The fallback ghost has `pointer-events: none`, so it does not take the hit.\n if (railEl.value?.matches(\":hover\")) {\n isExpanded.value = true;\n clearFallbackClickSwallow();\n } else {\n isExpanded.value = false;\n }\n window.clearTimeout(suppressPaletteClickTimer);\n suppressPaletteClickTimer = window.setTimeout(() => {\n suppressPaletteClick = false;\n }, 0);\n}\n\nconst builtInBlockTypeOrder: string[] = [\n \"section\",\n HERO_PALETTE_TYPE,\n \"image\",\n \"title\",\n \"paragraph\",\n \"button\",\n \"divider\",\n \"video\",\n \"social\",\n \"menu\",\n \"table\",\n \"spacer\",\n \"html\",\n];\n\nconst builtInBlockTypes = computed<BlockTypeItem[]>(() => {\n const types: BlockTypeItem[] = builtInBlockTypeOrder.map((type) => ({\n type,\n label: getBlockTypeLabel(type, t),\n }));\n\n // Countdown requires Templatical Cloud for server-side GIF rendering\n if (caps.plan) {\n types.splice(-1, 0, {\n type: \"countdown\",\n label: getBlockTypeLabel(\"countdown\", t),\n });\n }\n\n return types;\n});\n\nconst customBlockItems = computed<BlockTypeItem[]>(() => {\n return customBlockDefinitions.map((def) => ({\n type: `custom:${def.type}`,\n label: def.name,\n isCustom: true,\n icon: def.icon,\n }));\n});\n\nconst candidateBlockTypes = computed<BlockTypeItem[]>(() => [\n ...builtInBlockTypes.value,\n ...customBlockItems.value,\n]);\n\n// Apply the consumer's `paletteBlocks` allowlist + order when provided; otherwise show\n// the full default palette. Filtering only affects the palette — the block\n// registry stays complete, so existing content using a hidden type still renders.\nconst resolvedPalette = computed(() =>\n resolvePaletteBlocks(candidateBlockTypes.value, paletteBlocks),\n);\n\nconst blockTypes = computed<BlockTypeItem[]>(() => resolvedPalette.value.items);\n\n// Warn once per unknown `paletteBlocks` entry (a typo, an unregistered custom block, or\n// `countdown` outside a Cloud plan). Done in a watcher rather than inside the\n// computed so recomputes don't repeat the warning.\nconst warnedPaletteEntries = new Set<string>();\nwatch(\n () => resolvedPalette.value.unknown,\n (unknown) => {\n for (const entry of unknown) {\n if (warnedPaletteEntries.has(entry)) continue;\n warnedPaletteEntries.add(entry);\n logger.warn(\n `config.paletteBlocks: \"${entry}\" is not a built-in or registered custom block ` +\n `(use the \"custom:\" prefix for custom blocks) — skipping it in the palette.`,\n );\n }\n },\n { immediate: true },\n);\n\nfunction createBlockFromItem(item: BlockTypeItem): Block {\n if (item.isCustom) {\n const customType = item.type.replace(\"custom:\", \"\");\n const definition = customBlockDefinitions.find(\n (d) => d.type === customType,\n );\n if (definition) {\n return createCustomBlock(definition);\n }\n }\n\n // A shortcut, not a block type: a hero-mode section with starter content.\n if (item.type === HERO_PALETTE_TYPE) {\n return createHeroSection(blockDefaults?.value, t.blockDefaults.paragraph);\n }\n\n // `.value` at insert time, never destructured at setup: the recipient-facing\n // half of these defaults tracks the template's own content language, which\n // the author can change while the palette is mounted.\n return createBlock(item.type as BlockType, blockDefaults?.value);\n}\n\nfunction insertBlockFromItem(item: BlockTypeItem): void {\n if (!editor) return;\n const block = createBlockFromItem(item);\n // Land below the selection, not at the end: on a template taller than the\n // viewport an appended block is below the fold, and the canvas does not\n // follow on its own, so the click reads as a no-op (issue #568).\n // Selecting is not visible by itself, and the append fallback still lands\n // off-screen — the canvas has to follow either way.\n if (insertBlockAtSelection(editor, block)) scrollToBlock(block.id);\n}\n\nfunction handlePaletteClick(item: BlockTypeItem): void {\n // The drag element is this button. Sortable moves it into the canvas drop\n // slot and clears `ignoreNextClick` inside `_onDragOver` once the pointer\n // enters that list, so the click after mouseup still reaches this handler\n // and inserts a second block (#817).\n if (suppressPaletteClick) return;\n insertBlockFromItem(item);\n}\n\nfunction handlePaletteKeydown(event: KeyboardEvent, item: BlockTypeItem): void {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n insertBlockFromItem(item);\n }\n}\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 48px the canvas body leaves\n for the collapsed rail (`left-12`). -->\n <aside\n ref=\"railEl\"\n :aria-label=\"t.sidebarNav.palette\"\n class=\"tpl-sidebar-rail tpl:absolute tpl:top-14 tpl:bottom-0 tpl:left-0 tpl:z-40 tpl:box-border tpl:flex tpl:flex-col tpl:overflow-hidden\"\n :style=\"{\n width: isExpanded ? '200px' : '48px',\n backgroundColor: 'var(--tpl-bg-elevated)',\n borderRight: '1px solid var(--tpl-border)',\n boxShadow: isExpanded ? 'var(--tpl-shadow-lg)' : 'none',\n transition:\n 'width 200ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 200ms cubic-bezier(0.16, 1, 0.3, 1)',\n }\"\n @mouseenter=\"isExpanded = true\"\n @mouseleave=\"handleSidebarLeave\"\n @focusin=\"isExpanded = true\"\n @focusout=\"handleRailFocusOut\"\n >\n <!-- Saved blocks browser trigger. Needs the feature to be available (a\n provider configured, and in Cloud the plan to allow it). -->\n <div\n v-if=\"showSavedBlocksSection\"\n class=\"tpl:border-b tpl:px-1 tpl:pb-1 tpl:border-[var(--tpl-border)]\"\n >\n <button\n type=\"button\"\n :aria-label=\"t.sidebarNav.browseSavedBlocks\"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)]\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"caps.savedBlocks?.openBrowser()\"\n >\n <Package :size=\"20\" :stroke-width=\"1.5\" class=\"tpl:shrink-0\" />\n <!-- No `flex-1`: the rail inherits `text-align: center`, so a label\n stretched to fill the row centres its glyphs and sits visibly\n further right than the palette labels below it. Shrink-to-fit\n matches them exactly. -->\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ t.savedBlocks.title }}\n </span>\n </button>\n </div>\n <!-- The palette is the rail's scroll region: `flex-1` makes it fill the\n height left by the (optional) modules trigger, `min-h-0` lets it\n shrink below its content so `overflow-y-auto` engages. Without this\n the rail's `overflow-hidden` clips items below the fold on short\n viewports with no way to reach them (#231). -->\n <VueDraggable\n :model-value=\"blockTypes\"\n :group=\"{ name: 'blocks', pull: 'clone', put: false }\"\n :clone=\"createBlockFromItem\"\n :sort=\"false\"\n :animation=\"150\"\n :force-fallback=\"true\"\n :fallback-tolerance=\"PALETTE_DRAG_TOLERANCE_PX\"\n class=\"tpl:flex tpl:min-h-0 tpl:flex-1 tpl:flex-col tpl:gap-0.5 tpl:overflow-y-auto tpl:p-1\"\n @choose=\"handleDragChoose\"\n @start=\"handleDragStart\"\n @unchoose=\"handleDragUnchoose\"\n @end=\"handleDragEnd\"\n >\n <button\n v-for=\"blockType in blockTypes\"\n :key=\"blockType.type\"\n type=\"button\"\n :data-palette-type=\"blockType.type\"\n :aria-label=\"\n format(t.sidebarNav.insertBlock, { block: blockType.label })\n \"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:shrink-0 tpl:cursor-grab tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)] tpl:active:cursor-grabbing\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"handlePaletteClick(blockType)\"\n @keydown=\"handlePaletteKeydown($event, blockType)\"\n >\n <div\n class=\"tpl:flex tpl:shrink-0 tpl:items-center tpl:justify-center tpl:transition-transform tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:scale-105\"\n >\n <component\n :is=\"blockTypeIcons[blockType.type]\"\n v-if=\"blockTypeIcons[blockType.type]\"\n :size=\"20\"\n :stroke-width=\"1.5\"\n />\n <CustomBlockIcon\n v-else-if=\"blockType.isCustom\"\n :icon=\"blockType.icon\"\n :size=\"20\"\n />\n </div>\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ blockType.label }}\n </span>\n </button>\n </VueDraggable>\n </aside>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport type { Block, BlockType } from \"@templatical/types\";\nimport { createBlock, createCustomBlock } from \"@templatical/types\";\nimport { Package } from \"@lucide/vue\";\nimport { computed, inject, onScopeDispose, ref, watch } from \"vue\";\nimport { VueDraggable } from \"vue-draggable-plus\";\nimport CustomBlockIcon from \"./CustomBlockIcon.vue\";\nimport { blockTypeIcons } from \"../utils/blockTypeIcons\";\nimport { getBlockTypeLabel } from \"../utils/blockTypeLabels\";\nimport { createHeroSection, HERO_PALETTE_TYPE } from \"../utils/heroShortcut\";\nimport { resolvePaletteBlocks } from \"../utils/resolvePaletteBlocks\";\nimport { insertBlockAtSelection } from \"../utils/insertBlockAtSelection\";\nimport { useScrollToBlock } from \"../composables/useScrollToBlock\";\nimport { logger } from \"../utils/logger\";\nimport {\n CUSTOM_BLOCK_DEFINITIONS_KEY,\n PALETTE_BLOCKS_KEY,\n BLOCK_DEFAULTS_KEY,\n CAPABILITIES_KEY,\n EDITOR_KEY,\n} from \"../keys\";\n\ninterface BlockTypeItem {\n type: BlockType | string;\n label: string;\n isCustom?: boolean;\n icon?: string;\n}\n\nconst { t, format } = useI18n();\nconst customBlockDefinitions = inject(CUSTOM_BLOCK_DEFINITIONS_KEY, []);\nconst paletteBlocks = inject(PALETTE_BLOCKS_KEY, undefined);\nconst blockDefaults = inject(BLOCK_DEFAULTS_KEY, undefined);\nconst editor = inject(EDITOR_KEY, null);\nconst scrollToBlock = useScrollToBlock();\n\nconst caps = inject(CAPABILITIES_KEY, {});\n\n// Availability only — deliberately NOT `count > 0`. Gating on the loaded count\n// meant the entry appeared only once the consumer's `list()` resolved, so a slow\n// endpoint shifted the rail mid-session and an empty library hid the feature\n// entirely. The list is now fetched when the browser opens instead.\nconst showSavedBlocksSection = computed(\n () => caps.savedBlocks?.isAvailable.value === true,\n);\n\nconst isExpanded = ref(false);\nconst isDragging = ref(false);\nconst railEl = ref<HTMLElement | null>(null);\n\n// Sortable's default is 0, and the `fallbackTolerance &&` guard treats 0 as\n// \"no threshold\", so any pointer movement starts a force-fallback drag. The\n// palette button is also the click-to-insert control, and a drag that jitters\n// onto the canvas then clicks it inserts a second block (#817). 3–5px is\n// Sortable's own range for clickable items. 4 matches the e2e nudge in\n// `pointerDriveFromPalette` (`startX + 4`): Sortable starts the drag when\n// movement is not strictly below this value, so that nudge still counts.\nconst PALETTE_DRAG_TOLERANCE_PX = 4;\n\n// `start` means a drag actually began. A stationary click emits `choose` +\n// `unchoose` and never `start`, so this must not key off `isDragging` — that\n// flag flips at pointerdown. Cleared on a macrotask after `end`: `end` runs\n// inside mouseup, and the click is dispatched later in that same turn, after\n// microtasks. `nextTick` / `queueMicrotask` would drop the flag first and the\n// duplicate would land. `unchoose` fires before `end` on a completed drag, so\n// clearing there has the same hole.\nlet suppressPaletteClick = false;\nlet suppressPaletteClickTimer = 0;\n\nonScopeDispose(() => {\n window.clearTimeout(suppressPaletteClickTimer);\n});\n\n// `:focus-visible`, never `:focus`: a mouse click leaves the clicked palette\n// button focused, so a plain `:focus` test would pin the rail open from the\n// first click-to-insert onward — the very symptom this rail already had for\n// another reason (#568). Keyboard focus does keep it open, because collapsing\n// hides the label of the entry the user has focused.\nfunction hasKeyboardFocusInRail(): boolean {\n try {\n return railEl.value?.querySelector(\":focus-visible\") != null;\n } catch {\n // Firefox <85 / Safari <15.4 — reachable on the `shadowDom: false` tier,\n // whose browser floor predates the selector — throw on it. Reading that\n // as \"no keyboard focus\" keeps the collapse working there.\n return false;\n }\n}\n\nfunction handleSidebarLeave(): void {\n // Don't collapse while a Sortable drag is in progress. If the sidebar\n // shrinks (200px → 48px) DURING the drag's threshold-to-dragStarted\n // window, `dragEl.getBoundingClientRect()` returns a mid-transition\n // rect when Sortable's `_appendGhost` runs — the fallback ghost gets\n // stamped with that wrong rect and ends up visibly offset from the\n // cursor for the rest of the drag. Cleared on drag-end.\n if (isDragging.value) return;\n if (hasKeyboardFocusInRail()) return;\n isExpanded.value = false;\n}\n\nfunction handleDragChoose(): void {\n // `choose` fires synchronously inside Sortable's `_onTapStart` at\n // pointerdown, BEFORE any pointermove or mouseleave. `start` would be\n // too late — it fires only after the threshold-move dispatches\n // `_dragStarted`, by which time mouseleave may already have flipped\n // `isExpanded` and the sidebar may be mid-collapse.\n isDragging.value = true;\n}\n\nfunction handleDragUnchoose(): void {\n // `end` is not the counterpart of `choose` — Sortable gates it on\n // `Sortable.active`, which only `_dragStarted` sets, so a click on a palette\n // entry emits `choose` + `unchoose` and no `end` at all. Clearing the guard\n // only in `handleDragEnd` therefore latches it true on the first click and\n // `handleSidebarLeave` bails forever after: the rail stays expanded until\n // some later drag happens to complete (#568). `unchoose` fires on every\n // release, at drop time — long after `_appendGhost` captured its rect — so\n // it cannot re-open the race `handleDragChoose` guards.\n isDragging.value = false;\n}\n\nfunction handleDragStart(): void {\n // Click suppression only. The rail-width guard stays on `choose`: `start`\n // is after `_dragStarted`, which is too late to stop the collapse race.\n suppressPaletteClick = true;\n window.clearTimeout(suppressPaletteClickTimer);\n}\n\nfunction handleRailFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget;\n if (next instanceof Node && railEl.value?.contains(next)) return;\n // Inserting selects the new block and moves focus off the palette button.\n // The pointer is often still on the rail. Collapsing here shrinks the\n // label strip out from under it, and the next press opens the rail\n // instead of inserting (#818).\n if (railEl.value?.matches(\":hover\")) return;\n isExpanded.value = false;\n}\n\nfunction clearFallbackClickSwallow(): void {\n // A fallback drag sets Sortable's ignoreNextClick. Sortable clears it by\n // swallowing the next click. A slip that stays on the palette cancels\n // mouseup, so that click is never dispatched and the author's next press\n // is the one swallowed. This click is aimed at the document, not a palette\n // button, so it spends the swallow without inserting. The button's own\n // click stays suppressed until the macrotask in handleDragEnd.\n railEl.value?.ownerDocument.dispatchEvent(\n new MouseEvent(\"click\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n }),\n );\n}\n\nfunction handleDragEnd(): void {\n isDragging.value = false;\n // A canvas drop ends outside the rail, and `mouseleave` never fires for\n // that path: `handleSidebarLeave` bailed while `isDragging` was true.\n // Collapse only then. A press that slipped into a fallback drag and\n // released still on the palette must leave the rail open (#818), including\n // when focusout already collapsed it earlier in this same pointerup.\n // `:hover` matches the rail while the pointer is over a button inside it.\n // The fallback ghost has `pointer-events: none`, so it does not take the hit.\n if (railEl.value?.matches(\":hover\")) {\n isExpanded.value = true;\n clearFallbackClickSwallow();\n } else {\n isExpanded.value = false;\n }\n window.clearTimeout(suppressPaletteClickTimer);\n suppressPaletteClickTimer = window.setTimeout(() => {\n suppressPaletteClick = false;\n }, 0);\n}\n\nconst builtInBlockTypeOrder: string[] = [\n \"section\",\n HERO_PALETTE_TYPE,\n \"image\",\n \"title\",\n \"paragraph\",\n \"button\",\n \"divider\",\n \"video\",\n \"social\",\n \"menu\",\n \"table\",\n \"spacer\",\n \"html\",\n];\n\nconst builtInBlockTypes = computed<BlockTypeItem[]>(() => {\n const types: BlockTypeItem[] = builtInBlockTypeOrder.map((type) => ({\n type,\n label: getBlockTypeLabel(type, t),\n }));\n\n // Countdown requires Templatical Cloud for server-side GIF rendering\n if (caps.plan) {\n types.splice(-1, 0, {\n type: \"countdown\",\n label: getBlockTypeLabel(\"countdown\", t),\n });\n }\n\n return types;\n});\n\nconst customBlockItems = computed<BlockTypeItem[]>(() => {\n return customBlockDefinitions.map((def) => ({\n type: `custom:${def.type}`,\n label: def.name,\n isCustom: true,\n icon: def.icon,\n }));\n});\n\nconst candidateBlockTypes = computed<BlockTypeItem[]>(() => [\n ...builtInBlockTypes.value,\n ...customBlockItems.value,\n]);\n\n// Apply the consumer's `paletteBlocks` allowlist + order when provided; otherwise show\n// the full default palette. Filtering only affects the palette — the block\n// registry stays complete, so existing content using a hidden type still renders.\nconst resolvedPalette = computed(() =>\n resolvePaletteBlocks(candidateBlockTypes.value, paletteBlocks),\n);\n\nconst blockTypes = computed<BlockTypeItem[]>(() => resolvedPalette.value.items);\n\n// Warn once per unknown `paletteBlocks` entry (a typo, an unregistered custom block, or\n// `countdown` outside a Cloud plan). Done in a watcher rather than inside the\n// computed so recomputes don't repeat the warning.\nconst warnedPaletteEntries = new Set<string>();\nwatch(\n () => resolvedPalette.value.unknown,\n (unknown) => {\n for (const entry of unknown) {\n if (warnedPaletteEntries.has(entry)) continue;\n warnedPaletteEntries.add(entry);\n logger.warn(\n `config.paletteBlocks: \"${entry}\" is not a built-in or registered custom block ` +\n `(use the \"custom:\" prefix for custom blocks) — skipping it in the palette.`,\n );\n }\n },\n { immediate: true },\n);\n\nfunction createBlockFromItem(item: BlockTypeItem): Block {\n if (item.isCustom) {\n const customType = item.type.replace(\"custom:\", \"\");\n const definition = customBlockDefinitions.find(\n (d) => d.type === customType,\n );\n if (definition) {\n return createCustomBlock(definition);\n }\n }\n\n // A shortcut, not a block type: a hero-mode section with starter content.\n if (item.type === HERO_PALETTE_TYPE) {\n return createHeroSection(blockDefaults?.value, t.blockDefaults.paragraph);\n }\n\n // `.value` at insert time, never destructured at setup: the recipient-facing\n // half of these defaults tracks the template's own content language, which\n // the author can change while the palette is mounted.\n return createBlock(item.type as BlockType, blockDefaults?.value);\n}\n\nfunction insertBlockFromItem(item: BlockTypeItem): void {\n if (!editor) return;\n const block = createBlockFromItem(item);\n // Land below the selection, not at the end: on a template taller than the\n // viewport an appended block is below the fold, and the canvas does not\n // follow on its own, so the click reads as a no-op (issue #568).\n // Selecting is not visible by itself, and the append fallback still lands\n // off-screen — the canvas has to follow either way.\n if (insertBlockAtSelection(editor, block)) scrollToBlock(block.id);\n}\n\nfunction handlePaletteClick(item: BlockTypeItem): void {\n // The drag element is this button. Sortable moves it into the canvas drop\n // slot and clears `ignoreNextClick` inside `_onDragOver` once the pointer\n // enters that list, so the click after mouseup still reaches this handler\n // and inserts a second block (#817).\n if (suppressPaletteClick) return;\n insertBlockFromItem(item);\n}\n\nfunction handlePaletteKeydown(event: KeyboardEvent, item: BlockTypeItem): void {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n insertBlockFromItem(item);\n }\n}\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 48px the canvas body leaves\n for the collapsed rail (`left-12`). -->\n <aside\n ref=\"railEl\"\n :aria-label=\"t.sidebarNav.palette\"\n class=\"tpl-sidebar-rail tpl:absolute tpl:top-14 tpl:bottom-0 tpl:left-0 tpl:z-40 tpl:box-border tpl:flex tpl:flex-col tpl:overflow-hidden\"\n :style=\"{\n width: isExpanded ? '200px' : '48px',\n backgroundColor: 'var(--tpl-bg-elevated)',\n borderRight: '1px solid var(--tpl-border)',\n boxShadow: isExpanded ? 'var(--tpl-shadow-lg)' : 'none',\n transition:\n 'width 200ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 200ms cubic-bezier(0.16, 1, 0.3, 1)',\n }\"\n @mouseenter=\"isExpanded = true\"\n @mouseleave=\"handleSidebarLeave\"\n @focusin=\"isExpanded = true\"\n @focusout=\"handleRailFocusOut\"\n >\n <!-- Saved blocks browser trigger. Needs the feature to be available (a\n provider configured, and in Cloud the plan to allow it). -->\n <div\n v-if=\"showSavedBlocksSection\"\n class=\"tpl:border-b tpl:px-1 tpl:pb-1 tpl:border-[var(--tpl-border)]\"\n >\n <button\n type=\"button\"\n :aria-label=\"t.sidebarNav.browseSavedBlocks\"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)]\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"caps.savedBlocks?.openBrowser()\"\n >\n <Package :size=\"20\" :stroke-width=\"1.5\" class=\"tpl:shrink-0\" />\n <!-- No `flex-1`: the rail inherits `text-align: center`, so a label\n stretched to fill the row centres its glyphs and sits visibly\n further right than the palette labels below it. Shrink-to-fit\n matches them exactly. -->\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ t.savedBlocks.title }}\n </span>\n </button>\n </div>\n <!-- The palette is the rail's scroll region: `flex-1` makes it fill the\n height left by the (optional) modules trigger, `min-h-0` lets it\n shrink below its content so `overflow-y-auto` engages. Without this\n the rail's `overflow-hidden` clips items below the fold on short\n viewports with no way to reach them (#231). -->\n <VueDraggable\n :model-value=\"blockTypes\"\n :group=\"{ name: 'blocks', pull: 'clone', put: false }\"\n :clone=\"createBlockFromItem\"\n :sort=\"false\"\n :animation=\"150\"\n :force-fallback=\"true\"\n :fallback-tolerance=\"PALETTE_DRAG_TOLERANCE_PX\"\n class=\"tpl:flex tpl:min-h-0 tpl:flex-1 tpl:flex-col tpl:gap-0.5 tpl:overflow-y-auto tpl:p-1\"\n @choose=\"handleDragChoose\"\n @start=\"handleDragStart\"\n @unchoose=\"handleDragUnchoose\"\n @end=\"handleDragEnd\"\n >\n <button\n v-for=\"blockType in blockTypes\"\n :key=\"blockType.type\"\n type=\"button\"\n :data-palette-type=\"blockType.type\"\n :aria-label=\"\n format(t.sidebarNav.insertBlock, { block: blockType.label })\n \"\n class=\"tpl:flex tpl:h-10 tpl:w-full tpl:shrink-0 tpl:cursor-grab tpl:items-center tpl:gap-3 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:px-3 tpl:text-[var(--tpl-text-muted)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:bg-[var(--tpl-primary-light)] tpl:hover:text-[var(--tpl-primary)] tpl:active:cursor-grabbing\"\n :style=\"{\n justifyContent: isExpanded ? 'flex-start' : 'center',\n }\"\n @click=\"handlePaletteClick(blockType)\"\n @keydown=\"handlePaletteKeydown($event, blockType)\"\n >\n <div\n class=\"tpl:flex tpl:shrink-0 tpl:items-center tpl:justify-center tpl:transition-transform tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:scale-105\"\n >\n <component\n :is=\"blockTypeIcons[blockType.type]\"\n v-if=\"blockTypeIcons[blockType.type]\"\n :size=\"20\"\n :stroke-width=\"1.5\"\n />\n <CustomBlockIcon\n v-else-if=\"blockType.isCustom\"\n :icon=\"blockType.icon\"\n :size=\"20\"\n />\n </div>\n <span\n v-if=\"isExpanded\"\n class=\"tpl:truncate tpl:text-sm tpl:font-medium\"\n >\n {{ blockType.label }}\n </span>\n </button>\n </VueDraggable>\n </aside>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Toolbar and Template Settings are `defineAsyncComponent` behind the\n * `v-if`s that already gate them (a selected block, the Settings tab).\n * `defineAsyncComponent` fetches on first render, so a static import here\n * would pull ColorPicker, MergeTagInput, and every per-type toolbar into\n * the eager graph for every session. IssuesPanel in this file is the same\n * contract. Guarded by `tests/rightSidebarLazy.test.ts` and the\n * properties-panel cases in `cdn-chunk-granularity.test.ts` /\n * `bundle-topology.test.ts`.\n */\nimport { useI18n } from \"../composables/useI18n\";\nimport { TEMPLATE_LINT_KEY, TEMPLATE_SETTINGS_FIELDS_KEY } from \"../keys\";\nimport { ALL_TEMPLATE_SETTINGS_FIELDS } from \"../utils/templateSettingsFields\";\nimport type { Block, TemplateSettings } from \"@templatical/types\";\nimport { ListChecks, LayoutTemplate, PanelTop, Settings } from \"@lucide/vue\";\nimport { computed, defineAsyncComponent, inject, watch } from \"vue\";\n\nconst Toolbar = defineAsyncComponent(() => import(\"./Toolbar.vue\"));\nconst TemplateSettingsPanel = defineAsyncComponent(\n () => import(\"./TemplateSettings.vue\"),\n);\nconst IssuesPanel = defineAsyncComponent(\n () => import(\"./sidebar/IssuesPanel.vue\"),\n);\n\nconst props = defineProps<{\n selectedBlock: Block | null;\n settings: TemplateSettings;\n shiftedLeft?: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"update-block\", updates: Partial<Block>): void;\n (e: \"delete-block\"): void;\n (e: \"duplicate-block\"): void;\n (e: \"update-settings\", settings: Partial<TemplateSettings>): void;\n}>();\n\nconst { t } = useI18n();\n\nexport type RightSidebarTab = \"content\" | \"settings\" | \"issues\";\ntype Tab = RightSidebarTab;\n\n// `v-model:tab`: `Editor.vue` owns the tab. Without a parent binding it is local state.\nconst activeTab = defineModel<Tab>(\"tab\", { default: \"content\" });\n\nconst lint = inject(TEMPLATE_LINT_KEY, null);\n// `@templatical/quality` is an optional peer imported at mount. The tab renders\n// from the start, so apps that install it never see the tab pop in, and goes\n// once the import fails: without the package the panel has nothing to show.\nconst lintAvailable = computed(() => lint !== null && !lint.unavailable.value);\nconst issueCount = computed(() => lint?.issues.value.length ?? 0);\n\n// The tab follows the panel: with every setting excluded there is nothing for\n// it to open, and a tab onto an empty panel reads as a bug. Defaults to every\n// field, since the key is absent for a consumer who configured nothing.\nconst allowedSettingsFields = inject(\n TEMPLATE_SETTINGS_FIELDS_KEY,\n new Set(ALL_TEMPLATE_SETTINGS_FIELDS),\n);\nconst settingsEnabled = computed(() => allowedSettingsFields.size > 0);\n\nfunction tabClass(tab: Tab): string {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return \"tpl:flex-1 tpl:text-[var(--tpl-primary)]\";\n }\n return \"tpl:shrink-0 tpl:text-[var(--tpl-text-muted)] tpl:hover:text-[var(--tpl-text)]\";\n}\n\nfunction tabStyle(tab: Tab): Record<string, string> {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return {\n backgroundColor: \"var(--tpl-bg)\",\n // `-sm` is the step the shadow vocabulary assigns to a lifted control;\n // `-md` is dialog and side-panel depth, which overstates a 32px tab.\n boxShadow: \"var(--tpl-shadow-sm)\",\n };\n }\n return { backgroundColor: \"transparent\" };\n}\n\nwatch(\n () => props.selectedBlock?.id,\n (blockId) => {\n if (blockId) {\n activeTab.value = \"content\";\n }\n },\n);\n\n// The Issues tab can be picked while the quality import is in flight; when\n// that import then fails, the sidebar would otherwise show no panel at all.\nwatch(lintAvailable, (available) => {\n if (!available && activeTab.value === \"issues\") {\n activeTab.value = \"content\";\n }\n});\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 320px the canvas body leaves\n for this rail (`right-[320px]`); outside it, the rail covers the body's\n last pixel column, where the block toolbar's drag grip sits. -->\n <aside\n :aria-label=\"t.landmarks.rightSidebar\"\n class=\"tpl-right-sidebar tpl:absolute tpl:top-14 tpl:bottom-0 tpl:z-40 tpl:flex tpl:box-border tpl:w-[320px] tpl:flex-col tpl:bg-[var(--tpl-bg-elevated)] tpl:transition-all tpl:duration-200 tpl:border-l tpl:border-[var(--tpl-border)]\"\n :class=\"shiftedLeft ? 'tpl:right-[360px]' : 'tpl:right-0'\"\n >\n <div\n role=\"tablist\"\n class=\"tpl:relative tpl:flex tpl:gap-1 tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-active)] tpl:p-1.5\"\n >\n <button\n id=\"tpl-tab-content\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'content'\"\n aria-controls=\"tpl-tabpanel-content\"\n :aria-label=\"t.sidebar.content\"\n :title=\"t.sidebar.content\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('content')\"\n :style=\"tabStyle('content')\"\n @click=\"activeTab = 'content'\"\n >\n <PanelTop :size=\"14\" :stroke-width=\"2\" />\n <span v-if=\"activeTab === 'content'\">{{ t.sidebar.content }}</span>\n </button>\n <button\n v-if=\"settingsEnabled\"\n id=\"tpl-tab-settings\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'settings'\"\n aria-controls=\"tpl-tabpanel-settings\"\n :aria-label=\"t.sidebar.settings\"\n :title=\"t.sidebar.settings\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('settings')\"\n :style=\"tabStyle('settings')\"\n @click=\"activeTab = 'settings'\"\n >\n <Settings :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'settings'\">{{ t.sidebar.settings }}</span>\n </button>\n <button\n v-if=\"lintAvailable\"\n id=\"tpl-tab-issues\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'issues'\"\n aria-controls=\"tpl-tabpanel-issues\"\n :aria-label=\"t.issues.panelTabLabel\"\n :title=\"t.issues.panelTabLabel\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('issues')\"\n :style=\"tabStyle('issues')\"\n @click=\"activeTab = 'issues'\"\n >\n <ListChecks :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'issues'\">\n {{ t.issues.panelTabLabel }}\n </span>\n <span\n v-if=\"issueCount > 0\"\n class=\"tpl:ml-1 tpl:rounded-full tpl:bg-[var(--tpl-bg-hover)] tpl:px-1.5 tpl:text-[10px]\"\n >\n {{ issueCount }}\n </span>\n </button>\n </div>\n\n <div\n v-if=\"activeTab === 'content'\"\n id=\"tpl-tabpanel-content\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-content\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <Toolbar\n v-if=\"selectedBlock\"\n :block=\"selectedBlock\"\n @update=\"emit('update-block', $event)\"\n @delete=\"emit('delete-block')\"\n @duplicate=\"emit('duplicate-block')\"\n />\n <div\n v-else\n class=\"tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:px-6 tpl:py-10 tpl:text-center tpl:text-[var(--tpl-text-muted)]\"\n >\n <div class=\"tpl:mb-4 tpl:text-[var(--tpl-text-dim)]\">\n <LayoutTemplate :size=\"40\" :stroke-width=\"1.5\" />\n </div>\n <h3\n class=\"tpl:m-0 tpl:mb-2 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.sidebar.noSelection }}\n </h3>\n <p class=\"tpl:m-0 tpl:text-sm tpl:leading-normal\">\n {{ t.sidebar.noSelectionHint }}\n </p>\n </div>\n </div>\n\n <div\n v-if=\"activeTab === 'settings' && settingsEnabled\"\n id=\"tpl-tabpanel-settings\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-settings\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <TemplateSettingsPanel\n :settings=\"settings\"\n @update=\"emit('update-settings', $event)\"\n />\n </div>\n\n <div\n v-if=\"activeTab === 'issues' && lintAvailable\"\n id=\"tpl-tabpanel-issues\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-issues\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <IssuesPanel />\n </div>\n </aside>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Toolbar and Template Settings are `defineAsyncComponent` behind the\n * `v-if`s that already gate them (a selected block, the Settings tab).\n * `defineAsyncComponent` fetches on first render, so a static import here\n * would pull ColorPicker, MergeTagInput, and every per-type toolbar into\n * the eager graph for every session. IssuesPanel in this file is the same\n * contract. Guarded by `tests/rightSidebarLazy.test.ts` and the\n * properties-panel cases in `cdn-chunk-granularity.test.ts` /\n * `bundle-topology.test.ts`.\n */\nimport { useI18n } from \"../composables/useI18n\";\nimport { TEMPLATE_LINT_KEY, TEMPLATE_SETTINGS_FIELDS_KEY } from \"../keys\";\nimport { ALL_TEMPLATE_SETTINGS_FIELDS } from \"../utils/templateSettingsFields\";\nimport type { Block, TemplateSettings } from \"@templatical/types\";\nimport { ListChecks, LayoutTemplate, PanelTop, Settings } from \"@lucide/vue\";\nimport { computed, defineAsyncComponent, inject, watch } from \"vue\";\n\nconst Toolbar = defineAsyncComponent(() => import(\"./Toolbar.vue\"));\nconst TemplateSettingsPanel = defineAsyncComponent(\n () => import(\"./TemplateSettings.vue\"),\n);\nconst IssuesPanel = defineAsyncComponent(\n () => import(\"./sidebar/IssuesPanel.vue\"),\n);\n\nconst props = defineProps<{\n selectedBlock: Block | null;\n settings: TemplateSettings;\n shiftedLeft?: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"update-block\", updates: Partial<Block>): void;\n (e: \"delete-block\"): void;\n (e: \"duplicate-block\"): void;\n (e: \"update-settings\", settings: Partial<TemplateSettings>): void;\n}>();\n\nconst { t } = useI18n();\n\nexport type RightSidebarTab = \"content\" | \"settings\" | \"issues\";\ntype Tab = RightSidebarTab;\n\n// `v-model:tab`: `Editor.vue` owns the tab. Without a parent binding it is local state.\nconst activeTab = defineModel<Tab>(\"tab\", { default: \"content\" });\n\nconst lint = inject(TEMPLATE_LINT_KEY, null);\n// `@templatical/quality` is an optional peer imported at mount. The tab renders\n// from the start, so apps that install it never see the tab pop in, and goes\n// once the import fails: without the package the panel has nothing to show.\nconst lintAvailable = computed(() => lint !== null && !lint.unavailable.value);\nconst issueCount = computed(() => lint?.issues.value.length ?? 0);\n\n// The tab follows the panel: with every setting excluded there is nothing for\n// it to open, and a tab onto an empty panel reads as a bug. Defaults to every\n// field, since the key is absent for a consumer who configured nothing.\nconst allowedSettingsFields = inject(\n TEMPLATE_SETTINGS_FIELDS_KEY,\n new Set(ALL_TEMPLATE_SETTINGS_FIELDS),\n);\nconst settingsEnabled = computed(() => allowedSettingsFields.size > 0);\n\nfunction tabClass(tab: Tab): string {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return \"tpl:flex-1 tpl:text-[var(--tpl-primary)]\";\n }\n return \"tpl:shrink-0 tpl:text-[var(--tpl-text-muted)] tpl:hover:text-[var(--tpl-text)]\";\n}\n\nfunction tabStyle(tab: Tab): Record<string, string> {\n const isActive = activeTab.value === tab;\n if (isActive) {\n return {\n backgroundColor: \"var(--tpl-bg)\",\n // `-sm` is the step the shadow vocabulary assigns to a lifted control;\n // `-md` is dialog and side-panel depth, which overstates a 32px tab.\n boxShadow: \"var(--tpl-shadow-sm)\",\n };\n }\n return { backgroundColor: \"transparent\" };\n}\n\nwatch(\n () => props.selectedBlock?.id,\n (blockId) => {\n if (blockId) {\n activeTab.value = \"content\";\n }\n },\n);\n\n// The Issues tab can be picked while the quality import is in flight; when\n// that import then fails, the sidebar would otherwise show no panel at all.\nwatch(lintAvailable, (available) => {\n if (!available && activeTab.value === \"issues\") {\n activeTab.value = \"content\";\n }\n});\n</script>\n\n<template>\n <!-- `box-border` keeps the border inside the 320px the canvas body leaves\n for this rail (`right-[320px]`); outside it, the rail covers the body's\n last pixel column, where the block toolbar's drag grip sits. -->\n <aside\n :aria-label=\"t.landmarks.rightSidebar\"\n class=\"tpl-right-sidebar tpl:absolute tpl:top-14 tpl:bottom-0 tpl:z-40 tpl:flex tpl:box-border tpl:w-[320px] tpl:flex-col tpl:bg-[var(--tpl-bg-elevated)] tpl:transition-all tpl:duration-200 tpl:border-l tpl:border-[var(--tpl-border)]\"\n :class=\"shiftedLeft ? 'tpl:right-[360px]' : 'tpl:right-0'\"\n >\n <div\n role=\"tablist\"\n class=\"tpl:relative tpl:flex tpl:gap-1 tpl:border-b tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg-active)] tpl:p-1.5\"\n >\n <button\n id=\"tpl-tab-content\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'content'\"\n aria-controls=\"tpl-tabpanel-content\"\n :aria-label=\"t.sidebar.content\"\n :title=\"t.sidebar.content\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('content')\"\n :style=\"tabStyle('content')\"\n @click=\"activeTab = 'content'\"\n >\n <PanelTop :size=\"14\" :stroke-width=\"2\" />\n <span v-if=\"activeTab === 'content'\">{{ t.sidebar.content }}</span>\n </button>\n <button\n v-if=\"settingsEnabled\"\n id=\"tpl-tab-settings\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'settings'\"\n aria-controls=\"tpl-tabpanel-settings\"\n :aria-label=\"t.sidebar.settings\"\n :title=\"t.sidebar.settings\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('settings')\"\n :style=\"tabStyle('settings')\"\n @click=\"activeTab = 'settings'\"\n >\n <Settings :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'settings'\">{{ t.sidebar.settings }}</span>\n </button>\n <button\n v-if=\"lintAvailable\"\n id=\"tpl-tab-issues\"\n role=\"tab\"\n :aria-selected=\"activeTab === 'issues'\"\n aria-controls=\"tpl-tabpanel-issues\"\n :aria-label=\"t.issues.panelTabLabel\"\n :title=\"t.issues.panelTabLabel\"\n class=\"tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:gap-1.5 tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:px-3 tpl:py-2 tpl:text-xs tpl:font-medium tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)]\"\n :class=\"tabClass('issues')\"\n :style=\"tabStyle('issues')\"\n @click=\"activeTab = 'issues'\"\n >\n <ListChecks :size=\"14\" :stroke-width=\"1.5\" />\n <span v-if=\"activeTab === 'issues'\">\n {{ t.issues.panelTabLabel }}\n </span>\n <span\n v-if=\"issueCount > 0\"\n class=\"tpl:ml-1 tpl:rounded-full tpl:bg-[var(--tpl-bg-hover)] tpl:px-1.5 tpl:text-[10px]\"\n >\n {{ issueCount }}\n </span>\n </button>\n </div>\n\n <div\n v-if=\"activeTab === 'content'\"\n id=\"tpl-tabpanel-content\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-content\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <Toolbar\n v-if=\"selectedBlock\"\n :block=\"selectedBlock\"\n @update=\"emit('update-block', $event)\"\n @delete=\"emit('delete-block')\"\n @duplicate=\"emit('duplicate-block')\"\n />\n <div\n v-else\n class=\"tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:px-6 tpl:py-10 tpl:text-center tpl:text-[var(--tpl-text-muted)]\"\n >\n <div class=\"tpl:mb-4 tpl:text-[var(--tpl-text-dim)]\">\n <LayoutTemplate :size=\"40\" :stroke-width=\"1.5\" />\n </div>\n <h3\n class=\"tpl:m-0 tpl:mb-2 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.sidebar.noSelection }}\n </h3>\n <p class=\"tpl:m-0 tpl:text-sm tpl:leading-normal\">\n {{ t.sidebar.noSelectionHint }}\n </p>\n </div>\n </div>\n\n <div\n v-if=\"activeTab === 'settings' && settingsEnabled\"\n id=\"tpl-tabpanel-settings\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-settings\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <TemplateSettingsPanel\n :settings=\"settings\"\n @update=\"emit('update-settings', $event)\"\n />\n </div>\n\n <div\n v-if=\"activeTab === 'issues' && lintAvailable\"\n id=\"tpl-tabpanel-issues\"\n role=\"tabpanel\"\n aria-labelledby=\"tpl-tab-issues\"\n class=\"tpl:flex tpl:flex-1 tpl:flex-col tpl:overflow-y-auto\"\n >\n <IssuesPanel />\n </div>\n </aside>\n</template>\n","<script setup lang=\"ts\">\nimport { Monitor } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\n// Full-cover gate shown below the usable-width breakpoint (issue #235).\n// Rendered as the last child of `.tpl` and given a literal z-index above all\n// chrome (header z-50, sidebars z-40) AND `.tpl-popover-root` (z 10000), so the\n// opaque overlay covers everything including any open popover/modal.\n//\n// The z-index is a LITERAL rather than a token or a Tailwind utility, for two\n// separate reasons: a `var()` token would live on `:root`, unreachable from\n// inside the shadow root; and this notice must outrank `.tpl-popover-root`\n// (10000), which is itself a literal. Named z layers no longer exist — Tailwind\n// derives z utilities from `--z-index-*`, so a named one emits nothing (guarded\n// in `tests/design-system-conformance.test.ts`). Deliberately NOT written as a\n// class-like name in prose: that guard scans source text and cannot tell a\n// comment from a class attribute.\nconst { t } = useI18n();\n</script>\n\n<template>\n <div\n class=\"tpl-small-screen-notice tpl:absolute tpl:inset-0 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:gap-4 tpl:px-6 tpl:py-10 tpl:text-center tpl:bg-[var(--tpl-bg)] tpl:text-[var(--tpl-text-muted)]\"\n style=\"z-index: 10001\"\n role=\"status\"\n data-testid=\"small-screen-notice\"\n >\n <div class=\"tpl:text-[var(--tpl-text-dim)]\">\n <Monitor :size=\"48\" :stroke-width=\"1.5\" />\n </div>\n <h2\n class=\"tpl:m-0 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.smallScreen.title }}\n </h2>\n <p class=\"tpl:m-0 tpl:max-w-sm tpl:text-sm tpl:leading-normal\">\n {{ t.smallScreen.message }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Monitor } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\n// Full-cover gate shown below the usable-width breakpoint (issue #235).\n// Rendered as the last child of `.tpl` and given a literal z-index above all\n// chrome (header z-50, sidebars z-40) AND `.tpl-popover-root` (z 10000), so the\n// opaque overlay covers everything including any open popover/modal.\n//\n// The z-index is a LITERAL rather than a token or a Tailwind utility, for two\n// separate reasons: a `var()` token would live on `:root`, unreachable from\n// inside the shadow root; and this notice must outrank `.tpl-popover-root`\n// (10000), which is itself a literal. Named z layers no longer exist — Tailwind\n// derives z utilities from `--z-index-*`, so a named one emits nothing (guarded\n// in `tests/design-system-conformance.test.ts`). Deliberately NOT written as a\n// class-like name in prose: that guard scans source text and cannot tell a\n// comment from a class attribute.\nconst { t } = useI18n();\n</script>\n\n<template>\n <div\n class=\"tpl-small-screen-notice tpl:absolute tpl:inset-0 tpl:flex tpl:flex-col tpl:items-center tpl:justify-center tpl:gap-4 tpl:px-6 tpl:py-10 tpl:text-center tpl:bg-[var(--tpl-bg)] tpl:text-[var(--tpl-text-muted)]\"\n style=\"z-index: 10001\"\n role=\"status\"\n data-testid=\"small-screen-notice\"\n >\n <div class=\"tpl:text-[var(--tpl-text-dim)]\">\n <Monitor :size=\"48\" :stroke-width=\"1.5\" />\n </div>\n <h2\n class=\"tpl:m-0 tpl:text-base tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.smallScreen.title }}\n </h2>\n <p class=\"tpl:m-0 tpl:max-w-sm tpl:text-sm tpl:leading-normal\">\n {{ t.smallScreen.message }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n /** Positioning classes for the footer (left/right offsets). */\n positionClass?: string | string[];\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <footer\n class=\"tpl:pointer-events-none tpl:absolute tpl:bottom-0 tpl:z-50 tpl:flex tpl:h-8 tpl:items-center tpl:justify-end tpl:pr-4 tpl:text-[10px] tpl:opacity-90 tpl:transition-all tpl:duration-300 tpl:text-[var(--tpl-text-dim)]\"\n :class=\"positionClass\"\n >\n <div\n class=\"tpl:pointer-events-auto tpl:flex tpl:items-center tpl:gap-1.5 tpl:rounded-tl-lg tpl:p-1\"\n style=\"\n background-color: color-mix(\n in srgb,\n var(--tpl-canvas-bg) 85%,\n transparent\n );\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n \"\n >\n <span>{{ t.footer.poweredBy }}</span>\n <a\n href=\"https://templatical.com\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-1 tpl:font-medium tpl:transition-colors tpl:hover:opacity-80 tpl:text-[var(--tpl-text-muted)]\"\n style=\"text-decoration: none\"\n >\n <!-- An inline mark, not an image loaded from templatical.com: the docs promise init() makes no requests to Templatical, and editorFooter.test.ts holds that. -->\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">\n <rect\n x=\"10\"\n y=\"1\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(85% 0.08 55)\"\n transform=\"rotate(8 19 12)\"\n />\n <rect\n x=\"6\"\n y=\"2\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(77% 0.12 55)\"\n transform=\"rotate(-4 15 13)\"\n />\n <rect\n x=\"2\"\n y=\"4\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(70% 0.16 55)\"\n />\n <rect\n x=\"6\"\n y=\"9\"\n width=\"10\"\n height=\"1.8\"\n rx=\"0.9\"\n fill=\"white\"\n opacity=\"0.9\"\n />\n <rect\n x=\"6\"\n y=\"13.5\"\n width=\"7\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"17\"\n width=\"9\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"20.5\"\n width=\"5\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.4\"\n />\n </svg>\n Templatical\n </a>\n </div>\n </footer>\n</template>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n /** Positioning classes for the footer (left/right offsets). */\n positionClass?: string | string[];\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <footer\n class=\"tpl:pointer-events-none tpl:absolute tpl:bottom-0 tpl:z-50 tpl:flex tpl:h-8 tpl:items-center tpl:justify-end tpl:pr-4 tpl:text-[10px] tpl:opacity-90 tpl:transition-all tpl:duration-300 tpl:text-[var(--tpl-text-dim)]\"\n :class=\"positionClass\"\n >\n <div\n class=\"tpl:pointer-events-auto tpl:flex tpl:items-center tpl:gap-1.5 tpl:rounded-tl-lg tpl:p-1\"\n style=\"\n background-color: color-mix(\n in srgb,\n var(--tpl-canvas-bg) 85%,\n transparent\n );\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n \"\n >\n <span>{{ t.footer.poweredBy }}</span>\n <a\n href=\"https://templatical.com\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class=\"tpl:inline-flex tpl:items-center tpl:gap-1 tpl:font-medium tpl:transition-colors tpl:hover:opacity-80 tpl:text-[var(--tpl-text-muted)]\"\n style=\"text-decoration: none\"\n >\n <!-- An inline mark, not an image loaded from templatical.com: the docs promise init() makes no requests to Templatical, and editorFooter.test.ts holds that. -->\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">\n <rect\n x=\"10\"\n y=\"1\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(85% 0.08 55)\"\n transform=\"rotate(8 19 12)\"\n />\n <rect\n x=\"6\"\n y=\"2\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(77% 0.12 55)\"\n transform=\"rotate(-4 15 13)\"\n />\n <rect\n x=\"2\"\n y=\"4\"\n width=\"18\"\n height=\"22\"\n rx=\"3\"\n fill=\"oklch(70% 0.16 55)\"\n />\n <rect\n x=\"6\"\n y=\"9\"\n width=\"10\"\n height=\"1.8\"\n rx=\"0.9\"\n fill=\"white\"\n opacity=\"0.9\"\n />\n <rect\n x=\"6\"\n y=\"13.5\"\n width=\"7\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"17\"\n width=\"9\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.6\"\n />\n <rect\n x=\"6\"\n y=\"20.5\"\n width=\"5\"\n height=\"1.5\"\n rx=\"0.75\"\n fill=\"white\"\n opacity=\"0.4\"\n />\n </svg>\n Templatical\n </a>\n </div>\n </footer>\n</template>\n","import { onBeforeUnmount, onMounted, shallowRef, type ShallowRef } from \"vue\";\n\nconst pixels = (value: string) => Number.parseFloat(value) || 0;\n\ninterface HeaderFitMeasurement {\n availableWidth: number;\n leftWidth: number;\n centerWidth: number;\n rightWidth: number;\n paddingWidth: number;\n columnGap: number;\n borderWidth: number;\n}\n\n/** Internal decision shared by DOM measurement and numeric boundary tests. */\nexport function decideHeaderFit(measurement: HeaderFitMeasurement) {\n // Equal side tracks keep the centre anchored. A sum of the unequal side\n // widths would let the larger group overlap the centred view controls.\n const fullWidth =\n measurement.centerWidth +\n 2 * Math.max(measurement.leftWidth, measurement.rightWidth) +\n measurement.paddingWidth +\n 2 * measurement.columnGap +\n measurement.borderWidth;\n return { compact: measurement.availableWidth < fullWidth, fullWidth };\n}\n\n/** Keep the full header until its labels would overlap the centred controls. */\nexport function useHeaderFit(\n container: ShallowRef<HTMLElement | null>,\n header: ShallowRef<HTMLElement | null>,\n) {\n const compact = shallowRef(false);\n const fullWidth = shallowRef(0);\n let resizeObserver: ResizeObserver | undefined;\n let mutationObserver: MutationObserver | undefined;\n let mounted = false;\n let contentDirty = true;\n let scheduledFrame: number | null = null;\n let metricProbe: HTMLSpanElement | undefined;\n let probeWidth = 0;\n let probeHeight = 0;\n let headerGroups: HTMLElement[] = [];\n\n function groupsOverflow() {\n return headerGroups.some((group) => {\n const track = group.getBoundingClientRect();\n // Only direct controls count: an open, absolutely positioned popover can\n // extend beyond its track without changing the header's natural width.\n return Array.from(group.children).some((control) => {\n const bounds = control.getBoundingClientRect();\n return (\n bounds.width > 0 &&\n (bounds.left < track.left - 0.5 || bounds.right > track.right + 0.5)\n );\n });\n });\n }\n\n function measure() {\n if (!mounted || !container.value || !header.value) return;\n const available = container.value.getBoundingClientRect().width;\n // Hidden editors have no usable geometry yet. ResizeObserver retries when\n // their container becomes visible.\n if (available <= 0) return;\n if (\n !contentDirty &&\n !compact.value &&\n available >= fullWidth.value &&\n groupsOverflow()\n )\n contentDirty = true;\n if (!contentDirty && fullWidth.value > 0) {\n compact.value = available < fullWidth.value;\n return;\n }\n\n const element = header.value;\n const copy = element.ownerDocument.createElement(\"div\");\n for (const attribute of element.attributes) {\n if (!attribute.name.startsWith(\"data-\")) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n }\n copy.classList.remove(\"tpl-header\");\n copy.classList.add(\"tpl-header-measure\");\n copy.setAttribute(\"aria-hidden\", \"true\");\n copy.inert = true;\n for (const child of element.childNodes) {\n if (child !== metricProbe) copy.appendChild(child.cloneNode(true));\n }\n // No second Vue tree, duplicate IDs, test targets or focusable controls.\n for (const child of copy.querySelectorAll(\"*\")) {\n child.removeAttribute(\"id\");\n child.removeAttribute(\"data-testid\");\n }\n Object.assign(copy.style, {\n position: \"absolute\",\n inset: \"0 auto auto 0\",\n width: \"max-content\",\n height: \"auto\",\n visibility: \"hidden\",\n pointerEvents: \"none\",\n gridTemplateColumns: \"max-content max-content max-content\",\n });\n const groups = [\n \".tpl-header-left\",\n \".tpl-header-center\",\n \".tpl-header-right\",\n ].map((selector) => copy.querySelector<HTMLElement>(selector)!);\n for (const group of groups) {\n group.style.width = \"max-content\";\n group.style.minWidth = \"0\";\n }\n // The name is the one truncatable item. Measure the full controls with its\n // 24px floor, rather than compacting merely because a long name can shrink.\n const identity = copy.querySelector<HTMLElement>(\".tpl-header-identity\");\n if (identity) {\n identity.style.width = \"24px\";\n identity.style.minWidth = \"24px\";\n identity.style.flexShrink = \"0\";\n for (const child of identity.children) {\n (child as HTMLElement).style.maxWidth = \"100%\";\n }\n }\n container.value.appendChild(copy);\n try {\n const style = getComputedStyle(copy);\n const widths = groups.map((group) => group.getBoundingClientRect().width);\n // Always compare with full geometry, even while compact: the smaller\n // compact layout must never immediately trigger a return to full mode.\n const decision = decideHeaderFit({\n availableWidth: available,\n leftWidth: widths[0],\n centerWidth: widths[1],\n rightWidth: widths[2],\n paddingWidth:\n pixels(style.paddingLeft || style.paddingInline) +\n pixels(style.paddingRight || style.paddingInline),\n columnGap: pixels(style.columnGap),\n borderWidth:\n pixels(style.borderLeftWidth) + pixels(style.borderRightWidth),\n });\n fullWidth.value = decision.fullWidth;\n compact.value = decision.compact;\n contentDirty = false;\n } finally {\n copy.remove();\n }\n }\n\n function invalidateSize() {\n if (!mounted || scheduledFrame !== null) return;\n scheduledFrame = window.requestAnimationFrame(() => {\n scheduledFrame = null;\n measure();\n });\n }\n\n function invalidateContent() {\n if (!mounted) return;\n contentDirty = true;\n invalidateSize();\n }\n\n onMounted(() => {\n mounted = true;\n headerGroups = Array.from(header.value?.children ?? []) as HTMLElement[];\n // Establish the first compact/full state before paint. Later observer and\n // window deliveries share one frame; size changes reuse this full width.\n measure();\n if (!container.value || !header.value) return;\n // Intrinsic text size catches inherited base size, root size and already\n // loaded font changes without watching mutations on consumer-owned roots.\n metricProbe = header.value.ownerDocument.createElement(\"span\");\n metricProbe.className = \"tpl-header-metric-probe\";\n metricProbe.setAttribute(\"aria-hidden\", \"true\");\n metricProbe.inert = true;\n metricProbe.textContent = \"MWmw0123456789\";\n Object.assign(metricProbe.style, {\n position: \"absolute\",\n inset: \"0 auto auto 0\",\n width: \"max-content\",\n margin: \"0\",\n padding: \"0\",\n border: \"0\",\n font: \"inherit\",\n whiteSpace: \"pre\",\n visibility: \"hidden\",\n pointerEvents: \"none\",\n });\n header.value.appendChild(metricProbe);\n const initialProbe = metricProbe.getBoundingClientRect();\n probeWidth = initialProbe.width;\n probeHeight = initialProbe.height;\n if (typeof ResizeObserver !== \"undefined\") {\n resizeObserver = new ResizeObserver((entries) => {\n let metricsChanged = false;\n for (const entry of entries) {\n if (entry.target !== metricProbe) continue;\n const { width, height } = entry.contentRect;\n if (width !== probeWidth || height !== probeHeight)\n metricsChanged = true;\n probeWidth = width;\n probeHeight = height;\n }\n if (metricsChanged) invalidateContent();\n else invalidateSize();\n });\n resizeObserver.observe(container.value);\n for (const group of headerGroups) resizeObserver.observe(group);\n resizeObserver.observe(metricProbe);\n }\n // Includes lazy provider controls, slots, translated labels, language\n // names/counts, save states and comment counts. It also works while the\n // changed text is hidden by the compact styling.\n mutationObserver = new MutationObserver(invalidateContent);\n mutationObserver.observe(header.value, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true,\n attributeFilter: [\"class\", \"style\", \"title\", \"aria-label\", \"hidden\"],\n });\n window.addEventListener(\"resize\", invalidateSize);\n const fonts = header.value.ownerDocument.fonts;\n fonts?.addEventListener(\"loadingdone\", invalidateContent);\n if (fonts?.status === \"loading\") void fonts.ready.then(invalidateContent);\n });\n\n onBeforeUnmount(() => {\n mounted = false;\n if (scheduledFrame !== null) {\n window.cancelAnimationFrame(scheduledFrame);\n scheduledFrame = null;\n }\n resizeObserver?.disconnect();\n mutationObserver?.disconnect();\n metricProbe?.remove();\n metricProbe = undefined;\n headerGroups = [];\n window.removeEventListener(\"resize\", invalidateSize);\n header.value?.ownerDocument.fonts?.removeEventListener(\n \"loadingdone\",\n invalidateContent,\n );\n });\n\n return { compact, fullWidth };\n}\n","<!--\n Canvas Dark Mode Preview Toggle\n\n This toggle simulates how the email template will look when the recipient's\n email client uses dark mode (e.g. Gmail, Outlook, Apple Mail in dark theme).\n It applies a CSS filter (invert + hue-rotate) to the canvas area only.\n\n This is NOT the editor UI theme toggle. The editor UI theme (light/dark/auto)\n is controlled externally via the `uiTheme` config option or `editor.setTheme()`.\n-->\n<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Moon, Sun } from \"@lucide/vue\";\n\ndefineProps<{\n darkMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", darkMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-dark-mode-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: darkMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: darkMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :title=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :aria-pressed=\"darkMode\"\n @click=\"emit('change', !darkMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Moon v-if=\"darkMode\" key=\"moon\" :size=\"18\" :stroke-width=\"1.5\" />\n <Sun v-else key=\"sun\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-dark-mode-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-dark-mode-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<!--\n Canvas Dark Mode Preview Toggle\n\n This toggle simulates how the email template will look when the recipient's\n email client uses dark mode (e.g. Gmail, Outlook, Apple Mail in dark theme).\n It applies a CSS filter (invert + hue-rotate) to the canvas area only.\n\n This is NOT the editor UI theme toggle. The editor UI theme (light/dark/auto)\n is controlled externally via the `uiTheme` config option or `editor.setTheme()`.\n-->\n<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Moon, Sun } from \"@lucide/vue\";\n\ndefineProps<{\n darkMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", darkMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-dark-mode-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: darkMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: darkMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :title=\"darkMode ? t.darkMode.disable : t.darkMode.enable\"\n :aria-pressed=\"darkMode\"\n @click=\"emit('change', !darkMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Moon v-if=\"darkMode\" key=\"moon\" :size=\"18\" :stroke-width=\"1.5\" />\n <Sun v-else key=\"sun\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-dark-mode-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-dark-mode-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Eye, EyeOff } from \"@lucide/vue\";\n\ndefineProps<{\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", previewMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-preview-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: previewMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: previewMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :title=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :aria-pressed=\"previewMode\"\n @click=\"emit('change', !previewMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Eye v-if=\"previewMode\" key=\"eye\" :size=\"18\" :stroke-width=\"1.5\" />\n <EyeOff v-else key=\"eye-off\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-preview-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-preview-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { useI18n } from \"../composables/useI18n\";\nimport { Eye, EyeOff } from \"@lucide/vue\";\n\ndefineProps<{\n previewMode: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"change\", previewMode: boolean): void;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <button\n class=\"tpl-preview-toggle tpl:relative tpl:flex tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:p-2 tpl:transition-all\"\n :style=\"{\n color: previewMode ? 'var(--tpl-primary)' : 'var(--tpl-text-muted)',\n backgroundColor: previewMode ? 'var(--tpl-primary-light)' : 'transparent',\n }\"\n :aria-label=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :title=\"previewMode ? t.previewMode.disable : t.previewMode.enable\"\n :aria-pressed=\"previewMode\"\n @click=\"emit('change', !previewMode)\"\n >\n <Transition\n enter-active-class=\"tpl-icon-enter-active\"\n leave-active-class=\"tpl-icon-leave-active\"\n enter-from-class=\"tpl-icon-enter-from\"\n leave-to-class=\"tpl-icon-leave-to\"\n mode=\"out-in\"\n >\n <Eye v-if=\"previewMode\" key=\"eye\" :size=\"18\" :stroke-width=\"1.5\" />\n <EyeOff v-else key=\"eye-off\" :size=\"18\" :stroke-width=\"1.5\" />\n </Transition>\n </button>\n</template>\n\n<style scoped>\n.tpl-icon-enter-active,\n.tpl-icon-leave-active {\n transition:\n opacity 120ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 120ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-icon-enter-from {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-icon-leave-to {\n opacity: 0;\n transform: scale(0.8);\n}\n\n.tpl-preview-toggle:hover {\n background-color: var(--tpl-bg-hover);\n}\n\n.tpl-preview-toggle:active {\n transform: scale(0.92);\n}\n</style>\n","<script setup lang=\"ts\">\nimport { nextTick, ref } from \"vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { inputClass } from \"../constants/styleConstants\";\n\nconst props = defineProps<{\n /** The loaded template's name. Undefined renders the \"Untitled\" placeholder. */\n name?: string;\n /**\n * Whether the name may be changed. False when the provider withheld `save`:\n * there would be nowhere for the new name to go, so it renders as plain text.\n */\n editable: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"commit\", name: string): void;\n}>();\n\nconst { t } = useI18n();\n\nconst isEditing = ref(false);\nconst draft = ref(\"\");\nconst inputEl = ref<HTMLInputElement | null>(null);\n\nasync function startEditing(): Promise<void> {\n if (!props.editable) return;\n draft.value = props.name ?? \"\";\n isEditing.value = true;\n await nextTick();\n inputEl.value?.focus();\n inputEl.value?.select();\n}\n\nfunction commit(): void {\n // Escape already left edit mode, and removing the input fires `blur` — which\n // would otherwise commit the very draft the user just cancelled.\n if (!isEditing.value) return;\n isEditing.value = false;\n const next = draft.value.trim();\n // An empty name is rejected by reverting: the header would have nothing to\n // render, and a cleared field is far more likely a slip than an intent.\n if (!next || next === props.name) return;\n emit(\"commit\", next);\n}\n\nfunction cancel(): void {\n isEditing.value = false;\n}\n</script>\n\n<template>\n <input\n v-if=\"isEditing\"\n ref=\"inputEl\"\n v-model=\"draft\"\n type=\"text\"\n data-testid=\"template-name-input\"\n :aria-label=\"t.header.templateName\"\n :class=\"[\n inputClass,\n 'tpl:h-8 tpl:max-w-[260px] tpl:text-sm tpl:font-medium',\n ]\"\n @keydown.enter.prevent=\"commit\"\n @keydown.esc.prevent=\"cancel\"\n @blur=\"commit\"\n />\n <button\n v-else-if=\"editable\"\n type=\"button\"\n data-testid=\"template-name\"\n :title=\"t.header.rename\"\n :aria-label=\"t.header.rename\"\n class=\"tpl:max-w-[260px] tpl:cursor-pointer tpl:truncate tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-transparent tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:border-[var(--tpl-border)] tpl:hover:bg-[var(--tpl-bg-hover)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n @click=\"startEditing\"\n >\n {{ name || t.header.untitled }}\n </button>\n <span\n v-else\n data-testid=\"template-name\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n >\n {{ name || t.header.untitled }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { nextTick, ref } from \"vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { inputClass } from \"../constants/styleConstants\";\n\nconst props = defineProps<{\n /** The loaded template's name. Undefined renders the \"Untitled\" placeholder. */\n name?: string;\n /**\n * Whether the name may be changed. False when the provider withheld `save`:\n * there would be nowhere for the new name to go, so it renders as plain text.\n */\n editable: boolean;\n}>();\n\nconst emit = defineEmits<{\n (e: \"commit\", name: string): void;\n}>();\n\nconst { t } = useI18n();\n\nconst isEditing = ref(false);\nconst draft = ref(\"\");\nconst inputEl = ref<HTMLInputElement | null>(null);\n\nasync function startEditing(): Promise<void> {\n if (!props.editable) return;\n draft.value = props.name ?? \"\";\n isEditing.value = true;\n await nextTick();\n inputEl.value?.focus();\n inputEl.value?.select();\n}\n\nfunction commit(): void {\n // Escape already left edit mode, and removing the input fires `blur` — which\n // would otherwise commit the very draft the user just cancelled.\n if (!isEditing.value) return;\n isEditing.value = false;\n const next = draft.value.trim();\n // An empty name is rejected by reverting: the header would have nothing to\n // render, and a cleared field is far more likely a slip than an intent.\n if (!next || next === props.name) return;\n emit(\"commit\", next);\n}\n\nfunction cancel(): void {\n isEditing.value = false;\n}\n</script>\n\n<template>\n <input\n v-if=\"isEditing\"\n ref=\"inputEl\"\n v-model=\"draft\"\n type=\"text\"\n data-testid=\"template-name-input\"\n :aria-label=\"t.header.templateName\"\n :class=\"[\n inputClass,\n 'tpl:h-8 tpl:max-w-[260px] tpl:text-sm tpl:font-medium',\n ]\"\n @keydown.enter.prevent=\"commit\"\n @keydown.esc.prevent=\"cancel\"\n @blur=\"commit\"\n />\n <button\n v-else-if=\"editable\"\n type=\"button\"\n data-testid=\"template-name\"\n :title=\"t.header.rename\"\n :aria-label=\"t.header.rename\"\n class=\"tpl:max-w-[260px] tpl:cursor-pointer tpl:truncate tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-transparent tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)] tpl:transition-all tpl:duration-[120ms] tpl:ease-[cubic-bezier(0.16,1,0.3,1)] tpl:hover:border-[var(--tpl-border)] tpl:hover:bg-[var(--tpl-bg-hover)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n @click=\"startEditing\"\n >\n {{ name || t.header.untitled }}\n </button>\n <span\n v-else\n data-testid=\"template-name\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:py-1 tpl:text-sm tpl:font-medium tpl:text-[var(--tpl-text)]\"\n :class=\"{ 'tpl:text-[var(--tpl-text-dim)]': !name }\"\n >\n {{ name || t.header.untitled }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, ref } from \"vue\";\nimport { useIntervalFn } from \"@vueuse/core\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { UI_LOCALE_KEY } from \"../keys\";\nimport { formatAbsoluteDateTime } from \"../utils/formatAbsoluteDateTime\";\nimport { formatRelativeTime } from \"../utils/formatRelativeTime\";\n\nconst props = defineProps<{\n /** ISO 8601 timestamp, straight from the store. */\n iso: string;\n /** Which field it came from — decides the \"Updated\"/\"Created\" wording. */\n kind: \"updatedAt\" | \"createdAt\";\n}>();\n\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined);\n\n// The header stays open for as long as the session does, so a label computed\n// once would sit at \"Just now\" for hours. A minute is the formatter's smallest\n// bucket, so nothing finer would show anyway.\nconst tick = ref(0);\nuseIntervalFn(() => {\n tick.value += 1;\n}, 60000);\n\nconst label = computed(() => {\n // Depended on for its side effect: `formatRelativeTime` reads the clock\n // itself, so the tick is the only thing that can invalidate this.\n void tick.value;\n const relative = formatRelativeTime(props.iso, t.time, format);\n // Null covers a value that does not parse and one further into the future\n // than clock skew explains. Falling back to an absolute date would put a\n // number where the eye expects chrome, so the line is dropped instead.\n if (relative === null) return \"\";\n // The shared buckets are phrased to stand alone, so the smallest one is\n // capitalised (\"Just now\") and reads wrong inside \"Updated {time}\". Matched\n // against the label rather than re-deriving a one-minute threshold, so what\n // counts as \"just now\" stays `formatRelativeTime`'s decision alone.\n const isJustNow = relative === t.time.justNow;\n if (props.kind === \"updatedAt\") {\n return isJustNow\n ? t.header.updatedJustNow\n : format(t.header.updatedAt, { time: relative });\n }\n return isJustNow\n ? t.header.createdJustNow\n : format(t.header.createdAt, { time: relative });\n});\n\n/**\n * Full date for the tooltip — built by `Intl`, so it needs no i18n keys, but it\n * does need the editor's locale: `toLocaleString()` with no argument formats in\n * the BROWSER's, which put an English month name directly under German chrome.\n */\nconst absolute = computed(() => formatAbsoluteDateTime(props.iso, uiLocale));\n</script>\n\n<template>\n <!-- `px-2` aligns the line under the name field's text, which carries the same\n padding for its hover affordance. Present whether or not the name renders,\n so the left column reads the same in both. -->\n <span\n v-if=\"label\"\n data-testid=\"template-timestamp\"\n :title=\"absolute\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:text-xs tpl:leading-tight tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ label }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, ref } from \"vue\";\nimport { useIntervalFn } from \"@vueuse/core\";\nimport { useI18n } from \"../composables/useI18n\";\nimport { UI_LOCALE_KEY } from \"../keys\";\nimport { formatAbsoluteDateTime } from \"../utils/formatAbsoluteDateTime\";\nimport { formatRelativeTime } from \"../utils/formatRelativeTime\";\n\nconst props = defineProps<{\n /** ISO 8601 timestamp, straight from the store. */\n iso: string;\n /** Which field it came from — decides the \"Updated\"/\"Created\" wording. */\n kind: \"updatedAt\" | \"createdAt\";\n}>();\n\nconst { t, format } = useI18n();\nconst uiLocale = inject(UI_LOCALE_KEY, undefined);\n\n// The header stays open for as long as the session does, so a label computed\n// once would sit at \"Just now\" for hours. A minute is the formatter's smallest\n// bucket, so nothing finer would show anyway.\nconst tick = ref(0);\nuseIntervalFn(() => {\n tick.value += 1;\n}, 60000);\n\nconst label = computed(() => {\n // Depended on for its side effect: `formatRelativeTime` reads the clock\n // itself, so the tick is the only thing that can invalidate this.\n void tick.value;\n const relative = formatRelativeTime(props.iso, t.time, format);\n // Null covers a value that does not parse and one further into the future\n // than clock skew explains. Falling back to an absolute date would put a\n // number where the eye expects chrome, so the line is dropped instead.\n if (relative === null) return \"\";\n // The shared buckets are phrased to stand alone, so the smallest one is\n // capitalised (\"Just now\") and reads wrong inside \"Updated {time}\". Matched\n // against the label rather than re-deriving a one-minute threshold, so what\n // counts as \"just now\" stays `formatRelativeTime`'s decision alone.\n const isJustNow = relative === t.time.justNow;\n if (props.kind === \"updatedAt\") {\n return isJustNow\n ? t.header.updatedJustNow\n : format(t.header.updatedAt, { time: relative });\n }\n return isJustNow\n ? t.header.createdJustNow\n : format(t.header.createdAt, { time: relative });\n});\n\n/**\n * Full date for the tooltip — built by `Intl`, so it needs no i18n keys, but it\n * does need the editor's locale: `toLocaleString()` with no argument formats in\n * the BROWSER's, which put an English month name directly under German chrome.\n */\nconst absolute = computed(() => formatAbsoluteDateTime(props.iso, uiLocale));\n</script>\n\n<template>\n <!-- `px-2` aligns the line under the name field's text, which carries the same\n padding for its hover affordance. Present whether or not the name renders,\n so the left column reads the same in both. -->\n <span\n v-if=\"label\"\n data-testid=\"template-timestamp\"\n :title=\"absolute\"\n class=\"tpl:max-w-[260px] tpl:truncate tpl:px-2 tpl:text-xs tpl:leading-tight tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ label }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { Check, CircleAlert } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n status: \"idle\" | \"saved\" | \"error\";\n /** The provider's failure message, shown in a tooltip on the error state. */\n errorMessage: string;\n isDirty: boolean;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <!-- Three mutually exclusive states, in priority order: a failure outranks\n everything (it needs acknowledging), a fresh success outranks the dirty\n flag, and \"unsaved\" is the resting state once either decays. Rendered\n only when a templates provider can actually save — without one the editor\n never learns that a save completed, so this would read \"unsaved\" forever. -->\n <div\n v-if=\"status === 'error'\"\n aria-live=\"assertive\"\n data-testid=\"save-status-error\"\n class=\"tpl-tooltip tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-danger)]\"\n :data-tooltip=\"errorMessage\"\n >\n <CircleAlert :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saveFailed }}\n </div>\n <div\n v-else-if=\"status === 'saved'\"\n aria-live=\"polite\"\n data-testid=\"save-status-saved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-success)]\"\n >\n <Check :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saved }}\n </div>\n <div\n v-else-if=\"isDirty\"\n aria-live=\"polite\"\n data-testid=\"save-status-unsaved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <span\n class=\"tpl-pulse tpl:size-1.5 tpl:rounded-full tpl:bg-[var(--tpl-primary)]\"\n ></span>\n {{ t.header.unsaved }}\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Check, CircleAlert } from \"@lucide/vue\";\nimport { useI18n } from \"../composables/useI18n\";\n\ndefineProps<{\n status: \"idle\" | \"saved\" | \"error\";\n /** The provider's failure message, shown in a tooltip on the error state. */\n errorMessage: string;\n isDirty: boolean;\n}>();\n\nconst { t } = useI18n();\n</script>\n\n<template>\n <!-- Three mutually exclusive states, in priority order: a failure outranks\n everything (it needs acknowledging), a fresh success outranks the dirty\n flag, and \"unsaved\" is the resting state once either decays. Rendered\n only when a templates provider can actually save — without one the editor\n never learns that a save completed, so this would read \"unsaved\" forever. -->\n <div\n v-if=\"status === 'error'\"\n aria-live=\"assertive\"\n data-testid=\"save-status-error\"\n class=\"tpl-tooltip tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-danger)]\"\n :data-tooltip=\"errorMessage\"\n >\n <CircleAlert :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saveFailed }}\n </div>\n <div\n v-else-if=\"status === 'saved'\"\n aria-live=\"polite\"\n data-testid=\"save-status-saved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-success)]\"\n >\n <Check :size=\"12\" :stroke-width=\"2.5\" />\n {{ t.header.saved }}\n </div>\n <div\n v-else-if=\"isDirty\"\n aria-live=\"polite\"\n data-testid=\"save-status-unsaved\"\n class=\"tpl-status tpl:flex tpl:items-center tpl:gap-1.5 tpl:text-xs tpl:text-[var(--tpl-text-muted)]\"\n >\n <span\n class=\"tpl-pulse tpl:size-1.5 tpl:rounded-full tpl:bg-[var(--tpl-primary)]\"\n ></span>\n {{ t.header.unsaved }}\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Sparkles } from \"@lucide/vue\";\nimport { computed } from \"vue\";\nimport type { UseAiFeatureReturn } from \"../../composables/useAiFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { secondaryBtnCompactClass } from \"../../constants/styleConstants\";\n\nconst props = defineProps<{\n feature: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n >;\n}>();\n\nconst { t } = useI18n();\nconst isActive = computed(() => props.feature.panel.value === \"chat\");\n\nfunction toggle(): void {\n if (isActive.value) props.feature.close();\n else props.feature.open(\"chat\");\n}\n</script>\n\n<template>\n <!-- The header's shared compact recipe, like Comments and test email, so the\n row keeps one height, size and weight and Save stays its only amber\n surface. The amber is on the icon alone: `--tpl-primary-hover` is 3.64:1\n on `--tpl-bg`, clearing the 3:1 non-text floor that `--tpl-primary`\n (2.76:1) misses. Open, it takes the Comments button's open fill. -->\n <button\n v-if=\"feature.isAvailable.value && feature.has('chat')\"\n type=\"button\"\n data-testid=\"ai-menu-trigger\"\n :aria-pressed=\"isActive\"\n :aria-label=\"t.ai.menu.chat\"\n :title=\"t.ai.menu.chat\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n isActive\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click.stop=\"toggle\"\n >\n <Sparkles\n :size=\"16\"\n :stroke-width=\"2\"\n class=\"tpl:text-[var(--tpl-primary-hover)]\"\n aria-hidden=\"true\"\n />\n <span class=\"tpl-header-label\">{{ t.ai.menu.button }}</span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { Sparkles } from \"@lucide/vue\";\nimport { computed } from \"vue\";\nimport type { UseAiFeatureReturn } from \"../../composables/useAiFeature\";\nimport { useI18n } from \"../../composables/useI18n\";\nimport { secondaryBtnCompactClass } from \"../../constants/styleConstants\";\n\nconst props = defineProps<{\n feature: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n >;\n}>();\n\nconst { t } = useI18n();\nconst isActive = computed(() => props.feature.panel.value === \"chat\");\n\nfunction toggle(): void {\n if (isActive.value) props.feature.close();\n else props.feature.open(\"chat\");\n}\n</script>\n\n<template>\n <!-- The header's shared compact recipe, like Comments and test email, so the\n row keeps one height, size and weight and Save stays its only amber\n surface. The amber is on the icon alone: `--tpl-primary-hover` is 3.64:1\n on `--tpl-bg`, clearing the 3:1 non-text floor that `--tpl-primary`\n (2.76:1) misses. Open, it takes the Comments button's open fill. -->\n <button\n v-if=\"feature.isAvailable.value && feature.has('chat')\"\n type=\"button\"\n data-testid=\"ai-menu-trigger\"\n :aria-pressed=\"isActive\"\n :aria-label=\"t.ai.menu.chat\"\n :title=\"t.ai.menu.chat\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n isActive\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click.stop=\"toggle\"\n >\n <Sparkles\n :size=\"16\"\n :stroke-width=\"2\"\n class=\"tpl:text-[var(--tpl-primary-hover)]\"\n aria-hidden=\"true\"\n />\n <span class=\"tpl-header-label\">{{ t.ai.menu.button }}</span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { defineAsyncComponent, shallowRef } from \"vue\";\nimport { useHeaderFit } from \"../composables/useHeaderFit\";\nimport { LoaderCircle, MessageCircle, Save, Send } from \"@lucide/vue\";\n\nimport type {\n BaseEditorReturn,\n UseEditorCoreReturn,\n} from \"../composables/useEditorCore\";\nimport type { UseAiFeatureReturn } from \"../composables/useAiFeature\";\nimport type { UseCollaborationFeatureReturn } from \"../composables/useCollaborationFeature\";\nimport type { UseCommentsFeatureReturn } from \"../composables/useCommentsFeature\";\nimport type { UseTemplatesFeatureReturn } from \"../composables/useTemplatesFeature\";\nimport type { UseTestEmailFeatureReturn } from \"../composables/useTestEmailFeature\";\nimport type { UseVersionHistoryFeatureReturn } from \"../composables/useVersionHistoryFeature\";\nimport {\n primaryBtnCompactClass,\n secondaryBtnCompactClass,\n} from \"../constants/styleConstants\";\n\nimport ViewportToggle from \"./ViewportToggle.vue\";\nimport DarkModeToggle from \"./DarkModeToggle.vue\";\nimport PreviewToggle from \"./PreviewToggle.vue\";\nimport TemplateNameField from \"./TemplateNameField.vue\";\nimport TemplateTimestamp from \"./TemplateTimestamp.vue\";\nimport TemplateSaveStatus from \"./TemplateSaveStatus.vue\";\n// Eager, unlike the panels it opens: lazy, it rendered one chunk fetch after\n// the rest of the header. The AI panels stay lazy in `Editor.vue`, so an editor\n// without an `ai` provider downloads only this button.\nimport AiHeaderMenu from \"./ai/AiHeaderMenu.vue\";\n\n// Lazy: an editor with no `versionHistory` provider never downloads the control.\nconst VersionHistoryMenu = defineAsyncComponent(\n () => import(\"./VersionHistoryMenu.vue\"),\n);\n// Lazy: an editor without `localization` never downloads the language menu.\nconst LanguageMenu = defineAsyncComponent(\n () => import(\"./localization/LanguageMenu.vue\"),\n);\n// Lazy: an editor with no collaboration provider never downloads it.\nconst CollaboratorBar = defineAsyncComponent(\n () => import(\"./collaboration/CollaboratorBar.vue\"),\n);\n\n/**\n * The editor's one header. Both entry points render this — `initCloud()` adds its\n * own controls through the `left-extras` / `right-extras` slots rather than\n * through a second header component, which is what keeps the two layouts from\n * drifting apart again (they already had: only Cloud carried `min-w-[200px]`, so\n * the OSS centre column was never actually centred).\n *\n * The two slots are in the anchored columns on purpose. There is deliberately no\n * centre slot: that track's width must stay constant, and a slot is the one\n * thing a guard test cannot stop someone filling. See the centre column's own\n * comment for why width changes there move the Preview button.\n *\n * Everything here is capability-driven, so the same markup covers \"no providers\n * configured at all\" and a fully-wired Cloud session. Nothing in this file knows\n * that Cloud exists.\n */\nconst containerElement = shallowRef<HTMLElement | null>(null);\nconst headerElement = shallowRef<HTMLElement | null>(null);\nconst { compact, fullWidth } = useHeaderFit(containerElement, headerElement);\n\ndefineProps<{\n editor: BaseEditorReturn;\n localization?: { locales: string[] };\n core: UseEditorCoreReturn;\n /** Null when no `TemplatesProvider` is configured — no name, save or status. */\n templates: Pick<\n UseTemplatesFeatureReturn,\n | \"isAvailable\"\n | \"hasTemplate\"\n | \"name\"\n | \"timestamp\"\n | \"canSave\"\n | \"rename\"\n | \"status\"\n | \"errorMessage\"\n | \"isSaving\"\n | \"requestSave\"\n > | null;\n /**\n * Whether to render the inline name field, from `config.templates?.nameField`.\n * False hides it whether or not the provider can save — a consumer whose\n * store has no name column, or whose own chrome owns the name.\n */\n showTemplateName: boolean;\n testEmail: Pick<\n UseTestEmailFeatureReturn,\n \"isAvailable\" | \"isSending\" | \"open\"\n > | null;\n versionHistory: Pick<\n UseVersionHistoryFeatureReturn,\n | \"isAvailable\"\n | \"hasTemplate\"\n | \"versions\"\n | \"isLoading\"\n | \"isRestoring\"\n | \"previewingVersion\"\n | \"refresh\"\n | \"navigate\"\n > | null;\n /** Null when no `CommentsProvider` (or no `user`) is configured. */\n comments: Pick<\n UseCommentsFeatureReturn,\n \"isAvailable\" | \"hasTemplate\" | \"unresolvedCount\" | \"isOpen\" | \"toggle\"\n > | null;\n /** Null when no `CollaborationProvider` is configured. */\n collaboration: Pick<\n UseCollaborationFeatureReturn,\n \"isLive\" | \"people\" | \"connection\"\n > | null;\n /** Null when no `AiProvider` is configured. */\n ai: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n > | null;\n}>();\n</script>\n\n<template>\n <!-- Opaque, and `--tpl-shadow-sm` because that is the step the shadow\n vocabulary assigns to sticky chrome. `.tpl-body` starts at this header's\n own height, so nothing ever passes beneath it: a translucent fill has an\n identical surface behind it and a backdrop blur has nothing to blur,\n which costs a compositing layer to render exactly `--tpl-bg`. -->\n <div\n ref=\"containerElement\"\n class=\"tpl-header-container tpl:absolute tpl:inset-x-0 tpl:top-0 tpl:z-50 tpl:h-14\"\n >\n <header\n ref=\"headerElement\"\n :data-compact=\"compact\"\n :data-full-width=\"fullWidth\"\n class=\"tpl-header tpl:absolute tpl:top-0 tpl:right-0 tpl:left-0 tpl:z-50 tpl:grid tpl:h-14 tpl:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] tpl:items-center tpl:px-4 tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-sm)] tpl:border-b tpl:border-[var(--tpl-border)]\"\n >\n <!-- Left: the template's identity — the inline-editable name, and under it\n when the store dates its writes. Stacking the two needs 6px of bottom\n padding: the name is a button, so it carries border + `py-1` + half its\n leading above its text, while the timestamp carries nothing below its\n own. Centring the boxes therefore puts all of that lead at the top and\n reads as a misaligned pair. Only when both render — either alone is\n already centred on its own box. Equal side tracks keep the view controls\n centred; measured content decides when to compact. Nothing renders before a\n template exists; there is neither a name nor a write time yet. The stack\n is gated as a whole so an empty one cannot add a `gap-2.5` before the\n cloud extras. -->\n <div\n class=\"tpl-header-left tpl:flex tpl:min-w-0 tpl:items-center tpl:gap-2.5\"\n >\n <div\n v-if=\"\n templates?.isAvailable.value &&\n templates.hasTemplate.value &&\n (showTemplateName || templates.timestamp.value)\n \"\n class=\"tpl-header-identity tpl:flex tpl:min-w-0 tpl:flex-col tpl:items-start\"\n :class=\"{\n 'tpl:pb-1.5':\n showTemplateName && templates.timestamp.value !== null,\n }\"\n >\n <TemplateNameField\n v-if=\"showTemplateName\"\n :name=\"templates.name.value\"\n :editable=\"templates.canSave.value\"\n @commit=\"templates.rename\"\n />\n <TemplateTimestamp\n class=\"tpl-header-timestamp\"\n v-if=\"templates.timestamp.value\"\n :iso=\"templates.timestamp.value.iso\"\n :kind=\"templates.timestamp.value.kind\"\n />\n </div>\n <LanguageMenu\n v-if=\"localization\"\n :editor=\"editor\"\n :locales=\"localization.locales\"\n />\n <!-- Version history — the third piece of \"which template, and which\n version of it\", after the name and the write time. It sits here and\n not in the right column because that column's content already\n overflows its track: `justify-end` packs to the right edge, so an\n extra control there spills *leftward* over the centre track and\n swallows clicks meant for the Preview button. Measured — it covered\n it with the menu's own back-arrow. This column packs from the left\n and has the room.\n\n Needs a template as well as a provider: a version belongs to a\n template id, so before one is loaded there is nothing to list. -->\n <VersionHistoryMenu\n v-if=\"\n versionHistory?.isAvailable.value &&\n versionHistory.hasTemplate.value\n \"\n :versions=\"versionHistory.versions.value\"\n :is-loading=\"versionHistory.isLoading.value\"\n :is-restoring=\"versionHistory.isRestoring.value\"\n :previewing-id=\"versionHistory.previewingVersion.value?.id ?? null\"\n @open=\"versionHistory.refresh()\"\n @navigate=\"versionHistory.navigate($event)\"\n />\n <!-- Who else has the template open. Here, never in the centre track:\n the bar changes width as people come and go, and the centre must\n not (#574). This column packs from the left and moves nothing. -->\n <CollaboratorBar\n v-if=\"collaboration?.isLive.value\"\n :people=\"collaboration.people.value\"\n :connection=\"collaboration.connection.value\"\n />\n <slot name=\"left-extras\" />\n </div>\n\n <!-- Center: the three \"how am I viewing the canvas\" controls, and nothing\n else — ever.\n\n The grid is `1fr auto 1fr`, so this track is exactly max-content wide\n and the equal `fr` columns centre it. Any width change therefore\n redistributes symmetrically about the header's centre and moves every\n sibling by half the delta, whichever side of the change it sits on.\n DOM order buys nothing. So a conditional control here drags the Preview\n button out from under the cursor — 114.5px when the sample/label toggle\n used to live here, and repeatedly in Cloud as collaborators came and\n went (#574).\n\n Hence the rule: nothing in this track may be conditional. No `v-if`, no\n `v-show`, no slot. Conditional controls go in the edge-anchored `fr`\n columns, which grow away from their anchored edge; preview-only ones go\n on the preview surface, where `Editor.vue` floats them over the canvas.\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div\n class=\"tpl-header-center tpl:flex tpl:items-center tpl:justify-center tpl:gap-10\"\n >\n <ViewportToggle\n :viewport=\"editor.state.viewport\"\n @change=\"editor.setViewport\"\n />\n <DarkModeToggle\n :dark-mode=\"editor.state.darkMode\"\n @change=\"editor.setDarkMode\"\n />\n <PreviewToggle\n :preview-mode=\"editor.state.previewMode\"\n @change=\"editor.setPreviewMode\"\n />\n </div>\n\n <!-- Right: save status → Comments → AI → [cloud extras] → test email → Save.\n Save is last: it is the primary action. `justify-end` anchors the row to\n the right edge, so a control appearing at its start extends the row\n leftward and moves nothing already in it — but note the row is already\n at the edge of its track at common widths, so anything added here\n overflows onto the centre rather than fitting. -->\n <div\n class=\"tpl-header-right tpl:flex tpl:min-w-0 tpl:items-center tpl:justify-end tpl:gap-3\"\n >\n <!-- Gated on a provider that can actually save. Without one the editor\n never learns that a save completed, so the badge could only ever read\n \"unsaved\" — worse than showing nothing. -->\n <TemplateSaveStatus\n class=\"tpl-header-save-status\"\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n :status=\"templates.status.value\"\n :error-message=\"templates.errorMessage.value\"\n :is-dirty=\"editor.state.isDirty\"\n />\n\n <!-- Comments. Needs a template as well as a provider — a comment is keyed\n to a template id, so before one is loaded there is nothing to attach a\n thread to. Shared chrome, because comments are a shared\n provider-backed feature rather than a Cloud one. -->\n <button\n v-if=\"comments?.isAvailable.value && comments.hasTemplate.value\"\n type=\"button\"\n data-testid=\"comments-trigger\"\n :aria-label=\"\n comments.unresolvedCount.value > 0\n ? `${core.t.comments.button} (${comments.unresolvedCount.value})`\n : core.t.comments.button\n \"\n :title=\"core.t.comments.button\"\n :aria-expanded=\"comments.isOpen.value\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n comments.isOpen.value\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click=\"comments.toggle()\"\n >\n <MessageCircle :size=\"16\" :stroke-width=\"2\" />\n <span class=\"tpl-header-label\">{{ core.t.comments.button }}</span>\n <span\n v-if=\"comments.unresolvedCount.value > 0 && !comments.isOpen.value\"\n class=\"tpl-header-comment-count tpl:inline-flex tpl:size-4.5 tpl:items-center tpl:justify-center tpl:rounded-full tpl:text-[10px] tpl:font-semibold tpl:bg-[var(--tpl-primary)] tpl:text-[var(--tpl-on-primary)]\"\n >\n {{ comments.unresolvedCount.value }}\n </span>\n </button>\n\n <!-- AI: after Comments, before test email, as Cloud's AI button sat. -->\n <AiHeaderMenu v-if=\"ai\" :feature=\"ai\" />\n\n <slot name=\"right-extras\" />\n\n <!-- The shared recipe, like every control in this row. Shared rather than\n hand-rolled so all three keep one height — a bespoke string is how\n this button came to sit 4px shorter than its neighbours. -->\n <button\n v-if=\"testEmail?.isAvailable.value\"\n type=\"button\"\n data-testid=\"test-email-trigger\"\n :aria-label=\"core.t.testEmail.title\"\n :title=\"core.t.testEmail.title\"\n :disabled=\"testEmail.isSending.value\"\n :class=\"secondaryBtnCompactClass\"\n @click=\"testEmail.open()\"\n >\n <Send\n v-if=\"!testEmail.isSending.value\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <LoaderCircle\n v-else\n class=\"tpl-spinner\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <span class=\"tpl-header-label\">{{ core.t.testEmail.button }}</span>\n </button>\n\n <!-- Save is the editor's one primary, and it only takes that treatment\n while there is something to save. Amber announces intent or selection,\n so a Save that looks identical dirty or clean announces nothing — and\n it would be the loudest element in chrome that exists to recede behind\n the canvas. Gated on `hasTemplate` too, or a disabled button would\n light up before there is anywhere to save to.\n\n Amber with the paper colour on it is 2.80:1 in light mode. That is\n accepted rather than overlooked: every amber surface and accent in the\n editor shares this pairing, and correcting this one control alone would\n make it read as a different kind of thing. The Amber-Accent Exception\n in DESIGN.md records the decision and its limits — chief among them\n that amber must never be the only carrier of a state, which is why the\n `TemplateSaveStatus` badge says \"Unsaved\" in words beside it.\n\n The light lift is the same condition, and it is Flat-At-Rest applied\n rather than bent: a surface paints no shadow until something happens to\n it, and unsaved work is that something. It sits inline rather than in\n the recipe because the recipe is shared, and a primary button at rest\n elsewhere should still be flat.\n\n Hidden entirely when the provider withheld `save` — the read-only\n equivalent of the saved-blocks permission discipline: loading a\n template and editing it locally still works, there is simply nothing\n to persist. Disabled (with a reason in the tooltip) until a template\n exists, since `save()` patches an id. -->\n <button\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n type=\"button\"\n data-testid=\"template-save\"\n :class=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? primaryBtnCompactClass\n : secondaryBtnCompactClass\n \"\n :style=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? { boxShadow: 'var(--tpl-shadow-sm)' }\n : undefined\n \"\n :aria-label=\"\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n \"\n :disabled=\"templates.isSaving.value || !templates.hasTemplate.value\"\n :title=\"\n templates.hasTemplate.value\n ? core.t.header.save\n : core.t.header.saveNoTemplate\n \"\n @click=\"templates.requestSave()\"\n >\n <Save v-if=\"!templates.isSaving.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle\n v-else\n class=\"tpl-spinner\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <span class=\"tpl-header-label\">{{\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n }}</span>\n </button>\n </div>\n </header>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { defineAsyncComponent, shallowRef } from \"vue\";\nimport { useHeaderFit } from \"../composables/useHeaderFit\";\nimport { LoaderCircle, MessageCircle, Save, Send } from \"@lucide/vue\";\n\nimport type {\n BaseEditorReturn,\n UseEditorCoreReturn,\n} from \"../composables/useEditorCore\";\nimport type { UseAiFeatureReturn } from \"../composables/useAiFeature\";\nimport type { UseCollaborationFeatureReturn } from \"../composables/useCollaborationFeature\";\nimport type { UseCommentsFeatureReturn } from \"../composables/useCommentsFeature\";\nimport type { UseTemplatesFeatureReturn } from \"../composables/useTemplatesFeature\";\nimport type { UseTestEmailFeatureReturn } from \"../composables/useTestEmailFeature\";\nimport type { UseVersionHistoryFeatureReturn } from \"../composables/useVersionHistoryFeature\";\nimport {\n primaryBtnCompactClass,\n secondaryBtnCompactClass,\n} from \"../constants/styleConstants\";\n\nimport ViewportToggle from \"./ViewportToggle.vue\";\nimport DarkModeToggle from \"./DarkModeToggle.vue\";\nimport PreviewToggle from \"./PreviewToggle.vue\";\nimport TemplateNameField from \"./TemplateNameField.vue\";\nimport TemplateTimestamp from \"./TemplateTimestamp.vue\";\nimport TemplateSaveStatus from \"./TemplateSaveStatus.vue\";\n// Eager, unlike the panels it opens: lazy, it rendered one chunk fetch after\n// the rest of the header. The AI panels stay lazy in `Editor.vue`, so an editor\n// without an `ai` provider downloads only this button.\nimport AiHeaderMenu from \"./ai/AiHeaderMenu.vue\";\n\n// Lazy: an editor with no `versionHistory` provider never downloads the control.\nconst VersionHistoryMenu = defineAsyncComponent(\n () => import(\"./VersionHistoryMenu.vue\"),\n);\n// Lazy: an editor without `localization` never downloads the language menu.\nconst LanguageMenu = defineAsyncComponent(\n () => import(\"./localization/LanguageMenu.vue\"),\n);\n// Lazy: an editor with no collaboration provider never downloads it.\nconst CollaboratorBar = defineAsyncComponent(\n () => import(\"./collaboration/CollaboratorBar.vue\"),\n);\n\n/**\n * The editor's one header. Both entry points render this — `initCloud()` adds its\n * own controls through the `left-extras` / `right-extras` slots rather than\n * through a second header component, which is what keeps the two layouts from\n * drifting apart again (they already had: only Cloud carried `min-w-[200px]`, so\n * the OSS centre column was never actually centred).\n *\n * The two slots are in the anchored columns on purpose. There is deliberately no\n * centre slot: that track's width must stay constant, and a slot is the one\n * thing a guard test cannot stop someone filling. See the centre column's own\n * comment for why width changes there move the Preview button.\n *\n * Everything here is capability-driven, so the same markup covers \"no providers\n * configured at all\" and a fully-wired Cloud session. Nothing in this file knows\n * that Cloud exists.\n */\nconst containerElement = shallowRef<HTMLElement | null>(null);\nconst headerElement = shallowRef<HTMLElement | null>(null);\nconst { compact, fullWidth } = useHeaderFit(containerElement, headerElement);\n\ndefineProps<{\n editor: BaseEditorReturn;\n localization?: { locales: string[] };\n core: UseEditorCoreReturn;\n /** Null when no `TemplatesProvider` is configured — no name, save or status. */\n templates: Pick<\n UseTemplatesFeatureReturn,\n | \"isAvailable\"\n | \"hasTemplate\"\n | \"name\"\n | \"timestamp\"\n | \"canSave\"\n | \"rename\"\n | \"status\"\n | \"errorMessage\"\n | \"isSaving\"\n | \"requestSave\"\n > | null;\n /**\n * Whether to render the inline name field, from `config.templates?.nameField`.\n * False hides it whether or not the provider can save — a consumer whose\n * store has no name column, or whose own chrome owns the name.\n */\n showTemplateName: boolean;\n testEmail: Pick<\n UseTestEmailFeatureReturn,\n \"isAvailable\" | \"isSending\" | \"open\"\n > | null;\n versionHistory: Pick<\n UseVersionHistoryFeatureReturn,\n | \"isAvailable\"\n | \"hasTemplate\"\n | \"versions\"\n | \"isLoading\"\n | \"isRestoring\"\n | \"previewingVersion\"\n | \"refresh\"\n | \"navigate\"\n > | null;\n /** Null when no `CommentsProvider` (or no `user`) is configured. */\n comments: Pick<\n UseCommentsFeatureReturn,\n \"isAvailable\" | \"hasTemplate\" | \"unresolvedCount\" | \"isOpen\" | \"toggle\"\n > | null;\n /** Null when no `CollaborationProvider` is configured. */\n collaboration: Pick<\n UseCollaborationFeatureReturn,\n \"isLive\" | \"people\" | \"connection\"\n > | null;\n /** Null when no `AiProvider` is configured. */\n ai: Pick<\n UseAiFeatureReturn,\n \"panel\" | \"isAvailable\" | \"has\" | \"open\" | \"close\"\n > | null;\n}>();\n</script>\n\n<template>\n <!-- Opaque, and `--tpl-shadow-sm` because that is the step the shadow\n vocabulary assigns to sticky chrome. `.tpl-body` starts at this header's\n own height, so nothing ever passes beneath it: a translucent fill has an\n identical surface behind it and a backdrop blur has nothing to blur,\n which costs a compositing layer to render exactly `--tpl-bg`. -->\n <div\n ref=\"containerElement\"\n class=\"tpl-header-container tpl:absolute tpl:inset-x-0 tpl:top-0 tpl:z-50 tpl:h-14\"\n >\n <header\n ref=\"headerElement\"\n :data-compact=\"compact\"\n :data-full-width=\"fullWidth\"\n class=\"tpl-header tpl:absolute tpl:top-0 tpl:right-0 tpl:left-0 tpl:z-50 tpl:grid tpl:h-14 tpl:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] tpl:items-center tpl:px-4 tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-sm)] tpl:border-b tpl:border-[var(--tpl-border)]\"\n >\n <!-- Left: the template's identity — the inline-editable name, and under it\n when the store dates its writes. Stacking the two needs 6px of bottom\n padding: the name is a button, so it carries border + `py-1` + half its\n leading above its text, while the timestamp carries nothing below its\n own. Centring the boxes therefore puts all of that lead at the top and\n reads as a misaligned pair. Only when both render — either alone is\n already centred on its own box. Equal side tracks keep the view controls\n centred; measured content decides when to compact. Nothing renders before a\n template exists; there is neither a name nor a write time yet. The stack\n is gated as a whole so an empty one cannot add a `gap-2.5` before the\n cloud extras. -->\n <div\n class=\"tpl-header-left tpl:flex tpl:min-w-0 tpl:items-center tpl:gap-2.5\"\n >\n <div\n v-if=\"\n templates?.isAvailable.value &&\n templates.hasTemplate.value &&\n (showTemplateName || templates.timestamp.value)\n \"\n class=\"tpl-header-identity tpl:flex tpl:min-w-0 tpl:flex-col tpl:items-start\"\n :class=\"{\n 'tpl:pb-1.5':\n showTemplateName && templates.timestamp.value !== null,\n }\"\n >\n <TemplateNameField\n v-if=\"showTemplateName\"\n :name=\"templates.name.value\"\n :editable=\"templates.canSave.value\"\n @commit=\"templates.rename\"\n />\n <TemplateTimestamp\n class=\"tpl-header-timestamp\"\n v-if=\"templates.timestamp.value\"\n :iso=\"templates.timestamp.value.iso\"\n :kind=\"templates.timestamp.value.kind\"\n />\n </div>\n <LanguageMenu\n v-if=\"localization\"\n :editor=\"editor\"\n :locales=\"localization.locales\"\n />\n <!-- Version history — the third piece of \"which template, and which\n version of it\", after the name and the write time. It sits here and\n not in the right column because that column's content already\n overflows its track: `justify-end` packs to the right edge, so an\n extra control there spills *leftward* over the centre track and\n swallows clicks meant for the Preview button. Measured — it covered\n it with the menu's own back-arrow. This column packs from the left\n and has the room.\n\n Needs a template as well as a provider: a version belongs to a\n template id, so before one is loaded there is nothing to list. -->\n <VersionHistoryMenu\n v-if=\"\n versionHistory?.isAvailable.value &&\n versionHistory.hasTemplate.value\n \"\n :versions=\"versionHistory.versions.value\"\n :is-loading=\"versionHistory.isLoading.value\"\n :is-restoring=\"versionHistory.isRestoring.value\"\n :previewing-id=\"versionHistory.previewingVersion.value?.id ?? null\"\n @open=\"versionHistory.refresh()\"\n @navigate=\"versionHistory.navigate($event)\"\n />\n <!-- Who else has the template open. Here, never in the centre track:\n the bar changes width as people come and go, and the centre must\n not (#574). This column packs from the left and moves nothing. -->\n <CollaboratorBar\n v-if=\"collaboration?.isLive.value\"\n :people=\"collaboration.people.value\"\n :connection=\"collaboration.connection.value\"\n />\n <slot name=\"left-extras\" />\n </div>\n\n <!-- Center: the three \"how am I viewing the canvas\" controls, and nothing\n else — ever.\n\n The grid is `1fr auto 1fr`, so this track is exactly max-content wide\n and the equal `fr` columns centre it. Any width change therefore\n redistributes symmetrically about the header's centre and moves every\n sibling by half the delta, whichever side of the change it sits on.\n DOM order buys nothing. So a conditional control here drags the Preview\n button out from under the cursor — 114.5px when the sample/label toggle\n used to live here, and repeatedly in Cloud as collaborators came and\n went (#574).\n\n Hence the rule: nothing in this track may be conditional. No `v-if`, no\n `v-show`, no slot. Conditional controls go in the edge-anchored `fr`\n columns, which grow away from their anchored edge; preview-only ones go\n on the preview surface, where `Editor.vue` floats them over the canvas.\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div\n class=\"tpl-header-center tpl:flex tpl:items-center tpl:justify-center tpl:gap-10\"\n >\n <ViewportToggle\n :viewport=\"editor.state.viewport\"\n @change=\"editor.setViewport\"\n />\n <DarkModeToggle\n :dark-mode=\"editor.state.darkMode\"\n @change=\"editor.setDarkMode\"\n />\n <PreviewToggle\n :preview-mode=\"editor.state.previewMode\"\n @change=\"editor.setPreviewMode\"\n />\n </div>\n\n <!-- Right: save status → Comments → AI → [cloud extras] → test email → Save.\n Save is last: it is the primary action. `justify-end` anchors the row to\n the right edge, so a control appearing at its start extends the row\n leftward and moves nothing already in it — but note the row is already\n at the edge of its track at common widths, so anything added here\n overflows onto the centre rather than fitting. -->\n <div\n class=\"tpl-header-right tpl:flex tpl:min-w-0 tpl:items-center tpl:justify-end tpl:gap-3\"\n >\n <!-- Gated on a provider that can actually save. Without one the editor\n never learns that a save completed, so the badge could only ever read\n \"unsaved\" — worse than showing nothing. -->\n <TemplateSaveStatus\n class=\"tpl-header-save-status\"\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n :status=\"templates.status.value\"\n :error-message=\"templates.errorMessage.value\"\n :is-dirty=\"editor.state.isDirty\"\n />\n\n <!-- Comments. Needs a template as well as a provider — a comment is keyed\n to a template id, so before one is loaded there is nothing to attach a\n thread to. Shared chrome, because comments are a shared\n provider-backed feature rather than a Cloud one. -->\n <button\n v-if=\"comments?.isAvailable.value && comments.hasTemplate.value\"\n type=\"button\"\n data-testid=\"comments-trigger\"\n :aria-label=\"\n comments.unresolvedCount.value > 0\n ? `${core.t.comments.button} (${comments.unresolvedCount.value})`\n : core.t.comments.button\n \"\n :title=\"core.t.comments.button\"\n :aria-expanded=\"comments.isOpen.value\"\n :class=\"secondaryBtnCompactClass\"\n :style=\"\n comments.isOpen.value\n ? {\n backgroundColor: 'var(--tpl-primary-light)',\n borderColor: 'var(--tpl-primary-light)',\n }\n : undefined\n \"\n @click=\"comments.toggle()\"\n >\n <MessageCircle :size=\"16\" :stroke-width=\"2\" />\n <span class=\"tpl-header-label\">{{ core.t.comments.button }}</span>\n <span\n v-if=\"comments.unresolvedCount.value > 0 && !comments.isOpen.value\"\n class=\"tpl-header-comment-count tpl:inline-flex tpl:size-4.5 tpl:items-center tpl:justify-center tpl:rounded-full tpl:text-[10px] tpl:font-semibold tpl:bg-[var(--tpl-primary)] tpl:text-[var(--tpl-on-primary)]\"\n >\n {{ comments.unresolvedCount.value }}\n </span>\n </button>\n\n <!-- AI: after Comments, before test email, as Cloud's AI button sat. -->\n <AiHeaderMenu v-if=\"ai\" :feature=\"ai\" />\n\n <slot name=\"right-extras\" />\n\n <!-- The shared recipe, like every control in this row. Shared rather than\n hand-rolled so all three keep one height — a bespoke string is how\n this button came to sit 4px shorter than its neighbours. -->\n <button\n v-if=\"testEmail?.isAvailable.value\"\n type=\"button\"\n data-testid=\"test-email-trigger\"\n :aria-label=\"core.t.testEmail.title\"\n :title=\"core.t.testEmail.title\"\n :disabled=\"testEmail.isSending.value\"\n :class=\"secondaryBtnCompactClass\"\n @click=\"testEmail.open()\"\n >\n <Send\n v-if=\"!testEmail.isSending.value\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <LoaderCircle\n v-else\n class=\"tpl-spinner\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <span class=\"tpl-header-label\">{{ core.t.testEmail.button }}</span>\n </button>\n\n <!-- Save is the editor's one primary, and it only takes that treatment\n while there is something to save. Amber announces intent or selection,\n so a Save that looks identical dirty or clean announces nothing — and\n it would be the loudest element in chrome that exists to recede behind\n the canvas. Gated on `hasTemplate` too, or a disabled button would\n light up before there is anywhere to save to.\n\n Amber with the paper colour on it is 2.80:1 in light mode. That is\n accepted rather than overlooked: every amber surface and accent in the\n editor shares this pairing, and correcting this one control alone would\n make it read as a different kind of thing. The Amber-Accent Exception\n in DESIGN.md records the decision and its limits — chief among them\n that amber must never be the only carrier of a state, which is why the\n `TemplateSaveStatus` badge says \"Unsaved\" in words beside it.\n\n The light lift is the same condition, and it is Flat-At-Rest applied\n rather than bent: a surface paints no shadow until something happens to\n it, and unsaved work is that something. It sits inline rather than in\n the recipe because the recipe is shared, and a primary button at rest\n elsewhere should still be flat.\n\n Hidden entirely when the provider withheld `save` — the read-only\n equivalent of the saved-blocks permission discipline: loading a\n template and editing it locally still works, there is simply nothing\n to persist. Disabled (with a reason in the tooltip) until a template\n exists, since `save()` patches an id. -->\n <button\n v-if=\"templates?.isAvailable.value && templates.canSave.value\"\n type=\"button\"\n data-testid=\"template-save\"\n :class=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? primaryBtnCompactClass\n : secondaryBtnCompactClass\n \"\n :style=\"\n editor.state.isDirty && templates.hasTemplate.value\n ? { boxShadow: 'var(--tpl-shadow-sm)' }\n : undefined\n \"\n :aria-label=\"\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n \"\n :disabled=\"templates.isSaving.value || !templates.hasTemplate.value\"\n :title=\"\n templates.hasTemplate.value\n ? core.t.header.save\n : core.t.header.saveNoTemplate\n \"\n @click=\"templates.requestSave()\"\n >\n <Save v-if=\"!templates.isSaving.value\" :size=\"16\" :stroke-width=\"2\" />\n <LoaderCircle\n v-else\n class=\"tpl-spinner\"\n :size=\"16\"\n :stroke-width=\"2\"\n />\n <span class=\"tpl-header-label\">{{\n templates.isSaving.value ? core.t.header.saving : core.t.header.save\n }}</span>\n </button>\n </div>\n </header>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n inject,\n nextTick,\n ref,\n watch,\n type ComponentPublicInstance,\n} from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { ChevronDown, Search, X } from \"@lucide/vue\";\nimport type { MergeTag } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n MERGE_TAG_PICKER_KEY,\n MERGE_TAG_SHOW_RAW_VALUE_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\n\n// Picker singleton — provided by useEditorCore. We require it explicitly so\n// the modal is unmountable only in a non-editor context (which we don't\n// support). `requireInject` throws a clear message rather than letting a\n// silent inject default mask the misuse.\nconst picker = requireInject(MERGE_TAG_PICKER_KEY, \"MergeTagPickerModal\");\nconst { t, format } = useI18n();\n\n// Theming — same pattern as every other OSS panel (ParagraphToolbar,\n// RichTextLinkDialog). The panel carries the `tpl` token class, so it must\n// re-establish the theme locally: `data-tpl-theme` selects the dark token\n// block, and the inline `themeStyles` apply the consumer's `theme` config\n// overrides. Without these the base `.tpl` rule shadows both with light\n// defaults and the picker ignores dark mode + custom theme colors.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\nconst showRawValue = inject(MERGE_TAG_SHOW_RAW_VALUE_KEY, true);\n\n// Replacing an existing tag rather than inserting a new one. Drives the title\n// and which row starts highlighted.\nconst isChanging = computed(() => picker.current.value !== null);\n\nconst modalTitle = computed(() =>\n isChanging.value ? t.mergeTag.picker.changeTitle : t.mergeTag.picker.title,\n);\n\n/**\n * A row's native tooltip. The description alone when the consumer hid raw\n * tokens — the picker is a list of labels, so leaking the token here would\n * defeat `showRawValue` on the one surface that exists to choose tags.\n */\nfunction rowTitle(tag: MergeTag): string | undefined {\n if (!showRawValue) return tag.description || undefined;\n return tag.description ? `${tag.value} — ${tag.description}` : tag.value;\n}\n\n// --- Search ---\nconst rawSearch = ref(\"\");\n// 200ms debounce keeps filtering responsive at 1000+ tags. The raw value\n// drives the input element (so typing feels instant); the filter reads\n// the debounced copy.\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-merge-tag-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\n// --- Highlight (keyboard nav state) ---\nconst highlightedIndex = ref(0);\n\n// --- Grouping mode ---\n// Active only when at least one tag carries `group`. When inactive, the\n// list renders flat with no headers (not even \"Other\"). The plan locks\n// this down in \"Decisions locked in\" #7.\nconst hasGroups = computed(() =>\n picker.tags.value.some((tag) => Boolean(tag.group)),\n);\n\n// --- Collapsed groups (by label) ---\n// Reset on every modal open so each session starts with all groups\n// visible. Persistence across opens would surprise users who expanded\n// in a previous edit; the cost of re-collapsing is one click.\nconst collapsedGroups = ref<Set<string>>(new Set());\nfunction isCollapsed(group: string): boolean {\n return collapsedGroups.value.has(group);\n}\nfunction toggleGroup(group: string): void {\n const next = new Set(collapsedGroups.value);\n if (next.has(group)) next.delete(group);\n else next.add(group);\n collapsedGroups.value = next;\n // Re-anchor highlight to the first visible tag — index of a\n // previously-highlighted item may now point elsewhere after the\n // collapse rearranges visibleTags.\n highlightedIndex.value = 0;\n}\n\n// --- Filtered tags ---\n// Case-insensitive substring match against label, value, description.\n// Insertion order is preserved (per decision #9).\nconst filteredTags = computed<MergeTag[]>(() => {\n const query = search.value.trim().toLowerCase();\n if (!query) return picker.tags.value;\n return picker.tags.value.filter((tag) => {\n const haystack = [tag.label, tag.value, tag.description ?? \"\"]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(query);\n });\n});\n\n// --- Group order (insertion order of first appearance) ---\n// Computed against the *full* tags list (not the filtered one) so the\n// pill row stays stable as the user types. The pills represent the\n// configured groupings; filter just adjusts which items are shown.\nconst groupOrder = computed<string[]>(() => {\n if (!hasGroups.value) return [];\n const otherLabel = t.mergeTag.picker.otherGroup;\n const seen = new Set<string>();\n const order: string[] = [];\n for (const tag of picker.tags.value) {\n const key = tag.group ?? otherLabel;\n if (seen.has(key)) continue;\n seen.add(key);\n order.push(key);\n }\n return order;\n});\n\n// --- Rendered rows (header + tag entries) ---\n// Headers are only emitted in grouped mode AND only when there is no\n// active search query (per decisions #6 + #7). Flat-list mode and\n// search-active mode both render a header-less sequence.\n//\n// Collapsed groups still emit their header row (so the header stays\n// clickable), but skip their tag rows entirely — those tags are then\n// absent from `visibleTags` and the highlight skips over them.\ntype Row =\n | { kind: \"header\"; group: string; count: number }\n | { kind: \"tag\"; tag: MergeTag; index: number };\n\nconst rows = computed<Row[]>(() => {\n const tags = filteredTags.value;\n if (!hasGroups.value || searchActive.value) {\n return tags.map((tag, index) => ({ kind: \"tag\", tag, index }));\n }\n\n // Grouped mode: bucket by `group`, ungrouped → \"Other\".\n const otherLabel = t.mergeTag.picker.otherGroup;\n const buckets = new Map<string, MergeTag[]>();\n // Insertion order over the first appearance of each group label.\n const order: string[] = [];\n for (const tag of tags) {\n const key = tag.group ?? otherLabel;\n if (!buckets.has(key)) {\n buckets.set(key, []);\n order.push(key);\n }\n buckets.get(key)!.push(tag);\n }\n\n const result: Row[] = [];\n let tagIndex = 0;\n for (const groupKey of order) {\n const items = buckets.get(groupKey)!;\n result.push({ kind: \"header\", group: groupKey, count: items.length });\n if (collapsedGroups.value.has(groupKey)) continue;\n for (const tag of items) {\n result.push({ kind: \"tag\", tag, index: tagIndex });\n tagIndex++;\n }\n }\n return result;\n});\n\n// Flat list of tag-rows only — used for highlight bookkeeping. Keyboard\n// nav skips headers, so the highlight index addresses this list directly.\nconst visibleTags = computed(() =>\n rows.value.flatMap((row) => (row.kind === \"tag\" ? [row.tag] : [])),\n);\n\n/**\n * Whether the highlight is still waiting to land on the tag being replaced.\n *\n * `search` is debounced, so right after `open()` it can still hold the previous\n * session's query and the row we want may not be in `visibleTags` yet. The flag\n * keeps trying as the list settles, and any deliberate move by the user clears\n * it so a late debounce can't yank the highlight back.\n */\nlet preselectPending = false;\n\nfunction preselectCurrent(candidates: MergeTag[]): boolean {\n const target = picker.current.value;\n if (!target) return false;\n const index = candidates.findIndex((tag) => tag.value === target.value);\n if (index === -1) return false;\n highlightedIndex.value = index;\n return true;\n}\n\nfunction setHighlight(index: number): void {\n preselectPending = false;\n highlightedIndex.value = index;\n}\n\n// --- Lifecycle: focus search + reset state when modal opens ---\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (!isOpen) {\n preselectPending = false;\n return;\n }\n {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n collapsedGroups.value = new Set();\n preselectPending = !preselectCurrent(visibleTags.value);\n // Search input is mounted as part of the same render cycle the\n // modal opens; nextTick guarantees the ref is bound before focus.\n nextTick(() => {\n searchInputRef.value?.focus();\n });\n }\n },\n);\n\n// Keep the highlight inside the visible-tags bounds whenever the\n// filtered list shrinks (e.g. user typed a more specific query).\nwatch(visibleTags, (next) => {\n if (preselectPending && preselectCurrent(next)) {\n preselectPending = false;\n return;\n }\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\n// --- Actions ---\nfunction selectTag(tag: MergeTag): void {\n picker.resolve(tag);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleTags.value.length === 0) return;\n preselectPending = false;\n const next = highlightedIndex.value + delta;\n // Stop at edges (don't wrap) — feels more predictable in a long list.\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleTags.value.length - 1, next),\n );\n scrollHighlightIntoView();\n}\n\nconst listRef = ref<HTMLElement | null>(null);\n// One ref per group header so the pill row can `scrollIntoView` precisely.\n// Bound by callback-ref in the template; cleared (set to null) when Vue\n// unmounts the header during re-render.\nconst headerRefs = ref<Record<string, HTMLElement | null>>({});\n// Vue's callback-ref type widens to Element | ComponentPublicInstance | null\n// because the same ref shape works for both DOM elements and components.\n// Headers are always native buttons, so coerce to HTMLElement once here.\nfunction setHeaderRef(\n group: string,\n el: Element | ComponentPublicInstance | null,\n): void {\n headerRefs.value[group] = (el as HTMLElement | null) ?? null;\n}\n\nfunction scrollHighlightIntoView(): void {\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n const el = container.querySelector<HTMLElement>(\n `[data-merge-tag-index=\"${highlightedIndex.value}\"]`,\n );\n el?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction jumpToGroup(group: string): void {\n // Expand the group if it was collapsed — otherwise scrolling reveals\n // only the header, which is confusing for a \"jump to\" affordance.\n if (collapsedGroups.value.has(group)) {\n const next = new Set(collapsedGroups.value);\n next.delete(group);\n collapsedGroups.value = next;\n }\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n // Sum the height of every child rendered BEFORE the target header.\n // Avoids two browser quirks:\n // - `scrollIntoView({ block: \"start\" })` short-circuits when the\n // element is currently sticky-pinned at top.\n // - `offsetTop` historically misreported on sticky elements in some\n // Chromium versions; offsetHeight on each in-flow child is stable.\n // Each child is a top-level DOM row (header button or tag button),\n // and there are at most a few dozen, so the linear scan is cheap.\n let targetScrollTop = 0;\n let found = false;\n for (const child of Array.from(container.children) as HTMLElement[]) {\n if (\n child.dataset.testid === \"merge-tag-picker-group-header\" &&\n child.dataset.groupName === group\n ) {\n found = true;\n break;\n }\n targetScrollTop += child.offsetHeight;\n }\n if (!found) return;\n container.scrollTo({ top: targetScrollTop, behavior: \"smooth\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const tag = visibleTags.value[highlightedIndex.value];\n if (tag) selectTag(tag);\n }\n // Esc is forwarded by TplModal via its own keydown→close path.\n}\n\nfunction activeOptionId(): string | undefined {\n if (visibleTags.value.length === 0) return undefined;\n return `${listId}-opt-${highlightedIndex.value}`;\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\n\n// --- Empty states ---\n// Distinguish two cases so the messaging is honest:\n// - the consumer configured zero tags (defensive — button shouldn't even\n// render in that case but a programmatic open() should still degrade)\n// - the active search matched nothing\n//\n// `filteredTags` (NOT `visibleTags`) is the correct signal for \"no\n// results\" — visibleTags also excludes tags inside collapsed groups, so\n// collapsing every group would otherwise falsely trigger the empty\n// state and hide the headers the user wants to see.\nconst isEmptyConfig = computed(() => picker.tags.value.length === 0);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && filteredTags.value.length === 0,\n);\n\n// --- Pill row visibility ---\n// Pills jump-link to group headers; they only make sense when there are\n// at least 2 groups AND the user isn't currently searching (search\n// collapses the grouped view to a flat list, so the pills' targets\n// disappear).\nconst showPillRow = computed(\n () => hasGroups.value && groupOrder.value.length > 1 && !searchActive.value,\n);\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"merge-tag-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <!-- Header -->\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ modalTitle }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.mergeTag.picker.close\"\n data-testid=\"merge-tag-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <!-- Search -->\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.mergeTag.picker.searchPlaceholder\"\n :aria-label=\"t.mergeTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"merge-tag-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <!-- Group pills — visible only when grouping is active and the\n user isn't searching. Click a pill to jump (and expand) the\n matching group. Horizontally scrollable so a long group list\n degrades gracefully. -->\n <div\n v-if=\"showPillRow\"\n class=\"tpl:flex tpl:gap-1.5 tpl:overflow-x-auto tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2\"\n data-testid=\"merge-tag-picker-group-pills\"\n >\n <button\n v-for=\"group in groupOrder\"\n :key=\"group\"\n type=\"button\"\n class=\"tpl:flex tpl:flex-shrink-0 tpl:cursor-pointer tpl:items-center tpl:rounded-full tpl:border tpl:border-[var(--tpl-border)] tpl:bg-transparent tpl:px-2.5 tpl:py-0.5 tpl:text-[10px] tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n data-testid=\"merge-tag-picker-group-pill\"\n :data-group-name=\"group\"\n @click=\"jumpToGroup(group)\"\n >\n {{ group }}\n </button>\n </div>\n\n <!-- Body / list -->\n <!-- `position: relative` makes this the offsetParent for the sticky\n group headers below, so `header.offsetTop` reliably reports each\n header's natural in-flow position. jumpToGroup() depends on this\n — see the comment in jumpToGroup() for why scrollIntoView isn't\n sufficient. -->\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"modalTitle\"\n data-testid=\"merge-tag-picker-list\"\n >\n <template v-if=\"isEmptyConfig\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.empty }}\n </div>\n </template>\n <template v-else-if=\"isNoResults\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.noResults }}\n </div>\n </template>\n <template v-else>\n <template v-for=\"(row, rowIndex) in rows\" :key=\"rowIndex\">\n <button\n v-if=\"row.kind === 'header'\"\n :ref=\"(el) => setHeaderRef(row.group, el)\"\n type=\"button\"\n :aria-expanded=\"!isCollapsed(row.group)\"\n :aria-controls=\"listId\"\n class=\"tpl:sticky tpl:top-0 tpl:z-10 tpl:flex tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-1.5 tpl:border-none tpl:bg-[var(--tpl-bg-elevated)] tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-left tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)]\"\n data-testid=\"merge-tag-picker-group-header\"\n :data-group-name=\"row.group\"\n :data-group-collapsed=\"isCollapsed(row.group) ? 'true' : 'false'\"\n @click=\"toggleGroup(row.group)\"\n >\n <ChevronDown\n :size=\"12\"\n :stroke-width=\"2\"\n class=\"tpl:transition-transform\"\n :class=\"isCollapsed(row.group) ? 'tpl:-rotate-90' : ''\"\n />\n <span>{{ row.group }}</span>\n <span class=\"tpl:ml-1 tpl:font-normal\">\n ({{\n format(t.mergeTag.picker.groupCount, { count: row.count })\n }})\n </span>\n </button>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-merge-tag-index=\"row.index\"\n :data-merge-tag-value=\"row.tag.value\"\n :aria-current=\"\n row.tag.value === picker.current.value?.value\n ? 'true'\n : undefined\n \"\n :title=\"rowTitle(row.tag)\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"merge-tag-picker-item\"\n @mousemove=\"setHighlight(row.index)\"\n @click=\"selectTag(row.tag)\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.tag.label\n }}</span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.value }}\n </span>\n <span\n v-if=\"row.tag.description\"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.description }}\n </span>\n <!-- What the previews will render in Sample mode, so an author\n knows before inserting. Shown only when configured. -->\n <span\n v-if=\"row.tag.sample !== undefined\"\n data-testid=\"merge-tag-picker-sample\"\n class=\"tpl:line-clamp-1 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n format(t.mergeTag.picker.sample, { sample: row.tag.sample })\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n inject,\n nextTick,\n ref,\n watch,\n type ComponentPublicInstance,\n} from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { ChevronDown, Search, X } from \"@lucide/vue\";\nimport type { MergeTag } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n MERGE_TAG_PICKER_KEY,\n MERGE_TAG_SHOW_RAW_VALUE_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\n\n// Picker singleton — provided by useEditorCore. We require it explicitly so\n// the modal is unmountable only in a non-editor context (which we don't\n// support). `requireInject` throws a clear message rather than letting a\n// silent inject default mask the misuse.\nconst picker = requireInject(MERGE_TAG_PICKER_KEY, \"MergeTagPickerModal\");\nconst { t, format } = useI18n();\n\n// Theming — same pattern as every other OSS panel (ParagraphToolbar,\n// RichTextLinkDialog). The panel carries the `tpl` token class, so it must\n// re-establish the theme locally: `data-tpl-theme` selects the dark token\n// block, and the inline `themeStyles` apply the consumer's `theme` config\n// overrides. Without these the base `.tpl` rule shadows both with light\n// defaults and the picker ignores dark mode + custom theme colors.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\nconst showRawValue = inject(MERGE_TAG_SHOW_RAW_VALUE_KEY, true);\n\n// Replacing an existing tag rather than inserting a new one. Drives the title\n// and which row starts highlighted.\nconst isChanging = computed(() => picker.current.value !== null);\n\nconst modalTitle = computed(() =>\n isChanging.value ? t.mergeTag.picker.changeTitle : t.mergeTag.picker.title,\n);\n\n/**\n * A row's native tooltip. The description alone when the consumer hid raw\n * tokens — the picker is a list of labels, so leaking the token here would\n * defeat `showRawValue` on the one surface that exists to choose tags.\n */\nfunction rowTitle(tag: MergeTag): string | undefined {\n if (!showRawValue) return tag.description || undefined;\n return tag.description ? `${tag.value} — ${tag.description}` : tag.value;\n}\n\n// --- Search ---\nconst rawSearch = ref(\"\");\n// 200ms debounce keeps filtering responsive at 1000+ tags. The raw value\n// drives the input element (so typing feels instant); the filter reads\n// the debounced copy.\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-merge-tag-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\n// --- Highlight (keyboard nav state) ---\nconst highlightedIndex = ref(0);\n\n// --- Grouping mode ---\n// Active only when at least one tag carries `group`. When inactive, the\n// list renders flat with no headers (not even \"Other\"). The plan locks\n// this down in \"Decisions locked in\" #7.\nconst hasGroups = computed(() =>\n picker.tags.value.some((tag) => Boolean(tag.group)),\n);\n\n// --- Collapsed groups (by label) ---\n// Reset on every modal open so each session starts with all groups\n// visible. Persistence across opens would surprise users who expanded\n// in a previous edit; the cost of re-collapsing is one click.\nconst collapsedGroups = ref<Set<string>>(new Set());\nfunction isCollapsed(group: string): boolean {\n return collapsedGroups.value.has(group);\n}\nfunction toggleGroup(group: string): void {\n const next = new Set(collapsedGroups.value);\n if (next.has(group)) next.delete(group);\n else next.add(group);\n collapsedGroups.value = next;\n // Re-anchor highlight to the first visible tag — index of a\n // previously-highlighted item may now point elsewhere after the\n // collapse rearranges visibleTags.\n highlightedIndex.value = 0;\n}\n\n// --- Filtered tags ---\n// Case-insensitive substring match against label, value, description.\n// Insertion order is preserved (per decision #9).\nconst filteredTags = computed<MergeTag[]>(() => {\n const query = search.value.trim().toLowerCase();\n if (!query) return picker.tags.value;\n return picker.tags.value.filter((tag) => {\n const haystack = [tag.label, tag.value, tag.description ?? \"\"]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(query);\n });\n});\n\n// --- Group order (insertion order of first appearance) ---\n// Computed against the *full* tags list (not the filtered one) so the\n// pill row stays stable as the user types. The pills represent the\n// configured groupings; filter just adjusts which items are shown.\nconst groupOrder = computed<string[]>(() => {\n if (!hasGroups.value) return [];\n const otherLabel = t.mergeTag.picker.otherGroup;\n const seen = new Set<string>();\n const order: string[] = [];\n for (const tag of picker.tags.value) {\n const key = tag.group ?? otherLabel;\n if (seen.has(key)) continue;\n seen.add(key);\n order.push(key);\n }\n return order;\n});\n\n// --- Rendered rows (header + tag entries) ---\n// Headers are only emitted in grouped mode AND only when there is no\n// active search query (per decisions #6 + #7). Flat-list mode and\n// search-active mode both render a header-less sequence.\n//\n// Collapsed groups still emit their header row (so the header stays\n// clickable), but skip their tag rows entirely — those tags are then\n// absent from `visibleTags` and the highlight skips over them.\ntype Row =\n | { kind: \"header\"; group: string; count: number }\n | { kind: \"tag\"; tag: MergeTag; index: number };\n\nconst rows = computed<Row[]>(() => {\n const tags = filteredTags.value;\n if (!hasGroups.value || searchActive.value) {\n return tags.map((tag, index) => ({ kind: \"tag\", tag, index }));\n }\n\n // Grouped mode: bucket by `group`, ungrouped → \"Other\".\n const otherLabel = t.mergeTag.picker.otherGroup;\n const buckets = new Map<string, MergeTag[]>();\n // Insertion order over the first appearance of each group label.\n const order: string[] = [];\n for (const tag of tags) {\n const key = tag.group ?? otherLabel;\n if (!buckets.has(key)) {\n buckets.set(key, []);\n order.push(key);\n }\n buckets.get(key)!.push(tag);\n }\n\n const result: Row[] = [];\n let tagIndex = 0;\n for (const groupKey of order) {\n const items = buckets.get(groupKey)!;\n result.push({ kind: \"header\", group: groupKey, count: items.length });\n if (collapsedGroups.value.has(groupKey)) continue;\n for (const tag of items) {\n result.push({ kind: \"tag\", tag, index: tagIndex });\n tagIndex++;\n }\n }\n return result;\n});\n\n// Flat list of tag-rows only — used for highlight bookkeeping. Keyboard\n// nav skips headers, so the highlight index addresses this list directly.\nconst visibleTags = computed(() =>\n rows.value.flatMap((row) => (row.kind === \"tag\" ? [row.tag] : [])),\n);\n\n/**\n * Whether the highlight is still waiting to land on the tag being replaced.\n *\n * `search` is debounced, so right after `open()` it can still hold the previous\n * session's query and the row we want may not be in `visibleTags` yet. The flag\n * keeps trying as the list settles, and any deliberate move by the user clears\n * it so a late debounce can't yank the highlight back.\n */\nlet preselectPending = false;\n\nfunction preselectCurrent(candidates: MergeTag[]): boolean {\n const target = picker.current.value;\n if (!target) return false;\n const index = candidates.findIndex((tag) => tag.value === target.value);\n if (index === -1) return false;\n highlightedIndex.value = index;\n return true;\n}\n\nfunction setHighlight(index: number): void {\n preselectPending = false;\n highlightedIndex.value = index;\n}\n\n// --- Lifecycle: focus search + reset state when modal opens ---\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (!isOpen) {\n preselectPending = false;\n return;\n }\n {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n collapsedGroups.value = new Set();\n preselectPending = !preselectCurrent(visibleTags.value);\n // Search input is mounted as part of the same render cycle the\n // modal opens; nextTick guarantees the ref is bound before focus.\n nextTick(() => {\n searchInputRef.value?.focus();\n });\n }\n },\n);\n\n// Keep the highlight inside the visible-tags bounds whenever the\n// filtered list shrinks (e.g. user typed a more specific query).\nwatch(visibleTags, (next) => {\n if (preselectPending && preselectCurrent(next)) {\n preselectPending = false;\n return;\n }\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\n// --- Actions ---\nfunction selectTag(tag: MergeTag): void {\n picker.resolve(tag);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleTags.value.length === 0) return;\n preselectPending = false;\n const next = highlightedIndex.value + delta;\n // Stop at edges (don't wrap) — feels more predictable in a long list.\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleTags.value.length - 1, next),\n );\n scrollHighlightIntoView();\n}\n\nconst listRef = ref<HTMLElement | null>(null);\n// One ref per group header so the pill row can `scrollIntoView` precisely.\n// Bound by callback-ref in the template; cleared (set to null) when Vue\n// unmounts the header during re-render.\nconst headerRefs = ref<Record<string, HTMLElement | null>>({});\n// Vue's callback-ref type widens to Element | ComponentPublicInstance | null\n// because the same ref shape works for both DOM elements and components.\n// Headers are always native buttons, so coerce to HTMLElement once here.\nfunction setHeaderRef(\n group: string,\n el: Element | ComponentPublicInstance | null,\n): void {\n headerRefs.value[group] = (el as HTMLElement | null) ?? null;\n}\n\nfunction scrollHighlightIntoView(): void {\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n const el = container.querySelector<HTMLElement>(\n `[data-merge-tag-index=\"${highlightedIndex.value}\"]`,\n );\n el?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction jumpToGroup(group: string): void {\n // Expand the group if it was collapsed — otherwise scrolling reveals\n // only the header, which is confusing for a \"jump to\" affordance.\n if (collapsedGroups.value.has(group)) {\n const next = new Set(collapsedGroups.value);\n next.delete(group);\n collapsedGroups.value = next;\n }\n nextTick(() => {\n const container = listRef.value;\n if (!container) return;\n // Sum the height of every child rendered BEFORE the target header.\n // Avoids two browser quirks:\n // - `scrollIntoView({ block: \"start\" })` short-circuits when the\n // element is currently sticky-pinned at top.\n // - `offsetTop` historically misreported on sticky elements in some\n // Chromium versions; offsetHeight on each in-flow child is stable.\n // Each child is a top-level DOM row (header button or tag button),\n // and there are at most a few dozen, so the linear scan is cheap.\n let targetScrollTop = 0;\n let found = false;\n for (const child of Array.from(container.children) as HTMLElement[]) {\n if (\n child.dataset.testid === \"merge-tag-picker-group-header\" &&\n child.dataset.groupName === group\n ) {\n found = true;\n break;\n }\n targetScrollTop += child.offsetHeight;\n }\n if (!found) return;\n container.scrollTo({ top: targetScrollTop, behavior: \"smooth\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const tag = visibleTags.value[highlightedIndex.value];\n if (tag) selectTag(tag);\n }\n // Esc is forwarded by TplModal via its own keydown→close path.\n}\n\nfunction activeOptionId(): string | undefined {\n if (visibleTags.value.length === 0) return undefined;\n return `${listId}-opt-${highlightedIndex.value}`;\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\n\n// --- Empty states ---\n// Distinguish two cases so the messaging is honest:\n// - the consumer configured zero tags (defensive — button shouldn't even\n// render in that case but a programmatic open() should still degrade)\n// - the active search matched nothing\n//\n// `filteredTags` (NOT `visibleTags`) is the correct signal for \"no\n// results\" — visibleTags also excludes tags inside collapsed groups, so\n// collapsing every group would otherwise falsely trigger the empty\n// state and hide the headers the user wants to see.\nconst isEmptyConfig = computed(() => picker.tags.value.length === 0);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && filteredTags.value.length === 0,\n);\n\n// --- Pill row visibility ---\n// Pills jump-link to group headers; they only make sense when there are\n// at least 2 groups AND the user isn't currently searching (search\n// collapses the grouped view to a flat list, so the pills' targets\n// disappear).\nconst showPillRow = computed(\n () => hasGroups.value && groupOrder.value.length > 1 && !searchActive.value,\n);\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"merge-tag-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <!-- Header -->\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ modalTitle }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.mergeTag.picker.close\"\n data-testid=\"merge-tag-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <!-- Search -->\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.mergeTag.picker.searchPlaceholder\"\n :aria-label=\"t.mergeTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"merge-tag-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <!-- Group pills — visible only when grouping is active and the\n user isn't searching. Click a pill to jump (and expand) the\n matching group. Horizontally scrollable so a long group list\n degrades gracefully. -->\n <div\n v-if=\"showPillRow\"\n class=\"tpl:flex tpl:gap-1.5 tpl:overflow-x-auto tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2\"\n data-testid=\"merge-tag-picker-group-pills\"\n >\n <button\n v-for=\"group in groupOrder\"\n :key=\"group\"\n type=\"button\"\n class=\"tpl:flex tpl:flex-shrink-0 tpl:cursor-pointer tpl:items-center tpl:rounded-full tpl:border tpl:border-[var(--tpl-border)] tpl:bg-transparent tpl:px-2.5 tpl:py-0.5 tpl:text-[10px] tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n data-testid=\"merge-tag-picker-group-pill\"\n :data-group-name=\"group\"\n @click=\"jumpToGroup(group)\"\n >\n {{ group }}\n </button>\n </div>\n\n <!-- Body / list -->\n <!-- `position: relative` makes this the offsetParent for the sticky\n group headers below, so `header.offsetTop` reliably reports each\n header's natural in-flow position. jumpToGroup() depends on this\n — see the comment in jumpToGroup() for why scrollIntoView isn't\n sufficient. -->\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"modalTitle\"\n data-testid=\"merge-tag-picker-list\"\n >\n <template v-if=\"isEmptyConfig\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.empty }}\n </div>\n </template>\n <template v-else-if=\"isNoResults\">\n <div\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"merge-tag-picker-empty\"\n >\n {{ t.mergeTag.picker.noResults }}\n </div>\n </template>\n <template v-else>\n <template v-for=\"(row, rowIndex) in rows\" :key=\"rowIndex\">\n <button\n v-if=\"row.kind === 'header'\"\n :ref=\"(el) => setHeaderRef(row.group, el)\"\n type=\"button\"\n :aria-expanded=\"!isCollapsed(row.group)\"\n :aria-controls=\"listId\"\n class=\"tpl:sticky tpl:top-0 tpl:z-10 tpl:flex tpl:w-full tpl:cursor-pointer tpl:items-center tpl:gap-1.5 tpl:border-none tpl:bg-[var(--tpl-bg-elevated)] tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-left tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)]\"\n data-testid=\"merge-tag-picker-group-header\"\n :data-group-name=\"row.group\"\n :data-group-collapsed=\"isCollapsed(row.group) ? 'true' : 'false'\"\n @click=\"toggleGroup(row.group)\"\n >\n <ChevronDown\n :size=\"12\"\n :stroke-width=\"2\"\n class=\"tpl:transition-transform\"\n :class=\"isCollapsed(row.group) ? 'tpl:-rotate-90' : ''\"\n />\n <span>{{ row.group }}</span>\n <span class=\"tpl:ml-1 tpl:font-normal\">\n ({{\n format(t.mergeTag.picker.groupCount, { count: row.count })\n }})\n </span>\n </button>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-merge-tag-index=\"row.index\"\n :data-merge-tag-value=\"row.tag.value\"\n :aria-current=\"\n row.tag.value === picker.current.value?.value\n ? 'true'\n : undefined\n \"\n :title=\"rowTitle(row.tag)\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"merge-tag-picker-item\"\n @mousemove=\"setHighlight(row.index)\"\n @click=\"selectTag(row.tag)\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.tag.label\n }}</span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.value }}\n </span>\n <span\n v-if=\"row.tag.description\"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{ row.tag.description }}\n </span>\n <!-- What the previews will render in Sample mode, so an author\n knows before inserting. Shown only when configured. -->\n <span\n v-if=\"row.tag.sample !== undefined\"\n data-testid=\"merge-tag-picker-sample\"\n class=\"tpl:line-clamp-1 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n format(t.mergeTag.picker.sample, { sample: row.tag.sample })\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n getLogicMergeTagKeyword,\n isLogicMergeTagValue,\n type SyntaxPreset,\n} from \"@templatical/types\";\nimport { computed } from \"vue\";\n\n// Small outlined keyword chip (IF, ENDIF, FOR…) shown next to a tag in the\n// merge tag picker and the typing-autocomplete list. It marks a configured\n// tag whose `value` is a logic tag rather than a data tag, so authors can\n// tell at a glance which entries insert control flow. The visual mirrors the\n// on-canvas logic badge (outlined, primary color) for consistency. Renders\n// nothing when the value isn't logic-shaped, so callers can drop it into any\n// row unconditionally.\nconst props = defineProps<{ value: string; syntax: SyntaxPreset }>();\n\nconst isLogic = computed(() => isLogicMergeTagValue(props.value, props.syntax));\nconst keyword = computed(() =>\n getLogicMergeTagKeyword(props.value, props.syntax),\n);\n</script>\n\n<template>\n <span\n v-if=\"isLogic\"\n class=\"tpl:inline-flex tpl:flex-shrink-0 tpl:items-center tpl:rounded tpl:px-1.5 tpl:py-0.5 tpl:text-[10px] tpl:leading-none tpl:font-bold tpl:tracking-wide tpl:uppercase\"\n style=\"\n border: 1.5px solid\n color-mix(in srgb, var(--tpl-primary) 50%, transparent);\n color: var(--tpl-primary);\n \"\n data-testid=\"merge-tag-logic-badge\"\n :data-logic-keyword=\"keyword\"\n >\n {{ keyword }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport {\n getLogicMergeTagKeyword,\n isLogicMergeTagValue,\n type SyntaxPreset,\n} from \"@templatical/types\";\nimport { computed } from \"vue\";\n\n// Small outlined keyword chip (IF, ENDIF, FOR…) shown next to a tag in the\n// merge tag picker and the typing-autocomplete list. It marks a configured\n// tag whose `value` is a logic tag rather than a data tag, so authors can\n// tell at a glance which entries insert control flow. The visual mirrors the\n// on-canvas logic badge (outlined, primary color) for consistency. Renders\n// nothing when the value isn't logic-shaped, so callers can drop it into any\n// row unconditionally.\nconst props = defineProps<{ value: string; syntax: SyntaxPreset }>();\n\nconst isLogic = computed(() => isLogicMergeTagValue(props.value, props.syntax));\nconst keyword = computed(() =>\n getLogicMergeTagKeyword(props.value, props.syntax),\n);\n</script>\n\n<template>\n <span\n v-if=\"isLogic\"\n class=\"tpl:inline-flex tpl:flex-shrink-0 tpl:items-center tpl:rounded tpl:px-1.5 tpl:py-0.5 tpl:text-[10px] tpl:leading-none tpl:font-bold tpl:tracking-wide tpl:uppercase\"\n style=\"\n border: 1.5px solid\n color-mix(in srgb, var(--tpl-primary) 50%, transparent);\n color: var(--tpl-primary);\n \"\n data-testid=\"merge-tag-logic-badge\"\n :data-logic-keyword=\"keyword\"\n >\n {{ keyword }}\n </span>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { Search, X } from \"@lucide/vue\";\nimport type { LogicPair, LogicTag, SyntaxPreset } from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport LogicTagBadge from \"./LogicTagBadge.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n LOGIC_TAG_PICKER_KEY,\n MERGE_TAG_SYNTAX_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\nimport type { LogicTagPickerResult } from \"../composables/useLogicTagPicker\";\n\n// Picker singleton — provided by useEditorCore. Required explicitly so the\n// modal only functions inside an editor context.\nconst picker = requireInject(LOGIC_TAG_PICKER_KEY, \"LogicTagPickerModal\");\nconst { t } = useI18n();\nconst syntax = inject<SyntaxPreset>(\n MERGE_TAG_SYNTAX_KEY,\n SYNTAX_PRESETS.liquid,\n);\n\n// Theming — same pattern as MergeTagPickerModal: re-establish the theme\n// locally so the `.tpl` token root resolves dark mode + consumer overrides.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\n\nconst rawSearch = ref(\"\");\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-logic-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\nconst highlightedIndex = ref(0);\n\nfunction matches(haystackParts: (string | undefined)[]): boolean {\n const query = search.value.trim().toLowerCase();\n if (!query) return true;\n return haystackParts.filter(Boolean).join(\" \").toLowerCase().includes(query);\n}\n\nconst filteredTags = computed<LogicTag[]>(() =>\n picker.tags.value.filter((tag) =>\n matches([tag.label, tag.value, tag.description]),\n ),\n);\nconst filteredPairs = computed<LogicPair[]>(() =>\n picker.pairs.value.filter((pair) =>\n matches([pair.label, pair.before, pair.after, pair.description]),\n ),\n);\n\n// Tags and pairs share one grouped list: a `group` section holds both its\n// standalone tags and its open/close pairs, so a group used by both (e.g.\n// \"Conditions\") renders once instead of appearing separately for each kind.\n// The badge shape — one pill for a tag, two for a pair — signals\n// insert-vs-wrap per row.\ntype Entry =\n | { kind: \"tag\"; tag: LogicTag; group?: string }\n | { kind: \"pair\"; pair: LogicPair; group?: string };\n\n// Pairs first, then standalone tags, so within a shared group the wrapping\n// constructs (e.g. If VIP) sort ahead of single tokens (e.g. Else). Group\n// order follows first appearance across this combined sequence.\nconst filteredEntries = computed<Entry[]>(() => [\n ...filteredPairs.value.map((pair): Entry => ({\n kind: \"pair\",\n pair,\n group: pair.group,\n })),\n ...filteredTags.value.map((tag): Entry => ({\n kind: \"tag\",\n tag,\n group: tag.group,\n })),\n]);\n\nconst hasGroups = computed(\n () =>\n picker.tags.value.some((tag) => Boolean(tag.group)) ||\n picker.pairs.value.some((pair) => Boolean(pair.group)),\n);\n\n// Rows drive rendering; `items` is the parallel flat list of selectable\n// entries in render order, so `highlightedIndex` (keyboard nav) maps 1:1.\ntype Row =\n | { kind: \"header\"; label: string }\n | { kind: \"tag\"; tag: LogicTag; index: number }\n | { kind: \"pair\"; pair: LogicPair; index: number };\n\nfunction bucket(entries: Entry[]): [string, Entry[]][] {\n const otherLabel = t.logicTag.picker.otherGroup;\n const map = new Map<string, Entry[]>();\n const order: string[] = [];\n for (const entry of entries) {\n const key = entry.group ?? otherLabel;\n if (!map.has(key)) {\n map.set(key, []);\n order.push(key);\n }\n map.get(key)!.push(entry);\n }\n return order.map((key) => [key, map.get(key)!]);\n}\n\nconst built = computed(() => {\n const rows: Row[] = [];\n const items: LogicTagPickerResult[] = [];\n let idx = 0;\n\n const pushEntry = (entry: Entry): void => {\n if (entry.kind === \"tag\") {\n rows.push({ kind: \"tag\", tag: entry.tag, index: idx });\n items.push(entry.tag);\n } else {\n rows.push({ kind: \"pair\", pair: entry.pair, index: idx });\n items.push(entry.pair);\n }\n idx++;\n };\n\n const entries = filteredEntries.value;\n if (searchActive.value || !hasGroups.value) {\n // Flat list: search flattens groups (matches the merge-tag picker), and\n // an ungrouped config has no headers to render.\n for (const entry of entries) pushEntry(entry);\n } else {\n for (const [group, groupEntries] of bucket(entries)) {\n rows.push({ kind: \"header\", label: group });\n for (const entry of groupEntries) pushEntry(entry);\n }\n }\n\n return { rows, items };\n});\n\nconst visibleItems = computed(() => built.value.items);\n\nconst isEmptyConfig = computed(\n () => picker.tags.value.length === 0 && picker.pairs.value.length === 0,\n);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && visibleItems.value.length === 0,\n);\n\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (isOpen) {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n nextTick(() => searchInputRef.value?.focus());\n }\n },\n);\n\nwatch(visibleItems, (next) => {\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\nconst listRef = ref<HTMLElement | null>(null);\n\nfunction selectItem(item: LogicTagPickerResult): void {\n picker.resolve(item);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleItems.value.length === 0) return;\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleItems.value.length - 1, highlightedIndex.value + delta),\n );\n nextTick(() => {\n listRef.value\n ?.querySelector<HTMLElement>(\n `[data-logic-index=\"${highlightedIndex.value}\"]`,\n )\n ?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const item = visibleItems.value[highlightedIndex.value];\n if (item) selectItem(item);\n }\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\nfunction activeOptionId(): string | undefined {\n return visibleItems.value.length === 0\n ? undefined\n : `${listId}-opt-${highlightedIndex.value}`;\n}\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"logic-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.logicTag.picker.title }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.logicTag.picker.close\"\n data-testid=\"logic-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.logicTag.picker.searchPlaceholder\"\n :aria-label=\"t.logicTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"logic-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"t.logicTag.picker.title\"\n data-testid=\"logic-picker-list\"\n >\n <div\n v-if=\"isEmptyConfig\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.empty }}\n </div>\n <div\n v-else-if=\"isNoResults\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.noResults }}\n </div>\n <template v-else>\n <template v-for=\"(row, rowIndex) in built.rows\" :key=\"rowIndex\">\n <div\n v-if=\"row.kind === 'header'\"\n class=\"tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-header\"\n :data-group-name=\"row.label\"\n >\n {{ row.label }}\n </div>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-logic-index=\"row.index\"\n :data-logic-kind=\"row.kind\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"logic-picker-item\"\n @mousemove=\"highlightedIndex = row.index\"\n @click=\"selectItem(row.kind === 'tag' ? row.tag : row.pair)\"\n >\n <span\n class=\"tpl:flex tpl:w-full tpl:items-center tpl:justify-between tpl:gap-2\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.kind === \"tag\" ? row.tag.label : row.pair.label\n }}</span>\n <span\n v-if=\"row.kind === 'tag'\"\n class=\"tpl:flex tpl:items-center\"\n >\n <LogicTagBadge :value=\"row.tag.value\" :syntax=\"syntax\" />\n </span>\n <span v-else class=\"tpl:flex tpl:items-center tpl:gap-1\">\n <LogicTagBadge :value=\"row.pair.before\" :syntax=\"syntax\" />\n <span class=\"tpl:text-[var(--tpl-text-dim)]\">…</span>\n <LogicTagBadge :value=\"row.pair.after\" :syntax=\"syntax\" />\n </span>\n </span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.value\n : `${row.pair.before} … ${row.pair.after}`\n }}\n </span>\n <span\n v-if=\"\n (row.kind === 'tag'\n ? row.tag.description\n : row.pair.description) as string | undefined\n \"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.description\n : row.pair.description\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, inject, nextTick, ref, watch } from \"vue\";\nimport { refDebounced } from \"@vueuse/core\";\nimport { Search, X } from \"@lucide/vue\";\nimport type { LogicPair, LogicTag, SyntaxPreset } from \"@templatical/types\";\nimport { SYNTAX_PRESETS } from \"@templatical/types\";\nimport TplModal from \"./TplModal.vue\";\nimport LogicTagBadge from \"./LogicTagBadge.vue\";\nimport { useI18n } from \"../composables/useI18n\";\nimport {\n LOGIC_TAG_PICKER_KEY,\n MERGE_TAG_SYNTAX_KEY,\n THEME_STYLES_KEY,\n UI_THEME_KEY,\n requireInject,\n} from \"../keys\";\nimport type { LogicTagPickerResult } from \"../composables/useLogicTagPicker\";\n\n// Picker singleton — provided by useEditorCore. Required explicitly so the\n// modal only functions inside an editor context.\nconst picker = requireInject(LOGIC_TAG_PICKER_KEY, \"LogicTagPickerModal\");\nconst { t } = useI18n();\nconst syntax = inject<SyntaxPreset>(\n MERGE_TAG_SYNTAX_KEY,\n SYNTAX_PRESETS.liquid,\n);\n\n// Theming — same pattern as MergeTagPickerModal: re-establish the theme\n// locally so the `.tpl` token root resolves dark mode + consumer overrides.\nconst themeStyles = inject(THEME_STYLES_KEY, null);\nconst tplUiTheme = inject(UI_THEME_KEY, null);\n\nconst rawSearch = ref(\"\");\nconst search = refDebounced(rawSearch, 200);\nconst searchInputRef = ref<HTMLInputElement | null>(null);\nconst listId = \"tpl-logic-picker-list\";\nconst searchActive = computed(() => search.value.trim().length > 0);\n\nconst highlightedIndex = ref(0);\n\nfunction matches(haystackParts: (string | undefined)[]): boolean {\n const query = search.value.trim().toLowerCase();\n if (!query) return true;\n return haystackParts.filter(Boolean).join(\" \").toLowerCase().includes(query);\n}\n\nconst filteredTags = computed<LogicTag[]>(() =>\n picker.tags.value.filter((tag) =>\n matches([tag.label, tag.value, tag.description]),\n ),\n);\nconst filteredPairs = computed<LogicPair[]>(() =>\n picker.pairs.value.filter((pair) =>\n matches([pair.label, pair.before, pair.after, pair.description]),\n ),\n);\n\n// Tags and pairs share one grouped list: a `group` section holds both its\n// standalone tags and its open/close pairs, so a group used by both (e.g.\n// \"Conditions\") renders once instead of appearing separately for each kind.\n// The badge shape — one pill for a tag, two for a pair — signals\n// insert-vs-wrap per row.\ntype Entry =\n | { kind: \"tag\"; tag: LogicTag; group?: string }\n | { kind: \"pair\"; pair: LogicPair; group?: string };\n\n// Pairs first, then standalone tags, so within a shared group the wrapping\n// constructs (e.g. If VIP) sort ahead of single tokens (e.g. Else). Group\n// order follows first appearance across this combined sequence.\nconst filteredEntries = computed<Entry[]>(() => [\n ...filteredPairs.value.map((pair): Entry => ({\n kind: \"pair\",\n pair,\n group: pair.group,\n })),\n ...filteredTags.value.map((tag): Entry => ({\n kind: \"tag\",\n tag,\n group: tag.group,\n })),\n]);\n\nconst hasGroups = computed(\n () =>\n picker.tags.value.some((tag) => Boolean(tag.group)) ||\n picker.pairs.value.some((pair) => Boolean(pair.group)),\n);\n\n// Rows drive rendering; `items` is the parallel flat list of selectable\n// entries in render order, so `highlightedIndex` (keyboard nav) maps 1:1.\ntype Row =\n | { kind: \"header\"; label: string }\n | { kind: \"tag\"; tag: LogicTag; index: number }\n | { kind: \"pair\"; pair: LogicPair; index: number };\n\nfunction bucket(entries: Entry[]): [string, Entry[]][] {\n const otherLabel = t.logicTag.picker.otherGroup;\n const map = new Map<string, Entry[]>();\n const order: string[] = [];\n for (const entry of entries) {\n const key = entry.group ?? otherLabel;\n if (!map.has(key)) {\n map.set(key, []);\n order.push(key);\n }\n map.get(key)!.push(entry);\n }\n return order.map((key) => [key, map.get(key)!]);\n}\n\nconst built = computed(() => {\n const rows: Row[] = [];\n const items: LogicTagPickerResult[] = [];\n let idx = 0;\n\n const pushEntry = (entry: Entry): void => {\n if (entry.kind === \"tag\") {\n rows.push({ kind: \"tag\", tag: entry.tag, index: idx });\n items.push(entry.tag);\n } else {\n rows.push({ kind: \"pair\", pair: entry.pair, index: idx });\n items.push(entry.pair);\n }\n idx++;\n };\n\n const entries = filteredEntries.value;\n if (searchActive.value || !hasGroups.value) {\n // Flat list: search flattens groups (matches the merge-tag picker), and\n // an ungrouped config has no headers to render.\n for (const entry of entries) pushEntry(entry);\n } else {\n for (const [group, groupEntries] of bucket(entries)) {\n rows.push({ kind: \"header\", label: group });\n for (const entry of groupEntries) pushEntry(entry);\n }\n }\n\n return { rows, items };\n});\n\nconst visibleItems = computed(() => built.value.items);\n\nconst isEmptyConfig = computed(\n () => picker.tags.value.length === 0 && picker.pairs.value.length === 0,\n);\nconst isNoResults = computed(\n () => !isEmptyConfig.value && visibleItems.value.length === 0,\n);\n\nwatch(\n () => picker.isOpen.value,\n (isOpen) => {\n if (isOpen) {\n rawSearch.value = \"\";\n highlightedIndex.value = 0;\n nextTick(() => searchInputRef.value?.focus());\n }\n },\n);\n\nwatch(visibleItems, (next) => {\n if (highlightedIndex.value >= next.length) {\n highlightedIndex.value = Math.max(0, next.length - 1);\n }\n});\n\nconst listRef = ref<HTMLElement | null>(null);\n\nfunction selectItem(item: LogicTagPickerResult): void {\n picker.resolve(item);\n}\n\nfunction cancel(): void {\n picker.resolve(null);\n}\n\nfunction moveHighlight(delta: number): void {\n if (visibleItems.value.length === 0) return;\n highlightedIndex.value = Math.max(\n 0,\n Math.min(visibleItems.value.length - 1, highlightedIndex.value + delta),\n );\n nextTick(() => {\n listRef.value\n ?.querySelector<HTMLElement>(\n `[data-logic-index=\"${highlightedIndex.value}\"]`,\n )\n ?.scrollIntoView({ block: \"nearest\" });\n });\n}\n\nfunction onKeydown(event: KeyboardEvent): void {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n moveHighlight(1);\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n moveHighlight(-1);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const item = visibleItems.value[highlightedIndex.value];\n if (item) selectItem(item);\n }\n}\n\nfunction optionId(index: number): string {\n return `${listId}-opt-${index}`;\n}\nfunction activeOptionId(): string | undefined {\n return visibleItems.value.length === 0\n ? undefined\n : `${listId}-opt-${highlightedIndex.value}`;\n}\n</script>\n\n<template>\n <TplModal :visible=\"picker.isOpen.value\" @close=\"cancel\" @keydown=\"onKeydown\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n :aria-labelledby=\"`${listId}-title`\"\n :data-tpl-theme=\"tplUiTheme\"\n data-testid=\"logic-picker-modal\"\n class=\"tpl tpl:flex tpl:max-h-[80%] tpl:w-[420px] tpl:max-w-full tpl:flex-col tpl:rounded-[var(--tpl-radius)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:shadow-[var(--tpl-shadow-lg)]\"\n :style=\"themeStyles\"\n >\n <header\n class=\"tpl:flex tpl:items-center tpl:justify-between tpl:gap-3 tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <h2\n :id=\"`${listId}-title`\"\n class=\"tpl:m-0 tpl:text-sm tpl:font-semibold tpl:text-[var(--tpl-text)]\"\n >\n {{ t.logicTag.picker.title }}\n </h2>\n <button\n type=\"button\"\n class=\"tpl:flex tpl:h-7 tpl:w-7 tpl:cursor-pointer tpl:items-center tpl:justify-center tpl:rounded-[var(--tpl-radius-sm)] tpl:border-none tpl:bg-transparent tpl:text-[var(--tpl-text-dim)] tpl:transition-colors tpl:hover:bg-[var(--tpl-bg-hover)] tpl:hover:text-[var(--tpl-text)]\"\n :aria-label=\"t.logicTag.picker.close\"\n data-testid=\"logic-picker-close\"\n @click=\"cancel\"\n >\n <X :size=\"16\" :stroke-width=\"2\" />\n </button>\n </header>\n\n <div\n class=\"tpl:relative tpl:border-b tpl:border-[var(--tpl-border)] tpl:px-3 tpl:py-2.5\"\n >\n <Search\n class=\"tpl:pointer-events-none tpl:absolute tpl:top-1/2 tpl:left-5 tpl:-translate-y-1/2 tpl:text-[var(--tpl-text-dim)]\"\n :size=\"14\"\n :stroke-width=\"2\"\n />\n <input\n :id=\"`${listId}-search`\"\n ref=\"searchInputRef\"\n v-model=\"rawSearch\"\n type=\"text\"\n class=\"tpl:w-full tpl:rounded-[var(--tpl-radius-sm)] tpl:border tpl:border-[var(--tpl-border)] tpl:bg-[var(--tpl-bg)] tpl:py-1.5 tpl:pr-3 tpl:pl-8 tpl:text-sm tpl:text-[var(--tpl-text)] tpl:outline-none tpl:focus:border-[var(--tpl-primary)] tpl:focus:shadow-[var(--tpl-ring)]\"\n :placeholder=\"t.logicTag.picker.searchPlaceholder\"\n :aria-label=\"t.logicTag.picker.searchAriaLabel\"\n :aria-controls=\"listId\"\n :aria-activedescendant=\"activeOptionId()\"\n data-testid=\"logic-picker-search\"\n @keydown.enter.prevent\n />\n </div>\n\n <div\n :id=\"listId\"\n ref=\"listRef\"\n class=\"tpl:relative tpl:max-h-[60vh] tpl:flex-1 tpl:overflow-y-auto\"\n role=\"listbox\"\n :aria-label=\"t.logicTag.picker.title\"\n data-testid=\"logic-picker-list\"\n >\n <div\n v-if=\"isEmptyConfig\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.empty }}\n </div>\n <div\n v-else-if=\"isNoResults\"\n class=\"tpl:px-3 tpl:py-6 tpl:text-center tpl:text-xs tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-empty\"\n >\n {{ t.logicTag.picker.noResults }}\n </div>\n <template v-else>\n <template v-for=\"(row, rowIndex) in built.rows\" :key=\"rowIndex\">\n <div\n v-if=\"row.kind === 'header'\"\n class=\"tpl:px-3 tpl:pt-2.5 tpl:pb-1 tpl:text-xs tpl:font-medium tpl:text-[var(--tpl-text-dim)]\"\n data-testid=\"logic-picker-header\"\n :data-group-name=\"row.label\"\n >\n {{ row.label }}\n </div>\n <button\n v-else\n :id=\"optionId(row.index)\"\n type=\"button\"\n role=\"option\"\n :aria-selected=\"row.index === highlightedIndex\"\n :data-selected=\"row.index === highlightedIndex ? 'true' : 'false'\"\n :data-logic-index=\"row.index\"\n :data-logic-kind=\"row.kind\"\n class=\"tpl:flex tpl:w-full tpl:cursor-pointer tpl:flex-col tpl:items-start tpl:gap-0.5 tpl:border-none tpl:px-3 tpl:py-1.5 tpl:text-left tpl:transition-colors\"\n :class=\"\n row.index === highlightedIndex\n ? 'tpl:bg-[var(--tpl-primary-light)] tpl:text-[var(--tpl-primary)]'\n : 'tpl:bg-transparent tpl:text-[var(--tpl-text)] tpl:hover:bg-[var(--tpl-bg-hover)]'\n \"\n data-testid=\"logic-picker-item\"\n @mousemove=\"highlightedIndex = row.index\"\n @click=\"selectItem(row.kind === 'tag' ? row.tag : row.pair)\"\n >\n <span\n class=\"tpl:flex tpl:w-full tpl:items-center tpl:justify-between tpl:gap-2\"\n >\n <span class=\"tpl:text-sm tpl:font-medium\">{{\n row.kind === \"tag\" ? row.tag.label : row.pair.label\n }}</span>\n <span\n v-if=\"row.kind === 'tag'\"\n class=\"tpl:flex tpl:items-center\"\n >\n <LogicTagBadge :value=\"row.tag.value\" :syntax=\"syntax\" />\n </span>\n <span v-else class=\"tpl:flex tpl:items-center tpl:gap-1\">\n <LogicTagBadge :value=\"row.pair.before\" :syntax=\"syntax\" />\n <span class=\"tpl:text-[var(--tpl-text-dim)]\">…</span>\n <LogicTagBadge :value=\"row.pair.after\" :syntax=\"syntax\" />\n </span>\n </span>\n <span\n class=\"tpl:line-clamp-2 tpl:font-mono tpl:text-xs tpl:text-ellipsis tpl:break-all tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.value\n : `${row.pair.before} … ${row.pair.after}`\n }}\n </span>\n <span\n v-if=\"\n (row.kind === 'tag'\n ? row.tag.description\n : row.pair.description) as string | undefined\n \"\n class=\"tpl:line-clamp-2 tpl:text-xs tpl:text-ellipsis tpl:text-[var(--tpl-text-dim)]\"\n >\n {{\n row.kind === \"tag\"\n ? row.tag.description\n : row.pair.description\n }}\n </span>\n </button>\n </template>\n </template>\n </div>\n </div>\n </TplModal>\n</template>\n","<script setup lang=\"ts\">\nimport {\n computed,\n defineAsyncComponent,\n onMounted,\n onUnmounted,\n provide,\n ref,\n toRaw,\n watch,\n} from \"vue\";\nimport type { TemplaticalEditorConfig } from \"./index\";\nimport { useEditor } from \"@templatical/core\";\nimport type {\n Block,\n MergeTagsConfig,\n Template,\n TemplateContent,\n UiTheme,\n} from \"@templatical/types\";\nimport {\n cloneBlock,\n defaultLocaleOf,\n defaultLocaleGaps,\n safeClone,\n} from \"@templatical/types\";\n// Type-only, so no cloud module is statically reachable from the OSS entry —\n// see `cloud/runtime.ts` for why the seam is shaped this way.\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport NoticeStack from \"./components/NoticeStack.vue\";\nimport type { LocaleNotice } from \"./components/localization/LocaleNotices.vue\";\nimport LanguageBar from \"./components/localization/LanguageBar.vue\";\nimport { useLocaleActions } from \"./composables/useLocaleActions\";\nimport { useTranslationFeature } from \"./composables/useTranslationFeature\";\nimport {\n useActiveLocaleCoverage,\n useLocalizedDisplay,\n} from \"./composables/useLocalizedDisplay\";\nimport { useEditorCore } from \"./composables/useEditorCore\";\nimport { useCollaborationFeature } from \"./composables/useCollaborationFeature\";\nimport { useCommentsFeature } from \"./composables/useCommentsFeature\";\nimport { useAiFeature } from \"./composables/useAiFeature\";\nimport { toAiMergeTags } from \"./utils/aiMergeTags\";\nimport { useMediaFeature } from \"./composables/useMediaFeature\";\nimport { useSavedBlocksFeature } from \"./composables/useSavedBlocksFeature\";\nimport { useTemplatesFeature } from \"./composables/useTemplatesFeature\";\nimport { useTestEmailFeature } from \"./composables/useTestEmailFeature\";\nimport { useVersionHistoryFeature } from \"./composables/useVersionHistoryFeature\";\nimport { useSmallScreenNotice } from \"./composables/useSmallScreenNotice\";\nimport { useScrollToBlock } from \"./composables/useScrollToBlock\";\nimport { resolveAutoSave } from \"./types/auto-save\";\nimport { effectiveAltMaxLength } from \"./utils/aiFixableRules\";\nimport { resolveLintOptions } from \"./utils/resolveLintOptions\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\nimport { insertBlockAtSelection } from \"./utils/insertBlockAtSelection\";\nimport { withCollaborativeSave } from \"./utils/withCollaborativeSave\";\nimport { logger } from \"./utils/logger\";\nimport {\n normalizeRemoteOperations,\n withNormalizedContentWrites,\n withNormalizedTemplateLoads,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport type { Translations } from \"./i18n\";\nimport type { EditorCapabilities } from \"./types/editor-capabilities\";\nimport type { UseFontsReturn } from \"./composables/useFonts\";\nimport {\n ACTIVE_LOCALE_COVERAGE_KEY,\n AI_FEATURE_KEY,\n SIZE_CHECK_KEY,\n LOCALIZATION_KEY,\n LOCALE_ACTIONS_KEY,\n LOCALIZED_CONTENT_KEY,\n TRANSLATION_FEATURE_KEY,\n} from \"./keys\";\n\nimport { RotateCcw } from \"@lucide/vue\";\nimport { warningBtnCompactClass } from \"./constants/styleConstants\";\nimport Canvas from \"./components/Canvas.vue\";\nimport CustomBlockStylesheets from \"./components/CustomBlockStylesheets.vue\";\nimport Sidebar from \"./components/Sidebar.vue\";\nimport RightSidebar from \"./components/RightSidebar.vue\";\nimport type { RightSidebarTab } from \"./components/RightSidebar.vue\";\nimport SmallScreenNotice from \"./components/SmallScreenNotice.vue\";\nimport EditorFooter from \"./components/EditorFooter.vue\";\nimport EditorHeader from \"./components/EditorHeader.vue\";\nimport MergeTagModeToggle from \"./components/MergeTagModeToggle.vue\";\nimport MergeTagPickerModal from \"./components/MergeTagPickerModal.vue\";\nimport LogicTagPickerModal from \"./components/LogicTagPickerModal.vue\";\nimport \"./styles/index.css\";\n\nconst props = defineProps<{\n config: TemplaticalEditorConfig;\n translations: Translations;\n fontsManager: UseFontsReturn;\n /**\n * Shadow root the editor is mounted into. Supplied by `init()` when\n * `shadowDom: true`; undefined in light-DOM mode. Passed through to\n * `useEditorCore` so shadow-DOM-aware composables can resolve the\n * effective root via `EDITOR_ROOT_KEY`.\n */\n shadowRoot?: ShadowRoot;\n /**\n * Cloud's adapter wiring, supplied only by `initCloud()`.\n *\n * There is **one** editor component. Cloud is a set of providers on\n * `config` plus this runtime, which exists purely for the handful of\n * composables that must run at a specific point inside this `setup()` —\n * collaboration before the history interceptor, the lint save-gate after\n * `useEditorCore`. Everything else it contributes arrives through the\n * ordinary config keys an OSS consumer would fill in themselves.\n */\n cloud?: CloudRuntime;\n /**\n * Render the current template to MJML, for `testEmail`'s `includeMjml` option.\n *\n * Supplied by the entry point, which owns the resolution ladder behind\n * `editor.toMjml()` — a consumer's `render.toMjml` first, the bundled renderer\n * otherwise. Rendering here instead would attach a message the send pipeline\n * never produces, which is the one thing a test email exists to rule out.\n *\n * Absent means no MJML: a directly-mounted editor has no entry point to ask.\n */\n renderMjml?: () => Promise<string>;\n renderHtml?: () => Promise<string>;\n canRenderHtml?: () => boolean;\n /** Whether {@link renderMjml} reaches the bundled `@templatical/renderer`. */\n usesLocalRenderer?: () => boolean;\n}>();\n\nprovide(SIZE_CHECK_KEY, {\n renderHtml: () =>\n props.renderHtml?.() ??\n Promise.reject(new Error(\"HTML rendering is unavailable\")),\n canRenderHtml: () => props.canRenderHtml?.() ?? false,\n cloud: !!props.cloud,\n options: props.config.lint ?? {},\n});\n\n// The fourth place consumer content enters (the other three are the entry\n// points in `index.ts`: the mount seed, `setContent` and `create`). A template\n// fetched from the store never passes through the public API — core assigns it\n// to state itself — so the provider is wrapped here, on its way in. Wrapping\n// rather than normalizing after the load resolves is what keeps the load from\n// registering as an edit: core is handed content that is already correct.\n// These getters run when content arrives, after core exists. setMergeTags()\n// replaces core's list, so every incoming path must read that list at call time.\nconst liveMergeTags: MergeTagsConfig = {\n get tags() {\n return core.mergeTags.value;\n },\n get syntax() {\n return core.mergeTagSyntax;\n },\n};\nconst normalizedTemplates = props.config.templates\n ? withNormalizedTemplateLoads(props.config.templates, liveMergeTags)\n : undefined;\n\n// --- Collaboration (opt-in: a collaboration provider and a templates provider) ---\n// Built before `useEditor()`, which reads others' locks from it, and attached\n// right after. A template id is what a session joins, so without a templates\n// provider there is nothing to collaborate on.\nif (props.config.collaboration && !normalizedTemplates) {\n logger.warn(\n \"config.collaboration needs config.templates: collaboration runs on a \" +\n \"loaded template, and only a templates provider loads one. \" +\n \"Collaboration is off.\",\n );\n}\nconst collaboration =\n props.config.collaboration && normalizedTemplates\n ? useCollaborationFeature({\n provider: props.config.collaboration,\n loadTemplate: (id) => normalizedTemplates.load(id),\n user: props.config.user,\n // The same source the load normalizer reads, so a tag arriving in a\n // batch looks the way a loaded one does.\n mergeTags: liveMergeTags,\n onRemoteChange: props.config.onRemoteChange,\n onError: props.config.onError,\n })\n : null;\n\n// With collaboration, content is saved as operations; `save` only renames.\n// A save answers with what is open: the loaded template with the canvas's\n// content, which the backend holds once `settle()` has resolved.\nconst templatesProvider =\n normalizedTemplates && collaboration\n ? withCollaborativeSave(normalizedTemplates, collaboration.core, () => {\n const template = editor.state.template;\n return template\n ? {\n ...(toRaw(template) as Template),\n content: safeClone(toRaw(editor.content.value)),\n }\n : null;\n })\n : normalizedTemplates;\n\n// --- Core editor state ---\nconst structureNotice = ref(0);\nprovide(LOCALIZATION_KEY, props.config.localization);\nconst editor = useEditor({\n localization: props.config.localization ?? { locales: [] },\n onLocaleChange: props.config.onLocaleChange,\n onStructureChange: () => {\n structureNotice.value++;\n },\n content: props.config.content!,\n // Seeds a *new* template's body font when no `content` was supplied. Only the\n // deleted Cloud core passed this, so `init({ fonts: { defaultFont } })` never\n // reached a blank template.\n defaultFontFamily: props.config.fonts?.defaultFont,\n // Not `props.config.templateDefaults` raw: the editor's own `locale` seeds\n // the template's content language when the consumer left it unset, so a\n // German editor stops producing `<mjml lang=\"en\">` on a fresh template.\n templateDefaults: resolveTemplateDefaults(props.config),\n templates: templatesProvider,\n onError: props.config.onError,\n // Blocks other collaborators hold: they can't be selected here.\n lockedBlocks: collaboration?.locks,\n lockLocale: collaboration?.core.lockLocale,\n lockSessionId: collaboration?.core.sessionId,\n});\n\nconst localized = useLocalizedDisplay(editor);\nprovide(LOCALIZED_CONTENT_KEY, localized.content);\neditor.setCustomBlockDefinitions(props.config.customBlocks ?? []);\nif (collaboration) {\n watch(\n editor.activeLocale,\n (locale) => collaboration.core.setLockLocale(locale),\n { flush: \"sync\" },\n );\n}\ncollaboration?.attach(editor);\n\nconst cloudAttachment = props.cloud ? props.cloud.attach({ editor }) : null;\n\n// --- Templates (opt-in: only when a storage provider is configured) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header's name field, status indicator and save button — and what\n// makes Cmd+S mean \"persist now\".\nconst templates = templatesProvider\n ? useTemplatesFeature({\n provider: templatesProvider,\n editor,\n guardUnsavedChanges: props.config.templates?.unsavedChangesGuard,\n // Cloud's lint save-gate, when there is one. Read through a getter\n // because the gate needs `core.templateLint`, which does not exist yet.\n // Without this the collapse would have silently dropped the server's\n // `accessibility.blockOnError` policy.\n getSaveGate: props.cloud ? () => props.cloud!.getSaveGate() : undefined,\n })\n : null;\n\n// Reported to the consumer regardless of whether a provider is configured: a\n// `beforeunload` guard cannot cover SPA route changes, so an embedder needs this\n// to guard their own router — including when they persist via `onChange`.\nif (props.config.onDirtyChange) {\n watch(\n () => editor.state.isDirty,\n (isDirty) => props.config.onDirtyChange!(isDirty),\n );\n}\n\n// Outer `.tpl` ref — passed to `useEditorCore` so the active-editor\n// tracker can route keyboard shortcuts when two editors share a page.\nconst rootEl = ref<HTMLElement | null>(null);\n\n// --- Saved blocks (opt-in: only when a storage provider is configured) ---\n// Instantiated before `useEditorCore` so its capability can be passed in,\n// which is what lights up the shared save button and sidebar rail.\nconst savedBlocks = props.config.savedBlocks\n ? useSavedBlocksFeature({\n provider: props.config.savedBlocks,\n editor,\n onError: props.config.onError,\n // Cloud's store is plan-gated; a consumer's own store never is.\n isAvailable: props.cloud\n ? () => props.cloud!.isSavedBlocksAvailable()\n : undefined,\n })\n : null;\n\n// Lazily loaded so a consumer without a provider downloads none of the\n// saved-blocks UI. Rendered only when the feature is active.\nconst SavedBlocksPanels = defineAsyncComponent(\n () => import(\"./components/SavedBlocksPanels.vue\"),\n);\n\n// --- Media (opt-in: a provider and/or an `onRequestMedia` override) ---\n// Instantiated before `useEditorCore` so the synthesized function is what\n// gets provided as `ON_REQUEST_MEDIA_KEY`. The modal mounts only on the\n// provider path — a callback-only config never downloads it.\nconst mediaFeature =\n props.config.media || props.config.onRequestMedia\n ? useMediaFeature({\n provider: props.config.media,\n onRequestMedia: props.config.onRequestMedia,\n getTemplateId: () => editor.state.template?.id,\n onError: props.config.onError,\n })\n : null;\n\nconst MediaPanels = defineAsyncComponent(\n () => import(\"./components/MediaPanels.vue\"),\n);\n\n// --- Test email (opt-in: only when a sending provider is configured) ---\n// Created before `useEditorCore` so its capability can be passed in, same as\n// saved blocks.\nconst testEmail = props.config.testEmail\n ? useTestEmailFeature({\n provider: props.config.testEmail,\n getContent: () => editor.content.value,\n renderMjml: props.renderMjml,\n usesLocalRenderer: props.usesLocalRenderer,\n onError: props.config.onError,\n // Cloud folds in the plan feature and \"the template must be saved\", both\n // constraints of *its* sending path rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isTestEmailAvailable()\n : undefined,\n })\n : null;\n\nconst TestEmailPanel = defineAsyncComponent(\n () => import(\"./components/TestEmailPanel.vue\"),\n);\n\n// --- Comments (opt-in: only with a storage provider *and* a `user`) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header trigger and the per-block comment indicators.\n//\n// No `user` means no provider call at all — an unattributable comment is worse\n// than no comment feature, so `isAvailable` stays false and nothing renders.\nconst comments = props.config.comments\n ? useCommentsFeature({\n provider: props.config.comments,\n editor,\n user: props.config.user,\n // Cloud supplies its comments state; the open-source AI feature keeps\n // comments and AI panels exclusive in their shared 360px gutter.\n isOpen: cloudAttachment?.panelState.commentsOpen,\n onError: props.config.onError,\n // Cloud folds in the `commenting` plan feature and \"the template must be\n // saved\", both constraints of *its* store rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isCommentsAvailable()\n : undefined,\n // Cloud anchors a comment to a block in the saved template; a consumer's\n // store accepts whatever anchor it is given.\n isBlockSaved: props.cloud\n ? (blockId: string) => props.cloud!.isBlockSaved(blockId)\n : undefined,\n })\n : null;\n\nconst CommentsPanel = defineAsyncComponent(\n () => import(\"./components/CommentsPanel.vue\"),\n);\n\n// The AI panels: lazy, mounted only with an `ai` provider; each panel is its\n// own chunk inside.\nconst AiPanels = defineAsyncComponent(\n () => import(\"./components/ai/AiPanels.vue\"),\n);\n\n// --- AI (opt-in: an `ai` provider) ---\n// Built before `useEditorCore` so its capability is in the object core\n// provides. It reads core (the history and the merge tags) through\n// getters, at call time. Its panels are lazy (`AiPanels`); the header button\n// is not, so it renders with the rest of the header (`EditorHeader`).\nconst ai = props.config.ai\n ? useAiFeature({\n provider: props.config.ai,\n editor,\n localization: props.config.localization ?? { locales: [] },\n customBlockDefinitions: () => props.config.customBlocks ?? [],\n onStructureChange: () => {\n structureNotice.value++;\n },\n collaboration,\n history: () => core.history,\n reload: templates\n ? (id, shouldApply) => templates.load(id, shouldApply)\n : null,\n altMaxLength: () =>\n effectiveAltMaxLength(resolveLintOptions(props.config)),\n mergeTags: () => toAiMergeTags(core.mergeTags.value, core.mergeTagSyntax),\n normalize: (ops, content) =>\n normalizeRemoteOperations(ops, content, liveMergeTags),\n commentsOpen: comments?.isOpen ?? null,\n onError: props.config.onError,\n })\n : null;\nif (ai) provide(AI_FEATURE_KEY, ai);\n\n// One coverage pass per change in a language view, shared by the header\n// trigger, the language bar and its Translate counts.\nconst activeCoverage = useActiveLocaleCoverage(\n editor,\n props.config.customBlocks ?? [],\n);\nprovide(ACTIVE_LOCALE_COVERAGE_KEY, activeCoverage);\n\nconst translation = props.config.translation\n ? useTranslationFeature({\n provider: props.config.translation,\n editor,\n localization: props.config.localization,\n collaboration,\n history: () => core.history,\n definitions: () => props.config.customBlocks ?? [],\n syntax: () => core.mergeTagSyntax,\n coverage: () => activeCoverage.value,\n })\n : null;\nif (translation) provide(TRANSLATION_FEATURE_KEY, translation);\nconst localeNotice = ref<LocaleNotice | null>(null);\nwatch(\n [() => editor.state.template?.id ?? null, editor.loadVersion],\n () => {\n localeNotice.value = null;\n },\n { flush: \"sync\" },\n);\n// Undo (or any other change) that moves the default away from the notice's\n// language makes the notice untrue.\nwatch(\n () => defaultLocaleOf(editor.content.value),\n (current) => {\n if (localeNotice.value && localeNotice.value.language !== current)\n localeNotice.value = null;\n },\n { flush: \"sync\" },\n);\nconst localeActions = useLocaleActions({\n editor,\n history: () => core.history,\n collaboration,\n});\nprovide(LOCALE_ACTIONS_KEY, {\n setDefaultLocale(locale) {\n const notice = {\n language: locale,\n old: defaultLocaleOf(editor.content.value),\n count: defaultLocaleGaps(\n editor.content.value,\n locale,\n props.config.customBlocks,\n ).length,\n };\n const result = localeActions.setDefaultLocale(locale);\n if (result.applied) localeNotice.value = notice;\n return result;\n },\n});\nconst LocaleNotices = defineAsyncComponent(\n () => import(\"./components/localization/LocaleNotices.vue\"),\n);\n// Lazy: an editor without a collaboration provider never downloads it.\nconst CollaborationNotices = defineAsyncComponent(\n () => import(\"./components/collaboration/CollaborationNotices.vue\"),\n);\n\n// --- Cloud chrome (opt-in: only under `initCloud()`) ---\n// One lazy wrapper for every panel, overlay and modal Cloud adds, plus one for\n// its header controls. Same discipline as `SavedBlocksPanels` / `TestEmailPanel`:\n// an OSS consumer never downloads any of it.\nconst CloudPanels = defineAsyncComponent(\n () => import(\"./cloud/components/CloudPanels.vue\"),\n);\nconst CloudHeaderExtras = defineAsyncComponent(\n () => import(\"./cloud/components/CloudHeaderExtras.vue\"),\n);\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// The header control lives in `EditorHeader`; this is the preview banner, which\n// renders outside the header. Both are lazy.\nconst VersionHistoryPanels = defineAsyncComponent(\n () => import(\"./components/VersionHistoryPanels.vue\"),\n);\n\n// --- Auto-save ---\n// One debounced tick drives everything a consumer can ask for on a content\n// change: the `onChange` notification, and, when `templates.autoSave` is on,\n// the save itself. Sharing a single `useAutoSave` instance keeps the two in\n// step and inherits the pause-during-undo/redo behaviour `useEditorCore` wires\n// up around it. `config.changeDebounce` sets the cadence for both.\nconst autoSaveEnabled = resolveAutoSave(\n props.config.templates?.autoSave,\n false,\n);\nconst isAutoSaving = autoSaveEnabled && templates !== null;\n// The one way autosave can still be inert once a provider exists is its\n// `save` being `false` — a read-only store — which `requestAutoSave()` below\n// already no-ops per tick for; this warning is the only signal the consumer\n// gets. `templates !== null` is redundant with `autoSaveEnabled` at runtime\n// (the provider that enables autosave is the same provider that makes\n// `templates` non-null) but stays as an explicit conjunct so TypeScript can\n// narrow `templates.canSave.value` below without a non-null assertion.\nif (autoSaveEnabled && templates !== null && !templates.canSave.value) {\n logger.warn(\n \"config.templates.autoSave is on but this provider's save is false — \" +\n \"there is nothing to persist to. Give it a real save function, or \" +\n \"use `onChange` to persist the content yourself.\",\n );\n}\n// `changeDebounce` alone does not enable autosave — only `templates.autoSave`\n// does. A config with `changeDebounce` set, a provider present, `autoSave`\n// left unset, and no `onChange` has nothing consuming the timer at all,\n// which reads as intentional `onChange`-only pacing but is easy to reach by\n// mistake. Warn on exactly that combination; `autoSave: false` is a stated\n// decision and must stay silent.\nif (\n props.config.changeDebounce !== undefined &&\n templates !== null &&\n props.config.templates?.autoSave === undefined &&\n !props.config.onChange\n) {\n logger.warn(\n \"config.changeDebounce is set but nothing will use it — \" +\n \"config.templates.autoSave is unset and there is no onChange either, \" +\n \"so the timer has no consumer. Set config.templates.autoSave, or add \" +\n \"onChange, so the debounce takes effect.\",\n );\n}\n\nconst autoSaveOptions =\n props.config.onChange || isAutoSaving\n ? {\n onChange: () => {\n props.config.onChange?.(\n JSON.parse(JSON.stringify(editor.state.content)),\n );\n // `requestAutoSave()` already no-ops without a saveable template, so a\n // read-only provider costs one predicate per tick and nothing else.\n // It is the *ungated* request only in the sense that it never raises a\n // prompt: Cloud's lint gate still refuses it, which is what keeps\n // `accessibility.blockOnError` a policy rather than a manual-save\n // speed bump.\n if (isAutoSaving) templates!.requestAutoSave();\n },\n ...(props.config.changeDebounce !== undefined\n ? { debounce: props.config.changeDebounce }\n : {}),\n }\n : null;\n\n// --- Shared editor core (composables, provides, plugins, keyboard) ---\n// A named object rather than an inline literal: `useVersionHistoryFeature` can\n// only be built after core (it needs history/conditionPreview/autoSave), so its\n// capability is assigned in below, into the very object core provided.\nconst capabilities: EditorCapabilities = {\n ...(savedBlocks ? { savedBlocks: savedBlocks.capability } : {}),\n ...(templates ? { templates: templates.capability } : {}),\n ...(testEmail ? { testEmail: testEmail.capability } : {}),\n ...(comments ? { comments: comments.capability } : {}),\n ...(collaboration ? { collaboration: collaboration.capability } : {}),\n ...(ai ? { ai: ai.capability } : {}),\n};\n\nconst core = useEditorCore({\n editor,\n containerEl: rootEl,\n config: {\n uiTheme: props.config.uiTheme,\n theme: props.config.theme,\n blockDefaults: props.config.blockDefaults,\n templateDefaults: props.config.templateDefaults,\n customBlocks: props.config.customBlocks,\n paletteBlocks: props.config.paletteBlocks,\n htmlBlockPreview: props.config.htmlBlockPreview,\n layout: props.config.layout,\n sectionWrapper: props.config.sectionWrapper,\n colors: props.config.colors,\n templateSettings: props.config.templateSettings,\n mergeTags: props.config.mergeTags,\n logicTags: props.config.logicTags,\n displayConditions: props.config.displayConditions,\n // The synthesized Browse/drop handler. Null when neither a provider nor a\n // callback is configured, which is what keeps image fields URL-only.\n onRequestMedia: mediaFeature?.requestMedia ?? null,\n // Distinct from Browse: a read-only provider still opens the library.\n canDropMedia: mediaFeature?.canDrop ?? null,\n resolvePreview: props.config.resolvePreview,\n resolveImageUrl: props.config.resolveImageUrl,\n lint: resolveLintOptions(props.config),\n // For Intl-built labels (dates), which would otherwise format in the\n // BROWSER's locale and disagree with the translated chrome beside them.\n locale: props.config.locale,\n },\n translations: props.translations,\n fontsManager: props.fontsManager,\n autoSaveOptions,\n capabilities,\n editorRoot: props.shadowRoot,\n history: collaboration?.history,\n});\n\nconst rightSidebarTab = ref<RightSidebarTab>(\"content\");\nwatch(\n () => editor.state.template?.id,\n () => {\n if (editor.selectedBlock.value) rightSidebarTab.value = \"content\";\n },\n);\n\n// Cloud's setup-time wiring that needs `core`: the lint save-gate (reads\n// `core.templateLint`) and the capability entries Cloud contributes — mutated\n// into the very object `useEditorCore` provided, so injecting components see\n// them on first render.\nconst cloudReady =\n props.cloud && cloudAttachment\n ? props.cloud.ready({ core, capabilities })\n : null;\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// Constructed *after* `useEditorCore` because it drives `history` /\n// `conditionPreview` / `autoSave`, which core owns. Its capability is therefore\n// assigned into the object above rather than passed in — same object reference\n// core provided, mutated during setup, so injecting components see it on their\n// first render.\nconst versionHistory = props.config.versionHistory\n ? useVersionHistoryFeature({\n provider: props.config.versionHistory,\n // The fifth content-in path. A stored version holds whatever was written\n // to it, so it can carry bare tokens like any other loaded content, and\n // previewing one would put them on a canvas where every other tag is a\n // chip. Wrapped at `setContent` rather than at the provider, because\n // version content also arrives off the hydrated list and out of the\n // `fetched` cache without touching `get()`.\n editor: withNormalizedContentWrites(editor, liveMergeTags),\n history: core.history,\n conditionPreview: core.conditionPreview,\n autoSave: core.autoSave,\n // A version on the canvas is a preview, not an edit: collaboration stops\n // reading the canvas for it, and a restore re-syncs from the backend.\n collaboration: collaboration\n ? {\n suspend: collaboration.core.suspend,\n resume: collaboration.core.resume,\n catchUp: collaboration.core.catchUp,\n reportReplaceRefused: collaboration.reportReplaceRefused,\n }\n : null,\n // Lets the restore confirmation offer to persist unsaved work instead of\n // only warning about it. Without a templates provider — or with one whose\n // `save` is `false` — there is nowhere to put that work, and the\n // confirmation says so rather than offering an action that can't happen.\n // Cloud additionally refuses while the lint gate would block: stacking a\n // second modal on the confirmation would be worse than saying there is\n // currently nowhere to put the work.\n saveBeforeRestore: templates\n ? {\n canSave: () =>\n templates.canSave.value &&\n !(props.cloud?.getSaveGate()?.shouldBlock.value ?? false),\n save: () => templates.save(\"restore\"),\n }\n : null,\n onError: props.config.onError,\n })\n : null;\n\nif (versionHistory) capabilities.versionHistory = versionHistory.capability;\n\n/**\n * Left/right insets for the canvas body and the footer, which must always agree.\n *\n * Comments and the open-source AI panels widen the right gutter while open.\n */\n/**\n * Whether a 360px feature panel occupies the right-hand gutter.\n *\n * Comments and the open-source AI panels share this gutter; the AI feature\n * keeps their open states mutually exclusive. Cloud also supplies its panel\n * state, which shares the comments ref.\n *\n * Two things read this, and **both must**: the canvas/footer insets below, and\n * `RightSidebar`'s `shifted-left` — the properties panel sits at `right-0` too, so\n * a panel opening over it would swallow every click meant for the panel.\n */\nconst rightPanelOpen = computed(\n () =>\n comments?.isOpen.value === true ||\n (ai !== null && ai.panel.value !== null) ||\n cloudAttachment?.panelState.rightPanelOpen.value === true,\n);\n\nconst bodyInsetClass = computed(() => {\n if (editor.state.previewMode) return \"tpl:left-0 tpl:right-0\";\n return rightPanelOpen.value\n ? \"tpl:left-12 tpl:right-[680px]\"\n : \"tpl:left-12 tpl:right-[320px]\";\n});\n\n// Both bands participate in flow; wrapping and async banner loads resize one box.\nconst topChrome = ref<HTMLElement | null>(null);\nconst topChromeHeight = ref(0);\nconst contentInsetStyle = computed(() => ({\n top: `calc(3.5 * var(--tpl-base-size) + ${topChromeHeight.value}px)`,\n}));\nlet topChromeObserver: ResizeObserver | undefined;\nonMounted(() => {\n topChromeHeight.value = topChrome.value?.offsetHeight ?? 0;\n if (topChrome.value && typeof ResizeObserver !== \"undefined\") {\n topChromeObserver = new ResizeObserver(([entry]) => {\n if (entry)\n topChromeHeight.value =\n entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;\n });\n topChromeObserver.observe(topChrome.value);\n }\n});\nonUnmounted(() => topChromeObserver?.disconnect());\n\n// --- Small-screen gate (#235) ---\n// Below ~768px the three-pane chrome can't lay out usably; show a notice\n// instead. Opt out with `config.smallScreenNotice: false`.\nconst { showNotice: showSmallScreenNotice } = useSmallScreenNotice(\n () => props.config.smallScreenNotice,\n);\n\n// --- Lifecycle ---\nonMounted(async () => {\n await props.fontsManager.loadCustomFonts();\n});\n\nonUnmounted(() => {\n props.fontsManager.cleanupFontLinks();\n ai?.destroy();\n props.cloud?.destroy();\n core.destroy();\n});\n\n// --- Public API (accessed via template ref from init()) ---\n// The lifecycle trio comes from the templates feature when one exists, so a\n// programmatic save also drives the header's status. Without a provider it comes\n// straight from core, whose own methods reject with the actionable error.\nconst templateLifecycle = templates ?? editor;\n\nconst scrollToBlock = useScrollToBlock(core.editorRoot);\n\ndefineExpose({\n getLocale: () =>\n editor.activeLocale.value ?? defaultLocaleOf(editor.content.value),\n setLocale: (locale: string) => editor.setActiveLocale(locale),\n getContent: () => editor.content.value,\n setContent: (content: TemplateContent) => editor.setContent(content),\n insertBlock: (block: Block): string | null => {\n // The palette is hidden in preview mode, and preview has no selection.\n if (editor.state.previewMode) {\n logger.warn(\"insertBlock() does nothing in preview mode.\");\n return null;\n }\n // A copy with fresh ids throughout, so inserting the same library item\n // twice never puts two blocks, rows or items on the canvas with one id.\n const copy = cloneBlock(block);\n if (!insertBlockAtSelection(editor, copy)) return null;\n scrollToBlock(copy.id);\n return copy.id;\n },\n setTheme: (theme: UiTheme) => editor.setUiTheme(theme),\n setMergeTags: core.setMergeTags,\n isDirty: () => editor.state.isDirty,\n create: templateLifecycle.create,\n load: templateLifecycle.load,\n save: templateLifecycle.save,\n renderCustomBlock: core.registry.renderCustomBlock,\n getCustomBlockStylesheet: (customType: string) =>\n core.registry.getDefinition(customType)?.stylesheet,\n});\n</script>\n\n<template>\n <!-- @dragover/@drop.prevent: a file dropped outside an image drop zone would\n otherwise make the browser navigate to the file:// URL and destroy the\n editor session. Image zones (useImageDrop) handle their own drops; this\n only neutralizes the default action everywhere else (#229). -->\n <div\n ref=\"rootEl\"\n class=\"tpl tpl:relative tpl:h-full\"\n :class=\"{ 'tpl:dark': editor.state.darkMode }\"\n :data-tpl-theme=\"core.resolvedTheme.value\"\n :style=\"core.themeStyles.value\"\n @dragover.prevent\n @drop.prevent\n >\n <!-- Reactive `<style>` tags for custom-block definition stylesheets in\n use. Sits at the top so its rules apply to the canvas below. -->\n <CustomBlockStylesheets />\n <!-- Chrome wrapper — the clip belongs here, never on the root and never\n around `.tpl-popover-root`. Safari paints a `position: fixed`\n descendant clipped to an ancestor's `overflow: hidden` box while still\n resolving its layout against the viewport, so a dialog teleported\n under a clipping ancestor is cut off wherever it extends past the\n container, and its backdrop dims only the container's own area\n (#633). Keeping the clip on this element bounds the header, rails,\n canvas and footer without reaching the popover root, and this box is\n identical to the root's, so everything anchored `absolute` inside\n lands exactly where it would against the root. Locked by\n `tests/popover-root-clip-scope.test.ts`. -->\n <div class=\"tpl:absolute tpl:inset-0 tpl:overflow-hidden\">\n <!-- One header for both entry points. Cloud's own controls arrive through\n the three slots; everything else here is capability-gated, so the same\n markup covers \"no providers at all\" and a fully-wired Cloud session. -->\n <EditorHeader\n :editor=\"editor\"\n :localization=\"props.config.localization\"\n :core=\"core\"\n :templates=\"templates\"\n :show-template-name=\"config.templates?.nameField !== false\"\n :test-email=\"testEmail\"\n :version-history=\"versionHistory\"\n :comments=\"comments\"\n :collaboration=\"collaboration\"\n :ai=\"ai\"\n >\n <template v-if=\"cloudAttachment\" #left-extras>\n <CloudHeaderExtras part=\"left\" :cloud=\"cloudAttachment\" />\n </template>\n <template v-if=\"cloudAttachment\" #right-extras>\n <CloudHeaderExtras part=\"right\" :cloud=\"cloudAttachment\" />\n </template>\n </EditorHeader>\n\n <!-- Left sidebar — absolute, below header -->\n <Sidebar v-show=\"!editor.state.previewMode\" :style=\"contentInsetStyle\" />\n\n <!-- Canvas area — absolute, fills remaining space -->\n <div\n class=\"tpl-body tpl:absolute tpl:bottom-0 tpl:overflow-auto tpl:bg-[var(--tpl-canvas-bg)]\"\n style=\"\n transition:\n left var(--tpl-transition),\n right var(--tpl-transition);\n \"\n :style=\"contentInsetStyle\"\n :class=\"bodyInsetClass\"\n >\n <!-- Preview chrome, floated over the canvas.\n\n A zero-height sticky layer holding one absolutely-positioned,\n canvas-centred **column**. Zero height means the layer contributes no\n space of its own, so nothing here can push the canvas around — which\n is what lets the merge-tag toggle live over the preview instead of in\n the header, whose centre track re-centres on every width change and\n so dragged the Preview button 114.5px sideways each time the toggle\n appeared (#574).\n\n A column rather than two fixed offsets. Both pills are reachable at\n once — the restore pill needs hidden blocks, the toggle needs preview\n mode without a `resolvePreview`, and nothing makes those exclusive —\n so they have to stack. Doing that with a hardcoded second offset put\n the restore pill 48px down even when it rendered alone, which in\n editing mode (where the toggle never shows) dropped it onto the first\n block's content. Flow solves what the offset got wrong: whichever\n pills render sit tight under the header, in order.\n\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div class=\"tpl-preview-overlay tpl:sticky tpl:top-0 tpl:z-40 tpl:h-0\">\n <div\n class=\"tpl:absolute tpl:left-1/2 tpl:top-2 tpl:flex tpl:-translate-x-1/2 tpl:flex-col tpl:items-center tpl:gap-2\"\n >\n <!-- Sample / Label. Preview mode only: merge tags are never\n substituted on the editing canvas, so the choice would have no\n effect there. A configured `resolvePreview` supersedes samples\n entirely.\n\n The wrapper carries only the shadow that lifts the control off\n the canvas — no `backdrop-filter`, because the toggle's own\n `--tpl-bg-hover` fill is opaque and covers this box exactly, so a\n blur would composite a layer to show nothing. -->\n <Transition name=\"tpl-preview-pill\">\n <div\n v-if=\"\n editor.state.previewMode &&\n !core.previewResolution.supersedesSamples.value\n \"\n data-testid=\"merge-tag-mode-toggle-anchor\"\n class=\"tpl:rounded-[var(--tpl-radius-sm)] tpl:shadow-[var(--tpl-shadow-md)]\"\n >\n <MergeTagModeToggle\n :sample-mode=\"core.mergeTagSampleMode.value\"\n @change=\"core.mergeTagSampleMode.value = $event\"\n />\n </div>\n </Transition>\n <!-- Show all hidden blocks. The shared warning recipe, not a bespoke\n string: it has to read as the Sample/Label switch's sibling,\n since the two stack here, and a hand-rolled pill is how this one\n came to sit 8px shorter with a different radius and a 1.85:1\n label. `warningBtnCompactClass` carries why the amber is on the\n border rather than the text. -->\n <Transition name=\"tpl-preview-pill\">\n <button\n v-if=\"\n core.conditionPreview.hasHiddenBlocks.value &&\n core.appliesConditionFilter.value\n \"\n type=\"button\"\n :class=\"warningBtnCompactClass\"\n class=\"tpl:shadow-[var(--tpl-shadow-md)]\"\n data-testid=\"restore-hidden-blocks\"\n @click=\"core.conditionPreview.reset()\"\n >\n <RotateCcw :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.blockSettings.restoreHiddenBlocks }}\n </button>\n </Transition>\n </div>\n </div>\n <!-- No justify-center and no inline padding: the stage centres\n itself with auto margins and keeps its own clearance\n (Canvas.vue). A flex-centred child that overflows sticks out on\n both sides, and the left side can never be scrolled to. -->\n <main class=\"tpl-main tpl:flex tpl:py-8\">\n <Canvas\n :viewport=\"editor.state.viewport\"\n :content=\"core.previewResolution.content.value\"\n :selected-block-id=\"editor.state.selectedBlockId\"\n :dark-mode=\"editor.state.darkMode\"\n :preview-mode=\"editor.state.previewMode\"\n @select-block=\"editor.selectBlock\"\n />\n </main>\n </div>\n\n <EditorFooter\n v-if=\"config.branding !== false\"\n :position-class=\"[bodyInsetClass]\"\n />\n\n <!-- Keyboard reorder announcement region (visually hidden, screen-reader live) -->\n <div\n class=\"tpl-sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n :aria-label=\"core.t.landmarks.reorderAnnouncements\"\n >\n {{ core.keyboardReorder.announcement.value }}\n </div>\n\n <!-- Right sidebar — persisted with v-show -->\n <RightSidebar\n v-show=\"!editor.state.previewMode\"\n v-model:tab=\"rightSidebarTab\"\n :style=\"contentInsetStyle\"\n style=\"transition-property: right\"\n :selected-block=\"\n editor.selectedBlock.value\n ? localized.displayBlock(editor.selectedBlock.value)\n : null\n \"\n :settings=\"localized.settings.value\"\n :shifted-left=\"rightPanelOpen\"\n @update-block=\"\n (updates) =>\n editor.updateBlock(editor.state.selectedBlockId!, updates)\n \"\n @delete-block=\"\n () => {\n if (editor.state.selectedBlockId) {\n core.blockActions.deleteBlock(editor.state.selectedBlockId);\n }\n }\n \"\n @duplicate-block=\"\n () => {\n if (editor.selectedBlock.value) {\n core.blockActions.duplicateBlock(editor.selectedBlock.value);\n }\n }\n \"\n @update-settings=\"(updates) => editor.updateSettings(updates)\"\n />\n\n <div\n ref=\"topChrome\"\n class=\"tpl-top-chrome tpl:absolute tpl:top-14 tpl:right-0 tpl:left-0 tpl:z-40\"\n >\n <VersionHistoryPanels\n v-if=\"versionHistory?.isAvailable.value\"\n :feature=\"versionHistory\"\n />\n <LanguageBar\n v-if=\"config.localization\"\n :editor=\"editor\"\n :locales=\"config.localization.locales\"\n :feature=\"translation\"\n :change=\"structureNotice\"\n />\n </div>\n </div>\n\n <!-- Popover mount — Teleport target for toolbars, link dialog, modals.\n Every popup mounts here rather than at the page's `<body>`, so it\n renders inside the editor's effective DOM root and keeps the shadow\n root's adopted stylesheet; a body-level teleport leaves the shadow\n tree and renders unstyled. It also has to stay a child of `.tpl`, which\n declares `--tpl-base-size` and the colour tokens — `@theme inline`\n rebases the whole Tailwind length scale onto that variable, so a\n popup hoisted out would lose the sizing scale as well as the palette.\n Enforced by the `no-teleport-to-body` ESLint rule and\n `tests/global-refs-audit.test.ts`. -->\n <div\n :ref=\"(el) => (core.popoverRoot.value = el as HTMLElement | null)\"\n class=\"tpl-popover-root\"\n />\n\n <!-- Built-in merge tag picker modal. Reads picker state via injection;\n renders nothing until `picker.isOpen` flips true. -->\n <MergeTagPickerModal />\n\n <!-- Built-in logic picker modal (standalone logic feature). -->\n <LogicTagPickerModal />\n\n <!-- Saved blocks dialogs. Only mounted when a provider is configured;\n each dialog's chunk loads on first open. -->\n <SavedBlocksPanels\n v-if=\"savedBlocks?.isAvailable.value\"\n :feature=\"savedBlocks\"\n />\n\n <!-- Media library modal. Only mounted when a storage provider is\n configured; the modal's chunk loads on first Browse. A callback-only\n `onRequestMedia` never mounts this — the host brought a widget. -->\n <MediaPanels\n v-if=\"config.media && mediaFeature\"\n :feature=\"mediaFeature\"\n :provider=\"config.media\"\n :locale=\"config.locale\"\n :ui-theme=\"core.resolvedTheme.value\"\n :popover-target=\"core.popoverRoot.value\"\n />\n\n <TestEmailPanel v-if=\"testEmail?.isAvailable.value\" :feature=\"testEmail\" />\n\n <!-- The comments sidebar. Only mounted when a provider and a `user` are\n configured; the sidebar's own chunk loads the first time it opens. -->\n <CommentsPanel v-if=\"comments?.isAvailable.value\" :feature=\"comments\" />\n\n <!-- The AI chat panel shares the right gutter with\n comments, one at a time (D18). -->\n <AiPanels v-if=\"ai\" :feature=\"ai\" />\n\n <!-- Collaboration notices: a refused selection or edit, a skipped undo,\n a refused replace, reconnecting. -->\n <NoticeStack v-if=\"collaboration || localeNotice\">\n <CollaborationNotices v-if=\"collaboration\" :feature=\"collaboration\" />\n <LocaleNotices\n v-if=\"localeNotice\"\n :notice=\"localeNotice\"\n @dismiss=\"localeNotice = null\"\n />\n </NoticeStack>\n\n <!-- Cloud sidebars, modals and overlays. One lazy wrapper, mounted only\n under `initCloud()`; an OSS consumer downloads none of it. -->\n <CloudPanels\n v-if=\"cloud && cloudAttachment && cloudReady\"\n :editor=\"editor\"\n :core=\"core\"\n :runtime=\"cloud\"\n :cloud=\"cloudAttachment\"\n :ready=\"cloudReady\"\n />\n\n <!-- Small-screen gate (#235). Last child + a literal z-index above the\n chrome and `.tpl-popover-root`, so the opaque notice covers everything\n below the breakpoint. -->\n <SmallScreenNotice v-if=\"showSmallScreenNotice\" />\n </div>\n</template>\n\n<style scoped>\n.tpl-preview-pill-enter-active {\n transition:\n opacity 200ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 200ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-preview-pill-leave-active {\n transition:\n opacity 150ms ease-in,\n transform 150ms ease-in;\n}\n\n.tpl-preview-pill-enter-from,\n.tpl-preview-pill-leave-to {\n opacity: 0;\n transform: translateY(-8px) scale(0.9);\n}\n\n.tpl-preview-pill-enter-to,\n.tpl-preview-pill-leave-from {\n opacity: 1;\n transform: translateY(0) scale(1);\n}\n</style>\n","<script setup lang=\"ts\">\nimport {\n computed,\n defineAsyncComponent,\n onMounted,\n onUnmounted,\n provide,\n ref,\n toRaw,\n watch,\n} from \"vue\";\nimport type { TemplaticalEditorConfig } from \"./index\";\nimport { useEditor } from \"@templatical/core\";\nimport type {\n Block,\n MergeTagsConfig,\n Template,\n TemplateContent,\n UiTheme,\n} from \"@templatical/types\";\nimport {\n cloneBlock,\n defaultLocaleOf,\n defaultLocaleGaps,\n safeClone,\n} from \"@templatical/types\";\n// Type-only, so no cloud module is statically reachable from the OSS entry —\n// see `cloud/runtime.ts` for why the seam is shaped this way.\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport NoticeStack from \"./components/NoticeStack.vue\";\nimport type { LocaleNotice } from \"./components/localization/LocaleNotices.vue\";\nimport LanguageBar from \"./components/localization/LanguageBar.vue\";\nimport { useLocaleActions } from \"./composables/useLocaleActions\";\nimport { useTranslationFeature } from \"./composables/useTranslationFeature\";\nimport {\n useActiveLocaleCoverage,\n useLocalizedDisplay,\n} from \"./composables/useLocalizedDisplay\";\nimport { useEditorCore } from \"./composables/useEditorCore\";\nimport { useCollaborationFeature } from \"./composables/useCollaborationFeature\";\nimport { useCommentsFeature } from \"./composables/useCommentsFeature\";\nimport { useAiFeature } from \"./composables/useAiFeature\";\nimport { toAiMergeTags } from \"./utils/aiMergeTags\";\nimport { useMediaFeature } from \"./composables/useMediaFeature\";\nimport { useSavedBlocksFeature } from \"./composables/useSavedBlocksFeature\";\nimport { useTemplatesFeature } from \"./composables/useTemplatesFeature\";\nimport { useTestEmailFeature } from \"./composables/useTestEmailFeature\";\nimport { useVersionHistoryFeature } from \"./composables/useVersionHistoryFeature\";\nimport { useSmallScreenNotice } from \"./composables/useSmallScreenNotice\";\nimport { useScrollToBlock } from \"./composables/useScrollToBlock\";\nimport { resolveAutoSave } from \"./types/auto-save\";\nimport { effectiveAltMaxLength } from \"./utils/aiFixableRules\";\nimport { resolveLintOptions } from \"./utils/resolveLintOptions\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\nimport { insertBlockAtSelection } from \"./utils/insertBlockAtSelection\";\nimport { withCollaborativeSave } from \"./utils/withCollaborativeSave\";\nimport { logger } from \"./utils/logger\";\nimport {\n normalizeRemoteOperations,\n withNormalizedContentWrites,\n withNormalizedTemplateLoads,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport type { Translations } from \"./i18n\";\nimport type { EditorCapabilities } from \"./types/editor-capabilities\";\nimport type { UseFontsReturn } from \"./composables/useFonts\";\nimport {\n ACTIVE_LOCALE_COVERAGE_KEY,\n AI_FEATURE_KEY,\n SIZE_CHECK_KEY,\n LOCALIZATION_KEY,\n LOCALE_ACTIONS_KEY,\n LOCALIZED_CONTENT_KEY,\n TRANSLATION_FEATURE_KEY,\n} from \"./keys\";\n\nimport { RotateCcw } from \"@lucide/vue\";\nimport { warningBtnCompactClass } from \"./constants/styleConstants\";\nimport Canvas from \"./components/Canvas.vue\";\nimport CustomBlockStylesheets from \"./components/CustomBlockStylesheets.vue\";\nimport Sidebar from \"./components/Sidebar.vue\";\nimport RightSidebar from \"./components/RightSidebar.vue\";\nimport type { RightSidebarTab } from \"./components/RightSidebar.vue\";\nimport SmallScreenNotice from \"./components/SmallScreenNotice.vue\";\nimport EditorFooter from \"./components/EditorFooter.vue\";\nimport EditorHeader from \"./components/EditorHeader.vue\";\nimport MergeTagModeToggle from \"./components/MergeTagModeToggle.vue\";\nimport MergeTagPickerModal from \"./components/MergeTagPickerModal.vue\";\nimport LogicTagPickerModal from \"./components/LogicTagPickerModal.vue\";\nimport \"./styles/index.css\";\n\nconst props = defineProps<{\n config: TemplaticalEditorConfig;\n translations: Translations;\n fontsManager: UseFontsReturn;\n /**\n * Shadow root the editor is mounted into. Supplied by `init()` when\n * `shadowDom: true`; undefined in light-DOM mode. Passed through to\n * `useEditorCore` so shadow-DOM-aware composables can resolve the\n * effective root via `EDITOR_ROOT_KEY`.\n */\n shadowRoot?: ShadowRoot;\n /**\n * Cloud's adapter wiring, supplied only by `initCloud()`.\n *\n * There is **one** editor component. Cloud is a set of providers on\n * `config` plus this runtime, which exists purely for the handful of\n * composables that must run at a specific point inside this `setup()` —\n * collaboration before the history interceptor, the lint save-gate after\n * `useEditorCore`. Everything else it contributes arrives through the\n * ordinary config keys an OSS consumer would fill in themselves.\n */\n cloud?: CloudRuntime;\n /**\n * Render the current template to MJML, for `testEmail`'s `includeMjml` option.\n *\n * Supplied by the entry point, which owns the resolution ladder behind\n * `editor.toMjml()` — a consumer's `render.toMjml` first, the bundled renderer\n * otherwise. Rendering here instead would attach a message the send pipeline\n * never produces, which is the one thing a test email exists to rule out.\n *\n * Absent means no MJML: a directly-mounted editor has no entry point to ask.\n */\n renderMjml?: () => Promise<string>;\n renderHtml?: () => Promise<string>;\n canRenderHtml?: () => boolean;\n /** Whether {@link renderMjml} reaches the bundled `@templatical/renderer`. */\n usesLocalRenderer?: () => boolean;\n}>();\n\nprovide(SIZE_CHECK_KEY, {\n renderHtml: () =>\n props.renderHtml?.() ??\n Promise.reject(new Error(\"HTML rendering is unavailable\")),\n canRenderHtml: () => props.canRenderHtml?.() ?? false,\n cloud: !!props.cloud,\n options: props.config.lint ?? {},\n});\n\n// The fourth place consumer content enters (the other three are the entry\n// points in `index.ts`: the mount seed, `setContent` and `create`). A template\n// fetched from the store never passes through the public API — core assigns it\n// to state itself — so the provider is wrapped here, on its way in. Wrapping\n// rather than normalizing after the load resolves is what keeps the load from\n// registering as an edit: core is handed content that is already correct.\n// These getters run when content arrives, after core exists. setMergeTags()\n// replaces core's list, so every incoming path must read that list at call time.\nconst liveMergeTags: MergeTagsConfig = {\n get tags() {\n return core.mergeTags.value;\n },\n get syntax() {\n return core.mergeTagSyntax;\n },\n};\nconst normalizedTemplates = props.config.templates\n ? withNormalizedTemplateLoads(props.config.templates, liveMergeTags)\n : undefined;\n\n// --- Collaboration (opt-in: a collaboration provider and a templates provider) ---\n// Built before `useEditor()`, which reads others' locks from it, and attached\n// right after. A template id is what a session joins, so without a templates\n// provider there is nothing to collaborate on.\nif (props.config.collaboration && !normalizedTemplates) {\n logger.warn(\n \"config.collaboration needs config.templates: collaboration runs on a \" +\n \"loaded template, and only a templates provider loads one. \" +\n \"Collaboration is off.\",\n );\n}\nconst collaboration =\n props.config.collaboration && normalizedTemplates\n ? useCollaborationFeature({\n provider: props.config.collaboration,\n loadTemplate: (id) => normalizedTemplates.load(id),\n user: props.config.user,\n // The same source the load normalizer reads, so a tag arriving in a\n // batch looks the way a loaded one does.\n mergeTags: liveMergeTags,\n onRemoteChange: props.config.onRemoteChange,\n onError: props.config.onError,\n })\n : null;\n\n// With collaboration, content is saved as operations; `save` only renames.\n// A save answers with what is open: the loaded template with the canvas's\n// content, which the backend holds once `settle()` has resolved.\nconst templatesProvider =\n normalizedTemplates && collaboration\n ? withCollaborativeSave(normalizedTemplates, collaboration.core, () => {\n const template = editor.state.template;\n return template\n ? {\n ...(toRaw(template) as Template),\n content: safeClone(toRaw(editor.content.value)),\n }\n : null;\n })\n : normalizedTemplates;\n\n// --- Core editor state ---\nconst structureNotice = ref(0);\nprovide(LOCALIZATION_KEY, props.config.localization);\nconst editor = useEditor({\n localization: props.config.localization ?? { locales: [] },\n onLocaleChange: props.config.onLocaleChange,\n onStructureChange: () => {\n structureNotice.value++;\n },\n content: props.config.content!,\n // Seeds a *new* template's body font when no `content` was supplied. Only the\n // deleted Cloud core passed this, so `init({ fonts: { defaultFont } })` never\n // reached a blank template.\n defaultFontFamily: props.config.fonts?.defaultFont,\n // Not `props.config.templateDefaults` raw: the editor's own `locale` seeds\n // the template's content language when the consumer left it unset, so a\n // German editor stops producing `<mjml lang=\"en\">` on a fresh template.\n templateDefaults: resolveTemplateDefaults(props.config),\n templates: templatesProvider,\n onError: props.config.onError,\n // Blocks other collaborators hold: they can't be selected here.\n lockedBlocks: collaboration?.locks,\n lockLocale: collaboration?.core.lockLocale,\n lockSessionId: collaboration?.core.sessionId,\n});\n\nconst localized = useLocalizedDisplay(editor);\nprovide(LOCALIZED_CONTENT_KEY, localized.content);\neditor.setCustomBlockDefinitions(props.config.customBlocks ?? []);\nif (collaboration) {\n watch(\n editor.activeLocale,\n (locale) => collaboration.core.setLockLocale(locale),\n { flush: \"sync\" },\n );\n}\ncollaboration?.attach(editor);\n\nconst cloudAttachment = props.cloud ? props.cloud.attach({ editor }) : null;\n\n// --- Templates (opt-in: only when a storage provider is configured) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header's name field, status indicator and save button — and what\n// makes Cmd+S mean \"persist now\".\nconst templates = templatesProvider\n ? useTemplatesFeature({\n provider: templatesProvider,\n editor,\n guardUnsavedChanges: props.config.templates?.unsavedChangesGuard,\n // Cloud's lint save-gate, when there is one. Read through a getter\n // because the gate needs `core.templateLint`, which does not exist yet.\n // Without this the collapse would have silently dropped the server's\n // `accessibility.blockOnError` policy.\n getSaveGate: props.cloud ? () => props.cloud!.getSaveGate() : undefined,\n })\n : null;\n\n// Reported to the consumer regardless of whether a provider is configured: a\n// `beforeunload` guard cannot cover SPA route changes, so an embedder needs this\n// to guard their own router — including when they persist via `onChange`.\nif (props.config.onDirtyChange) {\n watch(\n () => editor.state.isDirty,\n (isDirty) => props.config.onDirtyChange!(isDirty),\n );\n}\n\n// Outer `.tpl` ref — passed to `useEditorCore` so the active-editor\n// tracker can route keyboard shortcuts when two editors share a page.\nconst rootEl = ref<HTMLElement | null>(null);\n\n// --- Saved blocks (opt-in: only when a storage provider is configured) ---\n// Instantiated before `useEditorCore` so its capability can be passed in,\n// which is what lights up the shared save button and sidebar rail.\nconst savedBlocks = props.config.savedBlocks\n ? useSavedBlocksFeature({\n provider: props.config.savedBlocks,\n editor,\n onError: props.config.onError,\n // Cloud's store is plan-gated; a consumer's own store never is.\n isAvailable: props.cloud\n ? () => props.cloud!.isSavedBlocksAvailable()\n : undefined,\n })\n : null;\n\n// Lazily loaded so a consumer without a provider downloads none of the\n// saved-blocks UI. Rendered only when the feature is active.\nconst SavedBlocksPanels = defineAsyncComponent(\n () => import(\"./components/SavedBlocksPanels.vue\"),\n);\n\n// --- Media (opt-in: a provider and/or an `onRequestMedia` override) ---\n// Instantiated before `useEditorCore` so the synthesized function is what\n// gets provided as `ON_REQUEST_MEDIA_KEY`. The modal mounts only on the\n// provider path — a callback-only config never downloads it.\nconst mediaFeature =\n props.config.media || props.config.onRequestMedia\n ? useMediaFeature({\n provider: props.config.media,\n onRequestMedia: props.config.onRequestMedia,\n getTemplateId: () => editor.state.template?.id,\n onError: props.config.onError,\n })\n : null;\n\nconst MediaPanels = defineAsyncComponent(\n () => import(\"./components/MediaPanels.vue\"),\n);\n\n// --- Test email (opt-in: only when a sending provider is configured) ---\n// Created before `useEditorCore` so its capability can be passed in, same as\n// saved blocks.\nconst testEmail = props.config.testEmail\n ? useTestEmailFeature({\n provider: props.config.testEmail,\n getContent: () => editor.content.value,\n renderMjml: props.renderMjml,\n usesLocalRenderer: props.usesLocalRenderer,\n onError: props.config.onError,\n // Cloud folds in the plan feature and \"the template must be saved\", both\n // constraints of *its* sending path rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isTestEmailAvailable()\n : undefined,\n })\n : null;\n\nconst TestEmailPanel = defineAsyncComponent(\n () => import(\"./components/TestEmailPanel.vue\"),\n);\n\n// --- Comments (opt-in: only with a storage provider *and* a `user`) ---\n// Built before `useEditorCore` so its capability can be passed in, which is what\n// lights up the header trigger and the per-block comment indicators.\n//\n// No `user` means no provider call at all — an unattributable comment is worse\n// than no comment feature, so `isAvailable` stays false and nothing renders.\nconst comments = props.config.comments\n ? useCommentsFeature({\n provider: props.config.comments,\n editor,\n user: props.config.user,\n // Cloud supplies its comments state; the open-source AI feature keeps\n // comments and AI panels exclusive in their shared 360px gutter.\n isOpen: cloudAttachment?.panelState.commentsOpen,\n onError: props.config.onError,\n // Cloud folds in the `commenting` plan feature and \"the template must be\n // saved\", both constraints of *its* store rather than of the contract.\n isAvailable: props.cloud\n ? () => props.cloud!.isCommentsAvailable()\n : undefined,\n // Cloud anchors a comment to a block in the saved template; a consumer's\n // store accepts whatever anchor it is given.\n isBlockSaved: props.cloud\n ? (blockId: string) => props.cloud!.isBlockSaved(blockId)\n : undefined,\n })\n : null;\n\nconst CommentsPanel = defineAsyncComponent(\n () => import(\"./components/CommentsPanel.vue\"),\n);\n\n// The AI panels: lazy, mounted only with an `ai` provider; each panel is its\n// own chunk inside.\nconst AiPanels = defineAsyncComponent(\n () => import(\"./components/ai/AiPanels.vue\"),\n);\n\n// --- AI (opt-in: an `ai` provider) ---\n// Built before `useEditorCore` so its capability is in the object core\n// provides. It reads core (the history and the merge tags) through\n// getters, at call time. Its panels are lazy (`AiPanels`); the header button\n// is not, so it renders with the rest of the header (`EditorHeader`).\nconst ai = props.config.ai\n ? useAiFeature({\n provider: props.config.ai,\n editor,\n localization: props.config.localization ?? { locales: [] },\n customBlockDefinitions: () => props.config.customBlocks ?? [],\n onStructureChange: () => {\n structureNotice.value++;\n },\n collaboration,\n history: () => core.history,\n reload: templates\n ? (id, shouldApply) => templates.load(id, shouldApply)\n : null,\n altMaxLength: () =>\n effectiveAltMaxLength(resolveLintOptions(props.config)),\n mergeTags: () => toAiMergeTags(core.mergeTags.value, core.mergeTagSyntax),\n normalize: (ops, content) =>\n normalizeRemoteOperations(ops, content, liveMergeTags),\n commentsOpen: comments?.isOpen ?? null,\n onError: props.config.onError,\n })\n : null;\nif (ai) provide(AI_FEATURE_KEY, ai);\n\n// One coverage pass per change in a language view, shared by the header\n// trigger, the language bar and its Translate counts.\nconst activeCoverage = useActiveLocaleCoverage(\n editor,\n props.config.customBlocks ?? [],\n);\nprovide(ACTIVE_LOCALE_COVERAGE_KEY, activeCoverage);\n\nconst translation = props.config.translation\n ? useTranslationFeature({\n provider: props.config.translation,\n editor,\n localization: props.config.localization,\n collaboration,\n history: () => core.history,\n definitions: () => props.config.customBlocks ?? [],\n syntax: () => core.mergeTagSyntax,\n coverage: () => activeCoverage.value,\n })\n : null;\nif (translation) provide(TRANSLATION_FEATURE_KEY, translation);\nconst localeNotice = ref<LocaleNotice | null>(null);\nwatch(\n [() => editor.state.template?.id ?? null, editor.loadVersion],\n () => {\n localeNotice.value = null;\n },\n { flush: \"sync\" },\n);\n// Undo (or any other change) that moves the default away from the notice's\n// language makes the notice untrue.\nwatch(\n () => defaultLocaleOf(editor.content.value),\n (current) => {\n if (localeNotice.value && localeNotice.value.language !== current)\n localeNotice.value = null;\n },\n { flush: \"sync\" },\n);\nconst localeActions = useLocaleActions({\n editor,\n history: () => core.history,\n collaboration,\n});\nprovide(LOCALE_ACTIONS_KEY, {\n setDefaultLocale(locale) {\n const notice = {\n language: locale,\n old: defaultLocaleOf(editor.content.value),\n count: defaultLocaleGaps(\n editor.content.value,\n locale,\n props.config.customBlocks,\n ).length,\n };\n const result = localeActions.setDefaultLocale(locale);\n if (result.applied) localeNotice.value = notice;\n return result;\n },\n});\nconst LocaleNotices = defineAsyncComponent(\n () => import(\"./components/localization/LocaleNotices.vue\"),\n);\n// Lazy: an editor without a collaboration provider never downloads it.\nconst CollaborationNotices = defineAsyncComponent(\n () => import(\"./components/collaboration/CollaborationNotices.vue\"),\n);\n\n// --- Cloud chrome (opt-in: only under `initCloud()`) ---\n// One lazy wrapper for every panel, overlay and modal Cloud adds, plus one for\n// its header controls. Same discipline as `SavedBlocksPanels` / `TestEmailPanel`:\n// an OSS consumer never downloads any of it.\nconst CloudPanels = defineAsyncComponent(\n () => import(\"./cloud/components/CloudPanels.vue\"),\n);\nconst CloudHeaderExtras = defineAsyncComponent(\n () => import(\"./cloud/components/CloudHeaderExtras.vue\"),\n);\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// The header control lives in `EditorHeader`; this is the preview banner, which\n// renders outside the header. Both are lazy.\nconst VersionHistoryPanels = defineAsyncComponent(\n () => import(\"./components/VersionHistoryPanels.vue\"),\n);\n\n// --- Auto-save ---\n// One debounced tick drives everything a consumer can ask for on a content\n// change: the `onChange` notification, and, when `templates.autoSave` is on,\n// the save itself. Sharing a single `useAutoSave` instance keeps the two in\n// step and inherits the pause-during-undo/redo behaviour `useEditorCore` wires\n// up around it. `config.changeDebounce` sets the cadence for both.\nconst autoSaveEnabled = resolveAutoSave(\n props.config.templates?.autoSave,\n false,\n);\nconst isAutoSaving = autoSaveEnabled && templates !== null;\n// The one way autosave can still be inert once a provider exists is its\n// `save` being `false` — a read-only store — which `requestAutoSave()` below\n// already no-ops per tick for; this warning is the only signal the consumer\n// gets. `templates !== null` is redundant with `autoSaveEnabled` at runtime\n// (the provider that enables autosave is the same provider that makes\n// `templates` non-null) but stays as an explicit conjunct so TypeScript can\n// narrow `templates.canSave.value` below without a non-null assertion.\nif (autoSaveEnabled && templates !== null && !templates.canSave.value) {\n logger.warn(\n \"config.templates.autoSave is on but this provider's save is false — \" +\n \"there is nothing to persist to. Give it a real save function, or \" +\n \"use `onChange` to persist the content yourself.\",\n );\n}\n// `changeDebounce` alone does not enable autosave — only `templates.autoSave`\n// does. A config with `changeDebounce` set, a provider present, `autoSave`\n// left unset, and no `onChange` has nothing consuming the timer at all,\n// which reads as intentional `onChange`-only pacing but is easy to reach by\n// mistake. Warn on exactly that combination; `autoSave: false` is a stated\n// decision and must stay silent.\nif (\n props.config.changeDebounce !== undefined &&\n templates !== null &&\n props.config.templates?.autoSave === undefined &&\n !props.config.onChange\n) {\n logger.warn(\n \"config.changeDebounce is set but nothing will use it — \" +\n \"config.templates.autoSave is unset and there is no onChange either, \" +\n \"so the timer has no consumer. Set config.templates.autoSave, or add \" +\n \"onChange, so the debounce takes effect.\",\n );\n}\n\nconst autoSaveOptions =\n props.config.onChange || isAutoSaving\n ? {\n onChange: () => {\n props.config.onChange?.(\n JSON.parse(JSON.stringify(editor.state.content)),\n );\n // `requestAutoSave()` already no-ops without a saveable template, so a\n // read-only provider costs one predicate per tick and nothing else.\n // It is the *ungated* request only in the sense that it never raises a\n // prompt: Cloud's lint gate still refuses it, which is what keeps\n // `accessibility.blockOnError` a policy rather than a manual-save\n // speed bump.\n if (isAutoSaving) templates!.requestAutoSave();\n },\n ...(props.config.changeDebounce !== undefined\n ? { debounce: props.config.changeDebounce }\n : {}),\n }\n : null;\n\n// --- Shared editor core (composables, provides, plugins, keyboard) ---\n// A named object rather than an inline literal: `useVersionHistoryFeature` can\n// only be built after core (it needs history/conditionPreview/autoSave), so its\n// capability is assigned in below, into the very object core provided.\nconst capabilities: EditorCapabilities = {\n ...(savedBlocks ? { savedBlocks: savedBlocks.capability } : {}),\n ...(templates ? { templates: templates.capability } : {}),\n ...(testEmail ? { testEmail: testEmail.capability } : {}),\n ...(comments ? { comments: comments.capability } : {}),\n ...(collaboration ? { collaboration: collaboration.capability } : {}),\n ...(ai ? { ai: ai.capability } : {}),\n};\n\nconst core = useEditorCore({\n editor,\n containerEl: rootEl,\n config: {\n uiTheme: props.config.uiTheme,\n theme: props.config.theme,\n blockDefaults: props.config.blockDefaults,\n templateDefaults: props.config.templateDefaults,\n customBlocks: props.config.customBlocks,\n paletteBlocks: props.config.paletteBlocks,\n htmlBlockPreview: props.config.htmlBlockPreview,\n layout: props.config.layout,\n sectionWrapper: props.config.sectionWrapper,\n colors: props.config.colors,\n templateSettings: props.config.templateSettings,\n mergeTags: props.config.mergeTags,\n logicTags: props.config.logicTags,\n displayConditions: props.config.displayConditions,\n // The synthesized Browse/drop handler. Null when neither a provider nor a\n // callback is configured, which is what keeps image fields URL-only.\n onRequestMedia: mediaFeature?.requestMedia ?? null,\n // Distinct from Browse: a read-only provider still opens the library.\n canDropMedia: mediaFeature?.canDrop ?? null,\n resolvePreview: props.config.resolvePreview,\n resolveImageUrl: props.config.resolveImageUrl,\n lint: resolveLintOptions(props.config),\n // For Intl-built labels (dates), which would otherwise format in the\n // BROWSER's locale and disagree with the translated chrome beside them.\n locale: props.config.locale,\n },\n translations: props.translations,\n fontsManager: props.fontsManager,\n autoSaveOptions,\n capabilities,\n editorRoot: props.shadowRoot,\n history: collaboration?.history,\n});\n\nconst rightSidebarTab = ref<RightSidebarTab>(\"content\");\nwatch(\n () => editor.state.template?.id,\n () => {\n if (editor.selectedBlock.value) rightSidebarTab.value = \"content\";\n },\n);\n\n// Cloud's setup-time wiring that needs `core`: the lint save-gate (reads\n// `core.templateLint`) and the capability entries Cloud contributes — mutated\n// into the very object `useEditorCore` provided, so injecting components see\n// them on first render.\nconst cloudReady =\n props.cloud && cloudAttachment\n ? props.cloud.ready({ core, capabilities })\n : null;\n\n// --- Version history (opt-in: only when a storage provider is configured) ---\n// Constructed *after* `useEditorCore` because it drives `history` /\n// `conditionPreview` / `autoSave`, which core owns. Its capability is therefore\n// assigned into the object above rather than passed in — same object reference\n// core provided, mutated during setup, so injecting components see it on their\n// first render.\nconst versionHistory = props.config.versionHistory\n ? useVersionHistoryFeature({\n provider: props.config.versionHistory,\n // The fifth content-in path. A stored version holds whatever was written\n // to it, so it can carry bare tokens like any other loaded content, and\n // previewing one would put them on a canvas where every other tag is a\n // chip. Wrapped at `setContent` rather than at the provider, because\n // version content also arrives off the hydrated list and out of the\n // `fetched` cache without touching `get()`.\n editor: withNormalizedContentWrites(editor, liveMergeTags),\n history: core.history,\n conditionPreview: core.conditionPreview,\n autoSave: core.autoSave,\n // A version on the canvas is a preview, not an edit: collaboration stops\n // reading the canvas for it, and a restore re-syncs from the backend.\n collaboration: collaboration\n ? {\n suspend: collaboration.core.suspend,\n resume: collaboration.core.resume,\n catchUp: collaboration.core.catchUp,\n reportReplaceRefused: collaboration.reportReplaceRefused,\n }\n : null,\n // Lets the restore confirmation offer to persist unsaved work instead of\n // only warning about it. Without a templates provider — or with one whose\n // `save` is `false` — there is nowhere to put that work, and the\n // confirmation says so rather than offering an action that can't happen.\n // Cloud additionally refuses while the lint gate would block: stacking a\n // second modal on the confirmation would be worse than saying there is\n // currently nowhere to put the work.\n saveBeforeRestore: templates\n ? {\n canSave: () =>\n templates.canSave.value &&\n !(props.cloud?.getSaveGate()?.shouldBlock.value ?? false),\n save: () => templates.save(\"restore\"),\n }\n : null,\n onError: props.config.onError,\n })\n : null;\n\nif (versionHistory) capabilities.versionHistory = versionHistory.capability;\n\n/**\n * Left/right insets for the canvas body and the footer, which must always agree.\n *\n * Comments and the open-source AI panels widen the right gutter while open.\n */\n/**\n * Whether a 360px feature panel occupies the right-hand gutter.\n *\n * Comments and the open-source AI panels share this gutter; the AI feature\n * keeps their open states mutually exclusive. Cloud also supplies its panel\n * state, which shares the comments ref.\n *\n * Two things read this, and **both must**: the canvas/footer insets below, and\n * `RightSidebar`'s `shifted-left` — the properties panel sits at `right-0` too, so\n * a panel opening over it would swallow every click meant for the panel.\n */\nconst rightPanelOpen = computed(\n () =>\n comments?.isOpen.value === true ||\n (ai !== null && ai.panel.value !== null) ||\n cloudAttachment?.panelState.rightPanelOpen.value === true,\n);\n\nconst bodyInsetClass = computed(() => {\n if (editor.state.previewMode) return \"tpl:left-0 tpl:right-0\";\n return rightPanelOpen.value\n ? \"tpl:left-12 tpl:right-[680px]\"\n : \"tpl:left-12 tpl:right-[320px]\";\n});\n\n// Both bands participate in flow; wrapping and async banner loads resize one box.\nconst topChrome = ref<HTMLElement | null>(null);\nconst topChromeHeight = ref(0);\nconst contentInsetStyle = computed(() => ({\n top: `calc(3.5 * var(--tpl-base-size) + ${topChromeHeight.value}px)`,\n}));\nlet topChromeObserver: ResizeObserver | undefined;\nonMounted(() => {\n topChromeHeight.value = topChrome.value?.offsetHeight ?? 0;\n if (topChrome.value && typeof ResizeObserver !== \"undefined\") {\n topChromeObserver = new ResizeObserver(([entry]) => {\n if (entry)\n topChromeHeight.value =\n entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;\n });\n topChromeObserver.observe(topChrome.value);\n }\n});\nonUnmounted(() => topChromeObserver?.disconnect());\n\n// --- Small-screen gate (#235) ---\n// Below ~768px the three-pane chrome can't lay out usably; show a notice\n// instead. Opt out with `config.smallScreenNotice: false`.\nconst { showNotice: showSmallScreenNotice } = useSmallScreenNotice(\n () => props.config.smallScreenNotice,\n);\n\n// --- Lifecycle ---\nonMounted(async () => {\n await props.fontsManager.loadCustomFonts();\n});\n\nonUnmounted(() => {\n props.fontsManager.cleanupFontLinks();\n ai?.destroy();\n props.cloud?.destroy();\n core.destroy();\n});\n\n// --- Public API (accessed via template ref from init()) ---\n// The lifecycle trio comes from the templates feature when one exists, so a\n// programmatic save also drives the header's status. Without a provider it comes\n// straight from core, whose own methods reject with the actionable error.\nconst templateLifecycle = templates ?? editor;\n\nconst scrollToBlock = useScrollToBlock(core.editorRoot);\n\ndefineExpose({\n getLocale: () =>\n editor.activeLocale.value ?? defaultLocaleOf(editor.content.value),\n setLocale: (locale: string) => editor.setActiveLocale(locale),\n getContent: () => editor.content.value,\n setContent: (content: TemplateContent) => editor.setContent(content),\n insertBlock: (block: Block): string | null => {\n // The palette is hidden in preview mode, and preview has no selection.\n if (editor.state.previewMode) {\n logger.warn(\"insertBlock() does nothing in preview mode.\");\n return null;\n }\n // A copy with fresh ids throughout, so inserting the same library item\n // twice never puts two blocks, rows or items on the canvas with one id.\n const copy = cloneBlock(block);\n if (!insertBlockAtSelection(editor, copy)) return null;\n scrollToBlock(copy.id);\n return copy.id;\n },\n setTheme: (theme: UiTheme) => editor.setUiTheme(theme),\n setMergeTags: core.setMergeTags,\n isDirty: () => editor.state.isDirty,\n create: templateLifecycle.create,\n load: templateLifecycle.load,\n save: templateLifecycle.save,\n renderCustomBlock: core.registry.renderCustomBlock,\n getCustomBlockStylesheet: (customType: string) =>\n core.registry.getDefinition(customType)?.stylesheet,\n});\n</script>\n\n<template>\n <!-- @dragover/@drop.prevent: a file dropped outside an image drop zone would\n otherwise make the browser navigate to the file:// URL and destroy the\n editor session. Image zones (useImageDrop) handle their own drops; this\n only neutralizes the default action everywhere else (#229). -->\n <div\n ref=\"rootEl\"\n class=\"tpl tpl:relative tpl:h-full\"\n :class=\"{ 'tpl:dark': editor.state.darkMode }\"\n :data-tpl-theme=\"core.resolvedTheme.value\"\n :style=\"core.themeStyles.value\"\n @dragover.prevent\n @drop.prevent\n >\n <!-- Reactive `<style>` tags for custom-block definition stylesheets in\n use. Sits at the top so its rules apply to the canvas below. -->\n <CustomBlockStylesheets />\n <!-- Chrome wrapper — the clip belongs here, never on the root and never\n around `.tpl-popover-root`. Safari paints a `position: fixed`\n descendant clipped to an ancestor's `overflow: hidden` box while still\n resolving its layout against the viewport, so a dialog teleported\n under a clipping ancestor is cut off wherever it extends past the\n container, and its backdrop dims only the container's own area\n (#633). Keeping the clip on this element bounds the header, rails,\n canvas and footer without reaching the popover root, and this box is\n identical to the root's, so everything anchored `absolute` inside\n lands exactly where it would against the root. Locked by\n `tests/popover-root-clip-scope.test.ts`. -->\n <div class=\"tpl:absolute tpl:inset-0 tpl:overflow-hidden\">\n <!-- One header for both entry points. Cloud's own controls arrive through\n the three slots; everything else here is capability-gated, so the same\n markup covers \"no providers at all\" and a fully-wired Cloud session. -->\n <EditorHeader\n :editor=\"editor\"\n :localization=\"props.config.localization\"\n :core=\"core\"\n :templates=\"templates\"\n :show-template-name=\"config.templates?.nameField !== false\"\n :test-email=\"testEmail\"\n :version-history=\"versionHistory\"\n :comments=\"comments\"\n :collaboration=\"collaboration\"\n :ai=\"ai\"\n >\n <template v-if=\"cloudAttachment\" #left-extras>\n <CloudHeaderExtras part=\"left\" :cloud=\"cloudAttachment\" />\n </template>\n <template v-if=\"cloudAttachment\" #right-extras>\n <CloudHeaderExtras part=\"right\" :cloud=\"cloudAttachment\" />\n </template>\n </EditorHeader>\n\n <!-- Left sidebar — absolute, below header -->\n <Sidebar v-show=\"!editor.state.previewMode\" :style=\"contentInsetStyle\" />\n\n <!-- Canvas area — absolute, fills remaining space -->\n <div\n class=\"tpl-body tpl:absolute tpl:bottom-0 tpl:overflow-auto tpl:bg-[var(--tpl-canvas-bg)]\"\n style=\"\n transition:\n left var(--tpl-transition),\n right var(--tpl-transition);\n \"\n :style=\"contentInsetStyle\"\n :class=\"bodyInsetClass\"\n >\n <!-- Preview chrome, floated over the canvas.\n\n A zero-height sticky layer holding one absolutely-positioned,\n canvas-centred **column**. Zero height means the layer contributes no\n space of its own, so nothing here can push the canvas around — which\n is what lets the merge-tag toggle live over the preview instead of in\n the header, whose centre track re-centres on every width change and\n so dragged the Preview button 114.5px sideways each time the toggle\n appeared (#574).\n\n A column rather than two fixed offsets. Both pills are reachable at\n once — the restore pill needs hidden blocks, the toggle needs preview\n mode without a `resolvePreview`, and nothing makes those exclusive —\n so they have to stack. Doing that with a hardcoded second offset put\n the restore pill 48px down even when it rendered alone, which in\n editing mode (where the toggle never shows) dropped it onto the first\n block's content. Flow solves what the offset got wrong: whichever\n pills render sit tight under the header, in order.\n\n Locked by `tests/headerCenterStability.test.ts`. -->\n <div class=\"tpl-preview-overlay tpl:sticky tpl:top-0 tpl:z-40 tpl:h-0\">\n <div\n class=\"tpl:absolute tpl:left-1/2 tpl:top-2 tpl:flex tpl:-translate-x-1/2 tpl:flex-col tpl:items-center tpl:gap-2\"\n >\n <!-- Sample / Label. Preview mode only: merge tags are never\n substituted on the editing canvas, so the choice would have no\n effect there. A configured `resolvePreview` supersedes samples\n entirely.\n\n The wrapper carries only the shadow that lifts the control off\n the canvas — no `backdrop-filter`, because the toggle's own\n `--tpl-bg-hover` fill is opaque and covers this box exactly, so a\n blur would composite a layer to show nothing. -->\n <Transition name=\"tpl-preview-pill\">\n <div\n v-if=\"\n editor.state.previewMode &&\n !core.previewResolution.supersedesSamples.value\n \"\n data-testid=\"merge-tag-mode-toggle-anchor\"\n class=\"tpl:rounded-[var(--tpl-radius-sm)] tpl:shadow-[var(--tpl-shadow-md)]\"\n >\n <MergeTagModeToggle\n :sample-mode=\"core.mergeTagSampleMode.value\"\n @change=\"core.mergeTagSampleMode.value = $event\"\n />\n </div>\n </Transition>\n <!-- Show all hidden blocks. The shared warning recipe, not a bespoke\n string: it has to read as the Sample/Label switch's sibling,\n since the two stack here, and a hand-rolled pill is how this one\n came to sit 8px shorter with a different radius and a 1.85:1\n label. `warningBtnCompactClass` carries why the amber is on the\n border rather than the text. -->\n <Transition name=\"tpl-preview-pill\">\n <button\n v-if=\"\n core.conditionPreview.hasHiddenBlocks.value &&\n core.appliesConditionFilter.value\n \"\n type=\"button\"\n :class=\"warningBtnCompactClass\"\n class=\"tpl:shadow-[var(--tpl-shadow-md)]\"\n data-testid=\"restore-hidden-blocks\"\n @click=\"core.conditionPreview.reset()\"\n >\n <RotateCcw :size=\"16\" :stroke-width=\"2\" />\n {{ core.t.blockSettings.restoreHiddenBlocks }}\n </button>\n </Transition>\n </div>\n </div>\n <!-- No justify-center and no inline padding: the stage centres\n itself with auto margins and keeps its own clearance\n (Canvas.vue). A flex-centred child that overflows sticks out on\n both sides, and the left side can never be scrolled to. -->\n <main class=\"tpl-main tpl:flex tpl:py-8\">\n <Canvas\n :viewport=\"editor.state.viewport\"\n :content=\"core.previewResolution.content.value\"\n :selected-block-id=\"editor.state.selectedBlockId\"\n :dark-mode=\"editor.state.darkMode\"\n :preview-mode=\"editor.state.previewMode\"\n @select-block=\"editor.selectBlock\"\n />\n </main>\n </div>\n\n <EditorFooter\n v-if=\"config.branding !== false\"\n :position-class=\"[bodyInsetClass]\"\n />\n\n <!-- Keyboard reorder announcement region (visually hidden, screen-reader live) -->\n <div\n class=\"tpl-sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n :aria-label=\"core.t.landmarks.reorderAnnouncements\"\n >\n {{ core.keyboardReorder.announcement.value }}\n </div>\n\n <!-- Right sidebar — persisted with v-show -->\n <RightSidebar\n v-show=\"!editor.state.previewMode\"\n v-model:tab=\"rightSidebarTab\"\n :style=\"contentInsetStyle\"\n style=\"transition-property: right\"\n :selected-block=\"\n editor.selectedBlock.value\n ? localized.displayBlock(editor.selectedBlock.value)\n : null\n \"\n :settings=\"localized.settings.value\"\n :shifted-left=\"rightPanelOpen\"\n @update-block=\"\n (updates) =>\n editor.updateBlock(editor.state.selectedBlockId!, updates)\n \"\n @delete-block=\"\n () => {\n if (editor.state.selectedBlockId) {\n core.blockActions.deleteBlock(editor.state.selectedBlockId);\n }\n }\n \"\n @duplicate-block=\"\n () => {\n if (editor.selectedBlock.value) {\n core.blockActions.duplicateBlock(editor.selectedBlock.value);\n }\n }\n \"\n @update-settings=\"(updates) => editor.updateSettings(updates)\"\n />\n\n <div\n ref=\"topChrome\"\n class=\"tpl-top-chrome tpl:absolute tpl:top-14 tpl:right-0 tpl:left-0 tpl:z-40\"\n >\n <VersionHistoryPanels\n v-if=\"versionHistory?.isAvailable.value\"\n :feature=\"versionHistory\"\n />\n <LanguageBar\n v-if=\"config.localization\"\n :editor=\"editor\"\n :locales=\"config.localization.locales\"\n :feature=\"translation\"\n :change=\"structureNotice\"\n />\n </div>\n </div>\n\n <!-- Popover mount — Teleport target for toolbars, link dialog, modals.\n Every popup mounts here rather than at the page's `<body>`, so it\n renders inside the editor's effective DOM root and keeps the shadow\n root's adopted stylesheet; a body-level teleport leaves the shadow\n tree and renders unstyled. It also has to stay a child of `.tpl`, which\n declares `--tpl-base-size` and the colour tokens — `@theme inline`\n rebases the whole Tailwind length scale onto that variable, so a\n popup hoisted out would lose the sizing scale as well as the palette.\n Enforced by the `no-teleport-to-body` ESLint rule and\n `tests/global-refs-audit.test.ts`. -->\n <div\n :ref=\"(el) => (core.popoverRoot.value = el as HTMLElement | null)\"\n class=\"tpl-popover-root\"\n />\n\n <!-- Built-in merge tag picker modal. Reads picker state via injection;\n renders nothing until `picker.isOpen` flips true. -->\n <MergeTagPickerModal />\n\n <!-- Built-in logic picker modal (standalone logic feature). -->\n <LogicTagPickerModal />\n\n <!-- Saved blocks dialogs. Only mounted when a provider is configured;\n each dialog's chunk loads on first open. -->\n <SavedBlocksPanels\n v-if=\"savedBlocks?.isAvailable.value\"\n :feature=\"savedBlocks\"\n />\n\n <!-- Media library modal. Only mounted when a storage provider is\n configured; the modal's chunk loads on first Browse. A callback-only\n `onRequestMedia` never mounts this — the host brought a widget. -->\n <MediaPanels\n v-if=\"config.media && mediaFeature\"\n :feature=\"mediaFeature\"\n :provider=\"config.media\"\n :locale=\"config.locale\"\n :ui-theme=\"core.resolvedTheme.value\"\n :popover-target=\"core.popoverRoot.value\"\n />\n\n <TestEmailPanel v-if=\"testEmail?.isAvailable.value\" :feature=\"testEmail\" />\n\n <!-- The comments sidebar. Only mounted when a provider and a `user` are\n configured; the sidebar's own chunk loads the first time it opens. -->\n <CommentsPanel v-if=\"comments?.isAvailable.value\" :feature=\"comments\" />\n\n <!-- The AI chat panel shares the right gutter with\n comments, one at a time (D18). -->\n <AiPanels v-if=\"ai\" :feature=\"ai\" />\n\n <!-- Collaboration notices: a refused selection or edit, a skipped undo,\n a refused replace, reconnecting. -->\n <NoticeStack v-if=\"collaboration || localeNotice\">\n <CollaborationNotices v-if=\"collaboration\" :feature=\"collaboration\" />\n <LocaleNotices\n v-if=\"localeNotice\"\n :notice=\"localeNotice\"\n @dismiss=\"localeNotice = null\"\n />\n </NoticeStack>\n\n <!-- Cloud sidebars, modals and overlays. One lazy wrapper, mounted only\n under `initCloud()`; an OSS consumer downloads none of it. -->\n <CloudPanels\n v-if=\"cloud && cloudAttachment && cloudReady\"\n :editor=\"editor\"\n :core=\"core\"\n :runtime=\"cloud\"\n :cloud=\"cloudAttachment\"\n :ready=\"cloudReady\"\n />\n\n <!-- Small-screen gate (#235). Last child + a literal z-index above the\n chrome and `.tpl-popover-root`, so the opaque notice covers everything\n below the breakpoint. -->\n <SmallScreenNotice v-if=\"showSmallScreenNotice\" />\n </div>\n</template>\n\n<style scoped>\n.tpl-preview-pill-enter-active {\n transition:\n opacity 200ms cubic-bezier(0.16, 1, 0.3, 1),\n transform 200ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n.tpl-preview-pill-leave-active {\n transition:\n opacity 150ms ease-in,\n transform 150ms ease-in;\n}\n\n.tpl-preview-pill-enter-from,\n.tpl-preview-pill-leave-to {\n opacity: 0;\n transform: translateY(-8px) scale(0.9);\n}\n\n.tpl-preview-pill-enter-to,\n.tpl-preview-pill-leave-from {\n opacity: 1;\n transform: translateY(0) scale(1);\n}\n</style>\n","/**\n * An `@import` rule. The URL alternatives are quote-aware because a URL can\n * carry `;` (Google Fonts' `wght@400;500`), which would otherwise end the\n * match mid-URL and leave the rest of it behind in the CSS.\n */\nconst IMPORT_RULE =\n /@import\\s*(?:url\\(\\s*(?:\"[^\"]*\"|'[^']*'|[^)]*)\\s*\\)|\"[^\"]*\"|'[^']*')[^;]*;/g;\n\n/**\n * Removes every `@import` rule from CSS headed for a constructed stylesheet.\n * A constructed sheet cannot hold one: `replaceSync` drops it and logs a\n * warning on the host page.\n */\nexport function stripStylesheetImports(css: string): string {\n return css.replace(IMPORT_RULE, \"\");\n}\n","import type {\n CustomBlock,\n CustomFont,\n RenderPayload,\n RenderProvider,\n TemplateContent,\n} from \"@templatical/types\";\nimport {\n defaultLocaleOf,\n resolveLocale,\n applyLayout,\n assertNoSlotInContent,\n assertNoWrapperInContent,\n safeClone,\n} from \"@templatical/types\";\nimport { preRenderCustomBlocks } from \"./preRenderCustomBlocks\";\n\n/** The fonts half of a {@link RenderPayload}, as the editor resolves it. */\nexport interface RenderFonts {\n customFonts: CustomFont[];\n defaultFallback: string;\n}\n\n/** Minimal slice of the fonts manager the payload needs. */\nexport interface RenderFontsSource {\n customFonts: { value: CustomFont[] };\n defaultFallback: { value: string };\n}\n\n/**\n * The fonts the editor is *actually* rendering with.\n *\n * The canvas's font set and the payload's are the same set *by construction*\n * rather than by agreement: nothing can switch custom faces off for a plan, so\n * there is no second source of truth to keep in step.\n */\nexport function resolveRenderFonts(source: RenderFontsSource): RenderFonts {\n return {\n customFonts: source.customFonts.value,\n defaultFallback: source.defaultFallback.value,\n };\n}\n\n/** What {@link buildRenderPayload} needs from an editor instance. */\nexport interface RenderPayloadSource {\n getContent: () => TemplateContent;\n renderCustomBlock: (block: CustomBlock) => Promise<string>;\n getCustomBlockStylesheet: (customType: string) => string | undefined;\n getFonts: () => RenderFonts;\n /**\n * Optional. Embedder shell spliced onto the payload's `content` so a BYO\n * `render.toMjml` cannot drop the chrome by treating payload content as\n * today's template. Omitting it (or returning undefined) leaves the\n * unshelled clone. Never written back into `getContent()`.\n */\n getLayout?: () => TemplateContent | undefined;\n}\n\n/**\n * Assemble the render-complete payload a {@link RenderProvider} is promised.\n *\n * \"Render-complete\" is the deal that lets the provider win over the bundled\n * renderer: local rendering sees custom blocks and fonts natively, a backend\n * doesn't, so the editor resolves both up front instead of each backend\n * rediscovering the problem.\n *\n * The content is a **defensive copy** (`safeClone`, same as `getContent()`, since\n * a drag inside a section can leave a Sortable expando cycle reachable from live\n * content). When `getLayout` returns a shell, that copy is composed (`applyLayout`)\n * so a BYO `render.toMjml` cannot drop the chrome by reading payload content as\n * today's template. Pre-rendering writes `renderedHtml` and\n * `renderedStylesheet` onto blocks, and doing that to the live tree would mark\n * the editor dirty and make an export mutate the document.\n */\nexport async function buildRenderPayload(\n source: RenderPayloadSource,\n options?: { locale?: string },\n): Promise<RenderPayload> {\n const raw = safeClone(source.getContent());\n const locale = options?.locale ?? defaultLocaleOf(raw);\n const localized =\n options?.locale !== undefined || raw.settings?.locales?.length\n ? resolveLocale(raw, locale)\n : raw;\n const layout = source.getLayout?.();\n const content = layout\n ? applyLayout(\n resolveLocale(layout, locale, { missing: \"default\" }),\n localized,\n )\n : localized;\n if (!layout) {\n assertNoSlotInContent(content);\n assertNoWrapperInContent(content);\n }\n await preRenderCustomBlocks(content, {\n renderCustomBlock: source.renderCustomBlock,\n getCustomBlockStylesheet: source.getCustomBlockStylesheet,\n });\n\n return { content, fonts: source.getFonts() };\n}\n\n/** What {@link createRenderMethods} needs to resolve each method. */\nexport interface RenderMethodsSource {\n /** The consumer's backend, when `render` was configured. */\n provider?: RenderProvider | null;\n buildPayload: (options?: { locale?: string }) => Promise<RenderPayload>;\n /**\n * Render MJML with the bundled `@templatical/renderer`. Expected to reject with\n * the \"install @templatical/renderer\" error when the optional peer is absent —\n * that rejection *is* the `toMjml()` chain's final `throw`.\n */\n renderLocalMjml: (options?: { locale?: string }) => Promise<string>;\n}\n\nexport interface RenderMethods {\n toMjml(options?: { locale?: string }): Promise<string>;\n toHtml(options?: { locale?: string }): Promise<string>;\n /** Whether the provider can produce sending-ready HTML without guessing. */\n canRenderHtml(): boolean;\n /**\n * Whether {@link toMjml} would reach the bundled `@templatical/renderer` —\n * false once the provider implements `toMjml` and owns the render itself.\n *\n * Exists so a caller can tell what a rejected render *could* have been caused\n * by. A missing optional peer is a plausible reading only on the local path;\n * on the provider path it never is, and acting on it would swallow the\n * backend's own error. The test-email dialog's `includeMjml` degradation is\n * the one consumer.\n *\n * Resolved per call, like the two render methods, so a provider completed\n * after construction answers for what would happen now.\n */\n usesLocalRenderer(): boolean;\n}\n\n/**\n * `editor.toMjml()` / `editor.toHtml()`, resolved **per method rather than per\n * provider** — a provider that implements one of the three methods is not thereby\n * claiming the others.\n *\n * | Call | Order |\n * |---|---|\n * | `toMjml()` | `provider.toMjml` → the bundled renderer → throw |\n * | `toHtml()` | `provider.toHtml` → `toMjml()` + `provider.compileMjml` → throw |\n *\n * `toHtml()` composes through `toMjml()` rather than forcing the local renderer,\n * so a provider whose MJML is authoritative (Cloud's is — it renders block types\n * a browser cannot) is not silently bypassed on the way to HTML. When the provider\n * only supplies `compileMjml`, that resolves to local MJML anyway, which is the\n * cheap tier working exactly as intended.\n *\n * **There is no local HTML path, ever.** The SDK deliberately does not bundle an\n * MJML compiler, so the last step is a rejection with instructions rather than a\n * guess.\n */\nexport function createRenderMethods(\n source: RenderMethodsSource,\n): RenderMethods {\n async function toMjml(options?: { locale?: string }): Promise<string> {\n const provider = source.provider;\n // Bound rather than narrowed in place: the call sits behind an `await`, and a\n // bound reference cannot be re-read as undefined afterwards.\n const providerToMjml = provider?.toMjml?.bind(provider);\n if (providerToMjml) {\n return providerToMjml(await source.buildPayload(options));\n }\n return source.renderLocalMjml(options);\n }\n\n async function toHtml(options?: { locale?: string }): Promise<string> {\n const provider = source.provider;\n\n const providerToHtml = provider?.toHtml?.bind(provider);\n if (providerToHtml) {\n return providerToHtml(await source.buildPayload(options));\n }\n\n const compileMjml = provider?.compileMjml?.bind(provider);\n if (compileMjml) {\n return compileMjml(await toMjml(options));\n }\n\n throw new Error(\n \"[Templatical] toHtml() requires a `render` provider implementing either \" +\n \"`toHtml` or `compileMjml`. The SDK does not bundle an MJML compiler, so \" +\n \"there is no local HTML path — point `compileMjml` at any mjml2html \" +\n \"endpoint (a hosted service, a container, or a CLI shell-out).\",\n );\n }\n\n function usesLocalRenderer(): boolean {\n return typeof source.provider?.toMjml !== \"function\";\n }\n\n function canRenderHtml(): boolean {\n return (\n typeof source.provider?.toHtml === \"function\" ||\n typeof source.provider?.compileMjml === \"function\"\n );\n }\n\n return { toMjml, toHtml, canRenderHtml, usesLocalRenderer };\n}\n","// eslint-disable-next-line @typescript-eslint/triple-slash-reference -- ambient-module declaration must be loaded for cross-package typecheck (workspace path alias resolves to source)\n/// <reference path=\"./virtual-modules.d.ts\" />\nimport { createApp, h, ref, type App, type Ref } from \"vue\";\nimport { DEFAULT_AUTO_SAVE_DEBOUNCE_MS } from \"@templatical/core\";\nimport type {\n AiProvider,\n Block,\n BlockDefaults,\n CollaborationProvider,\n CollaborationRemoteChange,\n ColorsConfig,\n CommentsProvider,\n CustomBlock,\n CustomBlockDefinition,\n DisplayConditionsConfig,\n EditorUser,\n FontsConfig,\n LogicTagsConfig,\n MediaProvider,\n MediaRequestContext,\n MediaResult,\n MergeTag,\n MergeTagsConfig,\n RenderProvider,\n SavedBlocksProvider,\n TestEmailProvider,\n TranslationProvider,\n Template,\n TemplateContent,\n TemplateDefaults,\n TemplateSettingsConfig,\n TemplatesProvider,\n ThemeOverrides,\n VersionHistoryProvider,\n UiTheme,\n ResolvePreview,\n} from \"@templatical/types\";\nimport {\n defaultLocaleOf,\n isLocaleTag,\n SdkError,\n assertNoSlotInContent,\n assertNoWrapperInContent,\n createDefaultTemplateContent,\n safeClone,\n validateLayout,\n} from \"@templatical/types\";\nimport { resolveTemplateDefaults } from \"./utils/resolveTemplateDefaults\";\n\nimport Editor from \"./Editor.vue\";\nimport type { CloudRuntime } from \"./cloud/runtime\";\nimport type { TemplaticalCloudEditorConfig } from \"./cloud/cloudConfig\";\nimport type { ResolveImageUrl } from \"./composables/useImageUrlResolver\";\nimport {\n getSupportedLocales,\n isLocaleSupported,\n loadTranslations,\n loadCloudTranslations,\n} from \"./i18n\";\nimport { logger } from \"./utils/logger\";\nimport { useFonts, type UseFontsReturn } from \"./composables\";\nimport { stripStylesheetImports } from \"./utils/stripStylesheetImports\";\nimport { toMjmlForInstance } from \"./utils/toMjml\";\nimport {\n normalizeBlockForConfig,\n normalizeContentForConfig,\n} from \"./utils/normalizeMergeTagMarkup\";\nimport {\n buildRenderPayload,\n createRenderMethods,\n resolveRenderFonts,\n type RenderMethods,\n} from \"./utils/renderProvider\";\nimport type { HtmlBlockPreviewConfig } from \"./utils/resolveHtmlBlockPreview\";\n// Compiled-CSS-as-string for shadow root adoption. The `virtual:editor-css`\n// module is owned by `scripts/inline-style-css-plugin.ts` — at build time it\n// captures every emitted CSS asset (Tailwind utilities + every `.vue` SFC\n// `<style>` block + `styles/index.css` rules) and replaces this import's\n// runtime value with the full library CSS string. In dev/test the plugin\n// returns `styles/index.css` source as a fallback.\n//\n// Separate concern from the side-effecting `import \"./styles/index.css\"` in\n// `Editor.vue`, which injects styles into `document.head` for light-DOM mode and\n// survives untouched.\n//\n// `ownedStyleRoots` tells the dev style mirror which `document.head` styles are\n// the editor's when a host app compiles it from source (see\n// `attachDevStyleMirror`).\n//\n// Ambient declaration for `virtual:editor-css` lives in `virtual-modules.d.ts`\n// referenced at the top of this file via triple-slash so it's visible to any\n// consumer typechecking through the workspace path alias.\nimport editorStylesInline, { ownedStyleRoots } from \"virtual:editor-css\";\n\n// ---------------------------------------------------------------------------\n// OSS config + return types\n// ---------------------------------------------------------------------------\n\nexport interface TemplaticalEditorConfig {\n /** Enabled template languages. Versions are added by the author. */\n localization?: { locales: string[]; doNotTranslate?: string[] };\n /** Translation backend for enabled language versions. */\n translation?: TranslationProvider;\n onLocaleChange?: (locale: string) => void;\n /**\n * Where to mount the editor — a CSS selector or an `HTMLElement`.\n *\n * Layout caveat: do NOT apply `transform`, `filter`, `perspective`, or\n * `will-change` to an ancestor of this element. Each establishes a CSS\n * containing block for `position: fixed`, which offsets the editor's\n * floating UI (color pickers, rich-text toolbars) and its drag ghost away\n * from their anchor — even when the transform's computed value is `none`\n * (an active/animated transform still promotes the element). For a\n * scroll/entrance effect on a wrapper, animate `opacity` instead of\n * `transform`.\n */\n container: string | HTMLElement;\n content?: TemplateContent;\n\n /**\n * Embedder-owned email shell, applied as an overlay at preview and at\n * `toMjml()` / `toHtml()`. Never written into `getContent()`, save, history,\n * or the editing canvas.\n *\n * A Templatical JSON document with exactly one `slot` — top-level (header /\n * footer / mat) or inside a layout `wrapper` (the card around author\n * sections). Build it with `createSlotBlock()` / `createWrapperBlock()`.\n *\n * See the [Layout](https://docs.templatical.com/guide/layout) guide.\n */\n layout?: TemplateContent;\n\n /**\n * Whether the section toolbar offers Add wrapper. Defaults to on\n * (`!== false`). Set `false` to hide the control, including where a\n * wrapper is legal (sibling-slot layout, or no layout).\n *\n * Presentation only: hiding never strips `section.wrapper` from content\n * and does not refuse `updateBlock`. A section that already has a wrapper\n * still shows the panel so it can be turned off.\n *\n * Independent of {@link layout}. A sibling-slot layout still wants the\n * control; hiding is this flag, not inferred from a layout being set.\n */\n sectionWrapper?: boolean;\n\n /**\n * Mount the editor inside a Shadow DOM (open mode) for CSS isolation\n * from the host page. Defaults to `true` — host stylesheets cannot\n * cascade past the shadow boundary into editor elements (`p`, `a`,\n * `input`, etc.), and editor utility classes never collide with host\n * class names.\n *\n * Set to `false` to mount in light DOM. Opt out when:\n * - Your host integration uses `document.querySelector` to reach\n * editor internals (with shadow DOM, use `container.shadowRoot\n * .querySelector(...)` instead).\n * - You need to support Firefox <101 or Safari <16.4, which lack the\n * `adoptedStyleSheets` API the shadow path relies on.\n *\n * Light-mode consumers should keep this set to `false` explicitly so\n * future SDK changes don't silently flip the default again.\n *\n * @default true\n */\n shadowDom?: boolean;\n\n onChange?: (content: TemplateContent) => void;\n onError?: (error: Error) => void;\n\n /**\n * Called whenever the editor's unsaved-changes state flips — `true` on the\n * first edit after a save, `false` once a save completes.\n *\n * Works with or without a `templates` provider, because the editor's own\n * `beforeunload` guard cannot cover SPA route changes: an embedded editor's\n * consumer has to guard their router themselves, and this is what they guard\n * it with.\n */\n onDirtyChange?: (isDirty: boolean) => void;\n\n /**\n * Storage backend for **the template itself** — the save/load lifecycle around\n * whatever is on the canvas.\n *\n * The editor owns the header's name field, save button and save-status\n * indicator, the Cmd+S shortcut, autosave and the unsaved-changes guard; you\n * own persistence. Three methods:\n *\n * ```ts\n * const editor = await init({\n * container,\n * templates: {\n * load: (id) => fetch(`/api/templates/${id}`).then((r) => r.json()),\n * create: (input) =>\n * fetch(\"/api/templates\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(input),\n * }).then((r) => r.json()),\n * save: (id, patch) =>\n * fetch(`/api/templates/${id}`, {\n * method: \"PATCH\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(patch),\n * }).then((r) => r.json()),\n * },\n * });\n *\n * await editor.load(\"tpl_123\");\n * ```\n *\n * Autosave (`templates.autoSave`), the unsaved-changes guard\n * (`templates.unsavedChangesGuard`) and the header's inline name field\n * (`templates.nameField`) are configured on this same object — grouped here\n * because none of the three mean anything without somewhere to save to.\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * name field, no save button, no status indicator — and `create()` / `load()` /\n * `save()` reject with an explanatory error. Persist the content yourself from\n * `onChange` instead; Cmd+S then flushes that notification immediately rather\n * than waiting out the debounce.\n *\n * Opening a template is deliberately imperative: there is no `templateId`\n * config key and no in-editor template browser, because choosing which\n * template to open belongs to your application.\n */\n templates?: TemplatesProvider;\n\n /**\n * Rendering backend — how the template becomes MJML, and how MJML becomes the\n * HTML you send.\n *\n * Separate from `templates` on purpose: saving and rendering run at different\n * frequencies (autosave would compile MJML on every debounce tick) and fail in\n * different ways. Every method is optional, and `editor.toMjml()` /\n * `editor.toHtml()` resolve each one independently:\n *\n * | Call | Order |\n * |---|---|\n * | `toMjml()` | `render.toMjml` → the bundled `@templatical/renderer` → throw |\n * | `toHtml()` | `render.toHtml` → `toMjml()`'s result + `render.compileMjml` → throw |\n *\n * **Omitted by default**, in which case `toMjml()` renders locally and\n * `toHtml()` rejects — the SDK deliberately bundles no MJML compiler, so there\n * is no local HTML path. One endpoint is enough to close that gap:\n *\n * ```ts\n * init({\n * container,\n * render: {\n * compileMjml: (mjml) =>\n * fetch(\"/api/mjml\", { method: \"POST\", body: mjml }).then((r) => r.text()),\n * },\n * });\n * ```\n *\n * Provider methods receive a **render-complete** payload: custom blocks already\n * resolved to `renderedHtml`, and the editor's effective fonts. Both are things\n * a backend cannot reconstruct from the template JSON alone.\n */\n render?: RenderProvider;\n\n /**\n * Storage backend for the template's **version history** — the past states a\n * user can browse, preview and restore.\n *\n * The editor owns the header's history control, the preview banner and the\n * restore flow; you own the storage. `list` and `get` are the operations;\n * `create` and `restore` can each be turned off by passing `false` instead of\n * a function.\n *\n * ```ts\n * init({\n * container,\n * versionHistory: {\n * list: (templateId) =>\n * fetch(`/api/templates/${templateId}/versions`).then((r) => r.json()),\n * get: (templateId, versionId) =>\n * fetch(`/api/templates/${templateId}/versions/${versionId}`)\n * .then((r) => r.json())\n * .then((v) => v.content),\n * create: false,\n * restore: (templateId, versionId) =>\n * fetch(`/api/templates/${templateId}/versions/${versionId}/restore`, {\n * method: \"POST\",\n * }).then((r) => r.json()),\n * },\n * });\n * ```\n *\n * **Omitted by default** — the control does not render and none of its UI is\n * downloaded. It also stays hidden until a template is loaded, since a version\n * belongs to a template id.\n *\n * **The editor never records a version by itself.** Whichever\n * `TemplatesProvider.save` you supply decides whether a save also records one,\n * so throttling and retention stay with the side that pays for the storage.\n */\n versionHistory?: VersionHistoryProvider;\n\n /**\n * How long the editor waits after the last edit before it fires `onChange`\n * and, when `templates.autoSave` is on, saves.\n *\n * One timer drives both, so they cannot drift apart. Set it with no templates\n * provider to pace `onChange` alone.\n *\n * @default 2000\n */\n changeDebounce?: number;\n\n /**\n * Storage backend for the **media library** — the picker behind Browse on\n * image fields, video thumbnails, and custom-block image fields.\n *\n * The editor owns the modal, grid, crop and insertion; you own persistence.\n * `list` is required; every other method is `false | fn`. All mutations\n * `false` is a read-only library: browse, search and pick still work.\n *\n * Implement the methods of `MediaProvider` against your own API, or use\n * the bundled browser-local provider for demos and prototypes:\n *\n * ```ts\n * import { init, createLocalStorageMediaProvider } from \"@templatical/editor\";\n *\n * init({ container, media: createLocalStorageMediaProvider() });\n * ```\n *\n * **Omitted by default.** Image fields stay URL-only. `onRequestMedia` is\n * the UI override (a host widget) and wins when both are set.\n */\n media?: MediaProvider;\n\n onRequestMedia?: OnRequestMedia;\n\n /**\n * Resolves the template for preview surfaces — typically evaluating logic\n * tags (`{% if %}` … `{% endif %}`) against real data on your backend.\n *\n * Called when a preview opens and when the test-email recipient changes,\n * debounced. Display-only: the result never reaches `getContent()`, a send or\n * an export. Rejecting is safe — the preview falls back to the unresolved\n * template and says so.\n *\n * Supersedes `MergeTag.sample` when configured: real data beats example data,\n * so the Sample/Label switch stops rendering.\n */\n resolvePreview?: ResolvePreview;\n\n /**\n * Display-only resolver for image `src` values. The canvas calls this to\n * obtain a preview URL for a src the user entered; the content model (and\n * `toMjml()` output) always keeps the canonical value. Return `null` — or\n * the input value — to use the src as-is.\n *\n * Use this when templates reference images by a value that isn't directly\n * displayable, e.g. plain file names resolved to ephemeral `blob:` URLs\n * from local storage:\n *\n * ```ts\n * resolveImageUrl: async (src) => {\n * const file = await fileStore.lookup(src);\n * return file ? URL.createObjectURL(file) : null;\n * }\n * ```\n *\n * The resolver is called once per committed src value (typing in the src\n * input is debounced, so partial values never reach it) and results are\n * cached per src for the editor's lifetime — including failures, which\n * fall back to displaying the src verbatim. Note the caching applies to\n * transient failures too: a src that failed to resolve stays unresolved\n * until the editor is re-initialized (a re-resolve hook may be added\n * later). Applies to image srcs, design-time placeholder previews, explicit\n * video thumbnails, and section and wrapper background images;\n * auto-derived provider thumbnails (YouTube/Vimeo) are already real URLs and\n * are never resolved, and a background image whose URL holds a merge tag is\n * neither resolved nor painted.\n */\n resolveImageUrl?: ResolveImageUrl;\n\n mergeTags?: MergeTagsConfig;\n /**\n * Standalone logic tags — control-flow tokens (`{% else %}`) and open/close\n * pairs (`{% if %}` … `{% endif %}`) inserted from a dedicated \"Insert logic\"\n * button. Separate from `mergeTags`; typed/pasted logic is highlighted\n * regardless of this config.\n */\n logicTags?: LogicTagsConfig;\n displayConditions?: DisplayConditionsConfig;\n customBlocks?: CustomBlockDefinition[];\n\n /**\n * Allowlist + order for the block palette. When non-empty, only the listed\n * block types appear in the sidebar palette, in exactly this order —\n * unlisted built-ins (e.g. `video`, `table`) are hidden. When omitted or\n * empty (`[]`), the full default palette is shown: an empty allowlist means\n * \"not configured\", not \"hide every block\".\n *\n * Reference built-in blocks by their bare type (`'section'`, `'image'`, …)\n * and custom blocks by their `custom:`-prefixed type (`'custom:qrcode'`),\n * so they can be interleaved freely:\n *\n * ```ts\n * paletteBlocks: ['section', 'title', 'image', 'custom:qrcode', 'button']\n * ```\n *\n * `'hero'` is a shortcut, not a block type: it inserts a one-column section\n * in hero mode with starter content.\n *\n * Unknown entries — a typo, an unregistered custom block, or `countdown`\n * outside a Cloud plan — are logged with a warning and skipped. Filtering\n * the palette never affects rendering: existing content using a hidden\n * block type still renders correctly.\n */\n paletteBlocks?: string[];\n\n /**\n * Render each HTML block's raw content as a live preview in the editor\n * canvas instead of the static placeholder card. **Off by default.**\n *\n * ```ts\n * htmlBlockPreview: true // shorthand for { enabled: true }\n * htmlBlockPreview: { enabled: true }\n * ```\n *\n * The content is rendered verbatim inside a sandboxed `<iframe>`\n * (`sandbox=\"allow-same-origin\"`, **no** `allow-scripts`): scripts and\n * inline event handlers never execute and styles can't bleed into the rest\n * of the editor. This is a preview-only setting — the MJML/HTML export path\n * renders HTML blocks regardless of it.\n *\n * @default false\n */\n htmlBlockPreview?: HtmlBlockPreviewConfig;\n\n fonts?: FontsConfig;\n\n /**\n * Base URL for the social-icon PNGs the renderer references in exported MJML\n * (the `<mj-image>` src for each Social block icon). Forwarded to\n * `@templatical/renderer`’s `socialIconsBaseUrl`; when omitted the renderer\n * uses its version-pinned jsDelivr default. Set it to self-host the icons\n * from your own origin. Trailing slash optional.\n *\n * Applies to the local `toMjml()` / `toHtml()` (via `compileMjml`) path only.\n * A `render.toMjml` provider wins over the bundled renderer and never sees\n * this — pass the URL to your own `renderToMjml` there. The editing canvas is\n * unaffected either way (it draws icons as inline SVG).\n */\n socialIconsBaseUrl?: string;\n\n /**\n * Editor-wide color-picker palette. `presets` appear as a clickable grid in\n * every color picker popover (block toolbars, template settings, rich-text\n * color, custom-block color fields) — clicking one applies it, and the preset\n * matching the current value is marked selected.\n *\n * ```ts\n * colors: {\n * presets: ['#0b5cff', '#111827', '#6b7280', '#ffffff'],\n * allowCustom: false, // lock authors to the presets above\n * }\n * ```\n *\n * `allowCustom` defaults to `true`. Set it to `false` (together with\n * `presets`) to hide the wheel and hex input so authors can only pick from the\n * palette — useful when embedding the editor as a white-label / brand-kit\n * tool. `allowCustom: false` is ignored, with a warning, when no `presets` are\n * configured, since that would leave the picker with no way to set a color.\n */\n colors?: ColorsConfig;\n\n /**\n * Which template settings the Settings panel exposes — an allowlist over the\n * members of `TemplateSettings`.\n *\n * ```ts\n * // Layout and Appearance only: no Language card, no Preheader card.\n * templateSettings: { fields: ['width', 'backgroundColor', 'fontFamily'] }\n *\n * templateSettings: { fields: false } // no Settings tab at all\n * ```\n *\n * **Omitted by default**, in which case every setting is editable. The list\n * only narrows: a card renders while at least one of its settings survives,\n * and the tab itself stops rendering once none do. It never reorders —\n * settings sit in fixed cards, so unlike {@link paletteBlocks} there is no\n * order to express.\n *\n * Presentation only, and not a security boundary. Hiding a setting never\n * changes its value: whatever the loaded content carries keeps rendering and\n * keeps round-tripping through `getContent()`. Set the ones you hide from the\n * content you hand the editor — `init({ content })`, or the `templates`\n * provider's own `load`, which is the seam for \"this template's locale comes\n * from my application, not from the author\".\n *\n * Sibling restrictions live on their own keys: {@link paletteBlocks} for the\n * block palette, `fonts.builtIns` for the font picker, `colors.allowCustom`\n * for free-form colors, and `templates.nameField` for the header's name.\n */\n templateSettings?: TemplateSettingsConfig;\n\n /**\n * Storage backend for **saved blocks** — reusable groups of blocks a user\n * saves from the canvas and re-inserts into other templates.\n *\n * The editor owns the UI (a save action on each block, a searchable browser\n * with preview, insert-at-position, rename, delete); you own persistence.\n * Implement the four methods of `SavedBlocksProvider` against your own API,\n * or use the bundled browser-local provider for demos and prototypes:\n *\n * ```ts\n * import { init, createLocalStorageSavedBlocksProvider } from \"@templatical/editor\";\n *\n * init({ container, savedBlocks: createLocalStorageSavedBlocksProvider() });\n * ```\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * save action, no sidebar entry, and none of its UI code is downloaded.\n *\n * Not to be confused with `customBlocks`, which registers developer-defined\n * block *types* with their own templates and field schemas.\n */\n savedBlocks?: SavedBlocksProvider;\n\n /**\n * Sending backend for **test emails** — letting a user mail themselves the\n * template they're editing.\n *\n * The editor owns the trigger, the dialog, recipient validation and the\n * sending/success/error states; you own delivery. One method is enough:\n *\n * ```ts\n * init({\n * container,\n * testEmail: {\n * send: ({ recipient, content }) =>\n * fetch(\"/api/test-email\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ recipient, content }),\n * }).then((r) => {\n * if (!r.ok) throw new Error(\"Could not send the test email\");\n * }),\n * },\n * });\n * ```\n *\n * **Omitted by default.** With no provider the feature is entirely off — no\n * button, and none of its UI code is downloaded.\n *\n * `allowedRecipients` restricts the picker but is **not** a security boundary:\n * it lives in the user's browser. Validate the recipient on your server.\n */\n testEmail?: TestEmailProvider;\n\n /**\n * Storage backend for **comments** — the review conversation on a template.\n *\n * The editor owns the panel, the threading, the resolve flow, the per-block\n * indicators and the jump-to-block affordance; you own persistence. Five\n * methods, each mutation turn-off-able by passing `false`:\n *\n * ```ts\n * init({\n * container,\n * user: { id: \"u_7\", name: \"Ada\" },\n * comments: {\n * list: (templateId) =>\n * fetch(`/api/templates/${templateId}/comments`).then((r) => r.json()),\n * create: (templateId, input) =>\n * fetch(`/api/templates/${templateId}/comments`, {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(input),\n * }).then((r) => r.json()),\n * update: (templateId, commentId, patch) =>\n * fetch(`/api/templates/${templateId}/comments/${commentId}`, {\n * method: \"PATCH\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(patch),\n * }).then((r) => r.json()),\n * delete: async (templateId, commentId) => {\n * await fetch(`/api/templates/${templateId}/comments/${commentId}`, {\n * method: \"DELETE\",\n * });\n * },\n * setResolved: (templateId, commentId, resolved) =>\n * fetch(`/api/templates/${templateId}/comments/${commentId}/resolve`, {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({ resolved }),\n * }).then((r) => r.json()),\n * },\n * });\n * ```\n *\n * **Requires {@link user}** — with no identity the feature reports itself\n * unavailable and nothing renders, rather than writing anonymous comments.\n *\n * **Omitted by default**, and the panel also stays hidden until a template is\n * loaded, since a comment belongs to a template id.\n *\n * The same object also carries outward events — `onCreated`, `onUpdated`,\n * `onDeleted`, `onResolved`, `onUnresolved` — each called with the comment and\n * whether the change was made locally or arrived through `subscribe`. That's\n * the hook for a \"3 new comments\" badge outside the editor.\n *\n * Realtime is an optional `subscribe` on the provider, not a prerequisite:\n * without it comments work identically, you simply see a colleague's on the next\n * read rather than immediately.\n */\n comments?: CommentsProvider;\n\n /**\n * Real-time collaboration over your backend: ordered operations, presence and\n * block locks.\n *\n * ```ts\n * const editor = await init({\n * container,\n * templates,\n * collaboration: {\n * join: (templateId, session, handlers) => myRealtime.join(templateId, session, handlers),\n * submit: (templateId, batch) => post(`/api/templates/${templateId}/operations`, batch),\n * operationsAfter: (templateId, revision) =>\n * get(`/api/templates/${templateId}/operations?after=${revision}`),\n * acquireLock: (templateId, blockId) => post(`/api/templates/${templateId}/locks`, { blockId }),\n * renewLock: (templateId, blockId) => put(`/api/templates/${templateId}/locks/${blockId}`),\n * releaseLock: (templateId, blockId) => del(`/api/templates/${templateId}/locks/${blockId}`),\n * },\n * });\n * await editor.load(\"tpl_123\");\n * ```\n *\n * **Needs `templates`**: a session joins a loaded template, and `load` must\n * return the template's `revision`. With a collaboration provider, every edit\n * reaches your backend as an operation through `submit`, so `templates.save`\n * receives only renames, and undo and redo send inverse operations that your\n * backend can refuse. Selecting a block takes its lock; the three lock methods\n * are optional together. Apply operations on your server with\n * `applyOperations` from `@templatical/types`.\n *\n * **Omitted by default.** See the Collaboration page under Connect your backend.\n */\n collaboration?: CollaborationProvider;\n\n /**\n * A batch of edits from another session landed on the canvas: who made it\n * (`actor`) and the operations. Not called for this editor's own edits, and\n * not for a re-sync that reloads the whole template.\n */\n onRemoteChange?: (change: CollaborationRemoteChange) => void;\n\n /**\n * Your AI backend: a chat that edits the template with Undo, rewrite in the\n * paragraph toolbar, static localized chat starters and\n * chat attachments. One member per feature; `false` leaves it out and the\n * editor hides its entry point:\n *\n * ```ts\n * import { createHttpAiProvider } from \"@templatical/ai-kit/client\";\n *\n * const editor = await init({\n * container,\n * templates,\n * ai: createHttpAiProvider({ baseUrl: \"/api/ai\" }),\n * });\n * await editor.load(\"tpl_123\");\n * ```\n *\n * **Needs a loaded template**: every AI request names it, so the entry\n * points show once `create()` or `load()` has resolved. With\n * `collaboration`, the AI's edits travel as this user's batches marked\n * `origin: \"ai\"`; without it they apply here. Either way a turn is one\n * Cmd/Ctrl+Z. Failures reach `onError`.\n *\n * **Omitted by default.** See AI under Connect your backend.\n */\n ai?: AiProvider;\n\n /**\n * Who is using the editor — needed by any feature that attributes work to a\n * person: {@link comments}, and the collaborator bar, which leaves this user's\n * own sessions out. It is a top-level key rather than part of either provider.\n *\n * ```ts\n * init({ container, user: { id: \"u_7\", name: \"Ada Lovelace\" } });\n * ```\n *\n * Not a security boundary — it identifies the user to the editor's UI, in the\n * user's own browser. Attribute writes server-side from the session your backend\n * already trusts.\n */\n user?: EditorUser;\n\n blockDefaults?: BlockDefaults;\n templateDefaults?: TemplateDefaults;\n\n theme?: ThemeOverrides;\n uiTheme?: UiTheme;\n locale?: string;\n\n /**\n * Show the \"Powered by Templatical\" footer. Defaults to `true`.\n * Set to `false` to hide the footer (no attribution required by the license).\n */\n branding?: boolean;\n\n /**\n * Show a \"use a larger screen\" notice instead of the editor chrome on\n * viewports narrower than ~768px. Defaults to `true`.\n *\n * The drag-and-drop editor is a desktop-class tool — the block palette,\n * canvas, and properties panel can't lay out usably on a phone, and touch\n * dragging is impractical. Rather than render a broken, cramped layout, the\n * editor shows a clear message below the breakpoint.\n *\n * Set to `false` if you handle small screens yourself (e.g. you embed the\n * editor in a deliberately narrow desktop pane). The check is viewport-based,\n * so it targets actual small devices, not narrow containers on a wide screen.\n *\n * @default true\n */\n smallScreenNotice?: boolean;\n\n /**\n * Template linter (`@templatical/quality`) configuration. Runs every\n * linter exported by the package (accessibility + structure).\n *\n * - When unset, the linter loads on demand once the user opens the panel.\n * - When `disabled: true`, the optional peer is never imported (saves the\n * chunk download) and the sidebar tab + inline badges are suppressed.\n * - `rules`/`thresholds` follow the shape exported by `@templatical/quality`.\n */\n lint?: import(\"@templatical/quality\").LintOptions;\n}\n\n/** Function type for media browser requests, used by both OSS and Cloud editors. */\nexport type OnRequestMedia = (\n context?: MediaRequestContext,\n) => Promise<MediaResult | null>;\n\ninterface TemplaticalEditorBase {\n getContent(): TemplateContent;\n getLocale(): string;\n setLocale(locale: string): void;\n setContent(content: TemplateContent): void;\n /**\n * Insert a block where a click on a palette item would put it: below the\n * selected block, in the same column when the selection is inside a section\n * (a section lands after that section instead), or at the end when nothing\n * usable is selected. The new block is selected and scrolled into view, so\n * repeated calls stack in order.\n *\n * The block is inserted as given: the editor defaults a palette block is\n * built with (`blockDefaults`, localized placeholder text, RTL alignment)\n * aren't applied, so insert ready-made content rather than fresh factory\n * blocks.\n *\n * Inserts a copy with fresh ids, so the same block can be inserted twice.\n * Bare merge tags are converted the same way `setContent` converts them.\n * Returns the inserted copy's id, or `null` once the instance is unmounted\n * or replaced by a later `init()` on its container, in preview mode (with a\n * warning), or when the block could not be placed. A slot or wrapper block\n * throws, as it does in `setContent`.\n */\n insertBlock(block: Block): string | null;\n setTheme(theme: UiTheme): void;\n /**\n * Replace the configured merge tags after `init()`.\n *\n * Everything that renders a tag reads the same list, so a replacement\n * repaints the canvas, the sidebar fields and the built-in picker together.\n * Use it when tags are minted or renamed while the editor is open — mutating\n * the array you passed to `init()` is not a supported substitute and will\n * not repaint anything already on screen.\n *\n * Type-ahead autocomplete is the one exception: whether it is active is\n * decided when a block opens for editing, so going from no tags to some\n * enables it for the next block opened, not one already being edited.\n */\n setMergeTags(tags: MergeTag[]): void;\n /**\n * Tear this editor down. It unmounts only this instance: once a later\n * `init()` on the same container has replaced it, or kept it from mounting,\n * calling `unmount()` here does nothing, so a stale handle never removes the\n * editor that replaced it. Calling it again after the teardown is also a\n * no-op.\n */\n unmount(): void;\n /**\n * Render the current template to MJML.\n *\n * Resolves `render.toMjml` first when a `render` provider supplies it, then the\n * bundled `@templatical/renderer` (which resolves custom blocks through the\n * editor's own registry). Rejects with a clear error when neither is available —\n * i.e. no provider method *and* the optional `@templatical/renderer` peer isn't\n * installed.\n */\n toMjml(options?: { locale?: string }): Promise<string>;\n /**\n * Render the current template to sending-ready HTML.\n *\n * Resolves `render.toHtml` first, then `toMjml()`'s output through\n * `render.compileMjml`. **Requires one of the two** — the SDK bundles no MJML\n * compiler, so with no `render` provider this always rejects, and the error says\n * which method to add.\n */\n toHtml(options?: { locale?: string }): Promise<string>;\n}\n\nexport interface TemplaticalEditor extends TemplaticalEditorBase {\n /**\n * Persist the current content as a new template through the configured\n * `templates` provider, and make the result the editor's template.\n *\n * `input.content`, when given, replaces the editor's content first. Always\n * present on the type; rejects with an explanatory error when no provider is\n * configured or when the provider set `create: false` — the same convention as\n * {@link toMjml}.\n */\n create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template>;\n /** Load a template by id and make it the editor's content. */\n load(templateId: string): Promise<Template>;\n /**\n * Persist the loaded template — name and content, as one patch. Rejects when\n * no provider is configured, when the provider set `save: false`, or when no\n * template has been created or loaded yet.\n */\n save(): Promise<Template>;\n /**\n * Whether there are edits the editor knows aren't persisted. Cleared by a\n * successful `save()` / `create()` / `load()`.\n *\n * Read it in a router guard; `onDirtyChange` is the push-based counterpart.\n */\n isDirty(): boolean;\n /**\n * Render a single custom block to its HTML representation, using the\n * registered custom block definition's template and the block's current\n * field values. `toMjml()` wires this into the renderer automatically.\n * Headless callers with definitions pass them as `customBlocks` to\n * `@templatical/renderer`.\n */\n renderCustomBlock(block: CustomBlock): Promise<string>;\n /**\n * Look up the definition-level `stylesheet` for a registered custom block\n * type. Returns the raw CSS string, or `undefined` when the type is unknown\n * or the definition has no stylesheet. `toMjml()` wires this into the\n * renderer automatically. Headless callers pass their definitions as\n * `customBlocks` to `@templatical/renderer`.\n */\n getCustomBlockStylesheet(customType: string): string | undefined;\n}\n\n/**\n * `initCloud()` returns the **same** editor `init()` does.\n *\n * That is the point rather than a tidy-up: Cloud is a set of provider\n * implementations behind the same interfaces a consumer would implement, so if\n * the two entry points still returned different shapes, the claim would be\n * false. It also means moving between them is a config change and never a\n * rewrite of the calling code.\n *\n * Three cloud-only members went with the convergence: `create()` takes\n * `init()`'s `{ name?, content? }` input object now, rather than a bare\n * `TemplateContent`; `setThemeOverrides` is gone (`config.theme` is applied\n * at init on both entry points, and the entitlement that gated changing it\n * later is gone); and `sendTestEmail` is gone (the shared dialog is the\n * supported path).\n */\nexport type TemplaticalCloudEditor = TemplaticalEditor;\n\n// ---------------------------------------------------------------------------\n// Shadow root helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Module-cached `CSSStyleSheet` built once from the inline editor CSS string.\n * `adoptedStyleSheets` accepts the same sheet object across multiple shadow\n * roots — sharing one sheet costs zero per-instance memory, regardless of\n * how many editors mount.\n */\nlet cachedEditorStyleSheet: CSSStyleSheet | null = null;\n\nfunction getEditorStyleSheet(): CSSStyleSheet {\n if (cachedEditorStyleSheet === null) {\n const sheet = new CSSStyleSheet();\n // The one `@import` in the editor's CSS loads Geist. The document-level\n // stylesheet (`style.css`, or `editor.css` from the CDN) imports it too,\n // and font faces loaded there reach the shadow tree, so stripping it\n // here loses nothing and keeps `replaceSync` from warning.\n sheet.replaceSync(stripStylesheetImports(editorStylesInline));\n cachedEditorStyleSheet = sheet;\n }\n return cachedEditorStyleSheet;\n}\n\ninterface MountTarget {\n target: Element;\n shadowRoot: ShadowRoot | null;\n /**\n * Disposer for any dev-mode side effects attached to the shadow root\n * (currently: the document.head `<style>` mirror's MutationObserver).\n * Always safe to call — no-op when no side effects were registered.\n */\n cleanup: () => void;\n}\n\n/**\n * Whether the dev mirror copies one `document.head` style. Vite tags each\n * style it injects with `data-vite-dev-id`, the source path, so with\n * `ownedStyleRoots` set only the editor's styles and the third-party CSS it\n * imports pass. An untagged style was injected at runtime (TipTap's\n * `<style data-tiptap-style>`) and stays mirrored: in production it never\n * reaches the shadow root, and that gap is #869, which waits on an upstream\n * TipTap fix.\n */\nfunction isMirroredStyle(el: HTMLStyleElement): boolean {\n if (!ownedStyleRoots) return true;\n const devId = el.getAttribute(\"data-vite-dev-id\");\n if (devId === null) return true;\n const path = devId.replace(/\\\\/g, \"/\");\n return (\n ownedStyleRoots.some((root) => path.startsWith(root)) ||\n path.includes(\"/node_modules/\")\n );\n}\n\n/**\n * Dev-only: mirror every `<style>` tag in `document.head` into the\n * shadow root's `adoptedStyleSheets`, and observe `document.head` so\n * Vite's HMR-injected style updates flow through to the shadow root\n * automatically.\n *\n * Background: Vite dev injects each `.vue` `<style scoped>` block as a\n * separate `<style>` element in `document.head` via HMR. Those don't\n * cross the shadow boundary, so a shadow-mounted editor in dev would\n * render with only the bundled `styles/index.css` rules — every SFC\n * scoped style (block selection outlines, sidebar layout, etc.) missing.\n *\n * In production builds, `inline-style-css-plugin.ts` captures every\n * emitted CSS asset at `generateBundle` time and inlines the full\n * library CSS as a single string adopted by the shadow root. This\n * dev-only mirror does the same thing at runtime by observing whatever\n * Vite ends up injecting.\n *\n * The dead-code-elimination on `import.meta.env.DEV` ensures the\n * observer + filter logic is stripped from production bundles entirely.\n *\n * Caveats:\n * - A host app that compiles the editor from source has its own styles\n * in `document.head` too. It passes `ownedRoots` to the CSS plugin,\n * and then only the editor's styles are mirrored (`isMirroredStyle`).\n * Without that option, the host's page-level styles are adopted as\n * well. That's harmless when consumers install the editor from npm\n * dist (the dev branch is dead-coded out).\n * - A constructed sheet cannot hold `@import`: `replaceSync` drops each\n * such rule and logs a warning, so they are stripped before the call.\n */\nfunction attachDevStyleMirror(shadowRoot: ShadowRoot): () => void {\n if (!import.meta.env?.DEV) return () => {};\n\n function buildSheets(): CSSStyleSheet[] {\n const sheets: CSSStyleSheet[] = [];\n // shadow-ok: dev-only HMR style mirror (production path is plugin-driven via adoptedStyleSheets)\n document.head.querySelectorAll(\"style\").forEach((el) => {\n if (!isMirroredStyle(el)) return;\n const text = el.textContent;\n if (!text) return;\n try {\n const sheet = new CSSStyleSheet();\n // These are document styles, so the document has loaded their\n // imports already.\n sheet.replaceSync(stripStylesheetImports(text));\n sheets.push(sheet);\n } catch {\n // Skip a style the CSSOM refuses to parse.\n }\n });\n return sheets;\n }\n\n function refresh(): void {\n // Keep the editor's primary (bundled) sheet first so its declarations\n // are the cascade fallback; dev sheets adopted after may override them\n // — same precedence model as production where everything ends up in\n // one stylesheet anyway.\n shadowRoot.adoptedStyleSheets = [getEditorStyleSheet(), ...buildSheets()];\n }\n\n refresh();\n\n const observer = new MutationObserver(() => refresh());\n // childList catches new/removed <style> tags; characterData + subtree\n // catches Vite HMR mutating an existing style's textContent in place.\n // shadow-ok: dev-only HMR style mirror observer\n observer.observe(document.head, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n\n return () => observer.disconnect();\n}\n\n/**\n * Resolve where Vue should mount: directly on the consumer's container\n * (light-DOM mode) or on a fresh `<div>` inside a newly-attached open\n * shadow root (shadow mode). In shadow mode, also attaches the editor's\n * cached `CSSStyleSheet` to the root so chrome renders with the right\n * styles inside the boundary, plus a dev-only mirror that observes\n * `document.head` (see `attachDevStyleMirror`).\n *\n * Idempotent: a second call on the same container reuses any existing\n * shadow root, clearing its contents so a prior mount's stale DOM doesn't\n * accumulate.\n */\nfunction resolveMountTarget(\n container: Element,\n shadowDom: boolean | undefined,\n): MountTarget {\n if (!shadowDom) {\n return { target: container, shadowRoot: null, cleanup: () => {} };\n }\n\n const shadowRoot =\n container.shadowRoot ?? container.attachShadow({ mode: \"open\" });\n\n // Adopt the editor stylesheet. Idempotent — repeated assignment of the\n // same sheet is fine. Dev mirror (below) will overwrite this with the\n // primary sheet + mirrored sheets, then keep them in sync.\n shadowRoot.adoptedStyleSheets = [getEditorStyleSheet()];\n\n // Clear stale content from a prior mount (re-init on same container).\n while (shadowRoot.firstChild) {\n shadowRoot.removeChild(shadowRoot.firstChild);\n }\n\n const host = document.createElement(\"div\");\n host.className = \"tpl-editor-host\";\n // Match the container's layout. Without an explicit size the host is a\n // default block element (height: auto) and the editor's `tpl:h-full`\n // template root collapses to content height because the height-100% chain\n // breaks at the shadow boundary. `width: 100%` is redundant for block\n // elements but harmless and explicit.\n host.style.cssText = \"display:block;height:100%;width:100%;\";\n shadowRoot.appendChild(host);\n\n const cleanup = attachDevStyleMirror(shadowRoot);\n\n return { target: host, shadowRoot, cleanup };\n}\n\n// ---------------------------------------------------------------------------\n// OSS init — sync\n// ---------------------------------------------------------------------------\n\ninterface OssEntry {\n app: App;\n editorRef: Ref<InstanceType<typeof Editor> | null>;\n /** Tear down dev-mode side effects (style mirror observer, etc.). */\n cleanup: () => void;\n}\n\n// Per-container registry so two `init()` calls with different containers\n// produce independent editor instances (multi-instance support). Re-init\n// on the same container still auto-unmounts the previous instance.\nconst ossEntries = new Map<Element, OssEntry>();\n\n// \"Last init'd\" container preserves the legacy single-instance behavior\n// of the top-level `unmount()` export — the playground (and other one-\n// editor consumers) calls bare `unmount()` and expects it to tear down\n// whatever was most recently mounted.\nlet lastOssContainer: Element | null = null;\n\n// Which call may take a container over. Every `init()` / `initCloud()` whose\n// `layout` and `content` pass `prepareLayoutAndContent` claims its container\n// before its first await, and mounts only if its claim is still the latest once\n// its awaits settle. Calls on one container settle in whatever\n// order their awaits finish (under React StrictMode's dev double effect, the\n// cancelled first call can settle after the second one mounted), so the order\n// the calls were made in decides which editor the container keeps. A WeakMap,\n// so a container that leaves the page takes its claim with it.\nlet lastClaimToken = 0;\nconst containerClaims = new WeakMap<Element, number>();\n\ninterface ContainerClaim {\n container: Element;\n token: number;\n}\n\n/**\n * Resolve the configured container and claim it for this call. Runs before\n * the first await of `init()` and `initCloud()`, so claims follow call order.\n */\nfunction claimContainer(target: string | HTMLElement): ContainerClaim {\n const container =\n typeof target === \"string\" ? document.querySelector(target) : target;\n\n if (!container) {\n throw new Error(`[Templatical] Container element not found: ${target}`);\n }\n\n const token = ++lastClaimToken;\n containerClaims.set(container, token);\n return { container, token };\n}\n\n// Tears down whatever app the container holds, or with `onlyApp` just that app:\n// an instance unmounts only itself. A StrictMode double-mount can call a\n// superseded instance's `unmount()` after its replacement mounted on the same\n// container, and a container-scoped teardown there removes the replacement and\n// leaves a blank editor. `mountEditor`'s auto-unmount and the top-level\n// `unmount()` export pass no `onlyApp`: they mean \"whatever this container\n// holds now\".\nfunction unmountOssContainer(container: Element, onlyApp?: App): void {\n const entry = ossEntries.get(container);\n if (!entry) return;\n if (onlyApp && entry.app !== onlyApp) return;\n entry.cleanup();\n entry.app.unmount();\n ossEntries.delete(container);\n if (lastOssContainer === container) {\n lastOssContainer = null;\n }\n}\n\n/**\n * Normalize the merge tags in `layout` and `content`, then refuse an illegal\n * tree. `init()` and `initCloud()` run this when they are called, before they\n * claim the container. A call that throws here rejects at once: it supersedes\n * no earlier call, and the container and the editor it shows stay exactly as\n * they were.\n *\n * Merge tags reach us in one of two shapes, and only one of them behaves like\n * a tag. Anything typed or pasted is already a `<span data-merge-tag>`, since\n * `MergeTagNode`'s input rules convert it on the spot; content that arrived\n * any other way — a consumer's stored JSON, an `@templatical/import-*`\n * conversion — still holds bare `{{tokens}}` that render as plain text.\n * Normalizing here, before the seed reaches `Editor.vue`, means core is\n * handed content that is already correct and never observes a mutation, so\n * nothing is marked dirty and no autosave tick fires for a load.\n *\n * This is one of four places content enters. The other three:\n * `instance.setContent` and `instance.create` below, and the `templates`\n * provider's `load`, wrapped in `Editor.vue` where it reaches core.\n * Overlay chrome is not seed content: merge tags in the shell, then refuse\n * an illegal tree.\n */\nfunction prepareLayoutAndContent(\n config: Pick<TemplaticalEditorConfig, \"layout\" | \"content\" | \"mergeTags\">,\n): void {\n if (config.layout) {\n config.layout = normalizeContentForConfig(config.layout, config.mergeTags);\n validateLayout(config.layout);\n }\n if (config.content) {\n config.content = normalizeContentForConfig(\n config.content,\n config.mergeTags,\n );\n assertNoSlotInContent(config.content);\n assertNoWrapperInContent(config.content);\n }\n}\n\nexport async function init(\n config: TemplaticalEditorConfig,\n): Promise<TemplaticalEditor> {\n // A copy, as `initCloud()` makes: the editor never writes to the caller's\n // config, which may be frozen. A key reassigned on that object after this call\n // does not reach the editor.\n const prepared = { ...config };\n if (\n prepared.translation !== undefined &&\n (prepared.translation === null ||\n typeof prepared.translation !== \"object\" ||\n typeof prepared.translation.translate !== \"function\")\n )\n throw new SdkError(\n \"translation must be an object with a translate function.\",\n );\n for (const locale of prepared.localization?.locales ?? []) {\n if (!isLocaleTag(locale))\n throw new SdkError(`Invalid localization locale \"${locale}\".`);\n }\n const terms = prepared.localization?.doNotTranslate;\n if (\n terms !== undefined &&\n (!Array.isArray(terms) ||\n terms.length > 500 ||\n terms.some(\n (term) =>\n typeof term !== \"string\" ||\n term.trim().length < 1 ||\n term.trim().length > 100,\n ))\n )\n throw new SdkError(\n \"localization.doNotTranslate must be an array of at most 500 terms, each 1–100 characters.\",\n );\n prepareLayoutAndContent(prepared);\n return mountEditor(prepared, claimContainer(prepared.container));\n}\n\n/**\n * The one mount path. `init()` calls it with no runtime; `initCloud()` calls it\n * with Cloud's, having already resolved auth, the plan and every adapter. Both\n * prepare `layout` and `content` and claim the container when they are called,\n * before this runs.\n */\nasync function mountEditor(\n config: TemplaticalEditorConfig,\n { container, token }: ContainerClaim,\n cloud?: CloudRuntime,\n): Promise<TemplaticalEditor> {\n // An unusable `locale` fell back to English in silence, so a typo — \"gr\" for\n // Greek (the country code, not the language code \"el\"), or \"english\" — was\n // indistinguishable from the option being ignored. Regions and stray\n // whitespace are NOT typos: they resolve to a base language by design.\n // `paletteBlocks` and `colors` both warn on input they cannot use; this makes\n // the third config option behave the same. Deliberately NOT extended to the\n // cloud chunk, which ships fewer locales on purpose (`guide/i18n.md` tells\n // contributors not to translate it) — warning there would fire for every\n // fr/es/nl/ca consumer, who did nothing wrong.\n if (config.locale !== undefined && !isLocaleSupported(config.locale)) {\n logger.warn(\n `config.locale: \"${config.locale}\" has no translations — falling back ` +\n `to English. Supported: ${getSupportedLocales().sort().join(\", \")}.`,\n );\n }\n\n // Load translations before mounting so child components can use useI18n synchronously\n const translations = await loadTranslations(config.locale ?? \"en\");\n\n // Create fonts manager to pass to Editor\n const fontsManager = useFonts(config.fonts);\n\n // A later `init()` or `initCloud()` on this container was made while this\n // one awaited, so the container is that call's. Mounting here would replace\n // its editor whenever this call settles last: under React StrictMode, with a\n // cancelled effect's editor, which that effect then unmounts, leaving the\n // container empty. So this call leaves the container alone and resolves\n // never mounted, like an instance a later `init()` replaced: its\n // `unmount()` is a no-op.\n if (containerClaims.get(container) !== token) {\n return createEditorInstance({\n config,\n editorRef: ref(null),\n fontsManager,\n unmount: () => {},\n }).instance;\n }\n\n // Auto-unmount any prior instance on the SAME container *after* awaits\n // — checking before the await would let two concurrent init() calls\n // both pass the guard and orphan the first-mounted app on this\n // container.\n unmountOssContainer(container);\n\n const mount = resolveMountTarget(container, config.shadowDom ?? true);\n const editorRef: Ref<InstanceType<typeof Editor> | null> = ref(null);\n\n const app = createApp({\n setup() {\n return () =>\n h(Editor, {\n config,\n translations,\n fontsManager,\n shadowRoot: mount.shadowRoot ?? undefined,\n cloud,\n // The test-email dialog's `includeMjml` payload comes off the same\n // ladder as `editor.toMjml()`, so a consumer's `render.toMjml` is what\n // a test carries when they configured one. `render` is declared below\n // and read at send time, never during this render.\n renderMjml: () => render.toMjml(),\n renderHtml: () => render.toHtml(),\n canRenderHtml: () => render.canRenderHtml(),\n usesLocalRenderer: () => render.usesLocalRenderer(),\n ref: editorRef,\n });\n },\n });\n\n app.mount(mount.target);\n\n ossEntries.set(container, { app, editorRef, cleanup: mount.cleanup });\n lastOssContainer = container;\n\n const { instance, render } = createEditorInstance({\n config,\n editorRef,\n fontsManager,\n // This instance's own app: once a later `init()` replaced it on the\n // container, this call must leave the replacement mounted.\n unmount: () => unmountOssContainer(container, app),\n });\n\n return instance;\n}\n\n/**\n * The object `init()` and `initCloud()` resolve with. It reaches the editor\n * through `editorRef`, which is `null` before the editor mounts and after it\n * unmounts, and for good on a call a later one superseded; every method\n * answers either way.\n */\nfunction createEditorInstance({\n config,\n editorRef,\n fontsManager,\n unmount,\n}: {\n config: TemplaticalEditorConfig;\n editorRef: Ref<InstanceType<typeof Editor> | null>;\n fontsManager: UseFontsReturn;\n unmount: () => void;\n}): { instance: TemplaticalEditor; render: RenderMethods } {\n const instance: TemplaticalEditor = {\n getContent() {\n // safeClone (not a naked JSON.stringify): a drag inside a section can\n // leave a Sortable expando cycle reachable from live content, which a\n // plain stringify chokes on (#203). The clone drops the back-ref.\n if (editorRef.value) {\n return safeClone(editorRef.value.getContent());\n }\n // Same defaults the mounted editor would have used, `locale` included:\n // a caller reading content before mount must not get a different\n // template than the one about to render.\n return safeClone(\n config.content ??\n createDefaultTemplateContent(\n config.fonts?.defaultFont,\n resolveTemplateDefaults(config),\n ),\n );\n },\n getLocale() {\n return (\n editorRef.value?.getLocale() ?? defaultLocaleOf(instance.getContent())\n );\n },\n setLocale(locale: string) {\n const content = instance.getContent();\n if (\n locale !== defaultLocaleOf(content) &&\n (!config.localization || !content.settings.locales?.includes(locale))\n ) {\n throw new SdkError(\n `This template has no \"${locale}\" version.`,\n undefined,\n \"unknown_locale\",\n );\n }\n editorRef.value?.setLocale(locale);\n },\n setContent(content: TemplateContent) {\n // Normalized once and used for both writes: `getContent()` falls back to\n // `config.content` before mount, so a raw write-back here would hand back\n // different content than the mounted editor holds.\n const normalized = normalizeContentForConfig(content, config.mergeTags);\n if (editorRef.value) {\n editorRef.value.setContent(normalized);\n }\n config.content = normalized;\n },\n insertBlock(block: Block) {\n // Before the mount and preview checks, so the mistake surfaces on every\n // path, not only once core's `addBlock` is reached. The asserts read\n // only `blocks`.\n const candidate = { blocks: [block] } as TemplateContent;\n assertNoSlotInContent(candidate);\n assertNoWrapperInContent(candidate);\n if (!editorRef.value) return null;\n // Consumer content arriving in, so it is normalized like `setContent`.\n return editorRef.value.insertBlock(\n normalizeBlockForConfig(block, config.mergeTags),\n );\n },\n setTheme(theme: UiTheme) {\n if (editorRef.value) {\n editorRef.value.setTheme(theme);\n }\n },\n setMergeTags(tags: MergeTag[]) {\n if (editorRef.value) {\n editorRef.value.setMergeTags(tags);\n return;\n }\n // Called before mount: fold it into the config the editor is about to\n // read, so the call is never silently lost.\n config.mergeTags = { ...config.mergeTags, tags };\n },\n unmount,\n create(input?: { name?: string; content?: TemplateContent }) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n // Supplied content becomes editor state before the provider is called,\n // so it is consumer content arriving in and gets the same treatment as\n // `setContent`. A contentless create is forwarded as-is — core then\n // persists the state it already holds, which is normalized already.\n return editorRef.value.create(\n input?.content\n ? {\n ...input,\n content: normalizeContentForConfig(\n input.content,\n config.mergeTags,\n ),\n }\n : input,\n );\n },\n load(templateId: string) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.load(templateId);\n },\n save() {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.save();\n },\n isDirty() {\n // Pre-mount there is nothing the editor could have changed, so the honest\n // answer is \"no unsaved edits\" rather than a throw.\n return editorRef.value?.isDirty() ?? false;\n },\n renderCustomBlock(block: CustomBlock) {\n if (!editorRef.value) {\n return Promise.reject(new Error(\"[Templatical] Editor not ready\"));\n }\n return editorRef.value.renderCustomBlock(block);\n },\n getCustomBlockStylesheet(customType: string) {\n // Pre-mount: registry is empty, so no definition has a stylesheet to\n // resolve. Returning undefined here matches the \"unknown type\" branch\n // and keeps the renderer's `getCustomBlockStylesheet` resolver total.\n if (!editorRef.value) {\n return undefined;\n }\n return editorRef.value.getCustomBlockStylesheet(customType);\n },\n toMjml: (options) => render.toMjml(options),\n toHtml: (options) => render.toHtml(options),\n };\n\n // Both methods resolve per call, so a provider added later in the config — or a\n // provider that implements only one method — behaves the same as one that\n // implements all three. `instance` is captured lazily, which is what lets the\n // payload builder read the editor's live content.\n const render = createRenderMethods({\n provider: config.render,\n buildPayload: (options) =>\n buildRenderPayload(\n {\n getContent: () => instance.getContent(),\n renderCustomBlock: (block: CustomBlock) =>\n instance.renderCustomBlock(block),\n getCustomBlockStylesheet: (customType: string) =>\n instance.getCustomBlockStylesheet(customType),\n getFonts: () => resolveRenderFonts(fontsManager),\n getLayout: () => config.layout,\n },\n options,\n ),\n renderLocalMjml: (options) =>\n toMjmlForInstance(\n {\n getContent: () => instance.getContent(),\n renderCustomBlock: (block: CustomBlock) =>\n instance.renderCustomBlock(block),\n getCustomBlockStylesheet: (customType: string) =>\n instance.getCustomBlockStylesheet(customType),\n getFonts: () => resolveRenderFonts(fontsManager),\n socialIconsBaseUrl: config.socialIconsBaseUrl,\n getLayout: () => config.layout,\n },\n ...(options ? ([options] as const) : []),\n ),\n });\n\n return { instance, render };\n}\n\n// ---------------------------------------------------------------------------\n// Cloud init — a thin adapter-wiring wrapper over init()\n// ---------------------------------------------------------------------------\n\n/**\n * Mount the editor against Templatical Cloud.\n *\n * **This is `init()` with Cloud's adapters filled in**, and deliberately nothing\n * more. Templates, rendering and version history are providers, so Cloud's entry\n * point is adapter wiring rather than a second editor:\n *\n * 1. Build the auth manager and complete the handshake.\n * 2. Health-check the API, and fetch the plan config.\n * 3. Build Cloud's adapters over that auth manager.\n * 4. Delegate to `init()`.\n *\n * A failure in steps 1–2 **rejects**, rather than mounting an editor that shows\n * an error overlay. That is the one place the wrapper is genuinely not `init()`:\n * `init()` cannot fail after it mounts, and OSS should not grow the ability. A\n * session that dies *later* — an auth refresh that cannot renew the token — does\n * still surface as an overlay, because by then there is an editor to cover.\n *\n * `templates`, `comments` and `versionHistory` are all keyed to a template\n * id Cloud issued, which also anchors the server-side export — a store Cloud\n * never issued ids for would degrade all of them silently. Cloud therefore\n * keeps each key's storage, but each key is still accepted, for its\n * configuration and events:\n * `templates.load`/`create`/`save`,\n * `comments.list`/`create`/`update`/`delete`/`setResolved`, and\n * `versionHistory.list`/`get`/`create`/`restore` are ignored with a warning\n * naming them, while `templates`' `autoSave`, `unsavedChangesGuard`,\n * `nameField`, `onSaved`, `onCreated`, `onLoaded`, `comments`' `onCreated`,\n * `onUpdated`, `onDeleted`, `onResolved`, `onUnresolved`, and\n * `versionHistory`'s `onCreated`, `onRestored` are all honoured.\n *\n * `render` is not a key here at all, unlike `init()` — Cloud renders\n * server-side for test email, sends and exports, so a supplied renderer\n * would change only what you preview and export, never what Cloud delivers.\n * `resolvePreview` is the same key with the same type on both entry points,\n * so upgrading an OSS integration is a deletion. `savedBlocks`, `testEmail`\n * and `media` are the same key on both entry points too, but Cloud widens\n * each type to also accept an events-only shape — `boolean |\n * SavedBlocksOptions | SavedBlocksProvider`, `Pick<TestEmailOptions,\n * \"onSent\" | \"defaultRecipient\"> | TestEmailProvider`, and\n * `false | MediaOptions | MediaProvider` — so upgrading is still a\n * deletion: drop the key to adopt Cloud's store or sender, or leave it\n * exactly as it is to keep your own.\n *\n * `user` is not a key either: Cloud signs comment writes against the auth token's\n * `user` claim, so it fills `init({ user })` from there rather than letting a\n * browser name someone else.\n */\nexport async function initCloud(\n config: TemplaticalCloudEditorConfig,\n): Promise<TemplaticalCloudEditor> {\n // Checked before the claim and the bootstrap, so an illegal `layout` or\n // `content` rejects without touching the container or making any request.\n // The three keys are copied first, so the caller's config is never written.\n const prepared = {\n layout: config.layout,\n content: config.content,\n mergeTags: config.mergeTags,\n };\n prepareLayoutAndContent(prepared);\n\n // Claimed before the bootstrap's requests go out, so a later call on this\n // container wins even when this call's bootstrap answers last, and a\n // selector that matches nothing rejects without making any request.\n const claim = claimContainer(config.container);\n\n // Dynamic imports — every cloud module is tree-shaken from the OSS bundle, and\n // an OSS consumer who never calls this downloads none of it.\n const [{ bootstrapCloud }, cloudTranslations] = await Promise.all([\n import(\"./cloud/createCloudRuntime\"),\n loadCloudTranslations(config.locale ?? \"en\"),\n ]);\n\n const { runtime, providers, user } = await bootstrapCloud({\n config,\n cloudTranslations,\n });\n\n return mountEditor(\n {\n container: config.container,\n content: prepared.content,\n layout: prepared.layout,\n sectionWrapper: config.sectionWrapper,\n shadowDom: config.shadowDom,\n locale: config.locale,\n uiTheme: config.uiTheme,\n theme: config.theme,\n branding: config.branding,\n smallScreenNotice: config.smallScreenNotice,\n blockDefaults: config.blockDefaults,\n templateDefaults: config.templateDefaults,\n customBlocks: config.customBlocks,\n paletteBlocks: config.paletteBlocks,\n htmlBlockPreview: config.htmlBlockPreview,\n colors: config.colors,\n templateSettings: config.templateSettings,\n fonts: config.fonts,\n mergeTags: config.mergeTags,\n logicTags: config.logicTags,\n displayConditions: config.displayConditions,\n resolvePreview: config.resolvePreview,\n lint: config.lint,\n onChange: config.onChange,\n onError: config.onError,\n onDirtyChange: config.onDirtyChange,\n // Cloud's adapters, behind the very keys a consumer would fill in\n // themselves. `savedBlocks` is absent when the consumer passed `false`.\n // `templates` spreads Cloud's own provider first so its load/create/save\n // always win over a consumer's config. Autosave defaults on here, unlike\n // `init()`, because Cloud always has a store to save to; the debounce\n // falls back to the same shared constant `useAutoSave` already defaults\n // to, made explicit so a consumer's own `changeDebounce` reaches it.\n templates: {\n ...providers.templates,\n autoSave: config.templates?.autoSave ?? true,\n unsavedChangesGuard: config.templates?.unsavedChangesGuard,\n nameField: config.templates?.nameField,\n },\n changeDebounce: config.changeDebounce ?? DEFAULT_AUTO_SAVE_DEBOUNCE_MS,\n render: providers.render,\n versionHistory: providers.versionHistory,\n savedBlocks: providers.savedBlocks,\n testEmail: providers.testEmail,\n comments: providers.comments,\n media: providers.media,\n onRequestMedia: config.onRequestMedia,\n // From the JWT. Undefined when the project's token carries no `user` claim,\n // which leaves comments unavailable rather than anonymous.\n user,\n },\n claim,\n runtime,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Unmount helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Unmount the most-recently-created OSS editor. Single-instance legacy\n * API — callers managing multiple editors should use `instance.unmount()`\n * from each returned object, which tears down only that instance.\n */\nexport function unmount(): void {\n if (lastOssContainer) {\n unmountOssContainer(lastOssContainer);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports\n// ---------------------------------------------------------------------------\n\nexport type { TemplaticalCloudEditorConfig } from \"./cloud/cloudConfig\";\nexport type {\n BlockDefaults,\n TemplateContent,\n TemplateDefaults,\n ThemeOverrides,\n UiTheme,\n MergeTagsConfig,\n LogicTagsConfig,\n LogicTag,\n LogicPair,\n DisplayConditionsConfig,\n CustomBlockDefinition,\n ViewportSize,\n ColorsConfig,\n CustomFont,\n FontsConfig,\n RenderPayload,\n RenderProvider,\n SavedBlock,\n SavedBlocksListParams,\n SavedBlocksOptions,\n SavedBlocksProvider,\n Template,\n TemplatePatch,\n TemplatesOptions,\n TemplateSaveTrigger,\n TemplateSettingsConfig,\n TemplatesProvider,\n TestEmailOptions,\n TestEmailPayload,\n TestEmailProvider,\n VersionHistoryOptions,\n CommentsOptions,\n CommentEventMeta,\n MediaAsset,\n MediaOptions,\n MediaProvider,\n MediaRequestContext,\n SdkErrorCode,\n BlockLock,\n BlockLockHolder,\n BlockParent,\n CollaborationActor,\n CollaborationConflictCode,\n CollaborationConnectionState,\n CollaborationHandlers,\n CollaborationJoin,\n CollaborationMember,\n CollaborationProvider,\n CollaborationRemoteChange,\n Operation,\n OperationBatch,\n OperationsAfterResult,\n RevisionedBatch,\n AiAppliedBatch,\n AiChatMessage,\n AiChatRequest,\n AiAltTextRequest,\n AiConversationProvider,\n AiChatAttachment,\n AiFeatureName,\n AiFixFinding,\n AiFixRequest,\n AiMergeTags,\n AiMessageBatch,\n AiOperationsResult,\n AiProvider,\n AiReplay,\n AiReplayContext,\n AiReplayOutcome,\n AiRequestBase,\n AiRewriteRequest,\n AiTurnHandlers,\n AiTurnResult,\n} from \"@templatical/types\";\n\n// Bundled browser-local saved-blocks / media providers. Re-exported here\n// (rather than leaving them to `@templatical/core`) because consumers\n// install only this package — core is bundled inline and isn't resolvable\n// on their side.\nexport { createLocalStorageSavedBlocksProvider } from \"@templatical/core\";\nexport type { LocalStorageSavedBlocksOptions } from \"@templatical/core\";\nexport { createLocalStorageMediaProvider } from \"@templatical/core\";\nexport type { LocalStorageMediaProviderOptions } from \"@templatical/core\";\n\nexport type { ResolveImageUrl } from \"./composables/useImageUrlResolver\";\nexport type { FontOption } from \"./composables/useFonts\";\nexport type { HtmlBlockPreviewConfig } from \"./utils/resolveHtmlBlockPreview\";\n\nexport {\n applyLayout,\n validateLayout,\n createSlotBlock,\n createWrapperBlock,\n createParagraphBlock,\n createDefaultTemplateContent,\n isSlot,\n isWrapper,\n layoutWrapsSlot,\n} from \"@templatical/types\";\n\nexport {\n getSupportedLocales,\n getSupportedCloudLocales,\n isLocaleSupported,\n isCloudLocaleSupported,\n getBaseLocale,\n} from \"./i18n\";\n\nexport { AI_FIXABLE_RULES, AI_ALT_TEXT_RULES } from \"./utils/aiFixableRules\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAMujB,KAAe;AA8BrB,SAAgBC,GAAwB,GAGP;CAC/B,IAAMC,IAAMC,EAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,MAAM,GAAG,GAC7CC,IAASF,KAAOF,GAAa,KAAKE,CAAG,IAAI,EAAE,QAAQA,EAAI,IAAI,KAAA;CAEjE,IAAKE,KAAWD,EAAO,kBAEvB,OAAO;EAAE,GAAGC;EAAQ,GAAGD,EAAO;CAAiB;AACjD;;A,aChDI1jB,KAAA,EAAA,OAAM,gJAA+I;;CADvJ,OAAAC,EAAA,GAAAC,EAIM,OAJNF,IAIM,CADJG,EAAQ4jB,EAAA,QAAA,SAAA,C;;;;;;;;;;;;;;;;;;;;;;;;A,0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