1
1
// Copyright (C) 2017-2024 Smart code 203358507
2
2
3
- import React from 'react' ;
3
+ import React , { useRef , useEffect , useCallback } from 'react' ;
4
4
import Button from 'stremio/common/Button' ;
5
5
import { useTranslation } from 'react-i18next' ;
6
6
import classNames from 'classnames' ;
@@ -19,33 +19,57 @@ type Props = {
19
19
20
20
const Dropdown = ( { level, setLevel, options, onSelect, selectedOption, menuOpen } : Props ) => {
21
21
const { t } = useTranslation ( ) ;
22
+ const optionsRef = useRef ( new Map ( ) ) ;
23
+ const containerRef = useRef ( null ) ;
22
24
23
- const onBackButtonClick = ( ) => {
25
+ const handleSetOptionRef = useCallback ( ( value : number ) => ( node : HTMLButtonElement | null ) => {
26
+ if ( node ) {
27
+ optionsRef . current . set ( value , node ) ;
28
+ } else {
29
+ optionsRef . current . delete ( value ) ;
30
+ }
31
+ } , [ ] ) ;
32
+
33
+ const handleBackClick = useCallback ( ( ) => {
24
34
setLevel ( level - 1 ) ;
25
- } ;
35
+ } , [ setLevel , level ] ) ;
26
36
27
- return (
28
- < div className = { classNames ( styles [ 'dropdown' ] , { [ styles [ 'open' ] ] : menuOpen } ) } role = { 'listbox' } >
29
- {
30
- level > 0 ?
31
- < Button className = { styles [ 'back-button' ] } onClick = { onBackButtonClick } >
32
- < Icon name = { 'caret-left' } className = { styles [ 'back-button-icon' ] } />
33
- { t ( 'BACK' ) }
34
- </ Button >
35
- : null
37
+ useEffect ( ( ) => {
38
+ if ( menuOpen && selectedOption && containerRef . current ) {
39
+ const selectedNode = optionsRef . current . get ( selectedOption . value ) ;
40
+ if ( selectedNode ) {
41
+ selectedNode . scrollIntoView ( {
42
+ behavior : 'smooth' ,
43
+ block : 'nearest'
44
+ } ) ;
36
45
}
37
- {
38
- options
39
- . filter ( ( option : MultiselectMenuOption ) => ! option . hidden )
40
- . map ( ( option : MultiselectMenuOption , index ) => (
41
- < Option
42
- key = { index }
43
- option = { option }
44
- onSelect = { onSelect }
45
- selectedOption = { selectedOption }
46
- />
47
- ) )
46
+ }
47
+ } , [ menuOpen , selectedOption ] ) ;
48
48
49
+ return (
50
+ < div
51
+ className = { classNames ( styles [ 'dropdown' ] , { [ styles [ 'open' ] ] : menuOpen } ) }
52
+ role = { 'listbox' }
53
+ ref = { containerRef }
54
+ >
55
+ { level > 0 ?
56
+ < Button className = { styles [ 'back-button' ] } onClick = { handleBackClick } >
57
+ < Icon name = { 'caret-left' } className = { styles [ 'back-button-icon' ] } />
58
+ { t ( 'BACK' ) }
59
+ </ Button >
60
+ : null
61
+ }
62
+ { options
63
+ . filter ( ( option : MultiselectMenuOption ) => ! option . hidden )
64
+ . map ( ( option : MultiselectMenuOption ) => (
65
+ < Option
66
+ key = { option . id }
67
+ ref = { handleSetOptionRef ( option . value ) }
68
+ option = { option }
69
+ onSelect = { onSelect }
70
+ selectedOption = { selectedOption }
71
+ />
72
+ ) )
49
73
}
50
74
</ div >
51
75
) ;
0 commit comments