@@ -192,6 +192,33 @@ const HeaderTools = ({
192192} ;
193193
194194// https://github.com/algolia/autocomplete.js#global-options
195+ const hitDataByUrl = { } ;
196+ let lastAlgoliaQueryID = null ;
197+
198+ // DocSearch v2 discards queryID from Algolia responses, so intercept XHR to capture it
199+ if ( typeof XMLHttpRequest !== 'undefined' ) {
200+ const origOpen = XMLHttpRequest . prototype . open ;
201+ XMLHttpRequest . prototype . open = function ( method , url ) {
202+ this . _algoliaUrl = typeof url === 'string' && url . includes ( '.algolia.' ) ? url : null ;
203+ return origOpen . apply ( this , arguments ) ;
204+ } ;
205+ const origSend = XMLHttpRequest . prototype . send ;
206+ XMLHttpRequest . prototype . send = function ( body ) {
207+ if ( this . _algoliaUrl ) {
208+ this . addEventListener ( 'load' , function ( ) {
209+ try {
210+ const data = JSON . parse ( this . responseText ) ;
211+ const result = data . results ? data . results [ 0 ] : data ;
212+ if ( result && result . queryID ) {
213+ lastAlgoliaQueryID = result . queryID ;
214+ }
215+ } catch ( e ) { }
216+ } ) ;
217+ }
218+ return origSend . apply ( this , arguments ) ;
219+ } ;
220+ }
221+
195222export function attachDocSearch ( algolia , inputSelector , timeout ) {
196223 if ( window . docsearch ) {
197224 return window . docsearch ( {
@@ -200,6 +227,40 @@ export function attachDocSearch(algolia, inputSelector, timeout) {
200227 hint : false ,
201228 appendTo : `.ws-global-search .pf-v6-c-text-input-group`
202229 } ,
230+ algoliaOptions : {
231+ clickAnalytics : true
232+ } ,
233+ transformData : function ( hits ) {
234+ Object . keys ( hitDataByUrl ) . forEach ( k => delete hitDataByUrl [ k ] ) ;
235+ hits . forEach ( ( hit , index ) => {
236+ if ( hit . url && hit . objectID ) {
237+ hitDataByUrl [ hit . url ] = {
238+ objectID : hit . objectID ,
239+ position : index + 1
240+ } ;
241+ }
242+ } ) ;
243+ return hits ;
244+ } ,
245+ handleSelected : function ( input , event , suggestion , datasetNumber , context ) {
246+ const hitData = hitDataByUrl [ suggestion . url ] ;
247+ if ( ! window . __algoliaInsightsDisabled && window . aa && hitData && lastAlgoliaQueryID ) {
248+ window . aa ( 'clickedObjectIDsAfterSearch' , {
249+ eventName : 'Search Result Clicked' ,
250+ index : algolia . indexName ,
251+ queryID : lastAlgoliaQueryID ,
252+ objectIDs : [ hitData . objectID ] ,
253+ positions : [ hitData . position ]
254+ } ) ;
255+ }
256+ if ( event && ( event . metaKey || event . ctrlKey ) ) {
257+ window . open ( suggestion . url , '_blank' ) ;
258+ } else if ( event && event . shiftKey ) {
259+ window . open ( suggestion . url ) ;
260+ } else {
261+ window . location . href = suggestion . url ;
262+ }
263+ } ,
203264 debug : process . env . NODE_ENV !== 'production' ,
204265 ...algolia
205266 } ) ;
0 commit comments