Skip to content

Open source CapCut alternative.

TypeScript

feat(ios): note labels on the phone

David Le310b42e737c5
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swift
index 6ca09be4..962f8ed4 100644
--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift
+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift
@@ -422,6 +422,8 @@ extension CutCloudClient: CloudSyncServicing {
var body: String
var colorIndex: Int
var folderId: String?
+ // Optional so a site from before labels still decodes.
+ var labelIds: [String]?
var updatedAt: Double
var deletedAt: Double?
var createdAt: Double
@@ -441,6 +443,7 @@ extension CutCloudClient: CloudSyncServicing {
body: dto.body,
colorIndex: dto.colorIndex,
folderId: dto.folderId.flatMap(UUID.init(uuidString:)),
+ labelIds: (dto.labelIds ?? []).compactMap(UUID.init(uuidString:)),
updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
deletedAt: dto.deletedAt.map { Date(timeIntervalSince1970: $0 / 1000) },
createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)
@@ -451,6 +454,7 @@ extension CutCloudClient: CloudSyncServicing {
struct NotesResponse: Decodable {
var notes: [NoteDTO]
var folders: [NoteFolderDTO]?
+ var labels: [NoteFolderDTO]?
}
let data = try await send(try request("GET", "/api/cut-cloud/notes"))
let response = try decode(NotesResponse.self, from: data)
@@ -470,6 +474,16 @@ extension CutCloudClient: CloudSyncServicing {
updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)
)
+ },
+ // Labels ride the same wire shape as folders.
+ labels: response.labels?.compactMap { dto in
+ guard let id = UUID(uuidString: dto.id) else { return nil }
+ return RemoteNoteLabel(
+ id: id,
+ name: dto.name,
+ updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
+ createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)
+ )
}
)
}
@@ -479,6 +493,7 @@ extension CutCloudClient: CloudSyncServicing {
"title": note.title,
"body": note.body,
"colorIndex": note.colorIndex,
+ "labelIds": note.labelIds.map { $0.uuidString.lowercased() },
"updatedAt": Int(note.updatedAt.timeIntervalSince1970 * 1000),
]
body["folderId"] = note.folderId.map { $0.uuidString.lowercased() } ?? NSNull()
@@ -507,6 +522,22 @@ extension CutCloudClient: CloudSyncServicing {
try request("DELETE", "/api/cut-cloud/notes/folders/\(id.uuidString.lowercased())")
)
}
+
+ func putNoteLabel(_ label: RemoteNoteLabel) async throws {
+ _ = try await send(
+ try request(
+ "PUT",
+ "/api/cut-cloud/notes/labels/\(label.id.uuidString.lowercased())",
+ body: ["name": label.name]
+ )
+ )
+ }
+
+ func deleteNoteLabel(id: UUID) async throws {
+ _ = try await send(
+ try request("DELETE", "/api/cut-cloud/notes/labels/\(id.uuidString.lowercased())")
+ )
+ }
}
// MARK: - Projects down-sync
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
index 5ddc5a0d..59a2267f 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
@@ -98,6 +98,7 @@ nonisolated public struct RemoteNote: Equatable, Sendable {
public var body: String
public var colorIndex: Int
public var folderId: UUID?
+ public var labelIds: [UUID]
public var updatedAt: Date
public var deletedAt: Date?
public var createdAt: Date
@@ -108,6 +109,7 @@ nonisolated public struct RemoteNote: Equatable, Sendable {
body: String,
colorIndex: Int,
folderId: UUID? = nil,
+ labelIds: [UUID] = [],
updatedAt: Date,
deletedAt: Date? = nil,
createdAt: Date = .now
@@ -117,6 +119,7 @@ nonisolated public struct RemoteNote: Equatable, Sendable {
self.body = body
self.colorIndex = colorIndex
self.folderId = folderId
+ self.labelIds = labelIds
self.updatedAt = updatedAt
self.deletedAt = deletedAt
self.createdAt = createdAt
@@ -139,20 +142,38 @@ nonisolated public struct RemoteNoteFolder: Equatable, Sendable {
}
}
+/// A note label as the cloud stores it. Like folders, labels carry no
+/// tombstone: a label missing from the listing was deleted.
+nonisolated public struct RemoteNoteLabel: Equatable, Sendable {
+ public var id: UUID
+ public var name: String
+ public var updatedAt: Date
+ public var createdAt: Date
+
+ public init(id: UUID, name: String, updatedAt: Date, createdAt: Date) {
+ self.id = id
+ self.name = name
+ self.updatedAt = updatedAt
+ self.createdAt = createdAt
+ }
+}
+
/// One listing of the account's notes: the notes themselves, tombstones
-/// included, and every folder they file into.
+/// included, every folder they file into, and every label they wear.
///
-/// `folders` is nil when the listing carried no folder key at all — an older
-/// site speaking to a newer phone. A reader treats that as "this response says
-/// nothing about folders", which is different from an empty list meaning the
-/// account has none.
+/// `folders` and `labels` are nil when the listing carried no such key at all
+/// — an older site speaking to a newer phone. A reader treats that as "this
+/// response says nothing about them", which is different from an empty list
+/// meaning the account has none.
nonisolated public struct RemoteNotes: Equatable, Sendable {
public var notes: [RemoteNote]
public var folders: [RemoteNoteFolder]?
+ public var labels: [RemoteNoteLabel]?
- public init(notes: [RemoteNote], folders: [RemoteNoteFolder]?) {
+ public init(notes: [RemoteNote], folders: [RemoteNoteFolder]?, labels: [RemoteNoteLabel]? = nil) {
self.notes = notes
self.folders = folders
+ self.labels = labels
}
}
@@ -294,6 +315,9 @@ public protocol CloudSyncServicing: AnyObject {
/// Create or rename one folder under the id the phone gave it.
func putNoteFolder(_ folder: RemoteNoteFolder) async throws
func deleteNoteFolder(id: UUID) async throws
+ /// Create or rename one label under the id the phone gave it.
+ func putNoteLabel(_ label: RemoteNoteLabel) async throws
+ func deleteNoteLabel(id: UUID) async throws
}
// MARK: - Projects (down-sync)
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
index 3b5c3cd6..a0423de8 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
@@ -15,6 +15,8 @@ final class NoteRecord {
var colorIndex: Int
/// The folder this note is filed in; nil is the top level.
var folderId: UUID?
+ /// The labels this note wears. Older rows carry nil and read as none.
+ var labelIds: [UUID]?
var createdAt: Date
/// Last edit, the sync's last-writer-wins clock. Older rows carry nil and
/// read as their creation time.
@@ -29,6 +31,7 @@ final class NoteRecord {
body = note.body
colorIndex = note.color.rawValue
folderId = note.folderId
+ labelIds = note.labelIds
createdAt = note.createdAt
updatedAt = note.updatedAt
self.dirty = dirty
@@ -41,6 +44,7 @@ final class NoteRecord {
body: body,
color: NoteColor(rawValue: colorIndex) ?? .butter,
folderId: folderId,
+ labelIds: labelIds ?? [],
createdAt: createdAt,
updatedAt: updatedAt ?? createdAt
)
@@ -70,6 +74,29 @@ final class NoteFolderRecord {
}
}
+/// A label notes wear. Labels are few and small like folders, so the whole
+/// set pushes and pulls each pass; `dirty` marks one this phone changed.
+@Model
+final class NoteLabelRecord {
+ @Attribute(.unique) var id: UUID
+ var name: String
+ var createdAt: Date
+ var updatedAt: Date
+ var dirty: Bool
+
+ init(_ label: NoteLabel, dirty: Bool) {
+ id = label.id
+ name = label.name
+ createdAt = label.createdAt
+ updatedAt = label.updatedAt
+ self.dirty = dirty
+ }
+
+ var label: NoteLabel {
+ NoteLabel(id: id, name: name, createdAt: createdAt, updatedAt: updatedAt)
+ }
+}
+
@Model
final class InspirationRecord {
@Attribute(.unique) var id: UUID
@@ -232,6 +259,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
let schema = Schema([
NoteRecord.self,
NoteFolderRecord.self,
+ NoteLabelRecord.self,
InspirationRecord.self,
RecordingRecord.self,
TombstoneRecord.self,
@@ -256,6 +284,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
existing.body = note.body
existing.colorIndex = note.color.rawValue
existing.folderId = note.folderId
+ existing.labelIds = note.labelIds
existing.updatedAt = note.updatedAt
existing.dirty = true
} else {
@@ -302,6 +331,38 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
try context.save()
}
+ public func loadNoteLabels() throws -> [NoteLabel] {
+ let descriptor = FetchDescriptor<NoteLabelRecord>(sortBy: [SortDescriptor(\.createdAt)])
+ return try context.fetch(descriptor).map(\.label)
+ }
+
+ public func upsert(_ label: NoteLabel) throws {
+ let id = label.id
+ let descriptor = FetchDescriptor<NoteLabelRecord>(predicate: #Predicate { $0.id == id })
+ if let existing = try context.fetch(descriptor).first {
+ existing.name = label.name
+ existing.updatedAt = label.updatedAt
+ existing.dirty = true
+ } else {
+ context.insert(NoteLabelRecord(label, dirty: true))
+ }
+ try context.save()
+ }
+
+ public func deleteNoteLabel(id: UUID) throws {
+ try context.delete(model: NoteLabelRecord.self, where: #Predicate { $0.id == id })
+ // Every note wearing the label lets it go, each as a write of its own
+ // so the cloud copies follow.
+ for record in try context.fetch(FetchDescriptor<NoteRecord>())
+ where record.labelIds?.contains(id) == true {
+ record.labelIds = record.labelIds?.filter { $0 != id }
+ record.updatedAt = .now
+ record.dirty = true
+ }
+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.noteLabel.rawValue, remoteId: id.uuidString, stamp: .now))
+ try context.save()
+ }
+
public func loadInspiration() throws -> [InspirationItem] {
let descriptor = FetchDescriptor<InspirationRecord>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])
return try context.fetch(descriptor).compactMap(\.item)
@@ -403,6 +464,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
existing.body = note.body
existing.colorIndex = note.color.rawValue
existing.folderId = note.folderId
+ existing.labelIds = note.labelIds
existing.updatedAt = note.updatedAt
existing.dirty = false
} else {
@@ -466,6 +528,48 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
try context.save()
}
+ public func dirtyNoteLabels() throws -> [NoteLabel] {
+ let descriptor = FetchDescriptor<NoteLabelRecord>(sortBy: [SortDescriptor(\.createdAt)])
+ return try context.fetch(descriptor).filter(\.dirty).map(\.label)
+ }
+
+ public func applyRemoteNoteLabel(_ label: NoteLabel) throws {
+ let id = label.id
+ let descriptor = FetchDescriptor<NoteLabelRecord>(predicate: #Predicate { $0.id == id })
+ if let existing = try context.fetch(descriptor).first {
+ guard !existing.dirty else { return }
+ existing.name = label.name
+ existing.updatedAt = label.updatedAt
+ } else {
+ context.insert(NoteLabelRecord(label, dirty: false))
+ }
+ try context.save()
+ }
+
+ public func clearNoteLabelDirty(id: UUID, ifUpdatedAt stamp: Date) throws {
+ let descriptor = FetchDescriptor<NoteLabelRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first, record.updatedAt == stamp else { return }
+ record.dirty = false
+ try context.save()
+ }
+
+ /// Label ids this phone holds that the cloud no longer lists, so they
+ /// were deleted elsewhere. A label still waiting to be pushed is not one
+ /// of them.
+ public func cleanNoteLabelIds() throws -> [UUID] {
+ let descriptor = FetchDescriptor<NoteLabelRecord>()
+ return try context.fetch(descriptor).filter { !$0.dirty }.map(\.id)
+ }
+
+ public func removeNoteLabelFromCloudDelete(id: UUID) throws {
+ try context.delete(model: NoteLabelRecord.self, where: #Predicate { $0.id == id })
+ for record in try context.fetch(FetchDescriptor<NoteRecord>())
+ where record.dirty != true && record.labelIds?.contains(id) == true {
+ record.labelIds = record.labelIds?.filter { $0 != id }
+ }
+ try context.save()
+ }
+
public func recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?) {
let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })
let record = try context.fetch(descriptor).first
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
index 021fa3b6..c04eb45f 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
@@ -47,6 +47,23 @@ nonisolated public struct NoteFolder: Identifiable, Equatable, Hashable, Sendabl
}
}
+/// A label notes carry. Like folders, ids are minted by whichever client
+/// makes the label, one PUT both creates and renames, and the cloud listing
+/// is the truth — a label missing from it was deleted.
+nonisolated public struct NoteLabel: Identifiable, Equatable, Hashable, Sendable {
+ public var id: UUID
+ public var name: String
+ public var createdAt: Date
+ public var updatedAt: Date
+
+ public init(id: UUID = UUID(), name: String, createdAt: Date = .now, updatedAt: Date = .now) {
+ self.id = id
+ self.name = name
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ }
+}
+
nonisolated public struct Note: Identifiable, Equatable, Sendable {
public var id: UUID
public var title: String
@@ -54,6 +71,9 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {
public var color: NoteColor
/// The folder this note is filed in; nil is the top level.
public var folderId: UUID?
+ /// The labels this note wears. They ride the note's own last-writer-wins
+ /// write; an id naming no label is dropped from view.
+ public var labelIds: [UUID]
public var createdAt: Date
/// Last edit, wherever it happened. The sync's last-writer-wins clock:
/// the newer stamp survives when the phone and the desktop both wrote.
@@ -65,6 +85,7 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {
body: String,
color: NoteColor,
folderId: UUID? = nil,
+ labelIds: [UUID] = [],
createdAt: Date = .now,
updatedAt: Date = .now
) {
@@ -73,6 +94,7 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {
self.body = body
self.color = color
self.folderId = folderId
+ self.labelIds = labelIds
self.createdAt = createdAt
self.updatedAt = updatedAt
}
@@ -248,6 +270,10 @@ public protocol IdeasStoring: AnyObject {
/// Delete a folder. Its notes come back to the top level rather than
/// going with it — the same line the cloud draws.
func deleteNoteFolder(id: UUID) throws
+ func loadNoteLabels() throws -> [NoteLabel]
+ func upsert(_ label: NoteLabel) throws
+ /// Delete a label. Every note wearing it lets it go, as its own write.
+ func deleteNoteLabel(id: UUID) throws
func loadInspiration() throws -> [InspirationItem]
func addLink(_ url: URL) throws -> InspirationItem
func addMedia(data: Data, isVideo: Bool) throws -> InspirationItem
@@ -275,6 +301,7 @@ nonisolated public enum IdeasFilter: String, CaseIterable, Sendable {
public final class IdeasModel {
public private(set) var notes: [Note] = []
public private(set) var folders: [NoteFolder] = []
+ public private(set) var labels: [NoteLabel] = []
public private(set) var inspiration: [InspirationItem] = []
public var filter: IdeasFilter = .all
@@ -300,6 +327,7 @@ public final class IdeasModel {
public func reloadFromStore() {
notes = (try? store.loadNotes()) ?? []
folders = (try? store.loadNoteFolders()) ?? []
+ labels = (try? store.loadNoteLabels()) ?? []
inspiration = (try? store.loadInspiration()) ?? []
}
@@ -354,6 +382,66 @@ public final class IdeasModel {
onLocalChange?()
}
+ // MARK: Labels
+
+ /// The labels a note wears, in the order the account lists them. An id
+ /// naming nothing — a label deleted on another device — drops from view.
+ public func labels(on note: Note) -> [NoteLabel] {
+ labels.filter { note.labelIds.contains($0.id) }
+ }
+
+ @discardableResult
+ public func addLabel(named name: String) -> NoteLabel? {
+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ let label = NoteLabel(name: trimmed)
+ try? store.upsert(label)
+ labels.append(label)
+ onLocalChange?()
+ return label
+ }
+
+ public func renameLabel(id: UUID, to name: String) {
+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty, var label = labels.first(where: { $0.id == id }) else { return }
+ label.name = trimmed
+ label.updatedAt = .now
+ try? store.upsert(label)
+ if let index = labels.firstIndex(where: { $0.id == id }) { labels[index] = label }
+ onLocalChange?()
+ }
+
+ /// Delete a label. Every note wearing it — the open draft too — lets it
+ /// go.
+ public func deleteLabel(id: UUID) {
+ try? store.deleteNoteLabel(id: id)
+ draft?.labelIds.removeAll { $0 == id }
+ reloadFromStore()
+ onLocalChange?()
+ }
+
+ /// Most labels one note may wear. The cloud refuses a write past this, so
+ /// the picker holds the same line — a label taken past it would come back
+ /// off the note on the next merge.
+ public static let maxLabelsPerNote = 20
+
+ /// Whether the open draft has room for another label.
+ public var draftTakesLabels: Bool {
+ (draft?.labelIds.count ?? 0) < Self.maxLabelsPerNote
+ }
+
+ /// Put a label on the open draft, or take it off.
+ public func toggleDraftLabel(_ id: UUID) {
+ guard var draft else { return }
+ if draft.labelIds.contains(id) {
+ draft.labelIds.removeAll { $0 == id }
+ } else {
+ guard draft.labelIds.count < Self.maxLabelsPerNote else { return }
+ draft.labelIds.append(id)
+ }
+ self.draft = draft
+ }
+
nonisolated public struct NoteDraft: Identifiable, Equatable {
public var id: UUID
public var title: String
@@ -362,6 +450,8 @@ public final class IdeasModel {
/// The folder the note is filed in — the one it was opened from for a
/// new note.
public var folderId: UUID?
+ /// The labels the note wears.
+ public var labelIds: [UUID]
public var isNew: Bool
public var hasContent: Bool {
@@ -378,10 +468,19 @@ public final class IdeasModel {
body: note.body,
color: note.color,
folderId: note.folderId,
+ labelIds: note.labelIds,
isNew: false
)
} else {
- draft = NoteDraft(id: UUID(), title: "", body: "", color: .butter, folderId: folderId, isNew: true)
+ draft = NoteDraft(
+ id: UUID(),
+ title: "",
+ body: "",
+ color: .butter,
+ folderId: folderId,
+ labelIds: [],
+ isNew: true
+ )
}
}
@@ -406,6 +505,7 @@ public final class IdeasModel {
body: body,
color: draft.color,
folderId: draft.folderId,
+ labelIds: draft.labelIds,
createdAt: existing?.createdAt ?? .now,
updatedAt: .now
)
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
index 7074ccd1..397d8738 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
@@ -18,6 +18,9 @@ nonisolated public struct SyncTombstone: Equatable, Sendable, Identifiable {
/// A note folder deleted here. The cloud row goes; the notes in it
/// come back to the top level on both sides.
case noteFolder
+ /// A note label deleted here. The cloud row goes, and every note
+ /// wearing it lets it go on both sides.
+ case noteLabel
/// A synced recording or inspiration item deleted here; the cloud
/// asset goes with it.
case libraryAsset
@@ -61,6 +64,13 @@ public protocol SyncJournalStoring: AnyObject {
func cleanNoteFolderIds() throws -> [UUID]
func removeNoteFolderFromCloudDelete(id: UUID) throws
+ // Labels: folders' twin — push-then-pull, no tombstone rows in the cloud.
+ func dirtyNoteLabels() throws -> [NoteLabel]
+ func applyRemoteNoteLabel(_ label: NoteLabel) throws
+ func clearNoteLabelDirty(id: UUID, ifUpdatedAt: Date) throws
+ func cleanNoteLabelIds() throws -> [UUID]
+ func removeNoteLabelFromCloudDelete(id: UUID) throws
+
// Recordings
func recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?)
/// Journal a recording's cloud copy. Returns false when the row is gone —
@@ -299,10 +309,11 @@ public final class SyncEngine {
return mediaAllowed && pendingMedia
}
- /// Folders and notes the phone still owes the cloud.
+ /// Folders, labels and notes the phone still owes the cloud.
private var notesPending: Bool {
!(((try? journal.dirtyNotes()) ?? []).isEmpty)
|| !(((try? journal.dirtyNoteFolders()) ?? []).isEmpty)
+ || !(((try? journal.dirtyNoteLabels()) ?? []).isEmpty)
}
/// Links the cloud has not been handed, or is still fetching.
@@ -337,6 +348,9 @@ public final class SyncEngine {
case .noteFolder:
guard let id = UUID(uuidString: tombstone.remoteId) else { break }
try await service.deleteNoteFolder(id: id)
+ case .noteLabel:
+ guard let id = UUID(uuidString: tombstone.remoteId) else { break }
+ try await service.deleteNoteLabel(id: id)
case .libraryAsset:
try await service.deleteLibraryAsset(id: tombstone.remoteId)
}
@@ -426,6 +440,24 @@ public final class SyncEngine {
// Transient; stays dirty.
}
}
+ // Labels go up before the notes that wear them, for the same reason.
+ for label in (try? journal.dirtyNoteLabels()) ?? [] {
+ do {
+ try await service.putNoteLabel(
+ RemoteNoteLabel(
+ id: label.id,
+ name: label.name,
+ updatedAt: label.updatedAt,
+ createdAt: label.createdAt
+ )
+ )
+ try? journal.clearNoteLabelDirty(id: label.id, ifUpdatedAt: label.updatedAt)
+ } catch CloudSyncError.unauthorized {
+ return
+ } catch {
+ // Transient; stays dirty.
+ }
+ }
// Push local edits first so the pull that follows can't overwrite them.
for note in (try? journal.dirtyNotes()) ?? [] {
do {
@@ -436,6 +468,7 @@ public final class SyncEngine {
body: note.body,
colorIndex: note.color.rawValue,
folderId: note.folderId,
+ labelIds: note.labelIds,
updatedAt: note.updatedAt,
createdAt: note.createdAt
)
@@ -453,6 +486,7 @@ public final class SyncEngine {
do {
let remote = try await service.fetchNotes()
try mergeRemoteFolders(remote.folders)
+ try mergeRemoteLabels(remote.labels)
try mergeRemoteNotes(remote.notes)
ideas?.reloadFromStore()
} catch {
@@ -492,6 +526,35 @@ public final class SyncEngine {
}
}
+ /// Labels merge the way folders do: the listing is the truth, and one
+ /// this phone has clean that the listing does not name was deleted on
+ /// the other side. A nil listing came from a site that does not speak
+ /// labels, and its silence leaves this phone's labels where they are.
+ private func mergeRemoteLabels(_ remote: [RemoteNoteLabel]?) throws {
+ guard let remote else { return }
+ let pendingDeletes = Set(
+ ((try? journal.tombstones()) ?? [])
+ .filter { $0.kind == .noteLabel }
+ .compactMap { UUID(uuidString: $0.remoteId) }
+ )
+ var live: Set<UUID> = []
+ for label in remote {
+ if pendingDeletes.contains(label.id) { continue }
+ live.insert(label.id)
+ try journal.applyRemoteNoteLabel(
+ NoteLabel(
+ id: label.id,
+ name: label.name,
+ createdAt: label.createdAt,
+ updatedAt: label.updatedAt
+ )
+ )
+ }
+ for id in try journal.cleanNoteLabelIds() where !live.contains(id) {
+ try journal.removeNoteLabelFromCloudDelete(id: id)
+ }
+ }
+
private func mergeRemoteNotes(_ remote: [RemoteNote]) throws {
let localById = Dictionary(
uniqueKeysWithValues: (ideas?.notes ?? []).map { ($0.id, $0) }
@@ -524,6 +587,7 @@ public final class SyncEngine {
body: remote.body,
color: NoteColor(rawValue: remote.colorIndex) ?? .butter,
folderId: remote.folderId,
+ labelIds: remote.labelIds,
createdAt: remote.createdAt,
updatedAt: remote.updatedAt
)
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
index af0f1bfd..db91d935 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
@@ -695,7 +695,7 @@ struct NotePickerSheet: View {
Button {
onPick(note)
} label: {
- NoteCard(note: note)
+ NoteCard(note: note, labels: ideas.labels(on: note))
}
.buttonStyle(.plain)
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift
index df9ef8de..6aae8266 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift
@@ -354,7 +354,7 @@ struct NotesGrid: View {
Button {
ideas.openEditor(for: note)
} label: {
- NoteCard(note: note)
+ NoteCard(note: note, labels: ideas.labels(on: note))
}
.buttonStyle(.plain)
.contextMenu {
@@ -499,6 +499,7 @@ private struct FolderPromptModifier: ViewModifier {
struct NoteCard: View {
let note: Note
+ var labels: [NoteLabel] = []
var body: some View {
VStack(alignment: .leading, spacing: 6) {
@@ -511,6 +512,9 @@ struct NoteCard: View {
.opacity(0.75)
.lineLimit(8)
Spacer(minLength: 0)
+ if !labels.isEmpty {
+ NoteLabelChips(names: labels.map(\.name))
+ }
}
.foregroundStyle(Color.notePaperInk)
.padding(14)
@@ -536,6 +540,104 @@ struct FoldCorner: Shape {
}
}
+/// The labels a note wears, as small chips wrapping onto as many lines as
+/// they need. Drawn in the note paper's ink, on the card and in the editor.
+struct NoteLabelChips: View {
+ let names: [String]
+
+ var body: some View {
+ ChipWrap(spacing: 5) {
+ ForEach(names, id: \.self) { name in
+ Text(name)
+ .font(.caption2.weight(.medium))
+ .lineLimit(1)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Color.black.opacity(0.1), in: Capsule())
+ }
+ }
+ // Stay clear of the card's folded corner.
+ .padding(.trailing, 18)
+ }
+}
+
+/// Lays subviews left to right, wrapping to a new line when the width runs
+/// out.
+///
+/// The height depends on the width, and a container is free to ask for a size
+/// without naming one — a card measured inside a scrolling grid does exactly
+/// that. Answering such an ask with a single line would report a height the
+/// placement then overflows, and the extra rows would be clipped by the card,
+/// so the width the layout was last placed at is remembered and answers for
+/// the one that was not given. The same cache holds the frames themselves,
+/// which the measure and the placement would otherwise each compute.
+struct ChipWrap: Layout {
+ var spacing: CGFloat = 5
+
+ struct Cache {
+ /// The last width `frames` was computed for, and its result.
+ var width: CGFloat?
+ var frames: [CGRect] = []
+ var bounds: CGSize = .zero
+ /// The width the layout was actually placed at, for an ask that names none.
+ var placed: CGFloat?
+ }
+
+ func makeCache(subviews: Subviews) -> Cache { Cache() }
+
+ func updateCache(_ cache: inout Cache, subviews: Subviews) {
+ cache.width = nil
+ }
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) -> CGSize {
+ layout(subviews, in: proposal.width ?? cache.placed ?? .infinity, cache: &cache).bounds
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) {
+ cache.placed = bounds.width
+ for (frame, subview) in zip(layout(subviews, in: bounds.width, cache: &cache).frames, subviews) {
+ subview.place(
+ at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY),
+ proposal: ProposedViewSize(frame.size)
+ )
+ }
+ }
+
+ private func layout(
+ _ subviews: Subviews,
+ in width: CGFloat,
+ cache: inout Cache
+ ) -> (frames: [CGRect], bounds: CGSize) {
+ if cache.width == width { return (cache.frames, cache.bounds) }
+ let laid = frames(for: subviews, in: width)
+ cache.width = width
+ cache.frames = laid.frames
+ cache.bounds = laid.bounds
+ return laid
+ }
+
+ private func frames(for subviews: Subviews, in width: CGFloat) -> (frames: [CGRect], bounds: CGSize) {
+ var frames: [CGRect] = []
+ var x: CGFloat = 0
+ var y: CGFloat = 0
+ var rowHeight: CGFloat = 0
+ var widest: CGFloat = 0
+ for subview in subviews {
+ let size = subview.sizeThatFits(.unspecified)
+ if x > 0, x + size.width > width {
+ x = 0
+ y += rowHeight + spacing
+ rowHeight = 0
+ }
+ frames.append(CGRect(origin: CGPoint(x: x, y: y), size: size))
+ rowHeight = max(rowHeight, size.height)
+ x += size.width + spacing
+ widest = max(widest, x - spacing)
+ }
+ return (frames, CGSize(width: widest, height: y + rowHeight))
+ }
+}
+
struct InspirationCard: View {
let item: InspirationItem
var ideas: IdeasModel
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift
index 338a0d1a..a43cecff 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift
@@ -10,6 +10,7 @@ struct NoteEditorView: View {
private enum Field { case title, body }
@FocusState private var focused: Field?
+ @State private var showingLabels = false
var body: some View {
let color = ideas.draft?.color ?? .butter
@@ -85,7 +86,36 @@ struct NoteEditorView: View {
}
}
- HStack {
+ // The labels the note wears. A tap on a chip takes it off; the
+ // tag button opens the picker that adds, makes, renames and
+ // deletes them.
+ if let draft = ideas.draft, !draft.labelIds.isEmpty {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(ideas.labels.filter { draft.labelIds.contains($0.id) }) { label in
+ Button {
+ ideas.toggleDraftLabel(label.id)
+ } label: {
+ HStack(spacing: 4) {
+ Text(label.name)
+ Image(systemName: "xmark")
+ .font(.system(size: 9, weight: .bold))
+ .opacity(0.5)
+ }
+ .font(.caption.weight(.medium))
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .background(Color.black.opacity(0.1), in: Capsule())
+ }
+ .accessibilityLabel("Remove label \(label.name)")
+ }
+ }
+ .padding(.horizontal, 20)
+ }
+ .padding(.top, 8)
+ }
+
+ HStack(spacing: 18) {
Button {
ideas.cycleDraftColor()
} label: {
@@ -95,11 +125,22 @@ struct NoteEditorView: View {
.frame(width: 32, height: 32)
}
.accessibilityLabel("Note color")
+ Button {
+ showingLabels = true
+ } label: {
+ Image(systemName: "tag")
+ .font(.title3.weight(.semibold))
+ }
+ .accessibilityLabel("Labels")
Spacer()
}
.padding(.horizontal, 20)
.padding(.vertical, 14)
}
+ .sheet(isPresented: $showingLabels) {
+ NoteLabelSheet(ideas: ideas)
+ .presentationDetents([.medium, .large])
+ }
.foregroundStyle(Color.notePaperInk)
.tint(Color.notePaperInk)
.background(color.backgroundColor, ignoresSafeAreaEdges: .all)
@@ -130,4 +171,89 @@ struct NoteEditorView: View {
)
}
}
+
+/// The label picker: every label on the account, the open note's checked. A
+/// tap puts one on the note or takes it off; the field at the top makes a new
+/// one and puts it on; a swipe renames or deletes one everywhere.
+private struct NoteLabelSheet: View {
+ @Bindable var ideas: IdeasModel
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var newName = ""
+ @State private var renaming: NoteLabel?
+ @State private var renameText = ""
+
+ var body: some View {
+ NavigationStack {
+ List {
+ Section {
+ TextField("New label", text: $newName)
+ .submitLabel(.done)
+ .onSubmit(create)
+ }
+ if !ideas.labels.isEmpty {
+ Section {
+ ForEach(ideas.labels) { label in
+ let worn = ideas.draft?.labelIds.contains(label.id) == true
+ Button {
+ ideas.toggleDraftLabel(label.id)
+ } label: {
+ HStack {
+ Text(label.name)
+ .foregroundStyle(.primary)
+ Spacer()
+ if worn {
+ Image(systemName: "checkmark")
+ .font(.body.weight(.semibold))
+ }
+ }
+ }
+ .disabled(!worn && !ideas.draftTakesLabels)
+ .swipeActions {
+ Button("Delete", systemImage: "trash", role: .destructive) {
+ ideas.deleteLabel(id: label.id)
+ }
+ Button("Rename", systemImage: "pencil") {
+ renameText = label.name
+ renaming = label
+ }
+ }
+ }
+ } footer: {
+ Text(
+ ideas.draftTakesLabels
+ ? "Deleting a label takes it off every note."
+ : "A note holds \(IdeasModel.maxLabelsPerNote) labels. Take one off to add another."
+ )
+ }
+ }
+ }
+ .navigationTitle("Labels")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Done") { dismiss() }
+ }
+ }
+ .alert("Rename Label", isPresented: renamingShown, presenting: renaming) { label in
+ TextField("Name", text: $renameText)
+ Button("Save") { ideas.renameLabel(id: label.id, to: renameText) }
+ Button("Cancel", role: .cancel) {}
+ }
+ }
+ }
+
+ private var renamingShown: Binding<Bool> {
+ Binding(
+ get: { renaming != nil },
+ set: { if !$0 { renaming = nil } }
+ )
+ }
+
+ private func create() {
+ guard ideas.draftTakesLabels, let label = ideas.addLabel(named: newName) else { return }
+ ideas.toggleDraftLabel(label.id)
+ newName = ""
+ }
+}
#endif
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index a695a75c..a4e8461e 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -219,9 +219,13 @@ import Testing
var downloads: [String] = []
var folders: [UUID: RemoteNoteFolder] = [:]
var deletedFolders: [UUID] = []
+ var labels: [UUID: RemoteNoteLabel] = [:]
+ var deletedLabels: [UUID] = []
/// Whether the listing carries a folders key at all. A site that
/// predates folders answers without one.
var reportsFolders = true
+ /// The same, for labels.
+ var reportsLabels = true
/// What an import job answers with once it is asked about.
var imported: LinkImport = .ready(
ImportedLink(
@@ -288,7 +292,8 @@ import Testing
func fetchNotes() async throws -> RemoteNotes {
RemoteNotes(
notes: Array(notes.values),
- folders: reportsFolders ? Array(folders.values) : nil
+ folders: reportsFolders ? Array(folders.values) : nil,
+ labels: reportsLabels ? Array(labels.values) : nil
)
}
@@ -315,6 +320,19 @@ import Testing
_ = noteId
}
}
+
+ func putNoteLabel(_ label: RemoteNoteLabel) async throws {
+ labels[label.id] = label
+ }
+
+ func deleteNoteLabel(id: UUID) async throws {
+ deletedLabels.append(id)
+ labels[id] = nil
+ for (noteId, note) in notes where note.labelIds.contains(id) {
+ notes[noteId]?.labelIds.removeAll { $0 == id }
+ _ = note
+ }
+ }
}
struct Rig {
@@ -659,6 +677,61 @@ import Testing
#expect(try rig.store.tombstones().isEmpty)
}
+ @Test func labelPushesAheadOfTheNoteWearingIt() async throws {
+ let rig = try makeRig()
+ let label = try #require(rig.ideas.addLabel(named: "Hooks"))
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "wearing it"
+ rig.ideas.toggleDraftLabel(label.id)
+ let note = try #require(rig.ideas.saveDraft())
+ await rig.engine.run()
+ #expect(rig.cloud.labels[label.id]?.name == "Hooks")
+ #expect(rig.cloud.notes[note.id]?.labelIds == [label.id])
+ }
+
+ @Test func labelDeletedInTheCloudComesOffItsNotes() async throws {
+ let rig = try makeRig()
+ let label = try #require(rig.ideas.addLabel(named: "Hooks"))
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "wearing it"
+ rig.ideas.toggleDraftLabel(label.id)
+ let note = try #require(rig.ideas.saveDraft())
+ await rig.engine.run()
+ // Gone from the desktop: the listing no longer names it, which is the
+ // only signal a label delete has.
+ rig.cloud.labels[label.id] = nil
+ await rig.engine.run()
+ #expect(rig.ideas.labels.isEmpty)
+ let held = try #require(rig.ideas.notes.first { $0.id == note.id })
+ #expect(rig.ideas.labels(on: held).isEmpty)
+ }
+
+ @Test func aListingWithoutLabelsKeepsTheOnesHere() async throws {
+ let rig = try makeRig()
+ let label = try #require(rig.ideas.addLabel(named: "Hooks"))
+ await rig.engine.run()
+ // A site that does not speak labels answers without the key; its
+ // silence leaves this phone's labels alone.
+ rig.cloud.reportsLabels = false
+ await rig.engine.run()
+ #expect(rig.ideas.labels.map(\.id) == [label.id])
+ }
+
+ @Test func labelDeletedHereReachesTheCloudAndItsNotes() async throws {
+ let rig = try makeRig()
+ let label = try #require(rig.ideas.addLabel(named: "Hooks"))
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "wearing it"
+ rig.ideas.toggleDraftLabel(label.id)
+ let note = try #require(rig.ideas.saveDraft())
+ await rig.engine.run()
+ rig.ideas.deleteLabel(id: label.id)
+ await rig.engine.run()
+ #expect(rig.cloud.deletedLabels == [label.id])
+ #expect(rig.cloud.notes[note.id]?.labelIds == [])
+ #expect(try rig.store.tombstones().isEmpty)
+ }
+
@Test func cellularCarriesNotesAndHoldsVideos() async throws {
// The default: notes are small enough to spend cellular data on, a
// clip is not. The clip says so on its card and moves on Wi-Fi.
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.md
index 3a942dd4..d16805d2 100644
--- a/docs/guides/ios-app.md
+++ b/docs/guides/ios-app.md
@@ -54,7 +54,12 @@ with tombstones so a delete made offline on either side still lands on the
other. The folders notes file into travel with them, under ids whichever
device made them chose; a folder carries no tombstone, so a folder the cloud
listing no longer names was deleted elsewhere and its notes come back to the
-top level.
+top level. Labels follow the same rule as folders: a note's labels ride its
+own write, and a label the listing no longer names comes off every note that
+wore it. A note wears twenty labels at most, and both pickers stop offering
+more at that count — the write past it is refused rather than trimmed, so a
+note never comes back from a merge wearing fewer labels than the person put
+on it.
Deletes on the shelf run both ways. A synced recording deleted on the phone
takes the cloud copy with it, and a clip deleted at the desk — from the Camera