Skip to content

A fast, helpful, and open-source document parser

add debug traces

Logan Markewich32a6f9fd2554
diff --git a/cli/parse.ts b/cli/parse.ts
index dd353d4..22d6e99 100644
--- a/cli/parse.ts
+++ b/cli/parse.ts
@@ -30,6 +30,7 @@ interface ParseCommandOptions {
config?: string;
quiet?: boolean;
debug?: boolean;
+ debugTrace?: boolean;
debugVisualize?: boolean;
debugOutput?: string;
debugTextFilter?: string[];
@@ -91,6 +92,7 @@ program
.option("--config <file>", "Config file (JSON)")
.option("-q, --quiet", "Suppress progress output")
.addOption(new Option("--debug", "Enable grid projection debug logging").hideHelp())
+ .addOption(new Option("--debug-trace", "Enable detailed render decision tracing").hideHelp())
.addOption(new Option("--debug-visualize", "Generate grid visualization PNGs").hideHelp())
.addOption(new Option("--debug-output <path>", "Output directory for debug files").hideHelp())
.addOption(
@@ -147,7 +149,7 @@ program
};
// Build debug config if any debug flags are set
- if (options.debug || options.debugVisualize) {
+ if (options.debug || options.debugTrace || options.debugVisualize) {
let regionFilter: { x1: number; y1: number; x2: number; y2: number } | undefined;
if (options.debugRegion) {
const [x1, y1, x2, y2] = options.debugRegion.split(",").map(Number);
@@ -155,6 +157,7 @@ program
}
config.debug = {
enabled: true,
+ trace: options.debugTrace,
visualize: options.debugVisualize,
visualizePath: options.debugOutput ?? "./debug-output",
outputPath: options.debugOutput ? `${options.debugOutput}/debug.log` : undefined,
diff --git a/src/processing/gridDebugLogger.ts b/src/processing/gridDebugLogger.ts
index a6520fe..a89ab00 100644
--- a/src/processing/gridDebugLogger.ts
+++ b/src/processing/gridDebugLogger.ts
@@ -57,6 +57,16 @@ export interface GridDebugConfig {
* @defaultValue `"./debug-output"`
*/
visualizePath?: string;
+
+ /**
+ * Enable trace mode for detailed render decision logging.
+ * When enabled, each render logs the full decision chain: initial targetX,
+ * lineMax computation, forward anchor checks, and which factor was the
+ * binding constraint. Forward anchor mutations are also traced with their
+ * triggering item. Respects textFilter/lineFilter/pageFilter.
+ * @defaultValue `false`
+ */
+ trace?: boolean;
}
export const DEFAULT_DEBUG_CONFIG: GridDebugConfig = {
@@ -81,6 +91,49 @@ export interface RenderedSegment {
snap: "left" | "right" | "center" | "floating" | "flowing";
}
+/** Context for a render decision trace — captures every factor that influenced targetX. */
+export interface RenderTraceContext {
+ snapType: "left" | "right" | "center" | "floating";
+
+ // Initial calculation
+ initialTargetX: number;
+ medianWidth: number;
+
+ // lineMax computation
+ lineMax: number;
+ lastSnapLeft?: number;
+ lastSnapLeftKey?: number;
+ rawLineTrimLength: number;
+ shouldSpace: number;
+
+ // For right snap: per-item lineMax candidates
+ lineMaxCandidates?: Array<{
+ text: string;
+ lineIndex: number;
+ lineItemCount: number;
+ filtered: boolean;
+ value: number;
+ }>;
+
+ // Forward anchor check
+ forwardAnchorValue?: number;
+
+ // prevAnchors check
+ prevAnchorValue?: number;
+
+ // Floating-specific
+ pdfFallbackUsed?: boolean;
+ pdfFallbackTargetX?: number;
+ floatingAnchorBump?: number;
+
+ // Sparse anchor (left snap)
+ isSparseAnchor?: boolean;
+
+ // Final
+ finalTargetX: number;
+ bindingConstraint: string;
+}
+
/** Captured data for a single page, used by the grid visualizer. */
export interface VisualizerPageData {
pageNum: number;
@@ -112,6 +165,10 @@ export class GridDebugLogger {
private currentPage: number = 0;
private writeOutput: (msg: string) => void;
+ // Trace mode: snap positions that matched-filter items belong to.
+ // Forward anchor mutations affecting these positions are always logged.
+ private trackedSnapPositions = new Set<number>();
+
// Visualization data collection
private vizPages: VisualizerPageData[] = [];
private currentVizPage?: VisualizerPageData;
@@ -282,6 +339,15 @@ export class GridDebugLogger {
/** Log snap assignment for a bbox */
logSnapAssignment(bbox: ProjectionTextBox, lineIndex: number, boxIndex: number): void {
if (!this.matchesBbox(bbox, lineIndex)) return;
+
+ // Track snap positions for matched items so we can trace forward anchor
+ // mutations that affect them even when the triggering item doesn't match filters
+ if (this.config.trace) {
+ if (bbox.leftAnchor) this.trackedSnapPositions.add(parseFloat(bbox.leftAnchor));
+ if (bbox.rightAnchor) this.trackedSnapPositions.add(parseFloat(bbox.rightAnchor));
+ if (bbox.centerAnchor) this.trackedSnapPositions.add(parseFloat(bbox.centerAnchor));
+ }
+
this.emit({
phase: "snap",
lineIndex,
@@ -359,6 +425,108 @@ export class GridDebugLogger {
});
}
+ /** Log block-level context (medianWidth, sparse anchors, snap maps) */
+ logBlockContext(
+ blockStart: number,
+ blockEnd: number,
+ medianWidth: number,
+ sparseLeftAnchors: Set<number>
+ ): void {
+ if (!this.config.trace || !this.config.enabled || this.isPageFiltered()) return;
+ let msg = `Block ${blockStart}-${blockEnd - 1}: medianWidth=${round2(medianWidth)}`;
+ if (sparseLeftAnchors.size > 0) {
+ msg += `, sparseLeft=[${[...sparseLeftAnchors].map(round2).join(", ")}]`;
+ }
+ this.emit({ phase: "trace-block", message: msg });
+ }
+
+ /** Log full render decision trace for a single item */
+ logRenderTrace(
+ bbox: ProjectionTextBox,
+ lineIndex: number,
+ ctx: RenderTraceContext
+ ): void {
+ if (!this.config.trace || !this.matchesBbox(bbox, lineIndex)) return;
+
+ const lines: string[] = [];
+ lines.push(
+ `"${bbox.str.substring(0, 40)}" → col ${ctx.finalTargetX} (${ctx.snapType}) [binding: ${ctx.bindingConstraint}]`
+ );
+ lines.push(
+ ` initial: round(${round2(bbox.x)} / ${round2(ctx.medianWidth)}) = ${ctx.initialTargetX}, COLUMN_SPACES cap → ${Math.min(ctx.initialTargetX, 4)}`
+ );
+
+ // lineMax details
+ if (ctx.lineMaxCandidates) {
+ // Right snap: show per-item candidates
+ lines.push(` lineMax: ${ctx.lineMax} from ${ctx.lineMaxCandidates.length} candidates:`);
+ for (const c of ctx.lineMaxCandidates) {
+ const mark = c.filtered ? " [FILTERED: single-item line]" : "";
+ lines.push(` L${c.lineIndex} "${c.text}" → ${c.value} (lineItems=${c.lineItemCount})${mark}`);
+ }
+ } else {
+ const parts: string[] = [];
+ if (ctx.lastSnapLeft !== undefined && ctx.lastSnapLeft > 0) {
+ parts.push(`lastSnapLeft=${ctx.lastSnapLeft}${ctx.lastSnapLeftKey !== undefined ? ` (from left@${round2(ctx.lastSnapLeftKey)})` : ""}`);
+ }
+ parts.push(`rawLine.trimEnd=${ctx.rawLineTrimLength}`);
+ if (ctx.shouldSpace > 0) parts.push(`shouldSpace=${ctx.shouldSpace}`);
+ lines.push(` lineMax: ${ctx.lineMax} (${parts.join(", ")})`);
+ }
+
+ // Forward anchor
+ if (ctx.forwardAnchorValue !== undefined) {
+ lines.push(` forwardAnchor: ${ctx.forwardAnchorValue}`);
+ }
+ // prevAnchors
+ if (ctx.prevAnchorValue !== undefined) {
+ lines.push(` prevAnchor: ${ctx.prevAnchorValue}`);
+ }
+ // Floating-specific
+ if (ctx.pdfFallbackUsed) {
+ lines.push(` pdfFallback: targetX raised to ${ctx.pdfFallbackTargetX} (empty line)`);
+ }
+ if (ctx.floatingAnchorBump !== undefined) {
+ lines.push(` floatingAnchor bump: +${ctx.floatingAnchorBump}`);
+ }
+ if (ctx.isSparseAnchor) {
+ lines.push(` sparse anchor: skipping forward anchor propagation and block padding`);
+ }
+
+ this.emit({
+ phase: "trace-render",
+ lineIndex,
+ text: bbox.str,
+ message: lines.join("\n"),
+ });
+ }
+
+ /** Log a forward anchor mutation with the triggering item */
+ logForwardAnchorMutation(
+ triggerText: string,
+ triggerLineIndex: number,
+ snapType: string,
+ snapPosition: number,
+ oldValue: number | undefined,
+ newValue: number,
+ rightBound: number
+ ): void {
+ if (!this.config.trace || !this.config.enabled || this.isPageFiltered()) return;
+ // Log if: no text filter, or trigger matches filter, or snap position is tracked
+ if (this.config.textFilter?.length) {
+ const text = triggerText.toLowerCase();
+ const matchesTrigger = this.config.textFilter.some((f) => text.includes(f.toLowerCase()));
+ const matchesPosition = this.trackedSnapPositions.has(snapPosition);
+ if (!matchesTrigger && !matchesPosition) return;
+ }
+ const oldStr = oldValue !== undefined ? `was ${oldValue}` : "unset";
+ this.emit({
+ phase: "trace-fwd-mutation",
+ lineIndex: triggerLineIndex,
+ message: `${snapType}@${round2(snapPosition)}: ${oldStr} → ${newValue} (triggered by "${triggerText.substring(0, 40)}" L${triggerLineIndex}, rightBound=${round2(rightBound)})`,
+ });
+ }
+
/** Log line composition (the full set of bboxes on a line) */
logLineComposition(lineIndex: number, line: ProjectionTextBox[]): void {
if (!this.config.enabled || this.isPageFiltered()) return;
@@ -453,6 +621,9 @@ class NoopGridDebugLogger extends GridDebugLogger {
override logRender(): void {}
override logForwardAnchor(): void {}
override logDuplicateResolution(): void {}
+ override logBlockContext(): void {}
+ override logRenderTrace(): void {}
+ override logForwardAnchorMutation(): void {}
override logLineComposition(): void {}
override flushSync(): void {}
override async flush(): Promise<void> {}
diff --git a/src/processing/gridProjection.ts b/src/processing/gridProjection.ts
index 255f8a9..122371e 100644
--- a/src/processing/gridProjection.ts
+++ b/src/processing/gridProjection.ts
@@ -1098,7 +1098,11 @@ function updateForwardAnchorRightBound(
snapMap: number[],
forwardAnchor: ForwardAnchor,
rightBound: number,
- anchorTarget: number
+ anchorTarget: number,
+ logger: GridDebugLogger,
+ triggerText: string,
+ triggerLineIndex: number,
+ snapType: string
): void {
// Anything snapped to the right of rightBound should be aligned to anchorTarget line length at minimum
// Also update nearby positions (within tolerance) to handle slight position variations between rows
@@ -1108,14 +1112,22 @@ function updateForwardAnchorRightBound(
const anchor = snapMap[i];
if (rightBound <= anchor) {
if (!forwardAnchor[anchor] || anchorTarget > forwardAnchor[anchor]) {
+ const oldValue = forwardAnchor[anchor];
forwardAnchor[anchor] = anchorTarget;
+ logger.logForwardAnchorMutation(
+ triggerText, triggerLineIndex, snapType, anchor, oldValue, anchorTarget, rightBound
+ );
}
// Also update nearby positions within tolerance
for (let j = i - 1; j >= 0; --j) {
const nearbyAnchor = snapMap[j];
if (anchor - nearbyAnchor > POSITION_TOLERANCE) break;
if (!forwardAnchor[nearbyAnchor] || anchorTarget > forwardAnchor[nearbyAnchor]) {
+ const oldValue = forwardAnchor[nearbyAnchor];
forwardAnchor[nearbyAnchor] = anchorTarget;
+ logger.logForwardAnchorMutation(
+ triggerText, triggerLineIndex, snapType, nearbyAnchor, oldValue, anchorTarget, rightBound
+ );
}
}
} else {
@@ -1129,7 +1141,9 @@ function updateForwardAnchors(
nextBbox: ProjectionTextBox | null,
snapMaps: SnapMaps,
forwardAnchors: PageForwardAnchors,
- lineLength: number
+ lineLength: number,
+ logger: GridDebugLogger,
+ lineIndex: number
): void {
// If this is the last item on the line (no nextBbox), don't propagate
// forward anchors. There's nothing to the right on this line that needs
@@ -1142,15 +1156,13 @@ function updateForwardAnchors(
if ((nextBbox.shouldSpace ?? 0) > 0) {
targetLength += nextBbox.shouldSpace ?? 0;
}
- updateForwardAnchorRightBound(snapMaps.left, forwardAnchors.left, rightBound, targetLength);
- updateForwardAnchorRightBound(snapMaps.right, forwardAnchors.right, rightBound, targetLength);
+ const triggerText = bbox.str;
+ updateForwardAnchorRightBound(snapMaps.left, forwardAnchors.left, rightBound, targetLength, logger, triggerText, lineIndex, "left");
+ updateForwardAnchorRightBound(snapMaps.right, forwardAnchors.right, rightBound, targetLength, logger, triggerText, lineIndex, "right");
// we do not update center anchors since centered text may span between snapped columns
updateForwardAnchorRightBound(
- snapMaps.floating,
- forwardAnchors.floating,
- rightBound,
- targetLength
+ snapMaps.floating, forwardAnchors.floating, rightBound, targetLength, logger, triggerText, lineIndex, "floating"
);
}
@@ -1492,6 +1504,8 @@ export function projectToGrid(
void sizes.height;
}
+ logger.logBlockContext(block.start, block.end, medianWidth, sparseLeftAnchors);
+
// compute snaps
for (let lineIndex = block.start; lineIndex < block.end; ++lineIndex) {
const line = lines[lineIndex];
@@ -1667,22 +1681,31 @@ export function projectToGrid(
break;
}
- let targetX = Math.min(Math.round(bbox.x / medianWidth), COLUMN_SPACES);
+ const initialTargetX = Math.round(bbox.x / medianWidth);
+ let targetX = Math.min(initialTargetX, COLUMN_SPACES);
let lastSnapLeft = 0;
+ let lastSnapLeftKey: number | undefined;
for (const key in forwardAnchors.left) {
// Use parseFloat to preserve decimal precision from anchor keys
const keyVal = parseFloat(key);
if (keyVal <= bbox.x && !sparseLeftAnchors.has(keyVal)) {
- lastSnapLeft = Math.max(lastSnapLeft, forwardAnchors.left[key]);
+ if (forwardAnchors.left[key] > lastSnapLeft) {
+ lastSnapLeft = forwardAnchors.left[key];
+ lastSnapLeftKey = keyVal;
+ }
}
}
+ const rawLineTrimLength = rawLines[lineIndex].trimEnd().length;
const lineMax = Math.max(
lastSnapLeft,
- rawLines[lineIndex].trimEnd().length + (bbox.shouldSpace ?? 0)
+ rawLineTrimLength + (bbox.shouldSpace ?? 0)
);
+ let bindingConstraint = "COLUMN_SPACES";
if (targetX < lineMax) {
targetX = lineMax;
+ bindingConstraint = lastSnapLeft >= rawLineTrimLength + (bbox.shouldSpace ?? 0)
+ ? "lastSnapLeft" : "lineMax";
}
// For floating items on lines with no rendered content (only block
@@ -1695,9 +1718,11 @@ export function projectToGrid(
if (pdfTargetX > targetX) {
targetX = pdfTargetX;
usedPdfFallback = true;
+ bindingConstraint = "pdfFallback";
}
}
+ let floatingAnchorBump: number | undefined;
if (!bbox.forceUnsnapped) {
const floatingAnchor = forwardAnchors.floating[Math.round(bbox.x)];
if (floatingAnchor && targetX < floatingAnchor) {
@@ -1706,11 +1731,29 @@ export function projectToGrid(
const maxFloatingGap = 4;
const adjustedAnchor = Math.min(floatingAnchor, targetX + maxFloatingGap);
if (adjustedAnchor > targetX) {
+ floatingAnchorBump = adjustedAnchor - targetX;
targetX = adjustedAnchor;
+ bindingConstraint = "floatingAnchor";
}
}
}
+ logger.logRenderTrace(bbox, lineIndex, {
+ snapType: "floating",
+ initialTargetX,
+ medianWidth,
+ lineMax,
+ lastSnapLeft: lastSnapLeft > 0 ? lastSnapLeft : undefined,
+ lastSnapLeftKey,
+ rawLineTrimLength,
+ shouldSpace: bbox.shouldSpace ?? 0,
+ pdfFallbackUsed: usedPdfFallback || undefined,
+ pdfFallbackTargetX: usedPdfFallback ? targetX : undefined,
+ floatingAnchorBump,
+ finalTargetX: targetX,
+ bindingConstraint,
+ });
+
rawLines[lineIndex] = rawLines[lineIndex].trimEnd();
if (targetX > rawLines[lineIndex].length) {
rawLines[lineIndex] += " ".repeat(targetX - rawLines[lineIndex].length);
@@ -1733,7 +1776,9 @@ export function projectToGrid(
nextBbox,
snapMaps,
forwardAnchors,
- rawLines[lineIndex].length
+ rawLines[lineIndex].length,
+ logger,
+ lineIndex
);
}
}
@@ -1761,7 +1806,8 @@ export function projectToGrid(
continue;
}
- let targetX = Math.min(Math.round(snapMaps.left[0] / medianWidth), COLUMN_SPACES);
+ const leftInitialTargetX = Math.round(snapMaps.left[0] / medianWidth);
+ let targetX = Math.min(leftInitialTargetX, COLUMN_SPACES);
const lineMax = Math.max(
...thisTurnSnap.map((v) => {
let spaceEnd = 0;
@@ -1780,21 +1826,27 @@ export function projectToGrid(
})
);
+ let leftBindingConstraint = "COLUMN_SPACES";
if (targetX < lineMax) {
targetX = lineMax;
+ leftBindingConstraint = "lineMax";
}
+ const leftForwardAnchorValue = forwardAnchors.left[snapMaps.left[0]];
if (
- forwardAnchors.left[snapMaps.left[0]] &&
- targetX < forwardAnchors.left[snapMaps.left[0]]
+ leftForwardAnchorValue &&
+ targetX < leftForwardAnchorValue
) {
- targetX = forwardAnchors.left[snapMaps.left[0]];
+ targetX = leftForwardAnchorValue;
+ leftBindingConstraint = "forwardAnchor";
}
+ const leftPrevAnchorValue = prevAnchors.forwardAnchorLeft[snapMaps.left[0]];
if (
- prevAnchors.forwardAnchorLeft[snapMaps.left[0]] &&
- targetX < prevAnchors.forwardAnchorLeft[snapMaps.left[0]]
+ leftPrevAnchorValue &&
+ targetX < leftPrevAnchorValue
) {
- targetX = prevAnchors.forwardAnchorLeft[snapMaps.left[0]];
+ targetX = leftPrevAnchorValue;
+ leftBindingConstraint = "prevAnchor";
}
if (!isSparseAnchor) {
@@ -1805,6 +1857,21 @@ export function projectToGrid(
for (const currentLeftSnapBox of thisTurnSnap) {
const lineIndex = currentLeftSnapBox.lineIndex;
if (flowingLines.has(lineIndex)) continue;
+
+ logger.logRenderTrace(currentLeftSnapBox.bbox, lineIndex, {
+ snapType: "left",
+ initialTargetX: leftInitialTargetX,
+ medianWidth,
+ lineMax,
+ rawLineTrimLength: rawLines[lineIndex].trimEnd().length,
+ shouldSpace: currentLeftSnapBox.bbox.shouldSpace ?? 0,
+ forwardAnchorValue: leftForwardAnchorValue || undefined,
+ prevAnchorValue: leftPrevAnchorValue || undefined,
+ isSparseAnchor: isSparseAnchor || undefined,
+ finalTargetX: targetX,
+ bindingConstraint: leftBindingConstraint,
+ });
+
if (targetX > rawLines[lineIndex].length) {
rawLines[lineIndex] += " ".repeat(targetX - rawLines[lineIndex].length);
}
@@ -1826,7 +1893,9 @@ export function projectToGrid(
nextBbox,
snapMaps,
forwardAnchors,
- rawLines[lineIndex].length
+ rawLines[lineIndex].length,
+ logger,
+ lineIndex
);
}
}
@@ -1863,45 +1932,59 @@ export function projectToGrid(
continue;
}
- let targetX = Math.min(Math.round(snapMaps.right[0] / medianWidth), COLUMN_SPACES);
+ const rightInitialTargetX = Math.round(snapMaps.right[0] / medianWidth);
+ let targetX = Math.min(rightInitialTargetX, COLUMN_SPACES);
// Filter out single-item lines from lineMax: full-width text (footnotes,
// titles) that coincidentally matches this right anchor shouldn't inflate
// the column position for actual data values.
- const lineMaxCandidates = thisTurnSnap
- .filter((v) => lines[v.lineIndex].length > 1)
- .map((v) => {
- let lastSnapLeft = 0;
- for (const key in forwardAnchors.left) {
- const keyVal = parseFloat(key);
- if (keyVal <= v.bbox.x && !sparseLeftAnchors.has(keyVal)) {
- lastSnapLeft = Math.max(lastSnapLeft, forwardAnchors.left[key]);
- }
+ const allRightCandidates = thisTurnSnap.map((v) => {
+ const isSingleItem = lines[v.lineIndex].length <= 1;
+ let lastSnapLeft = 0;
+ for (const key in forwardAnchors.left) {
+ const keyVal = parseFloat(key);
+ if (keyVal <= v.bbox.x && !sparseLeftAnchors.has(keyVal)) {
+ lastSnapLeft = Math.max(lastSnapLeft, forwardAnchors.left[key]);
}
- return (
- Math.max(
- lastSnapLeft,
- rawLines[v.lineIndex].trimEnd().length + (v.bbox.shouldSpace ?? 0)
- ) + v.bbox.strLength
- );
- });
+ }
+ const value = Math.max(
+ lastSnapLeft,
+ rawLines[v.lineIndex].trimEnd().length + (v.bbox.shouldSpace ?? 0)
+ ) + v.bbox.strLength;
+ return {
+ text: v.bbox.str.substring(0, 30),
+ lineIndex: v.lineIndex,
+ lineItemCount: lines[v.lineIndex].length,
+ filtered: isSingleItem,
+ value,
+ };
+ });
+ const lineMaxCandidates = allRightCandidates
+ .filter((c) => !c.filtered)
+ .map((c) => c.value);
const lineMax = lineMaxCandidates.length > 0
? Math.max(...lineMaxCandidates)
: 0;
+ let rightBindingConstraint = "COLUMN_SPACES";
if (targetX < lineMax) {
targetX = lineMax;
+ rightBindingConstraint = "lineMax";
}
+ const rightForwardAnchorValue = forwardAnchors.right[snapMaps.right[0]];
if (
- forwardAnchors.right[snapMaps.right[0]] &&
- targetX < forwardAnchors.right[snapMaps.right[0]]
+ rightForwardAnchorValue &&
+ targetX < rightForwardAnchorValue
) {
- targetX = forwardAnchors.right[snapMaps.right[0]];
+ targetX = rightForwardAnchorValue;
+ rightBindingConstraint = "forwardAnchor";
}
+ const rightPrevAnchorValue = prevAnchors.forwardAnchorRight[snapMaps.right[0]];
if (
- prevAnchors.forwardAnchorRight[snapMaps.right[0]] &&
- targetX < prevAnchors.forwardAnchorRight[snapMaps.right[0]]
+ rightPrevAnchorValue &&
+ targetX < rightPrevAnchorValue
) {
- targetX = prevAnchors.forwardAnchorRight[snapMaps.right[0]];
+ targetX = rightPrevAnchorValue;
+ rightBindingConstraint = "prevAnchor";
}
forwardAnchors.right[snapMaps.right[0]] = targetX;
logger.logForwardAnchor("right", snapMaps.right[0], targetX);
@@ -1909,6 +1992,21 @@ export function projectToGrid(
for (const currentRightSnapBox of thisTurnSnap) {
const lineIndex = currentRightSnapBox.lineIndex;
if (flowingLines.has(lineIndex)) continue;
+
+ logger.logRenderTrace(currentRightSnapBox.bbox, lineIndex, {
+ snapType: "right",
+ initialTargetX: rightInitialTargetX,
+ medianWidth,
+ lineMax,
+ rawLineTrimLength: rawLines[lineIndex].trimEnd().length,
+ shouldSpace: currentRightSnapBox.bbox.shouldSpace ?? 0,
+ lineMaxCandidates: allRightCandidates,
+ forwardAnchorValue: rightForwardAnchorValue || undefined,
+ prevAnchorValue: rightPrevAnchorValue || undefined,
+ finalTargetX: targetX,
+ bindingConstraint: rightBindingConstraint,
+ });
+
rawLines[lineIndex] = rawLines[lineIndex].trimEnd();
if (targetX > rawLines[lineIndex].trimEnd().length + currentRightSnapBox.bbox.strLength) {
rawLines[lineIndex] += " ".repeat(
@@ -1934,7 +2032,9 @@ export function projectToGrid(
nextBbox,
snapMaps,
forwardAnchors,
- rawLines[lineIndex].length
+ rawLines[lineIndex].length,
+ logger,
+ lineIndex
);
}
for (let index = block.start; index < block.end; ++index) {
@@ -1965,7 +2065,8 @@ export function projectToGrid(
snapMaps.center.shift();
continue;
}
- let targetX = Math.min(Math.round(snapMaps.center[0] / medianWidth), COLUMN_SPACES);
+ const centerInitialTargetX = Math.round(snapMaps.center[0] / medianWidth);
+ let targetX = Math.min(centerInitialTargetX, COLUMN_SPACES);
const lineMax = Math.max(
...thisTurnSnap.map((v) => {
let spaceEnd = 0;
@@ -1983,25 +2084,45 @@ export function projectToGrid(
})
);
+ let centerBindingConstraint = "COLUMN_SPACES";
if (targetX < lineMax) {
targetX = lineMax;
+ centerBindingConstraint = "lineMax";
}
+ const centerForwardAnchorValue = forwardAnchors.center[snapMaps.center[0]];
if (
- forwardAnchors.center[snapMaps.center[0]] &&
- targetX < forwardAnchors.center[snapMaps.center[0]]
+ centerForwardAnchorValue &&
+ targetX < centerForwardAnchorValue
) {
- targetX = forwardAnchors.center[snapMaps.center[0]];
+ targetX = centerForwardAnchorValue;
+ centerBindingConstraint = "forwardAnchor";
}
+ const centerPrevAnchorValue = prevAnchors.forwardAnchorCenter[snapMaps.center[0]];
if (
- prevAnchors.forwardAnchorCenter[snapMaps.center[0]] &&
- targetX < prevAnchors.forwardAnchorCenter[snapMaps.center[0]]
+ centerPrevAnchorValue &&
+ targetX < centerPrevAnchorValue
) {
- targetX = prevAnchors.forwardAnchorCenter[snapMaps.center[0]];
+ targetX = centerPrevAnchorValue;
+ centerBindingConstraint = "prevAnchor";
}
forwardAnchors.center[snapMaps.center[0]] = targetX;
logger.logForwardAnchor("center", snapMaps.center[0], targetX);
for (const currentCenterSnapBox of thisTurnSnap) {
if (flowingLines.has(currentCenterSnapBox.lineIndex)) continue;
+
+ logger.logRenderTrace(currentCenterSnapBox.bbox, currentCenterSnapBox.lineIndex, {
+ snapType: "center",
+ initialTargetX: centerInitialTargetX,
+ medianWidth,
+ lineMax,
+ rawLineTrimLength: rawLines[currentCenterSnapBox.lineIndex].trimEnd().length,
+ shouldSpace: currentCenterSnapBox.bbox.shouldSpace ?? 0,
+ forwardAnchorValue: centerForwardAnchorValue || undefined,
+ prevAnchorValue: centerPrevAnchorValue || undefined,
+ finalTargetX: targetX,
+ bindingConstraint: centerBindingConstraint,
+ });
+
if (
targetX >
rawLines[currentCenterSnapBox.lineIndex].length +