同步 sgs-frontend-mobile 源码
Some checks failed
CI / verify (push) Has been cancelled

This commit is contained in:
lyf
2026-07-27 11:26:01 +08:00
parent 575dca430f
commit 9ea1bfab71
181 changed files with 24395 additions and 5212 deletions

View File

@@ -8,7 +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
}
export type WechatMiniProgramBridgeResult =
@@ -16,11 +15,6 @@ 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'
const BRIDGE_WAIT_TIMEOUT = 2500
const BRIDGE_POLL_INTERVAL = 50
@@ -28,7 +22,6 @@ 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 => {
@@ -115,31 +108,6 @@ const navigateToHostLocationPage = (bridge: MiniProgramBridge, target: WechatOpe
}
})
const navigateBackToHostPage = (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' }
@@ -150,22 +118,8 @@ const openOnce = async (target: WechatOpenLocationTarget): Promise<WechatMiniPro
return navigateToHostLocationPage(bridge, validation.value)
}
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' }
return navigateBackToHostPage(bridge)
}
export const openWechatMiniProgramLocation = (target: WechatOpenLocationTarget) => {
if (pendingNavigation) return pendingNavigation
pendingNavigation = openOnce(target).finally(() => { pendingNavigation = null })
return pendingNavigation
}
export const returnToWechatMiniProgram = () => {
if (pendingReturn) return pendingReturn
pendingReturn = returnOnce().finally(() => { pendingReturn = null })
return pendingReturn
}

View File

