Cotton code
505 lines · 19.3 KB · SwiftRaw
// The pieces every Secrets screen is built from, each one of secrets.html's rules by name: the top bar (`.bar`), the// title (`.ph h3`), a section's heading (`h4`), a row (`.r`), a field (`.f`) with its quiet acts, the seal (the one// delight: Reveal unseals the dots left to right, one character every 16 ms), buttons (`.btn`, `.btn.go`,// `.btn.quiet`), pills (`.pill`), a switch (`.tog`), the search field, chips, initial rings (`.av`) and the text tabs// at the foot. Thin rules and space only.#if os(iOS)import SwiftUI/// A 1 px rule across the screen.struct SecretsRule: View {    var body: some View { Rectangle().fill(Plum.rule).frame(height: Plum.hair).accessibilityHidden(true) }}/// `.bar`: Back (named for where it goes) or Cancel at the left, one plain act at the right.struct SecretsBar<Trailing: View>: View {    var back: String?    var cancel: String?    var onBack: () -> Void = {}    @ViewBuilder var trailing: () -> Trailing    @ScaledMetric(relativeTo: .body) private var mark: CGFloat = 20    var body: some View {        HStack(spacing: 10) {            if let back {                Button(action: onBack) {                    HStack(spacing: 2) {                        SecretsMarkView(mark: .back, size: mark, ink: Plum.ink)                        Text(back).font(SecretsType.text(16)).lineLimit(1)                    }                    .foregroundStyle(Plum.ink)                    .frame(minHeight: 44)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityLabel(back)                .accessibilityIdentifier("secrets-back")            } else if let cancel {                Button(cancel, action: onBack)                    .font(SecretsType.text(16))                    .foregroundStyle(Plum.ink)                    .frame(minHeight: 44)                    .buttonStyle(.plain)                    .accessibilityIdentifier("secrets-cancel")            }            Spacer(minLength: 0)            trailing()        }        .frame(minHeight: 44)    }}extension SecretsBar where Trailing == EmptyView {    init(back: String? = nil, cancel: String? = nil, onBack: @escaping () -> Void = {}) {        self.init(back: back, cancel: cancel, onBack: onBack) { EmptyView() }    }}/// The bar's plain act at the right (`.bar .end`: Edit, Save).struct SecretsBarAct: View {    let label: String    var id: String    let action: () -> Void    var body: some View {        Button(label, action: action)            .font(SecretsType.text(16, .semibold))            .foregroundStyle(Plum.ink)            .frame(minHeight: 44)            .buttonStyle(.plain)            .accessibilityIdentifier(id)    }}/// `.ph h3`: the screen's title, 31 bold, wrapping rather than clipping at large text.struct SecretsTitle: View {    let text: String    var body: some View {        Text(text)            .font(SecretsType.title)            .tracking(-0.5)            .foregroundStyle(Plum.ink)            .fixedSize(horizontal: false, vertical: true)            .accessibilityAddTraits(.isHeader)            .padding(.top, 6)            .padding(.bottom, 2)    }}/// `.ph h4`: a section's heading, quiet, with space above.struct SecretsHeading: View {    let text: String    var body: some View {        Text(text)            .font(SecretsType.section)            .foregroundStyle(Plum.quiet)            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.top, 24)            .padding(.bottom, 2)            .accessibilityAddTraits(.isHeader)    }}/// `.note`: a quiet sentence under something.struct SecretsNote: View {    let text: String    var body: some View {        Text(text)            .font(SecretsType.small)            .foregroundStyle(Plum.quiet)            .lineSpacing(2)            .fixedSize(horizontal: false, vertical: true)            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.top, 12)    }}/// `.r`: a row of a list: an optional mark, the name over its second line, and something at the right; a rule under/// it unless it is the last.struct SecretsRow<Lead: View, End: View>: View {    let title: String    var line: String?    var lineMono = false    var last = false    @ViewBuilder var lead: () -> Lead    @ViewBuilder var end: () -> End    @Environment(\.dynamicTypeSize) private var rowSize    var body: some View {        VStack(spacing: 0) {            HStack(spacing: 12) {                lead()                VStack(alignment: .leading, spacing: 2) {                    Text(title)                        .font(SecretsType.rowName)                        .foregroundStyle(Plum.ink)                        .lineLimit(2)                    if let line, !line.isEmpty {                        Text(line)                            .font(lineMono ? SecretsType.mono(14, relativeTo: .footnote) : SecretsType.small)                            .foregroundStyle(Plum.quiet)                            .lineLimit(lineMono ? 1 : rowSize.isAccessibilitySize ? 4 : 2)                            .truncationMode(lineMono ? .middle : .tail)                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                end()            }            .padding(.vertical, 12)            .frame(minHeight: 44)            if !last { SecretsRule() }        }        .contentShape(Rectangle())    }}extension SecretsRow where Lead == EmptyView {    init(title: String, line: String? = nil, lineMono: Bool = false, last: Bool = false, @ViewBuilder end: @escaping () -> End) {        self.init(title: title, line: line, lineMono: lineMono, last: last, lead: { EmptyView() }, end: end)    }}/// A row's quiet word at the right (`.e`), or the accent's when it means "act here" (`.go-t`).struct SecretsEnd: View {    let text: String    var go = false    var body: some View {        Text(text)            .font(SecretsType.text(14, go ? .bold : .regular, relativeTo: .footnote))            .foregroundStyle(go ? Plum.accent : Plum.quiet)    }}/// `.av`: a person's initial in a thin ring.struct SecretsRing: View {    let initial: String    var size: CGFloat = 36    /// The ring grows a little with the phone's text, never past 1.5 times.    @ScaledMetric(relativeTo: .body) private var grow: CGFloat = 1    var body: some View {        let size = self.size * min(grow, 1.5)        // A person known only by their number has no letter to show: the ring holds a plain person, never "+".        Group {            if initial.first?.isLetter == true {                Text(initial).font(SecretsType.text(size * 0.42, .bold))            } else {                Image(systemName: "person").font(.system(size: size * 0.42, weight: .regular))            }        }            .foregroundStyle(Plum.ink)            .frame(width: size, height: size)            .background(Circle().fill(Plum.ground))            .overlay(Circle().strokeBorder(Plum.ink, lineWidth: size > 50 ? 1.5 : size < 30 ? 1.1 : 1.3))            .accessibilityHidden(true)    }}/// Small rings overlapping: the people who hold a secret.struct SecretsHolds: View {    let initials: [String]    var body: some View {        HStack(spacing: -6) {            ForEach(Array(initials.enumerated()), id: \.offset) { _, initial in SecretsRing(initial: initial, size: 24) }        }    }}/// `.btn`: the main act of a screen in the accent (`go`), an outlined one, or a quiet one; 52 tall, full width.struct SecretsButton: View {    enum Weight { case go, outline, quiet }    let label: String    var weight: Weight = .go    var id: String    let action: () -> Void    @Environment(\.isEnabled) private var enabled    var body: some View {        Button(action: action) {            Text(label)                .font(SecretsType.text(17, weight == .quiet ? .semibold : .bold))                .multilineTextAlignment(.center)                .foregroundStyle(weight == .go ? Plum.onAccent : Plum.ink)                .padding(.horizontal, 16)                .padding(.vertical, 12)                .frame(maxWidth: .infinity, minHeight: 52)                .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(weight == .go ? Plum.accent : .clear))                .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous)                    .strokeBorder(weight == .go ? Plum.accent : weight == .outline ? Plum.ink : Plum.rule, lineWidth: Plum.stroke))                .opacity(enabled ? 1 : 0.45)                .contentShape(RoundedRectangle(cornerRadius: 16))        }        .buttonStyle(SecretsPress())        .accessibilityIdentifier(id)    }}/// A press dims, briefly; nothing bounces.struct SecretsPress: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? 0.6 : 1).animation(.easeOut(duration: 0.12), value: configuration.isPressed)    }}/// A field's quiet act (`.acts button`): Reveal, Hide, Copy, Make one, Paste, Open.struct SecretsAct: View {    let label: String    var id: String    /// What VoiceOver says, when the word alone is not enough ("Reveal Password", not "Reveal" three times over).    var spoken: String? = nil    let action: () -> Void    var body: some View {        Button(action: action) {            Text(label)                .font(SecretsType.text(15, .semibold, relativeTo: .subheadline))                .foregroundStyle(Plum.ink)                .padding(.vertical, 4)                .frame(minHeight: 44)                .contentShape(Rectangle())        }        .buttonStyle(SecretsPress())        .accessibilityLabel(spoken ?? label)        .accessibilityIdentifier(id)    }}/// `.f`: a field of one secret: its small label over the value, its acts at the right, a rule under it (in ink when it/// is being typed in).struct SecretsFieldRow<Value: View, Acts: View>: View {    let label: String    var typing = false    @ViewBuilder var value: () -> Value    @ViewBuilder var acts: () -> Acts    @Environment(\.dynamicTypeSize) private var textSize    var body: some View {        VStack(alignment: .leading, spacing: 3) {            Text(label).font(SecretsType.label).foregroundStyle(Plum.quiet)            if textSize.isAccessibilitySize {                // At the largest text the value takes the whole width and its acts sit under it.                value().frame(maxWidth: .infinity, alignment: .leading)                HStack(spacing: 16) { acts() }            } else {                HStack(alignment: .center, spacing: 12) {                    value().frame(maxWidth: .infinity, alignment: .leading)                    HStack(spacing: 16) { acts() }.fixedSize()                }            }        }        .padding(.vertical, 12)        .overlay(alignment: .bottom) { Rectangle().fill(typing ? Plum.ink : Plum.rule).frame(height: Plum.hair) }        .accessibilityElement(children: .contain)    }}/// THE SEAL (secrets.html, "the one delight"): a hidden value as a row of dots; on Reveal the dots unseal left to/// right, one character every 16 ms, each letter dropping into place; Hide closes at once. With reduced motion the/// value just appears. The value is never offered to the pasteboard by selection.struct SecretsSeal: View {    /// The value once revealed; nil while sealed.    let value: String?    /// How many dots stand for it while sealed.    var dots = 12    var size: CGFloat = 17    @State private var shown = 0    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        Group {            if let value {                // Each character its own piece, so it can drop into place; a long value wraps between characters.                SecretsFlow(spacing: 0) {                    ForEach(Array(value.enumerated()), id: \.offset) { index, ch in                        Text(String(ch))                            .font(SecretsType.mono(size))                            .foregroundStyle(Plum.ink)                            .opacity(index < shown ? 1 : 0)                            .offset(y: index < shown ? 0 : -size * 0.35)                    }                }                .accessibilityElement(children: .ignore)                .accessibilityLabel(Text(verbatim: value))                .onAppear { unseal(value.count) }                .onChange(of: value) { _, now in shown = 0; unseal(now.count) }            } else {                Text(String(repeating: "•", count: dots))                    .font(SecretsType.mono(size))                    .foregroundStyle(Plum.quiet)                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    // VoiceOver says it is hidden; the value itself is read only after Reveal.                    .accessibilityLabel(SecretsWords.line("a11y.hidden"))                    .onAppear { shown = 0 }            }        }        // Wrapping long values (an .env line, a token) breaks between characters, never mid-word into a new face.        .textSelection(.disabled)    }    private func unseal(_ count: Int) {        guard !reduceMotion else { shown = count; return }        Task { @MainActor in            for index in 0..<count {                withAnimation(.easeOut(duration: 0.22)) { shown = index + 1 }                try? await Task.sleep(for: .milliseconds(16))            }        }    }}/// `.pill`: one choice of a few; the chosen one outlined in ink and bold.struct SecretsPill: View {    let label: String    let on: Bool    var id: String    let action: () -> Void    var body: some View {        Button(action: action) {            Text(label)                .font(SecretsType.text(15, on ? .bold : .regular, relativeTo: .subheadline))                .foregroundStyle(Plum.ink)                .padding(.horizontal, 14)                .padding(.vertical, 9)                .frame(minHeight: 44)                .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(on ? Plum.ink : Plum.rule, lineWidth: on ? Plum.stroke : Plum.hair))                .contentShape(RoundedRectangle(cornerRadius: 12))        }        .buttonStyle(SecretsPress())        .accessibilityAddTraits(on ? .isSelected : [])        .accessibilityIdentifier(id)    }}/// `.tog`: a switch drawn in ink, for a row of words.struct SecretsSwitchRow: View {    let label: String    var detail: String?    @Binding var on: Bool    var id: String    var body: some View {        VStack(spacing: 0) {            Toggle(isOn: $on) {                HStack(spacing: 6) {                    Text(label).font(SecretsType.body).foregroundStyle(Plum.ink)                    if let detail { Text(detail).font(SecretsType.mono(14)).foregroundStyle(Plum.quiet) }                }            }            .toggleStyle(SecretsToggleStyle())            .padding(.vertical, 12)            .accessibilityIdentifier(id)            SecretsRule()        }    }}struct SecretsToggleStyle: ToggleStyle {    func makeBody(configuration: Configuration) -> some View {        Button { configuration.isOn.toggle() } label: {            HStack {                configuration.label.frame(maxWidth: .infinity, alignment: .leading)                ZStack(alignment: configuration.isOn ? .trailing : .leading) {                    Capsule().fill(configuration.isOn ? Plum.ink : .clear)                    Capsule().strokeBorder(configuration.isOn ? Plum.ink : Plum.rule, lineWidth: Plum.stroke)                    Circle().fill(configuration.isOn ? Plum.ground : Plum.faint).frame(width: 17, height: 17).padding(.horizontal, 4)                }                .frame(width: 44, height: 26)                .animation(.easeOut(duration: 0.16), value: configuration.isOn)            }            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityValue(configuration.isOn ? Text("1") : Text("0"))        .accessibilityAddTraits(.isToggle)    }}/// A list's search field (`.search`).struct SecretsSearch: View {    let prompt: String    @Binding var text: String    var id: String    @ScaledMetric(relativeTo: .body) private var mark: CGFloat = 18    var body: some View {        HStack(spacing: 8) {            SecretsMarkView(mark: .search, size: mark, ink: Plum.faint)            TextField("", text: $text, prompt: Text(prompt).foregroundStyle(Plum.faint))                .font(SecretsType.text(16))                .foregroundStyle(Plum.ink)                .tint(Plum.accent)                .autocorrectionDisabled()                .textInputAutocapitalization(.never)                .submitLabel(.search)                .accessibilityIdentifier(id)        }        .padding(.horizontal, 12)        .padding(.vertical, 10)        .frame(minHeight: 44)        .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Plum.rule, lineWidth: Plum.hair))    }}/// `.chip`: a kind to narrow the list by.struct SecretsChip: View {    let label: String    let on: Bool    var id: String    let action: () -> Void    var body: some View {        Button(action: action) {            Text(label)                .font(SecretsType.text(14, on ? .bold : .regular, relativeTo: .footnote))                .foregroundStyle(on ? Plum.ink : Plum.quiet)                .lineLimit(1)                .fixedSize()                .padding(.horizontal, 12)                .padding(.vertical, 6)                .frame(minHeight: 36)                .overlay(Capsule().strokeBorder(on ? Plum.ink : Plum.rule, lineWidth: Plum.hair))                .contentShape(Capsule())        }        .buttonStyle(SecretsPress())        .accessibilityAddTraits(on ? .isSelected : [])        .accessibilityIdentifier(id)    }}/// A question asked over the screen in Secrets' own words: its title, what it means, the act and Cancel.struct SecretsAskCard: View {    let title: String    let body_: String    let yes: String    let no: String    let answer: (Bool) -> Void    var body: some View {        ZStack(alignment: .bottom) {            Plum.ink.opacity(0.28).ignoresSafeArea().onTapGesture { answer(false) }.accessibilityHidden(true)            VStack(alignment: .leading, spacing: 14) {                Text(title).font(SecretsType.text(22, .bold, relativeTo: .title2)).foregroundStyle(Plum.ink)                    .fixedSize(horizontal: false, vertical: true)                if !body_.isEmpty {                    Text(body_).font(SecretsType.body).foregroundStyle(Plum.ink).lineSpacing(3).fixedSize(horizontal: false, vertical: true)                }                VStack(spacing: 10) {                    SecretsButton(label: yes, weight: .go, id: "secrets-ask-yes") { answer(true) }                    SecretsButton(label: no.isEmpty ? SecretsWords.cancel : no, weight: .quiet, id: "secrets-ask-no") { answer(false) }                }                .padding(.top, 8)            }            .padding(Plum.side)            .padding(.bottom, 8)            .frame(maxWidth: .infinity, alignment: .leading)            .background(UnevenRoundedRectangle(topLeadingRadius: 24, topTrailingRadius: 24).fill(Plum.ground).ignoresSafeArea(edges: .bottom))            .overlay(alignment: .top) { UnevenRoundedRectangle(topLeadingRadius: 24, topTrailingRadius: 24).stroke(Plum.rule, lineWidth: Plum.hair) }            .transition(.move(edge: .bottom))            .accessibilityAddTraits(.isModal)        }    }}#endif