diff --git a/README.md b/README.md index 00b5a20..edafb21 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ | **[`docs/adr/`](docs/adr/)** | Architecture Decision Records: [`ADR 0001`](docs/adr/0001-password-hash-versioning.md) (Password Hashing), [`ADR 0002`](docs/adr/0002-ios-open-source-literature-focus-and-manga-feature-flag.md) (Manga Feature Flag), [`ADR 0003`](docs/adr/0003-comprehensive-catalog-seeding-and-chapter-1-continuity.md) (Catalog Seeding), [`ADR 0004`](docs/adr/0004-render-neon-postgres-deployment.md) (Render + Neon) | | **[`docs/final_milestone/MASTER_PROGRESS_LOG.md`](docs/final_milestone/MASTER_PROGRESS_LOG.md)** | Chronological engineering progress log across all phases and PRs | | **[`docs/MAC_LAB_RUNBOOK.md`](docs/MAC_LAB_RUNBOOK.md)** | Step-by-step computer lab setup, grading demo runbook, and troubleshooting | +| **[`docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md`](docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md)** | One-command wireless backend launcher (`start_wireless_server.sh`), Fedora Linux setup, and in-app server switcher | --- @@ -149,12 +150,12 @@ Fable is architected around **Feature-Driven Vertical Slices** combined with **M ``` *(All 100 tests must pass, verifying health checks, serialization contracts, Chapter 1 continuity, rate limits, auth hashing, and shelf sync logic).* -5. **Start the FastAPI Development Server:** +5. **Start the FastAPI Development Server (Single-Command Wireless Mode for Mac & Fedora Linux):** ```bash - cd backend - FABLE_ENV=development ../.venv/bin/uvicorn main:app --reload --host 127.0.0.1 --port 8001 + ./scripts/start_wireless_server.sh ``` - * **API Base URL:** `http://127.0.0.1:8001/api/v1` + *(This one command starts Uvicorn on `0.0.0.0:8001` in `development` mode, prints your Home Wi-Fi / Hotspot URL `http://:8001/api/v1`, and opens a live HTTPS Cloudflare tunnel `https://.trycloudflare.com/api/v1` for campus/mobile networks. Use `./scripts/start_wireless_server.sh --no-tunnel` for LAN/Simulator-only runs.)* + * **Local API Base URL:** `http://127.0.0.1:8001/api/v1` * **Interactive Swagger UI:** Open your browser and navigate to `http://127.0.0.1:8001/docs` * **Health Check:** `curl http://127.0.0.1:8001/api/v1/health` @@ -173,9 +174,11 @@ Fable is architected around **Feature-Driven Vertical Slices** combined with **M * Select an iOS Simulator running **iOS 17.0+** (e.g., **iPhone 16 Pro** or **iPhone 15 Pro**). 3. **Configure the API URL:** - * The `FABLE_API_BASE_URL` Xcode build setting is exposed through the generated Info.plist. It defaults to `http://127.0.0.1:8001/api/v1`, matching the Docker Compose host port. - * For a physical device, set it to the development machine's LAN address, such as `http://192.168.1.20:8001/api/v1`, and bind FastAPI to `0.0.0.0`. For release builds, use the deployed HTTPS API URL. - * ATS allows local networking for development and keeps arbitrary HTTP loads disabled. + * The `FABLE_API_BASE_URL` Xcode build setting is exposed through `frontend/FableApp-Info.plist`. It defaults to `http://127.0.0.1:8001/api/v1`, matching the local Uvicorn and Docker Compose host port. + * **In-App Backend Server URL Switcher (No Rebuild Needed):** Both `WelcomeView` (**"Server: … • Change"**) and `SettingsView` (**"Backend Server URL"**) let you change the active backend URL at runtime (`StoryAPIService.setCustomBaseURL`), automatically appending `/api/v1` if omitted, or switch with one tap to Render Cloud (`https://fable-api-cbo8.onrender.com/api/v1`). + * **Physical iPhone on Home Wi-Fi / Personal Hotspot (Mac or Fedora Linux):** Bind FastAPI to `0.0.0.0` (`uvicorn main:app --reload --host 0.0.0.0 --port 8001`) and enter your computer's LAN address (e.g., `http://192.168.1.20:8001/api/v1`) in the in-app **Backend Server URL** switcher. + * **Physical iPhone on Campus / Isolated Wi-Fi (Wireless Local Backend):** When campus Wi-Fi AP Client Isolation blocks peer-to-peer LAN traffic, expose your local FastAPI server over an instant SSH HTTPS tunnel (`ssh -T -R 80:127.0.0.1:8001 nokey@localhost.run`) and enter the generated `https://.app.lhr.life/api/v1` URL in the in-app **Backend Server URL** switcher—or tap **Use Render Cloud**. + * ATS (`NSAppTransportSecurity` in `frontend/FableApp-Info.plist`) allows local networking for development while keeping arbitrary HTTP loads disabled. `StoryAPIService.iso8601DateDecodingStrategy` supports both fractional-microsecond ISO-8601 timestamps from FastAPI and standard ISO-8601 timestamps. 4. **Build & Launch:** * Press `Cmd + R` (or click the **Play** button). @@ -251,6 +254,8 @@ Fable-IOS/ | **Simulator fails to connect to `127.0.0.1:8001`** | The API container is stopped or the app URL uses a different host port | Start it with `docker compose up -d --build` and verify `curl http://127.0.0.1:8001/api/v1/health`. Keep the Xcode Debug URL on port 8001. | | **Old cached build artifacts fail** | Previous user left stale build cache | Press `Shift + Cmd + K` (**Product** ➔ **Clean Build Folder**), then press `Cmd + B` to rebuild. | | **Offline Lab Network (No Internet)** | Campus Wi-Fi blocked or offline computer | Fable reads previously cached stories, chapters, images, and per-account shelf data. A first launch without network has no catalog to display. | +| **Physical iPhone "Untrusted Developer" / "Internet connection required"** | Free Apple ID Personal Team certificate requires one-time verification with `ppq.apple.com` | On the iPhone, temporarily enable **Mobile Data** (if campus Wi-Fi blocks Apple verification), go to **Settings ➔ General ➔ VPN & Device Management**, tap your Developer App profile, and tap **Trust**. | +| **Physical iPhone cannot reach Mac's local IP (`172.x.x.x:8001`) on campus Wi-Fi** | Campus Wi-Fi AP Client Isolation blocks peer-to-peer traffic between wireless clients | Run `ssh -T -R 80:127.0.0.1:8001 nokey@localhost.run` on the Mac and pass `FABLE_API_BASE_URL="https://.app.lhr.life/api/v1"` (or use the deployed Render URL `https://fable-api-cbo8.onrender.com/api/v1`). | --- diff --git a/backend/api/v1/endpoints/auth.py b/backend/api/v1/endpoints/auth.py index c558ec9..dbfcd58 100644 --- a/backend/api/v1/endpoints/auth.py +++ b/backend/api/v1/endpoints/auth.py @@ -1,3 +1,4 @@ +import os from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request, Response, status from core.rate_limit import extract_client_ip from schemas import ( @@ -41,27 +42,34 @@ def request_password_reset( request: Request, background_tasks: BackgroundTasks, ): + is_dev_env = os.environ.get("FABLE_ENV", "").strip().lower() == "development" + smtp_settings = None try: smtp_settings = load_smtp_settings() except EmailDeliveryConfigurationError as error: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Password recovery is temporarily unavailable.", - ) from error + if not is_dev_env: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Password recovery is temporarily unavailable.", + ) from error client_host = extract_client_ip(request) enforce_auth_rate_limit("password_reset", client_host, payload.email) token = auth_service.issue_password_reset_token(payload.email) - if token is not None: - background_tasks.add_task( - deliver_password_reset_email, - smtp_settings, - payload.email, - token, - ) - return { + response_body = { "message": "If an account uses this address, recovery instructions will arrive shortly." } + if token is not None: + if smtp_settings is not None: + background_tasks.add_task( + deliver_password_reset_email, + smtp_settings, + payload.email, + token, + ) + elif is_dev_env: + response_body["recoveryToken"] = token + return response_body @router.post("/auth/password-reset/confirm", status_code=status.HTTP_204_NO_CONTENT) diff --git a/docs/AGENT_HANDOFF_CONTEXT.md b/docs/AGENT_HANDOFF_CONTEXT.md index a63122d..24ef273 100644 --- a/docs/AGENT_HANDOFF_CONTEXT.md +++ b/docs/AGENT_HANDOFF_CONTEXT.md @@ -171,7 +171,12 @@ Below is the original file-and-line audit baseline gathered prior to executing * ## 5. Known Gotchas & Compiler Notes from This Session -1. **Swift Closure Type Inference in `StoryStore.swift`:** +1. **ISO-8601 Fractional Microseconds Decoding (`StoryAPIService.iso8601DateDecodingStrategy`):** + - FastAPI/Pydantic serializes UTC timestamps with fractional microseconds (e.g., `"2026-11-16T04:25:03.094537Z"`), whereas Swift's built-in `JSONDecoder.DateDecodingStrategy.iso8601` does not enable `.withFractionalSeconds` and throws `DecodingError.dataCorrupted`. Always use `StoryAPIService.iso8601DateDecodingStrategy` in `frontend/FableApp/Features/Library/Services/StoryAPIService.swift`, which supports both `.withFractionalSeconds` and standard `.withInternetDateTime`. +2. **Physical iPhone `Info.plist` Keys (`FABLE_API_BASE_URL` & `NSAppTransportSecurity`) & Runtime Server URL Override:** + - Xcode's `GENERATE_INFOPLIST_FILE = YES` ignores custom `INFOPLIST_KEY_FABLE_API_BASE_URL` and nested `INFOPLIST_KEY_NSAppTransportSecurity_*` settings unless `FABLE_API_BASE_URL$(FABLE_API_BASE_URL)` and `NSAppTransportSecurity` are explicitly declared in `frontend/FableApp-Info.plist`. + - `StoryAPIService.resolvedBaseURL()` dynamically checks `UserDefaults.standard.string(forKey: StoryAPIService.customBaseURLDefaultsKey)` (`"fable_custom_api_base_url"`) before falling back to `FABLE_API_BASE_URL`. Both `WelcomeView` and `SettingsView` expose an in-app **Backend Server URL** switcher (`StoryAPIService.setCustomBaseURL`) so a physical iPhone can switch between a Fedora/Mac LAN backend, an SSH tunnel, and Render Cloud without rebuilding in Xcode. +3. **Swift Closure Type Inference in `StoryStore.swift`:** - Around line 880 in `StoryStore.swift` (`availableGenres`), keep `let candidates: [(name: String, matcher: (String) -> Bool)] = [...]` as a single typed array literal and filter inside the `for (name, matcher) in candidates` loop (`if !Self.isMangaEnabled && name == "Manga" { continue }`). Splitting it into `candidates.append(contentsOf: [...])` causes Swift compiler error `Cannot infer type of closure parameter '$0' without a type annotation`. 2. **`ReaderTheme` Enum Cases:** - The dark themes in `ReaderTheme` (`frontend/FableApp/Core/Models/Models.swift`) are `.parchment`, `.sepia`, `.midnight`, and `.oled` (there is **no** `.night` case). diff --git a/docs/MAC_LAB_RUNBOOK.md b/docs/MAC_LAB_RUNBOOK.md index e6ecf41..a82dc48 100644 --- a/docs/MAC_LAB_RUNBOOK.md +++ b/docs/MAC_LAB_RUNBOOK.md @@ -58,6 +58,57 @@ Before running, clear any potential cache conflicts from previous students: - Press `Cmd + R` (**Product ➔ Run**). - The Simulator will launch and display the Library. The catalog loads live Gutenberg metadata and official covers; full text is fetched from the chapter endpoint when a book is opened. Without network access, expect a previously cached library or an empty state. +### Step 5b: Running on a Physical iPhone (USB & Wireless Local Backend) +1. **Connect iPhone via Lightning / USB-C** and verify Xcode/CoreDevice sees it: + ```bash + xcrun devicectl list devices + ``` +2. **Choose how your iPhone will reach the Backend API:** + - **Option A — Home Wi-Fi or iPhone Personal Hotspot (Direct LAN):** + Start FastAPI bound to `0.0.0.0`: + ```bash + cd backend + FABLE_ENV=development ../.venv/bin/uvicorn main:app --reload --host 0.0.0.0 --port 8001 + ``` + Use your Mac's Wi-Fi IP (`http://:8001/api/v1`) as `FABLE_API_BASE_URL`. + - **Option B — Campus Lab Wi-Fi with AP Client Isolation (Wireless Tunnel to Local Backend):** + Campus Wi-Fi routers (`172.22.x.x`) isolate wireless clients from connecting directly to each other's local IP. To use your Mac's local FastAPI server wirelessly from your iPhone, start a free SSH HTTPS tunnel in a second terminal: + ```bash + ssh -T -o ServerAliveInterval=30 -R 80:127.0.0.1:8001 nokey@localhost.run + ``` + Copy the printed `https://.app.lhr.life` address and set `FABLE_API_BASE_URL="https://.app.lhr.life/api/v1"`. + - **Option C — Deployed Cloud Backend (Render + Neon):** + Set `FABLE_API_BASE_URL="https://fable-api-cbo8.onrender.com/api/v1"`. +3. **Build, Sign & Install to the iPhone:** + ```bash + xcodebuild -project frontend/FableApp.xcodeproj -scheme FableApp \ + -destination 'id=' \ + DEVELOPMENT_TEAM= \ + FABLE_API_BASE_URL="https://.app.lhr.life/api/v1" \ + -allowProvisioningUpdates build + + xcrun devicectl device install app --device \ + ~/Library/Developer/Xcode/DerivedData/FableApp-*/Build/Products/Debug-iphoneos/FableApp.app + ``` + *(If macOS prompts for the Keychain password during `codesign`, enter the current Mac login password and click **Always Allow**).* +4. **Trust the Developer Certificate on Your iPhone (One-Time for Personal Teams):** + - On your iPhone, open **Settings ➔ General ➔ VPN & Device Management**, tap your **Developer App** profile, and tap **Trust**. + - If campus Wi-Fi blocks Apple's certificate verification server (`ppq.apple.com`) and shows *"An internet connection is required"*, temporarily switch your iPhone to **Mobile Data** for 5 seconds, tap **Trust**, and then re-enable Wi-Fi. +5. **Unplug & Use Wirelessly (Including from a Fedora Linux Laptop):** + - Once installed, you can change the backend server URL at any time **directly inside the iPhone app** without Xcode: + - On the **Welcome Screen** (before signing in), tap **"Server: … • Change"** at the bottom. + - Or inside the app, open **Shelf ➔ Settings ➔ Backend Server URL**. + - **Using Your Fedora Linux Laptop (or Mac) as the Wireless Backend in One Command:** + 1. Run the unified launcher script from the repository root: + ```bash + ./scripts/start_wireless_server.sh + ``` + *(Creates `.venv` if missing, starts FastAPI on `0.0.0.0:8001` with `FABLE_ENV=development`, and prints both your **Home Wi-Fi / Hotspot URL** `http://:8001/api/v1` and a **Public HTTPS Tunnel URL** `https://.trycloudflare.com/api/v1`.)* + 2. On Fedora, if using Home Wi-Fi / Hotspot directly, open port `8001` once: `sudo firewall-cmd --add-port=8001/tcp`. + 3. On your iPhone, tap **Server: … • Change** (or **Settings ➔ Backend Server URL**), paste either URL, and tap **Save**. + - **Re-signing / Refreshing the iOS App from Fedora Linux (7-Day Personal Team Expiry):** + - Free Apple ID ("Personal Team") provisioning profiles expire after 7 days. Without a physical Mac, build the `.ipa` on GitHub Actions (`macos-latest` runner) and sideload/refresh it on Fedora using **SideStore** or **`altserver-linux`** (`sudo dnf install usbmuxd libimobiledevice`). + --- ## 3. Final Capstone Grading & Demonstration Runbook ("The Hero Path") diff --git a/docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md b/docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md new file mode 100644 index 0000000..2c4fa9c --- /dev/null +++ b/docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md @@ -0,0 +1,115 @@ +# Wireless iPhone & Fedora Linux / Mac Server Guide + +This guide explains how to run the Fable backend with a single command on **Fedora Linux** or **macOS**, retrieve the live backend URL, and connect a physical iPhone running **FableApp** completely wirelessly—without Xcode or a Lightning cable. + +--- + +## 1. One-Command Wireless Backend Launcher + +From the repository root on **macOS** or **Fedora Linux**, run: + +```bash +./scripts/start_wireless_server.sh +``` + +What [`scripts/start_wireless_server.sh`](../scripts/start_wireless_server.sh) does automatically: +1. Creates `.venv` and installs `backend/requirements.txt` if not yet installed. +2. Starts FastAPI (`uvicorn main:app --reload --host 0.0.0.0 --port 8001`) with `FABLE_ENV=development` and `FABLE_DB_PATH=backend/fable.sqlite3` (or reuses an already-running backend on port `8001`). +3. Detects your computer's local Wi-Fi / Hotspot IPv4 address. +4. Starts `cloudflared` (installing it to `~/.local/bin/cloudflared` if missing) to create an HTTPS tunnel to your laptop, unless `--no-tunnel` is passed. +5. Prints all ready-to-use URLs in a summary block and cleans up child processes on `Ctrl+C`. + +### Flags & Environment Overrides + +| Option / Variable | Default | Purpose | +|---|---|---| +| `--tunnel` / `--no-tunnel` | `--tunnel` | Enable or skip the Cloudflare HTTPS tunnel (`FABLE_USE_TUNNEL=0\|1`). | +| `FABLE_BIND_ADDRESS` | `0.0.0.0` | Interface FastAPI binds to (`0.0.0.0` allows wireless devices on LAN/Hotspot). | +| `FABLE_PORT` | `8001` | Port for Uvicorn and the Cloudflare tunnel. | +| `FABLE_ENV` | `development` | Enables development features such as auto-returned `recoveryToken` without SMTP. | +| `FABLE_DB_PATH` | `backend/fable.sqlite3` | SQLite database file path. | +| `CLOUDFLARE_TUNNEL_TOKEN` | *(unset)* | Optional Cloudflare Zero Trust Named Tunnel token for a permanent fixed domain. | + +--- + +## 2. How to Get the URL for Your iPhone + +When `./scripts/start_wireless_server.sh` starts, look at the terminal banner it prints: + +```text +================================================================== + Fable Backend is LIVE for Wireless iPhone Connections +================================================================== + Local Health: http://127.0.0.1:8001/api/v1/health + Home Wi-Fi / Hotspot: http://192.168.1.50:8001/api/v1 + Public HTTPS Tunnel: https://random-words-here.trycloudflare.com/api/v1 + Render Cloud Fallback: https://fable-api-cbo8.onrender.com/api/v1 + + On your iPhone: Welcome ('Server: ... Change') or Settings -> + Backend Server URL -> paste the URL above -> Save. + Press Ctrl+C to stop. +================================================================== +``` + +Which URL should you choose? + +| Network Scenario | URL to Use | Notes | +|---|---|---| +| **Home Wi-Fi or iPhone Personal Hotspot** | **Home Wi-Fi / Hotspot** (`http://:8001/api/v1`) | Fastest option. Your laptop's local IP stays consistent on that network, so you only enter it once. | +| **Campus Wi-Fi (AP Client Isolation) or Mobile Data** | **Public HTTPS Tunnel** (`https://.trycloudflare.com/api/v1`) | Works across different networks when peer-to-peer LAN access is blocked. Quick tunnel subdomains rotate on restart unless `CLOUDFLARE_TUNNEL_TOKEN` is configured. | +| **No Laptop Running** | **Render Cloud Fallback** (`https://fable-api-cbo8.onrender.com/api/v1`) | Always available online. Note that Render Free blocks outbound SMTP ports (`25`/`465`/`587`), so password-reset emails are unavailable on Render Cloud. | + +> [!TIP] +> **Automatic `/api/v1` Normalization:** `StoryAPIService.normalizeBaseURLString` automatically appends `/api/v1` if you enter only the host and port (for example, `http://192.168.1.50:8001` or `https://example.trycloudflare.com`). + +--- + +## 3. Entering the URL Inside FableApp (No Rebuild Required) + +You can switch the active backend URL at runtime directly on your iPhone: + +1. **Before Signing In (Welcome Screen):** + - Tap the **`Server: • Change`** pill below *Continue as Guest*. +2. **While Signed In (Settings Screen):** + - Go to **Shelf ➔ Settings (gear icon) ➔ Backend Server URL**. +3. Choose an action in the **Backend Server URL** alert: + - **Save Custom URL** / **Save & Sync**: Saves your laptop's LAN or tunnel URL in `UserDefaults` (`fable_custom_api_base_url`). + - **Use Render Cloud**: Switches to `https://fable-api-cbo8.onrender.com/api/v1`. + - **Reset to Bundle Default**: Clears the custom override and reverts to `FABLE_API_BASE_URL` from `Info.plist`. + +--- + +## 4. Fedora Linux Specific Notes + +### Opening the Local Port for Home Wi-Fi / Hotspot +Fedora enables `firewalld` by default. Allow TCP port `8001` when connecting your iPhone directly to your laptop's **Home Wi-Fi / Hotspot** URL: + +```bash +sudo firewall-cmd --add-port=8001/tcp +# Optional: persist across reboots +sudo firewall-cmd --permanent --add-port=8001/tcp +``` + +*(If you connect via the **Public HTTPS Tunnel** `https://.trycloudflare.com`, opening port `8001` in `firewalld` is not required because `cloudflared` connects outbound.)* + +### Refreshing the iOS App Without a Mac (7-Day Personal Team Expiry) +Apple's free Personal Team developer certificates expire every **7 days**. From Fedora Linux: +- Build the `.ipa` artifact in CI (`macos-latest` GitHub Actions runner), then sideload and refresh it over USB or Wi-Fi using **SideStore** or **`altserver-linux`** (`sudo dnf install usbmuxd libimobiledevice`). + +--- + +## 5. Development Password Recovery & Timestamp Compatibility + +- **Development Password Reset (`FABLE_ENV=development`):** When SMTP environment variables (`FABLE_SMTP_HOST`, `FABLE_SMTP_FROM_EMAIL`) are unset in `development` mode, `POST /api/v1/auth/password-reset/request` returns a `recoveryToken` in the response payload for existing accounts, which `PasswordRecoveryViewModel` automatically fills into the recovery-code field on iOS. In `staging`/`production`, SMTP configuration remains required and missing SMTP returns HTTP `503`. +- **ISO-8601 Fractional Seconds:** `StoryAPIService.iso8601DateDecodingStrategy` parses both fractional-microsecond UTC timestamps emitted by FastAPI/Pydantic and standard ISO-8601 timestamps. + +--- + +## 6. Troubleshooting + +| Symptom | Cause | Fix | +|---|---|---| +| **"Offline Cache" or timeout right after unplugging USB** | Phone was pointed to a USB-only tunnel or campus Wi-Fi blocks phone internet | Open **Backend Server URL** on your iPhone and tap **Reset to Bundle Default** (or enter your tunnel/LAN URL). If campus Wi-Fi restricts phones, switch to **Mobile Data** or connect your laptop to your iPhone's **Personal Hotspot**. | +| **"An internet connection is required" when trusting Developer App** | Campus Wi-Fi blocks Apple's `ppq.apple.com` verification on mobile devices | Temporarily switch to **Mobile Data**, go to **Settings ➔ General ➔ VPN & Device Management**, tap **Trust**, then re-enable Wi-Fi. | +| **iPhone cannot connect to `http://:8001`** | Fedora firewall blocking `8001`, or router/campus Wi-Fi AP Client Isolation | Run `sudo firewall-cmd --add-port=8001/tcp` on Fedora. If on campus Wi-Fi, use the **Public HTTPS Tunnel** URL instead. | +| **Password reset returns `"The server could not complete the request."`** | Pointed at a stopped tunnel or Render Cloud without SMTP | Run `./scripts/start_wireless_server.sh` (`FABLE_ENV=development`), update **Backend Server URL** to the printed tunnel/LAN URL, and retry **Forgot Password?**. | diff --git a/frontend/FableApp-Info.plist b/frontend/FableApp-Info.plist index f753731..f4bbabd 100644 --- a/frontend/FableApp-Info.plist +++ b/frontend/FableApp-Info.plist @@ -2,6 +2,15 @@ + FABLE_API_BASE_URL + $(FABLE_API_BASE_URL) + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsLocalNetworking + + UIBackgroundModes audio diff --git a/frontend/FableApp/App/ContentView.swift b/frontend/FableApp/App/ContentView.swift index 115e2d8..2a9f299 100644 --- a/frontend/FableApp/App/ContentView.swift +++ b/frontend/FableApp/App/ContentView.swift @@ -72,6 +72,7 @@ struct ContentView: View { .onChange(of: auth.currentSession?.id) { _, _ in store.sessionDidChange() } + .preferredColorScheme(store.appAppearance.colorScheme) .environmentObject(store) } @@ -155,7 +156,7 @@ struct ContentView: View { .fill(.ultraThinMaterial) .overlay( RoundedRectangle(cornerRadius: 32, style: .continuous) - .stroke(Color.white.opacity(0.55), lineWidth: 0.8) + .stroke(FableTheme.divider.opacity(0.75), lineWidth: 0.8) ) .shadow(color: Color.black.opacity(0.08), radius: 16, x: 0, y: 6) .shadow(color: Color.black.opacity(0.03), radius: 3, x: 0, y: 1) diff --git a/frontend/FableApp/App/FableApp.swift b/frontend/FableApp/App/FableApp.swift index 7faab9f..14409bc 100644 --- a/frontend/FableApp/App/FableApp.swift +++ b/frontend/FableApp/App/FableApp.swift @@ -3,9 +3,12 @@ import SwiftData @main struct FableApp: App { + @AppStorage(AppAppearance.storageKey) private var appAppearanceRaw: String = AppAppearance.system.rawValue + var body: some Scene { WindowGroup { ContentView() + .preferredColorScheme((AppAppearance(rawValue: appAppearanceRaw) ?? .system).colorScheme) } .modelContainer(PersistenceService.shared.container) } diff --git a/frontend/FableApp/Core/Theme/FableTheme.swift b/frontend/FableApp/Core/Theme/FableTheme.swift index d7ab303..b440bb8 100644 --- a/frontend/FableApp/Core/Theme/FableTheme.swift +++ b/frontend/FableApp/Core/Theme/FableTheme.swift @@ -42,24 +42,99 @@ public extension View { } } +public enum AppAppearance: String, CaseIterable, Identifiable, Codable, Sendable { + case system = "System" + case light = "Light" + case dark = "Dark" + + public static let storageKey = "fable_pref_app_appearance" + + public var id: String { rawValue } + + public var displayName: String { rawValue } + + public var iconName: String { + switch self { + case .system: return "circle.lefthalf.filled" + case .light: return "sun.max.fill" + case .dark: return "moon.stars.fill" + } + } + + public var colorScheme: ColorScheme? { + switch self { + case .system: return nil + case .light: return .light + case .dark: return .dark + } + } +} + public enum FableTheme { - // MARK: - Modern Format-Agnostic Design Tokens + private static func adaptive( + light: (CGFloat, CGFloat, CGFloat), + dark: (CGFloat, CGFloat, CGFloat) + ) -> Color { + #if canImport(UIKit) + return Color(uiColor: UIColor { traits in + let rgb = traits.userInterfaceStyle == .dark ? dark : light + return UIColor(red: rgb.0, green: rgb.1, blue: rgb.2, alpha: 1.0) + }) + #else + return Color(red: light.0, green: light.1, blue: light.2) + #endif + } + + // MARK: - Modern Format-Agnostic Design Tokens (Adaptive Light + Dark) // Electric Indigo accent for vibrant, media-neutral focus - public static let brandPrimary = Color(red: 0.23, green: 0.35, blue: 0.96) // #3B59F6 Modern Electric Indigo - public static let brandSecondary = Color(red: 0.12, green: 0.16, blue: 0.24) // #1E293B Slate Navy - public static let brandAccent = Color(red: 0.49, green: 0.55, blue: 0.98) // #7D8CFA Soft Indigo Tint - public static let background = Color(red: 0.968, green: 0.972, blue: 0.980) // #F7F8FA Clean neutral canvas - public static let surface = Color(red: 0.933, green: 0.941, blue: 0.957) // #EEF0F4 Neutral container surface - public static let surfaceVariant = Color(red: 0.910, green: 0.922, blue: 0.941) // #E8EBF0 Clean interactive pill background - public static let textPrimary = Color(red: 0.07, green: 0.09, blue: 0.13) // #111721 Sharp high-contrast text - public static let textSecondary = Color(red: 0.30, green: 0.35, blue: 0.43) // #4D596E Clean slate secondary - public static let textMuted = Color(red: 0.353, green: 0.392, blue: 0.455) // #5A6474 Muted text with WCAG AA contrast on light surfaces - public static let cardBackground = Color.white // #FFFFFF Clean surface - public static let divider = Color(red: 0.89, green: 0.91, blue: 0.93) // #E3E8ED Fine hairline divider + public static let brandPrimary = adaptive( + light: (0.23, 0.35, 0.96), // #3B59F6 Modern Electric Indigo + dark: (0.36, 0.46, 1.00) // #5C75FF High-contrast Indigo for dark surfaces + ) + public static let brandSecondary = Color(red: 0.12, green: 0.16, blue: 0.24) // #1E293B Slate Navy (cover gradients) + public static let brandAccent = adaptive( + light: (0.49, 0.55, 0.98), // #7D8CFA Soft Indigo Tint + dark: (0.56, 0.62, 1.00) // #8F9EFF + ) + public static let background = adaptive( + light: (0.968, 0.972, 0.980), // #F7F8FA Clean neutral canvas + dark: (0.043, 0.059, 0.090) // #0B0F17 Deep editorial slate canvas + ) + public static let surface = adaptive( + light: (0.933, 0.941, 0.957), // #EEF0F4 Neutral container surface + dark: (0.078, 0.106, 0.149) // #141B26 Elevated dark container + ) + public static let surfaceVariant = adaptive( + light: (0.910, 0.922, 0.941), // #E8EBF0 Clean interactive pill background + dark: (0.110, 0.145, 0.204) // #1C2534 Dark pill & control surface + ) + public static let textPrimary = adaptive( + light: (0.07, 0.09, 0.13), // #111721 Sharp high-contrast text + dark: (0.945, 0.961, 0.976) // #F1F5F9 Crisp light editorial text + ) + public static let textSecondary = adaptive( + light: (0.30, 0.35, 0.43), // #4D596E Clean slate secondary + dark: (0.714, 0.761, 0.831) // #B6C2D4 Readable cool slate + ) + public static let textMuted = adaptive( + light: (0.353, 0.392, 0.455), // #5A6474 Muted text with WCAG AA contrast on light surfaces + dark: (0.580, 0.639, 0.722) // #94A3B8 Muted text with WCAG AA contrast on dark surfaces + ) + public static let cardBackground = adaptive( + light: (1.0, 1.0, 1.0), // #FFFFFF Clean surface + dark: (0.067, 0.094, 0.141) // #111824 Elevated dark card + ) + public static let divider = adaptive( + light: (0.89, 0.91, 0.93), // #E3E8ED Fine hairline divider + dark: (0.141, 0.188, 0.267) // #243044 Subtle dark hairline divider + ) // MARK: - Prototype Aliases & Visual Palette public static let terracotta = brandPrimary - public static let terracottaDark = Color(red: 0.15, green: 0.25, blue: 0.85) + public static let terracottaDark = adaptive( + light: (0.15, 0.25, 0.85), + dark: (0.28, 0.38, 0.95) + ) public static let warmCream = background public static let softPeach = surface public static let deepCharcoal = textPrimary diff --git a/frontend/FableApp/Features/Auth/ViewModels/PasswordRecoveryViewModel.swift b/frontend/FableApp/Features/Auth/ViewModels/PasswordRecoveryViewModel.swift index e9bc6b1..0709690 100644 --- a/frontend/FableApp/Features/Auth/ViewModels/PasswordRecoveryViewModel.swift +++ b/frontend/FableApp/Features/Auth/ViewModels/PasswordRecoveryViewModel.swift @@ -48,7 +48,12 @@ final class PasswordRecoveryViewModel: ObservableObject { defer { isLoading = false } do { + StoryAPIService.lastDevelopmentRecoveryToken = nil try await requestReset(normalizedEmail) + if let devToken = StoryAPIService.lastDevelopmentRecoveryToken, !devToken.isEmpty { + token = devToken + StoryAPIService.lastDevelopmentRecoveryToken = nil + } stage = .confirm statusMessage = "If an account uses this address, recovery instructions will arrive shortly." } catch { diff --git a/frontend/FableApp/Features/Auth/Views/SignInView.swift b/frontend/FableApp/Features/Auth/Views/SignInView.swift index b986cac..0af5cd4 100644 --- a/frontend/FableApp/Features/Auth/Views/SignInView.swift +++ b/frontend/FableApp/Features/Auth/Views/SignInView.swift @@ -52,7 +52,7 @@ public struct SignInView: View { .fableFont(size: 13, weight: .bold) .foregroundColor(FableTheme.textPrimary) .padding(8) - .background(Color.white) + .background(FableTheme.cardBackground) .clipShape(Circle()) .shadow(color: Color.black.opacity(0.05), radius: 3, y: 1) } diff --git a/frontend/FableApp/Features/Auth/Views/SignUpView.swift b/frontend/FableApp/Features/Auth/Views/SignUpView.swift index 9624b0b..1b80ffb 100644 --- a/frontend/FableApp/Features/Auth/Views/SignUpView.swift +++ b/frontend/FableApp/Features/Auth/Views/SignUpView.swift @@ -58,7 +58,7 @@ public struct SignUpView: View { .fableFont(size: 13, weight: .bold) .foregroundColor(FableTheme.textPrimary) .padding(8) - .background(Color.white) + .background(FableTheme.cardBackground) .clipShape(Circle()) .shadow(color: Color.black.opacity(0.05), radius: 3, y: 1) } diff --git a/frontend/FableApp/Features/Auth/Views/WelcomeView.swift b/frontend/FableApp/Features/Auth/Views/WelcomeView.swift index 00cc886..7a96d71 100644 --- a/frontend/FableApp/Features/Auth/Views/WelcomeView.swift +++ b/frontend/FableApp/Features/Auth/Views/WelcomeView.swift @@ -6,6 +6,9 @@ public struct WelcomeView: View { @State private var isShowingSignIn: Bool = false @State private var isShowingSignUp: Bool = false + @State private var isShowingServerConfig: Bool = false + @State private var customServerInput: String = StoryAPIService.resolvedBaseURL().absoluteString + @State private var activeServerLabel: String = StoryAPIService.resolvedBaseURL().host ?? "localhost" public init() {} @@ -132,10 +135,51 @@ public struct WelcomeView: View { .foregroundColor(FableTheme.textMuted) .padding(.vertical, 8) } + + Button(action: { + customServerInput = StoryAPIService.resolvedBaseURL().absoluteString + isShowingServerConfig = true + }) { + HStack(spacing: 6) { + Image(systemName: "server.rack") + .fableFont(size: 11, weight: .semibold) + Text("Server: \(activeServerLabel)") + .fableFont(size: 11, weight: .medium) + .lineLimit(1) + Text("• Change") + .fableFont(size: 11, weight: .bold) + .foregroundColor(FableTheme.brandPrimary) + } + .foregroundColor(FableTheme.textMuted) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(FableTheme.surface) + .clipShape(Capsule()) + } } .padding(.horizontal, 28) - .padding(.bottom, 36) + .padding(.bottom, 28) + } + } + .alert("Backend Server URL", isPresented: $isShowingServerConfig) { + TextField("http://192.168.1.50:8001/api/v1", text: $customServerInput) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + Button("Save Custom URL") { + let updated = StoryAPIService.setCustomBaseURL(customServerInput) + activeServerLabel = updated.host ?? updated.absoluteString + } + Button("Use Render Cloud") { + let updated = StoryAPIService.setCustomBaseURL(StoryAPIService.cloudRenderBaseURLString) + activeServerLabel = updated.host ?? updated.absoluteString + } + Button("Reset to Bundle Default") { + let updated = StoryAPIService.setCustomBaseURL(nil) + activeServerLabel = updated.host ?? updated.absoluteString } + Button("Cancel", role: .cancel) {} + } message: { + Text("Enter your Fedora/Mac LAN URL (e.g. http://192.168.1.50:8001/api/v1), an HTTPS tunnel URL, or choose Render Cloud.") } .sheet(isPresented: $isShowingSignIn) { SignInView(authVM: authVM, onNavigateToRegister: { diff --git a/frontend/FableApp/Features/Library/Services/PersistenceService.swift b/frontend/FableApp/Features/Library/Services/PersistenceService.swift index 4470807..5a53947 100644 --- a/frontend/FableApp/Features/Library/Services/PersistenceService.swift +++ b/frontend/FableApp/Features/Library/Services/PersistenceService.swift @@ -507,6 +507,8 @@ public final class PersistenceService { if let existing = storyEntity.annotations.first(where: { $0.id == annotation.id }) { guard existing.ownerUserId == ownerUserId else { return } existing.chapterNumber = annotation.chapterNumber + existing.utf16StartOffset = annotation.utf16StartOffset + existing.utf16EndOffset = annotation.utf16EndOffset existing.highlightedText = annotation.selectedText existing.note = annotation.note existing.styleRaw = annotation.color.rawValue diff --git a/frontend/FableApp/Features/Library/Services/StoryAPIService.swift b/frontend/FableApp/Features/Library/Services/StoryAPIService.swift index 54b23bd..b47b881 100644 --- a/frontend/FableApp/Features/Library/Services/StoryAPIService.swift +++ b/frontend/FableApp/Features/Library/Services/StoryAPIService.swift @@ -318,18 +318,76 @@ public extension StoryAPIServiceProtocol { } public final class StoryAPIService: StoryAPIServiceProtocol { - private let baseURL: URL + public nonisolated static let customBaseURLDefaultsKey = "fable_custom_api_base_url" + public nonisolated static let cloudRenderBaseURLString = "https://fable-api-cbo8.onrender.com/api/v1" + public nonisolated(unsafe) static var lastDevelopmentRecoveryToken: String? + + private let explicitBaseURL: URL? private let session: URLSession + public nonisolated var baseURL: URL { + Self.resolvedBaseURL(explicitBaseURL: explicitBaseURL) + } + nonisolated public init(baseURL: URL? = nil) { + self.explicitBaseURL = baseURL + let config = URLSessionConfiguration.default + config.timeoutIntervalForRequest = 20.0 + self.session = URLSession(configuration: config) + } + + public nonisolated static func resolvedBaseURL( + explicitBaseURL: URL? = nil, + defaults: UserDefaults = .standard + ) -> URL { + if let explicitBaseURL { + return explicitBaseURL + } + if let custom = defaults.string(forKey: customBaseURLDefaultsKey)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !custom.isEmpty { + if custom.contains(".app.lhr.life") || custom.contains("fd6e:") { + defaults.removeObject(forKey: customBaseURLDefaultsKey) + } else if let customURL = URL(string: normalizeBaseURLString(custom)) { + return customURL + } + } let infoBaseURL = Bundle.main.object(forInfoDictionaryKey: "FABLE_API_BASE_URL") as? String let configuredBaseURL = ProcessInfo.processInfo.environment["FABLE_API_BASE_URL"] ?? infoBaseURL - self.baseURL = baseURL - ?? configuredBaseURL.flatMap { URL(string: $0) } + return configuredBaseURL.flatMap { URL(string: $0) } ?? URL(string: "http://127.0.0.1:8001/api/v1")! - let config = URLSessionConfiguration.default - config.timeoutIntervalForRequest = 5.0 - self.session = URLSession(configuration: config) + } + + public nonisolated static func normalizeBaseURLString(_ rawValue: String) -> String { + var trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) + while trimmed.hasSuffix("/") { + trimmed.removeLast() + } + guard !trimmed.isEmpty, let url = URL(string: trimmed), url.scheme != nil, url.host != nil else { + return trimmed + } + if url.path.isEmpty || url.path == "/" { + return trimmed + "/api/v1" + } + return trimmed + } + + @discardableResult + public nonisolated static func setCustomBaseURL( + _ rawValue: String?, + defaults: UserDefaults = .standard + ) -> URL { + guard let rawValue else { + defaults.removeObject(forKey: customBaseURLDefaultsKey) + return resolvedBaseURL(defaults: defaults) + } + let normalized = normalizeBaseURLString(rawValue) + if normalized.isEmpty { + defaults.removeObject(forKey: customBaseURLDefaultsKey) + } else if let url = URL(string: normalized), url.scheme != nil, url.host != nil { + defaults.set(normalized, forKey: customBaseURLDefaultsKey) + } + return resolvedBaseURL(defaults: defaults) } static func providerRequest(for url: URL) -> URLRequest { @@ -338,6 +396,25 @@ public final class StoryAPIService: StoryAPIServiceProtocol { return request } + nonisolated static let iso8601DateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let string = try container.decode(String.self) + let fractional = ISO8601DateFormatter() + fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = fractional.date(from: string) { + return date + } + let standard = ISO8601DateFormatter() + standard.formatOptions = [.withInternetDateTime] + if let date = standard.date(from: string) { + return date + } + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Expected ISO8601 date string, got \(string)" + ) + } + private func validateResponse(_ response: URLResponse, data: Data) throws { guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { @@ -349,7 +426,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { public func fetchStories(genre: String? = nil, search: String? = nil, since: Date? = nil) async throws -> [Story] { let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy let pageSize = 50 var offset = 0 var stories: [Story] = [] @@ -409,7 +486,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(Story.self, from: data) } @@ -428,7 +505,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(Story.self, from: data) } @@ -450,7 +527,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { let (data, response) = try await session.data(for: request) try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([Story].self, from: data) } @@ -472,7 +549,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy let result = try decoder.decode(ShelfSyncResponse.self, from: data) return result.reconciledItems } @@ -495,7 +572,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([Story].self, from: data) } @@ -522,7 +599,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(Story.self, from: data) } @@ -541,7 +618,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([Chapter].self, from: data) } else if sourceProvider == "GUTENBERG" { throw URLError(.badURL) @@ -560,7 +637,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([Chapter].self, from: data) } else if sourceProvider == "STANDARD_EBOOKS" { throw URLError(.badURL) @@ -574,7 +651,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { if let (data, response) = try? await session.data(from: url), let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) { let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy if let chapters = try? decoder.decode([Chapter].self, from: data), !chapters.isEmpty { return chapters } @@ -599,7 +676,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { if let (data, response) = try? await session.data(for: req), let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) { let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy if let stories = try? decoder.decode([Story].self, from: data), !stories.isEmpty { return stories } @@ -696,7 +773,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { if let (data, response) = try? await session.data(for: backendReq), let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) { let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy if let chapters = try? decoder.decode([Chapter].self, from: data), !chapters.isEmpty { return chapters } @@ -819,7 +896,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([GenreCategory].self, from: data) } @@ -830,7 +907,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([Writer].self, from: data) } @@ -841,7 +918,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { throw URLError(.badServerResponse) } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(UpdateFeed.self, from: data) } @@ -858,7 +935,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { } let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode([ShelfSyncItem].self, from: data) } @@ -880,7 +957,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(AuthTokenResponse.self, from: data) } @@ -900,19 +977,49 @@ public final class StoryAPIService: StoryAPIServiceProtocol { try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(AuthTokenResponse.self, from: data) } public func requestPasswordReset(email: String) async throws { - let url = baseURL.appendingPathComponent("auth").appendingPathComponent("password-reset").appendingPathComponent("request") - var request = URLRequest(url: url) - request.httpMethod = "POST" - request.setValue("application/json", forHTTPHeaderField: "Content-Type") - request.httpBody = try JSONSerialization.data(withJSONObject: ["email": email]) + Self.lastDevelopmentRecoveryToken = nil + let bodyData = try JSONSerialization.data(withJSONObject: ["email": email]) + var candidateRoots: [URL] = [baseURL] + if explicitBaseURL == nil { + for fallbackString in [ + Bundle.main.object(forInfoDictionaryKey: "FABLE_API_BASE_URL") as? String, + Self.cloudRenderBaseURLString + ].compactMap({ $0 }) { + if let fallbackURL = URL(string: fallbackString), + !candidateRoots.contains(where: { $0.absoluteString == fallbackURL.absoluteString }) { + candidateRoots.append(fallbackURL) + } + } + } - let (data, response) = try await session.data(for: request) - try validateResponse(response, data: data) + var lastError: Error? + for root in candidateRoots { + let url = root.appendingPathComponent("auth").appendingPathComponent("password-reset").appendingPathComponent("request") + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = bodyData + request.timeoutInterval = 8.0 + + do { + let (data, response) = try await session.data(for: request) + try validateResponse(response, data: data) + if let payload = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let recoveryToken = payload["recoveryToken"] as? String, + !recoveryToken.isEmpty { + Self.lastDevelopmentRecoveryToken = recoveryToken + } + return + } catch { + lastError = error + } + } + throw lastError ?? APIRequestError(message: "The server could not complete the request.") } public func confirmPasswordReset(token: String, newPassword: String) async throws { @@ -971,7 +1078,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { let (data, response) = try await session.data(for: urlRequest) try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(AuthUserDTO.self, from: data) } @@ -995,7 +1102,7 @@ public final class StoryAPIService: StoryAPIServiceProtocol { try validateResponse(response, data: data) let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 + decoder.dateDecodingStrategy = Self.iso8601DateDecodingStrategy return try decoder.decode(AuthUserDTO.self, from: data) } } diff --git a/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift b/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift index b8182ee..8ed0a02 100644 --- a/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift +++ b/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift @@ -23,8 +23,12 @@ public final class StoryStore: ObservableObject { @Published var tourSelectedWriter: Writer? @Published var tourShelfTab: String = "Saved" @Published var isShowingChapterIndexSheet: Bool = false + @Published var downloadingStoryIds: Set = [] - // Reader Preferences (Persisted across launches) + // App & Reader Preferences (Persisted across launches) + @Published var appAppearance: AppAppearance = .system { + didSet { UserDefaults.standard.set(appAppearance.rawValue, forKey: AppAppearance.storageKey) } + } @Published var readerFont: ReaderFont = .serif { didSet { UserDefaults.standard.set(readerFont.rawValue, forKey: "fable_pref_reader_font") } } @@ -267,6 +271,10 @@ public final class StoryStore: ObservableObject { } private func loadReaderPreferences() { + if let appearanceRaw = UserDefaults.standard.string(forKey: AppAppearance.storageKey), + let appearance = AppAppearance(rawValue: appearanceRaw) { + self.appAppearance = appearance + } if let fontRaw = UserDefaults.standard.string(forKey: "fable_pref_reader_font"), let font = ReaderFont(rawValue: fontRaw) { self.readerFont = font @@ -1054,6 +1062,21 @@ public final class StoryStore: ObservableObject { } } + public func isStoryDownloaded(_ story: Story) -> Bool { + if let chapters = story.chapters, Self.hasUsableCachedChapters(chapters, format: story.contentFormat, allowExternalMangaSource: true) { + return true + } + let cached = PersistenceService.shared.cachedChapters(storyId: story.id) + return Self.hasUsableCachedChapters(cached, format: story.contentFormat, allowExternalMangaSource: true) + } + + public func downloadBookForOffline(_ story: Story) async throws { + guard !downloadingStoryIds.contains(story.id) else { return } + downloadingStoryIds.insert(story.id) + defer { downloadingStoryIds.remove(story.id) } + _ = try await fetchChapters(for: story) + } + func searchCatalog(query: String) async { let search = query.trimmingCharacters(in: .whitespacesAndNewlines) @@ -1932,16 +1955,36 @@ public final class StoryStore: ObservableObject { func updateAnnotation( _ annotation: Annotation, story: Story, + text: String? = nil, + startOffset: Int? = nil, + endOffset: Int? = nil, color: HighlightColor, note: String?, pinToJournal: Bool ) { var updated = annotation - updated.color = color - updated.note = note - updated.isPinnedToJournal = pinToJournal - updated.storyTitle = story.title - updated.storyAuthor = story.author + if let text = text { + updated = Annotation( + id: annotation.id, + storyId: annotation.storyId, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: annotation.chapterNumber, + utf16StartOffset: startOffset ?? annotation.utf16StartOffset, + utf16EndOffset: endOffset ?? annotation.utf16EndOffset, + selectedText: text, + note: note, + color: color, + isPinnedToJournal: pinToJournal, + createdAt: annotation.createdAt + ) + } else { + updated.color = color + updated.note = note + updated.isPinnedToJournal = pinToJournal + updated.storyTitle = story.title + updated.storyAuthor = story.author + } if let idx = activeStoryAnnotations.firstIndex(where: { $0.id == annotation.id }) { activeStoryAnnotations[idx] = updated } diff --git a/frontend/FableApp/Features/Library/Views/GenreDetailView.swift b/frontend/FableApp/Features/Library/Views/GenreDetailView.swift index ecce7a6..5f1d1af 100644 --- a/frontend/FableApp/Features/Library/Views/GenreDetailView.swift +++ b/frontend/FableApp/Features/Library/Views/GenreDetailView.swift @@ -74,7 +74,7 @@ public struct GenreDetailView: View { .fableFont(size: 18, weight: .semibold) .foregroundColor(FableTheme.textPrimary) .frame(width: 40, height: 40) - .background(Color.white) + .background(FableTheme.cardBackground) .clipShape(Circle()) } .accessibilityLabel("Back") @@ -93,7 +93,7 @@ public struct GenreDetailView: View { .fableFont(size: 15) .foregroundColor(isFollowing ? FableTheme.brandPrimary : FableTheme.textPrimary) .frame(width: 40, height: 40) - .background(Color.white) + .background(FableTheme.cardBackground) .clipShape(Circle()) } .accessibilityLabel(isFollowing ? "Unfollow genre" : "Follow genre") diff --git a/frontend/FableApp/Features/Library/Views/LibraryView.swift b/frontend/FableApp/Features/Library/Views/LibraryView.swift index 7a46727..7c475e3 100644 --- a/frontend/FableApp/Features/Library/Views/LibraryView.swift +++ b/frontend/FableApp/Features/Library/Views/LibraryView.swift @@ -232,7 +232,7 @@ public struct LibraryView: View { .foregroundColor(FableTheme.brandPrimary) .padding(.horizontal, 10) .padding(.vertical, 5) - .background(Color.white.opacity(0.95)) + .background(FableTheme.cardBackground.opacity(0.95)) .clipShape(Capsule()) .shadow(color: Color.black.opacity(0.06), radius: 3, y: 1) } @@ -249,7 +249,7 @@ public struct LibraryView: View { .fableFont(size: 13, weight: .semibold) .foregroundColor(featuredStory.isBookmarked ? FableTheme.brandPrimary : FableTheme.textPrimary) .padding(8) - .background(Color.white.opacity(0.95)) + .background(FableTheme.cardBackground.opacity(0.95)) .clipShape(Circle()) .shadow(color: Color.black.opacity(0.08), radius: 3, y: 1) } @@ -501,21 +501,43 @@ public struct LibraryView: View { } .buttonStyle(.plain) - Button { - FableHaptics.light() - withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) { - store.toggleBookmark(for: story) + HStack(spacing: 2) { + if store.downloadingStoryIds.contains(story.id) { + ProgressView() + .controlSize(.small) + .frame(width: 34, height: 34) + } else if !store.isStoryDownloaded(story) { + Button { + FableHaptics.medium() + Task { + try? await store.downloadBookForOffline(story) + } + } label: { + Image(systemName: "arrow.down.circle") + .fableFont(size: 14, weight: .semibold) + .foregroundColor(FableTheme.textMuted) + .frame(width: 34, height: 34) + .contentShape(Rectangle()) + } + .accessibilityLabel("Download book for offline") } - } label: { - Image(systemName: story.isBookmarked ? "bookmark.fill" : "bookmark") - .fableFont(size: 14, weight: .semibold) - .foregroundColor(story.isBookmarked ? FableTheme.brandPrimary : FableTheme.textMuted) - .frame(width: 40, height: 40) - .background(story.isBookmarked ? FableTheme.brandPrimary.opacity(0.1) : Color.clear) - .clipShape(Circle()) - .contentShape(Rectangle()) + + Button { + FableHaptics.light() + withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) { + store.toggleBookmark(for: story) + } + } label: { + Image(systemName: story.isBookmarked ? "bookmark.fill" : "bookmark") + .fableFont(size: 14, weight: .semibold) + .foregroundColor(story.isBookmarked ? FableTheme.brandPrimary : FableTheme.textMuted) + .frame(width: 36, height: 36) + .background(story.isBookmarked ? FableTheme.brandPrimary.opacity(0.1) : Color.clear) + .clipShape(Circle()) + .contentShape(Rectangle()) + } + .accessibilityLabel(story.isBookmarked ? "Remove bookmark" : "Bookmark story") } - .accessibilityLabel(story.isBookmarked ? "Remove bookmark" : "Bookmark story") } .padding(14) .frame(maxWidth: .infinity, alignment: .leading) @@ -657,38 +679,53 @@ public struct LibraryView: View { @ViewBuilder private func storyBadge(for story: Story) -> some View { - if story.contentFormat == .manga { - if story.badgeText == "DIRECT PANELS" { - HStack(spacing: 4) { - Image(systemName: "checkmark.seal.fill") - .fableFont(size: 8) - Text("DIRECT PANELS") - .fableFont(size: 9, weight: .heavy) - .tracking(0.5) - } - .foregroundColor(.white) - .padding(.horizontal, 7) - .padding(.vertical, 3) - .background(Color(red: 0.12, green: 0.58, blue: 0.32)) - .clipShape(Capsule()) - } else if story.badgeText == "OFFICIAL LINK" { - HStack(spacing: 4) { - Image(systemName: "arrow.up.right") - .fableFont(size: 8, weight: .bold) - Text("OFFICIAL LINK") - .fableFont(size: 9, weight: .heavy) - .tracking(0.5) + HStack(spacing: 6) { + if story.contentFormat == .manga { + if story.badgeText == "DIRECT PANELS" { + HStack(spacing: 4) { + Image(systemName: "checkmark.seal.fill") + .fableFont(size: 8) + Text("DIRECT PANELS") + .fableFont(size: 9, weight: .heavy) + .tracking(0.5) + } + .foregroundColor(.white) + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background(Color(red: 0.12, green: 0.58, blue: 0.32)) + .clipShape(Capsule()) + } else if story.badgeText == "OFFICIAL LINK" { + HStack(spacing: 4) { + Image(systemName: "arrow.up.right") + .fableFont(size: 8, weight: .bold) + Text("OFFICIAL LINK") + .fableFont(size: 9, weight: .heavy) + .tracking(0.5) + } + .foregroundColor(Color.orange) + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background(Color.orange.opacity(0.15)) + .clipShape(Capsule()) + } else { + HStack(spacing: 4) { + Image(systemName: "photo.on.rectangle.angled") + .fableFont(size: 8) + Text("MANGA") + .fableFont(size: 9, weight: .heavy) + .tracking(0.5) + } + .foregroundColor(FableTheme.brandPrimary) + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background(FableTheme.surface) + .clipShape(Capsule()) } - .foregroundColor(Color.orange) - .padding(.horizontal, 7) - .padding(.vertical, 3) - .background(Color.orange.opacity(0.15)) - .clipShape(Capsule()) } else { HStack(spacing: 4) { - Image(systemName: "photo.on.rectangle.angled") + Image(systemName: "book.closed.fill") .fableFont(size: 8) - Text("MANGA") + Text(story.sourceProvider == .standardEbooks ? "STANDARD EBOOKS" : story.genre.rawValue.uppercased()) .fableFont(size: 9, weight: .heavy) .tracking(0.5) } @@ -698,19 +735,21 @@ public struct LibraryView: View { .background(FableTheme.surface) .clipShape(Capsule()) } - } else { - HStack(spacing: 4) { - Image(systemName: "book.closed.fill") - .fableFont(size: 8) - Text(story.sourceProvider == .standardEbooks ? "STANDARD EBOOKS" : story.genre.rawValue.uppercased()) - .fableFont(size: 9, weight: .heavy) - .tracking(0.5) + + if store.isStoryDownloaded(story) { + HStack(spacing: 3) { + Image(systemName: "arrow.down.circle.fill") + .fableFont(size: 8) + Text("OFFLINE") + .fableFont(size: 8.5, weight: .heavy) + .tracking(0.5) + } + .foregroundColor(Color(red: 0.12, green: 0.62, blue: 0.32)) + .padding(.horizontal, 6) + .padding(.vertical, 2.5) + .background(Color(red: 0.12, green: 0.62, blue: 0.32).opacity(0.12)) + .clipShape(Capsule()) } - .foregroundColor(FableTheme.brandPrimary) - .padding(.horizontal, 7) - .padding(.vertical, 3) - .background(FableTheme.surface) - .clipShape(Capsule()) } } } diff --git a/frontend/FableApp/Features/Reader/Views/DisplayOptionsSheet.swift b/frontend/FableApp/Features/Reader/Views/DisplayOptionsSheet.swift index cd74c74..2cca586 100644 --- a/frontend/FableApp/Features/Reader/Views/DisplayOptionsSheet.swift +++ b/frontend/FableApp/Features/Reader/Views/DisplayOptionsSheet.swift @@ -7,6 +7,7 @@ struct DisplayOptionsSheet: View { @Environment(\.dismiss) var dismiss @ObservedObject private var narrator = AudioNarratorController.shared @State private var isShowingVoiceSheet: Bool = false + @State private var screenBrightness: Double = Double(UIScreen.main.brightness) var body: some View { VStack(spacing: 0) { @@ -26,6 +27,7 @@ struct DisplayOptionsSheet: View { livePreviewCard typographySection textSizeSection + brightnessSection backgroundSection lineSpacingSection readingLayoutSection @@ -198,6 +200,48 @@ struct DisplayOptionsSheet: View { .padding(.horizontal, 20) } + @ViewBuilder + private var brightnessSection: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text("SCREEN BRIGHTNESS") + .fableFont(size: 11, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.subtleSlate) + + Spacer() + + Text("\(Int(screenBrightness * 100))%") + .fableFont(size: 12, weight: .medium) + .foregroundColor(FableTheme.terracotta) + } + + HStack(spacing: 12) { + Image(systemName: "sun.min") + .fableFont(size: 14) + .foregroundColor(FableTheme.subtleSlate) + + Slider(value: $screenBrightness, in: 0.05...1.0) + .tint(FableTheme.brandPrimary) + .onChange(of: screenBrightness) { _, newValue in + UIScreen.main.brightness = CGFloat(newValue) + } + + Image(systemName: "sun.max.fill") + .fableFont(size: 16) + .foregroundColor(FableTheme.subtleSlate) + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(Color.gray.opacity(0.06)) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + .padding(.horizontal, 20) + .onAppear { + screenBrightness = Double(UIScreen.main.brightness) + } + } + @ViewBuilder private var backgroundSection: some View { VStack(alignment: .leading, spacing: 10) { diff --git a/frontend/FableApp/Features/Reader/Views/QuoteCardView.swift b/frontend/FableApp/Features/Reader/Views/QuoteCardView.swift new file mode 100644 index 0000000..3b07d51 --- /dev/null +++ b/frontend/FableApp/Features/Reader/Views/QuoteCardView.swift @@ -0,0 +1,284 @@ +import SwiftUI +#if canImport(UIKit) +import UIKit +#endif + +public struct QuoteCardView: View { + public let quoteText: String + public let storyTitle: String + public let storyAuthor: String + public let chapterNumber: Int? + public let note: String? + public let highlightColor: HighlightColor + + public init( + quoteText: String, + storyTitle: String, + storyAuthor: String, + chapterNumber: Int? = nil, + note: String? = nil, + highlightColor: HighlightColor = .terracotta + ) { + self.quoteText = quoteText + self.storyTitle = storyTitle + self.storyAuthor = storyAuthor + self.chapterNumber = chapterNumber + self.note = note + self.highlightColor = highlightColor + } + + public var body: some View { + VStack(alignment: .leading, spacing: 18) { + // Header: Fable Reads Branding & Chapter Tag + HStack(alignment: .center) { + HStack(spacing: 6) { + Image(systemName: "quote.opening") + .fableFont(size: 11, weight: .bold) + .foregroundColor(highlightColor.displayColor) + + Text("FABLE READS") + .fableFont(size: 10, weight: .heavy) + .tracking(1.4) + .foregroundColor(FableTheme.subtleSlate) + } + + Spacer() + + if let chap = chapterNumber { + Text("CHAPTER \(chap)") + .fableFont(size: 10, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.subtleSlate) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color.black.opacity(0.04)) + .clipShape(Capsule()) + } + } + + // Quote Excerpt + VStack(alignment: .leading, spacing: 8) { + Text("“\(quoteText.trimmingCharacters(in: .whitespacesAndNewlines))”") + .fableFont(size: 17, weight: .medium, design: .serif) + .italic() + .lineSpacing(5) + .foregroundColor(FableTheme.deepCharcoal) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } + .padding(.vertical, 4) + + // Optional Marginalia Note + if let note = note, !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 4) { + Image(systemName: "pencil.line") + .fableFont(size: 9, weight: .bold) + Text("READER NOTE") + .fableFont(size: 9, weight: .bold) + .tracking(0.8) + } + .foregroundColor(highlightColor.displayColor) + + Text(note) + .fableFont(size: 12, weight: .regular) + .foregroundColor(FableTheme.textSecondary) + .italic() + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(highlightColor.displayColor.opacity(0.12)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + + Divider() + .background(FableTheme.divider) + + // Footer: Story Title, Author, and App Mark + HStack(alignment: .bottom) { + VStack(alignment: .leading, spacing: 3) { + Text(storyTitle) + .fableFont(size: 14, weight: .bold, design: .serif) + .foregroundColor(FableTheme.deepCharcoal) + .lineLimit(2) + + Text("— \(storyAuthor)") + .fableFont(size: 12, weight: .medium) + .foregroundColor(FableTheme.textMuted) + } + + Spacer() + + VStack(alignment: .trailing, spacing: 2) { + HStack(spacing: 4) { + Image(systemName: "book.pages") + .fableFont(size: 10, weight: .semibold) + Text("fable") + .fableFont(size: 12, weight: .bold) + } + .foregroundColor(FableTheme.brandPrimary) + } + } + } + .padding(22) + .background( + RoundedRectangle(cornerRadius: 18) + .fill(Color(red: 0.99, green: 0.985, blue: 0.975)) + ) + .overlay( + RoundedRectangle(cornerRadius: 18) + .stroke(highlightColor.displayColor.opacity(0.35), lineWidth: 1.5) + ) + .shadow(color: Color.black.opacity(0.08), radius: 12, y: 5) + } +} + +#if canImport(UIKit) +@MainActor +public enum QuoteCardRenderer { + public static func renderImage( + quoteText: String, + storyTitle: String, + storyAuthor: String, + chapterNumber: Int? = nil, + note: String? = nil, + highlightColor: HighlightColor = .terracotta + ) -> UIImage? { + let card = QuoteCardView( + quoteText: quoteText, + storyTitle: storyTitle, + storyAuthor: storyAuthor, + chapterNumber: chapterNumber, + note: note, + highlightColor: highlightColor + ) + .frame(width: 360) + + let renderer = ImageRenderer(content: card) + renderer.scale = UIScreen.main.scale + return renderer.uiImage + } +} + +public struct QuoteCardShareSheet: View { + public let quoteText: String + public let storyTitle: String + public let storyAuthor: String + public let chapterNumber: Int? + public let note: String? + public let highlightColor: HighlightColor + + @Environment(\.dismiss) private var dismiss + @State private var renderedImage: UIImage? + @State private var hasSavedToPhotos: Bool = false + @State private var showSaveAlert: Bool = false + + public init( + quoteText: String, + storyTitle: String, + storyAuthor: String, + chapterNumber: Int? = nil, + note: String? = nil, + highlightColor: HighlightColor = .terracotta + ) { + self.quoteText = quoteText + self.storyTitle = storyTitle + self.storyAuthor = storyAuthor + self.chapterNumber = chapterNumber + self.note = note + self.highlightColor = highlightColor + } + + public var body: some View { + NavigationStack { + VStack(spacing: 20) { + Spacer() + + QuoteCardView( + quoteText: quoteText, + storyTitle: storyTitle, + storyAuthor: storyAuthor, + chapterNumber: chapterNumber, + note: note, + highlightColor: highlightColor + ) + .frame(maxWidth: 360) + .padding(.horizontal, 20) + + Spacer() + + VStack(spacing: 12) { + if let image = renderedImage { + ShareLink( + item: Image(uiImage: image), + preview: SharePreview("“\(storyTitle)” Quote", image: Image(uiImage: image)) + ) { + HStack(spacing: 8) { + Image(systemName: "square.and.arrow.up") + .fableFont(size: 15, weight: .semibold) + Text("Share Quote Card") + .fableFont(size: 15, weight: .semibold) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 14) + .background(FableTheme.brandPrimary) + .foregroundColor(.white) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } + + Button(action: { + UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) + FableHaptics.success() + hasSavedToPhotos = true + showSaveAlert = true + }) { + HStack(spacing: 6) { + Image(systemName: hasSavedToPhotos ? "checkmark" : "arrow.down.to.line") + .fableFont(size: 14, weight: .semibold) + Text(hasSavedToPhotos ? "Saved to Photos" : "Save to Photos") + .fableFont(size: 14, weight: .semibold) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + .background(Color.gray.opacity(0.1)) + .foregroundColor(FableTheme.deepCharcoal) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + } else { + ProgressView() + .padding(.vertical, 20) + } + } + .padding(.horizontal, 24) + .padding(.bottom, 24) + } + .background(Color(red: 0.95, green: 0.94, blue: 0.93).ignoresSafeArea()) + .navigationTitle("Quote Card") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button("Done") { + dismiss() + } + .fableFont(size: 15, weight: .semibold) + } + } + .task { + renderedImage = QuoteCardRenderer.renderImage( + quoteText: quoteText, + storyTitle: storyTitle, + storyAuthor: storyAuthor, + chapterNumber: chapterNumber, + note: note, + highlightColor: highlightColor + ) + } + .alert("Saved to Photos", isPresented: $showSaveAlert) { + Button("OK", role: .cancel) {} + } message: { + Text("Your quote card has been saved to your Photos library.") + } + } + } +} +#endif diff --git a/frontend/FableApp/Features/Reader/Views/ReaderView.swift b/frontend/FableApp/Features/Reader/Views/ReaderView.swift index caff99c..c9b6fa4 100644 --- a/frontend/FableApp/Features/Reader/Views/ReaderView.swift +++ b/frontend/FableApp/Features/Reader/Views/ReaderView.swift @@ -1,4 +1,5 @@ import SwiftUI +import Foundation public enum ReaderPassageMatcher { public static func paragraphs(from text: String) -> [String] { @@ -67,6 +68,224 @@ public enum ReaderPassageMatcher { } return nil } + + public static func words(from text: String) -> [String] { + text.components(separatedBy: .whitespacesAndNewlines) + .filter { !$0.isEmpty } + } + + public static func sentences(from text: String) -> [String] { + var results: [String] = [] + text.enumerateSubstrings(in: text.startIndex.. ClosedRange { + guard !words.isEmpty else { return 0...0 } + let targetWords = ReaderPassageMatcher.words(from: target) + guard !targetWords.isEmpty else { return 0...(words.count - 1) } + + let punctuation = CharacterSet.punctuationCharacters + let normalizedTarget = targetWords.map { $0.lowercased().trimmingCharacters(in: punctuation) } + let normalizedWords = words.map { $0.lowercased().trimmingCharacters(in: punctuation) } + + let targetCount = targetWords.count + let wordsCount = words.count + + if targetCount <= wordsCount { + for i in 0...(wordsCount - targetCount) { + var matches = true + for j in 0..) -> String { + guard !words.isEmpty else { return "" } + let safeLower = max(0, min(range.lowerBound, words.count - 1)) + let safeUpper = max(safeLower, min(range.upperBound, words.count - 1)) + return words[safeLower...safeUpper].joined(separator: " ") + } + + public static func locateSubstringOffsets( + in fullText: String, + substring: String, + withinParagraph paragraph: String? = nil + ) -> (start: Int, end: Int) { + let nsFull = fullText as NSString + if let para = paragraph, !para.isEmpty { + let paraRange = nsFull.range(of: para) + if paraRange.location != NSNotFound { + let nsPara = para as NSString + let subRange = nsPara.range(of: substring) + if subRange.location != NSNotFound { + let exactStart = paraRange.location + subRange.location + return (exactStart, exactStart + subRange.length) + } + } + } + let range = nsFull.range(of: substring) + if range.location != NSNotFound { + return (range.location, range.location + range.length) + } + return (0, substring.utf16.count) + } + + public static func generateSnippet(for query: String, in text: String, contextRadius: Int = 40) -> String { + let lowerText = text.lowercased() + let lowerQuery = query.lowercased() + guard let range = lowerText.range(of: lowerQuery) else { + return String(text.prefix(contextRadius * 2)) + } + + let start = text.index(range.lowerBound, offsetBy: -contextRadius, limitedBy: text.startIndex) ?? text.startIndex + let end = text.index(range.upperBound, offsetBy: contextRadius, limitedBy: text.endIndex) ?? text.endIndex + + var snippet = String(text[start.. text.startIndex { + snippet = "..." + snippet + } + if end < text.endIndex { + snippet = snippet + "..." + } + return snippet + } + + public static func search( + query: String, + in chapters: [Chapter], + fallbackParagraphs: [String] = [], + fallbackTitle: String = "Folio" + ) -> [InBookSearchMatch] { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return [] } + let lowerQuery = trimmed.lowercased() + var matches: [InBookSearchMatch] = [] + + if !chapters.isEmpty { + for (chapIdx, chapter) in chapters.enumerated() { + let paras = paragraphs(from: chapter.content) + for (paraIdx, para) in paras.enumerated() { + if para.localizedCaseInsensitiveContains(lowerQuery) { + let snippet = generateSnippet(for: trimmed, in: para) + matches.append( + InBookSearchMatch( + chapterIndex: chapIdx, + chapterNumber: chapter.chapterNumber, + chapterTitle: chapter.title.isEmpty ? "Chapter \(chapter.chapterNumber)" : chapter.title, + paragraphIndex: paraIdx, + pageNumber: max(1, paraIdx / 2 + 1), + snippet: snippet, + matchedText: trimmed, + fullParagraphText: para + ) + ) + } + } + } + } else { + for (paraIdx, para) in fallbackParagraphs.enumerated() { + if para.localizedCaseInsensitiveContains(lowerQuery) { + let snippet = generateSnippet(for: trimmed, in: para) + matches.append( + InBookSearchMatch( + chapterIndex: 0, + chapterNumber: 1, + chapterTitle: fallbackTitle, + paragraphIndex: paraIdx, + pageNumber: max(1, paraIdx / 2 + 1), + snippet: snippet, + matchedText: trimmed, + fullParagraphText: para + ) + ) + } + } + } + return matches + } + + public static func exportAnnotationsAsMarkdown(story: Story, annotations: [Annotation]) -> String { + let sorted = annotations.sorted { + if ($0.chapterNumber ?? 0) != ($1.chapterNumber ?? 0) { + return ($0.chapterNumber ?? 0) < ($1.chapterNumber ?? 0) + } + return $0.utf16StartOffset < $1.utf16EndOffset + } + + var md = """ + # Highlights & Marginalia: \(story.title) + **Author:** \(story.author) + **Total Highlights:** \(annotations.count) + + --- + + """ + + var currentChapter: Int? = nil + for annot in sorted { + let chap = annot.chapterNumber ?? 1 + if chap != currentChapter { + currentChapter = chap + md += "\n## Chapter \(chap)\n\n" + } + md += "> “\(annot.selectedText.trimmingCharacters(in: .whitespacesAndNewlines))”\n" + md += ">\n" + md += "> — *\(annot.color.displayName) highlight*\n" + if let note = annot.note, !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + md += "\n*Note: \(note)*\n" + } + md += "\n---\n\n" + } + return md + } +} + +public struct InBookSearchMatch: Identifiable, Equatable { + public let id = UUID() + public let chapterIndex: Int + public let chapterNumber: Int + public let chapterTitle: String + public let paragraphIndex: Int + public let pageNumber: Int + public let snippet: String + public let matchedText: String + public let fullParagraphText: String + + public init( + chapterIndex: Int, + chapterNumber: Int, + chapterTitle: String, + paragraphIndex: Int, + pageNumber: Int, + snippet: String, + matchedText: String, + fullParagraphText: String + ) { + self.chapterIndex = chapterIndex + self.chapterNumber = chapterNumber + self.chapterTitle = chapterTitle + self.paragraphIndex = paragraphIndex + self.pageNumber = pageNumber + self.snippet = snippet + self.matchedText = matchedText + self.fullParagraphText = fullParagraphText + } } public struct ReaderView: View { @@ -102,6 +321,20 @@ public struct ReaderView: View { @State private var isPinToJournal: Bool = true @State private var isShowingAnnotationSheet: Bool = false @State private var sessionStartTime: Date = Date() + @State private var activeParagraphForAnnotation: String = "" + @State private var paragraphWordsForAnnotation: [String] = [] + @State private var annotationStartWordIndex: Int = 0 + @State private var annotationEndWordIndex: Int = 0 + + // In-Book Search State (Feature 1) + @State private var isSearchActive: Bool = false + @State private var inBookSearchText: String = "" + @State private var searchMatches: [InBookSearchMatch] = [] + @State private var currentSearchMatchIndex: Int = 0 + + // Quote Card Sharing State (Feature 3) + @State private var isShowingQuoteCardShare: Bool = false + @State private var activeQuoteCardData: (text: String, note: String?, color: HighlightColor, chapter: Int?)? = nil public init(story: Story, initialTargetAnnotation: Annotation? = nil) { self.story = story @@ -226,16 +459,57 @@ public struct ReaderView: View { Spacer() - HStack(spacing: 8) { + HStack(spacing: 6) { + // In-Book Text Search Toggle (Feature 1) + Button(action: { + FableHaptics.selection() + withAnimation(.easeInOut(duration: 0.2)) { + isSearchActive.toggle() + } + }) { + Image(systemName: "magnifyingglass") + .fableFont(size: 13, weight: .semibold) + .foregroundColor(isSearchActive ? FableTheme.brandPrimary : store.readerTheme.textColor) + .frame(width: 36, height: 36) + .background(isSearchActive ? FableTheme.brandPrimary.opacity(0.12) : store.readerTheme.textColor.opacity(0.08)) + .clipShape(Circle()) + } + .accessibilityLabel("Search in book") + + // One-Tap Offline Download Button (Feature 2) + Button(action: { + FableHaptics.medium() + Task { + try? await store.downloadBookForOffline(story) + } + }) { + if store.downloadingStoryIds.contains(story.id) { + ProgressView() + .controlSize(.small) + .frame(width: 36, height: 36) + .background(store.readerTheme.textColor.opacity(0.08)) + .clipShape(Circle()) + } else { + let isDownloaded = store.isStoryDownloaded(story) + Image(systemName: isDownloaded ? "checkmark.circle.fill" : "arrow.down.circle") + .fableFont(size: 13, weight: .semibold) + .foregroundColor(isDownloaded ? Color(red: 0.12, green: 0.65, blue: 0.35) : store.readerTheme.textColor) + .frame(width: 36, height: 36) + .background(isDownloaded ? Color(red: 0.12, green: 0.65, blue: 0.35).opacity(0.12) : store.readerTheme.textColor.opacity(0.08)) + .clipShape(Circle()) + } + } + .accessibilityLabel(store.isStoryDownloaded(story) ? "Book downloaded for offline" : "Download book for offline") + // Table of Contents Sheet Button Button(action: { FableHaptics.selection() isShowingChapterSheet = true }) { Image(systemName: "list.bullet.rectangle") - .fableFont(size: 14, weight: .semibold) + .fableFont(size: 13, weight: .semibold) .foregroundColor(store.readerTheme.textColor) - .frame(width: 40, height: 40) + .frame(width: 36, height: 36) .background(store.readerTheme.textColor.opacity(0.08)) .clipShape(Circle()) } @@ -249,9 +523,9 @@ public struct ReaderView: View { } }) { Image(systemName: audioNarrator.isPlaying ? "speaker.wave.3.fill" : "speaker.wave.2") - .fableFont(size: 14, weight: .semibold) + .fableFont(size: 13, weight: .semibold) .foregroundColor(audioNarrator.isPlaying ? FableTheme.brandPrimary : store.readerTheme.textColor) - .frame(width: 40, height: 40) + .frame(width: 36, height: 36) .background(audioNarrator.isPlaying ? FableTheme.brandPrimary.opacity(0.15) : store.readerTheme.textColor.opacity(0.08)) .clipShape(Circle()) } @@ -265,9 +539,9 @@ public struct ReaderView: View { } }) { Image(systemName: currentStoryBookmarked ? "bookmark.fill" : "bookmark") - .fableFont(size: 14, weight: .semibold) + .fableFont(size: 13, weight: .semibold) .foregroundColor(currentStoryBookmarked ? FableTheme.brandPrimary : store.readerTheme.textColor) - .frame(width: 40, height: 40) + .frame(width: 36, height: 36) .background(currentStoryBookmarked ? FableTheme.brandPrimary.opacity(0.12) : store.readerTheme.textColor.opacity(0.08)) .clipShape(Circle()) } @@ -279,31 +553,139 @@ public struct ReaderView: View { store.isShowingDisplayOptions = true }) { Image(systemName: "textformat.size") - .fableFont(size: 14, weight: .semibold) + .fableFont(size: 13, weight: .semibold) .foregroundColor(store.readerTheme.textColor) - .frame(width: 40, height: 40) + .frame(width: 36, height: 36) .background(store.readerTheme.textColor.opacity(0.08)) .clipShape(Circle()) } .accessibilityLabel("Reading appearance options") - // Native Share Link - ShareLink( - item: "\(story.title) by \(story.author)\n\n\(story.synopsis)\n\nRead on Fable." - ) { + // Share & Export Menu (Feature 3) + Menu { + ShareLink("Share Book Details", item: "\(story.title) by \(story.author)\n\n\(story.synopsis)\n\nRead on Fable.") + + if !store.activeStoryAnnotations.isEmpty { + ShareLink( + "Export All Highlights (.md)", + item: ReaderPassageMatcher.exportAnnotationsAsMarkdown(story: story, annotations: store.activeStoryAnnotations) + ) + } + + Button { + let textToUse = selectedTextToAnnotate ?? activeParagraphs.first ?? story.title + activeQuoteCardData = ( + text: textToUse, + note: nil, + color: selectedHighlightColor, + chapter: activeChapter?.chapterNumber + ) + isShowingQuoteCardShare = true + } label: { + Label("Create Quote Card", systemImage: "photo.artframe") + } + } label: { Image(systemName: "square.and.arrow.up") - .fableFont(size: 14, weight: .semibold) + .fableFont(size: 13, weight: .semibold) .foregroundColor(store.readerTheme.textColor) - .frame(width: 40, height: 40) + .frame(width: 36, height: 36) .background(store.readerTheme.textColor.opacity(0.08)) .clipShape(Circle()) } - .accessibilityLabel("Share story") + .accessibilityLabel("Share and export options") } } .padding(.horizontal, 16) .padding(.vertical, 8) .transition(.move(edge: .top).combined(with: .opacity)) + + // In-Book Search Bar Overlay (Feature 1) + if isSearchActive { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .fableFont(size: 13, weight: .bold) + .foregroundColor(FableTheme.brandPrimary) + + TextField("Search in book...", text: $inBookSearchText) + .fableFont(size: 14) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .submitLabel(.search) + .onSubmit { + nextSearchMatch() + } + + if !inBookSearchText.isEmpty { + if searchMatches.isEmpty { + Text("0 matches") + .fableFont(size: 11, weight: .semibold) + .foregroundColor(FableTheme.textMuted) + } else { + Text("\(currentSearchMatchIndex + 1)/\(searchMatches.count)") + .fableFont(size: 11, weight: .bold) + .monospacedDigit() + .foregroundColor(FableTheme.brandPrimary) + + Button(action: { + previousSearchMatch() + }) { + Image(systemName: "chevron.up") + .fableFont(size: 11, weight: .bold) + .foregroundColor(store.readerTheme.textColor) + .frame(width: 26, height: 26) + .background(Color.gray.opacity(0.12)) + .clipShape(Circle()) + } + + Button(action: { + nextSearchMatch() + }) { + Image(systemName: "chevron.down") + .fableFont(size: 11, weight: .bold) + .foregroundColor(store.readerTheme.textColor) + .frame(width: 26, height: 26) + .background(Color.gray.opacity(0.12)) + .clipShape(Circle()) + } + } + + Button(action: { + inBookSearchText = "" + searchMatches = [] + currentSearchMatchIndex = 0 + }) { + Image(systemName: "xmark.circle.fill") + .fableFont(size: 13) + .foregroundColor(FableTheme.textMuted) + } + } + + Button("Done") { + withAnimation(.easeInOut(duration: 0.2)) { + isSearchActive = false + inBookSearchText = "" + searchMatches = [] + currentSearchMatchIndex = 0 + } + } + .fableFont(size: 13, weight: .semibold) + .foregroundColor(FableTheme.brandPrimary) + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background( + RoundedRectangle(cornerRadius: 12) + .fill(store.readerTheme.isDark ? Color(red: 0.18, green: 0.20, blue: 0.25) : Color.white) + .overlay( + RoundedRectangle(cornerRadius: 12) + .stroke(store.readerTheme.isDark ? Color.white.opacity(0.12) : Color.black.opacity(0.08), lineWidth: 0.8) + ) + .shadow(color: Color.black.opacity(0.08), radius: 6, y: 2) + ) + .padding(.horizontal, 16) + .padding(.bottom, 6) + .transition(.move(edge: .top).combined(with: .opacity)) + } } // Active Spoken Audio Narration Banner (Plan 04) @@ -388,7 +770,7 @@ public struct ReaderView: View { .tracking(1.2) .foregroundColor(FableTheme.brandPrimary) Spacer() - Text("Tap paragraph to annotate") + Text("Long press passage to annotate") .fableFont(size: 11) .foregroundColor(store.readerTheme.isDark ? Color.white.opacity(0.75) : FableTheme.textMuted) } @@ -868,26 +1250,98 @@ public struct ReaderView: View { tableOfContentsSheetView .presentationDetents([.medium, .large]) } + .sheet(isPresented: $isShowingQuoteCardShare) { + if let cardData = activeQuoteCardData { + QuoteCardShareSheet( + quoteText: cardData.text, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: cardData.chapter, + note: cardData.note, + highlightColor: cardData.color + ) + .presentationDetents([.large]) + } + } + .onChange(of: inBookSearchText) { _, newQuery in + let results = ReaderPassageMatcher.search( + query: newQuery, + in: chapters, + fallbackParagraphs: activeParagraphs, + fallbackTitle: story.title + ) + searchMatches = results + currentSearchMatchIndex = 0 + if !results.isEmpty { + navigateToSearchMatch(at: 0) + } + } .onChange(of: store.isShowingChapterIndexSheet) { _, newValue in isShowingChapterSheet = newValue } } - private func matchingAnnotation(for para: String) -> Annotation? { - store.activeStoryAnnotations.first { annot in + private func matchingAnnotations(for para: String) -> [Annotation] { + store.activeStoryAnnotations.filter { annot in if let annotChapter = annot.chapterNumber, let currentChapterNum = activeChapter?.chapterNumber, annotChapter != currentChapterNum { return false } - return para.contains(annot.selectedText) || annot.selectedText.contains(para) + let trimmed = annot.selectedText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + return para.contains(trimmed) || trimmed.contains(para) + } + } + + private func renderParagraphContent( + _ para: String, + annotations: [Annotation], + isSpoken: Bool, + searchQuery: String? = nil + ) -> AttributedString { + var attributed = AttributedString(para) + + // Highlight active search matches in bright gold + if let query = searchQuery?.trimmingCharacters(in: .whitespacesAndNewlines), !query.isEmpty { + var searchRange = attributed.startIndex.. some View { - let matchingAnnotation = matchingAnnotation(for: para) + let matching = matchingAnnotations(for: para) let isSpokenParagraph: Bool = { guard audioNarrator.isPlaying, audioNarrator.activeStoryId == story.id else { return false } @@ -902,7 +1356,14 @@ public struct ReaderView: View { return false }() - Text(para) + let attributed = renderParagraphContent( + para, + annotations: matching, + isSpoken: isSpokenParagraph, + searchQuery: isSearchActive ? inBookSearchText : nil + ) + + Text(attributed) .fableFont( size: 17, scale: CGFloat(store.readerFontSize / 100.0), @@ -911,12 +1372,8 @@ public struct ReaderView: View { ) .lineSpacing(store.readerLineSpacing.points) .foregroundColor(store.readerTheme.textColor) - .padding(matchingAnnotation != nil || isSpokenParagraph ? 6 : 0) - .background( - matchingAnnotation != nil - ? matchingAnnotation!.color.displayColor - : (isSpokenParagraph ? FableTheme.brandPrimary.opacity(0.12) : Color.clear) - ) + .padding(.vertical, matching.isEmpty && !isSpokenParagraph ? 0 : 4) + .padding(.horizontal, matching.isEmpty && !isSpokenParagraph ? 0 : 4) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(isSpokenParagraph ? FableTheme.brandPrimary.opacity(0.4) : Color.clear, lineWidth: 1) @@ -926,191 +1383,456 @@ public struct ReaderView: View { .contentShape(Rectangle()) .animation(.easeInOut(duration: 0.25), value: isSpokenParagraph) .onTapGesture { - self.editingAnnotation = matchingAnnotation - self.selectedTextToAnnotate = para - if let existing = matchingAnnotation { - self.selectedHighlightColor = existing.color - self.annotationNote = existing.note ?? "" - self.isPinToJournal = existing.isPinnedToJournal + if let existing = matching.first { + FableHaptics.selection() + openAnnotationSheet(for: para, existing: existing) } else { - self.selectedHighlightColor = .terracotta - self.annotationNote = "" - self.isPinToJournal = true + if store.hapticFeedback { + HapticManager.selection() + } + withAnimation(.easeInOut(duration: 0.2)) { + isChromeVisible.toggle() + } } - self.isShowingAnnotationSheet = true + } + .onLongPressGesture(minimumDuration: 0.35) { + FableHaptics.medium() + openAnnotationSheet(for: para, existing: matching.first) } } // Marginalia & Passage Annotation Modal (Plan 02) private var annotationSheetView: some View { - VStack(alignment: .leading, spacing: 18) { - Capsule() - .fill(Color.gray.opacity(0.3)) - .frame(width: 36, height: 5) - .frame(maxWidth: .infinity) - .padding(.top, 12) - - HStack { - Text(editingAnnotation != nil ? "Edit Annotation" : "Annotate Passage") - .fableFont(size: 18, weight: .bold, design: .serif) - .foregroundColor(FableTheme.deepCharcoal) + ScrollView(showsIndicators: false) { + VStack(alignment: .leading, spacing: 18) { + Capsule() + .fill(Color.gray.opacity(0.3)) + .frame(width: 36, height: 5) + .frame(maxWidth: .infinity) + .padding(.top, 12) - Spacer() + HStack { + Text(editingAnnotation != nil ? "Edit Annotation" : "Annotate Passage") + .fableFont(size: 18, weight: .bold, design: .serif) + .foregroundColor(FableTheme.deepCharcoal) + + Spacer() + + Button(action: { + isShowingAnnotationSheet = false + resetAnnotationState() + }) { + Image(systemName: "xmark") + .fableFont(size: 13, weight: .bold) + .foregroundColor(FableTheme.subtleSlate) + .padding(6) + .background(Color.gray.opacity(0.12)) + .clipShape(Circle()) + } + } + .padding(.horizontal, 20) - Button(action: { - isShowingAnnotationSheet = false - resetAnnotationState() - }) { - Image(systemName: "xmark") - .fableFont(size: 13, weight: .bold) + // Live Quote Excerpt Preview with Selected Highlight Color + VStack(alignment: .leading, spacing: 6) { + Text("SELECTED PASSAGE") + .fableFont(size: 10, weight: .bold) + .tracking(1.0) .foregroundColor(FableTheme.subtleSlate) - .padding(6) - .background(Color.gray.opacity(0.12)) - .clipShape(Circle()) + .padding(.horizontal, 20) + + Text("“\(selectedTextToAnnotate ?? "")”") + .fableFont(size: 14, weight: .medium, design: .serif) + .italic() + .foregroundColor(FableTheme.deepCharcoal) + .padding(14) + .frame(maxWidth: .infinity, alignment: .leading) + .background(selectedHighlightColor.displayColor) + .clipShape(RoundedRectangle(cornerRadius: 10)) + .overlay( + RoundedRectangle(cornerRadius: 10) + .stroke(selectedHighlightColor.displayColor.opacity(0.8), lineWidth: 1) + ) + .padding(.horizontal, 20) } - } - .padding(.horizontal, 20) - - if let excerpt = selectedTextToAnnotate { - Text("“\(excerpt.prefix(120))...”") - .fableFont(size: 13, weight: .regular, design: .serif) - .italic() - .foregroundColor(FableTheme.textSecondary) - .lineLimit(2) - .padding(12) - .background(FableTheme.surface) - .clipShape(RoundedRectangle(cornerRadius: 8)) - .padding(.horizontal, 20) - } - - // Highlight color picker - VStack(alignment: .leading, spacing: 8) { - Text("HIGHLIGHT COLOR") - .fableFont(size: 10, weight: .bold) - .tracking(1.0) - .foregroundColor(FableTheme.subtleSlate) - .padding(.horizontal, 20) - HStack(spacing: 12) { - ForEach(HighlightColor.allCases) { colorToken in - Button(action: { - selectedHighlightColor = colorToken - }) { - HStack(spacing: 8) { - Circle() - .fill(colorToken.displayColor.opacity(1.0)) - .frame(width: 16, height: 16) - Text(colorToken.displayName) - .fableFont(size: 13, weight: .medium) + // Passage Boundary Range Controls (Start & End Word Selectors) + if paragraphWordsForAnnotation.count > 1 { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text("CHOOSE WHERE TO START & END") + .fableFont(size: 10, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.subtleSlate) + + Spacer() + + Text("\(currentSelectedWordCount) of \(paragraphWordsForAnnotation.count) words") + .fableFont(size: 11, weight: .semibold) + .foregroundColor(FableTheme.brandPrimary) + } + .padding(.horizontal, 20) + + // Quick Presets Row + HStack(spacing: 8) { + Button("Full Paragraph") { + updateSelectedPassageRange(start: 0, end: paragraphWordsForAnnotation.count - 1) } - .frame(maxWidth: .infinity) - .padding(.vertical, 8) - .background(selectedHighlightColor == colorToken ? FableTheme.softPeach : Color.gray.opacity(0.08)) - .foregroundColor(selectedHighlightColor == colorToken ? FableTheme.terracotta : FableTheme.deepCharcoal) - .clipShape(RoundedRectangle(cornerRadius: 8)) - .overlay( - RoundedRectangle(cornerRadius: 8) - .stroke(selectedHighlightColor == colorToken ? FableTheme.terracotta : Color.clear, lineWidth: 1) + .buttonStyle(.bordered) + .controlSize(.mini) + .tint(FableTheme.brandPrimary) + + let sentences = ReaderPassageMatcher.sentences(from: activeParagraphForAnnotation) + if sentences.count > 1 { + Menu { + ForEach(Array(sentences.enumerated()), id: \.offset) { sIdx, sent in + Button("Sentence \(sIdx + 1): \(sent.prefix(30))...") { + selectSentence(at: sIdx, in: sentences) + } + } + } label: { + Label("By Sentence", systemImage: "text.quote") + .font(.caption2) + } + .buttonStyle(.bordered) + .controlSize(.mini) + .tint(FableTheme.brandPrimary) + } + + Spacer() + } + .padding(.horizontal, 20) + + // Start Word Control + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("Start:") + .fableFont(size: 12, weight: .medium) + .foregroundColor(FableTheme.textSecondary) + Text("\"\(startWordPreview)\"") + .fableFont(size: 12, weight: .bold) + .foregroundColor(FableTheme.brandPrimary) + .lineLimit(1) + Spacer() + Text("Word \(annotationStartWordIndex + 1)") + .fableFont(size: 11) + .foregroundColor(FableTheme.textMuted) + Stepper("", value: Binding( + get: { annotationStartWordIndex }, + set: { newStart in + let clamped = min(max(0, newStart), annotationEndWordIndex) + updateSelectedPassageRange(start: clamped, end: annotationEndWordIndex) + } + ), in: 0...annotationEndWordIndex) + .labelsHidden() + } + + Slider( + value: Binding( + get: { Double(annotationStartWordIndex) }, + set: { newStart in + let clamped = min(max(0, Int(newStart)), annotationEndWordIndex) + updateSelectedPassageRange(start: clamped, end: annotationEndWordIndex) + } + ), + in: 0...Double(max(0, paragraphWordsForAnnotation.count - 1)), + step: 1 ) + .tint(FableTheme.brandPrimary) } + .padding(.horizontal, 20) + + // End Word Control + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("End:") + .fableFont(size: 12, weight: .medium) + .foregroundColor(FableTheme.textSecondary) + Text("\"\(endWordPreview)\"") + .fableFont(size: 12, weight: .bold) + .foregroundColor(FableTheme.brandPrimary) + .lineLimit(1) + Spacer() + Text("Word \(annotationEndWordIndex + 1)") + .fableFont(size: 11) + .foregroundColor(FableTheme.textMuted) + Stepper("", value: Binding( + get: { annotationEndWordIndex }, + set: { newEnd in + let clamped = max(min(paragraphWordsForAnnotation.count - 1, newEnd), annotationStartWordIndex) + updateSelectedPassageRange(start: annotationStartWordIndex, end: clamped) + } + ), in: annotationStartWordIndex...max(annotationStartWordIndex, paragraphWordsForAnnotation.count - 1)) + .labelsHidden() + } + + Slider( + value: Binding( + get: { Double(annotationEndWordIndex) }, + set: { newEnd in + let clamped = max(min(paragraphWordsForAnnotation.count - 1, Int(newEnd)), annotationStartWordIndex) + updateSelectedPassageRange(start: annotationStartWordIndex, end: clamped) + } + ), + in: 0...Double(max(0, paragraphWordsForAnnotation.count - 1)), + step: 1 + ) + .tint(FableTheme.brandPrimary) + } + .padding(.horizontal, 20) } - } - .padding(.horizontal, 20) - } - - // Optional note field - VStack(alignment: .leading, spacing: 6) { - Text("NOTE (OPTIONAL)") - .fableFont(size: 10, weight: .bold) - .tracking(1.0) - .foregroundColor(FableTheme.subtleSlate) + .padding(.vertical, 8) + .background(Color.gray.opacity(0.04)) + .clipShape(RoundedRectangle(cornerRadius: 10)) .padding(.horizontal, 20) + } - TextField("Add your thoughts...", text: $annotationNote, axis: .vertical) - .fableFont(size: 14) - .lineLimit(2...4) - .padding(12) - .background(Color.gray.opacity(0.06)) - .clipShape(RoundedRectangle(cornerRadius: 8)) + // Highlight color picker + VStack(alignment: .leading, spacing: 8) { + Text("HIGHLIGHT COLOR") + .fableFont(size: 10, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.subtleSlate) + .padding(.horizontal, 20) + + HStack(spacing: 12) { + ForEach(HighlightColor.allCases) { colorToken in + Button(action: { + selectedHighlightColor = colorToken + }) { + HStack(spacing: 8) { + Circle() + .fill(colorToken.displayColor.opacity(1.0)) + .frame(width: 16, height: 16) + Text(colorToken.displayName) + .fableFont(size: 13, weight: .medium) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + .background(selectedHighlightColor == colorToken ? FableTheme.softPeach : Color.gray.opacity(0.08)) + .foregroundColor(selectedHighlightColor == colorToken ? FableTheme.terracotta : FableTheme.deepCharcoal) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(selectedHighlightColor == colorToken ? FableTheme.terracotta : Color.clear, lineWidth: 1) + ) + } + } + } .padding(.horizontal, 20) - } - - // Pin to Shelf Reading Journal Quote Deck Toggle - Toggle(isOn: $isPinToJournal) { - VStack(alignment: .leading, spacing: 2) { - Text("Pin to Shelf Journal Deck") - .fableFont(size: 14, weight: .semibold) - .foregroundColor(FableTheme.textPrimary) - Text("Promotes excerpt as a quote card on your shelf") - .fableFont(size: 11) - .foregroundColor(FableTheme.textMuted) } - } - .tint(FableTheme.brandPrimary) - .padding(.horizontal, 20) - - // Save / Update Action Button - VStack(spacing: 10) { - Button(action: { - let cleanNote = annotationNote.trimmingCharacters(in: .whitespacesAndNewlines) - let finalNote = cleanNote.isEmpty ? nil : cleanNote - if let existing = editingAnnotation { - store.updateAnnotation( - existing, - story: story, - color: selectedHighlightColor, - note: finalNote, - pinToJournal: isPinToJournal - ) - } else if let text = selectedTextToAnnotate { - let fullText = activeChapterText - let nsText = fullText as NSString - let targetRange = nsText.range(of: text) - let startOffset = targetRange.location != NSNotFound ? targetRange.location : 0 - let endOffset = targetRange.location != NSNotFound ? (targetRange.location + targetRange.length) : text.utf16.count - - store.addAnnotation( - story: story, - text: text, - chapterNumber: activeChapter?.chapterNumber, - startOffset: startOffset, - endOffset: endOffset, + + // Optional note field + VStack(alignment: .leading, spacing: 6) { + Text("NOTE (OPTIONAL)") + .fableFont(size: 10, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.subtleSlate) + .padding(.horizontal, 20) + + TextField("Add your thoughts...", text: $annotationNote, axis: .vertical) + .fableFont(size: 14) + .lineLimit(2...4) + .padding(12) + .background(Color.gray.opacity(0.06)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .padding(.horizontal, 20) + } + + // Pin to Shelf Reading Journal Quote Deck Toggle + Toggle(isOn: $isPinToJournal) { + VStack(alignment: .leading, spacing: 2) { + Text("Pin to Shelf Journal Deck") + .fableFont(size: 14, weight: .semibold) + .foregroundColor(FableTheme.textPrimary) + Text("Promotes excerpt as a quote card on your shelf") + .fableFont(size: 11) + .foregroundColor(FableTheme.textMuted) + } + } + .tint(FableTheme.brandPrimary) + .padding(.horizontal, 20) + + // Shareable Quote Card & Markdown Export (Feature 3) + VStack(spacing: 8) { + Button(action: { + let quote = selectedTextToAnnotate ?? activeParagraphForAnnotation + activeQuoteCardData = ( + text: quote, + note: annotationNote.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : annotationNote, color: selectedHighlightColor, - note: finalNote, - pinToJournal: isPinToJournal + chapter: activeChapter?.chapterNumber ) - } - isShowingAnnotationSheet = false - resetAnnotationState() - }) { - Text(editingAnnotation != nil ? "Update Annotation" : "Save Annotation") - .fableFont(size: 15, weight: .semibold) + isShowingQuoteCardShare = true + }) { + HStack(spacing: 8) { + Image(systemName: "photo.artframe") + .fableFont(size: 13, weight: .bold) + Text("Share as Quote Card") + .fableFont(size: 13, weight: .semibold) + } .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(FableTheme.brandPrimary) - .foregroundColor(.white) - .clipShape(RoundedRectangle(cornerRadius: 12)) - } + .padding(.vertical, 10) + .background(Color.gray.opacity(0.08)) + .foregroundColor(FableTheme.deepCharcoal) + .clipShape(RoundedRectangle(cornerRadius: 10)) + } - if let existing = editingAnnotation { - Button(role: .destructive) { - store.deleteAnnotation(id: existing.id, storyId: story.id) - isShowingAnnotationSheet = false - resetAnnotationState() - } label: { - Text("Delete Annotation") - .fableFont(size: 14, weight: .semibold) + if !store.activeStoryAnnotations.isEmpty { + let md = ReaderPassageMatcher.exportAnnotationsAsMarkdown(story: story, annotations: store.activeStoryAnnotations) + ShareLink( + item: md, + preview: SharePreview("\(story.title) Highlights (.md)") + ) { + HStack(spacing: 8) { + Image(systemName: "doc.plaintext") + .fableFont(size: 13, weight: .bold) + Text("Export All Highlights (.md)") + .fableFont(size: 13, weight: .semibold) + } .frame(maxWidth: .infinity) .padding(.vertical, 10) - .background(Color.red.opacity(0.08)) + .background(Color.gray.opacity(0.08)) + .foregroundColor(FableTheme.brandPrimary) .clipShape(RoundedRectangle(cornerRadius: 10)) + } + } + } + .padding(.horizontal, 20) + + // Save / Update Action Button + VStack(spacing: 10) { + Button(action: { + saveOrUpdateAnnotation() + }) { + Text(editingAnnotation != nil ? "Update Annotation" : "Save Annotation") + .fableFont(size: 15, weight: .semibold) + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + .background(FableTheme.brandPrimary) + .foregroundColor(.white) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + + if let existing = editingAnnotation { + Button(role: .destructive) { + store.deleteAnnotation(id: existing.id, storyId: story.id) + isShowingAnnotationSheet = false + resetAnnotationState() + } label: { + Text("Delete Annotation") + .fableFont(size: 14, weight: .semibold) + .frame(maxWidth: .infinity) + .padding(.vertical, 10) + .background(Color.red.opacity(0.08)) + .clipShape(RoundedRectangle(cornerRadius: 10)) + } } } + .padding(.horizontal, 20) + .padding(.bottom, 24) } - .padding(.horizontal, 20) - .padding(.bottom, 16) } } + + private var currentSelectedWordCount: Int { + guard !paragraphWordsForAnnotation.isEmpty else { return 0 } + return max(1, annotationEndWordIndex - annotationStartWordIndex + 1) + } + + private var startWordPreview: String { + guard paragraphWordsForAnnotation.indices.contains(annotationStartWordIndex) else { return "" } + return paragraphWordsForAnnotation[annotationStartWordIndex] + } + + private var endWordPreview: String { + guard paragraphWordsForAnnotation.indices.contains(annotationEndWordIndex) else { return "" } + return paragraphWordsForAnnotation[annotationEndWordIndex] + } + + private func openAnnotationSheet(for para: String, existing: Annotation?) { + self.activeParagraphForAnnotation = para + let words = ReaderPassageMatcher.words(from: para) + self.paragraphWordsForAnnotation = words + self.editingAnnotation = existing + + if let existing = existing { + self.selectedHighlightColor = existing.color + self.annotationNote = existing.note ?? "" + self.isPinToJournal = existing.isPinnedToJournal + self.selectedTextToAnnotate = existing.selectedText + + let range = ReaderPassageMatcher.wordRange(for: existing.selectedText, in: words) + self.annotationStartWordIndex = range.lowerBound + self.annotationEndWordIndex = range.upperBound + } else { + self.selectedHighlightColor = .terracotta + self.annotationNote = "" + self.isPinToJournal = true + self.annotationStartWordIndex = 0 + self.annotationEndWordIndex = max(0, words.count - 1) + self.selectedTextToAnnotate = words.isEmpty ? para : words.joined(separator: " ") + } + self.isShowingAnnotationSheet = true + } + + private func updateSelectedPassageRange(start: Int, end: Int) { + guard !paragraphWordsForAnnotation.isEmpty else { return } + let clampedStart = max(0, min(start, paragraphWordsForAnnotation.count - 1)) + let clampedEnd = max(clampedStart, min(end, paragraphWordsForAnnotation.count - 1)) + annotationStartWordIndex = clampedStart + annotationEndWordIndex = clampedEnd + selectedTextToAnnotate = ReaderPassageMatcher.substring( + from: paragraphWordsForAnnotation, + range: clampedStart...clampedEnd + ) + } + + private func selectSentence(at index: Int, in sentences: [String]) { + guard sentences.indices.contains(index) else { return } + let sentence = sentences[index] + let range = ReaderPassageMatcher.wordRange(for: sentence, in: paragraphWordsForAnnotation) + updateSelectedPassageRange(start: range.lowerBound, end: range.upperBound) + } + + private func saveOrUpdateAnnotation() { + let cleanNote = annotationNote.trimmingCharacters(in: .whitespacesAndNewlines) + let finalNote = cleanNote.isEmpty ? nil : cleanNote + let text = (selectedTextToAnnotate ?? activeParagraphForAnnotation).trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty else { return } + + let fullText = activeChapterText + let offsets = ReaderPassageMatcher.locateSubstringOffsets( + in: fullText, + substring: text, + withinParagraph: activeParagraphForAnnotation + ) + + if let existing = editingAnnotation { + store.updateAnnotation( + existing, + story: story, + text: text, + startOffset: offsets.start, + endOffset: offsets.end, + color: selectedHighlightColor, + note: finalNote, + pinToJournal: isPinToJournal + ) + } else { + store.addAnnotation( + story: story, + text: text, + chapterNumber: activeChapter?.chapterNumber, + startOffset: offsets.start, + endOffset: offsets.end, + color: selectedHighlightColor, + note: finalNote, + pinToJournal: isPinToJournal + ) + } + isShowingAnnotationSheet = false + resetAnnotationState() + } // Helper to reset annotation state private func resetAnnotationState() { @@ -1119,6 +1841,10 @@ public struct ReaderView: View { annotationNote = "" selectedHighlightColor = .terracotta isPinToJournal = true + activeParagraphForAnnotation = "" + paragraphWordsForAnnotation = [] + annotationStartWordIndex = 0 + annotationEndWordIndex = 0 } private func setCurrentPageProgrammatically(_ targetPage: Int) { @@ -1128,6 +1854,50 @@ public struct ReaderView: View { currentPage = clamped } + private func nextSearchMatch() { + guard !searchMatches.isEmpty else { return } + FableHaptics.selection() + let nextIdx = (currentSearchMatchIndex + 1) % searchMatches.count + navigateToSearchMatch(at: nextIdx) + } + + private func previousSearchMatch() { + guard !searchMatches.isEmpty else { return } + FableHaptics.selection() + let prevIdx = (currentSearchMatchIndex - 1 + searchMatches.count) % searchMatches.count + navigateToSearchMatch(at: prevIdx) + } + + private func navigateToSearchMatch(at index: Int) { + guard searchMatches.indices.contains(index) else { return } + currentSearchMatchIndex = index + let match = searchMatches[index] + + if !chapters.isEmpty && match.chapterIndex != currentChapterIndex { + selectChapter(at: match.chapterIndex) + } + + if store.isPaginatedMode { + if let targetPage = ReaderPassageMatcher.pageNumber( + for: Annotation( + storyId: story.id, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: match.chapterNumber, + utf16StartOffset: 0, + utf16EndOffset: match.matchedText.utf16.count, + selectedText: match.matchedText + ), + in: pages + ) { + setCurrentPageProgrammatically(targetPage) + } + } else { + pendingScrollParagraphId = "para-\(match.paragraphIndex)" + triggerScrollRestore() + } + } + private func turnPageBack() { if store.hapticFeedback { HapticManager.selection() diff --git a/frontend/FableApp/Features/Shelf/Views/ProfileView.swift b/frontend/FableApp/Features/Shelf/Views/ProfileView.swift index b93bed9..91d48a3 100644 --- a/frontend/FableApp/Features/Shelf/Views/ProfileView.swift +++ b/frontend/FableApp/Features/Shelf/Views/ProfileView.swift @@ -208,7 +208,7 @@ public struct ProfileView: View { .fableFont(size: 14, weight: selectedTab == tab ? .semibold : .medium) .frame(maxWidth: .infinity) .padding(.vertical, 10) - .background(selectedTab == tab ? Color.white : Color.clear) + .background(selectedTab == tab ? FableTheme.cardBackground : Color.clear) .foregroundColor(selectedTab == tab ? FableTheme.textPrimary : FableTheme.textMuted) .clipShape(RoundedRectangle(cornerRadius: 10)) .shadow(color: selectedTab == tab ? Color.black.opacity(0.06) : Color.clear, radius: 4, y: 1) diff --git a/frontend/FableApp/Features/Shelf/Views/SettingsView.swift b/frontend/FableApp/Features/Shelf/Views/SettingsView.swift index 841ff6d..731604b 100644 --- a/frontend/FableApp/Features/Shelf/Views/SettingsView.swift +++ b/frontend/FableApp/Features/Shelf/Views/SettingsView.swift @@ -11,6 +11,9 @@ public struct SettingsView: View { @State private var navigateToProfile: Bool = false @State private var isShowingSignOutAlert: Bool = false @State private var isShowingDiagnostics: Bool = false + @State private var isShowingServerConfig: Bool = false + @State private var customServerInput: String = StoryAPIService.resolvedBaseURL().absoluteString + @State private var currentServerURLString: String = StoryAPIService.resolvedBaseURL().absoluteString public init() {} @@ -73,6 +76,49 @@ public struct SettingsView: View { } .buttonStyle(.plain) + // App Appearance Section (System / Light / Dark) + VStack(alignment: .leading, spacing: 10) { + Text("APPEARANCE") + .fableFont(size: 11, weight: .bold) + .tracking(1.0) + .foregroundColor(FableTheme.textMuted) + .padding(.leading, 8) + + VStack(spacing: 12) { + HStack(spacing: 14) { + Image(systemName: store.appAppearance.iconName) + .fableFont(size: 16) + .foregroundColor(FableTheme.brandPrimary) + .frame(width: 32, height: 32) + .background(FableTheme.brandPrimary.opacity(0.12)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + + VStack(alignment: .leading, spacing: 2) { + Text("App Theme") + .fableFont(size: 15, weight: .medium) + .foregroundColor(FableTheme.textPrimary) + Text("Follow iOS system appearance or force Light / Dark") + .fableFont(size: 11) + .foregroundColor(FableTheme.textMuted) + } + + Spacer() + } + + Picker("App Theme", selection: $store.appAppearance) { + ForEach(AppAppearance.allCases) { appearance in + Text(appearance.displayName).tag(appearance) + } + } + .pickerStyle(.segmented) + .accessibilityLabel("App Theme") + } + .padding(16) + .background(FableTheme.cardBackground) + .clipShape(RoundedRectangle(cornerRadius: 16)) + .shadow(color: Color.black.opacity(0.03), radius: 6, y: 2) + } + // Reading Preferences Section VStack(alignment: .leading, spacing: 10) { Text("READING PREFERENCES") @@ -130,7 +176,7 @@ public struct SettingsView: View { .background(FableTheme.surface) .clipShape(RoundedRectangle(cornerRadius: 8)) - Text("Theme Mode") + Text("Reader Theme") .fableFont(size: 15, weight: .medium) .foregroundColor(FableTheme.textPrimary) @@ -300,11 +346,69 @@ public struct SettingsView: View { .padding(.horizontal, 16) .padding(.vertical, 12) } + + Divider().padding(.leading, 16) + + Button(action: { + customServerInput = StoryAPIService.resolvedBaseURL().absoluteString + isShowingServerConfig = true + }) { + HStack(spacing: 12) { + Image(systemName: "server.rack") + .fableFont(size: 16) + .foregroundColor(FableTheme.brandPrimary) + .frame(width: 32, height: 32) + .background(FableTheme.brandPrimary.opacity(0.12)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + + VStack(alignment: .leading, spacing: 2) { + Text("Backend Server URL") + .fableFont(size: 15, weight: .medium) + .foregroundColor(FableTheme.textPrimary) + + Text(currentServerURLString) + .fableFont(size: 11, design: .monospaced) + .foregroundColor(FableTheme.textMuted) + .lineLimit(1) + } + + Spacer() + + Image(systemName: "pencil") + .fableFont(size: 13, weight: .semibold) + .foregroundColor(FableTheme.brandPrimary) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + } } .background(FableTheme.cardBackground) .clipShape(RoundedRectangle(cornerRadius: 16)) .shadow(color: Color.black.opacity(0.03), radius: 6, y: 2) } + .alert("Backend Server URL", isPresented: $isShowingServerConfig) { + TextField("http://192.168.1.50:8001/api/v1", text: $customServerInput) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + Button("Save & Sync") { + let updated = StoryAPIService.setCustomBaseURL(customServerInput) + currentServerURLString = updated.absoluteString + Task { await store.syncWithCloudBackend() } + } + Button("Use Render Cloud") { + let updated = StoryAPIService.setCustomBaseURL(StoryAPIService.cloudRenderBaseURLString) + currentServerURLString = updated.absoluteString + Task { await store.syncWithCloudBackend() } + } + Button("Reset to Bundle Default") { + let updated = StoryAPIService.setCustomBaseURL(nil) + currentServerURLString = updated.absoluteString + Task { await store.syncWithCloudBackend() } + } + Button("Cancel", role: .cancel) {} + } message: { + Text("Enter your Fedora/Mac LAN URL (e.g. http://192.168.1.50:8001/api/v1), an HTTPS tunnel URL, or choose Render Cloud.") + } // Account & Session Section VStack(alignment: .leading, spacing: 10) { diff --git a/frontend/FableApp/Features/Shelf/Views/ShelfView.swift b/frontend/FableApp/Features/Shelf/Views/ShelfView.swift index 35e1da2..1a1183e 100644 --- a/frontend/FableApp/Features/Shelf/Views/ShelfView.swift +++ b/frontend/FableApp/Features/Shelf/Views/ShelfView.swift @@ -115,7 +115,7 @@ public struct ShelfView: View { .fableFont(size: 14, weight: selectedTab == tab ? .semibold : .medium) .frame(maxWidth: .infinity) .padding(.vertical, 10) - .background(selectedTab == tab ? Color.white : Color.clear) + .background(selectedTab == tab ? FableTheme.cardBackground : Color.clear) .foregroundColor(selectedTab == tab ? FableTheme.textPrimary : FableTheme.textMuted) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) .overlay( @@ -391,7 +391,7 @@ public struct ShelfView: View { ) VStack(alignment: .leading, spacing: 4) { - // Genre / Format Pill + // Genre / Format Pill & Offline Badge HStack(spacing: 6) { Text(story.contentFormat == .manga ? "MANGA" : (story.sourceProvider == .standardEbooks ? "STANDARD EBOOKS" : story.genre.rawValue.uppercased())) .fableFont(size: 8, weight: .heavy) @@ -400,6 +400,20 @@ public struct ShelfView: View { .padding(.vertical, 2) .background(FableTheme.surface) .clipShape(Capsule()) + + if store.isStoryDownloaded(story) { + HStack(spacing: 3) { + Image(systemName: "arrow.down.circle.fill") + .fableFont(size: 8) + Text("OFFLINE") + .fableFont(size: 8, weight: .heavy) + } + .foregroundColor(Color(red: 0.12, green: 0.62, blue: 0.32)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Color(red: 0.12, green: 0.62, blue: 0.32).opacity(0.12)) + .clipShape(Capsule()) + } } // Serif Title diff --git a/frontend/FableApp/Features/Write/Views/ManuscriptEditor.swift b/frontend/FableApp/Features/Write/Views/ManuscriptEditor.swift index 8ee5e2c..456715d 100644 --- a/frontend/FableApp/Features/Write/Views/ManuscriptEditor.swift +++ b/frontend/FableApp/Features/Write/Views/ManuscriptEditor.swift @@ -35,6 +35,7 @@ struct ManuscriptEditor: UIViewRepresentable { } func updateUIView(_ textView: UITextView, context: Context) { + textView.textColor = UIColor(FableTheme.textPrimary) if textView.text != text { textView.text = text } diff --git a/frontend/FableApp/Features/Write/Views/StoryPublishedSheet.swift b/frontend/FableApp/Features/Write/Views/StoryPublishedSheet.swift index 1d32085..ae99fc0 100644 --- a/frontend/FableApp/Features/Write/Views/StoryPublishedSheet.swift +++ b/frontend/FableApp/Features/Write/Views/StoryPublishedSheet.swift @@ -135,6 +135,6 @@ struct StoryPublishedSheet: View { } .presentationDetents([.fraction(0.65)]) .presentationDragIndicator(.hidden) - .background(Color.white) + .background(FableTheme.cardBackground) } } diff --git a/frontend/FableAppTests/FableAppTests.swift b/frontend/FableAppTests/FableAppTests.swift index 633b62e..665afdf 100644 --- a/frontend/FableAppTests/FableAppTests.swift +++ b/frontend/FableAppTests/FableAppTests.swift @@ -54,6 +54,7 @@ final class FableAppTests: XCTestCase { } func testMutedTextMeetsWCAGAAContrastOnLightSurfaces() { + let lightTraits = UITraitCollection(userInterfaceStyle: .light) let lightSurfaces: [(String, Color)] = [ ("background", FableTheme.background), ("surface", FableTheme.surface), @@ -62,15 +63,65 @@ final class FableAppTests: XCTestCase { ] for (name, surface) in lightSurfaces { - guard let ratio = contrastRatio(UIColor(FableTheme.textMuted), UIColor(surface)) else { + let fg = UIColor(FableTheme.textMuted).resolvedColor(with: lightTraits) + let bg = UIColor(surface).resolvedColor(with: lightTraits) + guard let ratio = contrastRatio(fg, bg) else { XCTFail("Unable to resolve colors for \(name)") continue } - XCTAssertGreaterThanOrEqual(ratio, 4.5, "Muted text must meet WCAG AA contrast on \(name)") + XCTAssertGreaterThanOrEqual(ratio, 4.5, "Muted text must meet WCAG AA contrast on light \(name)") } } + func testMutedTextMeetsWCAGAAContrastOnDarkSurfaces() { + let darkTraits = UITraitCollection(userInterfaceStyle: .dark) + let darkSurfaces: [(String, Color)] = [ + ("background", FableTheme.background), + ("surface", FableTheme.surface), + ("surface variant", FableTheme.surfaceVariant), + ("card background", FableTheme.cardBackground) + ] + + for (name, surface) in darkSurfaces { + let fg = UIColor(FableTheme.textMuted).resolvedColor(with: darkTraits) + let bg = UIColor(surface).resolvedColor(with: darkTraits) + guard let ratio = contrastRatio(fg, bg) else { + XCTFail("Unable to resolve dark colors for \(name)") + continue + } + + XCTAssertGreaterThanOrEqual(ratio, 4.5, "Muted text must meet WCAG AA contrast on dark \(name)") + } + } + + @MainActor + func testAppAppearanceColorSchemeMappingAndPersistence() { + XCTAssertNil(AppAppearance.system.colorScheme) + XCTAssertEqual(AppAppearance.light.colorScheme, .light) + XCTAssertEqual(AppAppearance.dark.colorScheme, .dark) + + let defaults = UserDefaults.standard + let original = defaults.string(forKey: AppAppearance.storageKey) + defer { + if let original { + defaults.set(original, forKey: AppAppearance.storageKey) + } else { + defaults.removeObject(forKey: AppAppearance.storageKey) + } + } + + let store = StoryStore() + store.appAppearance = .dark + XCTAssertEqual(defaults.string(forKey: AppAppearance.storageKey), AppAppearance.dark.rawValue) + + let reloaded = StoryStore() + XCTAssertEqual(reloaded.appAppearance, .dark) + + reloaded.appAppearance = .system + XCTAssertEqual(defaults.string(forKey: AppAppearance.storageKey), AppAppearance.system.rawValue) + } + @MainActor func testReaderTypographyCombinesDynamicTypeAndReaderScale() { let defaultSize = renderedReaderTextSize(scale: 1, dynamicTypeSize: .large) diff --git a/frontend/FableAppTests/PlanFeaturesRegressionTests.swift b/frontend/FableAppTests/PlanFeaturesRegressionTests.swift index 3c4759a..79f9841 100644 --- a/frontend/FableAppTests/PlanFeaturesRegressionTests.swift +++ b/frontend/FableAppTests/PlanFeaturesRegressionTests.swift @@ -221,6 +221,82 @@ final class PlanFeaturesRegressionTests: XCTestCase { XCTAssertEqual(ReaderPassageMatcher.pageNumber(for: quoteWithChapter, in: pages), pages.count) } + @MainActor + func testReaderPassageMatcherBoundarySelectionAndOffsetResolution() { + let paragraph = "Alice was beginning to get very tired of sitting by her sister on the bank. Once or twice she had peeped into the book." + let words = ReaderPassageMatcher.words(from: paragraph) + XCTAssertEqual(words.first, "Alice") + XCTAssertEqual(words.last, "book.") + XCTAssertEqual(words.count, 24) + + let sentences = ReaderPassageMatcher.sentences(from: paragraph) + XCTAssertEqual(sentences.count, 2) + XCTAssertEqual(sentences[0], "Alice was beginning to get very tired of sitting by her sister on the bank.") + XCTAssertEqual(sentences[1], "Once or twice she had peeped into the book.") + + // Test phrase range matching within words + let phrase = "very tired of sitting by her sister" + let range = ReaderPassageMatcher.wordRange(for: phrase, in: words) + let extracted = ReaderPassageMatcher.substring(from: words, range: range) + XCTAssertEqual(extracted, phrase) + + // Test offset resolution within full chapter text + let fullChapter = "Chapter I\n\nDown the Rabbit-Hole\n\n" + paragraph + let offsets = ReaderPassageMatcher.locateSubstringOffsets(in: fullChapter, substring: phrase, withinParagraph: paragraph) + let nsFull = fullChapter as NSString + let extractedFromOffsets = nsFull.substring(with: NSRange(location: offsets.start, length: offsets.end - offsets.start)) + XCTAssertEqual(extractedFromOffsets, phrase) + } + + @MainActor + func testStoryStoreUpdateAnnotationSupportsCustomRangeAndPersistenceSync() { + let store = StoryStore() + let storyId = UUID() + let story = Story( + id: storyId, + title: "Alice in Wonderland", + author: "Lewis Carroll", + genre: Genre(rawValue: "Classics"), + synopsis: "Classic fable", + content: "Alice was beginning to get very tired of sitting by her sister.", + readTimeMinutes: 2 + ) + store.stories.append(story) + + let initial = Annotation( + storyId: storyId, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: 1, + utf16StartOffset: 0, + utf16EndOffset: 63, + selectedText: "Alice was beginning to get very tired of sitting by her sister.", + color: .terracotta, + isPinnedToJournal: true + ) + store.activeStoryAnnotations = [initial] + + let trimmedPhrase = "very tired of sitting" + store.updateAnnotation( + initial, + story: story, + text: trimmedPhrase, + startOffset: 27, + endOffset: 48, + color: .sage, + note: "Key passage", + pinToJournal: false + ) + + let updated = store.activeStoryAnnotations.first(where: { $0.id == initial.id }) + XCTAssertEqual(updated?.selectedText, trimmedPhrase) + XCTAssertEqual(updated?.utf16StartOffset, 27) + XCTAssertEqual(updated?.utf16EndOffset, 48) + XCTAssertEqual(updated?.color, .sage) + XCTAssertEqual(updated?.note, "Key passage") + XCTAssertFalse(updated?.isPinnedToJournal ?? true) + } + @MainActor func testPacingEngineRejectsSubThreeSecondPageTurnsCapsIdleTimeAndMonotonicallyEstimatesRemainingMinutes() { let engine = PacingEngine() @@ -405,4 +481,135 @@ final class PlanFeaturesRegressionTests: XCTestCase { XCTAssertNotNil(service.fetchStory(id: annotatedStub.id)) XCTAssertEqual(service.fetchAllPinnedAnnotations(ownerUserId: nil).count, 1) } + + @MainActor + func testReaderInBookSearchAndSnippetGeneration() { + let chapter1 = Chapter( + storyId: UUID(), + chapterNumber: 1, + title: "Down the Rabbit-Hole", + content: "Alice was beginning to get very tired of sitting by her sister on the bank.\n\nSuddenly a white rabbit with pink eyes ran close by her.", + wordCount: 26 + ) + let chapter2 = Chapter( + storyId: UUID(), + chapterNumber: 2, + title: "The Pool of Tears", + content: "Curiouser and curiouser cried Alice!\n\nShe looked down at her feet and wondered if she would ever see the white rabbit again.", + wordCount: 22 + ) + + // Case-insensitive search across chapters + let matches = ReaderPassageMatcher.search(query: "white rabbit", in: [chapter1, chapter2]) + XCTAssertEqual(matches.count, 2) + XCTAssertEqual(matches[0].chapterNumber, 1) + XCTAssertEqual(matches[0].chapterIndex, 0) + XCTAssertEqual(matches[0].paragraphIndex, 1) + XCTAssertTrue(matches[0].snippet.lowercased().contains("white rabbit")) + + XCTAssertEqual(matches[1].chapterNumber, 2) + XCTAssertEqual(matches[1].chapterIndex, 1) + XCTAssertEqual(matches[1].paragraphIndex, 1) + + // Snippet generation test + let snippet = ReaderPassageMatcher.generateSnippet(for: "rabbit", in: chapter1.content, contextRadius: 15) + XCTAssertTrue(snippet.contains("rabbit")) + + // Empty and missing queries + XCTAssertTrue(ReaderPassageMatcher.search(query: "", in: [chapter1]).isEmpty) + XCTAssertTrue(ReaderPassageMatcher.search(query: " ", in: [chapter1]).isEmpty) + XCTAssertTrue(ReaderPassageMatcher.search(query: "cheshire cat", in: [chapter1]).isEmpty) + + // Single manuscript fallback search + let fallbackParas = ["It was the best of times, it was the worst of times.", "It was the age of wisdom."] + let fallbackMatches = ReaderPassageMatcher.search(query: "wisdom", in: [], fallbackParagraphs: fallbackParas, fallbackTitle: "Tale") + XCTAssertEqual(fallbackMatches.count, 1) + XCTAssertEqual(fallbackMatches[0].paragraphIndex, 1) + XCTAssertEqual(fallbackMatches[0].chapterTitle, "Tale") + } + + @MainActor + func testReaderExportAnnotationsAsMarkdown() { + let story = Story( + id: UUID(), + title: "Pride and Prejudice", + author: "Jane Austen", + genre: Genre(rawValue: "Romance"), + synopsis: "Classic", + content: "It is a truth universally acknowledged.", + readTimeMinutes: 5 + ) + + let annot1 = Annotation( + storyId: story.id, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: 1, + utf16StartOffset: 0, + utf16EndOffset: 39, + selectedText: "It is a truth universally acknowledged", + note: "Memorable opening line", + color: .terracotta, + isPinnedToJournal: true + ) + let annot2 = Annotation( + storyId: story.id, + storyTitle: story.title, + storyAuthor: story.author, + chapterNumber: 2, + utf16StartOffset: 0, + utf16EndOffset: 20, + selectedText: "Mr. Bennet was so odd a mixture", + note: nil, + color: .sage, + isPinnedToJournal: false + ) + + let md = ReaderPassageMatcher.exportAnnotationsAsMarkdown(story: story, annotations: [annot1, annot2]) + XCTAssertTrue(md.contains("# Highlights & Marginalia: Pride and Prejudice")) + XCTAssertTrue(md.contains("**Author:** Jane Austen")) + XCTAssertTrue(md.contains("## Chapter 1")) + XCTAssertTrue(md.contains("> “It is a truth universally acknowledged”")) + XCTAssertTrue(md.contains("Terracotta")) + XCTAssertTrue(md.contains("*Note: Memorable opening line*")) + XCTAssertTrue(md.contains("## Chapter 2")) + XCTAssertTrue(md.contains("> “Mr. Bennet was so odd a mixture”")) + } + + @MainActor + func testStoryStoreOfflineDownloadAndStatus() async throws { + let store = StoryStore() + let storyId = UUID() + var unCachedStory = Story( + id: storyId, + title: "Offline Test", + author: "Author", + genre: Genre(rawValue: "Classics"), + synopsis: "Test", + content: "", + readTimeMinutes: 1 + ) + unCachedStory.chapters = [] + XCTAssertFalse(store.isStoryDownloaded(unCachedStory)) + + var downloadedStory = Story( + id: UUID(), + title: "Downloaded Test", + author: "Author", + genre: Genre(rawValue: "Classics"), + synopsis: "Test", + content: "Full readable chapter one text.", + readTimeMinutes: 1 + ) + downloadedStory.chapters = [ + Chapter( + storyId: downloadedStory.id, + chapterNumber: 1, + title: "Ch 1", + content: "Full readable chapter one text.", + wordCount: 5 + ) + ] + XCTAssertTrue(store.isStoryDownloaded(downloadedStory)) + } } diff --git a/scripts/start_wireless_server.sh b/scripts/start_wireless_server.sh new file mode 100755 index 0000000..e951966 --- /dev/null +++ b/scripts/start_wireless_server.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +BACKEND_DIR="$REPO_ROOT/backend" +VENV_DIR="$REPO_ROOT/.venv" +HOST="${FABLE_BIND_ADDRESS:-0.0.0.0}" +PORT="${FABLE_PORT:-8001}" +ENV_MODE="${FABLE_ENV:-development}" +DB_PATH="${FABLE_DB_PATH:-$BACKEND_DIR/fable.sqlite3}" +USE_TUNNEL="${FABLE_USE_TUNNEL:-1}" + +for arg in "$@"; do + case "$arg" in + --no-tunnel) USE_TUNNEL=0 ;; + --tunnel) USE_TUNNEL=1 ;; + -h|--help) + cat </dev/null; then + kill "$SLEEP_PID" 2>/dev/null || true + fi + if [[ -n "$TUNNEL_PID" ]] && kill -0 "$TUNNEL_PID" 2>/dev/null; then + kill "$TUNNEL_PID" 2>/dev/null || true + fi + if [[ -n "$UVICORN_PID" ]] && kill -0 "$UVICORN_PID" 2>/dev/null; then + kill "$UVICORN_PID" 2>/dev/null || true + fi + if [[ -n "$TUNNEL_LOG" && -f "$TUNNEL_LOG" ]]; then + rm -f "$TUNNEL_LOG" + fi +} +trap cleanup EXIT INT TERM + +if [[ ! -x "$VENV_DIR/bin/python" ]]; then + echo "[fable] Creating Python virtual environment at $VENV_DIR..." + python3 -m venv "$VENV_DIR" +fi + +if [[ ! -x "$VENV_DIR/bin/uvicorn" ]]; then + echo "[fable] Installing backend dependencies..." + "$VENV_DIR/bin/pip" install --quiet -r "$BACKEND_DIR/requirements.txt" +fi + +detect_lan_ip() { + local ip="" + if command -v ipconfig >/dev/null 2>&1; then + for iface in en0 en1 en2 bridge100; do + ip="$(ipconfig getifaddr "$iface" 2>/dev/null || true)" + if [[ -n "$ip" ]]; then + echo "$ip" + return 0 + fi + done + fi + if command -v ip >/dev/null 2>&1; then + ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src") print $(i+1)}' | head -n1 || true)" + if [[ -n "$ip" ]]; then + echo "$ip" + return 0 + fi + fi + if command -v hostname >/dev/null 2>&1; then + ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" + if [[ -n "$ip" ]]; then + echo "$ip" + return 0 + fi + fi + echo "127.0.0.1" +} + +find_or_install_cloudflared() { + if command -v cloudflared >/dev/null 2>&1; then + command -v cloudflared + return 0 + fi + for candidate in /tmp/cloudflared "$HOME/.local/bin/cloudflared"; do + if [[ -x "$candidate" ]]; then + echo "$candidate" + return 0 + fi + done + + local os arch url target="$HOME/.local/bin/cloudflared" + os="$(uname -s)" + arch="$(uname -m)" + mkdir -p "$HOME/.local/bin" + + if [[ "$os" == "Darwin" ]]; then + if [[ "$arch" == "arm64" ]]; then + url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64.tgz" + else + url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64.tgz" + fi + echo "[fable] Downloading cloudflared for macOS ($arch)..." >&2 + curl -fsSL "$url" | tar -xz -C "$HOME/.local/bin" + chmod +x "$target" + echo "$target" + return 0 + elif [[ "$os" == "Linux" ]]; then + if [[ "$arch" == "aarch64" || "$arch" == "arm64" ]]; then + url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64" + else + url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64" + fi + echo "[fable] Downloading cloudflared for Linux ($arch)..." >&2 + curl -fsSL "$url" -o "$target" + chmod +x "$target" + echo "$target" + return 0 + fi + return 1 +} + +if curl -fsS -m 2 "http://127.0.0.1:$PORT/api/v1/health" >/dev/null 2>&1; then + echo "[fable] Backend already running on port $PORT." +else + echo "[fable] Starting FastAPI backend on $HOST:$PORT (FABLE_ENV=$ENV_MODE)..." + ( + cd "$BACKEND_DIR" + exec env FABLE_ENV="$ENV_MODE" FABLE_DB_PATH="$DB_PATH" \ + "$VENV_DIR/bin/uvicorn" main:app --reload --host "$HOST" --port "$PORT" + ) & + UVICORN_PID=$! + + for _ in $(seq 1 30); do + if curl -fsS -m 2 "http://127.0.0.1:$PORT/api/v1/health" >/dev/null 2>&1; then + break + fi + sleep 0.5 + done + if ! curl -fsS -m 2 "http://127.0.0.1:$PORT/api/v1/health" >/dev/null 2>&1; then + echo "[fable] Error: Backend failed to respond on http://127.0.0.1:$PORT/api/v1/health" >&2 + exit 1 + fi +fi + +LAN_IP="$(detect_lan_ip)" +TUNNEL_URL="" + +if [[ "$USE_TUNNEL" == "1" ]]; then + if CLOUDFLARED_BIN="$(find_or_install_cloudflared 2>/dev/null)"; then + if [[ -n "${CLOUDFLARE_TUNNEL_TOKEN:-}" ]]; then + echo "[fable] Starting configured Cloudflare Named Tunnel..." + "$CLOUDFLARED_BIN" tunnel --no-autoupdate run --token "$CLOUDFLARE_TUNNEL_TOKEN" >/dev/null 2>&1 & + TUNNEL_PID=$! + else + TUNNEL_LOG="$(mktemp)" + "$CLOUDFLARED_BIN" tunnel --no-autoupdate --url "http://127.0.0.1:$PORT" >"$TUNNEL_LOG" 2>&1 & + TUNNEL_PID=$! + for _ in $(seq 1 30); do + TUNNEL_URL="$(grep -Eo 'https://[a-zA-Z0-9.-]+\.trycloudflare\.com' "$TUNNEL_LOG" | head -n1 || true)" + if [[ -n "$TUNNEL_URL" ]]; then + break + fi + sleep 0.5 + done + fi + else + echo "[fable] Note: cloudflared not available; continuing with LAN server only." + fi +fi + +echo "" +echo "==================================================================" +echo " Fable Backend is LIVE for Wireless iPhone Connections" +echo "==================================================================" +echo " Local Health: http://127.0.0.1:$PORT/api/v1/health" +echo " Home Wi-Fi / Hotspot: http://$LAN_IP:$PORT/api/v1" +if [[ -n "$TUNNEL_URL" ]]; then + echo " Public HTTPS Tunnel: $TUNNEL_URL/api/v1" +fi +echo " Render Cloud Fallback: https://fable-api-cbo8.onrender.com/api/v1" +echo "" +echo " On your iPhone: Welcome ('Server: ... Change') or Settings ->" +echo " Backend Server URL -> paste the URL above -> Save." +if [[ "$(uname -s)" == "Linux" ]]; then + echo " Fedora LAN firewall tip: sudo firewall-cmd --add-port=$PORT/tcp" +fi +echo " Press Ctrl+C to stop." +echo "==================================================================" +echo "" + +if [[ -n "$TUNNEL_PID" || -n "$UVICORN_PID" ]]; then + wait +else + echo "[fable] Press Ctrl+C to exit." + while true; do + sleep 60 & + SLEEP_PID=$! + wait "$SLEEP_PID" || break + done +fi