-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathSearch.jsx
More file actions
813 lines (699 loc) · 32.9 KB
/
Search.jsx
File metadata and controls
813 lines (699 loc) · 32.9 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
import './Search.scss';
import { useRef, useState, useEffect } from 'react';
import { useRecoilState, useRecoilValue } from 'recoil';
import appConfigState from '../../atoms/appConfigState';
import categoriesState from '../../atoms/categoriesState';
import currentVenueNameState from '../../atoms/currentVenueNameState';
import { useInitialChatMessage } from '../../hooks/useInitialChatMessage';
import { useGemini } from '../../providers/GeminiProvider';
import { snapPoints } from '../../constants/snapPoints';
import { usePreventSwipe } from '../../hooks/usePreventSwipe';
import ListItemLocation from '../WebComponentWrappers/ListItemLocation/ListItemLocation';
import SearchField from '../WebComponentWrappers/Search/Search';
import filteredLocationsState from '../../atoms/filteredLocationsState';
import mapsIndoorsInstanceState from '../../atoms/mapsIndoorsInstanceState';
import currentLocationState from '../../atoms/currentLocationState';
import isLocationClickedState from '../../atoms/isLocationClickedState';
import getDesktopPaddingLeft from '../../helpers/GetDesktopPaddingLeft';
import languageState from '../../atoms/languageState';
import { useTranslation } from 'react-i18next';
import kioskLocationState from '../../atoms/kioskLocationState';
import getDesktopPaddingBottom from '../../helpers/GetDesktopPaddingBottom';
import { createPortal } from 'react-dom';
import useKeyboardState from '../../atoms/useKeyboardState';
import Keyboard from '../WebComponentWrappers/Keyboard/Keyboard';
import searchInputState from '../../atoms/searchInputState';
import searchResultsState from '../../atoms/searchResultsState';
import selectedCategoryState from '../../atoms/selectedCategoryState';
import Categories from './Categories/Categories';
import { useIsKioskContext } from '../../hooks/useIsKioskContext';
import { useIsDesktop } from '../../hooks/useIsDesktop';
import Legend from '../../assets/legend.svg?react';
import AskWithAiIcon from '../../assets/ask-with-ai-icon.svg?react';
import isLegendDialogVisibleState from '../../atoms/isLegendDialogVisibleState';
import legendSortedFieldsSelector from '../../selectors/legendSortedFieldsSelector';
import searchAllVenuesState from '../../atoms/searchAllVenues';
import isNullOrUndefined from '../../helpers/isNullOrUndefined';
import venuesInSolutionState from '../../atoms/venuesInSolutionState';
import initialVenueNameState from '../../atoms/initialVenueNameState';
import primaryColorState from '../../atoms/primaryColorState';
import PropTypes from 'prop-types';
Search.propTypes = {
categories: PropTypes.array,
onSetSize: PropTypes.func,
isOpen: PropTypes.bool,
onOpenChat: PropTypes.func
};
/**
* Show the search results.
*
* @param {Object} props
* @param {[[string, number]]} props.categories - All the unique categories that users can filter through.
* @param {function} props.onSetSize - Callback that is fired when the search field takes focus and when categories are clicked.
* @param {boolean} props.isOpen - Boolean that describes if the search page is open or not.
*
* @returns
*/
function Search({ onSetSize, isOpen, onOpenChat }) {
const appConfig = useRecoilValue(appConfigState);
const { t } = useTranslation();
const searchRef = useRef();
const scrollButtonsRef = useRef();
const requestAnimationFrameId = useRef();
/** Referencing the search field */
const searchFieldRef = useRef();
/** Referencing the keyboard element */
const keyboardRef = useRef();
/** Maximum number of search results to show */
const MAX_RESULTS = 100;
const [searchResults, setSearchResults] = useRecoilState(searchResultsState);
const categories = useRecoilValue(categoriesState);
const primaryColor = useRecoilValue(primaryColorState);
const useKeyboard = useRecoilValue(useKeyboardState);
/** Indicate if search results have been found */
const [showNotFoundMessage, setShowNotFoundMessage] = useState(false);
const [selectedCategory, setSelectedCategory] = useRecoilState(selectedCategoryState);
const scrollableContentSwipePrevent = usePreventSwipe();
const [hoveredLocation, setHoveredLocation] = useState();
const mapsIndoorsInstance = useRecoilValue(mapsIndoorsInstanceState);
const [, setFilteredLocations] = useRecoilState(filteredLocationsState);
const [, setCurrentLocation] = useRecoilState(currentLocationState);
const [, setIsLocationClicked] = useRecoilState(isLocationClickedState);
const [currentVenueName, setCurrentVenueName] = useRecoilState(currentVenueNameState);
const currentLanguage = useRecoilValue(languageState);
const isDesktop = useIsDesktop();
const kioskLocation = useRecoilValue(kioskLocationState);
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
const searchInput = useRecoilValue(searchInputState);
const { setInitialMessage, } = useInitialChatMessage();
const { enabled: isAiChatEnabled } = useGemini();
const isKioskContext = useIsKioskContext();
const [, setShowLegendDialog] = useRecoilState(isLegendDialogVisibleState);
const [showLegendButton, setShowLegendButton] = useState(false);
const legendSections = useRecoilValue(legendSortedFieldsSelector);
const searchAllVenues = useRecoilValue(searchAllVenuesState);
const venuesInSolution = useRecoilValue(venuesInSolutionState);
const initialVenueName = useRecoilValue(initialVenueNameState);
const [isInputFieldInFocus, setIsInputFieldInFocus] = useState(false);
const [showAskWithAiButton, setShowAskWithAiButton] = useState(false);
const skipHighlightRef = useRef(false);
const selectedCategoriesArray = useRef([]);
const [childKeys, setChildKeys] = useState([]);
const [areHorizontalCategoriesEnabled, setAreHorizontalCategoriesEnabled] = useState(false);
/**
* Handles go back function.
*/
function handleBack() {
// If selected categories tree has only parent category, then on back, we need to perform those clear functions.
// Else, remove child category from selected categories tree array.
if (selectedCategoriesArray.current.length === 0) {
setSelectedCategory(null);
setSearchResults([]);
setFilteredLocations([]);
setSize(snapPoints.FIT);
setIsInputFieldInFocus(true);
// If there's a search term and it's not just whitespace, re-trigger the search without category filter
const searchValue = searchFieldRef.current?.getValue()?.trim();
if (searchValue) {
searchFieldRef.current.triggerSearch();
} else {
// If it's empty or just whitespace, clear the search field
if (searchFieldRef.current) {
skipHighlightRef.current = true;
searchFieldRef.current.clear();
}
}
selectedCategoriesArray.current.pop();
} else {
selectedCategoriesArray.current.pop()
setSelectedCategory(selectedCategoriesArray.current[0])
}
}
/**
*
* Get the locations and filter through them based on categories selected.
*
* @param {string} category
*/
function getFilteredLocations(category) {
// Creates a selected categoriers tree, where first category in the array is parent and second one is child
// Ensure category is unique before pushing to selectedCategories.current
if (!selectedCategoriesArray.current.includes(category)) {
selectedCategoriesArray.current.push(category);
}
// If child category is being selected, we need to clear parent categories results in order to load proper data that belongs to child category.
if (selectedCategory) {
setSelectedCategory([]);
setSearchResults([]);
setFilteredLocations([]);
}
setSelectedCategory(category)
// Regarding the venue name: The venue parameter in the SDK's getLocations method is case sensitive.
// So when the currentVenueName is set based on a Locations venue property, the casing may differ.
// Thus we need to find the venue name from the list of venues.
window.mapsindoors.services.LocationsService.getLocations({
categories: category,
venue: searchAllVenues ? undefined : venuesInSolution.find(venue => venue.name.toLowerCase() === currentVenueName.toLowerCase())?.name,
}).then(results => onResults(results, true));
}
/**
* Communicate size change to parent component.
*
* @param {number} size
*/
function setSize(size) {
if (typeof onSetSize === 'function') {
onSetSize(size);
}
}
/**
* Sort search results alphabetically if configured to do so and a category is selected.
*
* @param {Array} results - Array of search results
* @returns {Array} Sorted or original array based on configuration
*/
function getSortedSearchResults(results) {
if (selectedCategory) {
return [...results].sort((a, b) => {
return (a.properties?.name || '')
.localeCompare(b.properties?.name || '', undefined, { numeric: true });
})
}
return results;
}
/**
* Handle search results from the search field.
*
* @param {array} locations - An array of MapsIndoors Location objects.
* @param {boolean} fitMapBounds - If the map bounds should be adjusted to fit the locations.
*/
function onResults(locations, fitMapBounds = false) {
const displayResults = locations.slice(0, MAX_RESULTS);
// Expand the sheet to occupy the entire screen
setSize(snapPoints.MAX);
setSearchResults(displayResults);
setFilteredLocations(displayResults);
setShowNotFoundMessage(displayResults.length === 0);
if (locations && fitMapBounds) {
fitMapBoundsToLocations(locations);
}
// Handles updates to scroll buttons when the category changes.
// When a category changes, the scroll buttons need to have their enabled/disabled states updated.
// Since some categories might load before the DOM element is fully rendered, we listen for the 'transitionend' event.
// The 'transitionend' event is triggered when the DOM element changes its size, which can occur as a result of new categories being fetched.
// Upon completion of the size transition, the 'updateScrollButtons' function is triggered to handle the updated state.
if (isKioskContext) {
searchRef.current?.addEventListener('transitionend', () => {
scrollButtonsRef?.current?.updateScrollButtons();
}, { once: true });
}
}
/**
* Adjusts the map view to fit the bounds of the provided locations.
* It will filter out Locations that are not on the current floor or not part of the current venue.
*
* @param {Array} locations - An array of Location objects to fit within the map bounds.
*/
function fitMapBoundsToLocations(locations) {
if (!mapsIndoorsInstance.goTo) return; // Early exit to prevent crashes if using an older version of the MapsIndoors JS SDK. The goTo method was introduced in version 4.38.0.
const currentFloorIndex = mapsIndoorsInstance.getFloor();
// Create a GeoJSON FeatureCollection from the locations that can be used as input to the goTo method.
const featureCollection = {
type: 'FeatureCollection',
features: locations
// Filter out locations that are not on the current floor. If those were included, it could result in a wrong fit since they are not visible on the map anyway.
.filter(location => parseInt(location.properties.floor, 10) === parseInt(currentFloorIndex, 10))
// Filter out locations that are not part of the current venue. Including those when fitting to bounds could cause the map to zoom out too much.
.filter(location => location.properties.venueId.toLowerCase() === currentVenueName.toLowerCase())
// Map the locations to GeoJSON features.
.map(location => ({
type: 'Feature',
geometry: location.geometry,
properties: location.properties
}))
};
if (featureCollection.features.length > 0) {
Promise.all([getBottomPadding(), getLeftPadding()]).then(([bottomPadding, leftPadding]) => {
mapsIndoorsInstance.goTo(featureCollection, {
maxZoom: 22,
padding: { bottom: bottomPadding, left: leftPadding, top: 0, right: 0 }
});
});
}
}
/**
* Handle search field value changes to control "Ask with AI" button visibility.
*/
function handleSearchChanged() {
if (searchFieldRef.current && isInputFieldInFocus) {
const currentValue = searchFieldRef.current.getValue();
const characterCount = currentValue ? currentValue.length : 0;
// Show button when character count is greater than 5
setShowAskWithAiButton(characterCount > 5);
} else {
setShowAskWithAiButton(false);
}
}
/**
* Clear results list when search field is cleared.
*/
function cleared() {
setSearchResults([]);
setShowNotFoundMessage(false);
setShowAskWithAiButton(false);
if (!skipHighlightRef.current) {
mapsIndoorsInstance?.highlight?.([]);
}
skipHighlightRef.current = false;
if (selectedCategory) {
getFilteredLocations(selectedCategory);
}
setFilteredLocations([]);
// If keyboard is not null or undefined, clear the input field
if (!isNullOrUndefined(keyboardRef.current)) {
keyboardRef.current.clearInputField();
}
}
/**
* When search field is clicked, maximize the sheet size and set focus on the from field,
* and if the useKeyboard prop is present, show the onscreen keyboard.
* But wait for any bottom sheet transition to end before doing that to avoid content jumping when virtual keyboard appears.
*/
function searchFieldClicked() {
searchFieldRef.current.getInputField();
const sheet = searchRef.current.closest('.sheet');
if (sheet) {
sheet.addEventListener('transitionend', () => {
searchFieldRef.current.focusInput();
setIsInputFieldInFocus(true);
handleSearchChanged();
}, { once: true });
} else {
searchFieldRef.current.focusInput();
setIsInputFieldInFocus(true);
handleSearchChanged();
}
}
/**
* Handle hovering over location.
*
* @param {object} location
*/
function onMouseEnter(location) {
setHoveredLocation(location);
}
/**
* Handle locations clicked on the map.
*
* @param {object} location
*/
function onLocationClicked(location) {
// Set the current venue to be the selected location venue.
if (location.properties.venueId.toLowerCase() !== currentVenueName.toLowerCase()) {
setCurrentVenueName(location.properties.venueId);
setIsLocationClicked(true);
}
const currentFloor = mapsIndoorsInstance.getFloor();
const locationFloor = location.properties.floor;
// Set the floor to the one that the location belongs to.
if (locationFloor !== currentFloor) {
mapsIndoorsInstance.setFloor(locationFloor);
}
setTimeout(() => {
setCurrentLocation(location);
}, 500);
Promise.all([getBottomPadding(), getLeftPadding()]).then(([bottomPadding, leftPadding]) => {
mapsIndoorsInstance.goTo(location, {
maxZoom: 22,
padding: { bottom: bottomPadding, left: leftPadding, top: 0, right: 0 }
});
});
}
/**
* Get bottom padding when selecting a location.
* Calculate all cases depending on the kioskLocation id prop as well.
*/
function getBottomPadding() {
return new Promise((resolve) => {
if (isDesktop) {
if (kioskLocation) {
getDesktopPaddingBottom().then(padding => resolve(padding));
} else {
resolve(0);
}
} else {
resolve(200);
}
});
}
/**
* Get left padding when selecting a location.
* Calculate all cases depending on the kioskLocation id prop as well.
*/
function getLeftPadding() {
return new Promise((resolve) => {
if (isDesktop) {
if (kioskLocation) {
resolve(0);
} else {
getDesktopPaddingLeft().then(padding => resolve(padding));
}
} else {
resolve(0);
}
});
}
/**
* Calculate the CSS for the container based on context.
*/
function calculateContainerStyle() {
if (searchResults.length > 0) {
let maxHeight;
if (isDesktop) {
// On desktop-sized viewports, we want the container to have a max height of 60% of the Map Template.
maxHeight = document.querySelector('.mapsindoors-map').clientHeight * 0.6 + 'px';
} else {
// On mobile-sized viewports, take up all available space if needed.
maxHeight = '100%';
}
return { display: 'flex', flexDirection: 'column', maxHeight, overflow: 'hidden' };
}
}
/**
* Determines if categories should be shown under the search field in kiosk mode.
*
* @returns {boolean} True if in kiosk context and showCategoriesUnderSearch is enabled, otherwise false.
*/
function shouldShowCategoriesUnderSearch() {
// We determine wether to show categories horizontally or vertically based on the areHorizontalCategoriesEnabled setting.
// Each layout has different styling and thus needs to be treated as separate options.
return isKioskContext && areHorizontalCategoriesEnabled;
}
/*
* Monitors clicks to manage sheet size and input focus state
*/
useEffect(() => {
const SEARCH_FOCUS_ELEMENTS = ['.search__info', '.search__back-button', '.categories', '.sheet__content'];
// We want to ignore: Floor Selector, View Mode Switch, My Position, View Selector, Mapbox zoom controls and Google Maps zoom controls
const IGNORE_CLOSE_ELEMENTS = ['.mi-floor-selector', '.view-mode-switch', '.mi-my-position', '.view-selector__toggle-button', '.building-list', '.mapboxgl-ctrl-bottom-right', '.gmnoprint', '.language-selector-portal'];
const handleSearchFieldFocus = (event) => {
const clickedInsideSearchArea = SEARCH_FOCUS_ELEMENTS.some(selector =>
event.target.closest(selector)
);
const clickedInsideIgnoreArea = IGNORE_CLOSE_ELEMENTS.some(selector =>
event.target.closest(selector)
);
const clickedInsideResults = event.target.closest('.search__results');
if (clickedInsideSearchArea) {
setSize(snapPoints.MAX);
requestAnimationFrameId.current = requestAnimationFrame(() => { // we use a requestAnimationFrame to ensure that the size change is applied before the focus (meaning that categories are rendered)
setIsInputFieldInFocus(true);
handleSearchChanged();
});
} else if (!clickedInsideResults && !clickedInsideIgnoreArea) {
setIsInputFieldInFocus(false);
setShowAskWithAiButton(false);
setSize(snapPoints.MIN);
setSelectedCategory(null);
setSearchResults([]);
setFilteredLocations([]);
selectedCategoriesArray.current = [];
}
};
if (isOpen) {
requestAnimationFrameId.current = requestAnimationFrame(() => { // we use a requestAnimationFrame to ensure that the click is not registered too early (while other sheets are still "active")
document.addEventListener('click', handleSearchFieldFocus);
});
} else {
document.removeEventListener('click', handleSearchFieldFocus);
}
return () => {
document.removeEventListener('click', handleSearchFieldFocus);
if (requestAnimationFrameId.current) {
cancelAnimationFrame(requestAnimationFrameId.current);
}
}
}, [isOpen]);
/*
* Sets currently hovered location.
*/
useEffect(() => {
return () => {
setHoveredLocation();
}
}, []);
/*
* Reset search state when Search component opens to ensure it starts in default state.
* This is particularly important when returning from directions/wayfinding.
* Only reset if there's stale state (results or category tree) without a selected category
*/
useEffect(() => {
// Only reset if Search is open, no category selected, but stale data exists
if (isOpen && !selectedCategory) {
// Reset search results and filtered locations
setSearchResults([]);
setFilteredLocations([]);
setShowNotFoundMessage(false);
// Clear the category selection tree
selectedCategoriesArray.current = [];
}
}, [isOpen, selectedCategory]);
/*
* React on changes in the venue prop.
* Deselect category and clear results list.
*/
useEffect(() => {
if (selectedCategory && currentVenueName !== initialVenueName) {
setSearchResults([]);
setSelectedCategory(null);
}
}, [currentVenueName]);
/*
* React on changes in the app language. Any existing category search needs to update with translated Locations.
*/
useEffect(() => {
if (selectedCategory) {
window.mapsindoors.services.LocationsService.once('update_completed', () => {
searchFieldRef.current.triggerSearch();
});
}
}, [currentLanguage]);
/*
* Handle location hover.
*/
useEffect(() => {
mapsIndoorsInstance?.on('mouseenter', onMouseEnter);
return () => {
mapsIndoorsInstance?.off('mouseenter', onMouseEnter);
}
}, [mapsIndoorsInstance]);
/*
* Setup scroll buttons to scroll in search results list when in kiosk mode.
*/
useEffect(() => {
if (isOpen && isKioskContext && searchResults.length > 0) {
const searchResultsElement = document.querySelector('.mapsindoors-map .search__results');
scrollButtonsRef.current.scrollContainerElementRef = searchResultsElement;
}
}, [searchResults, isOpen]);
/*
* When useKeyboard parameter is present, add click event listener which determines when the keyboard should be shown or not.
*/
useEffect(() => {
if (useKeyboard) {
const onClick = (event) => {
// Use the closest() method to check if the element that has been clicked traverses the element and its parents
// until it finds a node that matches the 'mi-keyboard' selector.
// If the user clicks on the keyboard or the search fields, the keyboard should stay visible.
if (event.target.closest('mi-keyboard') ||
event.target.tagName.toUpperCase() === 'MI-SEARCH' ||
event.target.tagName.toUpperCase() === 'INPUT') {
setIsKeyboardVisible(true)
} else {
setIsKeyboardVisible(false);
}
};
window.addEventListener('click', onClick, false);
return () => {
window.removeEventListener('click', onClick, false);
};
}
}, [useKeyboard]);
/*
* React on changes in the selected category state.
* If the selected category is present, get the filtered locations based on the selected category.
*/
useEffect(() => {
if (selectedCategory) {
getFilteredLocations(selectedCategory);
}
}, [selectedCategory]);
/*
* Get the legend sections and determine
* If the legend button should be shown.
*/
useEffect(() => {
if (kioskLocation) {
setShowLegendButton(legendSections.length > 0);
}
}, [kioskLocation]);
/**
*
*/
useEffect(() => {
const childKeys = categories.find(([key]) => key === selectedCategory)?.[1]?.childKeys || [];
setChildKeys(childKeys)
}, [categories, selectedCategory]);
/*
* Get app config and determine if categories should be shown under the search field in kiosk mode.
*/
useEffect(() => {
setAreHorizontalCategoriesEnabled(appConfig?.appSettings?.areHorizontalCategoriesEnabled === true || appConfig?.appSettings?.areHorizontalCategoriesEnabled === 'true');
}, [appConfig]);
/**
* Reset component state when search view is opened (returns from other views).
* Since the component is never unmounted, we need to manually reset state.
*/
useEffect(() => {
if (isOpen) {
// Reset local state to initial values
setShowNotFoundMessage(false);
setIsInputFieldInFocus(false);
setShowAskWithAiButton(false);
//setSearchDisabled(true);
// Clear search results to show fresh state
setSearchResults([]);
// Clear search field if needed
if (searchFieldRef.current) {
skipHighlightRef.current = true;
searchFieldRef.current.clear();
}
}
}, [isOpen, setSearchResults]);
/**
* Handle Enter key press on search input field to open chat when "Ask with AI" button is visible.
*/
useEffect(() => {
if (!isAiChatEnabled || !searchInput || !isInputFieldInFocus || !showAskWithAiButton) {
return;
}
const handleKeyDown = (event) => {
if (event.key === 'Enter' && onOpenChat) {
event.preventDefault();
const searchValue = (event.target?.value || searchInput?.value || '').trim();
if (searchValue) {
setInitialMessage(searchValue);
if (searchFieldRef.current) {
skipHighlightRef.current = true;
searchFieldRef.current.clear();
}
onOpenChat();
}
}
};
searchInput.addEventListener('keydown', handleKeyDown);
return () => {
if (searchInput) {
searchInput.removeEventListener('keydown', handleKeyDown);
}
};
}, [isAiChatEnabled, searchInput, isInputFieldInFocus, showAskWithAiButton, onOpenChat, setInitialMessage]);
return (
<div className="search"
ref={searchRef}
style={calculateContainerStyle()}>
{ /* Search info which includes legend button if in a Kiosk context. */}
<div className="search__info" style={{ gridTemplateColumns: isKioskContext && showLegendButton ? 'min-content 1fr min-content' : '1fr min-content' }}>
{isKioskContext && showLegendButton && <button className="search__legend" onClick={() => setShowLegendDialog(true)} aria-label={t('Show legend')}><Legend /></button>}
{ /* Search field that allows users to search for locations (MapsIndoors Locations and external) */}
<label className="search__label">
<span>{t('Search by name, category, building...')}</span>
<SearchField
ref={searchFieldRef}
mapsindoors={true}
placeholder={t('Search by name, category, building...')}
results={locations => onResults(locations)}
clicked={() => searchFieldClicked()}
cleared={() => cleared()}
changed={() => handleSearchChanged()}
category={selectedCategory}
disabled={!isOpen} // Disabled when not open to prevent content jumping, enabled when open for keyboard accessibility
/>
</label>
</div>
{/* Only show when AI chat is enabled, input is in focus and has more than 5 characters */}
{isAiChatEnabled && isInputFieldInFocus && showAskWithAiButton && (
<button
className="search__ask-ai-button"
style={{ '--ask-ai-button-primary-color': primaryColor }}
onClick={(e) => {
e.stopPropagation();
if (onOpenChat) {
const searchValue = (searchInput?.value || searchFieldRef.current?.getValue() || '').trim();
if (searchValue) {
setInitialMessage(searchValue);
if (searchFieldRef.current) {
skipHighlightRef.current = true;
searchFieldRef.current.clear();
}
onOpenChat();
}
}
}} type="button" aria-label={t('Ask with AI')} title={t('Ask with AI')}>
<AskWithAiIcon />
{t('Ask with AI')}
</button>
)}
{/* Vertical list of Categories */}
{/* Show full category list if (kiosk mode and showCategoriesUnderSearch is true) OR input is in focus, and only when searchResults are empty */}
{(shouldShowCategoriesUnderSearch() || isInputFieldInFocus) && !showNotFoundMessage && categories.length > 0 && searchResults.length === 0 && (
<Categories
onSetSize={onSetSize}
searchFieldRef={searchFieldRef}
getFilteredLocations={(category) => getFilteredLocations(category)}
isOpen={!!selectedCategory}
topLevelCategory={true}
categoryOrientation={areHorizontalCategoriesEnabled ? 'horizontal' : 'vertical'}
/>
)}
{/* Message shown if no search results were found or if the ask with AI button is shown */}
{!showAskWithAiButton && showNotFoundMessage && <p className="search__error"> {t('Nothing was found')}</p>}
{/* When search results are found (category is selected or search term is used) */}
{searchResults.length > 0 && (
<div className={`search__results prevent-scroll${isKioskContext ? ' search__results--kiosk' : ''}`} {...scrollableContentSwipePrevent}>
{/* Subcategories should only show if a top level category is selected and if that top level category has any childKeys */}
{selectedCategory && (
<Categories
handleBack={handleBack}
getFilteredLocations={(category) => getFilteredLocations(category)}
onLocationClicked={onLocationClicked}
childKeys={childKeys}
topLevelCategory={false}
selectedCategoriesArray={selectedCategoriesArray}
categoryOrientation={areHorizontalCategoriesEnabled ? 'horizontal' : 'vertical'}
/>
)}
{/* Show locations when there are any searchResults */}
{getSortedSearchResults(searchResults).map(location =>
<ListItemLocation
key={location.id}
location={location}
locationClicked={() => onLocationClicked(location)}
isHovered={location?.id === hoveredLocation?.id}
/>
)}
</div>
)}
{ /* Keyboard */}
{isKeyboardVisible && isDesktop && <Keyboard ref={keyboardRef} searchInputElement={searchInput}></Keyboard>}
{ /* Buttons to scroll in the list of search results if in kiosk context */}
{isOpen && isKioskContext && searchResults.length > 0 && createPortal(
<div className="search__scroll-buttons">
<mi-scroll-buttons ref={scrollButtonsRef}></mi-scroll-buttons>
</div>,
document.querySelector('.mapsindoors-map')
)}
</div>
)
}
export default Search;