@@ -186,8 +186,16 @@ function BaseSelectionList<TItem extends ListItem>(
186186 const incrementPage = ( ) => setCurrentPage ( ( prev ) => prev + 1 ) ;
187187
188188 const isItemSelected = useCallback (
189- ( item : TItem ) => item . isSelected ?? ( ( isSelected ?.( item ) ?? selectedItems . includes ( item . keyForList ?? '' ) ) && canSelectMultiple ) ,
190- [ isSelected , selectedItems , canSelectMultiple ] ,
189+ ( item : TItem ) => {
190+ if ( item . isSelected !== undefined ) {
191+ return item . isSelected ;
192+ }
193+ if ( isSelected ) {
194+ return isSelected ( item ) ;
195+ }
196+ return selectedItems . includes ( item . keyForList ?? '' ) ;
197+ } ,
198+ [ isSelected , selectedItems ] ,
191199 ) ;
192200
193201 /**
@@ -217,12 +225,20 @@ function BaseSelectionList<TItem extends ListItem>(
217225 offset += sectionHeaderHeight ;
218226
219227 section . data ?. forEach ( ( item , optionIndex ) => {
220- // Add item to the general flattened array
221- allOptions . push ( {
222- ...item ,
223- sectionIndex,
224- index : optionIndex ,
225- } ) ;
228+ // Add item to the general flattened array. Selected items should be in front of the array.
229+ if ( isItemSelected ( item ) && ! canSelectMultiple ) {
230+ allOptions . unshift ( {
231+ ...item ,
232+ sectionIndex,
233+ index : 0 ,
234+ } ) ;
235+ } else {
236+ allOptions . push ( {
237+ ...item ,
238+ sectionIndex,
239+ index : optionIndex ,
240+ } ) ;
241+ }
226242
227243 // If disabled, add to the disabled indexes array
228244 const isItemDisabled = ! ! section . isDisabled || ( item . isDisabled && ! isItemSelected ( item ) ) ;
@@ -276,12 +292,34 @@ function BaseSelectionList<TItem extends ListItem>(
276292 let remainingOptionsLimit = CONST . MAX_SELECTION_LIST_PAGE_LENGTH * currentPage ;
277293 const processedSections = getSectionsWithIndexOffset (
278294 sections . map ( ( section ) => {
279- const data = ! isEmpty ( section . data ) && remainingOptionsLimit > 0 ? section . data . slice ( 0 , remainingOptionsLimit ) : [ ] ;
280- remainingOptionsLimit -= data . length ;
295+ if ( isEmpty ( section . data ) || remainingOptionsLimit <= 0 ) {
296+ return {
297+ ...section ,
298+ data : [ ] ,
299+ } ;
300+ }
301+
302+ let sectionData = section . data ;
303+ if ( ! canSelectMultiple ) {
304+ const sectionSelectedItems : TItem [ ] = [ ] ;
305+ const sectionUnselectedItems : TItem [ ] = [ ] ;
306+ section . data . forEach ( ( item ) => {
307+ if ( isItemSelected ( item ) ) {
308+ sectionSelectedItems . push ( item ) ;
309+ } else {
310+ sectionUnselectedItems . push ( item ) ;
311+ }
312+ } ) ;
313+
314+ sectionData = [ ...sectionSelectedItems , ...sectionUnselectedItems ] ;
315+ }
316+
317+ const slicedData = sectionData . slice ( 0 , remainingOptionsLimit ) ;
318+ remainingOptionsLimit -= slicedData . length ;
281319
282320 return {
283321 ...section ,
284- data,
322+ data : slicedData ,
285323 } ;
286324 } ) ,
287325 ) ;
0 commit comments