@athoscommerce/snap-store-mobx 1.7.0 → 1.7.1-beta.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/cjs/Autocomplete/Stores/AutocompleteFacetStore.js +2 -1
  2. package/dist/cjs/Chat/ChatStore.d.ts +107 -0
  3. package/dist/cjs/Chat/ChatStore.d.ts.map +1 -0
  4. package/dist/cjs/Chat/ChatStore.js +680 -0
  5. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  6. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  7. package/dist/cjs/Chat/Stores/ChatAttachmentStore.js +316 -0
  8. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts +16 -0
  9. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  10. package/dist/cjs/Chat/Stores/ChatCompareStore.js +64 -0
  11. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +104 -0
  12. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  13. package/dist/cjs/Chat/Stores/ChatSessionStore.js +637 -0
  14. package/dist/cjs/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  15. package/dist/cjs/Search/Stores/SearchFacetStore.js +13 -10
  16. package/dist/cjs/Search/Stores/index.d.ts +1 -1
  17. package/dist/cjs/Search/Stores/index.d.ts.map +1 -1
  18. package/dist/cjs/Search/Stores/index.js +2 -1
  19. package/dist/cjs/index.d.ts +4 -0
  20. package/dist/cjs/index.d.ts.map +1 -1
  21. package/dist/cjs/index.js +5 -1
  22. package/dist/cjs/types.d.ts +24 -2
  23. package/dist/cjs/types.d.ts.map +1 -1
  24. package/dist/esm/Autocomplete/Stores/AutocompleteFacetStore.js +1 -1
  25. package/dist/esm/Chat/ChatStore.d.ts +107 -0
  26. package/dist/esm/Chat/ChatStore.d.ts.map +1 -0
  27. package/dist/esm/Chat/ChatStore.js +605 -0
  28. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  29. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  30. package/dist/esm/Chat/Stores/ChatAttachmentStore.js +224 -0
  31. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts +16 -0
  32. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  33. package/dist/esm/Chat/Stores/ChatCompareStore.js +50 -0
  34. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +104 -0
  35. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  36. package/dist/esm/Chat/Stores/ChatSessionStore.js +602 -0
  37. package/dist/esm/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  38. package/dist/esm/Search/Stores/SearchFacetStore.js +13 -10
  39. package/dist/esm/Search/Stores/index.d.ts +1 -1
  40. package/dist/esm/Search/Stores/index.d.ts.map +1 -1
  41. package/dist/esm/Search/Stores/index.js +1 -1
  42. package/dist/esm/index.d.ts +4 -0
  43. package/dist/esm/index.d.ts.map +1 -1
  44. package/dist/esm/index.js +2 -0
  45. package/dist/esm/types.d.ts +24 -2
  46. package/dist/esm/types.d.ts.map +1 -1
  47. package/package.json +5 -5
