Skip to content

Commit

Permalink
Add new feature for promting user for location when non given and get…
Browse files Browse the repository at this point in the history
…ting directions
  • Loading branch information
devcshort committed Dec 6, 2023
1 parent 2c38e95 commit ec1877b
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 30 deletions.
33 changes: 30 additions & 3 deletions packages/client/components/molecules/LocationAutocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,34 @@ import {
import { useTranslation } from 'next-i18next';
import { useAppConfig } from '../../lib/hooks/useAppConfig';
import { usePrevUrl } from '../../lib/hooks/usePrevUrl';
import { create } from 'zustand';

type Props = Partial<AutocompleteProps> &
RefAttributes<HTMLInputElement> & { defaultCoords?: string };

type LocationStore = {
location: string;
coords: string;
setLocation: (location: string) => void;
setCoords: (coords: string) => void;
};
export const useLocationStore = create<LocationStore>((set) => ({
location: '',
coords: '',
setLocation: (location: string) => set({ location }),
setCoords: (coords: string) => set({ coords }),
}));

export function LocationAutocomplete(props: Props) {
const theme = useMantineTheme();
const appConfig = useAppConfig();
const prevUrl = usePrevUrl();
const [isLoading, toggle] = useToggle([false, true]);
const [value, setValue] = useInputState(props?.defaultValue ?? '');
const {
location: value,
setLocation: setValue,
setCoords,
} = useLocationStore();
const [debounced] = useDebouncedValue(value, 200);
const [suggestions, setSuggestions] = useState<any[]>([]);
const hiddenInputRef = useRef<HTMLInputElement>(null);
Expand All @@ -42,6 +60,7 @@ export function LocationAutocomplete(props: Props) {
const handleItemSubmit = (e: any) => {
if (hiddenInputRef.current) {
setCookie(null, USER_PREF_COORDS, e.coordinates, { path: '/' });
setCoords(e.coordinates);
hiddenInputRef.current.value = e.coordinates;
}
};
Expand Down Expand Up @@ -69,6 +88,7 @@ export function LocationAutocomplete(props: Props) {
setCookie(null, USER_PREF_LOCATION, data.address, { path: '/' });
if (hiddenInputRef.current) {
setCookie(null, USER_PREF_COORDS, `${lng},${lat}`, { path: '/' });
setCoords(`${lng},${lat}`);
hiddenInputRef.current.value = `${lng},${lat}`;
}
} catch (err) {
Expand All @@ -82,7 +102,7 @@ export function LocationAutocomplete(props: Props) {

toggle(false);
},
[setValue, toggle, t]
[setValue, toggle, t, setCoords]
);

const getUserLocation = useCallback(() => {
Expand Down Expand Up @@ -135,6 +155,12 @@ export function LocationAutocomplete(props: Props) {
})();
}, [debounced, t]);

useEffect(() => {
if (props.defaultValue) {
setValue(props.defaultValue);
}
}, [props.defaultValue, setValue]);

useEffect(() => {
function routeChangeCompleteHandler(e: any) {
const prevQuery = prevUrl?.split('?')[1];
Expand All @@ -155,6 +181,7 @@ export function LocationAutocomplete(props: Props) {

if (hiddenInputRef.current) {
hiddenInputRef.current.value = newCoords || '';
setCoords(newCoords || '');
}
}
}
Expand All @@ -164,7 +191,7 @@ export function LocationAutocomplete(props: Props) {
return () => {
router.events.off('routeChangeComplete', routeChangeCompleteHandler);
};
}, [router.events, value, setValue, prevUrl]);
}, [router.events, value, setValue, prevUrl, setCoords]);

return (
<>
Expand Down
16 changes: 8 additions & 8 deletions packages/client/components/molecules/Result.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ export function Result(props: Props) {
const handleDirectionsClick = (e: any) => {
const coords = props?.location?.coordinates ? props?.coordinates : null;
if (coords?.length === 0) {
// e.preventDefault();
// openContextModal({
// modal: 'update-location',
// centered: true,
// innerProps: {
// serviceAtLocationId: props.id,
// },
// });
e.preventDefault();
openContextModal({
modal: 'update-location',
centered: true,
innerProps: {
location: props.location,
},
});
}
};

Expand Down
30 changes: 17 additions & 13 deletions packages/client/components/organisms/modals/UpdateLocation.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { Button, Group, Text } from '@mantine/core';
import { ContextModalProps } from '@mantine/modals';
import { useTranslation } from 'next-i18next';
import { LocationAutocomplete } from '../../molecules/LocationAutocomplete';
import {
LocationAutocomplete,
useLocationStore,
} from '../../molecules/LocationAutocomplete';
import { ReferralButton } from '../../atoms/ReferralButton';

type Props = ContextModalProps;
type Props = ContextModalProps<{ location: { coordinates: string } }>;

export function UpdateLocation(props: Props) {
const { t } = useTranslation('common');
const coords = useLocationStore((state) => state.coords);

return (
<>
<Text>What&apos;s your starting location?</Text>
<Text>{t('update_location.prompt_start_location')}</Text>

<LocationAutocomplete />

Expand All @@ -22,25 +26,25 @@ export function UpdateLocation(props: Props) {
>
{t('call_to_action.cancel')}
</Button>
{/* <ReferralButton
<ReferralButton
referralType="directions_referral"
resourceId={props.id}
resource={props}
fullWidth
target="_blank"
href={`https://www.google.com/maps/dir/?api=1&origin=${
props.coordinates
}&destination=${
props?.location?.coordinates
? Array.from(props?.location?.coordinates).reverse().join(',')
href={`https://www.google.com/maps/dir/?api=1&origin=${coords
.split(',')
.reverse()
.join(',')}&destination=${
props?.innerProps?.location?.coordinates
? Array.from(props?.innerProps?.location?.coordinates)
.reverse()
.join(',')
: ''
}`}
size="xs"
leftIcon={<IconNavigation size={props.theme.fontSizes.lg} />}
onClick={handleDirectionsClick}
>
{t('call_to_action.get_directions')}
</ReferralButton> */}
</ReferralButton>
</Group>
</>
);
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/ar/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "فشل إرسال الرسائل القصيرة",
"sms_send_failed_body": "فشل إرسال رسالتك."
},
"prompt_auth": "الرجاء تسجيل الدخول لاستخدام هذه الميزة."
"prompt_auth": "الرجاء تسجيل الدخول لاستخدام هذه الميزة.",
"update_location": {
"prompt_start_location": "ما هو موقع انطلاقك؟"
}
},
"data_providers": {
"provided_by": "البيانات المقدمة من"
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "SMS send failed",
"sms_send_failed_body": "Your message failed to send."
},
"prompt_auth": "Please login to use this feature."
"prompt_auth": "Please login to use this feature.",
"update_location": {
"prompt_start_location": "What's your starting location?"
}
},
"data_providers": {
"provided_by": "Data provided by"
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/es/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "Envío de SMS fallido",
"sms_send_failed_body": "Su mensaje no se pudo enviar."
},
"prompt_auth": "Inicia sesión para utilizar esta función."
"prompt_auth": "Inicia sesión para utilizar esta función.",
"update_location": {
"prompt_start_location": "¿Cuál es tu punto de partida?"
}
},
"data_providers": {
"provided_by": "Datos proporcionados por"
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/ne/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "SMS पठाउन सकिएन",
"sms_send_failed_body": "तपाईंको सन्देश पठाउन असफल भयो।"
},
"prompt_auth": "कृपया यो सुविधा प्रयोग गर्न लगइन गर्नुहोस्।"
"prompt_auth": "कृपया यो सुविधा प्रयोग गर्न लगइन गर्नुहोस्।",
"update_location": {
"prompt_start_location": "तपाईंको प्रारम्भिक स्थान के हो?"
}
},
"data_providers": {
"provided_by": "द्वारा प्रदान गरिएको डाटा"
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/so/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "Diritaanka SMS waa guul daraystay",
"sms_send_failed_body": "Fariintaadu waa ku guul daraystay in ay dirto"
},
"prompt_auth": "Fadlan gal si aad u isticmaasho sifadan"
"prompt_auth": "Fadlan gal si aad u isticmaasho sifadan",
"update_location": {
"prompt_start_location": "Waa maxay goobtaadu?"
}
},
"data_providers": {
"provided_by": "Xogta ay bixiyeen"
Expand Down
5 changes: 4 additions & 1 deletion packages/client/public/locales/vi/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"sms_send_failed_title": "Gửi tin nhắn SMS không thành công",
"sms_send_failed_body": "Tin nhắn của bạn không gửi được."
},
"prompt_auth": "Vui lòng đăng nhập để sử dụng tính năng này."
"prompt_auth": "Vui lòng đăng nhập để sử dụng tính năng này.",
"update_location": {
"prompt_start_location": "Vị trí xuất phát của bạn là gì?"
}
},
"data_providers": {
"provided_by": "Dữ liệu được cung cấp bởi"
Expand Down

0 comments on commit ec1877b

Please sign in to comment.