@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,326 @@
1
+ import { renderBlocks, renderInline } from "../../content/rich-text.ts";
2
+ import type { InlineMark, InlineNode, RichTextBlock, TextAlign } from "../../content/types.ts";
3
+
4
+ export type { InlineNode, RichTextBlock, TextAlign };
5
+
6
+ type BlockTag = Exclude<RichTextBlock["tag"], "ul" | "ol">;
7
+
8
+ const MARKS: Record<string, InlineMark> = {
9
+ B: "strong",
10
+ STRONG: "strong",
11
+ I: "em",
12
+ EM: "em",
13
+ U: "u",
14
+ S: "s",
15
+ STRIKE: "s",
16
+ DEL: "s",
17
+ SUB: "sub",
18
+ SUP: "sup",
19
+ };
20
+ const BLOCK_TAGS = ["P", "H1", "H2", "H3", "H4", "H5", "H6", "BLOCKQUOTE"];
21
+ const ALIGNMENTS: readonly string[] = ["left", "center", "right", "justify"];
22
+
23
+ // The edited content lives in the page frame's realm, so `instanceof` checks from here always fail.
24
+ function isElement(node: Node): node is HTMLElement {
25
+ return node.nodeType === Node.ELEMENT_NODE;
26
+ }
27
+
28
+ /**
29
+ * Spaces, tabs and line breaks the browser shows as one space, as in the page's source (`<p>\n Hello\n</p>`). A
30
+ * space the owner typed twice is a non-breaking space, which is kept.
31
+ */
32
+ const COLLAPSIBLE = /[ \t\n\r\f]+/g;
33
+
34
+ /** Whether the element shows its text's spaces and line breaks as written (`white-space: pre`, a code block). */
35
+ function keepsWhitespace(element: HTMLElement): boolean {
36
+ const view = element.ownerDocument.defaultView;
37
+ const whiteSpace = view ? view.getComputedStyle(element).whiteSpace : "normal";
38
+ return whiteSpace.startsWith("pre") || whiteSpace === "break-spaces";
39
+ }
40
+
41
+ /** An element's words as the page shows them: the source's indentation and line breaks are not saved. */
42
+ export function readText(element: HTMLElement): string {
43
+ const text = element.textContent ?? "";
44
+ return keepsWhitespace(element) ? text : text.replace(COLLAPSIBLE, " ").trim();
45
+ }
46
+
47
+ /** An element's formatted words, collapsed like `readText`: what is saved is what the page shows. */
48
+ export function readInlineText(element: HTMLElement): InlineNode[] {
49
+ const nodes = readInline(element);
50
+ return keepsWhitespace(element) ? nodes : tidy(nodes);
51
+ }
52
+
53
+ /** Collapses spaces inside the words, and drops those at the very start and end, also inside a link or a mark. */
54
+ function tidy(nodes: InlineNode[]): InlineNode[] {
55
+ const collapse = (node: InlineNode): InlineNode =>
56
+ typeof node === "string"
57
+ ? node.replace(COLLAPSIBLE, " ")
58
+ : "children" in node
59
+ ? { ...node, children: node.children.map(collapse) }
60
+ : node;
61
+ return trimEdge(trimEdge(nodes.map(collapse), "start"), "end");
62
+ }
63
+
64
+ /** Trims the first (or last) words, going into the formatting that holds them; what is left empty is dropped. */
65
+ function trimEdge(nodes: InlineNode[], edge: "start" | "end"): InlineNode[] {
66
+ const list = [...nodes];
67
+ const index = edge === "start" ? 0 : list.length - 1;
68
+ const node = list[index];
69
+ if (node === undefined) return list;
70
+ if (typeof node === "string") {
71
+ const trimmed = edge === "start" ? node.trimStart() : node.trimEnd();
72
+ if (trimmed === "") return trimEdge(edge === "start" ? list.slice(1) : list.slice(0, -1), edge);
73
+ list[index] = trimmed;
74
+ } else if ("children" in node && node.tag !== "br") {
75
+ list[index] = { ...node, children: trimEdge(node.children, edge) };
76
+ }
77
+ return list;
78
+ }
79
+
80
+ /** Reads inline formatting. Anything the server would not accept is unwrapped to its text. */
81
+ export function readInline(parent: Node): InlineNode[] {
82
+ return [...parent.childNodes].flatMap((node): InlineNode[] => {
83
+ if (node.nodeType === Node.TEXT_NODE) return node.textContent ? [node.textContent] : [];
84
+ return isElement(node) ? readElement(node) : [];
85
+ });
86
+ }
87
+
88
+ function readElement(element: HTMLElement): InlineNode[] {
89
+ if (element.tagName === "BR") return [{ tag: "br", children: [] }];
90
+ const children = readInline(element);
91
+ const href = element.getAttribute("href");
92
+ if (element.tagName === "A" && href) return [{ tag: "a", href, children }];
93
+ const mark = MARKS[element.tagName];
94
+ if (mark) return [{ tag: mark, children }];
95
+
96
+ const color = hexColor(element.getAttribute("color") ?? element.style.color);
97
+ const background = hexColor(element.style.backgroundColor);
98
+ if (!color && !background) return children;
99
+ return [{ tag: "span", ...(color && { color }), ...(background && { background }), children }];
100
+ }
101
+
102
+ /** Reads flowing content. Loose text between blocks becomes a paragraph. */
103
+ export function readBlocks(container: HTMLElement): RichTextBlock[] {
104
+ const blocks: RichTextBlock[] = [];
105
+ let loose: InlineNode[] = [];
106
+ const flushLoose = (): void => {
107
+ if (loose.some((node) => typeof node !== "string" || node.trim() !== ""))
108
+ blocks.push({ tag: "p", children: keepsWhitespace(container) ? loose : tidy(loose) });
109
+ loose = [];
110
+ };
111
+
112
+ for (const node of container.childNodes) {
113
+ if (!isElement(node)) {
114
+ if (node.textContent) loose.push(node.textContent);
115
+ } else if (node.tagName === "UL" || node.tagName === "OL") {
116
+ flushLoose();
117
+ const items = [...node.children]
118
+ .filter((item): item is HTMLElement => item.tagName === "LI")
119
+ .map((item) => readInlineText(item));
120
+ blocks.push({ tag: node.tagName === "UL" ? "ul" : "ol", items });
121
+ } else if (BLOCK_TAGS.includes(node.tagName) || node.tagName === "DIV") {
122
+ flushLoose();
123
+ const align = alignOf(node);
124
+ blocks.push({
125
+ tag: node.tagName === "DIV" ? "p" : (node.tagName.toLowerCase() as BlockTag),
126
+ ...(align && { align }),
127
+ children: readInlineText(node),
128
+ });
129
+ } else {
130
+ loose.push(...readElement(node));
131
+ }
132
+ }
133
+ flushLoose();
134
+ return blocks;
135
+ }
136
+
137
+ export function alignOf(element: HTMLElement): TextAlign | undefined {
138
+ const align = element.style.textAlign;
139
+ return ALIGNMENTS.includes(align) ? (align as TextAlign) : undefined;
140
+ }
141
+
142
+ export function hasFormatting(nodes: InlineNode[]): boolean {
143
+ return nodes.some((node) => typeof node !== "string");
144
+ }
145
+
146
+ /** Browsers report colors as `rgb(…)`; they are saved as hex. Fully transparent means no color. */
147
+ export function hexColor(value: string | null): string | undefined {
148
+ if (!value) return undefined;
149
+ if (/^#[0-9a-f]{3,8}$/i.test(value)) return value.toLowerCase();
150
+ const channels = value.match(/^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,/\s]+([\d.]+))?\s*\)$/);
151
+ if (!channels || channels[4] === "0") return undefined;
152
+ return `#${channels
153
+ .slice(1, 4)
154
+ .map((channel) => Number(channel).toString(16).padStart(2, "0"))
155
+ .join("")}`;
156
+ }
157
+
158
+ /** Markup that never shows as words: its text (CSS, scripts, Word's settings) must not land in the text. */
159
+ const HIDDEN_TAGS = "head, style, script, template, noscript, meta, link, title, xml, svg, img, picture, video, audio";
160
+ /** Wrappers that hold paragraphs of their own: their paragraphs are kept, the wrapper is not. */
161
+ const WRAPPER_TAGS = ["BODY", "MAIN", "ARTICLE", "SECTION", "HEADER", "FOOTER", "ASIDE", "NAV", "FORM", "CENTER"];
162
+ /** Tables and definition lists have no place in a text: each cell or entry becomes a paragraph of its own. */
163
+ const TABLE_TAGS = ["TABLE", "THEAD", "TBODY", "TFOOT", "TR", "DL", "FIGURE"];
164
+ const CELL_TAGS = ["TD", "TH", "CAPTION", "DT", "DD", "FIGCAPTION", "LI", "PRE", "ADDRESS"];
165
+ const BLOCK_SELECTOR = "p, h1, h2, h3, h4, h5, h6, blockquote, ul, ol, div, table, dl, li, pre";
166
+ /** As the server accepts links (`LINK_SCHEMES` in content/validate.ts); any other address would refuse the save. */
167
+ const LINK_SCHEMES = ["http:", "https:", "mailto:", "tel:"];
168
+
169
+ function allowedLink(href: string): boolean {
170
+ const value = href.trim();
171
+ if ((value.startsWith("/") && !value.startsWith("//")) || value.startsWith("#")) return true;
172
+ return URL.canParse(value) && LINK_SCHEMES.includes(new URL(value).protocol);
173
+ }
174
+
175
+ /** Puts an element's children in its place. */
176
+ function unwrap(element: HTMLElement): void {
177
+ element.replaceWith(...element.childNodes);
178
+ }
179
+
180
+ /** Gives an element another tag, keeping what it holds; its attributes are dropped. */
181
+ function retag(element: HTMLElement, tag: string): void {
182
+ const replacement = element.ownerDocument.createElement(tag);
183
+ replacement.append(...element.childNodes);
184
+ element.replaceWith(replacement);
185
+ }
186
+
187
+ /**
188
+ * Cleans pasted or dropped HTML so the reading above sees only what the editor itself makes. Colors are dropped:
189
+ * Word and other pages write their defaults inline (`color: windowtext`, `background: white`) in the same form as a
190
+ * color the toolbar sets, so a pasted color cannot be told from a chosen one.
191
+ */
192
+ function cleanForeign(body: HTMLElement): void {
193
+ for (const element of body.querySelectorAll<HTMLElement>(HIDDEN_TAGS)) element.remove();
194
+ // Word's list bullets and numbers are written as text in a span it marks to be ignored.
195
+ for (const element of body.querySelectorAll<HTMLElement>("[style]")) {
196
+ if (/mso-list:\s*ignore/i.test(element.getAttribute("style") ?? "")) element.remove();
197
+ }
198
+ const walker = body.ownerDocument.createTreeWalker(body, NodeFilter.SHOW_COMMENT);
199
+ const comments: Node[] = [];
200
+ while (walker.nextNode()) comments.push(walker.currentNode);
201
+ for (const comment of comments) comment.parentNode?.removeChild(comment);
202
+
203
+ for (const element of body.querySelectorAll<HTMLElement>("*")) {
204
+ element.removeAttribute("color");
205
+ element.style.removeProperty("color");
206
+ element.style.removeProperty("background");
207
+ element.style.removeProperty("background-color");
208
+ const href = element.getAttribute("href");
209
+ if (href !== null && !allowedLink(href)) element.removeAttribute("href");
210
+ }
211
+ // Lists stay lists; a list item outside one, a cell or an entry is a paragraph.
212
+ for (const element of [...body.querySelectorAll<HTMLElement>(CELL_TAGS.join(","))]) {
213
+ const inList = element.tagName === "LI" && /^(UL|OL)$/.test(element.parentElement?.tagName ?? "");
214
+ if (!inList) retag(element, "div");
215
+ }
216
+ for (const element of [...body.querySelectorAll<HTMLElement>(TABLE_TAGS.join(","))]) unwrap(element);
217
+ // Deepest first, so a wrapper inside a wrapper is gone before its parent is looked at.
218
+ for (const element of [...body.querySelectorAll<HTMLElement>(`${WRAPPER_TAGS.join(",")}, div`)].reverse()) {
219
+ if (WRAPPER_TAGS.includes(element.tagName) || element.querySelector(BLOCK_SELECTOR)) unwrap(element);
220
+ }
221
+ }
222
+
223
+ /** The words of blocks on one line, a space between blocks and in place of line breaks. */
224
+ function oneLine(text: string): string {
225
+ return text
226
+ .split(/\s*[\r\n\u2028\u2029]+\s*/)
227
+ .filter((line) => line.trim() !== "")
228
+ .join(" ")
229
+ .trim();
230
+ }
231
+
232
+ function blocksText(blocks: RichTextBlock[]): string {
233
+ const inlineText = (nodes: InlineNode[]): string =>
234
+ nodes
235
+ .map((node) =>
236
+ typeof node === "string"
237
+ ? node
238
+ : node.tag === "br"
239
+ ? "\n"
240
+ : "children" in node
241
+ ? inlineText(node.children)
242
+ : "",
243
+ )
244
+ .join("");
245
+ return blocks
246
+ .flatMap((block) => ("items" in block ? block.items.map(inlineText) : [inlineText(block.children)]))
247
+ .join("\n");
248
+ }
249
+
250
+ /** What a paste or a drop brings, read as the editor's own content; foreign markup never reaches the page. */
251
+ export type Transferred = { kind: "text"; text: string } | { kind: "html"; html: string } | { kind: "none" };
252
+
253
+ /**
254
+ * Reads pasted or dropped content for a text: its words alone, on one line, for a one-line text; formatting the
255
+ * editor knows (paragraphs, lists, bold, links…) for rich text. Files and images bring nothing: an image belongs in
256
+ * an image block, and its file name would only end up as words in the text.
257
+ */
258
+ export function readTransfer(data: DataTransfer | null, rich: boolean): Transferred {
259
+ if (!data) return { kind: "none" };
260
+ const html = data.getData("text/html");
261
+ const plain = data.getData("text/plain");
262
+ let blocks: RichTextBlock[] | undefined;
263
+ if (html.trim() !== "") {
264
+ const body = new DOMParser().parseFromString(html, "text/html").body;
265
+ cleanForeign(body);
266
+ blocks = readBlocks(body);
267
+ }
268
+ if (!rich) {
269
+ const text = oneLine(plain !== "" ? plain : blocks ? blocksText(blocks) : "");
270
+ return text === "" ? { kind: "none" } : { kind: "text", text };
271
+ }
272
+ if (!blocks) return plain.trim() === "" ? { kind: "none" } : { kind: "text", text: plain };
273
+ if (blocks.length === 0) return { kind: "none" };
274
+ const [first] = blocks;
275
+ // One paragraph joins the paragraph it is put in, instead of splitting it in two.
276
+ if (blocks.length === 1 && first && !("items" in first) && first.tag === "p") {
277
+ return { kind: "html", html: renderInline(first.children) };
278
+ }
279
+ return { kind: "html", html: renderBlocks(blocks) };
280
+ }
281
+
282
+ /** Puts what was read into the text being typed, where the caret is, as typing would (it can be undone). */
283
+ export function insertTransferred(page: Document, transferred: Transferred): void {
284
+ if (transferred.kind === "text") page.execCommand("insertText", false, transferred.text);
285
+ else if (transferred.kind === "html") page.execCommand("insertHTML", false, transferred.html);
286
+ }
287
+
288
+ /** Where a drop lands: the caret at that point of the page, as a range. */
289
+ function rangeAtPoint(page: Document, x: number, y: number): Range | null {
290
+ const position = page.caretPositionFromPoint?.(x, y);
291
+ if (position) {
292
+ const range = page.createRange();
293
+ range.setStart(position.offsetNode, position.offset);
294
+ return range;
295
+ }
296
+ // Safari before 18.4 only has the older WebKit call.
297
+ const legacy = page as Document & { caretRangeFromPoint?: (x: number, y: number) => Range | null };
298
+ return legacy.caretRangeFromPoint?.(x, y) ?? null;
299
+ }
300
+
301
+ /**
302
+ * Puts what was dropped into the text being typed, read as a paste is, where it was dropped. Words dragged from the
303
+ * same text (`from`, the selection when the drag started) move; from anywhere else they are copied. The browser's
304
+ * own drop is prevented by the caller: it would bring the markup in as it is, or open a dropped file.
305
+ */
306
+ export function dropTransferred(element: HTMLElement, event: DragEvent, from: Range | null, rich: boolean): void {
307
+ const page = element.ownerDocument;
308
+ const target = event.target as Node | null;
309
+ if (!target || !element.contains(target)) return;
310
+ const transferred = readTransfer(event.dataTransfer, rich);
311
+ const at = rangeAtPoint(page, event.clientX, event.clientY);
312
+ if (transferred.kind === "none" || !at || !element.contains(at.startContainer)) return;
313
+ const selection = page.getSelection();
314
+ if (!selection) return;
315
+ if (from && !from.collapsed && element.contains(from.commonAncestorContainer)) {
316
+ // Dropped onto the words being dragged: nothing moves.
317
+ if (from.isPointInRange(at.startContainer, at.startOffset)) return;
318
+ // The words leave their place first; the drop point follows the text around it as it changes.
319
+ selection.removeAllRanges();
320
+ selection.addRange(from);
321
+ page.execCommand("delete");
322
+ }
323
+ selection.removeAllRanges();
324
+ selection.addRange(at);
325
+ insertTransferred(page, transferred);
326
+ }
@@ -0,0 +1,239 @@
1
+ import { itemPathSegments } from "../../content/item-path.ts";
2
+ import { type LocaleConfig, itemPagePath } from "../../server/locales.ts";
3
+ import type { ContentType, Item, SitePage } from "./api.ts";
4
+
5
+ /**
6
+ * The site map as one tree, by address: a content type's items hang under the page their address starts with
7
+ * (`/produse/[category]/[slug]` under `/produse`), split by the field that comes first in the address, so products
8
+ * sit under their category. Types without pages, and the vocabularies, are kept apart for the site map to list
9
+ * after the pages.
10
+ */
11
+
12
+ /** One item, with the address of its page. */
13
+ export interface TreeItem {
14
+ item: Item;
15
+ path: string;
16
+ }
17
+
18
+ /** How many items a branch or group lists before "Show all"; a group with more is split again when it can be. */
19
+ export const ITEMS_SHOWN = 10;
20
+
21
+ /** A field items are split by, with the type of its values when it is a reference. */
22
+ export interface GroupField {
23
+ name: string;
24
+ label: string;
25
+ to?: string;
26
+ }
27
+
28
+ /** The items sharing a value of the field the address is split by, e.g. the products of one category. */
29
+ export interface TreeGroup {
30
+ /** Unique in the tree: the type, then the values of the group and of the groups it is in. */
31
+ key: string;
32
+ value: string;
33
+ label: string;
34
+ /** The address the group's items share, e.g. `/produse/ceramica`. */
35
+ path: string;
36
+ /** The page of the group's term, when its vocabulary gives its terms pages (often the same address as `path`). */
37
+ page?: string;
38
+ /** The term itself, when the group is one of a vocabulary's. */
39
+ term?: Item;
40
+ /** What a new item added in the group starts with: the values of this group and of the groups it is in. */
41
+ data: Record<string, string>;
42
+ /**
43
+ * A group with more items than are listed is split again, by the first other vocabulary of the type most of its
44
+ * items use (the ceramics by their style); `groups` are those, `rest` the items that use none.
45
+ */
46
+ subgroupBy?: GroupField;
47
+ groups: TreeGroup[];
48
+ rest: TreeItem[];
49
+ /** Every item of the group, subgroups included. */
50
+ items: TreeItem[];
51
+ }
52
+
53
+ /** A content type whose items have pages, placed in the tree. */
54
+ export interface TreeBranch {
55
+ type: ContentType;
56
+ /**
57
+ * The page the items hang under: one of the site's pages or the page of a group's term (the catalogs of the
58
+ * ceramics under Ceramică), or `null` when no page starts their address.
59
+ */
60
+ parent: string | null;
61
+ /** The address the items share before their own part, e.g. `/produse`. */
62
+ prefix: string;
63
+ /** The field the address is split by after the prefix, with the type of its values when it is a reference. */
64
+ groupBy?: GroupField;
65
+ /** The groups, in the owner's order when the field's vocabulary is ordered, else by title; empty when not split. */
66
+ groups: TreeGroup[];
67
+ /** Every item, in the owner's order when the type is ordered, else by title. */
68
+ items: TreeItem[];
69
+ }
70
+
71
+ export interface SiteTree {
72
+ branches: TreeBranch[];
73
+ /**
74
+ * Types whose items have no page, vocabularies among them. A vocabulary whose terms have pages is a branch of its
75
+ * own, unless the terms are already groups of a type's branch, where their pages open from.
76
+ */
77
+ unplaced: ContentType[];
78
+ }
79
+
80
+ const compare = (a: string, b: string) => a.localeCompare(b, undefined, { sensitivity: "base", numeric: true });
81
+
82
+ const trim = (path: string) => (path.length > 1 ? path.replace(/\/+$/, "") : path);
83
+
84
+ /** The items of an ordered type come from the API in the owner's order; the others are put in order of title. */
85
+ const ordered = <T>(list: T[], keep: boolean | undefined, title: (entry: T) => string): T[] =>
86
+ keep ? list : [...list].sort((a, b) => compare(title(a), title(b)));
87
+
88
+ type Field = ContentType["fields"][number];
89
+
90
+ export function buildSiteTree(
91
+ pages: SitePage[],
92
+ types: ContentType[],
93
+ itemsByType: Record<string, Item[]>,
94
+ locales: LocaleConfig | undefined,
95
+ ): SiteTree {
96
+ const pagePaths = new Set(pages.map((page) => trim(page.path)));
97
+ const branches: TreeBranch[] = [];
98
+ const unplaced: ContentType[] = [];
99
+ const typeOf = (key: string | undefined) => (key ? types.find((candidate) => candidate.key === key) : undefined);
100
+ const termsOf = (key: string | undefined) => (itemsByType[key ?? ""] ?? []).filter((term) => term.locale === "");
101
+
102
+ const groupField = (type: ContentType) => {
103
+ const segments = itemPathSegments(type);
104
+ const fixed = segments.findIndex((segment) => "field" in segment);
105
+ const leading = fixed === -1 ? segments.length : fixed;
106
+ const next = segments[leading];
107
+ const field =
108
+ next && "field" in next && next.field !== "slug"
109
+ ? type.fields.find((candidate) => candidate.name === next.field)
110
+ : undefined;
111
+ return { segments, leading, field };
112
+ };
113
+ const placed = types.filter((type) => type.hasPage);
114
+ const grouping = new Set(placed.flatMap((type) => (groupField(type).field?.to ? [groupField(type).field!.to!] : [])));
115
+ /** The pages of the terms that group a type's items: other types whose address starts with one hang under it. */
116
+ const termPages = new Set(
117
+ [...grouping].flatMap((key) => {
118
+ const vocabulary = typeOf(key);
119
+ return vocabulary?.hasPage ? termsOf(key).map((term) => trim(itemPagePath(vocabulary, term, locales))) : [];
120
+ }),
121
+ );
122
+ /** The terms each vocabulary has as subgroups somewhere, to tell whether it still needs a branch of its own. */
123
+ const subgrouped = new Map<string, Set<string>>();
124
+
125
+ /** The groups `entries` make by the values of `field`: every term or option first, then values nothing declares. */
126
+ function groupsBy(
127
+ type: ContentType,
128
+ field: Field,
129
+ entries: TreeItem[],
130
+ within: { key: string; path: string; data: Record<string, string> },
131
+ split: boolean,
132
+ ): TreeGroup[] {
133
+ const vocabulary = typeOf(field.to);
134
+ const declared = new Map<string, { label: string; term?: Item }>();
135
+ for (const term of field.to ? termsOf(field.to) : []) declared.set(term.slug, { label: term.title, term });
136
+ for (const option of field.options ?? []) {
137
+ if (typeof option === "string") declared.set(option, { label: option });
138
+ else declared.set(option.value, { label: option.label });
139
+ }
140
+ const byValue = new Map<string, TreeItem[]>();
141
+ for (const entry of entries) {
142
+ const value = String(entry.item.data[field.name] ?? "");
143
+ byValue.set(value, [...(byValue.get(value) ?? []), entry]);
144
+ }
145
+ const make = (value: string, label: string, term?: Item): TreeGroup => {
146
+ const items = byValue.get(value) ?? [];
147
+ const data = { ...within.data, ...(value && { [field.name]: value }) };
148
+ const group: TreeGroup = {
149
+ key: `${within.key}/${value}`,
150
+ value,
151
+ label,
152
+ path: split ? within.path : `${within.path}/${value || "-"}`,
153
+ ...(term && { term }),
154
+ ...(term && vocabulary?.hasPage && { page: itemPagePath(vocabulary, term, locales) }),
155
+ data,
156
+ groups: [],
157
+ rest: items,
158
+ items,
159
+ };
160
+ if (!split) subgroup(type, field, group);
161
+ return group;
162
+ };
163
+ // At the first level every term shows, even one no item uses yet, so an item can be added to it; a split
164
+ // shows the terms its items use.
165
+ const known = [...declared].filter(([value]) => !split || byValue.has(value));
166
+ const terms = known.map(([value, { label, term }]) => make(value, label, term));
167
+ // Options keep the order they are declared in; terms the vocabulary's order, or that of their titles.
168
+ const sorted = field.options || vocabulary?.ordered ? terms : ordered(terms, false, (group) => group.label);
169
+ const unknown = [...byValue.keys()]
170
+ .filter((value) => !declared.has(value) && (!split || value !== ""))
171
+ .map((value) => make(value, value || "—"));
172
+ if (split && field.to) {
173
+ const seen = subgrouped.get(field.to) ?? new Set<string>();
174
+ for (const group of terms) seen.add(group.value);
175
+ subgrouped.set(field.to, seen);
176
+ }
177
+ return [...sorted, ...unknown];
178
+ }
179
+
180
+ /** Splits a group too long to list by the first other vocabulary most of its items use. */
181
+ function subgroup(type: ContentType, groupedBy: Field, group: TreeGroup): void {
182
+ if (group.items.length <= ITEMS_SHOWN) return;
183
+ const field = type.fields.find(
184
+ (candidate) =>
185
+ candidate.name !== groupedBy.name &&
186
+ candidate.to &&
187
+ !candidate.multiple &&
188
+ typeOf(candidate.to)?.vocabulary &&
189
+ group.items.filter((entry) => String(entry.item.data[candidate.name] ?? "") !== "").length * 2 >=
190
+ group.items.length,
191
+ );
192
+ if (!field) return;
193
+ group.subgroupBy = { name: field.name, label: field.label, ...(field.to && { to: field.to }) };
194
+ group.groups = groupsBy(type, field, group.items, group, true);
195
+ group.rest = group.items.filter((entry) => String(entry.item.data[field.name] ?? "") === "");
196
+ }
197
+
198
+ for (const type of types) {
199
+ if (!type.hasPage) {
200
+ unplaced.push(type);
201
+ continue;
202
+ }
203
+ if (type.vocabulary && grouping.has(type.key)) continue;
204
+ const { segments, leading, field } = groupField(type);
205
+ // The address of an item with no values tells how many segments the language adds in front.
206
+ const sample = itemPagePath(type, { slug: "x", locale: "", data: {} }, locales).split("/").slice(1);
207
+ const offset = sample.length - segments.length;
208
+ const prefix = `/${sample.slice(0, offset + leading).join("/")}`;
209
+
210
+ let parent: string | null = null;
211
+ // Not under the home page: a type with no page of its own sits at the top of the tree instead.
212
+ for (let cut = offset + leading; cut > offset; cut--) {
213
+ const candidate = trim(`/${sample.slice(0, cut).join("/")}`);
214
+ if (pagePaths.has(candidate) || termPages.has(candidate)) {
215
+ parent = candidate;
216
+ break;
217
+ }
218
+ }
219
+
220
+ const groupBy = field && { name: field.name, label: field.label, ...(field.to && { to: field.to }) };
221
+
222
+ const items = ordered(
223
+ termsOf(type.key).map((item) => ({ item, path: itemPagePath(type, item, locales) })),
224
+ type.ordered,
225
+ (entry) => entry.item.title,
226
+ );
227
+
228
+ const groups = field ? groupsBy(type, field, items, { key: type.key, path: prefix, data: {} }, false) : [];
229
+
230
+ branches.push({ type, parent, prefix, ...(groupBy && { groupBy }), groups, items });
231
+ }
232
+
233
+ // A vocabulary whose terms are all subgroups somewhere opens from there, like one that groups the addresses.
234
+ const shown = branches.filter((branch) => {
235
+ const used = subgrouped.get(branch.type.key);
236
+ return !(branch.type.vocabulary && used && branch.items.every((entry) => used.has(entry.item.slug)));
237
+ });
238
+ return { branches: shown, unplaced };
239
+ }
@@ -0,0 +1,55 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ /**
4
+ * The editor's appearance: the system's light or dark one, or one the user picked in the ⋯ menu, which this browser
5
+ * remembers. Only the editor's own frame changes: the page being edited keeps the site's look.
6
+ */
7
+ export type Theme = "system" | "light" | "dark";
8
+
9
+ const KEY = "brim-editor-theme";
10
+ const darkScheme = matchMedia("(prefers-color-scheme: dark)");
11
+ const listeners = new Set<(theme: Theme) => void>();
12
+
13
+ function stored(): Theme {
14
+ try {
15
+ const value = localStorage.getItem(KEY);
16
+ return value === "light" || value === "dark" ? value : "system";
17
+ } catch {
18
+ return "system";
19
+ }
20
+ }
21
+
22
+ let current: Theme = stored();
23
+
24
+ function apply(): void {
25
+ const dark = current === "dark" || (current === "system" && darkScheme.matches);
26
+ document.documentElement.classList.toggle("dark", dark);
27
+ document.documentElement.style.colorScheme = dark ? "dark" : "light";
28
+ }
29
+
30
+ /** Draws the editor in the remembered appearance, and follows the system while it is the choice. */
31
+ export function startTheme(): void {
32
+ apply();
33
+ darkScheme.addEventListener("change", apply);
34
+ }
35
+
36
+ export function setTheme(theme: Theme): void {
37
+ current = theme;
38
+ try {
39
+ if (theme === "system") localStorage.removeItem(KEY);
40
+ else localStorage.setItem(KEY, theme);
41
+ } catch {
42
+ // Without storage the choice lasts until the editor is reloaded.
43
+ }
44
+ apply();
45
+ for (const listener of listeners) listener(theme);
46
+ }
47
+
48
+ export function useTheme(): [Theme, (theme: Theme) => void] {
49
+ const [theme, setState] = useState(current);
50
+ useEffect(() => {
51
+ listeners.add(setState);
52
+ return () => void listeners.delete(setState);
53
+ }, []);
54
+ return [theme, setTheme];
55
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": true,
9
+ "exactOptionalPropertyTypes": true,
10
+ "verbatimModuleSyntax": true,
11
+ "allowImportingTsExtensions": true,
12
+ "noEmit": true,
13
+ "skipLibCheck": true,
14
+ "types": [],
15
+ "jsx": "react-jsx"
16
+ },
17
+ "include": ["."]
18
+ }