Restructured the Sample app target in the Xcode project and added its unit tests target as well.

This commit is contained in:
2026-07-05 15:45:09 +02:00
parent 21d86cdc33
commit 8576d6bac6
7 changed files with 665 additions and 51 deletions
+21
View File
@@ -0,0 +1,21 @@
import SwiftUI
/// The entry point of the Attendi sample app.
///
/// The app is a thin shell over the `Features` package. It showcases the Recording feature attached to its real audio services
/// recording audio from the device's microphone, transcribing it on device in a locale picked from a toolbar menu, and presenting
/// the result in a modal sheet while the speech model assets of every picked locale preinstall in the background, with their
/// download events reported through the Notifying feature's transient in-app notifications.
@main
struct AttendiApp: App {
// MARK: Body
/// The content of the app: a single window group showing the ``ContentView``.
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@@ -0,0 +1,236 @@
import Foundation
import Notifying
import Observation
import Recording
extension ContentView {
/// The observable model that drives ``ContentView``.
///
/// The model owns the recording and transcribing services attached to the recording feature, along with the ``locale`` the feature
/// transcribes in, picked in the view's toolbar from the supported ``locales`` that ``load()`` fetches. It also holds the transcription
/// currently presented in the view's modal sheet: ``received(_:)`` presents the transcription of a processed recording, and
/// ``dismissed()`` clears it when the sheet closes.
///
/// Every picked locale kicks off ``preinstall()``, a cancellable task that preinstalls the locale's speech model assets through the
/// preinstalling service cancelling any download still in flight for a previously picked locale. The service's started, cancelled, and
/// failed download events are mapped to the transient, self-dismissing notifications of the ``notifier``.
@MainActor
@Observable
final class Model {
// MARK: Properties
/// The locale of the spoken language to transcribe.
var locale: Locale
/// The transcription currently presented in the modal sheet, or `nil` when none is shown.
var transcription: Transcription?
/// The locales the transcriber supports, sorted by their localized names, or empty while ``load()`` has not finished yet.
private(set) var locales: [Locale]
/// The service that captures the audio from a microphone.
@ObservationIgnored
let capturer: any Capturing
/// The locale whose speech model assets are preinstalled or being preinstalled, or `nil` when none are.
@ObservationIgnored
private var localePreinstalling: Locale?
/// The notifier that owns the transient in-app notifications reporting the download events.
@ObservationIgnored
let notifier: Notifier
/// The service that preinstalls the speech model assets of a picked locale.
@ObservationIgnored
private let preinstaller: any Preinstalling
/// The task that listens to the events emitted by the preinstalling service, or `nil` until the first preinstallation starts.
@ObservationIgnored
private var taskEvents: Task<Void, Never>?
/// The task that preinstalls the speech model assets of the last picked locale, or `nil` until the first locale is picked.
@ObservationIgnored
private var taskPreinstall: Task<Void, Never>?
/// The service that transcribes the recorded audio into text.
@ObservationIgnored
let transcriber: any Transcribing
// MARK: Initializers
/// Creates a model set to the user's current locale, with no supported locales loaded yet, attached to the given services
/// and notifier.
///
/// - Parameters:
/// - capturer: The service that captures the audio from a microphone. Defaults to the on-device ``AudioCapturing``.
/// - preinstaller: The service that preinstalls the speech model assets of a picked locale. Defaults to ``AssetPreinstalling``.
/// - transcriber: The service that transcribes the recorded audio into text. Defaults to the on-device ``AudioTranscribing``.
/// - notifier: The notifier that owns the transient in-app notifications. Defaults to a notifier with its standard dismissal delay.
init(
capturer: any Capturing = AudioCapturing(),
preinstaller: any Preinstalling = AssetPreinstalling(),
transcriber: any Transcribing = AudioTranscribing(),
notifier: Notifier = .init(),
) {
self.locale = .current
self.locales = []
self.capturer = capturer
self.notifier = notifier
self.preinstaller = preinstaller
self.transcriber = transcriber
}
// MARK: Methods
/// Loads the locales the transcriber supports into ``locales``, sorted by their localized names, and aligns ``locale`` with the
/// supported equivalent of its current value falling back to the supported equivalent of a default locale when none exists
/// so the locale picker starts with a valid selection.
func load() async {
locales =
await preinstaller
.supportedLocales()
.sorted {
name(for: $0).localizedStandardCompare(name(for: $1)) == .orderedAscending
}
locale =
if let equivalent = await preinstaller.supportedLocale(equivalentTo: locale) {
equivalent
}
else if let fallback = await preinstaller.supportedLocale(equivalentTo: .byDefault) {
fallback
}
else {
.current
}
preinstall()
}
/// Preinstalls the speech model assets for the current ``locale`` in a cancellable task, cancelling the preinstallation of any
/// previously picked locale still in flight which the ``notifier`` reports as a cancelled download. Does nothing when the
/// current locale is the one already preinstalled or being preinstalled.
func preinstall() {
guard localePreinstalling != locale else {
return
}
taskPreinstall?.cancel()
localePreinstalling = locale
listenToEvents()
taskPreinstall = Task { [locale] in
await preinstaller.preinstall(for: locale)
}
}
/// Returns the localized name of a locale for the locale picker.
///
/// - Parameter locale: The locale to name.
/// - Returns: The name of the locale in the user's current locale, or its identifier when no name is available.
func name(
for locale: Locale
) -> String {
Locale
.current
.localizedString(
forIdentifier: locale.identifier
)?.localizedCapitalized
?? locale.identifier
}
/// Handles the transcription of a processed recording, presenting it in the modal sheet.
///
/// - Parameter transcription: The transcription of the processed recording.
func received(
_ transcription: Transcription
) {
self.transcription = transcription
}
/// Handles the dismissal of the modal sheet.
func dismissed() {
transcription = nil
}
}
}
// MARK: - Helpers
private extension ContentView.Model {
// MARK: Methods
/// Starts listening to the events emitted by the preinstalling service, unless already listening: every started, cancelled, and
/// failed download is posted to the ``ContentView/Model/notifier``, and a cancellation or failure clears the preinstalled locale
/// only when it is still the affected one, so a newer preinstallation is never forgotten letting a re-pick retry.
func listenToEvents() {
guard taskEvents == nil else {
return
}
taskEvents = Task { [weak self, events = preinstaller.events] in
for await event in events {
guard let self else {
return
}
switch event {
case .cancelled(let locale):
if localePreinstalling == locale {
localePreinstalling = nil
}
notifier.post(
.warning,
message: String(localized: .viewRecordingNotificationDownloadCancelled(name(for: locale))),
symbol: Constant.Symbol.cancelled
)
case .failed(let locale):
if localePreinstalling == locale {
localePreinstalling = nil
}
notifier.post(
.error,
message: String(localized: .viewRecordingNotificationDownloadFailed(name(for: locale))),
symbol: Constant.Symbol.failed
)
case .started(let locale):
notifier.post(
.info,
message: String(localized: .viewRecordingNotificationDownloadStarted(name(for: locale))),
symbol: Constant.Symbol.started
)
}
}
}
}
}
// MARK: - Constants
/// The constant values used across the model.
private enum Constant {
/// The symbol constants.
enum Symbol {
/// The system symbol of a cancelled download.
static let cancelled = "xmark.circle"
/// The system symbol of a failed download.
static let failed = "exclamationmark.triangle"
/// The system symbol of a started download.
static let started = "arrow.down.circle"
}
}
private extension Locale {
/// The locale to fall back to when the transcriber supports no equivalent of the user's current locale.
static let byDefault: Locale = .init(identifier: "en_US")
}
@@ -0,0 +1,260 @@
import Notifying
import Recording
import SwiftUI
/// The root view of the Attendi sample app.
///
/// The view hosts the `RecordingView` feature from the `Recording` target of the `Features` package, which drives the whole recording flow,
/// inside a navigation stack, and presents the transcribed text of every processed recording in a modal sheet of its own navigation stack.
/// A toolbar menu picks the locale of the spoken language to transcribe, and every pick kicks off the preinstallation of the locale's speech
/// model assets, whose download events surface as transient in-app notifications banners wearing the `Notifying` target's label
/// style overlaying the feature just below the navigation bar.
///
/// The services attached to the feature, the transcription shown in the sheet, and the notifier owning the notifications live in the view's
/// ``Model``; the view itself only renders it and forwards the feature's output, the picker's changes, and the sheet's dismissal. All
/// user-facing text is localized through the app's string catalog.
struct ContentView: View {
// MARK: Properties
/// The model that owns the attached services, the transcription presented in the modal sheet, and the notifier of the in-app
/// notifications.
@State
private var model: Model
// MARK: Initializers
/// Creates a content view driven by the given model.
///
/// - Parameter model: The model that drives the view. Defaults to a model attached to the on-device services.
init(
model: Model = .init()
) {
self._model = State(initialValue: model)
}
// MARK: Body
/// The content of the view: a navigation stack with the recording feature's view, attached to the model's services and expanded to fill
/// the available space, with a toolbar picker for the locale of the spoken language to transcribe, and a modal sheet presenting the
/// transcribed text of every processed recording or a content unavailable message when the transcription is empty closable
/// through its toolbar button or a swipe. The notifier's in-app notifications overlay the feature, stacking downward just below the
/// navigation bar; each one slides in from the leading edge when posted and out again when its scheduled dismissal arrives, without
/// displacing the recording controls underneath. The notifier also announces every posted notification to assistive technologies,
/// since the banners themselves are transient.
var body: some View {
NavigationStack {
RecordingView(
capturer: model.capturer,
transcriber: model.transcriber,
locale: $model.locale,
) { transcription in
model.received(transcription)
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.navigationTitle(.viewRecordingNavigationTitle)
#if !os(macOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.toolbar {
ToolbarItem(placement: .primaryAction) {
menuLocale
}
}
.overlay(
alignment: .topLeading
) {
stackNotifications
}
.task {
await model.load()
}
.onChange(
of: model.locale,
initial: false
) {
model.preinstall()
}
}
.sheet(item: $model.transcription) { transcription in
sheetTranscription(for: transcription)
}
}
}
// MARK: - Subviews
private extension ContentView {
// MARK: Computed
/// The toolbar menu that picks the locale of the spoken language to transcribe from the supported locales, disabled until
/// they are loaded.
var menuLocale: some View {
Menu {
Picker(
.viewRecordingPickerLocaleTitle,
selection: $model.locale
) {
ForEach(
model.locales,
id: \.self
) {
Text(model.name(for: $0))
.tag($0)
}
}
.pickerStyle(.inline)
} label: {
Label(
.viewRecordingPickerLocaleTitle,
systemImage: "globe"
)
}
.disabled(model.locales.isEmpty)
.accessibilityHint(Text(.viewRecordingPickerLocaleHint))
}
/// The stack of the notifier's in-app notifications, each one sliding in from the leading edge when posted and out again when
/// its scheduled dismissal arrives.
var stackNotifications: some View {
VStack(
alignment: .leading,
spacing: Constant.Spacing.stack
) {
ForEach(
model.notifier.notifications
) { notification in
Label {
Text(notification.message)
} icon: {
Image(systemName: notification.symbol)
.accessibilityHidden(true)
}
.labelStyle(
.notification(
kind: notification.kind
)
)
.accessibilityElement(
children: .combine
)
.transition(
.move(
edge: .leading
).combined(
with: .opacity
)
)
}
}
.padding(.horizontal)
.animation(
.spring,
value: model.notifier.notifications
)
}
// MARK: Methods
/// Returns the content of the modal sheet presenting the given transcription or a content unavailable message when it is
/// empty inside a navigation stack of its own, closable through its toolbar button or a swipe.
///
/// - Parameter transcription: The transcription to present.
/// - Returns: The content of the modal sheet.
func sheetTranscription(
for transcription: Transcription
) -> some View {
NavigationStack {
Group {
if transcription.isEmpty {
ContentUnavailableView(
.viewTranscriptionUnavailableTitle,
systemImage: "text.page.slash",
description: Text(.viewTranscriptionUnavailableDescription)
)
}
else {
ScrollView {
Text(transcription.text)
.font(.body)
.fontWeight(.regular)
.foregroundStyle(.primary)
.frame(
maxWidth: .infinity,
alignment: .leading
)
.padding()
}
}
}
.navigationTitle(.viewTranscriptionNavigationTitle)
#if !os(macOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.toolbar {
Button(role: .close) {
model.dismissed()
}
}
}
.presentationDetents([.medium, .large])
}
}
// MARK: - Constants
/// The constant values used across the view.
private enum Constant {
/// The spacing constants.
enum Spacing {
/// The spacing between the elements of a stack.
static let stack: CGFloat = 8
}
}
// MARK: - Previews
/// The preinstalling service used by the previews, which resolves every locale as supported and downloads nothing.
private struct PreviewPreinstalling: Preinstalling {
/// The stream of events the service emits, which finishes immediately.
let events: AsyncStream<PreinstallingEvent> = .init { continuation in
continuation.finish()
}
func preinstall(
for locale: Locale
) async {
// The previews preinstall no speech model assets.
}
func supportedLocale(
equivalentTo locale: Locale
) async -> Locale? {
locale
}
func supportedLocales() async -> [Locale] {
[
Locale(identifier: "en-US"),
Locale(identifier: "nl-NL"),
]
}
}
#Preview(
"Content view"
) {
ContentView(
model: .init(
preinstaller: PreviewPreinstalling()
)
)
}