forked from colbygk/mathslax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypeset.js
74 lines (69 loc) · 1.99 KB
/
typeset.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
var MathJax = require('mathjax-node-svg2png');
var _ = require('underscore');
var Q = require('q');
var fs = require('fs');
MathJax.start();
// Application logic for typesetting.
var extractRawMath = function(text, prefix) {
var mathRegex = new RegExp("^\s*" + prefix + "\s*(.*)$","g");
var results = [];
var match;
while (match = mathRegex.exec(text)) {
results.push({ // mathObject
matchedText: match[0],
input: match[1],
output: null,
error: null,
});
}
return results;
};
var renderMath = function(mathObject, parseOptions) {
var defaultOptions = {
math: mathObject.input,
format: 'AsciiMath',
png: true,
font: 'TeX',
width: 600,
linebreaks: true,
};
var typesetOptions = _.extend(defaultOptions, parseOptions);
var deferred = Q.defer();
var typesetCallback = function(result) {
if (!result || !result.png || !!result.errors) {
mathObject.error = new Error('Invalid response from MathJax.');
mathObject.output = result;
deferred.reject(mathObject);
return;
}
var filename = encodeURIComponent(mathObject.input).replace(/\%/g, 'pc') + '.png';
var filepath = 'static/' + filename;
if (!fs.existsSync(filepath)) {
console.log('writing new PNG: %s', filename);
var pngData = new Buffer(result.png.slice(22), 'base64');
fs.writeFile(filepath, pngData, function(error) {
if (error) {
mathObject.error = error;
mathObject.output = null;
deferred.reject(mathObject);
}
});
} else {
console.log('using existing PNG: %s', filename);
}
mathObject.output = filepath;
deferred.resolve(mathObject);
};
MathJax.typeset(typesetOptions, typesetCallback);
return deferred.promise;
}
var typeset = function(text, prefixed) {
var rawMathArray = extractRawMath(text, prefixed);
if (rawMathArray.length === 0) {
return null;
}
return Q.all(_.map(rawMathArray, renderMath));
};
module.exports = {
typeset: typeset,
};