-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqtyMethods.ts
315 lines (265 loc) · 11.2 KB
/
qtyMethods.ts
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import TexParser from "mathjax-full/js/input/tex/TexParser";
import { displayOutputMml, findInnerText } from "./numDisplayMethods";
import { INumberPiece, parseNumber } from "./numMethods";
import { convertToFixed, postProcessNumber } from "./numPostProcessMethods";
import { findOptions, IOptions } from "./options/options";
import { IQuantityOptions, PrefixMode, SeparateUncertaintyUnits } from "./options/quantityOptions";
import { displayUnits, IUnitPiece, parseUnit } from "./unitMethods";
import { prefixPower } from "./units";
import { MmlNode } from "mathjax-full/js/core/MmlTree/MmlNode";
function combineExponent(parser: TexParser, num: INumberPiece, units: IUnitPiece[], options: IQuantityOptions): void {
if (!num.exponent || (!units || units.length === 0)) {
return;
}
const exponent = +(num.exponentSign + num.exponent);
let targetExponent: number;
for (const power of prefixPower.values()) {
if (power >= exponent) {
targetExponent = power;
} else {
break;
}
}
const firstUnit = units[0];
// prefix can be undefined, empty, or string... this specifically checks for empty
if (firstUnit.prefix) {
const unitPower = (firstUnit.power !== null ? +(firstUnit.power) : 1) * (firstUnit.position === 'denominator' ? -1 : 1);
const addedPower = firstUnit.prefix ? prefixPower.get(firstUnit.prefix) : 1;
targetExponent += addedPower * unitPower;
// just in case prefix was cm (2) and we added 3, there's no prefix for 5
while (!prefixPower.revHas(targetExponent)) {
targetExponent++;
}
}
// set new prefix
firstUnit.prefix = prefixPower.revGet(targetExponent);
const newExponent = targetExponent - exponent;
num.exponent = (Math.abs(newExponent)).toString();
num.exponentSign = Math.sign(newExponent) > 0 ? '' : '-';
convertToFixed(parser, num, options);
}
function extractExponent(parser: TexParser, num: INumberPiece, units: IUnitPiece[], options: IQuantityOptions): void {
if (units === null) {
return;
}
let powersOfTen = 0;
//let powersOfTwo = 0;
for (let i = 0; i < units.length; i++) {
const unit = units[i];
// run only if
// 1. prefix is present for all units except grams
// 2. prefix is present for grams when !extractMassInKilograms
// 2. prefix is not k for grams when extractMassInKilograms // special case
if ((unit.symbol !== 'g' && unit.prefix !== '') || (unit.symbol === 'g' && unit.prefix !== '' && !options["extract-mass-in-kilograms"])) {
const unitPower = ((unit.power !== undefined && unit.power !== null) ? +(unit.power) : 1) * (unit.position === 'denominator' ? -1 : 1);
// if (binaryPrefixPower.has(unit.prefix)){
// const prefPower = binaryPrefixPower.get(unit.prefix);
// powersOfTwo += (prefPower*unitPower);
// } else {
if (prefixPower.has(unit.prefix)) {
const prefPower = prefixPower.get(unit.prefix);
powersOfTen += (prefPower * unitPower);
} else {
// Don't do anything to this prefix. Can't convert it. Next unit...
continue;
}
unit.prefix = '';
} else if (unit.symbol === 'g' && unit.prefix !== 'k' && options["extract-mass-in-kilograms"]) {
const unitPower = ((unit.power !== undefined && unit.power !== null) ? +(unit.power) : 1) * (unit.position === 'denominator' ? -1 : 1);
if (prefixPower.has(unit.prefix)) {
const prefPower = prefixPower.get(unit.prefix);
powersOfTen += (prefPower * unitPower) - 3;
} else {
// this unit has no prefix...
powersOfTen = -3;
}
unit.prefix = 'k';
}
}
const currentExponent = (num.exponent ? +(num.exponentSign + num.exponent) : 0);
const newExponent = currentExponent + powersOfTen;
num.exponent = Math.abs(newExponent).toString();
num.exponentSign = Math.sign(newExponent) > 0 ? '' : '-';
if (!num.exponentMarker) {
num.exponentMarker = 'e';
}
}
export const prefixModeMap = new Map<PrefixMode, (parser: TexParser, num: INumberPiece, units: IUnitPiece[], options: IQuantityOptions) => void>([
// eslint-disable-next-line @typescript-eslint/no-empty-function
['input', (): void => { }],
['combine-exponent', combineExponent],
['extract-exponent', extractExponent]
]);
function findUncertaintyNode(root: MmlNode): MmlNode | null {
for (const x of root.childNodes) {
const mmlNode = x as MmlNode;
if (mmlNode) {
if (mmlNode.attributes) {
const names = mmlNode.attributes.getExplicitNames();
if (names.indexOf('data-siunitx-uncertainty') !== -1) {
return mmlNode;
}
}
const result = findUncertaintyNode(mmlNode);
if (result) {
return result;
}
}
}
return null;
}
const separateUncertaintyUnitsMmlMap = new Map<SeparateUncertaintyUnits, (num: MmlNode, units: MmlNode, quantityProduct: MmlNode, parser: TexParser, options: IQuantityOptions) => MmlNode>([
['single', (num: MmlNode, units: MmlNode, quantityProduct: MmlNode, parser: TexParser, _options: IQuantityOptions): MmlNode => {
const root = parser.create('node', 'inferredMrow', [], {});
root.appendChild(num);
root.appendChild(quantityProduct);
root.appendChild(units);
return root;
}],
['bracket', (num: MmlNode, units: MmlNode, quantityProduct: MmlNode, parser: TexParser, options: IQuantityOptions): MmlNode => {
const root = parser.create('node', 'inferredMrow', [], {});
let uncertaintyNode: MmlNode = null;
for (const x of num.childNodes) {
const result = findUncertaintyNode(x as MmlNode);
if (result) {
uncertaintyNode = result;
break;
}
}
if (uncertaintyNode) {
const leftBracket = parser.create('token', 'mo', {}, options["output-open-uncertainty"]);
const rightBracket = parser.create('token', 'mo', {}, options["output-close-uncertainty"]);
root.appendChild(leftBracket);
root.appendChild(num);
root.appendChild(rightBracket);
root.appendChild(quantityProduct);
root.appendChild(units);
return root;
} else {
root.appendChild(num);
root.appendChild(quantityProduct);
root.appendChild(units);
return root;
}
}],
['repeat', (num: MmlNode, units: MmlNode, quantityProduct: MmlNode, parser: TexParser, _options: IQuantityOptions): MmlNode => {
let uncertaintyNode: MmlNode = null;
for (const x of num.childNodes) {
const result = findUncertaintyNode(x as MmlNode);
if (result) {
uncertaintyNode = result;
break;
}
}
if (uncertaintyNode) {
const parent = uncertaintyNode.parent;
const uncertaintyPosition = parent.childNodes.indexOf(uncertaintyNode);
if (!quantityProduct) {
parent.childNodes.splice(uncertaintyPosition, 0, units);
parent.appendChild(units);
} else {
parent.childNodes.splice(uncertaintyPosition, 0, quantityProduct, units);
// To make it match the MathML structure of the previous insert,
// we should insert the 2nd unit at the same depth.
// However, SRE seems to rearrange it all anyways.
parent.appendChild(quantityProduct);
parent.appendChild(units);
}
return num;
} else {
const root = parser.create('node', 'inferredMrow', [], {});
root.appendChild(num);
root.appendChild(quantityProduct);
root.appendChild(units);
return root;
}
}]
]);
const separateUncertaintyUnitsMap = new Map<SeparateUncertaintyUnits, (num: string, units: string, options: IQuantityOptions) => string>([
['single', (num: string, units: string, options: IQuantityOptions): string => {
return num + options["quantity-product"] + units;
}],
['bracket', (num: string, units: string, options: IQuantityOptions): string => {
if (num.indexOf('\\pm') === -1) {
return num + options["quantity-product"] + units;
}
return options["output-open-uncertainty"] + num + options["output-close-uncertainty"] + options["quantity-product"] + units;
}],
['repeat', (num: string, units: string, options: IQuantityOptions): string => {
// split the num from the uncertainty, split on \\pm
const split = num.split('\\pm');
let separate = '';
for (let i = 0; i < split.length; i++) {
if (separate) {
separate += '\\pm';
}
separate += split[i];
separate += options["quantity-product"];
separate += units;
}
return separate;
}]
]);
export function createQuantityProductMml(parser: TexParser, options: IOptions): MmlNode | null {
let quantityProductNode = null;
const trimmedQuantityProduct = options["quantity-product"].trimStart();
if (trimmedQuantityProduct) {
const spacerNode = (new TexParser(trimmedQuantityProduct, parser.stack.env, parser.configuration)).mml();
const spacerUnicode = findInnerText(spacerNode);
quantityProductNode = parser.create('token', 'mo', {}, spacerUnicode);
} else {
quantityProductNode = parser.create('token', 'mo', {});
}
return quantityProductNode;
}
export function createUnitsNode(unitLatex: string, parser: TexParser, options: IOptions): MmlNode {
let unitNode = (new TexParser(unitLatex, parser.stack.env, parser.configuration)).mml();
const quantityProductNode = createQuantityProductMml(parser, options);
if (quantityProductNode) {
const root = parser.create('node', 'inferredMrow', [], {});
root.appendChild(quantityProductNode);
root.appendChild(unitNode);
unitNode = root;
}
return unitNode;
}
export function processQuantity(parser: TexParser): void {
let globalOptions: IOptions = { ...parser.options.siunitx as IOptions };
const localOptions = findOptions(parser, globalOptions);
let numString = parser.GetArgument('num');
const unitString = parser.GetArgument('unit');
let unitDisplay = '';
const isLiteral = (unitString.indexOf('\\') === -1);
const unitPieces = parseUnit(parser, unitString, globalOptions, localOptions, isLiteral);
if (globalOptions["parse-numbers"]) {
// going to assume evaluate expression is processed first, THEN the result is parsed normally
if (globalOptions["evaluate-expression"]) {
// TODO Sanitize Evaluate Expression!
let expression = globalOptions.expression
expression = expression.replace('#1', numString);
numString = eval(expression).toString();
}
// refresh global options from default
globalOptions = { ...parser.options.siunitx as IOptions };
Object.assign(globalOptions, localOptions);
const num = parseNumber(parser, numString, globalOptions);
// convert number and unit if necessary
prefixModeMap.get(globalOptions["prefix-mode"])?.(parser, num, unitPieces, globalOptions);
postProcessNumber(parser, num, globalOptions);
const numDisplay = displayOutputMml(num, parser, globalOptions);
// Need to process this after number because some options alter unit prefixes
unitDisplay = displayUnits(parser, unitPieces, globalOptions, isLiteral);
const unitNode = (new TexParser(unitDisplay, parser.stack.env, parser.configuration)).mml();
const quantityProductNode = createQuantityProductMml(parser, globalOptions);
const qtyDisplay = separateUncertaintyUnitsMmlMap.get(globalOptions["separate-uncertainty-units"])(numDisplay, unitNode, quantityProductNode, parser, globalOptions);
parser.Push(qtyDisplay);
} else {
// can't do any conversions with number since processing is off
const numDisplay = numString;
// Need to process this after number because some options alter unit prefixes
unitDisplay = displayUnits(parser, unitPieces, globalOptions, isLiteral);
const qtyDisplay = separateUncertaintyUnitsMap.get(globalOptions["separate-uncertainty-units"])(numDisplay, unitDisplay, globalOptions);
const qtyNode = (new TexParser(qtyDisplay, parser.stack.env, parser.configuration)).mml();
parser.Push(qtyNode);
}
}