@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.
- package/LICENSE +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
|
@@ -0,0 +1,1756 @@
|
|
|
1
|
+
import { type CSSProperties, useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { ChangePassword } from "./Login.tsx";
|
|
3
|
+
import { type BlockLayout, layoutOf } from "../../content/block-layout.ts";
|
|
4
|
+
import { blocksOf } from "../../content/block-values.ts";
|
|
5
|
+
import { BLOCK_TYPES, type BlockEntry } from "../../content/content-types.ts";
|
|
6
|
+
import {
|
|
7
|
+
type ContentType,
|
|
8
|
+
type DraftChange,
|
|
9
|
+
type Item,
|
|
10
|
+
type ItemDraft,
|
|
11
|
+
type NewPage,
|
|
12
|
+
type NodeRef,
|
|
13
|
+
type PageTemplateInfo,
|
|
14
|
+
type SeoSettings,
|
|
15
|
+
type SiteLocales,
|
|
16
|
+
type SitePage,
|
|
17
|
+
type User,
|
|
18
|
+
type Visibility,
|
|
19
|
+
api,
|
|
20
|
+
loadSiteInfo,
|
|
21
|
+
} from "./api.ts";
|
|
22
|
+
import { type Binding, Chrome, type Lock, nodeLabel, type StackActions } from "./Chrome.tsx";
|
|
23
|
+
import { EditorProvider } from "./context.ts";
|
|
24
|
+
import { Inspector } from "./Inspector.tsx";
|
|
25
|
+
import { ListingPanel } from "./ListingPanel.tsx";
|
|
26
|
+
import { FrameHandles, SidebarHandle, storedSidebarWidth } from "./Resize.tsx";
|
|
27
|
+
import { ItemField } from "./ItemForm.tsx";
|
|
28
|
+
import { type FormValue, nodeKinds } from "./kinds.ts";
|
|
29
|
+
import { ContentBrowser } from "./ContentBrowser.tsx";
|
|
30
|
+
import { type MediaFolder, MediaFolderContext } from "./widgets.tsx";
|
|
31
|
+
import { SiteMap } from "./SiteMap.tsx";
|
|
32
|
+
import { type OwnSeo, PageSettings } from "./PageSettings.tsx";
|
|
33
|
+
import { Sidebar } from "./Sidebar.tsx";
|
|
34
|
+
import { HistoryPanel } from "./HistoryPanel.tsx";
|
|
35
|
+
import { SiteSettings } from "./SiteSettings.tsx";
|
|
36
|
+
import { isComposing } from "./keys.ts";
|
|
37
|
+
import {
|
|
38
|
+
alignOf,
|
|
39
|
+
hasFormatting,
|
|
40
|
+
dropTransferred,
|
|
41
|
+
insertTransferred,
|
|
42
|
+
readBlocks,
|
|
43
|
+
readInlineText,
|
|
44
|
+
readText,
|
|
45
|
+
readTransfer,
|
|
46
|
+
} from "./rich-text.ts";
|
|
47
|
+
import { type DraftControls, type LanguageChoice, type SaveStatus, Toolbar, type Viewport } from "./Toolbar.tsx";
|
|
48
|
+
import { normalizePagePath } from "../../content/ids.ts";
|
|
49
|
+
import { itemPagePath, readItemPath } from "../../server/locales.ts";
|
|
50
|
+
import { itemLocale, localeOfPath, pathInLocale, translationsOf, useSiteLocales } from "./languages.ts";
|
|
51
|
+
|
|
52
|
+
const EDIT_PATH = "/admin/edit";
|
|
53
|
+
/** The content browser's folder of form responses. */
|
|
54
|
+
const RESPONSES_FOLDER = "form-responses";
|
|
55
|
+
const NODE_SELECTOR = "[data-brim-node]";
|
|
56
|
+
const STACK_SELECTOR = '[data-brim-kind="blocks"]';
|
|
57
|
+
/** Empty text, which would otherwise have no height to click on. Blocks such as a divider are empty on purpose. */
|
|
58
|
+
const TEXT_SELECTOR = ':is([data-brim-kind="text"], [data-brim-kind="richtext"]):empty';
|
|
59
|
+
/** An element showing an item's picked value (a date, a choice…); empty, it still needs a place to click. */
|
|
60
|
+
const FIELD_SELECTOR = '[data-brim-kind="field"]';
|
|
61
|
+
const PAGE_STYLE = `
|
|
62
|
+
${NODE_SELECTOR} { cursor: pointer; }
|
|
63
|
+
[data-brim-setting] { cursor: pointer; }
|
|
64
|
+
[data-brim-setting]:hover { outline: 1px dashed var(--brim-editor-selection, #6b6bff); outline-offset: 2px; }
|
|
65
|
+
${NODE_SELECTOR}[contenteditable] { cursor: text; outline: none; }
|
|
66
|
+
/* An empty element still has a place to click: to write in it, or to add the first block. */
|
|
67
|
+
${TEXT_SELECTOR}, ${STACK_SELECTOR}:not(:has(${NODE_SELECTOR})) { min-height: 1.5em; }
|
|
68
|
+
${TEXT_SELECTOR}::before { content: "Empty: click to write"; opacity: 0.45; }
|
|
69
|
+
${STACK_SELECTOR}:not(:has(${NODE_SELECTOR}))::before { content: "No blocks yet: add one with +"; opacity: 0.45; }
|
|
70
|
+
${FIELD_SELECTOR}:empty { display: inline-block; min-width: 4em; min-height: 1.5em; }
|
|
71
|
+
${FIELD_SELECTOR}:empty::before { content: attr(data-brim-label) ": empty"; opacity: 0.45; }
|
|
72
|
+
/* The hovered and the selected element, outlined on the page so the outline scrolls with it (see Chrome). */
|
|
73
|
+
/* Drawn just outside the box, so it never covers text or images that reach the element's edge. */
|
|
74
|
+
[data-brim-outline="hover"] { outline: 1px solid var(--brim-editor-selection, #1d4ed8) !important; outline-offset: 2px !important; }
|
|
75
|
+
[data-brim-outline="selected"] { outline: 2px solid var(--brim-editor-selection, #1d4ed8) !important; outline-offset: 2px !important; }
|
|
76
|
+
/* A phone or tablet preview shows no scrollbar, as on the device: it would take 15px of the width the page is
|
|
77
|
+
laid out for, and show as a white bar beside it. The page still scrolls. */
|
|
78
|
+
html[data-brim-viewport="mobile"], html[data-brim-viewport="tablet"] { scrollbar-width: none; }
|
|
79
|
+
/* Astro's own dev toolbar would sit on top of the page being edited. */
|
|
80
|
+
astro-dev-toolbar { display: none !important; }
|
|
81
|
+
`;
|
|
82
|
+
|
|
83
|
+
/** The page being edited is the part of the address after /admin/edit. */
|
|
84
|
+
function pagePathFromAddress(): string {
|
|
85
|
+
const path = location.pathname.startsWith(EDIT_PATH) ? location.pathname.slice(EDIT_PATH.length) : "";
|
|
86
|
+
return path === "" ? "/" : path;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Elements of the page belong to the frame's own realm, so `instanceof Element`
|
|
91
|
+
* from this document is always false for them; the node type is checked instead.
|
|
92
|
+
*/
|
|
93
|
+
function isElement(node: EventTarget | Node | null | undefined): node is HTMLElement {
|
|
94
|
+
return (node as Node | null | undefined)?.nodeType === 1;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function nodeOf(target: EventTarget | null): HTMLElement | null {
|
|
98
|
+
return isElement(target) ? target.closest<HTMLElement>(NODE_SELECTOR) : null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function parentNodeOf(element: HTMLElement): HTMLElement | null {
|
|
102
|
+
return element.parentElement?.closest<HTMLElement>(NODE_SELECTOR) ?? null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Text and rich text are typed directly on the page; everything else is edited in the inspector. */
|
|
106
|
+
function isEditedInPlace(element: HTMLElement): boolean {
|
|
107
|
+
return element.dataset.brimKind === "text" || element.dataset.brimKind === "richtext";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** An element showing one of an item's fields: its content belongs to the item, how it looks to the template. */
|
|
111
|
+
function isField(element: HTMLElement): boolean {
|
|
112
|
+
return element.dataset.brimItem !== undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One block of an item's `blocks` field: the item's content, kept in the field under this id. */
|
|
116
|
+
function isEntry(element: HTMLElement): boolean {
|
|
117
|
+
return element.dataset.brimEntry !== undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** An element showing an item's picked value: set in the side panel with the field's widget, never typed in place. */
|
|
121
|
+
function isPickedField(element: HTMLElement): boolean {
|
|
122
|
+
return element.dataset.brimKind === "field";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A stack of blocks has nothing to set itself; the + under it adds blocks to it. */
|
|
126
|
+
function isStack(element: HTMLElement): boolean {
|
|
127
|
+
return element.dataset.brimKind === "blocks";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* What an item's field takes from the element that shows it: an image's address and description, a gallery's or a
|
|
132
|
+
* carousel's images. The rest of the element's settings are how the template shows it.
|
|
133
|
+
*/
|
|
134
|
+
const IMAGE_CONTENT = ["url", "alt", "images"];
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* What the owner still changes on a gallery or carousel the site draws itself: the images and how they move. Its
|
|
138
|
+
* columns, arrows and dots are the site's markup, so they are not offered.
|
|
139
|
+
*/
|
|
140
|
+
const DRAWN_SETTINGS = ["images", "lightbox", "start", "autoplay", "autoplaySpeed", "pauseOnHover", "loop", "continuousSpeed"];
|
|
141
|
+
|
|
142
|
+
/** The image block's settings without its image, which belongs to the item. */
|
|
143
|
+
function withoutImageContent(form: FormValue): FormValue {
|
|
144
|
+
return Object.fromEntries(Object.entries(form).filter(([name]) => !IMAGE_CONTENT.includes(name)));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The loaded page is the page of an item, drawn by its type's template, which the `count` items in its language
|
|
149
|
+
* share; `translations` is the item in every language it is written in, itself included.
|
|
150
|
+
*/
|
|
151
|
+
interface ItemPage {
|
|
152
|
+
type: ContentType;
|
|
153
|
+
item: Item;
|
|
154
|
+
count: number;
|
|
155
|
+
translations: Item[];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* `/projects/lake-house` (or `/ro/projects/casa-de-la-lac`, or an address from the type's `path`) is the page of an
|
|
160
|
+
* item when its type has a template. A translation keeps its original's slug, so the item is looked up in the page's language.
|
|
161
|
+
*/
|
|
162
|
+
async function findItemPage(types: ContentType[], path: string, locales: SiteLocales | null): Promise<ItemPage | null> {
|
|
163
|
+
const address = readItemPath(
|
|
164
|
+
types.filter((candidate) => candidate.hasPage),
|
|
165
|
+
path,
|
|
166
|
+
locales ?? undefined,
|
|
167
|
+
);
|
|
168
|
+
if (!address) return null;
|
|
169
|
+
const { type } = address;
|
|
170
|
+
const { items } = await api.items(type.key);
|
|
171
|
+
const item = items.find((candidate) => candidate.slug === address.slug && candidate.locale === address.locale);
|
|
172
|
+
// The page redirects to the item's own address when its other parts (a category) do not agree.
|
|
173
|
+
if (!item || itemPagePath(type, item, locales ?? undefined) !== normalizePagePath(path)) return null;
|
|
174
|
+
const count = items.filter((candidate) => candidate.locale === address.locale).length;
|
|
175
|
+
return { type, item, count, translations: translationsOf(item, items) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const THEME_COLOR_NAMES = ["background", "light1", "light2", "accent", "primary", "dark1", "dark2"];
|
|
179
|
+
|
|
180
|
+
/** Color swatches in the sidebar show the site's own theme colors, read from the page being edited. */
|
|
181
|
+
function adoptThemeColors(view: Window): void {
|
|
182
|
+
const siteStyle = view.getComputedStyle(view.document.documentElement);
|
|
183
|
+
for (const name of THEME_COLOR_NAMES) {
|
|
184
|
+
const value = siteStyle.getPropertyValue(`--brim-theme-${name}`).trim();
|
|
185
|
+
if (value) document.documentElement.style.setProperty(`--brim-theme-${name}`, value);
|
|
186
|
+
else document.documentElement.style.removeProperty(`--brim-theme-${name}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Where the content browser opens: all content, or one content type, optionally on its new item form. */
|
|
191
|
+
interface BrowseTarget {
|
|
192
|
+
folder: string | null;
|
|
193
|
+
create: boolean;
|
|
194
|
+
/** What the new item starts with, e.g. the field a listing filters on. */
|
|
195
|
+
data?: Record<string, unknown>;
|
|
196
|
+
/** In Form responses, the form whose responses open first. */
|
|
197
|
+
form?: string;
|
|
198
|
+
/** A response to open straight away, e.g. from the email about it (`?response=<id>`). */
|
|
199
|
+
response?: string;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Reads what `<Seo>` left in the head for the editor; `null` when the page's layout has no `<Seo>`. */
|
|
203
|
+
function readPageSeo(page: Document, path: string): { path: string; seo: SeoSettings; own: OwnSeo } | null {
|
|
204
|
+
const content = page.querySelector('meta[name="brim-seo"]')?.getAttribute("content");
|
|
205
|
+
if (!content) return null;
|
|
206
|
+
try {
|
|
207
|
+
const { seo, own } = JSON.parse(content) as { seo?: SeoSettings; own?: OwnSeo };
|
|
208
|
+
return { path, seo: seo ?? {}, own: own ?? {} };
|
|
209
|
+
} catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** What the owner chose for a text besides its words. An empty alignment means the page's own. */
|
|
215
|
+
interface TextChoice {
|
|
216
|
+
as?: string;
|
|
217
|
+
align?: string;
|
|
218
|
+
options?: FormValue;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
interface TextEdit {
|
|
222
|
+
element: HTMLElement;
|
|
223
|
+
originalHtml: string;
|
|
224
|
+
originalAlign: string;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** One step of undo: the drafts it changed, each with how it was before and after. */
|
|
228
|
+
interface UndoStep {
|
|
229
|
+
changes: DraftChange[];
|
|
230
|
+
/** When it was last added to: quick changes of the same thing (typing in a field) are one step. */
|
|
231
|
+
at: number;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Changes of the same thing this close together are undone as one. */
|
|
235
|
+
const SAME_STEP_MS = 1500;
|
|
236
|
+
|
|
237
|
+
function isDrafted(value: unknown): value is { change: DraftChange; drafts: number } {
|
|
238
|
+
return typeof value === "object" && value !== null && "change" in value && "drafts" in value;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** What each field held when it was focused: one not changed since has no typing of its own to undo. */
|
|
242
|
+
const valueOnFocus = new WeakMap<EventTarget, string>();
|
|
243
|
+
|
|
244
|
+
/** Where Cmd+Z belongs to the browser: a field with typing of its own to undo. */
|
|
245
|
+
function typesItself(target: EventTarget | null): boolean {
|
|
246
|
+
const element = target as HTMLElement | null;
|
|
247
|
+
if (!element || element.nodeType !== 1) return false;
|
|
248
|
+
if (element.isContentEditable) return true;
|
|
249
|
+
if (element.tagName !== "INPUT" && element.tagName !== "TEXTAREA") return false;
|
|
250
|
+
return (element as HTMLInputElement).value !== valueOnFocus.get(element);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
type Shortcut = "undo" | "redo" | "save";
|
|
254
|
+
|
|
255
|
+
/** The key that moves the keyboard between the page and the side panel, as F6 moves between a browser's panes. */
|
|
256
|
+
const PANEL_KEY = "F6";
|
|
257
|
+
|
|
258
|
+
/** Cmd/Ctrl+Z undoes, Shift+Cmd+Z or Ctrl+Y redoes, Cmd/Ctrl+S saves. */
|
|
259
|
+
function shortcutOf(event: KeyboardEvent): Shortcut | undefined {
|
|
260
|
+
if (!(event.metaKey || event.ctrlKey) || event.altKey) return undefined;
|
|
261
|
+
const key = event.key.toLowerCase();
|
|
262
|
+
if (key === "z") return event.shiftKey ? "redo" : "undo";
|
|
263
|
+
if (key === "y" && !event.shiftKey) return "redo";
|
|
264
|
+
if (key === "s" && !event.shiftKey) return "save";
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function Editor({ user, onSignedOut }: { user: User; onSignedOut: () => void }) {
|
|
269
|
+
/** The frame showing the page. A second one draws the page again out of sight, then takes its place. */
|
|
270
|
+
const frame = useRef<HTMLIFrameElement | null>(null);
|
|
271
|
+
const slots = useRef<(HTMLIFrameElement | null)[]>([null, null]);
|
|
272
|
+
const [shown, setShown] = useState(0);
|
|
273
|
+
/** The frame drawing the page out of sight, and where to scroll it before it is shown. */
|
|
274
|
+
const incoming = useRef<{ slot: number; x: number; y: number } | null>(null);
|
|
275
|
+
/** Counts the pages asked of the frames: a page asked for before the latest one is never shown. */
|
|
276
|
+
const requests = useRef(0);
|
|
277
|
+
/** Set while the frame in view opens another page: drawing the old page again would bring it back. */
|
|
278
|
+
const opening = useRef(false);
|
|
279
|
+
const [initialPath] = useState(pagePathFromAddress);
|
|
280
|
+
const [path, setPath] = useState(initialPath);
|
|
281
|
+
const locales = useSiteLocales();
|
|
282
|
+
const [pages, setPages] = useState<SitePage[]>([]);
|
|
283
|
+
const [templates, setTemplates] = useState<PageTemplateInfo[]>([]);
|
|
284
|
+
const [viewport, setViewport] = useState<Viewport>("desktop");
|
|
285
|
+
/** The page preview's width dragged by its handles; `null` is the device's own. Settings still follow `viewport`. */
|
|
286
|
+
const [frameWidth, setFrameWidth] = useState<number | null>(null);
|
|
287
|
+
const [frameDragging, setFrameDragging] = useState(false);
|
|
288
|
+
/** The side panel's width dragged by its edge, kept in this browser; `null` is the editor's own. */
|
|
289
|
+
const [sidebarWidth, setSidebarWidth] = useState<number | null>(storedSidebarWidth);
|
|
290
|
+
const [workspaceElement, setWorkspaceElement] = useState<HTMLDivElement | null>(null);
|
|
291
|
+
const [canvasElement, setCanvasElement] = useState<HTMLElement | null>(null);
|
|
292
|
+
const [frameElement, setFrameElement] = useState<HTMLDivElement | null>(null);
|
|
293
|
+
// Read by attachToPage, which runs once per load; the effect keeps the pages already loaded current.
|
|
294
|
+
const viewportRef = useRef(viewport);
|
|
295
|
+
viewportRef.current = viewport;
|
|
296
|
+
useEffect(() => {
|
|
297
|
+
for (const slot of slots.current) {
|
|
298
|
+
const root = slot?.contentDocument?.documentElement;
|
|
299
|
+
if (root) root.dataset.brimViewport = viewport;
|
|
300
|
+
}
|
|
301
|
+
}, [viewport]);
|
|
302
|
+
const [status, setStatus] = useState<SaveStatus>({ state: "idle" });
|
|
303
|
+
/** How many changes on the whole site nobody has saved yet: visitors do not see them. */
|
|
304
|
+
const [draftCount, setDraftCount] = useState(0);
|
|
305
|
+
const [savingDrafts, setSavingDrafts] = useState(false);
|
|
306
|
+
/** The changes made in this window, to undo and redo; both empty once the drafts are saved or discarded. */
|
|
307
|
+
const undoSteps = useRef<UndoStep[]>([]);
|
|
308
|
+
const redoSteps = useRef<UndoStep[]>([]);
|
|
309
|
+
const [, setStepsChanged] = useState(0);
|
|
310
|
+
/** Set while an undo or redo runs, so another waits its turn. */
|
|
311
|
+
const replaying = useRef(false);
|
|
312
|
+
/** Changed by undo and redo, so the panels read their element or page again. */
|
|
313
|
+
const [revision, setRevision] = useState(0);
|
|
314
|
+
/** Set by undo, redo and discard: the panels are read again once the page drawn again is in place. */
|
|
315
|
+
const reread = useRef(false);
|
|
316
|
+
const [hovered, setHovered] = useState<HTMLElement | null>(null);
|
|
317
|
+
const [selected, setSelected] = useState<HTMLElement | null>(null);
|
|
318
|
+
// The step of a form that the sidebar has open: shown on the page, and again each time the page is drawn anew.
|
|
319
|
+
const formStep = useRef<{ node: string; step: number } | null>(null);
|
|
320
|
+
useEffect(() => {
|
|
321
|
+
const showStep = (element: HTMLElement | null) => {
|
|
322
|
+
const step = formStep.current;
|
|
323
|
+
if (!step || !element || element.dataset.brimKind !== "form" || step.node !== element.dataset.brimNode) return;
|
|
324
|
+
void element.ownerDocument.defaultView?.customElements
|
|
325
|
+
.whenDefined("brim-form")
|
|
326
|
+
.then(() => element.dispatchEvent(new CustomEvent("brim:show-step", { detail: step.step })));
|
|
327
|
+
};
|
|
328
|
+
const listener = (event: Event) => {
|
|
329
|
+
if (!selected) return;
|
|
330
|
+
formStep.current = { node: selected.dataset.brimNode ?? "", step: Number((event as CustomEvent).detail) };
|
|
331
|
+
showStep(selected);
|
|
332
|
+
};
|
|
333
|
+
window.addEventListener("brim-editor:form-step", listener);
|
|
334
|
+
showStep(selected);
|
|
335
|
+
return () => window.removeEventListener("brim-editor:form-step", listener);
|
|
336
|
+
}, [selected]);
|
|
337
|
+
const [textEdit, setTextEditState] = useState<TextEdit | null>(null);
|
|
338
|
+
/** The text being typed, read at once: two changes in a row must not both save it, or one miss it. */
|
|
339
|
+
const textEditRef = useRef<TextEdit | null>(null);
|
|
340
|
+
/** Whether something was typed in the text being edited, for the Save button. */
|
|
341
|
+
const [typed, setTyped] = useState(false);
|
|
342
|
+
/** The saves still on their way: Save waits for them, so the drafts it saves have every change in them. */
|
|
343
|
+
const writes = useRef(new Set<Promise<unknown>>());
|
|
344
|
+
/** Set while Save runs, read at once so a second Cmd+S does not start another. */
|
|
345
|
+
const savingNow = useRef(false);
|
|
346
|
+
/** What is being typed on the page into one of the item's fields, shown in the page settings before it is saved. */
|
|
347
|
+
const [liveField, setLiveField] = useState<{ field: string; value: unknown } | null>(null);
|
|
348
|
+
const [siteSettingsOpen, setSiteSettingsOpen] = useState(false);
|
|
349
|
+
const [changingPassword, setChangingPassword] = useState(false);
|
|
350
|
+
const [settingFocus, setSettingFocus] = useState<string | undefined>(undefined);
|
|
351
|
+
const [historyOpen, setHistoryOpen] = useState(false);
|
|
352
|
+
/**
|
|
353
|
+
* Page settings opened with the toolbar's button. Beside the page they show whenever nothing else does; on a phone,
|
|
354
|
+
* where the panel covers the page, only when asked for, like any panel.
|
|
355
|
+
*/
|
|
356
|
+
const [pageSettingsAsked, setPageSettingsAsked] = useState(false);
|
|
357
|
+
/**
|
|
358
|
+
* What the loaded page says about its SEO (see Seo.astro). It also covers pages the site map does not list,
|
|
359
|
+
* such as the page of a content item.
|
|
360
|
+
*/
|
|
361
|
+
const [loadedSeo, setLoadedSeo] = useState<{ path: string; seo: SeoSettings; own: OwnSeo } | null>(null);
|
|
362
|
+
/** Set while the content browser covers the page: the folder it opened on, and whether to start a new item. */
|
|
363
|
+
// `/admin/edit?response=<id>`, the link in the email about a message, opens that message.
|
|
364
|
+
const [browsing, setBrowsing] = useState<BrowseTarget | null>(() => {
|
|
365
|
+
const response = new URLSearchParams(location.search).get("response");
|
|
366
|
+
return response ? { folder: "form-responses", create: false, response } : null;
|
|
367
|
+
});
|
|
368
|
+
const [siteMapOpen, setSiteMapOpen] = useState(false);
|
|
369
|
+
const [types, setTypes] = useState<ContentType[]>([]);
|
|
370
|
+
const [itemPage, setItemPage] = useState<ItemPage | null>(null);
|
|
371
|
+
/** On an item's page: true while its type's template is edited, false while the item itself is. */
|
|
372
|
+
const [templateMode, setTemplateMode] = useState(() => new URLSearchParams(location.search).has("template"));
|
|
373
|
+
/** The stacks of blocks on the loaded page, each with a + to add to it. */
|
|
374
|
+
const [stacks, setStacks] = useState<HTMLElement[]>([]);
|
|
375
|
+
/** The item whose page is open, as last saved: a change starts from it even before the page has drawn it. */
|
|
376
|
+
const latestItem = useRef<Item | null>(null);
|
|
377
|
+
/** Counts closings of the content browser, where items may have changed: the item is then read again. */
|
|
378
|
+
const [browsed, setBrowsed] = useState(0);
|
|
379
|
+
/** Node to select again once the page has been drawn again with a saved change. */
|
|
380
|
+
const reselect = useRef<string | null>(null);
|
|
381
|
+
const typeName = (itemPage?.type.singular ?? "item").toLowerCase();
|
|
382
|
+
|
|
383
|
+
function setTextEdit(next: TextEdit | null): void {
|
|
384
|
+
textEditRef.current = next;
|
|
385
|
+
setTextEditState(next);
|
|
386
|
+
setTyped(false);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Whether the text being typed differs from what it was when typing started. */
|
|
390
|
+
function textEditChanged(): boolean {
|
|
391
|
+
const edit = textEditRef.current;
|
|
392
|
+
if (!edit) return false;
|
|
393
|
+
return edit.element.innerHTML !== edit.originalHtml || edit.element.style.textAlign !== edit.originalAlign;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Runs one save, reporting progress and failure in the toolbar. A session that ran out does not end up here: the
|
|
398
|
+
* request waits for the owner to sign in again and is sent again (see `whenSignedOut`).
|
|
399
|
+
*/
|
|
400
|
+
const run = useCallback(async (work: Promise<unknown>): Promise<boolean> => {
|
|
401
|
+
const settled = work.then(
|
|
402
|
+
() => undefined,
|
|
403
|
+
() => undefined,
|
|
404
|
+
);
|
|
405
|
+
writes.current.add(settled);
|
|
406
|
+
void settled.then(() => writes.current.delete(settled));
|
|
407
|
+
setStatus({ state: "saving" });
|
|
408
|
+
try {
|
|
409
|
+
const result = await work;
|
|
410
|
+
if (isDrafted(result)) remember(result.change, result.drafts);
|
|
411
|
+
setStatus({ state: "idle" });
|
|
412
|
+
return true;
|
|
413
|
+
} catch (failure) {
|
|
414
|
+
setStatus({ state: "error", message: failure instanceof Error ? failure.message : "Could not save." });
|
|
415
|
+
return false;
|
|
416
|
+
}
|
|
417
|
+
}, []);
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Waits until no save is on its way. A change can start a moment after what caused it (a field saves on blur, then
|
|
421
|
+
* waits for the text being typed), so it looks again after each wait.
|
|
422
|
+
*/
|
|
423
|
+
async function settle(): Promise<void> {
|
|
424
|
+
for (;;) {
|
|
425
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
426
|
+
if (writes.current.size === 0) return;
|
|
427
|
+
await Promise.all([...writes.current]);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** A change now in the draft: one more step to undo, or part of the last one when it changes the same thing. */
|
|
432
|
+
function remember(change: DraftChange, count: number): void {
|
|
433
|
+
setDraftCount(count);
|
|
434
|
+
if (JSON.stringify(change.before) === JSON.stringify(change.after)) return;
|
|
435
|
+
const last = undoSteps.current.at(-1);
|
|
436
|
+
const only = last?.changes.length === 1 ? last.changes[0] : undefined;
|
|
437
|
+
if (
|
|
438
|
+
last &&
|
|
439
|
+
only &&
|
|
440
|
+
only.target === change.target &&
|
|
441
|
+
only.key === change.key &&
|
|
442
|
+
Date.now() - last.at < SAME_STEP_MS
|
|
443
|
+
) {
|
|
444
|
+
last.changes[0] = { ...only, after: change.after };
|
|
445
|
+
last.at = Date.now();
|
|
446
|
+
} else {
|
|
447
|
+
undoSteps.current.push({ changes: [change], at: Date.now() });
|
|
448
|
+
}
|
|
449
|
+
redoSteps.current = [];
|
|
450
|
+
setStepsChanged((count) => count + 1);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Undo (`back`) or redo: the step's drafts are put back, then the page shows them. */
|
|
454
|
+
async function replay(back: boolean): Promise<void> {
|
|
455
|
+
if (replaying.current || savingDrafts) return;
|
|
456
|
+
replaying.current = true;
|
|
457
|
+
try {
|
|
458
|
+
// What is being typed is a change of its own, so it is the one undone.
|
|
459
|
+
await finishTextEdit();
|
|
460
|
+
const step = (back ? undoSteps.current : redoSteps.current).pop();
|
|
461
|
+
if (!step) return;
|
|
462
|
+
setStepsChanged((count) => count + 1);
|
|
463
|
+
let item: Item | undefined;
|
|
464
|
+
const changes = back ? [...step.changes].reverse() : step.changes;
|
|
465
|
+
const done = await run(
|
|
466
|
+
(async () => {
|
|
467
|
+
for (const change of changes) {
|
|
468
|
+
const answer = await api.putDraft(change, back ? change.before : change.after);
|
|
469
|
+
setDraftCount(answer.drafts);
|
|
470
|
+
if (answer.item) item = answer.item;
|
|
471
|
+
}
|
|
472
|
+
})(),
|
|
473
|
+
);
|
|
474
|
+
if (!done) {
|
|
475
|
+
// Not taken back: it stays where it was, to try again.
|
|
476
|
+
(back ? undoSteps.current : redoSteps.current).push(step);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
step.at = 0;
|
|
480
|
+
(back ? redoSteps.current : undoSteps.current).push(step);
|
|
481
|
+
setStepsChanged((count) => count + 1);
|
|
482
|
+
showReplayed(step.changes[0]!, item);
|
|
483
|
+
} finally {
|
|
484
|
+
replaying.current = false;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** The page shows what an undo or redo changed: drawn again, or opened when the change was made elsewhere. */
|
|
489
|
+
function showReplayed(change: DraftChange, item: Item | undefined): void {
|
|
490
|
+
reread.current = true;
|
|
491
|
+
setRevision((count) => count + 1);
|
|
492
|
+
void refreshPages();
|
|
493
|
+
const keep = selected?.dataset.brimNode;
|
|
494
|
+
if (item) {
|
|
495
|
+
itemSaved(item);
|
|
496
|
+
if (itemPage?.item.id === item.id) {
|
|
497
|
+
const address = itemPagePath(itemPage.type, item, locales ?? undefined);
|
|
498
|
+
if (address === path) redraw(keep);
|
|
499
|
+
else open(address);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (change.page && change.page !== path) navigate(change.page);
|
|
504
|
+
else redraw(keep);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Save: everything drafted becomes what visitors see. */
|
|
508
|
+
async function saveDrafts(): Promise<void> {
|
|
509
|
+
if (savingNow.current) return;
|
|
510
|
+
savingNow.current = true;
|
|
511
|
+
setSavingDrafts(true);
|
|
512
|
+
try {
|
|
513
|
+
// A field in the side panel saves what was typed in it when it loses focus: it is let go of, so that is saved
|
|
514
|
+
// too. The page's frame keeps its focus: the text typed there is saved just after.
|
|
515
|
+
const focused = document.activeElement;
|
|
516
|
+
if (focused instanceof HTMLElement && focused.tagName !== "IFRAME") focused.blur();
|
|
517
|
+
// Typed text that could not be saved stays open with the reason in the toolbar, and nothing is saved.
|
|
518
|
+
if (!(await finishTextEdit())) return;
|
|
519
|
+
// Every change made so far reaches the drafts before they are saved.
|
|
520
|
+
await settle();
|
|
521
|
+
setStatus({ state: "saving" });
|
|
522
|
+
const result = await api.saveDrafts();
|
|
523
|
+
setDraftCount(result.drafts);
|
|
524
|
+
undoSteps.current = [];
|
|
525
|
+
redoSteps.current = [];
|
|
526
|
+
setStepsChanged((count) => count + 1);
|
|
527
|
+
const failure = result.failed[0];
|
|
528
|
+
setStatus(
|
|
529
|
+
failure
|
|
530
|
+
? {
|
|
531
|
+
state: "error",
|
|
532
|
+
message: `${result.failed.length} ${result.failed.length === 1 ? "change was" : "changes were"} not saved: ${failure.error}`,
|
|
533
|
+
}
|
|
534
|
+
: { state: "saved" },
|
|
535
|
+
);
|
|
536
|
+
void refreshPages();
|
|
537
|
+
} catch (failure) {
|
|
538
|
+
setStatus({ state: "error", message: failure instanceof Error ? failure.message : "Could not save." });
|
|
539
|
+
} finally {
|
|
540
|
+
savingNow.current = false;
|
|
541
|
+
setSavingDrafts(false);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Discard: every unsaved change is thrown away, and the page shows what visitors see. */
|
|
546
|
+
async function discardDrafts(): Promise<void> {
|
|
547
|
+
const count = draftCount;
|
|
548
|
+
const what = count === 1 ? "the unsaved change" : `all ${count} unsaved changes`;
|
|
549
|
+
if (!window.confirm(`Throw away ${what}? The site goes back to what was last saved. This cannot be undone.`))
|
|
550
|
+
return;
|
|
551
|
+
if (textEditRef.current) {
|
|
552
|
+
textEditRef.current.element.removeAttribute("contenteditable");
|
|
553
|
+
setTextEdit(null);
|
|
554
|
+
}
|
|
555
|
+
let answer: { drafts: number } | undefined;
|
|
556
|
+
if (!(await run(api.discardDrafts().then((result) => (answer = result))))) return;
|
|
557
|
+
setDraftCount(answer?.drafts ?? 0);
|
|
558
|
+
undoSteps.current = [];
|
|
559
|
+
redoSteps.current = [];
|
|
560
|
+
setStepsChanged((value) => value + 1);
|
|
561
|
+
reread.current = true;
|
|
562
|
+
setRevision((value) => value + 1);
|
|
563
|
+
// The item is read again, as saved.
|
|
564
|
+
setBrowsed((value) => value + 1);
|
|
565
|
+
void refreshPages();
|
|
566
|
+
redraw(selected?.dataset.brimNode);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function shortcut(name: Shortcut): void {
|
|
570
|
+
if (name === "save") void saveDrafts();
|
|
571
|
+
else void replay(name === "undo");
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function refOf(element: HTMLElement): NodeRef {
|
|
575
|
+
const { brimItem: item, brimField: field, brimScope: scope } = element.dataset;
|
|
576
|
+
return {
|
|
577
|
+
path,
|
|
578
|
+
scope: scope === "site" || scope === "template" ? scope : "page",
|
|
579
|
+
nodeId: element.dataset.brimNode ?? "",
|
|
580
|
+
// In the template, a field's element saves how it looks, never the content of the item shown as a sample.
|
|
581
|
+
...(item && field && !templateMode && { item, field }),
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Why an element cannot be changed in the current mode, with the switch to the mode where it can. */
|
|
586
|
+
function lockOf(element: HTMLElement): Lock | undefined {
|
|
587
|
+
// The server found markup in the code's default text that a saved text cannot hold: typing would lose it.
|
|
588
|
+
if (element.dataset.brimUnkept !== undefined) return { hint: "Only the site's code can change this text" };
|
|
589
|
+
if (!templateMode && element.dataset.brimScope === "template" && !isField(element)) {
|
|
590
|
+
return { hint: `Part of the ${typeName} template`, action: "Edit template", onAction: () => switchMode(true) };
|
|
591
|
+
}
|
|
592
|
+
// Rich text, picked values and blocks are nothing but the item's content: the template has nothing to change.
|
|
593
|
+
// How a picked value is written (its date format, its element) is the site's code.
|
|
594
|
+
if (
|
|
595
|
+
templateMode &&
|
|
596
|
+
isField(element) &&
|
|
597
|
+
(element.dataset.brimKind === "richtext" || isPickedField(element) || isEntry(element) || isStack(element))
|
|
598
|
+
) {
|
|
599
|
+
return { hint: `Content of this ${typeName}`, action: `Edit ${typeName}`, onAction: () => switchMode(false) };
|
|
600
|
+
}
|
|
601
|
+
return undefined;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function switchMode(template: boolean): void {
|
|
605
|
+
select(null);
|
|
606
|
+
setTemplateMode(template);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** Whether the side panel has settings of the element's own to show; the text of an item is only typed. */
|
|
610
|
+
function hasSettings(element: HTMLElement): boolean {
|
|
611
|
+
if (lockOf(element) || isStack(element)) return false;
|
|
612
|
+
if (isPickedField(element)) return itemPage !== null;
|
|
613
|
+
if (!nodeKinds[element.dataset.brimKind ?? ""]) return false;
|
|
614
|
+
return !(isField(element) && !templateMode && isEditedInPlace(element));
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function itemSaved(item: Item | undefined): void {
|
|
618
|
+
if (!item) return;
|
|
619
|
+
if (latestItem.current?.id === item.id) latestItem.current = item;
|
|
620
|
+
setItemPage((page) => (page?.item.id === item.id ? { ...page, item } : page));
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Draws the page again in the frame out of sight, and shows it once it has loaded, scrolled where the owner was:
|
|
625
|
+
* the page in view stays until then, so nothing flashes. `keep` is the node to select again on it.
|
|
626
|
+
*/
|
|
627
|
+
function redraw(keep?: string): void {
|
|
628
|
+
// Another page is opening: it is drawn afresh anyway, and the one in view now would take its place.
|
|
629
|
+
if (opening.current) return;
|
|
630
|
+
const request = ++requests.current;
|
|
631
|
+
// What is being typed is saved first, or the page drawn again would show the text without it.
|
|
632
|
+
void finishTextEdit().then((saved) => {
|
|
633
|
+
if (!saved || request !== requests.current || opening.current) return;
|
|
634
|
+
reselect.current = keep ?? null;
|
|
635
|
+
const view = frame.current?.contentWindow;
|
|
636
|
+
// The frame not in view, read from the frames themselves: a caller's `shown` may be from before the last swap.
|
|
637
|
+
const slot = slots.current[0] === frame.current ? 1 : 0;
|
|
638
|
+
const next = slots.current[slot]?.contentWindow;
|
|
639
|
+
if (!view || !next) return;
|
|
640
|
+
incoming.current = { slot, x: view.scrollX, y: view.scrollY };
|
|
641
|
+
next.location.replace(view.location.href);
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Opens another address in the frame in view, once what is being typed is saved. A page still being drawn again
|
|
647
|
+
* out of sight was asked for before, so it is dropped: it would cover the page just opened.
|
|
648
|
+
*/
|
|
649
|
+
function open(address: string): void {
|
|
650
|
+
const request = ++requests.current;
|
|
651
|
+
incoming.current = null;
|
|
652
|
+
reselect.current = null;
|
|
653
|
+
opening.current = true;
|
|
654
|
+
void finishTextEdit().then((saved) => {
|
|
655
|
+
if (request !== requests.current) return;
|
|
656
|
+
// Typed text that could not be saved stays open on this page, with the reason in the toolbar.
|
|
657
|
+
if (!saved) {
|
|
658
|
+
opening.current = false;
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
frame.current?.contentWindow?.location.assign(address);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** A frame finished loading: the page drawn out of sight takes the place of the one in view. */
|
|
666
|
+
function frameLoaded(slot: number): void {
|
|
667
|
+
const pending = incoming.current;
|
|
668
|
+
if (pending?.slot === slot) {
|
|
669
|
+
incoming.current = null;
|
|
670
|
+
const previous = frame.current;
|
|
671
|
+
frame.current = slots.current[slot] ?? null;
|
|
672
|
+
frame.current?.contentWindow?.scrollTo(pending.x, pending.y);
|
|
673
|
+
setShown(slot);
|
|
674
|
+
attachToPage();
|
|
675
|
+
// Emptied, ready to draw the page the next time.
|
|
676
|
+
previous?.contentWindow?.location.replace("about:blank");
|
|
677
|
+
} else if (slots.current[slot] === frame.current) {
|
|
678
|
+
// The page in view opened another address: a page drawn again out of sight would be the one before it.
|
|
679
|
+
opening.current = false;
|
|
680
|
+
incoming.current = null;
|
|
681
|
+
attachToPage();
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** What the owner chose for this text besides its words: the element, its alignment and its presentation. */
|
|
686
|
+
function chosenForText(element: HTMLElement): TextChoice {
|
|
687
|
+
return JSON.parse(element.dataset.brimValue ?? "{}") as TextChoice;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function textValue(element: HTMLElement, chosen = chosenForText(element)): unknown {
|
|
691
|
+
if (element.dataset.brimKind === "richtext") return { blocks: readBlocks(element) };
|
|
692
|
+
// In the template a field's element keeps only how it looks: its words are the item's.
|
|
693
|
+
const lookOnly = templateMode && isField(element);
|
|
694
|
+
const rich = readInlineText(element);
|
|
695
|
+
// Chosen in the side panel ("" for none), or else as the text tools left it on the element.
|
|
696
|
+
const align = chosen.align ?? alignOf(element);
|
|
697
|
+
return {
|
|
698
|
+
text: lookOnly ? "" : readText(element),
|
|
699
|
+
...(!lookOnly && hasFormatting(rich) && { rich }),
|
|
700
|
+
...(chosen.as && { as: chosen.as }),
|
|
701
|
+
...(align && { align }),
|
|
702
|
+
...(chosen.options && Object.keys(chosen.options).length > 0 && { options: chosen.options }),
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Ends typing in place and saves what was typed; a change that follows waits for it, so nothing typed is lost.
|
|
708
|
+
* False when it could not be saved: the text is then open again with what was typed, to try again.
|
|
709
|
+
*/
|
|
710
|
+
async function finishTextEdit(): Promise<boolean> {
|
|
711
|
+
const edit = textEditRef.current;
|
|
712
|
+
if (!edit) return true;
|
|
713
|
+
const changed = textEditChanged();
|
|
714
|
+
const { element } = edit;
|
|
715
|
+
element.removeAttribute("contenteditable");
|
|
716
|
+
setTextEdit(null);
|
|
717
|
+
if (!changed) {
|
|
718
|
+
setLiveField(null);
|
|
719
|
+
return true;
|
|
720
|
+
}
|
|
721
|
+
const saved = isEntry(element)
|
|
722
|
+
? await saveEntry(element, textValue(element), false)
|
|
723
|
+
: await run(
|
|
724
|
+
api.saveNode(refOf(element), element.dataset.brimKind ?? "text", textValue(element)).then((answer) => {
|
|
725
|
+
itemSaved(answer.item);
|
|
726
|
+
return answer;
|
|
727
|
+
}),
|
|
728
|
+
);
|
|
729
|
+
if (!saved) {
|
|
730
|
+
// Still on the page in view and nothing else being typed: it stays open, so leaving the page still warns.
|
|
731
|
+
if (!textEditRef.current && element.isConnected && element.ownerDocument === frame.current?.contentDocument) {
|
|
732
|
+
element.contentEditable = "true";
|
|
733
|
+
setTextEdit(edit);
|
|
734
|
+
setTyped(true);
|
|
735
|
+
}
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
// The page settings show the item as saved from now on; until then they kept showing what was typed.
|
|
739
|
+
setLiveField(null);
|
|
740
|
+
return true;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Shows a value of the item being typed (on the page or in the page settings) in every other element of the page
|
|
745
|
+
* that shows the same field as text, so they all agree before it is saved. Other kinds are drawn again on save.
|
|
746
|
+
*/
|
|
747
|
+
function previewField(field: string, value: unknown, except?: HTMLElement): void {
|
|
748
|
+
const item = itemPage?.item;
|
|
749
|
+
const page = frame.current?.contentDocument;
|
|
750
|
+
if (!item || !page || typeof value !== "string") return;
|
|
751
|
+
const selector = `[data-brim-kind="text"][data-brim-item="${CSS.escape(item.id)}"][data-brim-field="${CSS.escape(field)}"]`;
|
|
752
|
+
for (const element of page.querySelectorAll<HTMLElement>(selector)) {
|
|
753
|
+
if (element !== except && element !== textEditRef.current?.element && !isEntry(element)) {
|
|
754
|
+
element.textContent = value;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** The item field an element shows, for its toolbar: a change on the page or in the page settings changes both. */
|
|
760
|
+
function bindingOf(element: HTMLElement): Binding | undefined {
|
|
761
|
+
if (!itemPage || !isField(element) || isEntry(element)) return undefined;
|
|
762
|
+
const name = element.dataset.brimField ?? "";
|
|
763
|
+
const field = name === "title" ? "Title" : (itemPage.type.fields.find((one) => one.name === name)?.label ?? name);
|
|
764
|
+
return {
|
|
765
|
+
label: `${itemPage.type.singular} · ${field}`,
|
|
766
|
+
note: templateMode
|
|
767
|
+
? `Shows each ${typeName}'s ${field}: how it looks is set here, the ${field} itself on each ${typeName}.`
|
|
768
|
+
: `Shows this ${typeName}'s ${field}: a change here or in Page Settings changes both.`,
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** The element and the presentation are drawn by the page's own markup, so the page is rendered again. */
|
|
773
|
+
async function changeTextPresentation(element: HTMLElement, chosen: TextChoice): Promise<void> {
|
|
774
|
+
if (await run(api.saveNode(refOf(element), "text", textValue(element, { ...chosenForText(element), ...chosen })))) {
|
|
775
|
+
element.removeAttribute("contenteditable");
|
|
776
|
+
setTextEdit(null);
|
|
777
|
+
redraw(element.dataset.brimNode);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** Selects an element: the side panel shows its settings, and text starts being typed in place. */
|
|
782
|
+
function select(element: HTMLElement | null): void {
|
|
783
|
+
if (textEditRef.current && textEditRef.current.element !== element) void finishTextEdit();
|
|
784
|
+
setSelected(element);
|
|
785
|
+
if (!element) return;
|
|
786
|
+
setSiteSettingsOpen(false);
|
|
787
|
+
setHistoryOpen(false);
|
|
788
|
+
setPageSettingsAsked(false);
|
|
789
|
+
|
|
790
|
+
const typed = isEditedInPlace(element) && !(templateMode && isField(element));
|
|
791
|
+
if (typed && !lockOf(element) && textEditRef.current?.element !== element) {
|
|
792
|
+
setTextEdit({ element, originalHtml: element.innerHTML, originalAlign: element.style.textAlign });
|
|
793
|
+
element.contentEditable = "true";
|
|
794
|
+
element.focus();
|
|
795
|
+
// Formatting is written as elements (<b>, <font>), which the saved model can describe.
|
|
796
|
+
element.ownerDocument.execCommand("styleWithCSS", false, "false");
|
|
797
|
+
element.ownerDocument.execCommand("defaultParagraphSeparator", false, "p");
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
async function changeFromInspector(element: HTMLElement, form: FormValue): Promise<void> {
|
|
802
|
+
const kindName = element.dataset.brimKind ?? "";
|
|
803
|
+
const kind = nodeKinds[kindName];
|
|
804
|
+
if (!kind) return;
|
|
805
|
+
|
|
806
|
+
if (isEntry(element)) {
|
|
807
|
+
await saveEntry(element, kind.toValue(form), true);
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
// The text panel holds the element, the alignment and the presentation, nothing else.
|
|
811
|
+
if (kindName === "text") return changeTextPresentation(element, form as TextChoice);
|
|
812
|
+
// The template keeps how a field's image is shown; the image itself stays the sample item's.
|
|
813
|
+
const value = templateMode && isField(element) ? withoutImageContent(form) : form;
|
|
814
|
+
const saving = api.saveNode(refOf(element), kindName, kind.toValue(value)).then((answer) => {
|
|
815
|
+
// A gallery or image showing an item's field saved into the item: the page settings, and any change made
|
|
816
|
+
// after, work on the item as it is now, never on the one from before (which would bring a removed image back).
|
|
817
|
+
itemSaved(answer.item);
|
|
818
|
+
return answer;
|
|
819
|
+
});
|
|
820
|
+
if (await run(saving)) {
|
|
821
|
+
if (kind.apply) kind.apply(element, form);
|
|
822
|
+
else redraw(element.dataset.brimNode);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
async function reset(element: HTMLElement): Promise<void> {
|
|
827
|
+
setTextEdit(null);
|
|
828
|
+
if (await run(api.resetNode(refOf(element)))) redraw(element.dataset.brimNode);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
async function changeVisibility(visibility: Visibility): Promise<void> {
|
|
832
|
+
if (itemPage) {
|
|
833
|
+
await finishTextEdit();
|
|
834
|
+
// Who can see the item changes at once; its unsaved content stays in the draft.
|
|
835
|
+
let saved: Item | undefined;
|
|
836
|
+
const { id, data } = itemPage.item;
|
|
837
|
+
if (!(await run(api.setItemVisibility(id, visibility).then((answer) => (saved = answer.item))))) return;
|
|
838
|
+
itemSaved(saved);
|
|
839
|
+
// An article published for the first time is given its date, which its page may show.
|
|
840
|
+
if (saved && saved.data.published !== data.published) redraw(selected?.dataset.brimNode);
|
|
841
|
+
} else if (await run(api.setVisibility(path, visibility))) setPages((await api.pages()).pages);
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Saves the item whose page is open, then draws its page again, at its new address if that changed, with `keep`
|
|
846
|
+
* selected. A change the page already shows, such as text typed in place, passes `refresh` false.
|
|
847
|
+
*/
|
|
848
|
+
async function saveItem(draft: ItemDraft, refresh = true, keep?: string): Promise<boolean> {
|
|
849
|
+
if (!itemPage) return false;
|
|
850
|
+
let saved: Item | undefined;
|
|
851
|
+
const work = api.draftItem(itemPage.item.id, draft, path).then((answer) => {
|
|
852
|
+
saved = answer.item;
|
|
853
|
+
return answer;
|
|
854
|
+
});
|
|
855
|
+
if (!(await run(work)) || !saved) return false;
|
|
856
|
+
itemSaved(saved);
|
|
857
|
+
if (!refresh) return true;
|
|
858
|
+
// The same page is drawn again out of sight and keeps its scroll; only a new address is opened afresh.
|
|
859
|
+
const address = itemPagePath(itemPage.type, saved, locales ?? undefined);
|
|
860
|
+
if (address === path) redraw(keep);
|
|
861
|
+
else open(address);
|
|
862
|
+
return true;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* A change made in the page settings, applied to the item as last saved once the text being typed is saved: the
|
|
867
|
+
* panel's copy of the item may not have the words just typed on the page yet. `keep` is the node to select again.
|
|
868
|
+
*/
|
|
869
|
+
async function changeItemFields(before: ItemDraft, after: ItemDraft, keep?: string): Promise<void> {
|
|
870
|
+
await finishTextEdit();
|
|
871
|
+
const item = latestItem.current;
|
|
872
|
+
if (!item) return;
|
|
873
|
+
const data = { ...item.data };
|
|
874
|
+
for (const key of new Set([...Object.keys(before.data), ...Object.keys(after.data)])) {
|
|
875
|
+
if (after.data[key] !== before.data[key]) data[key] = after.data[key];
|
|
876
|
+
}
|
|
877
|
+
const pick = <K extends "title" | "slug">(key: K) => (after[key] !== before[key] ? after[key] : item[key]);
|
|
878
|
+
if (after.visibility !== before.visibility) await changeVisibility(after.visibility);
|
|
879
|
+
const changed =
|
|
880
|
+
after.title !== before.title ||
|
|
881
|
+
after.slug !== before.slug ||
|
|
882
|
+
JSON.stringify(after.data) !== JSON.stringify(before.data);
|
|
883
|
+
if (!changed) return;
|
|
884
|
+
await saveItem({ title: pick("title"), slug: pick("slug"), visibility: item.visibility, data }, true, keep);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** The blocks stacked in a field of the item whose page is open, as last saved. */
|
|
888
|
+
function entriesOf(field: string): BlockEntry[] {
|
|
889
|
+
return blocksOf(latestItem.current?.data[field]);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** Saves a field's blocks into the item; `keep` is the block to select once the page is drawn again. */
|
|
893
|
+
async function saveBlocks(field: string, entries: BlockEntry[], keep?: string, refresh = true): Promise<boolean> {
|
|
894
|
+
const item = latestItem.current;
|
|
895
|
+
if (!item) return false;
|
|
896
|
+
return saveItem({ ...item, data: { ...item.data, [field]: entries } }, refresh, keep);
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** Adds, moves or deletes blocks once the text being typed is saved, working on the blocks as last saved. */
|
|
900
|
+
async function changeBlocks(field: string, change: (entries: BlockEntry[]) => BlockEntry[], keep?: string) {
|
|
901
|
+
if (!(await finishTextEdit())) return;
|
|
902
|
+
await saveBlocks(field, change(entriesOf(field)), keep);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** Saves one block with the item: its settings from the inspector, or its text typed in place. */
|
|
906
|
+
async function saveEntry(element: HTMLElement, value: unknown, refresh: boolean): Promise<boolean> {
|
|
907
|
+
const field = element.dataset.brimField ?? "";
|
|
908
|
+
const id = element.dataset.brimEntry;
|
|
909
|
+
const entries = entriesOf(field).map((entry) =>
|
|
910
|
+
entry.id === id ? { ...entry, value: value as Record<string, unknown> } : entry,
|
|
911
|
+
);
|
|
912
|
+
return saveBlocks(field, entries, id, refresh);
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** A block's width and side in its field, and saving a change of them with the item. */
|
|
916
|
+
function entryLayout(element: HTMLElement): { value: BlockLayout; onChange: (layout: BlockLayout) => void } {
|
|
917
|
+
const field = element.dataset.brimField ?? "";
|
|
918
|
+
const id = element.dataset.brimEntry;
|
|
919
|
+
const entry = entriesOf(field).find((candidate) => candidate.id === id);
|
|
920
|
+
return {
|
|
921
|
+
value: layoutOf(entry?.type ?? "", entry?.layout, entry?.value),
|
|
922
|
+
onChange: (layout) =>
|
|
923
|
+
void changeBlocks(field, (list) => list.map((other) => (other.id === id ? { ...other, layout } : other)), id),
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/** On a stack of blocks or one of its blocks, while the item is edited: add a block after it, move it, delete it. */
|
|
928
|
+
function stackOf(element: HTMLElement): StackActions | undefined {
|
|
929
|
+
const stack = isStack(element) ? element : isEntry(element) ? element.closest<HTMLElement>(STACK_SELECTOR) : null;
|
|
930
|
+
const field = stack?.dataset.brimField ?? "";
|
|
931
|
+
const declared = itemPage?.type.fields.find((candidate) => candidate.name === field);
|
|
932
|
+
if (templateMode || declared?.type !== "blocks") return undefined;
|
|
933
|
+
|
|
934
|
+
const id = isEntry(element) ? element.dataset.brimEntry : undefined;
|
|
935
|
+
const entries = entriesOf(field);
|
|
936
|
+
const index = entries.findIndex((entry) => entry.id === id);
|
|
937
|
+
// Each change is worked out on the blocks as they are when it runs, after any typing has been saved.
|
|
938
|
+
const without = (list: BlockEntry[]) => list.filter((entry) => entry.id !== id);
|
|
939
|
+
const move = (by: -1 | 1) => () =>
|
|
940
|
+
void changeBlocks(
|
|
941
|
+
field,
|
|
942
|
+
(list) => {
|
|
943
|
+
const from = list.findIndex((entry) => entry.id === id);
|
|
944
|
+
if (from === -1) return list;
|
|
945
|
+
const others = without(list);
|
|
946
|
+
return [...others.slice(0, from + by), list[from]!, ...others.slice(from + by)];
|
|
947
|
+
},
|
|
948
|
+
id,
|
|
949
|
+
);
|
|
950
|
+
return {
|
|
951
|
+
types: (declared.blocks ?? BLOCK_TYPES).map((type) => ({
|
|
952
|
+
type,
|
|
953
|
+
label: type === "richtext" ? "Text" : (nodeKinds[type]?.title ?? type),
|
|
954
|
+
})),
|
|
955
|
+
onAdd: (type) => {
|
|
956
|
+
const entry = {
|
|
957
|
+
id: `b${crypto.randomUUID().slice(0, 8)}`,
|
|
958
|
+
type,
|
|
959
|
+
value: type === "richtext" ? { blocks: [] } : {},
|
|
960
|
+
};
|
|
961
|
+
void changeBlocks(
|
|
962
|
+
field,
|
|
963
|
+
(list) => {
|
|
964
|
+
const after = list.findIndex((other) => other.id === id);
|
|
965
|
+
const at = after === -1 ? list.length : after + 1;
|
|
966
|
+
return [...list.slice(0, at), entry as BlockEntry, ...list.slice(at)];
|
|
967
|
+
},
|
|
968
|
+
entry.id,
|
|
969
|
+
);
|
|
970
|
+
},
|
|
971
|
+
onMoveUp: index > 0 ? move(-1) : undefined,
|
|
972
|
+
onMoveDown: index !== -1 && index < entries.length - 1 ? move(1) : undefined,
|
|
973
|
+
onDelete: index === -1 ? undefined : () => void changeBlocks(field, without),
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** The template is edited on the page of one of the type's items, shown as a sample. */
|
|
978
|
+
function editTemplate(samplePath: string): void {
|
|
979
|
+
setTemplateMode(true);
|
|
980
|
+
navigate(samplePath);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
async function changeSeo(seo: SeoSettings): Promise<void> {
|
|
984
|
+
let saved: SitePage | undefined;
|
|
985
|
+
if (!(await run(api.setSeo(path, seo).then((page) => (saved = page))))) return;
|
|
986
|
+
if (saved) setLoadedSeo((loaded) => (loaded?.path === path ? { ...loaded, seo: saved?.seo ?? {} } : loaded));
|
|
987
|
+
setPages((await api.pages()).pages);
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** A new page opens at once, so the owner fills it in where it will be seen. */
|
|
991
|
+
async function createPage(page: NewPage): Promise<boolean> {
|
|
992
|
+
let created: SitePage | undefined;
|
|
993
|
+
const done = await run(api.createPage(page).then((answer) => (created = answer.page)));
|
|
994
|
+
if (!done || !created) return false;
|
|
995
|
+
await refreshPages();
|
|
996
|
+
navigate(created.path);
|
|
997
|
+
return true;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
async function deletePage(page: SitePage): Promise<boolean> {
|
|
1001
|
+
if (!(await run(api.deletePage(page.path)))) return false;
|
|
1002
|
+
await refreshPages();
|
|
1003
|
+
if (page.path === path) navigate("/");
|
|
1004
|
+
return true;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/** A page added from a template moves to its new address and opens there; the old one redirects to it. */
|
|
1008
|
+
async function movePage(to: string): Promise<boolean> {
|
|
1009
|
+
// The text being typed is saved at the page's present address, before the page moves.
|
|
1010
|
+
if (!(await finishTextEdit())) return false;
|
|
1011
|
+
let moved: SitePage | undefined;
|
|
1012
|
+
if (!(await run(api.movePage(path, to).then(({ page }) => (moved = page))))) return false;
|
|
1013
|
+
await refreshPages();
|
|
1014
|
+
if (moved && moved.path !== path) navigate(moved.path);
|
|
1015
|
+
return true;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function navigate(next: string): void {
|
|
1019
|
+
setSiteMapOpen(false);
|
|
1020
|
+
setBrowsing(null);
|
|
1021
|
+
open(next);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
function browse(folder: string | null = null, create = false, data?: Record<string, unknown>, form?: string): void {
|
|
1025
|
+
select(null);
|
|
1026
|
+
setSiteMapOpen(false);
|
|
1027
|
+
setBrowsing({ folder, create, ...(data && { data }), ...(form !== undefined && { form }) });
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function leaveBrowser(): void {
|
|
1031
|
+
setBrowsing(null);
|
|
1032
|
+
setBrowsed((count) => count + 1);
|
|
1033
|
+
// An item saved from its form takes its drafted content with it.
|
|
1034
|
+
api.drafts().then(
|
|
1035
|
+
(answer) => setDraftCount(answer.drafts),
|
|
1036
|
+
() => undefined,
|
|
1037
|
+
);
|
|
1038
|
+
// Items changed in the browser show up on the page once it is rendered again.
|
|
1039
|
+
redraw();
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
async function refreshPages(): Promise<void> {
|
|
1043
|
+
setPages((await api.pages()).pages);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/** The same page in another of the site's languages: opened when it exists, else made from this one. */
|
|
1047
|
+
async function switchLanguage(code: string, fill: boolean): Promise<void> {
|
|
1048
|
+
if (!locales) return;
|
|
1049
|
+
// A translation is made from the page as saved, so the words being typed are saved first.
|
|
1050
|
+
if (!(await finishTextEdit())) return;
|
|
1051
|
+
if (itemPage) return switchItemLanguage(itemPage, code, locales);
|
|
1052
|
+
const target = pathInLocale(path, code, locales);
|
|
1053
|
+
if (!fill && pages.some((page) => page.path === target)) return navigate(target);
|
|
1054
|
+
let made: { path: string } | undefined;
|
|
1055
|
+
if (await run(api.translatePage(path, code).then((answer) => (made = answer)))) {
|
|
1056
|
+
await refreshPages();
|
|
1057
|
+
if (made) navigate(made.path);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/** The item's page in another language: its translation's page, or a new translation made from this item. */
|
|
1062
|
+
async function switchItemLanguage(page: ItemPage, code: string, locales: SiteLocales): Promise<void> {
|
|
1063
|
+
const translation = page.translations.find((item) => itemLocale(item, locales) === code);
|
|
1064
|
+
if (translation) return navigate(itemPagePath(page.type, translation, locales));
|
|
1065
|
+
let made: Item | undefined;
|
|
1066
|
+
if ((await run(api.translateItem(page.item.id, code).then((answer) => (made = answer.item)))) && made) {
|
|
1067
|
+
navigate(itemPagePath(page.type, made, locales));
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// A page written in code or added from a template, or the page of an item: its translations are the item's.
|
|
1072
|
+
const languageChoice: LanguageChoice | undefined = !locales
|
|
1073
|
+
? undefined
|
|
1074
|
+
: itemPage
|
|
1075
|
+
? {
|
|
1076
|
+
current: itemLocale(itemPage.item, locales),
|
|
1077
|
+
copy: false,
|
|
1078
|
+
options: locales.locales.map((code) => {
|
|
1079
|
+
const translation = itemPage.translations.find((item) => itemLocale(item, locales) === code);
|
|
1080
|
+
const target = translation ? itemPagePath(itemPage.type, translation, locales) : "";
|
|
1081
|
+
return { code, path: target, exists: Boolean(translation) };
|
|
1082
|
+
}),
|
|
1083
|
+
}
|
|
1084
|
+
: pages.some((page) => page.path === path)
|
|
1085
|
+
? {
|
|
1086
|
+
current: localeOfPath(path, locales) ?? locales.defaultLocale,
|
|
1087
|
+
copy: true,
|
|
1088
|
+
options: locales.locales.map((code) => {
|
|
1089
|
+
const target = pathInLocale(path, code, locales);
|
|
1090
|
+
return { code, path: target, exists: pages.some((page) => page.path === target) };
|
|
1091
|
+
}),
|
|
1092
|
+
}
|
|
1093
|
+
: undefined;
|
|
1094
|
+
|
|
1095
|
+
// The page's listeners are attached once per load; this keeps them calling the current handlers.
|
|
1096
|
+
/** Site Settings opened at one of the site's own settings, clicked on the page. */
|
|
1097
|
+
function openSetting(name: string): void {
|
|
1098
|
+
select(null);
|
|
1099
|
+
setHistoryOpen(false);
|
|
1100
|
+
setSettingFocus(name);
|
|
1101
|
+
setSiteSettingsOpen(true);
|
|
1102
|
+
}
|
|
1103
|
+
/** Whether leaving now would lose something: unsaved drafts, typed text, or a save still on its way. */
|
|
1104
|
+
const unsaved = (): boolean => draftCount > 0 || textEditChanged() || writes.current.size > 0;
|
|
1105
|
+
/** Moves the keyboard to the side panel, for the selected element's settings. */
|
|
1106
|
+
function focusPanel(): void {
|
|
1107
|
+
document.querySelector<HTMLElement>(".brim-editor-panel .brim-sidebar")?.focus();
|
|
1108
|
+
}
|
|
1109
|
+
/** Moves the keyboard back from the side panel to the page: to the selected element, else to the page itself. */
|
|
1110
|
+
function focusPage(): void {
|
|
1111
|
+
frame.current?.contentWindow?.focus();
|
|
1112
|
+
if (selected?.isConnected) selected.focus({ preventScroll: true });
|
|
1113
|
+
}
|
|
1114
|
+
const handlers = useRef({
|
|
1115
|
+
select,
|
|
1116
|
+
selected,
|
|
1117
|
+
textEdit,
|
|
1118
|
+
openSetting,
|
|
1119
|
+
shortcut,
|
|
1120
|
+
browsing,
|
|
1121
|
+
unsaved,
|
|
1122
|
+
focusPanel,
|
|
1123
|
+
focusPage,
|
|
1124
|
+
});
|
|
1125
|
+
handlers.current = { select, selected, textEdit, openSetting, shortcut, browsing, unsaved, focusPanel, focusPage };
|
|
1126
|
+
|
|
1127
|
+
function attachToPage(): void {
|
|
1128
|
+
const page = frame.current?.contentDocument;
|
|
1129
|
+
const view = frame.current?.contentWindow;
|
|
1130
|
+
if (!page || !view) return;
|
|
1131
|
+
|
|
1132
|
+
const loadedPath = view.location.pathname;
|
|
1133
|
+
setPath(loadedPath);
|
|
1134
|
+
setStacks([...page.querySelectorAll<HTMLElement>(STACK_SELECTOR)]);
|
|
1135
|
+
setLoadedSeo(readPageSeo(page, loadedPath));
|
|
1136
|
+
setHovered(null);
|
|
1137
|
+
// Text still being typed on the page before belongs to that page: it is saved there, never dropped.
|
|
1138
|
+
if (textEditRef.current) void finishTextEdit();
|
|
1139
|
+
|
|
1140
|
+
const style = page.createElement("style");
|
|
1141
|
+
style.textContent = PAGE_STYLE;
|
|
1142
|
+
page.head.append(style);
|
|
1143
|
+
page.documentElement.dataset.brimViewport = viewportRef.current;
|
|
1144
|
+
// The outline drawn on the page takes the editor's selection color.
|
|
1145
|
+
const selection = getComputedStyle(document.documentElement).getPropertyValue("--brim-canvas-selection").trim();
|
|
1146
|
+
if (selection) page.documentElement.style.setProperty("--brim-editor-selection", selection);
|
|
1147
|
+
adoptThemeColors(view);
|
|
1148
|
+
|
|
1149
|
+
page.addEventListener(
|
|
1150
|
+
"click",
|
|
1151
|
+
(event) => {
|
|
1152
|
+
// One of the site's own settings: it is changed in Site Settings, for every page that shows it.
|
|
1153
|
+
const setting = isElement(event.target) ? event.target.closest<HTMLElement>("[data-brim-setting]") : null;
|
|
1154
|
+
if (setting?.dataset.brimSetting) {
|
|
1155
|
+
event.preventDefault();
|
|
1156
|
+
event.stopPropagation();
|
|
1157
|
+
handlers.current.openSetting(setting.dataset.brimSetting);
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
const node = nodeOf(event.target);
|
|
1161
|
+
// A click inside the text being edited only moves the caret.
|
|
1162
|
+
if (node && node === handlers.current.textEdit?.element) return;
|
|
1163
|
+
if (node) {
|
|
1164
|
+
event.preventDefault();
|
|
1165
|
+
event.stopPropagation();
|
|
1166
|
+
}
|
|
1167
|
+
handlers.current.select(node);
|
|
1168
|
+
},
|
|
1169
|
+
true,
|
|
1170
|
+
);
|
|
1171
|
+
// Every element that can be selected is reached with Tab, as it is clicked. Only here, in the editor's frame:
|
|
1172
|
+
// the page visitors get has none of it. An element that is focusable already (a link, a button) stays as it is.
|
|
1173
|
+
for (const node of page.querySelectorAll<HTMLElement>(NODE_SELECTOR)) {
|
|
1174
|
+
if (!node.hasAttribute("tabindex") && node.tabIndex < 0) node.tabIndex = 0;
|
|
1175
|
+
}
|
|
1176
|
+
page.addEventListener("pointerover", (event) => setHovered(nodeOf(event.target)));
|
|
1177
|
+
page.documentElement.addEventListener("pointerleave", () => setHovered(null));
|
|
1178
|
+
// The element reached with Tab is outlined and named, as one under the pointer is.
|
|
1179
|
+
page.addEventListener("focusin", (event) => {
|
|
1180
|
+
const node = nodeOf(event.target);
|
|
1181
|
+
if (node && node === event.target) setHovered(node);
|
|
1182
|
+
});
|
|
1183
|
+
page.addEventListener("keydown", (event) => {
|
|
1184
|
+
// Enter or Escape that picks or cancels a word being composed (Japanese, Chinese) belongs to the input method:
|
|
1185
|
+
// it must not break the line, leave the text or save half a word.
|
|
1186
|
+
if (isComposing(event)) return;
|
|
1187
|
+
const name = shortcutOf(event);
|
|
1188
|
+
if (name) {
|
|
1189
|
+
const typing = handlers.current.textEdit;
|
|
1190
|
+
// While typing, Cmd+Z undoes the typing; once nothing typed is left, it goes on to the changes before.
|
|
1191
|
+
if (name !== "save" && typing && typing.element.innerHTML !== typing.originalHtml) return;
|
|
1192
|
+
event.preventDefault();
|
|
1193
|
+
if (typing && name !== "save") handlers.current.select(null);
|
|
1194
|
+
handlers.current.shortcut(name);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (event.key === PANEL_KEY) {
|
|
1198
|
+
event.preventDefault();
|
|
1199
|
+
handlers.current.focusPanel();
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
const typing = handlers.current.textEdit;
|
|
1203
|
+
if (event.key === "Escape") {
|
|
1204
|
+
const left = handlers.current.selected;
|
|
1205
|
+
handlers.current.select(null);
|
|
1206
|
+
// The keyboard stays on the element just left, to go on from there with Tab.
|
|
1207
|
+
if (left?.isConnected) left.focus({ preventScroll: true });
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
// An element reached with Tab is selected with Enter or Space, as a click selects it. A link inside it is
|
|
1211
|
+
// clicked by Enter, which selects it the same way without leaving the page.
|
|
1212
|
+
const node = nodeOf(event.target);
|
|
1213
|
+
if ((event.key === "Enter" || event.key === " ") && node && node === event.target && node !== typing?.element) {
|
|
1214
|
+
event.preventDefault();
|
|
1215
|
+
handlers.current.select(node);
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
// One text is one element, so Enter makes a line break; rich text starts a new paragraph.
|
|
1219
|
+
if (event.key === "Enter" && typing?.element.dataset.brimKind === "text") {
|
|
1220
|
+
event.preventDefault();
|
|
1221
|
+
page.execCommand("insertLineBreak");
|
|
1222
|
+
}
|
|
1223
|
+
});
|
|
1224
|
+
/** Whether what is pasted or dropped goes into a text kept on one line, which takes its words alone. */
|
|
1225
|
+
const oneLine = (element: HTMLElement): boolean => element.dataset.brimKind !== "richtext";
|
|
1226
|
+
page.addEventListener("paste", (event) => {
|
|
1227
|
+
const typing = handlers.current.textEdit;
|
|
1228
|
+
if (!typing) return;
|
|
1229
|
+
// Pasted content brings foreign markup: a text keeps its words, rich text the formatting the editor knows.
|
|
1230
|
+
event.preventDefault();
|
|
1231
|
+
insertTransferred(page, readTransfer(event.clipboardData, !oneLine(typing.element)));
|
|
1232
|
+
});
|
|
1233
|
+
// Words selected on the page and dragged: moved within the text being typed, copied from elsewhere.
|
|
1234
|
+
let dragged: Range | null = null;
|
|
1235
|
+
page.addEventListener("dragstart", () => {
|
|
1236
|
+
const selection = page.getSelection();
|
|
1237
|
+
dragged = selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;
|
|
1238
|
+
});
|
|
1239
|
+
page.addEventListener("dragend", () => (dragged = null));
|
|
1240
|
+
page.addEventListener("dragover", (event) => {
|
|
1241
|
+
const typing = handlers.current.textEdit;
|
|
1242
|
+
const into = typing && isElement(event.target) && typing.element.contains(event.target);
|
|
1243
|
+
// Only the text being typed takes a drop; a file dropped anywhere else would open in place of the page.
|
|
1244
|
+
if (!into || event.dataTransfer?.types.includes("Files")) {
|
|
1245
|
+
event.preventDefault();
|
|
1246
|
+
if (event.dataTransfer) event.dataTransfer.dropEffect = "none";
|
|
1247
|
+
}
|
|
1248
|
+
});
|
|
1249
|
+
page.addEventListener("drop", (event) => {
|
|
1250
|
+
// Never the browser's own drop: it would put the dropped markup in as it is, or open a dropped file.
|
|
1251
|
+
event.preventDefault();
|
|
1252
|
+
const typing = handlers.current.textEdit;
|
|
1253
|
+
const from = dragged;
|
|
1254
|
+
dragged = null;
|
|
1255
|
+
if (typing) dropTransferred(typing.element, event, from, !oneLine(typing.element));
|
|
1256
|
+
});
|
|
1257
|
+
|
|
1258
|
+
const pending = reselect.current;
|
|
1259
|
+
reselect.current = null;
|
|
1260
|
+
const again = pending ? page.querySelector<HTMLElement>(`[data-brim-node="${pending}"]`) : null;
|
|
1261
|
+
// A block just added below the fold is brought into view, so the owner sees what was made.
|
|
1262
|
+
const box = again?.getBoundingClientRect();
|
|
1263
|
+
if (again && box && (box.top < 0 || box.bottom > view.innerHeight)) again.scrollIntoView({ block: "center" });
|
|
1264
|
+
setSelected(again);
|
|
1265
|
+
if (reread.current) {
|
|
1266
|
+
reread.current = false;
|
|
1267
|
+
setRevision((count) => count + 1);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// Changes left unsaved last time are still in the draft.
|
|
1272
|
+
useEffect(() => {
|
|
1273
|
+
api.drafts().then(
|
|
1274
|
+
(answer) => setDraftCount(answer.drafts),
|
|
1275
|
+
() => undefined,
|
|
1276
|
+
);
|
|
1277
|
+
}, []);
|
|
1278
|
+
|
|
1279
|
+
// The same shortcuts outside the page: in the toolbar and the side panel, except in a field being typed in.
|
|
1280
|
+
useEffect(() => {
|
|
1281
|
+
const onKeyDown = (event: KeyboardEvent): void => {
|
|
1282
|
+
// From the side panel back to the page, and from anywhere else in the editor to the side panel.
|
|
1283
|
+
if (event.key === PANEL_KEY && !handlers.current.browsing) {
|
|
1284
|
+
event.preventDefault();
|
|
1285
|
+
const panel = document.querySelector(".brim-editor-panel");
|
|
1286
|
+
if (panel?.contains(document.activeElement)) handlers.current.focusPage();
|
|
1287
|
+
else handlers.current.focusPanel();
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
const name = shortcutOf(event);
|
|
1291
|
+
if (!name) return;
|
|
1292
|
+
// The content browser covers the page: undo or save there would change what is out of sight.
|
|
1293
|
+
if (handlers.current.browsing) return;
|
|
1294
|
+
if (name !== "save" && typesItself(event.target)) return;
|
|
1295
|
+
event.preventDefault();
|
|
1296
|
+
handlers.current.shortcut(name);
|
|
1297
|
+
};
|
|
1298
|
+
const onFocusIn = (event: FocusEvent): void => {
|
|
1299
|
+
const field = event.target as HTMLInputElement | null;
|
|
1300
|
+
if (field && (field.tagName === "INPUT" || field.tagName === "TEXTAREA")) valueOnFocus.set(field, field.value);
|
|
1301
|
+
};
|
|
1302
|
+
document.addEventListener("keydown", onKeyDown);
|
|
1303
|
+
document.addEventListener("focusin", onFocusIn);
|
|
1304
|
+
return () => {
|
|
1305
|
+
document.removeEventListener("keydown", onKeyDown);
|
|
1306
|
+
document.removeEventListener("focusin", onFocusIn);
|
|
1307
|
+
};
|
|
1308
|
+
}, []);
|
|
1309
|
+
|
|
1310
|
+
// Leaving with unsaved changes: drafts stay in the draft, but visitors do not see them until someone saves; text
|
|
1311
|
+
// being typed, or a save still on its way, would be lost.
|
|
1312
|
+
useEffect(() => {
|
|
1313
|
+
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
|
|
1314
|
+
if (handlers.current.unsaved()) event.preventDefault();
|
|
1315
|
+
};
|
|
1316
|
+
window.addEventListener("beforeunload", onBeforeUnload);
|
|
1317
|
+
return () => window.removeEventListener("beforeunload", onBeforeUnload);
|
|
1318
|
+
}, []);
|
|
1319
|
+
|
|
1320
|
+
// The Save button is offered from the first word typed, before the text is saved into the drafts.
|
|
1321
|
+
useEffect(() => {
|
|
1322
|
+
const element = textEdit?.element;
|
|
1323
|
+
if (!element) return;
|
|
1324
|
+
const onInput = (): void => setTyped(textEditChanged());
|
|
1325
|
+
element.addEventListener("input", onInput);
|
|
1326
|
+
return () => element.removeEventListener("input", onInput);
|
|
1327
|
+
}, [textEdit]);
|
|
1328
|
+
|
|
1329
|
+
// Read again when the site map opens: templates just added to the code, pages just added through the MCP.
|
|
1330
|
+
useEffect(() => {
|
|
1331
|
+
if (!siteMapOpen) return;
|
|
1332
|
+
api.templates().then(
|
|
1333
|
+
({ templates: list }) => setTemplates(list),
|
|
1334
|
+
() => undefined,
|
|
1335
|
+
);
|
|
1336
|
+
api.pages().then(
|
|
1337
|
+
({ pages: list }) => setPages(list),
|
|
1338
|
+
() => undefined,
|
|
1339
|
+
);
|
|
1340
|
+
}, [siteMapOpen]);
|
|
1341
|
+
|
|
1342
|
+
useEffect(() => {
|
|
1343
|
+
api.pages().then(
|
|
1344
|
+
({ pages: list }) => setPages(list),
|
|
1345
|
+
() => undefined,
|
|
1346
|
+
);
|
|
1347
|
+
}, [path]);
|
|
1348
|
+
|
|
1349
|
+
useEffect(() => {
|
|
1350
|
+
api.types().then(
|
|
1351
|
+
({ types: list }) => setTypes(list),
|
|
1352
|
+
() => undefined,
|
|
1353
|
+
);
|
|
1354
|
+
}, []);
|
|
1355
|
+
|
|
1356
|
+
// Whether the loaded page is an item's page; a page that is not has no template to edit.
|
|
1357
|
+
useEffect(() => {
|
|
1358
|
+
if (types.length === 0) return;
|
|
1359
|
+
let current = true;
|
|
1360
|
+
// The site's languages are waited for: until then a page under a language's prefix would not be recognised.
|
|
1361
|
+
loadSiteInfo()
|
|
1362
|
+
.then((info) => findItemPage(types, path, info.locales ?? null))
|
|
1363
|
+
.then(
|
|
1364
|
+
(found) => {
|
|
1365
|
+
if (!current) return;
|
|
1366
|
+
latestItem.current = found?.item ?? null;
|
|
1367
|
+
setItemPage(found);
|
|
1368
|
+
if (!found) setTemplateMode(false);
|
|
1369
|
+
},
|
|
1370
|
+
() => undefined,
|
|
1371
|
+
);
|
|
1372
|
+
return () => {
|
|
1373
|
+
current = false;
|
|
1374
|
+
};
|
|
1375
|
+
}, [types, path, browsed]);
|
|
1376
|
+
|
|
1377
|
+
// What was being typed belongs to the page it was typed on.
|
|
1378
|
+
useEffect(() => setLiveField(null), [path]);
|
|
1379
|
+
|
|
1380
|
+
// Typing into an element that shows one of the item's fields: the page settings and the field's other elements
|
|
1381
|
+
// on the page follow each keystroke.
|
|
1382
|
+
useEffect(() => {
|
|
1383
|
+
const element = textEdit?.element;
|
|
1384
|
+
if (!element || !isField(element) || isEntry(element) || templateMode) return;
|
|
1385
|
+
const field = element.dataset.brimField ?? "";
|
|
1386
|
+
const onInput = (): void => {
|
|
1387
|
+
const value =
|
|
1388
|
+
element.dataset.brimKind === "richtext" ? { blocks: readBlocks(element) } : element.innerText.trim();
|
|
1389
|
+
setLiveField({ field, value });
|
|
1390
|
+
previewField(field, value, element);
|
|
1391
|
+
};
|
|
1392
|
+
element.addEventListener("input", onInput);
|
|
1393
|
+
return () => element.removeEventListener("input", onInput);
|
|
1394
|
+
}, [textEdit, templateMode]);
|
|
1395
|
+
|
|
1396
|
+
useEffect(() => {
|
|
1397
|
+
const address = path === "/" ? EDIT_PATH : `${EDIT_PATH}${path}`;
|
|
1398
|
+
history.replaceState(null, "", templateMode ? `${address}?template` : address);
|
|
1399
|
+
}, [path, templateMode]);
|
|
1400
|
+
|
|
1401
|
+
const selectedKind = selected ? nodeKinds[selected.dataset.brimKind ?? ""] : undefined;
|
|
1402
|
+
const parent = selected ? parentNodeOf(selected) : null;
|
|
1403
|
+
const pageSeo = loadedSeo?.path === path ? loadedSeo : null;
|
|
1404
|
+
const sitePage = pages.find((page) => page.path === path) ?? {
|
|
1405
|
+
path,
|
|
1406
|
+
visibility: "published" as const,
|
|
1407
|
+
seo: pageSeo?.seo ?? {},
|
|
1408
|
+
};
|
|
1409
|
+
// The page of an item has the item's title, and is public when the item is.
|
|
1410
|
+
const currentPage = itemPage
|
|
1411
|
+
? { ...sitePage, title: itemPage.item.title, visibility: itemPage.item.visibility }
|
|
1412
|
+
: sitePage;
|
|
1413
|
+
const editingContent = selected !== null && isField(selected) && !templateMode;
|
|
1414
|
+
// The item with what is being typed on the page, which the page settings show before it is saved.
|
|
1415
|
+
const shownItem =
|
|
1416
|
+
itemPage && liveField
|
|
1417
|
+
? liveField.field === "title"
|
|
1418
|
+
? { ...itemPage.item, title: String(liveField.value) }
|
|
1419
|
+
: { ...itemPage.item, data: { ...itemPage.item.data, [liveField.field]: liveField.value } }
|
|
1420
|
+
: itemPage?.item;
|
|
1421
|
+
|
|
1422
|
+
// An element showing an item's field uploads like the item form does: to the item's folder, if the owner wants.
|
|
1423
|
+
const itemFolder: MediaFolder | undefined =
|
|
1424
|
+
selected?.dataset.brimItem && selected.dataset.brimItemType
|
|
1425
|
+
? {
|
|
1426
|
+
key: `${selected.dataset.brimItemType}/${selected.dataset.brimItem}`,
|
|
1427
|
+
label: selected.dataset.brimItemTitle ?? selected.dataset.brimItemType,
|
|
1428
|
+
}
|
|
1429
|
+
: undefined;
|
|
1430
|
+
|
|
1431
|
+
// Something the owner opened, as opposed to the page's settings shown when nothing else is: a phone shows only that.
|
|
1432
|
+
// Typing in a text is not asking for its panel: on a phone the panel would cover the text and its toolbar, which
|
|
1433
|
+
// has the same choices (element, alignment).
|
|
1434
|
+
const typingInPlace = textEdit !== null && textEdit.element === selected;
|
|
1435
|
+
const panelAsked =
|
|
1436
|
+
siteSettingsOpen ||
|
|
1437
|
+
historyOpen ||
|
|
1438
|
+
pageSettingsAsked ||
|
|
1439
|
+
Boolean(selected && hasSettings(selected) && !typingInPlace);
|
|
1440
|
+
// The side panel is always there: the selected element's settings, or else the page's, with its item's fields.
|
|
1441
|
+
const sidebar = historyOpen ? (
|
|
1442
|
+
<HistoryPanel
|
|
1443
|
+
path={path}
|
|
1444
|
+
onRestored={() => {
|
|
1445
|
+
// The page is drawn again with what came back; the lists of pages may have a page more.
|
|
1446
|
+
redraw();
|
|
1447
|
+
void refreshPages();
|
|
1448
|
+
}}
|
|
1449
|
+
onClose={() => setHistoryOpen(false)}
|
|
1450
|
+
/>
|
|
1451
|
+
) : siteSettingsOpen ? (
|
|
1452
|
+
<SiteSettings
|
|
1453
|
+
onClose={() => {
|
|
1454
|
+
setSiteSettingsOpen(false);
|
|
1455
|
+
setSettingFocus(undefined);
|
|
1456
|
+
}}
|
|
1457
|
+
focus={settingFocus}
|
|
1458
|
+
onSaved={() => redraw()}
|
|
1459
|
+
canManage={user.role === "owner"}
|
|
1460
|
+
locale={locales ? (localeOfPath(path, locales) ?? locales.defaultLocale) : undefined}
|
|
1461
|
+
onOpenResponses={
|
|
1462
|
+
user.permissions.includes("responses") ? (form) => browse(RESPONSES_FOLDER, false, undefined, form) : undefined
|
|
1463
|
+
}
|
|
1464
|
+
/>
|
|
1465
|
+
) : selected && selected.dataset.brimKind === "listing" ? (
|
|
1466
|
+
<ListingPanel
|
|
1467
|
+
key={`${path} ${selected.dataset.brimNode}`}
|
|
1468
|
+
element={selected}
|
|
1469
|
+
onOpen={(type) => browse(type)}
|
|
1470
|
+
onNew={(type, prefill) => browse(type, true, prefill)}
|
|
1471
|
+
onClose={() => select(null)}
|
|
1472
|
+
/>
|
|
1473
|
+
) : selected && isPickedField(selected) && itemPage && hasSettings(selected) ? (
|
|
1474
|
+
<PickedFieldPanel
|
|
1475
|
+
key={`${path} ${selected.dataset.brimNode} ${revision}`}
|
|
1476
|
+
element={selected}
|
|
1477
|
+
page={itemPage}
|
|
1478
|
+
// The element stays selected once the page is drawn again with the new value.
|
|
1479
|
+
onChange={(before, after) => void changeItemFields(before, after, selected.dataset.brimNode)}
|
|
1480
|
+
onClose={() => select(null)}
|
|
1481
|
+
/>
|
|
1482
|
+
) : selected && selectedKind && hasSettings(selected) ? (
|
|
1483
|
+
<MediaFolderContext.Provider value={itemFolder}>
|
|
1484
|
+
<Inspector
|
|
1485
|
+
key={`${path} ${templateMode} ${selected.dataset.brimNode} ${revision}`}
|
|
1486
|
+
element={selected}
|
|
1487
|
+
kind={selectedKind}
|
|
1488
|
+
note={
|
|
1489
|
+
selected.dataset.brimScope === "site"
|
|
1490
|
+
? "Shared across the site: a change here shows on every page."
|
|
1491
|
+
: templateMode
|
|
1492
|
+
? `Part of the ${typeName} template: a change here shows on every ${typeName}.`
|
|
1493
|
+
: undefined
|
|
1494
|
+
}
|
|
1495
|
+
only={
|
|
1496
|
+
isField(selected) && !isEntry(selected)
|
|
1497
|
+
? (name) => IMAGE_CONTENT.includes(name) !== templateMode
|
|
1498
|
+
: // A bare image is only a picture and its description: there is no frame to shape, size or caption.
|
|
1499
|
+
selected.dataset.brimBare !== undefined
|
|
1500
|
+
? (name) => IMAGE_CONTENT.includes(name)
|
|
1501
|
+
: selected.dataset.brimDrawn !== undefined
|
|
1502
|
+
? (name) => DRAWN_SETTINGS.includes(name)
|
|
1503
|
+
: undefined
|
|
1504
|
+
}
|
|
1505
|
+
onChange={(form) => void changeFromInspector(selected, form)}
|
|
1506
|
+
layout={isEntry(selected) ? entryLayout(selected) : undefined}
|
|
1507
|
+
onReset={editingContent ? undefined : () => void reset(selected)}
|
|
1508
|
+
resetNote={
|
|
1509
|
+
selected.dataset.brimScope === "site"
|
|
1510
|
+
? "This element is shared across the site, so it changes back on every page."
|
|
1511
|
+
: templateMode
|
|
1512
|
+
? `This is part of the ${typeName} template, so it changes back on every ${typeName}.`
|
|
1513
|
+
: "Only this page changes back."
|
|
1514
|
+
}
|
|
1515
|
+
onClose={() => select(null)}
|
|
1516
|
+
/>
|
|
1517
|
+
</MediaFolderContext.Provider>
|
|
1518
|
+
) : templateMode && itemPage ? (
|
|
1519
|
+
<Sidebar title={`${itemPage.type.singular} template`}>
|
|
1520
|
+
<p className="brim-sidebar-note">
|
|
1521
|
+
Select a part of the page to change it on every {typeName}. The {typeName}'s own content stays locked here.
|
|
1522
|
+
</p>
|
|
1523
|
+
</Sidebar>
|
|
1524
|
+
) : (
|
|
1525
|
+
<PageSettings
|
|
1526
|
+
// Drawn afresh once the page turns out to be an item's, so the item's fields start open.
|
|
1527
|
+
key={`${itemPage?.item.id ?? path} ${revision}`}
|
|
1528
|
+
page={currentPage}
|
|
1529
|
+
own={pageSeo?.own}
|
|
1530
|
+
item={
|
|
1531
|
+
itemPage && shownItem
|
|
1532
|
+
? {
|
|
1533
|
+
...itemPage,
|
|
1534
|
+
item: shownItem,
|
|
1535
|
+
onChange: (draft) => void changeItemFields(shownItem, draft),
|
|
1536
|
+
onDraft: (field, value) => previewField(field, value),
|
|
1537
|
+
}
|
|
1538
|
+
: undefined
|
|
1539
|
+
}
|
|
1540
|
+
onChange={(seo) => void changeSeo(seo)}
|
|
1541
|
+
onMove={movePage}
|
|
1542
|
+
onClose={() => setPageSettingsAsked(false)}
|
|
1543
|
+
/>
|
|
1544
|
+
);
|
|
1545
|
+
|
|
1546
|
+
const draftControls: DraftControls = {
|
|
1547
|
+
count: draftCount,
|
|
1548
|
+
typing: typed,
|
|
1549
|
+
saving: savingDrafts,
|
|
1550
|
+
onSave: () => void saveDrafts(),
|
|
1551
|
+
onDiscard: () => void discardDrafts(),
|
|
1552
|
+
onUndo: undoSteps.current.length > 0 ? () => void replay(true) : undefined,
|
|
1553
|
+
onRedo: redoSteps.current.length > 0 ? () => void replay(false) : undefined,
|
|
1554
|
+
};
|
|
1555
|
+
|
|
1556
|
+
return (
|
|
1557
|
+
<EditorProvider value={{ pages, viewport }}>
|
|
1558
|
+
{browsing && (
|
|
1559
|
+
<ContentBrowser
|
|
1560
|
+
pages={pages}
|
|
1561
|
+
initialFolder={browsing.folder}
|
|
1562
|
+
initialCreate={browsing.create}
|
|
1563
|
+
initialData={browsing.data}
|
|
1564
|
+
initialForm={browsing.form}
|
|
1565
|
+
initialResponse={browsing.response}
|
|
1566
|
+
run={run}
|
|
1567
|
+
onBack={leaveBrowser}
|
|
1568
|
+
onEditPage={navigate}
|
|
1569
|
+
onEditTemplate={editTemplate}
|
|
1570
|
+
onPagesChanged={() => void refreshPages()}
|
|
1571
|
+
/>
|
|
1572
|
+
)}
|
|
1573
|
+
{/* The page stays loaded behind the browser, so coming back is instant. */}
|
|
1574
|
+
<div className="brim-editor" hidden={browsing !== null}>
|
|
1575
|
+
<Toolbar
|
|
1576
|
+
user={user}
|
|
1577
|
+
page={currentPage}
|
|
1578
|
+
viewport={viewport}
|
|
1579
|
+
status={status}
|
|
1580
|
+
drafts={draftControls}
|
|
1581
|
+
siteMapOpen={siteMapOpen}
|
|
1582
|
+
pageSettingsOpen={!siteSettingsOpen && !historyOpen && !(selected && hasSettings(selected))}
|
|
1583
|
+
onSiteMap={() => setSiteMapOpen(!siteMapOpen)}
|
|
1584
|
+
onContent={() => browse()}
|
|
1585
|
+
onViewport={(next) => {
|
|
1586
|
+
// A device gives the page its own width again, also the one already chosen.
|
|
1587
|
+
setViewport(next);
|
|
1588
|
+
setFrameWidth(null);
|
|
1589
|
+
}}
|
|
1590
|
+
onVisibility={(visibility) => void changeVisibility(visibility)}
|
|
1591
|
+
onPageSettings={() => {
|
|
1592
|
+
select(null);
|
|
1593
|
+
setSiteSettingsOpen(false);
|
|
1594
|
+
setHistoryOpen(false);
|
|
1595
|
+
setPageSettingsAsked(!pageSettingsAsked);
|
|
1596
|
+
}}
|
|
1597
|
+
onHistory={() => {
|
|
1598
|
+
select(null);
|
|
1599
|
+
setSiteSettingsOpen(false);
|
|
1600
|
+
setHistoryOpen(true);
|
|
1601
|
+
}}
|
|
1602
|
+
onSiteSettings={
|
|
1603
|
+
// The site's own settings (phone, email…) are content; owners also get the form emails and redirects.
|
|
1604
|
+
user.permissions.includes("content")
|
|
1605
|
+
? () => {
|
|
1606
|
+
select(null);
|
|
1607
|
+
setHistoryOpen(false);
|
|
1608
|
+
setSiteSettingsOpen(true);
|
|
1609
|
+
}
|
|
1610
|
+
: undefined
|
|
1611
|
+
}
|
|
1612
|
+
onChangePassword={() => setChangingPassword(true)}
|
|
1613
|
+
onSignOut={() =>
|
|
1614
|
+
void finishTextEdit()
|
|
1615
|
+
.then(() => api.signOut())
|
|
1616
|
+
.then(onSignedOut)
|
|
1617
|
+
}
|
|
1618
|
+
languages={languageChoice}
|
|
1619
|
+
onLanguage={(code, fill) => void switchLanguage(code, fill)}
|
|
1620
|
+
template={
|
|
1621
|
+
itemPage && templateMode
|
|
1622
|
+
? {
|
|
1623
|
+
title: `${itemPage.type.singular} template`,
|
|
1624
|
+
note:
|
|
1625
|
+
itemPage.count === 1
|
|
1626
|
+
? `Changes show on every ${typeName}`
|
|
1627
|
+
: `Changes show on all ${itemPage.count} ${itemPage.type.label.toLowerCase()}`,
|
|
1628
|
+
onDone: () => switchMode(false),
|
|
1629
|
+
}
|
|
1630
|
+
: undefined
|
|
1631
|
+
}
|
|
1632
|
+
onEditTemplate={
|
|
1633
|
+
itemPage && !templateMode && user.permissions.includes("templates") ? () => switchMode(true) : undefined
|
|
1634
|
+
}
|
|
1635
|
+
/>
|
|
1636
|
+
{siteMapOpen && (
|
|
1637
|
+
<SiteMap
|
|
1638
|
+
pages={pages}
|
|
1639
|
+
templates={templates}
|
|
1640
|
+
currentPath={path}
|
|
1641
|
+
onNavigate={navigate}
|
|
1642
|
+
onBrowse={browse}
|
|
1643
|
+
onCreate={createPage}
|
|
1644
|
+
onDelete={deletePage}
|
|
1645
|
+
onClose={() => setSiteMapOpen(false)}
|
|
1646
|
+
/>
|
|
1647
|
+
)}
|
|
1648
|
+
<div
|
|
1649
|
+
ref={setWorkspaceElement}
|
|
1650
|
+
className="brim-editor-workspace"
|
|
1651
|
+
style={
|
|
1652
|
+
sidebarWidth === null ? undefined : ({ "--brim-sidebar-chosen": `${sidebarWidth}px` } as CSSProperties)
|
|
1653
|
+
}
|
|
1654
|
+
>
|
|
1655
|
+
<main ref={setCanvasElement} className="brim-editor-canvas" data-viewport={viewport}>
|
|
1656
|
+
<div
|
|
1657
|
+
ref={setFrameElement}
|
|
1658
|
+
className="brim-editor-frame"
|
|
1659
|
+
style={frameWidth === null ? undefined : { width: frameWidth, flex: "none" }}
|
|
1660
|
+
>
|
|
1661
|
+
{[0, 1].map((slot) => (
|
|
1662
|
+
<iframe
|
|
1663
|
+
key={slot}
|
|
1664
|
+
ref={(element) => {
|
|
1665
|
+
slots.current[slot] = element;
|
|
1666
|
+
if (slot === shown) frame.current = element;
|
|
1667
|
+
}}
|
|
1668
|
+
title={slot === shown ? "Page being edited" : "Page being drawn again"}
|
|
1669
|
+
src={slot === 0 ? initialPath : "about:blank"}
|
|
1670
|
+
data-hidden={slot === shown ? undefined : ""}
|
|
1671
|
+
aria-hidden={slot === shown ? undefined : true}
|
|
1672
|
+
tabIndex={slot === shown ? undefined : -1}
|
|
1673
|
+
onLoad={() => frameLoaded(slot)}
|
|
1674
|
+
/>
|
|
1675
|
+
))}
|
|
1676
|
+
<Chrome
|
|
1677
|
+
hovered={hovered}
|
|
1678
|
+
selected={selected}
|
|
1679
|
+
editing={textEdit?.element ?? null}
|
|
1680
|
+
// A plain text field keeps its words only; rich text fields and everything else take formatting.
|
|
1681
|
+
formatting={!(textEdit && isField(textEdit.element) && textEdit.element.dataset.brimKind === "text")}
|
|
1682
|
+
locked={selected ? lockOf(selected) : undefined}
|
|
1683
|
+
binding={selected ? bindingOf(selected) : undefined}
|
|
1684
|
+
stack={selected ? stackOf(selected) : undefined}
|
|
1685
|
+
inserters={stacks.flatMap((stack) => {
|
|
1686
|
+
// A selected block of the stack gets the +, to add after it; otherwise the stack's end does.
|
|
1687
|
+
const anchor = selected && isEntry(selected) && stack.contains(selected) ? selected : stack;
|
|
1688
|
+
const actions = stackOf(anchor);
|
|
1689
|
+
return actions ? [{ anchor, actions }] : [];
|
|
1690
|
+
})}
|
|
1691
|
+
onTextElement={(tag) => textEdit && void changeTextPresentation(textEdit.element, { as: tag })}
|
|
1692
|
+
onSelectParent={parent ? () => select(parent) : undefined}
|
|
1693
|
+
/>
|
|
1694
|
+
<FrameHandles
|
|
1695
|
+
canvas={canvasElement}
|
|
1696
|
+
frame={frameElement}
|
|
1697
|
+
width={frameWidth}
|
|
1698
|
+
dragging={frameDragging}
|
|
1699
|
+
onWidth={setFrameWidth}
|
|
1700
|
+
onDragging={setFrameDragging}
|
|
1701
|
+
/>
|
|
1702
|
+
</div>
|
|
1703
|
+
</main>
|
|
1704
|
+
{/* Says which element is selected, for those who cannot see the outline; the panel is one key away. */}
|
|
1705
|
+
<div className="brim-visually-hidden" role="status" aria-live="polite">
|
|
1706
|
+
{selected
|
|
1707
|
+
? `${nodeLabel(selected)} selected.${hasSettings(selected) ? " Press F6 for its settings." : ""}`
|
|
1708
|
+
: ""}
|
|
1709
|
+
</div>
|
|
1710
|
+
<div className="brim-editor-panel" data-asked={panelAsked ? "" : undefined}>
|
|
1711
|
+
<SidebarHandle workspace={workspaceElement} width={sidebarWidth} onWidth={setSidebarWidth} />
|
|
1712
|
+
{sidebar}
|
|
1713
|
+
</div>
|
|
1714
|
+
</div>
|
|
1715
|
+
</div>
|
|
1716
|
+
{changingPassword && <ChangePassword onClose={() => setChangingPassword(false)} />}
|
|
1717
|
+
</EditorProvider>
|
|
1718
|
+
);
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
/**
|
|
1722
|
+
* Beside an element showing one of the item's picked values: the field's widget, the same as in the item form. The
|
|
1723
|
+
* page is drawn again with the new value once it is saved.
|
|
1724
|
+
*/
|
|
1725
|
+
function PickedFieldPanel({
|
|
1726
|
+
element,
|
|
1727
|
+
page,
|
|
1728
|
+
onChange,
|
|
1729
|
+
onClose,
|
|
1730
|
+
}: {
|
|
1731
|
+
element: HTMLElement;
|
|
1732
|
+
page: ItemPage;
|
|
1733
|
+
onChange: (before: ItemDraft, after: ItemDraft) => void;
|
|
1734
|
+
onClose: () => void;
|
|
1735
|
+
}) {
|
|
1736
|
+
const name = element.dataset.brimField ?? "";
|
|
1737
|
+
const field = page.type.fields.find((candidate) => candidate.name === name);
|
|
1738
|
+
const { item } = page;
|
|
1739
|
+
return (
|
|
1740
|
+
<Sidebar title={field?.label ?? name} onClose={onClose}>
|
|
1741
|
+
{field ? (
|
|
1742
|
+
<ItemField
|
|
1743
|
+
type={page.type}
|
|
1744
|
+
field={field}
|
|
1745
|
+
value={item.data[name]}
|
|
1746
|
+
onChange={(value) => onChange(item, { ...item, data: { ...item.data, [name]: value } })}
|
|
1747
|
+
/>
|
|
1748
|
+
) : (
|
|
1749
|
+
<p className="brim-sidebar-note">
|
|
1750
|
+
{page.type.singular} has no field "{name}" any more. Its element on the page can be removed from the code.
|
|
1751
|
+
</p>
|
|
1752
|
+
)}
|
|
1753
|
+
<p className="brim-sidebar-note">Saved into this {page.type.singular.toLowerCase()}, like in its form.</p>
|
|
1754
|
+
</Sidebar>
|
|
1755
|
+
);
|
|
1756
|
+
}
|