Skip to content

Open source CapCut alternative.

TypeScript

feat(ios): the projects listing is kept on disk

David Lef43adb4824fa
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
index b42904dd..f0c24c58 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
@@ -1,6 +1,6 @@
import Foundation
-nonisolated public enum ProjectExport: Equatable, Sendable {
+nonisolated public enum ProjectExport: Equatable, Codable, Sendable {
case none
/// Something is there to play. `isPreview` marks the composited proxy the
/// editor renders for its own grid: it plays, but it is not the render an
@@ -11,7 +11,7 @@ nonisolated public enum ProjectExport: Equatable, Sendable {
/// A cloud project as the phone shows it: name, duration, a cached thumbnail
/// file, and which render a tap streams. Only thumbnails sync down — the
/// video stays in the cloud and streams on demand.
-nonisolated public struct Project: Identifiable, Equatable, Sendable {
+nonisolated public struct Project: Identifiable, Equatable, Codable, Sendable {
public var id: String
public var name: String
public var duration: TimeInterval
@@ -61,9 +61,58 @@ nonisolated public struct ProjectExportSize: Identifiable, Equatable, Sendable {
]
}
+/// The last listing this device saw, on disk. The Projects tab is a mirror of
+/// the cloud, so it opens on what it had and corrects itself in the
+/// background — nobody waits on the network to look at their own projects.
+///
+/// Application Support rather than Caches: a purged listing would put the
+/// spinner back on launch, which is the thing this exists to remove.
+struct ProjectListingCache {
+ private let file: URL?
+
+ init(directory: URL? = nil) {
+ let root = directory ?? (try? FileManager.default.url(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true
+ ))
+ file = root?.appending(path: "ProjectListing.json")
+ }
+
+ /// A listing whose shape this build no longer reads is simply not there;
+ /// the refresh writes a fresh one.
+ func read() -> [Project] {
+ guard let file, let data = try? Data(contentsOf: file),
+ let projects = try? JSONDecoder().decode([Project].self, from: data)
+ else { return [] }
+ // Posters live in Caches, which the system may empty out from under a
+ // listing that survived. A card whose poster is gone paints without
+ // one and gets it back on the next refresh.
+ return projects.map { project in
+ var project = project
+ if let thumbnail = project.thumbnail,
+ !FileManager.default.fileExists(atPath: thumbnail.localPath) {
+ project.thumbnail = nil
+ }
+ return project
+ }
+ }
+
+ func write(_ projects: [Project]) {
+ guard let file, let data = try? JSONEncoder().encode(projects) else { return }
+ try? data.write(to: file, options: .atomic)
+ }
+
+ func clear() {
+ guard let file else { return }
+ try? FileManager.default.removeItem(at: file)
+ }
+}
+
@Observable
public final class ProjectsModel {
- public private(set) var projects: [Project] = []
+ public private(set) var projects: [Project]
public private(set) var isLoading = false
/// Renders in flight, by project id. A run outlives the screen that asked
/// for it, so closing the player and coming back finds it where it was.
@@ -74,9 +123,24 @@ public final class ProjectsModel {
private var thumbnails: [String: URL] = [:]
private var exportTasks: [String: Task<Void, Never>] = [:]
private let service: (any CloudProjectsServicing)?
+ private let cache: ProjectListingCache
- public init(service: (any CloudProjectsServicing)? = nil) {
+ /// `cacheDirectory` is for tests; the app takes Application Support.
+ public init(service: (any CloudProjectsServicing)? = nil, cacheDirectory: URL? = nil) {
self.service = service
+ cache = ProjectListingCache(directory: cacheDirectory)
+ projects = cache.read()
+ }
+
+ /// Drop what this device knows about the account's projects. Sign-out
+ /// calls it, so the next account never opens on someone else's listing.
+ public func forget() {
+ for id in exportRuns.keys { clearExport(id) }
+ projects = []
+ summaries = [:]
+ latestExports = [:]
+ thumbnails = [:]
+ cache.clear()
}
// MARK: Exporting
@@ -184,6 +248,9 @@ public final class ProjectsModel {
async let exports: Void = fillExports(remote, service: service)
async let posters: Void = fillThumbnails(remote, service: service)
_ = await (exports, posters)
+ // The whole pass landed — names, exports and posters — so this is the
+ // listing the next launch opens on.
+ cache.write(projects)
}
/// Take a listing as the current set of projects, dropping what is gone
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
index 17d46f38..08d22862 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
@@ -10,7 +10,6 @@ struct ProjectsScreen: View {
var auth: AuthModel
@State private var playing: Project?
- @Environment(\.scenePhase) private var scenePhase
private let columns = [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)]
@@ -41,18 +40,15 @@ struct ProjectsScreen: View {
}
.refreshable { await projects.refresh() }
}
- // Projects are edited at the desk, so the listing is read again every
- // time this screen comes back into view — opening the tab, coming back
- // to the app, closing a project.
+ // The listing paints from disk and is read again on the way in, so a
+ // project edited at the desk a moment ago corrects itself while its
+ // card is already on screen. Coming back to the app is the shell's to
+ // refresh, whichever tab is showing.
.task { await projects.refresh() }
.onChange(of: app.selectedTab) { _, tab in
guard tab == .projects else { return }
Task { await projects.refresh() }
}
- .onChange(of: scenePhase) { _, phase in
- guard phase == .active, app.selectedTab == .projects else { return }
- Task { await projects.refresh() }
- }
.fullScreenCover(item: $playing, onDismiss: { Task { await projects.refresh() } }) { project in
ProjectPlayerView(project: project, projects: projects)
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
index 8e10ce5b..1d4d0309 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
@@ -78,6 +78,13 @@ public struct RootView<CameraPreview: View>: View {
guard scenePhase == .active else { return }
await media.sync?.beat()
}
+ // Projects are edited at the desk, so the tab opens on the listing
+ // this device already had and the cloud is read behind it — every
+ // time the app comes forward, whichever tab is on screen.
+ .task(id: scenePhase) {
+ guard scenePhase == .active, auth.isSignedIn else { return }
+ await projects.refresh()
+ }
.onChange(of: scenePhase) { _, phase in
if phase == .active, auth.isSignedIn {
media.sync?.kick()
@@ -86,6 +93,8 @@ public struct RootView<CameraPreview: View>: View {
.onChange(of: auth.isSignedIn) { _, signedIn in
guard signedIn else {
app.showsAnalytics = false
+ // The listing on disk belongs to the account that just left.
+ projects.forget()
return
}
media.sync?.kick()
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index cd9a735e..5287e655 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -656,6 +656,68 @@ import Testing
}
}
+@MainActor
+@Suite struct ProjectsListingTests {
+ final class FakeProjects: CloudProjectsServicing {
+ let remote: [RemoteProject]
+
+ init(remote: [RemoteProject] = []) { self.remote = remote }
+
+ func fetchProjects() async throws -> [RemoteProject] { remote }
+ func fetchExports(projectId: String) async throws -> [RemoteExport] { [] }
+ func startExport(projectId: String, preset: String) async throws -> String { "job" }
+ func exportProgress(jobId: String) async throws -> RenderProgress { .done }
+ func exportFile(jobId: String) async throws -> URL { URL(string: "https://example.com/e.mp4")! }
+ func streamURL(project: RemoteProject, export: RemoteExport?) async throws -> URL {
+ URL(string: "https://example.com/s.mp4")!
+ }
+ func thumbnailFile(for project: RemoteProject) async -> URL? { nil }
+ }
+
+ private func scratch() -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appending(path: "projects-\(UUID().uuidString)")
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ @Test func listingIsThereBeforeTheNetworkIs() async {
+ let directory = scratch()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let service = FakeProjects(remote: [
+ RemoteProject(
+ id: "p1",
+ name: "Marketing is the new moat",
+ duration: 26,
+ updatedAt: Date(timeIntervalSince1970: 1_700_000_000),
+ hasPreview: true
+ )
+ ])
+ let first = ProjectsModel(service: service, cacheDirectory: directory)
+ await first.refresh()
+ #expect(first.projects.count == 1)
+
+ // A fresh launch: the listing is on screen with nothing asked of the
+ // network yet.
+ let next = ProjectsModel(service: service, cacheDirectory: directory)
+ #expect(next.projects.map(\.id) == ["p1"])
+ #expect(next.projects.first?.name == "Marketing is the new moat")
+ }
+
+ @Test func signingOutLeavesNothingForTheNextAccount() async {
+ let directory = scratch()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let service = FakeProjects(remote: [
+ RemoteProject(id: "p1", name: "Mine", duration: 4, updatedAt: Date(), hasPreview: false)
+ ])
+ let model = ProjectsModel(service: service, cacheDirectory: directory)
+ await model.refresh()
+ model.forget()
+ #expect(model.projects.isEmpty)
+ #expect(ProjectsModel(service: service, cacheDirectory: directory).projects.isEmpty)
+ }
+}
+
@MainActor
@Suite struct AuthModelTests {
final class FakeAuth: AuthServicing {
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.md
index 83a474f2..370b0148 100644
--- a/docs/guides/ios-app.md
+++ b/docs/guides/ios-app.md
@@ -57,7 +57,11 @@ clears once space frees up.
Projects sync down as thumbnails only: the Projects tab lists cloud projects
with cached poster images, and a tap streams the latest export — or the
-composited preview when none exists — straight from the CDN.
+composited preview when none exists — straight from the CDN. The listing is
+kept on disk, so the tab opens on what this device already knew and reads the
+cloud behind it, every time the app comes forward and whichever tab is
+showing. Signing out drops it, so the next account never opens on someone
+else's projects.
The phone exports the whole cut. A control under the player's own sound
button, on screen exactly when that button is, opens a sheet of the sizes the