同步移动端源码并修复小程序嵌入标题
Some checks failed
CI / verify (push) Has been cancelled

This commit is contained in:
lyf
2026-07-28 18:37:40 +08:00
parent 06ad609e1f
commit 540bb8627f
62 changed files with 4196 additions and 1410 deletions

View File

@@ -8,8 +8,6 @@ import {
interface MiniProgramBridge {
getEnv?: (callback: (result: { miniprogram?: boolean }) => void) => void
navigateTo?: (options: { url: string; success?: () => void; fail?: (error: { errMsg?: string }) => void }) => void
navigateBack?: (options: { delta: number; success?: () => void; fail?: (error: { errMsg?: string }) => void }) => void
postMessage?: (options: { data: { type: string } }) => void
}
export type WechatMiniProgramBridgeResult =
@@ -17,20 +15,13 @@ export type WechatMiniProgramBridgeResult =
| { status: 'not-embedded' }
| { status: 'failed'; reason: 'invalid-target' | 'bridge-unavailable' | 'not-in-mini-program' | 'navigation-failed' | 'page-not-found' | 'timeout' }
export type WechatMiniProgramReturnResult =
| { status: 'returned' }
| { status: 'not-embedded' }
| { status: 'failed'; reason: 'bridge-unavailable' | 'not-in-mini-program' | 'navigation-failed' | 'timeout' }
const SDK_URL = 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js'
export const MINI_PROGRAM_RETURN_MESSAGE = 'museum-guide:return'
const BRIDGE_WAIT_TIMEOUT = 2500
const BRIDGE_POLL_INTERVAL = 50
const GET_ENV_TIMEOUT = 1500
const NAVIGATION_TIMEOUT = 3000
let pendingNavigation: Promise<WechatMiniProgramBridgeResult> | null = null
let pendingReturn: Promise<WechatMiniProgramReturnResult> | null = null
let sdkLoadPromise: Promise<void> | null = null
const getBridge = (): MiniProgramBridge | null => {
@@ -117,45 +108,6 @@ const navigateToHostLocationPage = (bridge: MiniProgramBridge, target: WechatOpe
}
})
const requestHostReturnFallback = (bridge: MiniProgramBridge) => {
if (!bridge.postMessage) return false
try {
bridge.postMessage({ data: { type: MINI_PROGRAM_RETURN_MESSAGE } })
return true
} catch (error) {
console.error('请求宿主小程序安全返回失败:', error)
return false
}
}
const navigateBackToHost = (bridge: MiniProgramBridge) => new Promise<WechatMiniProgramReturnResult>((resolve) => {
if (!bridge.navigateBack) return resolve({ status: 'failed', reason: 'bridge-unavailable' })
let settled = false
const finish = (result: WechatMiniProgramReturnResult) => {
if (settled) return
settled = true
clearTimeout(timeout)
resolve(result)
}
const timeout = setTimeout(() => finish({ status: 'failed', reason: 'timeout' }), NAVIGATION_TIMEOUT)
try {
bridge.navigateBack({
delta: 1,
success: () => finish({ status: 'returned' }),
fail: (error) => {
console.error('返回宿主小程序失败:', error)
finish({ status: 'failed', reason: 'navigation-failed' })
}
})
} catch (error) {
console.error('调用宿主小程序返回桥接失败:', error)
finish({ status: 'failed', reason: 'navigation-failed' })
}
})
const openOnce = async (target: WechatOpenLocationTarget): Promise<WechatMiniProgramBridgeResult> => {
const validation = validateWechatOpenLocationTarget(target)
if (!validation.ok) return { status: 'failed', reason: 'invalid-target' }
@@ -171,24 +123,3 @@ export const openWechatMiniProgramLocation = (target: WechatOpenLocationTarget)
pendingNavigation = openOnce(target).finally(() => { pendingNavigation = null })
return pendingNavigation
}
const returnOnce = async (): Promise<WechatMiniProgramReturnResult> => {
if (!isEmbeddedInWechatMiniProgram()) return { status: 'not-embedded' }
const bridge = await waitForBridge()
if (!bridge) return { status: 'failed', reason: 'bridge-unavailable' }
if (!await isMiniProgramWebView(bridge)) return { status: 'failed', reason: 'not-in-mini-program' }
const result = await navigateBackToHost(bridge)
if (result.status === 'returned') return result
// 宿主页可能由分享或冷启动直接打开,页面栈没有上一页时改由宿主执行安全回退。
if (requestHostReturnFallback(bridge)) return { status: 'returned' }
return result
}
export const returnToWechatMiniProgram = () => {
if (pendingReturn) return pendingReturn
pendingReturn = returnOnce().finally(() => { pendingReturn = null })
return pendingReturn
}

