ToolJet/frontend/src/Editor/Components/Map/Map.jsx
Kavin Venkatachalam 7f702c1d6b
[Feature]: Added Localisation (#3746)
* Added localisation

* Closed modal after language selection

* updated transaltaion setup

* Updated language tooltip

* Added fallback language support

* Adding english library resource for translation (#3844)

* Adding English dictionary for the widget lists in the inspector

* added leftSideBar object in en.json and implemented it for leftSidebar icon text

* renamed leftSideBar to leftSidebar and added resources for tip in the left side bar

* added english translation resources for leftsidebar debugger

* added english language resources for the global settings

* added english language resources for data sources in left sidebar

* added english language resources for the share button and share modal in the editor

* added english language resources for release button, manageOrgUsers, appVersionManager

* added english language resources for Queries and Please select a widget to inspect in the editor

* added english language resources for data source list , data source manager, and query manager(partially)

* added english language resources for queryManager, transformation, preview

* added english language resources for dark mode toggle in the headers inside homepage

* added fallback message for dark mode toggle

* added resources for language change in the headers inside homepage

* added resources for notification center in the header inside homepage

* added resources for organization and manage users components in header inside homepage

* added resources in manageGroupPermission

* added resources for manageGroupPermissionsResources component

* added resources for manageSSO and generalSettings components

* added resources for google sso

* added resources for github sso

* added resources for environment variables in manageSSO

* added resources for profile and setting page

* added resources for app card and app card menu

* added resources for folder section and app list in homepage

* added resources for header section in the homepage

* added resources for pagination in homepage

* added resources for modals in the homepage

* added resources for blank page

* added resources for login page

* added resources for forgot password page

* added resources for sign up page

* added resources for onBoarding component

* added resources for reset password page

* deleted duplicate key for readDocumentation

* deleted duplicate key for cancel in en.json and added translation for cancel at few places

* removing duplicate copy of save key in en.json

* added translation for CommentActions.jsx components

* deleted duplicate copy of search key in en.json and added resources for create and search queries , select keys

* fix typo errors

* fixed typo errors

* shorten the key for loginAndSignUpAndForgotPassword to loginSignupPage in en.json file and related files

* shorten the key noLoginMethodsEnabledForThisWorkspace to noLoginMethodsEnabled

* shorten the key pleaseCheckYourEmailForConfirmationLink to emailConfirmLink

* shorten the key dontHaveAccountYet to dontHaveAccount

* shorten keys from loginSignupPage key in en.json

* shorten keys of shareModal nested object in en.json

* shorten the key in appVersionManager nested object

* shorten the keys for queryManager nested object in the en.json

* delete duplicate copy of environmentVar and shorten manageEnvironmentVariables,environmentVariables

* shorten keys in the organization nested object

* shorten keys in the homePage nested object in en.json file

* added inspector and eventManager empty object

* added resources to RedirectSSO component

* added resources for OAuth2

* added resources for TemplateCard.jsx

* added resources for TemplateLibraryModal.jsx

* added resources for ConfirmationPage.jsx

* added resources for ConfirmationPage component

* removed translation in App.jsx file

* added resources for Slack.jsx

* added resources for GoogleSheets.jsx

* added resources for CodeBuilder.jsx

* added resources for CommentBody and CommentFooter

* added resources for TestConnection component

* added resources for AllignButton.jsx

* added resources for Openapi and Stripe components

* added resources for ErrorBoundary

* added resources for Viewer.jsx

* Translation for widgets, table

Co-authored-by: Kavin Venkatachalam <kavin.saratha@gmail.com>

* Commented Language selection

* Fixed typos

* Updated fr.json file

Co-authored-by: Manish Kushare <kushare.manish9@gmail.com>
2022-09-14 13:34:49 +05:30

186 lines
5.9 KiB
JavaScript

import React, { useState, useCallback, useEffect } from 'react';
import { GoogleMap, LoadScript, Marker, Autocomplete } from '@react-google-maps/api';
import { resolveReferences, resolveWidgetFieldValue } from '@/_helpers/utils';
import { darkModeStyles } from './styles';
import { useTranslation } from 'react-i18next';
export const Map = function Map({
id,
width,
height,
component,
darkMode,
onComponentClick,
currentState,
onComponentOptionChanged,
onComponentOptionsChanged,
onEvent,
// canvasWidth,
registerAction,
}) {
const center = component.definition.properties.initialLocation.value;
const defaultMarkerValue = component.definition.properties.defaultMarkers.value;
const { t } = useTranslation();
let defaultMarkers = [];
try {
defaultMarkers = defaultMarkerValue;
} catch (err) {
console.log(err);
}
const addNewMarkersProp = component.definition.properties.addNewMarkers;
const canAddNewMarkers = addNewMarkersProp ? resolveReferences(addNewMarkersProp.value, currentState) : false;
const canSearchProp = component.definition.properties.canSearch;
const canSearch = canSearchProp ? resolveReferences(canSearchProp.value, currentState) : false;
const widgetVisibility = component.definition.styles?.visibility?.value ?? true;
const disabledState = component.definition.styles?.disabledState?.value ?? false;
const parsedDisabledState =
typeof disabledState !== 'boolean' ? resolveWidgetFieldValue(disabledState, currentState) : disabledState;
let parsedWidgetVisibility = widgetVisibility;
try {
parsedWidgetVisibility = resolveReferences(parsedWidgetVisibility, currentState, []);
} catch (err) {
console.log(err);
}
const [gmap, setGmap] = useState(null);
const [autoComplete, setAutoComplete] = useState(null);
const [mapCenter, setMapCenter] = useState(resolveReferences(center, currentState));
const [markers, setMarkers] = useState(resolveReferences(defaultMarkers, currentState));
const containerStyle = {
width: '100%',
height,
};
function handleMapClick(e) {
if (!canAddNewMarkers) {
return;
}
const lat = e.latLng.lat();
const lng = e.latLng.lng();
const newMarkers = markers;
newMarkers.push({ lat, lng });
setMarkers(newMarkers);
onComponentOptionChanged(component, 'markers', newMarkers).then(() => onEvent('onCreateMarker', { component }));
}
function addMapUrlToJson(centerJson) {
centerJson.googleMapUrl = `https://www.google.com/maps/@?api=1&map_action=map&center=${centerJson?.lat},${centerJson?.lng}`;
return centerJson;
}
function handleBoundsChange() {
const mapBounds = gmap.getBounds();
const bounds = {
northEast: mapBounds.getNorthEast()?.toJSON(),
southWest: mapBounds.getSouthWest()?.toJSON(),
};
const newCenter = gmap.center?.toJSON();
setMapCenter(newCenter);
onComponentOptionsChanged(component, [
['bounds', bounds],
['center', addMapUrlToJson(newCenter)],
]).then(() => onEvent('onBoundsChange', { component }));
}
useEffect(() => {
const resolvedCenter = resolveReferences(center, currentState);
setMapCenter(resolvedCenter);
onComponentOptionsChanged(component, [['center', addMapUrlToJson(resolvedCenter)]]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [center]);
// eslint-disable-next-line react-hooks/exhaustive-deps
const onLoad = useCallback(function onLoad(mapInstance) {
setGmap(mapInstance);
const centerJson = mapInstance.center?.toJSON();
onComponentOptionsChanged(component, [['center', addMapUrlToJson(centerJson)]]);
});
function handleMarkerClick(index) {
onComponentOptionChanged(component, 'selectedMarker', markers[index]).then(() =>
onEvent('onMarkerClick', { component })
);
}
function onPlaceChanged() {
const location = autoComplete.getPlace().geometry.location?.toJSON();
setMapCenter(location);
handleBoundsChange();
}
function onAutocompleteLoad(autocompleteInstance) {
setAutoComplete(autocompleteInstance);
}
registerAction('setLocation', async function (lat, lng) {
if (lat && lng) setMapCenter(resolveReferences({ lat, lng }, currentState));
});
return (
<div
data-disabled={parsedDisabledState}
style={{ height, display: parsedWidgetVisibility ? '' : 'none' }}
onClick={(event) => {
event.stopPropagation();
onComponentClick(id, component, event);
}}
className="map-widget"
>
<div
className="map-center"
style={{
right: width * 0.5 - 18,
top: height * 0.5 - 50,
}}
>
<img className="mx-2" src="assets/images/icons/marker.svg" width="24" height="64" />
</div>
<LoadScript googleMapsApiKey={window.public_config.GOOGLE_MAPS_API_KEY} libraries={['places']}>
<GoogleMap
center={mapCenter}
mapContainerStyle={containerStyle}
zoom={12}
options={{
styles: darkMode === true ? darkModeStyles : '',
streetViewControl: false,
mapTypeControl: false,
draggable: true,
}}
onLoad={onLoad}
onClick={handleMapClick}
onDragEnd={handleBoundsChange}
>
{canSearch && (
<Autocomplete onPlaceChanged={onPlaceChanged} onLoad={onAutocompleteLoad}>
<input
type="text"
placeholder={t('globals.search', 'Search')}
className={`place-search-input ${darkMode && 'text-light bg-dark dark-theme-placeholder'}`}
/>
</Autocomplete>
)}
{Array.isArray(markers) && (
<>
{markers.map((marker, index) => (
<Marker key={index} position={marker} label={marker.label} onClick={() => handleMarkerClick(index)} />
))}
</>
)}
</GoogleMap>
</LoadScript>
</div>
);
};