@open-press/cli 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +11 -12
  2. package/dist/cli.js +298 -79
  3. package/package.json +9 -7
  4. package/template/core/AGENTS.md +0 -130
  5. package/template/core/CHANGELOG.md +0 -218
  6. package/template/core/README.md +0 -43
  7. package/template/core/engine/cli.mjs +0 -96
  8. package/template/core/engine/commands/_shared.mjs +0 -199
  9. package/template/core/engine/commands/deploy.mjs +0 -31
  10. package/template/core/engine/commands/dev.mjs +0 -49
  11. package/template/core/engine/commands/doctor.mjs +0 -229
  12. package/template/core/engine/commands/export.mjs +0 -8
  13. package/template/core/engine/commands/image.mjs +0 -29
  14. package/template/core/engine/commands/inspect.mjs +0 -35
  15. package/template/core/engine/commands/pdf.mjs +0 -26
  16. package/template/core/engine/commands/preview.mjs +0 -26
  17. package/template/core/engine/commands/render.mjs +0 -17
  18. package/template/core/engine/commands/replace.mjs +0 -41
  19. package/template/core/engine/commands/search.mjs +0 -33
  20. package/template/core/engine/commands/skills-sync.mjs +0 -71
  21. package/template/core/engine/commands/typecheck.mjs +0 -67
  22. package/template/core/engine/commands/upgrade.mjs +0 -159
  23. package/template/core/engine/commands/validate.mjs +0 -17
  24. package/template/core/engine/document-export.mjs +0 -15
  25. package/template/core/engine/output/chrome-pdf.d.mts +0 -34
  26. package/template/core/engine/output/chrome-pdf.mjs +0 -450
  27. package/template/core/engine/output/deploy-sync.mjs +0 -15
  28. package/template/core/engine/output/fonts.mjs +0 -62
  29. package/template/core/engine/output/katex-assets.mjs +0 -45
  30. package/template/core/engine/output/page-block.mjs +0 -30
  31. package/template/core/engine/output/pdf-media.mjs +0 -45
  32. package/template/core/engine/output/public-assets.mjs +0 -19
  33. package/template/core/engine/output/static-server.mjs +0 -571
  34. package/template/core/engine/react/caption-numbering.mjs +0 -73
  35. package/template/core/engine/react/comment-endpoint.d.mts +0 -11
  36. package/template/core/engine/react/comment-endpoint.mjs +0 -102
  37. package/template/core/engine/react/comment-marker.mjs +0 -374
  38. package/template/core/engine/react/document-entry.mjs +0 -331
  39. package/template/core/engine/react/document-export.mjs +0 -512
  40. package/template/core/engine/react/http-json.mjs +0 -24
  41. package/template/core/engine/react/mdx-compile.mjs +0 -629
  42. package/template/core/engine/react/measurement-css.mjs +0 -157
  43. package/template/core/engine/react/object-entities.mjs +0 -204
  44. package/template/core/engine/react/pagination/allocator.mjs +0 -167
  45. package/template/core/engine/react/pagination/regions.mjs +0 -81
  46. package/template/core/engine/react/pagination-constants.mjs +0 -3
  47. package/template/core/engine/react/pagination.mjs +0 -9
  48. package/template/core/engine/react/pipeline/allocate.mjs +0 -217
  49. package/template/core/engine/react/pipeline/final-render.mjs +0 -94
  50. package/template/core/engine/react/pipeline/frame-measurement.mjs +0 -306
  51. package/template/core/engine/react/pipeline/press-tree.mjs +0 -135
  52. package/template/core/engine/react/press-tree-inspection.mjs +0 -172
  53. package/template/core/engine/react/project-asset-endpoint.d.mts +0 -10
  54. package/template/core/engine/react/project-asset-endpoint.mjs +0 -361
  55. package/template/core/engine/react/section-css.mjs +0 -56
  56. package/template/core/engine/react/source-edit-endpoint.d.mts +0 -10
  57. package/template/core/engine/react/source-edit-endpoint.mjs +0 -75
  58. package/template/core/engine/react/sources/heading-numbering.mjs +0 -132
  59. package/template/core/engine/react/sources/mdx-resolver.mjs +0 -439
  60. package/template/core/engine/react/style-discovery.mjs +0 -160
  61. package/template/core/engine/runtime/config.d.mts +0 -48
  62. package/template/core/engine/runtime/config.mjs +0 -172
  63. package/template/core/engine/runtime/file-utils.mjs +0 -114
  64. package/template/core/engine/runtime/file-walk.mjs +0 -22
  65. package/template/core/engine/runtime/inspection.mjs +0 -328
  66. package/template/core/engine/runtime/issue-report.mjs +0 -44
  67. package/template/core/engine/runtime/page-geometry.mjs +0 -131
  68. package/template/core/engine/runtime/path-utils.mjs +0 -20
  69. package/template/core/engine/runtime/source-text-tools.d.mts +0 -102
  70. package/template/core/engine/runtime/source-text-tools.mjs +0 -832
  71. package/template/core/engine/runtime/source-workspace.mjs +0 -168
  72. package/template/core/engine/runtime/validation.mjs +0 -183
  73. package/template/core/index.html +0 -13
  74. package/template/core/openpress.config.mjs +0 -8
  75. package/template/core/package.json +0 -89
  76. package/template/core/src/main.tsx +0 -16
  77. package/template/core/src/openpress/app/OpenPressApp.tsx +0 -296
  78. package/template/core/src/openpress/app/OpenPressRuntime.tsx +0 -102
  79. package/template/core/src/openpress/app/WorkspaceGalleryPage.tsx +0 -219
  80. package/template/core/src/openpress/app/index.ts +0 -2
  81. package/template/core/src/openpress/core/Frame.tsx +0 -91
  82. package/template/core/src/openpress/core/FrameContext.tsx +0 -26
  83. package/template/core/src/openpress/core/MdxArea.tsx +0 -34
  84. package/template/core/src/openpress/core/Press.tsx +0 -55
  85. package/template/core/src/openpress/core/Workspace.tsx +0 -36
  86. package/template/core/src/openpress/core/cn.ts +0 -4
  87. package/template/core/src/openpress/core/index.tsx +0 -47
  88. package/template/core/src/openpress/core/primitives.tsx +0 -91
  89. package/template/core/src/openpress/core/types.ts +0 -236
  90. package/template/core/src/openpress/core/useSource.ts +0 -28
  91. package/template/core/src/openpress/document-model/anchorMapModel.ts +0 -27
  92. package/template/core/src/openpress/document-model/documentIndexes.ts +0 -329
  93. package/template/core/src/openpress/document-model/documentTypes.ts +0 -147
  94. package/template/core/src/openpress/document-model/index.ts +0 -7
  95. package/template/core/src/openpress/document-model/objectEntityModel.ts +0 -55
  96. package/template/core/src/openpress/document-model/projectIdentityModel.ts +0 -15
  97. package/template/core/src/openpress/document-model/reactDocumentMetadataModel.ts +0 -27
  98. package/template/core/src/openpress/document-model/workspaceManifestModel.ts +0 -57
  99. package/template/core/src/openpress/manuscript/index.tsx +0 -238
  100. package/template/core/src/openpress/mdx/index.ts +0 -96
  101. package/template/core/src/openpress/numbering/index.ts +0 -294
  102. package/template/core/src/openpress/reader/PageThumbnailsPanel.tsx +0 -168
  103. package/template/core/src/openpress/reader/PublicReaderPage.tsx +0 -267
  104. package/template/core/src/openpress/reader/ReaderNavigationPanel.tsx +0 -123
  105. package/template/core/src/openpress/reader/index.ts +0 -11
  106. package/template/core/src/openpress/reader/pageViewportScaleModel.ts +0 -73
  107. package/template/core/src/openpress/reader/readerPageRegistry.ts +0 -41
  108. package/template/core/src/openpress/reader/readerPageRoute.ts +0 -21
  109. package/template/core/src/openpress/reader/readerScroll.ts +0 -92
  110. package/template/core/src/openpress/reader/readerStateModel.ts +0 -15
  111. package/template/core/src/openpress/reader/readerTypes.ts +0 -4
  112. package/template/core/src/openpress/reader/usePageViewportScale.ts +0 -119
  113. package/template/core/src/openpress/reader/usePanelState.ts +0 -56
  114. package/template/core/src/openpress/reader/useReaderHashSync.ts +0 -61
  115. package/template/core/src/openpress/reader/useReaderKeyboardNav.ts +0 -48
  116. package/template/core/src/openpress/reader/useReaderRuntime.ts +0 -146
  117. package/template/core/src/openpress/reader/useReaderScrollAnchor.ts +0 -64
  118. package/template/core/src/openpress/shared/Panel.tsx +0 -77
  119. package/template/core/src/openpress/shared/frameScheduler.ts +0 -32
  120. package/template/core/src/openpress/shared/index.ts +0 -4
  121. package/template/core/src/openpress/shared/numberUtils.ts +0 -3
  122. package/template/core/src/openpress/shared/runtimeMode.ts +0 -11
  123. package/template/core/src/openpress/workbench/Workbench.tsx +0 -506
  124. package/template/core/src/openpress/workbench/actions/DeploymentControl.tsx +0 -157
  125. package/template/core/src/openpress/workbench/actions/ExportImageControl.tsx +0 -96
  126. package/template/core/src/openpress/workbench/actions/PageZoomControl.tsx +0 -182
  127. package/template/core/src/openpress/workbench/actions/SearchControl.tsx +0 -345
  128. package/template/core/src/openpress/workbench/actions/deploymentStatusModel.ts +0 -112
  129. package/template/core/src/openpress/workbench/actions/index.ts +0 -6
  130. package/template/core/src/openpress/workbench/actions/useDeploymentWorkbench.ts +0 -136
  131. package/template/core/src/openpress/workbench/dialog/WorkbenchDialog.tsx +0 -72
  132. package/template/core/src/openpress/workbench/dialog/index.ts +0 -1
  133. package/template/core/src/openpress/workbench/document/components/DocumentPanel.tsx +0 -127
  134. package/template/core/src/openpress/workbench/document/components/InlineSourceEditorLayer.tsx +0 -207
  135. package/template/core/src/openpress/workbench/document/components/ReaderStage.tsx +0 -9
  136. package/template/core/src/openpress/workbench/document/hooks/useDocumentWorkbenchModel.ts +0 -34
  137. package/template/core/src/openpress/workbench/document/hooks/useInlineDocumentEditor.ts +0 -525
  138. package/template/core/src/openpress/workbench/document/index.ts +0 -10
  139. package/template/core/src/openpress/workbench/index.ts +0 -2
  140. package/template/core/src/openpress/workbench/inspector/InlineInspectorLayer.tsx +0 -459
  141. package/template/core/src/openpress/workbench/inspector/index.ts +0 -5
  142. package/template/core/src/openpress/workbench/inspector/inlineCommentModel.ts +0 -125
  143. package/template/core/src/openpress/workbench/inspector/inspectorGeometryModel.ts +0 -160
  144. package/template/core/src/openpress/workbench/inspector/inspectorModel.ts +0 -408
  145. package/template/core/src/openpress/workbench/inspector/useInspectorComments.ts +0 -254
  146. package/template/core/src/openpress/workbench/mentions/MentionSuggestionList.tsx +0 -41
  147. package/template/core/src/openpress/workbench/mentions/index.ts +0 -2
  148. package/template/core/src/openpress/workbench/mentions/useComposerMentions.ts +0 -185
  149. package/template/core/src/openpress/workbench/panels/Panel.tsx +0 -1
  150. package/template/core/src/openpress/workbench/panels/PendingCommentsPanel.tsx +0 -80
  151. package/template/core/src/openpress/workbench/panels/WorkbenchControlPanel.tsx +0 -29
  152. package/template/core/src/openpress/workbench/panels/index.ts +0 -3
  153. package/template/core/src/openpress/workbench/project/ProjectEntryPanel.tsx +0 -525
  154. package/template/core/src/openpress/workbench/project/ProjectPreviewDialog.tsx +0 -35
  155. package/template/core/src/openpress/workbench/project/index.ts +0 -2
  156. package/template/core/src/openpress/workbench/project/projectPreviewTypes.ts +0 -11
  157. package/template/core/src/openpress/workbench/project/projectSourceModel.ts +0 -24
  158. package/template/core/src/openpress/workbench/shell/WorkbenchShell.tsx +0 -167
  159. package/template/core/src/openpress/workbench/shell/index.ts +0 -1
  160. package/template/core/src/openpress/workbench/workbenchFormatters.ts +0 -120
  161. package/template/core/src/openpress/workbench/workbenchTypes.ts +0 -35
  162. package/template/core/src/styles/openpress/app-shell.css +0 -251
  163. package/template/core/src/styles/openpress/media-workspace.css +0 -230
  164. package/template/core/src/styles/openpress/print-route.css +0 -184
  165. package/template/core/src/styles/openpress/project-preview-panel.css +0 -924
  166. package/template/core/src/styles/openpress/public-viewer.css +0 -688
  167. package/template/core/src/styles/openpress/reader-runtime.css +0 -989
  168. package/template/core/src/styles/openpress/responsive.css +0 -245
  169. package/template/core/src/styles/openpress/workbench-panels.css +0 -707
  170. package/template/core/src/styles/openpress/workbench.css +0 -1255
  171. package/template/core/src/styles/openpress/workspace-gallery.css +0 -300
  172. package/template/core/src/styles/openpress.css +0 -15
  173. package/template/core/src/vite-env.d.ts +0 -9
  174. package/template/core/tsconfig.json +0 -40
  175. package/template/core/vite.config.ts +0 -584
