A world-class math input for the web
1import { CaretNode, h, t, VNode } from "@caret-js/core";
2import { MathExpressionTag } from "../tags/mathExpression";
3import { CanBeAdjacentMultRightSideTag } from "../parselets/adjacentMultiplication";
4import { ParenthesesChildTag } from "../parselets/parentheses";
5
6export class DecimalNode extends CaretNode {
7 constructor(public value: string) {
8 super();
9 this.addTag(new MathExpressionTag()).addTag(
10 new CanBeAdjacentMultRightSideTag<DecimalNode>(
11 decimalAdjacentMultiplicationRightSideCheck
12 )
13 );
14 }
15
16 static from(value: string): DecimalNode {
17 return new DecimalNode(value);
18 }
19
20 toFloat(): number {
21 return parseFloat(this.value);
22 }
23
24 toDebugMathML(): VNode {
25 return h("mn", {}, t(this.value));
26 }
27}
28
29function decimalAdjacentMultiplicationRightSideCheck(
30 left: CaretNode,
31 right: DecimalNode
32): boolean {
33 if (right.hasTag(ParenthesesChildTag)) {
34 return true;
35 }
36
37 // Decimal nodes on the right side of adjacent multiplication must be non-negative
38 // For example, "x2" is "x multiplied by 2", but "x-2" is "x minus 2"
39 if (right.toFloat() < 0) {
40 return false;
41 }
42
43 if (left.hasTag(ParenthesesChildTag)) {
44 return true;
45 }
46
47 if (left instanceof DecimalNode) {
48 return false;
49 }
50
51 return false;
52}