@nickpaustian/tela 0.1.2 → 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 (43) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -1
  3. package/bin/tela.ts +18 -2
  4. package/lib/index.js +172 -7
  5. package/package.json +5 -2
  6. package/scripts/check-components.ts +20 -0
  7. package/scripts/media-sync.ts +41 -0
  8. package/scripts/republish.ts +24 -0
  9. package/src/api.ts +3 -3
  10. package/src/components/EntryEditor.lsp +174 -11
  11. package/src/components/EntryList.lsp +8 -0
  12. package/src/components/Field.lsp +92 -2
  13. package/src/components/LinkField.lsp +477 -0
  14. package/src/components/MarkdownField.lsp +19 -24
  15. package/src/components/PersonField.lsp +255 -0
  16. package/src/components/ReferenceField.lsp +22 -1
  17. package/src/components/RepeaterField.lsp +141 -13
  18. package/src/components/ToggleField.lsp +63 -0
  19. package/src/config/fields.ts +134 -1
  20. package/src/config/seo.ts +4 -2
  21. package/src/config/types.ts +158 -7
  22. package/src/content/derive-values.ts +14 -3
  23. package/src/content/entries.ts +1 -1
  24. package/src/content/entry.ts +15 -1
  25. package/src/content/export.ts +173 -14
  26. package/src/content/git.ts +1 -1
  27. package/src/content/hooks.ts +75 -0
  28. package/src/content/link-address.ts +168 -0
  29. package/src/content/links.ts +13 -0
  30. package/src/content/person.ts +11 -0
  31. package/src/content/placement.ts +48 -0
  32. package/src/content/references.ts +48 -4
  33. package/src/content/rules.ts +24 -4
  34. package/src/content/shape.ts +192 -0
  35. package/src/content/store.ts +17 -0
  36. package/src/content/url.ts +15 -1
  37. package/src/content/users.ts +32 -0
  38. package/src/content/validate.ts +12 -2
  39. package/src/index.ts +4 -1
  40. package/src/keys.ts +47 -0
  41. package/src/media/index.ts +5 -0
  42. package/src/server/index.ts +168 -34
  43. package/src/server/library-routes.ts +11 -3
@@ -5,6 +5,8 @@ import { sql } from "../db/client.ts"
5
5
  import { findCollection } from "./collections.ts"
6
6
  import { DIALECT } from "./richtext.ts"
7
7
  import { withDerived } from "./derive-values.ts"
8
+ import type { Collection } from "../config/types.ts"
9
+ import { dataShape, shapePath, shapeProblem, type DataShape } from "./shape.ts"
8
10
  import {
9
11
  collectReferences,
10
12
  findReferrers,
@@ -75,15 +77,31 @@ export function dialectDocument() {
75
77
  }
76
78
 
77
79
  export function entryPath(collection: string, slug: string) {
80
+ if (isDataSource(collection)) return join("content", "data", `${collection}.json`)
78
81
  return join("content", collection, `${slug}.json`)
79
82
  }
80
83
 
84
+ const isDataSource = (collection: string) => findCollection(collection)?.data === true
85
+
86
+ /**
87
+ * What goes in an entry's file: references as slugs, derived values beside
88
+ * their parts. A data source's slug is only how Tela finds its one record, so
89
+ * it stays out of the file.
90
+ */
91
+ function fileData(collection: Collection, data: Record<string, unknown>, slugs: Map<string, unknown>) {
92
+ const out = withDerived(collection, withSlugs(collection, data, slugs))
93
+ if (!collection.data) return out
94
+ const { slug: _slug, ...rest } = out
95
+ return rest
96
+ }
97
+
81
98
  export function indexPath(collection: string) {
82
99
  return join("content", collection, "index.json")
83
100
  }
84
101
 
85
102
  /** `cms:post:hello-world` — the key a page uses for its own entry. */
86
103
  export function entryCell(collection: string, slug: string) {
104
+ if (isDataSource(collection)) return `cms:data:${collection}`
87
105
  return `cms:${collection}:${slug}`
88
106
  }
89
107
 
@@ -174,10 +192,23 @@ export async function exportRelease(
174
192
  }
175
193
  }
176
194
 
