Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ extension Markdown.InlineCode: InlineConvertible {
)
let encoder = JSONEncoder()
if let payload = try? encoder.encode(attachmentData) {
let attachment = NSTextAttachment(data: payload, ofType: UTType.data.identifier)
let attachment = LatexAttachment(data: payload, ofType: UTType.data.identifier)
return NSMutableAttributedString(attachment: attachment)
}
}
Expand Down
44 changes: 44 additions & 0 deletions Sources/MarkdownText/UI/Paragraph/LatexViewProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

import Foundation
import CoreGraphics
import iosMath
import SwiftUI
#if canImport(UIKit)
Expand All @@ -12,6 +13,45 @@ import UIKit
import AppKit
#endif

#if canImport(UIKit)
final class LatexAttachment: NSTextAttachment {
private static let transparentImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in }

override func image(for bounds: CGRect,
attributes: [NSAttributedString.Key: Any],
location: any NSTextLocation,
textContainer: NSTextContainer?) -> UIImage? {
Self.transparentImage
}
}
#elseif canImport(AppKit)
final class LatexAttachment: NSTextAttachment {
private static let transparentImage: NSImage = {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(
data: nil,
width: 1,
height: 1,
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo
), let cgImage = context.makeImage() else {
return NSImage(size: NSSize(width: 1, height: 1))
}
return NSImage(cgImage: cgImage, size: NSSize(width: 1, height: 1))
}()

override func image(for bounds: NSRect,
attributes: [NSAttributedString.Key: Any],
location: any NSTextLocation,
textContainer: NSTextContainer?) -> NSImage? {
Self.transparentImage
}
}
#endif

// MARK: - LatexAttachmentData Color Resolution

extension LatexAttachmentData {
Expand Down Expand Up @@ -89,6 +129,10 @@ final class LatexViewProvider: NSTextAttachmentViewProvider {

override func loadView() {
let label = MTMathUILabel()
#if canImport(UIKit)
label.isOpaque = false
#endif
label.backgroundColor = .clear
label.latex = latex
label.textColor = textColor
label.displayErrorInline = false
Expand Down