1- import React from 'react'
21import './Selectable.css' ;
32
43function selectable ( List ) {
54 return class SelectableList extends List {
6- buildItem ( item ) {
7- const node = super . buildItem ( item ) ;
8- const { selected = [ ] } = this . state ;
9- let className = 'list-item' ;
10- if ( selected . includes ( item . id ) ) {
11- className = `${ className } list-item-selected` ;
12- }
13- return React . cloneElement ( node , { className } ) ;
5+ getItemClassName ( item ) {
6+ const className = super . getItemClassName ( item ) ;
7+ const {
8+ selected = [ ]
9+ } = this . state ;
10+
11+ return selected . includes ( item . id ) ?
12+ `${ className } list-item-selected` :
13+ className ;
1414 }
15+
1516 onItemClick ( toSelect , e ) {
1617 super . onItemClick ( toSelect , e ) ;
18+
1719 const { data, selection, onSelection } = this . props ;
20+
1821 let { selected = [ ] } = this . state ;
22+
1923 let add = true ;
24+
2025 if ( selection === 'multi' ) {
2126 const last = selected [ selected . length - 1 ] ;
27+
2228 if ( last != null ) {
2329 const lastIdx = data . findIndex ( item => item . id === last ) ;
2430 const currentIdx = data . findIndex ( item => item . id === toSelect . id ) ;
31+
2532 if ( lastIdx === currentIdx ) {
2633 // indices are the same, deselect
2734 selected . splice ( currentIdx - 1 , 1 ) ;
35+
2836 add = false ;
2937 }
38+
3039 if ( e . shiftKey ) {
3140 if ( lastIdx !== - 1 && currentIdx !== - 1 ) {
3241 // get all items between the last selected item
@@ -51,21 +60,25 @@ function selectable (List) {
5160 // single mode, clear out the array
5261 selected . length = 0 ;
5362 }
63+
5464 if ( add ) {
5565 selected . push ( toSelect . id ) ;
5666 }
67+
5768 if ( selected . length > 1 ) {
5869 // remove duplicates
5970 selected = [ ...new Set ( selected ) ] ;
6071 }
72+
6173 this . setState ( {
6274 selected
6375 } ) ;
76+
6477 if ( typeof onSelection === 'function' ) {
6578 onSelection ( selected . map ( id => data . find ( item => item . id === id ) ) ) ;
6679 }
6780 }
6881 }
6982}
70- export default selectable ;
7183
84+ export default selectable ;
0 commit comments