Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SearchBox: Refactoring and searchable stars #552

Merged
merged 7 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/components/Map/behaviour/PersistedScaleControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { isImperial, toggleImperial } from '../../helpers';

// https://github.com/maplibre/maplibre-gl-js/blob/afe4377706429a6b4e708e62a3c39a795ae8f28e/src/ui/control/scale_control.js#L36-L83

class ClickableScaleControl extends (ScaleControl as any) {
private onClick;
class ClickableScaleControl extends ScaleControl {
private onClick: () => void;

private getHoverText;
private getHoverText: () => string;
Dlurak marked this conversation as resolved.
Show resolved Hide resolved

constructor({ onClick, getHoverText, ...options }) {
super(options);
Expand Down
62 changes: 23 additions & 39 deletions src/components/SearchBox/AutocompleteInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,49 @@ import { onSelectedFactory } from './onSelectedFactory';
import { useUserThemeContext } from '../../helpers/theme';
import { useMapStateContext } from '../utils/MapStateContext';
import { onHighlightFactory } from './onHighlightFactory';
import { buildPhotonAddress } from './options/geocoder';
import { useMapCenter } from './utils';
import { getOptionLabel, useMapCenter } from './utils';
import { useSnackbar } from '../utils/SnackbarContext';
import { useKeyDown } from '../../helpers/hooks';
import { Option } from './types';

const useFocusOnSlash = () => {
const SearchBoxInput = ({ params, setInputValue, autocompleteRef }) => {
const inputRef = React.useRef<HTMLInputElement>(null);

useEffect(() => {
const onKeydown = (e) => {
if (e.key === '/') {
e.preventDefault();
inputRef.current?.focus();
}
};
window.addEventListener('keydown', onKeydown);

return () => {
window.removeEventListener('keydown', onKeydown);
};
}, []);

return inputRef;
};
useKeyDown('/', (e) => {
e.preventDefault();
inputRef.current?.focus();
});
Dlurak marked this conversation as resolved.
Show resolved Hide resolved

const SearchBoxInput = ({ params, setInputValue, autocompleteRef }) => {
// const inputRef = useFocusOnSlash();
const { InputLabelProps, InputProps, ...restParams } = params;

useEffect(() => {
// @ts-ignore
params.InputProps.ref(autocompleteRef.current);
}, []); // eslint-disable-line react-hooks/exhaustive-deps

const onChange = (e) => setInputValue(e.target.value);
const onFocus = (e) => e.target.select();

return (
<InputBase
{...restParams} // eslint-disable-line react/jsx-props-no-spreading
sx={{
height: '47px',
}}
// inputRef={inputRef}
inputRef={inputRef}
placeholder={t('searchbox.placeholder')}
onChange={onChange}
onFocus={onFocus}
onChange={({ target }) => setInputValue(target.value)}
onFocus={({ target }) => target.select()}
/>
);
};

export const AutocompleteInput = ({
type AutocompleteInputProps = {
inputValue: string;
setInputValue: (value: string) => void;
options: Option[];
autocompleteRef: React.MutableRefObject<undefined>;
setOverpassLoading: React.Dispatch<React.SetStateAction<boolean>>;
Dlurak marked this conversation as resolved.
Show resolved Hide resolved
};

export const AutocompleteInput: React.FC<AutocompleteInputProps> = ({
inputValue,
setInputValue,
options,
Expand All @@ -75,16 +67,8 @@ export const AutocompleteInput = ({
options={options}
// we need null to be able to select the same again (eg. category search)
value={null}
filterOptions={(x) => x}
getOptionLabel={(option) =>
option.properties?.name ||
option.preset?.presetForSearch?.name ||
option.overpass?.inputValue ||
(option.star && option.star.label) ||
(option.loader && '') ||
(option.properties && buildPhotonAddress(option.properties)) ||
''
}
filterOptions={(o) => o}
getOptionLabel={getOptionLabel}
Dlurak marked this conversation as resolved.
Show resolved Hide resolved
getOptionKey={(option) => JSON.stringify(option)}
onChange={onSelectedFactory(
setFeature,
Expand All @@ -94,7 +78,7 @@ export const AutocompleteInput = ({
setOverpassLoading,
)}
onHighlightChange={onHighlightFactory(setPreview)}
getOptionDisabled={(o) => o.loader}
getOptionDisabled={(o) => o.type === 'loader'}
autoComplete
disableClearable
autoHighlight
Expand Down
4 changes: 2 additions & 2 deletions src/components/SearchBox/SearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { useInputValueState } from './options/geocoder';
import { useOptions } from './useOptions';
import { HamburgerMenu } from '../Map/TopMenu/HamburgerMenu';
import { UserMenu } from '../Map/TopMenu/UserMenu';
import { Option } from './types';
Dlurak marked this conversation as resolved.
Show resolved Hide resolved

const TopPanel = styled.div<{ $isMobileMode: boolean }>`
position: absolute;
Expand Down Expand Up @@ -76,12 +77,11 @@ const SearchBox = () => {
const isMobileMode = useMobileMode();
const { featureShown } = useFeatureContext();
const { inputValue, setInputValue } = useInputValueState();
const [options, setOptions] = useState([]);
const [overpassLoading, setOverpassLoading] = useState(false);
const autocompleteRef = useRef();
const onClosePanel = useOnClosePanel();

useOptions(inputValue, setOptions);
const options = useOptions(inputValue);
Dlurak marked this conversation as resolved.
Show resolved Hide resolved

return (
<TopPanel $isMobileMode={isMobileMode}>
Expand Down
35 changes: 19 additions & 16 deletions src/components/SearchBox/onHighlightFactory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Feature } from '../../services/types';
import { GeocoderOption, Option } from './types';

const getElementType = (osmType) => {
const getElementType = (osmType: string) => {
switch (osmType) {
case 'R':
return 'relation';
Expand All @@ -13,9 +14,9 @@ const getElementType = (osmType) => {
}
};

export const getSkeleton = (option): Feature => {
const center = option.geometry.coordinates;
const { osm_id: id, osm_type: osmType, name } = option.properties;
export const getSkeleton = ({ geocoder }: GeocoderOption): Feature => {
const center = geocoder.geometry.coordinates;
const { osm_id: id, osm_type: osmType, name } = geocoder.properties;
const type = getElementType(osmType);
const [lon, lat] = center;

Expand All @@ -24,20 +25,22 @@ export const getSkeleton = (option): Feature => {
skeleton: true,
nonOsmObject: false,
osmMeta: { type, id: parseInt(id, 10) },
center: [parseFloat(lon), parseFloat(lat)],
center: [parseFloat(`${lon}`), parseFloat(`${lat}`)],
Dlurak marked this conversation as resolved.
Show resolved Hide resolved
tags: { name },
properties: { class: option.class, subclass: '' },
properties: { class: geocoder.properties.class, subclass: '' },
};
};

export const onHighlightFactory = (setPreview) => (e, option) => {
if (option?.star?.center) {
const { center } = option.star;
setPreview({ center });
return;
}
export const onHighlightFactory =
(setPreview: (feature: unknown) => void) => (_: never, option: Option) => {
if (!option) return;
if (option.type === 'star' && option.star.center) {
const { center } = option.star;
setPreview({ center });
return;
}

if (option?.geometry?.coordinates) {
setPreview(getSkeleton(option));
}
};
if (option.type === 'geocoder' && option.geocoder.geometry?.coordinates) {
setPreview(getSkeleton(option));
}
};
70 changes: 45 additions & 25 deletions src/components/SearchBox/onSelectedFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,28 @@ import { performOverpassSearch } from '../../services/overpassSearch';
import { t } from '../../services/intl';
import { fitBounds } from './utils';
import { getSkeleton } from './onHighlightFactory';
import { SnackbarContextType } from '../utils/SnackbarContext';
import { Severity } from '../utils/SnackbarContext';
import { addOverpassQueryHistory } from './options/overpass';
import { Feature } from '../../services/types';
import { Bbox } from '../utils/MapStateContext';
import {
GeocoderOption,
Option,
OverpassOption,
PresetOption,
StarOption,
} from './types';

const overpassOptionSelected = (
option,
setOverpassLoading,
bbox,
showToast: SnackbarContextType['showToast'],
option: OverpassOption | PresetOption,
setOverpassLoading: React.Dispatch<React.SetStateAction<boolean>>,
bbox: Bbox,
showToast: (message: string, severity?: Severity) => void,
) => {
const tagsOrQuery =
option.preset?.presetForSearch.tags ??
option.overpass.tags ??
option.overpass.query;
option.type === 'preset'
? option.preset?.presetForSearch.tags
: (option.overpass.tags ?? option.overpass.query);

const timeout = setTimeout(() => {
setOverpassLoading(true);
Expand All @@ -31,7 +40,7 @@ const overpassOptionSelected = (
showToast(content);
getOverpassSource()?.setData(geojson);

if (option.overpass?.query) {
if (option.type === 'overpass') {
addOverpassQueryHistory(option.overpass.query);
}
})
Expand All @@ -47,13 +56,18 @@ const overpassOptionSelected = (
});
};

const starOptionSelected = (option) => {
const apiId = getApiId(option.star.shortId);
const starOptionSelected = ({ star }: StarOption) => {
const apiId = getApiId(star.shortId);
Router.push(`/${getUrlOsmId(apiId)}`);
};

const geocoderOptionSelected = (option, setFeature) => {
if (!option?.geometry?.coordinates) return;
type SetFeature = (feature: Feature | null) => void;

const geocoderOptionSelected = (
option: GeocoderOption,
setFeature: SetFeature,
) => {
if (!option?.geocoder.geometry?.coordinates) return;

const skeleton = getSkeleton(option);
console.log('Search item selected:', { location: option, skeleton }); // eslint-disable-line no-console
Expand All @@ -66,19 +80,25 @@ const geocoderOptionSelected = (option, setFeature) => {
};

export const onSelectedFactory =
(setFeature, setPreview, bbox, showToast, setOverpassLoading) =>
(_, option) => {
(
setFeature: SetFeature,
setPreview: SetFeature,
bbox: Bbox,
showToast: (message: string, severity?: Severity) => void,
setOverpassLoading: React.Dispatch<React.SetStateAction<boolean>>,
) =>
(_: never, option: Option) => {
setPreview(null); // it could be stuck from onHighlight

if (option.star) {
starOptionSelected(option);
return;
switch (option.type) {
case 'star':
starOptionSelected(option);
break;
case 'overpass':
case 'preset':
overpassOptionSelected(option, setOverpassLoading, bbox, showToast);
break;
case 'geocoder':
geocoderOptionSelected(option, setFeature);
}

if (option.overpass || option.preset) {
overpassOptionSelected(option, setOverpassLoading, bbox, showToast);
return;
}

geocoderOptionSelected(option, setFeature);
};
40 changes: 31 additions & 9 deletions src/components/SearchBox/options/geocoder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import { getPoiClass } from '../../../services/getPoiClass';
import Maki from '../../utils/Maki';
import { fetchJson } from '../../../services/fetch';
import { intl } from '../../../services/intl';
import { Theme } from '../../../helpers/theme';
import { GeocoderOption, Option, PresetOption } from '../types';
import { MapCenter } from '../../../services/types';
import { View } from '../../utils/MapStateContext';

const PHOTON_SUPPORTED_LANGS = ['en', 'de', 'fr'];

const getApiUrl = (inputValue, view) => {
const getApiUrl = (inputValue: string, view: View) => {
const [zoom, lat, lon] = view;
const lvl = Math.max(0, Math.min(16, Math.round(zoom)));
const lvl = Math.max(0, Math.min(16, Math.round(parseFloat(zoom))));
const q = encodeURIComponent(inputValue);
const lang = intl.lang in PHOTON_SUPPORTED_LANGS ? intl.lang : 'default';
return `https://photon.komoot.io/api/?q=${q}&lon=${lon}&lat=${lat}&zoom=${lvl}&lang=${lang}`;
Expand All @@ -25,19 +29,25 @@ export const useInputValueState = () => {
const [inputValue, setInputValue] = useState('');
return {
inputValue,
setInputValue: useCallback((value) => {
setInputValue: useCallback((value: string) => {
currentInput = value;
setInputValue(value);
}, []),
};
};

export const fetchGeocoderOptions = debounce(
async (inputValue, view, setOptions, before, after) => {
async (
inputValue: string,
view: View,
setOptions: React.Dispatch<React.SetStateAction<Option[]>>,
before: PresetOption[],
after: PresetOption[],
) => {
try {
const searchResponse = await fetchJson(getApiUrl(inputValue, view), {
const searchResponse = (await fetchJson(getApiUrl(inputValue, view), {
abortableQueueName: GEOCODER_ABORTABLE_QUEUE,
});
})) as { features: GeocoderOption['geocoder'][] };
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would feel more straight forward, if we started with type PhotonResponse and derive the GeocoderOption from it.

Ideally i would expect a line like this:

const searchResponse = await fetchJson<PhotonResponse>(url, options);

If you agree, you may do it in this PR, another one, or I may do it later myself. 🙂


// This blocks rendering of old result, when user already changed input
if (inputValue !== currentInput) {
Expand All @@ -46,7 +56,14 @@ export const fetchGeocoderOptions = debounce(

const options = searchResponse?.features || [];

setOptions([...before, ...options, ...after]);
setOptions([
...before,
...options.map((feature) => ({
type: 'geocoder' as const,
geocoder: feature,
})),
...after,
]);
} catch (e) {
if (!(e instanceof DOMException && e.name === 'AbortError')) {
throw e;
Expand Down Expand Up @@ -123,8 +140,13 @@ export const buildPhotonAddress = ({
},
];
*/
export const renderGeocoder = (option, currentTheme, inputValue, mapCenter) => {
const { geometry, properties } = option;
export const renderGeocoder = (
{ geocoder }: GeocoderOption,
currentTheme: Theme,
inputValue: string,
mapCenter: MapCenter,
) => {
const { geometry, properties } = geocoder;
const { name, osm_key: tagKey, osm_value: tagValue } = properties;

const distance = getHumanDistance(mapCenter, geometry.coordinates);
Expand Down
Loading
Loading