Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# TimeFlow

## Frontend map setup

Copy `frontend/.env.example` to `frontend/.env` and set
`EXPO_PUBLIC_BAIDU_MAP_AK` to a Baidu Maps browser-side AK. Enable JavaScript
API v4 for that AK in the Baidu Maps console and add the development and
production web origins to its Referer whitelist. Native builds render the
same JavaScript API in a WebView, so its configured `baseUrl`
(`https://timeflow.local/`) must also be allowed by the AK configuration.
2 changes: 2 additions & 0 deletions frontend/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# Android emulator: 10.0.2.2 reaches the host machine.
EXPO_PUBLIC_API_URL=http://10.0.2.2:8000/api/v1
# Baidu Maps browser-side AK with JavaScript API v4 enabled.
EXPO_PUBLIC_BAIDU_MAP_AK=your-baidu-map-browser-ak
190 changes: 190 additions & 0 deletions frontend/src/components/BaiduMapWebView.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import type { MapLocation } from './MapPicker.types';

export type BaiduMapBridgeMessage =
| { type: 'map-ready' }
| { message: string; type: 'map-error' }
| { latitude: number; longitude: number; type: 'selecting' }
| { location: MapLocation; type: 'selected' }
| { message: string; type: 'location-error' }
| { results: MapLocation[]; type: 'search-results' }
| { type: 'search-error' };

function serializeForInlineScript(value: unknown) {
return JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
}

export function buildBaiduMapDocument(ak: string, initialLocation: MapLocation | null) {
const center = initialLocation ?? {
address: '上海市 · 默认地图中心',
latitude: 31.236305,
longitude: 121.480237,
};
const initialJson = serializeForInlineScript(initialLocation);
const centerJson = serializeForInlineScript(center);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P1] Escape values before embedding them into the HTML script. initialLocation can contain a user-controlled address, and JSON.stringify() does not neutralize </script>. An address such as </script><script>...</script> therefore breaks out of this script block and executes inside the WebView (and can forge bridge messages). Serialize for an HTML-script context, e.g. replace < with \u003c (and handle the other script-sensitive characters) before interpolation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f97a12c. Initial location and map center values now use HTML-safe inline-script serialization for <, >, &, U+2028, and U+2029. npm run check passes.

