Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,40 @@ struct MyView: View {

### Fonts

The view needs to be able to measure the current font's x-height to correctly size the characters inside of the rendered LaTeX SVG. To do that, the view must use the `UIFont`/`NSFont` classes and do its best to convert SwiftUI's `Font` structure into the correct `UIFont` instance. Currently, the view's functionality is limited to SwiftUI's static largeTitle, title, title1, headline, etc fonts.
The view needs to be able to measure the current font's x-height to correctly size the characters inside of the rendered LaTeX SVG. To do that, the view must use the `UIFont`/`NSFont` classes and do its best to convert SwiftUI's `Font` structure into the correct `UIFont` instance. Currently, the view's functionality is limited to SwiftUI's static largeTitle, title, title1, headline, etc fonts, or by using `UIFont`/`NSFont` types directly.

The `font` modifier has been overloaded so that you can give the `LaTeX` view `UIFont` and `NSFont` types directly. The following examples will render the size of the LaTeX correctly.

```swift
// SwiftUI perferred fonts
LaTeX("Hello, $\\LaTeX$!")
.font(.title)

LaTeX("Hello, $\\LaTeX$!")
.font(.caption)

// Any UIFont/NSFont - note that they should be passed directly to the view
LaTeX("Hello, $\\LaTeX$!")
.font(UIFont.systemFont(ofSize: 30))

LaTeX("Hello, $\\LaTeX$!")
.font(UIFont(name: "Avenir", size: 25)!)
```

The following examples will _not_ render the size of the LaTeX correctly.

```swift
// SwiftUI Font type, but not a preferred font
LaTeX("Hello, $\\LaTeX$!")
.font(.custom(name: "Avenir", size: 25))

LaTeX("Hello, $\\LaTeX$!")
.font(.system(size: 25))

// Wrapping UIFont/NSFont in a SwiftUI Font type
LaTeX("Hello, $\\LaTeX$!")
.font(Font(UIFont.systemFont(ofSize: 30)))
```

### Modifiers

Expand Down
16 changes: 13 additions & 3 deletions Sources/LaTeXSwiftUI/Extensions/EnvironmentValues+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,14 @@ private struct RenderingAnimationKey: EnvironmentKey {
static let defaultValue: Animation? = .none
}

private struct IgnoreSringFormatting: EnvironmentKey {
private struct IgnoreSringFormattingKey: EnvironmentKey {
static let defaultValue: Bool = false
}

private struct PlatformFontKey: EnvironmentKey {
static let defaultValue: _Font? = nil
}

extension EnvironmentValues {

/// The image rendering mode of this environment.
Expand Down Expand Up @@ -154,8 +158,14 @@ extension EnvironmentValues {

/// Whether string formatting such as markdown should be ignored or rendered.
var ignoreStringFormatting: Bool {
get { self[IgnoreSringFormatting.self] }
set { self[IgnoreSringFormatting.self] = newValue }
get { self[IgnoreSringFormattingKey.self] }
set { self[IgnoreSringFormattingKey.self] = newValue }
}

/// The specified UI/NSFont font to use, if any.
var platformFont: _Font? {
get { self[PlatformFontKey.self] }
set { self[PlatformFontKey.self] = newValue }
}

}
7 changes: 7 additions & 0 deletions Sources/LaTeXSwiftUI/Extensions/View+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,11 @@ public extension View {
environment(\.ignoreStringFormatting, ignore)
}

/// Sets the view's UI/NSFont font, if any.
/// - Parameter font: The UI/NSFont font to use.
/// - Returns: A view that uses the provided font.
internal func platformFont(_ font: _Font? = nil) -> some View {
environment(\.platformFont, font)
}

}
23 changes: 20 additions & 3 deletions Sources/LaTeXSwiftUI/LaTeX.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ public struct LaTeX: View {
/// The view's font.
@Environment(\.font) private var font

/// The view's UI/NSFont font.
@Environment(\.platformFont) private var platformFont

// MARK: Private properties

/// The view's renderer.
Expand Down Expand Up @@ -235,6 +238,20 @@ extension LaTeX {
style.makeBody(content: self)
}

#if os(iOS) || os(visionOS)
public func font(_ font: UIFont) -> some View {
self
.platformFont(font)
.font(Font(font))
}
#else
public func font(_ font: NSFont) -> some View {
self
.platformFont(font)
.font(Font(font))
}
#endif

}

// MARK: Private methods
Expand All @@ -255,7 +272,7 @@ extension LaTeX {
parsingMode: parsingMode,
processEscapes: processEscapes,
errorMode: errorMode,
font: font ?? .body,
xHeight: (platformFont?.xHeight ?? font?.xHeight) ?? Font.body.xHeight,
displayScale: displayScale)
}

Expand All @@ -267,7 +284,7 @@ extension LaTeX {
parsingMode: parsingMode,
processEscapes: processEscapes,
errorMode: errorMode,
font: font ?? .body,
xHeight: (platformFont?.xHeight ?? font?.xHeight) ?? Font.body.xHeight,
displayScale: displayScale,
renderingMode: imageRenderingMode)
}
Expand All @@ -282,7 +299,7 @@ extension LaTeX {
parsingMode: parsingMode,
processEscapes: processEscapes,
errorMode: errorMode,
font: font ?? .body,
xHeight: (platformFont?.xHeight ?? font?.xHeight) ?? Font.body.xHeight,
displayScale: displayScale,
renderingMode: imageRenderingMode)
}
Expand Down
5 changes: 2 additions & 3 deletions Sources/LaTeXSwiftUI/Models/Component.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ extension Component {
/// Converts the component to a `Text` view.
///
/// - Parameters:
/// - font: The font to use.
/// - xHeight: The font's x-height.
/// - displayScale: The view's display scale.
/// - renderingMode: The image rendering mode.
/// - errorMode: The error handling mode.
Expand All @@ -202,7 +202,7 @@ extension Component {
/// should be ignored or rendered.
/// - Returns: A text view.
func convertToText(
font: Font,
xHeight: CGFloat,
displayScale: CGFloat,
renderingMode: SwiftUI.Image.TemplateRenderingMode,
errorMode: LaTeX.ErrorMode,
Expand All @@ -227,7 +227,6 @@ extension Component {
}
}
else if let imageContainer {
let xHeight = _Font.preferredFont(from: font).xHeight
let offset = svg.geometry.verticalAlignment.toPoints(xHeight)
text = Text(imageContainer.image).baselineOffset(blockRenderingMode == .alwaysInline || !isInEquationBlock ? offset : 0)
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/LaTeXSwiftUI/Models/ComponentBlock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ extension ComponentBlock {
/// Converts a component block to a `Text` view.
///
/// - Parameters:
/// - font: The font to use.
/// - xHeight: The font's x-height.
/// - displayScale: The display scale.
/// - renderingMode: The rendering mode.
/// - errorMode: The error mode.
Expand All @@ -69,7 +69,7 @@ extension ComponentBlock {
/// should be ignored or rendered.
/// - Returns: A `Text` view.
@MainActor func toText(
font: Font?,
xHeight: CGFloat,
displayScale: CGFloat,
renderingMode: Image.TemplateRenderingMode,
errorMode: LaTeX.ErrorMode,
Expand All @@ -78,7 +78,7 @@ extension ComponentBlock {
) -> Text {
components.enumerated().map { i, component in
return component.convertToText(
font: font ?? .body,
xHeight: xHeight,
displayScale: displayScale,
renderingMode: renderingMode,
errorMode: errorMode,
Expand Down
31 changes: 15 additions & 16 deletions Sources/LaTeXSwiftUI/Models/Renderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,21 +105,21 @@ extension Renderer {
/// - parsingMode: The `parsingMode` environment variable.
/// - processEscapes: The `processEscapes` environment variable.
/// - errorMode: The `errorMode` environment variable.
/// - font: The `font environment` variable.
/// - xHeight: The font's x-height.
/// - displayScale: The `displayScale` environment variable.
func isCached(
latex: String,
unencodeHTML: Bool,
parsingMode: LaTeX.ParsingMode,
processEscapes: Bool,
errorMode: LaTeX.ErrorMode,
font: Font,
xHeight: CGFloat,
displayScale: CGFloat
) -> Bool {
let texOptions = TeXInputProcessorOptions(processEscapes: processEscapes, errorMode: errorMode)
return blocksExistInCache(
parseBlocks(latex: latex, unencodeHTML: unencodeHTML, parsingMode: parsingMode),
font: font,
xHeight: xHeight,
displayScale: displayScale,
texOptions: texOptions)
}
Expand All @@ -132,7 +132,7 @@ extension Renderer {
/// - parsingMode: The `parsingMode` environment variable.
/// - processEscapes: The `processEscapes` environment variable.
/// - errorMode: The `errorMode` environment variable.
/// - font: The `font` environment variable.
/// - xHeight: The font's x-height.
/// - displayScale: The `displayScale` environment variable.
/// - renderingMode: The `renderingMode` environment variable.
@MainActor func renderSync(
Expand All @@ -141,7 +141,7 @@ extension Renderer {
parsingMode: LaTeX.ParsingMode,
processEscapes: Bool,
errorMode: LaTeX.ErrorMode,
font: Font,
xHeight: CGFloat,
displayScale: CGFloat,
renderingMode: SwiftUI.Image.TemplateRenderingMode
) -> [ComponentBlock] {
Expand All @@ -156,7 +156,7 @@ extension Renderer {
let texOptions = TeXInputProcessorOptions(processEscapes: processEscapes, errorMode: errorMode)
blocks = render(
blocks: parseBlocks(latex: latex, unencodeHTML: unencodeHTML, parsingMode: parsingMode),
font: font,
xHeight: xHeight,
displayScale: displayScale,
renderingMode: renderingMode,
texOptions: texOptions)
Expand All @@ -174,7 +174,7 @@ extension Renderer {
/// - parsingMode: The `parsingMode` environment variable.
/// - processEscapes: The `processEscapes` environment variable.
/// - errorMode: The `errorMode` environment variable.
/// - font: The `font` environment variable.
/// - xHeight: The font's x-height.
/// - displayScale: The `displayScale` environment variable.
/// - renderingMode: The `renderingMode` environment variable.
func render(
Expand All @@ -183,7 +183,7 @@ extension Renderer {
parsingMode: LaTeX.ParsingMode,
processEscapes: Bool,
errorMode: LaTeX.ErrorMode,
font: Font,
xHeight: CGFloat,
displayScale: CGFloat,
renderingMode: SwiftUI.Image.TemplateRenderingMode
) async {
Expand All @@ -200,7 +200,7 @@ extension Renderer {
let texOptions = TeXInputProcessorOptions(processEscapes: processEscapes, errorMode: errorMode)
let renderedBlocks = render(
blocks: parseBlocks(latex: latex, unencodeHTML: unencodeHTML, parsingMode: parsingMode),
font: font,
xHeight: xHeight,
displayScale: displayScale,
renderingMode: renderingMode,
texOptions: texOptions)
Expand Down Expand Up @@ -249,14 +249,14 @@ extension Renderer {
///
/// - Parameters:
/// - blocks: The component blocks.
/// - font: The view's font.
/// - xHeight: The font's x-height.
/// - displayScale: The display scale to render at.
/// - renderingMode: The image rendering mode.
/// - texOptions: The MathJax Tex input processor options.
/// - Returns: An array of rendered blocks.
func render(
blocks: [ComponentBlock],
font: Font,
xHeight: CGFloat,
displayScale: CGFloat,
renderingMode: SwiftUI.Image.TemplateRenderingMode,
texOptions: TeXInputProcessorOptions
Expand All @@ -266,7 +266,7 @@ extension Renderer {
do {
let newComponents = try render(
block.components,
xHeight: font.xHeight,
xHeight: xHeight,
displayScale: displayScale,
renderingMode: renderingMode,
texOptions: texOptions)
Expand All @@ -288,7 +288,7 @@ extension Renderer {
///
/// - Parameters:
/// - components: The components to render.
/// - xHeight: The xHeight of the font to use.
/// - xHeight: The font's x-height.
/// - displayScale: The current display scale.
/// - renderingMode: The image rendering mode.
/// - texOptions: The MathJax TeX input processor options.
Expand Down Expand Up @@ -454,11 +454,11 @@ extension Renderer {
///
/// - Parameters:
/// - blocks: The blocks.
/// - font: The `font` environment variable.
/// - xHeight: The font's x-height.
/// - displayScale: The `displayScale` environment variable.
/// - texOptions: The `texOptions` environment variable.
/// - Returns: Whether the blocks are in the renderer's cache.
func blocksExistInCache(_ blocks: [ComponentBlock], font: Font, displayScale: CGFloat, texOptions: TeXInputProcessorOptions) -> Bool {
func blocksExistInCache(_ blocks: [ComponentBlock], xHeight: CGFloat, displayScale: CGFloat, texOptions: TeXInputProcessorOptions) -> Bool {
for block in blocks {
for component in block.components where component.type.isEquation {
let dataCacheKey = Cache.SVGCacheKey(
Expand All @@ -473,7 +473,6 @@ extension Renderer {
return false
}

let xHeight = _Font.preferredFont(from: font).xHeight
let imageCacheKey = Cache.ImageCacheKey(svg: svg, xHeight: xHeight)
guard Cache.shared.imageCacheValue(for: imageCacheKey) != nil else {
return false
Expand Down
58 changes: 58 additions & 0 deletions Sources/LaTeXSwiftUI/Previews/LaTeX_Previews+Fonts.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//
// LaTeX_Previews+Fonts.swift
// LaTeXSwiftUI
//
// Copyright (c) 2025 Colin Campbell
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//

import SwiftUI

#if os(iOS)
import UIKit
typealias PlatformFont = UIFont
#else
import Cocoa
typealias PlatformFont = NSFont
#endif

struct LaTeX_Previews_Fonts: PreviewProvider {

static var previews: some View {
VStack {
LaTeX("Hello, $\\LaTeX$!")
.font(.system(size: 25))

LaTeX("Hello, $\\LaTeX$!")
.font(PlatformFont.preferredFont(forTextStyle: .title1))

LaTeX("Hello, $\\LaTeX$!")
.font(PlatformFont.systemFont(ofSize: 36))

LaTeX("Hello, $\\LaTeX$!")
.font(PlatformFont.boldSystemFont(ofSize: 25))

LaTeX("Hello, $\\LaTeX$!")
.font(PlatformFont(name: "Avenir", size: 25)!)
}
.previewDisplayName("Fonts")
}

}
Loading