OMD Documentation

omdUtilities

This module provides a collection of utility functions primarily used for mapping math.js AST nodes to OMD node classes, determining rendering behavior, and calculating text dimensions. These functions are internal helpers that support the core OMD node system.

Functions

astToOmdType(type, ast)

Maps a math.js AST node type to its corresponding OMD node class. This function is crucial for dynamically creating the correct omdNode subclass based on the parsed expression.

Detailed Logic:

getNodeForAST(ast)

A wrapper function that takes a complete math.js AST node and returns the corresponding OMD node class. It uses astToOmdType internally, handling cases where the AST might have a mathjs property indicating its type.

getTextBounds(text, fontSize)

Calculates the rendered width and height of a given text string at a specific font size. This is achieved by creating a temporary, hidden <span> element in the DOM, applying the text and styling, measuring its dimensions, and then removing it.

shouldUseFractionNotation(ast)

Determines whether a division operation (represented by an AST node) should be rendered as a fraction (stacked numerator over denominator) or as a linear division (e.g., a / b). This decision is based on the complexity of the numerator and denominator.

isComplexExpression(ast)

Checks if an AST node represents a "complex" expression, typically one that contains multiple operations or nested structures. This function is used by shouldUseFractionNotation to decide on the appropriate rendering style for fractions.

Example

import { getNodeForAST, getTextBounds } from '@teachinglab/omd'; // Assuming @teachinglab/omd exports these
import * as math from 'mathjs';

// Example of getting a node class for an expression
const astExpression = math.parse('x + 2');
const NodeClassExpression = getNodeForAST(astExpression);
const nodeExpression = new NodeClassExpression(astExpression);
console.log(nodeExpression.type); // e.g., "omdBinaryExpressionNode"

// Example of getting a node class for an equation
const astEquation = math.parse('y = 2x');
const NodeClassEquation = getNodeForAST(astEquation);
const nodeEquation = new NodeClassEquation(astEquation);
console.log(nodeEquation.type); // "omdEquationNode"

// Example of getting text bounds
const bounds = getTextBounds('Hello World', 24);
console.log(`Text width: ${bounds.width}, height: ${bounds.height}`);
↑ Top