@perkyzz/emvb 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/THIRD_PARTY_NOTICES.md +32 -0
  4. package/licenses/fontawesome-free.LICENSE +165 -0
  5. package/licenses/lucide-static.LICENSE +43 -0
  6. package/licenses/remixicon.LICENSE +201 -0
  7. package/licenses/tabler-icons.LICENSE +21 -0
  8. package/package.json +76 -4
  9. package/src/admin/access/RequireEditor.tsx +39 -0
  10. package/src/admin/access/role.ts +36 -0
  11. package/src/admin/access/sidebar-shim.ts +108 -0
  12. package/src/admin/api.ts +75 -0
  13. package/src/admin/content-api.ts +210 -0
  14. package/src/admin/editor/Editor.tsx +532 -0
  15. package/src/admin/editor/EditorOverlay.tsx +66 -0
  16. package/src/admin/editor/ShortcutsDialog.tsx +30 -0
  17. package/src/admin/editor/SmallScreenNotice.tsx +21 -0
  18. package/src/admin/editor/TopBar.tsx +243 -0
  19. package/src/admin/editor/canvas/CanvasFrame.tsx +536 -0
  20. package/src/admin/editor/canvas/CanvasTextEdit.tsx +87 -0
  21. package/src/admin/editor/canvas/DeviceBar.tsx +91 -0
  22. package/src/admin/editor/canvas/EmptyCanvas.tsx +49 -0
  23. package/src/admin/editor/canvas/SelectionOverlay.tsx +239 -0
  24. package/src/admin/editor/canvas/canvas-events.ts +245 -0
  25. package/src/admin/editor/canvas/state-preview.ts +19 -0
  26. package/src/admin/editor/canvas/tab-reveal.ts +101 -0
  27. package/src/admin/editor/canvas/vnode-react.tsx +69 -0
  28. package/src/admin/editor/clipboard-store.ts +44 -0
  29. package/src/admin/editor/dialogs.tsx +164 -0
  30. package/src/admin/editor/dnd/drag-stash.ts +27 -0
  31. package/src/admin/editor/dnd/drop-target.ts +148 -0
  32. package/src/admin/editor/dnd/new-element.ts +107 -0
  33. package/src/admin/editor/editor-css.ts +625 -0
  34. package/src/admin/editor/exit.ts +27 -0
  35. package/src/admin/editor/host.ts +30 -0
  36. package/src/admin/editor/icons/IconLibraryDialog.tsx +850 -0
  37. package/src/admin/editor/icons/library.ts +243 -0
  38. package/src/admin/editor/icons/set-format.ts +29 -0
  39. package/src/admin/editor/icons/sets/fontawesome.json +1 -0
  40. package/src/admin/editor/icons/sets/lucide.json +1 -0
  41. package/src/admin/editor/icons/sets/remix.json +1 -0
  42. package/src/admin/editor/icons/sets/tabler.json +1 -0
  43. package/src/admin/editor/panels/AddPanel.tsx +146 -0
  44. package/src/admin/editor/panels/ClassesSection.tsx +372 -0
  45. package/src/admin/editor/panels/ColorControl.tsx +477 -0
  46. package/src/admin/editor/panels/ConditionsEditor.tsx +201 -0
  47. package/src/admin/editor/panels/ElementPanel.tsx +773 -0
  48. package/src/admin/editor/panels/LayersPanel.tsx +573 -0
  49. package/src/admin/editor/panels/LeftPanel.tsx +81 -0
  50. package/src/admin/editor/panels/PageSettings.tsx +255 -0
  51. package/src/admin/editor/panels/SettingsPanel.tsx +113 -0
  52. package/src/admin/editor/panels/SiteStylesDrawer.tsx +548 -0
  53. package/src/admin/editor/panels/TriggerSettings.tsx +132 -0
  54. package/src/admin/editor/panels/TriggersEditor.tsx +214 -0
  55. package/src/admin/editor/panels/VariableSection.tsx +530 -0
  56. package/src/admin/editor/panels/color-space.ts +195 -0
  57. package/src/admin/editor/panels/settings/AdvancedFields.tsx +119 -0
  58. package/src/admin/editor/panels/settings/BackgroundControls.tsx +418 -0
  59. package/src/admin/editor/panels/settings/BackgroundFill.tsx +221 -0
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +271 -0
  61. package/src/admin/editor/panels/settings/ChoiceGroup.tsx +138 -0
  62. package/src/admin/editor/panels/settings/ClassChip.tsx +167 -0
  63. package/src/admin/editor/panels/settings/ClassChipInput.tsx +451 -0
  64. package/src/admin/editor/panels/settings/DraftTextField.tsx +242 -0
  65. package/src/admin/editor/panels/settings/EffectsControls.tsx +354 -0
  66. package/src/admin/editor/panels/settings/FieldBindControl.tsx +119 -0
  67. package/src/admin/editor/panels/settings/FieldControl.tsx +270 -0
  68. package/src/admin/editor/panels/settings/FormBindControl.tsx +106 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +438 -0
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +170 -0
  71. package/src/admin/editor/panels/settings/ItemList.tsx +199 -0
  72. package/src/admin/editor/panels/settings/LengthRow.tsx +217 -0
  73. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +130 -0
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +220 -0
  75. package/src/admin/editor/panels/settings/NumberRow.tsx +154 -0
  76. package/src/admin/editor/panels/settings/StateSwitcher.tsx +87 -0
  77. package/src/admin/editor/panels/settings/StyleRow.tsx +563 -0
  78. package/src/admin/editor/panels/settings/VariableBinding.tsx +171 -0
  79. package/src/admin/editor/panels/settings/advanced-rules.ts +63 -0
  80. package/src/admin/editor/panels/settings/background-mode.ts +112 -0
  81. package/src/admin/editor/panels/settings/box-link-name.ts +38 -0
  82. package/src/admin/editor/panels/settings/box-sides.ts +153 -0
  83. package/src/admin/editor/panels/settings/button-url.ts +27 -0
  84. package/src/admin/editor/panels/settings/class-suggest.ts +53 -0
  85. package/src/admin/editor/panels/settings/form-names.ts +38 -0
  86. package/src/admin/editor/panels/settings/heading-warning.ts +25 -0
  87. package/src/admin/editor/panels/settings/image-alt.ts +25 -0
  88. package/src/admin/editor/panels/settings/length-units.ts +116 -0
  89. package/src/admin/editor/panels/settings/loop-context.ts +26 -0
  90. package/src/admin/editor/panels/settings/node-props.ts +11 -0
  91. package/src/admin/editor/panels/settings/style-sections.ts +394 -0
  92. package/src/admin/editor/panels/settings/svg-images.ts +14 -0
  93. package/src/admin/editor/panels/site-list.tsx +209 -0
  94. package/src/admin/editor/panels/variable-values.ts +73 -0
  95. package/src/admin/editor/restore-deleted.ts +80 -0
  96. package/src/admin/editor/section-templates.ts +50 -0
  97. package/src/admin/editor/shortcuts.ts +20 -0
  98. package/src/admin/editor/store.ts +240 -0
  99. package/src/admin/editor/useClipboardActions.ts +136 -0
  100. package/src/admin/editor/useEditorCommands.ts +203 -0
  101. package/src/admin/editor/useEditorData.ts +193 -0
  102. package/src/admin/editor/useEditorShortcuts.ts +180 -0
  103. package/src/admin/editor/useMediaQuery.ts +20 -0
  104. package/src/admin/editor/useNodeActions.ts +184 -0
  105. package/src/admin/editor/useSave.ts +242 -0
  106. package/src/admin/entry-status.ts +19 -0
  107. package/src/admin/forms-api.ts +73 -0
  108. package/src/admin/icon-uploads-api.ts +44 -0
  109. package/src/admin/index.tsx +20 -0
  110. package/src/admin/media-api.ts +68 -0
  111. package/src/admin/pages/CreateDialog.tsx +150 -0
  112. package/src/admin/pages/EditorPage.tsx +57 -0
  113. package/src/admin/pages/NewPageDialog.tsx +83 -0
  114. package/src/admin/pages/NewThemePartDialog.tsx +61 -0
  115. package/src/admin/pages/PageList.tsx +91 -0
  116. package/src/admin/pages/PagesPage.tsx +25 -0
  117. package/src/admin/pages/SetupShell.tsx +90 -0
  118. package/src/admin/pages/ThemeBuilderPage.tsx +25 -0
  119. package/src/admin/pages/ThemePartList.tsx +221 -0
  120. package/src/admin/pages/list-kit.tsx +125 -0
  121. package/src/admin/setup/plan.ts +150 -0
  122. package/src/admin/setup/run.ts +61 -0
  123. package/src/admin/setup/spec.ts +107 -0
  124. package/src/admin/setup/useSetupStatus.ts +62 -0
  125. package/src/admin/theme-api.ts +233 -0
  126. package/src/admin/ui.ts +244 -0
  127. package/src/admin/widgets/LayoutField.tsx +67 -0
  128. package/src/astro/EmVBPage.astro +63 -0
  129. package/src/astro/env.d.ts +5 -0
  130. package/src/astro/floats/EmVBFloatsRuntime.astro +9 -0
  131. package/src/astro/floats/index.ts +1 -0
  132. package/src/astro/floats/runtime.ts +78 -0
  133. package/src/astro/forms/EmVBFormsRuntime.astro +9 -0
  134. package/src/astro/forms/index.ts +1 -0
  135. package/src/astro/forms-definitions.ts +126 -0
  136. package/src/astro/index.ts +16 -0
  137. package/src/astro/menu/EmVBMenuRuntime.astro +9 -0
  138. package/src/astro/menu/index.ts +1 -0
  139. package/src/astro/menu/runtime.ts +37 -0
  140. package/src/astro/popups/EmVBPopupsRuntime.astro +9 -0
  141. package/src/astro/popups/index.ts +1 -0
  142. package/src/astro/popups/runtime.ts +296 -0
  143. package/src/astro/render.ts +108 -0
  144. package/src/astro/resolve-theme.ts +515 -0
  145. package/src/astro/resolve.ts +65 -0
  146. package/src/astro/tabs/EmVBTabsRuntime.astro +10 -0
  147. package/src/astro/tabs/index.ts +1 -0
  148. package/src/astro/tabs/runtime.ts +116 -0
  149. package/src/astro/theme-context.ts +89 -0
  150. package/src/astro/theme-posts.ts +84 -0
  151. package/src/constants.ts +12 -0
  152. package/src/core/arrange.ts +448 -0
  153. package/src/core/clipboard.ts +504 -0
  154. package/src/core/css/generate.ts +236 -0
  155. package/src/core/css/scope.ts +88 -0
  156. package/src/core/design/cascade.ts +28 -0
  157. package/src/core/design/classes.ts +224 -0
  158. package/src/core/design/devices.ts +56 -0
  159. package/src/core/design/states.ts +49 -0
  160. package/src/core/design/transfer.ts +132 -0
  161. package/src/core/design/variables.ts +359 -0
  162. package/src/core/elements/definition.ts +12 -0
  163. package/src/core/elements/dynamic-elements.ts +225 -0
  164. package/src/core/elements/field-id.ts +6 -0
  165. package/src/core/elements/form-elements.ts +219 -0
  166. package/src/core/elements/index.ts +960 -0
  167. package/src/core/elements/menu.ts +190 -0
  168. package/src/core/elements/plain-text.ts +32 -0
  169. package/src/core/forms/binding.ts +61 -0
  170. package/src/core/forms/definition.ts +45 -0
  171. package/src/core/forms/success-layout.ts +63 -0
  172. package/src/core/icons/catalog.ts +273 -0
  173. package/src/core/index.ts +380 -0
  174. package/src/core/limits.ts +9 -0
  175. package/src/core/migrate/index.ts +126 -0
  176. package/src/core/nesting.ts +51 -0
  177. package/src/core/render/context.ts +21 -0
  178. package/src/core/render/dynamic-post.ts +175 -0
  179. package/src/core/render/extras.ts +98 -0
  180. package/src/core/render/form.ts +235 -0
  181. package/src/core/render/index.ts +372 -0
  182. package/src/core/render/loop.ts +43 -0
  183. package/src/core/render/pagination.ts +76 -0
  184. package/src/core/render/section.ts +37 -0
  185. package/src/core/render/tabs.ts +76 -0
  186. package/src/core/render/vnode.ts +87 -0
  187. package/src/core/sanitize/css.ts +771 -0
  188. package/src/core/sanitize/embed-url.ts +160 -0
  189. package/src/core/sanitize/escape.ts +10 -0
  190. package/src/core/sanitize/href.ts +6 -0
  191. package/src/core/sanitize/media-url.ts +7 -0
  192. package/src/core/sanitize/svg-upload.ts +203 -0
  193. package/src/core/sanitize/svg.ts +374 -0
  194. package/src/core/sanitize/url.ts +31 -0
  195. package/src/core/schema/descriptors.ts +37 -0
  196. package/src/core/schema/design.ts +93 -0
  197. package/src/core/schema/layout.ts +1008 -0
  198. package/src/core/schema/state-names.ts +4 -0
  199. package/src/core/schema/style.ts +336 -0
  200. package/src/core/stats.ts +18 -0
  201. package/src/core/tabs/presence.ts +25 -0
  202. package/src/core/theme/conditions.ts +324 -0
  203. package/src/core/theme/dynamic.ts +143 -0
  204. package/src/core/theme/float.ts +113 -0
  205. package/src/core/theme/pagination.ts +97 -0
  206. package/src/core/theme/parse-doc.ts +36 -0
  207. package/src/core/theme/part-types.ts +81 -0
  208. package/src/core/theme/popup-markup.ts +41 -0
  209. package/src/core/theme/popup-rules.ts +62 -0
  210. package/src/core/theme/triggers.ts +104 -0
  211. package/src/core/tree-ops.ts +139 -0
  212. package/src/core/validate.ts +185 -0
  213. package/src/index.ts +18 -0
  214. package/src/server/design-routes.ts +125 -0
  215. package/src/server/hooks.ts +118 -0
  216. package/src/server/icon-routes.ts +79 -0
  217. package/src/server/plugin.ts +43 -0
