// A project's brand kit, applied to a database's theme in one act (design// note 26203e21, section 6, last line).//// The kit is the project's own record — named colours and role-tagged font// families, as `update_project` writes them. The act lays the kit over the// database's current theme and writes the result as the database's theme// row; nothing else about the theme moves, so a brand on `plain` stays// plain and a brand on `paper` keeps its photographs.//// COLOURS ARE MATCHED BY THEIR NAMES, because a kit's colours are a list a// person named ("Accent red", "Ink", "Paper") and not a set of slots. A word// in the name picks the role; a name with no role word is left alone; and a// kit that names no role at all lends its FIRST colour to the accent, since a// brand's first colour is the one it leads with. The colour rule still binds// the result: one accent, ink and grounds, state in the status colours.//// FONTS ARE MAPPED TO A SHIPPED FACE, because a theme never names a font// file. A family the binary carries is that face; any other is the system// face of its kind (monospaced for a mono, semibold for a display), which is// the nearest a build can draw without shipping the file.//// THE ACCENT IS ALSO THE DATABASE'S CAP AND ITS TAGS, because that is where a// database shows its colour: the cap wears the enamel nearest the accent (a// cap is one of twelve photographed enamels, never a dyed hex), and a family// whose tags are solid fills them with the accent itself, inked to read on it.//// THE KIT ARRIVES AS PLAIN VALUES (`ThemeBrandKit`), never as the record it// was read from: the look calls no core and reads no wire value, so the app// reads the kit off the project's record (`ThemeModel.wear(brand:)`) and hands// the look only what it lays down.importFoundation/// A project's brand kit, as the look reads it: its named colours and its/// role-tagged font families, in the kit's order and in the record's own/// spelling (`{"colors": [{"name", "hex"}], "fonts": [{"role", "family"}]}`)./// A key the record leaves out is nil; what a nil means is the look's rule/// (`Theme.applying(brand:)`), not the reader's.publicstructThemeBrandKit: Codable, Equatable, Sendable {publicstructColour: Codable, Equatable, Sendable {publicvar name: String?publicvar hex: String?publicinit(name: String?, hex: String?) {self.name = nameself.hex = hex } }publicstructFont: Codable, Equatable, Sendable {publicvar role: String?publicvar family: String?publicinit(role: String?, family: String?) {self.role = roleself.family = family } }publicvar colors: [Colour]publicvar fonts: [Font]publicinit(colors: [Colour] = [], fonts: [Font] = []) {self.colors = colorsself.fonts = fonts }}extensionTheme {/// This theme with `brand` laid over it: its named colours on the/// palette's roles, its fonts on the type roles.publicfunc applying(brand: ThemeBrandKit) -> Theme {var theme = selflet colours = brand.colors.compactMap { entry -> (name: String, colour: ThemeColor)? inguardlet hex = entry.hex, let colour = ThemeColor(hex: hex) else { returnnil }return ((entry.name ?? "").lowercased(), colour) }var light = theme.palette.lightvar matched = falsefor (name, colour) in colours {for role inThemeBrandRole.allCases where role.matches(name) { role.apply(colour, to: &light) matched = truebreak } }if !matched, let first = colours.first { light.accent = first.colour }// A palette that was light-only stays light-only.var dark = theme.palette.dark == theme.palette.light ? light : theme.palette.darkif light.accent != palette.light.accent {let tags = ThemeTags(fill: light.accent, ink: Self.ink(on: light.accent, palette: light)) light.tags = tags dark.tags = tags theme.cap.colour = CapColour.nearest(to: light.accent) } theme.palette = ThemePalettes(light: light, dark: dark)for font in brand.fonts {guardlet family = font.family, !family.isEmpty else { continue }ThemeBrandFont(role: font.role ?? "body", family: family).apply(to: &theme.type) }return theme }/// The palette's ink on a light fill, its card on a dark one.staticfunc ink(on fill: ThemeColor, palette: ThemePalette) -> ThemeColor {let luminance = 0.2126 * fill.red + 0.7152 * fill.green + 0.0722 * fill.bluereturn luminance > 0.55 ? palette.ink : palette.paper }}/// The palette roles a kit's colour can be named for, in the order a name is/// tried — the more specific word first, so "Ink (typewriter ribbon)" is the/// ribbon and "Plaster ground" is the muted ground.enumThemeBrandRole: CaseIterable {case print, accent, highlight, mutedGround, paper, ground, inkprivatevar words: [String] {switchself {case .print: return ["ribbon", "typewriter", "print"]case .accent: return ["accent", "primary", "brand"]case .highlight: return ["highlight"]case .mutedGround: return ["plaster", "muted", "surface"]case .paper: return ["paper", "card", "sheet"]case .ground: return ["ground", "background"]case .ink: return ["ink", "text", "foreground"] } }func matches(_ name: String) -> Bool {let tokens = Set(name.split { !$0.isLetter }.map(String.init))return words.contains { tokens.contains($0) } }func apply(_ colour: ThemeColor, to palette: inoutThemePalette) {switchself {case .print: palette.print = colourcase .accent: palette.accent = colourcase .highlight: palette.highlight = colourcase .mutedGround: palette.groundMuted = colourcase .paper: palette.paper = colourcase .ground: palette.ground = colourcase .ink: palette.ink = colour palette.inkBody = colour } }}/// One of a kit's fonts, on the type roles it fills.structThemeBrandFont {let role: Stringlet family: String/// The shipped face a family is, or nil for one the binary does not carry.var shipped: ThemeFace? {let name = family.lowercased()if name.contains("caveat") { return .caveat }if name.contains("instrument") { return .instrumentItalic }if name.contains("courier prime") { return name.contains("italic") ? .courierItalic : .courier }if name.contains("courier") { return .courierNew }if name.contains("fraunces") { return name.contains("text") ? .frauncesText : .frauncesTitle }returnnil }func apply(to type: inoutThemeType) {// The hand and the cap's lettering are faces of their own, whatever// role the kit filed them under.switch shipped {case .caveat?: type.hand = .caveatreturncase .instrumentItalic?: type.cap = .instrumentItalicreturndefault:break }switch role {case"display": type.display = shipped ?? .systemSemibold type.title = shipped.map { $0 == .frauncesTitle ? .frauncesText : $0 } ?? .systemSemiboldcase"mono":let face = shipped ?? .systemMonospaced type.figure = facedefault:let face = shipped ?? .system type.body = face type.meta = face == .courier ? .courierItalic : (face == .system ? .system : face) } }}extensionTheme {/// The theme as its row: every key written, so the row stands alone and a/// later build's default cannot change a theme someone chose. Colours are/// written as `#RRGGBBAA`.publicvar row: Data {func hex(_ colour: ThemeColor) -> String { colour.hexWithAlpha }func palette(_ palette: ThemePalette) -> [String: Any] {var out: [String: Any] = [:]for role inThemePalette.roles { out[role.name] = hex(palette[keyPath: role.path]) } out[ThemeRowForm.Palette.Key.pencil.rawValue] = palette.pencil out[ThemeRowForm.Palette.Key.tags.rawValue] = [ThemeTagKey.fill.rawValue: hex(palette.tags.fill), ThemeTagKey.ink.rawValue: hex(palette.tags.ink), ]return out }var type: [String: Any] = [:]for role inThemeType.roles { type[role.name] = self.type[keyPath: role.path].rawValue }var tokens: [String: Any] = self.scale.values.mapValues { Double($0) } tokens[ThemeScaleKey.radius.rawValue] = Double(self.scale.radius)for knob inThemeScale.knobs { tokens[knob.name] = Double(self.scale[keyPath: knob.path]) }let scale: [String: Any] = [ThemeScaleKey.tokens.rawValue: tokens]var cap: [String: Any] = [ThemeRowForm.Cap.Key.texture.rawValue: self.cap.texture.rawValue]iflet colour = self.cap.colour { cap[ThemeRowForm.Cap.Key.colour.rawValue] = colour.rawValue }let row: [String: Any] = [ThemeRowForm.Key.id.rawValue: id,ThemeRowForm.Key.name.rawValue: name,ThemeRowForm.Key.family.rawValue: family.rawValue,ThemeRowForm.Key.palette.rawValue: [ThemeRowForm.Palettes.Key.light.rawValue: palette(self.palette.light),ThemeRowForm.Palettes.Key.dark.rawValue: palette(self.palette.dark), ],ThemeRowForm.Key.type.rawValue: type,ThemeRowForm.Key.scale.rawValue: scale,ThemeRowForm.Key.texture.rawValue: [ThemeRowForm.Texture.Key.grain.rawValue: texture.grain,ThemeRowForm.Texture.Key.shadow.rawValue: texture.shadow.rawValue,ThemeRowForm.Texture.Key.tilt.rawValue: texture.tilt, ],ThemeRowForm.Key.cap.rawValue: cap, ]return (try? JSONSerialization.data(withJSONObject: row, options: [.sortedKeys])) ?? Data() }}extensionThemeColor {/// `#RRGGBB`, and `#RRGGBBAA` for a colour that is not opaque — what a/// person types and reads.publicvar hex: String {let full = hexWithAlphareturn alpha >= 1 ? String(full.prefix(7)) : full }/// `#RRGGBBAA`, every channel written — the row's spelling.publicvar hexWithAlpha: String {func byte(_ value: Double) -> String { String(format: "%02X", Int((min(1, max(0, value)) * 255).rounded())) }return"#" + byte(red) + byte(green) + byte(blue) + byte(alpha) }}