Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
39 lines
1.4 KiB
Swift
Executable File
39 lines
1.4 KiB
Swift
Executable File
// Occurrence-keyed list identity.
|
|
//
|
|
// Some CrossSound lists legitimately contain the same item twice: a playlist
|
|
// with a repeated track, a history with repeat plays, a queue with a track
|
|
// added twice. Neither naive identity works for those:
|
|
//
|
|
// - `ForEach(items)` (Identifiable by track id) hits DUPLICATE ids, which
|
|
// SwiftUI resolves by dropping/merging rows — the list visibly loses or
|
|
// doubles entries.
|
|
// - `ForEach(items.enumerated(), id: \.offset)` keys identity to the
|
|
// POSITION, so replacing the array's contents (the playlist back-fill:
|
|
// ~5 hydrated stubs → the full list) reuses each row view for a
|
|
// DIFFERENT track. Rows animate as content swaps rather than as moves,
|
|
// and any per-row @State belongs to the previous occupant.
|
|
//
|
|
// Keying on "item id + which occurrence of it this is" gives every row a
|
|
// stable identity that FOLLOWS it across inserts, moves and back-fills while
|
|
// keeping duplicates distinct.
|
|
|
|
import Foundation
|
|
|
|
public struct KeyedItem<Value>: Identifiable {
|
|
public let id: String
|
|
public let index: Int
|
|
public let value: Value
|
|
}
|
|
|
|
public func occurrenceKeyed<Value>(
|
|
_ items: [Value], id: (Value) -> String
|
|
) -> [KeyedItem<Value>] {
|
|
var seen: [String: Int] = [:]
|
|
return items.enumerated().map { index, value in
|
|
let key = id(value)
|
|
let n = seen[key, default: 0]
|
|
seen[key] = n + 1
|
|
return KeyedItem(id: "\(key)#\(n)", index: index, value: value)
|
|
}
|
|
}
|