@abraca/junis 2.87.0 → 2.88.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 (89) hide show
  1. package/dist/module.d.mts +4 -2
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +64 -6
  4. package/dist/runtime/assets/css/jun.css +2 -2
  5. package/dist/runtime/components/JunDocSurface.d.vue.ts +20 -2
  6. package/dist/runtime/components/JunDocSurface.vue +27 -2
  7. package/dist/runtime/components/JunDocSurface.vue.d.ts +20 -2
  8. package/dist/runtime/components/JunHead.vue +16 -4
  9. package/dist/runtime/components/JunNavDock.d.vue.ts +15 -0
  10. package/dist/runtime/components/JunNavDock.vue +94 -0
  11. package/dist/runtime/components/JunNavDock.vue.d.ts +15 -0
  12. package/dist/runtime/components/JunNavMenu.client.d.vue.ts +15 -0
  13. package/dist/runtime/components/JunNavMenu.client.vue +478 -0
  14. package/dist/runtime/components/JunNavMenu.client.vue.d.ts +15 -0
  15. package/dist/runtime/components/JunNavPreview.d.vue.ts +17 -0
  16. package/dist/runtime/components/JunNavPreview.vue +169 -0
  17. package/dist/runtime/components/JunNavPreview.vue.d.ts +17 -0
  18. package/dist/runtime/components/JunNavigation.d.vue.ts +4 -11
  19. package/dist/runtime/components/JunNavigation.vue +813 -138
  20. package/dist/runtime/components/JunNavigation.vue.d.ts +4 -11
  21. package/dist/runtime/components/JunNoteLinks.vue +1 -1
  22. package/dist/runtime/components/JunPageHero.vue +3 -3
  23. package/dist/runtime/components/JunSectionBar.d.vue.ts +41 -0
  24. package/dist/runtime/components/JunSectionBar.vue +144 -0
  25. package/dist/runtime/components/JunSectionBar.vue.d.ts +41 -0
  26. package/dist/runtime/components/renderers/JunConfigRenderer.vue +486 -6
  27. package/dist/runtime/components/renderers/JunEntryRenderer.vue +48 -0
  28. package/dist/runtime/composables/useJunCreatePage.js +7 -1
  29. package/dist/runtime/composables/useJunDocPage.d.ts +28 -0
  30. package/dist/runtime/composables/useJunDocPage.js +111 -20
  31. package/dist/runtime/composables/useJunGarden.d.ts +1 -1
  32. package/dist/runtime/composables/useJunGarden.js +3 -2
  33. package/dist/runtime/composables/useJunGestures.d.ts +53 -0
  34. package/dist/runtime/composables/useJunGestures.js +89 -0
  35. package/dist/runtime/composables/useJunMenuState.d.ts +4 -0
  36. package/dist/runtime/composables/useJunMenuState.js +5 -0
  37. package/dist/runtime/composables/useJunNavItems.d.ts +50 -0
  38. package/dist/runtime/composables/useJunNavItems.js +188 -0
  39. package/dist/runtime/composables/useJunNavSettings.d.ts +58 -1
  40. package/dist/runtime/composables/useJunNavSettings.js +110 -8
  41. package/dist/runtime/composables/useJunOptions.d.ts +1 -0
  42. package/dist/runtime/composables/useJunSiblings.d.ts +30 -0
  43. package/dist/runtime/composables/useJunSiblings.js +38 -0
  44. package/dist/runtime/composables/useJunSiteConfig.d.ts +51 -3
  45. package/dist/runtime/composables/useJunTheme.js +4 -1
  46. package/dist/runtime/composables/useJunViewingAccent.js +10 -0
  47. package/dist/runtime/layouts/jun.vue +21 -1
  48. package/dist/runtime/pages/doc.vue +2 -0
  49. package/dist/runtime/pages/index.vue +2 -0
  50. package/dist/runtime/server/api/health.get.d.ts +15 -0
  51. package/dist/runtime/server/api/health.get.js +7 -2
  52. package/dist/runtime/server/api/links.get.js +27 -3
  53. package/dist/runtime/server/api/resolve/[...slug].get.d.ts +20 -0
  54. package/dist/runtime/server/api/resolve/[...slug].get.js +31 -0
  55. package/dist/runtime/server/api/search.get.d.ts +1 -1
  56. package/dist/runtime/server/api/search.get.js +42 -39
  57. package/dist/runtime/server/api/tree.get.js +3 -1
  58. package/dist/runtime/server/janitor/junJanitorChores.d.ts +14 -7
  59. package/dist/runtime/server/janitor/junJanitorChores.js +21 -3
  60. package/dist/runtime/server/janitor/junJanitorMachine.js +36 -4
  61. package/dist/runtime/server/janitor/junJanitorPerform.d.ts +15 -1
  62. package/dist/runtime/server/janitor/junJanitorPerform.js +13 -5
  63. package/dist/runtime/server/janitor/junJanitorYText.d.ts +40 -3
  64. package/dist/runtime/server/janitor/junJanitorYText.js +60 -14
  65. package/dist/runtime/server/plugins/jun-janitor.js +132 -81
  66. package/dist/runtime/server/routes/jun-card.png.get.d.ts +2 -0
  67. package/dist/runtime/server/routes/jun-card.png.get.js +40 -0
  68. package/dist/runtime/server/utils/junCard.d.ts +39 -0
  69. package/dist/runtime/server/utils/junCard.js +159 -0
  70. package/dist/runtime/server/utils/junIcon.d.ts +27 -2
  71. package/dist/runtime/server/utils/junIcon.js +5 -5
  72. package/dist/runtime/server/utils/junJanitorStatus.d.ts +59 -0
  73. package/dist/runtime/server/utils/junJanitorStatus.js +27 -0
  74. package/dist/runtime/types.d.ts +225 -0
  75. package/dist/runtime/utils/junAdopt.d.ts +43 -0
  76. package/dist/runtime/utils/junAdopt.js +7 -0
  77. package/dist/runtime/utils/junGesture.d.ts +84 -0
  78. package/dist/runtime/utils/junGesture.js +40 -0
  79. package/dist/runtime/utils/junLetters.d.ts +86 -0
  80. package/dist/runtime/utils/junLetters.js +173 -0
  81. package/dist/runtime/utils/junNavValue.d.ts +56 -0
  82. package/dist/runtime/utils/junNavValue.js +36 -0
  83. package/dist/runtime/utils/junSearchRank.d.ts +79 -0
  84. package/dist/runtime/utils/junSearchRank.js +73 -0
  85. package/dist/runtime/utils/junSocial.d.ts +59 -0
  86. package/dist/runtime/utils/junSocial.js +56 -0
  87. package/dist/runtime/utils/junViewSpecs.d.ts +38 -0
  88. package/dist/runtime/utils/junViewSpecs.js +92 -1
  89. package/package.json +10 -8
