@molecule/app-margin-notes-react 4.0.2 → 5.0.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.
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-11-21T12:46:43.684Z
6
+ Generated: 2026-11-25T19:03:24.290Z
7
7
  -->
8
8
 
9
9
  # @molecule/app-margin-notes-react
@@ -275,7 +275,7 @@ interface MarginNoteKind {
275
275
  `<MarginNotes>` props.
276
276
 
277
277
  ```typescript
278
- interface MarginNotesProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
278
+ interface MarginNotesProps extends ForwardedElementProps<BoxProps<ReactNode>, 'children'> {
279
279
  /** The text, in reading order. */
280
280
  blocks: MarginNotesBlock[]
281
281
  /** Every note the blocks refer to. A document with none renders centred prose with no gutter. */
@@ -402,8 +402,8 @@ function defaultShownKinds(kinds?: { id: string; defaultOn?: boolean }[]): strin
402
402
  Peer dependencies:
403
403
 
404
404
  - `@molecule/app-react` ^4.0.0
405
- - `@molecule/app-ui` ^1.2.0
406
- - `@molecule/app-ui-react` ^4.0.0
405
+ - `@molecule/app-ui` ^1.9.0
406
+ - `@molecule/app-ui-react` ^4.7.0
407
407
  - `react` ^18.0.0 || ^19.0.0
408
408
 
409
409
  ### Runtime Dependencies
@@ -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;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAoUhE"}
1
+ {"version":3,"file":"MarginNotes.d.ts","sourceRoot":"","sources":["../src/MarginNotes.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAA;AAShC,OAAO,KAAK,EAA8B,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAM9E;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,OAAO,CA8ThE"}
@@ -1,13 +1,13 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
2
+ import { useCallback, useMemo, useState } from 'react';
3
3
  import { useTranslation } from '@molecule/app-react';
4
4
  import { getClassMap } from '@molecule/app-ui';
5
5
  import { Icon, Switch } from '@molecule/app-ui-react';
6
+ import { Box, Pressable, ScrollArea } from '@molecule/app-ui-react/elements';
6
7
  import { buildRows, defaultShownKinds } from './rows.js';
7
- /** Layout effect in the browser, plain effect on the server (where it never runs). */
8
- const useBrowserLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
9
- /** Where a phone reader's "current section" is read: this fraction down the viewport. */
10
- const READING_LINE = 0.35;
8
+ import { useReadingPosition } from './useReadingPosition.js';
9
+ const NO_NOTES = [];
10
+ const NO_KINDS = [];
11
11
  /**
12
12
  * Long-form text with notes beside each paragraph.
13
13
  *
@@ -24,7 +24,7 @@ const READING_LINE = 0.35;
24
24
  * @returns The layout.
25
25
  */
26
26
  export function MarginNotes(props) {
27
- const { blocks, notes = [], kinds = [], markLabel, measure = '38rem', gutterWidth = '18rem', shownKinds: shownKindsProp, onShownKindsChange, className, style, ...rest } = props;
27
+ const { blocks, notes = NO_NOTES, kinds = NO_KINDS, markLabel, measure = '38rem', gutterWidth = '18rem', shownKinds: shownKindsProp, onShownKindsChange, className, style, webStyle, ...rest } = props;
28
28
  const cm = getClassMap();
29
29
  const { t } = useTranslation();
30
30
  const pinLabel = t('marginNotes.aria.pin', undefined, {
@@ -57,71 +57,9 @@ export function MarginNotes(props) {
57
57
  return new Set(b?.noteIds ?? []);
58
58
  }, [activeBlock, blocks]);
59
59
  // Phone: the section being read, and a block the reader pinned.
60
- const firstWithNotes = rows.find((r) => r.noteIds.length > 0)?.id ?? null;
61
- const [readingRow, setReadingRow] = useState(firstWithNotes);
62
60
  const [pinnedBlock, setPinnedBlock] = useState(null);
63
- const rowRefs = useRef(new Map());
64
- useEffect(() => {
65
- if (!hasNotes || typeof window === 'undefined')
66
- return;
67
- let frame = 0;
68
- const read = () => {
69
- frame = 0;
70
- const line = window.innerHeight * READING_LINE;
71
- let current = null;
72
- for (const row of rows) {
73
- const el = rowRefs.current.get(row.id);
74
- if (!el)
75
- continue;
76
- if (el.getBoundingClientRect().top > line)
77
- break;
78
- if (row.noteIds.length > 0)
79
- current = row.id;
80
- }
81
- setReadingRow(current ?? firstWithNotes);
82
- };
83
- const onScroll = () => {
84
- if (!frame)
85
- frame = window.requestAnimationFrame(read);
86
- };
87
- read();
88
- window.addEventListener('scroll', onScroll, { passive: true });
89
- window.addEventListener('resize', onScroll);
90
- return () => {
91
- window.removeEventListener('scroll', onScroll);
92
- window.removeEventListener('resize', onScroll);
93
- if (frame)
94
- window.cancelAnimationFrame(frame);
95
- };
96
- }, [hasNotes, rows, firstWithNotes]);
97
- // A row that opens on a heading (or any block with a top margin) starts its
98
- // text below the row's top; push the notes down by the same distance so a
99
- // note lines up with the first line it covers, not the margin above it.
100
- const [noteOffsets, setNoteOffsets] = useState({});
101
- useBrowserLayoutEffect(() => {
102
- if (!hasNotes)
103
- return;
104
- const measureOffsets = () => {
105
- const next = {};
106
- for (const row of rows) {
107
- if (row.notes.length === 0)
108
- continue;
109
- const rowEl = rowRefs.current.get(row.id);
110
- const blockEl = document.getElementById(row.blocks[0].id);
111
- const first = blockEl?.firstElementChild ?? blockEl;
112
- if (!rowEl || !first)
113
- continue;
114
- const top = first.getBoundingClientRect().top - rowEl.getBoundingClientRect().top;
115
- const offset = Math.max(0, Math.round(top));
116
- if (offset)
117
- next[row.id] = offset;
118
- }
119
- setNoteOffsets((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
120
- };
121
- measureOffsets();
122
- window.addEventListener('resize', measureOffsets);
123
- return () => window.removeEventListener('resize', measureOffsets);
124
- }, [hasNotes, rows]);
61
+ const { rootRef, rowRefs, blockRefs, deviceHeight, readingRow, noteOffsets, onScroll } = useReadingPosition(rows, hasNotes);
62
+ const device = deviceHeight !== undefined;
125
63
  // Kinds that reach the panel only through a block's pin (notes about one paragraph).
126
64
  const tapOnly = useMemo(() => new Set(kinds.filter((k) => k.panel === 'tap').map((k) => k.id)), [kinds]);
127
65
  const panelNoteIds = useMemo(() => {
@@ -142,29 +80,43 @@ export function MarginNotes(props) {
142
80
  const panelNotes = panelNoteIds
143
81
  .map((id) => notesById.get(id))
144
82
  .filter((n) => !!n && inPanel(n));
145
- const switches = (placement) => kinds.length === 0 ? null : (_jsx("div", { role: "group", "aria-label": t('marginNotes.aria.toggles', undefined, {
83
+ const switches = (placement) => kinds.length === 0 ? null : (_jsx(Box, { as: "div", role: "group", "aria-label": t('marginNotes.aria.toggles', undefined, {
146
84
  defaultValue: 'Show or hide notes',
147
- }), 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))) }));
85
+ }), 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: ({ target }) => {
86
+ if (target && 'checked' in target && typeof target.checked === 'boolean') {
87
+ setShown(kind.id, target.checked);
88
+ }
89
+ }, className: placement === 'bar' ? cm.touchTarget : cm.touchTargetCompact, "data-mol-id": `margin-notes-switch-${placement}-${kind.id}` }, kind.id))) }));
148
90
  const noteView = (note, where) => {
149
91
  const emphasised = activeBlockNotes.has(note.id) || activeNote === note.id;
150
- 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));
92
+ return (_jsx(Box, { as: "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));
151
93
  };
152
- const containerStyle = {
153
- ...style,
154
- maxWidth: hasNotes ? `calc(${measure} + ${gutterWidth} + 4rem)` : measure,
155
- };
156
- return (_jsxs("div", { ...rest, className: cm.cn(cm.mxAuto, cm.w('full'), className), style: containerStyle, "data-mol-id": "margin-notes", children: [hasNotes && kinds.length > 0 && (_jsx("div", { className: cm.cn(cm.hiddenBelow('md'), cm.sp('mb', 6)), children: switches('side') })), _jsx("div", { className: cm.cn(cm.textSize('xl'), cm.stack(0)), children: rows.map((row) => (_jsxs("div", { ref: (el) => {
94
+ return (_jsxs(Box, { ...rest, as: "div", ref: rootRef, className: cm.cn(cm.mxAuto, cm.w('full'), className), style: device ? { height: deviceHeight, flexShrink: 1, ...style } : style, webStyle: {
95
+ ...webStyle,
96
+ maxWidth: hasNotes ? `calc(${measure} + ${gutterWidth} + 4rem)` : measure,
97
+ }, "data-mol-id": "margin-notes", children: [hasNotes && kinds.length > 0 && (_jsx(Box, { as: "div", className: cm.cn(cm.hiddenBelow('md'), cm.sp('mb', 6)), children: switches('side') })), _jsx(ScrollArea, { as: "div", onScroll: device ? onScroll : undefined, className: cm.cn(cm.textSize('xl'), cm.stack(0)), style: device ? { flexGrow: 1 } : undefined, children: rows.map((row) => (_jsxs(Box, { as: "div", ref: (el) => {
157
98
  if (el)
158
99
  rowRefs.current.set(row.id, el);
159
100
  else
160
101
  rowRefs.current.delete(row.id);
161
- }, className: cm.flex({ direction: 'row', align: 'start', gap: 'xl' }), "data-mol-id": `margin-notes-row-${row.id}`, children: [_jsx("div", { className: cm.flex1, style: { maxWidth: measure, minWidth: 0 }, children: row.blocks.map((block) => {
102
+ }, className: cm.flex({ direction: 'row', align: 'start', gap: 'xl' }), "data-mol-id": `margin-notes-row-${row.id}`, children: [_jsx(Box, { as: "div", className: cm.flex1, webStyle: { maxWidth: measure, minWidth: 0 }, children: row.blocks.map((block) => {
162
103
  const ids = block.noteIds ?? [];
163
104
  const tinted = !!activeNote && ids.includes(activeNote);
164
105
  const interactive = ids.length > 0;
165
106
  const togglePin = () => setPinnedBlock((p) => (p === block.id ? null : block.id));
166
- return (_jsxs("div", { id: block.id, "data-mol-id": `margin-notes-block-${block.id}`, "data-block-marked": block.marked ? 'true' : undefined, "data-block-pinned": pinnedBlock === block.id ? 'true' : undefined, onMouseEnter: interactive ? () => setActiveBlock(block.id) : undefined, onMouseLeave: interactive ? () => setActiveBlock(null) : undefined, onFocus: interactive ? () => setActiveBlock(block.id) : undefined, onBlur: interactive ? () => setActiveBlock(null) : undefined, className: cm.cn(cm.position('relative'), tinted && cm.bgPrimarySubtle), children: [block.marked && (_jsx("span", { role: markNamed ? 'img' : undefined, "aria-label": markNamed ? markLabel : undefined, "aria-hidden": markNamed ? undefined : 'true', "data-mol-id": `margin-notes-mark-${block.id}`, className: cm.cn(cm.position('absolute'), cm.roundedFull, cm.bgPrimary, cm.hiddenBelow('md')), style: { left: '-0.9rem', top: '0.75em', width: '6px', height: '6px' } })), block.content, interactive && (_jsx("div", { className: cm.cn(cm.hiddenFrom('md'), cm.flex({ justify: 'end' })), children: _jsx("button", { type: "button", "aria-pressed": pinnedBlock === block.id, "aria-label": pinLabel, "data-mol-id": `margin-notes-pin-${block.id}`, onClick: togglePin, className: cm.button({ variant: 'ghost', size: 'sm' }), children: _jsx(Icon, { name: "pin", size: 16, "aria-hidden": "true" }) }) }))] }, block.id));
167
- }) }), hasNotes && (_jsx("div", { className: cm.cn(cm.hiddenBelow('md'), cm.stack(3)), style: { width: gutterWidth, flexShrink: 0, paddingTop: noteOffsets[row.id] }, "aria-label": t('marginNotes.aria.notes', undefined, { defaultValue: 'Notes' }), role: "complementary", children: row.notes.map((note) => noteView(note, 'gutter')) }))] }, row.id))) }), hasNotes && (_jsxs(_Fragment, { children: [_jsx("div", { className: cm.hiddenFrom('md'), style: { height: '14rem' }, "aria-hidden": "true" }), _jsxs("div", { className: cm.cn(cm.hiddenFrom('md'), cm.position('fixed'), cm.surface, cm.borderT, cm.shadowLifted, cm.sp('p', 3), cm.stack(2)), style: { left: 0, right: 0, bottom: 0, zIndex: 20 }, "data-mol-id": "margin-notes-bar", children: [_jsxs("div", { role: "region", "aria-live": "polite", "aria-label": t('marginNotes.aria.panel', undefined, {
107
+ return (_jsxs(Box, { as: "div", ref: (element) => {
108
+ if (element)
109
+ blockRefs.current.set(block.id, element);
110
+ else
111
+ blockRefs.current.delete(block.id);
112
+ }, id: block.id, "data-mol-id": `margin-notes-block-${block.id}`, "data-block-marked": block.marked ? 'true' : undefined, "data-block-pinned": pinnedBlock === block.id ? 'true' : undefined, onMouseEnter: interactive ? () => setActiveBlock(block.id) : undefined, onMouseLeave: interactive ? () => setActiveBlock(null) : undefined, onFocus: interactive ? () => setActiveBlock(block.id) : undefined, onBlur: interactive ? () => setActiveBlock(null) : undefined, className: cm.cn(cm.position('relative'), tinted && cm.bgPrimarySubtle), children: [block.marked && (_jsx(Box, { as: "span", role: markNamed ? 'img' : undefined, "aria-label": markNamed ? markLabel : undefined, "aria-hidden": markNamed ? undefined : 'true', "data-mol-id": `margin-notes-mark-${block.id}`, className: cm.cn(cm.position('absolute'), cm.roundedFull, cm.bgPrimary, cm.hiddenBelow('md')), style: device ? { top: 15 } : undefined, webStyle: { left: '-0.9rem', top: '0.75em', width: '6px', height: '6px' } })), block.content, interactive && (_jsx(Box, { as: "div", className: cm.cn(cm.hiddenFrom('md'), cm.flex({ justify: 'end' })), children: _jsx(Pressable, { as: "button", type: "button", "aria-pressed": pinnedBlock === block.id, "aria-label": pinLabel, "data-mol-id": `margin-notes-pin-${block.id}`, onClick: togglePin, className: cm.button({ variant: 'ghost', size: 'sm' }), children: _jsx(Icon, { name: "pin", size: 16, "aria-hidden": "true" }) }) }))] }, block.id));
113
+ }) }), hasNotes && (_jsx(Box, { as: "div", className: cm.cn(cm.hiddenBelow('md'), cm.stack(3)), webStyle: {
114
+ width: gutterWidth,
115
+ flexShrink: 0,
116
+ paddingTop: noteOffsets.get(row.id),
117
+ }, "aria-label": t('marginNotes.aria.notes', undefined, { defaultValue: 'Notes' }), role: "complementary", children: row.notes.map((note) => noteView(note, 'gutter')) }))] }, row.id))) }), hasNotes && (_jsxs(_Fragment, { children: [!device && (_jsx(Box, { as: "div", className: cm.hiddenFrom('md'), webStyle: { height: '14rem' }, "aria-hidden": "true" })), _jsxs(Box, { as: "div", className: cm.cn(cm.hiddenFrom('md'), cm.position('fixed'), cm.surface, cm.borderT, cm.shadowLifted, cm.sp('p', 3), cm.stack(2)), style: device
118
+ ? { position: 'relative', flexShrink: 0, zIndex: 20 }
119
+ : { left: 0, right: 0, bottom: 0, zIndex: 20 }, "data-mol-id": "margin-notes-bar", children: [_jsxs(ScrollArea, { as: "div", role: "region", "aria-live": "polite", "aria-label": t('marginNotes.aria.panel', undefined, {
168
120
  defaultValue: 'Notes for this section',
169
- }), style: { maxHeight: '40vh', overflowY: 'auto' }, "data-mol-id": "margin-notes-panel", children: [panelNotes.map((note) => noteView(note, 'panel')), pinnedBlock && (_jsx("button", { type: "button", onClick: () => setPinnedBlock(null), className: cm.cn(cm.button({ variant: 'ghost', size: 'sm' }), cm.touchTarget), "data-mol-id": "margin-notes-dismiss", children: t('marginNotes.dismiss', undefined, { defaultValue: 'Hide notes' }) }))] }), switches('bar')] })] }))] }));
121
+ }), style: deviceHeight === undefined ? undefined : { maxHeight: deviceHeight * 0.4 }, webStyle: { maxHeight: '40vh', overflowY: 'auto' }, "data-mol-id": "margin-notes-panel", children: [panelNotes.map((note) => noteView(note, 'panel')), pinnedBlock && (_jsx(Pressable, { as: "button", type: "button", onClick: () => setPinnedBlock(null), className: cm.cn(cm.button({ variant: 'ghost', size: 'sm' }), cm.touchTarget), "data-mol-id": "margin-notes-dismiss", children: t('marginNotes.dismiss', undefined, { defaultValue: 'Hide notes' }) }))] }), switches('bar')] })] }))] }));
170
122
  }
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { HTMLAttributes, ReactNode } from 'react';
1
+ import type { ReactNode } from 'react';
2
+ import type { BoxProps, ForwardedElementProps } from '@molecule/app-ui';
2
3
  /**
3
4
  * One block of the text — usually a paragraph or heading from your markdown
4
5
  * renderer. Blocks render in order, in the prose column.
@@ -44,7 +45,7 @@ export interface MarginNoteKind {
44
45
  panel?: 'follow' | 'tap';
45
46
  }
46
47
  /** `<MarginNotes>` props. */
47
- export interface MarginNotesProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
48
+ export interface MarginNotesProps extends ForwardedElementProps<BoxProps<ReactNode>, 'children'> {
48
49
  /** The text, in reading order. */
49
50
  blocks: MarginNotesBlock[];
50
51
  /** Every note the blocks refer to. A document with none renders centred prose with no gutter. */
@@ -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;;;;;;;OAOG;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,MA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@module
5
+ */
6
+ import { type RefObject } from 'react';
7
+ import type { ElementHandle } from '@molecule/app-ui';
8
+ import type { MarginNotesRow } from './types.js';
9
+ interface ReadingPosition {
10
+ rootRef: RefObject<ElementHandle | null>;
11
+ rowRefs: RefObject<Map<string, ElementHandle>>;
12
+ blockRefs: RefObject<Map<string, ElementHandle>>;
13
+ deviceHeight: number | undefined;
14
+ readingRow: string | null;
15
+ noteOffsets: ReadonlyMap<string, number>;
16
+ onScroll: () => void;
17
+ }
18
+ /**
19
+ * Registers each document's own boxes and samples them in the renderer's window coordinates.
20
+ *
21
+ * @param rows - The ordered rows of this document.
22
+ * @param hasNotes - Whether there are notes to measure or follow.
23
+ * @returns Registered refs, viewport information and the notes' alignment.
24
+ */
25
+ export declare function useReadingPosition(rows: MarginNotesRow[], hasNotes: boolean): ReadingPosition;
26
+ export {};
27
+ //# sourceMappingURL=useReadingPosition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useReadingPosition.d.ts","sourceRoot":"","sources":["../src/useReadingPosition.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,SAAS,EAAiC,MAAM,OAAO,CAAA;AAErE,OAAO,KAAK,EAAE,aAAa,EAAmB,MAAM,kBAAkB,CAAA;AAOtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAKhD,UAAU,eAAe;IACvB,OAAO,EAAE,SAAS,CAAC,aAAa,GAAG,IAAI,CAAC,CAAA;IACxC,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IAC9C,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IAChD,YAAY,EAAE,MAAM,GAAG,SAAS,CAAA;IAChC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACxC,QAAQ,EAAE,MAAM,IAAI,CAAA;CACrB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,EAAE,EAAE,QAAQ,EAAE,OAAO,GAAG,eAAe,CAoG7F"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Measurements for the gutter and the reading line of the phone panel.
3
+ *
4
+ * @module
5
+ */
6
+ import { useCallback, useRef, useState } from 'react';
7
+ import { measureElement, observeElementViewport, useElementLayoutEffect, } from '@molecule/app-ui-react/elements';
8
+ /** The reading line is this fraction down the visible prose viewport. */
9
+ const READING_LINE = 0.35;
10
+ /**
11
+ * Registers each document's own boxes and samples them in the renderer's window coordinates.
12
+ *
13
+ * @param rows - The ordered rows of this document.
14
+ * @param hasNotes - Whether there are notes to measure or follow.
15
+ * @returns Registered refs, viewport information and the notes' alignment.
16
+ */
17
+ export function useReadingPosition(rows, hasNotes) {
18
+ const firstWithNotes = rows.find((row) => row.noteIds.length > 0)?.id ?? null;
19
+ const [readingRow, setReadingRow] = useState(firstWithNotes);
20
+ const [noteOffsets, setNoteOffsets] = useState(new Map());
21
+ const [deviceHeight, setDeviceHeight] = useState();
22
+ const viewportRef = useRef(undefined);
23
+ const rootRef = useRef(null);
24
+ const rowRefs = useRef(new Map());
25
+ const blockRefs = useRef(new Map());
26
+ const readingSample = useRef(0);
27
+ const onScroll = useCallback(() => {
28
+ const viewport = viewportRef.current;
29
+ if (!hasNotes || !viewport)
30
+ return;
31
+ const sample = ++readingSample.current;
32
+ const boxes = rows.flatMap((row) => {
33
+ if (row.noteIds.length === 0)
34
+ return [];
35
+ const box = rowRefs.current.get(row.id);
36
+ return box ? [{ id: row.id, box }] : [];
37
+ });
38
+ const read = (line) => {
39
+ const tops = new Map();
40
+ let pending = boxes.length;
41
+ const finish = () => {
42
+ if (sample !== readingSample.current)
43
+ return;
44
+ let current = firstWithNotes;
45
+ for (const { id } of boxes) {
46
+ const top = tops.get(id);
47
+ if (top === undefined || top > line)
48
+ break;
49
+ current = id;
50
+ }
51
+ setReadingRow(current);
52
+ };
53
+ if (pending === 0)
54
+ finish();
55
+ for (const { id, box } of boxes) {
56
+ measureElement(box, ({ y }) => {
57
+ tops.set(id, y);
58
+ if (--pending === 0)
59
+ finish();
60
+ });
61
+ }
62
+ };
63
+ if (viewport.scrollOwner === 'document')
64
+ read(viewport.height * READING_LINE);
65
+ else if (rootRef.current) {
66
+ // The reading line stays put as the notes bar takes more or less space.
67
+ measureElement(rootRef.current, ({ y, height }) => {
68
+ if (sample === readingSample.current)
69
+ read(y + height * READING_LINE);
70
+ });
71
+ }
72
+ }, [firstWithNotes, hasNotes, rows]);
73
+ const alignGutter = useCallback(() => {
74
+ const offsets = new Map();
75
+ for (const row of rows) {
76
+ if (row.notes.length === 0)
77
+ continue;
78
+ const frame = rowRefs.current.get(row.id);
79
+ const block = blockRefs.current.get(row.blocks[0].id);
80
+ if (!frame || !block)
81
+ continue;
82
+ measureElement(frame, (rowBox) => {
83
+ measureElement(block, (blockBox) => {
84
+ const offset = Math.max(0, Math.round(blockBox.y - rowBox.y));
85
+ if (offset)
86
+ offsets.set(row.id, offset);
87
+ }, 'content-start');
88
+ });
89
+ }
90
+ setNoteOffsets((previous) => previous.size === offsets.size &&
91
+ [...offsets].every(([id, offset]) => previous.get(id) === offset)
92
+ ? previous
93
+ : offsets);
94
+ }, [rows]);
95
+ useElementLayoutEffect(() => {
96
+ const root = rootRef.current;
97
+ if (!root)
98
+ return;
99
+ const stop = observeElementViewport(root, (next, resized) => {
100
+ viewportRef.current = next;
101
+ if (resized) {
102
+ setDeviceHeight(next.scrollOwner === 'element' ? next.height : undefined);
103
+ // A device lays the block and gutter out at the same row start. On web a
104
+ // heading can sit below that start because its top margin collapses.
105
+ if (hasNotes && next.scrollOwner === 'document')
106
+ alignGutter();
107
+ }
108
+ onScroll();
109
+ });
110
+ return () => {
111
+ readingSample.current++;
112
+ stop();
113
+ };
114
+ }, [alignGutter, hasNotes, onScroll]);
115
+ useElementLayoutEffect(() => {
116
+ if (deviceHeight !== undefined)
117
+ onScroll();
118
+ }, [deviceHeight, onScroll]);
119
+ return { rootRef, rowRefs, blockRefs, deviceHeight, readingRow, noteOffsets, onScroll };
120
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-margin-notes-react",
3
- "version": "4.0.2",
3
+ "version": "5.0.0",
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,21 +37,21 @@
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@molecule/app-react": "^4.0.0",
40
- "@molecule/app-ui": "^1.2.0",
41
- "@molecule/app-ui-react": "^4.0.0",
40
+ "@molecule/app-ui": "^1.9.0",
41
+ "@molecule/app-ui-react": "^4.7.0",
42
42
  "react": "^18.0.0 || ^19.0.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@molecule/app-i18n": "1.2.2",
46
- "@molecule/app-markdown": "1.0.4",
47
- "@molecule/app-markdown-marked": "1.0.3",
48
- "@molecule/app-react": "4.10.1",
49
- "@molecule/app-ui": "1.5.0",
50
- "@molecule/app-ui-react": "4.2.0",
45
+ "@molecule/app-i18n": "1.3.0",
46
+ "@molecule/app-markdown": "1.1.0",
47
+ "@molecule/app-markdown-marked": "1.1.0",
48
+ "@molecule/app-react": "4.17.0",
49
+ "@molecule/app-ui": "1.13.0",
50
+ "@molecule/app-ui-react": "4.11.0",
51
51
  "@testing-library/react": "16.3.3",
52
52
  "@types/node": "26.6.5",
53
53
  "@types/react": "19.3.0",
54
- "jsdom": "30.1.3",
54
+ "jsdom": "31.0.1",
55
55
  "react": "19.3.1",
56
56
  "react-dom": "19.3.1",
57
57
  "typescript": "6.0.3",