File size: 5,536 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import languages, { LanguageSlug } from '@automattic/languages';
import {
	UseQueryResult,
	UseQueryOptions,
	useInfiniteQuery,
	InfiniteData,
	QueryKey,
	QueryFunction,
	useQuery,
} from '@tanstack/react-query';
import { decodeEntities } from 'calypso/lib/formatting';
import {
	extractSearchInformation,
	getPreinstalledPremiumPluginsVariations,
	mapStarRatingToPercent,
} from 'calypso/lib/plugins/utils';
import { useSelector } from 'calypso/state';
import { getCurrentUserLocale } from 'calypso/state/current-user/selectors';
import { DEFAULT_PAGE_SIZE } from './constants';
import { search, searchBySlug } from './search-api';
import { getPluginsListKey } from './utils';
import type { ESHits, ESResponse, Plugin, PluginQueryOptions } from './types';

const getIconUrl = ( pluginSlug: string, icon: string ): string => {
	try {
		const url = new URL( icon || '' );
		return url.toString();
	} catch ( _ ) {}

	return buildDefaultIconUrl( pluginSlug );
};

function buildDefaultIconUrl( pluginSlug: string ) {
	return `https://s.w.org/plugins/geopattern-icon/${ pluginSlug }.svg`;
}

const mapIndexResultsToPluginData = ( results: ESHits ): Plugin[] => {
	if ( ! results ) {
		return [];
	}
	return results.map( ( { fields: hit, railcar } ) => {
		const plugin: Plugin = {
			name: decodeEntities( hit.plugin?.title ), // TODO: add localization
			slug: decodeEntities( hit.slug ),
			software_slug: hit.plugin?.software_slug,
			org_slug: hit.plugin?.org_slug,
			version: hit[ 'plugin.stable_tag' ],
			author: hit.author,
			author_name: hit.plugin?.author,
			author_profile: '', // TODO: get author profile URL
			tested: hit[ 'plugin.tested' ],
			rating: mapStarRatingToPercent( hit.plugin?.rating ),
			num_ratings: hit.plugin?.num_ratings,
			support_threads: hit[ 'plugin.support_threads' ],
			support_threads_resolved: hit[ 'plugin.support_threads_resolved' ],
			active_installs: hit.plugin?.active_installs,
			last_updated: hit.modified,
			short_description: decodeEntities( hit.plugin?.excerpt ), // TODO: add localization
			icon: getIconUrl( hit.slug, hit.plugin?.icons ),
			premium_slug: decodeEntities( hit.plugin?.premium_slug ),
			variations: {
				monthly: { product_id: hit.plugin?.store_product_monthly_id },
				yearly: { product_id: hit.plugin?.store_product_yearly_id },
			},
			railcar,
		};
		plugin.variations = getPreinstalledPremiumPluginsVariations( plugin );

		return plugin;
	} );
};

const getWpLocaleBySlug = ( slug: LanguageSlug ) => {
	const defaultLanguage = 'en';

	// the wpLocale for `en` would be `en_US`, but the server uses `en` too
	if ( defaultLanguage === slug ) {
		return slug;
	}

	return languages.find( ( l ) => l.langSlug === slug )?.wpLocale || defaultLanguage;
};

export const getESPluginQueryParams = (
	slug: string,
	locale: string,
	fields?: Array< string >
): {
	queryKey: QueryKey;
	queryFn: QueryFunction< { plugins: Plugin[]; pagination: { page: number } }, QueryKey >;
} => {
	const queryKey = [ 'es-plugin', slug ];
	const queryFn = () =>
		searchBySlug( slug, locale, { fields } )
			.then( ( { data }: { data: { results: ESHits } } ) =>
				mapIndexResultsToPluginData( data.results )
			)
			.then( ( plugins: Plugin[] ) => plugins?.[ 0 ] || null );
	return { queryKey, queryFn };
};

const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24;
export const useESPlugin = (
	slug: string,
	fields?: Array< string >,
	{
		enabled = true,
		staleTime = ONE_DAY_IN_MS,
		refetchOnMount = true,
	}: Omit< UseQueryOptions< any >, 'queryKey' > = {}
): UseQueryResult => {
	const locale = useSelector( getCurrentUserLocale );

	return useQuery( {
		...getESPluginQueryParams( slug, locale, fields ),
		enabled,
		staleTime,
		refetchOnMount,
	} );
};

type PageParam = string | number;

export const getESPluginsInfiniteQueryParams = (
	options: PluginQueryOptions,
	locale: string
): {
	queryKey: QueryKey;
	queryFn: QueryFunction< ESResponse, QueryKey, PageParam >;
	initialPageParam: PageParam;
} => {
	const [ searchTerm, author ] = extractSearchInformation( options.searchTerm );
	const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
	const queryKey = getPluginsListKey( [ 'DEBUG-new-site-seach' ], options, true );
	const groupId = options.category !== 'popular' ? 'marketplace' : 'wporg';
	const queryFn: QueryFunction< ESResponse, QueryKey, PageParam > = ( { pageParam } ) =>
		search( {
			query: searchTerm,
			author,
			groupId,
			category: options.category,
			pageHandle: pageParam + '',
			pageSize,
			locale: getWpLocaleBySlug( ( options.locale || locale ) as LanguageSlug ),
			slugs: options.slugs,
		} );
	return { queryKey, queryFn, initialPageParam: 1 };
};

export const useESPluginsInfinite = (
	options: PluginQueryOptions,
	{
		enabled = true,
		staleTime = 10000,
		refetchOnMount = true,
	}: Omit< UseQueryOptions< any >, 'queryKey' > = {}
) => {
	const locale = useSelector( getCurrentUserLocale );

	const { queryKey, queryFn, initialPageParam } = getESPluginsInfiniteQueryParams(
		options,
		locale
	);

	return useInfiniteQuery( {
		queryKey,
		queryFn,
		select: ( data: InfiniteData< ESResponse > ) => {
			return {
				...data,
				plugins: mapIndexResultsToPluginData( data.pages.flatMap( ( p ) => p.data.results ) ),
				pagination: {
					results: data.pages[ 0 ]?.data?.total,
					pages: data?.pages || [],
					page: data?.pageParams?.length || 0,
				},
			};
		},
		initialPageParam,
		getNextPageParam: ( lastPage ) => {
			return lastPage?.data?.page_handle || undefined;
		},
		enabled,
		staleTime,
		refetchOnMount,
	} );
};