View File

@@ -252,11 +252,20 @@ export const findGuideFloorBasemap = (
if (!isCompatibleGuideFloorBasemapManifest(manifest)) return null
const normalizedFloorId = String(floorId || '')
const normalizedVersion = String(modelVersion || '')
return manifest?.floors.find((floor) => (
const matchingFloors = (manifest?.floors || []).filter((floor) => (
(String(floor.floorId) === normalizedFloorId || floor.floorCode === normalizedFloorId)
&& (!normalizedVersion || floor.modelVersion === normalizedVersion)
&& isValidGuideBasemapEntry(floor)
)) || null
))
if (!matchingFloors.length) return null
if (!normalizedVersion) return matchingFloors[0]
const exactVersion = matchingFloors.find((floor) => floor.modelVersion === normalizedVersion)
if (exactVersion) return exactVersion
// The static WebP package can lag behind a published GLB version. A single
// valid floor image remains geometrically usable, while multiple candidates
// are ambiguous and must not be guessed.
return matchingFloors.length === 1 ? matchingFloors[0] : null
}
export const findGuideCompositeBasemap = (

View File

@@ -0,0 +1,81 @@
import {
translateBrowserCoordinates,
type OutdoorCoordinate
} from './OutdoorMapAppService'
export type BrowserLocationFailureReason = 'unsupported' | 'denied' | 'unavailable' | 'timeout' | 'insecure-context'
export type BrowserLocationPermissionState = 'granted' | 'denied' | 'prompt' | 'unsupported' | 'unknown'
export class BrowserLocationError extends Error {
constructor(public readonly reason: BrowserLocationFailureReason) {
super(messageFor(reason))
}
}
export interface BrowserGcjLocation extends OutdoorCoordinate {
accuracyMeters: number
timestamp: number
}
const messageFor = (reason: BrowserLocationFailureReason) => ({
unsupported: '当前浏览器不支持定位',
denied: '未获得位置权限',
unavailable: '暂时无法获取当前位置',
timeout: '定位超时,请稍后重试',
'insecure-context': '当前页面不是安全连接,无法使用位置服务'
}[reason])
const toFailureReason = (error: GeolocationPositionError): BrowserLocationFailureReason => {
if (error.code === error.PERMISSION_DENIED) return 'denied'
if (error.code === error.TIMEOUT) return 'timeout'
return 'unavailable'
}
const requestPosition = () => new Promise<GeolocationPosition>((resolve, reject) => {
if (typeof navigator === 'undefined' || !navigator.geolocation) {
reject(new BrowserLocationError('unsupported'))
return
}
if (typeof window !== 'undefined' && !window.isSecureContext) {
reject(new BrowserLocationError('insecure-context'))
return
}
navigator.geolocation.getCurrentPosition(resolve, (error) => {
reject(new BrowserLocationError(toFailureReason(error)))
}, {
enableHighAccuracy: true,
timeout: 10_000,
maximumAge: 15_000
})
})
export const getBrowserLocationPermissionState = async (): Promise<BrowserLocationPermissionState> => {
if (typeof navigator === 'undefined' || !navigator.geolocation) return 'unsupported'
if (!navigator.permissions?.query) return 'unknown'
try {
const permission = await navigator.permissions.query({ name: 'geolocation' as PermissionName })
return permission.state
} catch {
return 'unknown'
}
}
export const getBrowserGcjLocation = async (): Promise<BrowserGcjLocation> => {
const position = await requestPosition()
const translated = await translateBrowserCoordinates([{
latitude: position.coords.latitude,
longitude: position.coords.longitude
}])
const coordinate = translated.locations[0]
if (!coordinate) {
throw new BrowserLocationError('unavailable')
}
return {
...coordinate,
accuracyMeters: position.coords.accuracy,
timestamp: position.timestamp
}
}

View File

@@ -0,0 +1,180 @@
export type OutdoorTravelMode = 'DRIVING' | 'WALKING' | 'TRANSIT'
export interface OutdoorCoordinate {
latitude: number
longitude: number
}
export interface OutdoorMapProfile {
enabled: boolean
h5Enabled: boolean
available: boolean
state: OutdoorMapAvailabilityState
message?: string | null
lastCheckedAt?: string | null
quotaStatus: OutdoorMapQuotaStatus
availableModes: OutdoorTravelMode[]
jsMapEnabled: boolean
jsMapKey?: string | null
}
export type OutdoorMapAvailabilityState = 'AVAILABLE' | 'CHECKING' | 'CONFIG_INCOMPLETE' | 'PROVIDER_UNAVAILABLE' | 'QUOTA_EXHAUSTED' | 'MANUALLY_DISABLED'
export type OutdoorMapQuotaStatus = 'NOT_QUERYABLE' | 'PROVIDER_REPORTED_EXHAUSTED'
export interface OutdoorRoutePlan {
mode: OutdoorTravelMode
distance: number
/** 腾讯地图 WebService 返回的预计时长,单位为分钟。 */
duration: number
polyline: OutdoorCoordinate[]
}
export interface OutdoorPlace {
id: string
title: string
address: string
category: string
latitude: number
longitude: number
distance?: number | null
}
export interface OutdoorReverseGeocode {
address: string
province?: string
city?: string
district?: string
street?: string
streetNumber?: string
latitude: number
longitude: number
}
interface ApiResult<T> {
code: number
msg?: string
data: T
}
const appApiBaseUrl = (import.meta.env.VITE_API_BASE_URL?.trim() || '/app-api').replace(/\/$/, '')
let profilePromise: Promise<OutdoorMapProfile> | null = null
const availabilityListeners = new Set<(message: string) => void>()
const notifyOutdoorMapUnavailable = (message: string) => {
profilePromise = null
availabilityListeners.forEach((listener) => listener(message))
}
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
const response = await fetch(`${appApiBaseUrl}/gis/outdoor-map${path}`, {
...init,
headers: {
Accept: 'application/json',
...(init?.body ? { 'Content-Type': 'application/json' } : {}),
...init?.headers
}
})
let payload: ApiResult<T> | null = null
try {
payload = await response.json() as ApiResult<T>
} catch {
throw new Error('室外地图服务响应异常')
}
if (!response.ok || payload.code !== 0) {
const message = payload.msg || '室外地图服务请求失败'
if (path !== '/profile') notifyOutdoorMapUnavailable(message)
throw new Error(message)
}
return payload.data
}
export const getOutdoorMapProfile = () => {
if (!profilePromise) {
profilePromise = request<OutdoorMapProfile>('/profile').catch((error) => {
profilePromise = null
throw error
})
}
return profilePromise
}
export const resetOutdoorMapProfileCache = () => {
profilePromise = null
}
export const refreshOutdoorMapProfile = () => {
resetOutdoorMapProfileCache()
return getOutdoorMapProfile()
}
export const subscribeOutdoorMapAvailability = (listener: (message: string) => void) => {
availabilityListeners.add(listener)
return () => availabilityListeners.delete(listener)
}
export const planOutdoorRoute = (input: {
from: OutdoorCoordinate
to: OutdoorCoordinate
mode: OutdoorTravelMode
}) => request<OutdoorRoutePlan>('/routes/plan', {
method: 'POST',
body: JSON.stringify({
fromLatitude: input.from.latitude,
fromLongitude: input.from.longitude,
toLatitude: input.to.latitude,
toLongitude: input.to.longitude,
mode: input.mode
})
})
export const searchOutdoorPlaces = (input: {
keyword: string
region?: string
latitude?: number
longitude?: number
pageSize?: number
}) => {
const searchParams = new URLSearchParams({
keyword: input.keyword.trim(),
region: input.region?.trim() || '深圳市',
pageSize: String(input.pageSize || 10)
})
if (input.latitude !== undefined && input.longitude !== undefined) {
searchParams.set('latitude', String(input.latitude))
searchParams.set('longitude', String(input.longitude))
}
return request<{ items: OutdoorPlace[] }>(`/places/search?${searchParams.toString()}`)
}
export const suggestOutdoorPlaces = (input: {
keyword: string
region?: string
pageSize?: number
}) => {
const searchParams = new URLSearchParams({
keyword: input.keyword.trim(),
region: input.region?.trim() || '深圳市',
pageSize: String(input.pageSize || 10)
})
return request<{ items: OutdoorPlace[] }>(`/places/suggestions?${searchParams.toString()}`)
}
export const reverseGeocodeOutdoorLocation = (location: OutdoorCoordinate) => {
const searchParams = new URLSearchParams({
latitude: String(location.latitude),
longitude: String(location.longitude)
})
return request<OutdoorReverseGeocode>(`/geocoding/reverse?${searchParams.toString()}`)
}
export const translateBrowserCoordinates = (locations: OutdoorCoordinate[]) => request<{
sourceCoordinateSystem: 'WGS84'
targetCoordinateSystem: 'GCJ02'
locations: OutdoorCoordinate[]
}>('/coordinates/translate', {
method: 'POST',
body: JSON.stringify({ locations })
})

