-
Notifications
You must be signed in to change notification settings - Fork 326
/
createAlgoliaInsightsPlugin.ts
306 lines (273 loc) · 8.65 KB
/
createAlgoliaInsightsPlugin.ts
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import {
AutocompleteState,
AutocompletePlugin,
createRef,
debounce,
isEqual,
noop,
safelyRunOnBrowser,
} from '@algolia/autocomplete-shared';
import {
AutocompleteContext,
AutocompleteReshapeSource,
} from '@algolia/autocomplete-shared/dist/esm/core';
import { createClickedEvent } from './createClickedEvent';
import { createSearchInsightsApi } from './createSearchInsightsApi';
import { createViewedEvents } from './createViewedEvents';
import { isAlgoliaInsightsHit } from './isAlgoliaInsightsHit';
import {
AlgoliaInsightsHit,
AutocompleteInsightsApi,
InsightsClient,
OnActiveParams,
OnItemsChangeParams,
OnSelectParams,
} from './types';
const VIEW_EVENT_DELAY = 400;
const ALGOLIA_INSIGHTS_VERSION = '2.6.0';
const ALGOLIA_INSIGHTS_SRC = `https://cdn.jsdelivr.net/npm/search-insights@${ALGOLIA_INSIGHTS_VERSION}/dist/search-insights.min.js`;
type SendViewedObjectIDsParams = {
onItemsChange(params: OnItemsChangeParams): void;
items: AlgoliaInsightsHit[];
insights: AutocompleteInsightsApi;
state: AutocompleteState<any>;
};
const sendViewedObjectIDs = debounce<SendViewedObjectIDsParams>(
({ onItemsChange, items, insights, state }) => {
onItemsChange({
insights,
insightsEvents: createViewedEvents({ items }).map((event) => ({
eventName: 'Items Viewed',
...event,
})),
state,
});
},
VIEW_EVENT_DELAY
);
export type CreateAlgoliaInsightsPluginParams = {
/**
* The initialized Search Insights client.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-insightsclient
*/
insightsClient?: InsightsClient;
/**
* Hook to send an Insights event when the items change.
*
* By default, it sends a `viewedObjectIDs` event.
*
* In as-you-type experiences, items change as the user types. This hook is debounced every 400ms to reflect actual items that users notice and avoid generating too many events for items matching "in progress" queries.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onitemschange
*/
onItemsChange?(params: OnItemsChangeParams): void;
/**
* Hook to send an Insights event when an item is selected.
*
* By default, it sends a clickedObjectIDsAfterSearch event.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onselect
*/
onSelect?(params: OnSelectParams): void;
/**
* Hook to send an Insights event when an item is active.
*
* By default, it doesn't send any events.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onactive
*/
onActive?(params: OnActiveParams): void;
/**
* @internal
*/
__autocomplete_clickAnalytics?: boolean;
};
export function createAlgoliaInsightsPlugin(
options: CreateAlgoliaInsightsPluginParams
): AutocompletePlugin<any, undefined> {
const {
insightsClient: providedInsightsClient,
onItemsChange,
onSelect: onSelectEvent,
onActive: onActiveEvent,
__autocomplete_clickAnalytics,
} = getOptions(options);
let insightsClient = providedInsightsClient as InsightsClient;
if (!providedInsightsClient) {
safelyRunOnBrowser(({ window }) => {
const pointer = window.AlgoliaAnalyticsObject || 'aa';
if (typeof pointer === 'string') {
insightsClient = window[pointer];
}
if (!insightsClient) {
window.AlgoliaAnalyticsObject = pointer;
if (!window[pointer]) {
window[pointer] = (...args: any[]) => {
if (!window[pointer].queue) {
window[pointer].queue = [];
}
window[pointer].queue.push(args);
};
}
window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
insightsClient = window[pointer];
loadInsights(window);
}
});
}
// We return an empty plugin if `insightsClient` is still undefined at
// this stage, which can happen in server environments.
if (!insightsClient) {
return {};
}
const insights = createSearchInsightsApi(insightsClient);
const previousItems = createRef<AlgoliaInsightsHit[]>([]);
const debouncedOnStateChange = debounce<{
state: AutocompleteState<any>;
}>(({ state }) => {
if (!state.isOpen) {
return;
}
const items = state.collections
.reduce<unknown[]>((acc, current) => {
return [...acc, ...current.items];
}, [])
.filter(isAlgoliaInsightsHit);
if (
!isEqual(
previousItems.current.map((x) => x.objectID),
items.map((x) => x.objectID)
)
) {
previousItems.current = items;
if (items.length > 0) {
sendViewedObjectIDs({ onItemsChange, items, insights, state });
}
}
}, 0);
return {
name: 'aa.algoliaInsightsPlugin',
subscribe({ setContext, onSelect, onActive }) {
function setInsightsContext(userToken?: string) {
setContext({
algoliaInsightsPlugin: {
__algoliaSearchParameters: {
...(__autocomplete_clickAnalytics
? { clickAnalytics: true }
: {}),
...(userToken ? { userToken } : {}),
},
insights,
},
});
}
insightsClient('addAlgoliaAgent', 'insights-plugin');
setInsightsContext();
insightsClient('onUserTokenChange', setInsightsContext);
insightsClient('getUserToken', null, (_error, userToken) => {
setInsightsContext(userToken);
});
onSelect(({ item, state, event, source }) => {
if (!isAlgoliaInsightsHit(item)) {
return;
}
onSelectEvent({
state: state as AutocompleteState<any>,
event,
insights,
item,
insightsEvents: [
{
eventName: 'Item Selected',
...createClickedEvent({
item,
items: (source as AutocompleteReshapeSource<any>)
.getItems()
.filter(isAlgoliaInsightsHit),
}),
},
],
});
});
onActive(({ item, source, state, event }) => {
if (!isAlgoliaInsightsHit(item)) {
return;
}
onActiveEvent({
state: state as AutocompleteState<any>,
event,
insights,
item,
insightsEvents: [
{
eventName: 'Item Active',
...createClickedEvent({
item,
items: (source as AutocompleteReshapeSource<any>)
.getItems()
.filter(isAlgoliaInsightsHit),
}),
},
],
});
});
},
onStateChange({ state }) {
debouncedOnStateChange({ state: state as AutocompleteState<any> });
},
__autocomplete_pluginOptions: options,
};
}
function getAlgoliaSources(
algoliaSourceBase: string[] = [],
context: AutocompleteContext
) {
return [
...algoliaSourceBase,
'autocomplete-internal',
...((context.algoliaInsightsPlugin as Record<string, unknown>)
?.__automaticInsights
? ['autocomplete-automatic']
: []),
];
}
function getOptions(options: CreateAlgoliaInsightsPluginParams) {
return {
onItemsChange({ insights, insightsEvents, state }: OnItemsChangeParams) {
insights.viewedObjectIDs(
...insightsEvents.map((event) => ({
...event,
algoliaSource: getAlgoliaSources(event.algoliaSource, state.context),
}))
);
},
onSelect({ insights, insightsEvents, state }: OnSelectParams) {
insights.clickedObjectIDsAfterSearch(
...insightsEvents.map((event) => ({
...event,
algoliaSource: getAlgoliaSources(event.algoliaSource, state.context),
}))
);
},
onActive: noop,
__autocomplete_clickAnalytics: true,
...options,
};
}
function loadInsights(environment: typeof window) {
const errorMessage = `[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete`;
try {
const script = environment.document.createElement('script');
script.async = true;
script.src = ALGOLIA_INSIGHTS_SRC;
script.onerror = () => {
// eslint-disable-next-line no-console
console.error(errorMessage);
};
document.body.appendChild(script);
} catch (cause) {
// eslint-disable-next-line no-console
console.error(errorMessage);
}
}