forked from KaTeX/KaTeX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.js
179 lines (161 loc) · 5.68 KB
/
helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import katex from "../katex";
import ParseError from "../src/ParseError";
import parseTree from "../src/parseTree";
import Settings from "../src/Settings";
import diff from 'jest-diff';
import {RECEIVED_COLOR, printReceived, printExpected} from 'jest-matcher-utils';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
export function ConsoleWarning(message) {
Error.captureStackTrace(this, global.console.warn);
this.name = this.constructor.name;
this.message = message;
}
Object.setPrototypeOf(ConsoleWarning.prototype, Error.prototype);
/**
* Return the first raw string if x is tagged literal. Otherwise return x.
*/
export const r = x => x != null && x.hasOwnProperty('raw') ? x.raw[0] : x;
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This function is from https://github.com/facebook/jest/blob/9867e16e518d50c79
* 492f7f0d2bc1ef8dff37db4/packages/expect/src/to_throw_matchers.js and licensed
* under the MIT license found in the https://github.com/facebook/jest/blob/master/LICENSE.
*/
const printActualErrorMessage = error => {
if (error) {
const {message, stack} = separateMessageFromStack(error.stack);
return (
'Instead, it threw:\n' +
/* eslint-disable-next-line new-cap */
RECEIVED_COLOR(
` ${message}` +
formatStackTrace(
// remove KaTeX internal stack entries
stack.split('\n')
.filter(line => line.indexOf('new ParseError') === -1)
.join('\n'),
{
rootDir: process.cwd(),
testMatch: [],
},
{
noStackTrace: false,
},
),
)
);
}
return 'But it didn\'t throw anything.';
};
const printExpectedResult = (mode, isNot, expectedError) => expectedError == null
? (isNot ? 'fail ' : 'success ') + mode
: (isNot ? 'not throw a ' : `fail ${mode} with a `) +
(expectedError.name || `ParseError matching "${expectedError}"`);
export const nonstrictSettings = new Settings({strict: false});
export const strictSettings = new Settings({strict: true});
export const trustSettings = new Settings({trust: true});
/**
* Return the root node of the rendered HTML.
* @param expr
* @param settings
* @returns {Object}
*/
export function getBuilt(expr, settings = new Settings()) {
expr = r(expr); // support tagging literals
let rootNode = katex.__renderToDomTree(expr, settings);
if (rootNode.classes.indexOf('katex-error') >= 0) {
return rootNode;
}
if (rootNode.classes.indexOf('katex-display') >= 0) {
rootNode = rootNode.children[0];
}
// grab the root node of the HTML rendering
// rootNode.children[0] is the MathML rendering
const builtHTML = rootNode.children[1];
// combine the non-strut children of all base spans
const children = [];
for (let i = 0; i < builtHTML.children.length; i++) {
children.push(...builtHTML.children[i].children.filter(
(node) => node.classes.indexOf("strut") < 0));
}
return children;
}
/**
* Return the root node of the parse tree.
* @param expr
* @param settings
* @returns {Object}
*/
export function getParsed(expr, settings = new Settings()) {
expr = r(expr); // support tagging literals
return parseTree(expr, settings);
}
export const stripPositions = expr => {
if (typeof expr !== "object" || expr === null) {
return expr;
}
if (expr.loc && expr.loc.lexer && typeof expr.loc.start === "number") {
delete expr.loc;
}
Object.keys(expr).forEach(function(key) {
stripPositions(expr[key]);
});
return expr;
};
export const Mode = {
PARSE: {
apply: getParsed,
noun: 'parsing',
Verb: 'Parse',
},
BUILD: {
apply: getBuilt,
noun: 'building',
Verb: 'Build',
},
};
export const expectKaTeX = (expr, settings, mode, isNot, expectedError) => {
let pass = expectedError == null;
let error;
try {
mode.apply(expr, settings);
} catch (e) {
error = e;
if (e instanceof ParseError) {
pass = expectedError === ParseError || (typeof expectedError ===
"string" && e.message === `KaTeX parse error: ${expectedError}`);
} else if (e instanceof ConsoleWarning) {
pass = expectedError === ConsoleWarning;
} else {
pass = !!isNot; // always fail
}
}
return {
pass,
message: () => 'Expected the expression to ' +
printExpectedResult(mode.noun, isNot, expectedError) +
`:\n ${printReceived(r(expr))}\n` +
printActualErrorMessage(error),
};
};
export const expectEquivalent = (actual, expected, settings, mode, expand) => {
const actualTree = stripPositions(mode.apply(actual, settings));
const expectedTree = stripPositions(mode.apply(expected, settings));
const pass = JSON.stringify(actualTree) === JSON.stringify(expectedTree);
return {
pass,
message: pass
? () =>
`${mode.Verb} trees of ${printReceived(r(actual))} and ` +
`${printExpected(r(expected))} are equivalent`
: () => {
const diffString = diff(expectedTree, actualTree, {
expand,
});
return `${mode.Verb} trees of ${printReceived(r(actual))} and ` +
`${printExpected(r(expected))} are not equivalent` +
(diffString ? `:\n\n${diffString}` : '');
},
};
};