@open-press/core 0.5.0 → 0.7.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 +9 -5
- package/engine/cli.mjs +2 -5
- package/engine/commands/_shared.mjs +4 -4
- package/engine/commands/deploy.mjs +1 -1
- package/engine/commands/inspect.mjs +3 -3
- package/engine/commands/replace.mjs +1 -1
- package/engine/commands/search.mjs +1 -1
- package/engine/commands/validate.mjs +2 -2
- package/engine/document-export.mjs +1 -1
- package/engine/{chrome-pdf.mjs → output/chrome-pdf.mjs} +1 -2
- package/engine/{deploy-sync.mjs → output/deploy-sync.mjs} +2 -2
- package/engine/{fonts.mjs → output/fonts.mjs} +1 -1
- package/engine/{public-assets.mjs → output/public-assets.mjs} +2 -2
- package/engine/{static-server.mjs → output/static-server.mjs} +2 -2
- package/engine/react/caption-numbering.mjs +73 -0
- package/engine/react/comment-marker.mjs +54 -10
- package/engine/react/document-entry.mjs +124 -64
- package/engine/react/document-export.mjs +252 -311
- package/engine/react/mdx-compile.mjs +123 -3
- package/engine/react/measurement-css.mjs +3 -3
- package/engine/react/pagination/allocator.mjs +122 -0
- package/engine/react/pagination/regions.mjs +81 -0
- package/engine/react/pagination.mjs +9 -121
- package/engine/react/pipeline/allocate.mjs +248 -0
- package/engine/react/pipeline/final-render.mjs +94 -0
- package/engine/react/pipeline/frame-measurement.mjs +271 -0
- package/engine/react/pipeline/press-tree.mjs +135 -0
- package/engine/react/project-asset-endpoint.mjs +2 -2
- package/engine/react/{chapter-css.mjs → section-css.mjs} +12 -9
- package/engine/react/sources/heading-numbering.mjs +132 -0
- package/engine/react/sources/mdx-resolver.mjs +441 -0
- package/engine/react/{workspace-discovery.mjs → style-discovery.mjs} +29 -40
- package/engine/{config.mjs → runtime/config.mjs} +15 -0
- package/engine/{file-utils.mjs → runtime/file-utils.mjs} +1 -1
- package/engine/{inspection.mjs → runtime/inspection.mjs} +3 -4
- package/engine/{source-text-tools.mjs → runtime/source-text-tools.mjs} +24 -7
- package/engine/runtime/source-workspace.mjs +186 -0
- package/engine/{validation.mjs → runtime/validation.mjs} +19 -17
- package/package.json +5 -2
- package/src/openpress/anchorMap.ts +27 -0
- package/src/openpress/core/Frame.tsx +80 -0
- package/src/openpress/core/FrameContext.tsx +19 -0
- package/src/openpress/core/MdxArea.tsx +35 -0
- package/src/openpress/core/Press.tsx +34 -0
- package/src/openpress/core/index.tsx +34 -15
- package/src/openpress/core/primitives.tsx +23 -0
- package/src/openpress/core/types.ts +131 -19
- package/src/openpress/core/useSource.ts +28 -0
- package/src/openpress/manuscript/index.tsx +196 -0
- package/src/openpress/mdx/index.ts +88 -0
- package/src/openpress/numbering/index.ts +294 -0
- package/src/openpress/publicPage.tsx +4 -186
- package/src/openpress/reactDocumentMetadata.ts +2 -16
- package/src/openpress/types.ts +0 -16
- package/src/openpress/workbench.tsx +2 -36
- package/src/styles/openpress/responsive.css +0 -14
- package/tsconfig.json +4 -1
- package/vite.config.ts +10 -3
- package/engine/commands/migrate-to-react.mjs +0 -27
- package/engine/page-renderer.mjs +0 -217
- package/engine/react/migrate-to-react.mjs +0 -355
- package/engine/source-workspace.mjs +0 -76
- package/src/openpress/core/basePages.tsx +0 -87
- package/src/openpress/pagination.ts +0 -845
- /package/engine/{chrome-pdf.d.mts → output/chrome-pdf.d.mts} +0 -0
- /package/engine/{katex-assets.mjs → output/katex-assets.mjs} +0 -0
- /package/engine/{page-block.mjs → output/page-block.mjs} +0 -0
- /package/engine/{pdf-media.mjs → output/pdf-media.mjs} +0 -0
- /package/engine/{config.d.mts → runtime/config.d.mts} +0 -0
- /package/engine/{issue-report.mjs → runtime/issue-report.mjs} +0 -0
|
@@ -0,0 +1,248 @@
|
|
|
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
|
+
const SANITY_LIMIT = 200;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {object} opts
|
|
13
|
+
* @param {Array<FrameInstance>} opts.frames Layer 2 frame structure.
|
|
14
|
+
* @param {Array<MdxAreaMeasurement>} opts.mdxAreas Layer 3 MdxArea capacities.
|
|
15
|
+
* @param {Array<BlockMeasurement>} opts.blockHeights Layer 3 block heights.
|
|
16
|
+
* @param {Record<string, object>} opts.sources Resolved sources (for chain block lists).
|
|
17
|
+
* @returns {AllocationResult}
|
|
18
|
+
*/
|
|
19
|
+
export function allocateChains({ frames, mdxAreas, blockHeights, sources }) {
|
|
20
|
+
// Group MdxAreas by chainId, sorted by (frame order, indexInFrame)
|
|
21
|
+
const chainAreas = groupAreasByChain(frames, mdxAreas);
|
|
22
|
+
// Group block heights by chainId
|
|
23
|
+
const blockHeightsByChain = groupBlockHeights(blockHeights);
|
|
24
|
+
|
|
25
|
+
const allocation = {};
|
|
26
|
+
const warnings = [];
|
|
27
|
+
const totalPagesPerChain = {};
|
|
28
|
+
// Track per-chain how many extension iterations the caller (orchestrator)
|
|
29
|
+
// should request. The actual *cloning* is done at the Press tree level
|
|
30
|
+
// by feeding hints back to <Sections>; here we just report how many
|
|
31
|
+
// frames each chain *should* have.
|
|
32
|
+
|
|
33
|
+
for (const [chainId, chainSource] of iterateChains(sources)) {
|
|
34
|
+
const areas = chainAreas.get(chainId) ?? [];
|
|
35
|
+
const blocks = buildBlockStream(chainSource, blockHeightsByChain.get(chainId));
|
|
36
|
+
|
|
37
|
+
const regions = areas.map((a) => ({
|
|
38
|
+
id: `${a.frameKey}#${a.indexInFrame}`,
|
|
39
|
+
capacity: a.capacity,
|
|
40
|
+
pageIndex: 0, // not used here; we keep our own mapping
|
|
41
|
+
columnIndex: a.indexInFrame,
|
|
42
|
+
__frameKey: a.frameKey,
|
|
43
|
+
__chainId: chainId,
|
|
44
|
+
__overflow: a.overflow,
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
if (regions.length === 0 || blocks.length === 0) {
|
|
48
|
+
// No areas to fill, or no blocks to place.
|
|
49
|
+
if (blocks.length > 0 && !chainId.startsWith("toc:")) {
|
|
50
|
+
warnings.push({ code: "chain-has-no-area", chainId });
|
|
51
|
+
}
|
|
52
|
+
// Frames already correctly count to 0 for this chain.
|
|
53
|
+
// (Or it's a static-source chain like the cover, which doesn't allocate.)
|
|
54
|
+
// Skip.
|
|
55
|
+
// If chain has blocks but no areas, that's an authoring error.
|
|
56
|
+
const sourceFrameCount = frames.filter((f) => f.mdxAreas.some((a) => a.chainId === chainId)).length;
|
|
57
|
+
totalPagesPerChain[chainId] = Math.max(1, sourceFrameCount);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const { result, neededAreas } = greedyAllocate(blocks, regions);
|
|
62
|
+
const lastOverflow = regions[regions.length - 1].__overflow;
|
|
63
|
+
const sourceFramesForChain = uniqueFramesForChain(frames, chainId);
|
|
64
|
+
|
|
65
|
+
if (neededAreas > regions.length) {
|
|
66
|
+
// Overflow detected.
|
|
67
|
+
if (lastOverflow === "error") {
|
|
68
|
+
const remaining = blocks.slice(result.consumed).map((b) => b.id);
|
|
69
|
+
throw new Error(
|
|
70
|
+
`Chain "${chainId}" overflowed and the last MdxArea is overflow="error". ` +
|
|
71
|
+
`Remaining block IDs: ${remaining.slice(0, 5).join(", ")}${remaining.length > 5 ? `, ... (${remaining.length} total)` : ""}.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (lastOverflow === "truncate") {
|
|
75
|
+
warnings.push({
|
|
76
|
+
code: "chain-overflowed",
|
|
77
|
+
chainId,
|
|
78
|
+
remainingBlocks: blocks.length - result.consumed,
|
|
79
|
+
});
|
|
80
|
+
// Don't grow totalPages; truncate at current capacity.
|
|
81
|
+
totalPagesPerChain[chainId] = sourceFramesForChain;
|
|
82
|
+
recordAllocation(allocation, result, regions);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// overflow="extend" (default): scale frame count up.
|
|
86
|
+
const areasPerFrame = Math.max(1, regions.length / Math.max(1, sourceFramesForChain));
|
|
87
|
+
const extraAreasNeeded = neededAreas - regions.length;
|
|
88
|
+
const extraFramesNeeded = Math.ceil(extraAreasNeeded / areasPerFrame);
|
|
89
|
+
const newTotal = sourceFramesForChain + extraFramesNeeded;
|
|
90
|
+
if (newTotal > SANITY_LIMIT) {
|
|
91
|
+
throw new Error(
|
|
92
|
+
`Chain "${chainId}" would require ${newTotal} frames after extension, exceeding the sanity limit of ${SANITY_LIMIT}. ` +
|
|
93
|
+
`Check that block content fits within the MdxArea capacity.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
totalPagesPerChain[chainId] = newTotal;
|
|
97
|
+
// Don't record allocation yet — orchestrator will re-render with more
|
|
98
|
+
// frames and re-allocate.
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
totalPagesPerChain[chainId] = sourceFramesForChain;
|
|
103
|
+
recordAllocation(allocation, result, regions);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
allocation,
|
|
108
|
+
hints: { totalPagesPerChain },
|
|
109
|
+
warnings,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function greedyAllocate(blocks, regions) {
|
|
114
|
+
const filled = [];
|
|
115
|
+
let regionIndex = 0;
|
|
116
|
+
let currentBlockIds = [];
|
|
117
|
+
let currentHeight = 0;
|
|
118
|
+
let consumed = 0;
|
|
119
|
+
const flush = () => {
|
|
120
|
+
if (currentBlockIds.length === 0) return;
|
|
121
|
+
filled.push({
|
|
122
|
+
region: regions[regionIndex],
|
|
123
|
+
blockIds: currentBlockIds,
|
|
124
|
+
});
|
|
125
|
+
currentBlockIds = [];
|
|
126
|
+
currentHeight = 0;
|
|
127
|
+
};
|
|
128
|
+
for (let blockIndex = 0; blockIndex < blocks.length; blockIndex += 1) {
|
|
129
|
+
const block = blocks[blockIndex];
|
|
130
|
+
while (regionIndex < regions.length) {
|
|
131
|
+
const region = regions[regionIndex];
|
|
132
|
+
const nextBlock = blocks[blockIndex + 1];
|
|
133
|
+
const keepWithNextHeight = shouldKeepWithNext(block, nextBlock) ? block.height + nextBlock.height : 0;
|
|
134
|
+
if (
|
|
135
|
+
currentBlockIds.length > 0 &&
|
|
136
|
+
keepWithNextHeight > 0 &&
|
|
137
|
+
currentHeight + keepWithNextHeight > region.capacity
|
|
138
|
+
) {
|
|
139
|
+
flush();
|
|
140
|
+
regionIndex += 1;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (currentBlockIds.length === 0 || currentHeight + block.height <= region.capacity) {
|
|
144
|
+
currentBlockIds.push(block.id);
|
|
145
|
+
currentHeight += block.height;
|
|
146
|
+
consumed += 1;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
// Doesn't fit — flush current region and advance
|
|
150
|
+
flush();
|
|
151
|
+
regionIndex += 1;
|
|
152
|
+
}
|
|
153
|
+
if (regionIndex >= regions.length) break;
|
|
154
|
+
}
|
|
155
|
+
flush();
|
|
156
|
+
// neededAreas = total regions consumed if we had unlimited supply
|
|
157
|
+
// For overflow detection we estimate: if consumed < blocks.length, we need more areas.
|
|
158
|
+
let neededAreas = filled.length;
|
|
159
|
+
if (consumed < blocks.length) {
|
|
160
|
+
// Estimate how many more areas needed
|
|
161
|
+
const lastCap = regions[regions.length - 1].capacity;
|
|
162
|
+
const remainingBlocks = blocks.slice(consumed);
|
|
163
|
+
let h = 0;
|
|
164
|
+
let extra = 0;
|
|
165
|
+
let inExtra = false;
|
|
166
|
+
for (const b of remainingBlocks) {
|
|
167
|
+
if (!inExtra || h + b.height > lastCap) {
|
|
168
|
+
extra += 1;
|
|
169
|
+
h = b.height;
|
|
170
|
+
inExtra = true;
|
|
171
|
+
} else {
|
|
172
|
+
h += b.height;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
neededAreas += extra;
|
|
176
|
+
}
|
|
177
|
+
return { result: { filled, consumed }, neededAreas };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function shouldKeepWithNext(block, nextBlock) {
|
|
181
|
+
if (!nextBlock) return false;
|
|
182
|
+
return /^h[1-6]$/.test(String(block?.name ?? ""));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function recordAllocation(allocation, result, regions) {
|
|
186
|
+
for (const fill of result.filled) {
|
|
187
|
+
const frameKey = fill.region.__frameKey;
|
|
188
|
+
const chainId = fill.region.__chainId;
|
|
189
|
+
const areaIndex = fill.region.columnIndex;
|
|
190
|
+
if (!allocation[frameKey]) allocation[frameKey] = {};
|
|
191
|
+
if (!allocation[frameKey][chainId]) allocation[frameKey][chainId] = [];
|
|
192
|
+
allocation[frameKey][chainId][areaIndex] = fill.blockIds;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function groupAreasByChain(frames, mdxAreas) {
|
|
197
|
+
// mdxAreas come from chromium in DOM order. We need to order by (frame
|
|
198
|
+
// sequence position in Press tree, indexInFrame). Use frames[] order.
|
|
199
|
+
const frameOrder = new Map();
|
|
200
|
+
frames.forEach((f, idx) => frameOrder.set(f.frameKey, idx));
|
|
201
|
+
const byChain = new Map();
|
|
202
|
+
const sorted = [...mdxAreas].sort((a, b) => {
|
|
203
|
+
const fa = frameOrder.get(a.frameKey) ?? Number.MAX_SAFE_INTEGER;
|
|
204
|
+
const fb = frameOrder.get(b.frameKey) ?? Number.MAX_SAFE_INTEGER;
|
|
205
|
+
if (fa !== fb) return fa - fb;
|
|
206
|
+
return a.indexInFrame - b.indexInFrame;
|
|
207
|
+
});
|
|
208
|
+
for (const area of sorted) {
|
|
209
|
+
if (!byChain.has(area.chainId)) byChain.set(area.chainId, []);
|
|
210
|
+
byChain.get(area.chainId).push(area);
|
|
211
|
+
}
|
|
212
|
+
return byChain;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function groupBlockHeights(blockHeights) {
|
|
216
|
+
const byChain = new Map();
|
|
217
|
+
for (const block of blockHeights) {
|
|
218
|
+
if (!byChain.has(block.chainId)) byChain.set(block.chainId, new Map());
|
|
219
|
+
byChain.get(block.chainId).set(block.id, block.height);
|
|
220
|
+
}
|
|
221
|
+
return byChain;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function buildBlockStream(chainSource, heightMap) {
|
|
225
|
+
if (!chainSource || !heightMap) return [];
|
|
226
|
+
return chainSource.map((block) => ({
|
|
227
|
+
id: block.id,
|
|
228
|
+
kind: block.kind,
|
|
229
|
+
name: block.name,
|
|
230
|
+
height: heightMap.get(block.id) ?? 0,
|
|
231
|
+
}));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function* iterateChains(sources) {
|
|
235
|
+
for (const source of Object.values(sources)) {
|
|
236
|
+
for (const [chainId, blocks] of Object.entries(source.chains)) {
|
|
237
|
+
yield [chainId, blocks];
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function uniqueFramesForChain(frames, chainId) {
|
|
243
|
+
const set = new Set();
|
|
244
|
+
for (const f of frames) {
|
|
245
|
+
if (f.mdxAreas.some((a) => a.chainId === chainId)) set.add(f.frameKey);
|
|
246
|
+
}
|
|
247
|
+
return Math.max(1, set.size);
|
|
248
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
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
|
+
await page.evaluate(async () => {
|
|
139
|
+
await Promise.all(Array.from(document.images).map((img) => {
|
|
140
|
+
if (img.complete) return Promise.resolve();
|
|
141
|
+
return new Promise((resolve) => {
|
|
142
|
+
img.addEventListener("load", resolve, { once: true });
|
|
143
|
+
img.addEventListener("error", resolve, { once: true });
|
|
144
|
+
});
|
|
145
|
+
}));
|
|
146
|
+
if (document.fonts?.ready) await document.fonts.ready;
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
const mdxAreas = await page.evaluate((safety) => {
|
|
150
|
+
const zone = document.querySelector("[data-openpress-frames-zone]");
|
|
151
|
+
if (!zone) return [];
|
|
152
|
+
const areas = Array.from(zone.querySelectorAll("[data-openpress-mdx-area]"));
|
|
153
|
+
const out = [];
|
|
154
|
+
for (const el of areas) {
|
|
155
|
+
const frame = el.closest("[data-openpress-frame-key]");
|
|
156
|
+
if (!frame) continue;
|
|
157
|
+
const frameKey = frame.getAttribute("data-openpress-frame-key") || "";
|
|
158
|
+
const chainId = el.getAttribute("data-openpress-mdx-area-chain") || "";
|
|
159
|
+
const overflow = el.getAttribute("data-openpress-mdx-area-overflow") || "extend";
|
|
160
|
+
// Index within this frame's same-chain areas
|
|
161
|
+
const sameInFrame = Array.from(frame.querySelectorAll(`[data-openpress-mdx-area][data-openpress-mdx-area-chain="${chainId}"]`));
|
|
162
|
+
const indexInFrame = sameInFrame.indexOf(el);
|
|
163
|
+
const rect = measuredMdxAreaRect(el);
|
|
164
|
+
const inset = Math.min(safety.maxPx, Math.max(0, rect.height * safety.ratio));
|
|
165
|
+
const capacity = Math.max(1, rect.height - inset);
|
|
166
|
+
out.push({
|
|
167
|
+
frameKey,
|
|
168
|
+
chainId,
|
|
169
|
+
overflow,
|
|
170
|
+
indexInFrame,
|
|
171
|
+
capacity,
|
|
172
|
+
rawHeight: rect.height,
|
|
173
|
+
width: rect.width,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
|
|
178
|
+
function measuredMdxAreaRect(el) {
|
|
179
|
+
const rect = el.getBoundingClientRect();
|
|
180
|
+
if (rect.height > 1) return rect;
|
|
181
|
+
const candidates = [
|
|
182
|
+
el.parentElement,
|
|
183
|
+
el.closest(".page-body"),
|
|
184
|
+
el.closest("[data-openpress-frame-key]")?.querySelector(".page-body"),
|
|
185
|
+
];
|
|
186
|
+
for (const candidate of candidates) {
|
|
187
|
+
if (!candidate) continue;
|
|
188
|
+
const fallback = candidate.getBoundingClientRect();
|
|
189
|
+
if (fallback.height > rect.height) {
|
|
190
|
+
return {
|
|
191
|
+
height: fallback.height,
|
|
192
|
+
width: rect.width > 0 ? rect.width : fallback.width,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return rect;
|
|
197
|
+
}
|
|
198
|
+
}, { ratio: CAPACITY_SAFETY_RATIO, maxPx: CAPACITY_SAFETY_MAX_PX });
|
|
199
|
+
|
|
200
|
+
const blockHeights = await page.evaluate(() => {
|
|
201
|
+
const zone = document.querySelector("[data-openpress-blocks-zone]");
|
|
202
|
+
if (!zone) return [];
|
|
203
|
+
const out = [];
|
|
204
|
+
for (const chain of zone.querySelectorAll("[data-block-measurement-chain]")) {
|
|
205
|
+
const chainId = chain.getAttribute("data-block-measurement-chain") ?? "";
|
|
206
|
+
const parentTop = chain.parentElement?.getBoundingClientRect().top ?? chain.getBoundingClientRect().top;
|
|
207
|
+
let previousBottom = parentTop;
|
|
208
|
+
for (const el of Array.from(chain.querySelectorAll("[data-openpress-block-id]"))) {
|
|
209
|
+
const rect = el.getBoundingClientRect();
|
|
210
|
+
out.push({
|
|
211
|
+
id: el.getAttribute("data-openpress-block-id"),
|
|
212
|
+
height: Math.max(rect.height, rect.bottom - previousBottom),
|
|
213
|
+
chainId,
|
|
214
|
+
});
|
|
215
|
+
previousBottom = Math.max(previousBottom, rect.bottom);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
return { mdxAreas, blockHeights };
|
|
222
|
+
} finally {
|
|
223
|
+
await browser.close();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function escapeAttr(value) {
|
|
228
|
+
return String(value).replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function inlineMeasurementMediaUrls(html, mediaDir) {
|
|
232
|
+
if (!mediaDir || !html) return html;
|
|
233
|
+
let out = String(html);
|
|
234
|
+
const matches = new Set();
|
|
235
|
+
for (const match of out.matchAll(/\/openpress\/media\/([^"')\s>]+)/g)) {
|
|
236
|
+
matches.add(match[1]);
|
|
237
|
+
}
|
|
238
|
+
for (const rawName of matches) {
|
|
239
|
+
const dataUrl = await mediaDataUrl(mediaDir, rawName);
|
|
240
|
+
if (!dataUrl) continue;
|
|
241
|
+
out = out.replaceAll(`/openpress/media/${rawName}`, dataUrl);
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function mediaDataUrl(mediaDir, rawName) {
|
|
247
|
+
let fileName;
|
|
248
|
+
try {
|
|
249
|
+
fileName = decodeURIComponent(String(rawName));
|
|
250
|
+
} catch {
|
|
251
|
+
fileName = String(rawName);
|
|
252
|
+
}
|
|
253
|
+
if (!fileName || fileName !== path.basename(fileName)) return null;
|
|
254
|
+
const filePath = path.join(mediaDir, fileName);
|
|
255
|
+
let bytes;
|
|
256
|
+
try {
|
|
257
|
+
bytes = await fs.readFile(filePath);
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
return `data:${mediaMimeType(fileName)};base64,${bytes.toString("base64")}`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function mediaMimeType(fileName) {
|
|
265
|
+
const ext = path.extname(fileName).toLowerCase();
|
|
266
|
+
if (ext === ".svg") return "image/svg+xml";
|
|
267
|
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
|
268
|
+
if (ext === ".gif") return "image/gif";
|
|
269
|
+
if (ext === ".webp") return "image/webp";
|
|
270
|
+
return "image/png";
|
|
271
|
+
}
|