Cotton code
288 lines · 13.2 KB · SwiftRaw
// The VOICE NOTE face (image 12): the title typed at the top, the sound as a// row of ink strokes with a dark play button at its middle and the length// under it, the recorded date in the hand, then the transcript's first lines// typed out and fading into a handwritten "continued". The strokes are the// recording's own loudness, handed in by whoever holds its bytes; silence is// a dotted line. Every word is the core's (`FaceRead`).//// A MEETING is drawn on this face (its card's kind, 7f4a5f0fb; house// references 95 and 96) in the house's dress: its title typed heavy, the// day and hour it was held written large by hand under it, its length typed// under that, who spoke on little paper pills (`subtitle`: the core's list// of names, the first few and how many more), its state stamped while it is// still being turned into text (`state`), then the first of the pages its// card turns to (`card.pages`: what was said, the decisions, the transcript;// `DeckCardFill`) typed open-leaded, the turned card's foot saying "continued →". No// loudness is held for the deck, as for every meeting, so no strokes; and// no play button — playing is the fan's Play.import CottonPaperimport CottonValuesimport SwiftUIenum AudioFaceKnobs {    static let inset: CGFloat = 22    static let titleSize: CGFloat = 16    static let titleTop: CGFloat = 52    static let waveHeight: CGFloat = 40    static let waveTop: CGFloat = 34    static let play: CGFloat = 43    static let stroke: CGFloat = 1.3    static let strokeStep: CGFloat = 4.6    /// A peak below this is drawn as a dot: the quiet between words.    static let quiet: Float = 0.08    static let lengthSize: CGFloat = 11.5    static let dateHand: CGFloat = 14.5    static let transcriptSize: CGFloat = 11.8    static let transcriptLeading: CGFloat = 6    static let transcriptLines = 5    static let continuedHand: CGFloat = 15    static let speakersSize: CGFloat = 12.5    static let stampSize: CGFloat = 12    static let stampTurn: Double = -7    // The meeting's dress.    static let meetingInset = EdgeInsets(top: 30, leading: 30, bottom: 34, trailing: 28)    static let meetingTitle: CGFloat = 25    static let meetingDateHand: CGFloat = 24    static let meetingLength: CGFloat = 14    static let meetingSpeakers = 4    static let meetingPreview: CGFloat = 14    static let meetingLeading: CGFloat = 10    static let meetingLines = 7    static let meetingGap: CGFloat = 14}public struct AudioFace: View {    @Environment(\.theme) private var theme    let card: DeckCard    /// The recording's loudness across its length, each 0...1.    let peaks: [Float]    var play: () -> Void = {}    /// Words to type where the transcript goes when the card names none    /// (a meeting's first page).    var preview: String?    /// The preview is a Markdown column's words: set, never typed with marks.    var previewMarkdown = false    /// The pages its card turns to after it (`card.pages`), each a column's    /// words under its label (`FaceTurns`).    var pages: [CardPage] = []    /// The page shown first: 0, the face (a gallery's specimen of a page).    var opened = 0    public init(card: DeckCard, peaks: [Float], play: @escaping () -> Void = {}, preview: String? = nil, previewMarkdown: Bool = false,                pages: [CardPage] = [], opened: Int = 0) {        self.card = card        self.peaks = peaks        self.play = play        self.preview = preview        self.previewMarkdown = previewMarkdown        self.pages = pages        self.opened = opened    }    public var body: some View {        FaceTurns(pages: pages, opened: opened) {            if peaks.isEmpty { meeting } else { voiceNote }        }        .onCardPaper(AudioFaceCatalogue.stock.laid(card.pace))    }    /// A meeting's card: no loudness held, so no strokes and no play button.    private var meeting: some View {        VStack(alignment: .leading, spacing: 0) {            if let title = card.text("title") {                HeavyType(words: title, size: AudioFaceKnobs.meetingTitle)                    .lineLimit(3)                    .minimumScaleFactor(0.75)                    .accessibilityIdentifier("deck-title")                    .facePart(.title)            }            if let date = card.text("date") {                Text(HandRun.tail(date))                    .font(CottonFonts.hand(AudioFaceKnobs.meetingDateHand))                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .faceInk(.ink)                    .padding(.top, AudioFaceKnobs.meetingGap / 2)                    .accessibilityIdentifier("face-date")                    .facePart(.when)            }            if let length = card.text("length") {                Text(length)                    .font(CottonFonts.type(AudioFaceKnobs.meetingLength))                    .lineLimit(1)                    .faceInk(.ink)                    .padding(.top, AudioFaceKnobs.meetingGap / 2)                    .accessibilityIdentifier("face-length")            }            let speakers = card.words("subtitle")            if !speakers.isEmpty {                let shown = speakers.prefix(AudioFaceKnobs.meetingSpeakers)                ChipWrap(spacing: 8) {                    ForEach(Array(shown.enumerated()), id: \.offset) { _, speaker in PaperChip(words: speaker, round: true) }                    if speakers.count > shown.count {                        PaperChip(words: ShellLines.line("cards", "people.more", ["n": "\(speakers.count - shown.count)"]), round: true)                    }                }                .padding(.top, AudioFaceKnobs.meetingGap)                .accessibilityElement(children: .combine)                .accessibilityIdentifier("face-speakers")                .facePart(.subtitle)            }            if let state = card.text("state") {                RubberStamp(words: state.uppercased(), size: AudioFaceKnobs.stampSize, turn: AudioFaceKnobs.stampTurn)                    .padding(.top, AudioFaceKnobs.meetingGap + 4)                    .padding(.leading, 4)                    .facePart(.state)            }            if let said = card.text("body") ?? preview {                Text(previewMarkdown ? FaceMarkdown.set(said, theme: theme) : AttributedString(said))                    .font(CottonFonts.type(AudioFaceKnobs.meetingPreview))                    .lineSpacing(AudioFaceKnobs.meetingLeading)                    .lineLimit(AudioFaceKnobs.meetingLines)                    .truncationMode(.tail)                    .faceInk(.ink)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.top, AudioFaceKnobs.meetingGap + 6)                    .facePart(.body)            }            Spacer(minLength: 0)        }        .padding(AudioFaceKnobs.meetingInset)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)    }    /// A voice note's card: its strokes, the play button at their middle.    private var voiceNote: some View {        VStack(alignment: .leading, spacing: 0) {            if let title = card.text("title") {                Text(title)                    .font(CottonFonts.type(AudioFaceKnobs.titleSize))                    .lineLimit(2)                    .faceInk(.ink)                    .padding(.top, AudioFaceKnobs.titleTop)                    .accessibilityAddTraits(.isHeader)                    .facePart(.title)            }            if let speakers = card.text("subtitle") {                Text(speakers)                    .font(CottonFonts.type(AudioFaceKnobs.speakersSize))                    .lineLimit(2)                    .faceInk(.pencil)                    .padding(.top, 6)                    .accessibilityIdentifier("face-speakers")                    .facePart(.subtitle)            }            InkWaveform(peaks: peaks, gap: AudioFaceKnobs.play + 14)                .frame(height: AudioFaceKnobs.waveHeight)                .overlay {                    Button(action: play) { PlayDisc(size: AudioFaceKnobs.play) }                        .buttonStyle(MotionButtonStyle())                        .accessibilityLabel(card.text("title") ?? "")                        .facePart(.play)                }                .padding(.top, AudioFaceKnobs.waveTop)            if let length = card.text("length") {                Text(length)                    .font(CottonFonts.type(AudioFaceKnobs.lengthSize))                    .faceInk(.ink)                    .frame(maxWidth: .infinity)                    .padding(.top, 12)            }            if let date = card.text("date") {                Text(date)                    .font(CottonFonts.hand(AudioFaceKnobs.dateHand))                    .faceInk(.pencil)                    .padding(.top, 16)                    .facePart(.when)            }            if let state = card.text("state") {                RubberStamp(words: state.uppercased(), size: AudioFaceKnobs.stampSize, turn: AudioFaceKnobs.stampTurn)                    .padding(.top, 18)                    .padding(.leading, 4)                    .facePart(.state)            }            if let transcript = card.text("body") ?? preview {                Text(previewMarkdown ? FaceMarkdown.set(transcript, theme: theme) : AttributedString(transcript))                    .font(CottonFonts.type(AudioFaceKnobs.transcriptSize))                    .lineSpacing(AudioFaceKnobs.transcriptLeading)                    .lineLimit(AudioFaceKnobs.transcriptLines)                    .truncationMode(.tail)                    .faceInk(.ink)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.top, 22)                    .facePart(.body)                Text(ShellLines.line("cards", "audio.continued"))                    .font(CottonFonts.hand(AudioFaceKnobs.continuedHand))                    .faceInk(.pencil)                    .opacity(0.75)                    .padding(.top, 10)            }            Spacer(minLength: 0)        }        .padding(.horizontal, AudioFaceKnobs.inset)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)    }}/// The recording drawn in ink: a stroke per step, as tall as that stretch is/// loud; a dot where it is quiet; a gap at the middle for the play button.struct InkWaveform: View {    let peaks: [Float]    let gap: CGFloat    @Environment(\.theme) private var theme    var body: some View {        Canvas { context, size in            let step = AudioFaceKnobs.strokeStep            let count = Int(size.width / step)            guard count > 0, !peaks.isEmpty else { return }            let mid = size.width / 2            var strokes = Path()            var dots = Path()            for index in 0..<count {                let x = CGFloat(index) * step + step / 2                if abs(x - mid) < gap / 2 { continue }                let peak = peaks[min(peaks.count - 1, index * peaks.count / count)]                if peak < AudioFaceKnobs.quiet {                    dots.addEllipse(in: CGRect(x: x - 1, y: size.height / 2 - 1, width: 2, height: 2))                } else {                    let half = max(2, CGFloat(peak) * size.height / 2)                    strokes.move(to: CGPoint(x: x, y: size.height / 2 - half))                    strokes.addLine(to: CGPoint(x: x, y: size.height / 2 + half))                }            }            let ink = theme.print(.pencil)            context.stroke(strokes, with: .color(ink), style: StrokeStyle(lineWidth: AudioFaceKnobs.stroke, lineCap: .round))            context.fill(dots, with: .color(ink))        }        .blendMode(theme.printBlend)        .accessibilityHidden(true)    }}/// The audio face, by the kind's name, and the cards it is reviewed in: no/// loudness is held for a card, so no strokes; the pages it turns to after/// it, the first fading out on its face.public enum AudioFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "audio", specimens: [Specimen("shelf", shelf.reading { $0.pages = [CardPage(label: "Transcript", text: "Invented: a shallow teak shelf above the counter.")] })]) { card, _, _ in        AudioFace(card: card, peaks: [], preview: card.pages.first?.text, previewMarkdown: card.pages.first?.markdown == true, pages: card.pages)    }    public static let shelf = DeckCard(face: .audio, fields: [        "title": .text("Idea for the kitchen shelf"),        "length": .text("1:18"),        "date": .text("Tue 21 Oct, 7:40 am"),        "body": .text("So I was thinking we could get a shallow shelf above the counter, maybe in teak, to keep the everyday things like chai, mugs and the coffee jar. It should be around 90 cm, not too deep, and the brackets should be the plain black ones from the hardware shop on 12th Main."),    ])    /// An invented recording's loudness: quiet at the ends, speech between.    public static let shelfPeaks: [Float] = (0..<120).map { index in        let t = Float(index) / 119        guard t > 0.08, t < 0.92 else { return 0.02 }        let speech = abs(sin(Float(index) * 0.9) * 0.55 + sin(Float(index) * 0.37) * 0.35)        return min(1, 0.18 + speech)    }}