TheNoiseClock/PRD.md

521 lines
28 KiB
Markdown

# TheNoiseClock - Product Requirements Document
## Overview
TheNoiseClock is a SwiftUI-based iOS application that combines a customizable digital clock display with white noise playback and alarm functionality. The app is designed with a dark theme and focuses on providing a clean, distraction-free interface for time display and ambient sound management.
## Core Features
### 1. Digital Clock Display
- **Real-time clock** with automatic updates every second
- **Customizable time format**: 12-hour or 24-hour display
- **Optional seconds display** with toggle control
- **AM/PM badge** for 12-hour format (optional)
- **Segmented time display** with colon separators that adapt to orientation
- **Dynamic scaling** that maximizes available screen space usage
- **Portrait and landscape orientation support** with responsive font sizing
- **Optimal font sizing** that uses all available space efficiently
- **Immediate updates** on orientation changes and tab bar visibility changes
- **Fixed-width digit rendering** to prevent layout shifts and jumping
- **Individual digit views** with consistent spacing and alignment
- **Font customization** with family, weight, and design selection
- **Dynamic dot sizing** that matches selected font weight
- **Safe area handling** with proper Dynamic Island avoidance
- **Full-screen mode** with status bar hiding and tab bar expansion
- **Orientation-aware spacing** for optimal layout in all orientations
### 2. Clock Customization
- **Color customization**: User-selectable digit colors with color picker
- **Background color**: Customizable background with color picker
- **Glow effects**: Adjustable glow intensity (0-100%)
- **Size control**: Manual scaling (0-100%) or auto-fit mode
- **Opacity controls**: Separate opacity for clock digits and overlays
- **Random color mode**: Automatically changes digit color every minute
- **Preset themes**: Quick "Night" (black/white) and "Day" (white/black) themes
- **Font family selection**: Choose from System, San Francisco, Monaco, Courier fonts
- **Font weight options**: Ultra Light, Thin, Light, Regular, Medium, Semibold, Bold, Heavy, Black
- **Font design choices**: Default, Serif, Rounded, Monospaced designs
- **Live font preview**: Real-time preview of font changes in settings
- **Font persistence**: All font settings saved and restored automatically
### 3. Display Modes
- **Normal mode**: Standard interface with navigation and settings
- **Display mode**: Full-screen clock activated by long-press (0.6 seconds)
- **Automatic UI hiding**: Tab bar and navigation elements hide in display mode
- **Smooth transitions**: Animated transitions between modes
- **Status bar control**: Status bar automatically hidden in full-screen mode
- **Safe area expansion**: Clock expands into tab bar area when hidden
- **Dynamic Island awareness**: Proper spacing to avoid Dynamic Island overlap
- **Orientation handling**: Full-screen mode works in both portrait and landscape
- **Keep awake functionality**: Optional screen wake lock to prevent device sleep in display mode
- **Battery optimization**: Wake lock automatically disabled when exiting display mode
### 4. Information Overlays
- **Battery level display**: Real-time battery percentage with icon
- **Date display**: Current date in "d MMMM EEE" format (e.g., "7 September Mon")
- **Overlay opacity control**: Independent opacity for battery/date overlays
- **Automatic updates**: Battery and date update in real-time
### 5. White Noise Player
- **Multiple sound options**:
- White Noise (`white-noise.mp3`)
- Heavy Rain White Noise (`heavy-rain-white-noise.mp3`)
- Fan White Noise (`fan-white-noise-heater-303207.mp3`)
- **Continuous playback**: Sounds loop indefinitely
- **Simple controls**: Play/Stop button with visual feedback
- **Sound selection**: Dropdown picker for sound selection
- **JSON-based configuration**: Sound definitions loaded from external configuration
- **Bundle organization**: Sounds organized in category-based bundles
- **Shared audio player**: Singleton pattern prevents audio conflicts
- **Background audio support**: Continues playing when app is backgrounded
- **Audio interruption handling**: Automatically resumes after phone calls or route changes
- **Wake lock integration**: Prevents device sleep while audio is playing
- **Bluetooth audio support**: Works with AirPods and other Bluetooth audio devices
### 6. Advanced Alarm System
- **Multiple alarms**: Create and manage unlimited alarms
- **Rich alarm editor**: Full-featured alarm creation and editing interface
- **Time selection**: Wheel-style date picker with optimized font sizing for maximum readability
- **Dynamic alarm sounds**: Configurable alarm sounds loaded from JSON configuration
- **Sound preview**: Play/stop functionality for testing alarm sounds before selection
- **Sound organization**: Alarm sounds organized in bundles with categories
- **Custom labels**: User-defined alarm names and descriptions
- **Repeat schedules**: Set alarms to repeat on specific weekdays or daily
- **Sound selection**: Choose from extensive system sounds with live preview
- **Volume control**: Adjustable alarm volume (0-100%)
- **Vibration settings**: Enable/disable vibration for each alarm
- **Snooze functionality**: Configurable snooze duration (5, 7, 8, 9, 10, 15, 20 minutes)
- **Smart notifications**: Automatic scheduling for one-time and repeating alarms
- **Enable/disable toggles**: Individual alarm control with instant feedback
- **Notification integration**: Uses iOS UserNotifications framework with proper scheduling
- **Persistent storage**: Alarms saved to UserDefaults with backward compatibility
- **Alarm management**: Add, edit, delete, and duplicate alarms
- **Next trigger preview**: Shows when the next alarm will fire
- **Responsive time picker**: Font sizes adapt to available space and orientation
## Advanced Clock Display Features
### Fixed-Width Digit Rendering
- **Individual digit views**: Each digit (0-9) rendered in its own view component
- **Consistent spacing**: All digits use the width of the widest digit ("8") for uniform layout
- **Height consistency**: All digits use the height of the tallest digit ("8") to prevent vertical jumping
- **Layout stability**: No shifting or jumping when time changes (e.g., "11" to "12")
- **Perfect centering**: Each digit is centered within its fixed-width container
### Font Customization System
- **Font family selection**: System, San Francisco, Monaco, Courier options
- **Weight variations**: 9 weight options from Ultra Light to Black
- **Design choices**: Default, Serif, Rounded, Monospaced designs
- **Live preview**: Real-time font preview in settings interface
- **UIFont integration**: Proper font measurement for accurate sizing
- **Weight-based dot scaling**: Colon dots automatically scale with font weight
### Dynamic Layout and Sizing
- **GeometryReader integration**: Real-time container size detection
- **Orientation-aware calculations**: Different sizing algorithms for portrait vs landscape
- **Safe area handling**: Proper Dynamic Island avoidance and tab bar expansion
- **Maximum space utilization**: Font sizes calculated to use all available space
- **Responsive updates**: Immediate recalculation on orientation or layout changes
### Advanced Spacing and Alignment
- **Orientation-aware spacing**: Different spacing values for portrait vs landscape
- **Consistent segment spacing**: Uniform spacing between hours, minutes, seconds
- **Dot weight matching**: Colon dots scale with selected font weight
- **Overflow prevention**: Spacing calculations prevent content clipping
- **Perfect centering**: All elements centered both horizontally and vertically
### Full-Screen Mode Enhancements
- **Status bar hiding**: Automatic status bar hiding in full-screen mode
- **Tab bar expansion**: Clock expands into tab bar area when hidden
- **Safe area management**: Proper handling of Dynamic Island and other safe areas
- **Smooth transitions**: Animated transitions between normal and full-screen modes
- **Orientation support**: Full-screen mode works seamlessly in all orientations
## Technical Architecture
### Code Organization Principles
**TOP PRIORITY:** The codebase must be built with the following architectural principles from the beginning:
- **True Separation of Concerns:**
- Many small files with focused responsibilities
- Each module/class should have a single, well-defined purpose
- Avoid monolithic files with mixed responsibilities
- **View Structure Requirements:**
- **Single View Per File:** Each SwiftUI view must be in its own file
- **No Nested Views:** Views should not contain other view structs/classes in the same file
- **Component Extraction:** Complex views must be broken down into smaller, reusable components
- **Clean Main Views:** Main view files should only contain the primary view logic and helper methods
- **Component Organization:** Supporting views should be placed in appropriate `Components/` subdirectories
- **Constants and Enums:**
- Create constants, enums, and configuration objects to avoid duplicate code or values
- Centralize magic numbers, strings, and configuration values
- Use enums for type safety and clarity
- **Readability and Maintainability:**
- Code should be self-documenting with clear naming conventions
- Easy to understand, extend, and refactor
- Consistent patterns throughout the codebase
- **Extensibility:**
- Design for future growth and feature additions
- Modular architecture that allows easy integration of new components
- Clear interfaces between modules
- **Refactorability:**
- Code structure should make future refactoring straightforward
- Minimize coupling between components
- Use dependency injection and abstraction where appropriate
These principles are fundamental to the project's long-term success and must be applied consistently throughout development.
### App Structure
- **Main App**: `TheNoiseClockApp.swift` - Entry point with WindowGroup
- **Tab-based navigation**: Three main tabs (Clock, Alarms, Noise)
- **SwiftUI framework**: Modern declarative UI framework with iOS 18+ and iOS 26 features
- **Dark theme**: Preferred color scheme set to dark
### Data Models
- **ClockStyle**: @Observable class for clock customization settings
- Time format preferences (24-hour, seconds, AM/PM)
- Visual settings (colors, glow, scale, opacity)
- Overlay settings (battery, date, opacity)
- Background settings
- Font customization (family, weight, design)
- Color caching for performance optimization
- Persistent storage with JSON encoding/decoding
- **Alarm**: Codable struct for comprehensive alarm data
- UUID identifier
- Time and enabled state
- Custom label and description
- Repeat schedule (weekdays)
- Sound name with volume control
- Vibration settings
- Snooze duration configuration
- **Sound**: Simple struct for noise file management
- Display name and file name
- **LegacyAlarm**: Backward compatibility struct for old alarm data
### Data Persistence
- **AppStorage**: ClockStyle settings persisted as JSON
- **UserDefaults**: Alarm data persisted as JSON
- **Bundle resources**: Audio files stored in app bundle
### Audio System
- **AVFoundation**: AVAudioPlayer for noise playback
- **@Observable NoisePlayer**: Modern state management with preloading
- **Looping playback**: Infinite loop for ambient sounds
- **Audio session management**: Proper audio session configuration with background support
- **Error handling**: Graceful handling of missing audio files
- **AlarmTonePlayer**: Dedicated player for alarm sound previews
- **Background audio**: Continues playback when app is backgrounded
- **Interruption handling**: Automatic resume after phone calls and route changes
- **Wake lock integration**: Prevents device sleep during audio playback
- **Focus mode awareness**: Monitors and respects Focus mode settings
- **Notification compatibility**: Ensures alarms work with Focus modes enabled
### Notification System
- **UserNotifications**: iOS notification framework
- **Permission handling**: Automatic permission requests
- **Smart scheduling**: One-time and repeating alarm support
- **Calendar triggers**: Precise alarm scheduling with weekday support
- **Sound customization**: System sound selection with volume control
- **Multiple notifications**: Support for repeating alarms with unique identifiers
### Wake Lock System
- **WakeLockService**: Singleton service for managing screen wake lock
- **Display mode integration**: Automatically enables wake lock in full-screen display mode
- **Audio integration**: Enables wake lock during audio playback to prevent device sleep
- **Battery optimization**: Automatic wake lock management with proper cleanup
- **Timer-based maintenance**: Periodic wake lock refresh to ensure continuous operation
- **State management**: Tracks wake lock status and provides toggle functionality
### Focus Mode Integration
- **FocusModeService**: Comprehensive service for handling Focus mode interactions
- **Notification compatibility**: Ensures alarms work properly with Focus modes
- **Audio awareness**: Monitors Focus mode status for audio playback decisions
- **Permission management**: Requests notification permissions compatible with Focus modes
- **Alarm scheduling**: Uses Focus mode-aware notification scheduling
- **User settings**: Toggle to respect or override Focus mode restrictions
- **Guidance system**: Provides user instructions for optimal Focus mode configuration
## User Interface Design
### Navigation
- **TabView**: Three-tab interface (Clock, Alarms, Noise)
- **NavigationStack**: Modern navigation with back button support
- **Navigation destinations**: Deep linking for alarm editing
- **Toolbar integration**: Settings and add buttons in navigation bars
- **Sheet presentations**: Modal settings and alarm creation
### Visual Design
- **Rounded corners**: Modern iOS design language
- **Modern animations**: iOS 18+ smooth and bouncy animations
- **Color consistency**: Blue accent color throughout
- **Accessibility**: Proper labels and hidden decorative elements
- **Form-based layouts**: Organized sections for settings and alarm editing
- **Interactive controls**: Toggles, sliders, color pickers, and date pickers
### Settings Interface
- **Form-based layout**: Organized sections for different setting categories
- **Interactive controls**: Toggles, sliders, color pickers
- **Real-time updates**: Changes apply immediately
- **Sheet presentation**: Modal settings with detents
## File Structure and Organization
### Recommended File Organization
Following the separation of concerns principle, the codebase should be organized into focused, single-responsibility files:
```
TheNoiseClock/
├── App/
│ ├── TheNoiseClockApp.swift # App entry point and configuration
│ └── ContentView.swift # Main tab navigation coordinator
├── Core/
│ ├── Constants/
│ │ ├── AppConstants.swift # App-wide constants and configuration
│ │ ├── UIConstants.swift # UI-specific constants (colors, sizes, etc.)
│ │ └── AudioConstants.swift # Audio-related constants
│ ├── Extensions/
│ │ ├── Color+Extensions.swift # Color utilities and extensions
│ │ ├── Date+Extensions.swift # Date formatting and utilities
│ │ └── View+Extensions.swift # Common view modifiers and responsive utilities
│ └── Utilities/
│ ├── ColorUtils.swift # Color manipulation utilities
│ ├── FontUtils.swift # Font sizing, typography, and customization utilities
│ └── NotificationUtils.swift # Notification helper functions
├── Models/
│ ├── ClockStyle.swift # Clock customization data model
│ ├── Alarm.swift # Alarm data model
│ ├── Sound.swift # Sound data model
│ └── LegacyAlarm.swift # Backward compatibility model
├── ViewModels/
│ ├── ClockViewModel.swift # Clock display logic and state
│ ├── AlarmViewModel.swift # Alarm management logic
│ └── NoiseViewModel.swift # Audio playback state management
├── Views/
│ ├── Clock/
│ │ ├── ClockView.swift # Main clock display view
│ │ ├── ClockSettingsView.swift # Clock customization interface
│ │ └── Components/
│ │ ├── TimeDisplayView.swift # Advanced segmented time display with fixed-width digits
│ │ ├── BatteryOverlayView.swift # Battery level overlay
│ │ ├── DateOverlayView.swift # Date display overlay
│ │ └── TopOverlayView.swift # Combined overlay container
│ ├── Alarms/
│ │ ├── AlarmView.swift # Main alarm management view
│ │ ├── AddAlarmView.swift # Alarm creation interface
│ │ └── Components/
│ │ ├── AlarmRowView.swift # Individual alarm row component
│ │ ├── TimePickerSection.swift # Time selection component
│ │ ├── TimeUntilAlarmSection.swift # Time calculation display
│ │ ├── SoundSelectionView.swift # Sound selection with preview
│ │ ├── LabelEditView.swift # Label editing interface
│ │ └── SnoozeSelectionView.swift # Snooze duration selection
│ └── Noise/
│ ├── NoiseView.swift # Main white noise player interface
│ └── Components/
│ ├── SoundPickerView.swift # Sound selection component
│ └── SoundControlView.swift # Playback controls component
├── Services/
│ ├── NoisePlayer.swift # Audio playback service with background support
│ ├── AlarmService.swift # Alarm management service with Focus mode integration
│ ├── NotificationService.swift # Notification handling service
│ ├── WakeLockService.swift # Screen wake lock management service
│ └── FocusModeService.swift # Focus mode integration and notification management
└── Resources/
├── sounds.json # Sound configuration and definitions
├── Ambient.bundle/ # Ambient sound category
│ └── white-noise.mp3
├── Nature.bundle/ # Nature sound category
│ └── heavy-rain-white-noise.mp3
├── Mechanical.bundle/ # Mechanical sound category
│ └── fan-white-noise-heater.mp3
├── AlarmSounds.bundle/ # Alarm sound category
│ ├── digital-alarm.mp3
│ ├── iphone-alarm.mp3
│ ├── classic-alarm.mp3
│ ├── beep-alarm.mp3
│ ├── siren-alarm.mp3
│ └── voice-wakeup.mp3
└── Assets.xcassets/
└── [Asset catalogs]
```
### File Naming Conventions
- **Views**: Use descriptive names ending in `View` (e.g., `ClockView`, `AlarmRowView`)
- **ViewModels**: End with `ViewModel` (e.g., `ClockViewModel`, `AlarmViewModel`)
- **Services**: End with `Service` (e.g., `AlarmService`, `NotificationService`)
- **Models**: Use noun names (e.g., `Alarm`, `Sound`, `ClockStyle`)
- **Extensions**: Use `Type+Extensions` format (e.g., `Color+Extensions`)
- **Constants**: Use descriptive names ending in `Constants` (e.g., `AppConstants`)
### Code Organization Best Practices
- **Single Responsibility**: Each file should have one clear purpose
- **Dependency Injection**: Use protocols and dependency injection for testability
- **Protocol-Oriented Design**: Define protocols for services and data sources
- **Error Handling**: Centralized error types and handling patterns
- **Testing**: Separate test targets with comprehensive coverage
### Documentation Maintenance Requirements
**CRITICAL:** The PRD must be kept up-to-date with all code changes. The following procedures are mandatory:
#### Automatic PRD Updates
- **Every code change** that affects architecture, features, or file structure **MUST** include a corresponding PRD update
- **AI Assistant Responsibility**: When making code changes, the AI assistant must automatically:
1. **Identify PRD sections** that need updating based on the changes made
2. **Update relevant sections** without being asked
3. **Add new features** to the appropriate feature sections
4. **Update file structure** when new files or components are created
5. **Document new requirements** or architectural decisions
6. **Maintain consistency** between code and documentation
#### PRD Update Triggers
The following changes **automatically require** PRD updates:
- **New files or components** → Update file structure section
- **New features or functionality** → Update core features section
- **Architectural changes** → Update code organization principles
- **New services or models** → Update technical architecture
- **UI/UX changes** → Update user interaction sections
- **Configuration changes** → Update technical requirements
- **Bundle or resource changes** → Update resources section
#### Documentation Standards
- **Real-time updates**: PRD updates should happen in the same conversation as code changes
- **Comprehensive coverage**: All aspects of changes must be documented
- **Version consistency**: Code and documentation must always be in sync
- **No manual requests**: Users should not need to ask for PRD updates
## Key User Interactions
### Clock Tab
1. **View time**: Real-time clock display
2. **Access settings**: Tap gear icon in navigation bar
3. **Enter display mode**: Long-press anywhere on clock (0.6 seconds)
4. **Exit display mode**: Long-press again to return to normal mode
### Settings
1. **Time format**: Toggle 24-hour, seconds, AM/PM display
2. **Appearance**: Adjust colors, glow, size, opacity
3. **Display**: Control keep awake functionality for display mode
4. **Focus Modes**: Control how app behaves with Focus modes (Do Not Disturb)
5. **Overlays**: Control battery and date display
6. **Background**: Set background color and use presets
### Alarms Tab
1. **View alarms**: List of all created alarms with labels and repeat schedules
2. **Add alarm**: Tap + button to create new alarm with full editor
3. **Edit alarm**: Tap any alarm to open comprehensive editor
4. **Toggle alarm**: Use switch to enable/disable
5. **Delete alarm**: Swipe to delete or use delete button in editor
6. **Alarm editor features**:
- Time picker with next trigger preview
- Custom label editing
- Repeat schedule selection
- Sound picker with live preview
- Volume and vibration controls
- Snooze duration settings
### Noise Tab
1. **Select sound**: Choose from dropdown menu
2. **Play/Stop**: Single button to control playback
3. **Continuous playback**: Sounds loop until stopped
## Technical Requirements
### iOS Compatibility
- **Minimum iOS version**: iOS 18.0+ (Latest SwiftUI features and performance optimizations)
- **Target devices**: iPhone and iPad with full adaptive layout support
- **Orientation support**: Portrait and landscape with dynamic type support
- **Accessibility**: Full VoiceOver and Dynamic Type support
### Modern iOS Technology Stack
- **SwiftUI**: Latest declarative UI framework with iOS 18+ and iOS 26 features
- **Observation Framework**: Modern @Observable pattern for state management
- **SwiftData**: Advanced data persistence with iOS 18+ SwiftData features
- **Async/Await**: Modern concurrency patterns throughout
- **Structured Concurrency**: Task groups and actors for complex operations
- **Swift 6**: Latest language features and safety improvements
- **iOS 26 Features**: Latest platform capabilities where available
### Dependencies
- **SwiftUI**: Native iOS UI framework with latest features
- **AVFoundation**: Audio playback with modern async patterns and background support
- **UserNotifications**: Alarm notifications with rich content support
- **Combine**: Timer publishers and reactive programming
- **Observation**: Modern state management with @Observable
- **Foundation**: Core system frameworks and utilities
- **UIKit**: UIFont integration for precise text measurement and font customization
- **UIApplication**: Screen wake lock management and idle timer control
### Font and Typography Utilities
- **FontUtils.optimalFontSize()**: Calculates optimal font size for portrait orientation
- **FontUtils.maximumStretchedFontSize()**: Calculates maximum font size for stretched mode
- **FontUtils.customFont()**: Creates SwiftUI Font with custom family, weight, and design
- **FontUtils.customUIFont()**: Creates UIFont for precise text measurement
- **FontUtils.weightMultiplier()**: Calculates dot size multiplier based on font weight
- **FontUtils.calculateMaxTextWidth()**: Measures text width for fixed-width calculations
- **FontUtils.calculateMaxTextHeight()**: Measures text height for consistent digit sizing
- **FontUtils.timePickerFontSize()**: Optimized font sizing for DatePicker components
### Performance Considerations
- **Smart timer management**: Conditional timers based on settings
- **Debounced persistence**: Batched UserDefaults writes
- **Memory management**: Proper cleanup of audio players
- **Battery optimization**: Efficient update mechanisms
- **Color caching**: Avoid repeated hex-to-Color conversions
- **Dictionary lookups**: O(1) alarm access instead of linear search
- **Smooth animations**: Hardware-accelerated transitions
- **Preloaded audio**: Instant sound playback
- **Font measurement caching**: Efficient text size calculations
- **Fixed-width calculations**: Pre-calculated digit dimensions for consistent layout
- **Orientation-aware sizing**: Optimized font sizing algorithms for different orientations
## Future Enhancement Opportunities
- **Additional sound types**: More white noise variants
- **Sleep timer**: Auto-stop noise after specified time
- **Widget support**: Home screen clock widget
- **Apple Watch companion**: Watch app for quick time check
- **In-app purchases**: Premium sound packs
- **Custom sounds**: User-imported audio files
- **Multiple time zones**: World clock functionality
- **Alarm categories**: Group alarms by type (work, sleep, etc.)
- **Smart alarms**: Gradual volume increase
- **Weather integration**: Weather-based alarm sounds
- **Health integration**: Sleep tracking integration
## Development Notes
### Project Information
- **Created**: September 7, 2025
- **Framework**: SwiftUI with iOS 18.0+ target (latest stable features)
- **Architecture**: Modern SwiftUI with @Observable pattern and MVVM
- **Testing**: Comprehensive unit and UI test targets with Swift Testing
- **Version control**: Git repository with feature branch workflow
- **Performance**: Optimized for battery life and smooth operation
- **Modern iOS**: Uses latest iOS 18+ and iOS 26 features with Swift 6 language improvements
### Modern iOS Development Practices
- **Swift 6**: Latest language features including strict concurrency checking
- **Async/Await**: Modern concurrency patterns throughout the codebase
- **Observation Framework**: @Observable for reactive state management
- **SwiftUI Navigation**: Latest NavigationStack and navigation APIs with iOS 18+ features
- **Accessibility**: Full VoiceOver and Dynamic Type support with iOS 26 enhancements
- **Adaptive Layout**: Support for all device sizes and orientations
- **Performance**: Optimized for 120Hz ProMotion displays and iOS 26 performance improvements
- **Memory Management**: ARC with proper weak references and cleanup
- **Error Handling**: Result types and proper error propagation
- **Testing**: Swift Testing framework for modern test writing
- **iOS 26 Integration**: Latest platform features and capabilities where applicable
### Code Quality Standards
- **SwiftLint**: Automated code style enforcement
- **Documentation**: Comprehensive inline documentation with DocC
- **Type Safety**: Leverage Swift's type system for compile-time safety
- **Protocol-Oriented**: Use protocols for abstraction and testability
- **Dependency Injection**: Constructor injection for better testability
- **SOLID Principles**: Single responsibility, open/closed, dependency inversion