@glw907/cairn-cms 0.18.0 → 0.24.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 (106) hide show
  1. package/dist/components/DeleteDialog.svelte +81 -0
  2. package/dist/components/DeleteDialog.svelte.d.ts +21 -0
  3. package/dist/components/DeleteDialog.svelte.d.ts.map +1 -0
  4. package/dist/components/EditPage.svelte +127 -8
  5. package/dist/components/EditPage.svelte.d.ts +8 -0
  6. package/dist/components/EditPage.svelte.d.ts.map +1 -1
  7. package/dist/components/LinkPicker.svelte +109 -0
  8. package/dist/components/LinkPicker.svelte.d.ts +18 -0
  9. package/dist/components/LinkPicker.svelte.d.ts.map +1 -0
  10. package/dist/components/MarkdownEditor.svelte +33 -3
  11. package/dist/components/MarkdownEditor.svelte.d.ts +5 -0
  12. package/dist/components/MarkdownEditor.svelte.d.ts.map +1 -1
  13. package/dist/components/RenameDialog.svelte +72 -0
  14. package/dist/components/RenameDialog.svelte.d.ts +20 -0
  15. package/dist/components/RenameDialog.svelte.d.ts.map +1 -0
  16. package/dist/components/index.d.ts +3 -0
  17. package/dist/components/index.d.ts.map +1 -1
  18. package/dist/components/index.js +3 -0
  19. package/dist/components/link-completion.d.ts +16 -0
  20. package/dist/components/link-completion.d.ts.map +1 -0
  21. package/dist/components/link-completion.js +48 -0
  22. package/dist/components/markdown-format.d.ts +25 -5
  23. package/dist/components/markdown-format.d.ts.map +1 -1
  24. package/dist/components/markdown-format.js +85 -0
  25. package/dist/content/concepts.d.ts.map +1 -1
  26. package/dist/content/concepts.js +7 -0
  27. package/dist/content/frontmatter.d.ts +8 -0
  28. package/dist/content/frontmatter.d.ts.map +1 -1
  29. package/dist/content/frontmatter.js +19 -0
  30. package/dist/content/ids.d.ts +7 -0
  31. package/dist/content/ids.d.ts.map +1 -1
  32. package/dist/content/ids.js +11 -0
  33. package/dist/content/links.d.ts +7 -0
  34. package/dist/content/links.d.ts.map +1 -1
  35. package/dist/content/links.js +11 -0
  36. package/dist/content/manifest.d.ts +15 -1
  37. package/dist/content/manifest.d.ts.map +1 -1
  38. package/dist/content/manifest.js +45 -3
  39. package/dist/content/types.d.ts +6 -0
  40. package/dist/content/types.d.ts.map +1 -1
  41. package/dist/content/validate.d.ts.map +1 -1
  42. package/dist/content/validate.js +8 -1
  43. package/dist/delivery/content-index.d.ts +7 -0
  44. package/dist/delivery/content-index.d.ts.map +1 -1
  45. package/dist/delivery/content-index.js +7 -0
  46. package/dist/delivery/head.d.ts +2 -0
  47. package/dist/delivery/head.d.ts.map +1 -0
  48. package/dist/delivery/head.js +4 -0
  49. package/dist/delivery/index.d.ts +0 -1
  50. package/dist/delivery/index.d.ts.map +1 -1
  51. package/dist/delivery/index.js +0 -1
  52. package/dist/delivery/manifest.d.ts.map +1 -1
  53. package/dist/delivery/manifest.js +7 -0
  54. package/dist/github/repo.d.ts.map +1 -1
  55. package/dist/github/repo.js +8 -1
  56. package/dist/index.d.ts +7 -4
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +8 -3
  59. package/dist/render/pipeline.d.ts +4 -0
  60. package/dist/render/pipeline.d.ts.map +1 -1
  61. package/dist/render/pipeline.js +3 -1
  62. package/dist/render/registry.d.ts +1 -1
  63. package/dist/render/registry.d.ts.map +1 -1
  64. package/dist/render/rehype-dispatch.d.ts +5 -0
  65. package/dist/render/rehype-dispatch.d.ts.map +1 -1
  66. package/dist/render/rehype-dispatch.js +12 -1
  67. package/dist/render/remark-directives.d.ts.map +1 -1
  68. package/dist/render/remark-directives.js +15 -6
  69. package/dist/render/sanitize-schema.d.ts +4 -3
  70. package/dist/render/sanitize-schema.d.ts.map +1 -1
  71. package/dist/render/sanitize-schema.js +6 -5
  72. package/dist/sveltekit/content-routes.d.ts +11 -2
  73. package/dist/sveltekit/content-routes.d.ts.map +1 -1
  74. package/dist/sveltekit/content-routes.js +157 -9
  75. package/dist/sveltekit/public-routes.d.ts +1 -0
  76. package/dist/sveltekit/public-routes.d.ts.map +1 -1
  77. package/dist/sveltekit/public-routes.js +1 -1
  78. package/package.json +7 -1
  79. package/src/lib/components/DeleteDialog.svelte +81 -0
  80. package/src/lib/components/EditPage.svelte +127 -8
  81. package/src/lib/components/LinkPicker.svelte +109 -0
  82. package/src/lib/components/MarkdownEditor.svelte +33 -3
  83. package/src/lib/components/RenameDialog.svelte +72 -0
  84. package/src/lib/components/index.ts +3 -0
  85. package/src/lib/components/link-completion.ts +57 -0
  86. package/src/lib/components/markdown-format.ts +82 -0
  87. package/src/lib/content/concepts.ts +9 -0
  88. package/src/lib/content/frontmatter.ts +21 -0
  89. package/src/lib/content/ids.ts +12 -0
  90. package/src/lib/content/links.ts +13 -0
  91. package/src/lib/content/manifest.ts +55 -3
  92. package/src/lib/content/types.ts +6 -0
  93. package/src/lib/content/validate.ts +6 -1
  94. package/src/lib/delivery/content-index.ts +13 -0
  95. package/src/lib/delivery/head.ts +4 -0
  96. package/src/lib/delivery/index.ts +0 -1
  97. package/src/lib/delivery/manifest.ts +6 -0
  98. package/src/lib/github/repo.ts +8 -1
  99. package/src/lib/index.ts +10 -2
  100. package/src/lib/render/pipeline.ts +6 -1
  101. package/src/lib/render/registry.ts +1 -1
  102. package/src/lib/render/rehype-dispatch.ts +12 -1
  103. package/src/lib/render/remark-directives.ts +16 -5
  104. package/src/lib/render/sanitize-schema.ts +6 -5
  105. package/src/lib/sveltekit/content-routes.ts +178 -11
  106. package/src/lib/sveltekit/public-routes.ts +2 -1