@@ -0,0 +1,602 @@
1
+ import { makeObservable, observable, computed } from 'mobx';
2
+ import { v4 as uuidv4 } from 'uuid';
3
+ import { ChatAttachmentStore, } from '../Stores/ChatAttachmentStore';
4
+ import { ChatCompareStore } from './ChatCompareStore';
5
+ import { SearchResultStore, Product } from '../../Search/Stores/SearchResultStore';
6
+ function createChatResultStore(results, meta) {
7
+ return new SearchResultStore({
8
+ config: {},
9
+ state: { loaded: true },
10
+ data: {
11
+ search: { results },
12
+ meta,
13
+ },
14
+ });
15
+ }
16
+ function createChatProduct(result, meta) {
17
+ return new Product({
18
+ config: {},
19
+ data: { result, meta },
20
+ position: 0,
21
+ responseId: '',
22
+ });
23
+ }
24
+ /** Extract raw serializable data from a Product instance for storage. */
25
+ function serializeProduct(product) {
26
+ if (!(product instanceof Product))
27
+ return product;
28
+ const raw = {
29
+ id: product.id,
30
+ responseId: product.responseId,
31
+ mappings: product.mappings,
32
+ attributes: product.attributes,
33
+ badges: product.badges?.all?.map((b) => ({ tag: b.tag, value: b.value })) || [],
34
+ };
35
+ if (product.variants) {
36
+ raw.variants = {
37
+ data: product.variants.data.map((v) => ({
38
+ mappings: v.mappings,
39
+ attributes: v.attributes,
40
+ options: v.options,
41
+ badges: v.badges,
42
+ })),
43
+ optionConfig: product.variants.optionConfig,
44
+ };
45
+ }
46
+ return raw;
47
+ }
48
+ /** Serialize attachments for localStorage. Strips base64 from images (kept only at runtime). */
49
+ function serializeAttachmentsForStorage(items) {
50
+ return items.map((item) => {
51
+ if (item.type === 'image') {
52
+ return {
53
+ type: 'image',
54
+ id: item.id,
55
+ fileName: item.fileName,
56
+ imageId: item.imageId,
57
+ imageUrl: item.imageUrl,
58
+ thumbnailUrl: item.thumbnailUrl,
59
+ state: item.state,
60
+ error: item.error,
61
+ };
62
+ }
63
+ if (item.type === 'product') {
64
+ return {
65
+ type: 'product',
66
+ id: item.id,
67
+ productId: item.productId,
68
+ thumbnailUrl: item.thumbnailUrl,
69
+ name: item.name,
70
+ requestType: item.requestType,
71
+ state: item.state,
72
+ error: item.error,
73
+ };
74
+ }
75
+ return {
76
+ type: 'facet',
77
+ id: item.id,
78
+ key: item.key,
79
+ facetLabel: item.facetLabel,
80
+ value: item.value,
81
+ label: item.label,
82
+ count: item.count,
83
+ state: item.state,
84
+ error: item.error,
85
+ };
86
+ });
87
+ }
88
+ /** Convert a chat message array to a plain serializable form for localStorage. */
89
+ function serializeChatForStorage(chat) {
90
+ return chat.map((message) => {
91
+ switch (message.messageType) {
92
+ case 'productSearchResult': {
93
+ const msg = message;
94
+ return { ...msg, results: Array.from(msg.results || []).map(serializeProduct) };
95
+ }
96
+ case 'inspirationResult': {
97
+ const msg = message;
98
+ return {
99
+ ...msg,
100
+ inspirationSections: msg.inspirationSections?.map((section) => ({
101
+ ...section,
102
+ products: Array.from(section.products || []).map(serializeProduct),
103
+ })),
104
+ };
105
+ }
106
+ case 'productAnswer': {
107
+ const msg = message;
108
+ return { ...msg, sourceProduct: serializeProduct(msg.sourceProduct) };
109
+ }
110
+ case 'productComparison': {
111
+ const msg = message;
112
+ return { ...msg, searchResults: Array.from(msg.searchResults || []).map(serializeProduct) };
113
+ }
114
+ case 'productRecommendation': {
115
+ const msg = message;
116
+ return {
117
+ ...msg,
118
+ recommendationResult: msg.recommendationResult?.map((rec) => ({
119
+ ...rec,
120
+ results: Array.from(rec.results || []).map(serializeProduct),
121
+ })),
122
+ };
123
+ }
124
+ case 'productQuery': {
125
+ const msg = message;
126
+ return { ...msg, sourceProduct: serializeProduct(msg.sourceProduct) };
127
+ }
128
+ default:
129
+ return message;
130
+ }
131
+ });
132
+ }
133
+ export class ChatSessionStore {
134
+ constructor(params) {
135
+ this.chat = [];
136
+ this.actions = [];
137
+ this.attachments = new ChatAttachmentStore();
138
+ this.comparisons = new ChatCompareStore();
139
+ this.feedback = { rating: null, dismissed: false, justGiven: false };
140
+ this.createdAt = new Date();
141
+ this.requestType = '';
142
+ this.dismissedSideChatMessageId = null;
143
+ this.activeMessageId = null;
144
+ this.sessionLimitReached = false;
145
+ /** Whether raw stored results have been hydrated into Product/SearchResultStore instances. */
146
+ this.hydrated = true;
147
+ this.saveTimerId = null;
148
+ const { id, sessionId, chat, attachments, actions, feedback, createdAt, sessionEndTime, committedComparisons } = params.data || {};
149
+ const { stores } = params;
150
+ this.id = id || uuidv4();
151
+ this.sessionId = sessionId;
152
+ this.storage = stores.storage;
153
+ this.actions = actions || [];
154
+ this.createdAt = createdAt ? new Date(createdAt) : new Date();
155
+ this.sessionEndTime = sessionEndTime ? new Date(sessionEndTime) : undefined;
156
+ this.feedback = {
157
+ rating: feedback?.rating || null,
158
+ dismissed: feedback?.dismissed || false,
159
+ justGiven: false,
160
+ };
161
+ // if chat and attachments are passed, load them
162
+ if (chat && chat.length > 0) {
163
+ // productQuery messages only exist to drive the side-chat panel for an
164
+ // in-flight productQuery click; they must not be rehydrated on reload
165
+ // or the side chat would re-open without the matching primary-chat state
166
+ this.chat = chat.filter((message) => message.messageType !== 'productQuery');
167
+ }
168
+ if (attachments && attachments.length > 0) {
169
+ this.attachments.hydrate(attachments);
170
+ // Any attachment already referenced by a sent user message is no longer
171
+ // pending — transition it from 'active' to 'saved' so it stops appearing
172
+ // in the attachment context bar while remaining available via get(id) for
173
+ // rendering inside historical user messages.
174
+ const usedAttachmentIds = new Set();
175
+ this.chat.forEach((msg) => {
176
+ if (msg.messageType === 'user' && msg.attachments) {
177
+ msg.attachments.forEach((id) => usedAttachmentIds.add(id));
178
+ }
179
+ });
180
+ this.attachments.items.forEach((item) => {
181
+ if ((item.state === 'active' || item.state === 'attached') && usedAttachmentIds.has(item.id)) {
182
+ item.save();
183
+ }
184
+ });
185
+ }
186
+ // restore committed comparisons only if the thread is still anchored
187
+ // to a product comparison — either the last response was a
188
+ // productComparison or the user sent a follow-up before a response
189
+ // arrived (pending state)
190
+ if (committedComparisons && committedComparisons.length > 0) {
191
+ const EXCLUDED_MESSAGE_TYPES = ['topicDrift'];
192
+ const visibleMessages = this.chat.filter((message) => !EXCLUDED_MESSAGE_TYPES.includes(message.messageType));
193
+ const lastMessage = visibleMessages[visibleMessages.length - 1];
194
+ if (lastMessage?.messageType === 'productComparison' || lastMessage?.messageType === 'user') {
195
+ this.comparisons.committedItems = committedComparisons;
196
+ }
197
+ }
198
+ makeObservable(this, {
199
+ chat: observable,
200
+ requestType: observable,
201
+ actions: observable,
202
+ attachments: observable,
203
+ feedback: observable,
204
+ dismissedSideChatMessageId: observable,
205
+ activeMessageId: observable,
206
+ sessionLimitReached: observable,
207
+ activeMessage: computed,
208
+ });
209
+ }
210
+ dismissSideChat() {
211
+ // clear the override first so the fallback (last eligible message) is what we
212
+ // dismiss — otherwise closing while viewing an older message would leave the
213
+ // last message undismissed and the side chat would auto-reopen on it
214
+ this.activeMessageId = null;
215
+ const fallback = this.activeMessage;
216
+ if (fallback) {
217
+ this.dismissedSideChatMessageId = fallback.id;
218
+ }
219
+ }
220
+ setActiveMessage(id) {
221
+ this.activeMessageId = id;
222
+ this.dismissedSideChatMessageId = null;
223
+ // Reopening a previous productComparison switches the conversation context
224
+ // back to the comparison — drop any lingering 'discuss product' (productQuery)
225
+ // attachment so the footer reflects only the comparison products.
226
+ const target = this.chat.find((m) => m.id === id);
227
+ if (target?.messageType === 'productComparison') {
228
+ const productQueryAttachments = this.attachments.attached.filter((item) => item.type === 'product' && item.requestType === 'productQuery');
229
+ productQueryAttachments.forEach((item) => this.attachments.remove(item.id));
230
+ }
231
+ }
232
+ pushProductQueryMessage(result) {
233
+ // capture the side-chat message that was active at click time so a back action
234
+ // can restore it even when it's not the last message in the chat
235
+ const sourceMessageId = this.activeMessage?.id;
236
+ // drop any trailing productQuery so a fresh productQuery click replaces
237
+ // the side-chat target rather than stacking up
238
+ while (this.chat.length > 0 && this.chat[this.chat.length - 1]?.messageType === 'productQuery') {
239
+ this.chat.pop();
240
+ }
241
+ this.chat.push({
242
+ id: uuidv4(),
243
+ messageType: 'productQuery',
244
+ sourceProduct: result,
245
+ sourceMessageId,
246
+ });
247
+ // re-show the side chat in case the user previously dismissed it
248
+ this.dismissedSideChatMessageId = null;
249
+ this.activeMessageId = null;
250
+ this.save();
251
+ }
252
+ popProductQueryMessage(restoreActiveMessageId) {
253
+ while (this.chat.length > 0 && this.chat[this.chat.length - 1]?.messageType === 'productQuery') {
254
+ this.chat.pop();
255
+ }
256
+ this.activeMessageId = restoreActiveMessageId || null;
257
+ this.save();
258
+ }
259
+ get isExpired() {
260
+ // Prefer the server-provided end time (returned by chatInit); fall back to a
261
+ // 24-hour window from createdAt for sessions persisted before that field existed.
262
+ if (this.sessionEndTime) {
263
+ return Date.now() > this.sessionEndTime.getTime();
264
+ }
265
+ const ONE_DAY = 24 * 60 * 60 * 1000;
266
+ return Date.now() - this.createdAt.getTime() > ONE_DAY;
267
+ }
268
+ get topicDrift() {
269
+ const lastMessage = this.chat[this.chat.length - 1];
270
+ return lastMessage?.messageType === 'topicDrift' ? lastMessage : null;
271
+ }
272
+ get activeMessage() {
273
+ const EXCLUDED_MESSAGE_TYPES = ['topicDrift', 'productAnswer'];
274
+ if (this.activeMessageId) {
275
+ // Walk backward — the override is usually near the end
276
+ for (let i = this.chat.length - 1; i >= 0; i--) {
277
+ const m = this.chat[i];
278
+ if (m.id === this.activeMessageId && !EXCLUDED_MESSAGE_TYPES.includes(m.messageType)) {
279
+ return m;
280
+ }
281
+ }
282
+ }
283
+ // Find the last eligible message by iterating backwards
284
+ let lastMessage = null;
285
+ for (let i = this.chat.length - 1; i >= 0; i--) {
286
+ if (!EXCLUDED_MESSAGE_TYPES.includes(this.chat[i].messageType)) {
287
+ lastMessage = this.chat[i];
288
+ break;
289
+ }
290
+ }
291
+ // When the user sends a follow-up while in a productQuery flow (e.g. "discuss product"),
292
+ // the last visible message becomes a 'user' message which would close the secondary panel.
293
+ // Instead, keep the productQuery message as the active side-chat target so the product
294
+ // information panel stays open during and after the request.
295
+ if (lastMessage?.messageType === 'user' && this.requestType === 'productQuery') {
296
+ for (let i = this.chat.length - 1; i >= 0; i--) {
297
+ const m = this.chat[i];
298
+ if (m.messageType === 'productQuery' && !EXCLUDED_MESSAGE_TYPES.includes(m.messageType)) {
299
+ return m;
300
+ }
301
+ }
302
+ }
303
+ return lastMessage || null;
304
+ }
305
+ dismissTopicDrift() {
306
+ this.chat = this.chat.filter((m) => m.messageType !== 'topicDrift');
307
+ this.save();
308
+ }
309
+ handleTopicDrift() {
310
+ let lastUserMessage;
311
+ for (let i = this.chat.length - 1; i >= 0; i--) {
312
+ if (this.chat[i].messageType === 'user') {
313
+ lastUserMessage = this.chat[i];
314
+ break;
315
+ }
316
+ }
317
+ const messageText = lastUserMessage?.text;
318
+ // remove all topicDrift messages and the last user message that triggered the drift
319
+ if (lastUserMessage) {
320
+ const lastUserIndex = this.chat.lastIndexOf(lastUserMessage);
321
+ this.chat = this.chat.slice(0, lastUserIndex);
322
+ }
323
+ else {
324
+ this.chat = this.chat.filter((m) => m.messageType !== 'topicDrift');
325
+ }
326
+ this.save();
327
+ return messageText;
328
+ }
329
+ reset() {
330
+ this.attachments.reset();
331
+ this.chat = [];
332
+ this.actions = [];
333
+ this.feedback = { rating: null, dismissed: false, justGiven: false };
334
+ }
335
+ /** Persist the session to storage immediately (synchronous). */
336
+ saveImmediate() {
337
+ if (this.saveTimerId !== null) {
338
+ clearTimeout(this.saveTimerId);
339
+ this.saveTimerId = null;
340
+ }
341
+ this.storage.set(`chats.${this.id}`, {
342
+ sessionId: this.sessionId,
343
+ chat: serializeChatForStorage(this.chat),
344
+ attachments: serializeAttachmentsForStorage(this.attachments.items),
345
+ actions: this.actions,
346
+ feedback: { rating: this.feedback.rating, dismissed: this.feedback.dismissed },
347
+ createdAt: this.createdAt,
348
+ sessionEndTime: this.sessionEndTime,
349
+ committedComparisons: this.comparisons.committedItems,
350
+ });
351
+ }
352
+ /**
353
+ * Schedule a save — multiple calls within the debounce window are coalesced
354
+ * into a single localStorage write.
355
+ */
356
+ save() {
357
+ if (this.saveTimerId !== null) {
358
+ clearTimeout(this.saveTimerId);
359
+ }
360
+ this.saveTimerId = setTimeout(() => {
361
+ this.saveTimerId = null;
362
+ this.saveImmediate();
363
+ }, 0);
364
+ }
365
+ /** Remove oldest stored sessions when exceeding the limit. */
366
+ static pruneStoredSessions(storage, maxSessions = 10) {
367
+ const storedChats = storage.get('chats');
368
+ if (storedChats) {
369
+ const chatIds = Object.keys(storedChats);
370
+ if (chatIds.length > maxSessions) {
371
+ chatIds
372
+ .sort((a, b) => {
373
+ const aTime = new Date(storedChats[a]?.createdAt || 0).getTime();
374
+ const bTime = new Date(storedChats[b]?.createdAt || 0).getTime();
375
+ return aTime - bTime;
376
+ })
377
+ .slice(0, chatIds.length - maxSessions)
378
+ .forEach((id) => {
379
+ storage.set(`chats.${id}`, null);
380
+ });
381
+ }
382
+ }
383
+ }
384
+ /** Re-wrap raw stored results as Product / SearchResultStore instances. */
385
+ hydrateResults(meta) {
386
+ this.chat.forEach((message) => {
387
+ if (message.messageType === 'productSearchResult') {
388
+ const msg = message;
389
+ if (msg.results?.length && !(msg.results[0] instanceof Product)) {
390
+ msg.results = createChatResultStore(msg.results, meta);
391
+ }
392
+ }
393
+ else if (message.messageType === 'inspirationResult') {
394
+ const msg = message;
395
+ msg.inspirationSections?.forEach((section) => {
396
+ if (section.products?.length && !(section.products[0] instanceof Product)) {
397
+ section.products = createChatResultStore(section.products, meta);
398
+ }
399
+ });
400
+ }
401
+ else if (message.messageType === 'productAnswer') {
402
+ const msg = message;
403
+ if (msg.sourceProduct && !(msg.sourceProduct instanceof Product)) {
404
+ msg.sourceProduct = createChatProduct(msg.sourceProduct, meta);
405
+ }
406
+ }
407
+ else if (message.messageType === 'productComparison') {
408
+ const msg = message;
409
+ if (msg.searchResults?.length && !(msg.searchResults[0] instanceof Product)) {
410
+ msg.searchResults = createChatResultStore(msg.searchResults, meta);
411
+ }
412
+ }
413
+ else if (message.messageType === 'productRecommendation') {
414
+ const msg = message;
415
+ msg.recommendationResult?.forEach((rec) => {
416
+ if (rec.results?.length && !(rec.results[0] instanceof Product)) {
417
+ rec.results = createChatResultStore(rec.results, meta);
418
+ }
419
+ });
420
+ }
421
+ });
422
+ }
423
+ request(request, filterLabels) {
424
+ // clear the questions on new request
425
+ this.actions = [];
426
+ this.requestType = request.data.requestType;
427
+ this.activeMessageId = null;
428
+ // remove any attachments that failed to upload
429
+ const errorAttachments = this.attachments.items.filter((item) => item.state === 'error');
430
+ errorAttachments.forEach((item) => this.attachments.items.splice(this.attachments.items.indexOf(item), 1));
431
+ const attachments = [];
432
+ if (request.data.requestType === 'productSearch') {
433
+ const searchFilters = request.data.searchFilters;
434
+ if (searchFilters && searchFilters.length > 0) {
435
+ const filterTextArray = [];
436
+ searchFilters.forEach((filter) => {
437
+ const labelEntry = filterLabels?.[filter.key];
438
+ filter.options?.forEach((option) => {
439
+ const facetLabel = labelEntry?.facetLabel || filter.key;
440
+ if ('low' in option || 'high' in option) {
441
+ const low = option.low ?? '*';
442
+ const high = option.high ?? '*';
443
+ filterTextArray.push(`${facetLabel} ${low}-${high}`);
444
+ }
445
+ else {
446
+ const key = option.key;
447
+ const optionLabel = labelEntry?.values[key] || key;
448
+ filterTextArray.push(`${facetLabel} ${optionLabel}`);
449
+ }
450
+ });
451
+ });
452
+ this.chat.push({
453
+ id: uuidv4(),
454
+ messageType: 'user',
455
+ attachments: attachments.length > 0 ? attachments : undefined,
456
+ text: `Filter by ${filterTextArray.join(' and ')}`,
457
+ requestType: request.data.requestType,
458
+ request: request.data, // request is added here to conditionally display different text in MessageUser
459
+ });
460
+ }
461
+ else if (request.data.searchTerm) {
462
+ // for when a query is clicked from ChatInspirationResultMessage
463
+ this.chat.push({
464
+ id: uuidv4(),
465
+ messageType: 'user',
466
+ text: request.data.searchTerm,
467
+ requestType: request.data.requestType,
468
+ request: request.data, // request is added here to conditionally display different text in MessageUser
469
+ });
470
+ }
471
+ }
472
+ else if ('message' in request.data && request.data.message) {
473
+ if (request.data.requestType === 'imageSearch') {
474
+ const imageId = request.data.attachedImageId;
475
+ const attachedImage = this.attachments.attached.find((item) => item.type == 'image' && item.imageId == imageId);
476
+ if (attachedImage) {
477
+ attachments.push(attachedImage.id);
478
+ attachedImage.activate();
479
+ }
480
+ }
481
+ else if (request.data.requestType === 'productQuery') {
482
+ const productId = request.data.productId;
483
+ const attachedProduct = this.attachments.attached.find((item) => item.type == 'product' && item.productId == productId);
484
+ if (attachedProduct) {
485
+ attachments.push(attachedProduct.id);
486
+ attachedProduct.activate();
487
+ }
488
+ }
489
+ else if (request.data.requestType === 'productComparison') {
490
+ this.comparisons.compared.forEach((item) => {
491
+ const d = item.result?.display || item.result;
492
+ const attachment = this.attachments.add({
493
+ type: 'product',
494
+ requestType: 'productComparison',
495
+ productId: item.result.id,
496
+ name: d.mappings?.core?.name,
497
+ thumbnailUrl: d.mappings?.core?.thumbnailImageUrl || d.mappings?.core?.imageUrl || d.mappings?.core?.parentImageUrl,
498
+ });
499
+ if (attachment) {
500
+ attachments.push(attachment.id);
501
+ attachment.activate();
502
+ }
503
+ });
504
+ }
505
+ this.chat.push({
506
+ id: uuidv4(),
507
+ messageType: 'user',
508
+ attachments: attachments.length > 0 ? attachments : undefined,
509
+ text: request.data.message,
510
+ requestType: request.data.requestType,
511
+ });
512
+ }
513
+ else if (request.data?.requestType === 'productSimilar') {
514
+ const attachedSimilarProduct = this.attachments.attached.find((item) => item.type == 'product' && item.requestType == 'productSimilar');
515
+ if (attachedSimilarProduct) {
516
+ attachments.push(attachedSimilarProduct.id);
517
+ attachedSimilarProduct.activate();
518
+ this.chat.push({
519
+ id: uuidv4(),
520
+ messageType: 'user',
521
+ attachments: attachments.length > 0 ? attachments : undefined,
522
+ text: `Show similar products to "${attachedSimilarProduct.name || attachedSimilarProduct.productId}"`,
523
+ requestType: request.data.requestType,
524
+ });
525
+ }
526
+ }
527
+ else if (request.data?.requestType === 'productComparison') {
528
+ const productNames = [];
529
+ this.comparisons.compared.forEach((item) => {
530
+ const d = item.result?.display || item.result;
531
+ const attachment = this.attachments.add({
532
+ type: 'product',
533
+ requestType: 'productComparison',
534
+ productId: item.result.id,
535
+ name: d.mappings?.core?.name,
536
+ thumbnailUrl: d.mappings?.core?.thumbnailImageUrl || d.mappings?.core?.imageUrl || d.mappings?.core?.parentImageUrl,
537
+ });
538
+ if (attachment) {
539
+ attachments.push(attachment.id);
540
+ attachment.activate();
541
+ productNames.push(attachment.name || attachment.productId);
542
+ }
543
+ });
544
+ if (attachments.length > 0) {
545
+ this.chat.push({
546
+ id: uuidv4(),
547
+ messageType: 'user',
548
+ attachments: attachments,
549
+ text: `Compare ${productNames.map((name) => `"${name}"`).join(' and ')}`,
550
+ requestType: request.data.requestType,
551
+ });
552
+ }
553
+ }
554
+ // snapshot the comparison list into the committed list so the
555
+ // header section can clear and the footer can display them
556
+ if (request.data.requestType === 'productComparison') {
557
+ this.comparisons.commit();
558
+ }
559
+ this.save();
560
+ }
561
+ update(data) {
562
+ this.sessionId = data.chat.context.sessionId;
563
+ const meta = data.meta;
564
+ data.chat.data.forEach((messageData) => {
565
+ // check if the data has questions?
566
+ if (messageData.messageType === 'actions') {
567
+ this.actions.push({
568
+ type: 'actions',
569
+ data: messageData.actions,
570
+ });
571
+ return;
572
+ }
573
+ // convert raw results to Product instances (via SearchResultStore) so
574
+ // display components can use result.display for mask-aware rendering
575
+ if (messageData.messageType === 'productSearchResult' && messageData.results?.length) {
576
+ messageData.results = createChatResultStore(messageData.results, meta);
577
+ }
578
+ else if (messageData.messageType === 'inspirationResult' && messageData.inspirationSections?.length) {
579
+ messageData.inspirationSections = messageData.inspirationSections.map((section) => ({
580
+ ...section,
581
+ products: section.products?.length
582
+ ? createChatResultStore(section.products, meta)
583
+ : section.products,
584
+ }));
585
+ }
586
+ else if (messageData.messageType === 'productAnswer' && messageData.sourceProduct) {
587
+ messageData.sourceProduct = createChatProduct(messageData.sourceProduct, meta);
588
+ }
589
+ else if (messageData.messageType === 'productComparison' && messageData.searchResults?.length) {
590
+ messageData.searchResults = createChatResultStore(messageData.searchResults, meta);
591
+ }
592
+ else if (messageData.messageType === 'productRecommendation' && messageData.recommendationResult?.length) {
593
+ messageData.recommendationResult = messageData.recommendationResult.map((rec) => ({
594
+ ...rec,
595
+ results: rec.results?.length ? createChatResultStore(rec.results, meta) : rec.results,
596
+ }));
597
+ }
598
+ this.chat.push(messageData);
599
+ });
600
+ this.save();
601
+ }
602
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"SearchFacetStore.d.ts","sourceRoot":"","sources":["../../../../src/Search/Stores/SearchFacetStore.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,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AG,MAAM,CAAC;IAChB,GAAG,EAAE,UAAU,CAAC;gBAEX,QAAQ,EAAE,aAAa,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,wCAAwC;CAgBvG"}
@@ -238,15 +238,16 @@ export class ValueFacet extends Facet {
238
238
  export class FacetValue {
239
239
  constructor(services, facet, value) {
240
240
  Object.assign(this, value);
241
+ const urlManager = services.urlManager;
241
242
  if (this.filtered) {
242
- this.url = services.urlManager.remove('page').remove(`filter.${facet.field}`, value.value);
243
+ this.url = urlManager.remove('page').remove(`filter.${facet.field}`, value.value);
243
244
  }
244
245
  else {
245
- let valueUrl = services.urlManager.remove('page');
246
+ let valueUrl = urlManager.remove('page');
246
247
  if (facet.multiple == 'single') {
247
- valueUrl = valueUrl?.remove(`filter.${facet.field}`);
248
+ valueUrl = valueUrl.remove(`filter.${facet.field}`);
248
249
  }
249
- this.url = valueUrl?.merge(`filter.${facet.field}`, value.value);
250
+ this.url = valueUrl.merge(`filter.${facet.field}`, value.value);
250
251
  }
251
252
  }
252
253
  }
@@ -264,26 +265,28 @@ export class FacetHierarchyValue extends FacetValue {
264
265
  this.history = true;
265
266
  }
266
267
  }
268
+ const urlManager = services.urlManager;
267
269
  if (value.value) {
268
- this.url = services.urlManager.remove('page').set(`filter.${facet.field}`, value.value);
270
+ this.url = urlManager.remove('page').set(`filter.${facet.field}`, value.value);
269
271
  }
270
272
  else {
271
- this.url = services.urlManager.remove('page').remove(`filter.${facet.field}`);
273
+ this.url = urlManager.remove('page').remove(`filter.${facet.field}`);
272
274
  }
273
275
  }
