import SwiftUI import BloomKit // MARK: Routes struct TaxonRoute: Hashable { let id: Int } struct EdgesRoute: Hashable { let taxon: Int; let tier: Tier; let plant: Bool } struct InteractionsRoute: Hashable { let taxon: Int; let type: Int } struct LayerRoute: Hashable { let layer: Int var genus: Int? = nil } struct CladeRoute: Hashable { let clade: Int } struct MembersRoute: Hashable { let taxon: Int } struct SpeciesRoute: Hashable { let clade: Int } struct InteractionKindsRoute: Hashable { let taxon: Int } extension EnvironmentValues { /// Pushes a route onto the current tab's stack, for a button or menu that can't be a NavigationLink. @Entry var push: (any Hashable) -> Void = { _ in } } /// A tab's navigation: one path, so every page is pushed by value and lands on top. A page pushed any other /// way (a NavigationLink with a destination view, navigationDestination(item:)) sits outside the path, and a /// value link tapped on it lands underneath, out of sight until you go back. struct TabStack: View { @ViewBuilder let root: Root @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { root.bloomDestinations() } .environment(\.push) { path.append($0) } } } extension View { /// Every route the app pushes, registered once at each tab's root. func bloomDestinations() -> some View { navigationDestination(for: TaxonRoute.self) { TaxonView(id: $0.id) } .navigationDestination(for: EdgesRoute.self) { EdgeListView(route: $0) } .navigationDestination(for: InteractionsRoute.self) { InteractionListView(route: $0) } .navigationDestination(for: LayerRoute.self) { LayerView(layerID: $0.layer, genus: $0.genus) } .navigationDestination(for: CladeRoute.self) { CladeView(cladeID: $0.clade) } .navigationDestination(for: MembersRoute.self) { MembersView(route: $0) } .navigationDestination(for: SpeciesRoute.self) { SpeciesListView(route: $0) } .navigationDestination(for: CommunityRoute.self) { CommunityView(id: $0.id) } .navigationDestination(for: GardenRoute.self) { GardenSupportView(route: $0) } .navigationDestination(for: WatchlistRoute.self) { _ in WatchlistView() } .navigationDestination(for: InteractionKindsRoute.self) { InteractionKindsView(taxonID: $0.taxon) } .navigationDestination(for: MenuRoute.self) { MenuDestination(route: $0) } } } // MARK: Pieces struct Thumb: View { let photo: Photo? /// The taxon's group, for a placeholder that fits it. var group: String? = nil @ScaledMetric(relativeTo: .body) private var scaled: CGFloat = 44 var size: CGFloat? = nil var body: some View { let side = size ?? scaled AsyncImage(url: photo?.url(.square)) { phase in if let image = phase.image { image.resizable().scaledToFill() } else { Color.rule.overlay { Image(systemName: phase.error == nil ? Self.symbol(group) : "photo.badge.exclamationmark") .foregroundStyle(.tertiary) } } } .accessibilityHidden(true) .frame(width: side, height: side) .clipShape(.rect(cornerRadius: 6)) .overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(Color.ink.opacity(0.15), lineWidth: 1) } } static func symbol(_ group: String?) -> String { switch group { case "Aves": "bird" case "Insecta", "Arachnida": "ant" case "Mammalia": "pawprint" case "Reptilia", "Amphibia": "lizard" case "Actinopterygii": "fish" case "Mollusca": "tortoise" case "Fungi": "circle.dotted" case "Plantae": "leaf" default: "photo" } } } /// Common name first, the scientific name under it in italics where the rank calls for it. struct TaxonName: View { let taxon: Taxon var body: some View { VStack(alignment: .leading, spacing: 1) { Text(taxon.title) .font(taxon.titleIsScientific && taxon.italicName ? .binomial(.body).weight(.semibold) : .body.weight(.semibold)) .foregroundStyle(Color.ink).lineLimit(2) if let subtitle = taxon.subtitle { Text(subtitle).font(!taxon.titleIsScientific && taxon.italicName ? .binomial() : .subheadline) .foregroundStyle(.secondary).lineLimit(1) } else if !taxon.italicName { Text(taxon.rank).monoLabel().foregroundStyle(.secondary) } } } } /// Which standing a row shows under the names. enum GradeStyle { case full, exceptions, none } /// A taxon in a list: photo, names, its standing where you are under them, and a count on the right: /// how many listed partners a species has, or how many species a group holds, unless the row brings its own. struct TaxonRow: View { let taxon: Taxon var grade: GradeStyle = .full @ViewBuilder var trailing: Trailing @Environment(AppModel.self) private var model var body: some View { NavigationLink(value: TaxonRoute(id: taxon.id)) { HStack(spacing: 12) { Thumb(photo: taxon.photo, group: taxon.group) VStack(alignment: .leading, spacing: 4) { TaxonName(taxon: taxon) let keystone = model.isKeystone(taxon) if grade != .none || keystone { // Side by side when they fit, stacked when they don't. ViewThatFits(in: .horizontal) { HStack(spacing: 6) { marks(keystone) } VStack(alignment: .leading, spacing: 4) { marks(keystone) } } } } Spacer(minLength: 4) if Trailing.self == EmptyView.self { TaxonMetric(taxon: taxon) } else { trailing } } } } } extension TaxonRow { @ViewBuilder fileprivate func marks(_ keystone: Bool) -> some View { if grade != .none { GradeMark(taxon: taxon, exceptionsOnly: grade == .exceptions) } if keystone { KeystoneMark() } } } extension TaxonRow where Trailing == EmptyView { init(taxon: Taxon, grade: GradeStyle = .full) { self.init(taxon: taxon, grade: grade) { EmptyView() } } } /// A row's count: for a species, its listed partners (animals a plant supports, plants an animal needs); /// for a group, the species in it. struct TaxonMetric: View { @Environment(AppModel.self) private var model let taxon: Taxon @State private var species: Int? var body: some View { if taxon.isSpeciesLevel { let counts = model.support(of: taxon) let n = model.supportCount(taxon) if n > 0 { VStack(alignment: .trailing, spacing: 4) { CountLabel(value: n, unit: taxon.isPlant ? "animals" : "plants") TierBar(counts: counts).frame(width: 64) } } } else { // An empty view never runs its task, so something always stands here while it counts. ZStack { if let species, species > 0 { CountLabel(value: species, unit: "species") } else { Color.clear.frame(width: 1, height: 1) } } .task(id: taxon.id) { species = await model.speciesCount(taxon) } } } } /// The one filter on a list of taxa: only those native where you are. On unless turned off, and kept /// across pages and launches; off, every list still leads with the natives. struct NativeOnlyToggle: View { static let key = "nativeOnly" /// The page's own copy of the setting, so the page and the switch never hold two. @Binding var nativeOnly: Bool @Environment(AppModel.self) private var model var body: some View { Toggle("Native \(model.cell == nil ? "to the US" : "here") only", isOn: $nativeOnly).tint(.moss) } } extension String { /// The first letter capitalized, the rest left alone: "full sun, part shade" reads "Full sun, part shade". var sentenceCased: String { prefix(1).uppercased() + dropFirst() } } /// Filled: a fact about the taxon as a whole (its US status). Outlined: where you are. Dashed: inferred. struct Badge: View { let text: String let color: Color var filled = true var dashed = false @ScaledMetric(relativeTo: .caption2) private var hPad: CGFloat = 6 var body: some View { Text(text).monoLabel() .lineLimit(1) .fixedSize() .padding(.horizontal, hPad).padding(.vertical, 3) .foregroundStyle(filled ? Color.onAccent : color) .background(filled ? color : .clear, in: .rect(cornerRadius: 4)) .overlay { RoundedRectangle(cornerRadius: 4) .strokeBorder(color, style: StrokeStyle(lineWidth: filled ? 0 : 1, dash: dashed ? [3, 2] : [])) } } } /// The lichen plate the site gives keystone genera. struct KeystoneMark: View { var body: some View { Text("Keystone").monoLabel() .padding(.horizontal, 6).padding(.vertical, 3) .foregroundStyle(Color(hex: 0x17180F)) .background(Color.lichen, in: .rect(cornerRadius: 4)) .accessibilityLabel("Keystone genus") } } /// Counts by support tier, as horizontal strata. struct TierBar: View { let counts: [Tier: Int] var height: CGFloat = 6 var body: some View { let total = max(1, counts.values.reduce(0, +)) GeometryReader { geo in HStack(spacing: 1) { ForEach(Tier.ordered, id: \.self) { t in if let n = counts[t], n > 0 { t.color.frame(width: max(2, geo.size.width * CGFloat(n) / CGFloat(total))) } } } } .frame(height: height) .clipShape(.rect(cornerRadius: 1.5)) .accessibilityElement() .accessibilityLabel("Support by kind") .accessibilityValue(Tier.ordered.compactMap { t in counts[t].flatMap { $0 > 0 ? "\(t.title(plant: true)) \($0)" : nil } }.joined(separator: ", ")) } } struct CountLabel: View { let value: Int var unit: String? = nil var body: some View { VStack(alignment: .trailing, spacing: 0) { Text(value, format: .number).font(.system(.body, design: .monospaced).weight(.semibold)).foregroundStyle(Color.ink) if let unit { Text(unit).monoLabel().foregroundStyle(.secondary) } } } } /// A list section's header: bold and sentence case, the size of iOS's prominent headers, so a page scans by /// its sections. The mono capitals stay for small labels above a title. struct SectionLabel: View { let text: String var symbol: String? = nil var body: some View { Label { Text(text).foregroundStyle(Color.ink) } icon: { if let symbol { Image(systemName: symbol).foregroundStyle(Color.moss) } } .labelStyle(SectionLabelStyle(hasIcon: symbol != nil)) .font(.title3.weight(.bold)) .textCase(nil) .accessibilityAddTraits(.isHeader) } } private struct SectionLabelStyle: LabelStyle { let hasIcon: Bool func makeBody(configuration: Configuration) -> some View { HStack(alignment: .firstTextBaseline, spacing: 8) { if hasIcon { configuration.icon.font(.headline) } configuration.title } } } /// A heavy title set in compressed capitals, for the top of a page. Scales with Dynamic Type, capped /// where compressed black would turn into one word a line. struct DisplayTitle: View { let text: String var color: Color = .ink @ScaledMetric private var size: CGFloat = 44 init(text: String, size: CGFloat = 44, color: Color = .ink) { self.text = text self.color = color _size = ScaledMetric(wrappedValue: size, relativeTo: .largeTitle) } var body: some View { Text(text).font(.display(size)).textCase(.uppercase).foregroundStyle(color) .lineLimit(3).minimumScaleFactor(0.85) .dynamicTypeSize(...DynamicTypeSize.accessibility2) .accessibilityAddTraits(.isHeader) } } /// A large number in the display face, scaled with Dynamic Type. struct DisplayNumber: View { let value: Int var color: Color = .ink @ScaledMetric(relativeTo: .title) private var size: CGFloat = 30 var body: some View { Text(value, format: .number).font(.display(size)).foregroundStyle(color) .dynamicTypeSize(...DynamicTypeSize.accessibility2) } } struct EmptyNote: View { let text: String var body: some View { Text(text).font(.footnote).foregroundStyle(.secondary) } } // MARK: Page titles extension View { /// A page whose own hero carries its title: the bar stays (and its scroll edge effect with it), and the /// title fades into it once the hero has scrolled away. func heroTitle(_ title: String, after offset: CGFloat = 120) -> some View { modifier(HeroTitle(title: title, offset: offset)) } } private struct HeroTitle: ViewModifier { let title: String let offset: CGFloat @State private var shown = false func body(content: Content) -> some View { content .onScrollGeometryChange(for: Bool.self) { $0.contentOffset.y + $0.contentInsets.top > offset } action: { _, past in withAnimation(.easeInOut(duration: 0.2)) { shown = past } } .navigationTitle(title) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .principal) { Text(title).font(.headline).foregroundStyle(Color.ink).lineLimit(1).opacity(shown ? 1 : 0) .accessibilityHidden(!shown) } } } }