@brimsites/brimjs 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +22 -2
  3. package/bin/brim.js +5 -0
  4. package/dist/cli.js +3802 -0
  5. package/editor-dist/editor.css +1 -0
  6. package/editor-dist/editor.js +91 -0
  7. package/package.json +71 -3
  8. package/skills/brim-convert/SKILL.md +256 -0
  9. package/skills/brim-hosting/SKILL.md +221 -0
  10. package/src/astro-shim.d.ts +5 -0
  11. package/src/auth/accounts.ts +341 -0
  12. package/src/auth/password.ts +34 -0
  13. package/src/auth/permissions.ts +44 -0
  14. package/src/blocks/accordion/Accordion.astro +48 -0
  15. package/src/blocks/accordion/accordion.css +63 -0
  16. package/src/blocks/analytics/Analytics.astro +45 -0
  17. package/src/blocks/analytics/ConsentBanner.astro +41 -0
  18. package/src/blocks/analytics/analytics.client.ts +125 -0
  19. package/src/blocks/analytics/analytics.css +51 -0
  20. package/src/blocks/analytics/consent.ts +51 -0
  21. package/src/blocks/button/Button.astro +64 -0
  22. package/src/blocks/button/button.css +100 -0
  23. package/src/blocks/carousel/Carousel.astro +140 -0
  24. package/src/blocks/carousel/carousel.client.ts +153 -0
  25. package/src/blocks/carousel/carousel.css +181 -0
  26. package/src/blocks/data/icons.ts +285 -0
  27. package/src/blocks/data/image-shapes.ts +91 -0
  28. package/src/blocks/data/social-icons.ts +41 -0
  29. package/src/blocks/data/social-networks.ts +256 -0
  30. package/src/blocks/divider/Divider.astro +27 -0
  31. package/src/blocks/divider/divider.css +17 -0
  32. package/src/blocks/form/Captcha.astro +27 -0
  33. package/src/blocks/form/Form.astro +250 -0
  34. package/src/blocks/form/FormField.astro +138 -0
  35. package/src/blocks/form/Newsletter.astro +80 -0
  36. package/src/blocks/form/form.client.ts +339 -0
  37. package/src/blocks/form/form.css +271 -0
  38. package/src/blocks/gallery/ImageGallery.astro +126 -0
  39. package/src/blocks/gallery/gallery.css +43 -0
  40. package/src/blocks/gallery/lightbox.client.ts +178 -0
  41. package/src/blocks/gallery/lightbox.css +134 -0
  42. package/src/blocks/icon/Icon.astro +41 -0
  43. package/src/blocks/icon/icon.css +16 -0
  44. package/src/blocks/image/Image.astro +158 -0
  45. package/src/blocks/image/image.css +42 -0
  46. package/src/blocks/images.ts +64 -0
  47. package/src/blocks/in-editor.client.ts +8 -0
  48. package/src/blocks/listing/Listing.astro +288 -0
  49. package/src/blocks/listing/ListingCards.astro +48 -0
  50. package/src/blocks/listing/listing.css +136 -0
  51. package/src/blocks/listing/query.ts +363 -0
  52. package/src/blocks/map/Map.astro +75 -0
  53. package/src/blocks/map/map.css +32 -0
  54. package/src/blocks/schemas/accordion.ts +118 -0
  55. package/src/blocks/schemas/button.ts +78 -0
  56. package/src/blocks/schemas/carousel.ts +133 -0
  57. package/src/blocks/schemas/divider.ts +29 -0
  58. package/src/blocks/schemas/form-field-types.ts +29 -0
  59. package/src/blocks/schemas/form.ts +350 -0
  60. package/src/blocks/schemas/icon.ts +24 -0
  61. package/src/blocks/schemas/image-gallery.ts +54 -0
  62. package/src/blocks/schemas/image.ts +87 -0
  63. package/src/blocks/schemas/index.ts +33 -0
  64. package/src/blocks/schemas/listing.ts +14 -0
  65. package/src/blocks/schemas/map.ts +81 -0
  66. package/src/blocks/schemas/newsletter.ts +324 -0
  67. package/src/blocks/schemas/social-media.ts +348 -0
  68. package/src/blocks/schemas/text.ts +151 -0
  69. package/src/blocks/schemas/video.ts +57 -0
  70. package/src/blocks/search/Search.astro +147 -0
  71. package/src/blocks/search/search.css +69 -0
  72. package/src/blocks/search/state.ts +28 -0
  73. package/src/blocks/settings.ts +94 -0
  74. package/src/blocks/social/SocialMedia.astro +102 -0
  75. package/src/blocks/social/social-links.ts +16 -0
  76. package/src/blocks/social/social.css +31 -0
  77. package/src/blocks/theme.ts +35 -0
  78. package/src/blocks/types.ts +52 -0
  79. package/src/blocks/video/Video.astro +90 -0
  80. package/src/blocks/video/video-source.ts +77 -0
  81. package/src/blocks/video/video.client.ts +43 -0
  82. package/src/blocks/video/video.css +29 -0
  83. package/src/check.ts +1119 -0
  84. package/src/cli.ts +493 -0
  85. package/src/components/Blocks.astro +68 -0
  86. package/src/components/Field.astro +61 -0
  87. package/src/components/Footer.astro +36 -0
  88. package/src/components/Link.astro +18 -0
  89. package/src/components/MobileMenu.astro +77 -0
  90. package/src/components/Navbar.astro +42 -0
  91. package/src/components/RichText.astro +32 -0
  92. package/src/components/Seo.astro +202 -0
  93. package/src/components/Setting.astro +46 -0
  94. package/src/components/Shared.astro +17 -0
  95. package/src/components/Text.astro +91 -0
  96. package/src/components/blocks.css +86 -0
  97. package/src/components/index.ts +27 -0
  98. package/src/components/mobile-menu.client.ts +21 -0
  99. package/src/components/mobile-menu.css +52 -0
  100. package/src/components/text.css +48 -0
  101. package/src/config.ts +413 -0
  102. package/src/content/block-layout.ts +63 -0
  103. package/src/content/block-values.ts +48 -0
  104. package/src/content/content-check.ts +174 -0
  105. package/src/content/content-types.ts +408 -0
  106. package/src/content/drafts.ts +115 -0
  107. package/src/content/feed.ts +237 -0
  108. package/src/content/field-types.ts +107 -0
  109. package/src/content/history.ts +140 -0
  110. package/src/content/ids.ts +50 -0
  111. package/src/content/image-size.ts +212 -0
  112. package/src/content/image-sizes.ts +126 -0
  113. package/src/content/item-fields.ts +110 -0
  114. package/src/content/item-head.ts +126 -0
  115. package/src/content/item-image.ts +26 -0
  116. package/src/content/item-path.ts +122 -0
  117. package/src/content/items.ts +580 -0
  118. package/src/content/language-scopes.ts +40 -0
  119. package/src/content/media.ts +271 -0
  120. package/src/content/menus.ts +51 -0
  121. package/src/content/page-templates.ts +52 -0
  122. package/src/content/redirects.ts +112 -0
  123. package/src/content/references.ts +165 -0
  124. package/src/content/rich-text.ts +63 -0
  125. package/src/content/search.ts +167 -0
  126. package/src/content/seed.ts +229 -0
  127. package/src/content/site-settings.ts +111 -0
  128. package/src/content/sitemap.ts +143 -0
  129. package/src/content/store.ts +225 -0
  130. package/src/content/tags.ts +67 -0
  131. package/src/content/text-default.ts +139 -0
  132. package/src/content/types.ts +137 -0
  133. package/src/content/validate.ts +253 -0
  134. package/src/content/validation-error.ts +2 -0
  135. package/src/db/cached.ts +140 -0
  136. package/src/db/database.ts +15 -0
  137. package/src/db/libsql.ts +29 -0
  138. package/src/db/schema.ts +189 -0
  139. package/src/db/url.ts +44 -0
  140. package/src/editor/client/BlockSettings.tsx +1063 -0
  141. package/src/editor/client/Chrome.tsx +284 -0
  142. package/src/editor/client/ContentBrowser.tsx +1299 -0
  143. package/src/editor/client/Editor.tsx +1756 -0
  144. package/src/editor/client/HistoryPanel.tsx +114 -0
  145. package/src/editor/client/ImagesWidget.tsx +113 -0
  146. package/src/editor/client/Inspector.tsx +127 -0
  147. package/src/editor/client/ItemForm.tsx +535 -0
  148. package/src/editor/client/LinkWidget.tsx +440 -0
  149. package/src/editor/client/ListingPanel.tsx +99 -0
  150. package/src/editor/client/Login.tsx +338 -0
  151. package/src/editor/client/Menu.tsx +64 -0
  152. package/src/editor/client/PageSettings.tsx +270 -0
  153. package/src/editor/client/RedirectsSettings.tsx +130 -0
  154. package/src/editor/client/Resize.tsx +204 -0
  155. package/src/editor/client/Sidebar.tsx +51 -0
  156. package/src/editor/client/SiteMap.tsx +568 -0
  157. package/src/editor/client/SiteSettings.tsx +409 -0
  158. package/src/editor/client/TextTools.tsx +391 -0
  159. package/src/editor/client/Toolbar.tsx +449 -0
  160. package/src/editor/client/VideoUpload.tsx +251 -0
  161. package/src/editor/client/api.ts +417 -0
  162. package/src/editor/client/brand.ts +20 -0
  163. package/src/editor/client/connection.ts +98 -0
  164. package/src/editor/client/context.ts +19 -0
  165. package/src/editor/client/css.d.ts +2 -0
  166. package/src/editor/client/editor.css +4656 -0
  167. package/src/editor/client/fields.tsx +812 -0
  168. package/src/editor/client/icons.tsx +174 -0
  169. package/src/editor/client/keys.ts +15 -0
  170. package/src/editor/client/kinds.ts +289 -0
  171. package/src/editor/client/languages.ts +32 -0
  172. package/src/editor/client/main.tsx +100 -0
  173. package/src/editor/client/responses.ts +26 -0
  174. package/src/editor/client/rich-text.ts +326 -0
  175. package/src/editor/client/site-tree.ts +239 -0
  176. package/src/editor/client/theme.ts +55 -0
  177. package/src/editor/client/tsconfig.json +18 -0
  178. package/src/editor/client/tus.ts +137 -0
  179. package/src/editor/client/use-rect.ts +50 -0
  180. package/src/editor/client/widgets.tsx +1218 -0
  181. package/src/forms/captcha.ts +83 -0
  182. package/src/forms/define.ts +166 -0
  183. package/src/forms/fields.ts +197 -0
  184. package/src/forms/file-types.ts +108 -0
  185. package/src/forms/files.ts +216 -0
  186. package/src/forms/form-page.ts +9 -0
  187. package/src/forms/handler.ts +622 -0
  188. package/src/forms/spec.ts +89 -0
  189. package/src/forms/store.ts +96 -0
  190. package/src/forms/work.ts +50 -0
  191. package/src/icons/library.ts +144 -0
  192. package/src/icons/load.ts +63 -0
  193. package/src/index.ts +99 -0
  194. package/src/init.ts +257 -0
  195. package/src/integration.ts +469 -0
  196. package/src/mail/mailer.ts +197 -0
  197. package/src/mail/notify.ts +272 -0
  198. package/src/mail/settings.ts +173 -0
  199. package/src/mail/templates.ts +191 -0
  200. package/src/mcp/page-nodes.ts +209 -0
  201. package/src/mcp/server.ts +111 -0
  202. package/src/mcp/tools.ts +637 -0
  203. package/src/runtime/TemplatePage.astro +39 -0
  204. package/src/runtime/TemplatePageStatic.astro +13 -0
  205. package/src/runtime/admin-route.ts +80 -0
  206. package/src/runtime/connect.ts +53 -0
  207. package/src/runtime/content.ts +188 -0
  208. package/src/runtime/context.ts +131 -0
  209. package/src/runtime/form-files.ts +18 -0
  210. package/src/runtime/forms-route.ts +33 -0
  211. package/src/runtime/forms.ts +28 -0
  212. package/src/runtime/icons.ts +5 -0
  213. package/src/runtime/media.ts +175 -0
  214. package/src/runtime/middleware.ts +186 -0
  215. package/src/runtime/nav.ts +13 -0
  216. package/src/runtime/query-reads.ts +49 -0
  217. package/src/runtime/query-store.ts +16 -0
  218. package/src/runtime/request-state.ts +69 -0
  219. package/src/runtime/robots.ts +29 -0
  220. package/src/runtime/rss-static.ts +16 -0
  221. package/src/runtime/rss.ts +29 -0
  222. package/src/runtime/server.ts +29 -0
  223. package/src/runtime/sitemap.ts +34 -0
  224. package/src/runtime/template-paths.ts +34 -0
  225. package/src/runtime/uploads-route.ts +13 -0
  226. package/src/seed-cli.ts +253 -0
  227. package/src/server/auth.ts +31 -0
  228. package/src/server/fetch-image.ts +219 -0
  229. package/src/server/handler.ts +2106 -0
  230. package/src/server/http.ts +162 -0
  231. package/src/server/locales.ts +73 -0
  232. package/src/server/node.ts +57 -0
  233. package/src/server/query-params.ts +249 -0
  234. package/src/server/rate-limit.ts +72 -0
  235. package/src/server/video-host.ts +162 -0
  236. package/src/starter.ts +70 -0
  237. package/src/version.ts +4 -0
  238. package/src/virtual.d.ts +65 -0
