@sindingmind/cms-astro 0.0.0-stage → 0.1.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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +203 -2
- package/dist/attrs.d.ts +48 -0
- package/dist/attrs.js +26 -0
- package/dist/bridge.d.ts +8 -0
- package/dist/bridge.js +269 -0
- package/dist/content.d.ts +16 -0
- package/dist/content.js +36 -0
- package/dist/editing-flag.d.ts +8 -0
- package/dist/editing-flag.js +61 -0
- package/dist/fields.d.ts +237 -0
- package/dist/fields.js +140 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +64 -0
- package/dist/schema.d.ts +39 -0
- package/dist/schema.js +88 -0
- package/package.json +74 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@sindingmind/cms-astro`. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
4
|
+
and versions follow [Semantic Versioning](https://semver.org/). Before 1.0.0, a minor version may break the API.
|
|
5
|
+
|
|
6
|
+
## [0.1.0] - 2026-11-16
|
|
7
|
+
|
|
8
|
+
First public release.
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Field definitions (`defineCms`, `f.text`, `f.number`, `f.image`, `f.group`, `f.list`, `f.textList`) with optional
|
|
13
|
+
fields, placeholders, list limits, ids, defaults and position numbers (`orderField`).
|
|
14
|
+
- Zod schemas from the definitions (`objectOf`, `schemaOf`, `toZod`) with Danish validation messages, and data types
|
|
15
|
+
worked out from the fields.
|
|
16
|
+
- Astro content collections from the config (`cmsCollection`) for folder collections, single files and root lists,
|
|
17
|
+
plus `entryOf` and `inFileOrder` for root lists.
|
|
18
|
+
- Attribute helpers (`field`, `list`, `item`, `image`, `fokus`) and `isCmsEditing()`.
|
|
19
|
+
- The Astro integration: in `astro dev` with `CMS_PREVIEW=1` it marks the page, turns CSS motion off and loads the
|
|
20
|
+
editor bridge; in a build it folds `isCmsEditing()` calls to `false` and adds nothing else.
|
|
21
|
+
- Published as JavaScript with `.d.ts` files, with npm provenance.
|
|
22
|
+
|
|
23
|
+
[0.1.0]: https://github.com/sinding-mind/cms-astro/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sinding Mind ApS
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sindingmind/cms-astro
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The open part of the Sinding Mind CMS, a click-to-edit CMS for static [Astro](https://astro.build) sites.
|
|
4
|
+
|
|
5
|
+
Editable texts, lists and images live in YAML files with a schema in the site's own repository. This package gives a
|
|
6
|
+
site everything it needs to **build** with that content, and to **mark** its pages for a visual editor:
|
|
7
|
+
|
|
8
|
+
- field definitions (`defineCms`, `f.*`) and the Zod schemas built from them, with typed data in `getEntry()` and
|
|
9
|
+
`getCollection()`,
|
|
10
|
+
- Astro content collections from the same config (`cmsCollection`),
|
|
11
|
+
- attribute helpers for templates (`field`, `list`, `item`, `image`) and `isCmsEditing()` for client scripts,
|
|
12
|
+
- an Astro integration that, only in a preview (`astro dev` with `CMS_PREVIEW=1`), marks the page and loads a small
|
|
13
|
+
bridge script for the editor.
|
|
14
|
+
|
|
15
|
+
In a production build the package adds nothing: the HTML and every file in `dist/` are byte for byte what the site
|
|
16
|
+
would be without it.
|
|
17
|
+
|
|
18
|
+
The editor itself (the editing UI, the preview runner, the file API, image processing, login and publishing) is a
|
|
19
|
+
**separate, closed service** run by Sinding Mind ApS. It is not in this package and not needed to build a site. A
|
|
20
|
+
site that stops using the service keeps building with `astro build` as before.
|
|
21
|
+
|
|
22
|
+
MIT licensed. The validation messages are in Danish, because the editor is.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install --save-exact @sindingmind/cms-astro
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Needs Astro 7.3 or newer (a peer dependency). Pin the exact version and update it deliberately.
|
|
31
|
+
|
|
32
|
+
## Use
|
|
33
|
+
|
|
34
|
+
### 1. `cms.config.ts`: what may be edited
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { defineCms, f } from "@sindingmind/cms-astro/schema";
|
|
38
|
+
|
|
39
|
+
export default defineCms({
|
|
40
|
+
site: "Example Co.",
|
|
41
|
+
collections: {
|
|
42
|
+
pages: {
|
|
43
|
+
label: "Sider",
|
|
44
|
+
dir: "src/content/pages", // a folder: every *.yaml in it is one entry
|
|
45
|
+
fields: {
|
|
46
|
+
hero: f.group("Toppen af siden", {
|
|
47
|
+
heading: f.text("Overskrift", { max: 60 }),
|
|
48
|
+
lead: f.text("Indledning", { max: 220, multiline: true, optional: true }),
|
|
49
|
+
points: f.textList("Punkter", "Punkt", { max: 60 }, { min: 1, max: 5 }),
|
|
50
|
+
photo: f.image("Foto", { altMax: 200 }),
|
|
51
|
+
}),
|
|
52
|
+
prices: f.list("Priser", "Pris", {
|
|
53
|
+
name: f.text("Navn", { max: 40 }),
|
|
54
|
+
amount: f.number("Beløb", { min: 0 }),
|
|
55
|
+
}, { min: 1, max: 4, titleField: "name" }),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
faq: {
|
|
59
|
+
label: "Spørgsmål",
|
|
60
|
+
dir: "src/content",
|
|
61
|
+
file: "faq.yaml", // one file
|
|
62
|
+
root: "list", // the file is a list at the top level (`- id: ...`)
|
|
63
|
+
fields: {
|
|
64
|
+
items: f.list("Spørgsmål", "Spørgsmål", {
|
|
65
|
+
question: f.text("Spørgsmål", { max: 120 }),
|
|
66
|
+
answer: f.text("Svar", { max: 800, placeholders: ["price"] }),
|
|
67
|
+
}, { idField: "id", orderField: "order" }),
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Field types: `f.text`, `f.number`, `f.image`, `f.group`, `f.list` and `f.textList` (a list of plain strings). Options
|
|
75
|
+
include `max`/`min`, `optional`, `multiline`, `help`, `placeholders` (only these `{names}` may appear in a text),
|
|
76
|
+
`inline: false` (edit in the panel only), and for lists `titleField`, `idField`, `defaults`, `plural` and
|
|
77
|
+
`orderField` (a position number kept equal to the item's place in the file).
|
|
78
|
+
|
|
79
|
+
### 2. `src/content.config.ts`: collections from the same config
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { defineCollection } from "astro:content";
|
|
83
|
+
import { z } from "astro/zod";
|
|
84
|
+
import { cmsCollection } from "@sindingmind/cms-astro/content";
|
|
85
|
+
import cms from "../cms.config.ts";
|
|
86
|
+
|
|
87
|
+
export const collections = {
|
|
88
|
+
pages: defineCollection(cmsCollection(cms, "pages")),
|
|
89
|
+
// Fields the CMS does not show are added with `extend`, or Zod drops them.
|
|
90
|
+
faq: defineCollection(cmsCollection(cms, "faq", {
|
|
91
|
+
extend: (s) => s.extend({ order: z.number().int().min(1) }),
|
|
92
|
+
})),
|
|
93
|
+
};
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
A folder collection is `glob("*.yaml")`, a `file` collection is `glob(file)`, and a root list is Astro's `file()`
|
|
97
|
+
loader with the item's schema. The data is typed from the fields, so no casts are needed.
|
|
98
|
+
|
|
99
|
+
### 3. `astro.config.ts`: the integration
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { defineConfig } from "astro/config";
|
|
103
|
+
import cms from "@sindingmind/cms-astro";
|
|
104
|
+
|
|
105
|
+
export default defineConfig({
|
|
106
|
+
output: "static",
|
|
107
|
+
integrations: [cms()],
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Options: `editorOrigin` (the origin allowed to frame and talk to the preview; the `CMS_EDITOR_ORIGIN` environment
|
|
112
|
+
variable wins) and `keepMotion` (keep CSS animations in the preview).
|
|
113
|
+
|
|
114
|
+
### 4. Templates: the attribute helpers
|
|
115
|
+
|
|
116
|
+
```astro
|
|
117
|
+
---
|
|
118
|
+
import { getCollection, getEntry } from "astro:content";
|
|
119
|
+
import { field, list, item, image, fokus } from "@sindingmind/cms-astro/attrs";
|
|
120
|
+
import { entryOf, inFileOrder } from "@sindingmind/cms-astro/schema";
|
|
121
|
+
import cms from "../../cms.config.ts";
|
|
122
|
+
|
|
123
|
+
const page = (await getEntry("pages", "home"))!;
|
|
124
|
+
const { hero } = page.data;
|
|
125
|
+
const faq = entryOf(cms, "faq");
|
|
126
|
+
---
|
|
127
|
+
<h1 {...field(page, "hero.heading")}>{hero.heading}</h1>
|
|
128
|
+
<ul {...list(page, "hero.points")}>
|
|
129
|
+
{hero.points.map((p, i) => <li {...item(page, "hero.points", i)} {...field(page, `hero.points.${i}`)}>{p}</li>)}
|
|
130
|
+
</ul>
|
|
131
|
+
<img src={hero.photo.src.src} alt={hero.photo.alt} style={fokus(hero.photo)} {...image(page, "hero.photo")} />
|
|
132
|
+
<dl {...list(faq, "items")}>
|
|
133
|
+
{inFileOrder(cms, "faq", await getCollection("faq")).map(({ entry, index }) => (
|
|
134
|
+
<div {...item(faq, "items", index)}>
|
|
135
|
+
<dt {...field(faq, `items.${index}.question`)}>{entry.data.question}</dt>
|
|
136
|
+
<dd>{entry.data.answer}</dd>
|
|
137
|
+
</div>
|
|
138
|
+
))}
|
|
139
|
+
</dl>
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Outside the preview every helper returns `{}`. `item()` takes the item's position in the YAML file, not on the page.
|
|
143
|
+
Astro's `getCollection()` does not keep a `file()` list's order, so a root list shown on a page needs `orderField`, and
|
|
144
|
+
`inFileOrder()` sorts the entries and gives each its file position.
|
|
145
|
+
|
|
146
|
+
### 5. Editing mode in client scripts: `isCmsEditing()`
|
|
147
|
+
|
|
148
|
+
In the preview, `<html>` gets `data-cms-editing` before the site's scripts run, CSS animations and transitions finish
|
|
149
|
+
at once, and every `<details>` is opened. JavaScript animations are the site's own job:
|
|
150
|
+
|
|
151
|
+
```astro
|
|
152
|
+
<script>
|
|
153
|
+
import { isCmsEditing } from "@sindingmind/cms-astro/attrs";
|
|
154
|
+
if (!isCmsEditing()) startTypingEffect();
|
|
155
|
+
</script>
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
In a build the integration replaces every call `isCmsEditing()` with the literal `false` in the modules that import
|
|
159
|
+
it, so the check and the helper module disappear from the output, also when several page scripts import it. Call it
|
|
160
|
+
directly; a value use (`const f = isCmsEditing`) or a namespace import still works but is not folded away. For CSS,
|
|
161
|
+
use `html[data-cms-editing] .x { ... }`.
|
|
162
|
+
|
|
163
|
+
## Invariants
|
|
164
|
+
|
|
165
|
+
These are tested on every change (`test/fixture.test.ts`, on a small Astro site with the package installed from the
|
|
166
|
+
files the npm tarball contains):
|
|
167
|
+
|
|
168
|
+
- **A production build is byte-identical to the site without the package.** Every file in `dist/` (names and bytes)
|
|
169
|
+
equals a build with the integration removed, no-op attribute helpers and `isCmsEditing()` written as `false`. No
|
|
170
|
+
`data-cms-*` attribute, no `__CMS__`, no bridge, no editing stylesheet and no chunk with the helpers is built. Two
|
|
171
|
+
builds are also byte-identical to each other.
|
|
172
|
+
- `CMS_PREVIEW=1` has no effect outside `astro dev`.
|
|
173
|
+
- The package has no runtime dependencies, makes no network calls and needs no account. It does not write files.
|
|
174
|
+
|
|
175
|
+
## Security
|
|
176
|
+
|
|
177
|
+
- The preview marks are added only by `astro dev` with `CMS_PREVIEW=1`. Do not expose such a dev server to the
|
|
178
|
+
internet; the closed editor service runs it behind its own login.
|
|
179
|
+
- The bridge (the script injected into the preview) talks to the editor with `postMessage` only. It accepts messages
|
|
180
|
+
only from `window.parent` **and** from the configured editor origin, and only after a handshake that gives it a
|
|
181
|
+
nonce; every later message must carry that nonce. Its own messages go to the editor origin only.
|
|
182
|
+
- Messages are plain data. The bridge never inserts HTML it receives: texts are set with `textContent`, and an element
|
|
183
|
+
that contains other elements (a link, a `<mark>`) is never typed into or patched.
|
|
184
|
+
- The editor origin must be a bare origin (`https://editor.example`); anything else stops the dev server, because it
|
|
185
|
+
is written into an inline script.
|
|
186
|
+
- The overlay lives in a shadow DOM, so the site's CSS cannot reach it.
|
|
187
|
+
|
|
188
|
+
Report vulnerabilities as described in [SECURITY.md](SECURITY.md).
|
|
189
|
+
|
|
190
|
+
## Development
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
npm install
|
|
194
|
+
npm test # builds dist/, then unit tests and the fixture site (production build, types, astro dev)
|
|
195
|
+
npm run typecheck # tsc on the sources and the type tests
|
|
196
|
+
npm pack --dry-run # what would be published
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The package is compiled to JavaScript and `.d.ts` files in `dist/` (`npm run build`, also run by `prepack`). Releases:
|
|
200
|
+
[docs/RELEASING.md](docs/RELEASING.md).
|
|
201
|
+
|
|
202
|
+
## Licence
|
|
203
|
+
|
|
204
|
+
[MIT](LICENSE), Copyright (c) 2026 Sinding Mind ApS.
|
package/dist/attrs.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
type Entry = {
|
|
2
|
+
collection: string;
|
|
3
|
+
id: string;
|
|
4
|
+
};
|
|
5
|
+
/** A text field: the element's text content is the value. */
|
|
6
|
+
export declare const field: (e: Entry, path: string) => {
|
|
7
|
+
"data-cms-field": string;
|
|
8
|
+
} | {
|
|
9
|
+
"data-cms-field"?: undefined;
|
|
10
|
+
};
|
|
11
|
+
/** A list container. Items inside it must use item(). */
|
|
12
|
+
export declare const list: (e: Entry, path: string) => {
|
|
13
|
+
"data-cms-list": string;
|
|
14
|
+
} | {
|
|
15
|
+
"data-cms-list"?: undefined;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* One list item. `index` is the item's position in the YAML file, not on the page: if the template sorts or
|
|
19
|
+
* filters the list, keep the file position (for a root list, the order of getCollection()).
|
|
20
|
+
* For a text list the item is the text, so put both on the element: `{...item(e, "tillid", i)} {...field(e, `tillid.${i}`)}`.
|
|
21
|
+
*/
|
|
22
|
+
export declare const item: (e: Entry, path: string, index: number) => {
|
|
23
|
+
"data-cms-item": string;
|
|
24
|
+
} | {
|
|
25
|
+
"data-cms-item"?: undefined;
|
|
26
|
+
};
|
|
27
|
+
/** An image field ({ src, alt, fokus }). Put it on the <img>. */
|
|
28
|
+
export declare const image: (e: Entry, path: string) => {
|
|
29
|
+
"data-cms-image": string;
|
|
30
|
+
} | {
|
|
31
|
+
"data-cms-image"?: undefined;
|
|
32
|
+
};
|
|
33
|
+
/** CSS object-position for an image's focus point. Used in production too. */
|
|
34
|
+
export declare const fokus: (v: {
|
|
35
|
+
fokus?: {
|
|
36
|
+
x: number;
|
|
37
|
+
y: number;
|
|
38
|
+
};
|
|
39
|
+
}) => string;
|
|
40
|
+
/**
|
|
41
|
+
* True while the page is shown in the CMS editor. For the site's own client scripts: skip JS animations (typing
|
|
42
|
+
* effects, counters, carousels) and show the final text. In a build the integration replaces each call
|
|
43
|
+
* `isCmsEditing()` with the literal `false` in the module that imports it (editing-flag.ts), so the check and this
|
|
44
|
+
* module disappear from the output, also when several page scripts import it. Call it, do not pass it around: a
|
|
45
|
+
* value use is not folded (it still works). (`html[data-cms-editing]` is the same signal for CSS and inline scripts.)
|
|
46
|
+
*/
|
|
47
|
+
export declare const isCmsEditing: () => boolean;
|
|
48
|
+
export {};
|
package/dist/attrs.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Attribute helpers for templates. In a production build they return {} and the HTML is exactly what the
|
|
2
|
+
// template would render without the CMS. Only `astro dev` with CMS_PREVIEW=1 adds data-cms-* attributes.
|
|
3
|
+
import { preview } from "virtual:sinding-cms";
|
|
4
|
+
const ref = (e, path) => `${e.collection}/${e.id}#${path}`;
|
|
5
|
+
/** A text field: the element's text content is the value. */
|
|
6
|
+
export const field = (e, path) => (preview ? { "data-cms-field": ref(e, path) } : {});
|
|
7
|
+
/** A list container. Items inside it must use item(). */
|
|
8
|
+
export const list = (e, path) => (preview ? { "data-cms-list": ref(e, path) } : {});
|
|
9
|
+
/**
|
|
10
|
+
* One list item. `index` is the item's position in the YAML file, not on the page: if the template sorts or
|
|
11
|
+
* filters the list, keep the file position (for a root list, the order of getCollection()).
|
|
12
|
+
* For a text list the item is the text, so put both on the element: `{...item(e, "tillid", i)} {...field(e, `tillid.${i}`)}`.
|
|
13
|
+
*/
|
|
14
|
+
export const item = (e, path, index) => (preview ? { "data-cms-item": ref(e, `${path}.${index}`) } : {});
|
|
15
|
+
/** An image field ({ src, alt, fokus }). Put it on the <img>. */
|
|
16
|
+
export const image = (e, path) => (preview ? { "data-cms-image": ref(e, path) } : {});
|
|
17
|
+
/** CSS object-position for an image's focus point. Used in production too. */
|
|
18
|
+
export const fokus = (v) => `object-position:${v.fokus?.x ?? 50}% ${v.fokus?.y ?? 50}%`;
|
|
19
|
+
/**
|
|
20
|
+
* True while the page is shown in the CMS editor. For the site's own client scripts: skip JS animations (typing
|
|
21
|
+
* effects, counters, carousels) and show the final text. In a build the integration replaces each call
|
|
22
|
+
* `isCmsEditing()` with the literal `false` in the module that imports it (editing-flag.ts), so the check and this
|
|
23
|
+
* module disappear from the output, also when several page scripts import it. Call it, do not pass it around: a
|
|
24
|
+
* value use is not folded (it still works). (`html[data-cms-editing]` is the same signal for CSS and inline scripts.)
|
|
25
|
+
*/
|
|
26
|
+
export const isCmsEditing = () => preview;
|
package/dist/bridge.d.ts
ADDED
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Runs inside the preview page (only with CMS_PREVIEW=1). It marks editable elements, reports clicks to the
|
|
2
|
+
// editor, lets the user type directly in text fields, and applies quick text patches before the file is saved.
|
|
3
|
+
// Messages are plain data: the bridge never inserts HTML it receives.
|
|
4
|
+
const { editorOrigin } = window.__CMS__;
|
|
5
|
+
const SELECTOR = "[data-cms-field],[data-cms-image],[data-cms-item],[data-cms-list]";
|
|
6
|
+
let nonce = null;
|
|
7
|
+
let selected = null;
|
|
8
|
+
let editing = null;
|
|
9
|
+
let original = "";
|
|
10
|
+
/** Text fields the editor says must not be typed on the page (placeholders, markup made from the text). */
|
|
11
|
+
let noInline = new Set();
|
|
12
|
+
/** An element with child elements (a link, a <mark>) would lose them if typed into as plain text. */
|
|
13
|
+
const isPlainText = (el) => el.childElementCount === 0;
|
|
14
|
+
const refOf = (el) => {
|
|
15
|
+
const d = el.dataset;
|
|
16
|
+
if (d.cmsField)
|
|
17
|
+
return [d.cmsField, "text"];
|
|
18
|
+
if (d.cmsImage)
|
|
19
|
+
return [d.cmsImage, "image"];
|
|
20
|
+
if (d.cmsItem)
|
|
21
|
+
return [d.cmsItem, "item"];
|
|
22
|
+
if (d.cmsList)
|
|
23
|
+
return [d.cmsList, "list"];
|
|
24
|
+
return null;
|
|
25
|
+
};
|
|
26
|
+
const byRef = (ref) => [...document.querySelectorAll(SELECTOR)].filter((el) => refOf(el)?.[0] === ref);
|
|
27
|
+
function post(msg) {
|
|
28
|
+
if (nonce)
|
|
29
|
+
parent.postMessage({ ...msg, nonce }, editorOrigin);
|
|
30
|
+
}
|
|
31
|
+
// ---- Overlay (shadow DOM, so the site's CSS cannot reach it and it cannot reach the site) ----
|
|
32
|
+
const host = document.createElement("div");
|
|
33
|
+
host.setAttribute("data-cms-overlay", "");
|
|
34
|
+
const shadow = host.attachShadow({ mode: "open" });
|
|
35
|
+
shadow.innerHTML = `<style>
|
|
36
|
+
:host{all:initial}
|
|
37
|
+
.box{position:fixed;pointer-events:none;border-radius:6px;z-index:2147483646;display:none}
|
|
38
|
+
.hover{outline:2px dashed #2D68AF;outline-offset:3px}
|
|
39
|
+
.sel{outline:3px solid #2D68AF;outline-offset:3px;box-shadow:0 0 0 9999px rgba(20,35,58,.06)}
|
|
40
|
+
.tools{position:fixed;z-index:2147483647;display:none;gap:2px;background:#14233A;border-radius:8px;padding:3px;box-shadow:0 4px 16px rgba(0,0,0,.25)}
|
|
41
|
+
.tools button{all:unset;cursor:pointer;color:#fff;font:600 13px/1 system-ui,sans-serif;padding:8px 10px;border-radius:6px;min-width:24px;min-height:24px;text-align:center}
|
|
42
|
+
.tools button:hover,.tools button:focus-visible{background:#2D68AF;outline:2px solid #F8C838;outline-offset:0}
|
|
43
|
+
.label{position:fixed;z-index:2147483647;display:none;background:#2D68AF;color:#fff;font:600 12px/1 system-ui,sans-serif;padding:4px 7px;border-radius:4px;pointer-events:none}
|
|
44
|
+
</style>
|
|
45
|
+
<div class="box hover"></div><div class="box sel"></div><div class="label"></div>
|
|
46
|
+
<div class="tools" role="toolbar" aria-label="Element i listen">
|
|
47
|
+
<button data-op="up" aria-label="Flyt op" title="Flyt op">↑</button>
|
|
48
|
+
<button data-op="down" aria-label="Flyt ned" title="Flyt ned">↓</button>
|
|
49
|
+
<button data-op="duplicate" aria-label="Kopiér" title="Kopiér">Kopiér</button>
|
|
50
|
+
<button data-op="add" aria-label="Tilføj nyt efter" title="Tilføj nyt efter">+ Ny</button>
|
|
51
|
+
<button data-op="delete" aria-label="Slet" title="Slet">Slet</button>
|
|
52
|
+
</div>`;
|
|
53
|
+
const hoverBox = shadow.querySelector(".hover");
|
|
54
|
+
const selBox = shadow.querySelector(".sel");
|
|
55
|
+
const label = shadow.querySelector(".label");
|
|
56
|
+
const tools = shadow.querySelector(".tools");
|
|
57
|
+
let toolsFor = null;
|
|
58
|
+
let hovered = null;
|
|
59
|
+
function place(box, el) {
|
|
60
|
+
if (!el) {
|
|
61
|
+
box.style.display = "none";
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const r = el.getBoundingClientRect();
|
|
65
|
+
Object.assign(box.style, { display: "block", left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
|
66
|
+
}
|
|
67
|
+
function redraw() {
|
|
68
|
+
place(hoverBox, hovered && refOf(hovered)?.[0] !== selected ? hovered : null);
|
|
69
|
+
const selEl = selected ? byRef(selected)[0] ?? null : null;
|
|
70
|
+
place(selBox, selEl);
|
|
71
|
+
const itemEl = toolsFor ? byRef(toolsFor)[0] : null;
|
|
72
|
+
if (itemEl) {
|
|
73
|
+
const r = itemEl.getBoundingClientRect();
|
|
74
|
+
tools.style.display = "flex";
|
|
75
|
+
tools.style.left = `${Math.max(4, r.right - tools.offsetWidth)}px`;
|
|
76
|
+
tools.style.top = `${Math.max(4, r.top - tools.offsetHeight - 6)}px`;
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
tools.style.display = "none";
|
|
80
|
+
}
|
|
81
|
+
tools.addEventListener("click", (e) => {
|
|
82
|
+
const op = e.target.closest("button")?.dataset.op;
|
|
83
|
+
if (op && toolsFor)
|
|
84
|
+
post({ type: "list-op", ref: toolsFor, op });
|
|
85
|
+
});
|
|
86
|
+
// ---- Selection and inline text editing ----
|
|
87
|
+
function select(ref, scroll = false) {
|
|
88
|
+
selected = ref;
|
|
89
|
+
const el = ref ? byRef(ref)[0] : null;
|
|
90
|
+
const item = el?.closest("[data-cms-item]");
|
|
91
|
+
toolsFor = item ? refOf(item)[0] : null;
|
|
92
|
+
if (el && scroll)
|
|
93
|
+
el.scrollIntoView({ block: "center", behavior: "instant" });
|
|
94
|
+
redraw();
|
|
95
|
+
}
|
|
96
|
+
function startEditing(el, x, y) {
|
|
97
|
+
if (editing === el)
|
|
98
|
+
return;
|
|
99
|
+
stopEditing(true);
|
|
100
|
+
editing = el;
|
|
101
|
+
original = el.textContent ?? "";
|
|
102
|
+
el.contentEditable = "plaintext-only";
|
|
103
|
+
el.spellcheck = true;
|
|
104
|
+
el.focus({ preventScroll: true });
|
|
105
|
+
// Put the caret where the user clicked, not at the start.
|
|
106
|
+
const range = document.caretRangeFromPoint?.(x, y);
|
|
107
|
+
if (range) {
|
|
108
|
+
const s = getSelection();
|
|
109
|
+
s?.removeAllRanges();
|
|
110
|
+
s?.addRange(range);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function stopEditing(save) {
|
|
114
|
+
const el = editing;
|
|
115
|
+
if (!el)
|
|
116
|
+
return;
|
|
117
|
+
editing = null;
|
|
118
|
+
el.removeAttribute("contenteditable");
|
|
119
|
+
const ref = refOf(el)[0];
|
|
120
|
+
const value = (el.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
121
|
+
if (!save) {
|
|
122
|
+
el.textContent = original;
|
|
123
|
+
post({ type: "input", ref, value: original });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (value !== original)
|
|
127
|
+
post({ type: "commit", ref, value });
|
|
128
|
+
}
|
|
129
|
+
let visitor = false;
|
|
130
|
+
document.addEventListener("click", (e) => {
|
|
131
|
+
if (!nonce || visitor)
|
|
132
|
+
return;
|
|
133
|
+
const t = e.target;
|
|
134
|
+
if (host.contains(t))
|
|
135
|
+
return;
|
|
136
|
+
const el = t.closest(SELECTOR);
|
|
137
|
+
if (!el)
|
|
138
|
+
return;
|
|
139
|
+
const [ref, kind] = refOf(el);
|
|
140
|
+
// While editing, links and buttons must not fire when the user clicks their text.
|
|
141
|
+
e.preventDefault();
|
|
142
|
+
e.stopPropagation();
|
|
143
|
+
// A text the page shows differently from how it is stored is edited in the editor's panel instead.
|
|
144
|
+
const inline = kind === "text" && !noInline.has(ref) && isPlainText(el);
|
|
145
|
+
if (inline)
|
|
146
|
+
startEditing(el, e.clientX, e.clientY);
|
|
147
|
+
else
|
|
148
|
+
stopEditing(true);
|
|
149
|
+
select(ref);
|
|
150
|
+
post({ type: "select", ref, kind, inline, src: kind === "image" ? el.currentSrc : undefined });
|
|
151
|
+
}, true);
|
|
152
|
+
document.addEventListener("input", (e) => {
|
|
153
|
+
if (e.target === editing && editing) {
|
|
154
|
+
const ref = refOf(editing)[0];
|
|
155
|
+
const value = editing.textContent ?? "";
|
|
156
|
+
for (const other of byRef(ref))
|
|
157
|
+
if (other !== editing && isPlainText(other))
|
|
158
|
+
other.textContent = value;
|
|
159
|
+
post({ type: "input", ref, value });
|
|
160
|
+
redraw();
|
|
161
|
+
}
|
|
162
|
+
}, true);
|
|
163
|
+
document.addEventListener("keydown", (e) => {
|
|
164
|
+
if (!editing)
|
|
165
|
+
return;
|
|
166
|
+
if (e.key === "Enter") {
|
|
167
|
+
e.preventDefault();
|
|
168
|
+
stopEditing(true);
|
|
169
|
+
}
|
|
170
|
+
else if (e.key === "Escape") {
|
|
171
|
+
e.preventDefault();
|
|
172
|
+
stopEditing(false);
|
|
173
|
+
}
|
|
174
|
+
}, true);
|
|
175
|
+
document.addEventListener("focusout", (e) => { if (e.target === editing)
|
|
176
|
+
stopEditing(true); }, true);
|
|
177
|
+
document.addEventListener("mouseover", (e) => {
|
|
178
|
+
if (visitor)
|
|
179
|
+
return;
|
|
180
|
+
const el = e.target.closest(SELECTOR);
|
|
181
|
+
hovered = el;
|
|
182
|
+
if (el) {
|
|
183
|
+
label.textContent = { text: "Tekst", image: "Billede", item: "Element i liste", list: "Liste" }[refOf(el)[1]];
|
|
184
|
+
const r = el.getBoundingClientRect();
|
|
185
|
+
Object.assign(label.style, { display: "block", left: `${r.left}px`, top: `${Math.max(0, r.top - 22)}px` });
|
|
186
|
+
}
|
|
187
|
+
else
|
|
188
|
+
label.style.display = "none";
|
|
189
|
+
redraw();
|
|
190
|
+
});
|
|
191
|
+
addEventListener("scroll", redraw, { passive: true, capture: true });
|
|
192
|
+
addEventListener("resize", redraw);
|
|
193
|
+
// ---- Messages from the editor ----
|
|
194
|
+
addEventListener("message", (e) => {
|
|
195
|
+
if (e.source !== parent || e.origin !== editorOrigin)
|
|
196
|
+
return;
|
|
197
|
+
const m = e.data;
|
|
198
|
+
if (!m || typeof m !== "object" || typeof m.type !== "string")
|
|
199
|
+
return;
|
|
200
|
+
if (m.type === "hello") {
|
|
201
|
+
if (nonce || typeof m.nonce !== "string")
|
|
202
|
+
return;
|
|
203
|
+
nonce = m.nonce;
|
|
204
|
+
announce();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (m.nonce !== nonce)
|
|
208
|
+
return;
|
|
209
|
+
const ref = typeof m.ref === "string" ? m.ref : null;
|
|
210
|
+
switch (m.type) {
|
|
211
|
+
case "select":
|
|
212
|
+
select(ref, true);
|
|
213
|
+
break;
|
|
214
|
+
case "patch-text":
|
|
215
|
+
// Never flatten an element that has markup inside it; the real render arrives after the save.
|
|
216
|
+
if (ref && typeof m.value === "string" && !noInline.has(ref))
|
|
217
|
+
for (const el of byRef(ref))
|
|
218
|
+
if (el !== editing && isPlainText(el))
|
|
219
|
+
el.textContent = m.value;
|
|
220
|
+
redraw();
|
|
221
|
+
break;
|
|
222
|
+
case "fields":
|
|
223
|
+
if (Array.isArray(m.noInline))
|
|
224
|
+
noInline = new Set(m.noInline.filter((r) => typeof r === "string"));
|
|
225
|
+
break;
|
|
226
|
+
case "patch-image":
|
|
227
|
+
if (!ref)
|
|
228
|
+
break;
|
|
229
|
+
for (const el of byRef(ref)) {
|
|
230
|
+
const img = el;
|
|
231
|
+
if (typeof m.alt === "string")
|
|
232
|
+
img.alt = m.alt;
|
|
233
|
+
const f = m.fokus;
|
|
234
|
+
if (f && typeof f.x === "number" && typeof f.y === "number")
|
|
235
|
+
img.style.objectPosition = `${f.x}% ${f.y}%`;
|
|
236
|
+
}
|
|
237
|
+
break;
|
|
238
|
+
case "visitor-view":
|
|
239
|
+
visitor = m.on === true;
|
|
240
|
+
stopEditing(true);
|
|
241
|
+
host.style.display = visitor ? "none" : "";
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
function announce() {
|
|
246
|
+
const seen = new Set();
|
|
247
|
+
const fields = [...document.querySelectorAll(SELECTOR)].flatMap((el) => {
|
|
248
|
+
const [ref, kind] = refOf(el);
|
|
249
|
+
if (seen.has(ref))
|
|
250
|
+
return [];
|
|
251
|
+
seen.add(ref);
|
|
252
|
+
const img = kind === "image" ? el : null;
|
|
253
|
+
return [{ ref, kind, text: img ? img.alt : (el.textContent ?? "").trim().slice(0, 80), src: img ? img.currentSrc || img.src : undefined }];
|
|
254
|
+
});
|
|
255
|
+
post({ type: "ready", url: location.pathname, title: document.title, fields });
|
|
256
|
+
}
|
|
257
|
+
// Site convention while editing: every <details> is open, so answers and other folded text can be clicked.
|
|
258
|
+
// (CSS motion is turned off by the integration's head script; JS animations check isCmsEditing().)
|
|
259
|
+
const openDetails = () => document.querySelectorAll("details").forEach((d) => { d.open = true; });
|
|
260
|
+
openDetails();
|
|
261
|
+
addEventListener("load", openDetails);
|
|
262
|
+
// Keep the scroll position when the dev server reloads the page after a save.
|
|
263
|
+
addEventListener("pagehide", () => sessionStorage.setItem(`cms-scroll:${location.pathname}`, String(scrollY)));
|
|
264
|
+
const y = sessionStorage.getItem(`cms-scroll:${location.pathname}`);
|
|
265
|
+
if (y)
|
|
266
|
+
requestAnimationFrame(() => scrollTo({ top: Number(y), behavior: "instant" }));
|
|
267
|
+
document.body.append(host);
|
|
268
|
+
parent.postMessage({ type: "boot" }, editorOrigin);
|
|
269
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SchemaContext } from "astro/content/config";
|
|
2
|
+
import type { z } from "astro/zod";
|
|
3
|
+
import { type CmsConfig, type CollectionSchema, type ImageOf } from "./schema.ts";
|
|
4
|
+
/** Astro's `image()` helper, as content.config.ts gets it. */
|
|
5
|
+
type AstroImage = SchemaContext["image"];
|
|
6
|
+
/** The CMS's schema of a collection as the site's content.config.ts gets it (`src` of an image is Astro's image). */
|
|
7
|
+
export type CmsSchema<C extends CmsConfig, N extends keyof C["collections"]> = CollectionSchema<C["collections"][N], ImageOf<AstroImage>>;
|
|
8
|
+
export type CmsCollectionOptions<B = z.ZodTypeAny, S = z.ZodTypeAny> = {
|
|
9
|
+
/** Adds what the CMS does not edit: hidden fields of root-list items, locked page fields. Gets the CMS's schema. */
|
|
10
|
+
extend?: (schema: B, context: SchemaContext) => S;
|
|
11
|
+
};
|
|
12
|
+
export declare function cmsCollection<const C extends CmsConfig, N extends keyof C["collections"] & string, S = CmsSchema<C, N>>(config: C, name: N, options?: CmsCollectionOptions<CmsSchema<C, N>, S>): {
|
|
13
|
+
loader: import("astro/loaders").Loader;
|
|
14
|
+
schema: (context: SchemaContext) => S;
|
|
15
|
+
};
|
|
16
|
+
export {};
|
package/dist/content.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Astro content collections from cms.config.ts, so the loader and the schema always match what the CMS reads and
|
|
2
|
+
// writes. Use it in the site's content.config.ts:
|
|
3
|
+
//
|
|
4
|
+
// import { defineCollection } from "astro:content";
|
|
5
|
+
// import { cmsCollection } from "@sindingmind/cms-astro/content";
|
|
6
|
+
// import cms from "../cms.config.ts";
|
|
7
|
+
// export const collections = {
|
|
8
|
+
// forside: defineCollection(cmsCollection(cms, "forside")),
|
|
9
|
+
// faq: defineCollection(cmsCollection(cms, "faq", { extend: (s) => s.extend({ kategori: z.string() }) })),
|
|
10
|
+
// };
|
|
11
|
+
//
|
|
12
|
+
// - A folder collection (no `file`) is `glob("*.yaml")` in `dir`: one entry per file.
|
|
13
|
+
// - A page (`file`) is `glob(file)` in `dir`: one entry, whose id is the file name lower-cased, as everywhere else.
|
|
14
|
+
// - A root list (`root: "list"`) is `file(dir/file)`: one Astro entry per item (each item needs an `id`), and the
|
|
15
|
+
// schema is the item's. The CMS still sees the whole file as one entry (see entryOf()).
|
|
16
|
+
//
|
|
17
|
+
// Types: the schema is typed from the fields (see CollectionSchema in schema.ts), so `getEntry()` and
|
|
18
|
+
// `getCollection()` give typed data, with what `extend` adds on top. `name` must be a collection of the config.
|
|
19
|
+
import { file, glob } from "astro/loaders";
|
|
20
|
+
import { schemaOf } from "./schema.js";
|
|
21
|
+
export function cmsCollection(config, name, options = {}) {
|
|
22
|
+
if (!Object.hasOwn(config.collections, name))
|
|
23
|
+
throw new Error(`cms.config has no collection "${name}"`);
|
|
24
|
+
const collection = config.collections[name];
|
|
25
|
+
const base = collection.dir.replace(/\/+$/, "");
|
|
26
|
+
if (collection.root === "list" && !collection.file)
|
|
27
|
+
throw new Error(`Collection "${name}": a root list needs "file"`);
|
|
28
|
+
const loader = collection.root === "list" ? file(`${base}/${collection.file}`) : glob({ pattern: collection.file ?? "*.yaml", base });
|
|
29
|
+
return {
|
|
30
|
+
loader,
|
|
31
|
+
schema: (context) => {
|
|
32
|
+
const schema = schemaOf(collection, context.image);
|
|
33
|
+
return options.extend ? options.extend(schema, context) : schema;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const ATTRS_SPECIFIER = "@sindingmind/cms-astro/attrs";
|
|
2
|
+
/** The parser of the bundler's plugin context (`this.parse`): ESTree with `start`/`end` offsets. */
|
|
3
|
+
export type Parse = (code: string) => unknown;
|
|
4
|
+
/**
|
|
5
|
+
* Returns `code` with every `isCmsEditing()` call replaced by `value` (as a literal), or undefined if the module does
|
|
6
|
+
* not import `isCmsEditing` from the attrs module (or there is nothing to replace).
|
|
7
|
+
*/
|
|
8
|
+
export declare function foldEditingCalls(code: string, parse: Parse, value: boolean): string | undefined;
|