@openhi/sdk 0.0.0 → 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/LICENSE +19 -0
- package/README.md +205 -1
- package/astro/OpenhiPreview.astro +59 -0
- package/lib/api-base.d.ts +2 -0
- package/lib/api-base.js +22 -0
- package/lib/astro/index.d.ts +8 -0
- package/lib/astro/index.js +8 -0
- package/lib/astro/loaders.d.ts +131 -0
- package/lib/astro/loaders.js +318 -0
- package/lib/content/asset.d.ts +69 -0
- package/lib/content/asset.js +151 -0
- package/lib/content/blocks/catalogue.d.ts +11 -0
- package/lib/content/blocks/catalogue.js +71 -0
- package/lib/content/blocks/declare.d.ts +143 -0
- package/lib/content/blocks/declare.js +210 -0
- package/lib/content/blocks/index.d.ts +2 -0
- package/lib/content/blocks/index.js +2 -0
- package/lib/content/content-type.d.ts +52 -0
- package/lib/content/content-type.js +97 -0
- package/lib/content/import-plan.d.ts +56 -0
- package/lib/content/import-plan.js +71 -0
- package/lib/content/index.d.ts +14 -0
- package/lib/content/index.js +14 -0
- package/lib/content/page.d.ts +91 -0
- package/lib/content/page.js +222 -0
- package/lib/content/sanitise-html.d.ts +36 -0
- package/lib/content/sanitise-html.js +92 -0
- package/lib/content/section.d.ts +60 -0
- package/lib/content/section.js +59 -0
- package/lib/content/shapes.d.ts +68 -0
- package/lib/content/shapes.js +9 -0
- package/lib/content/theme.d.ts +25 -0
- package/lib/content/theme.js +54 -0
- package/lib/content/types.d.ts +142 -0
- package/lib/content/types.js +121 -0
- package/lib/errors.d.ts +25 -0
- package/lib/errors.js +25 -0
- package/lib/forms/index.d.ts +107 -0
- package/lib/forms/index.js +201 -0
- package/lib/index.d.ts +10 -0
- package/lib/index.js +9 -0
- package/lib/node/bin.d.ts +2 -0
- package/lib/node/bin.js +14 -0
- package/lib/node/cli/api.d.ts +24 -0
- package/lib/node/cli/api.js +62 -0
- package/lib/node/cli/check.d.ts +26 -0
- package/lib/node/cli/check.js +265 -0
- package/lib/node/cli/context.d.ts +37 -0
- package/lib/node/cli/context.js +55 -0
- package/lib/node/cli/env-check.d.ts +4 -0
- package/lib/node/cli/env-check.js +47 -0
- package/lib/node/cli/init.d.ts +2 -0
- package/lib/node/cli/init.js +171 -0
- package/lib/node/cli/load-blocks.d.ts +15 -0
- package/lib/node/cli/load-blocks.js +109 -0
- package/lib/node/cli/local-content.d.ts +47 -0
- package/lib/node/cli/local-content.js +126 -0
- package/lib/node/cli/main.d.ts +3 -0
- package/lib/node/cli/main.js +58 -0
- package/lib/node/cli/optional-tool.d.ts +8 -0
- package/lib/node/cli/optional-tool.js +26 -0
- package/lib/node/cli/pull.d.ts +2 -0
- package/lib/node/cli/pull.js +113 -0
- package/lib/node/cli/push.d.ts +6 -0
- package/lib/node/cli/push.js +227 -0
- package/lib/node/env.d.ts +34 -0
- package/lib/node/env.js +66 -0
- package/lib/node/index.d.ts +9 -0
- package/lib/node/index.js +8 -0
- package/lib/node/media.d.ts +56 -0
- package/lib/node/media.js +176 -0
- package/lib/node/read.d.ts +19 -0
- package/lib/node/read.js +55 -0
- package/lib/paging.d.ts +14 -0
- package/lib/paging.js +41 -0
- package/lib/preview/apply-draft.d.ts +42 -0
- package/lib/preview/apply-draft.js +185 -0
- package/lib/preview/index.d.ts +7 -0
- package/lib/preview/index.js +4 -0
- package/lib/preview/marks.d.ts +25 -0
- package/lib/preview/marks.js +17 -0
- package/lib/preview/runtime.d.ts +17 -0
- package/lib/preview/runtime.js +85 -0
- package/lib/preview/studio-origin.d.ts +3 -0
- package/lib/preview/studio-origin.js +38 -0
- package/lib/transport.d.ts +25 -0
- package/lib/transport.js +58 -0
- package/lib/trim-slashes.d.ts +4 -0
- package/lib/trim-slashes.js +14 -0
- package/package.json +124 -3
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { relative, resolve } from "node:path";
|
|
3
|
+
import { FHIR_ACCEPT, ofType } from "./read.js";
|
|
4
|
+
import { trimTrailingSlashes } from "../trim-slashes.js";
|
|
5
|
+
const STORED_FILE = /^ContentAsset\/([^/]+)\/\$content$/;
|
|
6
|
+
/** Names the kit wrote into the media directory, so only they are pruned. */
|
|
7
|
+
const MANIFEST = ".openhi-media.json";
|
|
8
|
+
/** Whether a name is one the kit would have written (an id plus a known extension). */
|
|
9
|
+
const ours = (name) => {
|
|
10
|
+
const dot = name.lastIndexOf(".");
|
|
11
|
+
const id = dot > 0 ? name.slice(0, dot) : name;
|
|
12
|
+
const ext = dot > 0 ? name.slice(dot) : "";
|
|
13
|
+
return (SAFE_ID.test(id) &&
|
|
14
|
+
(ext === "" || Object.values(EXTENSIONS).includes(ext)));
|
|
15
|
+
};
|
|
16
|
+
/** An id is a file name here, so it cannot carry a path. */
|
|
17
|
+
const SAFE_ID = /^[A-Za-z0-9.-]{1,64}$/;
|
|
18
|
+
function validId(id) {
|
|
19
|
+
return id !== undefined && SAFE_ID.test(id) && id !== "." && id !== ".."
|
|
20
|
+
? id
|
|
21
|
+
: undefined;
|
|
22
|
+
}
|
|
23
|
+
/** The id of an asset whose file OpenHI stores, from its `url`. */
|
|
24
|
+
export function storedAssetId(url) {
|
|
25
|
+
return typeof url === "string"
|
|
26
|
+
? validId(STORED_FILE.exec(url)?.[1])
|
|
27
|
+
: undefined;
|
|
28
|
+
}
|
|
29
|
+
const EXTENSIONS = {
|
|
30
|
+
"image/png": ".png",
|
|
31
|
+
"image/jpeg": ".jpg",
|
|
32
|
+
"image/gif": ".gif",
|
|
33
|
+
"image/webp": ".webp",
|
|
34
|
+
"image/avif": ".avif",
|
|
35
|
+
"image/svg+xml": ".svg",
|
|
36
|
+
"application/pdf": ".pdf",
|
|
37
|
+
};
|
|
38
|
+
export function extensionFor(contentType) {
|
|
39
|
+
return (EXTENSIONS[contentType.split(";")[0]?.trim().toLowerCase() ?? ""] ?? "");
|
|
40
|
+
}
|
|
41
|
+
/** How many files are fetched at once. */
|
|
42
|
+
const PARALLEL = 6;
|
|
43
|
+
async function signedUrl(api, id, get) {
|
|
44
|
+
const path = `/Website/${encodeURIComponent(api.website)}/assets/${encodeURIComponent(id)}`;
|
|
45
|
+
const response = await get(`${api.base}${path}`, {
|
|
46
|
+
headers: { Accept: FHIR_ACCEPT, Authorization: `Bearer ${api.key}` },
|
|
47
|
+
});
|
|
48
|
+
if (!response.ok)
|
|
49
|
+
throw new Error(`GET ${path} answered ${response.status}`);
|
|
50
|
+
const body = (await response.json());
|
|
51
|
+
if (typeof body.url !== "string")
|
|
52
|
+
throw new Error(`GET ${path} answered no url`);
|
|
53
|
+
return {
|
|
54
|
+
url: body.url,
|
|
55
|
+
contentType: body.contentType ?? "application/octet-stream",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Download every stored active asset the export lists.
|
|
60
|
+
*
|
|
61
|
+
* A file already in place is kept when its size is the asset's: the bytes
|
|
62
|
+
* of an asset change only when its record is replaced, so a build that
|
|
63
|
+
* caches the directory fetches nothing it has.
|
|
64
|
+
*/
|
|
65
|
+
export async function pullMedia(api, records, options = {}) {
|
|
66
|
+
const root = options.root ?? process.cwd();
|
|
67
|
+
const get = options.fetch ?? ((...args) => fetch(...args));
|
|
68
|
+
const dir = resolve(root, options.dir ?? "public/openhi-media");
|
|
69
|
+
// The kit prunes this directory, so it must be one the kit can own.
|
|
70
|
+
const outside = relative(resolve(root), dir);
|
|
71
|
+
if (outside.startsWith("..") || resolve(outside) === outside) {
|
|
72
|
+
throw new Error(`media.dir "${options.dir}" is outside the project root: use a folder inside it, such as public/openhi-media`);
|
|
73
|
+
}
|
|
74
|
+
if (dir === resolve(root) || dir === resolve(root, "public")) {
|
|
75
|
+
throw new Error(`media.dir "${options.dir}" is the project root or public/: use a folder of its own, such as public/openhi-media`);
|
|
76
|
+
}
|
|
77
|
+
const publicPath = trimTrailingSlashes(options.publicPath ?? "/openhi-media");
|
|
78
|
+
const used = referencedAssets(records, options.references);
|
|
79
|
+
const assets = ofType(records, "ContentAsset").filter((asset) => {
|
|
80
|
+
const id = storedAssetId(asset.url);
|
|
81
|
+
return asset.status === "active" && id !== undefined && used.has(id);
|
|
82
|
+
});
|
|
83
|
+
await mkdir(dir, { recursive: true });
|
|
84
|
+
const pull = async (asset) => {
|
|
85
|
+
const id = storedAssetId(asset.url);
|
|
86
|
+
const contentType = asset.contentType ?? "application/octet-stream";
|
|
87
|
+
const name = `${id}${extensionFor(contentType)}`;
|
|
88
|
+
const file = resolve(dir, name);
|
|
89
|
+
const have = await stat(file).then((info) => info.size, () => undefined);
|
|
90
|
+
if (have !== undefined && asset.size !== undefined && have === asset.size) {
|
|
91
|
+
return { id, path: `${publicPath}/${name}`, contentType, fetched: false };
|
|
92
|
+
}
|
|
93
|
+
const target = await signedUrl(api, id, get);
|
|
94
|
+
// The signed URL carries its own authority. The key is not sent to it.
|
|
95
|
+
const download = await get(target.url);
|
|
96
|
+
if (!download.ok) {
|
|
97
|
+
throw new Error(`downloading ContentAsset/${id} answered ${download.status}`);
|
|
98
|
+
}
|
|
99
|
+
await writeFile(file, new Uint8Array(await download.arrayBuffer()));
|
|
100
|
+
return { id, path: `${publicPath}/${name}`, contentType, fetched: true };
|
|
101
|
+
};
|
|
102
|
+
const pulled = [];
|
|
103
|
+
for (let at = 0; at < assets.length; at += PARALLEL) {
|
|
104
|
+
pulled.push(...(await Promise.all(assets.slice(at, at + PARALLEL).map(pull))));
|
|
105
|
+
}
|
|
106
|
+
// Only files the kit itself wrote on an earlier pull are pruned, as
|
|
107
|
+
// recorded in a manifest beside them: a shared folder such as
|
|
108
|
+
// public/images keeps everything it did not get from the kit.
|
|
109
|
+
const manifestFile = resolve(dir, MANIFEST);
|
|
110
|
+
const previous = await readFile(manifestFile, "utf8").then((text) => {
|
|
111
|
+
const parsed = JSON.parse(text);
|
|
112
|
+
return Array.isArray(parsed)
|
|
113
|
+
? parsed.filter((name) => typeof name === "string")
|
|
114
|
+
: [];
|
|
115
|
+
}, () => []);
|
|
116
|
+
const keep = new Set(pulled.map((file) => file.path.split("/").pop()));
|
|
117
|
+
for (const name of previous) {
|
|
118
|
+
if (!keep.has(name) && ours(name)) {
|
|
119
|
+
await rm(resolve(dir, name), { force: true });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (keep.size > 0) {
|
|
123
|
+
await writeFile(manifestFile, `${JSON.stringify([...keep].sort())}\n`);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
await rm(manifestFile, { force: true });
|
|
127
|
+
}
|
|
128
|
+
return pulled;
|
|
129
|
+
}
|
|
130
|
+
const ASSET_REFERENCE = /^ContentAsset\/([^/]+)(?:\/\$content)?$/;
|
|
131
|
+
/** The ids of the assets a site's content refers to, wherever they sit in a value. */
|
|
132
|
+
function referencedAssets(records, extra = []) {
|
|
133
|
+
const ids = new Set();
|
|
134
|
+
const visit = (node) => {
|
|
135
|
+
if (typeof node === "string") {
|
|
136
|
+
const id = ASSET_REFERENCE.exec(node)?.[1];
|
|
137
|
+
if (id !== undefined)
|
|
138
|
+
ids.add(id);
|
|
139
|
+
}
|
|
140
|
+
else if (Array.isArray(node))
|
|
141
|
+
node.forEach(visit);
|
|
142
|
+
else if (typeof node === "object" && node !== null)
|
|
143
|
+
Object.values(node).forEach(visit);
|
|
144
|
+
};
|
|
145
|
+
for (const record of records) {
|
|
146
|
+
if (record.resourceType !== "ContentAsset")
|
|
147
|
+
visit(record);
|
|
148
|
+
}
|
|
149
|
+
extra.forEach(visit);
|
|
150
|
+
return ids;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Point content at the files that were pulled.
|
|
154
|
+
*
|
|
155
|
+
* A string that is exactly `ContentAsset/{id}` or `ContentAsset/{id}/$content`
|
|
156
|
+
* becomes the path the site serves that file from, wherever it sits in the
|
|
157
|
+
* value. Nothing else is touched.
|
|
158
|
+
*/
|
|
159
|
+
export function localiseMedia(value, media) {
|
|
160
|
+
if (media.size === 0)
|
|
161
|
+
return value;
|
|
162
|
+
const visit = (node) => {
|
|
163
|
+
if (typeof node === "string") {
|
|
164
|
+
const match = /^ContentAsset\/([^/]+)(?:\/\$content)?$/.exec(node);
|
|
165
|
+
return ((match?.[1] !== undefined ? media.get(match[1])?.path : undefined) ??
|
|
166
|
+
node);
|
|
167
|
+
}
|
|
168
|
+
if (Array.isArray(node))
|
|
169
|
+
return node.map(visit);
|
|
170
|
+
if (typeof node === "object" && node !== null) {
|
|
171
|
+
return Object.fromEntries(Object.entries(node).map(([name, member]) => [name, visit(member)]));
|
|
172
|
+
}
|
|
173
|
+
return node;
|
|
174
|
+
};
|
|
175
|
+
return visit(value);
|
|
176
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { entriesOf } from "../paging.js";
|
|
2
|
+
import { FHIR_ACCEPT } from "../transport.js";
|
|
3
|
+
import type { ApiSettings } from "./env.js";
|
|
4
|
+
export { entriesOf, FHIR_ACCEPT };
|
|
5
|
+
/** A record in the site's export, whatever its type. */
|
|
6
|
+
export type SiteRecord = {
|
|
7
|
+
resourceType: string;
|
|
8
|
+
id?: string;
|
|
9
|
+
} & Record<string, unknown>;
|
|
10
|
+
/** Testing seam: the memo is process-wide and a test needs a clean one. */
|
|
11
|
+
export declare function forgetSiteRecords(): void;
|
|
12
|
+
export declare function readSite(api: ApiSettings): Promise<SiteRecord[]>;
|
|
13
|
+
/** The site's records of one type. */
|
|
14
|
+
export declare function ofType<T>(records: readonly SiteRecord[], resourceType: string): T[];
|
|
15
|
+
/**
|
|
16
|
+
* The entries of one tenant-defined content type, found by its definition's
|
|
17
|
+
* URL. None when the definition is not `publishable`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function contentEntries<T>(records: readonly SiteRecord[], definitionUrl: string): T[];
|
package/lib/node/read.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { entriesOf } from "../paging.js";
|
|
2
|
+
import { createClient, FHIR_ACCEPT } from "../transport.js";
|
|
3
|
+
export { entriesOf, FHIR_ACCEPT };
|
|
4
|
+
/**
|
|
5
|
+
* Everything the site's build reads, in one request.
|
|
6
|
+
*
|
|
7
|
+
* The site's export is the `Website` record, its content and its
|
|
8
|
+
* catalogue as one Bundle, and the key it opens belongs to one website.
|
|
9
|
+
* Memoised: the loaders run in one process and would otherwise each read
|
|
10
|
+
* the site.
|
|
11
|
+
*/
|
|
12
|
+
let siteRecords;
|
|
13
|
+
/** Testing seam: the memo is process-wide and a test needs a clean one. */
|
|
14
|
+
export function forgetSiteRecords() {
|
|
15
|
+
siteRecords = undefined;
|
|
16
|
+
}
|
|
17
|
+
export function readSite(api) {
|
|
18
|
+
siteRecords ?? (siteRecords = readExport(api));
|
|
19
|
+
return siteRecords;
|
|
20
|
+
}
|
|
21
|
+
async function readExport(api) {
|
|
22
|
+
if (api.key === undefined) {
|
|
23
|
+
throw new Error("OPENHI_WEBSITE_KEY is not set");
|
|
24
|
+
}
|
|
25
|
+
const path = `/Website/${encodeURIComponent(api.website)}/export`;
|
|
26
|
+
const client = createClient({ base: api.base, key: api.key });
|
|
27
|
+
const records = entriesOf(await client.request(path));
|
|
28
|
+
// A proxy answering 200 with HTML parses to nothing; without this the
|
|
29
|
+
// loaders would log zero records and keep git's content.
|
|
30
|
+
if (records[0]?.resourceType !== "Website" || records[0].id === undefined) {
|
|
31
|
+
throw new Error(`Website ${api.website} came back without its record; is ${api.base} the OpenHI API?`);
|
|
32
|
+
}
|
|
33
|
+
return records;
|
|
34
|
+
}
|
|
35
|
+
/** The site's records of one type. */
|
|
36
|
+
export function ofType(records, resourceType) {
|
|
37
|
+
return records.filter((record) => record.resourceType === resourceType);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The entries of one tenant-defined content type, found by its definition's
|
|
41
|
+
* URL. None when the definition is not `publishable`.
|
|
42
|
+
*/
|
|
43
|
+
export function contentEntries(records, definitionUrl) {
|
|
44
|
+
const found = ofType(records, "ContentDefinition").find((candidate) => candidate.url === definitionUrl);
|
|
45
|
+
const definition = found?.id;
|
|
46
|
+
if (found === undefined || definition === undefined) {
|
|
47
|
+
throw new Error(`no ContentDefinition at ${definitionUrl} — import it first`);
|
|
48
|
+
}
|
|
49
|
+
// Entries may reach public output only when the definition says so; absent
|
|
50
|
+
// means no.
|
|
51
|
+
if (found.publishable !== true)
|
|
52
|
+
return [];
|
|
53
|
+
return ofType(records, "Content").filter((content) => content.definition?.reference ===
|
|
54
|
+
`ContentDefinition/${definition}`);
|
|
55
|
+
}
|
package/lib/paging.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { OpenhiClient } from "./transport.js";
|
|
2
|
+
/** The records in a Bundle, whatever their type. */
|
|
3
|
+
export declare function entriesOf<T = {
|
|
4
|
+
resourceType: string;
|
|
5
|
+
}>(bundle: unknown): T[];
|
|
6
|
+
/**
|
|
7
|
+
* The path of a Bundle's next page, or `undefined` on the last one.
|
|
8
|
+
*
|
|
9
|
+
* A `next` link that points at another origin is ignored: following it would
|
|
10
|
+
* send the credential somewhere the client was never configured for.
|
|
11
|
+
*/
|
|
12
|
+
export declare function nextPagePath(bundle: unknown, base: string): string | undefined;
|
|
13
|
+
/** Every page of a search or export, following `next` links until there are none. */
|
|
14
|
+
export declare function pages(client: OpenhiClient, path: string): AsyncGenerator<unknown, void, undefined>;
|
package/lib/paging.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The records in a Bundle, whatever their type. */
|
|
2
|
+
export function entriesOf(bundle) {
|
|
3
|
+
return (bundle?.entry ?? [])
|
|
4
|
+
.map((entry) => entry.resource)
|
|
5
|
+
.filter((resource) => resource !== undefined);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The path of a Bundle's next page, or `undefined` on the last one.
|
|
9
|
+
*
|
|
10
|
+
* A `next` link that points at another origin is ignored: following it would
|
|
11
|
+
* send the credential somewhere the client was never configured for.
|
|
12
|
+
*/
|
|
13
|
+
export function nextPagePath(bundle, base) {
|
|
14
|
+
const links = bundle?.link;
|
|
15
|
+
const next = links?.find((link) => link.relation === "next")?.url;
|
|
16
|
+
if (next === undefined)
|
|
17
|
+
return undefined;
|
|
18
|
+
let target;
|
|
19
|
+
let origin;
|
|
20
|
+
try {
|
|
21
|
+
origin = new URL(base);
|
|
22
|
+
target = new URL(next, origin);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
if (target.origin !== origin.origin)
|
|
28
|
+
return undefined;
|
|
29
|
+
return `${target.pathname}${target.search}`;
|
|
30
|
+
}
|
|
31
|
+
/** Every page of a search or export, following `next` links until there are none. */
|
|
32
|
+
export async function* pages(client, path) {
|
|
33
|
+
let current = path;
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
while (current !== undefined && !seen.has(current)) {
|
|
36
|
+
seen.add(current);
|
|
37
|
+
const bundle = await client.request(current);
|
|
38
|
+
yield bundle;
|
|
39
|
+
current = nextPagePath(bundle, client.base);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { LayoutSection } from "../content/shapes.js";
|
|
2
|
+
/**
|
|
3
|
+
* Show Studio's unsaved draft on the page already here.
|
|
4
|
+
*
|
|
5
|
+
* A site is a static build, so a draft cannot be rendered: the blocks are
|
|
6
|
+
* components and only run when the site builds. Instead the markup
|
|
7
|
+
* says where each authored value went, and a draft is written into those
|
|
8
|
+
* places. Preview annotates the markup rather than
|
|
9
|
+
* rendering it. What is on screen stays the site's own markup, styles and
|
|
10
|
+
* scripts, with the words changed.
|
|
11
|
+
*
|
|
12
|
+
* - `data-openhi-block="<identifier>"` wraps each block.
|
|
13
|
+
* - `data-openhi-field="<name>"` holds one of its values. Add
|
|
14
|
+
* `data-openhi-html` when the build renders that value as HTML.
|
|
15
|
+
* - `data-openhi-list="<name>"` holds a repeating value, and
|
|
16
|
+
* `data-openhi-entry` marks each item in it. An item's own values are
|
|
17
|
+
* fields inside it. An item that is just a string is written into the
|
|
18
|
+
* entry's field when it has one, and into the entry itself when not.
|
|
19
|
+
*
|
|
20
|
+
* Text, lists, order and removal preview exactly. A value the build left
|
|
21
|
+
* out entirely, such as a lede that was empty, has nowhere to go until the
|
|
22
|
+
* next build, and neither has a block the page did not have: that one gets
|
|
23
|
+
* a stand-in saying so.
|
|
24
|
+
*/
|
|
25
|
+
export declare const BLOCK = "data-openhi-block";
|
|
26
|
+
export declare const FIELD = "data-openhi-field";
|
|
27
|
+
export declare const HTML = "data-openhi-html";
|
|
28
|
+
export declare const LIST = "data-openhi-list";
|
|
29
|
+
export declare const ENTRY = "data-openhi-entry";
|
|
30
|
+
export declare const HIDDEN = "data-openhi-hidden";
|
|
31
|
+
export interface DraftPatcherOptions {
|
|
32
|
+
/** Cleans an HTML value before it is written, as the build does. */
|
|
33
|
+
readonly sanitise: (html: string) => string;
|
|
34
|
+
/** What to call a block this page has never drawn, when known. */
|
|
35
|
+
readonly nameOf: (component: string) => string | undefined;
|
|
36
|
+
/** Called on each list entry copied to make room for a new item. */
|
|
37
|
+
readonly onClone?: (entry: Element) => void;
|
|
38
|
+
}
|
|
39
|
+
export interface DraftPatcher {
|
|
40
|
+
apply(sections: readonly LayoutSection[]): void;
|
|
41
|
+
}
|
|
42
|
+
export declare function createDraftPatcher(document: Document, options: DraftPatcherOptions): DraftPatcher;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Show Studio's unsaved draft on the page already here.
|
|
3
|
+
*
|
|
4
|
+
* A site is a static build, so a draft cannot be rendered: the blocks are
|
|
5
|
+
* components and only run when the site builds. Instead the markup
|
|
6
|
+
* says where each authored value went, and a draft is written into those
|
|
7
|
+
* places. Preview annotates the markup rather than
|
|
8
|
+
* rendering it. What is on screen stays the site's own markup, styles and
|
|
9
|
+
* scripts, with the words changed.
|
|
10
|
+
*
|
|
11
|
+
* - `data-openhi-block="<identifier>"` wraps each block.
|
|
12
|
+
* - `data-openhi-field="<name>"` holds one of its values. Add
|
|
13
|
+
* `data-openhi-html` when the build renders that value as HTML.
|
|
14
|
+
* - `data-openhi-list="<name>"` holds a repeating value, and
|
|
15
|
+
* `data-openhi-entry` marks each item in it. An item's own values are
|
|
16
|
+
* fields inside it. An item that is just a string is written into the
|
|
17
|
+
* entry's field when it has one, and into the entry itself when not.
|
|
18
|
+
*
|
|
19
|
+
* Text, lists, order and removal preview exactly. A value the build left
|
|
20
|
+
* out entirely, such as a lede that was empty, has nowhere to go until the
|
|
21
|
+
* next build, and neither has a block the page did not have: that one gets
|
|
22
|
+
* a stand-in saying so.
|
|
23
|
+
*/
|
|
24
|
+
export const BLOCK = "data-openhi-block";
|
|
25
|
+
export const FIELD = "data-openhi-field";
|
|
26
|
+
export const HTML = "data-openhi-html";
|
|
27
|
+
export const LIST = "data-openhi-list";
|
|
28
|
+
export const ENTRY = "data-openhi-entry";
|
|
29
|
+
export const HIDDEN = "data-openhi-hidden";
|
|
30
|
+
const STAND_IN = "data-openhi-stand-in";
|
|
31
|
+
export function createDraftPatcher(document, options) {
|
|
32
|
+
// What each element held as built, so a value the draft stops setting
|
|
33
|
+
// goes back to what the page had rather than keeping the last keystroke.
|
|
34
|
+
const built = new WeakMap();
|
|
35
|
+
// The last value written, so an unchanged field is not rewritten on every
|
|
36
|
+
// keystroke somewhere else on the page.
|
|
37
|
+
const written = new WeakMap();
|
|
38
|
+
// A copy of each list's first entry as built, so a list emptied by the
|
|
39
|
+
// draft can still grow again.
|
|
40
|
+
const templates = new WeakMap();
|
|
41
|
+
let start;
|
|
42
|
+
const hide = (element, hidden) => {
|
|
43
|
+
if (hidden)
|
|
44
|
+
element.setAttribute(HIDDEN, "");
|
|
45
|
+
else
|
|
46
|
+
element.removeAttribute(HIDDEN);
|
|
47
|
+
};
|
|
48
|
+
const write = (element, value) => {
|
|
49
|
+
if (!built.has(element))
|
|
50
|
+
built.set(element, element.innerHTML);
|
|
51
|
+
if (value === undefined || value === null) {
|
|
52
|
+
hide(element, false);
|
|
53
|
+
const original = built.get(element) ?? "";
|
|
54
|
+
if (written.has(element)) {
|
|
55
|
+
element.innerHTML = original;
|
|
56
|
+
written.delete(element);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (typeof value !== "string" && typeof value !== "number")
|
|
61
|
+
return;
|
|
62
|
+
const text = String(value);
|
|
63
|
+
hide(element, text.length === 0);
|
|
64
|
+
if (written.get(element) === text)
|
|
65
|
+
return;
|
|
66
|
+
written.set(element, text);
|
|
67
|
+
if (element.hasAttribute(HTML))
|
|
68
|
+
element.innerHTML = options.sanitise(text);
|
|
69
|
+
else
|
|
70
|
+
element.textContent = text;
|
|
71
|
+
};
|
|
72
|
+
/** The fields and lists that belong to `owner` and to nothing inside it. */
|
|
73
|
+
const ownedBy = (owner, selector, boundary) => [...owner.querySelectorAll(selector)].filter((element) => {
|
|
74
|
+
const nearest = element.parentElement?.closest(boundary) ?? null;
|
|
75
|
+
return nearest === owner || nearest === null || !owner.contains(nearest);
|
|
76
|
+
});
|
|
77
|
+
const fill = (owner, data) => {
|
|
78
|
+
for (const field of ownedBy(owner, `[${FIELD}]`, `[${ENTRY}],[${BLOCK}]`)) {
|
|
79
|
+
write(field, data[field.getAttribute(FIELD) ?? ""]);
|
|
80
|
+
}
|
|
81
|
+
for (const list of ownedBy(owner, `[${LIST}]`, `[${ENTRY}],[${BLOCK}]`)) {
|
|
82
|
+
fillList(list, data[list.getAttribute(LIST) ?? ""]);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const fillList = (list, value) => {
|
|
86
|
+
// Absent is "as built": a draft that says nothing about a list, because
|
|
87
|
+
// Studio has no editor for it, leaves it alone.
|
|
88
|
+
if (!Array.isArray(value))
|
|
89
|
+
return;
|
|
90
|
+
const entries = ownedBy(list, `[${ENTRY}]`, `[${LIST}]`);
|
|
91
|
+
const first = entries[0];
|
|
92
|
+
if (first !== undefined && !templates.has(list)) {
|
|
93
|
+
templates.set(list, first.cloneNode(true));
|
|
94
|
+
}
|
|
95
|
+
const template = templates.get(list);
|
|
96
|
+
if (template === undefined)
|
|
97
|
+
return;
|
|
98
|
+
value.forEach((item, index) => {
|
|
99
|
+
let entry = entries[index];
|
|
100
|
+
if (entry === undefined) {
|
|
101
|
+
entry = template.cloneNode(true);
|
|
102
|
+
options.onClone?.(entry);
|
|
103
|
+
const last = entries.at(-1);
|
|
104
|
+
if (last !== undefined)
|
|
105
|
+
last.after(entry);
|
|
106
|
+
else
|
|
107
|
+
list.append(entry);
|
|
108
|
+
entries.push(entry);
|
|
109
|
+
}
|
|
110
|
+
hide(entry, false);
|
|
111
|
+
if (typeof item === "object" && item !== null) {
|
|
112
|
+
fill(entry, item);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const fields = ownedBy(entry, `[${FIELD}]`, `[${ENTRY}],[${BLOCK}]`);
|
|
116
|
+
if (fields.length === 0)
|
|
117
|
+
write(entry, item);
|
|
118
|
+
else
|
|
119
|
+
for (const field of fields)
|
|
120
|
+
write(field, item);
|
|
121
|
+
});
|
|
122
|
+
for (const extra of entries.slice(value.length))
|
|
123
|
+
hide(extra, true);
|
|
124
|
+
};
|
|
125
|
+
const standIn = (section) => {
|
|
126
|
+
const element = document.createElement("div");
|
|
127
|
+
element.setAttribute(BLOCK, section.identifier);
|
|
128
|
+
element.setAttribute(STAND_IN, "");
|
|
129
|
+
const note = document.createElement("p");
|
|
130
|
+
const name = options.nameOf(section.component);
|
|
131
|
+
note.textContent = `${name === undefined ? "New block" : `New ${name} block`}. It appears here once the site is built with it.`;
|
|
132
|
+
element.append(note);
|
|
133
|
+
return element;
|
|
134
|
+
};
|
|
135
|
+
/** The element after `node` among its siblings, skipping text. */
|
|
136
|
+
const nextElement = (node) => {
|
|
137
|
+
let next = node.nextSibling;
|
|
138
|
+
while (next !== null && next.nodeType !== 1)
|
|
139
|
+
next = next.nextSibling;
|
|
140
|
+
return next;
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
apply(sections) {
|
|
144
|
+
const blocks = [...document.querySelectorAll(`[${BLOCK}]`)];
|
|
145
|
+
const first = blocks[0];
|
|
146
|
+
if (first === undefined)
|
|
147
|
+
return;
|
|
148
|
+
const parent = first.parentElement;
|
|
149
|
+
if (parent === null)
|
|
150
|
+
return;
|
|
151
|
+
if (start === undefined || !start.isConnected) {
|
|
152
|
+
start = document.createComment("openhi-preview");
|
|
153
|
+
parent.insertBefore(start, first);
|
|
154
|
+
}
|
|
155
|
+
const byId = new Map(blocks.map((element) => [element.getAttribute(BLOCK) ?? "", element]));
|
|
156
|
+
const shown = new Set();
|
|
157
|
+
let previous = start;
|
|
158
|
+
for (const section of sections) {
|
|
159
|
+
const element = byId.get(section.identifier) ?? standIn(section);
|
|
160
|
+
shown.add(element);
|
|
161
|
+
hide(element, false);
|
|
162
|
+
if (!element.hasAttribute(STAND_IN))
|
|
163
|
+
fill(element, section.data);
|
|
164
|
+
// Moved only when out of place: moving a node restarts whatever it
|
|
165
|
+
// was doing, and most edits reorder nothing.
|
|
166
|
+
if (element.parentElement === parent || !element.isConnected) {
|
|
167
|
+
if (nextElement(previous) !== element) {
|
|
168
|
+
parent.insertBefore(element, previous.nextSibling);
|
|
169
|
+
}
|
|
170
|
+
previous = element;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const element of blocks) {
|
|
174
|
+
if (shown.has(element))
|
|
175
|
+
continue;
|
|
176
|
+
// A stand-in the draft dropped goes; a block this page was built
|
|
177
|
+
// with is only hidden, so undoing the delete brings it straight back.
|
|
178
|
+
if (element.hasAttribute(STAND_IN))
|
|
179
|
+
element.remove();
|
|
180
|
+
else
|
|
181
|
+
hide(element, true);
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { BLOCK, createDraftPatcher, ENTRY, FIELD, HIDDEN, HTML, LIST, } from "./apply-draft.js";
|
|
2
|
+
export type { DraftPatcher, DraftPatcherOptions } from "./apply-draft.js";
|
|
3
|
+
export { block, entry, field, list } from "./marks.js";
|
|
4
|
+
export type { Marks } from "./marks.js";
|
|
5
|
+
export { isPreviewFrame, startPreview, WAITING } from "./runtime.js";
|
|
6
|
+
export type { PreviewOptions } from "./runtime.js";
|
|
7
|
+
export { isStudioOrigin } from "./studio-origin.js";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { BLOCK, createDraftPatcher, ENTRY, FIELD, HIDDEN, HTML, LIST, } from "./apply-draft.js";
|
|
2
|
+
export { block, entry, field, list } from "./marks.js";
|
|
3
|
+
export { isPreviewFrame, startPreview, WAITING } from "./runtime.js";
|
|
4
|
+
export { isStudioOrigin } from "./studio-origin.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attributes a site spreads onto its own markup so Studio's preview
|
|
3
|
+
* knows where each authored value went. A site annotates its markup and never
|
|
4
|
+
* re-renders a pushed page.
|
|
5
|
+
*
|
|
6
|
+
* ```astro
|
|
7
|
+
* <section {...block(section.identifier)}>
|
|
8
|
+
* <h2 {...field("title", { html: true })} set:html={title} />
|
|
9
|
+
* <ul {...list("items")}>
|
|
10
|
+
* {items.map((item) => <li {...entry()}><span {...field("label")}>{item.label}</span></li>)}
|
|
11
|
+
* </ul>
|
|
12
|
+
* </section>
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export type Marks = Record<string, string>;
|
|
16
|
+
/** Wraps a block. `identifier` is the section's, which is how Studio finds it. */
|
|
17
|
+
export declare function block(identifier: string): Marks;
|
|
18
|
+
/** Holds one authored value. `html` when the build renders that value as HTML. */
|
|
19
|
+
export declare function field(name: string, options?: {
|
|
20
|
+
readonly html?: boolean;
|
|
21
|
+
}): Marks;
|
|
22
|
+
/** Holds a repeating value; each item in it is marked with `entry()`. */
|
|
23
|
+
export declare function list(name: string): Marks;
|
|
24
|
+
/** One item of a list. Its own values are `field()`s inside it. */
|
|
25
|
+
export declare function entry(): Marks;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { BLOCK, ENTRY, FIELD, HTML, LIST } from "./apply-draft.js";
|
|
2
|
+
/** Wraps a block. `identifier` is the section's, which is how Studio finds it. */
|
|
3
|
+
export function block(identifier) {
|
|
4
|
+
return { [BLOCK]: identifier };
|
|
5
|
+
}
|
|
6
|
+
/** Holds one authored value. `html` when the build renders that value as HTML. */
|
|
7
|
+
export function field(name, options = {}) {
|
|
8
|
+
return { [FIELD]: name, ...(options.html === true && { [HTML]: "" }) };
|
|
9
|
+
}
|
|
10
|
+
/** Holds a repeating value; each item in it is marked with `entry()`. */
|
|
11
|
+
export function list(name) {
|
|
12
|
+
return { [LIST]: name };
|
|
13
|
+
}
|
|
14
|
+
/** One item of a list. Its own values are `field()`s inside it. */
|
|
15
|
+
export function entry() {
|
|
16
|
+
return { [ENTRY]: "" };
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Set on `<html>` by `<OpenhiPreview />` while the page waits for its first
|
|
3
|
+
* draft, so the version it was built with does not flash first. The
|
|
4
|
+
* component also clears it after a moment, in case no draft ever comes.
|
|
5
|
+
*/
|
|
6
|
+
export declare const WAITING = "data-openhi-waiting";
|
|
7
|
+
export interface PreviewOptions {
|
|
8
|
+
/** Block code to display name, for the stand-in of a block the page was not built with. */
|
|
9
|
+
readonly names?: Readonly<Record<string, string>>;
|
|
10
|
+
/** Called on each list entry copied to make room for a new item. */
|
|
11
|
+
readonly onClone?: (entry: Element) => void;
|
|
12
|
+
/** Origins to trust beyond OpenHI's own Studio, exactly as `location.origin` writes them. */
|
|
13
|
+
readonly studioOrigins?: readonly string[];
|
|
14
|
+
}
|
|
15
|
+
/** Whether this page was opened by Studio's preview frame. */
|
|
16
|
+
export declare function isPreviewFrame(window: Window): boolean;
|
|
17
|
+
export declare function startPreview(window: Window, options?: PreviewOptions): void;
|