@cossackframework/cms 0.0.0 → 0.9.1

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/agent-docs.json +259 -0
  4. package/app/README.md +78 -0
  5. package/app/cossack-recipe.json +43 -0
  6. package/app/src/auth-bot-check.ts +32 -0
  7. package/app/src/auth-bot-token.ts +11 -0
  8. package/app/src/auth-input.ts +35 -0
  9. package/app/src/auth-options.ts +18 -0
  10. package/app/src/auth-providers.ts +16 -0
  11. package/app/src/auth.ts +1082 -0
  12. package/app/src/brand.ts +68 -0
  13. package/app/src/cms/ai.ts +54 -0
  14. package/app/src/cms/analytics.ts +33 -0
  15. package/app/src/cms/block-errors.ts +55 -0
  16. package/app/src/cms/block-inserter.ts +111 -0
  17. package/app/src/cms/block-panel.ts +68 -0
  18. package/app/src/cms/block-rows.ts +44 -0
  19. package/app/src/cms/block-tree.ts +585 -0
  20. package/app/src/cms/blocks.css +708 -0
  21. package/app/src/cms/builder.ts +126 -0
  22. package/app/src/cms/cache.ts +44 -0
  23. package/app/src/cms/carousel.client.ts +52 -0
  24. package/app/src/cms/collab/presence.ts +69 -0
  25. package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
  26. package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
  27. package/app/src/cms/collab/room.ts +881 -0
  28. package/app/src/cms/compare.client.ts +47 -0
  29. package/app/src/cms/condition-control.ts +109 -0
  30. package/app/src/cms/content-api.ts +143 -0
  31. package/app/src/cms/content.ts +524 -0
  32. package/app/src/cms/countdown.client.ts +37 -0
  33. package/app/src/cms/editor-layout-editor.ts +260 -0
  34. package/app/src/cms/editor-layout-view.ts +37 -0
  35. package/app/src/cms/editor.ts +381 -0
  36. package/app/src/cms/entry.ts +26 -0
  37. package/app/src/cms/feeds.ts +145 -0
  38. package/app/src/cms/field-controls.ts +222 -0
  39. package/app/src/cms/field-group-editor.ts +105 -0
  40. package/app/src/cms/field-group-view.ts +211 -0
  41. package/app/src/cms/form-view.ts +203 -0
  42. package/app/src/cms/form.client.ts +203 -0
  43. package/app/src/cms/guards.ts +27 -0
  44. package/app/src/cms/handoff.ts +202 -0
  45. package/app/src/cms/headings.ts +51 -0
  46. package/app/src/cms/icons.ts +80 -0
  47. package/app/src/cms/import.client.ts +16 -0
  48. package/app/src/cms/index.ts +191 -0
  49. package/app/src/cms/lightbox.client.ts +109 -0
  50. package/app/src/cms/machine.ts +118 -0
  51. package/app/src/cms/maintenance.ts +97 -0
  52. package/app/src/cms/manage.ts +1236 -0
  53. package/app/src/cms/mcp-tools.ts +388 -0
  54. package/app/src/cms/mcp.ts +242 -0
  55. package/app/src/cms/media-chooser.ts +123 -0
  56. package/app/src/cms/media-usage.ts +57 -0
  57. package/app/src/cms/middleware.ts +199 -0
  58. package/app/src/cms/middlewares.ts +13 -0
  59. package/app/src/cms/network-ui.ts +36 -0
  60. package/app/src/cms/network-view.ts +38 -0
  61. package/app/src/cms/notes-announce.ts +65 -0
  62. package/app/src/cms/notes-rail.ts +207 -0
  63. package/app/src/cms/notification-rules.ts +66 -0
  64. package/app/src/cms/recovery.ts +82 -0
  65. package/app/src/cms/replace.ts +63 -0
  66. package/app/src/cms/reserved-paths.ts +19 -0
  67. package/app/src/cms/rich-text-field.ts +325 -0
  68. package/app/src/cms/rich-text-schema.ts +91 -0
  69. package/app/src/cms/rich-text.client.ts +255 -0
  70. package/app/src/cms/search.client.ts +116 -0
  71. package/app/src/cms/seo-head.ts +78 -0
  72. package/app/src/cms/seo.ts +241 -0
  73. package/app/src/cms/settings-draft.ts +218 -0
  74. package/app/src/cms/settings-file.ts +127 -0
  75. package/app/src/cms/settings-form.ts +180 -0
  76. package/app/src/cms/settings-languages.ts +125 -0
  77. package/app/src/cms/settings-nav.ts +102 -0
  78. package/app/src/cms/settings-network.ts +151 -0
  79. package/app/src/cms/settings-permalinks.ts +114 -0
  80. package/app/src/cms/settings-scroll.ts +10 -0
  81. package/app/src/cms/settings-search.ts +77 -0
  82. package/app/src/cms/settings-section.ts +38 -0
  83. package/app/src/cms/share.client.ts +27 -0
  84. package/app/src/cms/site-editing.ts +219 -0
  85. package/app/src/cms/site-editor.client.ts +1008 -0
  86. package/app/src/cms/site-editor.ts +99 -0
  87. package/app/src/cms/site-export.ts +60 -0
  88. package/app/src/cms/site-forms.ts +143 -0
  89. package/app/src/cms/site-import.ts +28 -0
  90. package/app/src/cms/site-session.ts +36 -0
  91. package/app/src/cms/site-taskbar.ts +77 -0
  92. package/app/src/cms/site-view.ts +1014 -0
  93. package/app/src/cms/site.ts +1322 -0
  94. package/app/src/cms/sitemaps.ts +131 -0
  95. package/app/src/cms/stat.client.ts +56 -0
  96. package/app/src/cms/style-controls.ts +252 -0
  97. package/app/src/cms/tabs.client.ts +36 -0
  98. package/app/src/cms/taskbar.ts +134 -0
  99. package/app/src/cms/term-icons.ts +10 -0
  100. package/app/src/cms/traffic.ts +26 -0
  101. package/app/src/cms/ui.ts +170 -0
  102. package/app/src/cms/updates.ts +124 -0
  103. package/app/src/cms/uploads.ts +26 -0
  104. package/app/src/cms/worker.ts +13 -0
  105. package/app/src/config/auth.ts +30 -0
  106. package/app/src/config/cms.ts +18 -0
  107. package/app/src/dashboard/access.ts +344 -0
  108. package/app/src/dashboard/agent-icons.ts +44 -0
  109. package/app/src/dashboard/app-passwords.ts +74 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +53 -0
  112. package/app/src/dashboard/head.ts +29 -0
  113. package/app/src/dashboard/icons.ts +15 -0
  114. package/app/src/dashboard/list-table.ts +120 -0
  115. package/app/src/dashboard/modules/roles.ts +15 -0
  116. package/app/src/dashboard/modules/sessions.ts +15 -0
  117. package/app/src/dashboard/modules/settings.ts +15 -0
  118. package/app/src/dashboard/modules/users.ts +18 -0
  119. package/app/src/dashboard/page.ts +67 -0
  120. package/app/src/dashboard/registry.ts +13 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +26 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +40 -0
  125. package/app/src/dashboard/user-sections.ts +172 -0
  126. package/app/src/lib/permissions.ts +84 -0
  127. package/app/src/middlewares/auth.ts +117 -0
  128. package/app/src/pages/(site)/[...path]/index.ts +609 -0
  129. package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
  130. package/app/src/pages/(site)/feed/index.ts +12 -0
  131. package/app/src/pages/(site)/index.ts +11 -0
  132. package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
  133. package/app/src/pages/(site)/layout.ts +219 -0
  134. package/app/src/pages/(site)/llms.txt/index.ts +23 -0
  135. package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
  136. package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
  137. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
  138. package/app/src/pages/(site)/robots.txt/index.ts +29 -0
  139. package/app/src/pages/(site)/search/index.ts +36 -0
  140. package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
  141. package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
  142. package/app/src/pages/api/auth/session.ts +48 -0
  143. package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
  144. package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
  145. package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
  146. package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
  147. package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
  148. package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
  149. package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
  150. package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
  151. package/app/src/pages/api/cms/cache/purge.ts +6 -0
  152. package/app/src/pages/api/cms/collections/index.ts +6 -0
  153. package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
  154. package/app/src/pages/api/cms/comments/[id].ts +9 -0
  155. package/app/src/pages/api/cms/comments/index.ts +126 -0
  156. package/app/src/pages/api/cms/comments/queue.ts +6 -0
  157. package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
  158. package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
  159. package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
  160. package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
  161. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
  162. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
  163. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
  164. package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
  165. package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
  166. package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
  167. package/app/src/pages/api/cms/export/[collection].ts +37 -0
  168. package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
  169. package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
  170. package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
  171. package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
  172. package/app/src/pages/api/cms/import/[collection].ts +23 -0
  173. package/app/src/pages/api/cms/mcp.ts +29 -0
  174. package/app/src/pages/api/cms/me/index.ts +6 -0
  175. package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
  176. package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
  177. package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
  178. package/app/src/pages/api/cms/media/[id].ts +6 -0
  179. package/app/src/pages/api/cms/media.ts +26 -0
  180. package/app/src/pages/api/cms/menus/[location].ts +14 -0
  181. package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
  182. package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
  183. package/app/src/pages/api/cms/network/sites/index.ts +14 -0
  184. package/app/src/pages/api/cms/notes/[id].ts +13 -0
  185. package/app/src/pages/api/cms/notes/index.ts +6 -0
  186. package/app/src/pages/api/cms/payments/webhook.ts +28 -0
  187. package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
  188. package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
  189. package/app/src/pages/api/cms/plugins/index.ts +6 -0
  190. package/app/src/pages/api/cms/recovery.ts +29 -0
  191. package/app/src/pages/api/cms/redirects/index.ts +9 -0
  192. package/app/src/pages/api/cms/roles/index.ts +6 -0
  193. package/app/src/pages/api/cms/schema/[collection].ts +13 -0
  194. package/app/src/pages/api/cms/search.ts +16 -0
  195. package/app/src/pages/api/cms/settings/[group].ts +9 -0
  196. package/app/src/pages/api/cms/settings/index.ts +9 -0
  197. package/app/src/pages/api/cms/site-export.ts +34 -0
  198. package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
  199. package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
  200. package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
  201. package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
  202. package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
  203. package/app/src/pages/api/cms/uploads/index.ts +26 -0
  204. package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
  205. package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
  206. package/app/src/pages/api/cms/users/index.ts +12 -0
  207. package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
  208. package/app/src/pages/api/cms/webhooks/index.ts +9 -0
  209. package/app/src/pages/auth/[provider]/callback.ts +11 -0
  210. package/app/src/pages/auth/[provider]/redirect.ts +9 -0
  211. package/app/src/pages/auth/forgot-password/index.ts +75 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +198 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +117 -0
  216. package/app/src/pages/auth/reset-password/index.ts +65 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +67 -0
  219. package/app/src/pages/auth/verify/index.ts +62 -0
  220. package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
  221. package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
  222. package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
  223. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
  224. package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
  225. package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
  226. package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
  227. package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
  228. package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
  229. package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
  230. package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
  231. package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
  232. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
  233. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
  234. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
  235. package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
  236. package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
  237. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
  238. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
  239. package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
  240. package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
  241. package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
  242. package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
  243. package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
  244. package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
  245. package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
  246. package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
  247. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
  248. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
  249. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
  250. package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
  251. package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
  252. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
  253. package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
  254. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
  255. package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
  256. package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
  257. package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
  258. package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
  259. package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
  260. package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
  261. package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
  262. package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
  263. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
  264. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
  265. package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
  266. package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
  267. package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
  268. package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
  269. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
  270. package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
  271. package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
  272. package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
  273. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
  274. package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
  275. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
  276. package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
  277. package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +320 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +255 -0
  282. package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
  283. package/app/src/pages/dashboard/roles/index.ts +134 -0
  284. package/app/src/pages/dashboard/roles/new/index.ts +95 -0
  285. package/app/src/pages/dashboard/sessions/index.ts +105 -0
  286. package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
  287. package/app/src/pages/dashboard/users/index.ts +299 -0
  288. package/app/src/pages/dashboard/users/new/index.ts +123 -0
  289. package/app/src/passkeys.client.ts +18 -0
  290. package/app/src/plugins/default-theme/assets/cover.svg +31 -0
  291. package/app/src/plugins/default-theme/assets/logo.svg +8 -0
  292. package/app/src/plugins/default-theme/parts/comments.ts +66 -0
  293. package/app/src/plugins/default-theme/parts/list.ts +38 -0
  294. package/app/src/plugins/default-theme/parts/media.ts +15 -0
  295. package/app/src/plugins/default-theme/parts/options.ts +45 -0
  296. package/app/src/plugins/default-theme/plugin.json +275 -0
  297. package/app/src/plugins/default-theme/templates/archive.ts +14 -0
  298. package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
  299. package/app/src/plugins/default-theme/templates/entry.ts +27 -0
  300. package/app/src/plugins/default-theme/templates/home.ts +8 -0
  301. package/app/src/plugins/default-theme/templates/layout.ts +40 -0
  302. package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
  303. package/app/src/plugins/default-theme/templates/search.ts +32 -0
  304. package/app/src/services/rbac.ts +65 -0
  305. package/app/src/services/roles.ts +89 -0
  306. package/app/src/services/users.ts +173 -0
  307. package/package.json +114 -2
  308. package/src/automations.ts +95 -0
  309. package/src/bindings.ts +138 -0
  310. package/src/block-references.ts +239 -0
  311. package/src/block-shape.ts +155 -0
  312. package/src/blocks.ts +1157 -0
  313. package/src/cache.ts +54 -0
  314. package/src/checks.ts +198 -0
  315. package/src/cloudflare-workers.d.ts +13 -0
  316. package/src/cloudflare.ts +61 -0
  317. package/src/collab.ts +372 -0
  318. package/src/collections.ts +421 -0
  319. package/src/comments.ts +46 -0
  320. package/src/cron.ts +95 -0
  321. package/src/dashboard-menu.ts +105 -0
  322. package/src/diff.ts +113 -0
  323. package/src/editor-layout.ts +316 -0
  324. package/src/errors.ts +50 -0
  325. package/src/field-groups.ts +498 -0
  326. package/src/fields.ts +411 -0
  327. package/src/form-builder.ts +1053 -0
  328. package/src/forms.ts +109 -0
  329. package/src/highlight.ts +134 -0
  330. package/src/hooks.ts +510 -0
  331. package/src/icon-catalog.ts +55 -0
  332. package/src/icons.ts +128 -0
  333. package/src/images.ts +149 -0
  334. package/src/index.ts +100 -0
  335. package/src/isolate-core.ts +245 -0
  336. package/src/isolate.ts +19 -0
  337. package/src/isolation.ts +69 -0
  338. package/src/mail.ts +182 -0
  339. package/src/manifest.ts +476 -0
  340. package/src/media.ts +193 -0
  341. package/src/menus.ts +287 -0
  342. package/src/module.ts +32 -0
  343. package/src/modules/content.ts +64 -0
  344. package/src/modules/forms.ts +35 -0
  345. package/src/node.ts +66 -0
  346. package/src/notes.ts +237 -0
  347. package/src/permissions.ts +139 -0
  348. package/src/plugin-settings.ts +114 -0
  349. package/src/records.ts +56 -0
  350. package/src/redirects.ts +59 -0
  351. package/src/resource.ts +245 -0
  352. package/src/richtext.ts +402 -0
  353. package/src/schema-json.ts +112 -0
  354. package/src/search.ts +89 -0
  355. package/src/seo.ts +477 -0
  356. package/src/server/accounts.ts +418 -0
  357. package/src/server/ai.ts +33 -0
  358. package/src/server/api-tokens.ts +91 -0
  359. package/src/server/areas.ts +116 -0
  360. package/src/server/audit.ts +94 -0
  361. package/src/server/auth.ts +89 -0
  362. package/src/server/automations.ts +190 -0
  363. package/src/server/autosaves.ts +69 -0
  364. package/src/server/brand-icons.ts +50 -0
  365. package/src/server/brands.ts +86 -0
  366. package/src/server/budget.ts +97 -0
  367. package/src/server/cache.ts +104 -0
  368. package/src/server/capabilities.ts +333 -0
  369. package/src/server/cloudflare.ts +92 -0
  370. package/src/server/comments.ts +237 -0
  371. package/src/server/drafts.ts +176 -0
  372. package/src/server/field-groups.ts +88 -0
  373. package/src/server/files.ts +780 -0
  374. package/src/server/forms.ts +726 -0
  375. package/src/server/handoffs.ts +107 -0
  376. package/src/server/host-schema.ts +312 -0
  377. package/src/server/host.ts +2892 -0
  378. package/src/server/images.ts +34 -0
  379. package/src/server/index.ts +59 -0
  380. package/src/server/indexnow.ts +91 -0
  381. package/src/server/isolation.ts +183 -0
  382. package/src/server/locked.ts +45 -0
  383. package/src/server/mail.ts +93 -0
  384. package/src/server/markdown.ts +24 -0
  385. package/src/server/menus.ts +286 -0
  386. package/src/server/network-policy.ts +60 -0
  387. package/src/server/network.ts +665 -0
  388. package/src/server/notes.ts +275 -0
  389. package/src/server/outbox.ts +213 -0
  390. package/src/server/path-moves.ts +33 -0
  391. package/src/server/payments.ts +59 -0
  392. package/src/server/previews.ts +62 -0
  393. package/src/server/purge.ts +140 -0
  394. package/src/server/reconcile.ts +38 -0
  395. package/src/server/redirects.ts +183 -0
  396. package/src/server/repository.ts +1107 -0
  397. package/src/server/schedules.ts +105 -0
  398. package/src/server/schema.ts +562 -0
  399. package/src/server/security.ts +391 -0
  400. package/src/server/seed.ts +52 -0
  401. package/src/server/shared-fields.ts +34 -0
  402. package/src/server/site-export.ts +151 -0
  403. package/src/server/site-import.ts +482 -0
  404. package/src/server/site-search.ts +289 -0
  405. package/src/server/site-settings.ts +286 -0
  406. package/src/server/sites.ts +243 -0
  407. package/src/server/stores.ts +314 -0
  408. package/src/server/stripe.ts +173 -0
  409. package/src/server/taxonomies.ts +415 -0
  410. package/src/server/tokens.ts +25 -0
  411. package/src/server/traffic.ts +118 -0
  412. package/src/server/users.ts +653 -0
  413. package/src/server/webhooks.ts +245 -0
  414. package/src/settings-controls.ts +54 -0
  415. package/src/settings-document.ts +111 -0
  416. package/src/settings.ts +426 -0
  417. package/src/storage/cloudflare.ts +94 -0
  418. package/src/storage/index.ts +30 -0
  419. package/src/storage/node.ts +114 -0
  420. package/src/taxonomy.ts +51 -0
  421. package/src/theme.ts +1135 -0
  422. package/src/to-markdown.ts +179 -0
  423. package/src/updates.ts +126 -0
  424. package/src/version.ts +2 -0
  425. package/src/vite.d.ts +25 -0
  426. package/src/vite.js +199 -0
  427. package/src/webhooks.ts +107 -0
