font size setting
This commit is contained in:
@@ -1,7 +1,41 @@
|
||||
import CoreText
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import SwiftData
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class FontSize {
|
||||
static let shared = FontSize()
|
||||
static let range = 9...20
|
||||
|
||||
private(set) var body = PrefsRecord.defaultFontSize
|
||||
|
||||
private init() {
|
||||
load()
|
||||
}
|
||||
|
||||
func load() {
|
||||
body = record()?.fontSize ?? PrefsRecord.defaultFontSize
|
||||
}
|
||||
|
||||
func set(_ size: Int) {
|
||||
if let r = record() {
|
||||
r.fontSize = size
|
||||
r.saved = Date()
|
||||
} else {
|
||||
persistence.insert(PrefsRecord(fontSize: size))
|
||||
}
|
||||
saveRecords()
|
||||
body = size
|
||||
}
|
||||
|
||||
private func record() -> PrefsRecord? {
|
||||
fetchRecords(FetchDescriptor<PrefsRecord>(sortBy: [SortDescriptor(\.saved, order: .reverse)])).first
|
||||
}
|
||||
}
|
||||
|
||||
enum Fonts {
|
||||
private static func file(_ subset: String, _ italic: Bool, _ weight: CGFloat) -> CTFontDescriptor {
|
||||
let url = Bundle.main.resourceURL!.appending(path: "fonts/atkinson-hyperlegible-mono-\(subset)-wght-\(italic ? "italic" : "normal").woff2")
|
||||
@@ -17,7 +51,10 @@ enum Fonts {
|
||||
|
||||
private static let fonts = Mutex<[String: CTFont]>([:])
|
||||
|
||||
// Call sites give sizes relative to a 13pt body; the user's font size shifts them all.
|
||||
@MainActor
|
||||
private static func cached(_ size: CGFloat, _ weight: CGFloat, _ italic: Bool) -> CTFont {
|
||||
let size = size + CGFloat(FontSize.shared.body - 13)
|
||||
let key = "\(size) \(weight) \(italic)"
|
||||
return fonts.withLock { fonts in
|
||||
if let f = fonts[key] {
|
||||
@@ -29,10 +66,12 @@ enum Fonts {
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
static func font(_ size: CGFloat, weight: CGFloat = 400, italic: Bool = false) -> Font {
|
||||
Font(cached(size, weight, italic))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
static func ns(_ size: CGFloat, weight: CGFloat = 400, italic: Bool = false) -> NSFont {
|
||||
cached(size, weight, italic) as NSFont
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user