|
|
import { generateAdminSections } from '@automattic/data-stores'; |
|
|
import { useHelpCenterContext } from '../contexts/HelpCenterContext'; |
|
|
import { useCustomizerUrls } from './use-customizer-url'; |
|
|
import { useSiteEditorUrls } from './use-site-editor-urls'; |
|
|
import { useSiteSlug } from './use-site-slug'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function filterListBySearchTerm( |
|
|
searchTerm = '', |
|
|
collection: ReturnType< typeof generateAdminSections > = [], |
|
|
limit = 4, |
|
|
locale = 'en' |
|
|
) { |
|
|
|
|
|
if ( ! searchTerm.length ) { |
|
|
return []; |
|
|
} |
|
|
|
|
|
const searchTermWords = searchTerm |
|
|
|
|
|
.split( /[\W_]+/g ) |
|
|
|
|
|
.filter( Boolean ) |
|
|
|
|
|
.map( ( word ) => word.toLowerCase() ); |
|
|
if ( ! searchTermWords.length ) { |
|
|
return []; |
|
|
} |
|
|
|
|
|
const searchRegex = new RegExp( |
|
|
|
|
|
|
|
|
|
|
|
searchTermWords |
|
|
.map( ( word, i ) => |
|
|
|
|
|
|
|
|
i + 1 === searchTermWords.length ? `(?=.*\\b${ word })` : `(?=.*\\b${ word }\\b)` |
|
|
) |
|
|
.join( '' ) + '.+', |
|
|
'gi' |
|
|
); |
|
|
|
|
|
const exactMatches: typeof collection = []; |
|
|
const partialMatches: typeof collection = []; |
|
|
const synonymMatches: typeof collection = []; |
|
|
|
|
|
collection.forEach( ( item ) => { |
|
|
if ( item.title.toLowerCase() === searchTerm.toLowerCase() ) { |
|
|
exactMatches.push( item ); |
|
|
} else if ( searchRegex.test( item.title ) ) { |
|
|
partialMatches.push( item ); |
|
|
} else if ( 'en' === locale && item.synonyms?.some( ( s ) => searchTermWords.includes( s ) ) ) { |
|
|
synonymMatches.push( item ); |
|
|
} |
|
|
} ); |
|
|
|
|
|
return [ ...exactMatches, ...partialMatches, ...synonymMatches ].slice( 0, limit ); |
|
|
} |
|
|
|
|
|
export function useAdminResults( searchTerm: string ) { |
|
|
const { site } = useHelpCenterContext(); |
|
|
const siteSlug = useSiteSlug(); |
|
|
const customizerUrls = useCustomizerUrls(); |
|
|
const siteEditorUrls = useSiteEditorUrls(); |
|
|
const { googleMailServiceFamily, locale, onboardingUrl, sectionName } = useHelpCenterContext(); |
|
|
|
|
|
if ( [ 'wp-admin', 'gutenberg-editor' ].includes( sectionName ) ) { |
|
|
return []; |
|
|
} |
|
|
|
|
|
if ( siteSlug ) { |
|
|
const sections = generateAdminSections( |
|
|
siteSlug, |
|
|
customizerUrls, |
|
|
siteEditorUrls, |
|
|
googleMailServiceFamily, |
|
|
onboardingUrl, |
|
|
site?.jetpack |
|
|
); |
|
|
const filteredSections = filterListBySearchTerm( searchTerm, sections, 4, locale ); |
|
|
|
|
|
return filteredSections; |
|
|
} |
|
|
|
|
|
return []; |
|
|
} |
|
|
|