diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 03f7b94..890789f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -19,6 +19,7 @@ jobs: node-version: 22 cache: npm - run: npm ci --ignore-scripts + - run: npm run build-sidebar-js --workspace docs - run: npm run build-sidebar-js --workspace slides - run: npm test diff --git a/Docs/ALEStylesheet.html b/Docs/ALEStylesheet.html index 4e9ceca..e28d23e 100644 --- a/Docs/ALEStylesheet.html +++ b/Docs/ALEStylesheet.html @@ -22,6 +22,7 @@ #renderer { max-width: 180px; } + /* Dropdown Button */ .dropbtn { background-color: #4caf50; diff --git a/Docs/Code.js b/Docs/Code.js index 15febde..c3fd368 100644 --- a/Docs/Code.js +++ b/Docs/Code.js @@ -15,6 +15,12 @@ var __assign = (this && this.__assign) || function () { }; /* exported onOpen, showSidebar, replaceEquations */ var DEBUG = false; //doing ctrl + m to get key to see errors is still needed; DEBUG is for all nondiagnostic information +// REASON: The image description itself cannot tell us whether it came from an explicit +// `_{...}` suffix or the automatic raw-LaTeX fallback. Keep a tiny flag in the existing +// equation link so de-rendering restores only explicit suffixes. It is appended to the +// existing fragment (never sent to the linked renderer) and stripped before +// Common.derenderEquation sees the URL. +var CUSTOM_ALT_TEXT_LINK_MARKER = "&ale_custom_alt=1"; function getDocsApp() { return { getUi: function () { @@ -137,6 +143,8 @@ function renderEquationWithCompatibility(equationOriginal, renderOptions) { function replaceEquations(sizeRaw, delimiter, renderer) { if (renderer === void 0) { renderer = "auto"; } var quality = 900; + // REASON: Custom descriptions are always enabled, including requests from older + // sidebars that still send a fourth argument or have an obsolete saved preference. var clientRender = renderer === "mathjax"; // REASON: In auto mode, start with MathJax on the client (never Codecogs first — // both because a Codecogs outage can hang UrlFetchApp long enough for @@ -597,11 +605,63 @@ function findPos(index, renderOptions, prevFailedStartElemIfIsEmpty) { } }; } - // REASON: pass endElement (the closing-delimiter findText result) so the deferred MathJax path + var equationRangeElement = range.getRangeElements()[0]; + var replacementRangeElement = equationRangeElement; + var nextStartElement = endElement; + var customAltText; + var suffix = getAccessibleAltTextSuffix(endElement); + if (suffix) { + var doc = getDocsApp().getActive(); + replacementRangeElement = doc.newRange() + .addElement(equationRangeElement.getElement().asText(), equationRangeElement.getStartOffset(), suffix.endOffsetInclusive) + .build() + .getRangeElements()[0]; + // REASON: while MathJax images render asynchronously, the suffix remains in the + // document. Resume after it so `$` or delimiter-like prose inside the description + // cannot be mistaken for another equation during the same scan. + nextStartElement = doc.newRange() + .addElement(equationRangeElement.getElement().asText(), suffix.endOffsetInclusive, suffix.endOffsetInclusive) + .build() + .getRangeElements()[0]; + customAltText = suffix.description; + } + // REASON: pass endElement (or the end of an explicit alt-text suffix) so the deferred MathJax path // can resume the scan strictly after this equation. Resuming from the equation span instead // (which starts at the opening delimiter) makes findText re-find this equation's own closing // `$` and pair it forward — see buildClientRenderResponse. - return findEquationAndPlaceImage(range.getRangeElements()[0], renderOptions, endElement); + return findEquationAndPlaceImage(equationRangeElement, replacementRangeElement, renderOptions, nextStartElement, customAltText); +} +// Parse an immediately-adjacent `_{...}` accessibility suffix. Nested braces are allowed, +// and escaped braces do not affect balancing. Malformed or empty suffixes are ordinary doc +// text and are deliberately left untouched. +function getAccessibleAltTextSuffix(endElement) { + var text = endElement.getElement().asText().getText(); + var suffixStart = endElement.getEndOffsetInclusive() + 1; + if (text.substring(suffixStart, suffixStart + 2) !== "_{") { + return null; + } + var depth = 1; + for (var i = suffixStart + 2; i < text.length; i++) { + var slashCount = 0; + for (var j = i - 1; j >= 0 && text.charAt(j) === "\\"; j--) { + slashCount++; + } + var escaped = slashCount % 2 === 1; + var char = text.charAt(i); + if (!escaped && char === "{") { + depth++; + } + else if (!escaped && char === "}") { + depth--; + if (depth === 0) { + var description = text.substring(suffixStart + 2, i); + return description.trim() === "" + ? null + : { description: description, endOffsetInclusive: i }; + } + } + } + return null; } function getEquation(rangeElement, delimiters) { var textElement = rangeElement.getElement().asText(); @@ -676,7 +736,7 @@ function clientRenderComplete(equations) { continue; } var equationBlob = Utilities.newBlob(Utilities.base64Decode(equation.renderedEquationB64), "image/png"); - var result = placeImage(rangeElements[0], equationBlob, mathjaxRenderer, equation.options.equationLinkEncoded, equation.options.size, equation.options.delim); + var result = placeImage(rangeElements[0], equationBlob, mathjaxRenderer, equation.options.equationLinkEncoded, equation.options.size, equation.options.delim, equation.options.customAltText); if (result.status === 8 /* DocsEquationRenderStatus.Success */) { c++; } @@ -709,23 +769,23 @@ function clientRenderComplete(equations) { * @param {integer} defaultSize The default/previous size of the text, in case size is null. * @param {string} delim[6] The text delimiters and regex delimiters for start and end in that order, and offset from front and back. */ -function findEquationAndPlaceImage(startElement, renderOptions, endElement) { +function findEquationAndPlaceImage(equationElement, replacementElement, renderOptions, nextStartElement, customAltText) { Common.reportDeltaTime(411); Common.reportDeltaTime(413); // GET VARIABLES - var textElement = startElement.getElement().asText(); - var size = getSize(renderOptions.size, renderOptions.defaultSize, startElement); - var equationOriginal = getEquation(startElement, renderOptions.delim); + var textElement = equationElement.getElement().asText(); + var size = getSize(renderOptions.size, renderOptions.defaultSize, equationElement); + var equationOriginal = getEquation(equationElement, renderOptions.delim); if (equationOriginal == "") { - console.log("No equation but undetected start and end as ", startElement.getStartOffset(), " ", startElement.getEndOffsetInclusive()); + console.log("No equation but undetected start and end as ", equationElement.getStartOffset(), " ", equationElement.getEndOffsetInclusive()); return { status: 3 /* DocsEquationRenderStatus.EmptyEquation */, // TODO: this _should_ be impossible - empty equations should be detected in findPos() - nextStartElement: startElement + nextStartElement: equationElement }; } // get font color - var colorHex = textElement.getForegroundColor(startElement.getStartOffset()); + var colorHex = textElement.getForegroundColor(equationElement.getStartOffset()); // Docs can return null or malformed colors in some edge cases. Fall back to black. var _a = getRgbFromHex(colorHex), r = _a[0], g = _a[1], b = _a[2]; // REASON: users build dark documents by highlighting text with a dark background @@ -733,14 +793,14 @@ function findEquationAndPlaceImage(startElement, renderOptions, endElement) { // highlight band, making light-colored equations invisible. Sample the text's // background color so the client bakes it into the image. No highlight (null) // keeps the image transparent, exactly as before. - var bgHex = textElement.getBackgroundColor(startElement.getStartOffset()); + var bgHex = textElement.getBackgroundColor(equationElement.getStartOffset()); var bgColor = bgHex ? getRgbFromHex(bgHex) : null; // add color info to render options var coloredRenderOptions = __assign(__assign(__assign({}, renderOptions), { r: r, g: g, b: b }), (bgColor ? { bgR: bgColor[0], bgG: bgColor[1], bgB: bgColor[2] } : {})); // REASON: Explicit MathJax and Automatic both render on the client first. // Automatic falls back to server renderers from the sidebar only if MathJax fails. if (renderOptions.clientRender || renderOptions.autoFallbackToClient) { - return buildClientRenderResponse(textElement, startElement, equationOriginal, coloredRenderOptions, size, endElement); + return buildClientRenderResponse(textElement, replacementElement, equationOriginal, coloredRenderOptions, size, nextStartElement, customAltText); } var _b = renderEquationWithCompatibility(equationOriginal, coloredRenderOptions), resp = _b.resp, renderer = _b.renderer, worked = _b.worked, authorizationError = _b.authorizationError; if (worked > Common.capableRenderers || !resp || !renderer) @@ -753,9 +813,9 @@ function findEquationAndPlaceImage(startElement, renderOptions, endElement) { renderer = Common.getRenderer(Common.rendererIds.CODECOGS); } Common.reportDeltaTime(517); - return placeImage(startElement, resp.getBlob(), renderer, equationOriginal, size, renderOptions.delim); + return placeImage(replacementElement, resp.getBlob(), renderer, equationOriginal, size, renderOptions.delim, customAltText); } -function buildClientRenderResponse(textElement, startElement, equationOriginal, coloredRenderOptions, size, endElement) { +function buildClientRenderResponse(textElement, startElement, equationOriginal, coloredRenderOptions, size, nextStartElement, customAltText) { // REASON: reEncode turns each in-equation newline into an encoded four-backslash // marker ("%5C%5C%5C%5C%20"), which must collapse back to a "\\ " row break for the // client renderer. Collapse it in ENCODED space (exactly like the Codecogs path in @@ -772,7 +832,7 @@ function buildClientRenderResponse(textElement, startElement, equationOriginal, .build(); // save this range for later (used by clientRenderComplete to place the image) var namedRange = doc.addNamedRange("ale-equation-range", range); - // REASON: resume the scan from the CLOSING-delimiter findText result (endElement), NOT from a + // REASON: resume the scan from the CLOSING-delimiter findText result (nextStartElement), NOT from a // range derived from the equation span. findText(pattern, from) continues from `from`'s // position; for single-`$` the opening and closing delimiter are the same character, so if we // resume from anything anchored at the OPENING delimiter (the whole-equation range, the @@ -783,9 +843,9 @@ function buildClientRenderResponse(textElement, startElement, equationOriginal, // after it on the following equation's opening delimiter. This mirrors the empty-equation path, // which already resumes from endElement. (A previous fix re-read the named range's span here and // passed the unit tests, but that span still starts at the opening `$`, so it mis-paired in - // production — confirmed via the Cloud Logging trace for a live user.) - var nextStartElement = endElement; - var clientRenderOptions = __assign(__assign({}, coloredRenderOptions), { size: size, rangeId: namedRange.getId(), equation: clientEquation, equationLinkEncoded: encodeURIComponent(clientEquation) }); + // production — confirmed via the Cloud Logging trace for a live user.) When a custom alt-text + // suffix is present, findPos supplies a one-character range at the suffix end instead. + var clientRenderOptions = __assign(__assign(__assign({}, coloredRenderOptions), { size: size, rangeId: namedRange.getId(), equation: clientEquation, equationLinkEncoded: encodeURIComponent(clientEquation) }), (customAltText !== undefined ? { customAltText: customAltText } : {})); return { status: 2 /* DocsEquationRenderStatus.ClientRender */, equationSize: size, @@ -839,7 +899,7 @@ function clientRenderFailed(equations) { continue; } var equationBlob = fallbackResult.resp.getBlob(); - var result = placeImage(rangeElements[0], equationBlob, fallbackResult.renderer, equationOriginal, equation.options.size, equation.options.delim); + var result = placeImage(rangeElements[0], equationBlob, fallbackResult.renderer, equationOriginal, equation.options.size, equation.options.delim, equation.options.customAltText); if (result.status === 8 /* DocsEquationRenderStatus.Success */) { c++; } @@ -887,7 +947,7 @@ function findInsertableAncestor(element) { // Log each distinct container type once per execution; the thrown error still carries // the message for the per-equation failure details. var reportedPlaceImageFailureTypes = new Set(); -function placeImage(startElement, renderedEquation, renderer, equation, size, delim) { +function placeImage(startElement, renderedEquation, renderer, equation, size, delim, customAltText) { // GET VARIABLES var textElement = startElement.getElement().asText(); var startOffset = startElement.getStartOffset(); @@ -957,7 +1017,7 @@ function placeImage(startElement, renderedEquation, renderer, equation, size, de try { // Configure and size the image while the source equation is still present. Only // commit the text replacement after all image-side operations have succeeded. - result = repairImage(paragraph, childIndex, size, renderer, delim, renderedEquation, equation); + result = repairImage(paragraph, childIndex, size, renderer, delim, renderedEquation, equation, customAltText); } catch (err) { // REASON: If image configuration fails, remove the uncommitted image and leave the @@ -977,12 +1037,13 @@ function placeImage(startElement, renderedEquation, renderer, equation, size, de paragraph.insertText(childIndex + 2, textCopy); // reinsert text after the image, with all the formatting return result; } -function repairImage(paragraph, childIndex, size, renderer, delim, resp, equationOriginal) { +function repairImage(paragraph, childIndex, size, renderer, delim, resp, equationOriginal, customAltText) { var attemptsToSetImageUrl = 3; Common.reportDeltaTime(552); // 3 seconds!! inserting an inline image takes time while (attemptsToSetImageUrl > 0) { try { - paragraph.getChild(childIndex + 1).asInlineImage().setLinkUrl(renderer[2] + equationOriginal + "#" + delim[6]); //added % delim 6 to keep track of which delimiter was used to render + var customAltMarker = customAltText !== undefined ? CUSTOM_ALT_TEXT_LINK_MARKER : ""; + paragraph.getChild(childIndex + 1).asInlineImage().setLinkUrl(renderer[2] + equationOriginal + "#" + delim[6] + customAltMarker); //added % delim 6 to keep track of which delimiter was used to render break; } catch (err) { @@ -997,9 +1058,27 @@ function repairImage(paragraph, childIndex, size, renderer, delim, resp, equatio throw new Error("Couldn't get equation child!"); // of image immediately after inserting } } + var equationImage = paragraph.getChild(childIndex + 1).asInlineImage(); + var imageAltText = customAltText !== undefined + ? customAltText + : getRawEquationAltText(equationOriginal); + try { + equationImage.setAltDescription(imageAltText); + } + catch (err) { + // REASON: raw LaTeX alt text is a backwards-compatible accessibility improvement, + // not a prerequisite for rendering. If Docs rejects unusually large metadata, keep + // the successfully rendered equation. Explicit custom text is different: deleting its + // source suffix without storing the description would lose user-authored content, so + // fail before the source is removed and let placeImage roll back the uncommitted image. + if (customAltText !== undefined) { + throw err; + } + console.warn("Could not set raw LaTeX image alt text; continuing with the rendered equation.", err); + } Common.reportDeltaTime(570); - var height = paragraph.getChild(childIndex + 1).asInlineImage().getHeight(); - var width = paragraph.getChild(childIndex + 1).asInlineImage().getWidth(); + var height = equationImage.getHeight(); + var width = equationImage.getWidth(); Common.debugLog("Pre-fixing size, width, height: " + size + ", " + width + ", " + height); //only a '1' is rendered as a 100 height (as of 10/20/19, now it is fetched as 90 height). putting an equationrendertime here just doesnt work //SET PROPERTIES OF IMAGE (Height, Width) var oldSize = size; // why use oldsize instead of new size @@ -1037,6 +1116,37 @@ function repairImage(paragraph, childIndex, size, renderer, delim, resp, equatio equationSize: oldSize }; } +function getRawEquationAltText(equationEncoded) { + try { + return Common.getClientEquation(equationEncoded, getDocsApp()); + } + catch (err) { + // Newly rendered equations use encodeURIComponent and should always decode. Preserve + // rendering if a legacy/custom renderer returns an unusual encoding. + console.warn("Could not decode raw LaTeX for image alt text; using the stored equation form.", err); + return equationEncoded; + } +} +function getDocsEquationLinkData(origURL) { + var markerPattern = /&ale_custom_alt=1$/; + return { + equationUrl: origURL.replace(markerPattern, ""), + hasCustomAltText: markerPattern.test(origURL) + }; +} +function getCustomAltTextSuffix(image, hasCustomAltText) { + if (!hasCustomAltText) { + return ""; + } + try { + var description = image.getAltDescription(); + return description ? "_{".concat(description, "}") : ""; + } + catch (err) { + console.warn("Could not read custom image alt text while de-rendering.", err); + return ""; + } +} function getBodyFromIndex(index) { var doc = getDocsApp().getActive(); var p = doc.getBody().getParent(); @@ -1077,13 +1187,14 @@ function removeAll(defaultDelimRaw) { if (image.getLinkUrl() === null) { continue; } + var linkData = getDocsEquationLinkData(origURL); // console.log("Current origURL " + origURL, origURL == "null", origURL === null, typeof origURL, Object.is(origURL, null), null instanceof Object, origURL instanceof Object, origURL instanceof String, !origURL) // console.log("Current origURL " + image.getLinkUrl(), image.getLinkUrl() === null, typeof image.getLinkUrl(), Object.is(image.getLinkUrl(), null), !image.getLinkUrl()) // REASON: same escape()-era %uXXXX guard as derenderInlineImage — one ancient // image must not crash De-render All for the whole document. var result = void 0; try { - result = Common.derenderEquation(origURL, getDocsApp()); + result = Common.derenderEquation(linkData.equationUrl, getDocsApp()); } catch (err) { console.error("removeAll: failed to decode equation URL; skipping image.", String(err), " url=", String(origURL).substring(0, 500)); @@ -1100,7 +1211,7 @@ function removeAll(defaultDelimRaw) { continue; } var parent_2 = image.getParent(); - parent_2.insertText(imageIndex, delim[0] + origEq + delim[1]); //INSERTS DELIMITERS + parent_2.insertText(imageIndex, delim[0] + origEq + delim[1] + getCustomAltTextSuffix(image, linkData.hasCustomAltText)); //INSERTS DELIMITERS image.removeFromParent(); counter += 1; } @@ -1121,13 +1232,14 @@ function derenderInlineImage(image, defaultDelim) { if (!origURL) { return 4 /* Common.DerenderResult.NullUrl */; } + var linkData = getDocsEquationLinkData(origURL); // REASON: images rendered in the escape()-encoding era carry %uXXXX sequences that // decodeURIComponent rejects (URIError: URI malformed). Uncaught, one ancient image // crashed the whole De-render run. Log WITH the URL so the offending encoding is // visible, and skip just this image. var result; try { - result = Common.derenderEquation(origURL, getDocsApp()); + result = Common.derenderEquation(linkData.equationUrl, getDocsApp()); } catch (err) { console.error("derenderInlineImage: failed to decode equation URL; skipping image.", String(err), " url=", String(origURL).substring(0, 500)); @@ -1143,7 +1255,7 @@ function derenderInlineImage(image, defaultDelim) { } var parent = image.getParent(); var imageIndex = parent.getChildIndex(image); - parent.insertText(imageIndex, delim[0] + origEq + delim[1]); //INSERTS DELIMITERS + parent.insertText(imageIndex, delim[0] + origEq + delim[1] + getCustomAltTextSuffix(image, linkData.hasCustomAltText)); //INSERTS DELIMITERS image.removeFromParent(); return 5 /* Common.DerenderResult.Success */; } diff --git a/Docs/Code.ts b/Docs/Code.ts index 62ff7fd..ea36d94 100644 --- a/Docs/Code.ts +++ b/Docs/Code.ts @@ -32,14 +32,33 @@ interface EquationFailureDetail { hint: string; // user-facing remediation suggestion } +interface DocsClientRenderOptions extends AutoLatexCommon.ClientRenderOptions { + customAltText?: string; +} + +interface DocsRenderOptions extends AutoLatexCommon.RenderOptions { +} + interface DocsEquationRenderResult { status: DocsEquationRenderStatus, equationSize?: number, nextStartElement?: GoogleAppsScript.Document.RangeElement, - clientRenderOptions?: AutoLatexCommon.ClientRenderOptions, + clientRenderOptions?: DocsClientRenderOptions, failureDetail?: EquationFailureDetail } +interface AccessibleAltTextSuffix { + description: string; + endOffsetInclusive: number; +} + +// REASON: The image description itself cannot tell us whether it came from an explicit +// `_{...}` suffix or the automatic raw-LaTeX fallback. Keep a tiny flag in the existing +// equation link so de-rendering restores only explicit suffixes. It is appended to the +// existing fragment (never sent to the linked renderer) and stripped before +// Common.derenderEquation sees the URL. +const CUSTOM_ALT_TEXT_LINK_MARKER = "&ale_custom_alt=1"; + interface DocsIntegratedApp extends AutoLatexCommon.IntegratedApp { getActive(): GoogleAppsScript.Document.Document; getBody(): GoogleAppsScript.Document.Body; @@ -191,6 +210,8 @@ function renderEquationWithCompatibility(equationOriginal: string, renderOptions */ function replaceEquations(sizeRaw: string, delimiter: string, renderer: string = "auto") { const quality = 900; + // REASON: Custom descriptions are always enabled, including requests from older + // sidebars that still send a fourth argument or have an obsolete saved preference. const clientRender = renderer === "mathjax"; // REASON: In auto mode, start with MathJax on the client (never Codecogs first — // both because a Codecogs outage can hang UrlFetchApp long enough for @@ -234,7 +255,7 @@ function replaceEquations(sizeRaw: string, delimiter: string, renderer: string = // Surfaced in the sidebar so the user knows we changed their doc on their behalf. let autoFixedCount = 0; - const baseRenderOptions: AutoLatexCommon.RenderOptions = { + const baseRenderOptions: DocsRenderOptions = { size, defaultSize: 11, inline: isInline, @@ -252,7 +273,7 @@ function replaceEquations(sizeRaw: string, delimiter: string, renderer: string = // REASON: Collect equations that need client-side MathJax rendering instead of returning // on the first one. This allows the server scan to finish across the document, then send // ALL MathJax work to the client for parallel rendering. - const clientRenderBatch: AutoLatexCommon.ClientRenderOptions[] = []; + const clientRenderBatch: DocsClientRenderOptions[] = []; const childCount = body.getBody().getParent().getNumChildren(); Common.reportDeltaTime(156); @@ -549,7 +570,7 @@ function buildEquationSnippet(startElement: GoogleAppsScript.Document.RangeEleme } } -function findPos(index: number, renderOptions: AutoLatexCommon.RenderOptions, prevFailedStartElemIfIsEmpty = null): DocsEquationRenderResult { +function findPos(index: number, renderOptions: DocsRenderOptions, prevFailedStartElemIfIsEmpty = null): DocsEquationRenderResult { Common.debugLog("Checking document section index # ", index); Common.reportDeltaTime(195); const docBody = getBodyFromIndex(index); @@ -704,11 +725,69 @@ function findPos(index: number, renderOptions: AutoLatexCommon.RenderOptions, pr }; } - // REASON: pass endElement (the closing-delimiter findText result) so the deferred MathJax path + const equationRangeElement = range.getRangeElements()[0]; + let replacementRangeElement = equationRangeElement; + let nextStartElement = endElement; + let customAltText: string | undefined; + const suffix = getAccessibleAltTextSuffix(endElement); + if (suffix) { + const doc = getDocsApp().getActive(); + replacementRangeElement = doc.newRange() + .addElement( + equationRangeElement.getElement().asText(), + equationRangeElement.getStartOffset(), + suffix.endOffsetInclusive + ) + .build() + .getRangeElements()[0]; + // REASON: while MathJax images render asynchronously, the suffix remains in the + // document. Resume after it so `$` or delimiter-like prose inside the description + // cannot be mistaken for another equation during the same scan. + nextStartElement = doc.newRange() + .addElement(equationRangeElement.getElement().asText(), suffix.endOffsetInclusive, suffix.endOffsetInclusive) + .build() + .getRangeElements()[0]; + customAltText = suffix.description; + } + + // REASON: pass endElement (or the end of an explicit alt-text suffix) so the deferred MathJax path // can resume the scan strictly after this equation. Resuming from the equation span instead // (which starts at the opening delimiter) makes findText re-find this equation's own closing // `$` and pair it forward — see buildClientRenderResponse. - return findEquationAndPlaceImage(range.getRangeElements()[0], renderOptions, endElement); + return findEquationAndPlaceImage(equationRangeElement, replacementRangeElement, renderOptions, nextStartElement, customAltText); +} + +// Parse an immediately-adjacent `_{...}` accessibility suffix. Nested braces are allowed, +// and escaped braces do not affect balancing. Malformed or empty suffixes are ordinary doc +// text and are deliberately left untouched. +function getAccessibleAltTextSuffix(endElement: GoogleAppsScript.Document.RangeElement): AccessibleAltTextSuffix | null { + const text = endElement.getElement().asText().getText(); + const suffixStart = endElement.getEndOffsetInclusive() + 1; + if (text.substring(suffixStart, suffixStart + 2) !== "_{") { + return null; + } + + let depth = 1; + for (let i = suffixStart + 2; i < text.length; i++) { + let slashCount = 0; + for (let j = i - 1; j >= 0 && text.charAt(j) === "\\"; j--) { + slashCount++; + } + const escaped = slashCount % 2 === 1; + const char = text.charAt(i); + if (!escaped && char === "{") { + depth++; + } else if (!escaped && char === "}") { + depth--; + if (depth === 0) { + const description = text.substring(suffixStart + 2, i); + return description.trim() === "" + ? null + : { description, endOffsetInclusive: i }; + } + } + } + return null; } @@ -759,7 +838,7 @@ function getSize(size: number, defaultSize: number, rangeElement: GoogleAppsScri * @param equations The rendered equations * @public */ -function clientRenderComplete(equations: { options: AutoLatexCommon.ClientRenderOptions, renderedEquationB64: string }[]) { +function clientRenderComplete(equations: { options: DocsClientRenderOptions, renderedEquationB64: string }[]) { const mathjaxRenderer = Common.getRenderer(Common.rendererIds.MATHJAX); let c = 0; let alreadyRenderedCount = 0; @@ -793,7 +872,7 @@ function clientRenderComplete(equations: { options: AutoLatexCommon.ClientRender } const equationBlob = Utilities.newBlob(Utilities.base64Decode(equation.renderedEquationB64), "image/png"); - const result = placeImage(rangeElements[0], equationBlob, mathjaxRenderer, equation.options.equationLinkEncoded, equation.options.size, equation.options.delim); + const result = placeImage(rangeElements[0], equationBlob, mathjaxRenderer, equation.options.equationLinkEncoded, equation.options.size, equation.options.delim, equation.options.customAltText); if (result.status === DocsEquationRenderStatus.Success) { c++; @@ -829,26 +908,32 @@ function clientRenderComplete(equations: { options: AutoLatexCommon.ClientRender * @param {string} delim[6] The text delimiters and regex delimiters for start and end in that order, and offset from front and back. */ -function findEquationAndPlaceImage(startElement: GoogleAppsScript.Document.RangeElement, renderOptions: AutoLatexCommon.RenderOptions, endElement: GoogleAppsScript.Document.RangeElement): DocsEquationRenderResult { +function findEquationAndPlaceImage( + equationElement: GoogleAppsScript.Document.RangeElement, + replacementElement: GoogleAppsScript.Document.RangeElement, + renderOptions: DocsRenderOptions, + nextStartElement: GoogleAppsScript.Document.RangeElement, + customAltText?: string +): DocsEquationRenderResult { Common.reportDeltaTime(411); Common.reportDeltaTime(413); // GET VARIABLES - const textElement = startElement.getElement().asText(); - const size = getSize(renderOptions.size, renderOptions.defaultSize, startElement); - const equationOriginal = getEquation(startElement, renderOptions.delim); + const textElement = equationElement.getElement().asText(); + const size = getSize(renderOptions.size, renderOptions.defaultSize, equationElement); + const equationOriginal = getEquation(equationElement, renderOptions.delim); if (equationOriginal == "") { - console.log("No equation but undetected start and end as ", startElement.getStartOffset(), " ", startElement.getEndOffsetInclusive()); + console.log("No equation but undetected start and end as ", equationElement.getStartOffset(), " ", equationElement.getEndOffsetInclusive()); return { status: DocsEquationRenderStatus.EmptyEquation, // TODO: this _should_ be impossible - empty equations should be detected in findPos() - nextStartElement: startElement + nextStartElement: equationElement }; } // get font color - const colorHex = textElement.getForegroundColor(startElement.getStartOffset()); + const colorHex = textElement.getForegroundColor(equationElement.getStartOffset()); // Docs can return null or malformed colors in some edge cases. Fall back to black. const [r, g, b] = getRgbFromHex(colorHex); @@ -857,7 +942,7 @@ function findEquationAndPlaceImage(startElement: GoogleAppsScript.Document.Range // highlight band, making light-colored equations invisible. Sample the text's // background color so the client bakes it into the image. No highlight (null) // keeps the image transparent, exactly as before. - const bgHex = textElement.getBackgroundColor(startElement.getStartOffset()); + const bgHex = textElement.getBackgroundColor(equationElement.getStartOffset()); const bgColor = bgHex ? getRgbFromHex(bgHex) : null; // add color info to render options @@ -870,7 +955,7 @@ function findEquationAndPlaceImage(startElement: GoogleAppsScript.Document.Range // REASON: Explicit MathJax and Automatic both render on the client first. // Automatic falls back to server renderers from the sidebar only if MathJax fails. if (renderOptions.clientRender || renderOptions.autoFallbackToClient) { - return buildClientRenderResponse(textElement, startElement, equationOriginal, coloredRenderOptions, size, endElement); + return buildClientRenderResponse(textElement, replacementElement, equationOriginal, coloredRenderOptions, size, nextStartElement, customAltText); } let { resp, renderer, worked, authorizationError } = renderEquationWithCompatibility(equationOriginal, coloredRenderOptions); @@ -884,16 +969,17 @@ function findEquationAndPlaceImage(startElement: GoogleAppsScript.Document.Range } Common.reportDeltaTime(517); - return placeImage(startElement, resp.getBlob(), renderer, equationOriginal, size, renderOptions.delim); + return placeImage(replacementElement, resp.getBlob(), renderer, equationOriginal, size, renderOptions.delim, customAltText); } function buildClientRenderResponse( textElement: GoogleAppsScript.Document.Text, startElement: GoogleAppsScript.Document.RangeElement, equationOriginal: string, - coloredRenderOptions: AutoLatexCommon.RenderOptions & { r: number; g: number; b: number }, + coloredRenderOptions: DocsRenderOptions & { r: number; g: number; b: number }, size: number, - endElement: GoogleAppsScript.Document.RangeElement + nextStartElement: GoogleAppsScript.Document.RangeElement, + customAltText?: string ): DocsEquationRenderResult { // REASON: reEncode turns each in-equation newline into an encoded four-backslash // marker ("%5C%5C%5C%5C%20"), which must collapse back to a "\\ " row break for the @@ -911,7 +997,7 @@ function buildClientRenderResponse( .build(); // save this range for later (used by clientRenderComplete to place the image) const namedRange = doc.addNamedRange("ale-equation-range", range); - // REASON: resume the scan from the CLOSING-delimiter findText result (endElement), NOT from a + // REASON: resume the scan from the CLOSING-delimiter findText result (nextStartElement), NOT from a // range derived from the equation span. findText(pattern, from) continues from `from`'s // position; for single-`$` the opening and closing delimiter are the same character, so if we // resume from anything anchored at the OPENING delimiter (the whole-equation range, the @@ -922,14 +1008,15 @@ function buildClientRenderResponse( // after it on the following equation's opening delimiter. This mirrors the empty-equation path, // which already resumes from endElement. (A previous fix re-read the named range's span here and // passed the unit tests, but that span still starts at the opening `$`, so it mis-paired in - // production — confirmed via the Cloud Logging trace for a live user.) - const nextStartElement = endElement; - const clientRenderOptions: AutoLatexCommon.ClientRenderOptions = { + // production — confirmed via the Cloud Logging trace for a live user.) When a custom alt-text + // suffix is present, findPos supplies a one-character range at the suffix end instead. + const clientRenderOptions: DocsClientRenderOptions = { ...coloredRenderOptions, size, rangeId: namedRange.getId(), equation: clientEquation, - equationLinkEncoded: encodeURIComponent(clientEquation) + equationLinkEncoded: encodeURIComponent(clientEquation), + ...(customAltText !== undefined ? { customAltText } : {}) }; return { status: DocsEquationRenderStatus.ClientRender, @@ -944,7 +1031,7 @@ function buildClientRenderResponse( * Tries remaining server-side renderers (Texrendr, Sciweavers) for the failed equations. * @public */ -function clientRenderFailed(equations: { options: AutoLatexCommon.ClientRenderOptions }[]) { +function clientRenderFailed(equations: { options: DocsClientRenderOptions }[]) { let c = 0; let authorizationFailure = false; console.log("MathJax client render failed, trying server fallback for", equations.length, "equations"); @@ -991,7 +1078,7 @@ function clientRenderFailed(equations: { options: AutoLatexCommon.ClientRenderOp } const equationBlob = fallbackResult.resp.getBlob(); - const result = placeImage(rangeElements[0], equationBlob, fallbackResult.renderer, equationOriginal, equation.options.size, equation.options.delim); + const result = placeImage(rangeElements[0], equationBlob, fallbackResult.renderer, equationOriginal, equation.options.size, equation.options.delim, equation.options.customAltText); if (result.status === DocsEquationRenderStatus.Success) { c++; @@ -1042,7 +1129,15 @@ function findInsertableAncestor(element: GoogleAppsScript.Document.Element) { // the message for the per-equation failure details. const reportedPlaceImageFailureTypes = new Set(); -function placeImage(startElement: GoogleAppsScript.Document.RangeElement, renderedEquation: GoogleAppsScript.Base.Blob, renderer: AutoLatexCommon.Renderer, equation: string, size: number, delim: AutoLatexCommon.Delimiter) { +function placeImage( + startElement: GoogleAppsScript.Document.RangeElement, + renderedEquation: GoogleAppsScript.Base.Blob, + renderer: AutoLatexCommon.Renderer, + equation: string, + size: number, + delim: AutoLatexCommon.Delimiter, + customAltText?: string +) { // GET VARIABLES let textElement = startElement.getElement().asText(); const startOffset = startElement.getStartOffset(); @@ -1118,7 +1213,7 @@ function placeImage(startElement: GoogleAppsScript.Document.RangeElement, render try { // Configure and size the image while the source equation is still present. Only // commit the text replacement after all image-side operations have succeeded. - result = repairImage(paragraph, childIndex, size, renderer, delim, renderedEquation, equation); + result = repairImage(paragraph, childIndex, size, renderer, delim, renderedEquation, equation, customAltText); } catch (err) { // REASON: If image configuration fails, remove the uncommitted image and leave the // original equation untouched. Cleanup itself is best-effort during a Docs outage. @@ -1137,12 +1232,22 @@ function placeImage(startElement: GoogleAppsScript.Document.RangeElement, render return result; } -function repairImage(paragraph: GoogleAppsScript.Document.ListItem | GoogleAppsScript.Document.Paragraph, childIndex: number, size: number, renderer: AutoLatexCommon.Renderer, delim: AutoLatexCommon.Delimiter, resp: GoogleAppsScript.Base.Blob, equationOriginal: string): DocsEquationRenderResult { +function repairImage( + paragraph: GoogleAppsScript.Document.ListItem | GoogleAppsScript.Document.Paragraph, + childIndex: number, + size: number, + renderer: AutoLatexCommon.Renderer, + delim: AutoLatexCommon.Delimiter, + resp: GoogleAppsScript.Base.Blob, + equationOriginal: string, + customAltText?: string +): DocsEquationRenderResult { let attemptsToSetImageUrl = 3; Common.reportDeltaTime(552); // 3 seconds!! inserting an inline image takes time while (attemptsToSetImageUrl > 0) { try { - paragraph.getChild(childIndex + 1).asInlineImage().setLinkUrl(renderer[2] + equationOriginal + "#" + delim[6]); //added % delim 6 to keep track of which delimiter was used to render + const customAltMarker = customAltText !== undefined ? CUSTOM_ALT_TEXT_LINK_MARKER : ""; + paragraph.getChild(childIndex + 1).asInlineImage().setLinkUrl(renderer[2] + equationOriginal + "#" + delim[6] + customAltMarker); //added % delim 6 to keep track of which delimiter was used to render break; } catch (err) { console.log("Couldn't insert child index!"); @@ -1157,9 +1262,27 @@ function repairImage(paragraph: GoogleAppsScript.Document.ListItem | GoogleAppsS } } + const equationImage = paragraph.getChild(childIndex + 1).asInlineImage(); + const imageAltText = customAltText !== undefined + ? customAltText + : getRawEquationAltText(equationOriginal); + try { + equationImage.setAltDescription(imageAltText); + } catch (err) { + // REASON: raw LaTeX alt text is a backwards-compatible accessibility improvement, + // not a prerequisite for rendering. If Docs rejects unusually large metadata, keep + // the successfully rendered equation. Explicit custom text is different: deleting its + // source suffix without storing the description would lose user-authored content, so + // fail before the source is removed and let placeImage roll back the uncommitted image. + if (customAltText !== undefined) { + throw err; + } + console.warn("Could not set raw LaTeX image alt text; continuing with the rendered equation.", err); + } + Common.reportDeltaTime(570); - const height = paragraph.getChild(childIndex + 1).asInlineImage().getHeight(); - const width = paragraph.getChild(childIndex + 1).asInlineImage().getWidth(); + const height = equationImage.getHeight(); + const width = equationImage.getWidth(); Common.debugLog("Pre-fixing size, width, height: " + size + ", " + width + ", " + height); //only a '1' is rendered as a 100 height (as of 10/20/19, now it is fetched as 90 height). putting an equationrendertime here just doesnt work //SET PROPERTIES OF IMAGE (Height, Width) @@ -1203,6 +1326,38 @@ function repairImage(paragraph: GoogleAppsScript.Document.ListItem | GoogleAppsS }; } +function getRawEquationAltText(equationEncoded: string): string { + try { + return Common.getClientEquation(equationEncoded, getDocsApp()); + } catch (err) { + // Newly rendered equations use encodeURIComponent and should always decode. Preserve + // rendering if a legacy/custom renderer returns an unusual encoding. + console.warn("Could not decode raw LaTeX for image alt text; using the stored equation form.", err); + return equationEncoded; + } +} + +function getDocsEquationLinkData(origURL: string) { + const markerPattern = /&ale_custom_alt=1$/; + return { + equationUrl: origURL.replace(markerPattern, ""), + hasCustomAltText: markerPattern.test(origURL) + }; +} + +function getCustomAltTextSuffix(image: GoogleAppsScript.Document.InlineImage, hasCustomAltText: boolean): string { + if (!hasCustomAltText) { + return ""; + } + try { + const description = image.getAltDescription(); + return description ? `_{${description}}` : ""; + } catch (err) { + console.warn("Could not read custom image alt text while de-rendering.", err); + return ""; + } +} + function getBodyFromIndex(index: number) { const doc = getDocsApp().getActive(); const p = doc.getBody().getParent(); @@ -1245,13 +1400,14 @@ function removeAll(defaultDelimRaw: string) { if (image.getLinkUrl() === null) { continue; } + const linkData = getDocsEquationLinkData(origURL); // console.log("Current origURL " + origURL, origURL == "null", origURL === null, typeof origURL, Object.is(origURL, null), null instanceof Object, origURL instanceof Object, origURL instanceof String, !origURL) // console.log("Current origURL " + image.getLinkUrl(), image.getLinkUrl() === null, typeof image.getLinkUrl(), Object.is(image.getLinkUrl(), null), !image.getLinkUrl()) // REASON: same escape()-era %uXXXX guard as derenderInlineImage — one ancient // image must not crash De-render All for the whole document. let result: ReturnType; try { - result = Common.derenderEquation(origURL, getDocsApp()); + result = Common.derenderEquation(linkData.equationUrl, getDocsApp()); } catch (err) { console.error("removeAll: failed to decode equation URL; skipping image.", String(err), " url=", String(origURL).substring(0, 500)); continue; @@ -1266,7 +1422,7 @@ function removeAll(defaultDelimRaw: string) { continue; } const parent = image.getParent() as GoogleAppsScript.Document.ListItem | GoogleAppsScript.Document.Paragraph; - parent.insertText(imageIndex, delim[0] + origEq + delim[1]); //INSERTS DELIMITERS + parent.insertText(imageIndex, delim[0] + origEq + delim[1] + getCustomAltTextSuffix(image, linkData.hasCustomAltText)); //INSERTS DELIMITERS image.removeFromParent(); counter += 1; } @@ -1292,13 +1448,14 @@ function derenderInlineImage( if (!origURL) { return Common.DerenderResult.NullUrl; } + const linkData = getDocsEquationLinkData(origURL); // REASON: images rendered in the escape()-encoding era carry %uXXXX sequences that // decodeURIComponent rejects (URIError: URI malformed). Uncaught, one ancient image // crashed the whole De-render run. Log WITH the URL so the offending encoding is // visible, and skip just this image. let result: ReturnType; try { - result = Common.derenderEquation(origURL, getDocsApp()); + result = Common.derenderEquation(linkData.equationUrl, getDocsApp()); } catch (err) { console.error("derenderInlineImage: failed to decode equation URL; skipping image.", String(err), " url=", String(origURL).substring(0, 500)); return Common.DerenderResult.InvalidUrl; @@ -1312,7 +1469,7 @@ function derenderInlineImage( } const parent = image.getParent() as GoogleAppsScript.Document.ListItem | GoogleAppsScript.Document.Paragraph; const imageIndex = parent.getChildIndex(image); - parent.insertText(imageIndex, delim[0] + origEq + delim[1]); //INSERTS DELIMITERS + parent.insertText(imageIndex, delim[0] + origEq + delim[1] + getCustomAltTextSuffix(image, linkData.hasCustomAltText)); //INSERTS DELIMITERS image.removeFromParent(); return Common.DerenderResult.Success; } diff --git a/Docs/Sidebar.html b/Docs/Sidebar.html index 3541164..79217ed 100644 --- a/Docs/Sidebar.html +++ b/Docs/Sidebar.html @@ -80,6 +80,7 @@ +

