Skip to content

Commit

Permalink
[iOS] Fix new menu item reordering
Browse files Browse the repository at this point in the history
This introduces a similar `move(fromOffsets:toOffset:)` method to `BrowserMenuModel` that will be used when re-ordering visible items from SwiftUI hierarchies.
  • Loading branch information
kylehickinson committed Jan 6, 2025
1 parent b375744 commit 5f69123
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
20 changes: 19 additions & 1 deletion ios/brave-ios/Sources/BrowserMenu/BrowserMenuModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,26 @@ import SwiftUI
reloadActions()
}

/// Moves a visible action found at a given index to a given offset based on the way that
/// SwiftUI supplies source indexes + destination offsets.
///
/// The destination offset not an index and instead a distance from the startIndex where an item
/// will be placed, which means the final offset is actually the endIndex (array count/"past the
/// end" index)
func moveVisibleActions(fromOffsets source: IndexSet, toOffset destination: Int) {
// For now we're just going to support moving a single item and drop any extras
guard let index = source.first, let action = visibleActions[safe: index] else { return }
reorderVisibleAction(
action,
to: destination >= visibleActions.endIndex ? visibleActions.endIndex - 1 : destination
)
}

/// Moves a visible action to a valid index
func reorderVisibleAction(_ action: Action, to index: Int) {
if visibleActions.isEmpty || !visibleActions.contains(where: { action.id == $0.id }) {
if visibleActions.isEmpty || !visibleActions.contains(where: { action.id == $0.id })
|| index >= visibleActions.endIndex
{
return
}
var newRank: Double = 0
Expand Down
15 changes: 2 additions & 13 deletions ios/brave-ios/Sources/BrowserMenu/CustomizeMenuView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,8 @@ struct CustomizeMenuView: View {
}
}
}
.onMove { indexSet, offset in
guard let index = indexSet.first, let action = model.visibleActions[safe: index] else {
return
}
// SwiftUI's move offset logic is a bit strange where the destination can be the
// count instead of the final valid index, so its safer to use SwiftUI's Collection
// API to handle it then get the valid destination index of that mutated array.
var ids = model.visibleActions.map(\.id)
ids.move(fromOffsets: indexSet, toOffset: offset)
guard let destination = ids.firstIndex(of: action.id) else {
return
}
model.reorderVisibleAction(action, to: destination)
.onMove { source, destination in
model.moveVisibleActions(fromOffsets: source, toOffset: destination)
}
.listRowBackground(Color(.secondaryBraveGroupedBackground))
} header: {
Expand Down

0 comments on commit 5f69123

Please sign in to comment.