@@ -2,14 +2,16 @@
2
2
  // A factory closes over the composed runtime and the GitHub token mint, so the read and
3
3
  // commit paths are unit-testable against a fetch double with an injected token, mirroring the
4
4
  // email `send` injection in auth-routes. A shim stays one line: `export const load = routes.editLoad`.
5
- import { redirect, error } from '@sveltejs/kit';
5
+ import { redirect, error, fail } from '@sveltejs/kit';
6
6
  import { findConcept } from '../content/concepts.js';
7
+ import { extractCairnLinks, formatCairnToken } from '../content/links.js';
7
8
  import { frontmatterFromForm, parseMarkdown, dateInputValue, serializeMarkdown } from '../content/frontmatter.js';
8
- import { isValidId, slugify, filenameFromId, composeDatedId } from '../content/ids.js';
9
+ import { isValidId, slugify, filenameFromId, composeDatedId, slugFromId, renameId } from '../content/ids.js';
10
+ import { rewriteCairnLink } from '../components/markdown-format.js';
9
11
  import { appCredentials } from '../github/credentials.js';
10
12
  import { listMarkdown, readRaw, commitFiles } from '../github/repo.js';
11
13
  import { cachedInstallationToken } from '../github/signing.js';
12
- import { emptyManifest, manifestEntryFromFile, parseManifest, serializeManifest, upsertEntry } from '../content/manifest.js';
14
+ import { emptyManifest, manifestEntryFromFile, parseManifest, serializeManifest, upsertEntry, removeEntry, inboundLinks } from '../content/manifest.js';
13
15
  import { CommitConflictError } from '../github/types.js';
14
16
  /** The signed-in editor the guard resolved, or a login redirect. Kept local to decouple event shapes. */