@@ -0,0 +1,39 @@
1
+ import { Banner, Empty, Loader } from "@cloudflare/kumo";
2
+ import { LockKeyIcon, WarningCircleIcon } from "@phosphor-icons/react";
3
+ import type * as React from "react";
4
+ import type { Fetcher } from "../api.ts";
5
+ import { canUseEmvb, useRole } from "./role.ts";
6
+
7
+ /** Renders `children` for editors and above, and a "no access" state below (D-020, D-024). */
8
+ export function RequireEditor({
9
+ fetcher,
10
+ children,
11
+ }: {
12
+ fetcher: Fetcher;
13
+ children: (role: number) => React.ReactNode;
14
+ }) {
15
+ const status = useRole(fetcher);
16
+ if (status.state === "loading") return <Loader />;
17
+ if (status.state === "error") {
18
+ return (
19
+ <Banner
20
+ variant="error"
21
+ icon={<WarningCircleIcon aria-hidden="true" />}
22
+ title="Couldn't check your access to EmVB"
23
+ description={status.message}
24
+ />
25
+ );
26
+ }
27
+ if (!canUseEmvb(status.role)) {
28
+ return (
29
+ <section data-emvb-access="denied">
30
+ <Empty
31
+ icon={<LockKeyIcon size={32} aria-hidden="true" />}
32
+ title="You don't have access to EmVB"
33
+ description="Visual pages are managed by editors and administrators. Ask an administrator if you need access."
34
+ />
35
+ </section>
36
+ );
37
+ }
38
+ return children(status.role);
39
+ }
@@ -0,0 +1,36 @@
1
+ import * as React from "react";
2
+ import { EDITOR_ROLE } from "../../constants.ts";
3
+ import { requestJson, type Fetcher } from "../api.ts";
4
+
5
+ export async function readRole(fetcher: Fetcher): Promise<number> {
6
+ const me = await requestJson<{ role?: unknown } | undefined>(fetcher, "/_emdash/api/auth/me");
7
+ return typeof me?.role === "number" ? me.role : 0;
8
+ }
9
+
10
+ /** D-020: EmVB is for editors and administrators. The server enforces the same line. */
11
+ export const canUseEmvb = (role: number) => role >= EDITOR_ROLE;
12
+
13
+ type RoleState =
14
+ | { state: "loading" }
15
+ | { state: "ready"; role: number }
16
+ | { state: "error"; message: string };
17
+
18
+ export function useRole(fetcher: Fetcher): RoleState {
19
+ const [status, setStatus] = React.useState<RoleState>({ state: "loading" });
20
+ React.useEffect(() => {
21
+ let active = true;
22
+ readRole(fetcher).then(
23
+ (role) => active && setStatus({ state: "ready", role }),
24
+ (error: unknown) =>
25
+ active &&
26
+ setStatus({
27
+ state: "error",
28
+ message: error instanceof Error ? error.message : String(error),
29
+ }),
30
+ );
31
+ return () => {
32
+ active = false;
33
+ };
34
+ }, [fetcher]);
35
+ return status;
36
+ }
@@ -0,0 +1,108 @@
1
+ import { EDITOR_ROLE, PLUGIN_ID } from "../../constants.ts";
2
+ import type { Fetcher } from "../api.ts";
3
+ import { readRole } from "./role.ts";
4
+
5
+ const SHIM_ID = "emvb-sidebar-shim";
6
+ const PAGES_HREF = `/_emdash/admin/plugins/${PLUGIN_ID}/pages`;
7
+ const THEME_HREF = `/_emdash/admin/plugins/${PLUGIN_ID}/theme`;
8
+ const SHIM_CSS = `.emdash-sidebar a[href$="${PAGES_HREF}"], .emdash-sidebar a[href$="${THEME_HREF}"] { display: none !important; }`;
9
+ const SECTION_LABEL = "EmVB";
10
+
11
+ let shownRole: number | null = null;
12
+
13
+ function sidebarOf(doc: Document) {
14
+ return doc.querySelector(".emdash-sidebar");
15
+ }
16
+
17
+ function linkIn(sidebar: Element, href: string) {
18
+ return sidebar.querySelector(`a[href$="${href}"]`);
19
+ }
20
+
21
+ /** EmDash 1.0.1 puts every plugin page in one Plugins group. Move EmVB's links into their own group. */
22
+ export function placeEmvbSection(doc: Document) {
23
+ const sidebar = sidebarOf(doc);
24
+ if (!sidebar) return;
25
+ const pages = linkIn(sidebar, PAGES_HREF);
26
+ if (!pages) return;
27
+ const pluginsGroup = pages.closest("[data-sidebar=group]");
28
+ if (!(pluginsGroup instanceof HTMLElement)) return;
29
+
30
+ let section = sidebar.querySelector("[data-emvb-nav]");
31
+ if (!(section instanceof HTMLElement)) {
32
+ section = doc.createElement("div");
33
+ section.setAttribute("data-sidebar", "group");
34
+ section.setAttribute("data-emvb-nav", "");
35
+ section.className = pluginsGroup.className;
36
+ const existingLabel = pluginsGroup.querySelector("[data-sidebar=group-label]");
37
+ const label =
38
+ existingLabel instanceof HTMLElement
39
+ ? existingLabel.cloneNode(true)
40
+ : doc.createElement("div");
41
+ if (label instanceof HTMLElement) {
42
+ if (!existingLabel) label.setAttribute("data-sidebar", "group-label");
43
+ const text = [...label.querySelectorAll("div")].find((node) => node.childElementCount === 0);
44
+ if (text) text.textContent = SECTION_LABEL;
45
+ else label.textContent = SECTION_LABEL;
46
+ section.append(label);
47
+ }
48
+ const existingMenu = pluginsGroup.querySelector("[data-sidebar=menu]");
49
+ const menu = doc.createElement("ul");
50
+ menu.setAttribute("data-sidebar", "menu");
51
+ if (existingMenu instanceof HTMLElement) menu.className = existingMenu.className;
52
+ section.append(menu);
53
+ pluginsGroup.before(section);
54
+ }
55
+
56
+ const menu = section.querySelector("[data-sidebar=menu]");
57
+ if (!menu) return;
58
+ for (const href of [PAGES_HREF, THEME_HREF]) {
59
+ const link = linkIn(sidebar, href);
60
+ const item = link?.closest("[data-sidebar=menu-item]") ?? link;
61
+ if (item && item.parentElement !== menu) menu.append(item);
62
+ }
63
+ }
64
+
65
+ /** `null` means the role isn't known yet: the link stays hidden so it never flashes for lower roles. */
66
+ export function applySidebarShim(doc: Document, role: number | null) {
67
+ const existing = doc.getElementById(SHIM_ID);
68
+ if (role !== null && role >= EDITOR_ROLE) {
69
+ existing?.remove();
70
+ return;
71
+ }
72
+ if (existing) return;
73
+ const style = doc.createElement("style");
74
+ style.id = SHIM_ID;
75
+ style.textContent = SHIM_CSS;
76
+ doc.head.append(style);
77
+ }
78
+
79
+ /**
80
+ * D-024 (b), until EmDash can role-gate plugin pages: hide EmVB sidebar links below editor.
81
+ * Cosmetic only; the pages and routes enforce access. If the role can't be read, the links
82
+ * are shown again rather than lost for editors.
83
+ */
84
+ function watchSidebar(doc: Document) {
85
+ if (doc.documentElement.dataset["emvbSidebarWatch"] === "1") return;
86
+ doc.documentElement.dataset["emvbSidebarWatch"] = "1";
87
+ const observer = new MutationObserver((records) => {
88
+ if (shownRole === null || shownRole < EDITOR_ROLE) return;
89
+ const sidebar = sidebarOf(doc);
90
+ if (!sidebar) return;
91
+ const inside = records.some((record) => sidebar.contains(record.target));
92
+ if (inside) placeEmvbSection(doc);
93
+ });
94
+ observer.observe(doc.body, { childList: true, subtree: true });
95
+ }
96
+
97
+ export async function installSidebarShim(doc: Document, fetcher: Fetcher) {
98
+ shownRole = null;
99
+ applySidebarShim(doc, null);
100
+ watchSidebar(doc);
101
+ try {
102
+ shownRole = await readRole(fetcher);
103
+ } catch {
104
+ shownRole = EDITOR_ROLE;
105
+ }
106
+ applySidebarShim(doc, shownRole);
107
+ if (shownRole >= EDITOR_ROLE) placeEmvbSection(doc);
108
+ }
@@ -0,0 +1,75 @@
1
+ import { apiFetch } from "emdash/plugin-utils";
2
+
3
+ export type Fetcher = (path: string, init?: RequestInit) => Promise<Response>;
4
+
5
+ export class ApiError extends Error {
6
+ constructor(
7
+ readonly status: number,
8
+ readonly code: string,
9
+ message: string,
10
+ ) {
11
+ super(message);
12
+ this.name = "ApiError";
13
+ }
14
+ }
15
+
16
+ /** `apiFetch` adds the `X-EmDash-Request` header private EmDash routes require (CSRF guard). */
17
+ export const defaultFetcher: Fetcher = (path, init) => apiFetch(path, init);
18
+
19
+ type Envelope<T> = { data?: T; error?: { code?: string; message?: string } };
20
+
21
+ /** The JSON envelope of an EmDash API response, or `{}` when the body isn't JSON. */
22
+ export async function readEnvelope<T>(response: Response): Promise<Envelope<T>> {
23
+ return (await response.json().catch(() => ({}))) as Envelope<T>;
24
+ }
25
+
26
+ /** The ApiError for a failed response, from its envelope's code and message when present. */
27
+ export const envelopeError = (response: Response, envelope: Envelope<unknown>) =>
28
+ new ApiError(
29
+ response.status,
30
+ envelope.error?.code ?? "HTTP_ERROR",
31
+ envelope.error?.message ?? response.statusText,
32
+ );
33
+
34
+ export async function requestJson<T>(
35
+ fetcher: Fetcher,
36
+ path: string,
37
+ init?: { method?: string; body?: unknown },
38
+ ): Promise<T> {
39
+ const response = await fetcher(path, {
40
+ method: init?.method ?? "GET",
41
+ ...(init?.body === undefined
42
+ ? {}
43
+ : { headers: { "content-type": "application/json" }, body: JSON.stringify(init.body) }),
44
+ });
45
+ const payload = await readEnvelope<T>(response);
46
+ if (!response.ok) throw envelopeError(response, payload);
47
+ return payload.data as T;
48
+ }
49
+
50
+ const LIST_PAGE = 50;
51
+ /** Enough for any real site (1000 entries); stops a cursor that never ends. */
52
+ const LIST_MAX_PAGES = 20;
53
+
54
+ /**
55
+ * Every entry of a content list, newest first, page by page (W-204): one request used to stop at
56
+ * the 50 most recently updated, so older pages and parts never showed in the lists.
57
+ */
58
+ export async function listAllItems<T>(fetcher: Fetcher, collectionPath: string): Promise<T[]> {
59
+ const items: T[] = [];
60
+ let cursor: string | undefined;
61
+ for (let page = 0; page < LIST_MAX_PAGES; page += 1) {
62
+ const query = `?limit=${LIST_PAGE}&orderBy=updatedAt&order=desc${
63
+ cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""
64
+ }`;
65
+ // oxlint-disable-next-line no-await-in-loop -- each page needs the previous page's cursor
66
+ const body = await requestJson<{ items?: T[]; nextCursor?: string }>(
67
+ fetcher,
68
+ `${collectionPath}${query}`,
69
+ );
70
+ items.push(...(body?.items ?? []));
71
+ cursor = body?.nextCursor || undefined;
72
+ if (!cursor) break;
73
+ }
74
+ return items;
75
+ }
@@ -0,0 +1,210 @@
1
+ import type {
2
+ ConditionsDoc,
3
+ DesignSystem,
4
+ FloatSettings,
5
+ Layout,
6
+ ThemePartType,
7
+ TriggersDoc,
8
+ } from "../core/index.ts";
9
+ import { PAGES_COLLECTION, PLUGIN_ID } from "../constants.ts";
10
+ import { listAllItems, requestJson, type Fetcher } from "./api.ts";
11
+ import { entryStatus } from "./entry-status.ts";
12
+
13
+ const CONTENT = `/_emdash/api/content/${PAGES_COLLECTION}`;
14
+
15
+ type RawItem = {
16
+ id: string;
17
+ slug?: string | null;
18
+ status?: string;
19
+ draftRevisionId?: string | null;
20
+ updatedAt?: string;
21
+ data?: Record<string, unknown>;
22
+ seo?: {
23
+ title?: string | null;
24
+ description?: string | null;
25
+ canonical?: string | null;
26
+ noIndex?: boolean | null;
27
+ image?: string | null;
28
+ } | null;
29
+ };
30
+
31
+ export type PageSummary = {
32
+ id: string;
33
+ title: string;
34
+ slug: string;
35
+ status: string;
36
+ updatedAt: string;
37
+ };
38
+
39
+ const titleOf = (item: RawItem) =>
40
+ typeof item.data?.["title"] === "string" && item.data["title"]
41
+ ? item.data["title"]
42
+ : "Untitled page";
43
+
44
+ export async function listPages(fetcher: Fetcher): Promise<PageSummary[]> {
45
+ const items = await listAllItems<RawItem>(fetcher, CONTENT);
46
+ return items.map((item) => ({
47
+ id: item.id,
48
+ title: titleOf(item),
49
+ slug: item.slug ?? "",
50
+ status: entryStatus(item),
51
+ updatedAt: item.updatedAt ?? "",
52
+ }));
53
+ }
54
+
55
+ export async function createPage(
56
+ fetcher: Fetcher,
57
+ input: { title: string; slug: string; layout: Layout },
58
+ ): Promise<string> {
59
+ const body = await requestJson<{ item: RawItem }>(fetcher, CONTENT, {
60
+ method: "POST",
61
+ body: { data: { title: input.title, layout: input.layout }, slug: input.slug },
62
+ });
63
+ return body.item.id;
64
+ }
65
+
66
+ export type PageDraft = {
67
+ title: string;
68
+ slug: string;
69
+ canvasMode: string;
70
+ seoTitle: string;
71
+ seoDescription: string;
72
+ /** W-284: absolute http(s) URL, or "" for none. Absent = leave the saved value alone. */
73
+ seoCanonical?: string;
74
+ /** W-284: ask search engines not to index the page. Absent = leave the saved value alone. */
75
+ seoNoIndex?: boolean;
76
+ /**
77
+ * W-287: social (OG) image as EmDash reads it: an absolute URL or a site path (the media
78
+ * library's `/_emdash/api/media/file/…`); "" for none. Absent = leave the saved value alone.
79
+ */
80
+ seoImage?: string;
81
+ layout: Layout | null;
82
+ /** Theme parts only (emvb_theme_parts). */
83
+ partType?: ThemePartType;
84
+ conditions?: ConditionsDoc;
85
+ /** Popups only — open triggers + thin advanced rules. */
86
+ triggers?: TriggersDoc;
87
+ /** Floats only — edge and whether a close button is offered. */
88
+ float?: FloatSettings;
89
+ };
90
+
91
+ /**
92
+ * W-284: EmDash accepts only an absolute http(s) canonical URL (or null) and refuses the whole
93
+ * save otherwise, so the panel flags anything else and the save leaves the stored one alone.
94
+ */
95
+ export function canonicalProblem(value: string): string | null {
96
+ const trimmed = value.trim();
97
+ if (!trimmed) return null;
98
+ try {
99
+ const url = new URL(trimmed);
100
+ if (url.protocol === "https:" || url.protocol === "http:") return null;
101
+ } catch {
102
+ // fall through
103
+ }
104
+ return "Not saved: use a full address starting with https://";
105
+ }
106
+
107
+ function seoBody(draft: PageDraft) {
108
+ const canonical = draft.seoCanonical;
109
+ return {
110
+ title: draft.seoTitle || null,
111
+ description: draft.seoDescription || null,
112
+ ...(canonical !== undefined && !canonicalProblem(canonical)
113
+ ? { canonical: canonical.trim() || null }
114
+ : {}),
115
+ ...(draft.seoNoIndex !== undefined ? { noIndex: draft.seoNoIndex } : {}),
116
+ ...(draft.seoImage !== undefined ? { image: draft.seoImage.trim() || null } : {}),
117
+ };
118
+ }
119
+
120
+ /** Saves the draft with `_rev`, so a concurrent change fails with 409 instead of being overwritten. */
121
+ export async function savePage(
122
+ fetcher: Fetcher,
123
+ id: string,
124
+ draft: PageDraft,
125
+ rev: string | null,
126
+ ): Promise<string> {
127
+ const body = await requestJson<{ _rev: string }>(
128
+ fetcher,
129
+ `${CONTENT}/${encodeURIComponent(id)}`,
130
+ {
131
+ method: "PUT",
132
+ body: {
133
+ data: { title: draft.title, layout: draft.layout, canvas_mode: draft.canvasMode },
134
+ slug: draft.slug,
135
+ seo: seoBody(draft),
136
+ ...(rev ? { _rev: rev } : {}),
137
+ },
138
+ },
139
+ );
140
+ return body["_rev"];
141
+ }
142
+
143
+ /** Publishes entry `id` of the collection at `contentPath`, sending `rev` so a stale draft fails. */
144
+ export async function publishEntry(
145
+ fetcher: Fetcher,
146
+ contentPath: string,
147
+ id: string,
148
+ rev: string | null,
149
+ ) {
150
+ const body = await requestJson<{ _rev: string; item: { slug?: string | null } }>(
151
+ fetcher,
152
+ `${contentPath}/${encodeURIComponent(id)}/publish`,
153
+ { method: "POST", body: rev ? { _rev: rev } : {} },
154
+ );
155
+ return { rev: body["_rev"], slug: body.item.slug ?? "" };
156
+ }
157
+
158
+ /**
159
+ * Drops the saved draft of entry `id` so it is back to its published version (W-193). EmDash's
160
+ * `discard-draft` checks `rev`, so a draft saved elsewhere meanwhile fails with 409.
161
+ */
162
+ export async function discardDraft(
163
+ fetcher: Fetcher,
164
+ collection: string,
165
+ id: string,
166
+ rev: string | null,
167
+ ): Promise<void> {
168
+ await requestJson<unknown>(
169
+ fetcher,
170
+ `/_emdash/api/content/${encodeURIComponent(collection)}/${encodeURIComponent(id)}/discard-draft`,
171
+ { method: "POST", body: rev === null ? {} : { _rev: rev } },
172
+ );
173
+ }
174
+
175
+ export const publishPage = (fetcher: Fetcher, id: string, rev: string | null) =>
176
+ publishEntry(fetcher, CONTENT, id, rev);
177
+
178
+ export async function previewUrl(fetcher: Fetcher, id: string): Promise<string> {
179
+ const body = await requestJson<{ url: string }>(
180
+ fetcher,
181
+ `${CONTENT}/${encodeURIComponent(id)}/preview-url`,
182
+ { method: "POST", body: {} },
183
+ );
184
+ return body.url;
185
+ }
186
+
187
+ export async function saveDesign(
188
+ fetcher: Fetcher,
189
+ design: DesignSystem,
190
+ revision: string | null,
191
+ ): Promise<string> {
192
+ const body = await requestJson<{ revision: string }>(
193
+ fetcher,
194
+ `/_emdash/api/plugins/${PLUGIN_ID}/design/save`,
195
+ { method: "POST", body: { design, revision } },
196
+ );
197
+ return body.revision;
198
+ }
199
+
200
+ export async function publishDesign(
201
+ fetcher: Fetcher,
202
+ publishedRevision: string | null,
203
+ ): Promise<string> {
204
+ const body = await requestJson<{ revision: string }>(
205
+ fetcher,
206
+ `/_emdash/api/plugins/${PLUGIN_ID}/design/publish`,
207
+ { method: "POST", body: { publishedRevision } },
208
+ );
209
+ return body.revision;
210
+ }