import type { EuiInMemoryTableProps } from '@elastic/eui' ; import { useCallback , useEffect , useMemo , useState } from 'react' ; import { debounce } from 'lodash' ; import type { DashboardSavedObject } from '../../../../../../../src/plugins/dashboard/public' ; import { useDashboardService } from '../../services/dashboard_service' ; import { useMlKibana } from '../../contexts/kibana' ; export interface DashboardItem { id : string ; title : string ; description : string | undefined ; attributes : DashboardSavedObject ; } export type EuiTableProps = EuiInMemoryTableProps < DashboardItem > ; export const useDashboardTable = ( ) => { const { notifications : { toasts } , } = useMlKibana ( ) ; const dashboardService = useDashboardService ( ) ; const [ isLoading , setIsLoading ] = useState ( false ) ; useEffect ( ( ) => { fetchDashboards ( ) ; return ( ) => { fetchDashboards . cancel ( ) ; } ; } , [ ] ) ; const search = useMemo ( ( ) => { return { onChange : ( { queryText } ) => { setIsLoading ( true ) ; fetchDashboards ( queryText ) ; } , box : { incremental : true , 'data-test-subj' : 'mlDashboardsSearchBox' , } , } ; } , [ ] ) ; const [ dashboardItems , setDashboardItems ] = useState < DashboardItem [ ] > ( [ ] ) ; const [ selectedItems , setSelectedItems ] = useState < DashboardItem [ ] > ( [ ] ) ; const fetchDashboards = useCallback ( debounce ( async ( query ? ) => { try { const response = await dashboardService . fetchDashboards ( query ) ; const items = response . savedObjects . map ( ( savedObject ) => { return { id : savedObject . id , title : savedObject . attributes . title , description : savedObject . attributes . description , attributes : savedObject . attributes , } ; } ) ; setDashboardItems ( items ) ; } catch ( e ) { toasts . danger ( { body : e , } ) ; } setIsLoading ( false ) ; } , 500 ) , [ ] ) ; const selection = { onSelectionChange : setSelectedItems , } ; return { dashboardItems , selectedItems , selection , search , isLoading } ; } ;