@@ -0,0 +1,490 @@
export interface GuideFloorBasemapViewBounds {
minX: number
maxX: number
minZ: number
maxZ: number
screenXAxis: '+X' | '-X'
screenYAxis: '+Z' | '-Z'
}
export interface GuideFloorBasemapCameraProjection {
type: 'perspective'
position: { x: number; y: number; z: number }
target: { x: number; y: number; z: number }
up: { x: number; y: number; z: number }
fov: number
near: number
far: number
aspect: number
}
export interface GuideFloorBasemapOrthographicProjection {
type: 'orthographic-xz'
minX: number
maxX: number
minZ: number
maxZ: number
planeY: number
center: { x: number; z: number }
width: number
height: number
screenRight: { x: number; z: number }
screenDown: { x: number; z: number }
}
export interface GuideFloorBasemapInitialViewport {
centerX: number
centerZ: number
visibleWorldSpan: number
maxVisibleWorldSpan: number
}
export interface GuideFloorBasemapEntry {
floorId: string
floorCode: string
modelVersion: string
projection?: GuideFloorBasemapOrthographicProjection
initialViewport?: GuideFloorBasemapInitialViewport
viewBounds?: GuideFloorBasemapViewBounds
cameraProjection?: GuideFloorBasemapCameraProjection
image: {
path: string
width: number
height: number
format: 'webp'
}
}
export interface GuideCompositeBasemapEntry extends GuideFloorBasemapEntry {
role: 'SAME_GROUND_COMPOSITE'
assetId: string
modelUrl: string
coverageFloorCodes: string[]
coverageFloorIds: string[]
}
export interface GuideFloorBasemapManifest {
schemaVersion: number
render?: {
projection?: string
projectionVersion?: string
}
floors: GuideFloorBasemapEntry[]
routeAssets: GuideCompositeBasemapEntry[]
}
export interface GuideFloorBasemapPoint {
x: number
y?: number
z: number
}
export interface GuideFloorBasemapProjectionFrame {
width: number
height: number
offsetX: number
offsetY: number
}
export const GUIDE_FLOOR_BASEMAP_MANIFEST_URL = '/static/guide-floor-basemaps/manifest.json'
export const GUIDE_FLOOR_BASEMAP_PROJECTION = 'orthographic-xz'
export const GUIDE_FLOOR_BASEMAP_PROJECTION_VERSION = 'ortho-yaw54-v2'
export const GUIDE_FLOOR_BASEMAP_SCHEMA_VERSION = 4
let manifestPromise: Promise<GuideFloorBasemapManifest | null> | null = null
const isFiniteNumber = (value: unknown): value is number => (
typeof value === 'number' && Number.isFinite(value)
)
const isValidViewBounds = (value: Partial<GuideFloorBasemapViewBounds> | null | undefined) => (
Boolean(value)
&& isFiniteNumber(value?.minX)
&& isFiniteNumber(value?.maxX)
&& isFiniteNumber(value?.minZ)
&& isFiniteNumber(value?.maxZ)
&& value!.maxX > value!.minX
&& value!.maxZ > value!.minZ
&& (value!.screenXAxis === '+X' || value!.screenXAxis === '-X')
&& (value!.screenYAxis === '+Z' || value!.screenYAxis === '-Z')
)
const isFiniteVector3 = (value: { x?: unknown; y?: unknown; z?: unknown } | null | undefined) => (
isFiniteNumber(value?.x)
&& isFiniteNumber(value?.y)
&& isFiniteNumber(value?.z)
)
const isValidCameraProjection = (
value: Partial<GuideFloorBasemapCameraProjection> | null | undefined
) => (
value?.type === 'perspective'
&& isFiniteVector3(value.position)
&& isFiniteVector3(value.target)
&& isFiniteVector3(value.up)
&& isFiniteNumber(value.fov)
&& value.fov > 0
&& value.fov < 180
&& isFiniteNumber(value.aspect)
&& value.aspect > 0
)
export const isValidGuideFloorOrthographicProjection = (
value: Partial<GuideFloorBasemapOrthographicProjection> | null | undefined
) => {
if (
value?.type !== 'orthographic-xz'
|| !isFiniteNumber(value.minX)
|| !isFiniteNumber(value.maxX)
|| !isFiniteNumber(value.minZ)
|| !isFiniteNumber(value.maxZ)
|| value.maxX <= value.minX
|| value.maxZ <= value.minZ
|| !isFiniteNumber(value.planeY)
|| !isFiniteNumber(value.center?.x)
|| !isFiniteNumber(value.center?.z)
|| !isFiniteNumber(value.width)
|| value.width <= 0
|| !isFiniteNumber(value.height)
|| value.height <= 0
|| !isFiniteNumber(value.screenRight?.x)
|| !isFiniteNumber(value.screenRight?.z)
|| !isFiniteNumber(value.screenDown?.x)
|| !isFiniteNumber(value.screenDown?.z)
) return false
const rightLength = Math.hypot(value.screenRight.x, value.screenRight.z)
const downLength = Math.hypot(value.screenDown.x, value.screenDown.z)
const dot = value.screenRight.x * value.screenDown.x
+ value.screenRight.z * value.screenDown.z
return Math.abs(rightLength - 1) < 1e-6
&& Math.abs(downLength - 1) < 1e-6
&& Math.abs(dot) < 1e-6
}
export const isValidGuideFloorBasemapInitialViewport = (
value: Partial<GuideFloorBasemapInitialViewport> | null | undefined
) => Boolean(
value
&& isFiniteNumber(value.centerX)
&& isFiniteNumber(value.centerZ)
&& isFiniteNumber(value.visibleWorldSpan)
&& value.visibleWorldSpan > 0
&& isFiniteNumber(value.maxVisibleWorldSpan)
&& value.maxVisibleWorldSpan >= value.visibleWorldSpan
)
export const isCompatibleGuideFloorBasemapManifest = (
manifest: GuideFloorBasemapManifest | null | undefined
) => {
if (!manifest || !Array.isArray(manifest.floors) || !Array.isArray(manifest.routeAssets)) return false
return manifest.schemaVersion === GUIDE_FLOOR_BASEMAP_SCHEMA_VERSION
&& manifest.render?.projection === GUIDE_FLOOR_BASEMAP_PROJECTION
&& manifest.render?.projectionVersion === GUIDE_FLOOR_BASEMAP_PROJECTION_VERSION
}
const isValidGuideBasemapEntry = (entry: GuideFloorBasemapEntry | null | undefined) => Boolean(
entry
&& isValidGuideFloorOrthographicProjection(entry.projection)
&& isValidGuideFloorBasemapInitialViewport(entry.initialViewport)
&& Math.abs(
entry.projection!.width / entry.projection!.height
- entry.image.width / entry.image.height
) < 1e-6
&& Boolean(entry.image?.path)
&& isFiniteNumber(entry.image?.width)
&& isFiniteNumber(entry.image?.height)
&& entry.image.width > 0
&& entry.image.height > 0
)
const normalizeFloorReference = (value: unknown) => String(value || '').trim().toUpperCase()
const getCompositeCoverageIdentities = (entry: GuideCompositeBasemapEntry) => {
if (
entry.role !== 'SAME_GROUND_COMPOSITE'
|| !entry.assetId
|| !entry.modelUrl
|| !entry.modelVersion
|| !entry.floorCode
|| !Array.isArray(entry.coverageFloorCodes)
|| !Array.isArray(entry.coverageFloorIds)
|| entry.coverageFloorCodes.length <= 1
|| entry.coverageFloorCodes.length !== entry.coverageFloorIds.length
|| !isValidGuideBasemapEntry(entry)
) return null
const identities = entry.coverageFloorCodes.map((floorCode, index) => new Set([
normalizeFloorReference(floorCode),
normalizeFloorReference(entry.coverageFloorIds[index])
].filter(Boolean)))
return identities.every((identity) => identity.size > 0) ? identities : null
}
export const getGuideFloorBasemapWorldBounds = (
basemap: GuideFloorBasemapEntry | null | undefined
) => {
if (isValidGuideFloorOrthographicProjection(basemap?.projection)) {
const projection = basemap!.projection!
return {
minX: projection.minX,
maxX: projection.maxX,
minZ: projection.minZ,
maxZ: projection.maxZ,
screenRight: projection.screenRight,
screenDown: projection.screenDown,
projectionCenterX: projection.center.x,
projectionCenterZ: projection.center.z,
projectionWidth: projection.width,
projectionHeight: projection.height,
initialVisibleWorldSpan: basemap?.initialViewport?.visibleWorldSpan,
maxVisibleWorldSpan: basemap?.initialViewport?.maxVisibleWorldSpan
}
}
return isValidViewBounds(basemap?.viewBounds) ? basemap!.viewBounds! : null
}
export const findGuideFloorBasemap = (
manifest: GuideFloorBasemapManifest | null | undefined,
floorId: string,
modelVersion?: string
) => {
if (!isCompatibleGuideFloorBasemapManifest(manifest)) return null
const normalizedFloorId = String(floorId || '')
const normalizedVersion = String(modelVersion || '')
return manifest?.floors.find((floor) => (
(String(floor.floorId) === normalizedFloorId || floor.floorCode === normalizedFloorId)
&& (!normalizedVersion || floor.modelVersion === normalizedVersion)
&& isValidGuideBasemapEntry(floor)
)) || null
}
export const findGuideCompositeBasemap = (
manifest: GuideFloorBasemapManifest | null | undefined,
coverageFloorReferences: string[]
) => {
if (!isCompatibleGuideFloorBasemapManifest(manifest)) return null
const routeFloorReferences = Array.from(new Set(
coverageFloorReferences.map(normalizeFloorReference).filter(Boolean)
))
if (routeFloorReferences.length <= 1) return null
return manifest!.routeAssets.find((entry) => {
const identities = getCompositeCoverageIdentities(entry)
if (!identities || identities.length !== routeFloorReferences.length) return false
return routeFloorReferences.every((reference) => (
identities.some((identity) => identity.has(reference))
)) && identities.every((identity) => (
routeFloorReferences.some((reference) => identity.has(reference))
))
}) || null
}
export const getGuideFloorBasemapFrame = (
containerWidth: number,
containerHeight: number,
imageWidth: number,
imageHeight: number,
fit: 'contain' | 'cover' = 'contain'
): GuideFloorBasemapProjectionFrame => {
const safeContainerWidth = Math.max(containerWidth, 1)
const safeContainerHeight = Math.max(containerHeight, 1)
const widthScale = safeContainerWidth / Math.max(imageWidth, 1)
const heightScale = safeContainerHeight / Math.max(imageHeight, 1)
const scale = fit === 'cover'
? Math.max(widthScale, heightScale)
: Math.min(widthScale, heightScale)
const width = imageWidth * scale
const height = imageHeight * scale
return {
width,
height,
offsetX: (safeContainerWidth - width) / 2,
offsetY: (safeContainerHeight - height) / 2
}
}
export const projectPointToGuideFloorBasemap = (
point: GuideFloorBasemapPoint,
basemap: GuideFloorBasemapEntry,
frame: GuideFloorBasemapProjectionFrame
) => {
const projection = basemap.projection
if (isValidGuideFloorOrthographicProjection(projection)) {
const deltaX = point.x - projection!.center.x
const deltaZ = point.z - projection!.center.z
const screenXRatio = 0.5 + (
deltaX * projection!.screenRight.x + deltaZ * projection!.screenRight.z
) / projection!.width
const screenYRatio = 0.5 + (
deltaX * projection!.screenDown.x + deltaZ * projection!.screenDown.z
) / projection!.height
return {
x: frame.offsetX + screenXRatio * frame.width,
y: frame.offsetY + screenYRatio * frame.height
}
}
const camera = basemap.cameraProjection
if (camera && isValidCameraProjection(camera)) {
const position = camera.position
const forward = {
x: camera.target.x - position.x,
y: camera.target.y - position.y,
z: camera.target.z - position.z
}
const forwardLength = Math.hypot(forward.x, forward.y, forward.z) || 1
forward.x /= forwardLength
forward.y /= forwardLength
forward.z /= forwardLength
const right = {
x: forward.y * camera.up.z - forward.z * camera.up.y,
y: forward.z * camera.up.x - forward.x * camera.up.z,
z: forward.x * camera.up.y - forward.y * camera.up.x
}
const rightLength = Math.hypot(right.x, right.y, right.z) || 1
right.x /= rightLength
right.y /= rightLength
right.z /= rightLength
const screenUp = {
x: right.y * forward.z - right.z * forward.y,
y: right.z * forward.x - right.x * forward.z,
z: right.x * forward.y - right.y * forward.x
}
const pointY = point.y || 0
const relative = {
x: point.x - position.x,
y: pointY - position.y,
z: point.z - position.z
}
const depth = relative.x * forward.x + relative.y * forward.y + relative.z * forward.z
const safeDepth = Math.max(depth, 0.001)
const tangent = Math.tan((camera.fov * Math.PI) / 360)
const ndcX = (relative.x * right.x + relative.y * right.y + relative.z * right.z)
/ (safeDepth * tangent * camera.aspect)
const ndcY = (relative.x * screenUp.x + relative.y * screenUp.y + relative.z * screenUp.z)
/ (safeDepth * tangent)
return {
x: frame.offsetX + ((ndcX + 1) / 2) * frame.width,
y: frame.offsetY + ((1 - ndcY) / 2) * frame.height
}
}
const bounds = basemap.viewBounds
if (!bounds) {
return {
x: frame.offsetX + frame.width / 2,
y: frame.offsetY + frame.height / 2
}
}
const xRatio = (point.x - bounds.minX) / (bounds.maxX - bounds.minX)
const zRatio = (point.z - bounds.minZ) / (bounds.maxZ - bounds.minZ)
const screenXRatio = bounds.screenXAxis === '+X' ? xRatio : 1 - xRatio
const screenYRatio = bounds.screenYAxis === '-Z' ? 1 - zRatio : zRatio
return {
x: frame.offsetX + screenXRatio * frame.width,
y: frame.offsetY + screenYRatio * frame.height
}
}
export const unprojectGuideFloorBasemapPoint = (
point: { x: number; y: number },
basemap: GuideFloorBasemapEntry,
frame: GuideFloorBasemapProjectionFrame
) => {
const projection = basemap.projection
if (isValidGuideFloorOrthographicProjection(projection)) {
const screenXRatio = (point.x - frame.offsetX) / Math.max(frame.width, 1)
const screenYRatio = (point.y - frame.offsetY) / Math.max(frame.height, 1)
const right = (screenXRatio - 0.5) * projection!.width
const down = (screenYRatio - 0.5) * projection!.height
return {
x: projection!.center.x
+ right * projection!.screenRight.x
+ down * projection!.screenDown.x,
z: projection!.center.z
+ right * projection!.screenRight.z
+ down * projection!.screenDown.z
}
}
const camera = basemap.cameraProjection
if (camera && isValidCameraProjection(camera)) {
const forward = {
x: camera.target.x - camera.position.x,
y: camera.target.y - camera.position.y,
z: camera.target.z - camera.position.z
}
const forwardLength = Math.hypot(forward.x, forward.y, forward.z) || 1
forward.x /= forwardLength
forward.y /= forwardLength
forward.z /= forwardLength
const right = {
x: forward.y * camera.up.z - forward.z * camera.up.y,
y: forward.z * camera.up.x - forward.x * camera.up.z,
z: forward.x * camera.up.y - forward.y * camera.up.x
}
const rightLength = Math.hypot(right.x, right.y, right.z) || 1
right.x /= rightLength
right.y /= rightLength
right.z /= rightLength
const screenUp = {
x: right.y * forward.z - right.z * forward.y,
y: right.z * forward.x - right.x * forward.z,
z: right.x * forward.y - right.y * forward.x
}
const ndcX = ((point.x - frame.offsetX) / Math.max(frame.width, 1)) * 2 - 1
const ndcY = 1 - ((point.y - frame.offsetY) / Math.max(frame.height, 1)) * 2
const tangent = Math.tan((camera.fov * Math.PI) / 360)
const direction = {
x: forward.x + right.x * ndcX * tangent * camera.aspect + screenUp.x * ndcY * tangent,
y: forward.y + right.y * ndcX * tangent * camera.aspect + screenUp.y * ndcY * tangent,
z: forward.z + right.z * ndcX * tangent * camera.aspect + screenUp.z * ndcY * tangent
}
const directionLength = Math.hypot(direction.x, direction.y, direction.z) || 1
direction.x /= directionLength
direction.y /= directionLength
direction.z /= directionLength
const planeY = camera.target.y
const distance = Math.abs(direction.y) > 1e-6
? (planeY - camera.position.y) / direction.y
: 0
return {
x: camera.position.x + direction.x * distance,
z: camera.position.z + direction.z * distance
}
}
const bounds = basemap.viewBounds
if (!bounds) return { x: 0, z: 0 }
const screenXRatio = (point.x - frame.offsetX) / Math.max(frame.width, 1)
const screenYRatio = (point.y - frame.offsetY) / Math.max(frame.height, 1)
const xRatio = bounds.screenXAxis === '+X' ? screenXRatio : 1 - screenXRatio
const zRatio = bounds.screenYAxis === '-Z' ? 1 - screenYRatio : screenYRatio
return {
x: bounds.minX + xRatio * (bounds.maxX - bounds.minX),
z: bounds.minZ + zRatio * (bounds.maxZ - bounds.minZ)
}
}
export const loadGuideFloorBasemapManifest = async () => {
if (manifestPromise) return manifestPromise
if (typeof fetch !== 'function') return null
const request = fetch(GUIDE_FLOOR_BASEMAP_MANIFEST_URL, { cache: 'no-cache' })
.then(async (response) => {
if (!response.ok) return null
const manifest = await response.json() as GuideFloorBasemapManifest
return isCompatibleGuideFloorBasemapManifest(manifest) ? manifest : null
})
.catch(() => null)
manifestPromise = request
const manifest = await request
if (!manifest && manifestPromise === request) manifestPromise = null
return manifest
}
export const resetGuideFloorBasemapManifestCacheForTests = () => {
manifestPromise = null
}

