diff --git a/.eslintrc.js b/.eslintrc.js index 40c6dcd0..187894b6 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,4 +1,4 @@ module.exports = { root: true, - extends: '@react-native-community', + extends: '@react-native', }; diff --git a/PROJECT.md b/PROJECT.md index f9085486..688c72c9 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -186,9 +186,12 @@ host it was made for (`admin-web`) is gone, and since B-52 the console mounts th How the barrel runs on the web: - **Web differences live in `.web.js` twins** inside this package (`Config`, `Localization`, `MapboxGLWrapper`, - `OptionPicker/OptionSheet`); a web bundler resolves them first. + `OptionPicker/OptionSheet`); a web bundler resolves them first. `MapboxGLWrapper/index.web.js` (0.8.0) is the + native surface on react-map-gl and loads the map (`MapboxGLWrapperMap.web.js`, with mapbox-gl and its stylesheet) + through `import()`, so the barrel does not put the map engine in a host's first page. `Geoposition/MapPicker` + has a web twin on that wrapper for the same reason: @rnmapbox/maps' web build imports mapbox-gl and its CSS. - **Native modules a web bundle cannot load are the host's web stubs** (CustomerApp `web-stubs/`: - `react-native-config`, the map wrapper's override, `navigator.geolocation`), applied only on the web. + `react-native-config`, `navigator.geolocation`), applied only on the web. - **`Config.web.js`**: on the web the host calls `configureComponents({ IMAGEKIT_URL, … })` once before rendering. Native `Config.js` exports the same function (merge, no behaviour change). - **Never import this package by its published name from inside it**, and import `../ScreenWrapper` diff --git a/packages/components/package-lock.json b/packages/components/package-lock.json index bbaa9f1f..00b6845f 100644 --- a/packages/components/package-lock.json +++ b/packages/components/package-lock.json @@ -1,12 +1,12 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.7.3", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.7.3", + "version": "0.8.0", "license": "ISC", "devDependencies": { "@jmstechnologiesinc/partner": "0.2.54", diff --git a/packages/components/package.json b/packages/components/package.json index 4015c5ab..dbb110db 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -1,6 +1,6 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.7.3", + "version": "0.8.0", "description": "Biblioteca de componentes de interfaz compartida por las aplicaciones de Daxir.", "author": "yerloveraaa ", "homepage": "https://github.com/jmstechnologiesinc/react-native-components#readme", @@ -53,6 +53,7 @@ "i18next": "^23.16.8", "i18next-browser-languagedetector": "^8.2.1", "lodash.memoize": "^4.1.2", + "mapbox-gl": "^3.5.0", "react": "19.2.3", "react-i18next": "^15.7.4", "react-map-gl": "^8.1.2", diff --git a/packages/components/src/Geoposition/MapPicker/index.web.js b/packages/components/src/Geoposition/MapPicker/index.web.js new file mode 100644 index 00000000..929d0b62 --- /dev/null +++ b/packages/components/src/Geoposition/MapPicker/index.web.js @@ -0,0 +1,104 @@ +// The web twin of MapPicker (index.js): the same props and layout on the package's web map wrapper instead of +// @rnmapbox/maps. @rnmapbox's own web build imports mapbox-gl and its stylesheet; reached from the barrel through this +// component, it put the whole map engine in every page of the web hosts, a map or not. The wrapper loads it with +// import() the first time a map renders. index.js, the native picker, is unchanged. +import { View, Dimensions, StyleSheet } from 'react-native'; +import React from 'react'; +import { Appbar, IconButton, MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; +import { moderateScale } from '@jmstechnologiesinc/react-native-size-matters'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import MapboxGLWrapper from '../../MapboxGLWrapper'; +import AddressSelectionSheet from './AddressSelectionSheet'; + +const MapPicker = ({ + mapRef, + cameraRef, + isLocationPermissionDenied, + isLoading, + setIsLoading, + onSaveLocation, + onRegionChangeComplete, + currentLocation, + currentMapAdress, + findUserLocation, + centerMapOnUserLocation, + onBackPress, +}) => { + const { height } = Dimensions.get('window'); + const insets = useSafeAreaInsets(); + + return ( + <> + setIsLoading(false)} + onRegionIsChanging={() => setIsLoading(true)} + > + {currentLocation ? ( + + ) : null} + + + + {currentLocation ? ( + + + + ) : null} + + {!isLocationPermissionDenied && ( + + + + )} + + + + + + + + ); +}; + +const styles = StyleSheet.create({ + map: { + flex: 1, + }, + centerButton: { + position: 'absolute', + right: MD3LightTheme.spacing.x2, + }, + backAction: { + position: 'absolute', + }, + iconLocation: { + position: 'absolute', + top: '50%', + left: '50%', + transform: [{ translateX: -41 }, { translateY: -56 }], + zIndex: 1, + }, +}); + +export default MapPicker; diff --git a/packages/components/src/MapboxGLWrapper/MapboxGLWrapperContainer.web.js b/packages/components/src/MapboxGLWrapper/MapboxGLWrapperContainer.web.js new file mode 100644 index 00000000..8a8b1db5 --- /dev/null +++ b/packages/components/src/MapboxGLWrapper/MapboxGLWrapperContainer.web.js @@ -0,0 +1,20 @@ +import React from 'react'; +import { StyleSheet, View } from 'react-native'; + +// The map's box on the web, shared by the map and by the placeholder index.web.js shows while the map's code loads, +// so the page keeps the same layout before and after. A `flex: 1` would beat the consumer's height: in CSS flex the +// 0 flex-basis wins over `height` and the map collapses to 0 (the order detail asks for 300). With an explicit +// height the box needs no flex. +const MapboxGLWrapperContainer = ({ style, children }) => { + const hasExplicitHeight = StyleSheet.flatten(style)?.height != null; + + return {children}; +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default MapboxGLWrapperContainer; diff --git a/packages/components/src/MapboxGLWrapper/MapboxGLWrapperMap.web.js b/packages/components/src/MapboxGLWrapper/MapboxGLWrapperMap.web.js new file mode 100644 index 00000000..6fe7678e --- /dev/null +++ b/packages/components/src/MapboxGLWrapper/MapboxGLWrapperMap.web.js @@ -0,0 +1,311 @@ +// The web map: the surface of `index.js` (@rnmapbox on native) rebuilt on react-map-gl v8 + mapbox-gl. index.web.js +// loads this module with import(), so its map engine (mapbox-gl, about 1.8 MB minified) and stylesheet reach the +// browser only when a screen shows a map, never with the app's first page. +// +// Moved from CustomerApp's web-stubs/mapbox-gl-wrapper.js, the host override that replaced the previous index.web.js +// (a monolithic GeoPositionTracker written against props nobody passes any more). Consumers use the composable +// {children} model; the mapping between @rnmapbox and react-map-gl is direct: +// +// ShapeSource + LineLayer -> + +// MarkerView / PointAnnot. -> +// Camera -> useMap() + flyTo / fitBounds +// +// DriverRouteMonitoring is DELIBERATELY simpler than the native one: it does not port the overview->follow state +// machine (Uber-style follow camera, off-route detection, memoized remaining route). That exists for a full-screen +// phone map; in a 300px desktop box it adds nothing, and it depends on onMapIdle/onCameraChanged. The web version +// frames origin and destination, draws the route and moves the vehicle. +// +// Out of scope on purpose (used only by DriverApp, which the web stubs out entirely): DrawTurnByTurnRoute, +// BusinessIconMarker and HeatMap stay no-ops, in index.web.js. + +import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; +import { Image, StyleSheet, View } from 'react-native'; + +import Map, { GeolocateControl, Layer, Marker, Source, useMap } from 'react-map-gl/mapbox'; +import 'mapbox-gl/dist/mapbox-gl.css'; + +import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; +import { MD3LightTheme, Text, TouchableRipple } from '@jmstechnologiesinc/react-native-paper'; + +import { Config } from '../Config'; +import MapboxGLWrapperContainer from './MapboxGLWrapperContainer'; +import carIcon from './assets/car.png'; + +const DEFAULT_ZOOM = 15; +const CAR_SIZE = 40; +const MAP_STYLE = 'mapbox://styles/mapbox/streets-v12'; + +// react-map-gl applies `style` to the map's div as a DOM style, not an RN style. A StyleSheet.create id (a number in +// react-native-web) reaches it as garbage, the container stays at height 0 and the map is invisible although its +// canvas renders. Hence the plain object. +const MAP_DOM_STYLE = { width: '100%', height: '100%' }; + +const isCoordinate = (longitude, latitude) => Number.isFinite(longitude) && Number.isFinite(latitude); + +// @rnmapbox hands onRegionDidChange a GeoJSON Feature whose `properties.isUserInteraction` tells the user's pan from a +// programmatic move. MapSelector reads both, so react-map-gl's events are repackaged in that same shape. +const toRegionFeature = (event) => { + const center = event?.target?.getCenter?.(); + + return { + type: 'Feature', + geometry: { type: 'Point', coordinates: [center?.lng, center?.lat] }, + properties: { + zoomLevel: event?.target?.getZoom?.(), + isUserInteraction: Boolean(event?.originalEvent), + }, + }; +}; + +export const MapboxGLWrapperMap = forwardRef( + ( + { + style, + children, + onDidFinishLoadingMap, + onRegionDidChange, + onRegionIsChanging, + onMapIdle, + onCameraChanged, + ...props + }, + ref + ) => { + const mapRef = useRef(null); + + useImperativeHandle(ref, () => ({ + getMap: () => mapRef.current?.getMap?.(), + })); + + return ( + + { + onRegionDidChange?.(toRegionFeature(event)); + onCameraChanged?.(toRegionFeature(event)); + }} + onIdle={onMapIdle} + {...props} + > + {children} + + + ); + } +); + +MapboxGLWrapperMap.displayName = 'MapboxGLWrapper'; + +// Takes @rnmapbox's prop shape (centerCoordinate / zoomLevel) and exposes the same imperative setCamera(), which is how +// MapSelector recenters on the GPS. +export const MapboxGLWrapperCamera = forwardRef(({ centerCoordinate, zoomLevel, animationDuration = 1000 }, ref) => { + const { current: map } = useMap(); + + const moveCamera = useCallback( + ({ centerCoordinate: center, zoomLevel: zoom, animationDuration: duration = animationDuration }) => { + if (!map || !center || !isCoordinate(center[0], center[1])) return; + map.flyTo({ center, zoom: zoom ?? zoomLevel ?? DEFAULT_ZOOM, duration }); + }, + [map, animationDuration, zoomLevel] + ); + + useImperativeHandle(ref, () => ({ setCamera: moveCamera }), [moveCamera]); + + // Only the INITIAL framing. Reframing on every prop change would fight the user's pan, which is exactly what + // MapPickerScreen needs to work. + const hasCenteredRef = useRef(false); + useEffect(() => { + if (hasCenteredRef.current || !centerCoordinate) return; + hasCenteredRef.current = true; + moveCamera({ centerCoordinate, zoomLevel, animationDuration: 0 }); + }, [centerCoordinate, zoomLevel, moveCamera]); + + return null; +}); + +MapboxGLWrapperCamera.displayName = 'MapboxGLWrapperCamera'; + +export const MapboxGLWrapperBoundingBoxCamera = forwardRef(({ coordinates, snapPoint = 0 }, ref) => { + const { current: map } = useMap(); + + const fit = useCallback(() => { + const points = (coordinates || []).filter((point) => point && isCoordinate(point[0], point[1])); + if (!map || points.length === 0) return; + + if (points.length === 1) { + map.flyTo({ center: points[0], zoom: DEFAULT_ZOOM, duration: 600 }); + return; + } + + const lngs = points.map((point) => point[0]); + const lats = points.map((point) => point[1]); + + map.fitBounds( + [ + [Math.min(...lngs), Math.min(...lats)], + [Math.max(...lngs), Math.max(...lats)], + ], + // The bottom sheet covers the lower part of the canvas; snapPoint is its height, as on native, so the + // framing lands in the visible area. + { padding: { top: 60, left: 60, right: 60, bottom: 60 + snapPoint }, duration: 600, maxZoom: 16 } + ); + }, [map, coordinates, snapPoint]); + + useImperativeHandle(ref, () => ({ fit }), [fit]); + + useEffect(fit, [fit]); + + return null; +}); + +MapboxGLWrapperBoundingBoxCamera.displayName = 'MapboxGLWrapperBoundingBoxCamera'; + +export const MapboxGLWrapperVehicleIconMarker = ({ longitude, latitude, rotation = 0 }) => + isCoordinate(longitude, latitude) ? ( + + + + ) : null; + +export const MapboxGLWrapperLocationTooltip = ({ latitude, longitude, title, onPress }) => + isCoordinate(longitude, latitude) ? ( + + + + {title?.length > 20 ? `${title.substring(0, 20)}...` : title} + {onPress ? : null} + + + + ) : null; + +export const MapboxGLWrapperPointAnnotationMaterialIcon = ({ coordinate, iconName = 'map-marker', iconSize = 32 }) => + coordinate && isCoordinate(coordinate[0], coordinate[1]) ? ( + + + + ) : null; + +export const MapboxGLWrapperUserLocation = () => ; + +const routeFeature = (coordinates) => ({ + type: 'Feature', + geometry: { type: 'LineString', coordinates }, + properties: {}, +}); + +export const MapboxGLWrapperDriverRouteMonitoring = forwardRef( + ({ originLocation, dropoffLocation, onLocationPress }, ref) => { + const [route, setRoute] = useState([]); + const [snapPoint, setSnapPoint] = useState(0); + const boundingBoxRef = useRef(null); + + const origin = isCoordinate(originLocation?.longitude, originLocation?.latitude) + ? [originLocation.longitude, originLocation.latitude] + : null; + const destination = isCoordinate(dropoffLocation?.longitude, dropoffLocation?.latitude) + ? [dropoffLocation.longitude, dropoffLocation.latitude] + : null; + + useImperativeHandle(ref, () => ({ + resetCamera: (nextSnapPoint) => { + if (Number.isFinite(nextSnapPoint)) setSnapPoint(nextSnapPoint); + boundingBoxRef.current?.fit(); + }, + setCameraSnapPoint: (nextSnapPoint) => { + if (Number.isFinite(nextSnapPoint)) setSnapPoint(nextSnapPoint); + }, + // Native uses these for the overview->follow transition, which does not exist here. + onMapIdle: () => {}, + onCameraChanged: () => {}, + })); + + useEffect(() => { + if (!origin || !destination) return; + + const url = + `https://api.mapbox.com/directions/v5/mapbox/driving/` + + `${origin[0]},${origin[1]};${destination[0]},${destination[1]}` + + `?geometries=geojson&overview=full&access_token=${Config.MAPBOX_ACCESS_TOKEN}`; + + let cancelled = false; + + fetch(url) + .then((response) => response.json()) + .then((json) => { + if (!cancelled && json.routes?.length) setRoute(json.routes[0].geometry.coordinates); + }) + .catch((error) => console.log('[route] directions error:', error?.message || error)); + + return () => { + cancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [origin?.[0], origin?.[1], destination?.[0], destination?.[1]]); + + const shape = useMemo(() => (route.length >= 2 ? routeFeature(route) : null), [route]); + + return ( + <> + + + {shape ? ( + + + + ) : null} + + {origin ? : null} + + {origin && originLocation?.formattedAddress ? ( + + ) : null} + + {destination ? : null} + + ); + } +); + +MapboxGLWrapperDriverRouteMonitoring.displayName = 'MapboxGLWrapperDriverRouteMonitoring'; + +const styles = StyleSheet.create({ + car: { + width: CAR_SIZE, + height: CAR_SIZE, + }, + tooltip: { + backgroundColor: MD3LightTheme.colors.background, + paddingHorizontal: 10, + paddingVertical: 4, + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + }, +}); diff --git a/packages/components/src/MapboxGLWrapper/index.web.js b/packages/components/src/MapboxGLWrapper/index.web.js index 2264e512..30743901 100644 --- a/packages/components/src/MapboxGLWrapper/index.web.js +++ b/packages/components/src/MapboxGLWrapper/index.web.js @@ -1,131 +1,62 @@ -import 'mapbox-gl/dist/mapbox-gl.css'; -import React, { useEffect, useState } from 'react'; -import Map, { Source, Layer, Marker } from 'react-map-gl'; -import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; - -import { ActivityIndicator, Dimensions, StyleSheet, View } from 'react-native'; -import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; -import { Config } from '../Config'; - -const GeoPositionTracker = ({ customerPosition, currentDriverPosition, vendorPosition }) => { - const [routeDirections, setRouteDirections] = useState(null); - const [destinationCoords, setDestinationCoords] = useState([customerPosition.longitude, customerPosition.latitude]); - const [loading, setLoading] = useState(true); - - useEffect(() => { - createRouteLine(vendorPosition, customerPosition); - }, []); - - useEffect(() => { - if (currentDriverPosition) { - createRouteLine(currentDriverPosition, customerPosition); - } - }, [currentDriverPosition]); - - const makeRouterFeature = (coordinates) => ({ - type: 'FeatureCollection', - features: [ - { - type: 'Feature', - geometry: { - type: 'LineString', - coordinates: coordinates, - }, - }, - ], - }); - - const createRouteLine = async (startPosition, endPosition) => { - setLoading(true); - - const startCoords = `${startPosition.longitude},${startPosition.latitude}`; - const endCoords = `${endPosition.longitude},${endPosition.latitude}`; - const url = `https://api.mapbox.com/directions/v5/mapbox/driving/${startCoords};${endCoords}?alternatives=false&geometries=geojson&steps=true&overview=full&access_token=${Config.MAPBOX_ACCESS_TOKEN}`; - - try { - const response = await fetch(url); - const json = await response.json(); - - if (json.routes && json.routes.length) { - const coordinates = json.routes[0].geometry.coordinates; - setRouteDirections(makeRouterFeature(coordinates)); - setDestinationCoords(coordinates[coordinates.length - 1]); - } - setLoading(false); - } catch (error) { - console.error('Error fetching directions:', error); - setLoading(false); - } - }; - - const centerCoordinate = currentDriverPosition - ? [currentDriverPosition.longitude, currentDriverPosition.latitude] - : [vendorPosition.longitude, vendorPosition.latitude]; - - console.log(centerCoordinate); - return ( - - - {centerCoordinate && ( - - - - )} - {routeDirections && ( - - - - )} - - {destinationCoords && ( - - - - )} - - {loading && ( - - )} - - ); +// The web twin of `index.js`: the same composable surface, {children} with its +// statics. The map itself (MapboxGLWrapperMap.web.js: react-map-gl, mapbox-gl and its stylesheet) is loaded with +// import() the first time a map renders. The package's barrel exports this wrapper, so a static import would put the +// map engine in every page of the host; Expo splits the web bundle at import() (docs.expo.dev, customizing Metro), as +// the host's lazy() screens do. +// +// Each map part is lazy() inside a Suspense of its own: the map shows its empty box while its code arrives, and a +// part never pulls the whole map back to that box (all parts come from the same chunk, loaded once). + +import React, { Suspense, forwardRef, lazy } from 'react'; + +import MapboxGLWrapperContainer from './MapboxGLWrapperContainer'; +import MapboxGLWrapperLocationSelectorPin from './MapboxGLWrapperLocationSelectorPin'; +import MapboxGLWrapperResetToInitialPositionIcon from './MapboxGLWrapperResetToInitialPositionIcon'; + +const loadMap = () => import('./MapboxGLWrapperMap'); + +const lazyMapPart = (exportName) => lazy(() => loadMap().then((module) => ({ default: module[exportName] }))); + +/** A map part, rendered once the map's code has arrived; nothing in its place until then. */ +const mapPart = (exportName, displayName) => { + const Part = lazyMapPart(exportName); + const MapPart = forwardRef((props, ref) => ( + + + + )); + MapPart.displayName = displayName; + + return MapPart; }; -const styles = StyleSheet.create({ - container: { - flex: 1, - height: 300, - }, - map: { - flex: 1, - }, +const LazyMap = lazyMapPart('MapboxGLWrapperMap'); + +const MapboxGLWrapper = forwardRef(({ style, ...props }, ref) => ( + }> + + +)); + +MapboxGLWrapper.displayName = 'MapboxGLWrapper'; + +const NoopMapComponent = () => null; + +export default Object.assign(MapboxGLWrapper, { + Camera: mapPart('MapboxGLWrapperCamera', 'MapboxGLWrapperCamera'), + BoundingBoxCamera: mapPart('MapboxGLWrapperBoundingBoxCamera', 'MapboxGLWrapperBoundingBoxCamera'), + FolowUserLocation: mapPart('MapboxGLWrapperUserLocation', 'MapboxGLWrapperUserLocation'), + VehicleIconMarker: mapPart('MapboxGLWrapperVehicleIconMarker', 'MapboxGLWrapperVehicleIconMarker'), + PointAnnotationMaterialIcon: mapPart( + 'MapboxGLWrapperPointAnnotationMaterialIcon', + 'MapboxGLWrapperPointAnnotationMaterialIcon' + ), + LocationTooltip: mapPart('MapboxGLWrapperLocationTooltip', 'MapboxGLWrapperLocationTooltip'), + DriverRouteMonitoring: mapPart('MapboxGLWrapperDriverRouteMonitoring', 'MapboxGLWrapperDriverRouteMonitoring'), + ResetToInitialPositionIcon: MapboxGLWrapperResetToInitialPositionIcon, + LocationSelectorPin: MapboxGLWrapperLocationSelectorPin, + // DriverApp only, which the web stubs out entirely. + DrawTurnByTurnRoute: NoopMapComponent, + BusinessIconMarker: NoopMapComponent, + HeatMap: NoopMapComponent, }); - -export default GeoPositionTracker;