示例工程 44-accessibility-localization-theming

44-accessibility-localization-theming/Sources/Ch44Kit/Accessibility.swift

swift · 8.0 KB

import SwiftUI
 
/// WCAG 对比度计算:输入 sRGB 分量(0...1),返回 1...21 的比值。
public enum Contrast {
    public static func relativeLuminance(red: Double, green: Double, blue: Double) -> Double {
        func linear(_ value: Double) -> Double {
            value <= 0.03928 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4)
        }
        return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue)
    }
 
    public static func ratio(
        foreground: (red: Double, green: Double, blue: Double),
        background: (red: Double, green: Double, blue: Double)
    ) -> Double {
        let first = relativeLuminance(
            red: foreground.red,
            green: foreground.green,
            blue: foreground.blue
        )
        let second = relativeLuminance(
            red: background.red,
            green: background.green,
            blue: background.blue
        )
        let lighter = max(first, second)
        let darker = min(first, second)
        return (lighter + 0.05) / (darker + 0.05)
    }
 
    public static func passesAA(_ ratio: Double, largeText: Bool = false) -> Bool {
        ratio >= (largeText ? 3.0 : 4.5)
    }
}
 
/// 动态字体缩放系数,按 `DynamicTypeSize` 给出近似倍率。
public enum TypeScale {
    public static func factor(for size: DynamicTypeSize) -> Double {
        switch size {
        case .xSmall: 0.82
        case .small: 0.90
        case .medium: 1.00
        case .large: 1.12
        case .xLarge: 1.24
        case .xxLarge: 1.36
        case .xxxLarge: 1.48
        case .accessibility1: 1.65
        case .accessibility2: 1.82
        case .accessibility3: 2.00
        case .accessibility4: 2.20
        case .accessibility5: 2.40
        @unknown default: 1.00
        }
    }
 
    public static func pointSize(base: Double, for size: DynamicTypeSize) -> Double {
        base * factor(for: size)
    }
}
 
/// 最小可读字号:低于这个值就提示设计问题。
public enum Readability {
    public static let minimumBodyPointSize: Double = 11
 
    public static func isReadable(pointSize: Double) -> Bool {
        pointSize >= minimumBodyPointSize
    }
}
 
/// 两种语言的文案表,演示 key 与 fallback。
public enum Strings {
    public enum Key: String, CaseIterable, Sendable {
        case startReading
        case searchPlaceholder
        case emptyTitle
    }
 
    private static let zh: [Key: String] = [
        .startReading: "开始阅读",
        .searchPlaceholder: "搜索教程",
        .emptyTitle: "没有结果",
    ]
 
    private static let en: [Key: String] = [
        .startReading: "Start reading",
        .searchPlaceholder: "Search tutorials",
        .emptyTitle: "No results",
    ]
 
    public static func text(_ key: Key, locale: Locale) -> String {
        let language = locale.language.languageCode?.identifier ?? "en"
        if language == "zh" {
            return zh[key] ?? en[key] ?? key.rawValue
        }
        return en[key] ?? key.rawValue
    }
}
 
/// 减少动态效果时的动画策略。
public enum MotionPolicy: String, Sendable {
    case full
    case reduced
 
    public static func resolve(reduceMotion: Bool) -> MotionPolicy {
        reduceMotion ? .reduced : .full
    }
 
    public var transitionName: String {
        switch self {
        case .full: "位移 + 淡入"
        case .reduced: "仅淡入"
        }
    }
}
 
/// 主题色板,附带对比度检查。
public struct Theme: Sendable {
    public let name: String
    public let foreground: (red: Double, green: Double, blue: Double)
    public let background: (red: Double, green: Double, blue: Double)
 
    public init(
        name: String,
        foreground: (red: Double, green: Double, blue: Double),
        background: (red: Double, green: Double, blue: Double)
    ) {
        self.name = name
        self.foreground = foreground
        self.background = background
    }
 
    public var contrastRatio: Double {
        Contrast.ratio(foreground: foreground, background: background)
    }
}
 
public enum Themes {
    public static let light = Theme(
        name: "浅色",
        foreground: (red: 0.06, green: 0.09, blue: 0.16),
        background: (red: 1, green: 1, blue: 1)
    )
    public static let dark = Theme(
        name: "深色",
        foreground: (red: 0.89, green: 0.91, blue: 0.94),
        background: (red: 0.06, green: 0.09, blue: 0.16)
    )
    public static let accentOnWhite = Theme(
        name: "主色 / 白底",
        foreground: (red: 0.145, green: 0.388, blue: 0.922),
        background: (red: 1, green: 1, blue: 1)
    )
}
 
/// 无障碍卡片:标签、值、提示、 traits 都显式给出。
public struct AccessibleCard: View {
    public init() {}
 
    public var body: some View {
        HStack(spacing: 12) {
            Image(systemName: "book.closed")
                .font(.system(size: 24))
                .accessibilityHidden(true)
            VStack(alignment: .leading, spacing: 4) {
                Text("Swift 教程")
                    .font(.system(size: 15, weight: .semibold))
                Text("60 章 · 从语言到 App")
                    .font(.system(size: 12))
                    .foregroundStyle(.secondary)
            }
            Spacer()
            Button("阅读") {}
                .buttonStyle(.bordered)
                .accessibilityLabel("开始阅读 Swift 教程")
                .accessibilityHint("打开第一章")
        }
        .padding(16)
        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
        .accessibilityElement(children: .combine)
        .accessibilityLabel("Swift 教程,60 章,从语言到 App")
    }
}
 
/// 截图板:对比度、字号、主题。
public struct AccessibilityBoard: View {
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            Text("无障碍与主题")
                .font(.system(size: 18, weight: .semibold))
            ForEach([Themes.light, Themes.dark, Themes.accentOnWhite], id: \.name) { theme in
                HStack(spacing: 10) {
                    RoundedRectangle(cornerRadius: 6)
                        .fill(
                            Color(
                                red: theme.foreground.red,
                                green: theme.foreground.green,
                                blue: theme.foreground.blue
                            )
                        )
                        .frame(width: 28, height: 28)
                        .overlay(
                            RoundedRectangle(cornerRadius: 6)
                                .strokeBorder(.quaternary)
                        )
                    Text(theme.name).font(.system(size: 12))
                    Spacer()
                    Text(String(format: "%.2f:1", theme.contrastRatio))
                        .font(.system(size: 11, design: .monospaced))
                        .foregroundStyle(
                            Contrast.passesAA(theme.contrastRatio) ? Color.secondary : Color.red)
                }
            }
            HStack(spacing: 6) {
                ForEach([DynamicTypeSize.small, .medium, .large, .accessibility2], id: \.self) {
                    size in
                    Text("Aa")
                        .font(.system(size: TypeScale.pointSize(base: 12, for: size)))
                        .frame(width: 40, height: 40)
                        .background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
                }
            }
        }
        .padding(18)
        .frame(width: 360, alignment: .leading)
        .background(Color.white)
    }
}
 
/// 截图:同一张卡片在浅色/深色下的对照。
public struct AccessibleCardBoard: View {
    public let dark: Bool
 
    public init(dark: Bool) {
        self.dark = dark
    }
 
    public var body: some View {
        AccessibleCard()
            .padding(16)
            .frame(width: 360)
            .background(dark ? Color(white: 0.12) : Color.white)
            .environment(\.colorScheme, dark ? .dark : .light)
    }
}