import type { BaseItem } from '@algolia/autocomplete-core' ; import type { OnStateChangeProps , AutocompletePlugin , } from '@algolia/autocomplete-js' ; type CreateClearLeftPluginProps = { initialQuery ? : string ; } ; type CustomAutocompletePlugin < TItem extends BaseItem , TData > = AutocompletePlugin < TItem , TData > & { unsubscribe ? : ( ) => void ; } ; export function createClearLeftPlugin < TItem extends Record < string , unknown > , TData > ( { initialQuery = '' , } = { } ) { let clearBtnEl ; let submitBtnEl ; let rafId = - 1 ; const toggleBtns = ( queryEmpty ) => { if ( clearBtnEl ) clearBtnEl . style . display = queryEmpty ? 'none' : 'block' ; if ( submitBtnEl ) submitBtnEl . style . display = queryEmpty ? 'block' : 'none' ; } ; return { subscribe ( ) { rafId = window . requestAnimationFrame ( ( ) => { clearBtnEl = document . querySelector ( '.aa-ClearButton' ) ; submitBtnEl = document . querySelector ( '.aa-SubmitButton' ) ; const prefixLabelEl = document . querySelector ( '.aa-InputWrapperPrefix .aa-Label' ) ; if ( clearBtnEl ) { prefixLabelEl ?. prepend ( clearBtnEl ) ; } toggleBtns ( ! initialQuery ) ; } ) ; } , unsubscribe ( ) { window . cancelAnimationFrame ( rafId ) ; } , onStateChange ( { state } ) { toggleBtns ( ! state . query ) ; } , } ; }