@@ -1,217 +0,0 @@
1
- // Layer 4 — Allocation.
2
- //
3
- // Per chain, fills MdxAreas with block IDs using the Phase 1 region allocator.
4
- // Returns:
5
- // - `allocation`: { [frameKey]: { [chainId]: blockIds[][] } } — areas per chain, area index → blockIds
6
- // - `hints`: { totalPagesPerChain: { [chainId]: number } } — fed back to <Sections>
7
- // - `warnings`: chain-overflowed, etc.
8
-
9
- import { allocateBlocksToRegions, estimateRegionsNeeded } from "../pagination/allocator.mjs";
10
-
11
- const SANITY_LIMIT = 200;
12
-
13
- /**
14
- * @param {object} opts
15
- * @param {Array<FrameInstance>} opts.frames Layer 2 frame structure.
16
- * @param {Array<MdxAreaMeasurement>} opts.mdxAreas Layer 3 MdxArea capacities.
17
- * @param {Array<BlockMeasurement>} opts.blockHeights Layer 3 block heights.
18
- * @param {Record<string, object>} opts.sources Resolved sources (for chain block lists).
19
- * @returns {AllocationResult}
20
- */
21
- export function allocateChains({ frames, mdxAreas, blockHeights, sources }) {
22
- // Group MdxAreas by chainId, sorted by (frame order, indexInFrame)
23
- const chainAreas = groupAreasByChain(frames, mdxAreas);
24
- // Group block heights by chainId
25
- const blockHeightsByChain = groupBlockHeights(blockHeights);
26
-
27
- const allocation = {};
28
- const warnings = [];
29
- const totalPagesPerChain = {};
30
- // Track per-chain how many extension iterations the caller (orchestrator)
31
- // should request. The actual *cloning* is done at the Press tree level
32
- // by feeding hints back to <Sections>; here we just report how many
33
- // frames each chain *should* have.
34
-
35
- for (const [chainId, chainSource] of iterateChains(sources)) {
36
- const areas = chainAreas.get(chainId) ?? [];
37
- const blocks = buildBlockStream(chainSource, blockHeightsByChain.get(chainId));
38
-
39
- const regions = areas.map((a) => ({
40
- id: `${a.frameKey}#${a.indexInFrame}`,
41
- capacity: a.capacity,
42
- pageIndex: 0, // not used here; we keep our own mapping
43
- columnIndex: a.indexInFrame,
44
- __frameKey: a.frameKey,
45
- __chainId: chainId,
46
- __overflow: a.overflow,
47
- }));
48
-
49
- if (regions.length === 0 || blocks.length === 0) {
50
- // No areas to fill, or no blocks to place.
51
- if (blocks.length > 0 && !chainId.startsWith("toc:")) {
52
- warnings.push({ code: "chain-has-no-area", chainId });
53
- }
54
- // Frames already correctly count to 0 for this chain.
55
- // (Or it's a static-source chain like the cover, which doesn't allocate.)
56
- // Skip.
57
- // If chain has blocks but no areas, that's an authoring error.
58
- const sourceFrameCount = frames.filter((f) => f.mdxAreas.some((a) => a.chainId === chainId)).length;
59
- totalPagesPerChain[chainId] = Math.max(1, sourceFrameCount);
60
- continue;
61
- }
62
-
63
- const { result, neededAreas } = allocateBlocksToFiniteRegions(blocks, regions);
64
- const lastOverflow = regions[regions.length - 1].__overflow;
65
- const sourceFramesForChain = uniqueFramesForChain(frames, chainId);
66
-
67
- if (neededAreas > regions.length) {
68
- // Overflow detected.
69
- if (lastOverflow === "error") {
70
- const remaining = blocks.slice(result.consumed).map((b) => b.id);
71
- throw new Error(
72
- `Chain "${chainId}" overflowed and the last MdxArea is overflow="error". ` +
73
- `Remaining block IDs: ${remaining.slice(0, 5).join(", ")}${remaining.length > 5 ? `, ... (${remaining.length} total)` : ""}.`,
74
- );
75
- }
76
- if (lastOverflow === "truncate") {
77
- warnings.push({
78
- code: "chain-overflowed",
79
- chainId,
80
- remainingBlocks: blocks.length - result.consumed,
81
- });
82
- // Don't grow totalPages; truncate at current capacity.
83
- totalPagesPerChain[chainId] = sourceFramesForChain;
84
- recordAllocation(allocation, result, regions);
85
- continue;
86
- }
87
- // overflow="extend" (default): scale frame count up.
88
- const areasPerFrame = Math.max(1, regions.length / Math.max(1, sourceFramesForChain));
89
- const extraAreasNeeded = neededAreas - regions.length;
90
- const extraFramesNeeded = Math.ceil(extraAreasNeeded / areasPerFrame);
91
- const newTotal = sourceFramesForChain + extraFramesNeeded;
92
- if (newTotal > SANITY_LIMIT) {
93
- throw new Error(
94
- `Chain "${chainId}" would require ${newTotal} frames after extension, exceeding the sanity limit of ${SANITY_LIMIT}. ` +
95
- `Check that block content fits within the MdxArea capacity.`,
96
- );
97
- }
98
- totalPagesPerChain[chainId] = newTotal;
99
- // Don't record allocation yet — orchestrator will re-render with more
100
- // frames and re-allocate.
101
- continue;
102
- }
103
-
104
- totalPagesPerChain[chainId] = sourceFramesForChain;
105
- recordAllocation(allocation, result, regions);
106
- }
107
-
108
- return {
109
- allocation,
110
- hints: { totalPagesPerChain },
111
- warnings,
112
- };
113
- }
114
-
115
- function allocateBlocksToFiniteRegions(blocks, regions) {
116
- const byRegionId = new Map(regions.map((region) => [region.id, region]));
117
- const result = allocateBlocksToRegions(blocks, finiteRegionStream(regions), {
118
- keepWithNext: shouldKeepWithNext,
119
- });
120
- const filled = result.regions.map((region) => ({
121
- region: byRegionId.get(region.regionId),
122
- blockIds: region.blockIds,
123
- })).filter((fill) => fill.region);
124
- const consumed = result.consumedCount;
125
- const remaining = blocks.slice(consumed);
126
- const extraNeeded = remaining.length > 0
127
- ? estimateRegionsNeeded(remaining, regions[regions.length - 1].capacity, {
128
- keepWithNext: shouldKeepWithNext,
129
- })
130
- : 0;
131
- return {
132
- result: { filled, consumed },
133
- neededAreas: filled.length + extraNeeded,
134
- };
135
- }
136
-
137
- function shouldKeepWithNext(block, nextBlock) {
138
- if (!nextBlock) return false;
139
- const name = String(block?.name ?? "");
140
- return /^h[1-6]$/.test(name) || name === "caption";
141
- }
142
-
143
- function finiteRegionStream(regions) {
144
- let index = 0;
145
- return {
146
- next() {
147
- return index < regions.length ? regions[index++] : null;
148
- },
149
- };
150
- }
151
-
152
- function recordAllocation(allocation, result, regions) {
153
- for (const fill of result.filled) {
154
- const frameKey = fill.region.__frameKey;
155
- const chainId = fill.region.__chainId;
156
- const areaIndex = fill.region.columnIndex;
157
- if (!allocation[frameKey]) allocation[frameKey] = {};
158
- if (!allocation[frameKey][chainId]) allocation[frameKey][chainId] = [];
159
- allocation[frameKey][chainId][areaIndex] = fill.blockIds;
160
- }
161
- }
162
-
163
- function groupAreasByChain(frames, mdxAreas) {
164
- // mdxAreas come from chromium in DOM order. We need to order by (frame
165
- // sequence position in Press tree, indexInFrame). Use frames[] order.
166
- const frameOrder = new Map();
167
- frames.forEach((f, idx) => frameOrder.set(f.frameKey, idx));
168
- const byChain = new Map();
169
- const sorted = [...mdxAreas].sort((a, b) => {
170
- const fa = frameOrder.get(a.frameKey) ?? Number.MAX_SAFE_INTEGER;
171
- const fb = frameOrder.get(b.frameKey) ?? Number.MAX_SAFE_INTEGER;
172
- if (fa !== fb) return fa - fb;
173
- return a.indexInFrame - b.indexInFrame;
174
- });
175
- for (const area of sorted) {
176
- if (!byChain.has(area.chainId)) byChain.set(area.chainId, []);
177
- byChain.get(area.chainId).push(area);
178
- }
179
- return byChain;
180
- }
181
-
182
- function groupBlockHeights(blockHeights) {
183
- const byChain = new Map();
184
- for (const block of blockHeights) {
185
- if (!byChain.has(block.chainId)) byChain.set(block.chainId, new Map());
186
- byChain.get(block.chainId).set(block.id, block.height);
187
- }
188
- return byChain;
189
- }
190
-
191
- function buildBlockStream(chainSource, heightMap) {
192
- if (!chainSource || !heightMap) return [];
193
- return chainSource
194
- .filter((block) => block.layout !== "attached")
195
- .map((block) => ({
196
- id: block.id,
197
- kind: block.kind,
198
- name: block.name,
199
- height: heightMap.get(block.id) ?? 0,
200
- }));
201
- }
202
-
203
- function* iterateChains(sources) {
204
- for (const source of Object.values(sources)) {
205
- for (const [chainId, blocks] of Object.entries(source.chains)) {
206
- yield [chainId, blocks];
207
- }
208
- }
209
- }
210
-
211
- function uniqueFramesForChain(frames, chainId) {
212
- const set = new Set();
213
- for (const f of frames) {
214
- if (f.mdxAreas.some((a) => a.chainId === chainId)) set.add(f.frameKey);
215
- }
216
- return Math.max(1, set.size);
217
- }
@@ -1,94 +0,0 @@
1
- // Layer 5 — Final Render.
2
- //
3
- // Given the allocation map (frameKey -> chainId -> areaIndex -> blockIds),
4
- // pre-compiles each MdxArea's block subset into React nodes, then renders
5
- // the Press tree one more time with `PressContext.allocation` populated.
6
- // The output HTML is parsed back into per-frame fragments for document.json.
7
-
8
- import React from "react";
9
- import { expandPressTree } from "./press-tree.mjs";
10
- import { compileChainBlocks } from "../sources/mdx-resolver.mjs";
11
-
12
- /**
13
- * @returns {{ frames: Array<{ frameKey, role, chrome, html, blockIds, mdxAreas }>, html: string }}
14
- */
15
- export async function renderFinalPress({
16
- Press,
17
- PressContext,
18
- sources,
19
- hints,
20
- toc,
21
- allocation: blockAllocation, // chainId blockId allocator output: { [frameKey]: { [chainId]: blockIds[][] } }
22
- renderRegistry,
23
- }) {
24
- // 1. Compile React nodes per (frameKey, chainId, areaIndex)
25
- const reactAllocation = await buildReactAllocation(blockAllocation, sources, renderRegistry, toc);
26
-
27
- // 2. Render Press tree with allocation in context
28
- const { html, frames } = expandPressTree({
29
- Press,
30
- PressContext,
31
- sources,
32
- hints,
33
- toc,
34
- allocation: reactAllocation,
35
- });
36
-
37
- // 3. Annotate frame instances with blockIds (for document.json)
38
- const framesWithBlocks = frames.map((frame) => {
39
- const frameBlocks = blockAllocation[frame.frameKey] ?? {};
40
- const blockIds = [];
41
- const mdxAreas = frame.mdxAreas.map((area) => {
42
- const ids = frameBlocks[area.chainId]?.[area.indexInFrame] ?? [];
43
- blockIds.push(...ids);
44
- return {
45
- chainId: area.chainId,
46
- indexInFrame: area.indexInFrame,
47
- blockIds: ids,
48
- };
49
- });
50
- return {
51
- frameKey: frame.frameKey,
52
- role: frame.role,
53
- chrome: frame.chrome,
54
- html: frame.html,
55
- blockIds,
56
- mdxAreas,
57
- };
58
- });
59
-
60
- return { frames: framesWithBlocks, html };
61
- }
62
-
63
- async function buildReactAllocation(blockAllocation, sources, renderRegistry, toc) {
64
- /** @type {Record<string, Record<string, React.ReactNode[]>>} */
65
- const out = {};
66
- const sourceOfChain = new Map();
67
- for (const source of Object.values(sources)) {
68
- for (const chainId of Object.keys(source.chains)) {
69
- sourceOfChain.set(chainId, source.id);
70
- }
71
- }
72
-
73
- for (const [frameKey, chainMap] of Object.entries(blockAllocation)) {
74
- out[frameKey] = {};
75
- for (const [chainId, areaArr] of Object.entries(chainMap)) {
76
- const nodesByArea = [];
77
- for (let areaIndex = 0; areaIndex < areaArr.length; areaIndex++) {
78
- const blockIds = areaArr[areaIndex] ?? [];
79
- if (blockIds.length === 0) {
80
- nodesByArea[areaIndex] = null;
81
- continue;
82
- }
83
- const sourceId = sourceOfChain.get(chainId);
84
- const renderData = renderRegistry.get(sourceId);
85
- const compiled = await compileChainBlocks({ renderData, chainId, blockIds, toc });
86
- nodesByArea[areaIndex] = compiled.map(({ Content }, i) =>
87
- React.createElement(Content, { key: `${areaIndex}-${i}` }),
88
- );
89
- }
90
- out[frameKey][chainId] = nodesByArea;
91
- }
92
- }
93
- return out;
94
- }
@@ -1,306 +0,0 @@
1
- // Layer 3 — Frame Measurement.
2
- //
3
- // Renders the Press tree (from Layer 2) plus a hidden "blocks zone" that
4
- // contains every chain's full content, sends the combined document to
5
- // Chromium, then queries the DOM for:
6
- // - MdxArea capacities (per frameKey + chainId + indexInFrame)
7
- // - Block heights (per chainId + blockId)
8
- //
9
- // The blocks zone uses the same `.page-body` CSS context as the live
10
- // frames so widths and font metrics match.
11
-
12
- import fs from "node:fs/promises";
13
- import path from "node:path";
14
- import React from "react";
15
- import { renderToStaticMarkup } from "react-dom/server";
16
- import { chromium } from "playwright";
17
- import { createCaptionNumberingState, numberCaptionsInHtml } from "../caption-numbering.mjs";
18
- import { compileChainBlocks } from "../sources/mdx-resolver.mjs";
19
-
20
- const DEFAULT_VIEWPORT = { width: 794, height: 1123 };
21
-
22
- // Safety inset applied to measured MdxArea capacities. A small reserve keeps
23
- // content that visually fits "exactly" from clipping due to anti-aliasing,
24
- // line breaks, and rounding.
25
- const CAPACITY_SAFETY_RATIO = 0.04;
26
- const CAPACITY_SAFETY_MAX_PX = 96;
27
-
28
- /**
29
- * @param {object} opts
30
- * @param {string} opts.pressHtml Rendered Press tree HTML (Layer 2).
31
- * @param {Record<string, object>} opts.sources Resolved sources keyed by sourceId.
32
- * @param {Map<string, object>} opts.renderRegistry Internal render data per sourceId.
33
- * @param {string} opts.css Combined CSS for measurement context.
34
- * @param {string=} opts.baseHref Base URL for relative media paths in MDX.
35
- * @param {string=} opts.mediaDir Local media dir for inlining /openpress/media/* assets.
36
- * @param {object=} opts.captionNumbering Caption label formatter options.
37
- * @param {{width:number,height:number}=} opts.viewport
38
- */
39
- export async function measureFrames({
40
- pressHtml,
41
- sources,
42
- renderRegistry,
43
- css = "",
44
- baseHref = "",
45
- mediaDir = "",
46
- captionNumbering = {},
47
- viewport = DEFAULT_VIEWPORT,
48
- }) {
49
- const chainContent = await buildChainContent(sources, renderRegistry, captionNumbering);
50
- const html = await buildMeasurementDocument({ pressHtml, chainContent, css, baseHref, mediaDir });
51
- return runChromiumMeasurement(html, viewport);
52
- }
53
-
54
- async function buildChainContent(sources, renderRegistry, captionNumbering) {
55
- const out = new Map();
56
- const captionState = createCaptionNumberingState();
57
- for (const source of Object.values(sources)) {
58
- for (const [chainId, blocks] of Object.entries(source.chains)) {
59
- const blockIds = blocks.map((b) => b.id);
60
- const renderData = renderRegistry.get(source.id);
61
- const compiled = await compileChainBlocks({ renderData, chainId, blockIds });
62
- const html = compiled
63
- .map(({ Content }, idx) => renderToStaticMarkup(React.createElement(Content, { key: idx })))
64
- .join("");
65
- out.set(
66
- chainId,
67
- chainId.startsWith("toc:") ? html : numberCaptionsInHtml(html, captionNumbering, captionState),
68
- );
69
- }
70
- }
71
- return out;
72
- }
73
-
74
- async function buildMeasurementDocument({ pressHtml, chainContent, css, baseHref, mediaDir }) {
75
- const normalizedPressHtml = await inlineMeasurementMediaUrls(pressHtml, mediaDir);
76
- const blocksZoneParts = [];
77
- for (const [chainId, contentHtml] of chainContent.entries()) {
78
- const normalizedContentHtml = await inlineMeasurementMediaUrls(contentHtml, mediaDir);
79
- const containerTag = chainId.startsWith("toc:") ? "ol" : "div";
80
- const containerClass = chainId.startsWith("toc:") ? ' class="toc-list"' : "";
81
- blocksZoneParts.push(`
82
- <section class="reader-page reader-page--content" data-openpress-measure-frame="${escapeAttr(chainId)}" data-page-kind="content">
83
- <div class="page-frame">
84
- <main class="page-body">
85
- <${containerTag}${containerClass} data-block-measurement-chain="${escapeAttr(chainId)}" style="overflow: visible;">
86
- ${normalizedContentHtml}
87
- </${containerTag}>
88
- </main>
89
- </div>
90
- </section>
91
- `);
92
- }
93
- const blocksZone = blocksZoneParts.join("\n");
94
-
95
- return `<!doctype html>
96
- <html>
97
- <head>
98
- <meta charset="utf-8">
99
- ${baseHref ? `<base href="${escapeAttr(baseHref)}">` : ""}
100
- <style>
101
- body { margin: 0; }
102
- ${css}
103
- /* Reader-page is hidden by default in the workspace theme (only the
104
- is-active page is shown). Override visibility in measurement zones
105
- but do not touch the page-frame display, because the theme uses
106
- CSS grid with grid-template-rows reserving page-header and
107
- page-footer space; we must preserve that layout so MdxArea
108
- inherits the real page-body cell height. */
109
- [data-openpress-frames-zone] .reader-page,
110
- [data-openpress-blocks-zone] .reader-page {
111
- display: block !important;
112
- }
113
- /* MdxArea fills its grid/flex parent so we measure the layout slot,
114
- not the inserted content. */
115
- [data-openpress-frames-zone] [data-openpress-mdx-area="true"] {
116
- display: block;
117
- box-sizing: border-box;
118
- min-height: 0;
119
- align-self: stretch;
120
- overflow: visible;
121
- }
122
- [data-openpress-frames-zone] { position: relative; }
123
- [data-openpress-blocks-zone] { position: fixed; left: -200000px; top: 0; visibility: hidden; pointer-events: none; }
124
- </style>
125
- </head>
126
- <body>
127
- <div data-openpress-frames-zone>${normalizedPressHtml}</div>
128
- <div data-openpress-blocks-zone>${blocksZone}</div>
129
- </body>
130
- </html>`;
131
- }
132
-
133
- async function runChromiumMeasurement(html, viewport) {
134
- const browser = await chromium.launch();
135
- try {
136
- const page = await browser.newPage({ viewport });
137
- await page.setContent(html, { waitUntil: "load" });
138
- // Match the print-ready settle: fonts first (font metrics affect image
139
- // alt-text fallback boxes), then await every image's `complete` AND
140
- // `decode()` so intrinsic sizes are committed before layout, then two
141
- // animation frames so the chromium layout pass observes the final box
142
- // model. Without this, `getBoundingClientRect()` on figures that hold
143
- // images can race the decode and return collapsed heights, causing the
144
- // allocator to pack too many blocks per page.
145
- await page.evaluate(async () => {
146
- if (document.fonts?.ready) await document.fonts.ready;
147
- await Promise.all(Array.from(document.images).map(async (img) => {
148
- if (!img.complete) {
149
- await new Promise((resolve) => {
150
- const settle = () => {
151
- img.removeEventListener("load", settle);
152
- img.removeEventListener("error", settle);
153
- resolve(undefined);
154
- };
155
- img.addEventListener("load", settle, { once: true });
156
- img.addEventListener("error", settle, { once: true });
157
- });
158
- }
159
- await img.decode?.().catch(() => undefined);
160
- }));
161
- await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
162
- });
163
-
164
- const mdxAreas = await page.evaluate((safety) => {
165
- const zone = document.querySelector("[data-openpress-frames-zone]");
166
- if (!zone) return [];
167
- const areas = Array.from(zone.querySelectorAll("[data-openpress-mdx-area]"));
168
- const out = [];
169
- for (const el of areas) {
170
- const frame = el.closest("[data-openpress-frame-key]");
171
- if (!frame) continue;
172
- const frameKey = frame.getAttribute("data-openpress-frame-key") || "";
173
- const chainId = el.getAttribute("data-openpress-mdx-area-chain") || "";
174
- const overflow = el.getAttribute("data-openpress-mdx-area-overflow") || "extend";
175
- // Index within this frame's same-chain areas
176
- const sameInFrame = Array.from(frame.querySelectorAll(`[data-openpress-mdx-area][data-openpress-mdx-area-chain="${chainId}"]`));
177
- const indexInFrame = sameInFrame.indexOf(el);
178
- const rect = measuredMdxAreaRect(el);
179
- const inset = Math.min(safety.maxPx, Math.max(0, rect.height * safety.ratio));
180
- const capacity = Math.max(1, rect.height - inset);
181
- out.push({
182
- frameKey,
183
- chainId,
184
- overflow,
185
- indexInFrame,
186
- capacity,
187
- rawHeight: rect.height,
188
- width: rect.width,
189
- });
190
- }
191
- return out;
192
-
193
- function measuredMdxAreaRect(el) {
194
- const rect = el.getBoundingClientRect();
195
- if (rect.height > 1) return rect;
196
- const candidates = [
197
- el.parentElement,
198
- el.closest(".page-body"),
199
- el.closest("[data-openpress-frame-key]")?.querySelector(".page-body"),
200
- ];
201
- for (const candidate of candidates) {
202
- if (!candidate) continue;
203
- const fallback = candidate.getBoundingClientRect();
204
- if (fallback.height > rect.height) {
205
- return {
206
- height: fallback.height,
207
- width: rect.width > 0 ? rect.width : fallback.width,
208
- };
209
- }
210
- }
211
- return rect;
212
- }
213
- }, { ratio: CAPACITY_SAFETY_RATIO, maxPx: CAPACITY_SAFETY_MAX_PX });
214
-
215
- const blockHeights = await page.evaluate(() => {
216
- const zone = document.querySelector("[data-openpress-blocks-zone]");
217
- if (!zone) return [];
218
- const out = [];
219
- for (const chain of zone.querySelectorAll("[data-block-measurement-chain]")) {
220
- const chainId = chain.getAttribute("data-block-measurement-chain") ?? "";
221
- const parentTop = chain.parentElement?.getBoundingClientRect().top ?? chain.getBoundingClientRect().top;
222
- let previousBottom = parentTop;
223
- for (const el of Array.from(chain.querySelectorAll("[data-openpress-block-id]"))) {
224
- if (el.tagName.toLowerCase() === "caption") continue;
225
- if (el.getAttribute("data-openpress-block-layout") === "attached") continue;
226
- // Cells inherit their row's block-id so the inspector can resolve a
227
- // SourceBlock when clicking inside a <td>. Skip them here so the
228
- // row's measured height isn't overwritten by each cell.
229
- if (el.getAttribute("data-openpress-inherited-block-id") === "true") continue;
230
- const rect = el.getBoundingClientRect();
231
- out.push({
232
- id: el.getAttribute("data-openpress-block-id"),
233
- height: Math.max(rect.height, rect.bottom - previousBottom),
234
- chainId,
235
- });
236
- previousBottom = Math.max(previousBottom, rect.bottom);
237
- }
238
- }
239
- return out;
240
- });
241
-
242
- return { mdxAreas, blockHeights };
243
- } finally {
244
- await browser.close();
245
- }
246
- }
247
-
248
- function escapeAttr(value) {
249
- return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
250
- }
251
-
252
- async function inlineMeasurementMediaUrls(html, mediaDir) {
253
- if (!mediaDir || !html) return html;
254
- let out = String(html);
255
- const matches = new Set();
256
- for (const match of out.matchAll(/\bsrc=(['"])([^\1]*?)\1/g)) {
257
- const src = match[2];
258
- if (!src) continue;
259
- if (src.startsWith('/openpress/media/')) {
260
- matches.add(src.slice('/openpress/media/'.length));
261
- continue;
262
- }
263
- if (src.startsWith('media/')) {
264
- matches.add(src.slice('media/'.length));
265
- continue;
266
- }
267
- if (src.startsWith('./media/')) {
268
- matches.add(src.slice('./media/'.length));
269
- }
270
- }
271
- for (const rawName of matches) {
272
- const dataUrl = await mediaDataUrl(mediaDir, rawName);
273
- if (!dataUrl) continue;
274
- out = out.replaceAll(`/openpress/media/${rawName}`, dataUrl);
275
- out = out.replaceAll(`media/${rawName}`, dataUrl);
276
- out = out.replaceAll(`./media/${rawName}`, dataUrl);
277
- }
278
- return out;
279
- }
280
-
281
- async function mediaDataUrl(mediaDir, rawName) {
282
- let fileName;
283
- try {
284
- fileName = decodeURIComponent(String(rawName));
285
- } catch {
286
- fileName = String(rawName);
287
- }
288
- if (!fileName || fileName !== path.basename(fileName)) return null;
289
- const filePath = path.join(mediaDir, fileName);
290
- let bytes;
291
- try {
292
- bytes = await fs.readFile(filePath);
293
- } catch {
294
- return null;
295
- }
296
- return `data:${mediaMimeType(fileName)};base64,${bytes.toString("base64")}`;
297
- }
298
-
299
- function mediaMimeType(fileName) {
300
- const ext = path.extname(fileName).toLowerCase();
301
- if (ext === ".svg") return "image/svg+xml";
302
- if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
303
- if (ext === ".gif") return "image/gif";
304
- if (ext === ".webp") return "image/webp";
305
- return "image/png";
306
- }