[5.x] Fix moving custom section to 1st position in CP Nav #12993
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request attempts to fix an issue where moving a custom section to the 1st position would cause it to be moved to the last position instead.
Note
I don't really know how the nav builder works, so I asked Claude to write me a failing test and come up with a solution. Feel free to tweak as necessary.
Fixes #12419
Root Cause
The issue was in the
NavTransformer::calculateMinimumItemsForReorder()method. When the new navigation list contained custom sections (items not in the original list), the algorithm that calculated which items to include in the reorder array didn't account for custom items inserted in the middle of the list.The original algorithm used
zip()to pair items from the reversed original and new lists, but when the lists had different lengths (due to custom sections), the pairing was incorrect, leading to the wrong minimum count being calculated.The Fix
I made two key changes:
calculateMinimumItemsForReorder()method (src/CP/Navigation/NavTransformer.php):• Added logic to detect custom items (items not in the original list)
• Check if custom items have any original items after them (to distinguish between custom items in the middle vs. at the end)
• For custom items in the middle, include enough items in the reorder array to establish their position
• Custom items at the end are automatically appended and don't need to be in the reorder array
minify()method (src/CP/Navigation/NavTransformer.php):• Changed from
$reorder ? ... to! empty($reorder) ? ...for better clarity• This ensures that empty arrays are correctly treated as falsy