View File

@@ -0,0 +1,99 @@
import { getOutdoorMapProfile } from './OutdoorMapAppService'
export interface TencentLatLng {
getLat?: () => number
getLng?: () => number
lat?: number
lng?: number
}
export interface TencentMapInstance {
setCenter: (center: TencentLatLng) => void
getCenter?: () => TencentLatLng
getZoom?: () => number
setZoom?: (zoom: number) => void
panBy?: (offset: { x: number; y: number }) => void
on: (event: string, listener: (event: { latLng?: TencentLatLng }) => void) => void
destroy: () => void
}
export interface TencentMapApi {
Map: new (container: HTMLElement, options: {
center: TencentLatLng
zoom: number
zoomControl?: boolean
rotationControl?: boolean
scaleControl?: boolean
mapTypeControl?: boolean
}) => TencentMapInstance
LatLng: new (latitude: number, longitude: number) => TencentLatLng
MarkerStyle: new (options: Record<string, unknown>) => unknown
PolylineStyle: new (options: Record<string, unknown>) => unknown
MultiMarker: new (options: Record<string, unknown>) => unknown
MultiPolyline: new (options: Record<string, unknown>) => unknown
}
declare global {
interface Window {
TMap?: TencentMapApi
}
}
const scriptLoads = new Map<string, Promise<TencentMapApi>>()
const hintedOrigins = new Set<string>()
const hintTencentMapOrigin = (origin: string) => {
if (hintedOrigins.has(origin) || typeof document === 'undefined') return
hintedOrigins.add(origin)
const dnsPrefetch = document.createElement('link')
dnsPrefetch.rel = 'dns-prefetch'
dnsPrefetch.href = origin
document.head.appendChild(dnsPrefetch)
const preconnect = document.createElement('link')
preconnect.rel = 'preconnect'
preconnect.href = origin
preconnect.crossOrigin = 'anonymous'
document.head.appendChild(preconnect)
}
const prepareTencentMapNetwork = () => {
hintTencentMapOrigin('https://map.qq.com')
hintTencentMapOrigin('https://mapapi.qq.com')
}
export const loadTencentJsMapScript = (key: string): Promise<TencentMapApi> => {
prepareTencentMapNetwork()
const existing = scriptLoads.get(key)
if (existing) return existing
const promise = new Promise<TencentMapApi>((resolve, reject) => {
if (window.TMap) {
resolve(window.TMap)
return
}
const script = document.createElement('script')
script.async = true
script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${encodeURIComponent(key)}`
script.onload = () => window.TMap ? resolve(window.TMap) : reject(new Error('腾讯 JS 地图加载失败'))
script.onerror = () => reject(new Error('腾讯 JS 地图网络加载失败'))
document.head.appendChild(script)
}).catch((error) => {
scriptLoads.delete(key)
throw error
})
scriptLoads.set(key, promise)
return promise
}
export const preloadTencentJsMap = async () => {
if (typeof window === 'undefined') return false
prepareTencentMapNetwork()
const profile = await getOutdoorMapProfile()
if (!profile.available || !profile.jsMapEnabled || !profile.jsMapKey) return false
await loadTencentJsMapScript(profile.jsMapKey)
return true
}

View File

@@ -2,6 +2,12 @@
* 腾讯地图 WebService API 服务
* 用于 POI 搜索、地址解析、路线规划等
*/
import {
planOutdoorRoute,
searchOutdoorPlaces,
type OutdoorPlace,
type OutdoorTravelMode
} from '@/services/outdoor/OutdoorMapAppService'
const TENCENT_MAP_KEY = import.meta.env.VITE_TENCENT_MAP_KEY?.trim() || ''
const TENCENT_MAP_BASE_URL = 'https://apis.map.qq.com/ws'
@@ -55,6 +61,45 @@ const createUnavailableRouteResult = (message = 'H5 端腾讯地图路线规划
message
})
const toTencentPoi = (place: OutdoorPlace): TencentPoiResult => ({
id: place.id,
title: place.title,
address: place.address,
category: place.category,
lat: place.latitude,
lng: place.longitude,
location: {
lat: place.latitude,
lng: place.longitude
},
distance: place.distance ?? undefined
})
const planH5Route = async (
from: RoutePoint,
to: RoutePoint,
mode: OutdoorTravelMode
): Promise<RouteResult> => {
try {
const route = await planOutdoorRoute({ from, to, mode })
return {
status: 0,
message: 'ok',
routes: [{
id: 0,
startPoint: from,
endPoint: to,
distance: route.distance,
duration: route.duration,
polyline: route.polyline,
steps: []
}]
}
} catch (error) {
return createUnavailableRouteResult(error instanceof Error ? error.message : '路线规划失败')
}
}
/**
* 路线规划起点/终点坐标
*/
@@ -172,8 +217,7 @@ export async function planWalkingRoute(
to: RoutePoint
): Promise<RouteResult> {
if (isH5BrowserRuntime) {
console.info('H5 端跳过腾讯地图步行路线 WebService 请求,避免浏览器 CORS 拦截')
return createUnavailableRouteResult()
return planH5Route(from, to, 'WALKING')
}
return new Promise((resolve) => {
@@ -250,8 +294,7 @@ export async function planDrivingRoute(
to: RoutePoint
): Promise<RouteResult> {
if (isH5BrowserRuntime) {
console.info('H5 端跳过腾讯地图驾车路线 WebService 请求,避免浏览器 CORS 拦截')
return createUnavailableRouteResult()
return planH5Route(from, to, 'DRIVING')
}
return new Promise((resolve) => {
@@ -328,8 +371,7 @@ export async function planTransitRoute(
to: RoutePoint
): Promise<RouteResult> {
if (isH5BrowserRuntime) {
console.info('H5 端跳过腾讯地图公交路线 WebService 请求,避免浏览器 CORS 拦截')
return createUnavailableRouteResult()
return planH5Route(from, to, 'TRANSIT')
}
return new Promise((resolve) => {
@@ -417,13 +459,14 @@ export function searchPoi(
pageSize: number = 10
): Promise<TencentSearchResult> {
if (isH5BrowserRuntime) {
console.info('H5 端跳过腾讯地图 POI WebService 搜索,避免浏览器 CORS 拦截:', {
keyword,
region,
pageIndex,
pageSize
})
return Promise.resolve(createUnavailableSearchResult())
return searchOutdoorPlaces({ keyword, region, pageSize })
.then(({ items }) => ({
status: 0,
message: 'ok',
count: items.length,
data: items.map(toTencentPoi)
}))
.catch((error) => createUnavailableSearchResult(error instanceof Error ? error.message : undefined))
}
const boundary = `region(${region},0)`
@@ -518,13 +561,17 @@ export function searchNearbyPoi(
radius: number = 1000
): Promise<TencentSearchResult> {
if (isH5BrowserRuntime) {
console.info('H5 端跳过腾讯地图周边 WebService 搜索,避免浏览器 CORS 拦截:', {
lat,
lng,
return searchOutdoorPlaces({
keyword,
radius
})
return Promise.resolve(createUnavailableSearchResult())
latitude: lat,
longitude: lng,
pageSize: 10
}).then(({ items }) => ({
status: 0,
message: 'ok',
count: items.length,
data: items.map(toTencentPoi)
})).catch((error) => createUnavailableSearchResult(error instanceof Error ? error.message : undefined))
}
const boundary = `nearby(${lat},${lng},${radius})`