//
// NSAttributedString+Extensions.swift
// NetNewsWire
//
// Created by Nate Weaver on 2020-04-07.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
#if canImport(AppKit)
import AppKit
typealias RSFont = NSFont
#else
import UIKit
typealias RSFont = UIFont
#endif
import RSParser
@MainActor extension NSAttributedString {
/// Returns a copy with `baseFont` merged into each run's existing
/// font attribute, preserving whatever traits (bold, italic, etc.)
/// those runs already had. The base font contributes its family
/// and size; per-run traits win.
///
/// - Parameters:
/// - baseFont: The font whose family and size should be merged
/// into every run.
func applyingBaseFont(_ baseFont: RSFont) -> NSAttributedString {
let mutable = self.mutableCopy() as! NSMutableAttributedString
let fullRange = NSRange(location: 0, length: mutable.length)
let size = baseFont.pointSize
let baseDescriptor = baseFont.fontDescriptor
let baseSymbolicTraits = baseDescriptor.symbolicTraits
mutable.enumerateAttribute(.font, in: fullRange, options: []) { (font, range, _) in
guard let font = font as? RSFont else {
return
}
let currentDescriptor = font.fontDescriptor
let symbolicTraits = baseSymbolicTraits.union(currentDescriptor.symbolicTraits)
var descriptor = currentDescriptor.addingAttributes(baseDescriptor.fontAttributes)
#if canImport(AppKit)
descriptor = descriptor.withSymbolicTraits(symbolicTraits)
#else
descriptor = descriptor.withSymbolicTraits(symbolicTraits)!
#endif
let newFont = RSFont(descriptor: descriptor, size: size)
mutable.addAttribute(.font, value: newFont as Any, range: range)
}
return mutable.copy() as! NSAttributedString
}
/// Initialize an attributed string from text. Style the text
/// based on a small list of allowed inline HTML tags.
///
/// This is not a full HTML renderer. It recognizes only the
/// inline stylistic tags enumerated by `Style.init(forTag:)`.
/// It also decodes HTML character entities
/// (`&`, `…`, etc.).
///
/// Unrecognized tags are dropped and the text between them
/// passes through as literal text. So `click`
/// becomes `click`, `
` disappears entirely (no content),
/// `` becomes `alert(1)`. Tag attributes
/// (`href`, `src`, `class`, etc.) are discarded along with their
/// tags. CSS is not interpreted.
///
/// - Parameters:
/// - simpleHTML: The text to parse. May contain any of the
/// allowed tags above. Any other tag is stripped but
/// its inner text is kept.
/// - locale: The locale used to pick quotation marks when
/// rendering `` tags.
convenience init(simpleHTML: String, locale: Locale = Locale.current) {
self.init(attributedString: Self.buildAttributedString(html: simpleHTML, locale: locale))
}
}
// MARK: - Private
@MainActor private extension NSAttributedString {
enum InTag {
case none
case opening
case closing
}
enum Style {
case bold
case italic
case superscript
case `subscript`
case underline
case strikethrough
case monospace
init?(forTag: String) {
switch forTag {
case "b", "strong":
self = .bold
case "i", "em", "cite", "var", "dfn":
self = .italic
case "sup":
self = .superscript
case "sub":
self = .subscript
case "u", "ins":
self = .underline
case "s", "del":
self = .strikethrough
case "code", "samp", "tt", "kbd":
self = .monospace
default:
return nil
}
}
}
/// Accumulate runs of plain text and flush each run to `NSMutableString`
/// once at the next tag boundary, rather than doing
/// `mutableString.append(String(char))` per grapheme. Record a
/// list of `(range, styles)` pairs during the scan and then hand them
/// off to `applyAttributes`.
static func buildAttributedString(html: String, locale: Locale) -> NSAttributedString {
let baseFont = RSFont.systemFont(ofSize: RSFont.systemFontSize)
var inTag: InTag = .none
var tag = ""
var currentStyles = CountedSet