@molecule/app-margin-notes-react
v4.0.2
Published
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
Maintainers
Readme
@molecule/app-margin-notes-react
Margin notes: long-form text with notes beside each paragraph — annotated essays, commentary, and posts that show which paragraphs an AI wrote and the prompt behind each.
Desktop: a large-type prose column and a narrower notes column to its right; each note lines up with the paragraph (or run of paragraphs) it belongs to and appears once. Hovering or focusing a paragraph emphasises its notes; hovering or focusing a note tints the paragraphs it covers. A paragraph can carry a small mark in its left margin. Note kinds (say, "Summaries" and "Prompts") each get a real switch. Phone: the notes column gives way to a bar fixed to the bottom that shows the notes for the section being read and follows the reader; a noted paragraph's pin button pins its notes, a second press lets go; the switches live in the bar. A document with no notes renders centred prose at full measure with no notes column, no switches and no bar.
The example is a complete static-site post body: it takes the post's
provenance.json (written at build time by @molecule/api-text-provenance,
whose example produces exactly this shape) and a TL;DR per section, and
renders every block with a summary beside its section (switch ON), the prompt
beside the AI paragraphs it wrote (switch OFF), a margin mark on each AI
paragraph, the AI-share line, and the phone bar — all correct in the
prerendered HTML before any JavaScript runs.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
// PostBody.tsx — a post's body with notes beside it, rendered from the post's provenance.json
// (written at build time by @molecule/api-text-provenance) and its section summaries.
import type { JSX } from 'react'
import {
type MarginNote,
type MarginNoteKind,
MarginNotes,
type MarginNotesBlock,
} from '@molecule/app-margin-notes-react'
import { requireProvider } from '@molecule/app-markdown'
import { useTranslation } from '@molecule/app-react'
import { getClassMap } from '@molecule/app-ui'
// One entry of provenance.json's `spans`: a block of the post's markdown, in page order.
export interface PostSpan {
text: string
origin: 'human' | 'ai'
prompt?: string
model?: string
}
// provenance.json, as the build wrote it.
export interface PostProvenance {
aiShare: number
prompts: string[]
spans: PostSpan[]
}
// The span indexes that start a section: 0 (the lead), then every heading at the post's
// shallowest heading level. Key your summaries by these indexes.
export function sectionStarts(spans: PostSpan[]): number[] {
const level = (text: string): number => text.match(/^#{1,6}(?=\s)/)?.[0].length ?? 0
const top = Math.min(...spans.map((span) => level(span.text) || 7))
return spans.flatMap((span, i) => (i === 0 || level(span.text) === top ? [i] : []))
}
// summaries: TL;DR text per section, keyed by the section's start index from sectionStarts().
export function PostBody({
provenance,
summaries = {},
}: {
provenance: PostProvenance
summaries?: Record<number, string>
}): JSX.Element {
const cm = getClassMap()
const { t } = useTranslation()
const markdown = requireProvider()
const label = cm.cn(cm.textSize('xs'), cm.uppercase, cm.trackingWide, cm.fontWeight('semibold'))
const starts = new Set(sectionStarts(provenance.spans))
const notes: MarginNote[] = []
const promptNoteIds = new Map<string, string>()
const blocks: MarginNotesBlock[] = provenance.spans.map((span, i) => {
// The section summary, if this span starts one; only this iteration reads it.
let summaryId: string | undefined
if (starts.has(i)) {
summaryId = summaries[i] ? `summary-${i}` : undefined
if (summaryId) {
notes.push({
id: summaryId,
kind: 'summary',
content: (
<>
<p className={label}>{t('post.tldr', undefined, { defaultValue: 'TL;DR' })}</p>
<p>{summaries[i]}</p>
</>
),
})
}
}
const noteIds = summaryId ? [summaryId] : []
if (span.origin === 'ai' && span.prompt) {
let id = promptNoteIds.get(span.prompt)
if (!id) {
id = `prompt-${promptNoteIds.size}`
promptNoteIds.set(span.prompt, id)
notes.push({
id,
kind: 'prompt',
content: (
<>
<p className={cm.cn(label, cm.textPrimary)}>
{t(
'post.promptBy',
{ model: span.model ?? '' },
{ defaultValue: 'Prompt · {{model}}' },
)}
</p>
<p className={cm.textPrimary}>{span.prompt}</p>
</>
),
})
}
noteIds.push(id)
}
return {
id: `block-${i}`,
content: <div dangerouslySetInnerHTML={{ __html: markdown.render(span.text).html }} />,
noteIds,
marked: span.origin === 'ai',
}
})
const kinds: MarginNoteKind[] = [
{
id: 'summary',
label: t('post.summaries', undefined, { defaultValue: 'Summaries' }),
defaultOn: true,
},
{
id: 'prompt',
label: t('post.prompts', undefined, { defaultValue: 'Prompts' }),
defaultOn: false,
panel: 'tap',
},
]
const percent = Math.round(provenance.aiShare * 100)
const count = provenance.prompts.length
const share =
count === 0
? t('post.allHuman', undefined, {
defaultValue: 'Every word of this post was written by a person.',
})
: t(
count === 1 ? 'post.aiShareOne' : 'post.aiShare',
{ percent, count },
{
defaultValue:
count === 1
? '{{percent}}% of the words were written by an AI, from 1 prompt'
: '{{percent}}% of the words were written by an AI, from {{count}} prompts',
},
)
return (
<div className={cm.prose}>
<p
className={cm.cn(cm.textCenter, cm.textMuted, cm.textSize('sm'))}
data-mol-id="post-ai-share"
>
{share}
</p>
<MarginNotes
blocks={blocks}
notes={notes}
kinds={kinds}
markLabel={t('post.aiWritten', undefined, { defaultValue: 'Written with AI' })}
/>
</div>
)
}
// In the Post page, in place of the single dangerouslySetInnerHTML body:
// <PostBody provenance={post.provenance} summaries={post.summaries} />Type
feature
Installation
npm install @molecule/app-margin-notes-react @molecule/app-react @molecule/app-ui @molecule/app-ui-react react
npm install -D @types/reactAPI
Interfaces
MarginNotesBlock
One block of the text — usually a paragraph or heading from your markdown renderer. Blocks render in order, in the prose column.
interface MarginNotesBlock {
/** Stable id, unique within the document (used as the DOM anchor). */
id: string
/** The rendered block (e.g. `<p>…</p>`). */
content: ReactNode
/** Ids of the notes that belong to this block (see {@link MarginNote}). */
noteIds?: string[]
/**
* Draw a small mark in this block's left margin — the one permanent sign on
* the prose itself (e.g. "written with AI"). Unmarked blocks carry none.
*/
marked?: boolean
}MarginNote
A note shown beside the block(s) it belongs to.
interface MarginNote {
/** Stable id, referenced from {@link MarginNotesBlock.noteIds}. */
id: string
/** The kind this note belongs to ({@link MarginNoteKind.id}), for its switch. */
kind: string
/** The rendered note. */
content: ReactNode
}MarginNoteKind
A kind of note the reader can show or hide with a switch.
interface MarginNoteKind {
/** Stable id, referenced from {@link MarginNote.kind}. */
id: string
/** The switch's visible label, already translated (e.g. "Summaries"). */
label: string
/** Whether this kind shows before the reader touches its switch. Default `true`. */
defaultOn?: boolean
/**
* How this kind reaches the phone panel. `'follow'` (default): the panel
* shows it for the section being read, following the reader. `'tap'`: only
* when the reader presses the pin button of a block it belongs to (and gone
* on the second press) — for notes about one paragraph rather than the
* section. The pin shows the note even while its switch is off: on a phone
* the pin is how it is found.
*/
panel?: 'follow' | 'tap'
}MarginNotesProps
<MarginNotes> props.
interface MarginNotesProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
/** The text, in reading order. */
blocks: MarginNotesBlock[]
/** Every note the blocks refer to. A document with none renders centred prose with no gutter. */
notes?: MarginNote[]
/** The note kinds, in the order their switches appear. Kinds absent here are always shown. */
kinds?: MarginNoteKind[]
/**
* Accessible name of the margin mark, already translated (e.g. "Written with
* AI"). Without it (or with a blank one) the mark is decorative and hidden
* from assistive technology — a margin mark carries no meaning on its own.
*/
markLabel?: string
/** Width of the prose column (a CSS length). Default `38rem`. */
measure?: string
/** Width of the notes column (a CSS length). Default `18rem`. */
gutterWidth?: string
/** Controlled: the ids of the kinds currently shown. Omit to let the component own it. */
shownKinds?: string[]
/** Called with the new list of shown kind ids whenever the reader flips a switch. */
onShownKindsChange?: (shown: string[]) => void
}MarginNotesRow
One row of the layout: a run of blocks and the notes shown beside it.
interface MarginNotesRow {
/** The row's key: the id of its first block. */
id: string
/** The blocks in this row, in order. */
blocks: MarginNotesBlock[]
/** Notes shown beside this row — each note appears in exactly one row, its first. */
notes: MarginNote[]
/** Every note id any block in this row refers to (for the phone panel). */
noteIds: string[]
}Functions
MarginNotes(props)
Long-form text with notes beside each paragraph.
Desktop: a prose column and, to its right, a narrower notes column; each note lines up with the block(s) it belongs to and appears once. Phone: the notes column disappears and a bar fixed to the bottom shows the notes for the section being read (a noted block's pin button pins its notes, a second press lets go), with the kind switches in the bar. Every default — which kinds show, which surface a width gets — is decided in the first render and by CSS, so server-rendered or prerendered HTML is right before any JavaScript runs.
function MarginNotes(props: MarginNotesProps): JSX.Elementprops— See {@link MarginNotesProps}.
Returns: The layout.
buildRows(blocks, notes)
Group blocks into layout rows and place each note once.
A row runs for as long as its blocks are covered by a note it OPENED with: a section's summary (every block of the section refers to it) keeps the whole section in one row, and a note that first appears mid-row — a prompt behind one of the section's paragraphs — joins that row's gutter but does not extend the row. (A prompt that produced paragraphs in several sections once carried a row across the next heading, and that section's summary was drawn beside the previous section.) A sticky note is bounded by its row, so this is what keeps a summary pinned until its section ends; splitting the row wherever the note set changed released it after the first paragraph. A run of blocks with no notes is a row of its own. Each note is shown once, in the first row that refers to it.
function buildRows(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesRow[]blocks— The text, in reading order.notes— Every note the blocks refer to; ids with no note are ignored.
Returns: The rows, in reading order.
mergeRepeatedNotes(blocks, notes)
One note per act of writing: when consecutive blocks each carry their own note with the same kind and the same plain-text content (one prompt that produced three paragraphs, recorded as three notes), every later block is pointed at the first block's note instead. {@link buildRows} places each note once, so the prompt is shown once, beside the first paragraph it produced, and hovering any of those paragraphs highlights that one note. The same text appearing again after a block without it is a new act, and keeps its own note.
function mergeRepeatedNotes(blocks: MarginNotesBlock[], notes?: MarginNote[]): MarginNotesBlock[]blocks— The text, in reading order.notes— Every note the blocks refer to.
Returns: The blocks, with repeated notes pointed at the first copy.
defaultShownKinds(kinds)
The kinds shown before the reader touches a switch.
function defaultShownKinds(kinds?: { id: string; defaultOn?: boolean }[]): string[]kinds— The switchable kinds.
Returns: The ids of the kinds that default on.
Injection Notes
Requirements
Peer dependencies:
@molecule/app-react^4.0.0@molecule/app-ui^1.2.0@molecule/app-ui-react^4.0.0react^18.0.0 || ^19.0.0
Runtime Dependencies
@molecule/app-react@molecule/app-ui@molecule/app-ui-reactreactDo NOT hand-build an annotator — no grid of your own, no hover or scroll script, no margin dots, no bottom bar, no toggle state. This component is all of it: pass
blocks,notesandkinds.Do NOT set the defaults in a
useEffector hide notes with your own CSS.kinds[].defaultOnis read in the FIRST render, sorenderToString/prerender already ships a default-off kind with the HTMLhiddenattribute and its switch reading off; the desktop/phone split is CSS (cm.hiddenBelow('md')/cm.hiddenFrom('md')).Do NOT render the body as one HTML string. Pass one block per top-level markdown block (paragraph, heading, list, code), each with a stable
id— the example renders each provenance span with@molecule/app-markdown. The component adds no markup inside a block.Do NOT make one note per paragraph. Make ONE note per prompt (or per section summary) and put its id in the
noteIdsof every block it covers: it shows once, beside the first. Consecutive blocks with the samenoteIdsform one row.Do NOT add a second copy of the notes for phones (inline between paragraphs, a popover). The bar is the phone's copy.
Do NOT import
@molecule/api-*packages into the page — they are server-only. The page reads what the build wrote (provenance.json, or spans passed to the prerender).The example needs
@molecule/app-markdownand a markdown bond (@molecule/app-markdown-marked), bonded once at startup:setProvider(provider).Section notes follow the reader; paragraph notes wait for the pin. On a phone the panel shows the kinds with
panel: 'follow'(the default) for the section in view. A kind about ONE paragraph (a prompt, a citation) getspanel: 'tap': while its switch is off it shows only when that paragraph's pin button is pressed (and goes on the second press); once its switch is ON it follows the section in view like a'follow'kind, so the switch always shows something.The mark is drawn on the block, as an absolutely-placed dot inside the block's own wrapper (hidden on phones). At rest a marked block is typeset exactly like an unmarked one.
Controlled or not: pass
shownKinds+onShownKindsChangeto own the switches' state (e.g. to remember it); otherwise the component does.The phone bar reserves space at the end of the text so it never covers the last paragraph. UI strings come from the companion locale bond
@molecule/app-locales-margin-notes; kind labels andmarkLabelare yours to translate.
Translations
Translation strings are provided by @molecule/app-locales-margin-notes.