diff --git a/tests/docs-alt-text.test.js b/tests/docs-alt-text.test.js new file mode 100644 index 0000000..bb80ec7 --- /dev/null +++ b/tests/docs-alt-text.test.js @@ -0,0 +1,317 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +const docsCodePath = path.join(__dirname, "..", "Docs", "Code.js"); +const sidebarHtmlPath = path.join(__dirname, "..", "Docs", "Sidebar.html"); +const sidebarTsPath = path.join(__dirname, "..", "Docs", "Sidebar.ts"); + +function loadDocsCode(overrides = {}) { + const context = { + Common: { + DerenderResult: { + EmptyEquation: 2, + InvalidUrl: 0, + NullUrl: 1, + Success: 5, + }, + debugLog: () => {}, + getClientEquation: equation => decodeURIComponent(equation), + invalidEquationHashCodecogsFirst50: "never-matches", + reportDeltaTime: () => {}, + sizeImage: () => {}, + }, + DocumentApp: { + ElementType: { + BODY_SECTION: "BODY_SECTION", + TEXT: "TEXT", + }, + getActiveDocument: () => ({ getBody: () => ({}) }), + getUi: () => ({}), + }, + Set, + console: { error: () => {}, log: () => {}, warn: () => {} }, + decodeURIComponent, + encodeURIComponent, + escape, + ...overrides, + }; + vm.createContext(context); + vm.runInContext(fs.readFileSync(docsCodePath, "utf8"), context, { + filename: docsCodePath, + }); + return context; +} + +function makeEndElement(text, closingDelimiterEnd) { + const textElement = { + asText: () => textElement, + getText: () => text, + }; + return { + getElement: () => textElement, + getEndOffsetInclusive: () => closingDelimiterEnd, + }; +} + +test("custom alt-text suffix parsing supports balanced prose and rejects unsafe forms", () => { + const context = loadDocsCode(); + + const nested = context.getAccessibleAltTextSuffix( + makeEndElement("$$x$$_{x squared (for {real} x)} trailing", 4), + ); + assert.deepEqual( + JSON.parse(JSON.stringify(nested)), + { description: "x squared (for {real} x)", endOffsetInclusive: 31 }, + ); + + assert.equal( + context.getAccessibleAltTextSuffix(makeEndElement("$$x$$_{}", 4)), + null, + "empty descriptions must remain ordinary document text", + ); + assert.equal( + context.getAccessibleAltTextSuffix(makeEndElement("$$x$$_{unfinished", 4)), + null, + "an unclosed suffix must never be consumed", + ); + assert.equal( + context.getAccessibleAltTextSuffix(makeEndElement("$$x$$ _{not adjacent}", 4)), + null, + "the custom description syntax must be immediately adjacent", + ); +}); + +function makeImageHarness({ altSetterThrows = false } = {}) { + const state = { altDescription: null, linkUrl: null }; + const image = { + asInlineImage: () => image, + getHeight: () => 100, + getWidth: () => 200, + setAltDescription(description) { + if (altSetterThrows) throw new Error("alt metadata too large"); + state.altDescription = description; + return image; + }, + setLinkUrl(url) { + state.linkUrl = url; + return image; + }, + }; + const paragraph = { + getChild: () => image, + }; + return { image, paragraph, state }; +} + +const mathJaxRenderer = [0, "", "https://example.test/equation?latex=", "", "", "MathJax"]; +const doubleDollar = ["$$", "$$", "", "", 2, 1, 0]; +const fakePng = { getDataAsString: () => "png" }; + +test("every rendered Docs equation receives raw LaTeX alt text without changing its link", () => { + const context = loadDocsCode(); + const { paragraph, state } = makeImageHarness(); + + const result = context.repairImage( + paragraph, + 0, + 11, + mathJaxRenderer, + doubleDollar, + fakePng, + encodeURIComponent("\\frac{1}{2}"), + ); + + assert.equal(result.status, 8); + assert.equal(state.altDescription, "\\frac{1}{2}"); + assert.equal(state.linkUrl, "https://example.test/equation?latex=%5Cfrac%7B1%7D%7B2%7D#0"); +}); + +test("raw alt-text metadata failures never fail an otherwise valid render", () => { + const context = loadDocsCode(); + const { paragraph, state } = makeImageHarness({ altSetterThrows: true }); + + assert.doesNotThrow(() => context.repairImage( + paragraph, + 0, + 11, + mathJaxRenderer, + doubleDollar, + fakePng, + encodeURIComponent("x"), + )); + assert.equal(state.linkUrl, "https://example.test/equation?latex=x#0"); +}); + +test("custom suffix text becomes alt text and is marked for exact de-rendering", () => { + const context = loadDocsCode(); + const { paragraph, state } = makeImageHarness(); + + context.repairImage( + paragraph, + 0, + 11, + mathJaxRenderer, + doubleDollar, + fakePng, + encodeURIComponent("x^2"), + "x squared", + ); + + assert.equal(state.altDescription, "x squared"); + assert.equal(state.linkUrl, "https://example.test/equation?latex=x%5E2#0&ale_custom_alt=1"); +}); + +test("custom alt-text metadata failures abort before authored suffix text can be removed", () => { + const context = loadDocsCode(); + const { paragraph } = makeImageHarness({ altSetterThrows: true }); + + assert.throws( + () => context.repairImage( + paragraph, + 0, + 11, + mathJaxRenderer, + doubleDollar, + fakePng, + encodeURIComponent("x^2"), + "x squared", + ), + /alt metadata too large/, + ); +}); + +test("placeImage rolls back the image and preserves source text when custom alt text cannot be stored", () => { + const context = loadDocsCode({ Utilities: { sleep: () => {} } }); + const source = "Before $$x$$_{x squared} after"; + const state = { imageRemoved: false }; + let text; + const image = { + asInlineImage: () => image, + removeFromParent: () => { + state.imageRemoved = true; + }, + setAltDescription: () => { + throw new Error("alt metadata rejected"); + }, + setLinkUrl: () => image, + }; + const paragraph = { + getChild: () => image, + getChildIndex: child => child === text ? 0 : -1, + getParent: () => null, + insertInlineImage: () => image, + }; + text = { + asText: () => text, + copy: () => ({ + asText() { return this; }, + editAsText() { return this; }, + deleteText() { return this; }, + getText: () => " after", + }), + editAsText: () => text, + getParent: () => paragraph, + getText: () => source, + deleteText: () => { + throw new Error("source text must not be deleted"); + }, + }; + const span = { + getElement: () => text, + getStartOffset: () => 7, + getEndOffsetInclusive: () => 23, + }; + + assert.throws( + () => context.placeImage(span, fakePng, mathJaxRenderer, encodeURIComponent("x"), 11, doubleDollar, "x squared"), + /alt metadata rejected/, + ); + assert.equal(text.getText(), source); + assert.equal(state.imageRemoved, true); +}); + +function makeDerenderHarness({ linkUrl, altDescription }) { + const state = { insertedText: null, removed: false }; + const parent = { + getChildIndex: () => 0, + insertText: (_index, text) => { + state.insertedText = text; + }, + }; + const image = { + getAltDescription: () => altDescription, + getLinkUrl: () => linkUrl, + getParent: () => parent, + removeFromParent: () => { + state.removed = true; + }, + }; + return { image, state }; +} + +test("de-render restores explicit custom suffixes but does not duplicate raw fallback alt text", () => { + const context = loadDocsCode(); + context.Common.derenderEquation = url => { + assert.equal(url, "https://example.test/equation?latex=x%5E2#0", "Docs marker must be stripped before Common decodes the URL"); + return { delim: doubleDollar, origEq: "x^2" }; + }; + + const custom = makeDerenderHarness({ + linkUrl: "https://example.test/equation?latex=x%5E2#0&ale_custom_alt=1", + altDescription: "x squared", + }); + assert.equal(context.derenderInlineImage(custom.image, doubleDollar), 5); + assert.equal(custom.state.insertedText, "$$x^2$$_{x squared}"); + assert.equal(custom.state.removed, true); + + const raw = makeDerenderHarness({ + linkUrl: "https://example.test/equation?latex=x%5E2#0", + altDescription: "x^2", + }); + assert.equal(context.derenderInlineImage(raw.image, doubleDollar), 5); + assert.equal(raw.state.insertedText, "$$x^2$$"); +}); + +test("De-render All also restores explicit custom suffixes", () => { + const context = loadDocsCode(); + const custom = makeDerenderHarness({ + linkUrl: "https://example.test/equation?latex=x%5E2#0&ale_custom_alt=1", + altDescription: "x squared", + }); + const body = { + getImages: () => [custom.image], + getType: () => "BODY_SECTION", + }; + const documentRoot = { + getChild: () => body, + getNumChildren: () => 1, + }; + body.getParent = () => documentRoot; + const document = { getBody: () => body }; + context.DocumentApp.getActiveDocument = () => document; + context.Common.assert = condition => assert.equal(condition, true); + context.Common.getDelimiters = () => doubleDollar; + context.Common.derenderEquation = url => { + assert.equal(url, "https://example.test/equation?latex=x%5E2#0"); + return { delim: doubleDollar, origEq: "x^2" }; + }; + + assert.equal(context.removeAll("$$"), 1); + assert.equal(custom.state.insertedText, "$$x^2$$_{x squared}"); + assert.equal(custom.state.removed, true); +}); + +test("Docs alt text requires no sidebar option or preference", () => { + const html = fs.readFileSync(sidebarHtmlPath, "utf8"); + const source = fs.readFileSync(sidebarTsPath, "utf8"); + assert.doesNotMatch(html, /custom-alt-text|Use custom screen-reader text/); + assert.doesNotMatch(source, /customAltText/); + const context = loadDocsCode({ PropertiesService: { + getUserProperties: () => ({ getProperty: () => "false" }), + } }); + context.Common.getPrefs = () => ({ size: "auto", delim: "$$", renderer: "auto" }); + assert.deepEqual(context.getPrefs(), context.Common.getPrefs()); +}); diff --git a/tests/docs-dollar-pairing.test.js b/tests/docs-dollar-pairing.test.js index 3b40387..4540692 100644 --- a/tests/docs-dollar-pairing.test.js +++ b/tests/docs-dollar-pairing.test.js @@ -9,7 +9,7 @@ const delimiters = { parentheses: ["\\(", "\\)", "\\\\\\(", "\\\\\\)", 2, 1, 3], }; -function collectClientEquations(paragraphTexts, delimiter = delimiters.singleDollar) { +function collectClientRenderOptions(paragraphTexts, delimiter = delimiters.singleDollar) { const { context } = loadDocsCode(paragraphTexts, delimiter); const renderOptions = { size: 11, @@ -41,13 +41,17 @@ function collectClientEquations(paragraphTexts, delimiter = delimiters.singleDol assert.equal(result.status, 2, "expected a MathJax client-render result"); assert.ok(result.nextStartElement, "the batch scan must advance its cursor"); - equations.push(result.clientRenderOptions.equation); + equations.push(result.clientRenderOptions); cursor = result.nextStartElement; } assert.fail("delimiter scan did not terminate"); } +function collectClientEquations(paragraphTexts, delimiter = delimiters.singleDollar) { + return collectClientRenderOptions(paragraphTexts, delimiter).map(options => options.equation); +} + test("MathJax batch keeps adjacent inline equations paired", () => { assert.deepEqual( collectClientEquations(["$1$ and $2$"]), @@ -72,6 +76,30 @@ test("the cursor fix preserves double-dollar equation pairing", () => { ); }); +test("custom alt-text suffixes are attached to their equation and skipped by the batch scanner", () => { + const options = collectClientRenderOptions( + ["$$x$$_{read $$five$$ aloud} then $$y$$_{why}"], + delimiters.doubleDollar, + ); + assert.deepEqual( + options.map(option => ({ equation: option.equation, customAltText: option.customAltText })), + [ + { equation: "x", customAltText: "read $$five$$ aloud" }, + { equation: "y", customAltText: "why" }, + ], + ); +}); + +test("custom alt-text suffix syntax is recognized without an option", () => { + const options = collectClientRenderOptions( + ["$$x$$_{x squared}"], + delimiters.doubleDollar, + ); + assert.equal(options.length, 1); + assert.equal(options[0].equation, "x"); + assert.equal(options[0].customAltText, "x squared"); +}); + test("the cursor fix preserves bracket-delimited equation pairing", () => { assert.deepEqual( collectClientEquations( diff --git a/tests/evidence/pr69/01-source-fixtures.jpg b/tests/evidence/pr69/01-source-fixtures.jpg new file mode 100644 index 0000000..dc9bfc0 Binary files /dev/null and b/tests/evidence/pr69/01-source-fixtures.jpg differ diff --git a/tests/evidence/pr69/02-advanced-settings-no-checkbox.jpg b/tests/evidence/pr69/02-advanced-settings-no-checkbox.jpg new file mode 100644 index 0000000..ff0c232 Binary files /dev/null and b/tests/evidence/pr69/02-advanced-settings-no-checkbox.jpg differ diff --git a/tests/evidence/pr69/03-six-equations-rendered.jpg b/tests/evidence/pr69/03-six-equations-rendered.jpg new file mode 100644 index 0000000..748b04a Binary files /dev/null and b/tests/evidence/pr69/03-six-equations-rendered.jpg differ diff --git a/tests/evidence/pr69/04-alt-text-raw-fallback.jpg b/tests/evidence/pr69/04-alt-text-raw-fallback.jpg new file mode 100644 index 0000000..4310e75 Binary files /dev/null and b/tests/evidence/pr69/04-alt-text-raw-fallback.jpg differ diff --git a/tests/evidence/pr69/05-alt-text-custom-description.jpg b/tests/evidence/pr69/05-alt-text-custom-description.jpg new file mode 100644 index 0000000..16c1103 Binary files /dev/null and b/tests/evidence/pr69/05-alt-text-custom-description.jpg differ diff --git a/tests/evidence/pr69/06-alt-text-balanced-braces.jpg b/tests/evidence/pr69/06-alt-text-balanced-braces.jpg new file mode 100644 index 0000000..ae8df1f Binary files /dev/null and b/tests/evidence/pr69/06-alt-text-balanced-braces.jpg differ diff --git a/tests/evidence/pr69/07-derender-all-round-trip.jpg b/tests/evidence/pr69/07-derender-all-round-trip.jpg new file mode 100644 index 0000000..020a636 Binary files /dev/null and b/tests/evidence/pr69/07-derender-all-round-trip.jpg differ diff --git a/tests/evidence/pr69/README.md b/tests/evidence/pr69/README.md new file mode 100644 index 0000000..545c37a --- /dev/null +++ b/tests/evidence/pr69/README.md @@ -0,0 +1,62 @@ +# PR #69 live Docs evidence — alt text, always on + +Captured 2026-09-18 in Google Docs, against this branch's Docs code pushed to the +Docs Apps Script **project head** (Common pinned to v8, `developmentMode: false`; +pulled back and verified byte-identical to what was pushed). The Docs Marketplace +release stays v95 — nothing here is published to users. + +These replace the screenshots in the PR's 2026-09-15 comment. Those were taken +against the earlier opt-in revision and show an "alt text" checkbox that no +longer exists. Work happened in a new document tab so the earlier QA content and +the rest of the document were left untouched. + +## Fixtures + +Six cases in one tab, covering the whole `_{description}` rule: + +``` +1 raw fallback: $$x^2$$ +2 custom description: $$a^2+b^2=c^2$$_{Pythagorean theorem} +3 balanced braces: $$z^2$$_{square of {z}} +4 empty suffix stays visible: $$q^2$$_{} +5 non-adjacent suffix stays visible: $$r^2$$ _{leave visible} +6 unclosed suffix stays visible: $$s^2$$_{unfinished +``` + +![Source fixtures](01-source-fixtures.jpg) + +## There is no setting any more + +![Advanced Settings with no alt-text checkbox](02-advanced-settings-no-checkbox.jpg) + +Advanced Settings now holds only Delimiter Style and Preferred Renderer. Alt text +is not a choice the user has to find and turn on. + +## Rendered + +![Six equations rendered](03-six-equations-rendered.jpg) + +`Status: 6 equations rendered`. Cases 2 and 3 consumed their `_{...}` suffix; +cases 4, 5 and 6 left theirs visible in the document, exactly as authored. + +## What a screen reader gets + +Read out of Google's own Image options → Alt text panel, not from our code. + +| Case | Alt text | +| --- | --- | +| `$$x^2$$` | ![raw LaTeX fallback](04-alt-text-raw-fallback.jpg) | +| `$$a^2+b^2=c^2$$_{Pythagorean theorem}` | ![custom description](05-alt-text-custom-description.jpg) | +| `$$z^2$$_{square of {z}}` | ![balanced braces preserved](06-alt-text-balanced-braces.jpg) | + +Case 1 falls back to the raw source `x^2`. Case 2 uses the authored description. +Case 3 keeps the inner braces, so nested `{}` in a description survives. + +## Round trip + +![De-render All restores every fixture](07-derender-all-round-trip.jpg) + +`Status: 6 equations de-rendered`, and all six lines come back character for +character — including `_{Pythagorean theorem}` and `_{square of {z}}`, which were +consumed at render time, and the three suffixes that were deliberately left +alone. Nothing is duplicated and nothing is lost. diff --git a/types/docs-types/index.d.ts b/types/docs-types/index.d.ts index 6ecbc3d..616286d 100644 --- a/types/docs-types/index.d.ts +++ b/types/docs-types/index.d.ts @@ -26,7 +26,7 @@ declare namespace google { removeAll(defaultDelimRaw: string): void //intrinsic; - replaceEquations(sizeRaw: string, delimiter: string, renderer: string): void //union; + replaceEquations(sizeRaw: string, delimiter: string, renderer: string, customAltText?: boolean): void //union; }