@@ -31,6 +31,35 @@ export default defineEventHandler(async (event) => {
31
31
  }
32
32
  const parentId = entry?.parentId ?? null;
33
33
  const parent = parentId ? tree[parentId] : void 0;
34
+ const trail = [];
35
+ {
36
+ const seen = /* @__PURE__ */ new Set([docId]);
37
+ let cursor = parentId;
38
+ while (cursor && trail.length < 12 && !seen.has(cursor)) {
39
+ seen.add(cursor);
40
+ const node = tree[cursor];
41
+ if (!node || node.trashed || isJunOwnerOnlyDoc(node)) break;
42
+ trail.unshift({ id: cursor, title: node.label ?? "", slug: idToSlug[cursor] ?? null });
43
+ cursor = node.parentId ?? null;
44
+ }
45
+ }
46
+ const rootId = junRootDocId();
47
+ const branch = trail.find((step) => step.id !== rootId);
48
+ const sectionParentId = branch?.id ?? (docId !== rootId && (!parentId || parentId === rootId) ? docId : null);
49
+ const sectionParent = sectionParentId ? tree[sectionParentId] : void 0;
50
+ const section = sectionParentId && sectionParent ? {
51
+ parentId: sectionParentId,
52
+ parentTitle: sectionParent.label ?? "",
53
+ parentSlug: idToSlug[sectionParentId] ?? null,
54
+ items: Object.entries(tree).filter(
55
+ ([id, e]) => !!e && e.parentId === sectionParentId && id !== sectionParentId && !e.trashed && e.meta?.hidden !== true && e.meta?.draft !== true && !isJunOwnerOnlyDoc(e) && !e.meta?.signerId && e.meta?.replyTo == null && e.meta?.t == null
56
+ ).sort(([, a], [, b]) => (a.order ?? 0) - (b.order ?? 0)).map(([id, e]) => ({
57
+ id,
58
+ title: e.label ?? "",
59
+ slug: idToSlug[id] ?? null,
60
+ icon: typeof e.meta?.icon === "string" ? e.meta.icon : void 0
61
+ })).slice(0, 40)
62
+ } : null;
34
63
  return {
35
64
  found: true,
36
65
  cacheReady,
@@ -42,6 +71,8 @@ export default defineEventHandler(async (event) => {
42
71
  parentId,
43
72
  parentType: parent?.type ?? null,
44
73
  parentTitle: parent?.label ?? null,
74
+ trail,
75
+ section,
45
76
  html: await junDocHtml(docId)
46
77
  };
47
78
  });
@@ -5,7 +5,7 @@ export interface JunSearchHit {
5
5
  href: string;
6
6
  type: string;
7
7
  parentId?: string | null;
8
- /** HTML-safe, with the match wrapped in `<mark>`. */
8
+ /** HTML-safe, with each matched term wrapped in `<mark>`. */
9
9
  snippet?: string;
10
10
  rank: number;
11
11
  }
@@ -1,25 +1,36 @@
1
1
  import { defineEventHandler, getQuery } from "h3";
2
2
  import { junDocHtml, junDocTree, junRootDocId, junSlugMap } from "../utils/junCache.js";
3
3
  import { isJunOwnerOnlyDoc } from "../utils/junVisibility.js";
4
+ import { junSearchScore, junSearchSnippet, junSearchTerms } from "../../utils/junSearchRank.js";
4
5
  const escapeHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5
6
  function toText(html) {
6
7
  return html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
7
8
  }
8
- function markSnippet(text, q) {
9
- const idx = text.toLowerCase().indexOf(q.toLowerCase());
10
- if (idx < 0) return escapeHtml(text.slice(0, 140));
11
- const start = Math.max(0, idx - 40);
12
- const pre = (start > 0 ? "\u2026" : "") + text.slice(start, idx);
13
- const hit = text.slice(idx, idx + q.length);
14
- const post = text.slice(idx + q.length, idx + q.length + 80);
15
- const tail = idx + q.length + 80 < text.length ? "\u2026" : "";
16
- return `${escapeHtml(pre)}<mark>${escapeHtml(hit)}</mark>${escapeHtml(post)}${tail}`;
9
+ function markSnippet(text, terms) {
10
+ const { start, end, marks } = junSearchSnippet(text, terms);
11
+ let out = start > 0 ? "\u2026" : "";
12
+ let at = start;
13
+ for (const range of marks) {
14
+ if (range.start < at) continue;
15
+ out += escapeHtml(text.slice(at, range.start));
16
+ out += `<mark>${escapeHtml(text.slice(range.start, range.end))}</mark>`;
17
+ at = range.end;
18
+ }
19
+ out += escapeHtml(text.slice(at, end));
20
+ if (end < text.length) out += "\u2026";
21
+ return out;
22
+ }
23
+ function typeFilter(raw) {
24
+ const values = (Array.isArray(raw) ? raw : [raw]).flatMap((v) => String(v ?? "").split(",")).map((v) => v.trim()).filter(Boolean);
25
+ return values.length ? new Set(values) : null;
17
26
  }
18
27
  export default defineEventHandler(async (event) => {
19
- const q = String(getQuery(event).q ?? "").trim();
20
- const limit = Math.min(Number(getQuery(event).limit ?? 20) || 20, 50);
28
+ const query = getQuery(event);
29
+ const q = String(query.q ?? "").trim();
30
+ const limit = Math.min(Number(query.limit ?? 20) || 20, 50);
21
31
  if (q.length < 2) return [];
22
- const ql = q.toLowerCase();
32
+ const terms = junSearchTerms(q);
33
+ const types = typeFilter(query.type);
23
34
  const rootId = junRootDocId();
24
35
  const [tree, idToSlug] = await Promise.all([junDocTree(), junSlugMap()]);
25
36
  const hits = [];
@@ -27,46 +38,38 @@ export default defineEventHandler(async (event) => {
27
38
  if (!entry || entry.trashed) continue;
28
39
  if (id === rootId) continue;
29
40
  if (isJunOwnerOnlyDoc(entry)) continue;
41
+ if (types && !types.has(entry.type ?? "doc")) continue;
30
42
  const label = entry.label ?? "";
31
43
  const meta = entry.meta ?? {};
32
44
  const excerpt = [meta.excerpt, meta.description].filter((v) => typeof v === "string" && !!v).join(" \u2014 ");
33
- const labelIdx = label.toLowerCase().indexOf(ql);
34
- const excerptIdx = excerpt.toLowerCase().indexOf(ql);
35
- let rank = 0;
36
- let snippet;
37
- if (labelIdx === 0) rank = 100;
38
- else if (labelIdx > 0) rank = 80;
39
- if (excerptIdx >= 0 && rank < 60) {
40
- rank = 60;
41
- snippet = markSnippet(excerpt, q);
42
- }
43
- if (!rank) {
44
- const body = typeof meta.body === "string" ? meta.body : "";
45
- if (body && body.toLowerCase().includes(ql)) {
46
- rank = 45;
47
- snippet = markSnippet(body, q);
48
- }
49
- }
50
- if (!rank) {
45
+ const body = typeof meta.body === "string" ? meta.body : "";
46
+ let score = junSearchScore(terms, { label, excerpt, body });
47
+ let searchedBody = body;
48
+ if (!score) {
51
49
  const html = await junDocHtml(id);
52
50
  if (html) {
53
- const text = toText(html);
54
- if (text.toLowerCase().includes(ql)) {
55
- rank = 40;
56
- snippet = markSnippet(text, q);
57
- }
51
+ searchedBody = `${body} ${toText(html)}`.trim();
52
+ score = junSearchScore(terms, { label, excerpt, body: searchedBody });
58
53
  }
59
54
  }
60
- if (!rank) continue;
55
+ if (!score) continue;
56
+ const haystack = [excerpt, searchedBody].find(
57
+ (text) => text && terms.every((t) => text.toLowerCase().includes(t))
58
+ ) ?? excerpt ?? searchedBody;
61
59
  hits.push({
62
60
  id,
63
61
  title: label || "Untitled",
64
62
  href: `/${idToSlug[id] ?? id}`,
65
63
  type: entry.type ?? "doc",
66
64
  parentId: entry.parentId ?? null,
67
- snippet,
68
- rank
65
+ snippet: haystack ? markSnippet(haystack, terms) : void 0,
66
+ rank: Math.round(score),
67
+ updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : 0
69
68
  });
70
69
  }
71
- return hits.sort((a, b) => b.rank - a.rank).slice(0, limit);
70
+ hits.sort((a, b) => b.rank - a.rank || b.updatedAt - a.updatedAt);
71
+ return hits.slice(0, limit).map(({ updatedAt, ...hit }) => {
72
+ void updatedAt;
73
+ return hit;
74
+ });
72
75
  });
@@ -13,7 +13,9 @@ export default defineEventHandler(async () => {
13
13
  if (meta) {
14
14
  const kept = {};
15
15
  for (const [k, v] of Object.entries(meta)) {
16
- if (!META_OMIT.has(k)) kept[k] = v;
16
+ if (META_OMIT.has(k)) continue;
17
+ if (k === "body" && meta.bodyIsMirror === true) continue;
18
+ kept[k] = v;
17
19
  }
18
20
  meta = kept;
19
21
  }
@@ -16,6 +16,16 @@ export interface JunJanitorDocState {
16
16
  order: number;
17
17
  meta: Record<string, unknown>;
18
18
  text?: string;
19
+ /**
20
+ * The node name of each body block, aligned with the newline-separated
21
+ * blocks of `text` — `['heading', 'paragraph', 'paragraph']`.
22
+ *
23
+ * Optional for the same reason `text` is, and for one more: a notebook
24
+ * written before this existed has no `shape`, and a janitor reading one must
25
+ * behave exactly as it did rather than refusing to work. Absent means "put
26
+ * everything back as a paragraph", which is what it always did.
27
+ */
28
+ shape?: string[];
19
29
  trashed?: boolean;
20
30
  /**
21
31
  * The tree entry's own timestamp. Not compared as a chore — it is a SIGNAL:
@@ -58,12 +68,15 @@ export type JunChore = (ChoreBase & {
58
68
  kind: 'body.restore';
59
69
  at: number;
60
70
  text: string;
71
+ /** The node name of each block this restore RE-OPENS. See `blockTypesFor`. */
72
+ blockTypes?: string[];
61
73
  }) | (ChoreBase & {
62
74
  kind: 'body.replace';
63
75
  at: number;
64
76
  remove: string;
65
77
  restore: string;
66
78
  style: JunRemovalStyle;
79
+ blockTypes?: string[];
67
80
  }) | (ChoreBase & {
68
81
  kind: 'entry.rename';
69
82
  from: string;
@@ -129,16 +142,10 @@ export interface JunChorePolicy {
129
142
  protectChildCount: number;
130
143
  }
131
144
  export declare const JUN_CHORE_POLICY_DEFAULT: JunChorePolicy;
132
- /**
133
- * Compare one document's prose against its baseline.
134
- *
135
- * `impatient` comes from the state machine — the janitor that has cleaned the
136
- * same page three times today stops doing it politely, one character at a
137
- * time. Same divergence, different performance.
138
- */
139
145
  export declare function planBodyChores(docId: string, baselineText: string, liveText: string, options?: {
140
146
  policy?: JunChorePolicy;
141
147
  impatient?: boolean;
148
+ shape?: readonly string[];
142
149
  }): JunBodyChore[];
143
150
  /**
144
151
  * Compare the whole tree — labels, order, the watched meta keys, and pages
@@ -1,4 +1,5 @@
1
1
  import { junDiffText, describeSize, editShape } from "./junJanitorDiff.js";
2
+ import { junIsAdopted } from "../../utils/junAdopt.js";
2
3
  export const JUN_CHORE_POLICY_DEFAULT = {
3
4
  backspaceLimit: 90,
4
5
  wholesaleLimit: 4e3,
@@ -55,11 +56,21 @@ function editKey(docId, edit) {
55
56
  const sample = (edit.remove || edit.restore).slice(0, 24);
56
57
  return `${docId}:${edit.at}:${sample}`;
57
58
  }
59
+ function blockTypesFor(baselineText, shape, baseAt, restore) {
60
+ const breaks = (restore.match(/\n/g) ?? []).length;
61
+ if (!shape?.length || !breaks) return void 0;
62
+ let index = 0;
63
+ for (let i = 0; i < baseAt && i < baselineText.length; i++) {
64
+ if (baselineText[i] === "\n") index++;
65
+ }
66
+ return shape.slice(index, index + breaks + 1).map((name) => name ?? "paragraph");
67
+ }
58
68
  export function planBodyChores(docId, baselineText, liveText, options = {}) {
59
69
  const policy = options.policy ?? JUN_CHORE_POLICY_DEFAULT;
60
70
  if (policy.ignoreDocIds.includes(docId)) return [];
61
71
  const edits = junDiffText(baselineText, liveText);
62
72
  const chores = [];
73
+ let drift = 0;
63
74
  for (const edit of edits) {
64
75
  const id = editKey(docId, edit);
65
76
  const shape = editShape(edit);
@@ -73,8 +84,10 @@ export function planBodyChores(docId, baselineText, liveText, options = {}) {
73
84
  remove: edit.remove,
74
85
  restore: edit.restore,
75
86
  style: "cut",
76
- severity: "egregious"
87
+ severity: "egregious",
88
+ blockTypes: blockTypesFor(baselineText, options.shape, edit.at + drift, edit.restore)
77
89
  });
90
+ drift += edit.restore.length - edit.remove.length;
78
91
  continue;
79
92
  }
80
93
  if (shape === "addition") {
@@ -94,7 +107,8 @@ export function planBodyChores(docId, baselineText, liveText, options = {}) {
94
107
  docId,
95
108
  at: edit.at,
96
109
  text: edit.restore,
97
- severity: severityFor(edit.restore.length)
110
+ severity: severityFor(edit.restore.length),
111
+ blockTypes: blockTypesFor(baselineText, options.shape, edit.at + drift, edit.restore)
98
112
  });
99
113
  } else {
100
114
  chores.push({
@@ -105,9 +119,11 @@ export function planBodyChores(docId, baselineText, liveText, options = {}) {
105
119
  remove: edit.remove,
106
120
  restore: edit.restore,
107
121
  style: styleFor(edit.remove.length, policy, !!options.impatient),
108
- severity: severityFor(Math.max(edit.remove.length, edit.restore.length))
122
+ severity: severityFor(Math.max(edit.remove.length, edit.restore.length)),
123
+ blockTypes: blockTypesFor(baselineText, options.shape, edit.at + drift, edit.restore)
109
124
  });
110
125
  }
126
+ drift += edit.restore.length - edit.remove.length;
111
127
  }
112
128
  return chores;
113
129
  }
@@ -127,6 +143,7 @@ export function planTreeChores(baseline, live, options = {}) {
127
143
  if (ignored.has(id)) continue;
128
144
  const now = live.docs[id];
129
145
  if (!now || now.trashed) {
146
+ if (junIsAdopted(base)) continue;
130
147
  chores.push({
131
148
  kind: "doc.restore",
132
149
  id: `restore:${id}`,
@@ -199,6 +216,7 @@ export function planTreeChores(baseline, live, options = {}) {
199
216
  }
200
217
  for (const [id, now] of Object.entries(live.docs)) {
201
218
  if (ignored.has(id) || baseline.docs[id] || now.trashed) continue;
219
+ if (junIsAdopted(now)) continue;
202
220
  if (childCount(live, id) >= policy.protectChildCount) continue;
203
221
  chores.push({
204
222
  kind: "doc.remove",
@@ -22,7 +22,8 @@ import {
22
22
  scorePatrol
23
23
  } from "./junJanitorPatrol.js";
24
24
  import { junHear } from "./junJanitorListen.js";
25
- import { junBlocks, displayToBody, displayToBodyPos, junCursorState, junFragmentText } from "./junJanitorYText.js";
25
+ import { junBlockNames, junBlocks, displayToBody, displayToBodyPos, junCursorState, junFragmentText } from "./junJanitorYText.js";
26
+ import { junIsAdopted } from "../../utils/junAdopt.js";
26
27
  import { junPerform, junRangeMatches } from "./junJanitorPerform.js";
27
28
  import {
28
29
  junBin,
@@ -211,7 +212,8 @@ export function createJunJanitorMachine(options, deps) {
211
212
  const outcome = await junPerform(
212
213
  handle,
213
214
  displayToBodyPos(blocks, chore.at),
214
- planTyping(chore.text, choreRng, { profile: motor, careful: false })
215
+ planTyping(chore.text, choreRng, { profile: motor, careful: false }),
216
+ { blockTypes: chore.blockTypes }
215
217
  );
216
218
  deps.actor.setCursor(null);
217
219
  return outcome.status === "done";
@@ -227,7 +229,8 @@ export function createJunJanitorMachine(options, deps) {
227
229
  const typedBack = await junPerform(
228
230
  handle,
229
231
  displayToBodyPos(junBlocks(fragment), chore.at),
230
- planTyping(chore.restore, choreRng, { profile: motor, careful: true })
232
+ planTyping(chore.restore, choreRng, { profile: motor, careful: true }),
233
+ { blockTypes: chore.blockTypes }
231
234
  );
232
235
  deps.actor.setCursor(null);
233
236
  return typedBack.status === "done";
@@ -300,7 +303,8 @@ export function createJunJanitorMachine(options, deps) {
300
303
  const liveText = junFragmentText(handle.fragment);
301
304
  const chores = planBodyChores(docId, baseText, liveText, {
302
305
  policy: chorePolicy(),
303
- impatient: mem.grudge >= IMPATIENT_AT
306
+ impatient: mem.grudge >= IMPATIENT_AT,
307
+ shape: baselineSnapshot?.docs[docId]?.shape
304
308
  });
305
309
  mem.lastVisitedAt = now();
306
310
  deps.log(
@@ -433,6 +437,7 @@ export function createJunJanitorMachine(options, deps) {
433
437
  if (rng.chance(0.15)) await speak("aside");
434
438
  return idleWait();
435
439
  }
440
+ adoptNew(live);
436
441
  const treeChores = planTreeChores(baselineSnapshot, live, { policy: chorePolicy() }).filter((c) => c.kind !== "body.remove" && c.kind !== "body.restore" && c.kind !== "body.replace").filter((c) => remember(c.docId).givenUpUntil < at);
437
442
  if (treeChores.length && withinBudget(at)) {
438
443
  const chore = treeChores[0];
@@ -487,6 +492,32 @@ export function createJunJanitorMachine(options, deps) {
487
492
  await visit(target.docId, live);
488
493
  return idleWait();
489
494
  }
495
+ function adoptNew(live) {
496
+ if (!baselineSnapshot) return;
497
+ let adopted = 0;
498
+ let released = 0;
499
+ for (const [id, doc] of Object.entries(live.docs)) {
500
+ if (baselineSnapshot.docs[id] || doc.trashed || ignored.has(id)) continue;
501
+ if (!junIsAdopted(doc)) continue;
502
+ baselineSnapshot.docs[id] = { ...doc, text: void 0, shape: void 0 };
503
+ adopted++;
504
+ }
505
+ const kept = {};
506
+ for (const [id, base] of Object.entries(baselineSnapshot.docs)) {
507
+ const doc = live.docs[id];
508
+ if (junIsAdopted(base) && (!doc || doc.trashed)) {
509
+ released++;
510
+ continue;
511
+ }
512
+ kept[id] = base;
513
+ }
514
+ if (released) baselineSnapshot.docs = kept;
515
+ if (!adopted && !released) return;
516
+ deps.log(
517
+ `${adopted} page(s) the studio made adopted, ${released} released \u2014 the site is what the owner left`
518
+ );
519
+ if (baselineHandle) junWriteBaseline(baselineHandle, baselineSnapshot);
520
+ }
490
521
  async function captureBaseline() {
491
522
  const handle = options.mode === "clean" ? await deps.baseline() : null;
492
523
  if (!handle && options.mode === "clean") return false;
@@ -500,6 +531,7 @@ export function createJunJanitorMachine(options, deps) {
500
531
  const open = await deps.actor.enter(doc.id);
501
532
  if (!open) continue;
502
533
  doc.text = junFragmentText(open.fragment);
534
+ doc.shape = junBlockNames(open.fragment);
503
535
  }
504
536
  await deps.actor.leave();
505
537
  if (handle) junWriteBaseline(handle, snapshot);
@@ -41,6 +41,20 @@ export interface JunPerformHandle {
41
41
  /** Stop now — kill switch, shift end, or the doc changed under us. */
42
42
  aborted?: () => boolean;
43
43
  }
44
+ export interface JunPerformOptions {
45
+ /**
46
+ * The kinds of block this plan's text belongs in, starting with the block it
47
+ * starts in — `['heading', 'paragraph', 'blockquote']`. Break `i` closes
48
+ * `blockTypes[i]` and opens `blockTypes[i + 1]`, so the list is one longer
49
+ * than the number of breaks.
50
+ *
51
+ * The baseline records a block's type (`shape`), and without passing it
52
+ * through, every restored block came back a `paragraph`: a page the janitor
53
+ * tidied lost a little more of its structure each time, which is the
54
+ * opposite of restoring it.
55
+ */
56
+ blockTypes?: readonly string[];
57
+ }
44
58
  export type JunPerformOutcome = {
45
59
  status: 'done';
46
60
  removed: string;
@@ -58,7 +72,7 @@ export type JunPerformOutcome = {
58
72
  * is what makes a plan's overshoot-and-repair land as the same gesture a person
59
73
  * would make. `cut` removes a whole range at once.
60
74
  */
61
- export declare function junPerform(handle: JunPerformHandle, at: number | JunBodyPos, steps: readonly JunMotorStep[]): Promise<JunPerformOutcome>;
75
+ export declare function junPerform(handle: JunPerformHandle, at: number | JunBodyPos, steps: readonly JunMotorStep[], options?: JunPerformOptions): Promise<JunPerformOutcome>;
62
76
  /**
63
77
  * Is the text at `at` still the text the plan was built for?
64
78
  *
@@ -8,8 +8,10 @@ import {
8
8
  junPruneEmptyBlocks,
9
9
  junSplitParagraph
10
10
  } from "./junJanitorYText.js";
11
- export async function junPerform(handle, at, steps) {
11
+ export async function junPerform(handle, at, steps, options = {}) {
12
12
  const { doc, fragment } = handle;
13
+ const blockTypes = options.blockTypes ?? [];
14
+ let breaks = 0;
13
15
  const start = typeof at === "number" ? at : at.body;
14
16
  let bias = typeof at === "number" ? "left" : at.bias;
15
17
  let caret = Math.max(0, Math.min(start, junBodyLength(fragment)));
@@ -43,11 +45,17 @@ export async function junPerform(handle, at, steps) {
43
45
  break;
44
46
  }
45
47
  case "type": {
48
+ if (step.char === "\n") {
49
+ doc.transact(() => {
50
+ junEnsureStructure(fragment);
51
+ junSplitParagraph(fragment, caret, blockTypes[breaks], blockTypes[breaks + 1]);
52
+ });
53
+ breaks++;
54
+ bias = "right";
55
+ typed += step.char;
56
+ break;
57
+ }
46
58
  doc.transact(() => {
47
- if (step.char === "\n") {
48
- junSplitParagraph(fragment, caret);
49
- return;
50
- }
51
59
  junEnsureStructure(fragment);
52
60
  const pos = junFindText(fragment, caret, bias);
53
61
  if (pos) pos.text.insert(pos.offset, step.char);
@@ -125,11 +125,48 @@ export declare function junGlobalIndexOf(fragment: Y.XmlFragment, target: Y.XmlT
125
125
  export declare function junEnsureStructure(fragment: Y.XmlFragment): void;
126
126
  /** The last body paragraph's text node, creating one if the body is empty. */
127
127
  export declare function junLastParagraph(fragment: Y.XmlFragment): Y.XmlText;
128
+ /** The node name of every body block, in order. Aligned with `junBlocks`. */
129
+ export declare function junBlockNames(fragment: Y.XmlFragment): string[];
128
130
  /**
129
- * Split the block containing `bodyIndex`, returning the new block's text node.
130
- * This is what pressing Return does.
131
+ * The paragraph break — what pressing Return does, in the one direction that is
132
+ * safe for a bot.
133
+ *
134
+ * It closes the block BEHIND the caret: the text before `bodyIndex` moves into
135
+ * a NEW element inserted in front, and everything after it stays where it is,
136
+ * in the element it was already in. The returned text node is the one the caret
137
+ * is now in, so a caller keeps typing into it.
138
+ *
139
+ * ## Why the head moves and not the tail
140
+ *
141
+ * A conventional split keeps the original node for the head and moves the tail.
142
+ * Here the head is text the janitor typed seconds ago and the tail is somebody
143
+ * else's untouched prose — so moving the head means every relative position,
144
+ * every open cursor and every concurrent edit in the tail survives, and only
145
+ * the bot's own characters change nodes.
146
+ *
147
+ * ## Why the two node names exist
148
+ *
149
+ * A restored block has a TYPE, and the baseline knows it (`shape`). Without it
150
+ * every restored heading came back as a paragraph, so a page the janitor
151
+ * cleaned lost its structure a little more each time.
152
+ *
153
+ * `headNodeName` types the block being closed. `tailNodeName` types the one the
154
+ * caret lands in — and is applied ONLY when the split emptied it, which is the
155
+ * single case where re-making an element destroys nothing. A tail with text
156
+ * still in it is somebody else's block and keeps its own kind, whatever the
157
+ * baseline says.
158
+ *
159
+ * Falling back to the SOURCE block's own name is what makes the unknown case
160
+ * behave: splitting a heading gives two headings, which is what an editor does.
161
+ *
162
+ * > The bug this replaced: the old version inserted an EMPTY paragraph after
163
+ * > the current block, ignored it, and let `junPerform` advance the caret by
164
+ * > one — but a paragraph break is zero body characters, so everything after
165
+ * > the break was typed one character deep INTO THE NEXT BLOCK. Restoring a
166
+ * > paragraph above a heading spelled its text into the heading:
167
+ * > `one\ntwo` + `The Heading` came out as `oneTtwohe Heading`, styled h1.
131
168
  */
132
- export declare function junSplitParagraph(fragment: Y.XmlFragment, bodyIndex: number): Y.XmlText;
169
+ export declare function junSplitParagraph(fragment: Y.XmlFragment, bodyIndex: number, headNodeName?: string, tailNodeName?: string): Y.XmlText;
133
170
  /**
134
171
  * Delete `count` characters starting at BODY index `at`, across as many text
135
172
  * nodes and blocks as the range covers.
@@ -170,23 +170,69 @@ export function junLastParagraph(fragment) {
170
170
  fragment.push([para]);
171
171
  return text;
172
172
  }
173
- export function junSplitParagraph(fragment, bodyIndex) {
174
- let offset = 0;
175
- let insertAt = fragment.length;
176
- for (let i = 0; i < fragment.length; i++) {
177
- const child = fragment.get(i);
178
- if (!isElement(child) || isSchemaNode(child)) continue;
179
- const len = elementTextLength(child);
180
- if (offset + len >= bodyIndex) {
181
- insertAt = i + 1;
182
- break;
173
+ export function junBlockNames(fragment) {
174
+ return junBlocks(fragment).map((b) => b.nodeName);
175
+ }
176
+ function moveTextPrefix(src, dest, count) {
177
+ if (count <= 0) return 0;
178
+ const delta = src.toDelta();
179
+ const prefix = [];
180
+ let taken = 0;
181
+ for (const op of delta) {
182
+ if (taken >= count) break;
183
+ if (typeof op.insert === "string") {
184
+ const slice = op.insert.slice(0, count - taken);
185
+ if (!slice) continue;
186
+ prefix.push({ insert: slice, ...op.attributes ? { attributes: op.attributes } : {} });
187
+ taken += slice.length;
188
+ } else if (op.insert !== void 0) {
189
+ const value = op.insert;
190
+ prefix.push({
191
+ insert: typeof value?.clone === "function" ? value.clone() : op.insert,
192
+ ...op.attributes ? { attributes: op.attributes } : {}
193
+ });
194
+ taken += 1;
183
195
  }
184
- offset += len;
185
196
  }
186
- const para = new Y.XmlElement("paragraph");
197
+ if (!taken) return 0;
198
+ dest.applyDelta(prefix);
199
+ src.delete(0, taken);
200
+ return taken;
201
+ }
202
+ export function junSplitParagraph(fragment, bodyIndex, headNodeName, tailNodeName) {
203
+ const blocks = junBlocks(fragment);
204
+ const target = blocks.find((b) => bodyIndex >= b.bodyStart && bodyIndex <= b.bodyStart + b.text.length) ?? blocks[blocks.length - 1];
205
+ if (!target) {
206
+ const head2 = new Y.XmlElement(headNodeName ?? "paragraph");
207
+ head2.insert(0, [new Y.XmlText()]);
208
+ const tail = new Y.XmlElement("paragraph");
209
+ const text2 = new Y.XmlText();
210
+ tail.insert(0, [text2]);
211
+ fragment.push([head2, tail]);
212
+ return text2;
213
+ }
214
+ const local = Math.max(0, Math.min(bodyIndex - target.bodyStart, target.text.length));
215
+ const head = new Y.XmlElement(headNodeName ?? target.nodeName);
216
+ const headText = new Y.XmlText();
217
+ head.insert(0, [headText]);
218
+ const first = target.el.get(0);
219
+ if (local > 0 && isText(first)) moveTextPrefix(first, headText, local);
220
+ fragment.insert(target.childIndex, [head]);
221
+ const tailIndex = target.childIndex + 1;
222
+ if (tailNodeName && tailNodeName !== target.nodeName && elementTextLength(target.el) === 0 && target.el.length <= 1) {
223
+ const tail = new Y.XmlElement(tailNodeName);
224
+ const text2 = new Y.XmlText();
225
+ tail.insert(0, [text2]);
226
+ fragment.delete(tailIndex, 1);
227
+ fragment.insert(tailIndex, [tail]);
228
+ return text2;
229
+ }
230
+ for (let i = 0; i < target.el.length; i++) {
231
+ const child = target.el.get(i);
232
+ if (isText(child)) return child;
233
+ }
187
234
  const text = new Y.XmlText();
188
- para.insert(0, [text]);
189
- fragment.insert(insertAt, [para]);
235
+ target.el.insert(0, [text]);
190
236
  return text;
191
237
  }
192
238
  export function junDeleteRange(fragment, at, count) {