@@ -0,0 +1,535 @@
1
+ import { type ReactNode, useEffect, useRef, useState } from "react";
2
+ import { optionValues, optionsOf } from "../../content/content-types.ts";
3
+ import { renderBlocks } from "../../content/rich-text.ts";
4
+ import { rankTags, tagsOf } from "../../content/tags.ts";
5
+ import type { RichTextValue } from "../../content/types.ts";
6
+ import { type ContentField, type ContentType, type Item, type ItemDraft, api } from "./api.ts";
7
+ import {
8
+ CheckboxWidget,
9
+ DateWidget,
10
+ ImageWidget,
11
+ type ReferenceTerm,
12
+ ReferenceWidget,
13
+ SelectWidget,
14
+ SettingField,
15
+ TagsWidget,
16
+ TextWidget,
17
+ } from "./fields.tsx";
18
+ import type { Schema } from "./kinds.ts";
19
+ import { GalleryFieldWidget } from "./ImagesWidget.tsx";
20
+ import { LinkWidget } from "./LinkWidget.tsx";
21
+ import { dropTransferred, insertTransferred, readBlocks, readTransfer } from "./rich-text.ts";
22
+ import { MediaFolderContext } from "./widgets.tsx";
23
+ import { TextTools } from "./TextTools.tsx";
24
+
25
+ /** The item in the site's languages: which exist, which is this one, and how to open or add the others. */
26
+ export interface ItemLanguages {
27
+ codes: string[];
28
+ current: string;
29
+ items: Record<string, Item | undefined>;
30
+ onOpen: (item: Item) => void;
31
+ onTranslate: (code: string) => void;
32
+ }
33
+
34
+ const VISIBILITY_OPTIONS = [
35
+ { value: "published", label: "Published" },
36
+ { value: "private", label: "Private" },
37
+ ];
38
+
39
+ // Each row is two text boxes; rows left wholly empty are dropped when the item is saved.
40
+ const KEY_VALUE: Schema = {
41
+ type: "list",
42
+ label: "Rows",
43
+ addLabel: "Add row",
44
+ item: { type: "group", fields: { label: { type: "text", label: "Label" }, value: { type: "text", label: "Value" } } },
45
+ };
46
+
47
+ const LEAVE_UNSAVED = "Leave without saving? Your changes to this item will be lost.";
48
+
49
+ /** The form for one item of a content type: its title, address, visibility and the fields the type declares. */
50
+ export function ItemForm({
51
+ type,
52
+ item,
53
+ initialData,
54
+ error,
55
+ onSave,
56
+ onDelete,
57
+ onCancel,
58
+ onDirty,
59
+ languages,
60
+ }: {
61
+ type: ContentType;
62
+ item: Item | undefined;
63
+ /** What a new item's fields start with. */
64
+ initialData?: Record<string, unknown> | undefined;
65
+ /** Why the last save was refused. */
66
+ error: string | undefined;
67
+ onSave: (draft: ItemDraft) => void;
68
+ onDelete: (() => void) | undefined;
69
+ onCancel: () => void;
70
+ /** Told whether the form has changes not saved yet, so leaving it another way can ask first. */
71
+ onDirty?: ((dirty: boolean) => void) | undefined;
72
+ /** On a site with languages: the item in each of them, and how to open or add one. */
73
+ languages?: ItemLanguages | undefined;
74
+ }) {
75
+ // A new item stays out of sight until it is published, like a new page.
76
+ const [draft, setDraft] = useState<ItemDraft>(
77
+ () => item ?? { title: "", slug: "", visibility: "private", data: { ...initialData } },
78
+ );
79
+ const [start] = useState(draft);
80
+ const dirty = JSON.stringify(draft) !== JSON.stringify(start);
81
+ const dirtyRef = useRef(dirty);
82
+ dirtyRef.current = dirty;
83
+ useEffect(() => onDirty?.(dirty), [dirty]);
84
+ // Gone (saved, or left after asking): it holds nothing unsaved any more.
85
+ useEffect(() => () => onDirty?.(false), []);
86
+
87
+ // Closing the tab or reloading with changes in the form would lose them.
88
+ useEffect(() => {
89
+ if (!dirty) return;
90
+ const onBeforeUnload = (event: BeforeUnloadEvent): void => event.preventDefault();
91
+ window.addEventListener("beforeunload", onBeforeUnload);
92
+ return () => window.removeEventListener("beforeunload", onBeforeUnload);
93
+ }, [dirty]);
94
+
95
+ /** Runs `leave` once the owner agrees to lose what is not saved; at once when nothing is. */
96
+ const leaving =
97
+ (leave: () => void) =>
98
+ (): void => {
99
+ if (!dirtyRef.current || window.confirm(LEAVE_UNSAVED)) leave();
100
+ };
101
+
102
+ return (
103
+ <MediaFolderContext.Provider
104
+ value={item ? { key: `${type.key}/${item.id}`, label: item.title } : { label: type.singular.toLowerCase() }}
105
+ >
106
+ <form
107
+ className="cb-item-form"
108
+ onSubmit={(event) => {
109
+ event.preventDefault();
110
+ onSave(draft);
111
+ }}
112
+ >
113
+ <header className="cb-item-form__header">
114
+ <h2>{item ? item.title : `New ${type.singular.toLowerCase()}`}</h2>
115
+ <div className="cb-item-form__actions">
116
+ <button type="button" className="cb-toolbar-btn" onClick={leaving(onCancel)}>
117
+ Cancel
118
+ </button>
119
+ {onDelete && (
120
+ <button type="button" className="cb-toolbar-btn danger" onClick={onDelete}>
121
+ Delete
122
+ </button>
123
+ )}
124
+ <button type="submit" className="cb-new-btn">
125
+ {item ? "Save" : `Create ${type.singular}`}
126
+ </button>
127
+ </div>
128
+ </header>
129
+ {languages && (
130
+ <div className="cb-item-languages" role="group" aria-label="Languages">
131
+ <span className="cb-item-languages__label">Language</span>
132
+ {languages.codes.map((code) => {
133
+ const translation = languages.items[code];
134
+ const current = code === languages.current;
135
+ return translation ? (
136
+ <button
137
+ key={code}
138
+ type="button"
139
+ className="cb-language-chip"
140
+ aria-current={current ? "true" : undefined}
141
+ title={current ? "This item" : `Open the ${code.toUpperCase()} version`}
142
+ disabled={current}
143
+ onClick={leaving(() => languages.onOpen(translation))}
144
+ >
145
+ {code.toUpperCase()}
146
+ </button>
147
+ ) : (
148
+ <button
149
+ key={code}
150
+ type="button"
151
+ className="cb-language-chip cb-language-chip--missing"
152
+ disabled={!item}
153
+ title={item ? `Translate into ${code.toUpperCase()}: a private copy to translate` : "Save first"}
154
+ onClick={leaving(() => languages.onTranslate(code))}
155
+ >
156
+ + {code.toUpperCase()}
157
+ </button>
158
+ );
159
+ })}
160
+ </div>
161
+ )}
162
+ {error && (
163
+ <p className="field-error cb-item-form__error" role="alert">
164
+ {error}
165
+ </p>
166
+ )}
167
+ <ItemFields type={type} draft={draft} onChange={setDraft} />
168
+ <SelectWidget
169
+ label="Visibility"
170
+ options={VISIBILITY_OPTIONS}
171
+ value={draft.visibility}
172
+ onChange={(visibility) => setDraft({ ...draft, visibility: visibility as ItemDraft["visibility"] })}
173
+ />
174
+ </form>
175
+ </MediaFolderContext.Provider>
176
+ );
177
+ }
178
+
179
+ /** An item's title, address and the fields its type declares: in the item form, and beside the item's page. */
180
+ export function ItemFields({
181
+ type,
182
+ draft,
183
+ onChange,
184
+ onDraft,
185
+ }: {
186
+ type: ContentType;
187
+ draft: ItemDraft;
188
+ onChange: (draft: ItemDraft) => void;
189
+ /** Each keystroke in a text field, before it is saved on blur: for a live preview of the page. */
190
+ onDraft?: ((field: string, value: unknown) => void) | undefined;
191
+ }): ReactNode {
192
+ return (
193
+ <>
194
+ <TextWidget
195
+ label="Title"
196
+ value={draft.title}
197
+ onDraft={onDraft && ((title) => onDraft("title", title))}
198
+ onChange={(title) => onChange({ ...draft, title })}
199
+ />
200
+ <TextWidget
201
+ label="Address"
202
+ description={`The item's own part of its link: ${(type.path ?? `/${type.slug}/[slug]`).replace("[slug]", "…")} Empty makes it from the title.`}
203
+ value={draft.slug}
204
+ onChange={(slug) => onChange({ ...draft, slug })}
205
+ />
206
+ {type.fields.map((field) => (
207
+ <ItemField
208
+ key={field.name}
209
+ type={type}
210
+ field={field}
211
+ value={draft.data[field.name]}
212
+ onDraft={onDraft && ((value) => onDraft(field.name, value))}
213
+ onChange={(value) => onChange({ ...draft, data: { ...draft.data, [field.name]: value } })}
214
+ />
215
+ ))}
216
+ </>
217
+ );
218
+ }
219
+
220
+ /** One field of an item with its widget: in the item form, the page settings, and beside an element showing it. */
221
+ export function ItemField({
222
+ type,
223
+ field,
224
+ value,
225
+ onDraft,
226
+ onChange,
227
+ }: {
228
+ type: ContentType;
229
+ field: ContentField;
230
+ value: unknown;
231
+ /** Each keystroke in a text field, before it is saved on blur. */
232
+ onDraft?: ((value: string) => void) | undefined;
233
+ onChange: (value: unknown) => void;
234
+ }): ReactNode {
235
+ const label = field.required ? `${field.label} *` : field.label;
236
+ const text = typeof value === "string" ? value : "";
237
+
238
+ switch (field.type) {
239
+ case "text":
240
+ return <TextWidget label={label} description={field.help} value={text} onDraft={onDraft} onChange={onChange} />;
241
+ case "url":
242
+ return <LinkWidget label={label} description={field.help} value={text} onChange={onChange} />;
243
+ case "email":
244
+ return <TextWidget label={label} description={field.help} type="email" value={text} onChange={onChange} />;
245
+ case "date":
246
+ return <DateWidget label={label} description={field.help} value={text} onChange={onChange} />;
247
+ case "textarea":
248
+ return (
249
+ <TextWidget
250
+ label={label}
251
+ description={field.help}
252
+ value={text}
253
+ multiline
254
+ onDraft={onDraft}
255
+ onChange={onChange}
256
+ />
257
+ );
258
+ case "number":
259
+ return (
260
+ <TextWidget
261
+ label={label}
262
+ description={field.help}
263
+ value={typeof value === "number" ? String(value) : ""}
264
+ onChange={(next) => onChange(next.trim() === "" ? undefined : Number(next))}
265
+ />
266
+ );
267
+ case "boolean":
268
+ return <CheckboxWidget label={label} description={field.help} checked={value === true} onChange={onChange} />;
269
+ case "select":
270
+ return (
271
+ <SelectWidget
272
+ label={label}
273
+ description={field.help}
274
+ options={optionsOf(field)}
275
+ value={text}
276
+ onChange={onChange}
277
+ />
278
+ );
279
+ case "image":
280
+ return <ImageWidget label={label} value={(value ?? {}) as Record<string, unknown>} onChange={onChange} />;
281
+ case "gallery":
282
+ return <GalleryFieldWidget label={label} value={value} onChange={onChange} />;
283
+ case "richtext":
284
+ return <RichTextField label={label} value={value as RichTextValue | undefined} onChange={onChange} />;
285
+ case "keyvalue":
286
+ return <KeyValueField label={label} value={value} onChange={onChange} />;
287
+ case "reference":
288
+ return <ReferenceField field={field} label={label} value={value} onChange={onChange} />;
289
+ case "tags":
290
+ return <TagsField type={type} field={field} label={label} value={tagsOf(value)} onChange={onChange} />;
291
+ case "blocks":
292
+ // Blocks are added and arranged on the item's page, where they are seen.
293
+ return (
294
+ <div className="field-group">
295
+ <span className="field-label">{label}</span>
296
+ <p className="field-description">{field.help ?? "Added and arranged on the page itself."}</p>
297
+ </div>
298
+ );
299
+ }
300
+ }
301
+
302
+ /** An item's tags, offering its field's own list, or else the tags the type's other items already have. */
303
+ function TagsField({
304
+ type,
305
+ field,
306
+ label,
307
+ value,
308
+ onChange,
309
+ }: {
310
+ type: ContentType;
311
+ field: ContentField;
312
+ label: string;
313
+ value: string[];
314
+ onChange: (tags: string[]) => void;
315
+ }) {
316
+ const fixed = field.options !== undefined && field.options.length > 0;
317
+ const [used, setUsed] = useState<string[]>([]);
318
+ useEffect(() => {
319
+ if (fixed) return;
320
+ let current = true;
321
+ api.items(type.key).then(
322
+ ({ items }) => current && setUsed(rankTags(items.map((item) => item.data[field.name])).map(({ tag }) => tag)),
323
+ () => undefined,
324
+ );
325
+ return () => {
326
+ current = false;
327
+ };
328
+ }, [type.key, field.name, fixed]);
329
+
330
+ return (
331
+ <TagsWidget
332
+ label={label}
333
+ description={field.help}
334
+ value={value}
335
+ suggestions={fixed ? optionValues(field) : used}
336
+ fixed={fixed}
337
+ onChange={onChange}
338
+ />
339
+ );
340
+ }
341
+
342
+ /**
343
+ * A reference field: the vocabulary's terms in the one reference widget, and new terms added to the vocabulary from
344
+ * here (published when the user may publish, else private, as any new item).
345
+ */
346
+ function ReferenceField({
347
+ field,
348
+ label,
349
+ value,
350
+ onChange,
351
+ }: {
352
+ field: ContentField;
353
+ label: string;
354
+ value: unknown;
355
+ onChange: (value: unknown) => void;
356
+ }) {
357
+ const [target, setTarget] = useState<ContentType | undefined>(undefined);
358
+ useEffect(() => {
359
+ let current = true;
360
+ contentTypes().then(
361
+ (types) => current && setTarget(types.find((candidate) => candidate.key === field.to)),
362
+ () => undefined,
363
+ );
364
+ return () => {
365
+ current = false;
366
+ };
367
+ }, [field.to]);
368
+ const [terms, setTerms] = useState<ReferenceTerm[]>([]);
369
+ useEffect(() => {
370
+ let current = true;
371
+ api.items(field.to ?? "").then(
372
+ ({ items }) => current && setTerms(termsOf(items)),
373
+ () => undefined,
374
+ );
375
+ return () => {
376
+ current = false;
377
+ };
378
+ }, [field.to]);
379
+
380
+ const slugs = Array.isArray(value) ? (value as string[]) : typeof value === "string" && value ? [value] : [];
381
+ const vocabulary = target?.label ?? field.to ?? "";
382
+ const description = field.help ?? (target ? `From the vocabulary ${target.label}.` : undefined);
383
+
384
+ async function add(title: string): Promise<ReferenceTerm | undefined> {
385
+ if (!field.to) return undefined;
386
+ const made = await api.createItem(field.to, { title, slug: "", visibility: "published", data: {} });
387
+ const term = { value: made.item.slug, label: made.item.title };
388
+ setTerms((known) => [...known, term].sort((a, b) => a.label.localeCompare(b.label)));
389
+ return term;
390
+ }
391
+
392
+ return (
393
+ <ReferenceWidget
394
+ label={label}
395
+ description={description}
396
+ vocabulary={vocabulary}
397
+ terms={terms}
398
+ value={slugs}
399
+ multiple={field.multiple === true}
400
+ required={field.required === true}
401
+ onChange={(next) => onChange(field.multiple ? next : (next[0] ?? undefined))}
402
+ onAdd={add}
403
+ />
404
+ );
405
+ }
406
+
407
+ /** The site's content types, asked once: a form with several reference fields needs their names, not new requests. */
408
+ let typesRequest: Promise<ContentType[]> | undefined;
409
+ function contentTypes(): Promise<ContentType[]> {
410
+ typesRequest ??= api.types().then(({ types }) => types);
411
+ typesRequest.catch(() => (typesRequest = undefined));
412
+ return typesRequest;
413
+ }
414
+
415
+ /** A vocabulary's terms by title; a translated term shares its slug, so it is listed once, by its default title. */
416
+ function termsOf(items: Item[]): ReferenceTerm[] {
417
+ const bySlug = new Map<string, string>();
418
+ for (const item of [...items].sort((a, b) => Number(a.locale !== "") - Number(b.locale !== ""))) {
419
+ if (!bySlug.has(item.slug)) bySlug.set(item.slug, item.title);
420
+ }
421
+ return [...bySlug]
422
+ .map(([slug, title]) => ({ value: slug, label: title }))
423
+ .sort((a, b) => a.label.localeCompare(b.label));
424
+ }
425
+
426
+ /**
427
+ * Rows of a key–value field. The item is saved as soon as it changes and the server drops rows left empty, so a row
428
+ * just added is kept here, shown and typed into, and only rows with something in them are sent.
429
+ */
430
+ function KeyValueField({
431
+ label,
432
+ value,
433
+ onChange,
434
+ }: {
435
+ label: string;
436
+ value: unknown;
437
+ onChange: (value: unknown) => void;
438
+ }) {
439
+ const saved = Array.isArray(value) ? (value as Record<string, unknown>[]) : [];
440
+ const [rows, setRows] = useState<Record<string, unknown>[]>(saved);
441
+ const filled = (list: Record<string, unknown>[]) =>
442
+ list.filter((row) => String(row.label ?? "").trim() !== "" || String(row.value ?? "").trim() !== "");
443
+ // The item changed elsewhere (another field's save, history, another tab): show what it holds now.
444
+ useEffect(() => {
445
+ if (JSON.stringify(filled(rows)) !== JSON.stringify(saved)) setRows(saved);
446
+ // eslint-disable-next-line react-hooks/exhaustive-deps
447
+ }, [JSON.stringify(saved)]);
448
+
449
+ return (
450
+ <SettingField
451
+ schema={{ ...KEY_VALUE, label }}
452
+ value={rows}
453
+ onChange={(next) => {
454
+ const list = Array.isArray(next) ? (next as Record<string, unknown>[]) : [];
455
+ setRows(list);
456
+ if (JSON.stringify(filled(list)) !== JSON.stringify(saved)) onChange(filled(list));
457
+ }}
458
+ />
459
+ );
460
+ }
461
+
462
+ /** Flowing text with the same formatting toolbar as text on the page. */
463
+ function RichTextField({
464
+ label,
465
+ value,
466
+ onChange,
467
+ }: {
468
+ label: string;
469
+ value: RichTextValue | undefined;
470
+ onChange: (value: RichTextValue) => void;
471
+ }) {
472
+ const [element, setElement] = useState<HTMLDivElement | null>(null);
473
+ /** The words being dragged within the field, which move rather than copy when dropped in it. */
474
+ const dragged = useRef<Range | null>(null);
475
+ // The starting markup is set once; afterwards the browser owns the edited content.
476
+ const [initialHtml] = useState(() => renderBlocks(value?.blocks ?? []) || "<p><br></p>");
477
+ // Written elsewhere (on the page), the field follows; never while the owner is writing in it.
478
+ useEffect(() => {
479
+ if (!element || element.ownerDocument.activeElement === element) return;
480
+ const html = renderBlocks(value?.blocks ?? []) || "<p><br></p>";
481
+ if (element.innerHTML !== html) element.innerHTML = html;
482
+ }, [element, value]);
483
+
484
+ return (
485
+ <div className="field-group">
486
+ <span className="field-label">{label}</span>
487
+ <div className="brim-richtext-field">
488
+ <div
489
+ className="brim-element__toolbar brim-richtext-field__toolbar"
490
+ role="toolbar"
491
+ aria-label={`${label} formatting`}
492
+ >
493
+ {element && <TextTools element={element} kind="richtext" onElement={() => undefined} />}
494
+ </div>
495
+ <div
496
+ ref={setElement}
497
+ className="brim-richtext-field__content"
498
+ contentEditable
499
+ suppressContentEditableWarning
500
+ role="textbox"
501
+ aria-multiline="true"
502
+ aria-label={label}
503
+ dangerouslySetInnerHTML={{ __html: initialHtml }}
504
+ onFocus={(event) => {
505
+ event.currentTarget.ownerDocument.execCommand("styleWithCSS", false, "false");
506
+ event.currentTarget.ownerDocument.execCommand("defaultParagraphSeparator", false, "p");
507
+ }}
508
+ onBlur={(event) => onChange({ blocks: readBlocks(event.currentTarget) })}
509
+ // Pasted or dropped content brings foreign markup: only the formatting the editor knows is kept.
510
+ onPaste={(event) => {
511
+ event.preventDefault();
512
+ insertTransferred(event.currentTarget.ownerDocument, readTransfer(event.clipboardData, true));
513
+ }}
514
+ onDragStart={() => {
515
+ const selection = document.getSelection();
516
+ dragged.current = selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;
517
+ }}
518
+ onDragEnd={() => (dragged.current = null)}
519
+ onDragOver={(event) => {
520
+ // A dropped file has no place in the text, and would open in place of the editor.
521
+ if (event.dataTransfer.types.includes("Files")) {
522
+ event.preventDefault();
523
+ event.dataTransfer.dropEffect = "none";
524
+ }
525
+ }}
526
+ onDrop={(event) => {
527
+ event.preventDefault();
528
+ dropTransferred(event.currentTarget, event.nativeEvent, dragged.current, true);
529
+ dragged.current = null;
530
+ }}
531
+ />
532
+ </div>
533
+ </div>
534
+ );
535
+ }