aboutsummaryrefslogtreecommitdiff
path: root/Sources/NorgUI/Math/NorgMathRenderer.swift
blob: 4fcf60f75e4d150db4da0a073a88214df3e32dcd (plain)
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
import SwiftUI

#if canImport(UIKit)
  import UIKit
  public typealias PlatformImage = UIImage
#elseif canImport(AppKit)
  import AppKit
  public typealias PlatformImage = NSImage
#endif

public enum NorgMathMode: Sendable {
  case inline
  case block
}

public struct NorgMathImage {
  public let image: PlatformImage
  public let size: CGSize
  public let descent: CGFloat

  public init(image: PlatformImage, size: CGSize, descent: CGFloat) {
    self.image = image
    self.size = size
    self.descent = descent
  }

  public var swiftUIImage: Image {
    #if canImport(UIKit)
      Image(uiImage: image)
    #elseif canImport(AppKit)
      Image(nsImage: image)
    #endif
  }
}

/// Renders LaTeX-style math into an image for display.
public protocol NorgMathRenderer: Sendable {
  /// Render `latex` at the given point size and colour.
  ///
  /// - Returns: the rendered image, or `nil` if the input could not be
  ///   rendered (the caller then keeps its text fallback).
  @MainActor
  func render(
    latex: String, mode: NorgMathMode, fontSize: CGFloat, color: Color?
  ) async -> NorgMathImage?
}