Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

fix(export): measure the real font box so cjk glyph tops keep their ink

M Avdiced02e14dbc1
diff --git a/src/core/export/__tests__/pdf-text.test.ts b/src/core/export/__tests__/pdf-text.test.ts
index 7e746e3..55cabde 100644
--- a/src/core/export/__tests__/pdf-text.test.ts
+++ b/src/core/export/__tests__/pdf-text.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { needsRaster, segments, wrap } from '@/core/export/pdf-text';
+import { boxFrom, layout, needsRaster, segments, wrap } from '@/core/export/pdf-text';
describe('needsRaster', () => {
it('leaves latin text on the vector path', () => {
@@ -54,3 +54,96 @@ describe('wrap', () => {
expect(wrap('supercalifragilistic', 5, measure)).toEqual(['supercalifragilistic']);
});
});
+
+const MM_PER_PT = 25.4 / 72;
+
+// Noto Sans CJK reports a box far taller than the 0.8em the raster path used to
+// assume; Latin faces sit comfortably inside it. These are the two cases that
+// decide whether a glyph keeps its top row.
+const CJK_BOX = { ascent: 13.92, descent: 3.456 }; // 1.16em / 0.288em at 12pt
+const LATIN_BOX = { ascent: 9, descent: 3 }; // 0.75em / 0.25em at 12pt
+
+const metrics = (ascent?: number, descent?: number) => ({
+ fontBoundingBoxAscent: ascent,
+ fontBoundingBoxDescent: descent,
+});
+
+describe('boxFrom', () => {
+ it('reads the font box the engine reports', () => {
+ expect(boxFrom([metrics(13.92, 3.456)], 12)).toEqual(CJK_BOX);
+ });
+
+ it('takes the tallest box when a run mixes scripts', () => {
+ const box = boxFrom([metrics(9, 3), metrics(13.92, 3.456)], 12);
+ expect(box).toEqual(CJK_BOX);
+ });
+
+ it('falls back to the old ratio when the engine withholds the box', () => {
+ const box = boxFrom([metrics(undefined, undefined)], 12);
+ expect(box.ascent).toBeCloseTo(9.6);
+ expect(box.descent).toBeCloseTo(2.4);
+ });
+
+ it('falls back when the engine reports a zero ascent', () => {
+ const box = boxFrom([metrics(0, 0)], 10);
+ expect(box.ascent).toBeCloseTo(8);
+ expect(box.descent).toBeCloseTo(2);
+ });
+});
+
+describe('layout', () => {
+ const lineHeightMm = 5;
+ const step = lineHeightMm / MM_PER_PT;
+
+ it('puts the first baseline at the font ascent, so the glyph top is not clipped', () => {
+ // The defect: the baseline used to sit at 0.8em (9.6px), which is above the
+ // 13.92px CJK ascent, so every CJK line lost its top rows off the canvas.
+ const l = layout(40, 1, lineHeightMm, CJK_BOX);
+ expect(l.baselines[0]).toBeCloseTo(CJK_BOX.ascent);
+ expect(l.baselines[0]).toBeGreaterThan(12 * 0.8);
+ });
+
+ it('grows the canvas when ascent plus descent exceeds the line height', () => {
+ const l = layout(40, 1, lineHeightMm, CJK_BOX);
+ const needed = CJK_BOX.ascent + CJK_BOX.descent;
+ expect(needed).toBeGreaterThan(step); // the case under test is real
+ expect(l.height / MM_PER_PT).toBeGreaterThanOrEqual(needed);
+ });
+
+ it('leaves the height at the line box when the font fits inside it', () => {
+ const l = layout(40, 2, lineHeightMm, LATIN_BOX);
+ // ink needs 26.2px and the two line boxes need 28.3px, so the line box governs
+ expect(LATIN_BOX.ascent + step + LATIN_BOX.descent).toBeLessThan(2 * step);
+ expect(l.height / MM_PER_PT).toBeCloseTo(2 * step, 0);
+ });
+
+ it('steps each baseline by exactly one line height', () => {
+ const l = layout(40, 3, lineHeightMm, LATIN_BOX);
+ expect(l.baselines).toHaveLength(3);
+ expect(l.baselines[1] - l.baselines[0]).toBeCloseTo(step);
+ expect(l.baselines[2] - l.baselines[1]).toBeCloseTo(step);
+ });
+
+ it('keeps the last descender inside the canvas', () => {
+ const l = layout(40, 4, lineHeightMm, CJK_BOX);
+ const lastInk = l.baselines[3] + CJK_BOX.descent;
+ expect(l.height / MM_PER_PT).toBeGreaterThanOrEqual(lastInk);
+ });
+
+ it('reports millimetres that match the device pixels, so addImage cannot stretch', () => {
+ const l = layout(40, 2, lineHeightMm, CJK_BOX);
+ expect(l.width).toBeCloseTo((l.deviceWidth / 4) * MM_PER_PT);
+ expect(l.height).toBeCloseTo((l.deviceHeight / 4) * MM_PER_PT);
+ });
+
+ it('reports the ascent in millimetres, since pdf-export offsets the image by it', () => {
+ const l = layout(40, 1, lineHeightMm, CJK_BOX);
+ expect(l.ascent).toBeCloseTo(CJK_BOX.ascent * MM_PER_PT);
+ });
+
+ it('never asks for a zero-sized canvas', () => {
+ const l = layout(0.01, 1, lineHeightMm, LATIN_BOX);
+ expect(l.deviceWidth).toBeGreaterThanOrEqual(1);
+ expect(l.deviceHeight).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/src/core/export/pdf-text.ts b/src/core/export/pdf-text.ts
index c049d2a..c3310b2 100644
--- a/src/core/export/pdf-text.ts
+++ b/src/core/export/pdf-text.ts
@@ -1,6 +1,8 @@
const MM_PER_PT = 25.4 / 72;
const RASTER_SCALE = 4;
+// Only a fallback, for engines that withhold the fontBoundingBox metrics.
const ASCENT_RATIO = 0.8;
+const DESCENT_RATIO = 0.2;
const RASTER_FONTS =
'"Noto Sans", "Noto Sans CJK SC", "Noto Sans CJK JP", "Microsoft YaHei", "PingFang SC", "Hiragino Sans", "Malgun Gothic", system-ui, -apple-system, "Segoe UI", Arial, sans-serif';
@@ -76,13 +78,81 @@ export interface RasterText {
ascent: number;
}
+function fontSpec(sizePt: number, bold: boolean): string {
+ return `${bold ? 'bold ' : ''}${sizePt}px ${RASTER_FONTS}`;
+}
+
export function measurer(sizePt: number, bold: boolean): ((s: string) => number) | null {
const ctx = context();
if (!ctx) return null;
- ctx.font = `${bold ? 'bold ' : ''}${sizePt}px ${RASTER_FONTS}`;
+ ctx.font = fontSpec(sizePt, bold);
return (s: string) => ctx.measureText(s).width * MM_PER_PT;
}
+export interface FontBox {
+ ascent: number;
+ descent: number;
+}
+
+interface BoxMetrics {
+ fontBoundingBoxAscent?: number;
+ fontBoundingBoxDescent?: number;
+}
+
+/**
+ * The tallest font box across the measured lines, in css px.
+ *
+ * A font stack renders CJK through a fallback face whose box is far taller than
+ * a latin one, so the box has to be measured from the text actually being drawn.
+ * Assuming a fixed ratio clipped the top rows off every CJK line.
+ */
+export function boxFrom(metrics: BoxMetrics[], sizePt: number): FontBox {
+ let ascent = 0;
+ let descent = 0;
+ for (const m of metrics) {
+ if (typeof m.fontBoundingBoxAscent === 'number' && Number.isFinite(m.fontBoundingBoxAscent)) {
+ ascent = Math.max(ascent, m.fontBoundingBoxAscent);
+ }
+ if (typeof m.fontBoundingBoxDescent === 'number' && Number.isFinite(m.fontBoundingBoxDescent)) {
+ descent = Math.max(descent, m.fontBoundingBoxDescent);
+ }
+ }
+ if (ascent > 0) return { ascent, descent };
+ return { ascent: sizePt * ASCENT_RATIO, descent: sizePt * DESCENT_RATIO };
+}
+
+export interface RasterLayout {
+ deviceWidth: number;
+ deviceHeight: number;
+ width: number;
+ height: number;
+ ascent: number;
+ baselines: number[];
+}
+
+/**
+ * Canvas geometry for a run of lines: the device pixels to allocate, the
+ * millimetres those pixels stand for, and where each baseline sits.
+ *
+ * Kept pure so the geometry is testable without a canvas implementation, which
+ * jsdom does not provide.
+ */
+export function layout(widest: number, lineCount: number, lineHeight: number, box: FontBox): RasterLayout {
+ const count = Math.max(lineCount, 1);
+ const step = lineHeight / MM_PER_PT;
+ const ink = box.ascent + (count - 1) * step + box.descent;
+ const deviceWidth = Math.max(1, Math.ceil((widest / MM_PER_PT) * RASTER_SCALE));
+ const deviceHeight = Math.max(1, Math.ceil(Math.max(count * step, ink) * RASTER_SCALE));
+ return {
+ deviceWidth,
+ deviceHeight,
+ width: (deviceWidth / RASTER_SCALE) * MM_PER_PT,
+ height: (deviceHeight / RASTER_SCALE) * MM_PER_PT,
+ ascent: box.ascent * MM_PER_PT,
+ baselines: Array.from({ length: count }, (_, i) => box.ascent + i * step),
+ };
+}
+
export function rasterize(
lines: string[],
sizePt: number,
@@ -90,21 +160,27 @@ export function rasterize(
lineHeight: number,
color: string,
): RasterText | null {
- const measure = measurer(sizePt, bold);
- if (!measure) return null;
- const widest = Math.max(...lines.map(measure), 0.01);
- const height = lines.length * lineHeight;
+ const probe = context();
+ if (!probe) return null;
+ const font = fontSpec(sizePt, bold);
+ probe.font = font;
+ const widest = Math.max(...lines.map((line) => probe.measureText(line).width * MM_PER_PT), 0.01);
+ const inked = lines.filter((line) => line.length > 0);
+ const box = boxFrom(
+ (inked.length ? inked : ['M']).map((line) => probe.measureText(line)),
+ sizePt,
+ );
+ const frame = layout(widest, lines.length, lineHeight, box);
+
const canvas = document.createElement('canvas');
- canvas.width = Math.ceil((widest / MM_PER_PT) * RASTER_SCALE);
- canvas.height = Math.ceil((height / MM_PER_PT) * RASTER_SCALE);
+ canvas.width = frame.deviceWidth;
+ canvas.height = frame.deviceHeight;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
ctx.scale(RASTER_SCALE, RASTER_SCALE);
- ctx.font = `${bold ? 'bold ' : ''}${sizePt}px ${RASTER_FONTS}`;
+ ctx.font = font;
ctx.fillStyle = color;
ctx.textBaseline = 'alphabetic';
- const ascent = sizePt * ASCENT_RATIO;
- const step = lineHeight / MM_PER_PT;
- for (const [i, line] of lines.entries()) ctx.fillText(line, 0, ascent + i * step);
- return { dataUrl: canvas.toDataURL('image/png'), width: widest, height, ascent: ascent * MM_PER_PT };
+ for (const [i, line] of lines.entries()) ctx.fillText(line, 0, frame.baselines[i]);
+ return { dataUrl: canvas.toDataURL('image/png'), width: frame.width, height: frame.height, ascent: frame.ascent };
}