@@ -0,0 +1,2382 @@
1
+ import { Cossack, Page, State, ClientState, Server, Client, On, OnWindow, PreventNavigation, type HeadValue, ClientVisibleError } from '@cossackframework/core';
2
+ import { input } from '@cossackframework/core/input';
3
+ import { Avatar, Button, Checkbox, Combobox, Icon, Input, Modal, NativeSelect, Textarea, CodeEditor, Tabs } from '@cossackframework/ui';
4
+ import { html, component, unsafeHTML, type TemplateResult } from '@cossackframework/renderer';
5
+ import { applyTreeOp, ARTICLE_TYPES, blockId, CORE_BLOCKS, entryAuthors, groupPeers, livePeers, patchKey, PendingKeys, richTextPath, parseRichTextPath, scalarKey, treeHash, treeOps, systemPrincipal, entryChecks, evaluateRule, fieldVisibility, findBlock, flattenBlocks, flattenGroupFields, formatBytes, hasPermission, isCmsError, languageName, mediaKind, recordSchema, recordTitle, renderSeoTemplate, richTextBlocks, TITLE_SEPARATORS, updateBlock, PERMISSIONS, participantColor, formatNoteTarget, noteBlock, noteField, noteThreads, parseNoteTarget, type Block, type BlockCondition, type Check, type EmbeddedBlock, type JsonSchema, type MediaKind, type Note, type NoteAction, type NoteRange, type NoteStatus, type NoteThread, type RecordShape, type RichTextDoc, type Participant, type PeerPresence, type PeerState, type TreeOp, blocksPlain, richTextPlain, principalId } from '@cossackframework/cms';
6
+ import { blockPanel } from '#app/cms/block-panel';
7
+ import { describeBlockError } from '#app/cms/block-errors';
8
+ import { blockIdOf, styleValues, withStyle, type BlockTab, type StyleValues } from '#app/cms/style-controls';
9
+ import { renderMarkdown, type CmsHost } from '@cossackframework/cms/server';
10
+ import { openMatches } from '#app/cms/site';
11
+ import { mentionableUsers } from '#app/cms/site-editing';
12
+ import { applyEntryJson, editorView, entryJson, entryValues, fieldErrors, listUpTo, mediaPreviews, parentOptions, patternBlocks, routeResource, saveEntry, termOptions, type MediaPreview, type SaveIntent } from '#app/cms/content';
13
+ import { blockDefaults, contentField, controlValue, editorBlocks, editorInput, entryUrl, suggestedSlug, type EditorBlock, type EditorField, type EditorValues, type EditorView, type TermOption } from '#app/cms/editor';
14
+ import { collabEditors, RichTextField, richTextEditors, type RichTextFieldProps } from '#app/cms/rich-text-field';
15
+ import type { Caret, NoteMark } from '#app/cms/rich-text.client';
16
+ import { EntryRoom, type NoteChange, type RoomHandle, type RoomSnapshot } from '#app/cms/collab/room';
17
+ import { avatarStack, namesOf, onTab, presenceChip, presenceOutline, type Someone } from '#app/cms/collab/presence';
18
+ import { BlockTree, blockSummary } from '#app/cms/block-tree';
19
+ import { inlineNoteTools, noteButton, noteMarker, notesRail, type NoteAnchorView, type NoteComposer } from '#app/cms/notes-rail';
20
+ import { bindingChoices, choicesControl, fieldControl, groupFields, multipleControl, type BindingChoice } from '#app/cms/field-controls';
21
+ import { chooserKind, MEDIA_ACCEPT, MEDIA_KIND_CHOICES, uploadFile } from '#app/cms/media-chooser';
22
+ import { FieldGroupView, plainBlocks, visibilityTypes, type RowPath } from '#app/cms/field-group-view';
23
+ import { box, CONTROL, countBadge, iconButton, linkButton, notice, rememberTab, shortDate, STATUS_LABELS, statusBadge, tabFromQuery } from '#app/cms/ui';
24
+ import { editorLayoutView } from '#app/cms/editor-layout-view';
25
+ import { hasIcon, icon } from '#app/cms/icons';
26
+ import { boxFields, layoutBoxes } from '@cossackframework/cms';
27
+ import { conditionControl, conditionFields } from '#app/cms/condition-control';
28
+ import { notificationRulesControl } from '#app/cms/notification-rules';
29
+ import { siteOrigin } from '#app/cms/seo';
30
+
31
+ /** Assistant suggestions per account: each one spends the site's AI budget. */
32
+ const SUGGESTIONS = { max: 20, windowMs: 60_000 };
33
+
34
+ type MediaTarget = { field: string; block?: string; key?: string; multiple?: boolean; insert?: boolean; richText?: boolean; dialog?: boolean; group?: boolean; /** The rich text editor to insert into, when it is not the field's own. */ editor?: string;
35
+ /** The file goes to the panel's Style tab: the block's background image or video. */ style?: 'image' | 'video';
36
+ /** The kind of file the library opens on: the field's first declared kind; images when absent. */ fileKind?: string;
37
+ /** The rows the value sits in, from the top down: `key` is then a field of the innermost row. */ rows?: RowPath };
38
+ /** Field block kinds whose values read as text, as editor field kinds, for the binding picker. */
39
+ const BINDABLE_FIELD_BLOCKS: Record<string, EditorField['kind']> = { text: 'string', textarea: 'text', markdown: 'text', number: 'number', integer: 'integer', boolean: 'boolean', choice: 'enum', date: 'datetime' };
40
+
41
+ /** A block being edited in the side panel: one of a blocks field's tree, or one embedded in a rich text field. */
42
+ interface BlockDialog { field: string; id: string; type: string; values: Record<string, unknown>; errors: Record<string, string>; embedded: boolean; tab: BlockTab; style: StyleValues; /** In a form: when the block shows. */ when?: BlockCondition; /** An embedded block's rich text editor, when it is not the field's own (rich text inside a block). */ editor?: string }
43
+
44
+ /** A translation of the entry, or a language it has none in yet. */
45
+ interface TranslationLink { code: string; label: string; id: string | null; title: string; status: string }
46
+
47
+ /** Whether two field values are the same as JSON, as the room carries them. */
48
+ function sameValue(a: unknown, b: unknown): boolean {
49
+ if (a === b) return true;
50
+ try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
51
+ }
52
+
53
+ /**
54
+ * The entry editor for every collection and resource. A new entry is `/new`. The title drives
55
+ * the slug until the slug is edited; the Publish box's status select and button set the status,
56
+ * and a future publication time schedules the entry. Changed values are autosaved every 30
57
+ * seconds through the autosave API, which touches no state here, and offered back when the
58
+ * editor opens. A reload (the browser's, or the dev server's) keeps unsaved values in session
59
+ * storage and puts them back without asking.
60
+ */
61
+ @Page({ transport: 'http' })
62
+ export default class EntryEditor extends Cossack {
63
+ @State() route = '';
64
+ @State() id = 'new';
65
+ @State() view: EditorView | null = null;
66
+ @State() values: EditorValues = {};
67
+ /** The application has an AI provider: the Assistant box offers suggestions. */
68
+ @State() assistant = false;
69
+ @State() assistantBusy = '';
70
+ @State() assistantError = '';
71
+ @State() rev = 0;
72
+ @State() meta = { createdAt: 0, updatedAt: 0, author: '', url: '' as string | null };
73
+ @State() slugTouched = false;
74
+ @State() editingSlug = false;
75
+ @State() errors: Record<string, string> = {};
76
+ @State() message = '';
77
+ @State() error = '';
78
+ @State() saving = false;
79
+ @State() revisions: { revision: number; at: number; actor: string }[] = [];
80
+ @State() parents: TermOption[] = [];
81
+ @State() references: Record<string, { id: string; title: string }[]> = {};
82
+ @State() previews: Record<string, MediaPreview> = {};
83
+ @State() tabs: Record<string, 'write' | 'preview'> = {};
84
+ /** The editor's view: one of the layout's tabs, or `json`, the entry as the API answers it. */
85
+ @State() mode = 'edit';
86
+ @State() json = '';
87
+ /** The entry's JSON Schema, for the JSON tab's completion and linting. */
88
+ @State() schema: JsonSchema | null = null;
89
+ @State() jsonDirty = false;
90
+ @State() rendered: Record<string, string> = {};
91
+ @State() picker: { open: boolean; target: MediaTarget | null; search: string; kind: string; items: (MediaPreview & { size: string; name: string })[] } = { open: false, target: null, search: '', kind: '', items: [] };
92
+ /** Why files of the last upload in the media picker failed, shown in the picker. */
93
+ @State() pickerErrors: string[] = [];
94
+ @State() termDrafts: Record<string, { name: string; parent: string }> = {};
95
+ @State() tagDrafts: Record<string, string> = {};
96
+ @State() canManageTerms = false;
97
+ /** The entry's authors and, for people who edit others' entries, who else can be one: a user's name and picture by ID. */
98
+ @State() people: { id: string; name: string; avatar: string | null }[] = [];
99
+ @State() chooseAuthors = false;
100
+ @State() blockDialog: BlockDialog | null = null;
101
+ /** The saved status, which the Publish button's label depends on. */
102
+ @State() savedStatus = '';
103
+ @State() comments = false;
104
+ /** The active theme's templates an editor can choose for this entry, such as `entry-wide`. */
105
+ @State() templates: string[] = [];
106
+ @State() languages: { multilingual: boolean; options: { code: string; label: string }[] } = { multilingual: false, options: [] };
107
+ @State() translations: TranslationLink[] = [];
108
+ /** Fields the same in every language are read-only: the user cannot update every translation. */
109
+ @State() sharedLocked = false;
110
+ /** What the search preview needs: the site, the separator and the templates that apply to this collection. */
111
+ @State() seo = { origin: '', siteTitle: '', tagline: '', separator: '–', titleTemplate: '%title% %sep% %site%', descriptionTemplate: '%excerpt%', collection: '', article: false, summary: false };
112
+ /** Entries of the site related to this one's title, to link to. */
113
+ @State() linkSuggestions: { title: string; url: string; collection: string }[] = [];
114
+ @ClientState() checksOpen = false;
115
+ @State() previewLink = '';
116
+ @State() previewLinks = 0;
117
+ /** A newer autosave than the saved entry, offered for restore. */
118
+ @State() autosaveOffer: { at: number } | null = null;
119
+ @State() autosavedAt = 0;
120
+ @State() patternChoices: { id: string; title: string; synced: boolean }[] = [];
121
+ @State() patternTitles: Record<string, string> = {};
122
+ /** For patterns: the collections whose new entries can start from one. */
123
+ @State() collectionChoices: { name: string; label: string }[] = [];
124
+ @State() patternPicker: { open: boolean; field: string; starter: boolean } = { open: false, field: '', starter: false };
125
+ /** Changes since the last autosave. */
126
+ @ClientState() dirty = false;
127
+ /** Changes since the last save. */
128
+ @ClientState() unsaved = false;
129
+ private autosaveTimer: ReturnType<typeof setInterval> | undefined;
130
+ /** The values as last loaded, saved or autosaved, so an unchanged editor sends nothing. */
131
+ private autosaved = '';
132
+ private autosaving = false;
133
+ /** The last editorial checks and the values and blocks they were made from. */
134
+ private checked: { key: unknown[]; checks: Check[] } | null = null;
135
+ /** What each hidden tab last showed, and the tab that was open then. */
136
+ private hiddenTabs = new Map<string, { active: string; content: TemplateResult }>();
137
+ // --- Co-editing: a saved entry is edited in its room, with everyone who has it open ---------
138
+ /** The room, once this tab joined it. */
139
+ @ClientState() room: RoomHandle | null = null;
140
+ /** Everyone in the room, this tab included. */
141
+ @ClientState() peers: PeerState[] = [];
142
+ @ClientState() roomStatus = { connected: false, dirty: false, diverged: false, oversized: false };
143
+ /** This tab's ID in the room. */
144
+ private self = '';
145
+ /** This tab's changes the room has not echoed yet. */
146
+ private pending = new PendingKeys();
147
+ /** Changes made before this tab joined the room, by field: kept over the room's first snapshot, then sent to it. */
148
+ private beforeJoin = new Map<string, { previous: unknown; value: unknown }>();
149
+ private presenceTimer: ReturnType<typeof setTimeout> | undefined;
150
+ private previewRefresh: ReturnType<typeof setTimeout> | undefined;
151
+ /** This tab is telling the room about its own save: the room's "saved by" is not news here. */
152
+ private savingSelf = false;
153
+ // --- Notes: review threads on the entry, its fields, blocks and passages, through the room ---
154
+ @State() notes: Note[] = [];
155
+ /** Who the notes name, by user ID. */
156
+ @State() noteAuthors: Record<string, Someone> = {};
157
+ /** People a note can mention: the site's users but the viewer. */
158
+ @State() mentionable: { id: string; name: string }[] = [];
159
+ /** The viewer's user ID: their own notes can be changed and removed. */
160
+ @State() meId = '';
161
+ /** The viewer removes anyone's notes (user administrators). */
162
+ @State() canRemoveNotes = false;
163
+ /** Open notes keep the entry from being published (Settings → Writing). */
164
+ @State() notesGate = false;
165
+ /** The rail is open; `?notes=open` opens it on arrival, from the lists' markers and the home card. */
166
+ @State() notesOpen = false;
167
+ @ClientState() notesFilter: NoteStatus = 'open';
168
+ @ClientState() composer: NoteComposer | null = null;
169
+ @ClientState() editingNote: { id: string; body: string } | null = null;
170
+ /** The thread chosen in the rail, highlighted there and in the content. */
171
+ @ClientState() activeNote: string | null = null;
172
+ /** A note waiting for the viewer to confirm its removal. */
173
+ @ClientState() noteRemoval: string | null = null;
174
+ @ClientState() notesBusy = false;
175
+ @ClientState() notesError = '';
176
+ /** Text notes whose words the editor could not find: shown on their block or field instead. */
177
+ @ClientState() detachedNotes: string[] = [];
178
+ /** Where text notes sit now in the open editors, by note ID, for writing back after a save. */
179
+ private noteRanges = new Map<string, NoteRange>();
180
+
181
+ head(): HeadValue {
182
+ const title = this.view ? (this.id === 'new' ? `${__('New')} ${this.view.singular.toLowerCase()}` : `${__('Edit')} ${this.view.singular.toLowerCase()}`) : __('Editor');
183
+ return { title };
184
+ }
185
+
186
+ async init() {
187
+ this.route = this.c.req.param('collection') ?? '';
188
+ this.id = this.c.req.param('id') ?? 'new';
189
+ const cms = this.c.get('cms');
190
+ this.assistant = cms.ai !== null;
191
+ const principal = this.c.get('principal');
192
+ try {
193
+ const view = await editorView(cms, this.route, principal);
194
+ const { resource } = routeResource(cms, this.route);
195
+ const record = this.id === 'new' ? null : await cms.resource(resource.id).get(this.id, { principal });
196
+ if (this.id !== 'new' && (!record || !cms.resource(resource.id).canUpdate(record, principal))) { this.error = __('This entry does not exist or you cannot edit it.'); this.c.status(404); return; }
197
+ if (!record && evaluateRule(resource.access.create, principal) === 'deny') { this.error = __('You cannot create entries here.'); this.c.status(403); return; }
198
+ this.view = view;
199
+ this.schema = recordSchema(resource);
200
+ this.values = await entryValues(cms, view, record);
201
+ // A new entry starts from the collection's content template.
202
+ const content = contentField(view);
203
+ if (!record && content && view.template.length && !this.blocks(content).length) this.values = { ...this.values, [content]: view.template };
204
+ if (!record && view.publishable && view.resource === 'cms/posts') {
205
+ this.values = { ...this.values, status: await cms.settings.get('writing.defaultStatus') };
206
+ }
207
+ this.slugTouched = Boolean(record);
208
+ this.canManageTerms = evaluateRule({ permission: 'cms:terms' }, principal) === 'allow';
209
+ this.previews = await mediaPreviews(cms, this.values, view);
210
+ if (view.hierarchical) this.parents = await parentOptions(cms, resource.id, record?.id ?? null, principal);
211
+ for (const field of view.fields.filter(entry => entry.kind === 'reference' && entry.target !== resource.id)) {
212
+ const records = await listUpTo(cms, field.target, { order: { field: 'updatedAt', direction: 'desc' } }, principal, 200).catch(() => []);
213
+ const target = cms.resourceById(field.target);
214
+ this.references = { ...this.references, [field.name]: records.map(entry => ({ id: entry.id, title: recordTitle(entry, target.titleField) })) };
215
+ }
216
+ const collection = resource.owner === 'cms' ? cms.collection(resource.name) : null;
217
+ // Off under Settings → Discussion: the entry's switch hides with the comments.
218
+ this.comments = Boolean(collection?.comments) && await cms.settings.get('discussion.enabled');
219
+ if (resource.fields.template) this.templates = await cms.entryTemplates();
220
+ if (resource.fields.authors) {
221
+ // Only people who edit others' entries choose authors; others see who they are.
222
+ this.chooseAuthors = evaluateRule(resource.access.update, principal) === 'allow';
223
+ const current = record ? entryAuthors(record) : principal.kind === 'user' ? [principal.id] : [];
224
+ const known = await cms.users.getMany(current);
225
+ const others = this.chooseAuthors ? (await cms.users.list({ limit: 100 })).items : [];
226
+ this.people = [...current.map(id => known.get(id)).filter(user => user !== undefined), ...others.filter(user => !current.includes(user.id))]
227
+ .map(user => ({ id: user.id, name: user.name || user.email, avatar: user.avatar }));
228
+ }
229
+ if (record) {
230
+ this.rev = record.rev;
231
+ this.savedStatus = String(record.status ?? '');
232
+ const authors = entryAuthors(record).map(id => this.people.find(person => person.id === id)?.name).filter(Boolean).join(', ');
233
+ this.meta = { createdAt: record.createdAt, updatedAt: record.updatedAt, author: authors, url: collection ? (await cms.entryUrls(collection, [record])).get(record.id) ?? null : null };
234
+ if (this.meta.url && view.publishable && record.status !== 'published') this.meta = { ...this.meta, url: null };
235
+ await this.loadRevisions(record.id);
236
+ if (view.path !== null || view.route === 'forms') this.previewLinks = await cms.previews.count(resource.id, record.id).catch(() => 0);
237
+ }
238
+ // The entry's notes, with who wrote them; opening the entry marks the viewer's mentions seen.
239
+ if (record && principal.kind === 'user' && cms.resource(resource.id).canUpdate(record, principal)) {
240
+ this.meId = principal.id;
241
+ this.canRemoveNotes = hasPermission(principal, PERMISSIONS.manageUsers);
242
+ this.notes = await cms.notes.forEntry(resource.id, record.id).catch(() => []);
243
+ const authors = await cms.users.getMany([...new Set([principal.id, ...this.notes.map(note => note.userId)])]);
244
+ this.noteAuthors = Object.fromEntries([...authors.values()].map(user => [user.id, { user: user.id, name: user.name || user.email, avatar: user.avatar, color: participantColor(user.id) }]));
245
+ this.mentionable = await mentionableUsers(cms, principal);
246
+ this.notesGate = await cms.settings.get('writing.requireResolvedNotes');
247
+ this.notesOpen = this.c.req.query('notes') === 'open';
248
+ await cms.notes.markSeen(principal.id, resource.id, record.id).catch(() => undefined);
249
+ }
250
+ const settings = await cms.settings.all();
251
+ this.seo = {
252
+ origin: siteOrigin(this.c), siteTitle: settings['general.siteTitle'], tagline: settings['general.tagline'], separator: TITLE_SEPARATORS[settings['seo.titleSeparator']] ?? '–', collection: collection?.label ?? '',
253
+ titleTemplate: collection?.seoTemplates?.title || settings['seo.entryTitle'], descriptionTemplate: collection?.seoTemplates?.description || settings['seo.entryDescription'],
254
+ article: ARTICLE_TYPES.has(collection?.schema?.type ?? 'WebPage'), summary: Boolean(resource.fields.summary),
255
+ };
256
+ if (collection && typeof collection.path === 'string' && record) await this.loadLinkSuggestions(String(record.title ?? ''), record.id);
257
+ const languages = await cms.languages();
258
+ this.languages = { multilingual: languages.multilingual, options: languages.all.map(code => ({ code, label: languageName(code) })) };
259
+ if (collection && languages.multilingual) {
260
+ const locale = this.c.req.query('locale');
261
+ if (!record && locale && languages.all.includes(locale)) this.values = { ...this.values, locale };
262
+ if (record) await this.loadTranslations(collection.name, record.id);
263
+ }
264
+ // Unsaved work on a new entry from a closed tab or a crash; a saved entry's room keeps its draft instead.
265
+ const autosave = await cms.latestAutosave(resource.id, this.id, principal).catch(() => null);
266
+ if (autosave && !record) this.autosaveOffer = { at: autosave.at };
267
+ if (!record && collection && collection.name !== 'patterns') await this.loadPatterns(collection.name, true);
268
+ if (collection?.name === 'patterns') this.collectionChoices = cms.collections().filter(entry => entry.name !== 'patterns').map(entry => ({ name: entry.name, label: entry.label }));
269
+ await this.loadPatternTitles();
270
+ const saved = this.c.req.query('saved');
271
+ this.message = saved === 'published' ? __('Published.') : saved === 'scheduled' ? __('Scheduled.') : saved === 'pending' ? __('Submitted for review.') : saved === '1' ? __('Saved.') : '';
272
+ this.mode = tabFromQuery(this.c.req.query('tab'), this.editorTabs());
273
+ if (this.mode === 'json' && record) this.json = await entryJson(cms, this.route, record);
274
+ } catch (error) {
275
+ this.error = isCmsError(error) ? error.message : __('The editor could not be loaded.');
276
+ if (isCmsError(error, 'CMS_NOT_FOUND')) this.c.status(404);
277
+ }
278
+ }
279
+
280
+ private async loadRevisions(id: string) {
281
+ const cms = this.c.get('cms');
282
+ const resource = cms.resourceById(this.resourceId());
283
+ const revisions = resource.revisions ? await cms.resource(resource.id).revisions(id, { principal: this.c.get('principal') }, { limit: 10 }).catch(() => []) : [];
284
+ const actors = await cms.users.getMany(revisions.map(entry => entry.actor ?? '').filter(Boolean));
285
+ this.revisions = revisions.map(entry => ({ revision: entry.revision, at: entry.at, actor: actors.get(entry.actor ?? '')?.name ?? entry.actor ?? '' }));
286
+ }
287
+
288
+ private async loadTranslations(collectionName: string, id: string) {
289
+ const cms = this.c.get('cms');
290
+ const principal = this.c.get('principal');
291
+ const record = await cms.resource(`cms/${collectionName}`).get(id, { principal });
292
+ if (!record) return;
293
+ const found = await cms.translations(cms.collection(collectionName), record, { principal });
294
+ if (Object.values(cms.resourceById(`cms/${collectionName}`).fields).some(field => field.translatable === false)) {
295
+ // Every translation counts, also the ones this user cannot read.
296
+ const others = [...(await cms.translations(cms.collection(collectionName), record, { principal: systemPrincipal('translations') })).values()].filter(entry => entry.id !== record.id).map(entry => entry.id);
297
+ this.sharedLocked = others.length > 0 && (await cms.resource(`cms/${collectionName}`).updatable(others, { principal })).size < others.length;
298
+ }
299
+ this.translations = this.languages.options.map(option => {
300
+ const entry = found.get(option.code);
301
+ return { code: option.code, label: option.label, id: entry?.id ?? null, title: entry ? recordTitle(entry, 'title') : '', status: String(entry?.status ?? '') };
302
+ });
303
+ }
304
+
305
+ /** Titles of the synced patterns the entry's content and rich text use, for their blocks. */
306
+ private async loadPatternTitles() {
307
+ const ids = Object.values(this.values).flatMap(value => value && typeof value === 'object' && (value as RichTextDoc).type === 'doc'
308
+ ? richTextBlocks(value as RichTextDoc).filter(block => block.type === 'core/pattern').map(block => String(block.data.pattern))
309
+ : Array.isArray(value) && value.every(entry => entry && typeof entry === 'object' && 'type' in entry) ? flattenBlocks(value as Block[]).filter(block => block.type === 'core/pattern').map(block => String(block.data.pattern)) : []);
310
+ if (!ids.length) return;
311
+ const found = await this.c.get('cms').resource('cms/patterns').getMany(ids, { principal: this.c.get('principal') }).catch(() => new Map<string, RecordShape>());
312
+ this.patternTitles = { ...this.patternTitles, ...Object.fromEntries([...found].map(([id, record]) => [id, recordTitle(record, 'title')])) };
313
+ }
314
+
315
+ /** Patterns to insert, or with `starter`, those offered as this collection's starting layouts. */
316
+ private async loadPatterns(collectionName: string, starter: boolean) {
317
+ const cms = this.c.get('cms');
318
+ const page = await cms.resource('cms/patterns').list({ order: { field: 'title', direction: 'asc' }, limit: 100 }, { principal: this.c.get('principal') }).catch(() => ({ records: [] }));
319
+ this.patternChoices = page.records.filter(record => !starter || (Array.isArray(record.starter) && record.starter.includes(collectionName)))
320
+ .map(record => ({ id: record.id, title: recordTitle(record, 'title'), synced: record.synced !== false }));
321
+ if (starter && this.patternChoices.length) this.patternPicker = { open: true, field: '', starter: true };
322
+ }
323
+
324
+ // --- Editing ---------------------------------------------------------------
325
+
326
+ @Client()
327
+ set(name: string, value: unknown) {
328
+ const previous = this.values[name];
329
+ this.values = { ...this.values, [name]: value };
330
+ this.dirty = true;
331
+ this.unsaved = true;
332
+ if (this.errors[name]) this.errors = Object.fromEntries(Object.entries(this.errors).filter(([key]) => key !== name));
333
+ this.share(name, previous, value);
334
+ }
335
+
336
+ @Client()
337
+ setTitle(value: string) {
338
+ const title = this.view?.titleField || 'title';
339
+ const previous = this.values;
340
+ this.values = { ...this.values, [title]: value, ...(this.view?.slug && !this.slugTouched ? { slug: suggestedSlug(value) } : {}) };
341
+ this.dirty = true;
342
+ this.unsaved = true;
343
+ if (this.errors[title]) this.errors = Object.fromEntries(Object.entries(this.errors).filter(([key]) => key !== title));
344
+ this.share(title, previous[title], value);
345
+ if (this.values.slug !== previous.slug) this.share('slug', previous.slug, this.values.slug);
346
+ }
347
+
348
+ /** A field of a group, such as the SEO title. */
349
+ @Client()
350
+ setGroup(name: string, key: string, value: unknown) {
351
+ this.set(name, { ...((this.values[name] as Record<string, unknown> | undefined) ?? {}), [key]: value });
352
+ }
353
+
354
+ /** The value of a row's field, through the rows above it. */
355
+ private rowValue(field: string, rows: RowPath, key: string): unknown {
356
+ let current: unknown = this.values[field];
357
+ for (const [index, row] of rows.entries()) {
358
+ const list = Array.isArray(current) ? current as Record<string, unknown>[] : [];
359
+ const found = list.find(entry => entry._id === row.id);
360
+ if (!found) return undefined;
361
+ current = index === rows.length - 1 ? found[key] : found[rows[index + 1]!.field];
362
+ }
363
+ return current;
364
+ }
365
+
366
+ /** Set a row's field through the rows above it; the rows are copied on the way down. */
367
+ @Client()
368
+ setRowValue(field: string, rows: RowPath, key: string, value: unknown) {
369
+ const update = (list: unknown, depth: number): unknown => {
370
+ const entries = Array.isArray(list) ? list as Record<string, unknown>[] : [];
371
+ const row = rows[depth]!;
372
+ return entries.map(entry => entry._id !== row.id ? entry : depth === rows.length - 1 ? { ...entry, [key]: value } : { ...entry, [rows[depth + 1]!.field]: update(entry[rows[depth + 1]!.field], depth + 1) });
373
+ };
374
+ this.set(field, update(this.values[field], 0));
375
+ }
376
+
377
+ // --- Co-editing --------------------------------------------------------------
378
+
379
+ /** The field a value belongs to; undefined for the editor's own keys (title, slug, status…), which are scalars. */
380
+ private fieldOf(name: string): EditorField | undefined {
381
+ return this.view?.fields.find(field => field.name === name);
382
+ }
383
+
384
+ /** Rich text keys of a block type: their documents travel as steps, not as patches. */
385
+ private richKeys(type: string): string[] {
386
+ return this.view?.blocks.find(block => block.name === type)?.fields.filter(field => field.kind === 'richtext').map(field => field.name) ?? [];
387
+ }
388
+
389
+ /** Send a change to the room: a blocks field as ops by block, a rich text field not at all (its steps went already), anything else as a value. */
390
+ @Client()
391
+ private share(name: string, previous: unknown, value: unknown) {
392
+ const room = this.room;
393
+ // Typed before the room was joined: the first snapshot keeps it, and sends it then.
394
+ if (!room) { this.beforeJoin.set(name, { previous: this.beforeJoin.get(name)?.previous ?? previous, value }); return; }
395
+ // A field with its own access rule is not in the room: it is saved with this tab's own save.
396
+ if (this.view?.restricted.includes(name)) return;
397
+ const field = this.fieldOf(name);
398
+ if (field?.kind === 'richtext' && !field.multiple) return;
399
+ if (field?.kind === 'blocks') {
400
+ const before = Array.isArray(previous) ? previous as EditorBlock[] : [];
401
+ const after = Array.isArray(value) ? value as EditorBlock[] : [];
402
+ for (const op of treeOps(name, before, after, { skip: (type, key) => this.richKeys(type).includes(key) })) {
403
+ const key = op.kind === 'patch' ? patchKey(name, op.id, op.path) : `tree:${name}`;
404
+ this.pending.sent(key);
405
+ room.tree(op).then(result => { if (!result.applied) { this.pending.settled(key); void this.resyncBlocks(name); } })
406
+ .catch(() => this.pending.settled(key));
407
+ }
408
+ return;
409
+ }
410
+ const key = scalarKey(name);
411
+ this.pending.sent(key);
412
+ room.set(name, value).then(result => { if (!result.applied) this.pending.settled(key); }).catch(() => this.pending.settled(key));
413
+ }
414
+
415
+ /** The room's tree of a blocks field replaces this editor's: after a dropped op, or a hash that differs. */
416
+ @Client()
417
+ private async resyncBlocks(name: string) {
418
+ const room = this.room;
419
+ if (!room) return;
420
+ try {
421
+ const { blocks } = await room.blocks(name);
422
+ this.values = { ...this.values, [name]: blocks as EditorBlock[] };
423
+ this.followDialog(name);
424
+ this.previewsSoon();
425
+ } catch { /* the next snapshot brings it */ }
426
+ }
427
+
428
+ @Client()
429
+ private onRoomReady(handle: RoomHandle) {
430
+ this.self = handle.peer;
431
+ this.room = handle;
432
+ }
433
+
434
+ /**
435
+ * The room's draft replaces the values, apart from fields this tab has changes in flight for
436
+ * and, on the first snapshot, fields it changed before the room was joined, which go to the
437
+ * room now instead of being lost.
438
+ */
439
+ @Client()
440
+ private onSnapshot(snapshot: RoomSnapshot, options: { initial: boolean; resets: readonly string[] }) {
441
+ const values = { ...this.values };
442
+ const trees: string[] = [];
443
+ const early = options.initial ? new Map(this.beforeJoin) : new Map<string, { previous: unknown; value: unknown }>();
444
+ if (options.initial) this.beforeJoin.clear();
445
+ for (const [name, value] of Object.entries(snapshot.values)) {
446
+ const field = this.fieldOf(name);
447
+ if (!options.initial && !this.pending.accepts(field?.kind === 'blocks' ? `tree:${name}` : scalarKey(name))) continue;
448
+ if (early.has(name)) continue;
449
+ // The same value keeps the editor's own: a new array of equal blocks would remount their
450
+ // rich text editors, and someone already typing would lose focus and cursor.
451
+ if (sameValue(values[name], value)) continue;
452
+ // A shared rich text document is the editor's own; the items of a multiple field come as a value.
453
+ values[name] = value;
454
+ if (field?.kind === 'blocks') trees.push(name);
455
+ }
456
+ this.values = values;
457
+ for (const name of trees) this.followDialog(name);
458
+ this.rev = snapshot.rev;
459
+ // The room holds the notes while it lives: its list replaces what the page loaded.
460
+ this.notes = snapshot.notes;
461
+ this.noteAuthors = { ...this.noteAuthors, ...snapshot.people };
462
+ if (options.initial) {
463
+ this.pending.clear();
464
+ this.announce({ tab: this.mode });
465
+ for (const [name, change] of early) this.share(name, name in snapshot.values ? snapshot.values[name] : change.previous, values[name]);
466
+ }
467
+ this.previewsSoon();
468
+ }
469
+
470
+ @Client()
471
+ private onRemoteSet(peer: string, name: string, value: unknown) {
472
+ const key = scalarKey(name);
473
+ if (peer === this.self) { this.pending.settled(key); return; }
474
+ if (!this.pending.accepts(key)) return;
475
+ this.values = { ...this.values, [name]: value };
476
+ if (this.fieldOf(name)?.media) this.previewsSoon();
477
+ }
478
+
479
+ @Client()
480
+ private onRemoteTree(peer: string, op: TreeOp, hash: string) {
481
+ const name = op.field;
482
+ const key = op.kind === 'patch' ? patchKey(name, op.id, op.path) : `tree:${name}`;
483
+ if (peer === this.self) {
484
+ this.pending.settled(key);
485
+ if (this.pending.accepts(`tree:${name}`) && treeHash(this.blocks(name)) !== hash) void this.resyncBlocks(name);
486
+ return;
487
+ }
488
+ if (!this.pending.accepts(key)) return;
489
+ const next = applyTreeOp(this.blocks(name), op) as EditorBlock[] | null;
490
+ if (!next) { void this.resyncBlocks(name); return; }
491
+ this.values = { ...this.values, [name]: next };
492
+ this.followDialog(name, op);
493
+ if (this.pending.accepts(`tree:${name}`) && treeHash(next) !== hash) void this.resyncBlocks(name);
494
+ this.previewsSoon();
495
+ }
496
+
497
+ /** Who is in the room; the others' selections become carets in the rich text documents they are in. */
498
+ @Client()
499
+ private onPeers(peers: readonly PeerState[], self: string) {
500
+ this.self = self;
501
+ this.peers = livePeers(peers, Date.now());
502
+ const me = this.myUser();
503
+ const carets = new Map<string, Caret[]>();
504
+ for (const peer of this.peers) {
505
+ const selection = peer.presence.selection;
506
+ if (peer.peer === self || peer.user === me || !selection) continue;
507
+ carets.set(selection.path, [...carets.get(selection.path) ?? [], { peer: peer.peer, name: peer.name, color: peer.color, anchor: selection.anchor, head: selection.head }]);
508
+ }
509
+ for (const [path, editor] of collabEditors) editor.collab?.setCarets(carets.get(path) ?? []);
510
+ }
511
+
512
+ @Client()
513
+ private onRoomStatus(status: { connected: boolean; dirty: boolean; diverged: boolean; oversized: boolean }) {
514
+ this.roomStatus = status;
515
+ if (status.connected) this.unsaved = status.dirty;
516
+ }
517
+
518
+ @Client()
519
+ private onRemoteSaved(by: string, rev: number) {
520
+ this.rev = rev;
521
+ this.unsaved = false;
522
+ this.dirty = false;
523
+ if (!this.savingSelf) {
524
+ this.message = `${by} ${__('saved this entry.')}`;
525
+ // The room's snapshot leaves out the fields with their own access rule: read them again, or this tab's next save would put back what it had.
526
+ if (this.view?.fields.some(field => this.view!.restricted.includes(field.name))) void this.reloadRestricted();
527
+ }
528
+ }
529
+
530
+ /** The fields the room leaves out, as saved now, for this editor. */
531
+ @Server()
532
+ async reloadRestricted() {
533
+ const cms = this.c.get('cms');
534
+ if (this.id === 'new') return;
535
+ await this.assertEditor();
536
+ const view = await this.serverView();
537
+ const record = await cms.resource(this.resourceId()).get(this.id, { principal: this.c.get('principal') });
538
+ if (!record) return;
539
+ const saved = await entryValues(cms, view, record);
540
+ const names = view.fields.map(field => field.name).filter(name => view.restricted.includes(name));
541
+ this.values = { ...this.values, ...Object.fromEntries(names.map(name => [name, saved[name]])) };
542
+ }
543
+
544
+ /** Tell the room this tab saved; the others hear who did, this tab keeps its own notice. */
545
+ @Client()
546
+ private async announceSaved() {
547
+ const room = this.room;
548
+ if (!room) return;
549
+ this.savingSelf = true;
550
+ try { await room.saved(); } catch { /* the next join brings the room's draft */ }
551
+ finally { this.savingSelf = false; }
552
+ }
553
+
554
+ /** Where this tab is, for the others. */
555
+ @Client()
556
+ private announce(state: PeerPresence) {
557
+ this.room?.presence(state);
558
+ }
559
+
560
+ @Client()
561
+ private announceSelection(path: string, anchor: number, head: number) {
562
+ if (this.presenceTimer) clearTimeout(this.presenceTimer);
563
+ this.presenceTimer = setTimeout(() => this.announce({ selection: { path, anchor, head } }), 100);
564
+ }
565
+
566
+ /** Focus moved: the field (`data-field`) and the block (`data-block-tree-item`, or the side panel's `data-block-sheet`) around it. */
567
+ @On('focusin')
568
+ @Client()
569
+ private trackFocus(event: FocusEvent) {
570
+ if (!this.room) return;
571
+ const target = event.target instanceof Element ? event.target : null;
572
+ const field = target?.closest('[data-field]')?.getAttribute('data-field') || undefined;
573
+ const block = (target?.closest('[data-block-tree-item]')?.getAttribute('data-block-tree-item') || target?.closest('[data-block-sheet]')?.getAttribute('data-block-sheet')) || undefined;
574
+ this.announce({ field, block });
575
+ }
576
+
577
+ /**
578
+ * The side panel shows its block as the room has it: a remote patch changes that one key (what this
579
+ * tab types in the others stays), a replaced tree brings the whole block, and a removed block closes it.
580
+ */
581
+ @Client()
582
+ private followDialog(field: string, op?: TreeOp) {
583
+ const dialog = this.blockDialog;
584
+ if (!dialog || dialog.embedded || dialog.field !== field) return;
585
+ if (op && (op.kind === 'insert' || op.kind === 'move' || op.id !== dialog.id)) return;
586
+ const block = findBlock(this.blocks(field), dialog.id);
587
+ if (!block) { this.blockDialog = null; return; }
588
+ const option = this.view?.blocks.find(entry => entry.name === block.type);
589
+ if (!option) return;
590
+ const valueOf = (entry: EditorField) => block.data[entry.name] ?? controlValue(entry, entry.defaultValue);
591
+ const { when: _previous, ...rest } = dialog;
592
+ if (op?.kind === 'patch') {
593
+ if (op.path.startsWith('data.')) {
594
+ const entry = option.fields.find(candidate => candidate.name === op.path.slice(5));
595
+ if (entry && entry.kind !== 'richtext') this.blockDialog = { ...dialog, values: { ...dialog.values, [entry.name]: valueOf(entry) }, errors: { ...dialog.errors, [entry.name]: '' } };
596
+ } else if (op.path === 'style' || op.path === 'layout') this.blockDialog = { ...dialog, style: styleValues(block) };
597
+ else if (op.path === 'when') this.blockDialog = block.when ? { ...rest, when: block.when } : rest;
598
+ return;
599
+ }
600
+ this.blockDialog = { ...rest, style: styleValues(block), ...(block.when ? { when: block.when } : {}),
601
+ values: Object.fromEntries(option.fields.filter(entry => entry.kind !== 'richtext').map(entry => [entry.name, valueOf(entry)])) };
602
+ }
603
+
604
+ // --- Notes ---------------------------------------------------------------------------------
605
+
606
+ /** Open threads: the roots still waiting for review. */
607
+ private openRoots(): Note[] {
608
+ return this.notes.filter(note => !note.parentId && note.status === 'open');
609
+ }
610
+
611
+ /** Open threads on a field, counting those on its blocks and passages. */
612
+ private fieldNoteCount(field: string): number {
613
+ return this.openRoots().filter(note => { const target = parseNoteTarget(note.target); return !!target && noteField(target) === field; }).length;
614
+ }
615
+
616
+ /** Open threads by block ID in a blocks field, counting the passages inside each block. */
617
+ private blockNoteCounts(field: string): Record<string, number> {
618
+ const counts: Record<string, number> = {};
619
+ for (const note of this.openRoots()) {
620
+ const target = parseNoteTarget(note.target);
621
+ const block = target ? noteBlock(target) : null;
622
+ if (block && block.field === field) counts[block.block] = (counts[block.block] ?? 0) + 1;
623
+ }
624
+ return counts;
625
+ }
626
+
627
+ /** A field's name in words: its label, a taxonomy's, or a sidebar key's. */
628
+ private fieldLabel(name: string): string {
629
+ return this.fieldOf(name)?.label ?? this.view?.taxonomies.find(taxonomy => taxonomy.name === name)?.label ?? __(SIDEBAR_LABELS[name] ?? name);
630
+ }
631
+
632
+ /** The marker and the add button beside a field's label; nothing on a new entry, which has no room yet. */
633
+ private noteTools(field: string, options: { always?: boolean } = {}): TemplateResult | null {
634
+ if (this.id === 'new') return null;
635
+ const label = this.fieldLabel(field);
636
+ return html`<span class="ml-auto inline-flex items-center gap-1">
637
+ ${noteMarker(this.fieldNoteCount(field), label, () => this.showNotes({ field }))}
638
+ ${noteButton(`note-${field.replace(/[^a-zA-Z0-9_-]/g, '-')}`, label, () => this.startNote(formatNoteTarget({ kind: 'field', field })), options)}</span>`;
639
+ }
640
+
641
+ /** The notes of a rich text document, for its editor: their last known places and the words they quote; and the toolbar's Note. */
642
+ private notesFor(path: string | null): Partial<Pick<RichTextFieldProps, 'notes' | 'onNote'>> {
643
+ if (!path || this.id === 'new') return {};
644
+ const marks = this.notes.filter(note => !note.parentId && note.status === 'open' && note.target === `text:${path}`).map(note => ({ id: note.id, range: note.range, quote: note.quote }));
645
+ return {
646
+ notes: { marks, active: this.activeNote, onClick: (id: string) => this.selectNote(id, { reveal: false }), onMoved: (placed: readonly NoteMark[]) => this.onNotesPlaced(path, placed) },
647
+ // Without a passage, the note goes on the document's block, or on the field.
648
+ onNote: (range: NoteRange | null, quote: string) => {
649
+ const parsed = parseRichTextPath(path);
650
+ const whole = parsed?.block ? formatNoteTarget({ kind: 'block', field: parsed.field, block: parsed.block.id }) : formatNoteTarget({ kind: 'field', field: parsed?.field ?? path });
651
+ this.startNote(range ? `text:${path}` : whole, range, quote);
652
+ },
653
+ };
654
+ }
655
+
656
+ /** Where a document's notes sit now; those the editor could not place are detached. */
657
+ @Client()
658
+ private onNotesPlaced(path: string, placed: readonly NoteMark[]) {
659
+ const found = new Set<string>();
660
+ for (const mark of placed) { this.noteRanges.set(mark.id, { from: mark.from, to: mark.to }); found.add(mark.id); }
661
+ const here = (id: string) => this.notes.find(note => note.id === id)?.target === `text:${path}`;
662
+ const detached = this.notes.filter(note => !note.parentId && note.status === 'open' && here(note.id) && !found.has(note.id)).map(note => note.id);
663
+ const next = [...this.detachedNotes.filter(id => !here(id)), ...detached].sort();
664
+ if (next.join() !== [...this.detachedNotes].sort().join()) this.detachedNotes = next;
665
+ }
666
+
667
+ /** Where a thread sits, in words, for the rail. */
668
+ private noteAnchor(root: Note): NoteAnchorView {
669
+ const target = parseNoteTarget(root.target);
670
+ if (!target || target.kind === 'entry') return { label: __('This entry'), quote: '', detached: false };
671
+ if (target.kind === 'field') return { label: this.fieldLabel(target.field), quote: '', detached: false };
672
+ const at = noteBlock(target);
673
+ if (!at) return { label: this.fieldLabel(target.kind === 'text' ? target.path : ''), quote: root.quote, detached: this.detachedNotes.includes(root.id) };
674
+ const block = findBlock(this.blocks(at.field), at.block);
675
+ const option = block ? this.view?.blocks.find(entry => entry.name === block.type) : undefined;
676
+ const label = block ? option?.label ?? block.type : __('A removed block');
677
+ const summary = block ? blockSummary(block, this.previews, option) : '';
678
+ if (target.kind === 'block') return { label: summary ? `${label}: ${summary}` : label, quote: '', detached: !block };
679
+ return { label, quote: root.quote, detached: !block || this.detachedNotes.includes(root.id) };
680
+ }
681
+
682
+ @Client()
683
+ private startNote(target: string, range: NoteRange | null = null, quote = '') {
684
+ this.composer = { target, range, quote, parentId: null, body: '' };
685
+ this.editingNote = null;
686
+ this.activeNote = null;
687
+ this.notesFilter = 'open';
688
+ this.notesError = '';
689
+ this.notesOpen = true;
690
+ }
691
+
692
+ /** Open the rail on the notes of a field or a block: the first open thread there is chosen. */
693
+ @Client()
694
+ private showNotes(where: { field?: string; block?: string }) {
695
+ const first = this.openRoots().find(note => {
696
+ const target = parseNoteTarget(note.target);
697
+ if (!target) return false;
698
+ return where.block ? noteBlock(target)?.block === where.block : noteField(target) === where.field;
699
+ });
700
+ this.notesFilter = 'open';
701
+ this.notesOpen = true;
702
+ if (first) this.activeNote = first.id;
703
+ }
704
+
705
+ /** Choose a thread: the rail opens on it and the entry scrolls to where it sits. */
706
+ @Client()
707
+ private selectNote(id: string, options: { reveal?: boolean } = {}) {
708
+ const root = this.notes.find(note => note.id === id);
709
+ this.activeNote = id;
710
+ this.notesOpen = true;
711
+ if (root) this.notesFilter = root.status;
712
+ if (root && options.reveal !== false) void this.revealNote(root);
713
+ }
714
+
715
+ /** Scroll to a thread's place, on its tab, and flash it. */
716
+ @Client()
717
+ private async revealNote(root: Note) {
718
+ const target = parseNoteTarget(root.target);
719
+ if (!target || target.kind === 'entry') return;
720
+ const field = noteField(target);
721
+ const tab = field ? this.tabOf(field) : null;
722
+ if (tab && tab !== this.mode) { await this.showMode(tab); await new Promise(resolve => setTimeout(resolve, 50)); }
723
+ const block = noteBlock(target);
724
+ const element = document.querySelector<HTMLElement>(`.cms-note[data-note="${root.id}"]`)
725
+ ?? (block ? document.querySelector<HTMLElement>(`[data-block-tree-item="${block.block}"]`) : null)
726
+ ?? (field ? document.querySelector<HTMLElement>(`[data-field="${field}"]`) : null);
727
+ if (!element) return;
728
+ element.scrollIntoView({ block: 'center', behavior: 'smooth' });
729
+ element.classList.add('cms-note-flash');
730
+ setTimeout(() => element.classList.remove('cms-note-flash'), 2000);
731
+ }
732
+
733
+ @Client()
734
+ private async postNote() {
735
+ const composer = this.composer;
736
+ if (!composer || !this.room || !composer.body.trim()) return;
737
+ this.notesBusy = true;
738
+ this.notesError = '';
739
+ try {
740
+ const note = await this.room.note({ kind: 'create', target: composer.target, range: composer.range, quote: composer.quote, body: composer.body, parentId: composer.parentId });
741
+ this.composer = null;
742
+ if (note) {
743
+ this.applyNote({ kind: 'created', note, author: this.noteAuthors[note.userId] ?? { user: note.userId, name: __('You'), avatar: null, color: participantColor(note.userId) } });
744
+ this.activeNote = note.parentId ?? note.id;
745
+ }
746
+ } catch (error) { this.notesError = (error as Error).message || __('The note could not be saved.'); }
747
+ finally { this.notesBusy = false; }
748
+ }
749
+
750
+ @Client()
751
+ private async noteAction(action: NoteAction) {
752
+ if (!this.room) return;
753
+ this.notesBusy = true;
754
+ this.notesError = '';
755
+ try { await this.room.note(action); }
756
+ catch (error) { this.notesError = (error as Error).message || __('The note could not be changed.'); }
757
+ finally { this.notesBusy = false; }
758
+ }
759
+
760
+ @Client()
761
+ private async saveNoteEdit() {
762
+ const editing = this.editingNote;
763
+ if (!editing || !editing.body.trim()) return;
764
+ await this.noteAction({ kind: 'edit', id: editing.id, body: editing.body });
765
+ if (!this.notesError) this.editingNote = null;
766
+ }
767
+
768
+ /** A note change from the room, or this tab's own, applied once. */
769
+ @Client()
770
+ private applyNote(change: NoteChange) {
771
+ switch (change.kind) {
772
+ case 'created':
773
+ if (this.notes.some(note => note.id === change.note.id)) return;
774
+ this.noteAuthors = { ...this.noteAuthors, [change.author.user]: change.author };
775
+ this.notes = [...this.notes.map(note => note.id === change.note.parentId ? { ...note, updatedAt: change.note.createdAt } : note), change.note];
776
+ return;
777
+ case 'edited':
778
+ case 'status':
779
+ this.notes = this.notes.map(note => note.id === change.note.id ? change.note : note);
780
+ return;
781
+ case 'removed': {
782
+ const gone = new Set(change.ids);
783
+ this.notes = this.notes.filter(note => !gone.has(note.id));
784
+ for (const id of gone) this.noteRanges.delete(id);
785
+ if (this.activeNote && gone.has(this.activeNote)) this.activeNote = null;
786
+ if (this.composer?.parentId && gone.has(this.composer.parentId)) this.composer = null;
787
+ if (this.editingNote && gone.has(this.editingNote.id)) this.editingNote = null;
788
+ return;
789
+ }
790
+ case 'moved':
791
+ this.notes = this.notes.map(note => { const move = change.moves.find(entry => entry.id === note.id); return move ? { ...note, range: move.range } : note; });
792
+ return;
793
+ }
794
+ }
795
+
796
+ /** After a save, the places of the passages that moved are written back, so a reload finds them. */
797
+ @Client()
798
+ private persistNoteMoves() {
799
+ if (!this.room) return;
800
+ const moves = this.notes.filter(note => !note.parentId && note.target.startsWith('text:')).flatMap(note => {
801
+ const live = this.noteRanges.get(note.id);
802
+ return live && (live.from !== note.range?.from || live.to !== note.range?.to) ? [{ id: note.id, range: live }] : [];
803
+ });
804
+ if (moves.length) void this.room.note({ kind: 'move', moves }).catch(() => undefined);
805
+ }
806
+
807
+ private notesRailView(): TemplateResult | null {
808
+ if (this.id === 'new') return null;
809
+ return notesRail({
810
+ id: 'entry-notes', open: this.notesOpen, threads: noteThreads(this.notes), filter: this.notesFilter, people: this.noteAuthors, me: this.meId, admin: this.canRemoveNotes,
811
+ active: this.activeNote, composer: this.composer, editing: this.editingNote, mentionable: this.mentionable, busy: this.notesBusy, error: this.notesError,
812
+ anchor: root => this.noteAnchor(root),
813
+ onClose: () => { this.notesOpen = false; }, onFilter: filter => { this.notesFilter = filter; }, onSelect: id => this.selectNote(id),
814
+ onCompose: composer => { this.composer = composer; }, onSubmit: () => { void this.postNote(); },
815
+ onEdit: editing => { this.editingNote = editing; }, onSaveEdit: () => { void this.saveNoteEdit(); },
816
+ onResolve: id => { void this.noteAction({ kind: 'resolve', id }); }, onReopen: id => { void this.noteAction({ kind: 'reopen', id }); }, onRemove: id => { this.noteRemoval = id; },
817
+ });
818
+ }
819
+
820
+ private noteRemovalModal(): TemplateResult {
821
+ const note = this.noteRemoval ? this.notes.find(entry => entry.id === this.noteRemoval) : undefined;
822
+ return component(Modal, { open: !!note, size: 'max-w-md', 'aria-label': __('Remove note'), onOpenChange: (open: boolean) => { if (!open) this.noteRemoval = null; } }, note ? html`
823
+ <div class="space-y-4">
824
+ <h2 class="text-lg font-semibold text-foreground">${note.parentId ? __('Remove this reply?') : __('Remove this thread?')}</h2>
825
+ <p class="text-sm text-muted-foreground">${note.parentId ? __('The reply is deleted for everyone.') : __('The note and its replies are deleted for everyone.')}</p>
826
+ <div class="flex justify-end gap-2">
827
+ ${component(Button, { type: 'button', variant: 'outline', '@click': () => { this.noteRemoval = null; } }, __('Cancel'))}
828
+ ${component(Button, { type: 'button', variant: 'destructive', '@click': () => { this.noteRemoval = null; void this.noteAction({ kind: 'remove', id: note.id }); } }, __('Remove'))}
829
+ </div>
830
+ </div>` : html``);
831
+ }
832
+
833
+ /** The header's Notes button: opens the rail, with the count of open threads. */
834
+ private notesToggle(): TemplateResult | null {
835
+ if (this.id === 'new') return null;
836
+ const open = this.openRoots().length;
837
+ return html`<button type="button" class=${`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm cursor-pointer [&_svg]:size-4 ${this.notesOpen ? 'border-amber-500 bg-amber-500/10 text-foreground' : 'border-border bg-background text-foreground hover:bg-muted'}`}
838
+ aria-pressed=${this.notesOpen ? 'true' : 'false'} data-notes-toggle=${open} @click=${() => { this.notesOpen = !this.notesOpen; }}>
839
+ ${component(Icon, { entry: icon('notes'), size: 16 })}${__('Notes')}${open ? html`<span class="rounded-full bg-amber-500/15 px-1.5 text-xs font-medium text-amber-700 dark:text-amber-300">${open}</span>` : null}</button>`;
840
+ }
841
+
842
+ /** Media previews follow the values, a little after they changed. */
843
+ @Client()
844
+ private previewsSoon() {
845
+ if (this.previewRefresh) return;
846
+ this.previewRefresh = setTimeout(() => { this.previewRefresh = undefined; void this.refreshPreviews(this.values); }, 500);
847
+ }
848
+
849
+ /** Whether a field is one rich text document the room holds (a multiple field travels as one value). */
850
+ private sharedRichText(name: string): boolean {
851
+ const field = this.fieldOf(name);
852
+ return field?.kind === 'richtext' && !field.multiple && !this.view?.restricted.includes(name);
853
+ }
854
+
855
+ /** The rich text editor's part in the room, for a document at `path`. */
856
+ private collabFor(path: string | null): { collab?: RichTextFieldProps['collab'] } {
857
+ const room = this.room;
858
+ if (!room || !path) return {};
859
+ return { collab: { path, clientID: this.self, transport: room.transport(path), onSelection: (anchor: number, head: number) => this.announceSelection(path, anchor, head) } };
860
+ }
861
+
862
+ private myUser(): string {
863
+ return this.peers.find(peer => peer.peer === this.self)?.user ?? '';
864
+ }
865
+
866
+ /** Other users whose focus is in a field of the entry, by its presence anchor (not in a block). */
867
+ private peersIn(field: string): Someone[] {
868
+ const me = this.myUser();
869
+ return this.peers.filter(peer => peer.user !== me && peer.presence.field === field && !peer.presence.block);
870
+ }
871
+
872
+ /**
873
+ * A row around one synced control, named for presence (`data-field`) and, when another editor
874
+ * is in it, outlined in their color with a chip under its label. The sidebar's rows are named
875
+ * by their key (`status`, `parent`, a taxonomy's name) and the search box's by `seo.<key>`;
876
+ * the resource's own fields have `fieldRow`, group fields the `FieldGroupView`.
877
+ */
878
+ private tracked(field: string, body: TemplateResult, options: { label?: TemplateResult | null; class?: string; /** The control is one line of text: its note tools sit inside it, at the right. */ inline?: boolean } = {}): TemplateResult {
879
+ const here = this.peersIn(field);
880
+ const tools = this.noteTools(field);
881
+ const inline = options.inline === true && tools !== null;
882
+ return html`<div class=${`group ${options.class ?? 'space-y-1'}`} data-field=${field} style=${presenceOutline(here)}>
883
+ ${options.label ? html`<div class="flex items-center gap-3"><div class="min-w-0 flex-1">${options.label}</div>${inline ? null : tools}</div>` : inline ? null : tools}
884
+ ${here.length ? presenceChip(here, __('is here')) : null}${inline ? inlineNoteTools(body, tools) : body}</div>`;
885
+ }
886
+
887
+ /** Other users in each block, or dragging it, by block ID. */
888
+ private editingBlocks(): Record<string, Someone[]> {
889
+ const me = this.myUser();
890
+ const result: Record<string, Someone[]> = {};
891
+ for (const peer of this.peers) {
892
+ if (peer.user === me) continue;
893
+ for (const id of [peer.presence.block, peer.presence.dragging]) if (id) (result[id] ??= []).push(peer);
894
+ }
895
+ return result;
896
+ }
897
+
898
+ private participants(): Participant[] {
899
+ return groupPeers(this.peers);
900
+ }
901
+
902
+ private roomProps(): EntryRoom['props'] {
903
+ return {
904
+ onReady: (handle: RoomHandle) => this.onRoomReady(handle),
905
+ onSnapshot: (snapshot: RoomSnapshot, options: { initial: boolean; resets: readonly string[] }) => this.onSnapshot(snapshot, options),
906
+ onSet: (peer: string, field: string, value: unknown) => this.onRemoteSet(peer, field, value),
907
+ onTree: (peer: string, op: TreeOp, hash: string) => this.onRemoteTree(peer, op, hash),
908
+ onPeers: (peers: readonly PeerState[], self: string) => this.onPeers(peers, self),
909
+ onSaved: (by: string, rev: number) => this.onRemoteSaved(by, rev),
910
+ onNote: (change: NoteChange) => this.applyNote(change),
911
+ onStatus: (status: { connected: boolean; dirty: boolean; diverged: boolean; oversized: boolean }) => this.onRoomStatus(status),
912
+ };
913
+ }
914
+
915
+ // --- Autosave ----------------------------------------------------------------
916
+
917
+ onMount() {
918
+ this.autosaved = this.snapshot();
919
+ // The first save's outcome came in the address; shown, the address is the entry's alone, as a reload should not repeat it.
920
+ const url = new URL(window.location.href);
921
+ if (url.searchParams.has('saved')) { url.searchParams.delete('saved'); window.history.replaceState(window.history.state, '', url); }
922
+ // A saved entry is edited in its room, whose draft replaces the autosave and the reload restore.
923
+ if (this.id !== 'new') return;
924
+ this.autosaveTimer = setInterval(() => { void this.autosaveTick(); }, 30_000);
925
+ this.recoverDraft();
926
+ }
927
+
928
+ onCleanup() {
929
+ if (this.autosaveTimer) clearInterval(this.autosaveTimer);
930
+ if (this.presenceTimer) clearTimeout(this.presenceTimer);
931
+ if (this.previewRefresh) clearTimeout(this.previewRefresh);
932
+ }
933
+
934
+ /** Where unsaved values wait out a reload: one key per editor URL. */
935
+ private draftKey(): string {
936
+ return `cms:draft:${window.location.pathname}`;
937
+ }
938
+
939
+ /** Before a reload or a close, unsaved values go to session storage; a saved editor leaves nothing. */
940
+ @OnWindow('beforeunload')
941
+ keepDraft() {
942
+ try {
943
+ if (this.unsaved && this.view && !this.room) window.sessionStorage.setItem(this.draftKey(), JSON.stringify({ at: Date.now(), values: this.values }));
944
+ else window.sessionStorage.removeItem(this.draftKey());
945
+ } catch { /* storage may be unavailable; the autosave still has the draft */ }
946
+ }
947
+
948
+ /** After a reload, recent unsaved values come straight back; the autosave stays as the fallback. */
949
+ @Client()
950
+ private recoverDraft() {
951
+ let stored: { at?: number; values?: EditorValues } | null = null;
952
+ try {
953
+ const raw = window.sessionStorage.getItem(this.draftKey());
954
+ window.sessionStorage.removeItem(this.draftKey());
955
+ stored = raw ? JSON.parse(raw) as { at?: number; values?: EditorValues } : null;
956
+ } catch { return; }
957
+ if (!stored?.values || typeof stored.values !== 'object' || typeof stored.at !== 'number' || Date.now() - stored.at > 15 * 60_000) return;
958
+ this.values = { ...this.values, ...stored.values };
959
+ this.unsaved = true;
960
+ this.dirty = true;
961
+ this.autosaveOffer = null;
962
+ this.message = __('Your unsaved changes were kept through the reload. Save to keep them.');
963
+ void this.refreshPreviews(this.values);
964
+ }
965
+
966
+ /** Published entries of the site whose text matches the title: candidates for internal links, this entry left out. */
967
+ @Server({ input: input.args(input.string({ maxLength: 2000 }), input.string({ maxLength: 2000 })) })
968
+ async loadLinkSuggestions(title: string, exclude: string) {
969
+ const cms = this.c.get('cms');
970
+ const query = title.replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter(word => word.length > 2).slice(0, 8).join(' ');
971
+ if (!query) { this.linkSuggestions = []; return; }
972
+ const found: { title: string; url: string; collection: string }[] = [];
973
+ for (const collection of cms.collections()) {
974
+ if (typeof collection.path !== 'string' || found.length >= 8) continue;
975
+ const resource = cms.resourceById(`cms/${collection.name}`);
976
+ if (!Object.values(resource.fields).some(field => field.search)) continue;
977
+ try {
978
+ const principal = this.c.get('principal');
979
+ const records = openMatches(cms, resource.id, await cms.resource(resource.id).search(query, { limit: 6, ...(collection.publishable === false ? {} : { where: { status: 'published' } }) }, { principal }), principal).filter(record => record.id !== exclude);
980
+ const urls = await cms.entryUrls(collection, records);
981
+ for (const record of records) if (urls.get(record.id)) found.push({ title: recordTitle(record, 'title'), url: urls.get(record.id)!, collection: collection.singular });
982
+ } catch (error) { if (!isCmsError(error)) throw error; }
983
+ }
984
+ this.linkSuggestions = found.slice(0, 8);
985
+ }
986
+
987
+ /** Previews of the media the recovered values name. */
988
+ @Server({ input: input.args(input.record()) })
989
+ async refreshPreviews(values: EditorValues) {
990
+ const cms = this.c.get('cms');
991
+ this.previews = await mediaPreviews(cms, values, await this.serverView());
992
+ }
993
+
994
+ /** The values as the autosave stores them; a control that cannot be serialized counts as unchanged. */
995
+ private snapshot(): string {
996
+ try { return JSON.stringify(this.values); } catch { return this.autosaved; }
997
+ }
998
+
999
+ /**
1000
+ * Store the values when they changed since the last load, save or autosave. A plain request
1001
+ * to the autosave API, not a server method: nothing of this page's state comes back, so the
1002
+ * editor keeps its focus, selection and any keystrokes in flight.
1003
+ */
1004
+ @Client()
1005
+ async autosaveTick() {
1006
+ if (this.saving || this.autosaving || !this.view) return;
1007
+ const snapshot = this.snapshot();
1008
+ if (snapshot === this.autosaved) { this.dirty = false; return; }
1009
+ this.autosaving = true;
1010
+ try {
1011
+ const response = await fetch(`/api/cms/content/${this.route}/${this.id}/autosave`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: snapshot, credentials: 'same-origin' });
1012
+ if (!response.ok) throw new Error(`autosave ${response.status}`);
1013
+ const { at } = await response.json() as { at: number };
1014
+ this.autosaved = snapshot;
1015
+ this.dirty = false;
1016
+ this.autosavedAt = at;
1017
+ } catch (error) {
1018
+ console.warn('[cms] the draft could not be autosaved', error);
1019
+ } finally { this.autosaving = false; }
1020
+ }
1021
+
1022
+ /**
1023
+ * Server methods act on the collection and entry the URL names, never on the client's state.
1024
+ * The first save of a new entry stays on `/new` until the browser's URL follows, so `/new`
1025
+ * keeps the saved ID the state carries; every method checks the principal's rights to it.
1026
+ */
1027
+ private fromRoute(): void {
1028
+ this.route = this.c.req.param('collection') ?? '';
1029
+ const id = this.c.req.param('id') ?? 'new';
1030
+ if (id !== 'new' || !this.id) this.id = id;
1031
+ }
1032
+
1033
+ /** This route's editor view as the host builds it, once per request: fields, blocks and taxonomies never come from the client. */
1034
+ private routeView?: Promise<EditorView>;
1035
+ private serverView(): Promise<EditorView> {
1036
+ this.fromRoute();
1037
+ return this.routeView ??= editorView(this.c.get('cms'), this.route, this.c.get('principal'));
1038
+ }
1039
+
1040
+ /**
1041
+ * Refuse a server method unless the principal may edit this entry, or create one for a new
1042
+ * entry: the page itself only asks for a dashboard account.
1043
+ */
1044
+ private async assertEditor(): Promise<void> {
1045
+ this.fromRoute();
1046
+ const cms = this.c.get('cms');
1047
+ const principal = this.c.get('principal');
1048
+ const { resource } = routeResource(cms, this.route);
1049
+ if (this.id === 'new') {
1050
+ if (evaluateRule(resource.access.create, principal) === 'deny') throw new ClientVisibleError(__('You cannot create entries here.'));
1051
+ return;
1052
+ }
1053
+ const record = await cms.resource(resource.id).get(this.id, { principal });
1054
+ if (!record || !cms.resource(resource.id).canUpdate(record, principal)) throw new ClientVisibleError(__('This entry does not exist or you cannot edit it.'));
1055
+ }
1056
+
1057
+ /** The resource this editor's route names, read on the server. */
1058
+ private resourceId(): string {
1059
+ this.fromRoute();
1060
+ return routeResource(this.c.get('cms'), this.route).resource.id;
1061
+ }
1062
+
1063
+ @Server()
1064
+ async storeAutosave(values: EditorValues) {
1065
+ this.autosavedAt = await this.c.get('cms').autosave(this.resourceId(), this.id, this.c.get('principal'), values);
1066
+ }
1067
+
1068
+ /** Restore the autosave; the restored values are what is stored, so the next tick sends nothing. */
1069
+ @Client()
1070
+ async restore() {
1071
+ await this.restoreAutosave();
1072
+ this.autosaved = this.snapshot();
1073
+ this.unsaved = true;
1074
+ }
1075
+
1076
+ @Server()
1077
+ async restoreAutosave() {
1078
+ const cms = this.c.get('cms');
1079
+ const autosave = await cms.latestAutosave(this.resourceId(), this.id, this.c.get('principal'));
1080
+ if (autosave?.data && typeof autosave.data === 'object' && !Array.isArray(autosave.data)) {
1081
+ this.values = { ...this.values, ...(autosave.data as EditorValues) };
1082
+ this.previews = await mediaPreviews(cms, this.values, await this.serverView());
1083
+ this.message = __('The autosave is restored. Save to keep it.');
1084
+ }
1085
+ this.autosaveOffer = null;
1086
+ }
1087
+
1088
+ @Server()
1089
+ async dismissAutosave() {
1090
+ await this.c.get('cms').discardAutosave(this.resourceId(), this.id, this.c.get('principal'));
1091
+ this.autosaveOffer = null;
1092
+ }
1093
+
1094
+ /** Leaving with unsaved changes asks first; they stay in the autosave either way. In a connected room the draft is kept there, so no prompt. */
1095
+ @PreventNavigation()
1096
+ @Client()
1097
+ confirmLeave(): boolean {
1098
+ return this.unsaved && !this.roomStatus.connected && !window.confirm(__('Leave the editor? Your latest changes are not saved.'));
1099
+ }
1100
+
1101
+ // --- Previews ------------------------------------------------------------------
1102
+
1103
+ /** Open the preview with the current changes: they are autosaved first. */
1104
+ @Client()
1105
+ async openPreview() {
1106
+ if (!this.view || this.id === 'new') return;
1107
+ const preview = window.open('about:blank', '_blank');
1108
+ try {
1109
+ await this.storeAutosave(this.values);
1110
+ this.dirty = false;
1111
+ this.autosaved = this.snapshot();
1112
+ if (preview) preview.location.href = `/preview/${this.view.route}/${this.id}`;
1113
+ } catch { preview?.close(); this.message = ''; this.error = __('The preview could not be prepared.'); }
1114
+ }
1115
+
1116
+ @Server()
1117
+ async createPreviewLink() {
1118
+ const cms = this.c.get('cms');
1119
+ try {
1120
+ const link = await cms.createPreviewLink(this.resourceId(), this.id, this.c.get('principal'));
1121
+ this.previewLink = `${siteOrigin(this.c)}/preview/${this.route}/${this.id}?token=${link.token}`;
1122
+ this.previewLinks = await cms.previews.count(this.resourceId(), this.id);
1123
+ } catch (error) { this.error = isCmsError(error) ? error.message : __('The link could not be created.'); }
1124
+ }
1125
+
1126
+ @Server()
1127
+ async revokePreviewLinks() {
1128
+ const cms = this.c.get('cms');
1129
+ await cms.revokePreviewLinks(this.resourceId(), this.id, this.c.get('principal'));
1130
+ this.previewLink = '';
1131
+ this.previewLinks = 0;
1132
+ }
1133
+
1134
+ @Client()
1135
+ async copyPreviewLink() {
1136
+ this.message = '';
1137
+ this.error = '';
1138
+ try { await navigator.clipboard.writeText(this.previewLink); this.message = __('Link copied.'); }
1139
+ catch { this.error = __('Copy the link from the box.'); }
1140
+ }
1141
+
1142
+ // --- Translations --------------------------------------------------------------
1143
+
1144
+ /** Open the entry's translation in a language, starting it as a draft copy when there is none. */
1145
+ @Server()
1146
+ async translate(locale: string) {
1147
+ const cms = this.c.get('cms');
1148
+ this.fromRoute();
1149
+ try {
1150
+ const translation = await cms.translateEntry(this.route, this.id, locale, this.c.get('principal'));
1151
+ return this.redirect(`/dashboard/content/${this.route}/${translation.id}`);
1152
+ } catch (error) { this.error = isCmsError(error) ? error.message : __('The translation could not be started.'); }
1153
+ }
1154
+
1155
+ // --- Patterns ------------------------------------------------------------------
1156
+
1157
+ @Client()
1158
+ async openPatterns(field: string) {
1159
+ this.patternPicker = { open: true, field, starter: false };
1160
+ await this.findPatterns();
1161
+ }
1162
+
1163
+ @Server()
1164
+ async findPatterns() {
1165
+ this.fromRoute();
1166
+ await this.loadPatterns(this.route, false);
1167
+ }
1168
+
1169
+ /** Insert a pattern: synced ones as a reference that follows the pattern, others as a copy. */
1170
+ /** Add a pattern to the content: a synced one as a Pattern block, otherwise a copy of its blocks. A starting layout replaces the content. */
1171
+ @Client()
1172
+ async insertPattern(id: string, copy: boolean) {
1173
+ const picker = this.patternPicker;
1174
+ this.patternPicker = { open: false, field: '', starter: false };
1175
+ const choice = this.patternChoices.find(entry => entry.id === id);
1176
+ const view = this.view;
1177
+ if (!choice || !view) return;
1178
+ const field = picker.starter ? contentField(view) ?? '' : picker.field;
1179
+ const content = await this.patternContent(id);
1180
+ if (!field || !content) return;
1181
+ this.patternTitles = { ...this.patternTitles, [id]: choice.title };
1182
+ const added: EditorBlock[] = choice.synced && !copy ? [{ _id: blockId(), type: 'core/pattern', data: { pattern: id } }] : editorBlocks(content as EditorBlock[], view.blocks);
1183
+ this.set(field, picker.starter ? added : [...this.blocks(field), ...added]);
1184
+ }
1185
+
1186
+ @Server()
1187
+ async patternContent(id: string): Promise<Block[] | null> {
1188
+ return patternBlocks(this.c.get('cms'), id, this.c.get('principal'));
1189
+ }
1190
+
1191
+ @Client()
1192
+ setSlug(value: string) {
1193
+ this.slugTouched = true;
1194
+ this.set('slug', value.toLowerCase().replace(/\s+/g, '-'));
1195
+ }
1196
+
1197
+ @Client()
1198
+ toggleTerm(taxonomy: string, id: string, checked: boolean) {
1199
+ const current = (this.values[taxonomy] as string[] | undefined) ?? [];
1200
+ this.set(taxonomy, checked ? [...new Set([...current, id])] : current.filter(entry => entry !== id));
1201
+ }
1202
+
1203
+ @Client()
1204
+ addTags(taxonomy: string) {
1205
+ const names = (this.tagDrafts[taxonomy] ?? '').split(',').map(name => name.trim()).filter(Boolean);
1206
+ const current = (this.values[taxonomy] as string[] | undefined) ?? [];
1207
+ const known = new Set(current.map(name => name.toLowerCase()));
1208
+ this.set(taxonomy, [...current, ...names.filter(name => !known.has(name.toLowerCase()))]);
1209
+ this.tagDrafts = { ...this.tagDrafts, [taxonomy]: '' };
1210
+ }
1211
+
1212
+ @Client()
1213
+ removeTag(taxonomy: string, name: string) {
1214
+ this.set(taxonomy, ((this.values[taxonomy] as string[] | undefined) ?? []).filter(entry => entry !== name));
1215
+ }
1216
+
1217
+ /** Tabs and previews are kept by the editor's ID, so a block's Markdown in the panel previews its own text, not an entry field's. */
1218
+ @Client()
1219
+ async showTab(id: string, tab: 'write' | 'preview', text: string) {
1220
+ this.tabs = { ...this.tabs, [id]: tab };
1221
+ if (tab === 'preview') await this.preview(id, text);
1222
+ }
1223
+
1224
+ @Server({ input: input.args(input.string({ minLength: 1, maxLength: 200 }), input.string({ maxLength: 100_000 })) })
1225
+ async preview(id: string, text: string) {
1226
+ this.rendered = { ...this.rendered, [id]: renderMarkdown(text.slice(0, 200_000)) };
1227
+ }
1228
+
1229
+ /** Wrap the selection of the Markdown editor `id` (its text is `text`) in `before` and `after`. */
1230
+ @Client()
1231
+ format(id: string, text: string, change: (value: string) => void, before: string, after = '', placeholder = '') {
1232
+ const element = document.getElementById(id) as HTMLTextAreaElement | null;
1233
+ const start = element?.selectionStart ?? text.length;
1234
+ const end = element?.selectionEnd ?? text.length;
1235
+ const selected = text.slice(start, end) || placeholder;
1236
+ change(`${text.slice(0, start)}${before}${selected}${after}${text.slice(end)}`);
1237
+ requestAnimationFrame(() => { element?.focus(); element?.setSelectionRange(start + before.length, start + before.length + selected.length); });
1238
+ }
1239
+
1240
+ // --- Blocks ----------------------------------------------------------------
1241
+
1242
+ private blocks(field: string): EditorBlock[] {
1243
+ return (this.values[field] as EditorBlock[] | undefined) ?? [];
1244
+ }
1245
+
1246
+ @Client()
1247
+ setBlock(field: string, id: string, key: string, value: unknown) {
1248
+ this.set(field, updateBlock(this.blocks(field), id, block => ({ ...block, data: { ...block.data, [key]: value } })));
1249
+ }
1250
+
1251
+ // --- Media -----------------------------------------------------------------
1252
+
1253
+ @Client()
1254
+ async openPicker(target: MediaTarget) {
1255
+ this.picker = { ...this.picker, open: true, target, kind: target.fileKind ?? 'image' };
1256
+ this.pickerErrors = [];
1257
+ await this.findMedia(this.picker.search, this.picker.kind);
1258
+ }
1259
+
1260
+ @Client()
1261
+ closePicker() {
1262
+ this.picker = { ...this.picker, open: false, target: null };
1263
+ }
1264
+
1265
+ @Server({ input: input.args(input.string({ maxLength: 2000 }), input.string({ maxLength: 2000 })) })
1266
+ async findMedia(search: string, kind: string) {
1267
+ await this.assertEditor();
1268
+ const files = this.c.get('cms').files;
1269
+ if (!files) { this.picker = { ...this.picker, items: [] }; return; }
1270
+ const page = await files.list({ search: search.slice(0, 100), limit: 40, ...(kind ? { kind: kind as MediaKind } : {}) });
1271
+ this.picker = { ...this.picker, search, kind, items: page.items.map(file => ({ id: file.id, url: `/media/${file.id}/${encodeURIComponent(file.name)}`, title: file.title, alt: file.alt,
1272
+ contentType: file.contentType, width: file.width, height: file.height, size: formatBytes(file.size), name: file.name })) };
1273
+ }
1274
+
1275
+ @Client()
1276
+ choose(file: MediaPreview) {
1277
+ const target = this.picker.target;
1278
+ if (!target) return;
1279
+ this.previews = { ...this.previews, [file.id]: file };
1280
+ if (target.style) {
1281
+ if (this.blockDialog) this.setDialogStyle({ ...this.blockDialog.style, style: { ...this.blockDialog.style.style, [target.style]: file.id } });
1282
+ } else if (target.richText) {
1283
+ const editor = richTextEditors.get(target.editor ?? `field-${target.field}`);
1284
+ if (mediaKind(file.contentType) === 'image') editor?.insertImage({ src: file.url, alt: file.alt || file.title, mediaId: file.id });
1285
+ else editor?.insertLink(file.title || __('Download'), file.url);
1286
+ } else if (target.group && target.key) {
1287
+ this.setGroup(target.field, target.key, file.id);
1288
+ } else if (target.rows?.length && target.key) {
1289
+ const current = this.rowValue(target.field, target.rows, target.key);
1290
+ this.setRowValue(target.field, target.rows, target.key, target.multiple ? [...new Set([...(Array.isArray(current) ? current as string[] : []), file.id])] : file.id);
1291
+ } else if (target.insert) {
1292
+ const markdown = mediaKind(file.contentType) === 'image' ? `![${file.alt || file.title}](${file.url})` : `[${file.title}](${file.url})`;
1293
+ if (target.dialog && target.key && this.blockDialog) this.format(target.editor ?? '', String(this.blockDialog.values[target.key] ?? ''), value => this.setDialogValue(target.key!, value), `${markdown}\n`);
1294
+ else this.format(target.editor ?? `field-${target.field}`, String(this.values[target.field] ?? ''), value => this.set(target.field, value), `${markdown}\n`);
1295
+ } else if (target.dialog && target.key && this.blockDialog) {
1296
+ const current = this.blockDialog.values[target.key];
1297
+ this.setDialogValue(target.key, target.multiple ? [...new Set([...(Array.isArray(current) ? current as string[] : []), file.id])] : file.id);
1298
+ } else if (target.block !== undefined && target.key) {
1299
+ const current = findBlock(this.blocks(target.field), target.block)?.data[target.key];
1300
+ this.setBlock(target.field, target.block, target.key, target.multiple ? [...new Set([...(Array.isArray(current) ? current : []), file.id])] : file.id);
1301
+ } else {
1302
+ const current = this.values[target.field];
1303
+ this.set(target.field, target.multiple ? [...new Set([...(Array.isArray(current) ? current as string[] : []), file.id])] : file.id);
1304
+ }
1305
+ if (!target.multiple) this.closePicker();
1306
+ }
1307
+
1308
+ @Client()
1309
+ async uploadInPicker(event: Event) {
1310
+ const input = event.currentTarget as HTMLInputElement;
1311
+ const files = [...(input.files ?? [])];
1312
+ this.pickerErrors = [];
1313
+ for (const file of files) {
1314
+ try { this.choose(await uploadFile(file)); }
1315
+ catch (error) { this.pickerErrors = [...this.pickerErrors, (error as Error).message || __('The upload failed.')]; }
1316
+ }
1317
+ input.value = '';
1318
+ await this.findMedia('', this.picker.kind);
1319
+ }
1320
+
1321
+ // --- Blocks in rich text ---------------------------------------------------
1322
+
1323
+ @Client()
1324
+ insertRichBlock(field: string, type: string, editorId?: string) {
1325
+ const option = this.view?.blocks.find(block => block.name === type);
1326
+ const editor = richTextEditors.get(editorId ?? `field-${field}`);
1327
+ if (!option || !editor) return;
1328
+ const values = blockDefaults(option);
1329
+ const block: EmbeddedBlock = { _id: blockId(), type, data: editorInput(option.fields, values).input };
1330
+ editor.insertBlock(block);
1331
+ if (option.fields.length) this.blockDialog = { field, id: block._id, type, values, errors: {}, embedded: true, tab: 'general', style: styleValues({}), ...(editorId ? { editor: editorId } : {}) };
1332
+ }
1333
+
1334
+ @Client()
1335
+ editRichBlock(field: string, block: EmbeddedBlock, editorId?: string) {
1336
+ const empty = { tab: 'general' as const, style: styleValues({}), ...(editorId ? { editor: editorId } : {}) };
1337
+ if (block.type === 'core/pattern') { this.blockDialog = { field, id: block._id, type: block.type, values: { pattern: block.data.pattern }, errors: {}, embedded: true, ...empty }; return; }
1338
+ const option = this.view?.blocks.find(entry => entry.name === block.type);
1339
+ if (!option) { this.message = ''; this.error = __('This block type is no longer available.'); return; }
1340
+ this.blockDialog = { field, id: block._id, type: block.type, errors: {}, embedded: true, ...empty,
1341
+ values: Object.fromEntries(option.fields.map(entry => [entry.name, controlValue(entry, block.data[entry.name] ?? entry.defaultValue)])) };
1342
+ }
1343
+
1344
+ /** Open a block of a blocks field in the side panel: its settings on the General tab, its style on the Style tab. */
1345
+ @Client()
1346
+ editTreeBlock(field: string, id: string) {
1347
+ const block = findBlock(this.blocks(field), id);
1348
+ const option = this.view?.blocks.find(entry => entry.name === block?.type);
1349
+ if (block?.type === 'core/pattern') { this.blockDialog = { field, id, type: block.type, values: { pattern: block.data.pattern }, errors: {}, embedded: false, tab: 'general', style: styleValues({}) }; return; }
1350
+ if (!block || !option) return;
1351
+ this.blockDialog = { field, id, type: block.type, errors: {}, embedded: false, tab: 'general', style: styleValues(block), ...(block.when ? { when: block.when } : {}),
1352
+ values: Object.fromEntries(option.fields.filter(entry => entry.kind !== 'richtext').map(entry => [entry.name, block.data[entry.name] ?? controlValue(entry, entry.defaultValue)])) };
1353
+ }
1354
+
1355
+ @Client()
1356
+ setDialogValue(name: string, value: unknown) {
1357
+ if (!this.blockDialog) return;
1358
+ this.applyBlockDialog({ ...this.blockDialog, values: { ...this.blockDialog.values, [name]: value }, errors: { ...this.blockDialog.errors, [name]: '' } });
1359
+ }
1360
+
1361
+ @Client()
1362
+ setDialogStyle(style: StyleValues) {
1363
+ if (this.blockDialog) this.applyBlockDialog({ ...this.blockDialog, style });
1364
+ }
1365
+
1366
+ @Client()
1367
+ setDialogCondition(when: BlockCondition | null) {
1368
+ if (!this.blockDialog) return;
1369
+ const { when: _previous, ...rest } = this.blockDialog;
1370
+ this.applyBlockDialog(when ? { ...rest, when } : rest);
1371
+ }
1372
+
1373
+ @Client()
1374
+ showDialogTab(tab: BlockTab) {
1375
+ if (this.blockDialog) this.blockDialog = { ...this.blockDialog, tab };
1376
+ }
1377
+
1378
+ /**
1379
+ * The panel's state goes into its block at once: an embedded block back into its rich text,
1380
+ * a tree block into its field with its style and condition. A value its field cannot take
1381
+ * stays in the panel with its message; saving checks what is required.
1382
+ */
1383
+ @Client()
1384
+ applyBlockDialog(dialog: BlockDialog) {
1385
+ const option = this.view?.blocks.find(block => block.name === dialog.type);
1386
+ if (!option) return;
1387
+ if (dialog.embedded) {
1388
+ const { input, errors } = editorInput(option.fields, dialog.values);
1389
+ this.blockDialog = { ...dialog, errors: { ...dialog.errors, ...errors } };
1390
+ richTextEditors.get(dialog.editor ?? `field-${dialog.field}`)?.updateBlock(dialog.id, input);
1391
+ return;
1392
+ }
1393
+ const fields = option.fields.filter(entry => entry.kind !== 'richtext');
1394
+ const { input, errors } = editorInput(fields, dialog.values);
1395
+ // A valid new ID under Advanced re-keys the block; the panel follows it.
1396
+ const taken = this.otherBlockIds(dialog.field, dialog.id);
1397
+ const id = blockIdOf({ _id: dialog.id }, dialog.style, taken);
1398
+ this.blockDialog = { ...dialog, id, errors: { ...dialog.errors, ...errors } };
1399
+ // Rich text stays as it is in the tree; the panel's values replace the rest, and the condition follows the panel.
1400
+ this.set(dialog.field, updateBlock(this.blocks(dialog.field), dialog.id, block => {
1401
+ const { when: _previous, ...rest } = block;
1402
+ return withStyle({ ...rest, ...(dialog.when ? { when: dialog.when } : {}), data: { ...Object.fromEntries(Object.entries(block.data).filter(([name]) => option.fields.find(entry => entry.name === name)?.kind === 'richtext')), ...input } }, dialog.style, taken);
1403
+ }));
1404
+ }
1405
+
1406
+ /** The IDs of a field's blocks apart from one, which a custom block ID may not repeat. */
1407
+ private otherBlockIds(field: string, except: string): ReadonlySet<string> {
1408
+ return new Set(flattenBlocks(this.blocks(field)).map(block => block._id).filter(id => id !== except));
1409
+ }
1410
+
1411
+ /** Replace a synced pattern in the content with a copy of its blocks, which no longer follow the pattern. */
1412
+ @Client()
1413
+ async detachPattern() {
1414
+ const dialog = this.blockDialog;
1415
+ if (!dialog || dialog.embedded || !this.view) return;
1416
+ this.blockDialog = null;
1417
+ const content = await this.patternContent(String(dialog.values.pattern ?? ''));
1418
+ if (!content) return;
1419
+ const copy = editorBlocks(content as EditorBlock[], this.view.blocks);
1420
+ const replace = (blocks: EditorBlock[]): EditorBlock[] => blocks.flatMap(block => block._id === dialog.id ? copy : [block.children ? { ...block, children: replace(block.children) } : block]);
1421
+ this.set(dialog.field, replace(this.blocks(dialog.field)));
1422
+ }
1423
+
1424
+ // --- Terms -----------------------------------------------------------------
1425
+
1426
+ @Server()
1427
+ async addTerm(taxonomy: string, name: string, parent: string) {
1428
+ const cms = this.c.get('cms');
1429
+ try {
1430
+ const view = await this.serverView();
1431
+ // Only a taxonomy the collection has: the client names it.
1432
+ if (!view.taxonomies.some(entry => entry.name === taxonomy)) throw new ClientVisibleError(__('This collection has no such taxonomy.'));
1433
+ const term = await cms.taxonomies.create(taxonomy, { name, parent: parent || null }, { principal: this.c.get('principal') });
1434
+ this.view = { ...view, taxonomies: await Promise.all(view.taxonomies.map(async entry => entry.name === taxonomy ? { ...entry, terms: await termOptions(cms, taxonomy) } : entry)) };
1435
+ this.values = { ...this.values, [taxonomy]: [...((this.values[taxonomy] as string[] | undefined) ?? []), term.id] };
1436
+ this.termDrafts = { ...this.termDrafts, [taxonomy]: { name: '', parent: '' } };
1437
+ } catch (error) {
1438
+ this.error = isCmsError(error) || error instanceof ClientVisibleError ? error.message : __('The term could not be added.');
1439
+ }
1440
+ }
1441
+
1442
+ // --- Saving ----------------------------------------------------------------
1443
+
1444
+ @Client()
1445
+ async submit(intent: SaveIntent) {
1446
+ // A blank title is caught here, before the request; the server refuses it too.
1447
+ const title = this.view?.titleField ?? '';
1448
+ if (this.view?.titleRequired && intent !== 'trash' && !String(this.values[title] ?? '').trim()) {
1449
+ this.errors = { ...this.errors, [title]: __('Enter a title.') };
1450
+ this.message = '';
1451
+ this.error = __('Enter a title before saving.');
1452
+ document.getElementById('field-title')?.focus();
1453
+ return;
1454
+ }
1455
+ this.saving = true;
1456
+ this.error = '';
1457
+ this.message = '';
1458
+ // In a room, save what everyone wrote: the room's draft, apart from this tab's changes still on their way.
1459
+ if (this.room) { try { this.onSnapshot(await this.room.fresh(), { initial: false, resets: [] }); } catch { /* save what this tab holds */ } }
1460
+ try { await this.save(this.values, intent, this.rev); }
1461
+ finally { this.saving = false; }
1462
+ if (this.error) this.revealErrorTab();
1463
+ else {
1464
+ this.dirty = false;
1465
+ this.unsaved = false;
1466
+ this.autosaved = this.snapshot();
1467
+ void this.announceSaved();
1468
+ this.persistNoteMoves();
1469
+ void this.settleUrl();
1470
+ }
1471
+ }
1472
+
1473
+ /**
1474
+ * After the first save, the editor opens at the entry's own address, where its room is. The
1475
+ * outcome travels as `saved`, so the page shows it again, and leaves the address once shown.
1476
+ */
1477
+ @Client()
1478
+ private async settleUrl() {
1479
+ if (this.id === 'new' || !window.location.pathname.endsWith('/new')) return;
1480
+ const query = new URLSearchParams(window.location.search);
1481
+ query.set('saved', this.message === __('Published.') ? 'published' : this.message === __('Scheduled.') ? 'scheduled' : this.message === __('Submitted for review.') ? 'pending' : '1');
1482
+ await this.navigate(`/dashboard/content/${this.route}/${this.id}?${query}${window.location.hash}`, { history: 'replace' });
1483
+ // The same page stays mounted through the navigation, so the address is settled here, not in `onMount`.
1484
+ const url = new URL(window.location.href);
1485
+ if (url.searchParams.has('saved')) { url.searchParams.delete('saved'); window.history.replaceState(window.history.state, '', url); }
1486
+ }
1487
+
1488
+ @Server()
1489
+ async save(values: EditorValues, intent: SaveIntent, rev: number) {
1490
+ const cms = this.c.get('cms');
1491
+ this.errors = {};
1492
+ this.fromRoute();
1493
+ try {
1494
+ const record = await saveEntry(cms, this.route, this.id === 'new' ? null : this.id, values, intent, rev, this.c.get('principal'));
1495
+ // A new entry becomes this editor's entry: the page stays, and the browser's URL follows.
1496
+ if (this.id === 'new') this.id = record.id;
1497
+ await this.refreshSaved(cms, record, intent);
1498
+ } catch (error) {
1499
+ this.errors = fieldErrors(error);
1500
+ this.error = isCmsError(error) ? error.message : __('The entry could not be saved.');
1501
+ }
1502
+ }
1503
+
1504
+
1505
+ /** What the editor shows after a write: the saved values, the status, the URL and the revisions. */
1506
+ private async refreshSaved(cms: CmsHost, record: RecordShape, intent: SaveIntent) {
1507
+ this.rev = record.rev;
1508
+ const view = await this.serverView();
1509
+ const before = this.savedStatus;
1510
+ this.savedStatus = String(record.status ?? '');
1511
+ this.values = await entryValues(cms, view, record);
1512
+ this.previews = await mediaPreviews(cms, this.values, view);
1513
+ const collection = cms.resourceById(view.resource).owner === 'cms' ? cms.collection(cms.resourceById(view.resource).name) : null;
1514
+ const url = collection ? (await cms.entryUrls(collection, [record])).get(record.id) ?? null : null;
1515
+ this.meta = { ...this.meta, updatedAt: record.updatedAt, url: view.publishable && record.status !== 'published' ? null : url };
1516
+ this.autosaveOffer = null;
1517
+ this.message = intent === 'trash' ? __('Moved to the trash.') : intent === 'restore' ? __('Restored as a draft.')
1518
+ : record.status === 'scheduled' ? __('Scheduled.') : record.status === 'published' && before !== 'published' ? __('Published.')
1519
+ : record.status === 'pending' && before !== 'pending' ? __('Submitted for review.') : __('Saved.');
1520
+ await this.loadRevisions(record.id);
1521
+ if (this.mode === 'json' || this.json) { this.json = await entryJson(cms, this.route, record); this.jsonDirty = false; }
1522
+ }
1523
+
1524
+ @Server()
1525
+ async loadJson() {
1526
+ const cms = this.c.get('cms');
1527
+ try {
1528
+ await this.assertEditor();
1529
+ const { resource } = routeResource(cms, this.route);
1530
+ const record = await cms.resource(resource.id).get(this.id, { principal: this.c.get('principal') });
1531
+ if (!record) { this.error = __('This entry does not exist or you cannot read it.'); return; }
1532
+ this.json = await entryJson(cms, this.route, record);
1533
+ this.jsonDirty = false;
1534
+ } catch (error) {
1535
+ this.error = isCmsError(error) || error instanceof ClientVisibleError ? error.message : __('The entry could not be loaded.');
1536
+ }
1537
+ }
1538
+
1539
+ @Server()
1540
+ async applyJson(text: string, rev: number) {
1541
+ const cms = this.c.get('cms');
1542
+ this.errors = {};
1543
+ this.error = '';
1544
+ this.fromRoute();
1545
+ try {
1546
+ const record = await applyEntryJson(cms, this.route, this.id, text, rev, this.c.get('principal'));
1547
+ await this.refreshSaved(cms, record, 'update');
1548
+ } catch (error) {
1549
+ this.errors = fieldErrors(error);
1550
+ this.error = isCmsError(error) ? error.message : __('The entry could not be saved.');
1551
+ }
1552
+ }
1553
+
1554
+ /** The tabs this entry has: the layout's, then JSON for a saved entry. */
1555
+ private editorTabs(): string[] {
1556
+ return [...(this.view?.layout.tabs.map(tab => tab.id) ?? ['edit']), ...(this.id !== 'new' ? ['json'] : [])];
1557
+ }
1558
+
1559
+ /** The tab a field's box is on, so an error can open it; null for the sidebar's boxes, which every tab shows. */
1560
+ private tabOf(name: string): string | null {
1561
+ const view = this.view;
1562
+ if (!view) return null;
1563
+ const groups = view.groups.map(group => ({ id: group.id, blocks: plainBlocks(group.blocks) }));
1564
+ for (const tab of view.layout.tabs) for (const entry of layoutBoxes(plainBlocks(tab.blocks))) if (boxFields(entry.id, groups).includes(name)) return tab.id;
1565
+ for (const entry of layoutBoxes(plainBlocks(view.layout.sidebar))) if (boxFields(entry.id, groups).includes(name)) return null;
1566
+ return view.layout.tabs[0]?.id ?? 'edit';
1567
+ }
1568
+
1569
+ /** How many of the errors sit on a tab's own boxes. */
1570
+ private errorsOn(tab: string): number {
1571
+ return Object.keys(this.errors).filter(name => this.tabOf(name) === tab).length;
1572
+ }
1573
+
1574
+ /** After a refused save, open the tab that holds the first error when the open tab has none. */
1575
+ @Client()
1576
+ private revealErrorTab() {
1577
+ if (this.errorsOn(this.mode)) return;
1578
+ const tabs = this.editorTabs();
1579
+ const target = Object.keys(this.errors).map(name => this.tabOf(name)).find((tab): tab is string => tab !== null && tabs.includes(tab));
1580
+ if (target && target !== this.mode) void this.showMode(target);
1581
+ }
1582
+
1583
+ @Client()
1584
+ async showMode(mode: string) {
1585
+ if (mode === this.mode) return;
1586
+ this.mode = mode;
1587
+ this.announce({ tab: mode });
1588
+ rememberTab(mode, this.editorTabs());
1589
+ if (mode === 'json' && !this.jsonDirty) await this.loadJson();
1590
+ }
1591
+
1592
+ @Client()
1593
+ async submitJson() {
1594
+ this.saving = true;
1595
+ this.message = '';
1596
+ try { await this.applyJson(this.json, this.rev); }
1597
+ finally { this.saving = false; }
1598
+ if (!this.error) { this.dirty = false; this.unsaved = false; this.autosaved = this.snapshot(); void this.announceSaved(); if (!this.message) this.message = __('Saved.'); }
1599
+ }
1600
+
1601
+ private jsonPanel(): TemplateResult {
1602
+ return html`<div class="space-y-3">
1603
+ <p class="text-sm text-muted-foreground">${__('The entry as the content API answers it. Fields such as id, rev and url are read-only; everything else is saved as a PATCH would be, with the same checks.')}</p>
1604
+ ${Object.keys(this.errors).length ? html`<ul role="alert" class="space-y-1 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive">${Object.entries(this.errors).map(([name, message]) => html`<li><code class="text-xs">${name}</code> ${this.describe(message)}</li>`)}</ul>` : null}
1605
+ ${component(CodeEditor, { id: 'field-json', value: this.json, language: 'json', label: __('Entry JSON'), ...(this.schema ? { schema: this.schema } : {}), class: 'min-h-[24rem] rounded-md border border-input bg-background shadow-xs focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]',
1606
+ onChange: (value: string) => { this.json = value; this.jsonDirty = true; this.dirty = true; } })}
1607
+ <div class="flex items-center gap-2">
1608
+ ${component(Button, { type: 'button', size: 'sm', disabled: this.saving || !this.jsonDirty, '@click': () => this.submitJson() }, __('Apply JSON'))}
1609
+ ${component(Button, { type: 'button', size: 'sm', variant: 'outline', disabled: this.saving, '@click': () => this.loadJson() }, __('Reload'))}
1610
+ </div>
1611
+ </div>`;
1612
+ }
1613
+
1614
+ // --- Rendering -------------------------------------------------------------
1615
+
1616
+ private errorFor(name: string): TemplateResult | null {
1617
+ return this.errors[name] ? html`<p role="alert" class="text-xs text-destructive">${this.describe(this.errors[name]!)}</p>` : null;
1618
+ }
1619
+
1620
+ /** A message naming a block by its ID, said with the block's name instead. */
1621
+ private describe(message: string): string {
1622
+ const view = this.view;
1623
+ if (!view) return message;
1624
+ return describeBlockError(message, view.fields.filter(field => field.kind === 'blocks').flatMap(field => this.blocks(field.name)), view.blocks);
1625
+ }
1626
+
1627
+ private mediaControl(target: MediaTarget, value: unknown, label: string): TemplateResult {
1628
+ const ids = Array.isArray(value) ? value as string[] : typeof value === 'string' && value ? [value] : [];
1629
+ const remove = (id: string) => target.group && target.key ? this.setGroup(target.field, target.key, null)
1630
+ : target.rows?.length && target.key ? this.setRowValue(target.field, target.rows, target.key, target.multiple ? ids.filter(entry => entry !== id) : null)
1631
+ : target.dialog && target.key ? this.setDialogValue(target.key, target.multiple ? ids.filter(entry => entry !== id) : null)
1632
+ : target.block !== undefined && target.key
1633
+ ? this.setBlock(target.field, target.block, target.key, target.multiple ? ids.filter(entry => entry !== id) : null)
1634
+ : this.set(target.field, target.multiple ? ids.filter(entry => entry !== id) : null);
1635
+ return html`<div class="space-y-2">
1636
+ ${ids.length ? html`<div class=${target.multiple ? 'grid grid-cols-3 gap-2' : ''}>${ids.map(id => {
1637
+ const file = this.previews[id];
1638
+ return html`<figure class="group relative overflow-hidden rounded-md border border-border bg-muted">
1639
+ ${file && mediaKind(file.contentType) === 'image'
1640
+ ? html`<img src=${file.url} alt=${file.alt} class="aspect-video w-full object-cover" loading="lazy">`
1641
+ : file && mediaKind(file.contentType) === 'video' ? html`<video src=${file.url} class="aspect-video w-full bg-black" controls preload="metadata"></video>`
1642
+ : file && mediaKind(file.contentType) === 'audio' ? html`<div class="space-y-1 p-3"><p class="truncate text-xs text-muted-foreground">${file.title || file.alt}</p><audio src=${file.url} class="w-full" controls preload="metadata"></audio></div>`
1643
+ : html`<p class="p-3 text-xs text-muted-foreground">${file?.title ?? id}</p>`}
1644
+ <div class="absolute right-1 top-1 rounded bg-background">${iconButton(['media', target.field, target.block, target.key, id, 'remove'].filter(Boolean).join('-').replace(/[^\w-]+/g, '-'), 'trash-bin-trash', __('Remove'), () => remove(id), { danger: true, class: 'shadow-sm' })}</div>
1645
+ </figure>`;
1646
+ })}</div>` : null}
1647
+ ${component(Button, { type: 'button', variant: 'outline', size: 'sm', '@click': () => this.openPicker(target) },
1648
+ ids.length && !target.multiple ? `${__('Replace')} ${label.toLowerCase()}` : `${__('Choose')} ${label.toLowerCase()}`)}
1649
+ </div>`;
1650
+ }
1651
+
1652
+ private control(field: EditorField, value: unknown, change: (value: unknown) => void, target: MediaTarget, id: string): TemplateResult {
1653
+ // A pattern's starting layouts: the collections, one checkbox each.
1654
+ if (this.view?.route === 'patterns' && field.name === 'starter' && target.block === undefined) {
1655
+ const chosen = Array.isArray(value) ? value.map(String) : [];
1656
+ return html`<div id=${id} class="space-y-1.5">${this.collectionChoices.map(choice => html`<div>${component(Checkbox, { label: choice.label, checked: chosen.includes(choice.name), '@change': (event: Event) => change((event.target as HTMLInputElement).checked
1657
+ ? [...new Set([...chosen, choice.name])] : chosen.filter(name => name !== choice.name)) })}</div>`)}</div>`;
1658
+ }
1659
+ // A multiple field: this editor's control for the kind, once per item; a multiple choice is checkboxes and a gallery the media control.
1660
+ if (field.multiple && !field.media) {
1661
+ if (field.kind === 'enum') return choicesControl(field, value, change, id);
1662
+ return multipleControl(field, value, change, id, (item, itemChange, itemId) => this.control({ ...field, multiple: false }, item, itemChange, target, itemId));
1663
+ }
1664
+ // A group of an entry (a form's settings): its subfields with this editor's controls, media and Markdown included.
1665
+ if (field.kind === 'json' && field.fields.length && target.block === undefined && !target.group) {
1666
+ return groupFields(field, value, change, id, (sub, subValue, subChange, subId) => this.control(sub, subValue, subChange, { field: target.field, group: true, key: sub.name }, subId));
1667
+ }
1668
+ // A form's notifications: a list of emails, not JSON.
1669
+ if (this.view?.route === 'forms' && field.name === 'notifications' && target.block === undefined) {
1670
+ return notificationRulesControl(String(value ?? ''), conditionFields(this.blocks('body'), this.view.blocks), id, change);
1671
+ }
1672
+ switch (field.kind) {
1673
+ // Rows outside a layout (a plugin resource's): the group view renders them with this editor's controls.
1674
+ case 'rows': return component(FieldGroupView, {
1675
+ id, blocks: [{ _id: field.name, type: 'field/repeater', data: { name: field.name, label: field.label } }], options: this.view?.blocks ?? [], fields: [field], values: { [field.name]: value },
1676
+ onChange: (_name: string, next: unknown) => change(next), hidden: new Set<string>(),
1677
+ // The field's row around this control shows who is in the field itself; the view shows who is in each row's controls.
1678
+ presence: (anchor: string) => anchor === field.name ? [] : this.peersIn(anchor),
1679
+ control: (sub: EditorField, subValue: unknown, subChange: (value: unknown) => void, rows: RowPath, subId: string) => this.control(sub, subValue, subChange, { field: target.field, rows, key: sub.name }, subId),
1680
+ });
1681
+ case 'text': if (field.format === 'markdown' && target.block === undefined) return this.markdownControl(field, value, change, id, target); break;
1682
+ case 'blocks': return this.blocksControl(field);
1683
+ // Rich text inside a block, or one item of a multiple field: its own editor for the picker and its blocks; inside the
1684
+ // side panel (a block embedded in rich text) it takes no blocks, as the panel cannot open a second one.
1685
+ // In a room, a block's rich text and the entry's own rich text fields are edited together; the side panel's and a list's items are not.
1686
+ case 'richtext': {
1687
+ // The document's path in the room, when it is shared there: notes sit on shared documents alone.
1688
+ const shared = target.block !== undefined || id !== field.name
1689
+ ? target.dialog || target.rows || target.group ? null : target.block !== undefined ? richTextPath(target.field, { id: target.block, key: target.key ?? field.name })
1690
+ : id === `field-${field.name}` && this.sharedRichText(field.name) ? richTextPath(field.name) : null
1691
+ : this.sharedRichText(field.name) ? richTextPath(field.name) : null;
1692
+ if (target.block !== undefined || id !== field.name) return component(RichTextField, {
1693
+ id, label: field.label, value: (value as RichTextDoc | null) ?? null, blocks: target.dialog ? [] : this.richTextBlocks(field), onChange: (doc: RichTextDoc) => change(doc),
1694
+ onMedia: () => this.openPicker({ field: target.field, richText: true, editor: id }),
1695
+ onInsertBlock: (type: string) => this.insertRichBlock(target.field, type, id), onEditBlock: (block: EmbeddedBlock) => this.editRichBlock(target.field, block, id),
1696
+ bindings: this.bindings(), patternTitles: this.patternTitles,
1697
+ ...this.collabFor(shared), ...this.notesFor(shared),
1698
+ });
1699
+ return component(RichTextField, {
1700
+ id, label: field.label, value: (value as RichTextDoc | null) ?? null,
1701
+ blocks: this.richTextBlocks(field), bindings: this.bindings(),
1702
+ onChange: (doc: RichTextDoc) => change(doc),
1703
+ onMedia: () => this.openPicker({ field: field.name, richText: true }),
1704
+ onInsertBlock: (type: string) => this.insertRichBlock(field.name, type),
1705
+ onEditBlock: (block: EmbeddedBlock) => this.editRichBlock(field.name, block),
1706
+ patternTitles: this.patternTitles,
1707
+ ...this.collabFor(shared), ...this.notesFor(shared),
1708
+ });
1709
+ }
1710
+ // Media files open this editor's picker, which knows where the chosen file goes.
1711
+ default: if (field.media && field.kind === 'string') return this.mediaControl({ ...target, multiple: field.multiple, fileKind: chooserKind(field) }, value, field.label);
1712
+ }
1713
+ return fieldControl(field, value, change, id, { options: this.references[field.name] ?? [], ...(this.view ? { sources: this.view.sources } : {}), ...(target.block !== undefined && !field.media ? { bindings: this.bindings() } : {}),
1714
+ ...(target.dialog && this.blockDialog ? { language: String(this.blockDialog.values.language ?? '') } : {}) }) ?? html``;
1715
+ }
1716
+
1717
+ /** The block types a rich text field can embed. */
1718
+ private richTextBlocks(field: EditorField) {
1719
+ return (this.view?.blocks ?? []).filter(block => block.name !== 'core/pattern' && !block.input && block.category !== 'data' && (!field.blocks.length || field.blocks.includes(block.name)));
1720
+ }
1721
+
1722
+ /** The entry's fields a block's text may show (`{{ $.price }}`): the collection's and its field groups', apart from blocks and rich text. */
1723
+ private bindings(): BindingChoice[] {
1724
+ const view = this.view;
1725
+ if (!view) return [];
1726
+ const grouped = flattenGroupFields(plainBlocks(view.groups.flatMap(group => group.blocks)))
1727
+ .flatMap(block => {
1728
+ const kind = BINDABLE_FIELD_BLOCKS[block.type.replace(/^field\//, '')];
1729
+ const name = String(block.data.name ?? '');
1730
+ return kind && name ? [{ name, label: String(block.data.label ?? name), kind, media: false }] : [];
1731
+ });
1732
+ const own = view.fields.filter(field => !grouped.some(entry => entry.name === field.name));
1733
+ return bindingChoices([...own, ...grouped]);
1734
+ }
1735
+
1736
+ private markdownControl(field: EditorField, value: unknown, change: (value: unknown) => void, id: string, target: MediaTarget): TemplateResult {
1737
+ const tab = this.tabs[id] ?? 'write';
1738
+ const text = String(value ?? '');
1739
+ const wrap = (before: string, after: string, placeholder: string) => this.format(id, text, next => change(next), before, after, placeholder);
1740
+ const tool = (label: string, title: string, run: () => void) => html`<button type="button" title=${title} aria-label=${title}
1741
+ class="rounded px-2 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground border-none bg-transparent cursor-pointer" @click=${run}>${label}</button>`;
1742
+ return component(Tabs, {
1743
+ id: `${id}-editor`, label: `${field.label} ${__('editor')}`, value: tab, variant: 'underline',
1744
+ class: 'rounded-lg border border-border bg-card [&>.cs-tabs__panel]:mt-0',
1745
+ listProps: { class: 'w-full' }, onValueChange: (entry: string) => this.showTab(id, entry === 'preview' ? 'preview' : 'write', text),
1746
+ items: [
1747
+ { value: 'write', label: __('Write'), content: html`
1748
+ <div class="flex flex-wrap items-center gap-0.5 border-b border-border px-2 py-1.5" role="toolbar" aria-label=${__('Formatting')}>
1749
+ ${tool('B', __('Bold'), () => wrap('**', '**', __('bold text')))}
1750
+ ${tool('I', __('Italic'), () => wrap('_', '_', __('italic text')))}
1751
+ ${tool('H2', __('Heading'), () => wrap('\n## ', '\n', __('Heading')))}
1752
+ ${tool('“ ”', __('Quote'), () => wrap('\n> ', '\n', __('Quote')))}
1753
+ ${tool('• List', __('Bulleted list'), () => wrap('\n- ', '\n', __('Item')))}
1754
+ ${tool('</>', __('Code'), () => wrap('`', '`', 'code'))}
1755
+ ${tool(__('Link'), __('Link'), () => wrap('[', '](https://)', __('link text')))}
1756
+ ${tool(__('Add media'), __('Add media'), () => this.openPicker({ ...target, insert: true, editor: id }))}
1757
+ </div>
1758
+ <textarea id=${id} class="block min-h-[22rem] w-full resize-y rounded-b-lg border-0 bg-transparent p-4 font-mono text-sm leading-6 text-foreground focus:outline-none"
1759
+ .value=${String(value ?? '')} @input=${(event: Event) => change((event.target as HTMLTextAreaElement).value)}
1760
+ aria-describedby=${`${id}-hint`}></textarea>
1761
+ <p id=${`${id}-hint`} class="border-t border-border px-4 py-2 text-xs text-muted-foreground">${__('Markdown: **bold**, _italic_, ## headings, - lists, [links](https://example.com). Blocks: {{ block core/button label="Buy" url="/cart" /}}; values: {{ $.price }}, {{ $site.title }}.')}</p>` },
1762
+ { value: 'preview', label: __('Preview'), content: html`<div class="cms-prose min-h-[22rem] p-4">${this.rendered[id] ? unsafeHTML(this.rendered[id]!) : html`<p class="text-muted-foreground">${__('Nothing to preview.')}</p>`}</div>` },
1763
+ ],
1764
+ });
1765
+ }
1766
+
1767
+ private blocksControl(field: EditorField): TemplateResult {
1768
+ return html`<div class="space-y-3">
1769
+ ${component(BlockTree, {
1770
+ // Every block opens in the panel; in a form, with its conditional logic.
1771
+ id: `field-${field.name}`, blocks: this.blocks(field.name), options: this.view?.blocks ?? [], allowed: field.blocks, form: field.form, error: this.errors[field.name] ?? '',
1772
+ onEdit: (id: string) => this.editTreeBlock(field.name, id), lock: this.view?.templateLock,
1773
+ // Patterns go into the content; not into forms, and not into patterns.
1774
+ ...(field.form || this.view?.route === 'patterns' ? {} : { onPatterns: () => this.openPatterns(field.name) }),
1775
+ onChange: (blocks: EditorBlock[]) => this.set(field.name, blocks),
1776
+ control: (entry: EditorField, value: unknown, change: (value: unknown) => void, block: EditorBlock, id: string) => this.control(entry, value, change, { field: field.name, block: block._id, key: entry.name }, id),
1777
+ editing: this.editingBlocks(), onDrag: (id: string | null) => this.announce({ dragging: id ?? undefined }),
1778
+ ...(this.id === 'new' ? {} : { notes: this.blockNoteCounts(field.name), onNote: (id: string) => this.startNote(formatNoteTarget({ kind: 'block', field: field.name, block: id })), onNotes: (id: string) => this.showNotes({ block: id }) }),
1779
+ })}
1780
+ ${this.errorFor(field.name)}
1781
+ </div>`;
1782
+ }
1783
+
1784
+ /** A field with its label, help and error; inside a box titled by the label, the label is for screen readers alone. */
1785
+ private fieldRow(field: EditorField, options: { labelHidden?: boolean } = {}): TemplateResult {
1786
+ const id = `field-${field.name}`;
1787
+ const value = this.values[field.name];
1788
+ const shared = field.shared && this.languages.multilingual;
1789
+ const control = this.control(field, value, entry => this.set(field.name, entry), { field: field.name }, id);
1790
+ const here = this.peersIn(field.name);
1791
+ const tools = this.noteTools(field.name);
1792
+ // One line of text carries its note tools inside, as the title does; other controls show them beside the label.
1793
+ const inline = tools !== null && field.kind === 'string' && !field.media && !field.multiple && !field.choicesFrom && !field.fields.length;
1794
+ const shown = shared && this.sharedLocked ? html`<fieldset disabled class="contents">${control}</fieldset>` : control;
1795
+ return html`<div class="group space-y-1.5" data-shared=${shared ? 'true' : ''} data-field=${field.name} style=${presenceOutline(here)}>
1796
+ ${field.kind === 'boolean' ? tools : html`<div class="flex items-center gap-2"><label for=${id} class=${options.labelHidden ? 'sr-only' : 'block text-sm font-medium text-foreground'}>${field.label}${field.required ? html`<span class="text-destructive"> *</span>` : null}</label>${inline ? null : tools}</div>`}
1797
+ ${here.length ? presenceChip(here, __('is here')) : null}
1798
+ ${inline ? inlineNoteTools(shown, tools) : shown}
1799
+ ${field.description && !(field.kind === 'text' && field.format === 'markdown') ? html`<p class="text-xs text-muted-foreground">${field.description}</p>` : null}
1800
+ ${shared ? html`<p class="text-xs text-muted-foreground">${this.sharedLocked ? __('Same in every language. You cannot edit every translation, so it is read-only here.') : __('Same in every language: saving copies it to the translations.')}</p>` : null}
1801
+ ${field.kind === 'blocks' ? null : this.errorFor(field.name)}
1802
+ </div>`;
1803
+ }
1804
+
1805
+ private publishBox(view: EditorView): TemplateResult {
1806
+ const status = String(this.values.status ?? 'draft');
1807
+ const isNew = this.id === 'new';
1808
+ const live = this.savedStatus === 'published' || this.savedStatus === 'scheduled';
1809
+ const at = typeof this.values.publishedAt === 'string' && this.values.publishedAt ? Date.parse(`${this.values.publishedAt}Z`) : NaN;
1810
+ const future = Number.isFinite(at) && at > Date.now();
1811
+ const button = (label: string, intent: SaveIntent, variant: 'default' | 'outline' = 'default') =>
1812
+ component(Button, { type: 'button', variant, size: 'sm', disabled: this.saving, '@click': () => this.submit(intent) }, label);
1813
+ const primary = !view.publishable ? button(isNew ? __('Save') : __('Update'), 'update')
1814
+ : status === 'trash' ? button(__('Restore'), 'restore')
1815
+ : live && (status === 'published' || status === 'scheduled') ? button(future ? __('Update schedule') : __('Update'), 'update')
1816
+ : status === 'published' || status === 'scheduled' ? button(future ? __('Schedule') : __('Publish'), 'update')
1817
+ : status === 'pending' ? button(__('Submit for review'), 'update')
1818
+ : button(__('Save draft'), 'update');
1819
+ const selectable = ['draft', 'pending', 'published'] as const;
1820
+ return box(view.publishable ? __('Publish') : __('Save'), html`
1821
+ ${view.publishable && status !== 'trash' ? this.tracked('status', component(NativeSelect, { id: 'field-status', size: 'sm', '@change': (event: Event) => this.set('status', (event.target as HTMLSelectElement).value) }, html`
1822
+ ${selectable.map(value => html`<option value=${value} ?selected=${(status === 'scheduled' ? 'published' : status) === value}>${value === 'published' && future ? __('Scheduled') : __(STATUS_LABELS[value])}</option>`)}`),
1823
+ { label: html`<label for="field-status" class="block text-xs font-medium text-foreground">${__('Status')}</label>` })
1824
+ : view.publishable ? html`<p class="flex items-center gap-2 text-sm text-muted-foreground">${__('Status')}: ${statusBadge(status)}</p>` : null}
1825
+ ${view.publishable ? this.tracked('publishedAt', html`
1826
+ ${component(Input, { id: 'field-publishedAt', type: 'datetime-local', size: 'sm', '.value': String(this.values.publishedAt ?? ''), '@input': (event: Event) => this.set('publishedAt', (event.target as HTMLInputElement).value) })}
1827
+ <p class="text-xs text-muted-foreground">${future && (status === 'published' || status === 'scheduled') ? __('Goes live at this time.') : __('Leave empty to publish immediately.')}</p>
1828
+ ${this.errorFor('publishedAt')}`,
1829
+ { label: html`<label for="field-publishedAt" class="block text-xs font-medium text-foreground">${live && !future ? __('Published on (UTC)') : __('Publish on (UTC)')}</label>` }) : null}
1830
+ ${view.publishable && status !== 'trash' ? this.tracked('unpublishAt', html`
1831
+ ${component(Input, { id: 'field-unpublishAt', type: 'datetime-local', size: 'sm', '.value': String(this.values.unpublishAt ?? ''), '@input': (event: Event) => this.set('unpublishAt', (event.target as HTMLInputElement).value) })}
1832
+ <p class="text-xs text-muted-foreground">${__('Goes back to draft at this time. Leave empty to keep it published.')}</p>
1833
+ ${this.errorFor('unpublishAt')}`,
1834
+ { label: html`<label for="field-unpublishAt" class="block text-xs font-medium text-foreground">${__('Unpublish on (UTC)')}</label>` }) : null}
1835
+ ${!isNew && (view.path !== null || view.route === 'forms') ? html`<div class="space-y-2 border-t border-border pt-3">
1836
+ <div class="flex flex-wrap items-center gap-2">
1837
+ ${component(Button, { type: 'button', variant: 'outline', size: 'sm', '@click': () => this.openPreview() }, __('Preview'))}
1838
+ ${status !== 'published' ? component(Button, { type: 'button', variant: 'ghost', size: 'sm', '@click': () => this.createPreviewLink() }, __('Get preview link')) : null}
1839
+ </div>
1840
+ ${this.previewLink ? html`<div class="flex gap-1"><input readonly aria-label=${__('Preview link')} class=${`${CONTROL} py-1 text-xs`} .value=${this.previewLink}
1841
+ @focus=${(event: Event) => (event.target as HTMLInputElement).select()}>${component(Button, { type: 'button', size: 'sm', variant: 'outline', '@click': () => this.copyPreviewLink() }, __('Copy'))}</div>
1842
+ <p class="text-xs text-muted-foreground">${__('Anyone with the link can see this entry for 7 days.')}</p>` : null}
1843
+ ${this.previewLinks ? html`<p class="text-xs text-muted-foreground">${this.previewLinks} ${this.previewLinks === 1 ? __('preview link is active.') : __('preview links are active.')}
1844
+ <button type="button" class="text-destructive hover:underline bg-transparent border-none p-0 cursor-pointer" @click=${() => this.revokePreviewLinks()}>${__('Revoke')}</button></p>` : null}
1845
+ </div>` : null}
1846
+ ${isNew ? null : html`<dl class="space-y-0.5 text-xs text-muted-foreground">
1847
+ ${this.meta.author && !this.values.authors ? html`<div>${__('Author')}: <span class="text-foreground">${this.meta.author}</span></div>` : null}
1848
+ <div>${__('Last modified')}: ${shortDate(this.meta.updatedAt)}</div>
1849
+ <div>${__('Revision')} #${this.rev}</div>
1850
+ </dl>`}
1851
+ ${this.autosavedAt ? html`<p class="text-xs text-muted-foreground" aria-live="polite">${__('Draft autosaved at')} ${shortDate(this.autosavedAt)}</p>` : null}
1852
+ <div class="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3">
1853
+ ${view.publishable && !isNew && status !== 'trash'
1854
+ ? html`<button type="button" class="text-sm text-destructive hover:underline bg-transparent border-none p-0 cursor-pointer" @click=${() => this.submit('trash')}>${__('Move to trash')}</button>`
1855
+ : html`<span></span>`}
1856
+ <span class="flex flex-wrap gap-2">${primary}</span>
1857
+ </div>`, { id: 'publish-box' });
1858
+ }
1859
+
1860
+ /** The editorial checks over the current values; plugin blocks are read by their text fields. */
1861
+ private checks(): Check[] {
1862
+ const seo = (this.values.seo as Record<string, unknown> | undefined) ?? {};
1863
+ const blocks = Object.entries(this.values).flatMap(([name, value]) => this.view?.fields.find(field => field.name === name)?.kind === 'blocks' && Array.isArray(value) ? value as Block[] : []);
1864
+ let host = '';
1865
+ try { host = new URL(this.seo.origin).host; } catch { /* no origin yet */ }
1866
+ const input = { title: String(this.values.title ?? ''), seoTitle: String(seo.title ?? ''), description: String(seo.description ?? ''), summary: String(this.values.summary ?? ''), host, article: this.seo.article };
1867
+ // Reading the content walks every block's text: typing in another field reuses the last result.
1868
+ const openNotes = this.openRoots().length;
1869
+ const key = [...Object.values(input), ...blocks, openNotes, this.notesGate];
1870
+ if (this.checked && this.checked.key.length === key.length && this.checked.key.every((part, index) => part === key[index])) return this.checked.checks;
1871
+ // Open notes are a soft check; with the Writing setting on, they hold publishing, and the check says so.
1872
+ const notes: Check[] = openNotes ? [{ id: 'notes', status: 'warn', message: this.notesGate
1873
+ ? (openNotes === 1 ? __('1 open note holds this entry back from publishing.') : `${openNotes} ${__('open notes hold this entry back from publishing.')}`)
1874
+ : (openNotes === 1 ? __('1 open note is waiting for review.') : `${openNotes} ${__('open notes are waiting for review.')}`) }] : [];
1875
+ const checks = [...entryChecks({ ...input, blocks, types: new Map(CORE_BLOCKS.map(block => [block.name, block])) }), ...notes];
1876
+ this.checked = { key, checks };
1877
+ return checks;
1878
+ }
1879
+
1880
+ @Client()
1881
+ async copyLink(url: string) {
1882
+ this.message = '';
1883
+ this.error = '';
1884
+ try { await navigator.clipboard.writeText(`${this.seo.origin}${url}`); this.message = __('Link copied.'); }
1885
+ catch { this.error = __('The link could not be copied.'); }
1886
+ }
1887
+
1888
+ /** Search title, description and image, with a preview of the search result. */
1889
+ /** The Assistant box: the model suggests a title, an excerpt or a summary from the content; the person keeps or edits it. */
1890
+ private assistantBox(): TemplateResult {
1891
+ const button = (kind: 'title' | 'excerpt' | 'summary', label: string, shown: boolean) => shown ? html`<button type="button" class="rounded-md border border-border bg-background px-2.5 py-1 text-xs text-foreground hover:bg-muted disabled:opacity-50" ?disabled=${Boolean(this.assistantBusy)} @click=${() => this.ask(kind)}>${this.assistantBusy === kind ? __('Thinking…') : label}</button>` : null;
1892
+ return box(__('Assistant'), html`<div class="space-y-2">
1893
+ <p class="text-xs text-muted-foreground">${__('Suggestions from the content, written into the field for you to edit.')}</p>
1894
+ <div class="flex flex-wrap gap-2">${button('title', __('Suggest a title'), this.values.title !== undefined)}${button('excerpt', __('Suggest an excerpt'), this.values.excerpt !== undefined)}${button('summary', __('Suggest a summary'), this.values.summary !== undefined)}</div>
1895
+ ${this.assistantError ? html`<p role="alert" class="text-xs text-destructive">${this.assistantError}</p>` : null}
1896
+ </div>`, { id: 'box-assistant' });
1897
+ }
1898
+
1899
+ @Client()
1900
+ async ask(kind: 'title' | 'excerpt' | 'summary') {
1901
+ this.assistantBusy = kind;
1902
+ this.assistantError = '';
1903
+ try {
1904
+ const text = await this.suggest(kind, this.values);
1905
+ if (text) this.set(kind, text);
1906
+ } catch (error) {
1907
+ this.assistantError = (error as Error).message || __('No suggestion came back.');
1908
+ } finally { this.assistantBusy = ''; }
1909
+ }
1910
+
1911
+ /** Ask the application's model for one field, from the entry's text as it stands in the editor. */
1912
+ @Server()
1913
+ async suggest(kind: 'title' | 'excerpt' | 'summary', values: EditorValues): Promise<string> {
1914
+ const cms = this.c.get('cms');
1915
+ if (!cms.ai) throw new ClientVisibleError(__('The application has no AI provider.'));
1916
+ if (!['title', 'excerpt', 'summary'].includes(kind)) throw new ClientVisibleError(__('Unknown suggestion.'));
1917
+ await this.assertEditor();
1918
+ const principal = this.c.get('principal');
1919
+ if (!(await cms.security.attempt('suggest', principalId(principal), SUGGESTIONS.max, SUGGESTIONS.windowMs))) throw new ClientVisibleError(__('Too many suggestions in a short time. Wait a minute and try again.'));
1920
+ const parts: string[] = [];
1921
+ for (const [name, value] of Object.entries(values)) {
1922
+ if (name === kind || parts.join(' ').length > 12_000) continue;
1923
+ if (typeof value === 'string' && ['title', 'excerpt', 'summary'].includes(name) && value.trim()) parts.push(`${name}: ${value.trim()}`);
1924
+ else if (Array.isArray(value) && value.length && typeof value[0] === 'object' && value[0] && 'type' in (value[0] as object)) parts.push(blocksPlain(value as Block[], cms.blockTypes, doc => richTextPlain(doc), 12_000));
1925
+ else if (value && typeof value === 'object' && (value as { type?: string }).type === 'doc') parts.push(richTextPlain(value as RichTextDoc, 12_000));
1926
+ }
1927
+ const content = parts.join('\n\n').trim().slice(0, 12_000);
1928
+ if (!content) throw new ClientVisibleError(__('Write some content first.'));
1929
+ const ask = kind === 'title' ? 'Write one title of at most 70 characters for this content. Answer with the title alone.'
1930
+ : kind === 'excerpt' ? 'Write a one-sentence excerpt of at most 160 characters that invites reading this content. Answer with the sentence alone.'
1931
+ : 'Write a summary of two or three sentences that answers what this content is about, for readers and answer engines. Answer with the summary alone.';
1932
+ const answer = await cms.ai.complete({ system: 'You write for a website. Answer in the language of the content, plainly, with no quotation marks, labels or Markdown.', prompt: `${ask}\n\nContent:\n${content}`, maxTokens: 300 });
1933
+ return answer.replace(/^["'“”‘’\s]+|["'“”‘’\s]+$/g, '').replace(/^(?:Title|Excerpt|Summary):\s*/i, '').slice(0, kind === 'title' ? 200 : 2000);
1934
+ }
1935
+
1936
+ private seoBox(): TemplateResult {
1937
+ const seo = (this.values.seo as Record<string, unknown> | undefined) ?? {};
1938
+ const variables = { title: String(seo.title ?? '') || String(this.values.title ?? ''), sep: this.seo.separator, site: this.seo.siteTitle, tagline: this.seo.tagline, excerpt: String(seo.description ?? '') || String(this.values.excerpt ?? ''), author: this.meta.author, collection: this.seo.collection };
1939
+ const title = renderSeoTemplate(this.seo.titleTemplate, variables);
1940
+ const description = String(seo.description ?? '') || renderSeoTemplate(this.seo.descriptionTemplate, variables);
1941
+ const url = `${this.seo.origin}${this.meta.url ?? (this.view?.path !== null ? entryUrl(this.view?.path, [String(this.values.slug ?? '') || 'slug']) ?? '' : '')}`;
1942
+ const counter = (text: string, ideal: number) => html`<span class=${`text-xs ${[...text].length > ideal ? 'text-amber-600' : 'text-muted-foreground'}`}>${[...text].length} / ${ideal}</span>`;
1943
+ // Each key is its own presence anchor (`seo.description`), so the chip sits on the row someone else is in.
1944
+ const text = (key: string, label: string, ideal: number, multiline = false) => this.tracked(`seo.${key}`,
1945
+ multiline ? component(Textarea, { id: `seo-${key}`, rows: 3, '.value': String(seo[key] ?? ''), '@input': (event: Event) => this.setGroup('seo', key, (event.target as HTMLTextAreaElement).value) })
1946
+ : component(Input, { id: `seo-${key}`, '.value': String(seo[key] ?? ''), '@input': (event: Event) => this.setGroup('seo', key, (event.target as HTMLInputElement).value) }),
1947
+ { label: html`<div class="flex items-center justify-between gap-3"><label for=${`seo-${key}`} class="block text-sm font-medium text-foreground">${label}</label>${counter(String(seo[key] ?? ''), ideal)}</div>`, inline: !multiline });
1948
+ const check = (key: string, label: string) => this.tracked(`seo.${key}`, html`<div>${component(Checkbox, { label, checked: seo[key] === true, '@change': (event: Event) => this.setGroup('seo', key, (event.target as HTMLInputElement).checked) })}</div>`);
1949
+ const checks = this.checks();
1950
+ const tone = (status: Check['status']) => status === 'ok' ? 'bg-emerald-500' : status === 'warn' ? 'bg-amber-500' : 'bg-sky-500';
1951
+ const warnings = checks.filter(check => check.status === 'warn').length;
1952
+ return html`<section aria-labelledby="seo-title-heading" class="space-y-4 rounded-lg border border-border bg-card p-4">
1953
+ <h2 id="seo-title-heading" class="text-sm font-semibold text-foreground">${__('Search and sharing')}</h2>
1954
+ ${this.seo.summary ? this.tracked('summary', html`
1955
+ ${component(Textarea, { id: 'field-summary', rows: 3, '.value': String(this.values.summary ?? ''), '@input': (event: Event) => this.set('summary', (event.target as HTMLTextAreaElement).value) })}
1956
+ <p class="text-xs text-muted-foreground">${__('Two or three sentences that answer what this is about. Shown first by the theme, quoted by answer engines, and the meta description when there is none.')}</p>
1957
+ ${this.errorFor('summary')}`,
1958
+ { label: html`<div class="flex items-center justify-between gap-3"><label for="field-summary" class="block text-sm font-medium text-foreground">${__('Summary')}</label>${counter(String(this.values.summary ?? ''), 300)}</div>` }) : null}
1959
+ <details class="rounded-md border border-border" ?open=${this.checksOpen} @toggle=${(event: Event) => { this.checksOpen = (event.target as HTMLDetailsElement).open; }}>
1960
+ <summary class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm text-foreground">
1961
+ <span class=${`inline-block size-2.5 rounded-full ${warnings ? 'bg-amber-500' : 'bg-emerald-500'}`} aria-hidden="true"></span>
1962
+ ${__('Readiness for search and answer engines')}${warnings ? html` <span class="text-muted-foreground">(${warnings} ${warnings === 1 ? __('warning') : __('warnings')})</span>` : null}</summary>
1963
+ <ul class="space-y-1.5 border-t border-border px-3 py-2 text-sm">${checks.map(check => html`<li class="flex items-start gap-2"><span class=${`mt-1.5 inline-block size-2 shrink-0 rounded-full ${tone(check.status)}`} aria-hidden="true"></span><span class="text-muted-foreground">${__(check.message)}</span></li>`)}</ul>
1964
+ </details>
1965
+ <div class="rounded-md border border-border bg-background p-3" aria-label=${__('Search result preview')}>
1966
+ <p class="truncate text-xs text-emerald-700 dark:text-emerald-400">${url}</p>
1967
+ <p class="truncate text-base text-blue-700 dark:text-blue-400">${title || __('Add a title')}</p>
1968
+ <p class="line-clamp-2 text-sm text-muted-foreground">${description || __('Search engines show a part of the content when there is no description.')}</p>
1969
+ </div>
1970
+ ${text('title', __('SEO title'), 60)}
1971
+ ${text('description', __('Meta description'), 155, true)}
1972
+ <details class="space-y-3 text-sm">
1973
+ <summary class="cursor-pointer text-muted-foreground">${__('Sharing on social networks')}</summary>
1974
+ <div class="rounded-md border border-border bg-background p-3" aria-label=${__('Shared link preview')}>
1975
+ <p class="text-xs uppercase text-muted-foreground">${new URL(this.seo.origin || 'http://localhost').host}</p>
1976
+ <p class="truncate font-semibold text-foreground">${String(seo.socialTitle ?? '') || String(seo.title ?? '') || String(this.values.title ?? '') || __('Add a title')}</p>
1977
+ <p class="line-clamp-2 text-muted-foreground">${String(seo.socialDescription ?? '') || description}</p>
1978
+ </div>
1979
+ ${text('socialTitle', __('Social title'), 70)}
1980
+ ${text('socialDescription', __('Social description'), 200, true)}
1981
+ ${this.tracked('seo.image', html`${this.mediaControl({ field: 'seo', key: 'image', group: true }, seo.image ?? null, __('Image'))}
1982
+ <p class="text-xs text-muted-foreground">${__('Shown when the entry is shared. Defaults to the featured image. 1200 × 630 pixels suits every network.')}</p>`,
1983
+ { label: html`<span class="block text-sm font-medium text-foreground">${__('Social image')}</span>` })}
1984
+ </details>
1985
+ ${this.tracked('seo.canonical', html`${component(Input, { id: 'seo-canonical', placeholder: url, '.value': String(seo.canonical ?? ''), '@input': (event: Event) => this.setGroup('seo', 'canonical', (event.target as HTMLInputElement).value) })}
1986
+ <p class="text-xs text-muted-foreground">${__('Only when this content first appeared at another address.')}</p>`,
1987
+ { label: html`<label for="seo-canonical" class="block text-sm font-medium text-foreground">${__('Canonical URL')}</label>`, inline: true })}
1988
+ ${check('noindex', __('Hide from search engines'))}
1989
+ ${check('cornerstone', __('Cornerstone content: one of the site\'s most important entries'))}
1990
+ ${this.linkSuggestions.length ? html`<div class="space-y-1">
1991
+ <p class="text-sm font-medium text-foreground">${__('Related entries to link to')}</p>
1992
+ <ul class="space-y-1 text-sm">${this.linkSuggestions.map(entry => html`<li class="flex items-center justify-between gap-2">
1993
+ <a href=${entry.url} target="_blank" rel="noopener" class="truncate text-primary hover:underline" title=${entry.title}>${entry.title}</a>
1994
+ <button type="button" class="shrink-0 text-xs text-muted-foreground hover:text-foreground bg-transparent border-none p-0 cursor-pointer" @click=${() => this.copyLink(entry.url)}>${__('Copy link')}</button></li>`)}</ul>
1995
+ <p class="text-xs text-muted-foreground">${__('Internal links help engines find and rank related entries.')}</p>
1996
+ </div>` : null}
1997
+ <details class="space-y-3 text-sm">
1998
+ <summary class="cursor-pointer text-muted-foreground">${__('Snippets and AI answers')}</summary>
1999
+ ${check('nosnippet', __('No snippets: engines show the title only and do not quote the page in AI answers'))}
2000
+ ${seo.nosnippet === true ? null : this.tracked('seo.maxSnippet', html`
2001
+ ${component(Input, { id: 'seo-maxSnippet', type: 'number', min: 0, size: 'sm', placeholder: __('No limit'), '.value': seo.maxSnippet === undefined || seo.maxSnippet === null ? '' : String(seo.maxSnippet), '@input': (event: Event) => { const value = (event.target as HTMLInputElement).value; this.setGroup('seo', 'maxSnippet', value === '' ? null : Number(value)); } })}
2002
+ <p class="text-xs text-muted-foreground">${__('max-snippet: how much of the text results and AI Overviews may quote.')}</p>`,
2003
+ { label: html`<label for="seo-maxSnippet" class="block text-sm font-medium text-foreground">${__('Longest quote, in characters')}</label>` })}
2004
+ ${check('noarchive', __('No cached copy (Bing: also keeps the page out of Copilot training)'))}
2005
+ </details>
2006
+ ${this.errorFor('seo')}
2007
+ </section>`;
2008
+ }
2009
+
2010
+ /** The entry's language and its translations. */
2011
+ private languagesBox(view: EditorView): TemplateResult {
2012
+ const current = String(this.values.locale ?? '');
2013
+ return box(__('Languages'), html`
2014
+ ${this.id === 'new' ? html`<div class="space-y-1">
2015
+ <label for="field-locale" class="block text-xs font-medium text-foreground">${__('Language')}</label>
2016
+ ${component(NativeSelect, { id: 'field-locale', size: 'sm', '@change': (event: Event) => this.set('locale', (event.target as HTMLSelectElement).value) }, html`
2017
+ ${this.languages.options.map(option => html`<option value=${option.code} ?selected=${option.code === current}>${option.label}</option>`)}`)}
2018
+ </div>` : html`<p class="text-sm text-foreground">${__('Language')}: <strong>${this.languages.options.find(option => option.code === current)?.label ?? current}</strong></p>
2019
+ <ul class="space-y-1.5 text-sm">${this.translations.filter(entry => entry.code !== current).map(entry => html`<li class="flex items-center justify-between gap-2">
2020
+ <span class="text-muted-foreground">${entry.label}</span>
2021
+ ${entry.id ? html`<a href=${`/dashboard/content/${view.route}/${entry.id}`} class="truncate text-primary hover:underline" title=${entry.title}>${__('Edit')}${entry.status && entry.status !== 'published' ? ` (${__(STATUS_LABELS[entry.status] ?? entry.status)})` : ''}</a>`
2022
+ : html`<button type="button" class="text-primary hover:underline bg-transparent border-none p-0 cursor-pointer" @click=${() => this.translate(entry.code)}>+ ${__('Translate')}</button>`}
2023
+ </li>`)}</ul>`}`);
2024
+ }
2025
+
2026
+ private taxonomyBox(taxonomy: EditorView['taxonomies'][number]): TemplateResult {
2027
+ const selected = (this.values[taxonomy.name] as string[] | undefined) ?? [];
2028
+ if (!taxonomy.hierarchical) {
2029
+ const suggestions = taxonomy.terms.filter(term => !selected.some(name => name.toLowerCase() === term.name.toLowerCase())).slice(0, 12);
2030
+ // The box is one anchor: focus in its input, its terms or its new-term form counts as being in the taxonomy.
2031
+ return box(taxonomy.label, this.tracked(taxonomy.name, html`
2032
+ <div class="flex gap-2">
2033
+ <input id=${`tags-${taxonomy.name}`} class=${CONTROL} list=${`tags-${taxonomy.name}-list`} placeholder=${__('Separate with commas')}
2034
+ .value=${this.tagDrafts[taxonomy.name] ?? ''} aria-label=${`${__('Add')} ${taxonomy.label.toLowerCase()}`}
2035
+ @input=${(event: Event) => { this.tagDrafts = { ...this.tagDrafts, [taxonomy.name]: (event.target as HTMLInputElement).value }; }}
2036
+ @keydown=${(event: KeyboardEvent) => { if (event.key === 'Enter') { event.preventDefault(); this.addTags(taxonomy.name); } }}>
2037
+ ${component(Button, { type: 'button', size: 'sm', variant: 'outline', '@click': () => this.addTags(taxonomy.name) }, __('Add'))}
2038
+ </div>
2039
+ <datalist id=${`tags-${taxonomy.name}-list`}>${taxonomy.terms.map(term => html`<option value=${term.name}></option>`)}</datalist>
2040
+ ${selected.length ? html`<ul class="flex flex-wrap gap-1.5">${selected.map(name => html`<li class="inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-0.5 text-xs text-foreground">
2041
+ ${name}<button type="button" class="text-muted-foreground hover:text-destructive bg-transparent border-none cursor-pointer" aria-label=${`${__('Remove')} ${name}`} @click=${() => this.removeTag(taxonomy.name, name)}>×</button></li>`)}</ul>` : null}
2042
+ ${suggestions.length ? html`<p class="text-xs text-muted-foreground">${__('Choose from')}: ${suggestions.map((term, index) => html`${index ? ', ' : ''}<button type="button" class="text-primary hover:underline bg-transparent border-none p-0 cursor-pointer"
2043
+ @click=${() => this.set(taxonomy.name, [...selected, term.name])}>${term.name}</button>`)}</p>` : null}
2044
+ ${this.errorFor(taxonomy.name)}`, { class: 'space-y-3' }));
2045
+ }
2046
+ const draft = this.termDrafts[taxonomy.name] ?? { name: '', parent: '' };
2047
+ return box(taxonomy.label, this.tracked(taxonomy.name, html`
2048
+ <div class="max-h-56 space-y-1 overflow-y-auto">
2049
+ ${taxonomy.terms.length ? taxonomy.terms.map(term => html`<div style=${`padding-left: ${term.depth * 1.25}rem`}>
2050
+ ${component(Checkbox, { label: term.name, checked: selected.includes(term.id), '@change': (event: Event) => this.toggleTerm(taxonomy.name, term.id, (event.target as HTMLInputElement).checked) })}</div>`)
2051
+ : html`<p class="text-xs text-muted-foreground">${__('None yet.')}</p>`}
2052
+ </div>
2053
+ ${this.canManageTerms ? html`<details class="text-sm">
2054
+ <summary class="cursor-pointer text-primary">+ ${__('New')} ${taxonomy.singular.toLowerCase()}</summary>
2055
+ <div class="mt-2 space-y-2">
2056
+ <input class=${CONTROL} aria-label=${`${__('New')} ${taxonomy.singular.toLowerCase()}`} .value=${draft.name}
2057
+ @input=${(event: Event) => { this.termDrafts = { ...this.termDrafts, [taxonomy.name]: { ...draft, name: (event.target as HTMLInputElement).value } }; }}>
2058
+ <select class=${CONTROL} aria-label=${__('Parent')} @change=${(event: Event) => { this.termDrafts = { ...this.termDrafts, [taxonomy.name]: { ...draft, parent: (event.target as HTMLSelectElement).value } }; }}>
2059
+ <option value="">— ${__('Parent')} —</option>
2060
+ ${taxonomy.terms.map(term => html`<option value=${term.id} ?selected=${draft.parent === term.id}>${'— '.repeat(term.depth)}${term.name}</option>`)}
2061
+ </select>
2062
+ ${component(Button, { type: 'button', size: 'sm', variant: 'outline', disabled: !draft.name.trim(), '@click': () => this.addTerm(taxonomy.name, draft.name, draft.parent) }, `${__('New')} ${taxonomy.singular.toLowerCase()}`)}
2063
+ </div>
2064
+ </details>` : null}
2065
+ ${this.errorFor(taxonomy.name)}`, { class: 'space-y-3' }));
2066
+ }
2067
+
2068
+ private pickerModal(): TemplateResult {
2069
+ const target = this.picker.target;
2070
+ return component(Modal, { open: this.picker.open, size: 'max-w-4xl', 'aria-label': __('Media library'), onOpenChange: (open: boolean) => { if (!open) this.closePicker(); } }, html`
2071
+ <div class="space-y-4">
2072
+ <div class="flex items-center justify-between gap-3">
2073
+ <h2 class="text-lg font-semibold text-foreground">${target?.insert ? __('Add media') : __('Choose media')}</h2>
2074
+ ${component(Button, { type: 'button', variant: 'ghost', size: 'sm', '@click': () => this.closePicker() }, __('Close'))}
2075
+ </div>
2076
+ <div class="flex flex-wrap items-center gap-2">
2077
+ <input type="search" class=${`${CONTROL} max-w-xs`} placeholder=${__('Search media')} aria-label=${__('Search media')} .value=${this.picker.search}
2078
+ @change=${(event: Event) => this.findMedia((event.target as HTMLInputElement).value, this.picker.kind)}>
2079
+ <select class=${`${CONTROL} max-w-[10rem]`} aria-label=${__('Media type')} @change=${(event: Event) => this.findMedia(this.picker.search, (event.target as HTMLSelectElement).value)}>
2080
+ ${MEDIA_KIND_CHOICES.map(choice => html`<option value=${choice.value} ?selected=${this.picker.kind === choice.value}>${__(choice.label)}</option>`)}
2081
+ </select>
2082
+ <label class="inline-flex cursor-pointer items-center rounded-md border border-border px-3 py-2 text-sm text-foreground hover:bg-muted">
2083
+ ${__('Upload files')}<input type="file" multiple accept=${this.picker.kind === 'image' ? 'image/*' : MEDIA_ACCEPT} class="sr-only" @change=${(event: Event) => this.uploadInPicker(event)}>
2084
+ </label>
2085
+ </div>
2086
+ ${this.pickerErrors.map(error => notice(error, 'error'))}
2087
+ <ul class="grid max-h-[60vh] grid-cols-2 gap-3 overflow-y-auto sm:grid-cols-4">
2088
+ ${this.picker.items.map(file => html`<li>
2089
+ <button type="button" class="w-full overflow-hidden rounded-md border border-border bg-muted text-left hover:ring-2 hover:ring-ring cursor-pointer p-0" @click=${() => this.choose(file)}>
2090
+ ${mediaKind(file.contentType) === 'image' ? html`<img src=${file.url} alt=${file.alt} class="aspect-square w-full object-cover" loading="lazy">`
2091
+ : html`<span class="flex aspect-square items-center justify-center p-2 text-xs text-muted-foreground">${file.name}</span>`}
2092
+ <span class="block truncate bg-card px-2 py-1 text-xs text-foreground">${file.title || file.name} · ${file.size}</span>
2093
+ </button>
2094
+ </li>`)}
2095
+ </ul>
2096
+ ${this.picker.items.length ? null : html`<p class="text-sm text-muted-foreground">${__('No media found. Upload files to add them.')}</p>`}
2097
+ </div>`);
2098
+ }
2099
+
2100
+ /** Patterns to insert, or a new entry's starting layouts. */
2101
+ private patternModal(): TemplateResult {
2102
+ const picker = this.patternPicker;
2103
+ const close = () => { this.patternPicker = { open: false, field: '', starter: false }; };
2104
+ return component(Modal, { open: picker.open, size: 'max-w-2xl', 'aria-label': __('Patterns'), onOpenChange: (open: boolean) => { if (!open) close(); } }, html`
2105
+ <div class="space-y-4">
2106
+ <div class="flex items-center justify-between gap-3">
2107
+ <h2 class="text-lg font-semibold text-foreground">${picker.starter ? __('Start from a pattern') : __('Insert a pattern')}</h2>
2108
+ ${component(Button, { type: 'button', variant: 'ghost', size: 'sm', '@click': close }, picker.starter ? __('Start blank') : __('Close'))}
2109
+ </div>
2110
+ ${this.patternChoices.length ? html`<ul class="divide-y divide-border rounded-md border border-border">${this.patternChoices.map(choice => html`<li class="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
2111
+ <span class="min-w-0"><span class="block truncate text-sm font-medium text-foreground">${choice.title}</span>
2112
+ <span class="text-xs text-muted-foreground">${choice.synced ? __('Synced: edits to the pattern show here too') : __('Inserted as a copy')}</span></span>
2113
+ <span class="flex gap-2">
2114
+ ${component(Button, { type: 'button', size: 'sm', '@click': () => this.insertPattern(choice.id, false) }, picker.starter ? __('Use') : __('Insert'))}
2115
+ ${choice.synced ? component(Button, { type: 'button', size: 'sm', variant: 'outline', '@click': () => this.insertPattern(choice.id, true) }, __('Insert a copy')) : null}
2116
+ </span></li>`)}</ul>`
2117
+ : html`<p class="text-sm text-muted-foreground">${__('No patterns yet.')} <a href="/dashboard/content/patterns/new" class="text-primary hover:underline">${__('Create a pattern')}</a></p>`}
2118
+ </div>`);
2119
+ }
2120
+
2121
+ private blockDialogModal(): TemplateResult | null {
2122
+ const dialog = this.blockDialog;
2123
+ if (dialog?.type === 'core/pattern') {
2124
+ const id = String(dialog.values.pattern ?? '');
2125
+ return component(Modal, { open: true, size: 'max-w-lg', 'aria-label': __('Synced pattern'), onOpenChange: (open: boolean) => { if (!open) this.blockDialog = null; } }, html`
2126
+ <div class="space-y-4">
2127
+ <h2 class="text-lg font-semibold text-foreground">${this.patternTitles[id] ?? __('Synced pattern')}</h2>
2128
+ <p class="text-sm text-muted-foreground">${__('This pattern shows its current content wherever it is used. Edit the pattern to change it everywhere, or detach it to change it only here.')}</p>
2129
+ <div class="flex flex-wrap justify-end gap-2">
2130
+ <a href=${`/dashboard/content/patterns/${id}`} target="_blank" rel="noopener" class="inline-flex items-center rounded-md border border-border px-3 py-1.5 text-sm text-foreground no-underline hover:bg-muted">${__('Edit pattern')} ↗</a>
2131
+ ${dialog.embedded ? null : component(Button, { type: 'button', variant: 'outline', '@click': () => this.detachPattern() }, __('Detach'))}
2132
+ ${component(Button, { type: 'button', '@click': () => { this.blockDialog = null; } }, __('Done'))}
2133
+ </div>
2134
+ </div>`);
2135
+ }
2136
+ const option = this.view?.blocks.find(block => block.name === dialog?.type) ?? null;
2137
+ const fields = dialog && option ? option.fields.filter(entry => dialog.embedded || entry.kind !== 'richtext') : [];
2138
+ return blockPanel({
2139
+ id: 'entry-block', open: Boolean(dialog && option), option, tab: dialog?.tab ?? 'general', style: dialog?.style ?? styleValues({}), presets: this.view?.presets ?? { colors: [], gradients: [], fontSizes: [], spacing: [] },
2140
+ styleTab: dialog ? !dialog.embedded : false,
2141
+ // Focus in the panel counts as focus in the block; the others' presence there shows in the panel as in the tree.
2142
+ ...(dialog && !dialog.embedded ? { block: dialog.id, field: dialog.field, editing: this.editingBlocks()[dialog.id] ?? [], taken: this.otherBlockIds(dialog.field, dialog.id) } : {}),
2143
+ ...(dialog ? { media: { previews: this.previews, choose: (property: 'image' | 'video') => this.openPicker({ field: dialog.field, dialog: true, style: property, fileKind: property }) } } : {}),
2144
+ onTab: tab => this.showDialogTab(tab), onStyle: style => this.setDialogStyle(style), onClose: () => { this.blockDialog = null; },
2145
+ general: dialog && option ? html`${fields.length ? fields.map(entry => {
2146
+ const id = `block-${dialog.id}-${entry.name}`;
2147
+ return html`<div class="space-y-1">
2148
+ ${entry.kind === 'boolean' ? null : html`<label for=${id} class="block text-sm font-medium text-foreground">${entry.label}${entry.required ? ' *' : ''}</label>`}
2149
+ ${this.control(entry, dialog.values[entry.name], value => this.setDialogValue(entry.name, value), { field: dialog.field, key: entry.name, dialog: true }, id)}
2150
+ ${entry.description ? html`<p class="text-xs text-muted-foreground">${entry.description}</p>` : null}
2151
+ ${dialog.errors[entry.name] ? html`<p role="alert" class="text-xs text-destructive">${entry.label} ${dialog.errors[entry.name]}</p>` : null}
2152
+ </div>`;
2153
+ }) : html`<p class="text-sm text-muted-foreground">${__('This block has no settings.')}</p>`}
2154
+ ${!dialog.embedded && this.view?.fields.find(entry => entry.name === dialog.field)?.form
2155
+ ? conditionControl(dialog.when, conditionFields(this.blocks(dialog.field), this.view.blocks, dialog.id), `block-${dialog.id}`, when => this.setDialogCondition(when ?? null))
2156
+ : null}` : html``,
2157
+ });
2158
+ }
2159
+
2160
+ /** The theme template for this entry, when the active theme offers more than its default. */
2161
+ templateBox(): TemplateResult | null {
2162
+ const current = String(this.values.template ?? '');
2163
+ if (!this.templates.length && !current) return null;
2164
+ // A template the active theme no longer has stays listed, so saving keeps it.
2165
+ const choices = current && !this.templates.includes(current) ? [...this.templates, current] : this.templates;
2166
+ const label = (name: string) => name.slice('entry-'.length).replace(/[-_]+/g, ' ').replace(/^./, letter => letter.toUpperCase());
2167
+ return box(__('Template'), this.tracked('template', html`
2168
+ <select id="field-template" class=${CONTROL} @change=${(event: Event) => this.set('template', (event.target as HTMLSelectElement).value)}>
2169
+ <option value="" ?selected=${!current}>${__('Default template')}</option>
2170
+ ${choices.map(name => html`<option value=${name} ?selected=${name === current}>${label(name)}${this.templates.includes(name) ? '' : ` (${__('not in the active theme')})`}</option>`)}
2171
+ </select>
2172
+ ${this.errorFor('template')}`, { label: html`<label for="field-template" class="sr-only">${__('Template')}</label>` }));
2173
+ }
2174
+
2175
+ /** The blocks the conditions hide, computed once per render for every group box. */
2176
+ private hidden: ReadonlySet<string> = new Set();
2177
+
2178
+ private groupBox(group: EditorView['groups'][number]): TemplateResult {
2179
+ const view = this.view!;
2180
+ const body = component(FieldGroupView, {
2181
+ id: `group-${group.id}`, blocks: group.blocks, options: view.blocks, fields: view.fields, values: this.values, hidden: this.hidden, errors: this.errors,
2182
+ onChange: (name: string, value: unknown) => this.set(name, value), presence: (anchor: string) => this.peersIn(anchor),
2183
+ control: (field: EditorField, value: unknown, change: (value: unknown) => void, rows: RowPath, controlId: string) =>
2184
+ this.control(field, value, change, rows.length ? { field: rows[0]!.field, rows, key: field.name } : { field: field.name }, controlId),
2185
+ });
2186
+ return box(group.title, html`${group.description ? html`<p class="text-xs text-muted-foreground">${group.description}</p>` : null}${body}`, { id: `group-${group.id}-title` });
2187
+ }
2188
+
2189
+ private attributesBox(): TemplateResult {
2190
+ return box(__('Attributes'), html`
2191
+ ${this.tracked('parent', html`
2192
+ <select id="field-parent" class=${CONTROL} @change=${(event: Event) => this.set('parent', (event.target as HTMLSelectElement).value)}>
2193
+ <option value="" ?selected=${!this.values.parent}>(${__('no parent')})</option>
2194
+ ${this.parents.map(option => html`<option value=${option.id} ?selected=${option.id === this.values.parent}>${'— '.repeat(option.depth)}${option.name}</option>`)}
2195
+ </select>
2196
+ ${this.errorFor('parent')}`, { label: html`<label for="field-parent" class="block text-xs font-medium text-foreground">${__('Parent')}</label>` })}
2197
+ ${this.tracked('menuOrder', component(Input, { id: 'field-menuOrder', type: 'number', size: 'sm', '.value': String(this.values.menuOrder ?? '0'), '@input': (event: Event) => this.set('menuOrder', (event.target as HTMLInputElement).value) }),
2198
+ { label: html`<label for="field-menuOrder" class="block text-xs font-medium text-foreground">${__('Order')}</label>` })}`, { id: 'box-attributes' });
2199
+ }
2200
+
2201
+ /**
2202
+ * The Authors box: who wrote the entry, the first its main author, as Git co-authors. People
2203
+ * who edit others' entries add, remove and reorder them; a new entry starts with its creator.
2204
+ */
2205
+ private authorsBox(): TemplateResult {
2206
+ const ids = Array.isArray(this.values.authors) ? (this.values.authors as string[]) : [];
2207
+ // A new entry's creator, loaded first, is its author until others are added.
2208
+ const shown = ids.length ? ids : this.id === 'new' && this.people[0] ? [this.people[0].id] : [];
2209
+ const person = (id: string) => this.people.find(entry => entry.id === id) ?? { id, name: __('Unknown user'), avatar: null };
2210
+ const set = (next: string[]) => this.set('authors', next);
2211
+ const choices = this.people.filter(entry => !shown.includes(entry.id)).map(entry => ({ value: entry.id, label: entry.name }));
2212
+ return box(__('Authors'), this.tracked('authors', html`<ul class="space-y-1.5" data-authors>${shown.map((id, index) => html`<li class="flex items-center gap-2 text-sm">
2213
+ ${component(Avatar, { src: person(id).avatar ?? undefined, alt: person(id).name, size: 24 })}
2214
+ <span class="min-w-0 flex-1 truncate text-foreground">${person(id).name}${index === 0 && shown.length > 1 ? html` <span class="text-xs text-muted-foreground">${__('main')}</span>` : null}</span>
2215
+ ${this.chooseAuthors && index > 0 ? iconButton(`author-${id}-up`, 'arrow-up', `${__('Make main author')} ${person(id).name}`, () => set([id, ...shown.filter(entry => entry !== id)])) : null}
2216
+ ${this.chooseAuthors && shown.length > 1 ? iconButton(`author-${id}-remove`, 'close-circle', `${__('Remove')} ${person(id).name}`, () => set(shown.filter(entry => entry !== id)), { danger: true }) : null}
2217
+ </li>`)}</ul>
2218
+ ${this.chooseAuthors && choices.length ? component(Combobox, { id: 'field-authors-add', options: choices, value: '', placeholder: __('Add an author…'), emptyLabel: __('Nobody matches.'),
2219
+ onValueChange: (value: string) => { if (value) set([...shown, value]); } }) : null}`, { class: 'space-y-3' }), { id: 'box-authors' });
2220
+ }
2221
+
2222
+ private discussionBox(view: EditorView): TemplateResult {
2223
+ return box(__('Discussion'), html`${this.tracked('commentsOpen', html`<div>${component(Checkbox, { id: 'field-commentsOpen', label: __('Allow comments'), checked: this.values.commentsOpen !== false, '@change': (event: Event) => this.set('commentsOpen', (event.target as HTMLInputElement).checked) })}</div>`)}
2224
+ ${this.id === 'new' ? null : html`<a href=${`/dashboard/comments?collection=${view.route}&entry=${this.id}`} class="text-xs text-primary hover:underline">${__('Comments on this entry')}</a>`}`, { id: 'box-discussion' });
2225
+ }
2226
+
2227
+ private revisionsBox(view: EditorView): TemplateResult {
2228
+ return box(__('Revisions'), html`<ol class="space-y-1 text-xs text-muted-foreground">
2229
+ ${this.revisions.map(entry => html`<li>#${entry.revision} · ${shortDate(entry.at)}${entry.actor ? html` · <span class="text-foreground">${entry.actor}</span>` : null}</li>`)}
2230
+ </ol>
2231
+ ${this.revisions.length > 1 ? html`<a href=${`/dashboard/content/${view.route}/${this.id}/revisions`} class="text-sm text-primary hover:underline">${__('Compare and restore')}</a>` : null}`, { id: 'box-revisions' });
2232
+ }
2233
+
2234
+ /**
2235
+ * One of the layout's boxes, by ID; nothing when this entry does not have it (a monolingual
2236
+ * site has no Languages box, a new entry no revisions). Blocks fields such as the content stand
2237
+ * on their own; every other field is a box titled by its label.
2238
+ */
2239
+ private boxView(id: string): TemplateResult | null {
2240
+ const view = this.view!;
2241
+ if (id.startsWith('field:')) {
2242
+ const field = view.fields.find(entry => entry.name === id.slice('field:'.length));
2243
+ if (!field) return null;
2244
+ if (field.kind === 'blocks') return this.fieldRow(field);
2245
+ // A checkbox says its help text, or Yes, since the box's title is the label.
2246
+ const inner = field.kind === 'boolean' ? { ...field, label: field.description || __('Yes'), description: '' } : field;
2247
+ return box(field.label, this.fieldRow(inner, { labelHidden: true }), { id: `box-field-${field.name}` });
2248
+ }
2249
+ if (id.startsWith('group:')) {
2250
+ const group = view.groups.find(entry => entry.id === id.slice('group:'.length));
2251
+ return group ? this.groupBox(group) : null;
2252
+ }
2253
+ if (id.startsWith('taxonomy:')) {
2254
+ const taxonomy = view.taxonomies.find(entry => entry.name === id.slice('taxonomy:'.length));
2255
+ return taxonomy ? this.taxonomyBox(taxonomy) : null;
2256
+ }
2257
+ switch (id) {
2258
+ case 'seo': return view.path !== null && this.values.seo !== undefined ? this.seoBox() : null;
2259
+ case 'attributes': return view.hierarchical ? this.attributesBox() : null;
2260
+ case 'authors': return this.values.authors !== undefined ? this.authorsBox() : null;
2261
+ case 'languages': return this.languages.multilingual && this.values.locale !== undefined && view.resource.startsWith('cms/') ? this.languagesBox(view) : null;
2262
+ case 'template': return this.templateBox();
2263
+ case 'discussion': return this.comments ? this.discussionBox(view) : null;
2264
+ case 'revisions': return this.revisions.length ? this.revisionsBox(view) : null;
2265
+ case 'assistant': return this.assistant ? this.assistantBox() : null;
2266
+ default: return null;
2267
+ }
2268
+ }
2269
+
2270
+ render() {
2271
+ const view = this.view;
2272
+ if (!view) return html`<div class="space-y-4">${notice(this.error || __('Loading…'), this.error ? 'error' : 'info')}${linkButton(__('Back'), `/dashboard/content/${this.route}`, 'outline')}</div>`;
2273
+ const titleField = view.titleField;
2274
+ this.hidden = fieldVisibility(plainBlocks(view.groups.flatMap(group => group.blocks)), visibilityTypes(view.blocks), this.values).hidden;
2275
+ const tabs = this.editorTabs();
2276
+ // A hidden tab keeps what it showed until another tab opens: the renderer leaves the same
2277
+ // template as it is, so typing in one tab renders that tab alone.
2278
+ const active = tabs.includes(this.mode) ? this.mode : tabs[0];
2279
+ const shown = (id: string, content: () => TemplateResult) => {
2280
+ if (id === active) { this.hiddenTabs.delete(id); return content(); }
2281
+ const kept = this.hiddenTabs.get(id);
2282
+ if (kept?.active === active) return kept.content;
2283
+ const fresh = content();
2284
+ this.hiddenTabs.set(id, { active, content: fresh });
2285
+ return fresh;
2286
+ };
2287
+ const tabLabel = (id: string) => id === 'json' ? 'JSON' : __(view.layout.tabs.find(tab => tab.id === id)?.label || id);
2288
+ // A tab's icon, when it names one of the catalog's.
2289
+ const tabIcon = (id: string) => {
2290
+ const name = view.layout.tabs.find(tab => tab.id === id)?.icon;
2291
+ return hasIcon(name) ? html`<span class="mr-1.5 inline-flex align-middle [&_svg]:size-4" aria-hidden="true">${component(Icon, { entry: icon(name), size: 16 })}</span>` : null;
2292
+ };
2293
+ const base = `/dashboard/content/${view.route}`;
2294
+ // Who else is on each tab, for the tab labels.
2295
+ const participants = this.participants();
2296
+ const me = this.myUser();
2297
+ // Forms have no URL: their slug names them where the Form block places them.
2298
+ const form = view.route === 'forms';
2299
+ const permalink = view.slug ? form ? String(this.values.slug ?? '') || '…' : entryUrl(view.path, [String(this.values.slug ?? '') || '…']) : null;
2300
+ // The open Notes rail takes the right of the screen: the editor makes room for it, so the sidebar's boxes and Save stay reachable.
2301
+ return html`<div class=${`space-y-6 ${this.notesOpen ? 'lg:pr-[26rem]' : ''}`}>
2302
+ <div class="flex flex-wrap items-center justify-between gap-3">
2303
+ <div class="flex items-center gap-3">
2304
+ <h1 class="text-2xl font-bold text-foreground">${this.id === 'new' ? `${__('New')} ${view.singular.toLowerCase()}` : `${__('Edit')} ${view.singular.toLowerCase()}`}</h1>
2305
+ ${this.id === 'new' ? null : linkButton(__('New'), `${base}/new`, 'outline')}
2306
+ </div>
2307
+ <div class="flex items-center gap-3 text-sm">
2308
+ ${this.id !== 'new' ? component(EntryRoom, this.roomProps()) : null}
2309
+ ${this.notesToggle()}
2310
+ ${this.room && !this.roomStatus.connected ? html`<span role="status" class="text-xs text-muted-foreground">${__('Reconnecting…')}</span>` : null}
2311
+ ${this.meta.url ? html`<a href=${this.meta.url} class="text-primary hover:underline" target="_blank" rel="noopener">${__('View')} ${view.singular.toLowerCase()} ↗</a>` : null}
2312
+ ${form && this.id !== 'new' ? html`<a href=${`/dashboard/forms/${this.id}/submissions`} class="text-primary hover:underline">${__('Submissions')}</a>` : null}
2313
+ <a href=${form ? '/dashboard/forms' : base} class="text-muted-foreground hover:text-foreground">← ${__('All')} ${view.label.toLowerCase()}</a>
2314
+ </div>
2315
+ </div>
2316
+ ${this.message ? notice(this.message, 'success') : null}
2317
+ ${this.error ? notice(this.describe(this.error), 'error') : null}
2318
+ ${this.roomStatus.diverged ? html`<div role="status" class="flex flex-wrap items-center justify-between gap-3 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-foreground">
2319
+ <span>${__('This entry was changed outside the editor. The draft here no longer starts from the saved entry.')}</span>
2320
+ ${component(Button, { type: 'button', size: 'sm', '@click': () => { void this.room?.reload(); } }, __('Reload the draft from the entry'))}
2321
+ </div>` : null}
2322
+ ${this.roomStatus.oversized ? notice(__('The draft is too large to be kept between sessions. Save soon, or shorten it.'), 'warning') : null}
2323
+ ${this.autosaveOffer ? html`<div role="status" class="flex flex-wrap items-center justify-between gap-3 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-foreground">
2324
+ <span>${this.id === 'new' ? __('You have unsaved work from') : __('There is an autosave of this entry that is newer than the version below, from')} ${shortDate(this.autosaveOffer.at)}.</span>
2325
+ <span class="flex gap-2">${component(Button, { type: 'button', size: 'sm', '@click': () => this.restore() }, __('Restore the autosave'))}
2326
+ ${component(Button, { type: 'button', size: 'sm', variant: 'ghost', '@click': () => this.dismissAutosave() }, __('Dismiss'))}</span>
2327
+ </div>` : null}
2328
+ <div class=${`grid gap-x-6 ${this.mode === 'json' ? '' : 'lg:grid-cols-[minmax(0,1fr)_20rem]'}`}>
2329
+ ${component(Tabs, {
2330
+ id: 'entry', label: __('Editor view'), value: this.mode, variant: 'underline', class: 'contents [&>.cs-tabs__panel]:min-w-0',
2331
+ listProps: { class: `col-span-full w-full flex-wrap [&>[data-value=json]]:ms-auto ${tabs.length > 1 ? '' : 'hidden'}` },
2332
+ onValueChange: (mode: string) => this.showMode(mode),
2333
+ items: [...view.layout.tabs.map((tab, index) => ({
2334
+ value: tab.id, ariaLabel: `${tabLabel(tab.id)}${this.errorsOn(tab.id) ? ` (${this.errorsOn(tab.id)})` : ''}${onTab(participants, tab.id, me).length ? `. ${__('Here')}: ${namesOf(onTab(participants, tab.id, me))}` : ''}`,
2335
+ label: html`<span class=${this.errorsOn(tab.id) ? 'text-destructive' : ''}>${tabIcon(tab.id)}${tabLabel(tab.id)}${this.errorsOn(tab.id) ? countBadge(this.errorsOn(tab.id)) : null}${onTab(participants, tab.id, me).length ? html`<span class="ml-1.5 inline-flex align-middle">${avatarStack(onTab(participants, tab.id, me), { size: 16, max: 3, label: `${tabLabel(tab.id)}: ${__('here')}` })}</span>` : null}</span>`,
2336
+ content: shown(tab.id, () => html`<div class="space-y-5">
2337
+ ${index === 0 && titleField ? html`<div class="group space-y-1" data-field=${titleField} style=${presenceOutline(this.peersIn(titleField))}>
2338
+ ${this.peersIn(titleField).length ? presenceChip(this.peersIn(titleField), __('is here')) : null}
2339
+ <label for="field-title" class="sr-only">${__('Title')}</label>
2340
+ <div class="relative">
2341
+ <input id="field-title" class=${`w-full rounded-lg border bg-background px-4 py-3 pr-20 text-xl font-semibold text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring ${this.errors[titleField] ? 'border-destructive' : 'border-input'}`}
2342
+ placeholder=${__('Add title')} .value=${String(this.values[titleField] ?? '')} @input=${(event: Event) => this.setTitle((event.target as HTMLInputElement).value)}
2343
+ ?required=${view.titleRequired} aria-invalid=${this.errors[titleField] ? 'true' : 'false'} aria-describedby=${this.errors[titleField] ? 'field-title-error' : undefined}>
2344
+ <span class="absolute right-3 top-1/2 -translate-y-1/2">${this.noteTools(titleField)}</span>
2345
+ </div>
2346
+ ${this.errors[titleField] ? html`<p id="field-title-error" role="alert" class="text-xs text-destructive">${this.errors[titleField]}</p>` : null}
2347
+ </div>` : null}
2348
+ ${index === 0 && permalink !== null ? html`<div class="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
2349
+ <span>${form ? __('Slug') : __('Permalink')}:</span>
2350
+ ${this.editingSlug ? html`<input id="field-slug" class=${`${CONTROL} max-w-xs py-1`} aria-label=${__('Slug')} .value=${String(this.values.slug ?? '')}
2351
+ @input=${(event: Event) => this.setSlug((event.target as HTMLInputElement).value)}>
2352
+ ${component(Button, { type: 'button', size: 'sm', variant: 'outline', '@click': () => { this.editingSlug = false; } }, __('OK'))}`
2353
+ : html`<code class="rounded bg-muted px-1.5 py-0.5 text-foreground">${permalink}</code>
2354
+ <button type="button" class="text-primary hover:underline bg-transparent border-none p-0 cursor-pointer" @click=${() => { this.editingSlug = true; }}>${__('Edit')}</button>`}
2355
+ <span class="sr-only" aria-live="polite">${String(this.values.slug ?? '')}</span>
2356
+ ${form ? html`<span class="basis-full text-xs">${__('Place the form on a page with the Form block and this slug.')}</span>` : null}
2357
+ ${this.errorFor('slug')}
2358
+ </div>` : null}
2359
+ ${editorLayoutView(tab.blocks, id => this.boxView(id))}
2360
+ </div>`),
2361
+ })), ...(tabs.includes('json') ? [{ value: 'json', label: 'JSON', content: this.mode === 'json' ? this.jsonPanel() : null }] : [])],
2362
+ })}
2363
+ <aside class=${`mt-4 space-y-4 ${this.mode === 'json' ? 'hidden' : ''}`}>
2364
+ ${this.publishBox(view)}
2365
+ ${editorLayoutView(view.layout.sidebar, id => this.boxView(id), { sidebar: true })}
2366
+ </aside>
2367
+ </div>
2368
+ ${this.pickerModal()}
2369
+ ${this.blockDialogModal()}
2370
+ ${this.patternModal()}
2371
+ ${this.notesRailView()}
2372
+ ${this.noteRemovalModal()}
2373
+ </div>`;
2374
+ }
2375
+ }
2376
+
2377
+ /** The sidebar's keys in words, for note anchors on them. */
2378
+ const SIDEBAR_LABELS: Record<string, string> = {
2379
+ status: 'Status', publishedAt: 'Publish date', parent: 'Parent', menuOrder: 'Order', template: 'Template', authors: 'Authors', commentsOpen: 'Discussion', summary: 'Summary',
2380
+ 'seo.title': 'SEO title', 'seo.description': 'Meta description', 'seo.socialTitle': 'Social title', 'seo.socialDescription': 'Social description', 'seo.image': 'Social image',
2381
+ 'seo.canonical': 'Canonical URL', 'seo.noindex': 'Hide from search engines', 'seo.cornerstone': 'Cornerstone content', 'seo.nosnippet': 'No snippets', 'seo.maxSnippet': 'Longest quote', 'seo.noarchive': 'No cached copy',
2382
+ };