All files / web/src/components/toys/coordinate-plane/ruler RulerEquationLabel.tsx

0% Statements 0/313
0% Branches 0/1
0% Functions 0/1
0% Lines 0/313

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client'

import type { EquationForm, Fraction, MixedNumber } from './types'
import { toMixedNumber, isInteger, toStandardForm } from './fractionMath'

export type EquationDisplayForm = 'slope-intercept' | 'standard'

/**
 * Math font stack — same chain as MathDisplay.tsx
 */
const mathFontFamily = [
  '"STIX Two Math"',
  '"Cambria Math"',
  '"Latin Modern Math"',
  '"XITS Math"',
  'math',
  'serif',
].join(', ')

// ── MathML helpers ─────────────────────────────────────────────────

/** Render a mixed number as MathML nodes */
function MixedNumberMml({ m }: { m: MixedNumber }) {
  // Pure integer
  if (m.fracNum === 0) {
    return <mn>{m.negative ? `\u2212${m.whole}` : `${m.whole}`}</mn>
  }

  // Pure fraction (no whole part)
  if (m.whole === 0) {
    return (
      <mrow>
        {m.negative && <mo>&minus;</mo>}
        <mfrac>
          <mn>{m.fracNum}</mn>
          <mn>{m.fracDen}</mn>
        </mfrac>
      </mrow>
    )
  }

  // Mixed number
  return (
    <mrow>
      <mn>{m.negative ? `\u2212${m.whole}` : `${m.whole}`}</mn>
      <mfrac>
        <mn>{m.fracNum}</mn>
        <mn>{m.fracDen}</mn>
      </mfrac>
    </mrow>
  )
}

/** Render a fraction (possibly mixed) as MathML */
function FractionMml({ f }: { f: Fraction }) {
  return <MixedNumberMml m={toMixedNumber(f)} />
}

/** Render the slope coefficient with variable x */
function SlopeTerm({ slope }: { slope: Fraction }) {
  const m = toMixedNumber(slope)

  // slope = 1: just "x"
  if (slope.num === 1 && slope.den === 1) {
    return <mi>x</mi>
  }

  // slope = -1: "−x"
  if (slope.num === -1 && slope.den === 1) {
    return (
      <mrow>
        <mo>&minus;</mo>
        <mi>x</mi>
      </mrow>
    )
  }

  // Integer slope
  if (isInteger(slope)) {
    return (
      <mrow>
        <mn>{slope.num}</mn>
        <mi>x</mi>
      </mrow>
    )
  }

  // Fractional slope: render as mixed number then x
  return (
    <mrow>
      {m.negative && <mo>&minus;</mo>}
      {m.whole > 0 && <mn>{m.whole}</mn>}
      <mfrac>
        <mn>{m.fracNum}</mn>
        <mn>{m.fracDen}</mn>
      </mfrac>
      <mi>x</mi>
    </mrow>
  )
}

// ── Main component ─────────────────────────────────────────────────

interface RulerEquationLabelProps {
  equation: EquationForm
  /** Which equation form to display (only affects 'general' equations) */
  equationForm?: EquationDisplayForm
  /** Screen position (px) — driven by sliderT, not always midpoint */
  screenX: number
  screenY: number
  /** Angle of the ruler line in radians */
  angle: number
  isDark: boolean
  /** Whether the equation probe is currently being dragged */
  isDragging?: boolean
  /** Pointer-down handler for the card */
  onIndicatorPointerDown?: (e: React.PointerEvent) => void
  /** Ref to the outer positioned container — used by RAF loop for position sync */
  containerRef?: React.MutableRefObject<HTMLDivElement | null>
}

