@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,1218 @@
1
+ /** Sidebar controls carried over from BrimCMS. Each mirrors the control the grid editor had for the same setting. */
2
+ import { type ReactNode, createContext, useContext, useEffect, useId, useRef, useState } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import type { Icon, IconSearch, IconSetInfo } from "../../icons/library.ts";
5
+ import { IMAGE_SHAPES, type ImageShape } from "../../blocks/data/image-shapes.ts";
6
+ import { SOCIAL_NETWORKS, orderSocialNetworks } from "../../blocks/data/social-networks.ts";
7
+ import { THEME_COLOR_DEFAULTS } from "../../blocks/theme.ts";
8
+ import { type MediaFile, api } from "./api.ts";
9
+ import { useBrandColors } from "./brand.ts";
10
+ import { ArrowLeftIcon, ChevronRightIcon, PlusIcon } from "./icons.tsx";
11
+ import { isComposing } from "./keys.ts";
12
+
13
+ interface Option {
14
+ value: string;
15
+ label: string;
16
+ }
17
+
18
+ /** A slider with a number box beside it. Double-click the slider to go back to the default. */
19
+ export function RangeWidget({
20
+ label,
21
+ description,
22
+ value,
23
+ min,
24
+ max,
25
+ step = 1,
26
+ defaultValue,
27
+ onChange,
28
+ }: {
29
+ label: string;
30
+ description?: string | undefined;
31
+ value: number;
32
+ min: number;
33
+ max: number;
34
+ step?: number | undefined;
35
+ defaultValue?: number | undefined;
36
+ onChange: (value: number) => void;
37
+ }) {
38
+ const id = useId();
39
+ /** Where the slider is while it is dragged: the change is saved once, when it is let go. */
40
+ const [dragged, setDragged] = useState<number | null>(null);
41
+ const shown = dragged ?? value;
42
+ const release = (): void => {
43
+ if (dragged === null) return;
44
+ setDragged(null);
45
+ if (dragged !== value) onChange(dragged);
46
+ };
47
+ const percent = ((shown - min) / (max - min)) * 100;
48
+ return (
49
+ <div className="field-group">
50
+ <label className="field-label" htmlFor={id}>
51
+ {label}
52
+ </label>
53
+ {description && <p className="field-description">{description}</p>}
54
+ <div className="field-range-control">
55
+ <input
56
+ id={id}
57
+ className="field-range"
58
+ type="range"
59
+ min={min}
60
+ max={max}
61
+ step={step}
62
+ value={shown}
63
+ style={{ "--range-pct": `${percent}%` } as React.CSSProperties}
64
+ onChange={(event) => setDragged(Number(event.target.value))}
65
+ onPointerUp={release}
66
+ onKeyUp={release}
67
+ onBlur={release}
68
+ onDoubleClick={() => defaultValue !== undefined && onChange(defaultValue)}
69
+ />
70
+ <NumberBox
71
+ className="field-input field-range-number"
72
+ label={label}
73
+ min={min}
74
+ max={max}
75
+ step={step}
76
+ value={shown}
77
+ onChange={onChange}
78
+ />
79
+ </div>
80
+ </div>
81
+ );
82
+ }
83
+
84
+ function clamp(value: number, min: number, max: number): number {
85
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : min;
86
+ }
87
+
88
+ /**
89
+ * A number box that keeps what is typed as it is and brings it within its bounds once done (on blur or Enter):
90
+ * clamping each keystroke would turn the "1" of "12" into the minimum before the "2" is typed.
91
+ */
92
+ function NumberBox({
93
+ className,
94
+ label,
95
+ min,
96
+ max,
97
+ step,
98
+ value,
99
+ onChange,
100
+ }: {
101
+ className: string;
102
+ label?: string | undefined;
103
+ min: number;
104
+ max: number;
105
+ step?: number | undefined;
106
+ value: number;
107
+ onChange: (value: number) => void;
108
+ }) {
109
+ const [draft, setDraft] = useState(String(value));
110
+ useEffect(() => setDraft(String(value)), [value]);
111
+ const commit = (): void => {
112
+ const next = clamp(Number(draft), min, max);
113
+ setDraft(String(next));
114
+ if (next !== value) onChange(next);
115
+ };
116
+ return (
117
+ <input
118
+ className={className}
119
+ type="number"
120
+ aria-label={label}
121
+ min={min}
122
+ max={max}
123
+ step={step}
124
+ value={draft}
125
+ onChange={(event) => setDraft(event.target.value)}
126
+ onBlur={commit}
127
+ onKeyDown={(event) => event.key === "Enter" && !isComposing(event) && commit()}
128
+ />
129
+ );
130
+ }
131
+
132
+ /** A row of named sizes. When the schema names a custom-value setting, "custom" reveals a number box for it. */
133
+ export function SizeWidget({
134
+ label,
135
+ description,
136
+ options,
137
+ value,
138
+ custom,
139
+ onChange,
140
+ }: {
141
+ label: string;
142
+ description?: string | undefined;
143
+ options: Option[];
144
+ value: string;
145
+ custom?:
146
+ | { title: string; value: number; min: number; max: number; step: number; onChange: (value: number) => void }
147
+ | undefined;
148
+ onChange: (value: string) => void;
149
+ }) {
150
+ return (
151
+ <div className="field-group">
152
+ <span className="field-label">{label}</span>
153
+ {description && <p className="field-description">{description}</p>}
154
+ <div className="size-picker" role="group" aria-label={label}>
155
+ {options.map((option) => (
156
+ <button
157
+ key={option.value}
158
+ type="button"
159
+ className="size-btn"
160
+ aria-pressed={option.value === value}
161
+ onClick={() => onChange(option.value)}
162
+ >
163
+ {option.label}
164
+ </button>
165
+ ))}
166
+ </div>
167
+ {custom && value === "custom" && (
168
+ <label className="size-custom">
169
+ <span className="field-description">{custom.title}</span>
170
+ <NumberBox
171
+ className="field-input"
172
+ min={custom.min}
173
+ max={custom.max}
174
+ step={custom.step}
175
+ value={custom.value}
176
+ onChange={custom.onChange}
177
+ />
178
+ </label>
179
+ )}
180
+ </div>
181
+ );
182
+ }
183
+
184
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
185
+
186
+ /** Round swatches of the site's theme colors, then a custom color. Stores a theme key or a hex color. */
187
+ export function ColorSelectWidget({
188
+ label,
189
+ description,
190
+ options,
191
+ value,
192
+ allowCustom,
193
+ onChange,
194
+ }: {
195
+ label: string;
196
+ description?: string | undefined;
197
+ options: Option[];
198
+ value: string;
199
+ allowCustom: boolean;
200
+ onChange: (value: string) => void;
201
+ }) {
202
+ const brand = useBrandColors();
203
+ const isBrand = brand.some((color) => color.value === value.toLowerCase());
204
+ const isCustom = HEX.test(value) && !isBrand;
205
+ /**
206
+ * The color being picked: shown on the swatch as the picker moves, saved once when the picker closes (the
207
+ * browser's "change"), not on every step of the drag.
208
+ */
209
+ const [picking, setPicking] = useState<string | null>(null);
210
+ const picker = useRef<HTMLInputElement | null>(null);
211
+ const changeRef = useRef(onChange);
212
+ changeRef.current = onChange;
213
+ useEffect(() => {
214
+ const input = picker.current;
215
+ if (!input) return;
216
+ const done = (): void => {
217
+ setPicking(null);
218
+ changeRef.current(input.value);
219
+ };
220
+ input.addEventListener("change", done);
221
+ return () => input.removeEventListener("change", done);
222
+ }, [allowCustom]);
223
+ return (
224
+ <div className="field-group">
225
+ <span className="field-label">{label}</span>
226
+ {description && <p className="field-description">{description}</p>}
227
+ <div className="rwcs-inline-colors" role="group" aria-label={label}>
228
+ {allowCustom &&
229
+ brand.map((color) => (
230
+ <button
231
+ key={`brand-${color.value}-${color.name}`}
232
+ type="button"
233
+ className="rwcs-swatch rwcs-swatch--brand"
234
+ aria-pressed={color.value === value.toLowerCase()}
235
+ aria-label={`${color.name} (brand)`}
236
+ title={`${color.name} · brand color`}
237
+ style={{ "--swatch": color.value } as React.CSSProperties}
238
+ onClick={() => onChange(color.value)}
239
+ />
240
+ ))}
241
+ {options.map((option) => (
242
+ <button
243
+ key={option.value}
244
+ type="button"
245
+ className="rwcs-swatch"
246
+ data-empty={option.value === "" || option.value === "auto" || option.value === "none"}
247
+ aria-pressed={option.value === value}
248
+ aria-label={option.label}
249
+ title={option.label}
250
+ style={
251
+ {
252
+ "--swatch": `var(--brim-theme-${option.value}, ${THEME_COLOR_DEFAULTS[option.value] ?? "transparent"})`,
253
+ } as React.CSSProperties
254
+ }
255
+ onClick={() => onChange(option.value)}
256
+ />
257
+ ))}
258
+ {allowCustom && (
259
+ <label
260
+ className="rwcs-swatch rwcs-inline-custom-btn"
261
+ data-active={isCustom}
262
+ title="Custom color"
263
+ style={isCustom || picking ? ({ "--swatch": picking ?? value } as React.CSSProperties) : undefined}
264
+ >
265
+ {!isCustom && !picking && <PlusIcon />}
266
+ <input
267
+ ref={picker}
268
+ type="color"
269
+ aria-label="Custom color"
270
+ value={picking ?? (isCustom ? value : "#000000")}
271
+ onChange={(event) => setPicking(event.target.value)}
272
+ />
273
+ </label>
274
+ )}
275
+ </div>
276
+ </div>
277
+ );
278
+ }
279
+
280
+ function IconPreview({ icon }: { icon: Icon | null | undefined }): ReactNode {
281
+ if (!icon) return <span className="ipw-none">∅</span>;
282
+ // Brim's own icons are outlines; a pack's icons carry their own fill and stroke.
283
+ const outline = icon.outline
284
+ ? ({
285
+ fill: "none",
286
+ stroke: "currentColor",
287
+ strokeWidth: 2,
288
+ strokeLinecap: "round",
289
+ strokeLinejoin: "round",
290
+ } as const)
291
+ : { fill: "currentColor" };
292
+ return (
293
+ <svg
294
+ width="18"
295
+ height="18"
296
+ viewBox={icon.viewBox}
297
+ {...outline}
298
+ aria-hidden="true"
299
+ dangerouslySetInnerHTML={{ __html: icon.body }}
300
+ />
301
+ );
302
+ }
303
+
304
+ /** Icons already shown once, by their saved value, so a settings panel does not ask again for each. */
305
+ const knownIcons = new Map<string, Icon | null>();
306
+
307
+ /**
308
+ * Shows the chosen icon; opens a searchable grid of the site's icons, laid over the sidebar. The site decides
309
+ * which sets there are: Brim's own, part of it, and packs it added. A set is searched on the server, as a pack
310
+ * can hold thousands of icons.
311
+ */
312
+ export function IconPickerWidget({
313
+ label,
314
+ value,
315
+ onChange,
316
+ }: {
317
+ label: string;
318
+ value: string;
319
+ onChange: (value: string) => void;
320
+ }) {
321
+ const [open, setOpen] = useState(false);
322
+ const [search, setSearch] = useState("");
323
+ const [sets, setSets] = useState<IconSetInfo[]>([]);
324
+ const [set, setSet] = useState<string>();
325
+ const [found, setFound] = useState<IconSearch>({ icons: [], total: 0 });
326
+ const [current, setCurrent] = useState<Icon | null | undefined>(knownIcons.get(value));
327
+ const [problem, setProblem] = useState("");
328
+
329
+ // The sets, and how the chosen icon looks.
330
+ useEffect(() => {
331
+ let stale = false;
332
+ api
333
+ .icons(value)
334
+ .then((answer) => {
335
+ if (stale) return;
336
+ knownIcons.set(value, answer.icon ?? null);
337
+ setCurrent(answer.icon ?? null);
338
+ setSets(answer.sets);
339
+ // Open on the set the chosen icon is from.
340
+ setSet((now) => now ?? answer.sets.find((one) => value.startsWith(`${one.id}:`))?.id ?? answer.sets[0]?.id);
341
+ })
342
+ .catch(
343
+ (error: unknown) => !stale && setProblem(error instanceof Error ? error.message : "Could not load icons."),
344
+ );
345
+ return () => {
346
+ stale = true;
347
+ };
348
+ }, [value]);
349
+
350
+ // The icons of the open set, asked again shortly after the search stops changing.
351
+ useEffect(() => {
352
+ if (!open || !set) return;
353
+ let stale = false;
354
+ const wait = setTimeout(
355
+ () => {
356
+ api
357
+ .searchIcons(set, search)
358
+ .then((answer) => {
359
+ if (stale) return;
360
+ for (const icon of answer.icons) knownIcons.set(icon.value, icon);
361
+ setFound(answer);
362
+ setProblem("");
363
+ })
364
+ .catch(
365
+ (error: unknown) => !stale && setProblem(error instanceof Error ? error.message : "Could not load icons."),
366
+ );
367
+ },
368
+ search ? 200 : 0,
369
+ );
370
+ return () => {
371
+ stale = true;
372
+ clearTimeout(wait);
373
+ };
374
+ }, [open, set, search]);
375
+
376
+ const choose = (name: string): void => {
377
+ onChange(name);
378
+ setOpen(false);
379
+ };
380
+
381
+ return (
382
+ <div className="field-group">
383
+ <span className="field-label">{label}</span>
384
+ <button type="button" className="ipw-trigger" onClick={() => setOpen(true)}>
385
+ <IconPreview icon={current} />
386
+ <span className="ipw-name">{current ? current.name : "Choose icon..."}</span>
387
+ <ChevronRightIcon />
388
+ </button>
389
+ {open &&
390
+ createPortal(
391
+ <div
392
+ className="ipw-panel"
393
+ role="dialog"
394
+ aria-label="Choose Icon"
395
+ onKeyDown={(event) => event.key === "Escape" && !isComposing(event) && setOpen(false)}
396
+ >
397
+ <header className="ipw-header">
398
+ <button type="button" className="brim-sidebar-close-btn" aria-label="Back" onClick={() => setOpen(false)}>
399
+ <ArrowLeftIcon />
400
+ </button>
401
+ <h2>Choose Icon</h2>
402
+ </header>
403
+ {sets.length > 1 && (
404
+ <div className="ipw-sets" role="tablist" aria-label="Icon sets">
405
+ {sets.map((one) => (
406
+ <button
407
+ key={one.id}
408
+ type="button"
409
+ role="tab"
410
+ className="ipw-set"
411
+ aria-selected={one.id === set}
412
+ title={`${one.name} · ${one.total} icons`}
413
+ onClick={() => {
414
+ setFound({ icons: [], total: 0 });
415
+ setSet(one.id);
416
+ }}
417
+ >
418
+ {one.name}
419
+ </button>
420
+ ))}
421
+ </div>
422
+ )}
423
+ <input
424
+ className="field-input ipw-search"
425
+ type="search"
426
+ placeholder="Search icons..."
427
+ autoFocus
428
+ value={search}
429
+ onChange={(event) => setSearch(event.target.value)}
430
+ />
431
+ {problem && (
432
+ <p className="field-description" role="alert">
433
+ {problem}
434
+ </p>
435
+ )}
436
+ {sets.length === 0 && !problem && <p className="field-description">This site offers no icons.</p>}
437
+ <div className="ipw-grid">
438
+ <button
439
+ type="button"
440
+ className="ipw-cell"
441
+ aria-pressed={!current}
442
+ title="None"
443
+ onClick={() => choose("none")}
444
+ >
445
+ <IconPreview icon={null} />
446
+ </button>
447
+ {found.icons.map((icon) => (
448
+ <button
449
+ key={icon.value}
450
+ type="button"
451
+ className="ipw-cell"
452
+ aria-pressed={icon.value === value}
453
+ title={icon.name}
454
+ onClick={() => choose(icon.value)}
455
+ >
456
+ <IconPreview icon={icon} />
457
+ </button>
458
+ ))}
459
+ </div>
460
+ {found.total > found.icons.length && (
461
+ <p className="field-description">
462
+ Showing {found.icons.length} of {found.total}. Search to find the others.
463
+ </p>
464
+ )}
465
+ </div>,
466
+ document.body,
467
+ )}
468
+ </div>
469
+ );
470
+ }
471
+
472
+ const BREAKPOINTS = ["Desktop", "Tablet", "Mobile"] as const;
473
+
474
+ /** One number per preview size, each stored in its own setting. */
475
+ export function BreakpointNumberWidget({
476
+ label,
477
+ description,
478
+ values,
479
+ }: {
480
+ label: string;
481
+ description?: string | undefined;
482
+ /** Desktop, tablet and mobile, in that order. A breakpoint without its own setting is left out. */
483
+ values: ({ value: number; min: number; max: number; onChange: (value: number) => void } | undefined)[];
484
+ }) {
485
+ return (
486
+ <div className="field-group">
487
+ <span className="field-label">{label}</span>
488
+ {description && <p className="field-description">{description}</p>}
489
+ <div className="breakpoint-number">
490
+ {values.map(
491
+ (entry, index) =>
492
+ entry && (
493
+ <label key={BREAKPOINTS[index]}>
494
+ <span>{BREAKPOINTS[index]}</span>
495
+ <NumberBox
496
+ className="field-input"
497
+ min={entry.min}
498
+ max={entry.max}
499
+ value={entry.value}
500
+ onChange={entry.onChange}
501
+ />
502
+ </label>
503
+ ),
504
+ )}
505
+ </div>
506
+ </div>
507
+ );
508
+ }
509
+
510
+ /** The image folder of the item being edited: one folder per item, e.g. one project's photos. */
511
+ export interface MediaFolder {
512
+ /** `<type>/<item id>`; absent while the item is new and not saved yet. */
513
+ key?: string | undefined;
514
+ /** How the item is named to the owner: its title, or e.g. "project" while it is new. */
515
+ label: string;
516
+ }
517
+
518
+ /**
519
+ * Provided by the item form. Inside it, uploads ask whether the image goes to the gallery or to the
520
+ * item's own folder; everywhere else (a page's blocks) they go to the gallery without asking.
521
+ */
522
+ export const MediaFolderContext = createContext<MediaFolder | undefined>(undefined);
523
+
524
+ /**
525
+ * The image picker: upload a file (or drop one on the box), choose one already uploaded,
526
+ * or paste an address. Stores the image's address.
527
+ */
528
+ export function ImageUploadWidget({
529
+ label,
530
+ description,
531
+ value,
532
+ onChange,
533
+ }: {
534
+ label: string;
535
+ description?: string | undefined;
536
+ value: string;
537
+ onChange: (url: string, file?: MediaFile) => void;
538
+ }) {
539
+ const [busy, setBusy] = useState(false);
540
+ const [error, setError] = useState("");
541
+ const [choosing, setChoosing] = useState(false);
542
+ const [address, setAddress] = useState("");
543
+ const [pending, setPending] = useState<File>();
544
+ const [note, setNote] = useState("");
545
+ const fileInput = useRef<HTMLInputElement>(null);
546
+ const folder = useContext(MediaFolderContext);
547
+
548
+ /** In a saved item the owner chooses where the image goes; elsewhere it goes to the gallery. */
549
+ function receive(file: File | undefined): void {
550
+ if (!file) return;
551
+ if (folder?.key) return setPending(file);
552
+ // A new item has no folder yet: its id only exists once it is saved.
553
+ setNote(folder ? `Saved to the gallery. Save this ${folder.label} once to give it its own image folder.` : "");
554
+ void upload(file, "");
555
+ }
556
+
557
+ async function upload(file: File, destination: string): Promise<void> {
558
+ setPending(undefined);
559
+ setBusy(true);
560
+ setError("");
561
+ try {
562
+ const uploaded = await api.upload(file, destination);
563
+ onChange(uploaded.url, uploaded);
564
+ } catch (failure) {
565
+ setError(failure instanceof Error ? failure.message : "Could not upload the image.");
566
+ } finally {
567
+ setBusy(false);
568
+ }
569
+ }
570
+
571
+ return (
572
+ <div className="field-group">
573
+ <span className="field-label">{label}</span>
574
+ {description && <p className="field-description">{description}</p>}
575
+ <div
576
+ className="image-widget-container"
577
+ data-busy={busy}
578
+ onDragOver={(event) => event.preventDefault()}
579
+ onDrop={(event) => {
580
+ event.preventDefault();
581
+ receive(event.dataTransfer.files[0]);
582
+ }}
583
+ >
584
+ {value ? (
585
+ <>
586
+ <img className="preview-img" src={value} alt="" />
587
+ <div className="image-widget-actions">
588
+ <button type="button" className="btn-upload" onClick={() => fileInput.current?.click()}>
589
+ Replace
590
+ </button>
591
+ <button type="button" className="btn-gallery" onClick={() => setChoosing(true)}>
592
+ Choose from site
593
+ </button>
594
+ <button type="button" className="btn-remove" onClick={() => onChange("")}>
595
+ Remove
596
+ </button>
597
+ </div>
598
+ </>
599
+ ) : (
600
+ <>
601
+ <p className="image-widget-empty">No image selected</p>
602
+ <div className="image-widget-actions">
603
+ <button type="button" className="btn-upload" onClick={() => fileInput.current?.click()}>
604
+ Upload
605
+ </button>
606
+ <button type="button" className="btn-gallery" onClick={() => setChoosing(true)}>
607
+ Choose from site
608
+ </button>
609
+ </div>
610
+ <form
611
+ className="external-url-panel"
612
+ onSubmit={(event) => {
613
+ event.preventDefault();
614
+ if (address.trim()) onChange(address.trim());
615
+ }}
616
+ >
617
+ <input
618
+ className="field-input"
619
+ type="text"
620
+ aria-label="Image address"
621
+ placeholder="https://example.com"
622
+ value={address}
623
+ onChange={(event) => setAddress(event.target.value)}
624
+ />
625
+ <button type="submit" className="btn-apply-url" aria-label="Use this address">
626
+ <ChevronRightIcon />
627
+ </button>
628
+ </form>
629
+ <p className="field-description">Paste image URL or use the options above</p>
630
+ </>
631
+ )}
632
+ {busy && <p className="image-widget-overlay">Uploading…</p>}
633
+ <input
634
+ ref={fileInput}
635
+ type="file"
636
+ accept="image/jpeg,image/png,image/gif,image/webp,image/avif"
637
+ hidden
638
+ onChange={(event) => {
639
+ receive(event.target.files?.[0]);
640
+ event.target.value = "";
641
+ }}
642
+ />
643
+ {pending && folder?.key && (
644
+ <div className="image-destination" role="group" aria-label="Where to save the image">
645
+ <p>Where should this image go?</p>
646
+ <button type="button" className="btn-upload" onClick={() => void upload(pending, folder.key ?? "")}>
647
+ Folder of “{folder.label}”
648
+ </button>
649
+ <button type="button" className="btn-gallery" onClick={() => void upload(pending, "")}>
650
+ Gallery
651
+ </button>
652
+ <button type="button" className="btn-remove" onClick={() => setPending(undefined)}>
653
+ Cancel
654
+ </button>
655
+ </div>
656
+ )}
657
+ </div>
658
+ {error && (
659
+ <p className="field-error" role="alert">
660
+ {error}
661
+ </p>
662
+ )}
663
+ {note && !error && <p className="field-description">{note}</p>}
664
+ {choosing && (
665
+ <MediaPicker
666
+ folder={folder}
667
+ onPick={(file) => {
668
+ setChoosing(false);
669
+ onChange(file.url, file);
670
+ }}
671
+ onClose={() => setChoosing(false)}
672
+ />
673
+ )}
674
+ </div>
675
+ );
676
+ }
677
+
678
+ /**
679
+ * The images already uploaded to the site, to pick one from: all of them, the gallery, and, when opened
680
+ * from a saved item, that item's own folder, where it starts.
681
+ */
682
+ function MediaPicker({
683
+ folder,
684
+ onPick,
685
+ onClose,
686
+ }: {
687
+ folder: MediaFolder | undefined;
688
+ onPick: (file: MediaFile) => void;
689
+ onClose: () => void;
690
+ }) {
691
+ const [files, setFiles] = useState<MediaFile[]>();
692
+ /** Where the next page starts; absent once the last one is shown. */
693
+ const [next, setNext] = useState<string>();
694
+ const [search, setSearch] = useState("");
695
+ /** The search as asked of the server: once typing pauses. */
696
+ const [query, setQuery] = useState("");
697
+ const [tab, setTab] = useState<string>(folder?.key ?? "all");
698
+ const loadingMore = useRef(false);
699
+ const end = useRef<HTMLDivElement>(null);
700
+ const tabs = [
701
+ { key: "all", label: "All images" },
702
+ { key: "gallery", label: "Gallery" },
703
+ ...(folder?.key ? [{ key: folder.key, label: `Folder of “${folder.label}”` }] : []),
704
+ ];
705
+ // The server searches and filters the whole library and answers a page at a time: thousands of images stay
706
+ // reachable, and the picker never holds them all.
707
+ const asked = { search: query, ...(tab !== "all" && { folder: tab === "gallery" ? "" : tab }) };
708
+ useEffect(() => {
709
+ const pause = setTimeout(() => setQuery(search.trim()), 250);
710
+ return () => clearTimeout(pause);
711
+ }, [search]);
712
+ useEffect(() => {
713
+ let current = true;
714
+ setFiles(undefined);
715
+ setNext(undefined);
716
+ void api.media(asked).then((page) => {
717
+ if (!current) return;
718
+ setFiles(page.files);
719
+ setNext(page.next);
720
+ });
721
+ return () => {
722
+ current = false;
723
+ };
724
+ }, [tab, query]);
725
+ // The next page comes as the end of the grid scrolls into view.
726
+ useEffect(() => {
727
+ const marker = end.current;
728
+ if (!marker || !next) return;
729
+ const observer = new IntersectionObserver(
730
+ (entries) => {
731
+ if (!entries.some((entry) => entry.isIntersecting) || loadingMore.current) return;
732
+ loadingMore.current = true;
733
+ void api
734
+ .media({ ...asked, after: next })
735
+ .then((page) => {
736
+ setFiles((shown) => [...(shown ?? []), ...page.files]);
737
+ setNext(page.next);
738
+ })
739
+ .finally(() => {
740
+ loadingMore.current = false;
741
+ });
742
+ },
743
+ { root: marker.parentElement, rootMargin: "600px" },
744
+ );
745
+ observer.observe(marker);
746
+ return () => observer.disconnect();
747
+ }, [next, files]);
748
+ const shown = files;
749
+
750
+ return createPortal(
751
+ <div className="cb-modal-overlay" onClick={onClose}>
752
+ <div
753
+ className="media-picker"
754
+ role="dialog"
755
+ aria-label="Choose from site"
756
+ onClick={(event) => event.stopPropagation()}
757
+ >
758
+ <header>
759
+ <h3>Gallery</h3>
760
+ <input
761
+ className="field-input"
762
+ type="search"
763
+ placeholder="Search images..."
764
+ value={search}
765
+ onChange={(event) => setSearch(event.target.value)}
766
+ />
767
+ <button type="button" className="cb-toolbar-btn" onClick={onClose}>
768
+ Close
769
+ </button>
770
+ </header>
771
+ <nav className="media-picker-tabs" aria-label="Folders">
772
+ {tabs.map(({ key, label }) => (
773
+ <button key={key} type="button" aria-pressed={tab === key} onClick={() => setTab(key)}>
774
+ {label}
775
+ </button>
776
+ ))}
777
+ </nav>
778
+ {!shown ? (
779
+ <p className="cb-state">Loading...</p>
780
+ ) : shown.length === 0 ? (
781
+ <p className="cb-state">{query ? "No image has that name." : "No images here yet. Upload one first."}</p>
782
+ ) : (
783
+ <div className="media-picker-grid">
784
+ {shown.map((file) => (
785
+ <button key={file.id} type="button" title={file.name} onClick={() => onPick(file)}>
786
+ <img src={file.thumbnail ?? file.url} alt={file.name} loading="lazy" decoding="async" />
787
+ </button>
788
+ ))}
789
+ {next && <div ref={end} className="media-picker-more" aria-hidden="true" />}
790
+ </div>
791
+ )}
792
+ </div>
793
+ </div>,
794
+ document.body,
795
+ );
796
+ }
797
+
798
+ /** Drag the dot to say which part of the image must stay visible when it is cropped. */
799
+ export function FocusWidget({
800
+ label,
801
+ image,
802
+ x,
803
+ y,
804
+ inherited,
805
+ onChange,
806
+ }: {
807
+ label: string;
808
+ image: string;
809
+ /** Percentages from the left and the top; `undefined` means not set for this preview size. */
810
+ x: number | undefined;
811
+ y: number | undefined;
812
+ /** What applies while this preview size has no value of its own. */
813
+ inherited: { x: number | undefined; y: number | undefined };
814
+ onChange: (x: number, y: number) => void;
815
+ }) {
816
+ const frame = useRef<HTMLDivElement>(null);
817
+ const currentX = x ?? inherited.x ?? 50;
818
+ const currentY = y ?? inherited.y ?? 50;
819
+
820
+ function moveTo(clientX: number, clientY: number): void {
821
+ const bounds = frame.current?.getBoundingClientRect();
822
+ if (!bounds) return;
823
+ onChange(
824
+ Math.round(clamp(((clientX - bounds.left) / bounds.width) * 100, 0, 100)),
825
+ Math.round(clamp(((clientY - bounds.top) / bounds.height) * 100, 0, 100)),
826
+ );
827
+ }
828
+
829
+ return (
830
+ <div className="field-group">
831
+ <span className="field-label">{label}</span>
832
+ <div
833
+ ref={frame}
834
+ className="focus-frame"
835
+ style={{ "--focus-x": `${currentX}%`, "--focus-y": `${currentY}%` } as React.CSSProperties}
836
+ onPointerDown={(event) => {
837
+ event.currentTarget.setPointerCapture(event.pointerId);
838
+ moveTo(event.clientX, event.clientY);
839
+ }}
840
+ onPointerMove={(event) => event.buttons === 1 && moveTo(event.clientX, event.clientY)}
841
+ >
842
+ {image && <img src={image} alt="" draggable={false} />}
843
+ <button
844
+ type="button"
845
+ className="focus-point"
846
+ aria-label="Focal point. Use the arrow keys to move it."
847
+ onKeyDown={(event) => {
848
+ const step = event.shiftKey ? 10 : 1;
849
+ const move: Record<string, [number, number]> = {
850
+ ArrowLeft: [-step, 0],
851
+ ArrowRight: [step, 0],
852
+ ArrowUp: [0, -step],
853
+ ArrowDown: [0, step],
854
+ };
855
+ const delta = move[event.key];
856
+ if (!delta) return;
857
+ event.preventDefault();
858
+ onChange(clamp(currentX + delta[0], 0, 100), clamp(currentY + delta[1], 0, 100));
859
+ }}
860
+ />
861
+ </div>
862
+ <div className="focus-footer">
863
+ <span className="focus-value">
864
+ {currentX}% {currentY}%{x === undefined ? " inherited" : ""}
865
+ </span>
866
+ <button type="button" className="focus-reset" onClick={() => onChange(50, 50)}>
867
+ Center
868
+ </button>
869
+ </div>
870
+ </div>
871
+ );
872
+ }
873
+
874
+ function shapeStyle(shape: ImageShape): React.CSSProperties {
875
+ if (shape.radius) return { borderRadius: shape.radius };
876
+ if (shape.polygon) return { clipPath: `polygon(${shape.polygon})` };
877
+ return {};
878
+ }
879
+
880
+ /** A grid of the shapes an image can be cut to. */
881
+ export function ShapeWidget({
882
+ label,
883
+ value,
884
+ onChange,
885
+ }: {
886
+ label: string;
887
+ value: string;
888
+ onChange: (value: string) => void;
889
+ }) {
890
+ return (
891
+ <div className="field-group">
892
+ <span className="field-label">{label}</span>
893
+ <div className="shape-grid" role="group" aria-label={label}>
894
+ {IMAGE_SHAPES.map((shape) => (
895
+ <button
896
+ key={shape.key}
897
+ type="button"
898
+ className="shape-option"
899
+ aria-pressed={shape.key === value}
900
+ aria-label={shape.label}
901
+ title={shape.label}
902
+ onClick={() => onChange(shape.key)}
903
+ >
904
+ {shape.path ? (
905
+ <svg className="shape-swatch" viewBox={shape.path.viewBox} aria-hidden="true">
906
+ <path d={shape.path.d} fill="currentColor" />
907
+ </svg>
908
+ ) : (
909
+ <span className="shape-swatch" style={shapeStyle(shape)} />
910
+ )}
911
+ </button>
912
+ ))}
913
+ </div>
914
+ </div>
915
+ );
916
+ }
917
+
918
+ /**
919
+ * A list of collapsible cards, one per entry, with move and remove controls.
920
+ * BrimCMS used it for gallery images and accordion items.
921
+ */
922
+ export function CardList<Entry>({
923
+ label,
924
+ addLabel,
925
+ entries,
926
+ title,
927
+ thumbnail,
928
+ create,
929
+ render,
930
+ onChange,
931
+ }: {
932
+ label: string;
933
+ addLabel: string;
934
+ entries: Entry[];
935
+ title: (entry: Entry, index: number) => string;
936
+ thumbnail?: (entry: Entry) => string | undefined;
937
+ create: (index: number) => Entry;
938
+ render: (entry: Entry, change: (entry: Entry) => void) => ReactNode;
939
+ onChange: (entries: Entry[]) => void;
940
+ }) {
941
+ const [open, setOpen] = useState<number | null>(null);
942
+
943
+ function move(index: number, offset: number): void {
944
+ const next = [...entries];
945
+ const [entry] = next.splice(index, 1);
946
+ if (entry === undefined) return;
947
+ next.splice(index + offset, 0, entry);
948
+ setOpen(null);
949
+ onChange(next);
950
+ }
951
+
952
+ return (
953
+ <div className="field-group card-list">
954
+ <div className="card-list-header">
955
+ <span className="field-label">{label}</span>
956
+ <span className="card-list-count">{entries.length}</span>
957
+ </div>
958
+ {entries.map((entry, index) => {
959
+ const image = thumbnail?.(entry);
960
+ return (
961
+ <div key={index} className="card-list-item" data-open={open === index}>
962
+ <div className="card-list-row">
963
+ <button
964
+ type="button"
965
+ className="card-list-toggle"
966
+ aria-expanded={open === index}
967
+ onClick={() => setOpen(open === index ? null : index)}
968
+ >
969
+ {image && <img src={image} alt="" />}
970
+ <span>{title(entry, index)}</span>
971
+ </button>
972
+ <button
973
+ type="button"
974
+ className="card-list-btn"
975
+ disabled={index === 0}
976
+ aria-label="Move up"
977
+ title="Move up"
978
+ onClick={() => move(index, -1)}
979
+ >
980
+ ↑
981
+ </button>
982
+ <button
983
+ type="button"
984
+ className="card-list-btn"
985
+ disabled={index === entries.length - 1}
986
+ aria-label="Move down"
987
+ title="Move down"
988
+ onClick={() => move(index, 1)}
989
+ >
990
+ ↓
991
+ </button>
992
+ <button
993
+ type="button"
994
+ className="card-list-btn"
995
+ aria-label="Remove"
996
+ title="Remove"
997
+ onClick={() => onChange(entries.filter((_, i) => i !== index))}
998
+ >
999
+ ×
1000
+ </button>
1001
+ </div>
1002
+ {open === index && (
1003
+ <div className="card-list-body">
1004
+ {render(entry, (next) => onChange(entries.map((current, i) => (i === index ? next : current))))}
1005
+ </div>
1006
+ )}
1007
+ </div>
1008
+ );
1009
+ })}
1010
+ <button
1011
+ type="button"
1012
+ className="card-list-add"
1013
+ onClick={() => {
1014
+ setOpen(entries.length);
1015
+ onChange([...entries, create(entries.length)]);
1016
+ }}
1017
+ >
1018
+ + {addLabel}
1019
+ </button>
1020
+ </div>
1021
+ );
1022
+ }
1023
+
1024
+ const FIT_OPTIONS = [
1025
+ { value: "contain", label: "Fit", description: "Shows the whole picture" },
1026
+ { value: "cover", label: "Fill", description: "Crops to cover the area" },
1027
+ ];
1028
+
1029
+ /** Fit shows the whole picture; Fill crops it to cover its area. */
1030
+ export function FitWidget({
1031
+ label,
1032
+ description,
1033
+ value,
1034
+ onChange,
1035
+ }: {
1036
+ label: string;
1037
+ description?: string | undefined;
1038
+ value: string;
1039
+ onChange: (value: string) => void;
1040
+ }) {
1041
+ return (
1042
+ <div className="field-group">
1043
+ <span className="field-label">{label}</span>
1044
+ {description && <p className="field-description">{description}</p>}
1045
+ <div className="size-picker" role="group" aria-label={label}>
1046
+ {FIT_OPTIONS.map((option) => (
1047
+ <button
1048
+ key={option.value}
1049
+ type="button"
1050
+ className="size-btn fit-option"
1051
+ aria-pressed={option.value === value}
1052
+ title={option.description}
1053
+ onClick={() => onChange(option.value)}
1054
+ >
1055
+ {option.label}
1056
+ </button>
1057
+ ))}
1058
+ </div>
1059
+ </div>
1060
+ );
1061
+ }
1062
+
1063
+ /**
1064
+ * The networks of a social block, in the order they are shown. Each can be switched off;
1065
+ * in profile mode each also takes the address of the site's own profile.
1066
+ */
1067
+ export function SocialNetworksWidget({
1068
+ label,
1069
+ description,
1070
+ order,
1071
+ settings,
1072
+ withProfiles,
1073
+ onPatch,
1074
+ }: {
1075
+ label: string;
1076
+ description?: string | undefined;
1077
+ order: unknown;
1078
+ settings: Record<string, unknown>;
1079
+ withProfiles: boolean;
1080
+ onPatch: (patch: Record<string, unknown>) => void;
1081
+ }) {
1082
+ const networks = orderSocialNetworks(SOCIAL_NETWORKS, order);
1083
+
1084
+ function move(index: number, offset: number): void {
1085
+ const keys = networks.map((network) => network.key);
1086
+ const [key] = keys.splice(index, 1);
1087
+ if (key === undefined) return;
1088
+ keys.splice(index + offset, 0, key);
1089
+ onPatch({ networkOrder: keys });
1090
+ }
1091
+
1092
+ return (
1093
+ <div className="field-group">
1094
+ <span className="field-label">{label}</span>
1095
+ {description && <p className="field-description">{description}</p>}
1096
+ {networks.map((network, index) => {
1097
+ const enabled = settings[`${network.key}Enabled`] !== false;
1098
+ return (
1099
+ <div key={network.key} className="card-list-item">
1100
+ <div className="card-list-row">
1101
+ <label className="card-list-toggle">
1102
+ <input
1103
+ className="field-checkbox"
1104
+ type="checkbox"
1105
+ checked={enabled}
1106
+ onChange={(event) => onPatch({ [`${network.key}Enabled`]: event.target.checked })}
1107
+ />
1108
+ <span>{network.label}</span>
1109
+ </label>
1110
+ <button
1111
+ type="button"
1112
+ className="card-list-btn"
1113
+ disabled={index === 0}
1114
+ aria-label={`Move ${network.label} up`}
1115
+ onClick={() => move(index, -1)}
1116
+ >
1117
+ ↑
1118
+ </button>
1119
+ <button
1120
+ type="button"
1121
+ className="card-list-btn"
1122
+ disabled={index === networks.length - 1}
1123
+ aria-label={`Move ${network.label} down`}
1124
+ onClick={() => move(index, 1)}
1125
+ >
1126
+ ↓
1127
+ </button>
1128
+ </div>
1129
+ {withProfiles && enabled && (
1130
+ <div className="card-list-body">
1131
+ <DraftInput
1132
+ label={`${network.label} address`}
1133
+ value={
1134
+ typeof settings[network.profileField] === "string" ? (settings[network.profileField] as string) : ""
1135
+ }
1136
+ placeholder={
1137
+ network.key === "email"
1138
+ ? "name@example.com"
1139
+ : network.key === "phone"
1140
+ ? "+40 700 000 000"
1141
+ : "https://…"
1142
+ }
1143
+ onChange={(value) => onPatch({ [network.profileField]: value })}
1144
+ />
1145
+ </div>
1146
+ )}
1147
+ </div>
1148
+ );
1149
+ })}
1150
+ </div>
1151
+ );
1152
+ }
1153
+
1154
+ /** A plain input that reports its value when the person leaves it or presses Enter. */
1155
+ function DraftInput({
1156
+ label,
1157
+ value,
1158
+ placeholder,
1159
+ onChange,
1160
+ }: {
1161
+ label: string;
1162
+ value: string;
1163
+ placeholder?: string;
1164
+ onChange: (value: string) => void;
1165
+ }) {
1166
+ const [draft, setDraft] = useState(value);
1167
+ useEffect(() => setDraft(value), [value]);
1168
+ return (
1169
+ <input
1170
+ className="field-input"
1171
+ type="text"
1172
+ aria-label={label}
1173
+ placeholder={placeholder}
1174
+ value={draft}
1175
+ onChange={(event) => setDraft(event.target.value)}
1176
+ onBlur={() => draft !== value && onChange(draft.trim())}
1177
+ onKeyDown={(event) => event.key === "Enter" && !isComposing(event) && event.currentTarget.blur()}
1178
+ />
1179
+ );
1180
+ }
1181
+
1182
+ interface FoundPlace {
1183
+ lat: string;
1184
+ lon: string;
1185
+ display_name: string;
1186
+ }
1187
+
1188
+ /**
1189
+ * Looks an address up on OpenStreetMap and reports where it is.
1190
+ * The address is sent to OpenStreetMap's search service only when the person presses Find.
1191
+ */
1192
+ export function LocationSearch({ address, onFound }: { address: string; onFound: (lat: number, lng: number) => void }) {
1193
+ const [state, setState] = useState<"idle" | "searching" | "missing" | "failed">("idle");
1194
+
1195
+ async function find(): Promise<void> {
1196
+ setState("searching");
1197
+ try {
1198
+ const query = new URLSearchParams({ format: "json", limit: "1", q: address });
1199
+ const response = await fetch(`https://nominatim.openstreetmap.org/search?${query}`);
1200
+ const [place] = (await response.json()) as FoundPlace[];
1201
+ if (!place) return setState("missing");
1202
+ onFound(Number(Number(place.lat).toFixed(6)), Number(Number(place.lon).toFixed(6)));
1203
+ setState("idle");
1204
+ } catch {
1205
+ setState("failed");
1206
+ }
1207
+ }
1208
+
1209
+ return (
1210
+ <div className="location-search">
1211
+ <button type="button" disabled={address.trim() === "" || state === "searching"} onClick={() => void find()}>
1212
+ {state === "searching" ? "Finding…" : "Find on map"}
1213
+ </button>
1214
+ {state === "missing" && <span className="field-error">No place found for this address.</span>}
1215
+ {state === "failed" && <span className="field-error">Could not reach the map search.</span>}
1216
+ </div>
1217
+ );
1218
+ }