View File

@@ -1,5 +1,9 @@
import * as THREE from 'three'
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js'
import {
recordGuidePerformance,
startGuidePerformance
} from '@/services/performance/guidePerformance'
export interface GuideModelResourceSet {
geometries: Set<THREE.BufferGeometry>
@@ -357,6 +361,14 @@ export class GuideModelLoadManager {
if (cached) {
cached.lastUsedAt = Date.now()
this.diagnostics.hits += 1
recordGuidePerformance({
kind: 'model',
name: options.label,
startedAt: getNow(),
durationMs: 0,
outcome: 'cache-hit',
detail: { url, key }
})
logModelDiagnostic('cache-hit', {
label: options.label,
url,
@@ -376,8 +388,17 @@ export class GuideModelLoadManager {
let inFlight = this.inFlightCache.get(key)
const startedAt = getNow()
let finishPerformance: ReturnType<typeof startGuidePerformance> | null = null
if (inFlight) {
this.diagnostics.inFlightHits += 1
recordGuidePerformance({
kind: 'model',
name: options.label,
startedAt,
durationMs: 0,
outcome: 'cache-hit',
detail: { url, key, layer: 'in-flight' }
})
logModelDiagnostic('in-flight-hit', {
label: options.label,
url,
@@ -385,6 +406,7 @@ export class GuideModelLoadManager {
diagnostics: this.getDiagnostics()
})
} else {
finishPerformance = startGuidePerformance('model', options.label, { url, key })
logModelDiagnostic('load-start', {
label: options.label,
url,
@@ -398,6 +420,9 @@ export class GuideModelLoadManager {
try {
gltf = await inFlight
} catch (error) {
finishPerformance?.('failure', {
error: error instanceof Error ? error.message : String(error)
})
logModelDiagnostic('load-failed', {
label: options.label,
url,
@@ -420,6 +445,9 @@ export class GuideModelLoadManager {
}
this.sourceCache.set(key, entry)
this.trim()
finishPerformance?.('success', {
sourceEntries: this.sourceCache.size
})
logModelDiagnostic('load-complete', {
label: options.label,
url,

View File

@@ -0,0 +1,147 @@
const CACHE_NAME = 'sgs-guide-model-v1'
const INDEX_STORAGE_KEY = 'sgs.guide.model-cache-index.v1'
const MAX_ENTRIES = 6
interface CacheIndexEntry {
key: string
touchedAt: number
}
export interface PersistentModelAsset {
url: string
release: () => void
}
const getCacheStorage = () => (
typeof globalThis !== 'undefined' && 'caches' in globalThis
? globalThis.caches
: null
)
const getStorage = () => (
typeof localStorage !== 'undefined' ? localStorage : null
)
const buildCacheKey = (url: string, version?: string) => {
const normalizedUrl = url.trim()
const normalizedVersion = version?.trim() || normalizedUrl
const separator = normalizedUrl.includes('?') ? '&' : '?'
return `${normalizedUrl}${separator}__sgs_model_version=${encodeURIComponent(normalizedVersion)}`
}
const readIndex = (): CacheIndexEntry[] => {
try {
const raw = getStorage()?.getItem(INDEX_STORAGE_KEY)
const parsed = raw ? JSON.parse(raw) : []
return Array.isArray(parsed)
? parsed.filter((entry): entry is CacheIndexEntry => (
Boolean(entry)
&& typeof entry.key === 'string'
&& typeof entry.touchedAt === 'number'
))
: []
} catch {
return []
}
}
const writeIndex = (entries: CacheIndexEntry[]) => {
try {
getStorage()?.setItem(INDEX_STORAGE_KEY, JSON.stringify(entries))
} catch {
// Persistent cache is an optimization. Storage quota failures must not block map loading.
}
}
const touchIndex = (key: string) => {
const now = Date.now()
const next = readIndex()
.filter((entry) => entry.key !== key)
next.push({ key, touchedAt: now })
writeIndex(next)
return next
}
const removeFromIndex = (key: string) => {
writeIndex(readIndex().filter((entry) => entry.key !== key))
}
export class GuideModelPersistentCache {
async get(url: string, version?: string): Promise<PersistentModelAsset | null> {
const cacheStorage = getCacheStorage()
if (!cacheStorage || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return null
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
const response = await cache.match(key)
if (!response) return null
const blob = await response.blob()
if (!blob.size) {
await cache.delete(key)
removeFromIndex(key)
return null
}
touchIndex(key)
const objectUrl = URL.createObjectURL(blob)
return {
url: objectUrl,
release: () => URL.revokeObjectURL(objectUrl)
}
} catch {
return null
}
}
async store(url: string, version?: string): Promise<void> {
const cacheStorage = getCacheStorage()
if (!cacheStorage || typeof fetch !== 'function') return
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
if (await cache.match(key)) {
await this.prune(cache, touchIndex(key))
return
}
// The preceding GLTF request is normally still in the browser HTTP cache, so this does
// not redownload a successful asset on standard H5 browsers.
const response = await fetch(url, { cache: 'force-cache' })
if (!response.ok || !response.body) return
await cache.put(key, response)
await this.prune(cache, touchIndex(key))
} catch {
// Cache writes are deliberately best-effort.
}
}
async remove(url: string, version?: string): Promise<void> {
const cacheStorage = getCacheStorage()
if (!cacheStorage) return
const key = buildCacheKey(url, version)
try {
const cache = await cacheStorage.open(CACHE_NAME)
await cache.delete(key)
} catch {
// Ignore cache cleanup failures and continue with a normal network request.
}
removeFromIndex(key)
}
private async prune(cache: Cache, entries: CacheIndexEntry[]) {
const staleEntries = [...entries]
.sort((left, right) => left.touchedAt - right.touchedAt)
.slice(0, Math.max(0, entries.length - MAX_ENTRIES))
if (!staleEntries.length) return
await Promise.all(staleEntries.map((entry) => cache.delete(entry.key)))
const staleKeys = new Set(staleEntries.map((entry) => entry.key))
writeIndex(entries.filter((entry) => !staleKeys.has(entry.key)))
}
}
export const guideModelPersistentCache = new GuideModelPersistentCache()

View File

@@ -0,0 +1,154 @@
import {
shouldPreferTwoDimensionalGuide,
type GuideRenderNetworkInfo
} from '@/services/performance/guideRenderModePolicy'
export type BackgroundPreloadTask = () => void | Promise<void>
interface IdleDeadlineLike {
timeRemaining?: () => number
didTimeout?: boolean
}
interface BackgroundPreloadSchedulerHost {
setTimeout: typeof setTimeout
clearTimeout: typeof clearTimeout
requestIdleCallback?: (callback: (deadline: IdleDeadlineLike) => void, options?: { timeout?: number }) => number
cancelIdleCallback?: (handle: number) => void
}
export type BackgroundPreloadNetworkInfo = GuideRenderNetworkInfo
export interface BackgroundPreloadPolicy {
allowed: boolean
reason: 'normal' | 'save-data' | 'slow-network'
delayMs: number
}
export interface BackgroundPreloadSchedulerOptions {
delayMs?: number
idleTimeoutMs?: number
networkInfo?: BackgroundPreloadNetworkInfo | null
}
const normalizeEffectiveType = (effectiveType?: string) => (
String(effectiveType || '').trim().toLowerCase()
)
const getDefaultHost = (): BackgroundPreloadSchedulerHost | null => {
if (typeof window === 'undefined') return null
const candidate = window as typeof window & {
requestIdleCallback?: BackgroundPreloadSchedulerHost['requestIdleCallback']
cancelIdleCallback?: BackgroundPreloadSchedulerHost['cancelIdleCallback']
}
return {
setTimeout: window.setTimeout.bind(window),
clearTimeout: window.clearTimeout.bind(window),
requestIdleCallback: candidate.requestIdleCallback?.bind(window),
cancelIdleCallback: candidate.cancelIdleCallback?.bind(window)
}
}
export const getBackgroundPreloadPolicy = (
networkInfo?: BackgroundPreloadNetworkInfo | null
): BackgroundPreloadPolicy => {
if (networkInfo?.saveData) {
return { allowed: false, reason: 'save-data', delayMs: 0 }
}
if (shouldPreferTwoDimensionalGuide(networkInfo)) {
return { allowed: false, reason: 'slow-network', delayMs: 0 }
}
const effectiveType = normalizeEffectiveType(networkInfo?.effectiveType)
return {
allowed: true,
reason: 'normal',
delayMs: effectiveType === '3g' ? 2400 : 900
}
}
export const getBrowserNetworkInfo = (): BackgroundPreloadNetworkInfo | null => {
if (typeof navigator === 'undefined') return null
const candidate = navigator as Navigator & {
connection?: BackgroundPreloadNetworkInfo
}
return candidate.connection || null
}
export const createBackgroundPreloadScheduler = (
host: BackgroundPreloadSchedulerHost | null = getDefaultHost()
) => {
let generation = 0
let delayHandle: ReturnType<typeof setTimeout> | null = null
let idleHandle: number | null = null
const clearScheduledWork = () => {
if (delayHandle !== null) {
host?.clearTimeout(delayHandle)
delayHandle = null
}
if (idleHandle !== null) {
host?.cancelIdleCallback?.(idleHandle)
idleHandle = null
}
}
const cancel = () => {
generation += 1
clearScheduledWork()
}
const schedule = (
task: BackgroundPreloadTask,
options: BackgroundPreloadSchedulerOptions = {}
) => {
cancel()
if (!host) return false
const policy = getBackgroundPreloadPolicy(
options.networkInfo === undefined ? getBrowserNetworkInfo() : options.networkInfo
)
if (!policy.allowed) return false
const scheduledGeneration = generation
const idleTimeoutMs = Math.max(options.idleTimeoutMs ?? 3000, 0)
const delayMs = Math.max(options.delayMs ?? policy.delayMs, 0)
const runWhenIdle = () => {
if (scheduledGeneration !== generation) return
const run = () => {
idleHandle = null
if (scheduledGeneration !== generation) return
void task()
}
if (host.requestIdleCallback) {
idleHandle = host.requestIdleCallback(run, { timeout: idleTimeoutMs })
} else {
delayHandle = host.setTimeout(run, 0)
}
}
if (delayMs > 0) {
delayHandle = host.setTimeout(() => {
delayHandle = null
runWhenIdle()
}, delayMs)
} else {
runWhenIdle()
}
return true
}
return {
schedule,
cancel,
dispose: cancel
}
}

View File

@@ -0,0 +1,163 @@
export type GuidePerformanceKind = 'api' | 'model' | 'media' | 'interaction'
export type GuidePerformanceOutcome = 'start' | 'success' | 'failure' | 'cache-hit' | 'stale-fallback' | 'cancelled'
export interface GuidePerformanceRecord {
kind: GuidePerformanceKind
name: string
startedAt: number
durationMs?: number
outcome: GuidePerformanceOutcome
detail?: Record<string, unknown>
}
export interface GuidePerformanceOperationSummary {
kind: GuidePerformanceKind
name: string
count: number
successCount: number
failureCount: number
cancelledCount: number
cacheHitCount: number
staleFallbackCount: number
p50Ms?: number
p95Ms?: number
maxMs?: number
}
export interface GuidePerformanceSummary {
operationCount: number
apiCacheHitCount: number
apiNetworkRequestCount: number
apiCacheHitRate?: number
operations: GuidePerformanceOperationSummary[]
}
const MAX_RECORDS = 240
const records: GuidePerformanceRecord[] = []
const now = () => (
typeof performance !== 'undefined' && typeof performance.now === 'function'
? performance.now()
: Date.now()
)
const publish = () => {
if (typeof window === 'undefined') return
const target = window as typeof window & {
__SGS_GUIDE_PERFORMANCE__?: {
snapshot: () => GuidePerformanceRecord[]
summary: () => GuidePerformanceSummary
clear: () => void
}
}
target.__SGS_GUIDE_PERFORMANCE__ = {
snapshot: () => getGuidePerformanceRecords(),
summary: () => getGuidePerformanceSummary(),
clear: clearGuidePerformanceRecords
}
}
export const recordGuidePerformance = (record: GuidePerformanceRecord) => {
records.push({
...record,
detail: record.detail ? { ...record.detail } : undefined
})
if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS)
publish()
}
export const startGuidePerformance = (
kind: GuidePerformanceKind,
name: string,
detail?: Record<string, unknown>
) => {
const startedAt = now()
recordGuidePerformance({ kind, name, startedAt, outcome: 'start', detail })
return (
outcome: Exclude<GuidePerformanceOutcome, 'start'>,
nextDetail?: Record<string, unknown>
) => {
recordGuidePerformance({
kind,
name,
startedAt,
durationMs: Math.round(Math.max(0, now() - startedAt)),
outcome,
detail: {
...detail,
...nextDetail
}
})
}
}
export const getGuidePerformanceRecords = () => records.map((record) => ({
...record,
detail: record.detail ? { ...record.detail } : undefined
}))
const percentile = (durations: number[], ratio: number) => {
if (!durations.length) return undefined
const sorted = [...durations].sort((left, right) => left - right)
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1))
return sorted[index]
}
export const getGuidePerformanceSummary = (): GuidePerformanceSummary => {
const completed = records.filter((record) => record.outcome !== 'start')
const grouped = new Map<string, GuidePerformanceRecord[]>()
completed.forEach((record) => {
const key = `${record.kind}:${record.name}`
const items = grouped.get(key) || []
items.push(record)
grouped.set(key, items)
})
const operations = [...grouped.values()]
.map((items): GuidePerformanceOperationSummary => {
const sample = items[0]
const durations = items
.map((item) => item.durationMs)
.filter((duration): duration is number => typeof duration === 'number')
return {
kind: sample.kind,
name: sample.name,
count: items.length,
successCount: items.filter((item) => item.outcome === 'success').length,
failureCount: items.filter((item) => item.outcome === 'failure').length,
cancelledCount: items.filter((item) => item.outcome === 'cancelled').length,
cacheHitCount: items.filter((item) => item.outcome === 'cache-hit').length,
staleFallbackCount: items.filter((item) => item.outcome === 'stale-fallback').length,
p50Ms: percentile(durations, 0.5),
p95Ms: percentile(durations, 0.95),
maxMs: durations.length ? Math.max(...durations) : undefined
}
})
.sort((left, right) => left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name))
const apiRecords = completed.filter((record) => record.kind === 'api')
const apiCacheHitCount = apiRecords.filter((record) => record.outcome === 'cache-hit').length
const apiNetworkRequestCount = apiRecords.filter((record) => (
record.outcome === 'success' || record.outcome === 'failure'
)).length
return {
operationCount: completed.length,
apiCacheHitCount,
apiNetworkRequestCount,
apiCacheHitRate: apiCacheHitCount + apiNetworkRequestCount > 0
? Number((apiCacheHitCount / (apiCacheHitCount + apiNetworkRequestCount)).toFixed(4))
: undefined,
operations
}
}
export const clearGuidePerformanceRecords = () => {
records.splice(0, records.length)
publish()
}
publish()

View File

@@ -0,0 +1,58 @@
export interface GuideRenderNetworkInfo {
saveData?: boolean
effectiveType?: string
downlink?: number
rtt?: number
}
export type GuideIndoorRenderMode = 'three-d' | 'two-d'
const twoDimensionalNetworkTypes = new Set(['slow-2g', '2g'])
export const GUIDE_WEAK_NETWORK_THRESHOLDS = {
lowDownlinkMbps: 1.5,
highRttMs: 500
} as const
const normalizeEffectiveType = (effectiveType?: string) => (
String(effectiveType || '').trim().toLowerCase()
)
const isPositiveFiniteNumber = (value: unknown): value is number => (
typeof value === 'number' && Number.isFinite(value) && value > 0
)
const isReportedDownlinkWeak = (downlink: unknown) => (
isPositiveFiniteNumber(downlink)
&& downlink < GUIDE_WEAK_NETWORK_THRESHOLDS.lowDownlinkMbps
)
const isReportedRttWeak = (rtt: unknown) => (
isPositiveFiniteNumber(rtt)
&& rtt >= GUIDE_WEAK_NETWORK_THRESHOLDS.highRttMs
)
// A GLB scene is useful only when it can be interactive. Prefer the WebP
// basemap before requesting model assets when the browser explicitly reports a
// constrained connection. Visitors can always opt back into 3D manually.
export const shouldPreferTwoDimensionalGuide = (
networkInfo: GuideRenderNetworkInfo | null | undefined
) => {
if (!networkInfo) return false
if (networkInfo.saveData) return true
const effectiveType = normalizeEffectiveType(networkInfo.effectiveType)
if (twoDimensionalNetworkTypes.has(effectiveType)) return true
return isReportedDownlinkWeak(networkInfo.downlink) || isReportedRttWeak(networkInfo.rtt)
}
export const resolveInitialGuideRenderMode = (
queryValue: string | null | undefined,
networkInfo: GuideRenderNetworkInfo | null | undefined
): GuideIndoorRenderMode => {
const requestedMode = String(queryValue || '').trim().toLowerCase()
if (requestedMode === '2d' || requestedMode === 'two-d') return 'two-d'
if (requestedMode === '3d' || requestedMode === 'three-d') return 'three-d'
return shouldPreferTwoDimensionalGuide(networkInfo) ? 'two-d' : 'three-d'
}

View File

@@ -0,0 +1,51 @@
export interface GuideRendererEnvironment {
devicePixelRatio?: number
deviceMemory?: number
hardwareConcurrency?: number
maxTouchPoints?: number
viewportWidth?: number
saveData?: boolean
userAgent?: string
}
const mobileUserAgent = /Android|iPhone|iPad|iPod|Mobile/i
const readGuideRendererEnvironment = (): GuideRendererEnvironment => {
if (typeof window === 'undefined') return {}
const navigatorWithHints = navigator as Navigator & {
deviceMemory?: number
connection?: { saveData?: boolean }
}
return {
devicePixelRatio: window.devicePixelRatio,
deviceMemory: navigatorWithHints.deviceMemory,
hardwareConcurrency: navigator.hardwareConcurrency,
maxTouchPoints: navigator.maxTouchPoints,
viewportWidth: window.innerWidth,
saveData: navigatorWithHints.connection?.saveData,
userAgent: navigator.userAgent
}
}
const isMobileEnvironment = (environment: GuideRendererEnvironment) => (
mobileUserAgent.test(environment.userAgent || '')
|| (Boolean(environment.maxTouchPoints) && (environment.viewportWidth || 0) <= 900)
)
export const getGuideRendererPixelRatio = (
environment: GuideRendererEnvironment = readGuideRendererEnvironment(),
desktopCap = 1.5
) => {
const devicePixelRatio = Number.isFinite(environment.devicePixelRatio)
? Math.max(environment.devicePixelRatio || 1, 0.75)
: 1
const mobile = isMobileEnvironment(environment)
const constrained = Boolean(environment.saveData)
|| Number.isFinite(environment.deviceMemory) && (environment.deviceMemory || 0) <= 2
|| Number.isFinite(environment.hardwareConcurrency) && (environment.hardwareConcurrency || 0) <= 2
const cap = constrained ? 1 : mobile ? Math.min(desktopCap, 1.25) : desktopCap
return Math.min(devicePixelRatio, Math.max(cap, 1))
}

View File

@@ -0,0 +1,60 @@
import type {
SgsMapSDKConstructor
} from '@/types/sgs-map-sdk'
let loadingScriptUrl = ''
let loadRequest: Promise<SgsMapSDKConstructor> | null = null
const findExistingScript = (scriptUrl: string) => (
Array.from(document.scripts).find((script) => script.src.endsWith(scriptUrl) || script.getAttribute('src') === scriptUrl)
)
export const loadSgsMapScript = (scriptUrl: string): Promise<SgsMapSDKConstructor> => {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return Promise.reject(new Error('SGS Map SDK 只能在 H5 浏览器环境中加载'))
}
if (window.SGSMapSDK) {
return Promise.resolve(window.SGSMapSDK)
}
if (loadRequest && loadingScriptUrl === scriptUrl) {
return loadRequest
}
loadingScriptUrl = scriptUrl
const request = new Promise<SgsMapSDKConstructor>((resolve, reject) => {
const existingScript = findExistingScript(scriptUrl)
const script = existingScript || document.createElement('script')
const resolveLoadedSdk = () => {
if (!window.SGSMapSDK) {
reject(new Error('SGS Map SDK 脚本已加载,但未发现 window.SGSMapSDK'))
return
}
resolve(window.SGSMapSDK)
}
script.addEventListener('load', resolveLoadedSdk, { once: true })
script.addEventListener('error', () => {
reject(new Error(`SGS Map SDK 脚本加载失败: ${scriptUrl}`))
}, { once: true })
if (!existingScript) {
script.src = scriptUrl
script.async = true
document.head.appendChild(script)
return
}
if (window.SGSMapSDK) {
resolveLoadedSdk()
}
}).finally(() => {
loadRequest = null
})
loadRequest = request
return request
}

View File

@@ -0,0 +1,165 @@
import type {
SgsMapEvents,
SgsMapSDKInstance,
SgsMarkerConfig,
SgsMapNode,
SgsRouteOptions,
SgsRouteResult
} from '@/types/sgs-map-sdk'
import {
loadSgsMapScript
} from './SgsMapScriptLoader'
interface SgsMapServiceOptions {
container: HTMLElement
scriptUrl: string
sdkUrl: string
targetOrigin: string
floorId: string | number
timeout: number
}
type SgsMapListener<K extends keyof SgsMapEvents> = (payload: SgsMapEvents[K]) => void
export class SgsMapService {
private sdk: SgsMapSDKInstance | null = null
private readyPromise: Promise<SgsMapEvents['ready']> | null = null
private resolveReady: ((payload: SgsMapEvents['ready']) => void) | null = null
private rejectReady: ((error: Error) => void) | null = null
private listeners: Array<() => void> = []
private externalListeners: Array<{
event: keyof SgsMapEvents
listener: (payload: SgsMapEvents[keyof SgsMapEvents]) => void
}> = []
private disposed = false
constructor(private readonly options: SgsMapServiceOptions) {}
async init() {
if (this.readyPromise) return this.readyPromise
this.readyPromise = new Promise<SgsMapEvents['ready']>((resolve, reject) => {
this.resolveReady = resolve
this.rejectReady = reject
})
loadSgsMapScript(this.options.scriptUrl)
.then((SDKConstructor) => {
if (this.disposed) {
this.rejectReady?.(new Error('SGS Map SDK 初始化已取消'))
return
}
this.sdk = new SDKConstructor({
container: this.options.container,
sdkUrl: this.options.sdkUrl,
targetOrigin: this.options.targetOrigin,
floorId: this.options.floorId,
timeout: this.options.timeout
})
this.externalListeners.forEach(({ event, listener }) => {
this.registerSdkListener(event, listener)
})
this.registerSdkListener('ready', (payload) => {
this.resolveReady?.(payload)
})
this.registerSdkListener('loadError', (payload) => {
this.rejectReady?.(new Error(payload.detail || 'SGS Map SDK 地图基座加载失败'))
})
this.registerSdkListener('error', (payload) => {
if (!this.sdk?.getIsReady()) {
this.rejectReady?.(new Error(payload.message || payload.code || 'SGS Map SDK 初始化失败'))
}
})
})
.catch((error) => {
this.rejectReady?.(error instanceof Error ? error : new Error('SGS Map SDK 初始化失败'))
})
return this.readyPromise
}
on<K extends keyof SgsMapEvents>(event: K, listener: SgsMapListener<K>) {
this.externalListeners.push({
event,
listener: listener as (payload: SgsMapEvents[keyof SgsMapEvents]) => void
})
if (this.sdk) {
this.registerSdkListener(event, listener)
}
}
private registerSdkListener<K extends keyof SgsMapEvents>(event: K, listener: SgsMapListener<K>) {
if (!this.sdk) return
this.sdk.on(event, listener)
this.listeners.push(() => {
this.sdk?.off(event, listener)
})
}
private async getReadySdk() {
if (!this.sdk) {
await this.init()
}
await this.readyPromise
if (!this.sdk || this.disposed) {
throw new Error('SGS Map SDK 已销毁')
}
return this.sdk
}
async changeFloor(floorId: string | number, options?: { forceReload?: boolean }) {
const sdk = await this.getReadySdk()
return sdk.changeFloor(floorId, this.options.timeout, options)
}
async focusTo(node: SgsMapNode | string) {
const sdk = await this.getReadySdk()
sdk.focusTo(node)
}
async addMarker(config: SgsMarkerConfig) {
const sdk = await this.getReadySdk()
sdk.addMarker(config)
}
async clearMarkers() {
const sdk = await this.getReadySdk()
sdk.clearMarkers()
}
async resetView() {
const sdk = await this.getReadySdk()
return sdk.resetView(this.options.timeout)
}
async setViewMode(mode: '2d' | '3d') {
const sdk = await this.getReadySdk()
return sdk.setViewMode(mode, this.options.timeout)
}
async planRoute(from: SgsMapNode | string, to: SgsMapNode | string, options?: SgsRouteOptions): Promise<SgsRouteResult> {
const sdk = await this.getReadySdk()
return sdk.planRoute(from, to, options, this.options.timeout)
}
destroy() {
this.disposed = true
this.listeners.splice(0).forEach((cleanup) => cleanup())
this.sdk?.destroy()
this.sdk = null
this.rejectReady?.(new Error('SGS Map SDK 已销毁'))
this.resolveReady = null
this.rejectReady = null
this.readyPromise = null
}
}