export function RulerEquationLabel({
  equation,
  equationForm = 'slope-intercept',
  screenX,
  screenY,
  angle,
  isDark,
  isDragging = false,
  onIndicatorPointerDown,
  containerRef,
}: RulerEquationLabelProps) {
  // Normalize angle to keep text readable (within ±90°)
  let displayAngle = angle
  while (displayAngle > Math.PI / 2) displayAngle -= Math.PI
  while (displayAngle < -Math.PI / 2) displayAngle += Math.PI

  // Offset the card above the ruler line so the canvas probe dot is visible.
  // Card height is constant (no dynamic content), so -50% centering is stable.
  const offsetPx = 18
  const perpX = -Math.sin(displayAngle) * offsetPx
  const perpY = Math.cos(displayAngle) * offsetPx

  const color = isDark ? 'rgba(226, 232, 240, 0.95)' : 'rgba(30, 41, 59, 0.95)'
  const bgColor = isDark ? 'rgba(30, 41, 59, 0.75)' : 'rgba(255, 255, 255, 0.75)'

  return (
    <div
      ref={(el) => {
        if (containerRef) containerRef.current = el
      }}
      data-element="ruler-equation-label"
      style={{
        position: 'absolute',
        left: screenX + perpX,
        top: screenY + perpY,
        transform: `translate(-50%, -50%) rotate(${displayAngle}rad)`,
        pointerEvents: 'none',
        userSelect: 'none',
        whiteSpace: 'nowrap',
      }}
    >
      <div
        data-element="equation-probe-card"
        onPointerDown={onIndicatorPointerDown}
        style={{
          background: bgColor,
          backdropFilter: 'blur(6px)',
          borderRadius: 6,
          padding: '3px 8px',
          display: 'inline-block',
          pointerEvents: 'auto',
          cursor: isDragging ? 'grabbing' : 'grab',
          touchAction: 'none',
        }}
      >
        {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
        <math
          {...({ xmlns: 'http://www.w3.org/1998/Math/MathML' } as any)}
          style={{
            fontFamily: mathFontFamily,
            fontSize: 16,
            color,
          }}
        >
          <EquationMml equation={equation} equationForm={equationForm} />
        </math>
      </div>
    </div>
  )
}

// ── Equation MathML ────────────────────────────────────────────────

function EquationMml({
  equation,
  equationForm,
}: {
  equation: EquationForm
  equationForm: EquationDisplayForm
}) {
  switch (equation.kind) {
    case 'point':
      return (
        <mrow>
          <mo>(</mo>
          <mn>{equation.x}</mn>
          <mo>,</mo>
          <mn>{equation.y}</mn>
          <mo>)</mo>
        </mrow>
      )

    case 'vertical':
      return (
        <mrow>
          <mi>x</mi>
          <mo>=</mo>
          <mn>{equation.x}</mn>
        </mrow>
      )

    case 'horizontal':
      return (
        <mrow>
          <mi>y</mi>
          <mo>=</mo>
          <mn>{equation.y}</mn>
        </mrow>
      )

    case 'general':
      if (equationForm === 'standard') {
        return <StandardFormMml slope={equation.slope} intercept={equation.intercept} />
      }
      return <SlopeInterceptMml slope={equation.slope} intercept={equation.intercept} />
  }
}

/** Render y = mx + b */
function SlopeInterceptMml({ slope, intercept }: { slope: Fraction; intercept: Fraction }) {
  const hasIntercept = intercept.num !== 0
  const interceptNeg = intercept.num < 0

  // Special case: slope is 0 → y = b
  if (slope.num === 0) {
    return (
      <mrow>
        <mi>y</mi>
        <mo>=</mo>
        <FractionMml f={intercept} />
      </mrow>
    )
  }

  return (
    <mrow>
      <mi>y</mi>
      <mo>=</mo>
      <SlopeTerm slope={slope} />
      {hasIntercept && (
        <>
          <mo>{interceptNeg ? '\u2212' : '+'}</mo>
          <FractionMml f={interceptNeg ? { num: -intercept.num, den: intercept.den } : intercept} />
        </>
      )}
    </mrow>
  )
}

/** Render an integer coefficient with its variable as a term in standard form */
function StdTerm({
  coeff,
  variable,
  isFirst,
}: {
  coeff: number
  variable: string
  isFirst: boolean
}) {
  if (coeff === 0) return null

  const absCoeff = Math.abs(coeff)
  const neg = coeff < 0

  return (
    <>
      {isFirst ? (
        // First term: show minus sign as unary, no plus
        neg && <mo>&minus;</mo>
      ) : (
        // Subsequent terms: show + or −
        <mo>{neg ? '\u2212' : '+'}</mo>
      )}
      {absCoeff !== 1 && <mn>{absCoeff}</mn>}
      <mi>{variable}</mi>
    </>
  )
}

/** Render Ax + By = C */
function StandardFormMml({ slope, intercept }: { slope: Fraction; intercept: Fraction }) {
  const { a, b, c } = toStandardForm(slope, intercept)

  return (
    <mrow>
      {a !== 0 && <StdTerm coeff={a} variable="x" isFirst />}
      {b !== 0 && <StdTerm coeff={b} variable="y" isFirst={a === 0} />}
      <mo>=</mo>
      <mn>{c < 0 ? `\u2212${Math.abs(c)}` : `${c}`}</mn>
    </mrow>
  )
}