177
- const slugs = new Map<string, unknown>([
178
- ...(await publishedReferences([...wanted].filter((id) => !staged.has(id)))),
179
- ...staged,
180
- ])
195
+ const elsewhere = [...wanted].filter((id) => !staged.has(id))
196
+ const slugs = new Map<string, unknown>([...(await publishedReferences(elsewhere, { pictures: "named" })), ...staged])
197
+ // A data source stands alone for other apps, so its pictures are copied in.
198
+ const sourced = [...published, ...alsoWrite].some((row) => findCollection(row.collection)?.data)
199
+ const copied = sourced ? new Map<string, unknown>([...(await publishedReferences(elsewhere)), ...staged]) : slugs
200
+ const referencesFor = (collection: Collection) => (collection.data ? copied : slugs)
201
+
202
+ // Before anything is written, so a refused shape leaves the repo untouched.
203
+ const shapes = new Map<string, DataShape>()
204
+ for (const row of [...published, ...alsoWrite]) {
205
+ const collection = findCollection(row.collection)
206
+ if (!collection?.data || shapes.has(collection.name)) continue
207
+ const next = dataShape(collection)
208
+ const problem = shapeProblem(await read(options.root, shapePath(collection.name)), next)
209
+ if (problem) throw problem
210
+ shapes.set(collection.name, next)
211
+ }
181
212
 
182
213
  // A slug is a file name, so moving one leaves the old file behind. Removed
183
214
  // before anything is written, so a release that renames A to B and B to
@@ -210,16 +241,31 @@ export async function exportRelease(
210
241
  await write(
211
242
  options.root,
212
243
  path,
213
- collection
214
- ? withDerived(collection, withSlugs(collection, row.data, slugs))
215
- : row.data,
244
+ collection ? fileData(collection, row.data, referencesFor(collection)) : row.data,
216
245
  )
217
246
 
218
247
  files.push(path)
219
248
  cells.push(entryCell(row.collection, slug))
220
- touched.add(row.collection)
249
+ if (!collection?.data) touched.add(row.collection)
221
250
  }
222
251
 
