90 lines · 3.3 KB · SwiftRaw
// The pick chip: the chosen option's tint dot and full name, and the menu it// opens, anchored to it: a row per option with its dot and full name, the// current one ticked, the app's sections in the app's order, and an optional// "new…" row at the end. A long list scrolls inside the menu.import SwiftUI#if canImport(UIKit)import UIKit#endifstruct ComposerPickChip: View { let pick: ComposerPick let style: ComposerStyle let identifier: String let picked: (ComposerPickChoice) -> Void var body: some View { Menu { ForEach(pick.sections) { section in Section { ForEach(section.options) { option in Toggle(isOn: Binding(get: { option.id == pick.chosen }, set: { _ in picked(.option(option.id)) })) { Label { Text(verbatim: option.name) } icon: { ComposerPickDot.image(option.tint) } } .accessibilityIdentifier("\(identifier)-pick-\(option.id)") } } header: { if let title = section.title { Text(verbatim: title) } } } if let new = pick.new { Section { Button { picked(.new) } label: { Label { Text(verbatim: new) } icon: { Image(systemName: "plus") } } .accessibilityIdentifier("\(identifier)-pick-new") } } } label: { chip } .menuOrder(.fixed) .accessibilityLabel(Text(verbatim: pick.label)) .accessibilityValue(Text(verbatim: pick.current?.name ?? "")) .accessibilityIdentifier("\(identifier)-pick") } private var chip: some View { HStack(spacing: 7) { if let tint = pick.current?.tint { Circle().fill(tint).frame(width: 10, height: 10) } Text(verbatim: pick.current?.name ?? "") .font(style.chipFace.font) .foregroundStyle(style.ink) .lineLimit(1) .truncationMode(.tail) Image(systemName: "chevron.up.chevron.down") .font(.system(size: 11, weight: .semibold)) .foregroundStyle(style.faint) } .padding(.horizontal, 12) .frame(minHeight: 34) .background(Capsule().fill(style.chip)) .frame(minHeight: 44) .contentShape(Rectangle()) }}/// A tint dot a system menu draws in its own colour: a menu row's image is/// otherwise drawn in the menu's ink.enum ComposerPickDot { static func image(_ tint: Color?) -> Image { #if canImport(UIKit) guard let tint else { return Image(uiImage: UIImage()) } let size = CGSize(width: 14, height: 14) let drawn = UIGraphicsImageRenderer(size: size).image { context in UIColor(tint).setFill() context.cgContext.fillEllipse(in: CGRect(origin: .zero, size: size).insetBy(dx: 1, dy: 1)) } return Image(uiImage: drawn.withRenderingMode(.alwaysOriginal)) #else return Image(systemName: tint == nil ? "" : "circle.fill") #endif }}