SPB Git

Repository Public

FontFamilyPicker.swift 11.2 KB 225 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/FontFamilyPicker.swift3// Description: Searchable font family picker: every family previewed in its own face, system designs first, families that are not4//              installed flagged; plus the weights a family really offers.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import CoreText11import DocModel12import DocLayout1314/// Installed families and per-family facts, computed once per launch.15final class FontCatalog {16    static let shared = FontCatalog()17    private(set) lazy var installed: [String] = FontCache.availableFamilies().filter { !FontCache.systemFamilies.contains($0) }18    private var weights: [String: [Int]] = [:]19    private var latin: [String: Bool] = [:]2021    /// CSS-like weights (100…900) the family offers. Families that are not installed report regular and bold.22    func weights(for family: String) -> [Int] {23        if let w = weights[family] { return w }24        var out: [Int]25        switch family {26        case "New York": out = [400, 500, 600, 700, 800, 900]27        case "SF Mono": out = [300, 400, 500, 600, 700, 800]28        case "SF Pro", "SF Pro Display", "SF Pro Text", "SF Pro Rounded", "System": out = [100, 200, 300, 400, 500, 600, 700, 800, 900]29        default:30            let members = NSFontManager.shared.availableMembers(ofFontFamily: family) ?? []31            let set = Set(members.compactMap { m -> Int? in32                guard m.count > 2, let w = m[2] as? Int else { return nil }33                switch w {34                case ...2: return 10035                case 3: return 20036                case 4: return 30037                case 5: return 40038                case 6: return 50039                case 7, 8: return 60040                case 9: return 70041                case 10, 11: return 80042                default: return 90043                }44            })45            out = set.isEmpty ? [400, 700] : set.sorted()46            // Every family can be emboldened by the engine's bold trait; keep the regular/bold pair reachable.47            if out.count == 1 { out = Array(Set(out + [400, 700])).sorted() }48        }49        weights[family] = out50        return out51    }5253    /// Whether the family can draw its own name (symbol and dingbat fonts cannot).54    func drawsLatin(_ family: String) -> Bool {55        if FontCache.systemFamilies.contains(family) { return true }56        if let k = latin[family] { return k }57        let font = CTFontCreateWithName(family as CFString, 12, nil)58        var ok = (CTFontCopyFamilyName(font) as String).caseInsensitiveCompare(family) == .orderedSame59        if ok {60            let chars = Array(family.utf16.filter { $0 != 0x20 })61            var glyphs = [CGGlyph](repeating: 0, count: chars.count)62            ok = chars.isEmpty || CTFontGetGlyphsForCharacters(font, chars, &glyphs, chars.count)63        }64        latin[family] = ok65        return ok66    }6768    static func weightName(_ w: Int) -> String {69        switch w {70        case ..<150: return String(localized: "Ultralight")71        case ..<250: return String(localized: "Thin")72        case ..<350: return String(localized: "Light")73        case ..<450: return String(localized: "Regular")74        case ..<550: return String(localized: "Medium")75        case ..<650: return String(localized: "Semibold")76        case ..<750: return String(localized: "Bold")77        case ..<850: return String(localized: "Heavy")78        default: return String(localized: "Black")79        }80    }81}8283/// The family button and its popover.84struct FontFamilyPicker: View {85    let current: String86    var width: CGFloat = 17687    var identifier = "font-family"88    let onPick: (String) -> Void89    @State private var open = false9091    var body: some View {92        let installed = FontCache.shared.isInstalled(current)93        Button { open = true } label: {94            HStack(spacing: 5) {95                if !installed {96                    Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 10)).foregroundStyle(ORIX.Palette.warning)97                }98                Text(current)99                    .font(installed && FontCatalog.shared.drawsLatin(current) ? .documentFamily(current, size: 12.5) : .system(size: 12))100                    .foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.tail)101                Spacer(minLength: 0)102                Image(systemName: "chevron.up.chevron.down").font(.system(size: 8, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)103            }104            .padding(.horizontal, 7).frame(width: width, height: 24)105            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))106            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(open ? ORIX.Palette.accent : ORIX.Palette.hairline))107            .contentShape(Rectangle())108        }109        .buttonStyle(.plain)110        .help(installed ? Text("Font family") : Text("\(current) is not installed on this Mac. The text is drawn with a substitute."))111        .accessibilityLabel(Text("Font family"))112        .accessibilityValue(installed ? Text(current) : Text("\(current), not installed"))113        .accessibilityIdentifier(identifier)114        .popover(isPresented: $open, arrowEdge: .leading) {115            FontFamilyList(current: current) { family in open = false; onPick(family) }116        }117    }118}119120private struct FontFamilyList: View {121    let current: String122    let onPick: (String) -> Void123    @State private var query = ""124    @State private var highlighted: String?125    /// Row to bring into view after a keyboard move (hovering must not scroll).126    @State private var keyboardTarget: String?127    @FocusState private var searchFocused: Bool128129    private struct Entry: Identifiable { let family: String; let section: Int; var id: String { "\(section)-\(family)" } }130131    private var entries: [Entry] {132        let q = query.trimmingCharacters(in: .whitespaces)133        func keep(_ f: String) -> Bool { q.isEmpty || f.localizedCaseInsensitiveContains(q) }134        var out: [Entry] = []135        // Families the document asks for that this Mac does not have (the current one included).136        var missing = FontCache.shared.missingFamilies137        if !FontCache.shared.isInstalled(current), !missing.contains(current) { missing.insert(current, at: 0) }138        out += missing.filter(keep).map { Entry(family: $0, section: 0) }139        out += FontCache.systemFamilies.filter(keep).map { Entry(family: $0, section: 1) }140        out += FontCatalog.shared.installed.filter(keep).map { Entry(family: $0, section: 2) }141        return out142    }143144    var body: some View {145        let list = entries146        VStack(spacing: 0) {147            HStack(spacing: 6) {148                Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)149                TextField("Search fonts", text: $query)150                    .textFieldStyle(.plain).font(.system(size: 12.5)).focused($searchFocused)151                    .onSubmit { if let f = highlighted ?? list.first?.family { onPick(f) } }152                    .accessibilityIdentifier("font-search")153                if !query.isEmpty {154                    Button { query = "" } label: { Image(systemName: "xmark.circle.fill").font(.system(size: 11)) }155                        .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary).accessibilityLabel(Text("Clear search"))156                }157            }158            .padding(.horizontal, 10).frame(height: 34)159            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)160            ScrollViewReader { proxy in161                ScrollView {162                    LazyVStack(alignment: .leading, spacing: 0) {163                        ForEach(Array(list.enumerated()), id: \.element.id) { index, entry in164                            if index == 0 || list[index - 1].section != entry.section { sectionHeader(entry.section) }165                            row(entry)166                        }167                        if list.isEmpty {168                            Text("No font matches “\(query)”.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).padding(14)169                        }170                    }171                    .padding(.vertical, 4)172                }173                .onChange(of: keyboardTarget) { _, h in if let h, let e = list.first(where: { $0.family == h }) { proxy.scrollTo(e.id) } }174                .onAppear { if let e = list.first(where: { $0.family == current && $0.section > 0 }) ?? list.first(where: { $0.family == current }) { proxy.scrollTo(e.id, anchor: .center) } }175            }176        }177        .frame(width: 268, height: 400)178        .background(ORIX.Palette.chrome)179        .onAppear { searchFocused = true }180        .onChange(of: query) { _, _ in highlighted = nil }181        .onKeyPress(.downArrow) { move(1, in: list); return .handled }182        .onKeyPress(.upArrow) { move(-1, in: list); return .handled }183    }184185    private func move(_ delta: Int, in list: [Entry]) {186        guard !list.isEmpty else { return }187        let i = highlighted.flatMap { h in list.firstIndex { $0.family == h } } ?? (delta > 0 ? -1 : list.count)188        highlighted = list[max(0, min(list.count - 1, i + delta))].family189        keyboardTarget = highlighted190    }191192    private func sectionHeader(_ section: Int) -> some View {193        let title: LocalizedStringKey = section == 0 ? "Not installed" : (section == 1 ? "System designs" : "Installed")194        return Text(title).font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)195            .padding(.horizontal, 12).padding(.top, 8).padding(.bottom, 3)196            .accessibilityAddTraits(.isHeader)197    }198199    private func row(_ entry: Entry) -> some View {200        let family = entry.family201        let missing = entry.section == 0202        let ownFace = !missing && FontCatalog.shared.drawsLatin(family)203        return Button { onPick(family) } label: {204            HStack(spacing: 6) {205                Image(systemName: "checkmark").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.accent).opacity(family == current ? 1 : 0)206                Text(family).font(ownFace ? .documentFamily(family, size: 14) : .system(size: 12.5)).foregroundStyle(ORIX.Palette.text).lineLimit(1)207                Spacer(minLength: 4)208                if missing {209                    Label("Missing", systemImage: "exclamationmark.triangle.fill").font(.system(size: 10, weight: .medium)).foregroundStyle(ORIX.Palette.warning)210                } else if !ownFace {211                    Text(verbatim: "Aa ✦").font(.custom(family, fixedSize: 13)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).accessibilityHidden(true)212                }213            }214            .padding(.horizontal, 10).frame(height: 26)215            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(highlighted == family ? ORIX.Palette.accent.opacity(0.16) : .clear).padding(.horizontal, 4))216            .contentShape(Rectangle())217        }218        .buttonStyle(.plain)219        .onHover { if $0 { highlighted = family } }220        .id(entry.id)221        .accessibilityLabel(missing ? Text("\(family), not installed") : Text(family))222        .accessibilityAddTraits(family == current ? .isSelected : [])223    }224}225
Files main
Menu

Theme