15
17
  function sessionOf(event) {
@@ -135,15 +137,21 @@ export function createContentRoutes(runtime, deps = {}) {
135
137
  throw error(400, 'Invalid entry id');
136
138
  const isNew = event.url.searchParams.get('new') === '1';
137
139
  const token = await mintToken(event.platform?.env ?? {});
138
- const raw = await readRaw(runtime.backend, `${concept.dir}/${filenameFromId(id)}`, token);
140
+ const datePrefix = concept.routing.dated ? concept.datePrefix : null;
141
+ // The entry file and the manifest are independent reads sharing the token; fetch them together.
142
+ const [raw, manifestRaw] = await Promise.all([
143
+ readRaw(runtime.backend, `${concept.dir}/${filenameFromId(id)}`, token),
144
+ readRaw(runtime.backend, runtime.manifestPath, token),
145
+ ]);
139
146
  if (raw === null && !isNew)
140
147
  throw error(404, 'Entry not found');
141
148
  const parsed = raw === null ? { frontmatter: {}, body: '' } : parseMarkdown(raw);
142
149
  const title = typeof parsed.frontmatter.title === 'string' && parsed.frontmatter.title.trim() ? parsed.frontmatter.title : id;
143
150
  let linkTargets = [];
144
- const manifestRaw = await readRaw(runtime.backend, runtime.manifestPath, token);
151
+ let inbound = [];
145
152
  if (manifestRaw !== null) {
146
- linkTargets = parseManifest(manifestRaw).entries.map((e) => ({
153
+ const manifest = parseManifest(manifestRaw);
154
+ linkTargets = manifest.entries.map((e) => ({
147
155
  concept: e.concept,
148
156
  id: e.id,
149
157
  permalink: e.permalink,
@@ -151,6 +159,7 @@ export function createContentRoutes(runtime, deps = {}) {
151
159
  date: e.date,
152
160
  draft: e.draft,
153
161
  }));
162
+ inbound = inboundLinks(manifest, concept.id, id);
154
163
  }
155
164
  return {
156
165
  conceptId: concept.id,
@@ -162,8 +171,11 @@ export function createContentRoutes(runtime, deps = {}) {
162
171
  title,
163
172
  isNew,
164
173
  saved: event.url.searchParams.get('saved') === '1',
174
+ renamed: event.url.searchParams.get('renamed') === '1',
165
175
  error: event.url.searchParams.get('error'),
176
+ slug: slugFromId(id, datePrefix),
166
177
  linkTargets,
178
+ inboundLinks: inbound,
167
179
  };
168
180
  }
169
181
  /** Match a commit conflict by class and by name (bundling can alias the class identity). */
@@ -200,7 +212,29 @@ export function createContentRoutes(runtime, deps = {}) {
200
212
  const manifestRaw = await readRaw(runtime.backend, runtime.manifestPath, token);
201
213
  const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
202
214
  const row = manifestEntryFromFile(concept, { path, raw: markdown });
203
- const nextManifest = serializeManifest(upsertEntry(manifest, row));
215
+ const upserted = upsertEntry(manifest, row);
216
+ const nextManifest = serializeManifest(upserted);
217
+ // Save guard: resolve the body's cairn links against the manifest with this entry upserted, so a
218
+ // self-link and a link to any existing target resolves. A link to an absent target hard-blocks
219
+ // the save (it would red the deploy build and the author would not see it); a link to a draft
220
+ // target commits with a warning, since it is valid and resolves once the target is published.
221
+ const byKey = new Map(upserted.entries.map((e) => [`${e.concept}/${e.id}`, e]));
222
+ const absent = [];
223
+ const draft = [];
224
+ for (const ref of extractCairnLinks(body)) {
225
+ // A self-link is valid by construction (the upserted manifest holds this very entry), so
226
+ // skip it before classifying. Mirrors inboundLinks's self-exclusion.
227
+ if (ref.concept === concept.id && ref.id === id)
228
+ continue;
229
+ const target = byKey.get(`${ref.concept}/${ref.id}`);
230
+ if (!target)
231
+ absent.push(formatCairnToken(ref));
232
+ else if (target.draft)
233
+ draft.push(formatCairnToken(ref));
234
+ }
235
+ if (absent.length) {
236
+ return fail(400, { brokenLinks: absent, body });
237
+ }
204
238
  try {
205
239
  await commitFiles(runtime.backend, [
206
240
  { path, content: markdown },
@@ -214,7 +248,121 @@ export function createContentRoutes(runtime, deps = {}) {
214
248
  }
215
249
  throw err;
216
250
  }
217
- throw redirect(303, `/admin/${concept.id}/${id}?saved=1`);
251
+ const savedQuery = draft.length ? `saved=1&drafts=${encodeURIComponent(draft.join(','))}` : 'saved=1';
252
+ throw redirect(303, `/admin/${concept.id}/${id}?${savedQuery}`);
253
+ }
254
+ /** Delete an entry. Block-until-clean: refuse while inbound links exist (naming them), else commit
255
+ * the file removal and the manifest patch in one commit. The inbound recheck here is the
256
+ * authoritative gate, closing the load-to-delete race. */
257
+ async function deleteAction(event) {
258
+ const editor = sessionOf(event);
259
+ const concept = conceptOf(runtime, event.params);
260
+ const id = event.params.id ?? '';
261
+ if (!isValidId(id))
262
+ throw error(400, 'Invalid entry id');
263
+ const path = `${concept.dir}/${filenameFromId(id)}`;
264
+ const token = await mintToken(event.platform?.env ?? {});
265
+ // An absent manifest degrades the inbound gate to "allow": with no manifest there is nothing to
266
+ // check, and the build's cairn: backstop still catches any dangling token, mirroring saveAction.
267
+ const manifestRaw = await readRaw(runtime.backend, runtime.manifestPath, token);
268
+ const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
269
+ const inbound = inboundLinks(manifest, concept.id, id);
270
+ if (inbound.length) {
271
+ return fail(409, { inboundLinks: inbound });
272
+ }
273
+ const nextManifest = serializeManifest(removeEntry(manifest, concept.id, id));
274
+ try {
275
+ await commitFiles(runtime.backend, [
276
+ { path, content: null },
277
+ { path: runtime.manifestPath, content: nextManifest },
278
+ ], { message: `Delete ${concept.label.toLowerCase()}: ${id}`, author: { name: editor.displayName, email: editor.email } }, token);
279
+ }
280
+ catch (err) {
281
+ if (isConflict(err)) {
282
+ const message = 'This file changed since you opened it. Reload and try again.';
283
+ throw redirect(303, `/admin/${concept.id}/${id}?error=${encodeURIComponent(message)}`);
284
+ }
285
+ throw err;
286
+ }
287
+ throw redirect(303, `/admin/${concept.id}`);
288
+ }
289
+ /** Rename an entry: change its slug, move the file, and rewrite every inbound cairn token in one
290
+ * atomic commit, so no internal link breaks. The collision check and the inbound recompute here
291
+ * are the authoritative gate. The same last-writer-wins manifest race as save and delete applies,
292
+ * caught by the build's fail-closed backstop. */
293
+ async function renameAction(event) {
294
+ const editor = sessionOf(event);
295
+ const concept = conceptOf(runtime, event.params);
296
+ const id = event.params.id ?? '';
297
+ if (!isValidId(id))
298
+ throw error(400, 'Invalid entry id');
299
+ const form = await event.request.formData();
300
+ const newSlug = String(form.get('slug') ?? '').trim();
301
+ if (!isValidId(newSlug)) {
302
+ return fail(400, { renameError: 'Enter a valid slug: lowercase letters, numbers, and hyphens.' });
303
+ }
304
+ const datePrefix = concept.routing.dated ? concept.datePrefix : null;
305
+ if (concept.routing.dated && /^\d{4}-/.test(newSlug)) {
306
+ return fail(400, { renameError: 'Leave the date out of the slug.' });
307
+ }
308
+ if (newSlug === slugFromId(id, datePrefix)) {
309
+ return fail(400, { renameError: 'That is already the slug.' });
310
+ }
311
+ const newId = renameId(id, newSlug, datePrefix);
312
+ const oldPath = `${concept.dir}/${filenameFromId(id)}`;
313
+ const newPath = `${concept.dir}/${filenameFromId(newId)}`;
314
+ const token = await mintToken(event.platform?.env ?? {});
315
+ // Collision guard: refuse if a file already exists at the new path. This 409 covers two cases a
316
+ // single readRaw cannot tell apart: a static collision with an existing entry, and a
317
+ // concurrent-rename race where another editor renamed onto this path between load and submit.
318
+ const clobber = await readRaw(runtime.backend, newPath, token);
319
+ if (clobber !== null) {
320
+ return fail(409, { renameError: 'An entry with that slug already exists.' });
321
+ }
322
+ const [entryRaw, manifestRaw] = await Promise.all([
323
+ readRaw(runtime.backend, oldPath, token),
324
+ readRaw(runtime.backend, runtime.manifestPath, token),
325
+ ]);
326
+ if (entryRaw === null)
327
+ throw error(404, 'Entry not found');
328
+ const manifest = manifestRaw === null ? emptyManifest() : parseManifest(manifestRaw);
329
+ const oldHref = formatCairnToken({ concept: concept.id, id });
330
+ const newHref = formatCairnToken({ concept: concept.id, id: newId });
331
+ // The moved file keeps its content, except a self-token rewrite. Re-derive its manifest row from
332
+ // the new path so the row carries the new id and permalink by construction.
333
+ const movedRaw = rewriteCairnLink(entryRaw, oldHref, newHref);
334
+ const changes = [
335
+ { path: oldPath, content: null },
336
+ { path: newPath, content: movedRaw },
337
+ ];
338
+ let next = removeEntry(manifest, concept.id, id);
339
+ next = upsertEntry(next, manifestEntryFromFile(concept, { path: newPath, raw: movedRaw }));
340
+ // Rewrite every inbound linker's body and re-derive its row, so its outbound edge points at the
341
+ // new id. A linker missing from the repo is skipped; the build backstop catches any drift.
342
+ for (const linker of inboundLinks(manifest, concept.id, id)) {
343
+ const linkerConcept = findConcept(runtime.concepts, linker.concept);
344
+ if (!linkerConcept)
345
+ continue;
346
+ const linkerPath = `${linkerConcept.dir}/${filenameFromId(linker.id)}`;
347
+ const linkerRaw = await readRaw(runtime.backend, linkerPath, token);
348
+ if (linkerRaw === null)
349
+ continue;
350
+ const rewritten = rewriteCairnLink(linkerRaw, oldHref, newHref);
351
+ changes.push({ path: linkerPath, content: rewritten });
352
+ next = upsertEntry(next, manifestEntryFromFile(linkerConcept, { path: linkerPath, raw: rewritten }));
353
+ }
354
+ changes.push({ path: runtime.manifestPath, content: serializeManifest(next) });
355
+ try {
356
+ await commitFiles(runtime.backend, changes, { message: `Rename ${concept.label.toLowerCase()}: ${id} to ${newId}`, author: { name: editor.displayName, email: editor.email } }, token);
357
+ }
358
+ catch (err) {
359
+ if (isConflict(err)) {
360
+ const message = 'This file changed since you opened it. Reload and try again.';
361
+ throw redirect(303, `/admin/${concept.id}/${id}?error=${encodeURIComponent(message)}`);
362
+ }
363
+ throw err;
364
+ }
365
+ throw redirect(303, `/admin/${concept.id}/${newId}?renamed=1`);
218
366
  }
219
- return { layoutLoad, indexRedirect, listLoad, createAction, editLoad, saveAction, mintToken };
367
+ return { layoutLoad, indexRedirect, listLoad, createAction, editLoad, saveAction, deleteAction, renameAction, mintToken };
220
368
  }
@@ -40,6 +40,7 @@ export interface TagIndexData {
40
40
  }
41
41
  /** One entry's data: the detail entry, its rendered html, and its canonical URL. */
42
42
  export interface EntryData {
43
+ concept: string;
43
44
  entry: ContentEntry;
44
45
  html: string;
45
46
  canonicalUrl: string;
@@ -1 +1 @@
1
- {"version":3,"file":"public-routes.d.ts","sourceRoot":"","sources":["../../src/lib/sveltekit/public-routes.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,oDAAoD;AACpD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,WAAW,CAAA;KAAE,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtG,MAAM,EAAE,MAAM,CAAC;IACf,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,uDAAuD;IACvD,WAAW,EAAE,MAAM,CAAC;IACpB,6DAA6D;IAC7D,KAAK,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC;6EACyE;IACzE,YAAY,CAAC,EAAE,MAAM,CAAC;C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A;KAAE,KAAG,OAAO,CAAC,SAAS,CAAC;6BA0BjC,MAAM,KAAG,QAAQ;8BAKhB,MAAM,KAAG,YAAY;yBAK1B,MAAM,SAAS;QAAE,MAAM,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAG,OAAO;mBAO5D;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE;EAKvC"}
@@ -41,7 +41,7 @@ export function createPublicRoutes(deps) {
41
41
  ...(fields.author ? { author: fields.author } : {}),
42
42
  ...(entry.date ? { feeds } : {}),
43
43
  });
44
- return { entry, html: await render(entry.body, { stagger: true, resolve: buildLinkResolver(site) }), canonicalUrl, seo, newer, older };
44
+ return { concept: entry.concept, entry, html: await render(entry.body, { stagger: true, resolve: buildLinkResolver(site) }), canonicalUrl, seo, newer, older };
45
45
  }
46
46
  /** The chronological archive for one concept: every non-draft summary, newest-first. */
47
47
  function archiveLoad(conceptId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glw907/cairn-cms",
3
- "version": "0.18.0",
3
+ "version": "0.24.0",
4
4
  "description": "Embedded, magic-link, GitHub-committing CMS for SvelteKit/Cloudflare sites.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -53,6 +53,11 @@
53
53
  "svelte": "./dist/delivery/index.js",
54
54
  "default": "./dist/delivery/index.js"
55
55
  },
56
+ "./delivery/head": {
57
+ "types": "./dist/delivery/head.d.ts",
58
+ "svelte": "./dist/delivery/head.js",
59
+ "default": "./dist/delivery/head.js"
60
+ },
56
61
  "./package.json": "./package.json"
57
62
  },
58
63
  "files": [
@@ -64,6 +69,7 @@
64
69
  "svelte": "^5.0.0"
65
70
  },
66
71
  "dependencies": {
72
+ "@codemirror/autocomplete": "^6.20.2",
67
73
  "@codemirror/commands": "^6.10.3",
68
74
  "@codemirror/lang-markdown": "^6.5.0",
69
75
  "@codemirror/language": "^6.12.3",
@@ -0,0 +1,81 @@
1
+ <!--
2
+ @component
3
+ The Delete control and its modal. With no inbound links it is a plain confirm that posts to the
4
+ ?/delete action. With inbound links it blocks: it names how many entries link here and lists them,
5
+ each linking to its edit page, so the author repoints or removes those links first. Built on a native
6
+ <dialog>, following the LinkPicker a11y conventions.
7
+ -->
8
+ <script lang="ts">
9
+ import type { InboundLink } from '../content/manifest.js';
10
+
11
+ interface Props {
12
+ /** The concept this entry belongs to, e.g. "posts". Posted with the confirm. */
13
+ conceptId: string;
14
+ /** The entry id within its concept. Posted with the confirm. */
15
+ id: string;
16
+ /** A human label for the concept, e.g. "Post", used in the prompts. */
17
+ label: string;
18
+ /** The entries that link to this one; non-empty blocks the delete. */
19
+ inboundLinks: InboundLink[];
20
+ }
21
+
22
+ let { conceptId, id, label, inboundLinks }: Props = $props();
23
+
24
+ let dialog = $state<HTMLDialogElement | null>(null);
25
+ const blocked = $derived(inboundLinks.length > 0);
26
+ const noun = $derived(label.toLowerCase());
27
+ // One inbound link reads "1 post links here ... repoint it"; many reads "2 posts link here ...
28
+ // repoint them". The subject-verb agreement inverts the usual plural-s, so derive each form once.
29
+ const single = $derived(inboundLinks.length === 1);
30
+ const nouns = $derived(single ? noun : `${noun}s`);
31
+ const verb = $derived(single ? 'links' : 'link');
32
+ const pronoun = $derived(single ? 'it' : 'them');
33
+
34
+ function open() {
35
+ dialog?.showModal();
36
+ }
37
+ function close() {
38
+ dialog?.close();
39
+ }
40
+ </script>
41
+
42
+ <button type="button" class="btn btn-sm btn-ghost text-error" aria-haspopup="dialog" onclick={open}>
43
+ Delete
44
+ </button>
45
+
46
+ <dialog class="modal" aria-labelledby="cairn-delete-dialog-title" bind:this={dialog}>
47
+ <div class="modal-box">
48
+ <div class="mb-3 flex items-center justify-between">
49
+ <h2 id="cairn-delete-dialog-title" class="text-base font-semibold">Delete this {label.toLowerCase()}?</h2>
50
+ <button type="button" class="btn btn-ghost btn-sm" aria-label="Close" onclick={close}>✕</button>
51
+ </div>
52
+
53
+ {#if blocked}
54
+ <p class="mb-2 text-sm">
55
+ {inboundLinks.length} {nouns} {verb} here. Remove or repoint {pronoun} before deleting, so no link is left
56
+ broken.
57
+ </p>
58
+ <ul class="menu w-full">
59
+ {#each inboundLinks as link (link.concept + '/' + link.id)}
60
+ <li>
61
+ <a href={`/admin/${link.concept}/${link.id}`}>{link.title}</a>
62
+ </li>
63
+ {/each}
64
+ </ul>
65
+ <div class="mt-3 flex justify-end">
66
+ <button type="button" class="btn btn-sm" onclick={close}>Close</button>
67
+ </div>
68
+ {:else}
69
+ <p class="mb-3 text-sm">This cannot be undone.</p>
70
+ <form method="POST" action="?/delete" class="flex justify-end gap-2">
71
+ <input type="hidden" name="concept" value={conceptId} />
72
+ <input type="hidden" name="id" value={id} />
73
+ <button type="button" class="btn btn-sm" onclick={close}>Cancel</button>
74
+ <button type="submit" class="btn btn-sm btn-error">Delete this {label.toLowerCase()}</button>
75
+ </form>
76
+ {/if}
77
+ </div>
78
+ <form method="dialog" class="modal-backdrop">
79
+ <button tabindex="-1" aria-label="Close">close</button>
80
+ </form>
81
+ </dialog>
@@ -8,6 +8,11 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
8
8
  import { untrack } from 'svelte';
9
9
  import MarkdownEditor from './MarkdownEditor.svelte';
10
10
  import ComponentInsertDialog from './ComponentInsertDialog.svelte';
11
+ import LinkPicker from './LinkPicker.svelte';
12
+ import DeleteDialog from './DeleteDialog.svelte';
13
+ import RenameDialog from './RenameDialog.svelte';
14
+ import { cairnLinkCompletionSource } from './link-completion.js';
15
+ import { unwrapCairnLink } from './markdown-format.js';
11
16
  import type { ComponentRegistry } from '../render/registry.js';
12
17
  import type { IconSet } from '../render/glyph.js';
13
18
  import type { EditData } from '../sveltekit/content-routes.js';
@@ -24,21 +29,86 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
24
29
  render?: (md: string, opts?: { stagger?: boolean; resolve?: LinkResolve }) => string | Promise<string>;
25
30
  /** The site's icon set, for the guided form's icon fields. */
26
31
  icons?: IconSet;
32
+ /** The `?/save` or `?/delete` action result. Carries the save guard's broken links when a save was
33
+ * blocked, or the delete guard's inbound linkers when a delete was refused. */
34
+ form?: { brokenLinks?: string[]; body?: string; inboundLinks?: import('../content/manifest.js').InboundLink[]; renameError?: string } | null;
27
35
  }
28
36
 
29
- let { data, registry, render, icons }: Props = $props();
37
+ let { data, registry, render, icons, form }: Props = $props();
30
38
 
31
- // `body` is local editor state seeded once from the prop; it diverges as the user types.
32
- // untrack() captures the initial value without subscribing to future prop changes.
33
- let body = $state(untrack(() => data.body));
39
+ // `body` is local editor state seeded once; it diverges as the user types. A blocked save returns
40
+ // the author's edited markdown as form.body, so seed from that when present to keep the edits and
41
+ // the broken link they were told to fix. On the success and delete-refused paths form carries no
42
+ // body, so it falls back to the committed data.body. untrack() captures the initial value without
43
+ // subscribing to future prop changes.
44
+ let body = $state(untrack(() => form?.body ?? data.body));
34
45
  let showPreview = $state(false);
35
46
  let previewHtml = $state('');
36
47
  let insert = $state.raw<(text: string) => void>(() => {});
48
+ let insertLink = $state.raw<(href: string, title: string) => void>(() => {});
49
+
50
+ // The save guard's broken links, from the blocked action result. The fix unwraps a link in the
51
+ // local body, which the bound editor reconciles, so the author re-saves clean.
52
+ const brokenLinks = $derived(form?.brokenLinks ?? []);
53
+ // Track the hrefs the author has already fixed this session. The banner reads the immutable action
54
+ // result, so without this a fixed row would linger and "Remove link" would read as a no-op.
55
+ let removedLinks = $state<string[]>([]);
56
+ const visibleBrokenLinks = $derived(brokenLinks.filter((h) => !removedLinks.includes(h)));
57
+ function removeBrokenLink(href: string) {
58
+ // Hide the row only when the unwrap changed the body. A genuine no-op keeps the row honest.
59
+ const next = unwrapCairnLink(body, href);
60
+ if (next !== body) {
61
+ body = next;
62
+ removedLinks = [...removedLinks, href];
63
+ }
64
+ }
65
+
66
+ // The delete guard's inbound linkers, from a refused delete (fail 409). Empty when the delete was
67
+ // not refused. When set, a delete was blocked by a link that appeared since the page loaded.
68
+ const deleteRefusedLinks = $derived(form?.inboundLinks ?? []);
69
+
70
+ // A rename that hit a collision or an invalid slug returns form.renameError.
71
+ const renameError = $derived(form?.renameError ?? '');
72
+
73
+ // After a save that links to a draft target, the redirect carries ?drafts=<tokens>.
74
+ let draftWarning = $state('');
75
+ $effect(() => {
76
+ const search = typeof location === 'undefined' ? '' : location.search;
77
+ const drafts = new URLSearchParams(search).get('drafts');
78
+ draftWarning = drafts ? drafts.split(',').filter(Boolean).join(', ') : '';
79
+ });
80
+
81
+ // One persistent live region announces the current message, since a {#if}-gated role element
82
+ // inserted fresh is announced inconsistently. A polite region carries the success and draft
83
+ // notices; an assertive region carries the errors. The visible banners below keep their styling
84
+ // but drop their roles, so a message is announced once.
85
+ const politeMessage = $derived.by(() => {
86
+ if (draftWarning) return `Saved. This page links to unpublished pages: ${draftWarning}.`;
87
+ if (data.saved) return 'Saved.';
88
+ if (data.renamed) return `The URL is now ${data.slug}.`;
89
+ return '';
90
+ });
91
+ const assertiveMessage = $derived.by(() => {
92
+ if (data.error) return data.error;
93
+ if (renameError) return renameError;
94
+ if (deleteRefusedLinks.length) {
95
+ const count = deleteRefusedLinks.length;
96
+ return `This ${data.label.toLowerCase()} could not be deleted. ${count} ${count === 1 ? 'page links' : 'pages link'} to it.`;
97
+ }
98
+ if (visibleBrokenLinks.length) {
99
+ const count = visibleBrokenLinks.length;
100
+ return `This page links to ${count} missing ${count === 1 ? 'page' : 'pages'}.`;
101
+ }
102
+ return '';
103
+ });
37
104
 
38
105
  // The manifest-backed resolver turns a cairn: link into its live permalink in the preview, and
39
106
  // returns undefined for a missing target so the render step marks it cairn-broken-link.
40
107
  const resolveLink = $derived(manifestLinkResolver(data.linkTargets));
41
108
 
109
+ // The [[ autocomplete source over the same link targets, handed to the editor's generic seam.
110
+ const completionSources = $derived([cairnLinkCompletionSource(data.linkTargets)]);
111
+
42
112
  const PREVIEW_KEY = 'cairn-admin:preview';
43
113
 
44
114
  $effect(() => {
@@ -85,6 +155,9 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
85
155
  </div>
86
156
  <div class="flex items-center gap-2">
87
157
  <ComponentInsertDialog {registry} {insert} {icons} />
158
+ <LinkPicker linkTargets={data.linkTargets} insert={insertLink} />
159
+ <RenameDialog conceptId={data.conceptId} id={data.id} label={data.label} slug={data.slug} />
160
+ <DeleteDialog conceptId={data.conceptId} id={data.id} label={data.label} inboundLinks={data.inboundLinks} />
88
161
  <button
89
162
  type="button"
90
163
  class="btn btn-sm btn-ghost"
@@ -97,11 +170,51 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
97
170
  </div>
98
171
  </header>
99
172
 
100
- {#if data.saved}
101
- <div role="status" class="alert alert-success mb-4 text-sm">Saved.</div>
173
+ <div class="sr-only" aria-live="polite">{politeMessage}</div>
174
+ <div class="sr-only" aria-live="assertive">{assertiveMessage}</div>
175
+
176
+ {#if data.saved && !draftWarning}
177
+ <div class="alert alert-success mb-4 text-sm">Saved.</div>
178
+ {/if}
179
+ {#if data.renamed}
180
+ <div class="alert alert-success mb-4 text-sm">The URL is now {data.slug}.</div>
102
181
  {/if}
103
182
  {#if data.error}
104
- <div role="alert" class="alert alert-error mb-4 text-sm">{data.error}</div>
183
+ <div class="alert alert-error mb-4 text-sm">{data.error}</div>
184
+ {/if}
185
+ {#if renameError}
186
+ <div class="alert alert-error mb-4 text-sm">{renameError}</div>
187
+ {/if}
188
+ {#if deleteRefusedLinks.length}
189
+ <div class="alert alert-error mb-4 flex-col items-start text-sm">
190
+ <p class="font-medium">This {data.label.toLowerCase()} could not be deleted.</p>
191
+ <p>{deleteRefusedLinks.length} {deleteRefusedLinks.length === 1 ? 'page' : 'pages'} now link to it. Remove or repoint the {deleteRefusedLinks.length === 1 ? 'link' : 'links'} listed below, then delete again.</p>
192
+ <ul class="mt-1 w-full">
193
+ {#each deleteRefusedLinks as link (link.concept + '/' + link.id)}
194
+ <li>
195
+ <a class="link" href={`/admin/${link.concept}/${link.id}`}>{link.title}</a>
196
+ </li>
197
+ {/each}
198
+ </ul>
199
+ </div>
200
+ {/if}
201
+ {#if visibleBrokenLinks.length}
202
+ <div class="alert alert-error mb-4 flex-col items-start text-sm">
203
+ <p>This page links to {visibleBrokenLinks.length === 1 ? 'a page' : 'pages'} that no longer {visibleBrokenLinks.length === 1 ? 'exists' : 'exist'}. Remove the broken {visibleBrokenLinks.length === 1 ? 'link' : 'links'} and save again.</p>
204
+ <ul class="mt-1 w-full">
205
+ {#each visibleBrokenLinks as href (href)}
206
+ <li class="flex items-center justify-between gap-2">
207
+ <code class="text-xs">{href}</code>
208
+ <button type="button" class="btn btn-xs" onclick={() => removeBrokenLink(href)}>Remove link</button>
209
+ </li>
210
+ {/each}
211
+ </ul>
212
+ </div>
213
+ {/if}
214
+ {#if draftWarning}
215
+ <div class="alert alert-warning mb-4 text-sm">
216
+ Saved. Note: this page links to unpublished {draftWarning.includes(',') ? 'pages' : 'a page'} ({draftWarning}), which will 404 until published.
217
+ </div>
105
218
  {/if}
106
219
 
107
220
  <form method="POST" action="?/save" class="lg:grid lg:grid-cols-[1fr_20rem] lg:gap-6">
@@ -109,7 +222,13 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
109
222
 
110
223
  <div class="lg:order-1">
111
224
  <div class="rounded-box border border-base-300 bg-base-100 overflow-hidden">
112
- <MarkdownEditor bind:value={body} name="body" registerInsert={(fn) => (insert = fn)} />
225
+ <MarkdownEditor
226
+ bind:value={body}
227
+ name="body"
228
+ registerInsert={(fn) => (insert = fn)}
229
+ registerInsertLink={(fn) => (insertLink = fn)}
230
+ {completionSources}
231
+ />
113
232
  </div>
114
233
  {#if showPreview}
115
234
  <section
@@ -0,0 +1,109 @@
1
+ <!--
2
+ @component
3
+ The "Link to page" control and its modal. It lists the site's posts and pages from the committed
4
+ manifest (the linkTargets the editor receives), grouped by concept with Pages first, each post
5
+ showing its date and each draft marked. Picking a target inserts a cairn: internal link through the
6
+ editor's registerInsertLink seam. Built on a native <dialog>, following the component dialog's a11y
7
+ conventions. The plain-URL link stays the toolbar's link button; this is for an internal target.
8
+ -->
9
+ <script lang="ts">
10
+ import type { LinkTarget } from '../content/manifest.js';
11
+ import { formatCairnToken } from '../content/links.js';
12
+
13
+ interface Props {
14
+ /** The site's link targets, from the committed manifest (editLoad ships them). */
15
+ linkTargets: LinkTarget[];
16
+ /** Insert an inline cairn link at the editor cursor. */
17
+ insert: (href: string, title: string) => void;
18
+ }
19
+
20
+ let { linkTargets, insert }: Props = $props();
21
+
22
+ let dialog = $state<HTMLDialogElement | null>(null);
23
+ let query = $state('');
24
+
25
+ // Group filtered targets by concept, Pages first then Posts then any other concept, so the list
26
+ // reads in a stable order. The filter is a case-insensitive title substring.
27
+ const ORDER: Record<string, number> = { pages: 0, posts: 1 };
28
+ function rank(concept: string): number {
29
+ return ORDER[concept] ?? 2;
30
+ }
31
+ function heading(concept: string): string {
32
+ if (concept === 'pages') return 'Pages';
33
+ if (concept === 'posts') return 'Posts';
34
+ return concept.charAt(0).toUpperCase() + concept.slice(1);
35
+ }
36
+
37
+ const groups = $derived.by(() => {
38
+ const q = query.trim().toLowerCase();
39
+ const matched = q ? linkTargets.filter((t) => t.title.toLowerCase().includes(q)) : linkTargets;
40
+ const byConcept = new Map<string, LinkTarget[]>();
41
+ for (const t of matched) {
42
+ const list = byConcept.get(t.concept) ?? [];
43
+ list.push(t);
44
+ byConcept.set(t.concept, list);
45
+ }
46
+ return [...byConcept.entries()]
47
+ .map(([concept, items]) => ({ concept, heading: heading(concept), items }))
48
+ .sort((a, b) => rank(a.concept) - rank(b.concept) || a.heading.localeCompare(b.heading));
49
+ });
50
+
51
+ function open() {
52
+ query = '';
53
+ dialog?.showModal();
54
+ }
55
+ function close() {
56
+ dialog?.close();
57
+ }
58
+ function choose(target: LinkTarget) {
59
+ insert(formatCairnToken(target), target.title);
60
+ close();
61
+ }
62
+ </script>
63
+
64
+ <button type="button" class="btn btn-sm btn-ghost" aria-haspopup="dialog" aria-label="Link to page" onclick={open}>
65
+ Link to page
66
+ </button>
67
+
68
+ <dialog class="modal" aria-labelledby="cairn-link-dialog-title" bind:this={dialog}>
69
+ <div class="modal-box">
70
+ <div class="mb-3 flex items-center justify-between">
71
+ <h2 id="cairn-link-dialog-title" class="text-base font-semibold">Link to a page</h2>
72
+ <button type="button" class="btn btn-ghost btn-sm" aria-label="Close" onclick={close}>✕</button>
73
+ </div>
74
+
75
+ <input
76
+ type="search"
77
+ class="input input-bordered mb-3 w-full"
78
+ placeholder="Search by title"
79
+ aria-label="Search pages and posts"
80
+ bind:value={query}
81
+ />
82
+
83
+ {#if groups.length === 0}
84
+ <p class="text-sm text-[var(--color-muted)]">No pages or posts to link to.</p>
85
+ {:else}
86
+ {#each groups as group (group.concept)}
87
+ <h3 class="mt-2 mb-1 text-xs font-semibold tracking-wide text-[var(--color-muted)] uppercase">{group.heading}</h3>
88
+ <ul class="menu w-full">
89
+ {#each group.items as target (`${target.concept}/${target.id}`)}
90
+ <li>
91
+ <button type="button" onclick={() => choose(target)}>
92
+ <span class="flex flex-col items-start">
93
+ <span class="font-medium">{target.title}</span>
94
+ <span class="text-xs text-[var(--color-muted)]">
95
+ {#if target.draft}<span class="badge badge-ghost badge-sm mr-1">Draft</span>{/if}
96
+ {#if target.date}{target.date}{/if}
97
+ </span>
98
+ </span>
99
+ </button>
100
+ </li>
101
+ {/each}
102
+ </ul>
103
+ {/each}
104
+ {/if}
105
+ </div>
106
+ <form method="dialog" class="modal-backdrop">
107
+ <button tabindex="-1" aria-label="Close">close</button>
108
+ </form>
109
+ </dialog>