Favourites: drag-and-drop reorder per fuel; stored order drives single-widget favourite

This commit is contained in:
FuelBoard Contributor
2026-08-14 10:48:53 +01:00
parent aa95d214e8
commit fbf8c79feb
5 changed files with 139 additions and 43 deletions
+31
View File
@@ -490,6 +490,37 @@ struct FuelStore {
}
}
/// Reorders ONE fuel's favourites within the global array (drag-and-drop in
/// the Favourites tab). The moved fuel's block stays at its original
/// position in the array; other fuels keep their relative order. The array
/// order IS the widget order the first favourite of a fuel is the
/// "single widget" favourite.
static func reorderedFavourites(_ favourites: [FavouriteEntry],
fuel: FuelType,
fromOffsets source: IndexSet,
toOffset destination: Int) -> [FavouriteEntry] {
var fuelEntries = favourites.filter { $0.fuel == fuel }
// Manual reorder (Foundation-only file Array.move(fromOffsets:) is
// a SwiftUI helper). Reproduces the standard drag semantics: remove
// the source items, then insert at the destination, shifted by the
// number of removed items that were before it.
let moving = source.sorted()
let removed = moving.map { fuelEntries[$0] }
for index in moving.reversed() {
fuelEntries.remove(at: index)
}
var insertion = destination
for index in moving where index < destination {
insertion -= 1
}
fuelEntries.insert(contentsOf: removed, at: min(max(insertion, 0), fuelEntries.count))
let movedIDs = Set(fuelEntries.map(\.id))
var others = favourites.filter { !movedIDs.contains($0.id) }
let blockIndex = favourites.firstIndex { $0.fuel == fuel } ?? others.count
others.insert(contentsOf: fuelEntries, at: min(blockIndex, others.count))
return others
}
// MARK: Alerts
static func loadAlertsEnabled() -> Bool {