Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions Sheets/Code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
// existing rendered sheets in user spreadsheets rely on this exact prefix to identify
// Auto-LaTeX images during removeAll / editEquations.
const ALE_ALT_TEXT_PREFIX = "ALE-Latex:";
// REASON: point size Automatic/Inline renders are scaled to. Matches the defaultSize
// used when scanning cells, so a rendered equation reads like the text it replaced.
const SHEETS_DEFAULT_EQUATION_SIZE = 11;

// REASON: Mirror of Docs's DocsApp / Slides's IntegratedApp pattern. The Common library
// expects an IntegratedApp shape for helpers that walk back from a fully-rendered image
Expand Down Expand Up @@ -509,17 +512,24 @@ function insertRenderedImage(
image.setAltTextDescription(ALE_ALT_TEXT_PREFIX + Utilities.base64Encode(originalCellValue));
image.setAltTextTitle("Auto-LaTeX equation");

// REASON: If the user requested an explicit pixel size via the sidebar's "Custom"
// option, apply it here. Scale the width by the same factor — setHeight alone
// REASON: Always scale. Server renderers return the equation at \dpi{900}, so an
// OverGridImage inserted at its natural size is several hundred pixels tall — one
// equation covered ~14 rows and overlapped the next one (seen live 2026-09-19).
// Automatic/Inline arrive here as size 0, which used to skip this block entirely and
// leave the giant native image in place; fall back to the cell-text default so the
// image sits on its row. Scale the width by the same factor — setHeight alone
// stretches the image because OverGridImage does not preserve aspect ratio.
if (preferredSize > 0) {
const currentHeight = image.getHeight();
const currentWidth = image.getWidth();
const targetHeight = preferredSize * 4;
image.setHeight(targetHeight);
if (currentHeight > 0 && currentWidth > 0) {
image.setWidth(Math.max(1, Math.round(currentWidth * targetHeight / currentHeight)));
}
const currentHeight = image.getHeight();
const currentWidth = image.getWidth();
// An explicit size keeps its historical 4x multiplier. Automatic/Inline (size 0) aim
// at a single default row (~21px) instead, so consecutive equations in a column do
// not overlap each other the way a 2-row-tall image does.
const targetHeight = preferredSize > 0
? preferredSize * 4
: SHEETS_DEFAULT_EQUATION_SIZE * 2;
image.setHeight(targetHeight);
if (currentHeight > 0 && currentWidth > 0) {
image.setWidth(Math.max(1, Math.round(currentWidth * targetHeight / currentHeight)));
}

// REASON: Clear the cell value AFTER inserting the image. If we cleared first and
Expand Down
158 changes: 158 additions & 0 deletions tests/helpers/sheets-harness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { compileScript } = require("./compile-script");

const sheetsCodePath = process.env.AUTOLATEX_SHEETS_CODE_PATH
|| path.join(__dirname, "../..", "Sheets/Code.ts");

// REASON: Sheets equations are whole-cell, so the container model is a grid of strings
// plus a list of OverGridImages, not a paragraph stream like Docs. Only the Spreadsheet
// boundary is doubled here — cell scanning, delimiter parsing, renderer routing, base64
// round-trip storage and de-rendering all run the real Sheets/Code.ts against real Common.
function createOverGridImage(sheet, blob, col, row) {
let altDescription = "";
let altTitle = "";
// REASON: a real server render comes back at \dpi{900}, so the OverGridImage's
// natural size is huge (hundreds of px tall). Model that, otherwise a test cannot
// tell whether the code scales the image down for the cell or leaves it native.
let height = 520;
let width = 1400;
const image = {
blob,
anchorCol: col,
anchorRow: row,
removed: false,
setAnchorCell(range) { image.anchorCol = range.getColumn(); image.anchorRow = range.getRow(); return image; },
// Real Sheets returns a full Range here; restoreEquationFromImage calls
// getValue/setValue/getA1Notation on it, so a row/col pair is not enough.
getAnchorCell: () => sheet.getRange(image.anchorRow, image.anchorCol),
setAltTextDescription(v) { altDescription = v; return image; },
getAltTextDescription: () => altDescription,
setAltTextTitle(v) { altTitle = v; return image; },
getAltTextTitle: () => altTitle,
getHeight: () => height,
setHeight(v) { height = v; return image; },
getWidth: () => width,
setWidth(v) { width = v; return image; },
remove() { image.removed = true; sheet._images = sheet._images.filter(i => i !== image); },
};
return image;
}

function createSheet(name, sheetId, grid) {
const rows = grid.map(r => r.slice());
const sheet = {
_images: [],
getName: () => name,
getSheetId: () => sheetId,
getMaxRows: () => rows.length,
getMaxColumns: () => Math.max(...rows.map(r => r.length), 1),
// Last row/column with content, matching Sheets semantics (1-based, 0 when empty).
getLastRow: () => {
for (let r = rows.length - 1; r >= 0; r--) {
if ((rows[r] || []).some(c => c !== undefined && String(c) !== "")) return r + 1;
}
return 0;
},
getLastColumn: () => {
let last = 0;
for (const line of rows) {
for (let c = (line || []).length - 1; c >= 0; c--) {
if (line[c] !== undefined && String(line[c]) !== "") { last = Math.max(last, c + 1); break; }
}
}
return last;
},
getActiveRange: () => makeRange(1, 1, rows.length, Math.max(...rows.map(r => r.length), 1)),
getImages: () => sheet._images.slice(),
getDataRange: () => makeRange(1, 1, rows.length, Math.max(...rows.map(r => r.length), 1)),
getRange: (row, col, numRows = 1, numCols = 1) => makeRange(row, col, numRows, numCols),
insertImage(blob, col, row) {
const image = createOverGridImage(sheet, blob, col, row);
sheet._images.push(image);
return image;
},
};
function makeRange(row, col, numRows = 1, numCols = 1) {
return {
row, col,
getRow: () => row,
getColumn: () => col,
getA1Notation: () => String.fromCharCode(64 + col) + row,
getNumRows: () => numRows,
getNumColumns: () => numCols,
getValues: () => Array.from({ length: numRows }, (_, r) =>
Array.from({ length: numCols }, (_, c) => {
const line = rows[row - 1 + r] || [];
const cell = line[col - 1 + c];
return cell === undefined ? "" : cell;
})),
getValue: () => {
const line = rows[row - 1] || [];
return line[col - 1] === undefined ? "" : line[col - 1];
},
setValue(v) {
while (rows.length < row) rows.push([]);
rows[row - 1][col - 1] = v;
return this;
},
// Sheets reads colours for the whole scanned block at once, so this must be a grid.
getFontColors: () => Array.from({ length: numRows }, () =>
Array.from({ length: numCols }, () => "#000000")),
getBackgrounds: () => Array.from({ length: numRows }, () =>
Array.from({ length: numCols }, () => "#ffffff")),
getFontColorObject: () => ({ asRgbColor: () => ({ asHexString: () => "#000000" }) }),
getBackgroundObject: () => ({ asRgbColor: () => ({ asHexString: () => "#ffffff" }) }),
getFontSize: () => 10,
};
}
sheet._rows = rows;
return sheet;
}

// `common` is a vm context produced by tests/helpers/render-matrix.js commonHarness().
function loadSheetsCode(grid, common, { sheetName = "Sheet1", sheetId = 0 } = {}) {
const sheet = createSheet(sheetName, sheetId, grid);
const spreadsheet = {
getSheets: () => [sheet],
getActiveSheet: () => sheet,
getId: () => "test-spreadsheet",
getName: () => "test",
};
const uiCalls = [];
const context = vm.createContext({
Common: common,
console: { log() {}, warn() {}, error() {} },
SpreadsheetApp: {
getActiveSpreadsheet: () => spreadsheet,
getUi: () => ({
createAddonMenu: () => ({ addItem: () => ({ addToUi() { uiCalls.push("menu"); } }) }),
showSidebar: () => uiCalls.push("sidebar"),
}),
},
Utilities: {
base64Encode: s => Buffer.from(String(s), "utf8").toString("base64"),
base64Decode: s => Array.from(Buffer.from(String(s), "base64")),
// restoreEquationFromImage decodes the alt text through newBlob().getDataAsString().
newBlob: bytes => ({
bytes,
getBytes: () => bytes,
getDataAsString: () => Buffer.from(bytes).toString("utf8"),
}),
sleep() {},
},
ScriptApp: {
AuthMode: { FULL: "FULL", LIMITED: "LIMITED", NONE: "NONE" },
getAuthorizationInfo: () => ({
getAuthorizationStatus: () => "NOT_REQUIRED",
getAuthorizationUrl: () => null,
}),
},
Session: { getTemporaryActiveUserKey: () => "test-user" },
});
vm.runInContext(compileScript(sheetsCodePath), context, { filename: "Sheets.harness.js" });
return { context, sheet, spreadsheet, uiCalls, rows: () => sheet._rows };
}

module.exports = { loadSheetsCode, createSheet };
107 changes: 107 additions & 0 deletions tests/sheets-render.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { commonHarness } = require('./helpers/render-matrix');
const { loadSheetsCode } = require('./helpers/sheets-harness');

// Sheets had no test coverage at all before this file, which is why its behaviour was
// only ever checked by hand in a live spreadsheet. These run the real Sheets/Code.ts
// against the real Common library; only the SpreadsheetApp boundary is doubled.

function setup(grid) {
const harness = commonHarness();
const doc = loadSheetsCode(grid, harness.common);
return { ...harness, ...doc };
}

test('server renderer replaces a whole-cell equation with an anchored image', () => {
const { context, sheet, urls } = setup([['$$1+1=2$$'], ['plain text']]);
const result = context.replaceEquations('smart', '$$', 'codecogs');

assert.equal(result.successCount, 1, 'exactly the one equation cell renders');
assert.equal(result.failureCount, 0);
assert.equal(sheet.getImages().length, 1, 'one image inserted');
assert.ok(urls.some(u => u.includes('codecogs')), 'explicit renderer choice is honoured');
// Anchored to the originating cell, not left at absolute pixel coordinates.
const image = sheet.getImages()[0];
assert.equal(image.getAnchorCell().getRow(), 1);
assert.equal(image.getAnchorCell().getColumn(), 1);
});

test('the original cell text is recoverable from the image alt text', () => {
const source = '$$\\frac{a}{b}$$';
const { context, sheet } = setup([[source]]);
context.replaceEquations('smart', '$$', 'codecogs');

const alt = sheet.getImages()[0].getAltTextDescription();
assert.match(alt, /^ALE-Latex:/, 'alt text carries the round-trip prefix');
const decoded = Buffer.from(alt.replace(/^ALE-Latex:/, ''), 'base64').toString('utf8');
assert.equal(decoded, source, 'base64 payload reconstructs the exact authored cell');
});

test('de-render restores the authored text and removes the image', () => {
const source = '$$x^2$$';
const { context, sheet, rows } = setup([[source]]);
context.replaceEquations('smart', '$$', 'codecogs');
assert.equal(sheet.getImages().length, 1);

const restored = context.removeAll('$$');
assert.equal(restored, 1, 'one equation de-rendered');
assert.equal(sheet.getImages().length, 0, 'image removed');
assert.equal(rows()[0][0], source, 'cell text restored character for character');
});

test('a cell mixing prose with an equation is left alone', () => {
// Documented Sheets limitation: equations are whole-cell only.
const { context, sheet, rows } = setup([['before $$x^2$$ after']]);
const result = context.replaceEquations('smart', '$$', 'codecogs');

assert.equal(result.successCount, 0, 'partial-cell equations are not rendered');
assert.equal(sheet.getImages().length, 0);
assert.equal(rows()[0][0], 'before $$x^2$$ after', 'the cell is untouched');
});

test('Automatic and MathJax hand equations to the client instead of fetching', () => {
for (const renderer of ['auto', 'mathjax']) {
const { context, urls, sheet } = setup([['$$1+1=2$$']]);
const result = context.replaceEquations('smart', '$$', renderer);

assert.equal(urls.length, 0, `${renderer} must not hit a server renderer`);
assert.equal(sheet.getImages().length, 0, `${renderer} defers image placement to the client`);
assert.equal(result.clientEquations.length, 1, `${renderer} returns the equation to the sidebar`);
assert.equal(decodeURIComponent(result.clientEquations[0].equationLinkEncoded ?? '1+1=2'), '1+1=2');
}
});

test('the retired Sciweavers renderer is unreachable from Sheets', () => {
const { context, urls } = setup([['$$1+1=2$$']]);
context.replaceEquations('smart', '$$', 'codecogs');
for (const url of urls) {
assert.ok(!url.includes('sciweavers.org'), `must not request sciweavers: ${url}`);
}
});

test('every equation cell in a multi-row sheet renders once', () => {
const { context, sheet } = setup([['$$a$$'], ['$$b$$'], [''], ['$$c$$']]);
const result = context.replaceEquations('smart', '$$', 'codecogs');

assert.equal(result.successCount, 3, 'three equation cells, blank row skipped');
assert.equal(sheet.getImages().length, 3);
const anchoredRows = sheet.getImages().map(i => i.getAnchorCell().getRow()).sort();
assert.deepEqual(anchoredRows, [1, 2, 4], 'each image anchors to its own source row');
});

test('Automatic size scales the rendered image down to the cell, not native 900dpi', () => {
// A server render arrives at \dpi{900}; inserted unscaled it spans ~14 rows and
// overlaps neighbouring equations. Automatic must size it like the cell's text.
const { context, sheet } = setup([['$$1+1=2$$']]);
context.replaceEquations('smart', '$$', 'codecogs');

const image = sheet.getImages()[0];
// One default Sheets row is ~21px; anything taller overlaps the next equation.
assert.ok(image.getHeight() <= 30,
`Automatic must fit about one row, got ${image.getHeight()}px tall`);
// Aspect ratio must be preserved — setHeight alone stretches an OverGridImage.
const ratio = image.getWidth() / image.getHeight();
assert.ok(Math.abs(ratio - (1400 / 520)) < 0.1,
`aspect ratio must be preserved, got ${ratio.toFixed(2)}`);
});
Loading