@molecule/app-margin-notes-react 1.0.0 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-09-24T06:29:04.932Z
6
+ Generated: 2026-09-29T09:18:29.037Z
7
7
  -->
8
8
 
9
9
  # @molecule/app-margin-notes-react
@@ -25,29 +25,123 @@ carry a small mark in its left margin. Note kinds (say, "Summaries" and
25
25
  fixed to the bottom that shows the notes for the section being read and
26
26
  follows the reader; tapping a paragraph pins its notes, tapping again lets
27
27
  go; the switches live in the bar. A document with no notes renders centred
28
- prose at full measure with no notes column.
28
+ prose at full measure with no notes column, no switches and no bar.
29
+
30
+ The example is a complete static-site post body: it takes the post's
31
+ `provenance.json` (written at build time by `@molecule/api-text-provenance`,
32
+ whose example produces exactly this shape) and a TL;DR per section, and
33
+ renders every block with a summary beside its section (switch ON), the prompt
34
+ beside the AI paragraphs it wrote (switch OFF), a margin mark on each AI
35
+ paragraph, the AI-share line, and the phone bar — all correct in the
36
+ prerendered HTML before any JavaScript runs.
29
37
 
30
38
  ## Quick Start
31
39
 
32
40
  ```tsx
33
- import { MarginNotes } from '@molecule/app-margin-notes-react'
41
+ // PostBody.tsx — a post's body with notes beside it, rendered from the post's provenance.json
42
+ // (written at build time by @molecule/api-text-provenance) and its section summaries.
43
+ import type { JSX } from 'react'
44
+
45
+ import {
46
+ type MarginNote,
47
+ type MarginNoteKind,
48
+ MarginNotes,
49
+ type MarginNotesBlock,
50
+ } from '@molecule/app-margin-notes-react'
51
+ import { requireProvider } from '@molecule/app-markdown'
52
+ import { useTranslation } from '@molecule/app-react'
53
+ import { getClassMap } from '@molecule/app-ui'
54
+
55
+ // One entry of provenance.json's `spans`: a block of the post's markdown, in page order.
56
+ export interface PostSpan {
57
+ text: string
58
+ origin: 'human' | 'ai'
59
+ prompt?: string
60
+ model?: string
61
+ }
34
62
 
35
- // blocks: your rendered paragraphs, in order; notes: what goes beside them.
36
- ;<MarginNotes
37
- blocks={[
38
- { id: 'p1', content: <p>Every post carries a map of who wrote what.</p>, noteIds: ['s1'] },
39
- {
40
- id: 'p2',
41
- content: <p>The map is built from the session export.</p>,
42
- noteIds: ['s1', 'q1'],
43
- marked: true,
44
- },
45
- ]}
46
- notes={[
47
- { id: 's1', kind: 'summary', content: <p>How the map is made.</p> },
48
- { id: 'q1', kind: 'prompt', content: <p>“explain the map” — claude-opus-4</p> },
49
- ]}
50
- kinds={[
63
+ // provenance.json, as the build wrote it.
64
+ export interface PostProvenance {
65
+ aiShare: number
66
+ prompts: string[]
67
+ spans: PostSpan[]
68
+ }
69
+
70
+ // The span indexes that start a section: 0 (the lead), then every heading at the post's
71
+ // shallowest heading level. Key your summaries by these indexes.
72
+ export function sectionStarts(spans: PostSpan[]): number[] {
73
+ const level = (text: string): number => text.match(/^#{1,6}(?=\s)/)?.[0].length ?? 0
74
+ const top = Math.min(...spans.map((span) => level(span.text) || 7))
75
+ return spans.flatMap((span, i) => (i === 0 || level(span.text) === top ? [i] : []))
76
+ }
77
+
78
+ // summaries: TL;DR text per section, keyed by the section's start index from sectionStarts().
79
+ export function PostBody({
80
+ provenance,
81
+ summaries = {},
82
+ }: {
83
+ provenance: PostProvenance
84
+ summaries?: Record<number, string>
85
+ }): JSX.Element {
86
+ const cm = getClassMap()
87
+ const { t } = useTranslation()
88
+ const markdown = requireProvider()
89
+ const label = cm.cn(cm.textSize('xs'), cm.uppercase, cm.trackingWide, cm.fontWeight('semibold'))
90
+ const starts = new Set(sectionStarts(provenance.spans))
91
+ const notes: MarginNote[] = []
92
+ const promptNoteIds = new Map<string, string>()
93
+ let summaryId: string | undefined
94
+
95
+ const blocks: MarginNotesBlock[] = provenance.spans.map((span, i) => {
96
+ if (starts.has(i)) {
97
+ summaryId = summaries[i] ? `summary-${i}` : undefined
98
+ if (summaryId) {
99
+ notes.push({
100
+ id: summaryId,
101
+ kind: 'summary',
102
+ content: (
103
+ <>
104
+ <p className={label}>{t('post.tldr', undefined, { defaultValue: 'TL;DR' })}</p>
105
+ <p>{summaries[i]}</p>
106
+ </>
107
+ ),
108
+ })
109
+ }
110
+ }
111
+ const noteIds = summaryId ? [summaryId] : []
112
+ if (span.origin === 'ai' && span.prompt) {
113
+ let id = promptNoteIds.get(span.prompt)
114
+ if (!id) {
115
+ id = `prompt-${promptNoteIds.size}`
116
+ promptNoteIds.set(span.prompt, id)
117
+ notes.push({
118
+ id,
119
+ kind: 'prompt',
120
+ content: (
121
+ <>
122
+ <p className={cm.cn(label, cm.textPrimary)}>
123
+ {t(
124
+ 'post.promptBy',
125
+ { model: span.model ?? '' },
126
+ { defaultValue: 'Prompt · {{model}}' },
127
+ )}
128
+ </p>
129
+ <p className={cm.textPrimary}>{span.prompt}</p>
130
+ </>
131
+ ),
132
+ })
133
+ }
134
+ noteIds.push(id)
135
+ }
136
+ return {
137
+ id: `block-${i}`,
138
+ content: <div dangerouslySetInnerHTML={{ __html: markdown.render(span.text).html }} />,
139
+ noteIds,
140
+ marked: span.origin === 'ai',
141
+ }
142
+ })
143
+
144
+ const kinds: MarginNoteKind[] = [
51
145
  {
52
146
  id: 'summary',
53
147
  label: t('post.summaries', undefined, { defaultValue: 'Summaries' }),
@@ -59,9 +153,45 @@ import { MarginNotes } from '@molecule/app-margin-notes-react'
59
153
  defaultOn: false,
60
154
  panel: 'tap',
61
155
  },
62
- ]}
63
- markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
64
- />
156
+ ]
157
+ const percent = Math.round(provenance.aiShare * 100)
158
+ const count = provenance.prompts.length
159
+ const share =
160
+ count === 0
161
+ ? t('post.allHuman', undefined, {
162
+ defaultValue: 'Every word of this post was written by a person.',
163
+ })
164
+ : t(
165
+ count === 1 ? 'post.aiShareOne' : 'post.aiShare',
166
+ { percent, count },
167
+ {
168
+ defaultValue:
169
+ count === 1
170
+ ? '{{percent}}% of the words were written by an AI, from 1 prompt'
171
+ : '{{percent}}% of the words were written by an AI, from {{count}} prompts',
172
+ },
173
+ )
174
+
175
+ return (
176
+ <div className={cm.prose}>
177
+ <p
178
+ className={cm.cn(cm.textCenter, cm.textMuted, cm.textSize('sm'))}
179
+ data-mol-id="post-ai-share"
180
+ >
181
+ {share}
182
+ </p>
183
+ <MarginNotes
184
+ blocks={blocks}
185
+ notes={notes}
186
+ kinds={kinds}
187
+ markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
188
+ />
189
+ </div>
190
+ )
191
+ }
192
+
193
+ // In the Post page, in place of the single dangerouslySetInnerHTML body:
194
+ // <PostBody provenance={post.provenance} summaries={post.summaries} />
65
195
  ```
66
196
 
67
197
  ## Type
@@ -110,7 +240,8 @@ interface MarginNoteKind {
110
240
  * How this kind reaches the phone panel. `'follow'` (default): the panel
111
241
  * shows it for the section being read, following the reader. `'tap'`: only
112
242
  * when the reader taps a block it belongs to (and gone on the second tap) —
113
- * for notes about one paragraph rather than the section.
243
+ * for notes about one paragraph rather than the section. A tap shows the
244
+ * note even while its switch is off: on a phone the tap is how it is found.
114
245
  */
115
246
  panel?: 'follow' | 'tap'
116
247
  }
@@ -185,11 +316,17 @@ interface MarginNotesRow {
185
316
 
186
317
  Group blocks into layout rows and place each note once.
187
318
 
188
- A row is a run of consecutive blocks that refer to exactly the same set of
189
- notes (a paragraph run sharing one note), or a run of consecutive blocks
190
- with no notes. Each note is shown beside the FIRST row that refers to it and
191
- never again, so a note covering several paragraphs — even ones that are not
192
- next to each other — appears once on the page.
319
+ A row runs for as long as its blocks are covered by a note it OPENED with: a
320
+ section's summary (every block of the section refers to it) keeps the whole
321
+ section in one row, and a note that first appears mid-row — a prompt behind
322
+ one of the section's paragraphs — joins that row's gutter but does not
323
+ extend the row. (A prompt that produced paragraphs in several sections once
324
+ carried a row across the next heading, and that section's summary was drawn
325
+ beside the previous section.) A sticky note is
326
+ bounded by its row, so this is what keeps a summary pinned until its section
327
+ ends; splitting the row wherever the note set changed released it after the
328
+ first paragraph. A run of blocks with no notes is a row of its own. Each note
329
+ is shown once, in the first row that refers to it.
193
330
 
194
331
  ```typescript
195
332
  function buildRows(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesRow[]
@@ -232,6 +369,25 @@ function MarginNotes(props: MarginNotesProps): JSX.Element
232
369
 
233
370
  **Returns:** The layout.
234
371
 
372
+ #### `mergeRepeatedNotes(blocks, notes)`
373
+
374
+ One note per act of writing: when consecutive blocks each carry their own
375
+ note with the same kind and the same plain-text content (one prompt that produced three
376
+ paragraphs, recorded as three notes), every later block is pointed at the
377
+ first block's note instead. {@link buildRows} places each note once, so the
378
+ prompt is shown once, beside the first paragraph it produced, and hovering
379
+ any of those paragraphs highlights that one note. The same text appearing
380
+ again after a block without it is a new act, and keeps its own note.
381
+
382
+ ```typescript
383
+ function mergeRepeatedNotes(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesBlock[]
384
+ ```
385
+
386
+ - `blocks` — The text, in reading order.
387
+ - `notes` — Every note the blocks refer to.
388
+
389
+ **Returns:** The blocks, with repeated notes pointed at the first copy.
390
+
235
391
  ## Injection Notes
236
392
 
237
393
  ### Requirements
@@ -239,7 +395,7 @@ function MarginNotes(props: MarginNotesProps): JSX.Element
239
395
  Peer dependencies:
240
396
 
241
397
  - `@molecule/app-react` ^1.0.1
242
- - `@molecule/app-ui` ^1.1.1
398
+ - `@molecule/app-ui` ^1.2.0
243
399
  - `@molecule/app-ui-react` ^1.0.1
244
400
  - `react` ^18.0.0 || ^19.0.0
245
401
 
@@ -250,33 +406,46 @@ Peer dependencies:
250
406
  - `@molecule/app-ui-react`
251
407
  - `react`
252
408
 
253
- - **Defaults are right before JavaScript runs.** Which kinds show comes from
254
- `kinds[].defaultOn` in the FIRST render (a hidden note carries the HTML
255
- `hidden` attribute), and the desktop/phone split is CSS
256
- (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`). Prerender the page with
257
- `renderToString` and a kind that defaults off is already absent; do NOT
258
- toggle defaults in a `useEffect` of your own.
259
- - **One note, one place.** A note shows beside the FIRST row that refers to
260
- it. Give consecutive paragraphs that share a note the same `noteIds` and
261
- they form one row with the note beside them once. A paragraph whose
262
- `noteIds` differ from its neighbour's starts a new row.
263
- - **The mark is drawn on the block**, as an absolutely-placed dot inside the
264
- block's own wrapper (hidden on phones, where there is no margin). At rest a
265
- marked block is typeset exactly like an unmarked one.
266
- - **Pass rendered blocks, not markdown.** Split your renderer's output into
267
- top-level blocks (one per paragraph/heading/list) and give each a stable
268
- `id`; the component adds no markup inside them.
269
- - **Section notes follow the reader; paragraph notes wait for a tap.** On a
409
+ - **Do NOT hand-build an annotator** — no grid of your own, no hover or
410
+ scroll script, no margin dots, no bottom bar, no toggle state. This
411
+ component is all of it: pass `blocks`, `notes` and `kinds`.
412
+ - **Do NOT set the defaults in a `useEffect` or hide notes with your own
413
+ CSS.** `kinds[].defaultOn` is read in the FIRST render, so
414
+ `renderToString`/prerender already ships a default-off kind with the HTML
415
+ `hidden` attribute and its switch reading off; the desktop/phone split is
416
+ CSS (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`).
417
+ - **Do NOT render the body as one HTML string.** Pass one block per
418
+ top-level markdown block (paragraph, heading, list, code), each with a
419
+ stable `id` — the example renders each provenance span with
420
+ `@molecule/app-markdown`. The component adds no markup inside a block.
421
+ - **Do NOT make one note per paragraph.** Make ONE note per prompt (or per
422
+ section summary) and put its id in the `noteIds` of every block it covers:
423
+ it shows once, beside the first. Consecutive blocks with the same
424
+ `noteIds` form one row.
425
+ - **Do NOT add a second copy of the notes for phones** (inline between
426
+ paragraphs, a popover). The bar is the phone's copy.
427
+ - **Do NOT import `@molecule/api-*` packages into the page** — they are
428
+ server-only. The page reads what the build wrote (`provenance.json`, or
429
+ spans passed to the prerender).
430
+ - The example needs `@molecule/app-markdown` and a markdown bond
431
+ (`@molecule/app-markdown-marked`), bonded once at startup:
432
+ `setProvider(provider)`.
433
+ - Section notes follow the reader; paragraph notes wait for a tap. On a
270
434
  phone the panel shows the kinds with `panel: 'follow'` (the default) for
271
- the section in view. Give a kind that is about ONE paragraph (a prompt, a
272
- citation) `panel: 'tap'`: it shows when that paragraph is tapped and goes
273
- on the second tap.
274
- - **Controlled or not.** Pass `shownKinds` + `onShownKindsChange` to own the
435
+ the section in view. A kind about ONE paragraph (a prompt, a citation)
436
+ gets `panel: 'tap'`: while its switch is off it shows only when that
437
+ paragraph is tapped (and goes on the second tap); once its switch is ON it
438
+ follows the section in view like a `'follow'` kind, so the switch always
439
+ shows something.
440
+ - The mark is drawn on the block, as an absolutely-placed dot inside the
441
+ block's own wrapper (hidden on phones). At rest a marked block is typeset
442
+ exactly like an unmarked one.
443
+ - Controlled or not: pass `shownKinds` + `onShownKindsChange` to own the
275
444
  switches' state (e.g. to remember it); otherwise the component does.
276
445
  - The phone bar reserves space at the end of the text so it never covers the
277
446
  last paragraph. UI strings come from the companion locale bond
278
- `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are yours
279
- to translate.
447
+ `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are
448
+ yours to translate.
280
449
 
281
450
  ## Translations
282
451
 
@@ -1 +1 @@
1
- {"version":3,"file":"MarginNotes.d.ts","sourceRoot":"","sources":["../src/MarginNotes.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,GAAG,EAAE,MAAM,OAAO,CAAA;AAQ/C,OAAO,KAAK,EAAc,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAQ9D;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAsShE"}
1
+ {"version":3,"file":"MarginNotes.d.ts","sourceRoot":"","sources":["../src/MarginNotes.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,GAAG,EAAE,MAAM,OAAO,CAAA;AAQ/C,OAAO,KAAK,EAAc,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAQ9D;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAgThE"}
@@ -121,17 +121,26 @@ export function MarginNotes(props) {
121
121
  if (pinnedBlock)
122
122
  return blocks.find((b) => b.id === pinnedBlock)?.noteIds ?? [];
123
123
  const ids = rows.find((r) => r.id === readingRow)?.noteIds ?? [];
124
- return ids.filter((id) => !tapOnly.has(notesById.get(id)?.kind ?? ''));
125
- }, [pinnedBlock, readingRow, blocks, rows, tapOnly, notesById]);
124
+ // A tap kind follows the reader too once its switch is ON: turning the
125
+ // switch on must show something on a phone, not wait for a tap.
126
+ return ids.filter((id) => {
127
+ const note = notesById.get(id);
128
+ return !!note && (!tapOnly.has(note.kind) || isShown(note));
129
+ });
130
+ }, [pinnedBlock, readingRow, blocks, rows, tapOnly, notesById, isShown]);
131
+ // A tapped block's tap-kind notes show whatever their switch says: on a phone
132
+ // the tap is the only way to reach a note about one paragraph (a prompt that
133
+ // defaults off). Follow-kind notes keep obeying their switch.
134
+ const inPanel = (note) => isShown(note) || (pinnedBlock !== null && tapOnly.has(note.kind));
126
135
  const panelNotes = panelNoteIds
127
136
  .map((id) => notesById.get(id))
128
- .filter((n) => !!n && isShown(n));
137
+ .filter((n) => !!n && inPanel(n));
129
138
  const switches = (placement) => kinds.length === 0 ? null : (_jsx("div", { role: "group", "aria-label": t('marginNotes.aria.toggles', undefined, {
130
139
  defaultValue: 'Show or hide notes',
131
140
  }), className: cm.flex({ direction: 'row', wrap: 'wrap', gap: 'md', align: 'center' }), "data-mol-id": `margin-notes-switches-${placement}`, children: kinds.map((kind) => (_jsx(Switch, { label: kind.label, checked: shown.includes(kind.id), onChange: (event) => setShown(kind.id, event.target.checked), className: placement === 'bar' ? cm.touchTarget : cm.touchTargetCompact, "data-mol-id": `margin-notes-switch-${placement}-${kind.id}` }, kind.id))) }));
132
141
  const noteView = (note, where) => {
133
142
  const emphasised = activeBlockNotes.has(note.id) || activeNote === note.id;
134
- return (_jsx("aside", { hidden: !isShown(note), tabIndex: where === 'gutter' ? 0 : -1, "data-note-kind": note.kind, "data-note-emphasis": emphasised ? 'true' : undefined, "data-mol-id": `margin-note-${where}-${note.id}`, onMouseEnter: where === 'gutter' ? () => setActiveNote(note.id) : undefined, onMouseLeave: where === 'gutter' ? () => setActiveNote(null) : undefined, onFocus: where === 'gutter' ? () => setActiveNote(note.id) : undefined, onBlur: where === 'gutter' ? () => setActiveNote(null) : undefined, className: cm.cn(cm.sp('p', 3), cm.textSize('sm'), cm.textMuted, emphasised && cm.bgPrimarySubtle, emphasised && cm.shadowLifted), children: note.content }, note.id));
143
+ return (_jsx("aside", { hidden: where === 'panel' ? !inPanel(note) : !isShown(note), tabIndex: where === 'gutter' ? 0 : -1, "data-note-kind": note.kind, "data-note-emphasis": emphasised ? 'true' : undefined, "data-mol-id": `margin-note-${where}-${note.id}`, onMouseEnter: where === 'gutter' ? () => setActiveNote(note.id) : undefined, onMouseLeave: where === 'gutter' ? () => setActiveNote(null) : undefined, onFocus: where === 'gutter' ? () => setActiveNote(note.id) : undefined, onBlur: where === 'gutter' ? () => setActiveNote(null) : undefined, className: cm.cn(cm.sp('p', 3), cm.textSize('sm'), cm.textMuted, emphasised && cm.bgPrimarySubtle, emphasised && cm.shadowLifted), children: note.content }, note.id));
135
144
  };
136
145
  const containerStyle = {
137
146
  ...style,
package/dist/index.d.ts CHANGED
@@ -12,58 +12,215 @@
12
12
  * fixed to the bottom that shows the notes for the section being read and
13
13
  * follows the reader; tapping a paragraph pins its notes, tapping again lets
14
14
  * go; the switches live in the bar. A document with no notes renders centred
15
- * prose at full measure with no notes column.
15
+ * prose at full measure with no notes column, no switches and no bar.
16
+ *
17
+ * The example is a complete static-site post body: it takes the post's
18
+ * `provenance.json` (written at build time by `@molecule/api-text-provenance`,
19
+ * whose example produces exactly this shape) and a TL;DR per section, and
20
+ * renders every block with a summary beside its section (switch ON), the prompt
21
+ * beside the AI paragraphs it wrote (switch OFF), a margin mark on each AI
22
+ * paragraph, the AI-share line, and the phone bar — all correct in the
23
+ * prerendered HTML before any JavaScript runs.
16
24
  *
17
25
  * @example
18
26
  * ```tsx
19
- * import { MarginNotes } from '@molecule/app-margin-notes-react'
27
+ * // PostBody.tsx — a post's body with notes beside it, rendered from the post's provenance.json
28
+ * // (written at build time by @molecule/api-text-provenance) and its section summaries.
29
+ * import type { JSX } from 'react'
30
+ *
31
+ * import {
32
+ * type MarginNote,
33
+ * type MarginNoteKind,
34
+ * MarginNotes,
35
+ * type MarginNotesBlock,
36
+ * } from '@molecule/app-margin-notes-react'
37
+ * import { requireProvider } from '@molecule/app-markdown'
38
+ * import { useTranslation } from '@molecule/app-react'
39
+ * import { getClassMap } from '@molecule/app-ui'
40
+ *
41
+ * // One entry of provenance.json's `spans`: a block of the post's markdown, in page order.
42
+ * export interface PostSpan {
43
+ * text: string
44
+ * origin: 'human' | 'ai'
45
+ * prompt?: string
46
+ * model?: string
47
+ * }
48
+ *
49
+ * // provenance.json, as the build wrote it.
50
+ * export interface PostProvenance {
51
+ * aiShare: number
52
+ * prompts: string[]
53
+ * spans: PostSpan[]
54
+ * }
55
+ *
56
+ * // The span indexes that start a section: 0 (the lead), then every heading at the post's
57
+ * // shallowest heading level. Key your summaries by these indexes.
58
+ * export function sectionStarts(spans: PostSpan[]): number[] {
59
+ * const level = (text: string): number => text.match(/^#{1,6}(?=\s)/)?.[0].length ?? 0
60
+ * const top = Math.min(...spans.map((span) => level(span.text) || 7))
61
+ * return spans.flatMap((span, i) => (i === 0 || level(span.text) === top ? [i] : []))
62
+ * }
63
+ *
64
+ * // summaries: TL;DR text per section, keyed by the section's start index from sectionStarts().
65
+ * export function PostBody({
66
+ * provenance,
67
+ * summaries = {},
68
+ * }: {
69
+ * provenance: PostProvenance
70
+ * summaries?: Record<number, string>
71
+ * }): JSX.Element {
72
+ * const cm = getClassMap()
73
+ * const { t } = useTranslation()
74
+ * const markdown = requireProvider()
75
+ * const label = cm.cn(cm.textSize('xs'), cm.uppercase, cm.trackingWide, cm.fontWeight('semibold'))
76
+ * const starts = new Set(sectionStarts(provenance.spans))
77
+ * const notes: MarginNote[] = []
78
+ * const promptNoteIds = new Map<string, string>()
79
+ * let summaryId: string | undefined
80
+ *
81
+ * const blocks: MarginNotesBlock[] = provenance.spans.map((span, i) => {
82
+ * if (starts.has(i)) {
83
+ * summaryId = summaries[i] ? `summary-${i}` : undefined
84
+ * if (summaryId) {
85
+ * notes.push({
86
+ * id: summaryId,
87
+ * kind: 'summary',
88
+ * content: (
89
+ * <>
90
+ * <p className={label}>{t('post.tldr', undefined, { defaultValue: 'TL;DR' })}</p>
91
+ * <p>{summaries[i]}</p>
92
+ * </>
93
+ * ),
94
+ * })
95
+ * }
96
+ * }
97
+ * const noteIds = summaryId ? [summaryId] : []
98
+ * if (span.origin === 'ai' && span.prompt) {
99
+ * let id = promptNoteIds.get(span.prompt)
100
+ * if (!id) {
101
+ * id = `prompt-${promptNoteIds.size}`
102
+ * promptNoteIds.set(span.prompt, id)
103
+ * notes.push({
104
+ * id,
105
+ * kind: 'prompt',
106
+ * content: (
107
+ * <>
108
+ * <p className={cm.cn(label, cm.textPrimary)}>
109
+ * {t(
110
+ * 'post.promptBy',
111
+ * { model: span.model ?? '' },
112
+ * { defaultValue: 'Prompt · {{model}}' },
113
+ * )}
114
+ * </p>
115
+ * <p className={cm.textPrimary}>{span.prompt}</p>
116
+ * </>
117
+ * ),
118
+ * })
119
+ * }
120
+ * noteIds.push(id)
121
+ * }
122
+ * return {
123
+ * id: `block-${i}`,
124
+ * content: <div dangerouslySetInnerHTML={{ __html: markdown.render(span.text).html }} />,
125
+ * noteIds,
126
+ * marked: span.origin === 'ai',
127
+ * }
128
+ * })
129
+ *
130
+ * const kinds: MarginNoteKind[] = [
131
+ * {
132
+ * id: 'summary',
133
+ * label: t('post.summaries', undefined, { defaultValue: 'Summaries' }),
134
+ * defaultOn: true,
135
+ * },
136
+ * {
137
+ * id: 'prompt',
138
+ * label: t('post.prompts', undefined, { defaultValue: 'Prompts' }),
139
+ * defaultOn: false,
140
+ * panel: 'tap',
141
+ * },
142
+ * ]
143
+ * const percent = Math.round(provenance.aiShare * 100)
144
+ * const count = provenance.prompts.length
145
+ * const share =
146
+ * count === 0
147
+ * ? t('post.allHuman', undefined, {
148
+ * defaultValue: 'Every word of this post was written by a person.',
149
+ * })
150
+ * : t(
151
+ * count === 1 ? 'post.aiShareOne' : 'post.aiShare',
152
+ * { percent, count },
153
+ * {
154
+ * defaultValue:
155
+ * count === 1
156
+ * ? '{{percent}}% of the words were written by an AI, from 1 prompt'
157
+ * : '{{percent}}% of the words were written by an AI, from {{count}} prompts',
158
+ * },
159
+ * )
160
+ *
161
+ * return (
162
+ * <div className={cm.prose}>
163
+ * <p
164
+ * className={cm.cn(cm.textCenter, cm.textMuted, cm.textSize('sm'))}
165
+ * data-mol-id="post-ai-share"
166
+ * >
167
+ * {share}
168
+ * </p>
169
+ * <MarginNotes
170
+ * blocks={blocks}
171
+ * notes={notes}
172
+ * kinds={kinds}
173
+ * markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
174
+ * />
175
+ * </div>
176
+ * )
177
+ * }
20
178
  *
21
- * // blocks: your rendered paragraphs, in order; notes: what goes beside them.
22
- * <MarginNotes
23
- * blocks={[
24
- * { id: 'p1', content: <p>Every post carries a map of who wrote what.</p>, noteIds: ['s1'] },
25
- * { id: 'p2', content: <p>The map is built from the session export.</p>, noteIds: ['s1', 'q1'], marked: true },
26
- * ]}
27
- * notes={[
28
- * { id: 's1', kind: 'summary', content: <p>How the map is made.</p> },
29
- * { id: 'q1', kind: 'prompt', content: <p>“explain the map” — claude-opus-4</p> },
30
- * ]}
31
- * kinds={[
32
- * { id: 'summary', label: t('post.summaries', undefined, { defaultValue: 'Summaries' }), defaultOn: true },
33
- * { id: 'prompt', label: t('post.prompts', undefined, { defaultValue: 'Prompts' }), defaultOn: false, panel: 'tap' },
34
- * ]}
35
- * markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
36
- * />
179
+ * // In the Post page, in place of the single dangerouslySetInnerHTML body:
180
+ * // <PostBody provenance={post.provenance} summaries={post.summaries} />
37
181
  * ```
38
182
  *
39
183
  * @remarks
40
- * - **Defaults are right before JavaScript runs.** Which kinds show comes from
41
- * `kinds[].defaultOn` in the FIRST render (a hidden note carries the HTML
42
- * `hidden` attribute), and the desktop/phone split is CSS
43
- * (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`). Prerender the page with
44
- * `renderToString` and a kind that defaults off is already absent; do NOT
45
- * toggle defaults in a `useEffect` of your own.
46
- * - **One note, one place.** A note shows beside the FIRST row that refers to
47
- * it. Give consecutive paragraphs that share a note the same `noteIds` and
48
- * they form one row with the note beside them once. A paragraph whose
49
- * `noteIds` differ from its neighbour's starts a new row.
50
- * - **The mark is drawn on the block**, as an absolutely-placed dot inside the
51
- * block's own wrapper (hidden on phones, where there is no margin). At rest a
52
- * marked block is typeset exactly like an unmarked one.
53
- * - **Pass rendered blocks, not markdown.** Split your renderer's output into
54
- * top-level blocks (one per paragraph/heading/list) and give each a stable
55
- * `id`; the component adds no markup inside them.
56
- * - **Section notes follow the reader; paragraph notes wait for a tap.** On a
184
+ * - **Do NOT hand-build an annotator** — no grid of your own, no hover or
185
+ * scroll script, no margin dots, no bottom bar, no toggle state. This
186
+ * component is all of it: pass `blocks`, `notes` and `kinds`.
187
+ * - **Do NOT set the defaults in a `useEffect` or hide notes with your own
188
+ * CSS.** `kinds[].defaultOn` is read in the FIRST render, so
189
+ * `renderToString`/prerender already ships a default-off kind with the HTML
190
+ * `hidden` attribute and its switch reading off; the desktop/phone split is
191
+ * CSS (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`).
192
+ * - **Do NOT render the body as one HTML string.** Pass one block per
193
+ * top-level markdown block (paragraph, heading, list, code), each with a
194
+ * stable `id` — the example renders each provenance span with
195
+ * `@molecule/app-markdown`. The component adds no markup inside a block.
196
+ * - **Do NOT make one note per paragraph.** Make ONE note per prompt (or per
197
+ * section summary) and put its id in the `noteIds` of every block it covers:
198
+ * it shows once, beside the first. Consecutive blocks with the same
199
+ * `noteIds` form one row.
200
+ * - **Do NOT add a second copy of the notes for phones** (inline between
201
+ * paragraphs, a popover). The bar is the phone's copy.
202
+ * - **Do NOT import `@molecule/api-*` packages into the page** — they are
203
+ * server-only. The page reads what the build wrote (`provenance.json`, or
204
+ * spans passed to the prerender).
205
+ * - The example needs `@molecule/app-markdown` and a markdown bond
206
+ * (`@molecule/app-markdown-marked`), bonded once at startup:
207
+ * `setProvider(provider)`.
208
+ * - Section notes follow the reader; paragraph notes wait for a tap. On a
57
209
  * phone the panel shows the kinds with `panel: 'follow'` (the default) for
58
- * the section in view. Give a kind that is about ONE paragraph (a prompt, a
59
- * citation) `panel: 'tap'`: it shows when that paragraph is tapped and goes
60
- * on the second tap.
61
- * - **Controlled or not.** Pass `shownKinds` + `onShownKindsChange` to own the
210
+ * the section in view. A kind about ONE paragraph (a prompt, a citation)
211
+ * gets `panel: 'tap'`: while its switch is off it shows only when that
212
+ * paragraph is tapped (and goes on the second tap); once its switch is ON it
213
+ * follows the section in view like a `'follow'` kind, so the switch always
214
+ * shows something.
215
+ * - The mark is drawn on the block, as an absolutely-placed dot inside the
216
+ * block's own wrapper (hidden on phones). At rest a marked block is typeset
217
+ * exactly like an unmarked one.
218
+ * - Controlled or not: pass `shownKinds` + `onShownKindsChange` to own the
62
219
  * switches' state (e.g. to remember it); otherwise the component does.
63
220
  * - The phone bar reserves space at the end of the text so it never covers the
64
221
  * last paragraph. UI strings come from the companion locale bond
65
- * `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are yours
66
- * to translate.
222
+ * `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are
223
+ * yours to translate.
67
224
  *
68
225
  * @module
69
226
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AAEH,cAAc,kBAAkB,CAAA;AAChC,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiOG;AAEH,cAAc,kBAAkB,CAAA;AAChC,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -12,58 +12,215 @@
12
12
  * fixed to the bottom that shows the notes for the section being read and
13
13
  * follows the reader; tapping a paragraph pins its notes, tapping again lets
14
14
  * go; the switches live in the bar. A document with no notes renders centred
15
- * prose at full measure with no notes column.
15
+ * prose at full measure with no notes column, no switches and no bar.
16
+ *
17
+ * The example is a complete static-site post body: it takes the post's
18
+ * `provenance.json` (written at build time by `@molecule/api-text-provenance`,
19
+ * whose example produces exactly this shape) and a TL;DR per section, and
20
+ * renders every block with a summary beside its section (switch ON), the prompt
21
+ * beside the AI paragraphs it wrote (switch OFF), a margin mark on each AI
22
+ * paragraph, the AI-share line, and the phone bar — all correct in the
23
+ * prerendered HTML before any JavaScript runs.
16
24
  *
17
25
  * @example
18
26
  * ```tsx
19
- * import { MarginNotes } from '@molecule/app-margin-notes-react'
27
+ * // PostBody.tsx — a post's body with notes beside it, rendered from the post's provenance.json
28
+ * // (written at build time by @molecule/api-text-provenance) and its section summaries.
29
+ * import type { JSX } from 'react'
30
+ *
31
+ * import {
32
+ * type MarginNote,
33
+ * type MarginNoteKind,
34
+ * MarginNotes,
35
+ * type MarginNotesBlock,
36
+ * } from '@molecule/app-margin-notes-react'
37
+ * import { requireProvider } from '@molecule/app-markdown'
38
+ * import { useTranslation } from '@molecule/app-react'
39
+ * import { getClassMap } from '@molecule/app-ui'
40
+ *
41
+ * // One entry of provenance.json's `spans`: a block of the post's markdown, in page order.
42
+ * export interface PostSpan {
43
+ * text: string
44
+ * origin: 'human' | 'ai'
45
+ * prompt?: string
46
+ * model?: string
47
+ * }
48
+ *
49
+ * // provenance.json, as the build wrote it.
50
+ * export interface PostProvenance {
51
+ * aiShare: number
52
+ * prompts: string[]
53
+ * spans: PostSpan[]
54
+ * }
55
+ *
56
+ * // The span indexes that start a section: 0 (the lead), then every heading at the post's
57
+ * // shallowest heading level. Key your summaries by these indexes.
58
+ * export function sectionStarts(spans: PostSpan[]): number[] {
59
+ * const level = (text: string): number => text.match(/^#{1,6}(?=\s)/)?.[0].length ?? 0
60
+ * const top = Math.min(...spans.map((span) => level(span.text) || 7))
61
+ * return spans.flatMap((span, i) => (i === 0 || level(span.text) === top ? [i] : []))
62
+ * }
63
+ *
64
+ * // summaries: TL;DR text per section, keyed by the section's start index from sectionStarts().
65
+ * export function PostBody({
66
+ * provenance,
67
+ * summaries = {},
68
+ * }: {
69
+ * provenance: PostProvenance
70
+ * summaries?: Record<number, string>
71
+ * }): JSX.Element {
72
+ * const cm = getClassMap()
73
+ * const { t } = useTranslation()
74
+ * const markdown = requireProvider()
75
+ * const label = cm.cn(cm.textSize('xs'), cm.uppercase, cm.trackingWide, cm.fontWeight('semibold'))
76
+ * const starts = new Set(sectionStarts(provenance.spans))
77
+ * const notes: MarginNote[] = []
78
+ * const promptNoteIds = new Map<string, string>()
79
+ * let summaryId: string | undefined
80
+ *
81
+ * const blocks: MarginNotesBlock[] = provenance.spans.map((span, i) => {
82
+ * if (starts.has(i)) {
83
+ * summaryId = summaries[i] ? `summary-${i}` : undefined
84
+ * if (summaryId) {
85
+ * notes.push({
86
+ * id: summaryId,
87
+ * kind: 'summary',
88
+ * content: (
89
+ * <>
90
+ * <p className={label}>{t('post.tldr', undefined, { defaultValue: 'TL;DR' })}</p>
91
+ * <p>{summaries[i]}</p>
92
+ * </>
93
+ * ),
94
+ * })
95
+ * }
96
+ * }
97
+ * const noteIds = summaryId ? [summaryId] : []
98
+ * if (span.origin === 'ai' && span.prompt) {
99
+ * let id = promptNoteIds.get(span.prompt)
100
+ * if (!id) {
101
+ * id = `prompt-${promptNoteIds.size}`
102
+ * promptNoteIds.set(span.prompt, id)
103
+ * notes.push({
104
+ * id,
105
+ * kind: 'prompt',
106
+ * content: (
107
+ * <>
108
+ * <p className={cm.cn(label, cm.textPrimary)}>
109
+ * {t(
110
+ * 'post.promptBy',
111
+ * { model: span.model ?? '' },
112
+ * { defaultValue: 'Prompt · {{model}}' },
113
+ * )}
114
+ * </p>
115
+ * <p className={cm.textPrimary}>{span.prompt}</p>
116
+ * </>
117
+ * ),
118
+ * })
119
+ * }
120
+ * noteIds.push(id)
121
+ * }
122
+ * return {
123
+ * id: `block-${i}`,
124
+ * content: <div dangerouslySetInnerHTML={{ __html: markdown.render(span.text).html }} />,
125
+ * noteIds,
126
+ * marked: span.origin === 'ai',
127
+ * }
128
+ * })
129
+ *
130
+ * const kinds: MarginNoteKind[] = [
131
+ * {
132
+ * id: 'summary',
133
+ * label: t('post.summaries', undefined, { defaultValue: 'Summaries' }),
134
+ * defaultOn: true,
135
+ * },
136
+ * {
137
+ * id: 'prompt',
138
+ * label: t('post.prompts', undefined, { defaultValue: 'Prompts' }),
139
+ * defaultOn: false,
140
+ * panel: 'tap',
141
+ * },
142
+ * ]
143
+ * const percent = Math.round(provenance.aiShare * 100)
144
+ * const count = provenance.prompts.length
145
+ * const share =
146
+ * count === 0
147
+ * ? t('post.allHuman', undefined, {
148
+ * defaultValue: 'Every word of this post was written by a person.',
149
+ * })
150
+ * : t(
151
+ * count === 1 ? 'post.aiShareOne' : 'post.aiShare',
152
+ * { percent, count },
153
+ * {
154
+ * defaultValue:
155
+ * count === 1
156
+ * ? '{{percent}}% of the words were written by an AI, from 1 prompt'
157
+ * : '{{percent}}% of the words were written by an AI, from {{count}} prompts',
158
+ * },
159
+ * )
160
+ *
161
+ * return (
162
+ * <div className={cm.prose}>
163
+ * <p
164
+ * className={cm.cn(cm.textCenter, cm.textMuted, cm.textSize('sm'))}
165
+ * data-mol-id="post-ai-share"
166
+ * >
167
+ * {share}
168
+ * </p>
169
+ * <MarginNotes
170
+ * blocks={blocks}
171
+ * notes={notes}
172
+ * kinds={kinds}
173
+ * markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
174
+ * />
175
+ * </div>
176
+ * )
177
+ * }
20
178
  *
21
- * // blocks: your rendered paragraphs, in order; notes: what goes beside them.
22
- * <MarginNotes
23
- * blocks={[
24
- * { id: 'p1', content: <p>Every post carries a map of who wrote what.</p>, noteIds: ['s1'] },
25
- * { id: 'p2', content: <p>The map is built from the session export.</p>, noteIds: ['s1', 'q1'], marked: true },
26
- * ]}
27
- * notes={[
28
- * { id: 's1', kind: 'summary', content: <p>How the map is made.</p> },
29
- * { id: 'q1', kind: 'prompt', content: <p>“explain the map” — claude-opus-4</p> },
30
- * ]}
31
- * kinds={[
32
- * { id: 'summary', label: t('post.summaries', undefined, { defaultValue: 'Summaries' }), defaultOn: true },
33
- * { id: 'prompt', label: t('post.prompts', undefined, { defaultValue: 'Prompts' }), defaultOn: false, panel: 'tap' },
34
- * ]}
35
- * markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
36
- * />
179
+ * // In the Post page, in place of the single dangerouslySetInnerHTML body:
180
+ * // <PostBody provenance={post.provenance} summaries={post.summaries} />
37
181
  * ```
38
182
  *
39
183
  * @remarks
40
- * - **Defaults are right before JavaScript runs.** Which kinds show comes from
41
- * `kinds[].defaultOn` in the FIRST render (a hidden note carries the HTML
42
- * `hidden` attribute), and the desktop/phone split is CSS
43
- * (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`). Prerender the page with
44
- * `renderToString` and a kind that defaults off is already absent; do NOT
45
- * toggle defaults in a `useEffect` of your own.
46
- * - **One note, one place.** A note shows beside the FIRST row that refers to
47
- * it. Give consecutive paragraphs that share a note the same `noteIds` and
48
- * they form one row with the note beside them once. A paragraph whose
49
- * `noteIds` differ from its neighbour's starts a new row.
50
- * - **The mark is drawn on the block**, as an absolutely-placed dot inside the
51
- * block's own wrapper (hidden on phones, where there is no margin). At rest a
52
- * marked block is typeset exactly like an unmarked one.
53
- * - **Pass rendered blocks, not markdown.** Split your renderer's output into
54
- * top-level blocks (one per paragraph/heading/list) and give each a stable
55
- * `id`; the component adds no markup inside them.
56
- * - **Section notes follow the reader; paragraph notes wait for a tap.** On a
184
+ * - **Do NOT hand-build an annotator** — no grid of your own, no hover or
185
+ * scroll script, no margin dots, no bottom bar, no toggle state. This
186
+ * component is all of it: pass `blocks`, `notes` and `kinds`.
187
+ * - **Do NOT set the defaults in a `useEffect` or hide notes with your own
188
+ * CSS.** `kinds[].defaultOn` is read in the FIRST render, so
189
+ * `renderToString`/prerender already ships a default-off kind with the HTML
190
+ * `hidden` attribute and its switch reading off; the desktop/phone split is
191
+ * CSS (`cm.hiddenBelow('md')` / `cm.hiddenFrom('md')`).
192
+ * - **Do NOT render the body as one HTML string.** Pass one block per
193
+ * top-level markdown block (paragraph, heading, list, code), each with a
194
+ * stable `id` — the example renders each provenance span with
195
+ * `@molecule/app-markdown`. The component adds no markup inside a block.
196
+ * - **Do NOT make one note per paragraph.** Make ONE note per prompt (or per
197
+ * section summary) and put its id in the `noteIds` of every block it covers:
198
+ * it shows once, beside the first. Consecutive blocks with the same
199
+ * `noteIds` form one row.
200
+ * - **Do NOT add a second copy of the notes for phones** (inline between
201
+ * paragraphs, a popover). The bar is the phone's copy.
202
+ * - **Do NOT import `@molecule/api-*` packages into the page** — they are
203
+ * server-only. The page reads what the build wrote (`provenance.json`, or
204
+ * spans passed to the prerender).
205
+ * - The example needs `@molecule/app-markdown` and a markdown bond
206
+ * (`@molecule/app-markdown-marked`), bonded once at startup:
207
+ * `setProvider(provider)`.
208
+ * - Section notes follow the reader; paragraph notes wait for a tap. On a
57
209
  * phone the panel shows the kinds with `panel: 'follow'` (the default) for
58
- * the section in view. Give a kind that is about ONE paragraph (a prompt, a
59
- * citation) `panel: 'tap'`: it shows when that paragraph is tapped and goes
60
- * on the second tap.
61
- * - **Controlled or not.** Pass `shownKinds` + `onShownKindsChange` to own the
210
+ * the section in view. A kind about ONE paragraph (a prompt, a citation)
211
+ * gets `panel: 'tap'`: while its switch is off it shows only when that
212
+ * paragraph is tapped (and goes on the second tap); once its switch is ON it
213
+ * follows the section in view like a `'follow'` kind, so the switch always
214
+ * shows something.
215
+ * - The mark is drawn on the block, as an absolutely-placed dot inside the
216
+ * block's own wrapper (hidden on phones). At rest a marked block is typeset
217
+ * exactly like an unmarked one.
218
+ * - Controlled or not: pass `shownKinds` + `onShownKindsChange` to own the
62
219
  * switches' state (e.g. to remember it); otherwise the component does.
63
220
  * - The phone bar reserves space at the end of the text so it never covers the
64
221
  * last paragraph. UI strings come from the companion locale bond
65
- * `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are yours
66
- * to translate.
222
+ * `@molecule/app-locales-margin-notes`; kind labels and `markLabel` are
223
+ * yours to translate.
67
224
  *
68
225
  * @module
69
226
  */
package/dist/rows.d.ts CHANGED
@@ -2,17 +2,37 @@ import type { MarginNote, MarginNotesBlock, MarginNotesRow } from './types.js';
2
2
  /**
3
3
  * Group blocks into layout rows and place each note once.
4
4
  *
5
- * A row is a run of consecutive blocks that refer to exactly the same set of
6
- * notes (a paragraph run sharing one note), or a run of consecutive blocks
7
- * with no notes. Each note is shown beside the FIRST row that refers to it and
8
- * never again, so a note covering several paragraphs — even ones that are not
9
- * next to each other — appears once on the page.
5
+ * A row runs for as long as its blocks are covered by a note it OPENED with: a
6
+ * section's summary (every block of the section refers to it) keeps the whole
7
+ * section in one row, and a note that first appears mid-row — a prompt behind
8
+ * one of the section's paragraphs — joins that row's gutter but does not
9
+ * extend the row. (A prompt that produced paragraphs in several sections once
10
+ * carried a row across the next heading, and that section's summary was drawn
11
+ * beside the previous section.) A sticky note is
12
+ * bounded by its row, so this is what keeps a summary pinned until its section
13
+ * ends; splitting the row wherever the note set changed released it after the
14
+ * first paragraph. A run of blocks with no notes is a row of its own. Each note
15
+ * is shown once, in the first row that refers to it.
10
16
  *
11
17
  * @param blocks - The text, in reading order.
12
18
  * @param notes - Every note the blocks refer to; ids with no note are ignored.
13
19
  * @returns The rows, in reading order.
14
20
  */
15
21
  export declare function buildRows(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesRow[];
22
+ /**
23
+ * One note per act of writing: when consecutive blocks each carry their own
24
+ * note with the same kind and the same plain-text content (one prompt that produced three
25
+ * paragraphs, recorded as three notes), every later block is pointed at the
26
+ * first block's note instead. {@link buildRows} places each note once, so the
27
+ * prompt is shown once, beside the first paragraph it produced, and hovering
28
+ * any of those paragraphs highlights that one note. The same text appearing
29
+ * again after a block without it is a new act, and keeps its own note.
30
+ *
31
+ * @param blocks - The text, in reading order.
32
+ * @param notes - Every note the blocks refer to.
33
+ * @returns The blocks, with repeated notes pointed at the first copy.
34
+ */
35
+ export declare function mergeRepeatedNotes(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesBlock[];
16
36
  /**
17
37
  * The kinds shown before the reader touches a switch.
18
38
  *
@@ -1 +1 @@
1
- {"version":3,"file":"rows.d.ts","sourceRoot":"","sources":["../src/rows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAE9E;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,gBAAgB,EAAE,EAAE,KAAK,GAAE,UAAU,EAAO,GAAG,cAAc,EAAE,CA0BhG;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,EAAO,GAAG,MAAM,EAAE,CAE7F"}
1
+ {"version":3,"file":"rows.d.ts","sourceRoot":"","sources":["../src/rows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAE9E;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,gBAAgB,EAAE,EAAE,KAAK,GAAE,UAAU,EAAO,GAAG,cAAc,EAAE,CAoChG;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,gBAAgB,EAAE,EAC1B,KAAK,GAAE,UAAU,EAAO,GACvB,gBAAgB,EAAE,CAyBpB;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,EAAO,GAAG,MAAM,EAAE,CAE7F"}
package/dist/rows.js CHANGED
@@ -1,17 +1,24 @@
1
1
  /**
2
2
  * Group blocks into layout rows and place each note once.
3
3
  *
4
- * A row is a run of consecutive blocks that refer to exactly the same set of
5
- * notes (a paragraph run sharing one note), or a run of consecutive blocks
6
- * with no notes. Each note is shown beside the FIRST row that refers to it and
7
- * never again, so a note covering several paragraphs — even ones that are not
8
- * next to each other — appears once on the page.
4
+ * A row runs for as long as its blocks are covered by a note it OPENED with: a
5
+ * section's summary (every block of the section refers to it) keeps the whole
6
+ * section in one row, and a note that first appears mid-row — a prompt behind
7
+ * one of the section's paragraphs — joins that row's gutter but does not
8
+ * extend the row. (A prompt that produced paragraphs in several sections once
9
+ * carried a row across the next heading, and that section's summary was drawn
10
+ * beside the previous section.) A sticky note is
11
+ * bounded by its row, so this is what keeps a summary pinned until its section
12
+ * ends; splitting the row wherever the note set changed released it after the
13
+ * first paragraph. A run of blocks with no notes is a row of its own. Each note
14
+ * is shown once, in the first row that refers to it.
9
15
  *
10
16
  * @param blocks - The text, in reading order.
11
17
  * @param notes - Every note the blocks refer to; ids with no note are ignored.
12
18
  * @returns The rows, in reading order.
13
19
  */
14
20
  export function buildRows(blocks, notes = []) {
21
+ blocks = mergeRepeatedNotes(blocks, notes);
15
22
  const byId = new Map(notes.map((n) => [n.id, n]));
16
23
  const known = (ids) => [...new Set(ids ?? [])].filter((id) => byId.has(id));
17
24
  const key = (ids) => [...ids].sort().join('\u0000');
@@ -19,15 +26,26 @@ export function buildRows(blocks, notes = []) {
19
26
  const placed = new Set();
20
27
  let current = null;
21
28
  let currentKey = '';
29
+ let opening = [];
22
30
  for (const block of blocks) {
23
31
  const ids = known(block.noteIds);
24
32
  const k = key(ids);
25
- if (current && k === currentKey) {
33
+ const stillCovered = current !== null && ids.some((id) => opening.includes(id));
34
+ if (current && (k === currentKey || stillCovered)) {
26
35
  current.blocks.push(block);
36
+ for (const id of ids) {
37
+ if (!current.noteIds.includes(id))
38
+ current.noteIds.push(id);
39
+ if (placed.has(id))
40
+ continue;
41
+ placed.add(id);
42
+ current.notes.push(byId.get(id));
43
+ }
27
44
  continue;
28
45
  }
29
- current = { id: block.id, blocks: [block], notes: [], noteIds: ids };
46
+ current = { id: block.id, blocks: [block], notes: [], noteIds: [...ids] };
30
47
  currentKey = k;
48
+ opening = ids;
31
49
  for (const id of ids) {
32
50
  if (placed.has(id))
33
51
  continue;
@@ -38,6 +56,47 @@ export function buildRows(blocks, notes = []) {
38
56
  }
39
57
  return rows;
40
58
  }
59
+ /**
60
+ * One note per act of writing: when consecutive blocks each carry their own
61
+ * note with the same kind and the same plain-text content (one prompt that produced three
62
+ * paragraphs, recorded as three notes), every later block is pointed at the
63
+ * first block's note instead. {@link buildRows} places each note once, so the
64
+ * prompt is shown once, beside the first paragraph it produced, and hovering
65
+ * any of those paragraphs highlights that one note. The same text appearing
66
+ * again after a block without it is a new act, and keeps its own note.
67
+ *
68
+ * @param blocks - The text, in reading order.
69
+ * @param notes - Every note the blocks refer to.
70
+ * @returns The blocks, with repeated notes pointed at the first copy.
71
+ */
72
+ export function mergeRepeatedNotes(blocks, notes = []) {
73
+ const byId = new Map(notes.map((n) => [n.id, n]));
74
+ // Only plain-text content can be compared; a rendered element is never merged.
75
+ const content = (n) => typeof n.content === 'string' || typeof n.content === 'number'
76
+ ? `${n.kind}\u0000${String(n.content).trim()}`
77
+ : `\u0001${n.id}`;
78
+ // Content → id of the note the PREVIOUS block showed for it.
79
+ let previous = new Map();
80
+ return blocks.map((block) => {
81
+ const current = new Map();
82
+ let changed = false;
83
+ const noteIds = (block.noteIds ?? []).map((id) => {
84
+ const note = byId.get(id);
85
+ if (!note)
86
+ return id;
87
+ const key = content(note);
88
+ const first = previous.get(key);
89
+ const use = first ?? id;
90
+ if (use !== id)
91
+ changed = true;
92
+ if (!current.has(key))
93
+ current.set(key, use);
94
+ return use;
95
+ });
96
+ previous = current;
97
+ return changed ? { ...block, noteIds: [...new Set(noteIds)] } : block;
98
+ });
99
+ }
41
100
  /**
42
101
  * The kinds shown before the reader touches a switch.
43
102
  *
package/dist/types.d.ts CHANGED
@@ -37,7 +37,8 @@ export interface MarginNoteKind {
37
37
  * How this kind reaches the phone panel. `'follow'` (default): the panel
38
38
  * shows it for the section being read, following the reader. `'tap'`: only
39
39
  * when the reader taps a block it belongs to (and gone on the second tap) —
40
- * for notes about one paragraph rather than the section.
40
+ * for notes about one paragraph rather than the section. A tap shows the
41
+ * note even while its switch is off: on a phone the tap is how it is found.
41
42
  */
42
43
  panel?: 'follow' | 'tap';
43
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEtD;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,sEAAsE;IACtE,EAAE,EAAE,MAAM,CAAA;IACV,4CAA4C;IAC5C,OAAO,EAAE,SAAS,CAAA;IAClB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAED,sDAAsD;AACtD,MAAM,WAAW,UAAU;IACzB,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAA;IACV,iFAAiF;IACjF,IAAI,EAAE,MAAM,CAAA;IACZ,yBAAyB;IACzB,OAAO,EAAE,SAAS,CAAA;CACnB;AAED,gEAAgE;AAChE,MAAM,WAAW,cAAc;IAC7B,0DAA0D;IAC1D,EAAE,EAAE,MAAM,CAAA;IACV,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAA;IACb,oFAAoF;IACpF,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAA;CACzB;AAED,6BAA6B;AAC7B,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,EAAE,UAAU,CAAC;IACxF,kCAAkC;IAClC,MAAM,EAAE,gBAAgB,EAAE,CAAA;IAC1B,iGAAiG;IACjG,KAAK,CAAC,EAAE,UAAU,EAAE,CAAA;IACpB,8FAA8F;IAC9F,KAAK,CAAC,EAAE,cAAc,EAAE,CAAA;IACxB,uFAAuF;IACvF,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,iEAAiE;IACjE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,0FAA0F;IAC1F,UAAU,CAAC,EAAE,MAAM,EAAE,CAAA;IACrB,qFAAqF;IACrF,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,CAAA;CAC/C;AAED,4EAA4E;AAC5E,MAAM,WAAW,cAAc;IAC7B,gDAAgD;IAChD,EAAE,EAAE,MAAM,CAAA;IACV,wCAAwC;IACxC,MAAM,EAAE,gBAAgB,EAAE,CAAA;IAC1B,qFAAqF;IACrF,KAAK,EAAE,UAAU,EAAE,CAAA;IACnB,2EAA2E;IAC3E,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEtD;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,sEAAsE;IACtE,EAAE,EAAE,MAAM,CAAA;IACV,4CAA4C;IAC5C,OAAO,EAAE,SAAS,CAAA;IAClB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAED,sDAAsD;AACtD,MAAM,WAAW,UAAU;IACzB,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAA;IACV,iFAAiF;IACjF,IAAI,EAAE,MAAM,CAAA;IACZ,yBAAyB;IACzB,OAAO,EAAE,SAAS,CAAA;CACnB;AAED,gEAAgE;AAChE,MAAM,WAAW,cAAc;IAC7B,0DAA0D;IAC1D,EAAE,EAAE,MAAM,CAAA;IACV,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAA;IACb,oFAAoF;IACpF,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAA;CACzB;AAED,6BAA6B;AAC7B,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,EAAE,UAAU,CAAC;IACxF,kCAAkC;IAClC,MAAM,EAAE,gBAAgB,EAAE,CAAA;IAC1B,iGAAiG;IACjG,KAAK,CAAC,EAAE,UAAU,EAAE,CAAA;IACpB,8FAA8F;IAC9F,KAAK,CAAC,EAAE,cAAc,EAAE,CAAA;IACxB,uFAAuF;IACvF,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,iEAAiE;IACjE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,0FAA0F;IAC1F,UAAU,CAAC,EAAE,MAAM,EAAE,CAAA;IACrB,qFAAqF;IACrF,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,CAAA;CAC/C;AAED,4EAA4E;AAC5E,MAAM,WAAW,cAAc;IAC7B,gDAAgD;IAChD,EAAE,EAAE,MAAM,CAAA;IACV,wCAAwC;IACxC,MAAM,EAAE,gBAAgB,EAAE,CAAA;IAC1B,qFAAqF;IACrF,KAAK,EAAE,UAAU,EAAE,CAAA;IACnB,2EAA2E;IAC3E,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-margin-notes-react",
3
- "version": "1.0.0",
3
+ "version": "1.0.6",
4
4
  "description": "Long-form reading layout with notes beside each paragraph: aligned notes column, margin marks, two-way hover, switchable note kinds, and a phone bar that follows the reader",
5
5
  "homepage": "https://www.molecule.dev/packages/app-margin-notes-react",
6
6
  "type": "module",
@@ -37,14 +37,17 @@
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@molecule/app-react": "^1.0.1",
40
- "@molecule/app-ui": "^1.1.1",
40
+ "@molecule/app-ui": "^1.2.0",
41
41
  "@molecule/app-ui-react": "^1.0.1",
42
42
  "react": "^18.0.0 || ^19.0.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@molecule/app-i18n": "1.0.2",
45
+ "@molecule/app-i18n": "1.0.3",
46
+ "@molecule/app-markdown": "1.0.2",
47
+ "@molecule/app-markdown-marked": "1.0.2",
46
48
  "@molecule/app-react": "1.6.0",
47
- "@molecule/app-ui": "1.1.1",
49
+ "@molecule/app-ui": "1.3.4",
50
+ "@molecule/app-ui-react": "1.2.2",
48
51
  "@testing-library/react": "16.3.2",
49
52
  "@types/node": "26.1.2",
50
53
  "@types/react": "19.2.17",
@@ -52,7 +55,6 @@
52
55
  "react": "19.2.8",
53
56
  "react-dom": "19.2.8",
54
57
  "typescript": "6.0.3",
55
- "vitest": "4.1.11",
56
- "@molecule/app-ui-react": "1.0.2"
58
+ "vitest": "4.1.11"
57
59
  }
58
60
  }