252
+ for (const [name, shape] of shapes) {
253
+ const path = shapePath(name)
254
+ if (JSON.stringify(await read(options.root, path)) === JSON.stringify(shape)) continue
255
+ await write(options.root, path, shape)
256
+ files.push(path)
257
+ }
258
+
259
+ const pictures = await writePictures(
260
+ [...published, ...alsoWrite].flatMap((row) => {
261
+ const collection = findCollection(row.collection)
262
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
263
+ }),
264
+ options.root,
265
+ )
266
+ files.push(...pictures.files)
267
+ cells.push(...pictures.cells)
268
+
223
269
  for (const collection of touched) {
224
270
  const path = indexPath(collection)
225
271
  const rows = await publishedRows(collection, releaseId)
@@ -284,6 +330,8 @@ export async function exportRemoval(
284
330
  const files = [path]
285
331
  const cells = [entryCell(collection, slug)]
286
332
 
333
+ if (isDataSource(collection)) return { files, cells }
334
+
287
335
  // The index always changes: the entry has left it.
288
336
  const indexFile = indexPath(collection)
289
337
  const rows = await publishedRows(collection)
@@ -341,10 +389,10 @@ async function rewriteWithout(
341
389
  if (!collection || !slug) continue
342
390
 
343
391
  const wanted = collectReferences(collection, row.data).flatMap((one) => one.ids)
344
- const slugs = await publishedReferences(wanted)
392
+ const slugs = await publishedReferences(wanted, { pictures: collection.data ? "copied" : "named" })
345
393
 
346
394
  const path = entryPath(row.collection, slug)
347
- await write(root, path, withDerived(collection, withSlugs(collection, row.data, slugs)))
395
+ await write(root, path, fileData(collection, row.data, slugs))
348
396
 
349
397
  files.push(path)
350
398
  cells.push(entryCell(row.collection, slug))
@@ -467,14 +515,12 @@ async function writeMissing(
467
515
  const wanted = definition
468
516
  ? collectReferences(definition, row.data).flatMap((one) => one.ids)
469
517
  : []
470
- const slugs = await publishedReferences(wanted)
518
+ const slugs = await publishedReferences(wanted, { pictures: definition?.data ? "copied" : "named" })
471
519
 
472
520
  await write(
473
521
  root,
474
522
  path,
475
- definition
476
- ? withDerived(definition, withSlugs(definition, row.data, slugs))
477
- : row.data,
523
+ definition ? fileData(definition, row.data, slugs) : row.data,
478
524
  )
479
525
 
480
526
  files.push(path)
@@ -506,3 +552,116 @@ async function read(root: string, path: string) {
506
552
  return null
507
553
  }
508
554
  }
555
+
556
+ /** Where a picture a page names is published: `content/media/<id>.json`. */
557
+ export const picturePath = (id: string) => join("content", "media", `${id}.json`)
558
+
559
+ /** `cms:media:<id>` - the key a page's picture is read under. */
560
+ export const pictureCell = (id: string) => `cms:media:${id}`
561
+
562
+ /**
563
+ * The pictures some entries name, each written to its own file when what it
564
+ * says has changed. Ids that aren't pictures are passed over, and a picture
565
+ * the library no longer has is left unwritten, like the reference to it.
566
+ */
567
+ async function writePictures(ids: string[], root: string): Promise<ExportResult> {
568
+ const files: string[] = []
569
+ const cells: string[] = []
570
+ const unique = [...new Set(ids)]
571
+ if (!unique.length) return { files, cells }
572
+
573
+ const media = await sql`
574
+ select id from entries
575
+ where collection = 'media' and deleted_at is null
576
+ and id = any(string_to_array(${unique.join(",")}, ',')::uuid[])
577
+ `
578
+ const pictureIds = media.map((row: any) => String(row.id))
579
+ if (!pictureIds.length) return { files, cells }
580
+
581
+ const resolved = await publishedReferences(pictureIds)
582
+ for (const id of pictureIds) {
583
+ const picture = resolved.get(id)
584
+ if (picture === undefined) continue
585
+ const path = picturePath(id)
586
+ if (JSON.stringify(await read(root, path)) === JSON.stringify(picture)) continue
587
+ await write(root, path, picture)
588
+ files.push(path)
589
+ cells.push(pictureCell(id))
590
+ }
591
+ return { files, cells }
592
+ }
593
+
594
+ /**
595
+ * Pictures whose words or file changed (a credit corrected in the library, a
596
+ * new alt text), published again: each one's own file, and every data source
597
+ * using it, since those carry their pictures. Pages name a picture rather than
598
+ * copy it, so its file is all they need; a picture the library has dropped
599
+ * loses its file, and the pages naming it rebuild without it.
600
+ */
601
+ export async function republishPictures(ids: string[], options: { root: string }): Promise<ExportResult> {
602
+ const files: string[] = []
603
+ const cells: string[] = []
604
+ const resolved = await publishedReferences(ids)
605
+
606
+ for (const id of new Set(ids)) {
607
+ const path = picturePath(id)
608
+ const was = await read(options.root, path)
609
+ const now = resolved.get(id)
610
+ if (now === undefined) {
611
+ if (was === null) continue
612
+ await rm(join(options.root, path), { force: true })
613
+ } else {
614
+ if (JSON.stringify(was) === JSON.stringify(now)) continue
615
+ await write(options.root, path, now)
616
+ }
617
+ files.push(path)
618
+ cells.push(pictureCell(id))
619
+ }
620
+
621
+ const sources: { id: string }[] = []
622
+ for (const id of new Set(ids)) {
623
+ for (const one of await findReferrers(id)) {
624
+ if (findCollection(one.collection)?.data) sources.push({ id: one.id })
625
+ }
626
+ }
627
+ if (sources.length) {
628
+ const live = await sql`
629
+ select e.id from entries e
630
+ where e.published_version_id is not null
631
+ and e.id = any(string_to_array(${sources.map((one) => one.id).join(",")}, ',')::uuid[])
632
+ `
633
+ const rewritten = await rewriteWithout(live.map((row: any) => ({ id: String(row.id) })), options.root)
634
+ for (const [i, path] of rewritten.files.entries()) {
635
+ // Written again either way; only a change is worth a rebuild.
636
+ files.push(path)
637
+ cells.push(rewritten.cells[i]!)
638
+ }
639
+ }
640
+
641
+ return { files, cells }
642
+ }
643
+
644
+ /**
645
+ * Published entries written again from their published versions, under the
646
+ * rules publishing follows now, with the pictures they name: for when how
647
+ * content is written changes (pictures named rather than copied, say). Drafts
648
+ * stay drafts; nothing that isn't live is published.
649
+ */
650
+ export async function republishEntries(options: { root: string; collections?: string[] }): Promise<ExportResult> {
651
+ const live = await sql`
652
+ select e.id, e.collection, v.data
653
+ from entries e
654
+ join entry_versions v on v.id = e.published_version_id
655
+ where e.deleted_at is null
656
+ `
657
+ const rows = live.filter((row: any) => !options.collections || options.collections.includes(String(row.collection)))
658
+ const rewritten = await rewriteWithout(rows.map((row: any) => ({ id: String(row.id) })), options.root)
659
+ const pictures = await writePictures(
660
+ rows.flatMap((row: any) => {
661
+ const collection = findCollection(String(row.collection))
662
+ return collection && !collection.data ? collectReferences(collection, row.data ?? {}).flatMap((one) => one.ids) : []
663
+ }),
664
+ options.root,
665
+ )
666
+ return { files: [...rewritten.files, ...pictures.files], cells: [...rewritten.cells, ...pictures.cells] }
667
+ }
@@ -139,7 +139,7 @@ export function commitMessage(
139
139
  label: string | null,
140
140
  exported: ExportResult,
141
141
  ): string {
142
- const entries = exported.files.filter((file) => !file.endsWith("index.json"))
142
+ const entries = exported.files.filter((file) => !file.endsWith("index.json") && !file.endsWith(".schema.json"))
143
143
  const subject = label
144
144
  ? `Publish ${label}`
145
145
  : entries.length === 1
@@ -0,0 +1,75 @@
1
+ import type { PublishHook } from "../config/types.ts"
2
+ import type { CommitResult } from "./git.ts"
3
+
4
+ export type PublishEvent = "published" | "unpublished" | "removed"
5
+
6
+ export interface PublishNotice {
7
+ event: PublishEvent
8
+ commit: string | null
9
+ files: string[]
10
+ cells: string[]
11
+ collections: string[]
12
+ }
13
+
14
+ /** `content/posts/a.json` is posts; `content/data/hours.json` is the hours data source. */
15
+ export function collectionsIn(files: string[]): string[] {
16
+ const names = files.flatMap((file) => {
17
+ const parts = file.split("/")
18
+ if (parts[0] !== "content" || parts.length < 3 || parts[1] === ".tela") return []
19
+ if (parts[1] === "data") return [parts[2]!.replace(/(\.schema)?\.json$/, "")]
20
+ return [parts[1]!]
21
+ })
22
+ return [...new Set(names)]
23
+ }
24
+
25
+ export function noticeOf(event: PublishEvent, commit: CommitResult): PublishNotice | null {
26
+ if (!commit.sha && !commit.pushed) return null
27
+ return { event, commit: commit.sha, files: commit.files, cells: commit.cells, collections: collectionsIn(commit.files) }
28
+ }
29
+
30
+ const wants = (hook: PublishHook, notice: PublishNotice) =>
31
+ !hook.collections?.length || notice.collections.some((name) => hook.collections!.includes(name))
32
+
33
+ async function call(hook: PublishHook, notice: PublishNotice, timeoutMs: number) {
34
+ const res = await fetch(hook.url, {
35
+ method: "POST",
36
+ headers: {
37
+ "content-type": "application/json",
38
+ ...(hook.token ? { authorization: `Bearer ${hook.token}` } : {}),
39
+ },
40
+ body: JSON.stringify(notice),
41
+ signal: AbortSignal.timeout(timeoutMs),
42
+ })
43
+ if (!res.ok) throw new Error(`answered ${res.status}`)
44
+ }
45
+
46
+ /**
47
+ * Tell each hook what changed. Never throws: the content is already live, so a
48
+ * hook that is down is logged and tried once more, not a failed publish.
49
+ */
50
+ export async function notifyHooks(
51
+ hooks: PublishHook[] | undefined,
52
+ notice: PublishNotice | null,
53
+ { retryAfterMs = 2000, timeoutMs = 10_000 } = {},
54
+ ): Promise<{ url: string; ok: boolean }[]> {
55
+ if (!notice || !hooks?.length) return []
56
+ return Promise.all(
57
+ hooks
58
+ .filter((hook) => wants(hook, notice))
59
+ .map(async (hook) => {
60
+ for (const attempt of [1, 2]) {
61
+ try {
62
+ await call(hook, notice, timeoutMs)
63
+ return { url: hook.url, ok: true }
64
+ } catch (error) {
65
+ if (attempt === 2) {
66
+ console.error(`[tela] publish hook ${hook.url} failed: ${(error as Error).message}`)
67
+ return { url: hook.url, ok: false }
68
+ }
69
+ await Bun.sleep(retryAfterMs)
70
+ }
71
+ }
72
+ return { url: hook.url, ok: false }
73
+ }),
74
+ )
75
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * What an editor typed into a link field, read the way they meant it.
3
+ *
4
+ * Words are a search for a page. Anything shaped like an address is tidied
5
+ * into one: an email gets `mailto:`, a phone number `tel:`, a bare
6
+ * `example.org` its `https://`, and an address on this site's own hosts
7
+ * becomes the path, so it keeps working wherever the site is served from.
8
+ */
9
+ export type TypedLink =
10
+ | { kind: "empty" }
11
+ | { kind: "words"; words: string }
12
+ | { kind: "address"; href: string; label: string; own: boolean }
13
+
14
+ const EMAIL = /^[^\s@/:]+@[^\s@/]+\.[^\s@/]+$/
15
+ const PHONE = /^\+?[\d ()-]{8,}$/
16
+ const DOMAIN = /^[\w-]+(\.[\w-]+)*\.[a-z]{2,}(:\d+)?([/?#]\S*)?$/i
17
+
18
+ const bareHost = (host: string) => host.toLowerCase().replace(/^www\./, "")
19
+
20
+ /** The hosts an address on this site may be written with, from its root addresses. */
21
+ export function hostsOf(roots: (string | undefined | null)[]): string[] {
22
+ const hosts = new Set<string>()
23
+ for (const root of roots) {
24
+ if (!root) continue
25
+ try {
26
+ hosts.add(bareHost(new URL(root).host))
27
+ } catch {
28
+ // A root that is not an address names no host.
29
+ }
30
+ }
31
+ return [...hosts]
32
+ }
33
+
34
+ function fromUrl(text: string, hosts: string[]): TypedLink {
35
+ let url: URL
36
+ try {
37
+ url = new URL(text)
38
+ } catch {
39
+ return { kind: "words", words: text }
40
+ }
41
+ if (url.protocol !== "http:" && url.protocol !== "https:") return { kind: "words", words: text }
42
+ if (hosts.includes(bareHost(url.host))) {
43
+ const path = url.pathname + url.search + url.hash
44
+ return { kind: "address", href: path, label: path, own: true }
45
+ }
46
+ return { kind: "address", href: url.href, label: url.host.replace(/^www\./, "") + (url.pathname === "/" ? "" : url.pathname), own: false }
47
+ }
48
+
49
+ export function readTypedLink(typed: string | undefined | null, hosts: string[] = []): TypedLink {
50
+ const text = (typed ?? "").trim()
51
+ if (!text) return { kind: "empty" }
52
+
53
+ if (/^tela:/i.test(text)) return { kind: "address", href: text, label: text, own: true }
54
+ if (/^mailto:/i.test(text)) return { kind: "address", href: text, label: text.slice(7), own: false }
55
+ if (/^tel:/i.test(text)) return { kind: "address", href: text, label: text.slice(4), own: false }
56
+ if (EMAIL.test(text)) return { kind: "address", href: "mailto:" + text, label: text, own: false }
57
+ if (PHONE.test(text) && (text.match(/\d/g) ?? []).length >= 8) {
58
+ return { kind: "address", href: "tel:" + text.replace(/[^\d+]/g, ""), label: text, own: false }
59
+ }
60
+ if (text.startsWith("/") && !text.startsWith("//")) return { kind: "address", href: text, label: text, own: true }
61
+ if (text.startsWith("#")) return { kind: "address", href: text, label: text, own: true }
62
+ if (/^https?:\/\//i.test(text)) return fromUrl(text, hosts)
63
+ if (text.startsWith("//")) return fromUrl("https:" + text, hosts)
64
+ if (!/\s/.test(text) && DOMAIN.test(text)) return fromUrl("https://" + text, hosts)
65
+
66
+ return { kind: "words", words: text }
67
+ }
68
+
69
+ /** A path to compare with an entry's address: no query, no fragment, no trailing slash. */
70
+ export function comparablePath(href: string): string {
71
+ const path = href.replace(/[?#].*$/, "").replace(/\/+$/, "")
72
+ return path || "/"
73
+ }
74
+
75
+ /** The fragment of an address, kept when it is swapped for the page it names. */
76
+ export const fragmentOf = (href: string) => /#.*$/.exec(href)?.[0] ?? ""
77
+
78
+ /**
79
+ * What a link field may go to.
80
+ *
81
+ * `pages` is anything on this site: an entry picked from the list, or a path.
82
+ * `files` is the library's files; `web` another site's address; `sections` a
83
+ * part of the same page; `email` and `phone` writing to or calling someone.
84
+ */
85
+ export const LINK_KINDS = ["pages", "files", "web", "sections", "email", "phone"] as const
86
+ export type LinkKind = (typeof LINK_KINDS)[number]
87
+
88
+ /** What a link field takes when it says nothing: everything but files. */
89
+ export const DEFAULT_LINK_KINDS: LinkKind[] = ["pages", "web", "sections", "email", "phone"]
90
+
91
+ export function acceptedKinds(accepts: readonly string[] | undefined): LinkKind[] {
92
+ const known = (accepts ?? DEFAULT_LINK_KINDS).filter((one): one is LinkKind => (LINK_KINDS as readonly string[]).includes(one))
93
+ return known.length ? known : DEFAULT_LINK_KINDS
94
+ }
95
+
96
+ /** Which kind an address is. */
97
+ export function kindOfHref(href: string): LinkKind | null {
98
+ if (/^tela:media\//i.test(href)) return "files"
99
+ if (/^tela:/i.test(href) || (href.startsWith("/") && !href.startsWith("//"))) return "pages"
100
+ if (href.startsWith("#")) return "sections"
101
+ if (/^mailto:/i.test(href)) return "email"
102
+ if (/^tel:/i.test(href)) return "phone"
103
+ if (/^https?:\/\//i.test(href)) return "web"
104
+ return null
105
+ }
106
+
107
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
108
+ const escapeName = (name: string) => name.replace(/[^\w-]/g, "")
109
+
110
+ /** The pattern a stored link must match, for the kinds a field takes. */
111
+ export function linkPattern(kinds: LinkKind[], collections?: string[]): string {
112
+ const entries = collections?.length ? `(${collections.map(escapeName).join("|")})` : "(?!media/)[\\w-]+"
113
+ const parts: Record<LinkKind, string[]> = {
114
+ pages: [`tela:${entries}/${UUID}(#\\S*)?`, "/(?!/)\\S*"],
115
+ files: [`tela:media/${UUID}`],
116
+ web: ["https?://\\S+"],
117
+ sections: ["#\\S+"],
118
+ email: ["mailto:\\S+@\\S+"],
119
+ phone: ["tel:\\+?\\d+"],
120
+ }
121
+ return `^(${kinds.flatMap((kind) => parts[kind]).join("|")})$`
122
+ }
123
+
124
+ const listed = (words: string[]) =>
125
+ words.length <= 1 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`
126
+
127
+ /** What the box says before anything is typed. */
128
+ export function linkPlaceholder(kinds: LinkKind[]): string {
129
+ const search = [kinds.includes("pages") ? "pages" : "", kinds.includes("files") ? "files" : ""].filter(Boolean)
130
+ const paste = [
131
+ kinds.includes("web") ? "an address" : kinds.includes("pages") ? "a path" : "",
132
+ kinds.includes("email") ? "an email" : "",
133
+ kinds.includes("phone") ? "a phone number" : "",
134
+ ].filter(Boolean)
135
+ const searching = search.length ? `Search ${search.join(" and ")}` : ""
136
+ const pasting = paste.length ? `paste ${listed(paste)}` : ""
137
+ const said = [searching, pasting].filter(Boolean).join(", or ")
138
+ return said.charAt(0).toUpperCase() + said.slice(1)
139
+ }
140
+
141
+ /** What to say when a link is not one the field takes. */
142
+ export function linkMessage(kinds: LinkKind[]): string {
143
+ const choose = [kinds.includes("pages") ? "a page" : "", kinds.includes("files") ? "a file" : ""].filter(Boolean)
144
+ const paste = [
145
+ kinds.includes("web") ? "a full address" : "",
146
+ kinds.includes("email") ? "an email" : "",
147
+ kinds.includes("phone") ? "a phone number" : "",
148
+ ].filter(Boolean)
149
+ const said = [
150
+ choose.length ? `Choose ${choose.join(" or ")} from the list` : "",
151
+ paste.length ? `paste ${listed(paste)}` : "",
152
+ ]
153
+ .filter(Boolean)
154
+ .join(", or ")
155
+ return said.charAt(0).toUpperCase() + said.slice(1) + "."
156
+ }
157
+
158
+ const REFUSED: Record<LinkKind, string> = {
159
+ pages: "This link can't go to a page on this site.",
160
+ files: "This link can't go to a file.",
161
+ web: "This link can't go to another site.",
162
+ sections: "This link can't go to a part of the page.",
163
+ email: "This link can't be an email address.",
164
+ phone: "This link can't be a phone number.",
165
+ }
166
+
167
+ /** Why an address of this kind is turned away. */
168
+ export const refusedKind = (kind: LinkKind) => REFUSED[kind]
@@ -40,6 +40,19 @@ export function linkedEntries(markdown: string): EntryLink[] {
40
40
  }))
41
41
  }
42
42
 
43
+ /**
44
+ * What a link field publishes: an entry by its slug, a file by its address,
45
+ * anything else as written. Nothing, when what it named is not on the site.
46
+ */
47
+ export function publishedLink(value: string, resolved: Map<string, unknown>): string | undefined {
48
+ const link = parseLink(value)
49
+ if (!link) return value
50
+ const target = resolved.get(link.id)
51
+ if (typeof target === "string" && target) return linkTo(link.collection, target, link.fragment)
52
+ const src = target && typeof target === "object" ? (target as { src?: unknown }).src : undefined
53
+ return typeof src === "string" && src ? src : undefined
54
+ }
55
+
43
56
  /**
44
57
  * The markdown with each id swapped for what it publishes as, and each link
45
58
  * to something that publishes as nothing reduced to its words.
@@ -12,6 +12,17 @@ export function personName(person: Named): string {
12
12
  return full || text(person?.name) || text(person?.email)
13
13
  }
14
14
 
15
+ /**
16
+ * What to call somebody in public: their name, or nothing.
17
+ *
18
+ * Unlike `personName`, never their address. This is what leaves the CMS - a
19
+ * byline on a published page, a name offered to an editor who may not read
20
+ * accounts - and an address is not something either should be given.
21
+ */
22
+ export function publicName(person: Named): string {
23
+ return [text(person?.firstName), text(person?.lastName)].filter(Boolean).join(" ") || text(person?.name)
24
+ }
25
+
15
26
  /** Two letters to stand for somebody where there is no room for the name. */
16
27
  export function initialsOf(person: Named): string {
17
28
  const first = text(person?.firstName)
@@ -0,0 +1,48 @@
1
+ import type { Block } from "../config/types.ts"
2
+
3
+ /**
4
+ * Which blocks the picker offers, and where.
5
+ *
6
+ * Most blocks are the shared library and go anywhere. A block made `for` some
7
+ * pages is offered on those alone, in a group of its own, so one-off sections
8
+ * never crowd the library. A block that comes `once` leaves the picker when
9
+ * the list already holds it.
10
+ */
11
+
12
+ const trimmed = (path: string) => {
13
+ const bare = path.replace(/[?#].*$/, "").replace(/\/+$/, "")
14
+ return bare || "/"
15
+ }
16
+
17
+ /** Whether an address is one of the pages a block is for. `/x/*` is everything under `/x`. */
18
+ export function madeFor(path: string | null | undefined, patterns: readonly string[] | undefined): boolean {
19
+ if (!path || !patterns?.length) return false
20
+ const here = trimmed(path)
21
+ return patterns.some((pattern) => {
22
+ if (pattern.endsWith("/*")) {
23
+ const under = trimmed(pattern.slice(0, -2))
24
+ return here.startsWith(under === "/" ? "/" : under + "/")
25
+ }
26
+ return trimmed(pattern) === here
27
+ })
28
+ }
29
+
30
+ export interface Offered {
31
+ /** Made for this page. */
32
+ here: Block[]
33
+ /** The shared library. */
34
+ library: Block[]
35
+ }
36
+
37
+ export function offeredBlocks(blocks: readonly Block[], path: string | null | undefined, used: readonly string[] = []): Offered {
38
+ const available = blocks.filter((block) => !(block.once && used.includes(block.name)))
39
+ return {
40
+ here: available.filter((block) => block.for?.length && madeFor(path, block.for)),
41
+ library: available.filter((block) => !block.for?.length),
42
+ }
43
+ }
44
+
45
+ /** Blocks a list holds more than once that may only be there once. */
46
+ export function repeatedOnce(blocks: readonly Block[], used: readonly string[]): Block[] {
47
+ return blocks.filter((block) => block.once && used.filter((name) => name === block.name).length > 1)
48
+ }