274
276
  }
275
277
  export class FacetRangeValue {
276
278
  constructor(services, facet, value) {
277
279
  Object.assign(this, value);
280
+ const urlManager = services.urlManager;
278
281
  if (this.filtered) {
279
- this.url = services.urlManager.remove('page').remove(`filter.${facet.field}`, [{ low: this.low, high: this.high }]);
282
+ this.url = urlManager.remove('page').remove(`filter.${facet.field}`, [{ low: this.low, high: this.high }]);
280
283
  }
281
284
  else {
282
- let valueUrl = services.urlManager.remove('page');
285
+ let valueUrl = urlManager.remove('page');
283
286
  if (facet.multiple == 'single') {
284
- valueUrl = valueUrl?.remove(`filter.${facet.field}`);
287
+ valueUrl = valueUrl.remove(`filter.${facet.field}`);
285
288
  }
286
- this.url = valueUrl?.merge(`filter.${facet.field}`, [{ low: this.low, high: this.high }]);
289
+ this.url = valueUrl.merge(`filter.${facet.field}`, [{ low: this.low, high: this.high }]);
287
290
  }
288
291
  }
289
292
  }
@@ -2,7 +2,7 @@ export { SearchMerchandisingStore, BannerContent, ContentType, MerchandisingCont
2
2
  export { SearchFacetStore, ValueFacet, RangeFacet, FacetValue, FacetHierarchyValue, FacetRangeValue } from './SearchFacetStore';
3
3
  export { SearchFilterStore, Filter } from './SearchFilterStore';
4
4
  export { SearchPaginationStore, Page } from './SearchPaginationStore';
5
- export { SearchResultStore, Product, Banner, VariantSelection, VariantSelectionValue } from './SearchResultStore';
5
+ export { SearchResultStore, Product, Banner, Variants, VariantSelection, VariantSelectionValue } from './SearchResultStore';
6
6
  export { SearchSortingStore } from './SearchSortingStore';
7
7
  export { SearchQueryStore } from './SearchQueryStore';
8
8
  export { SearchHistoryStore } from './SearchHistoryStore';