SPB Git

Repository Public

WidgetViews.swift 18.8 KB 415 lines swift

1// SP Notes iOS2// File: WidgetShared/WidgetViews.swift3// Description: The views of the note widgets (recent notes, pinned notes, new note, one chosen note) for every supported family,4//              on the Note Visual System 2.0 tokens (`SPNotesDesign`: graphite neutrals, ultramarine accent, serif titles).5//              They take the family as a parameter so they can also be rendered outside WidgetKit (snapshot tests). While the6//              app lock is on they show a redacted state: placeholders and « Verrouillé — ouvre SP Notes », never a title or7//              a preview. In the accented and vibrant rendering modes the tokens give way to the system's primary / secondary8//              styles and to `widgetAccentable`, so nothing relies on colour.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import SPNotesDesign13import SwiftUI14import WidgetKit1516/// The colours of a widget for the rendering mode it is drawn in.17struct WidgetTone {18    var mode: WidgetRenderingMode = .fullColor19    private var full: Bool { mode == .fullColor }2021    static let background = NVColor.bg2223    var fg: AnyShapeStyle { full ? AnyShapeStyle(NVColor.fg) : AnyShapeStyle(.primary) }24    var muted: AnyShapeStyle { full ? AnyShapeStyle(NVColor.fgMuted) : AnyShapeStyle(.secondary) }25    var accent: AnyShapeStyle { full ? AnyShapeStyle(NVColor.accent) : AnyShapeStyle(.primary) }26    var danger: AnyShapeStyle { full ? AnyShapeStyle(NVColor.dangerText) : AnyShapeStyle(.primary) }27    /// Behind a button.28    var soft: AnyShapeStyle { full ? AnyShapeStyle(NVColor.accentSoft) : AnyShapeStyle(Color.primary.opacity(0.14)) }29    /// A redacted line.30    var placeholder: AnyShapeStyle { full ? AnyShapeStyle(NVColor.bgHover) : AnyShapeStyle(Color.primary.opacity(0.2)) }31    var line: AnyShapeStyle { full ? AnyShapeStyle(NVColor.line) : AnyShapeStyle(Color.primary.opacity(0.2)) }32}3334/// Serif titles of the Note Visual System, scaled with Dynamic Type.35enum WidgetFont {36    static let title = Font.system(.headline, design: .serif).weight(.semibold)37    static let rowTitle = Font.system(.subheadline, design: .serif).weight(.semibold)38    static let label = Font.system(.caption).weight(.semibold)39}4041/// Gives the content the tone of the current rendering mode.42struct WidgetToneReader<Content: View>: View {43    @Environment(\.widgetRenderingMode) private var mode44    @ViewBuilder let content: (WidgetTone) -> Content45    var body: some View { content(WidgetTone(mode: mode)) }46}4748/// Which list a list widget shows.49enum WidgetListKind: Sendable {50    case recent, pinned5152    var title: LocalizedStringKey { self == .recent ? "Récentes" : "Épinglées" }53    var symbol: String { self == .recent ? "clock" : "pin.fill" }54    var emptyMessage: LocalizedStringKey { self == .recent ? "Aucune note pour l’instant" : "Épingle une note pour la retrouver ici" }55    /// Opened when the widget has nothing to open in particular.56    var fallbackURL: URL { DeepLink.newNote.url }57}5859extension WidgetFamily {60    var isAccessory: Bool { self == .accessoryCircular || self == .accessoryRectangular || self == .accessoryInline }61    /// Number of notes a list widget shows.62    var noteCapacity: Int {63        switch self {64        case .systemMedium: return 365        case .systemLarge, .systemExtraLarge: return 666        default: return 167        }68    }69}7071/// Time today, otherwise day and month: short enough for a row.72struct WidgetDateText: View {73    let date: Date74    var body: some View {75        if Calendar.current.isDateInToday(date) {76            Text(date, format: .dateTime.hour().minute())77        } else {78            Text(date, format: .dateTime.day().month(.abbreviated))79        }80    }81}8283struct WidgetHeader: View {84    let title: LocalizedStringKey85    let symbol: String86    var tone = WidgetTone()87    var body: some View {88        Label(title, systemImage: symbol)89            .font(WidgetFont.label)90            .foregroundStyle(tone.accent)91            .widgetAccentable()92            .lineLimit(1)93    }94}9596/// Shown when there is nothing to list: the database is not there yet, or the list is empty.97struct WidgetMessageView: View {98    let message: LocalizedStringKey99    var symbol = "note.text"100    var compact = false101    var tone = WidgetTone()102103    var body: some View {104        VStack(spacing: compact ? 2 : 8) {105            if !compact {106                Image(systemName: symbol).font(.title2).foregroundStyle(tone.accent).widgetAccentable().accessibilityHidden(true)107            }108            Text(message)109                .font(compact ? .caption : .footnote.weight(.medium))110                .foregroundStyle(compact ? AnyShapeStyle(.primary) : tone.muted)111                .multilineTextAlignment(.center)112                .minimumScaleFactor(0.8)113        }114        .frame(maxWidth: .infinity, maxHeight: .infinity)115    }116}117118extension WidgetContent {119    static var openAppMessage: LocalizedStringKey { "Ouvre SP Notes pour commencer" }120}121122// MARK: locked (redacted) state123124/// What every widget shows while the app lock is on: grey lines where the content would be and one sentence. No title, no125/// preview, no task text is ever given to this view — there is nothing to un-redact.126struct WidgetLockedView: View {127    let family: WidgetFamily128    /// Header of the widget (its kind is not private).129    var title: LocalizedStringKey?130    var symbol = "lock.fill"131    var tone = WidgetTone()132133    var body: some View {134        switch family {135        case .accessoryCircular:136            ZStack {137                AccessoryWidgetBackground()138                Image(systemName: "lock.fill").font(.title3.weight(.semibold)).widgetAccentable()139            }140            .accessibilityLabel(Text(WidgetLock.message))141        case .accessoryInline:142            Label { Text(WidgetLock.message) } icon: { Image(systemName: "lock.fill") }143        case .accessoryRectangular:144            VStack(alignment: .leading, spacing: 3) {145                Label { Text("SP Notes") } icon: { Image(systemName: "lock.fill") }.font(.caption2.weight(.semibold)).widgetAccentable().lineLimit(1)146                bar(width: 96, height: 8)147                Text(WidgetLock.message).font(.caption2).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.7)148            }149            .frame(maxWidth: .infinity, alignment: .leading)150            .accessibilityElement(children: .ignore)151            .accessibilityLabel(Text(WidgetLock.message))152        default:153            VStack(alignment: .leading, spacing: 0) {154                // Without a title the host view draws its own header (and the lock mark).155                if let title {156                    HStack {157                        WidgetHeader(title: title, symbol: symbol, tone: tone)158                        Spacer(minLength: 0)159                        Image(systemName: "lock.fill").font(.caption.weight(.semibold)).foregroundStyle(tone.muted).widgetAccentable().accessibilityHidden(true)160                    }161                    .padding(.bottom, 10)162                } else {163                    Spacer().frame(height: 6)164                }165                VStack(alignment: .leading, spacing: family == .systemSmall ? 8 : 12) {166                    ForEach(0..<rows, id: \.self) { index in167                        VStack(alignment: .leading, spacing: 5) {168                            bar(width: [0.62, 0.48, 0.7, 0.4, 0.56, 0.5][index % 6] * 200, height: 10)169                            if family != .systemSmall || index == 0 { bar(width: [0.9, 0.72, 0.82, 0.66, 0.9, 0.6][index % 6] * (family == .systemSmall ? 120 : 280), height: 7).opacity(0.7) }170                        }171                    }172                }173                .accessibilityHidden(true)174                Spacer(minLength: 6)175                Text(WidgetLock.message)176                    .font(.caption.weight(.medium))177                    .foregroundStyle(tone.muted)178                    .lineLimit(2)179                    .minimumScaleFactor(0.8)180            }181            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)182        }183    }184185    private var rows: Int { family == .systemLarge || family == .systemExtraLarge ? 5 : 2 }186187    private func bar(width: CGFloat, height: CGFloat) -> some View {188        RoundedRectangle(cornerRadius: height / 2, style: .continuous).fill(tone.placeholder).frame(maxWidth: width).frame(height: height)189    }190}191192// MARK: lists193194struct NotesListWidgetView: View {195    let kind: WidgetListKind196    let content: WidgetContent197    let family: WidgetFamily198199    var body: some View {200        WidgetToneReader { tone in201            if content == .locked {202                WidgetLockedView(family: family, title: kind.title, symbol: kind.symbol, tone: tone)203            } else {204                switch family {205                case .accessoryRectangular: accessory206                case .systemSmall: small(tone)207                default: list(tone)208                }209            }210        }211    }212213    private var message: LocalizedStringKey { content == .unavailable ? WidgetContent.openAppMessage : kind.emptyMessage }214215    @ViewBuilder private var accessory: some View {216        if let note = content.notes.first {217            VStack(alignment: .leading, spacing: 1) {218                Label(kind.title, systemImage: kind.symbol).font(.caption2.weight(.semibold)).widgetAccentable().lineLimit(1)219                Text(note.title).font(.headline).lineLimit(1).privacySensitive()220                if !note.preview.isEmpty { Text(note.preview).font(.caption).lineLimit(1).foregroundStyle(.secondary).privacySensitive() }221            }222            .frame(maxWidth: .infinity, alignment: .leading)223            .widgetURL(note.url)224        } else {225            WidgetMessageView(message: message, compact: true).widgetURL(kind.fallbackURL)226        }227    }228229    @ViewBuilder private func small(_ tone: WidgetTone) -> some View {230        if let note = content.notes.first {231            VStack(alignment: .leading, spacing: 4) {232                WidgetHeader(title: kind.title, symbol: kind.symbol, tone: tone)233                Text(note.title).font(WidgetFont.title).foregroundStyle(tone.fg).lineLimit(2).privacySensitive()234                if !note.preview.isEmpty {235                    Text(note.preview).font(.caption).foregroundStyle(tone.muted).lineLimit(3).privacySensitive()236                }237                Spacer(minLength: 0)238                WidgetDateText(date: note.updatedAt).font(.caption2).foregroundStyle(tone.muted)239            }240            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)241            .widgetURL(note.url)242        } else {243            WidgetMessageView(message: message, symbol: kind == .pinned ? "pin" : "note.text", tone: tone).widgetURL(kind.fallbackURL)244        }245    }246247    @ViewBuilder private func list(_ tone: WidgetTone) -> some View {248        let notes = Array(content.notes.prefix(family.noteCapacity))249        VStack(alignment: .leading, spacing: 0) {250            HStack {251                WidgetHeader(title: kind.title, symbol: kind.symbol, tone: tone)252                Spacer()253                Link(destination: DeepLink.newNote.url) {254                    Image(systemName: "square.and.pencil").font(.subheadline.weight(.semibold)).foregroundStyle(tone.accent).widgetAccentable()255                }256                .accessibilityLabel(Text("Nouvelle note"))257            }258            .padding(.bottom, 6)259            if notes.isEmpty {260                WidgetMessageView(message: message, symbol: kind == .pinned ? "pin" : "note.text", tone: tone)261            } else {262                ForEach(Array(notes.enumerated()), id: \.element.id) { index, note in263                    if index > 0 { Rectangle().fill(tone.line).frame(height: 0.5) }264                    Link(destination: note.url) { WidgetNoteRow(note: note, tone: tone) }265                        .frame(maxHeight: .infinity)266                }267                // Keeps the rows at their natural size when the list is shorter than the widget.268                if notes.count < family.noteCapacity {269                    Spacer(minLength: 0).frame(maxHeight: .infinity).layoutPriority(Double(family.noteCapacity - notes.count))270                }271            }272        }273        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)274        .widgetURL(notes.first?.url ?? kind.fallbackURL)275    }276}277278private struct WidgetNoteRow: View {279    let note: WidgetNote280    let tone: WidgetTone281    var body: some View {282        HStack(alignment: .firstTextBaseline, spacing: 8) {283            VStack(alignment: .leading, spacing: 1) {284                Text(note.title).font(WidgetFont.rowTitle).foregroundStyle(tone.fg).lineLimit(1)285                if !note.preview.isEmpty {286                    Text(note.preview).font(.caption).foregroundStyle(tone.muted).lineLimit(1)287                }288            }289            .privacySensitive()290            Spacer(minLength: 4)291            WidgetDateText(date: note.updatedAt).font(.caption2).foregroundStyle(tone.muted).lineLimit(1).fixedSize()292        }293        .padding(.vertical, 3)294        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)295        .contentShape(Rectangle())296    }297}298299// MARK: new note300301struct NewNoteWidgetView: View {302    let family: WidgetFamily303304    var body: some View {305        WidgetToneReader { tone in306            switch family {307            case .accessoryCircular:308                ZStack {309                    AccessoryWidgetBackground()310                    Image(systemName: "square.and.pencil").font(.title2.weight(.semibold)).widgetAccentable()311                }312                .accessibilityLabel(Text("Nouvelle note"))313                .widgetURL(DeepLink.newNote.url)314            case .systemMedium:315                HStack(spacing: 12) {316                    Link(destination: DeepLink.newNote.url) { WidgetQuickButton(title: "Note", symbol: "square.and.pencil", tone: tone) }317                    Link(destination: DeepLink.new(kind: .tasks, text: nil).url) { WidgetQuickButton(title: "Liste de tâches", symbol: "checklist", tone: tone) }318                }319                .widgetURL(DeepLink.newNote.url)320            default:321                VStack(alignment: .leading, spacing: 0) {322                    Image(systemName: "square.and.pencil")323                        .font(.system(size: 34, weight: .semibold))324                        .foregroundStyle(tone.accent)325                        .widgetAccentable()326                        .accessibilityHidden(true)327                    Spacer(minLength: 0)328                    Text("Nouvelle note").font(WidgetFont.title).foregroundStyle(tone.fg)329                    Text("SP Notes").font(.caption).foregroundStyle(tone.muted)330                }331                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)332                .widgetURL(DeepLink.newNote.url)333            }334        }335    }336}337338/// A large tappable tile (symbol over a label).339struct WidgetQuickButton: View {340    let title: LocalizedStringKey341    let symbol: String342    var tone = WidgetTone()343    var compact = false344    var body: some View {345        VStack(spacing: compact ? 3 : 8) {346            Image(systemName: symbol).font((compact ? Font.body : Font.title).weight(.semibold)).foregroundStyle(tone.accent).widgetAccentable().accessibilityHidden(true)347            Text(title).font((compact ? Font.caption2 : Font.subheadline).weight(.semibold)).foregroundStyle(tone.fg).lineLimit(1).minimumScaleFactor(0.7)348        }349        .frame(maxWidth: .infinity, maxHeight: .infinity)350        .background(tone.soft, in: RoundedRectangle(cornerRadius: compact ? NVRadius.lg : 16, style: .continuous))351        .contentShape(RoundedRectangle(cornerRadius: compact ? NVRadius.lg : 16, style: .continuous))352    }353}354355// MARK: one note356357/// What the configurable widget shows.358enum SingleNoteState: Sendable, Equatable {359    /// No note chosen yet.360    case unconfigured361    /// The chosen note no longer exists (deleted, or the database is not readable).362    case missing363    /// The app lock is on: the note is not read.364    case locked365    case note(WidgetNote)366}367368struct SingleNoteWidgetView: View {369    let state: SingleNoteState370    let family: WidgetFamily371372    var body: some View {373        WidgetToneReader { tone in374            switch state {375            case .locked:376                WidgetLockedView(family: family, title: "Note", symbol: "note.text", tone: tone)377            case .unconfigured:378                WidgetMessageView(message: "Touche le widget de façon prolongée pour choisir une note", symbol: "note.text.badge.plus", tone: tone)379            case .missing:380                WidgetMessageView(message: "Cette note n’est plus disponible", symbol: "questionmark.folder", tone: tone)381            case .note(let note):382                VStack(alignment: .leading, spacing: 4) {383                    HStack(alignment: .firstTextBaseline) {384                        Text(note.title).font(WidgetFont.title).foregroundStyle(tone.fg).lineLimit(family == .systemSmall ? 2 : 1).widgetAccentable()385                        Spacer(minLength: 4)386                        if family != .systemSmall {387                            WidgetDateText(date: note.updatedAt).font(.caption2).foregroundStyle(tone.muted).fixedSize()388                        }389                    }390                    Text(note.preview.isEmpty ? String(localized: "Note vide") : note.preview)391                        .font(family == .systemSmall ? .caption : .footnote)392                        .foregroundStyle(tone.muted)393                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)394                }395                .privacySensitive()396                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)397                .widgetURL(note.url)398            }399        }400    }401}402403// MARK: sample content (gallery placeholders, redacted by the system)404405extension WidgetNote {406    static let samples: [WidgetNote] = [407        WidgetNote(id: "00000000-0000-4000-8000-000000000001", title: "Idées pour le voyage", preview: "Réserver le train, comparer deux hôtels près du port.", updatedAt: .now, pinned: true),408        WidgetNote(id: "00000000-0000-4000-8000-000000000002", title: "Liste d’épicerie", preview: "Pain, tomates, café, fromage", updatedAt: .now.addingTimeInterval(-3_600)),409        WidgetNote(id: "00000000-0000-4000-8000-000000000003", title: "Réunion de lundi", preview: "Ordre du jour et points à suivre", updatedAt: .now.addingTimeInterval(-86_400)),410        WidgetNote(id: "00000000-0000-4000-8000-000000000004", title: "Lectures", preview: "Trois articles à terminer cette semaine", updatedAt: .now.addingTimeInterval(-2 * 86_400)),411        WidgetNote(id: "00000000-0000-4000-8000-000000000005", title: "Budget du mois", preview: "Loyer, transport, sorties", updatedAt: .now.addingTimeInterval(-3 * 86_400)),412        WidgetNote(id: "00000000-0000-4000-8000-000000000006", title: "Citations", preview: "« La simplicité est la sophistication suprême. »", updatedAt: .now.addingTimeInterval(-5 * 86_400)),413    ]414}415
Files main
Menu

Theme