@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,812 @@
1
+ import { type KeyboardEvent, type ReactNode, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
2
+ import { createPortal } from "react-dom";
3
+ import { cleanTag, hasTag, sameTag } from "../../content/tags.ts";
4
+ import { CalendarIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from "./icons.tsx";
5
+ import { type FormValue, type Schema, emptyValue } from "./kinds.ts";
6
+ import { LinkWidget } from "./LinkWidget.tsx";
7
+ import { ImageUploadWidget } from "./widgets.tsx";
8
+ import { isComposing } from "./keys.ts";
9
+
10
+ interface FieldProps<Value = unknown> {
11
+ schema: Schema;
12
+ value: Value;
13
+ onChange: (value: unknown) => void;
14
+ }
15
+
16
+ /** Renders the widget for one value. Groups and lists nest. */
17
+ export function SettingField({ schema, value, onChange }: FieldProps): ReactNode {
18
+ switch (schema.type) {
19
+ case "text":
20
+ return (
21
+ <TextWidget
22
+ label={schema.label}
23
+ value={asString(value)}
24
+ multiline={schema.multiline ?? false}
25
+ onChange={onChange}
26
+ />
27
+ );
28
+ case "url":
29
+ return <LinkWidget label={schema.label} value={asString(value)} onChange={onChange} />;
30
+ case "image":
31
+ return <ImageWidget label={schema.label} value={asRecord(value)} onChange={onChange} />;
32
+ case "select":
33
+ return <SelectWidget label={schema.label} options={schema.options} value={asString(value)} onChange={onChange} />;
34
+ case "group":
35
+ return <GroupWidget schema={schema} value={asRecord(value)} onChange={onChange} />;
36
+ case "list":
37
+ return <ListWidget schema={schema} value={Array.isArray(value) ? value : []} onChange={onChange} />;
38
+ }
39
+ }
40
+
41
+ function asString(value: unknown): string {
42
+ return typeof value === "string" ? value : "";
43
+ }
44
+
45
+ function asRecord(value: unknown): FormValue {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as FormValue) : {};
47
+ }
48
+
49
+ /** A text input that reports its value when the person leaves it or presses Enter, not on every key. */
50
+ export function TextWidget({
51
+ label,
52
+ value,
53
+ placeholder,
54
+ description,
55
+ multiline = false,
56
+ type = "text",
57
+ limit,
58
+ onDraft,
59
+ onChange,
60
+ }: {
61
+ label: string;
62
+ value: string;
63
+ placeholder?: string | undefined;
64
+ description?: string | undefined;
65
+ multiline?: boolean;
66
+ type?: "text" | "email" | "password";
67
+ /** Shows how many characters are written against this recommended length; going over is allowed. */
68
+ limit?: number | undefined;
69
+ /** Each keystroke, before the value is saved on blur: for a live preview. */
70
+ onDraft?: ((draft: string) => void) | undefined;
71
+ onChange: (value: string) => void;
72
+ }) {
73
+ const id = useId();
74
+ const [draft, setDraft] = useState(value);
75
+ useEffect(() => setDraft(value), [value]);
76
+ const edit = (next: string): void => {
77
+ setDraft(next);
78
+ onDraft?.(next);
79
+ };
80
+
81
+ return (
82
+ <div className="field-group">
83
+ <label className="field-label" htmlFor={id}>
84
+ {label}
85
+ </label>
86
+ {description && <p className="field-description">{description}</p>}
87
+ {multiline ? (
88
+ <textarea
89
+ id={id}
90
+ className="field-input"
91
+ rows={4}
92
+ value={draft}
93
+ placeholder={placeholder}
94
+ onChange={(event) => edit(event.target.value)}
95
+ onBlur={() => draft !== value && onChange(draft)}
96
+ />
97
+ ) : (
98
+ <input
99
+ id={id}
100
+ className="field-input"
101
+ type={type}
102
+ value={draft}
103
+ placeholder={placeholder}
104
+ onChange={(event) => edit(event.target.value)}
105
+ onBlur={() => draft !== value && onChange(draft)}
106
+ onKeyDown={(event) => event.key === "Enter" && !isComposing(event) && event.currentTarget.blur()}
107
+ />
108
+ )}
109
+ {limit !== undefined && (
110
+ <p className="field-counter" data-over={draft.length > limit ? "" : undefined} aria-live="polite">
111
+ {draft.length} / {limit}
112
+ </p>
113
+ )}
114
+ </div>
115
+ );
116
+ }
117
+
118
+ /** A day as `YYYY-MM-DD`, read and written in local time so the chosen day never shifts by a timezone. */
119
+ function parseDay(value: string): Date | undefined {
120
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
121
+ if (!match) return undefined;
122
+ const day = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
123
+ return Number.isNaN(day.getTime()) ? undefined : day;
124
+ }
125
+
126
+ function formatDay(day: Date): string {
127
+ const pad = (n: number): string => String(n).padStart(2, "0");
128
+ return `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`;
129
+ }
130
+
131
+ function sameDay(a: Date | undefined, b: Date): boolean {
132
+ return a !== undefined && formatDay(a) === formatDay(b);
133
+ }
134
+
135
+ function addDays(day: Date, offset: number): Date {
136
+ return new Date(day.getFullYear(), day.getMonth(), day.getDate() + offset);
137
+ }
138
+
139
+ /** The 6 weeks shown for a month, starting on Monday. */
140
+ function monthGrid(month: Date): Date[] {
141
+ const first = new Date(month.getFullYear(), month.getMonth(), 1);
142
+ const start = addDays(first, -((first.getDay() + 6) % 7));
143
+ return Array.from({ length: 42 }, (_, i) => addDays(start, i));
144
+ }
145
+
146
+ const WEEKDAYS = Array.from({ length: 7 }, (_, i) =>
147
+ new Date(2024, 0, 1 + i).toLocaleDateString(undefined, { weekday: "short" }).slice(0, 2),
148
+ );
149
+
150
+ /** A day picked from a calendar. Stores `YYYY-MM-DD`; empty when cleared. */
151
+ export function DateWidget({
152
+ label,
153
+ value,
154
+ description,
155
+ onChange,
156
+ }: {
157
+ label: string;
158
+ value: string;
159
+ description?: string | undefined;
160
+ onChange: (value: string) => void;
161
+ }) {
162
+ const selected = parseDay(value);
163
+ const [open, setOpen] = useState(false);
164
+ const [focused, setFocused] = useState<Date>(() => selected ?? new Date());
165
+ const [position, setPosition] = useState({ top: 0, left: 0 });
166
+ const trigger = useRef<HTMLButtonElement>(null);
167
+ const popover = useRef<HTMLDivElement>(null);
168
+ const today = new Date();
169
+
170
+ const show = (): void => {
171
+ setFocused(selected ?? new Date());
172
+ setOpen(true);
173
+ };
174
+
175
+ const pick = (day: Date | undefined): void => {
176
+ setOpen(false);
177
+ trigger.current?.focus();
178
+ const next = day ? formatDay(day) : "";
179
+ if (next !== value) onChange(next);
180
+ };
181
+
182
+ useLayoutEffect(() => {
183
+ if (!open || !trigger.current || !popover.current) return;
184
+ const bounds = trigger.current.getBoundingClientRect();
185
+ const height = popover.current.offsetHeight;
186
+ const below = bounds.bottom + 4 + height <= window.innerHeight;
187
+ setPosition({ top: below ? bounds.bottom + 4 : Math.max(4, bounds.top - 4 - height), left: bounds.left });
188
+ }, [open]);
189
+
190
+ useEffect(() => {
191
+ if (!open) return;
192
+ const close = (event: Event): void => {
193
+ const target = event.target as Node;
194
+ if (!trigger.current?.contains(target) && !popover.current?.contains(target)) setOpen(false);
195
+ };
196
+ document.addEventListener("pointerdown", close);
197
+ return () => document.removeEventListener("pointerdown", close);
198
+ }, [open]);
199
+
200
+ // Keeps keyboard focus on the focused day as it moves.
201
+ useEffect(() => {
202
+ if (!open) return;
203
+ popover.current?.querySelector<HTMLButtonElement>(`[data-day="${formatDay(focused)}"]`)?.focus();
204
+ }, [open, focused]);
205
+
206
+ const moveMonth = (offset: number): void =>
207
+ setFocused(new Date(focused.getFullYear(), focused.getMonth() + offset, 1));
208
+
209
+ const onKey = (event: KeyboardEvent): void => {
210
+ if (isComposing(event)) return;
211
+ const moves: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
212
+ if (event.key in moves) {
213
+ event.preventDefault();
214
+ setFocused(addDays(focused, moves[event.key]!));
215
+ } else if (event.key === "PageUp" || event.key === "PageDown") {
216
+ event.preventDefault();
217
+ const offset = event.key === "PageUp" ? -1 : 1;
218
+ setFocused(new Date(focused.getFullYear(), focused.getMonth() + offset, focused.getDate()));
219
+ } else if (event.key === "Escape") {
220
+ event.preventDefault();
221
+ setOpen(false);
222
+ trigger.current?.focus();
223
+ }
224
+ };
225
+
226
+ return (
227
+ <div className="field-group">
228
+ <span className="field-label">{label}</span>
229
+ {description && <p className="field-description">{description}</p>}
230
+ <button
231
+ ref={trigger}
232
+ type="button"
233
+ className="field-select field-date"
234
+ data-open={open}
235
+ aria-haspopup="dialog"
236
+ aria-expanded={open}
237
+ aria-label={`${label}: ${selected ? selected.toLocaleDateString() : "no date"}`}
238
+ onClick={() => (open ? setOpen(false) : show())}
239
+ >
240
+ <span className="field-select-label" data-empty={selected ? undefined : ""}>
241
+ {selected
242
+ ? selected.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" })
243
+ : "Pick a date"}
244
+ </span>
245
+ <span className="field-select-chevron">
246
+ <CalendarIcon />
247
+ </span>
248
+ </button>
249
+ {open &&
250
+ createPortal(
251
+ <div
252
+ ref={popover}
253
+ className="field-calendar"
254
+ role="dialog"
255
+ aria-label={label}
256
+ style={position}
257
+ onKeyDown={onKey}
258
+ >
259
+ <div className="field-calendar-header">
260
+ <button type="button" aria-label="Previous month" onClick={() => moveMonth(-1)}>
261
+ <ChevronLeftIcon />
262
+ </button>
263
+ <span aria-live="polite">
264
+ {focused.toLocaleDateString(undefined, { month: "long", year: "numeric" })}
265
+ </span>
266
+ <button type="button" aria-label="Next month" onClick={() => moveMonth(1)}>
267
+ <ChevronRightIcon />
268
+ </button>
269
+ </div>
270
+ <div className="field-calendar-grid" role="grid">
271
+ {WEEKDAYS.map((weekday) => (
272
+ <span key={weekday} className="field-calendar-weekday" role="columnheader">
273
+ {weekday}
274
+ </span>
275
+ ))}
276
+ {monthGrid(focused).map((day) => {
277
+ const key = formatDay(day);
278
+ return (
279
+ <button
280
+ key={key}
281
+ type="button"
282
+ role="gridcell"
283
+ data-day={key}
284
+ tabIndex={sameDay(focused, day) ? 0 : -1}
285
+ className="field-calendar-day"
286
+ data-outside={day.getMonth() !== focused.getMonth() ? "" : undefined}
287
+ data-today={sameDay(today, day) ? "" : undefined}
288
+ aria-selected={sameDay(selected, day)}
289
+ aria-label={day.toLocaleDateString(undefined, { dateStyle: "full" })}
290
+ onClick={() => pick(day)}
291
+ >
292
+ {day.getDate()}
293
+ </button>
294
+ );
295
+ })}
296
+ </div>
297
+ <div className="field-calendar-footer">
298
+ <button type="button" onClick={() => pick(undefined)} disabled={!selected}>
299
+ Clear
300
+ </button>
301
+ <button type="button" onClick={() => pick(new Date())}>
302
+ Today
303
+ </button>
304
+ </div>
305
+ </div>,
306
+ document.body,
307
+ )}
308
+ </div>
309
+ );
310
+ }
311
+
312
+ /** An image with its description, as content items and the site's logo keep it: `{ src, alt }`. */
313
+ export function ImageWidget({
314
+ label,
315
+ value,
316
+ onChange,
317
+ }: {
318
+ label: string;
319
+ value: FormValue;
320
+ onChange: (value: unknown) => void;
321
+ }) {
322
+ const src = asString(value.src);
323
+ const alt = asString(value.alt);
324
+
325
+ return (
326
+ <fieldset className="brim-setting-group">
327
+ <legend>{label}</legend>
328
+ <ImageUploadWidget label="Image" value={src} onChange={(next) => onChange({ src: next, alt })} />
329
+ <TextWidget
330
+ label="Alt Text (SEO)"
331
+ value={alt}
332
+ placeholder="Describe the image"
333
+ onChange={(next) => onChange({ src, alt: next })}
334
+ />
335
+ </fieldset>
336
+ );
337
+ }
338
+
339
+ function GroupWidget({
340
+ schema,
341
+ value,
342
+ onChange,
343
+ }: FieldProps<FormValue> & { schema: Extract<Schema, { type: "group" }> }) {
344
+ const fields = Object.entries(schema.fields).map(([name, field]) => (
345
+ <SettingField
346
+ key={name}
347
+ schema={field}
348
+ value={value[name]}
349
+ onChange={(next) => onChange({ ...value, [name]: next })}
350
+ />
351
+ ));
352
+ if (!schema.label) return fields;
353
+ return (
354
+ <fieldset className="brim-setting-group">
355
+ <legend>{schema.label}</legend>
356
+ {fields}
357
+ </fieldset>
358
+ );
359
+ }
360
+
361
+ function ListWidget({
362
+ schema,
363
+ value,
364
+ onChange,
365
+ }: FieldProps<unknown[]> & { schema: Extract<Schema, { type: "list" }> }) {
366
+ function move(index: number, offset: number): void {
367
+ const next = [...value];
368
+ [next[index], next[index + offset]] = [next[index + offset], next[index]];
369
+ onChange(next);
370
+ }
371
+
372
+ return (
373
+ <fieldset className="brim-setting-group">
374
+ <legend>
375
+ {schema.label} · {value.length}
376
+ </legend>
377
+ {value.map((item, index) => (
378
+ <div className="brim-array-item" key={index}>
379
+ <div className="brim-actions">
380
+ <span>Item {index + 1}</span>
381
+ <button
382
+ type="button"
383
+ disabled={index === 0}
384
+ aria-label={`Move item ${index + 1} up`}
385
+ onClick={() => move(index, -1)}
386
+ >
387
+ ↑
388
+ </button>
389
+ <button
390
+ type="button"
391
+ disabled={index === value.length - 1}
392
+ aria-label={`Move item ${index + 1} down`}
393
+ onClick={() => move(index, 1)}
394
+ >
395
+ ↓
396
+ </button>
397
+ <button
398
+ type="button"
399
+ aria-label={`Remove item ${index + 1}`}
400
+ onClick={() => onChange(value.filter((_, i) => i !== index))}
401
+ >
402
+ Remove
403
+ </button>
404
+ </div>
405
+ <SettingField
406
+ schema={schema.item}
407
+ value={item}
408
+ onChange={(next) => onChange(value.map((current, i) => (i === index ? next : current)))}
409
+ />
410
+ </div>
411
+ ))}
412
+ <button type="button" onClick={() => onChange([...value, emptyValue(schema.item)])}>
413
+ {schema.addLabel}
414
+ </button>
415
+ </fieldset>
416
+ );
417
+ }
418
+
419
+ export function CheckboxWidget({
420
+ label,
421
+ description,
422
+ checked,
423
+ onChange,
424
+ }: {
425
+ label: string;
426
+ description?: string | undefined;
427
+ checked: boolean;
428
+ onChange: (checked: boolean) => void;
429
+ }) {
430
+ const id = useId();
431
+ return (
432
+ <div className="field-group">
433
+ <label className="field-label-checkbox" htmlFor={id}>
434
+ <input
435
+ id={id}
436
+ className="field-checkbox"
437
+ type="checkbox"
438
+ checked={checked}
439
+ onChange={(event) => onChange(event.target.checked)}
440
+ />
441
+ <span className="checkbox-label-text">{label}</span>
442
+ </label>
443
+ {description && <p className="field-description">{description}</p>}
444
+ </div>
445
+ );
446
+ }
447
+
448
+ /** Custom dropdown, so the options follow the editor's theme. Rendered on <body> to escape clipping. */
449
+ export function SelectWidget({
450
+ label,
451
+ description,
452
+ options,
453
+ value,
454
+ onChange,
455
+ }: {
456
+ label: string;
457
+ description?: string | undefined;
458
+ options: { value: string; label: string }[];
459
+ value: string;
460
+ onChange: (value: string) => void;
461
+ }) {
462
+ const [open, setOpen] = useState(false);
463
+ const [position, setPosition] = useState({ top: 0, left: 0, width: 0 });
464
+ const trigger = useRef<HTMLButtonElement>(null);
465
+ const dropdown = useRef<HTMLDivElement>(null);
466
+ const selected = options.find((option) => option.value === value);
467
+
468
+ useLayoutEffect(() => {
469
+ if (!open || !trigger.current) return;
470
+ const bounds = trigger.current.getBoundingClientRect();
471
+ // Under the field, unless the window ends before the list does and there is more room above it.
472
+ const height = dropdown.current?.offsetHeight ?? 0;
473
+ const below = window.innerHeight - bounds.bottom - 12;
474
+ const above = bounds.top - 12;
475
+ const top = height > below && above > below ? Math.max(8, bounds.top - 4 - height) : bounds.bottom + 4;
476
+ setPosition({ top, left: bounds.left, width: bounds.width });
477
+ }, [open]);
478
+
479
+ useEffect(() => {
480
+ if (!open) return;
481
+ const close = (event: Event): void => {
482
+ const target = event.target as Node;
483
+ if (!trigger.current?.contains(target) && !dropdown.current?.contains(target)) setOpen(false);
484
+ };
485
+ document.addEventListener("pointerdown", close);
486
+ return () => document.removeEventListener("pointerdown", close);
487
+ }, [open]);
488
+
489
+ return (
490
+ <div className="field-group">
491
+ <span className="field-label">{label}</span>
492
+ {description && <p className="field-description">{description}</p>}
493
+ <button
494
+ ref={trigger}
495
+ type="button"
496
+ className="field-select"
497
+ data-open={open}
498
+ aria-haspopup="listbox"
499
+ aria-expanded={open}
500
+ aria-label={label}
501
+ onClick={() => setOpen(!open)}
502
+ onKeyDown={(event) => event.key === "Escape" && !isComposing(event) && setOpen(false)}
503
+ >
504
+ <span className="field-select-label">{selected?.label ?? value}</span>
505
+ <span className="field-select-chevron">
506
+ <ChevronDownIcon />
507
+ </span>
508
+ </button>
509
+ {open &&
510
+ createPortal(
511
+ <div ref={dropdown} className="field-select-dropdown" role="listbox" style={position}>
512
+ {options.map((option) => (
513
+ <button
514
+ key={option.value}
515
+ type="button"
516
+ role="option"
517
+ aria-selected={option.value === value}
518
+ className={`field-select-option${option.value === value ? " field-select-option--selected" : ""}`}
519
+ onClick={() => {
520
+ setOpen(false);
521
+ if (option.value !== value) onChange(option.value);
522
+ }}
523
+ >
524
+ {option.label}
525
+ </button>
526
+ ))}
527
+ </div>,
528
+ document.body,
529
+ )}
530
+ </div>
531
+ );
532
+ }
533
+
534
+ /**
535
+ * A list of tags, each a chip with a × to remove it. Typing and Enter (or a comma) adds one; Backspace in the empty
536
+ * box removes the last. `suggestions` are offered while typing: the tags already used, so the same word is spelled
537
+ * the same way, or with `fixed`, the only tags the field takes.
538
+ */
539
+ export function TagsWidget({
540
+ label,
541
+ description,
542
+ value,
543
+ suggestions = [],
544
+ fixed = false,
545
+ onChange,
546
+ }: {
547
+ label: string;
548
+ description?: string | undefined;
549
+ value: string[];
550
+ suggestions?: string[] | undefined;
551
+ /** Only `suggestions` can be chosen. */
552
+ fixed?: boolean;
553
+ onChange: (tags: string[]) => void;
554
+ }) {
555
+ const id = useId();
556
+ const input = useRef<HTMLInputElement>(null);
557
+ const [draft, setDraft] = useState("");
558
+ const offered = suggestions.filter((tag) => !hasTag(value, tag));
559
+
560
+ function add(text: string): void {
561
+ const next = [...value];
562
+ for (const typed of text.split(",")) {
563
+ const tag = cleanTag(typed);
564
+ // A tag already used keeps its spelling: "Garden" typed as "garden" is still the same tag.
565
+ const chosen = suggestions.find((known) => sameTag(known, tag)) ?? (fixed ? undefined : tag);
566
+ if (chosen && !hasTag(next, chosen)) next.push(chosen);
567
+ }
568
+ setDraft("");
569
+ if (next.length !== value.length) onChange(next);
570
+ }
571
+
572
+ return (
573
+ <div className="field-group">
574
+ <label className="field-label" htmlFor={id}>
575
+ {label}
576
+ </label>
577
+ {description && <p className="field-description">{description}</p>}
578
+ <div className="field-tags" onClick={() => input.current?.focus()}>
579
+ {value.map((tag) => (
580
+ <span key={tag} className="field-tag">
581
+ {tag}
582
+ <button
583
+ type="button"
584
+ className="field-tag__remove"
585
+ aria-label={`Remove ${tag}`}
586
+ title="Remove"
587
+ onClick={() => onChange(value.filter((existing) => existing !== tag))}
588
+ >
589
+ ×
590
+ </button>
591
+ </span>
592
+ ))}
593
+ <input
594
+ ref={input}
595
+ id={id}
596
+ className="field-tags__input"
597
+ list={offered.length > 0 ? `${id}-tags` : undefined}
598
+ value={draft}
599
+ placeholder={value.length === 0 ? (fixed ? "Choose a tag" : "Add a tag") : ""}
600
+ onChange={(event) => {
601
+ const text = event.target.value;
602
+ // A suggestion picked from the list comes as one replacement, not as letters typed.
603
+ const native = event.nativeEvent as Partial<InputEvent>;
604
+ const picked = native.inputType === undefined || native.inputType === "insertReplacementText";
605
+ if (text.includes(",") || (picked && offered.includes(text))) add(text);
606
+ else setDraft(text);
607
+ }}
608
+ onKeyDown={(event) => {
609
+ // Enter or Escape that picks or cancels a word being composed belongs to the input method.
610
+ if (isComposing(event)) return;
611
+ if (event.key === "Enter") {
612
+ // Inside a form, Enter adds the tag instead of saving the form.
613
+ event.preventDefault();
614
+ if (draft.trim()) add(draft);
615
+ } else if (event.key === "Backspace" && draft === "" && value.length > 0) {
616
+ onChange(value.slice(0, -1));
617
+ }
618
+ }}
619
+ onBlur={() => draft.trim() && add(draft)}
620
+ />
621
+ {offered.length > 0 && (
622
+ <datalist id={`${id}-tags`}>
623
+ {offered.map((tag) => (
624
+ <option key={tag} value={tag} />
625
+ ))}
626
+ </datalist>
627
+ )}
628
+ </div>
629
+ </div>
630
+ );
631
+ }
632
+
633
+ /** A term of a vocabulary as a reference widget offers it: the slug it saves and the title it shows. */
634
+ export interface ReferenceTerm {
635
+ value: string;
636
+ label: string;
637
+ }
638
+
639
+ /**
640
+ * The editor's one widget for references to a vocabulary's terms, wherever an item's fields are edited (the item
641
+ * form, Page Settings, a new item). Typing filters the terms by title, whatever the case and accents; when no term
642
+ * has that title, "Add … to <vocabulary>" creates it and picks it. One term, or several shown as chips.
643
+ */
644
+ export function ReferenceWidget({
645
+ label,
646
+ description,
647
+ vocabulary,
648
+ terms,
649
+ value,
650
+ multiple = false,
651
+ required = false,
652
+ onChange,
653
+ onAdd,
654
+ }: {
655
+ label: string;
656
+ description?: string | undefined;
657
+ /** The vocabulary's name, as the "Add" option says it: "Categories". */
658
+ vocabulary: string;
659
+ terms: ReferenceTerm[];
660
+ value: string[];
661
+ multiple?: boolean;
662
+ required?: boolean;
663
+ onChange: (slugs: string[]) => void;
664
+ /** Creates a term with this title; answers it, or nothing when it could not be made. */
665
+ onAdd?: (title: string) => Promise<ReferenceTerm | undefined>;
666
+ }) {
667
+ const id = useId();
668
+ const box = useRef<HTMLDivElement>(null);
669
+ const input = useRef<HTMLInputElement>(null);
670
+ const [draft, setDraft] = useState("");
671
+ const [open, setOpen] = useState(false);
672
+ const [adding, setAdding] = useState(false);
673
+ const [position, setPosition] = useState({ top: 0, left: 0, width: 0 });
674
+ const fold = (text: string) => text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLocaleLowerCase().trim();
675
+ const chosen = value.map((slug) => terms.find((term) => term.value === slug) ?? { value: slug, label: slug });
676
+ const typed = fold(draft);
677
+ const offered = terms
678
+ .filter((term) => !value.includes(term.value) || !multiple)
679
+ .filter((term) => typed === "" || fold(term.label).includes(typed));
680
+ const exact = terms.some((term) => fold(term.label) === typed);
681
+ const canAdd = onAdd !== undefined && typed !== "" && !exact;
682
+
683
+ useLayoutEffect(() => {
684
+ if (!open || !box.current) return;
685
+ const bounds = box.current.getBoundingClientRect();
686
+ setPosition({ top: bounds.bottom + 4, left: bounds.left, width: bounds.width });
687
+ }, [open, draft, value.length]);
688
+
689
+ function pick(term: ReferenceTerm): void {
690
+ setDraft("");
691
+ setOpen(multiple);
692
+ if (multiple) {
693
+ if (!value.includes(term.value)) onChange([...value, term.value]);
694
+ input.current?.focus();
695
+ } else if (value[0] !== term.value) {
696
+ onChange([term.value]);
697
+ }
698
+ }
699
+
700
+ async function add(): Promise<void> {
701
+ if (!onAdd || adding) return;
702
+ setAdding(true);
703
+ try {
704
+ const term = await onAdd(draft.trim());
705
+ if (term) pick(term);
706
+ } finally {
707
+ setAdding(false);
708
+ }
709
+ }
710
+
711
+ return (
712
+ <div className="field-group">
713
+ <label className="field-label" htmlFor={id}>
714
+ {label}
715
+ </label>
716
+ {description && <p className="field-description">{description}</p>}
717
+ <div ref={box} className="field-tags" onClick={() => input.current?.focus()}>
718
+ {multiple &&
719
+ chosen.map((term) => (
720
+ <span key={term.value} className="field-tag">
721
+ {term.label}
722
+ <button
723
+ type="button"
724
+ className="field-tag__remove"
725
+ aria-label={`Remove ${term.label}`}
726
+ title="Remove"
727
+ onClick={() => onChange(value.filter((slug) => slug !== term.value))}
728
+ >
729
+ ×
730
+ </button>
731
+ </span>
732
+ ))}
733
+ <input
734
+ ref={input}
735
+ id={id}
736
+ className="field-tags__input"
737
+ role="combobox"
738
+ aria-expanded={open}
739
+ aria-controls={`${id}-terms`}
740
+ autoComplete="off"
741
+ value={draft}
742
+ placeholder={multiple ? (value.length === 0 ? `Choose or add` : "") : (chosen[0]?.label ?? `Choose or add`)}
743
+ onFocus={() => setOpen(true)}
744
+ onChange={(event) => {
745
+ setDraft(event.target.value);
746
+ setOpen(true);
747
+ }}
748
+ onKeyDown={(event) => {
749
+ // Enter or Escape that picks or cancels a word being composed belongs to the input method.
750
+ if (isComposing(event)) return;
751
+ if (event.key === "Enter") {
752
+ // Inside a form, Enter picks the first term (or adds the typed one) instead of saving the form.
753
+ event.preventDefault();
754
+ const first = offered[0];
755
+ if (first && (typed === "" || fold(first.label) === typed || !canAdd)) pick(first);
756
+ else if (canAdd) void add();
757
+ } else if (event.key === "Escape") {
758
+ setOpen(false);
759
+ } else if (event.key === "Backspace" && draft === "" && multiple && value.length > 0) {
760
+ onChange(value.slice(0, -1));
761
+ }
762
+ }}
763
+ onBlur={() => setTimeout(() => setOpen(false), 150)}
764
+ />
765
+ {!multiple && !required && value.length > 0 && (
766
+ <button
767
+ type="button"
768
+ className="field-tag__remove"
769
+ aria-label={`Clear ${label}`}
770
+ title="Clear"
771
+ onClick={() => onChange([])}
772
+ >
773
+ ×
774
+ </button>
775
+ )}
776
+ </div>
777
+ {open &&
778
+ (offered.length > 0 || canAdd) &&
779
+ createPortal(
780
+ <div id={`${id}-terms`} className="field-select-dropdown" role="listbox" style={position}>
781
+ {offered.map((term) => (
782
+ <button
783
+ key={term.value}
784
+ type="button"
785
+ role="option"
786
+ aria-selected={value.includes(term.value)}
787
+ className={`field-select-option${value.includes(term.value) ? " field-select-option--selected" : ""}`}
788
+ onMouseDown={(event) => event.preventDefault()}
789
+ onClick={() => pick(term)}
790
+ >
791
+ {term.label}
792
+ </button>
793
+ ))}
794
+ {canAdd && (
795
+ <button
796
+ type="button"
797
+ role="option"
798
+ aria-selected={false}
799
+ className="field-select-option field-select-option--add"
800
+ disabled={adding}
801
+ onMouseDown={(event) => event.preventDefault()}
802
+ onClick={() => void add()}
803
+ >
804
+ {adding ? "Adding…" : `Add “${draft.trim()}” to ${vocabulary}`}
805
+ </button>
806
+ )}
807
+ </div>,
808
+ document.body,
809
+ )}
810
+ </div>
811
+ );
812
+ }