diff --git a/packages/docsearch-react/src/DocSearch.tsx b/packages/docsearch-react/src/DocSearch.tsx index c769c65..9106b55 100644 --- a/packages/docsearch-react/src/DocSearch.tsx +++ b/packages/docsearch-react/src/DocSearch.tsx @@ -43,6 +43,7 @@ export interface DocSearchProps { navigator?: AutocompleteOptions['navigator']; translations?: DocSearchTranslations; getMissingResultsUrl?: ({ query }: { query: string }) => string; + matomoSearchAnalytics?: boolean; } export function DocSearch(props: DocSearchProps) { diff --git a/packages/docsearch-react/src/DocSearchModal.tsx b/packages/docsearch-react/src/DocSearchModal.tsx index 56f7bb9..dbfc710 100644 --- a/packages/docsearch-react/src/DocSearchModal.tsx +++ b/packages/docsearch-react/src/DocSearchModal.tsx @@ -2,6 +2,8 @@ import type { AutocompleteState } from '@algolia/autocomplete-core'; import { createAutocomplete } from '@algolia/autocomplete-core'; import React from 'react'; +import { createMatomoPlugin } from './MatomoPlugin'; + import { MAX_QUERY_SIZE } from './constants'; import type { DocSearchProps } from './DocSearch'; import type { FooterTranslations } from './Footer'; @@ -50,6 +52,7 @@ export function DocSearchModal({ initialQuery: initialQueryFromProp = '', translations = {}, getMissingResultsUrl, + matomoSearchAnalytics = false, }: DocSearchModalProps) { const { footer: footerTranslations, @@ -125,6 +128,13 @@ export function DocSearchModal({ [favoriteSearches, recentSearches, disableUserPersonalization] ); + var plugins_to_load: any = []; + + if (matomoSearchAnalytics) { + const matomoPlugin = createMatomoPlugin(); + plugins_to_load.push(matomoPlugin); + }; + const autocomplete = React.useMemo( () => createAutocomplete< @@ -282,6 +292,7 @@ export function DocSearchModal({ ); }); }, + plugins: plugins_to_load, }), [ typesenseCollectionName, diff --git a/packages/docsearch-react/src/MatomoPlugin.tsx b/packages/docsearch-react/src/MatomoPlugin.tsx new file mode 100644 index 0000000..350cd54 --- /dev/null +++ b/packages/docsearch-react/src/MatomoPlugin.tsx @@ -0,0 +1,27 @@ +import debounce from 'lodash/debounce'; + +declare global { + interface Window { + _paq: any; + } +} + +var query_cache = ""; + +function _matomoSiteSearch(query: string, hits: string) { + query_cache = query; + var _paq = window._paq = window._paq || []; + _paq.push(['trackSiteSearch', query, false, hits]); +} + +var matomoSiteSearch_debounced = debounce(_matomoSiteSearch, 500); + +export function createMatomoPlugin() { + return { + onStateChange({ state }) { + if ( state.isOpen && state.query.length > 2 && query_cache !== state.query ) { + matomoSiteSearch_debounced(state.query, state.context.nbHits); + } + }, + }; +}; \ No newline at end of file