import { i18n } from '@kbn/i18n' ; import apm from 'elastic-apm-node' ; import type { Logger } from 'src/core/server' ; import type { HeadlessChromiumDriver } from '../browsers' ; import { Layout } from '../layouts' ; import { CONTEXT_GETNUMBEROFITEMS , CONTEXT_READMETADATA } from './constants' ; export const getNumberOfItems = async ( browser , logger , timeout , layout ) : Promise < number > => { const span = apm . startSpan ( 'get_number_of_items' , 'read' ) ; const { renderComplete : renderCompleteSelector , itemsCountAttribute } = layout . selectors ; let itemsCount ; logger . debug ( i18n . translate ( 'xpack.screenshotting.screencapture.logWaitingForElements' , { defaultMessage : 'waiting for elements or items count attribute; or not found to interrupt' , } ) ) ; try { await browser . waitForSelector ( `${ renderCompleteSelector },[${ itemsCountAttribute }]` , { timeout } , { context : CONTEXT_READMETADATA } , logger ) ; itemsCount = await browser . evaluate ( { fn : ( selector , countAttribute ) => { const elementWithCount = document . querySelector ( `[${ countAttribute }]` ) ; if ( elementWithCount && elementWithCount != null ) { const count = elementWithCount . getAttribute ( countAttribute ) ; if ( count && count != null ) { return parseInt ( count , 10 ) ; } } return document . querySelectorAll ( selector ) . length ; } , args : [ renderCompleteSelector , itemsCountAttribute ] , } , { context : CONTEXT_GETNUMBEROFITEMS } , logger ) ; } catch ( error ) { logger . error ( error ) ; throw new Error ( i18n . translate ( 'xpack.screenshotting.screencapture.readVisualizationsError' , { defaultMessage : `An error occurred when trying to read the page for visualization panel info: {error}` , values : { error } , } ) ) ; } span ?. end ( ) ; return itemsCount ; } ;