return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
<style>
html, body, #map { width: 100%; height: 100%; margin: 0; overflow: hidden; }
body { background: #dce3dc; }
</style>
<script src="https://api.map.baidu.com/api?v=4.0&ak=${encodeURIComponent(ak)}"></script>
</head>
<body>
<div id="map"></div>
<script>
(function () {
var bridge = window.ReactNativeWebView;
var center = ${centerJson};
var initialLocation = ${initialJson};

function emit(payload) {
if (bridge) bridge.postMessage(JSON.stringify(payload));
}

function fallbackAddress(point) {
return '百度地图选点 · ' + point.lat.toFixed(5) + ', ' + point.lng.toFixed(5);
}

try {
if (!window.BMap) throw new Error('Baidu JSAPI did not load');

window.BMap.coordType = 'bd09ll';
var centerPoint = new BMap.Point(center.longitude, center.latitude);
var map = new BMap.Map('map', {
center: centerPoint,
enablePinchZoom: true,
enableWheelZoom: true,
fixCenterWhenResize: true,
zoom: initialLocation ? 17 : 14
});
var marker = null;
var markerSvg = '<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28"><circle cx="14" cy="14" r="11" fill="#D9F65A" stroke="#142821" stroke-width="4"/></svg>';
var markerIcon = new BMap.Icon(
'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(markerSvg),
new BMap.Size(28, 28),
{ anchor: new BMap.Size(14, 14) }
);
var geocoder = new BMap.Geocoder({ language: 'zh-CN' });

function placeMarker(point) {
if (marker) {
marker.setPosition(point);
} else {
marker = new BMap.Marker(point, { icon: markerIcon });
map.addOverlay(marker);
}
}

function selectPoint(point) {
var finished = false;
placeMarker(point);
emit({ type: 'selecting', latitude: point.lat, longitude: point.lng });

var timeout = setTimeout(function () {
if (finished) return;
finished = true;
emit({
type: 'selected',
location: {
address: fallbackAddress(point),
latitude: point.lat,
longitude: point.lng
}
});
}, 6000);

geocoder.getLocation(point, function (result) {
if (finished) return;
finished = true;
clearTimeout(timeout);
emit({
type: 'selected',
location: {
address: result && result.address ? result.address : fallbackAddress(point),
latitude: point.lat,
longitude: point.lng
}
});
});
}

map.addEventListener('click', function (event) {
selectPoint(event.point);
});

if (initialLocation) {
placeMarker(new BMap.Point(initialLocation.longitude, initialLocation.latitude));
}

var localSearch = new BMap.LocalSearch(map, {
pageCapacity: 5,
renderOptions: { autoViewport: false },
onSearchComplete: function (rawResults) {
var result = Array.isArray(rawResults) ? rawResults[0] : rawResults;
var locations = [];
if (result) {
var count = Math.min(result.getCurrentNumPois(), 5);
for (var index = 0; index < count; index += 1) {
var poi = result.getPoi(index);
if (!poi || !poi.point) continue;
locations.push({
address: poi.address ? poi.title + ' · ' + poi.address : poi.title,
latitude: poi.point.lat,
longitude: poi.point.lng
});
}
}
emit({ type: 'search-results', results: locations });
}
});

window.__timeflowSearch = function (query) {
try {
localSearch.search(query);
} catch (error) {
emit({ type: 'search-error' });
}
};

window.__timeflowLocate = function () {
try {
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (result) {
if (geolocation.getStatus() !== 0 || !result || !result.point) {
emit({ type: 'location-error', message: '无法获取当前位置,请允许定位权限后重试。' });
return;
}
map.setCenter(result.point, { noAnimation: false });
map.setZoom(17, { noAnimation: false });
selectPoint(result.point);
}, { enableHighAccuracy: true });
} catch (error) {
emit({ type: 'location-error', message: '无法获取当前位置,请允许定位权限后重试。' });
}
};

window.__timeflowSelect = function (longitude, latitude) {
var point = new BMap.Point(longitude, latitude);
placeMarker(point);
map.setCenter(point, { noAnimation: false });
map.setZoom(17, { noAnimation: false });
};

emit({ type: 'map-ready' });
} catch (error) {
emit({ type: 'map-error', message: '地图加载失败,请检查网络或百度地图密钥配置。' });
}
})();
</script>
</body>
</html>`;
}
180 changes: 180 additions & 0 deletions frontend/src/components/MapPicker.native.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { View } from 'react-native';
import { WebView, WebViewMessageEvent } from 'react-native-webview';

import { BaiduMapBridgeMessage, buildBaiduMapDocument } from './BaiduMapWebView';
import { BAIDU_MAP_AK, createCoordinateLocation } from './MapPicker.services';
import { mapPickerStyles as styles } from './MapPicker.styles';
import { MapPickerOverlay } from './MapPickerOverlay';
import type { MapLocation, MapPickerProps } from './MapPicker.types';

const SEARCH_TIMEOUT_MS = 8000;

type PendingSearch = {
reject: (error: Error) => void;
resolve: (locations: MapLocation[]) => void;
timeout: ReturnType<typeof setTimeout>;
};

export function MapPicker({ initialLocation, onCancel, onConfirm }: MapPickerProps) {
const webViewRef = useRef<WebView>(null);
const pendingSearchRef = useRef<PendingSearch | null>(null);
const [selection, setSelection] = useState<MapLocation | null>(initialLocation);
const [locating, setLocating] = useState(false);
const [locationError, setLocationError] = useState<string | null>(null);
const [mapReady, setMapReady] = useState(false);
const [mapError, setMapError] = useState<string | null>(
BAIDU_MAP_AK ? null : '缺少百度地图浏览器端密钥,请完成地图服务配置。',
);
const document = useMemo(
() => buildBaiduMapDocument(BAIDU_MAP_AK, initialLocation),
[initialLocation],
);

useEffect(() => {
return () => {
if (pendingSearchRef.current) {
clearTimeout(pendingSearchRef.current.timeout);
pendingSearchRef.current = null;
}
};
}, []);

const failPendingSearch = useCallback((message: string) => {
const pending = pendingSearchRef.current;
if (!pending) return;
clearTimeout(pending.timeout);
pending.reject(new Error(message));
pendingSearchRef.current = null;
}, []);

const handleMessage = useCallback(
({ nativeEvent }: WebViewMessageEvent) => {
let message: BaiduMapBridgeMessage;
try {
message = JSON.parse(nativeEvent.data) as BaiduMapBridgeMessage;
} catch {
return;
}

if (message.type === 'map-ready') {
setMapReady(true);
setMapError(null);
if (!initialLocation) {
webViewRef.current?.injectJavaScript('window.__timeflowLocate(); true;');
}
return;
}
if (message.type === 'map-error') {
setMapReady(false);
setMapError(message.message);
failPendingSearch(message.message);
return;
}
if (message.type === 'selecting') {
setLocationError(null);
setSelection(createCoordinateLocation(message.latitude, message.longitude));
setLocating(true);
return;
}
if (message.type === 'selected') {
setSelection(message.location);
setLocating(false);
setLocationError(null);
return;
}
if (message.type === 'location-error') {
setLocating(false);
setLocationError(message.message);
return;
}
if (message.type === 'search-results') {
const pending = pendingSearchRef.current;
if (!pending) return;
clearTimeout(pending.timeout);
pending.resolve(message.results);
pendingSearchRef.current = null;
return;
}
if (message.type === 'search-error') {
failPendingSearch('Baidu place search failed');
}
},
[failPendingSearch, initialLocation],
);

const searchLocations = useCallback(
(query: string) => {
return new Promise<MapLocation[]>((resolve, reject) => {
if (!mapReady || !webViewRef.current) {
reject(new Error('Baidu map is not ready'));
return;
}

failPendingSearch('A newer search replaced this request');
const timeout = setTimeout(() => {
failPendingSearch('Baidu place search timed out');
}, SEARCH_TIMEOUT_MS);
pendingSearchRef.current = { reject, resolve, timeout };
webViewRef.current.injectJavaScript(
`window.__timeflowSearch(${JSON.stringify(query)}); true;`,
);
});
},
[failPendingSearch, mapReady],
);

const selectSearchResult = (location: MapLocation) => {
setLocationError(null);
setLocating(false);
setSelection(location);
webViewRef.current?.injectJavaScript(
`window.__timeflowSelect(${location.longitude}, ${location.latitude}); true;`,
);
};

const locateCurrentPosition = () => {
setLocationError(null);
setLocating(true);
webViewRef.current?.injectJavaScript('window.__timeflowLocate(); true;');
};

return (
<View style={styles.screen}>
{BAIDU_MAP_AK ? (
<WebView
androidLayerType="hardware"
domStorageEnabled
geolocationEnabled
javaScriptCanOpenWindowsAutomatically={false}
javaScriptEnabled
onError={() => {
setMapReady(false);
setMapError('地图加载失败,请检查网络或百度地图密钥配置。');
}}
onMessage={handleMessage}
originWhitelist={['https://*']}
ref={webViewRef}
scrollEnabled={false}
setSupportMultipleWindows={false}
source={{ baseUrl: 'https://timeflow.local/', html: document }}
style={styles.mapCanvas}
/>
) : (
<View style={styles.mapCanvas} />
)}
<MapPickerOverlay
locating={locating}
locationError={locationError}
mapError={mapError}
mapReady={mapReady}
onCancel={onCancel}
onLocate={locateCurrentPosition}
onConfirm={() => selection && onConfirm(selection)}
onSearch={searchLocations}
onSelectSearchResult={selectSearchResult}
selection={selection}
/>
</View>
);
}
Loading
Loading