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
23 changes: 23 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Regression tests

on:
pull_request:
push:
branches: [master]

permissions:
contents: read

jobs:
tests:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci --ignore-scripts
- run: npm run build-sidebar-js --workspace slides
- run: npm test
41 changes: 27 additions & 14 deletions Slides/Code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@

type PageElement = GoogleAppsScript.Slides.Shape | GoogleAppsScript.Slides.TableCell;

// REASON: Common's const enum is erased from its published JavaScript. Clasp's
// isolated transpilation leaves Common.DerenderResult accesses at runtime, so
// both de-render actions crash even with an image selected. Keep these local
// values aligned with AutoLatexCommon.DerenderResult (the sidebar wire format).
const enum SlidesDerenderResult {
CursorNotFound = 0,
EmptyEquation = 1,
InvalidUrl = 2,
NonExistentElement = 3,
NullUrl = 4,
Success = 5
}

interface DerenderData {
red: number,
green: number,
Expand Down Expand Up @@ -1442,7 +1455,7 @@ function removeAll(defaultDelimRaw: string) {
const defaultDelim = Common.getDelimiters(defaultDelimRaw);
for (const slide of IntegratedApp.getBody()) {
for (const image of slide.getImages()) {
if (derenderImage(image, defaultDelim, slide) === Common.DerenderResult.Success) counter++;
if (derenderImage(image, defaultDelim, slide) === SlidesDerenderResult.Success) counter++;
}
}
return counter;
Expand All @@ -1460,14 +1473,14 @@ function derenderImage(image: GoogleAppsScript.Slides.Image, defaultDelim: AutoL
// bail out cleanly so the iteration in removeAll just skips this one.
const rawTitle = image.getTitle();
if (!rawTitle || !rawTitle.trim()) {
return Common.DerenderResult.InvalidUrl;
return SlidesDerenderResult.InvalidUrl;
}
let derenderData: DerenderData | [number, number, number, string, number];
try {
derenderData = JSON.parse(rawTitle);
} catch (err) {
console.log("derenderImage: image title is not Auto-LaTeX JSON; skipping.", rawTitle, err);
return Common.DerenderResult.InvalidUrl;
return SlidesDerenderResult.InvalidUrl;
}

if (Array.isArray(derenderData)) {
Expand All @@ -1492,7 +1505,7 @@ function derenderImage(image: GoogleAppsScript.Slides.Image, defaultDelim: AutoL

Common.debugLog("image description is: " + origURL);

if (!origURL) return Common.DerenderResult.NullUrl;
if (!origURL) return SlidesDerenderResult.NullUrl;

Common.debugLog("Original URL from image", origURL);
// REASON: same escape()-era %uXXXX guard as Docs — decodeURIComponent rejects those
Expand All @@ -1502,15 +1515,15 @@ function derenderImage(image: GoogleAppsScript.Slides.Image, defaultDelim: AutoL
result = Common.derenderEquation(origURL, IntegratedApp);
} catch (err) {
console.error("derenderImage: failed to decode equation URL; skipping image.", String(err), " url=", String(origURL).substring(0, 500));
return Common.DerenderResult.InvalidUrl;
return SlidesDerenderResult.InvalidUrl;
}
if (!result) return Common.DerenderResult.InvalidUrl;
if (!result) return SlidesDerenderResult.InvalidUrl;
const { delim: newDelim, origEq } = result;
const delim = newDelim || defaultDelim;

if (origEq.length <= 0) {
console.log("Empty equation derender.");
return Common.DerenderResult.EmptyEquation;
return SlidesDerenderResult.EmptyEquation;
}

const equationText = delim[0] + origEq + delim[1];
Expand All @@ -1521,7 +1534,7 @@ function derenderImage(image: GoogleAppsScript.Slides.Image, defaultDelim: AutoL
if (derenderData.spaceCount && derenderData.pageElementId) {
if (restoreEquationIntoSpaceGap(slide, derenderData, equationText, colors, size)) {
image.remove();
return Common.DerenderResult.Success;
return SlidesDerenderResult.Success;
}
// gap not found (box deleted or spaces edited) — fall through to the legacy new-box path
}
Expand All @@ -1543,7 +1556,7 @@ function derenderImage(image: GoogleAppsScript.Slides.Image, defaultDelim: AutoL

Common.debugLog("textRange: " + textRange + "type: " + typeof textRange);

return Common.DerenderResult.Success;
return SlidesDerenderResult.Success;
}

// Find where to reinsert an equation over its placeholder spaces. The `count` placeholder spaces
Expand Down Expand Up @@ -1636,22 +1649,22 @@ function editEquations(sizeRaw: string, delimiter: string, renderer: string = "a
.filter(el => el.getPageElementType() === SlidesApp.PageElementType.IMAGE)
.map(el => el.asImage());
if (images.length === 0) {
return { result: Common.DerenderResult.NonExistentElement, successCount: 0 };
return { result: SlidesDerenderResult.NonExistentElement, successCount: 0 };
}
let successCount = 0;
let lastFailureResult = Common.DerenderResult.InvalidUrl;
let lastFailureResult = SlidesDerenderResult.InvalidUrl;
for (const image of images) {
const result = derenderImage(image, defaultDelim, currentPage);
if (result === Common.DerenderResult.Success) {
if (result === SlidesDerenderResult.Success) {
successCount++;
} else {
lastFailureResult = result;
}
}
return successCount > 0
? { result: Common.DerenderResult.Success, successCount }
? { result: SlidesDerenderResult.Success, successCount }
: { result: lastFailureResult, successCount: 0 };
} else {
return { result: Common.DerenderResult.CursorNotFound, successCount: 0 };
return { result: SlidesDerenderResult.CursorNotFound, successCount: 0 };
}
}
16 changes: 12 additions & 4 deletions Slides/Sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,14 @@ function insertText(){
}


function showDerenderFailure(error: any) {
// REASON: server exceptions are not selection errors. Preserve their details
// as escaped text so permissions/service failures can actually be diagnosed.
const detail = typeof error === "string" ? error : error?.message || "Unknown server error.";
console.error("Slides de-render failed.", error);
showError("Could not de-render equations. " + $("<div>").text(detail).html(), "Status: Error, de-render failed.");
}

function editText(){
this.disabled = true;
$('#error').remove();
Expand Down Expand Up @@ -508,7 +516,7 @@ function editText(){
function(msg, element) {
$("#loading").html('');
clearInterval(runDots);
showError("Please select equation image to be derendered.", "Status: Error, please select equation to be derendered.");
showDerenderFailure(msg);
element.disabled = false;
})
.withUserObject(this)
Expand Down Expand Up @@ -547,7 +555,7 @@ function undoAll(){
function(msg, element) {
$("#loading").html('');
clearInterval(runDots);
showError("Please select image.", "Status: Error, please select image.");
showDerenderFailure(msg);
element.disabled = false;
})
.withUserObject(this)
Expand Down Expand Up @@ -602,10 +610,10 @@ $(document).keydown(function(e){
$("#loading").html("Status: " + returnSuccess + " equations de-rendered.");
})
.withFailureHandler(
function() {
function(msg) {
$("#loading").html('');
clearInterval(runDots);
showError("Please select image.", "Status: Error, please select image.");
showDerenderFailure(msg);
})
.removeAll(delimiter);
}
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"homepage": "https://github.com/Divide-By-0/autolatex#readme",
"scripts": {
"test": "node --test tests/*.test.js",
"test:docs": "node --test tests/docs-dollar-pairing.test.js"
"test:docs": "node --test tests/docs-*.test.js",
"test:slides": "node --test tests/slides-*.test.js"
},
"devDependencies": {
"@grimsteel/clasp-types": "^1.7.3",
Expand Down
48 changes: 48 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Regression tests

Run `npm ci --ignore-scripts` and `npm test` from a clean checkout. GitHub
Actions runs the same commands for pull requests and pushes to master on Node 22.
Use `npm run test:docs` or `npm run test:slides` for the app-specific suites.

Coverage includes Docs delimiter pairing and image-insertion failure safety,
Slides delimiter pairing and MathJax background selection, shared MathJax
startup/render deadlines, and Workspace single-dollar rendering.

Slides de-render regressions exercise both public server actions with compiled
Common code (no runtime `DerenderResult` export), multiple/legacy images and
selection errors. Sidebar tests invoke both buttons through a failing RPC and
check that the real error is escaped, displayed, and the button re-enabled.
CI also builds the Slides sidebar. To replay against read-only downloads of an
Apps Script project and its pinned Common version, set `ALE_SLIDES_JS` and
`ALE_COMMON_JS` to their absolute `Code.js` paths and run
`node --test tests/slides-derender.test.js`.

The September de-render failure reproduced against remote Slides project HEAD
and Common v8: `Common.DerenderResult` was undefined at the selected-image
breakpoint despite one IMAGE in a PAGE_ELEMENT selection. The v7 deployment
inlines constants correctly, so this reproduction does not establish the
reporter's installed version. Keep the local Slides enum aligned with the
sidebar's `AutoLatexCommon.DerenderResult` values; full-program TypeScript builds
and isolated transpilation must both work.

These are local Node tests with Apps Script contract doubles, not live Google
Docs/Slides integration tests. They do not prove image appearance, authorization,
or actual Google range behavior. Some older tests inspect source structure or
simulate round-trips; do not describe those as full render/de-render coverage.
Docs tests currently load the committed `Docs/Code.js`; keep it synchronized
with TypeScript changes. The Slides delimiter and Workspace tests compile tracked
TypeScript in memory through `helpers/compile-script.js`.

For interactive debugging, run, for example:

```sh
node inspect --port=19348 tests/workspace-dollar-pairing.test.js
```

Set a breakpoint with `sb(lineNumber)`, continue with `cont`, and inspect values
with `exec expression`. Use an unused port and exit the debugger when finished.

The initial clean-checkout run on `f26d04d` passed 29 tests and failed two:
the Workspace harness read ignored `Workspace/Docs.js`. A breakpoint at its
file read confirmed `exists: false` for input `$1$`. Compiling `Workspace/Docs.ts`
in memory fixes the harness dependency; both existing regression tests then pass.
13 changes: 13 additions & 0 deletions tests/helpers/compile-script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const fs = require("node:fs");
const ts = require("typescript");

// NOTE: Apps Script build outputs can be ignored or stale in a clean checkout.
// Compile tracked source in memory so tests exercise the code being reviewed.
function compileScript(filename) {
return ts.transpileModule(fs.readFileSync(filename, "utf8"), {
fileName: filename,
compilerOptions: { target: ts.ScriptTarget.ES2020 },
}).outputText;
}

module.exports = { compileScript };
75 changes: 75 additions & 0 deletions tests/helpers/slides-derender-harness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const root = path.join(__dirname, '../..');

// Model the library boundary using a full emit: transpileModule preserves const
// enums and would invent the very runtime export that production Common lacks.
function compileCommon() {
const outputs = [];
const program = ts.createProgram(['Common/Unicode.ts', 'Common/Code.ts'].map(p => path.join(root, p)), {
target: ts.ScriptTarget.ES5, skipLibCheck: true, types: [],
});
program.emit(undefined, (filename, text) => {
if (filename.endsWith('.js')) outputs.push(text);
});
return outputs.join('\n');
}
const commonSource = process.env.ALE_COMMON_JS
? fs.readFileSync(process.env.ALE_COMMON_JS, 'utf8') : compileCommon();
const slidesFilename = process.env.ALE_SLIDES_JS || path.join(root, 'Slides/Code.ts');
const slidesSource = process.env.ALE_SLIDES_JS
? fs.readFileSync(slidesFilename, 'utf8')
: ts.transpileModule(fs.readFileSync(slidesFilename, 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES5 },
}).outputText;

function harness(titles, selectionType = 'PAGE_ELEMENT') {
const restored = [];
const common = vm.createContext({
console,
PropertiesService: { getUserProperties: () => ({ setProperty() {} }) },
});
vm.runInContext(commonSource, common, { filename: 'Common.runtime.js' });
const images = titles.map(title => ({
removed: false,
getTitle: () => title,
getLeft: () => 10, getTop: () => 20,
getWidth: () => 100, getHeight: () => 30,
getPageElementType: () => 'IMAGE',
asImage() { return this; },
remove() { this.removed = true; },
}));
const style = { setForegroundColor() { return this; }, setFontSize() { return this; } };
const slide = {
getImages: () => images.filter(image => !image.removed),
insertShape: () => ({ getText: () => ({ insertText: (_offset, text) => {
restored.push(text);
return { getTextStyle: () => style };
} }) }),
};
const selection = {
getCurrentPage: () => slide,
getSelectionType: () => selectionType,
getPageElementRange: () => ({ getPageElements: () => images }),
};
const runtime = vm.createContext({
Common: common, console,
SlidesApp: {
getActivePresentation: () => ({ getSlides: () => [slide], getSelection: () => selection }),
SelectionType: { PAGE_ELEMENT: 'PAGE_ELEMENT' },
PageElementType: { IMAGE: 'IMAGE' },
ShapeType: { TEXT_BOX: 'TEXT_BOX' },
},
});
vm.runInContext(slidesSource, runtime, { filename: slidesFilename });
return { runtime, common, images, restored };
}

function equationTitle() {
return JSON.stringify({ red: 0, green: 0, blue: 0,
origURL: 'https://www.codecogs.com/eqnedit.php?latex=x%2B1#0',
size: 14, width: 100, height: 30 });
}
module.exports = { harness, equationTitle };
56 changes: 56 additions & 0 deletions tests/slides-derender-sidebar.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const test = require('node:test');
const ts = require('typescript');
const filename = process.env.ALE_SLIDES_SIDEBAR_TS || path.join(__dirname, '../Slides/Sidebar.ts');
const source = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES2020 },
}).outputText;

for (const action of ['editText', 'undoAll']) {
test(`Slides ${action} displays the actual RPC failure and re-enables its button`, () => {
const elements = new Map();
let displayedError;
let failure;
let button;
let stopped = false;
const escapeHtml = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const $ = selector => {
if (!elements.has(selector)) {
let content = '';
const element = {
ready() {}, click() {}, keydown() {}, remove() {},
text(value) { content = escapeHtml(value); return this; },
html(value) { if (value === undefined) return content; content = value; return this; },
after(value) { displayedError = value; },
};
elements.set(selector, element);
}
// showError passes its error div HTML to jQuery.
return typeof selector === 'string' && selector.startsWith('<div id="error"') ? selector : elements.get(selector);
};
const run = {
withSuccessHandler() { return this; },
withFailureHandler(callback) { failure = callback; return this; },
withUserObject(value) { button = value; return this; },
editEquations() { failure({ message: 'Service unavailable <retry>' }, button); },
removeAll() { failure({ message: 'Service unavailable <retry>' }, button); },
};
const runtime = vm.createContext({
$, window: {}, google: { script: { run } }, console: { error() {} },
document: { createElement: () => ({ getContext: () => null }) },
setInterval: () => 1, clearInterval: () => { stopped = true; },
});
vm.runInContext(source, runtime, { filename });
runtime.getCurrentSettings = () => ({ sizeRaw: '14', delimiter: '$$', renderer: 'auto' });
const clicked = { disabled: false };
runtime[action].call(clicked);
assert.match(displayedError, /Service unavailable &lt;retry&gt;/);
assert.doesNotMatch(displayedError, /Please select/);
assert.equal($('#loading').html(), 'Status: Error, de-render failed.');
assert.equal(clicked.disabled, false);
assert.equal(stopped, true);
});
}
Loading
Loading