Skip to content
Draft
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
1 change: 1 addition & 0 deletions components/bin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"#menu/*": "mj-context-menu/cjs/*",
"#sre/*": "speech-rule-engine/cjs/*",
"#mhchem/*": "mhchemparser/dist/*",
"#asciimathml/*": "asciimathml/dist/cjs/*",
"#default-font/*": "@mathjax/mathjax-newcm-font/cjs/*"
}
}
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"#menu/*": "mj-context-menu/js/*",
"#sre/*": "speech-rule-engine/js/*",
"#mhchem/*": "mhchemparser/esm/*",
"#asciimathml/*": "asciimathml/dist/esm/*",
"#default-font/*": "@mathjax/mathjax-newcm-font/mjs/*"
},
"files": [
Expand All @@ -80,9 +81,8 @@
"clean:lib": "clean() { pnpm -s log:single \"Cleaning $1 component libs\"; pnpm rimraf -g components/$1'/**/lib'; }; clean",
"clean:mod": "clean() { pnpm -s log:comp \"Cleaning $1 module\"; pnpm -s clean:dir $1 && pnpm -s clean:lib $1; }; clean",
"=============================================================================== copy": "",
"copy:assets": "pnpm -s log:comp 'Copying assets'; copy() { pnpm -s copy:mj2 $1 && pnpm -s copy:mml3 $1 && pnpm -s copy:html $1; }; copy",
"copy:assets": "pnpm -s log:comp 'Copying assets'; copy() { pnpm -s copy:mml3 $1 && pnpm -s copy:html $1; }; copy",
"copy:html": "copy() { pnpm -s log:single 'Copying sre auxiliary files'; pnpm copyfiles -u 1 'ts/a11y/sre/*.html' 'ts/a11y/sre/require.*' $1; }; copy",
"copy:mj2": "copy() { pnpm -s log:single 'Copying legacy code AsciiMath'; pnpm copyfiles -u 1 'ts/input/asciimath/legacy/**/*' $1; }; copy",
"copy:mml3": "copy() { pnpm -s log:single 'Copying legacy code MathML3'; pnpm copyfiles -u 1 ts/input/mathml/mml3/mml3.sef.json $1; }; copy",
"copy:pkg": "copy() { pnpm -s log:single \"Copying package.json to $1\"; pnpm copyfiles -u 2 components/bin/package.json $1; }; copy",
"=============================================================================== log": "",
Expand Down Expand Up @@ -169,6 +169,7 @@
},
"dependencies": {
"@mathjax/mathjax-newcm-font": "4.1.0",
"asciimathml": "^2.3.7",
"mhchemparser": "^4.2.1",
"mj-context-menu": "^1.0.0",
"speech-rule-engine": "5.0.0-beta.3"
Expand Down
183 changes: 170 additions & 13 deletions ts/input/asciimath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,64 @@
*/

import { AbstractInputJax } from '../core/InputJax.js';
import { LegacyAsciiMath } from './asciimath/legacy.js';
import { separateOptions, OptionList } from '../util/Options.js';
import { userOptions, separateOptions, OptionList } from '../util/Options.js';
import { MathDocument } from '../core/MathDocument.js';
import { MathItem } from '../core/MathItem.js';
import { MmlNode } from '../core/MmlTree/MmlNode.js';
import { MmlFactory } from '../core/MmlTree/MmlFactory.js';
import { Property } from '../core/Tree/Node.js';

import { FindAsciiMath } from './asciimath/FindAsciiMath.js';
import AsciiMathError from './asciimath/AsciiMathError.js';
import ParseOptions from './asciimath/ParseOptions.js';
import { AsciiMathParser } from '#asciimathml/AsciiMathParser.js';
import { INodeAdapter, IParseOptions } from '#asciimathml/NodeAdapter.js';

export class MmlNodeAdapter implements INodeAdapter {
constructor(private node: MmlNode) {}

get kind() { return this.node.kind; }
get text() { return (this.node as any).text; }
get childNodes() {
return this.node.childNodes.map(n => new MmlNodeAdapter(n));
}

setAttribute(name: string, value: string): void {
this.node.attributes.set(name, value);
}

getAttribute(name: string): Property {
return this.node.attributes.get(name);
}

appendChild(child: INodeAdapter): void {
if ((child as MmlNodeAdapter).node.parent !== null) {
const childNode = (child as MmlNodeAdapter).node.parent.removeChild((child as MmlNodeAdapter).node);
this.node.appendChild(childNode);
} else {
this.node.appendChild((child as MmlNodeAdapter).node);
}
}

replaceChild(newChild: INodeAdapter, oldChild: INodeAdapter): void {
this.node.replaceChild(
(newChild as MmlNodeAdapter).node,
(oldChild as MmlNodeAdapter).node
);
}

removeFirstChild(): void {
this.node.removeChild(this.node.childNodes[0]);
}

removeLastChild(): void {
this.node.removeChild(this.node.childNodes[this.node.childNodes.length - 1]);
}

// Expose underlying node when needed
get underlyingNode() { return this.node; }
}


/*****************************************************************/
/**
Expand All @@ -39,44 +91,137 @@ import { FindAsciiMath } from './asciimath/FindAsciiMath.js';
*/
export class AsciiMath<N, T, D> extends AbstractInputJax<N, T, D> {
/**
* The name of the input jax
* Name of input jax.
*
* @type {string}
*/
public static NAME: string = 'AsciiMath';

/**
* @override
* Default options for the jax.
*
* @type {OptionList}
*/
public static OPTIONS: OptionList = {
...AbstractInputJax.OPTIONS,
FindAsciiMath: null,
// Decimal sign character
decimalsign: '.',
// Display style (for limits)
displaystyle: true,
// Additional symbols to add
additionalSymbols: [],
formatError: (jax: AsciiMath<any, any, any>, err: AsciiMathError) =>
jax.formatError(err),
};

/**
* The FindMath object used to search for AsciiMath in the document
* The FindAsciiMath instance used for locating AsciiMath in strings
*/
protected findAsciiMath: FindAsciiMath<N, T, D>;

/**
* The AsciiMath code that is parsed.
*
* @type {string}
*/
protected asciimath: string;

/**
* The Math node that results from parsing.
*
* @type {MmlNode}
*/
protected mathNode: MmlNode;

private _parseOptions: ParseOptions;

/**
* @override
*/
constructor(options: OptionList) {
const [, find, am] = separateOptions(
constructor(options: OptionList = {}) {
const [rest, am, find] = separateOptions(
options,
FindAsciiMath.OPTIONS,
AsciiMath.OPTIONS
AsciiMath.OPTIONS,
FindAsciiMath.OPTIONS
);
super(am);
this.findAsciiMath =
this.options['FindAsciiMath'] || new FindAsciiMath(find);
this._parseOptions = new ParseOptions(this.mmlFactory, [this.options]);
userOptions(this._parseOptions.options, rest);
}

/**
* @override
*/
public setMmlFactory(mmlFactory: MmlFactory) {
super.setMmlFactory(mmlFactory);
this._parseOptions.mmlFactory = mmlFactory;
}

/**
* @returns {ParseOptions} The parse options that configure this JaX instance.
*/
public get parseOptions(): ParseOptions {
return this._parseOptions;
}

/**
* Use legacy AsciiMath input jax for now
*
* @override
*/
public compile(math: MathItem<N, T, D>, _document: MathDocument<N, T, D>) {
return LegacyAsciiMath.Compile(math.math, math.display);
public compile(
math: MathItem<N, T, D>,
document: MathDocument<N, T, D>
): MmlNode {
this.parseOptions.clear();
this.parseOptions.mathItem = math;
this.executeFilters(this.preFilters, math, document, this.parseOptions);
this.asciimath = math.math;
let node: MmlNode;

const mmlConfig: IParseOptions<MmlNodeAdapter> = {
create: (tag, children) => {
const node = this.mmlFactory.create(tag);
children?.forEach(c => node.appendChild(c.underlyingNode));
return new MmlNodeAdapter(node);
},
createText: (text) => {
const textNode = this.mmlFactory.create('text');
(textNode as any).text = text;
return new MmlNodeAdapter(textNode);
},
options: {
decimalsign: this.parseOptions.options.decimalsign,
displaystyle: this.parseOptions.options.displaystyle,
additionalSymbols: this.parseOptions.options?.additionalSymbols || []
}
};

try {
const parser = new AsciiMathParser(mmlConfig);
const result = parser.mml(this.asciimath);
node = (result as MmlNodeAdapter).underlyingNode;
} catch (err) {
if (!(err instanceof AsciiMathError)) {
throw err;
}
this.parseOptions.error = true;
node = this.options.formatError(this, err);
}

node = this.parseOptions.create('math', [node]);
node.attributes.set('data-asciimath', this.asciimath);
node.setInheritedAttributes({}, false, 0, false);

if (math.display) {
node.attributes.set('display', 'block')
}

this.parseOptions.root = node;
this.executeFilters(this.postFilters, math, document, this.parseOptions);
this.mathNode = this.parseOptions.root;
return this.mathNode;
}

/**
Expand All @@ -85,4 +230,16 @@ export class AsciiMath<N, T, D> extends AbstractInputJax<N, T, D> {
public findMath(strings: string[]) {
return this.findAsciiMath.findMath(strings);
}

/**
* Default formatter for error messages:
* wrap an error into a node for output.
*
* @param {AsciiMathError} err The AsciiMathError.
* @returns {MmlNode} The merror node.
*/
public formatError(err: AsciiMathError): MmlNode {
const message = err.message.replace(/\n.*/, '');
return this.parseOptions.createError(message, err.id, this.asciimath);
}
}
88 changes: 88 additions & 0 deletions ts/input/asciimath/AsciiMathError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*************************************************************
*
* Copyright (c) 2025 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* @file Error class for the AsciiMath parser.
*
* @author mathjax@mathjax.org (MathJax Consortium)
*/

export default class AsciiMathError {
private static pattern =
/%(\d+|\{\d+\}|\{[a-z]+:%\d+(?:\|(?:%\{\d+\}|%.|[^}])*)+\}|.)/g;

/**
* Default error message.
*
* @type {string}
*/
public message: string;

/**
* The old MathJax processing function.
*
* @param {string} str The basic error message.
* @param {string[]} args The arguments to be replaced in the error message.
* @returns {string} The processed error string.
*/
private static processString(str: string, args: string[]): string {
const parts = str.split(AsciiMathError.pattern);
for (let i = 1, m = parts.length; i < m; i += 2) {
let c = parts[i].charAt(0);
if (c >= '0' && c <= '9') {
parts[i] = args[parseInt(parts[i], 10) - 1];
if (typeof parts[i] === 'number') {
parts[i] = parts[i].toString();
}
} else if (c === '{') {
c = parts[i].substring(1);
if (c >= '0' && c <= '9') {
parts[i] =
args[
parseInt(
parts[i].substring(1, parts[i].length - 1),
10
) - 1
];
if (typeof parts[i] === 'number') {
parts[i] = parts[i].toString();
}
} else {
const match = parts[i].match(/^\{([a-z]+):%(\d+)\|(.*)\}$/);
if (match) {
parts[i] = '%' + parts[i];
}
}
}
}
return parts.join('');
}

/**
* @class
* @param {string} id message id (for localization)
* @param {string} message text of English message
* @param {string[]=} rest any substitution arguments
*/
constructor(
public id: string,
message: string,
...rest: string[]
) {
this.message = AsciiMathError.processString(message, rest);
}
}
Loading
Loading