@collabdt/core 0.11.2 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/components/ui/FilesManager/src/FileItemComponent.js.map +1 -1
- package/dist/core/components/ui/uploadFile.d.ts +3 -2
- package/dist/core/components/ui/uploadFile.d.ts.map +1 -1
- package/dist/core/components/ui/uploadFile.js +8 -7
- package/dist/core/components/ui/uploadFile.js.map +1 -1
- package/dist/core/components/viewers/Viewer.d.ts.map +1 -1
- package/dist/core/components/viewers/Viewer.js +7 -10
- package/dist/core/components/viewers/Viewer.js.map +1 -1
- package/dist/core/components/viewers/bim/src/BimLoadingState/index.js +1 -1
- package/dist/core/components/viewers/bim/src/BimLoadingState/index.js.map +1 -1
- package/dist/core/components/viewers/bim/src/BimSidebar/src/FileTab/src/usePlaceableFileRows.d.ts.map +1 -1
- package/dist/core/components/viewers/bim/src/BimSidebar/src/FileTab/src/usePlaceableFileRows.js +12 -13
- package/dist/core/components/viewers/bim/src/BimSidebar/src/FileTab/src/usePlaceableFileRows.js.map +1 -1
- package/dist/core/components/viewers/bim/src/Splats/splatPlacementStore.d.ts +3 -3
- package/dist/core/components/viewers/bim/src/Splats/splatPlacementStore.d.ts.map +1 -1
- package/dist/core/components/viewers/bim/src/Splats/splatPlacementStore.js +2 -18
- package/dist/core/components/viewers/bim/src/Splats/splatPlacementStore.js.map +1 -1
- package/dist/core/components/viewers/bim/src/lib/applyModelPlacement.d.ts +1 -1
- package/dist/core/components/viewers/bim/src/lib/applyModelPlacement.d.ts.map +1 -1
- package/dist/core/components/viewers/bim/src/lib/applyModelPlacement.js +2 -2
- package/dist/core/components/viewers/bim/src/lib/applyModelPlacement.js.map +1 -1
- package/dist/core/components/viewers/bim/src/lib/buildingLocationParams.d.ts +1 -0
- package/dist/core/components/viewers/bim/src/lib/buildingLocationParams.d.ts.map +1 -1
- package/dist/core/components/viewers/bim/src/lib/buildingLocationParams.js +10 -2
- package/dist/core/components/viewers/bim/src/lib/buildingLocationParams.js.map +1 -1
- package/dist/core/components/viewers/bim/src/lib/useViewerLocation.d.ts +1 -1
- package/dist/core/components/viewers/bim/src/lib/useViewerLocation.js.map +1 -1
- package/dist/core/components/viewers/bim/utils/setCameraLookAt.d.ts.map +1 -1
- package/dist/core/components/viewers/bim/utils/setCameraLookAt.js +13 -14
- package/dist/core/components/viewers/bim/utils/setCameraLookAt.js.map +1 -1
- package/dist/core/components/viewers/map/MapViewer.d.ts.map +1 -1
- package/dist/core/components/viewers/map/MapViewer.js +11 -8
- package/dist/core/components/viewers/map/MapViewer.js.map +1 -1
- package/dist/core/components/viewers/map/datasets/src/minioDatasets.d.ts.map +1 -1
- package/dist/core/components/viewers/map/datasets/src/minioDatasets.js +16 -8
- package/dist/core/components/viewers/map/datasets/src/minioDatasets.js.map +1 -1
- package/dist/core/components/viewers/map/src/Geocoder.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/Geocoder.js +23 -20
- package/dist/core/components/viewers/map/src/Geocoder.js.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.js +7 -6
- package/dist/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.js.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/FileModelLayer/FileModelLayer.js +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/FileModelLayer/FileModelLayer.js.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.js +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.js.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/index.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/index.js +12 -23
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/index.js.map +1 -1
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useDatasetFeatures.d.ts +23 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useDatasetFeatures.d.ts.map +1 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useDatasetFeatures.js +67 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useDatasetFeatures.js.map +1 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useViewportDatasetToast.d.ts +4 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useViewportDatasetToast.d.ts.map +1 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useViewportDatasetToast.js +24 -0
- package/dist/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/useViewportDatasetToast.js.map +1 -0
- package/dist/core/components/viewers/map/src/MapSidebar/src/SettingsTab/src/LocationSettings.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/MapSidebar/src/SettingsTab/src/LocationSettings.js +12 -32
- package/dist/core/components/viewers/map/src/MapSidebar/src/SettingsTab/src/LocationSettings.js.map +1 -1
- package/dist/core/components/viewers/map/src/Placement/MapPlacementHost.js +1 -1
- package/dist/core/components/viewers/map/src/Placement/MapPlacementHost.js.map +1 -1
- package/dist/core/components/viewers/map/src/Placement/mapPlacementGeo.d.ts +1 -1
- package/dist/core/components/viewers/map/src/Placement/mapPlacementGeo.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/Placement/mapPlacementGeo.js +2 -2
- package/dist/core/components/viewers/map/src/Placement/mapPlacementGeo.js.map +1 -1
- package/dist/core/components/viewers/map/src/Placement/mapPlacementTarget.js +1 -1
- package/dist/core/components/viewers/map/src/Placement/mapPlacementTarget.js.map +1 -1
- package/dist/core/components/viewers/map/src/Placement/useMapPlacementTarget.js +1 -1
- package/dist/core/components/viewers/map/src/Placement/useMapPlacementTarget.js.map +1 -1
- package/dist/core/components/viewers/map/src/tools/shareMapTool.d.ts.map +1 -1
- package/dist/core/components/viewers/map/src/tools/shareMapTool.js +24 -14
- package/dist/core/components/viewers/map/src/tools/shareMapTool.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoder.d.ts +1 -0
- package/dist/core/components/viewers/map/utils/geocoder.d.ts.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoder.js +5 -0
- package/dist/core/components/viewers/map/utils/geocoder.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/adapters.d.ts +2 -0
- package/dist/core/components/viewers/map/utils/geocoding/adapters.d.ts.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/adapters.js +8 -1
- package/dist/core/components/viewers/map/utils/geocoding/adapters.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/index.d.ts +3 -0
- package/dist/core/components/viewers/map/utils/geocoding/index.d.ts.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/index.js +20 -3
- package/dist/core/components/viewers/map/utils/geocoding/index.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/osm.d.ts +2 -0
- package/dist/core/components/viewers/map/utils/geocoding/osm.d.ts.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/osm.js +32 -1
- package/dist/core/components/viewers/map/utils/geocoding/osm.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/pelias.d.ts +2 -0
- package/dist/core/components/viewers/map/utils/geocoding/pelias.d.ts.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/pelias.js +30 -1
- package/dist/core/components/viewers/map/utils/geocoding/pelias.js.map +1 -1
- package/dist/core/components/viewers/map/utils/geocoding/placeSearch.d.ts +17 -0
- package/dist/core/components/viewers/map/utils/geocoding/placeSearch.d.ts.map +1 -0
- package/dist/core/components/viewers/map/utils/geocoding/placeSearch.js +26 -0
- package/dist/core/components/viewers/map/utils/geocoding/placeSearch.js.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationParams.d.ts +38 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationParams.d.ts.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationParams.js +91 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationParams.js.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationTarget.d.ts +25 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationTarget.d.ts.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationTarget.js +71 -0
- package/dist/core/components/viewers/map/utils/urlLocation/locationTarget.js.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/resolveLocationTarget.d.ts +20 -0
- package/dist/core/components/viewers/map/utils/urlLocation/resolveLocationTarget.d.ts.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/resolveLocationTarget.js +103 -0
- package/dist/core/components/viewers/map/utils/urlLocation/resolveLocationTarget.js.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/useUrlFlyTo.d.ts +4 -0
- package/dist/core/components/viewers/map/utils/urlLocation/useUrlFlyTo.d.ts.map +1 -0
- package/dist/core/components/viewers/map/utils/urlLocation/useUrlFlyTo.js +72 -0
- package/dist/core/components/viewers/map/utils/urlLocation/useUrlFlyTo.js.map +1 -0
- package/dist/core/components/viewers/shared/intake/useFileIntake.d.ts.map +1 -1
- package/dist/core/components/viewers/shared/intake/useFileIntake.js +3 -26
- package/dist/core/components/viewers/shared/intake/useFileIntake.js.map +1 -1
- package/dist/core/components/viewers/shared/placement/fileTransform.d.ts +9 -0
- package/dist/core/components/viewers/shared/placement/fileTransform.d.ts.map +1 -0
- package/dist/core/components/viewers/shared/placement/fileTransform.js +32 -0
- package/dist/core/components/viewers/shared/placement/fileTransform.js.map +1 -0
- package/dist/core/components/viewers/shared/placement/objectTarget.js +2 -2
- package/dist/core/components/viewers/shared/placement/objectTarget.js.map +1 -1
- package/dist/core/components/viewers/shared/pointcloud/pointCloudPlacementStore.d.ts +2 -3
- package/dist/core/components/viewers/shared/pointcloud/pointCloudPlacementStore.d.ts.map +1 -1
- package/dist/core/components/viewers/shared/pointcloud/pointCloudPlacementStore.js +4 -14
- package/dist/core/components/viewers/shared/pointcloud/pointCloudPlacementStore.js.map +1 -1
- package/dist/core/hooks/useShareUrl.d.ts.map +1 -1
- package/dist/core/hooks/useShareUrl.js +5 -9
- package/dist/core/hooks/useShareUrl.js.map +1 -1
- package/dist/core/i18n/messages/en.json +4 -0
- package/dist/core/i18n/messages/es.json +4 -0
- package/dist/core/i18n/messages/fr.json +4 -0
- package/dist/core/types/datasetTypes.d.ts +5 -0
- package/dist/core/types/datasetTypes.d.ts.map +1 -1
- package/dist/core/types/dbTypes.d.ts +40 -0
- package/dist/core/types/dbTypes.d.ts.map +1 -1
- package/dist/core/types/dbTypes.js +18 -0
- package/dist/core/types/dbTypes.js.map +1 -1
- package/dist/core/types/index.d.ts +2 -2
- package/dist/core/types/index.d.ts.map +1 -1
- package/dist/core/types/index.js +7 -1
- package/dist/core/types/index.js.map +1 -1
- package/dist/core/utils/geo/reprojectGeometry.d.ts +14 -0
- package/dist/core/utils/geo/reprojectGeometry.d.ts.map +1 -0
- package/dist/core/utils/geo/reprojectGeometry.js +58 -0
- package/dist/core/utils/geo/reprojectGeometry.js.map +1 -0
- package/dist/core/utils/geo/wktToGeometry.d.ts +5 -0
- package/dist/core/utils/geo/wktToGeometry.d.ts.map +1 -0
- package/dist/core/utils/geo/wktToGeometry.js +34 -0
- package/dist/core/utils/geo/wktToGeometry.js.map +1 -0
- package/package.json +1 -1
|
@@ -10,8 +10,11 @@ function parseDescription(value) {
|
|
|
10
10
|
return null;
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
+
function withBbox(url, bbox) {
|
|
14
|
+
return `${url}${url.includes("?") ? "&" : "?"}bbox=${bbox.map((value) => value.toFixed(6)).join(",")}`;
|
|
15
|
+
}
|
|
13
16
|
async function fetchOrganizationalMinioDatasets(organizationId, publishedTilesInCatalog = /* @__PURE__ */ new Set()) {
|
|
14
|
-
var _a, _b;
|
|
17
|
+
var _a, _b, _c, _d;
|
|
15
18
|
let rows = [];
|
|
16
19
|
try {
|
|
17
20
|
const res = await fetch("/api/files");
|
|
@@ -35,14 +38,18 @@ async function fetchOrganizationalMinioDatasets(organizationId, publishedTilesIn
|
|
|
35
38
|
if (!sourceUrl) continue;
|
|
36
39
|
const name = ((_a = row.name) == null ? void 0 : _a.replace(/\.geojson$/i, "")) || `Dataset ${row.id}`;
|
|
37
40
|
const id = `org-minio-${row.id}`;
|
|
41
|
+
const viewport = typeof (meta == null ? void 0 : meta.minZoom) === "number" ? { minZoom: meta.minZoom } : void 0;
|
|
38
42
|
let cached = null;
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
const response = await fetch(sourceUrl);
|
|
43
|
+
const fetchGeoJson = async (url) => {
|
|
44
|
+
const response = await fetch(url);
|
|
42
45
|
if (!response.ok) {
|
|
43
|
-
throw new Error(`Failed to fetch GeoJSON from ${
|
|
46
|
+
throw new Error(`Failed to fetch GeoJSON from ${url}: ${response.status}`);
|
|
44
47
|
}
|
|
45
|
-
|
|
48
|
+
return await response.json();
|
|
49
|
+
};
|
|
50
|
+
const getFeatures = async (options) => {
|
|
51
|
+
if (viewport && (options == null ? void 0 : options.bbox)) return fetchGeoJson(withBbox(sourceUrl, options.bbox));
|
|
52
|
+
cached != null ? cached : cached = await fetchGeoJson(sourceUrl);
|
|
46
53
|
return cached;
|
|
47
54
|
};
|
|
48
55
|
const getFields = async () => [];
|
|
@@ -59,14 +66,15 @@ async function fetchOrganizationalMinioDatasets(organizationId, publishedTilesIn
|
|
|
59
66
|
description: `Uploaded ${(_b = row.uploadedAt) != null ? _b : ""}`.trim(),
|
|
60
67
|
dateReleased: typeof row.uploadedAt === "string" ? row.uploadedAt : "",
|
|
61
68
|
dateUpdated: typeof row.uploadedAt === "string" ? row.uploadedAt : "",
|
|
62
|
-
countrySubdivision: "",
|
|
63
|
-
municipality: "",
|
|
69
|
+
countrySubdivision: (_c = row.countrySubdivision) != null ? _c : "",
|
|
70
|
+
municipality: (_d = row.municipality) != null ? _d : "",
|
|
64
71
|
sourceUrl,
|
|
65
72
|
url: sourceUrl,
|
|
66
73
|
clickable: true,
|
|
67
74
|
properties: {},
|
|
68
75
|
getFeatures,
|
|
69
76
|
getFields,
|
|
77
|
+
viewport,
|
|
70
78
|
dataManagementSystem: "other",
|
|
71
79
|
datasetType: "GeoJSON",
|
|
72
80
|
group: DatasetGroup.Organizational,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../src/core/components/viewers/map/datasets/src/minioDatasets.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { DatasetGroup } from '../../../../../types/dbTypes'\nimport { layerColorByName } from '../../utils/stringToColour'\n\nimport type { Dataset } from '../../../../../types/datasetTypes'\nimport type { AllGeoJSON } from '@turf/turf'\n\n/**\n * Hydrates uploaded GeoJSON datasets persisted via \"Add Dataset\". Looks up File\n * rows tagged `organizational-dataset` and builds Dataset entries whose\n * `getFeatures` lazy-loads the GeoJSON on first render.\n */\n\ninterface OrgDatasetDescription {\n bucket?: string\n geometryType?: 'points' | 'lines' | 'polygons'\n layerStyles?: Record<string, Record<string, string | number>>\n tiledTable?: string\n tiledAt?: string\n featuresIngested?: number\n featuresSkipped?: number\n}\n\ninterface RawFileRow {\n id: number\n type?: string | null\n tag?: string | null\n name?: string | null\n /** Presigned, expiring download URL minted per request by /api/files. */\n url?: string | null\n description?: string | null\n uploadedAt?: string | Date | null\n}\n\nconst TAG = 'organizational-dataset'\n\nfunction parseDescription(value: string | null | undefined): OrgDatasetDescription | null {\n if (!value) return null\n try {\n const parsed = JSON.parse(value)\n return typeof parsed === 'object' && parsed !== null ? parsed as OrgDatasetDescription : null\n }\n catch {\n return null\n }\n}\n\nexport async function fetchOrganizationalMinioDatasets(\n organizationId: number,\n publishedTilesInCatalog: ReadonlySet<string> = new Set(),\n): Promise<Dataset[]> {\n let rows: RawFileRow[] = []\n try {\n const res = await fetch('/api/files')\n if (!res.ok) {\n console.warn(`fetchOrganizationalMinioDatasets: /api/files returned ${res.status}`)\n return []\n }\n const body = await res.json()\n rows = Array.isArray(body?.files) ? body.files : []\n }\n catch (err) {\n console.warn('fetchOrganizationalMinioDatasets: /api/files request failed', err)\n return []\n }\n\n const datasets: Dataset[] = []\n for (const row of rows) {\n if (row.type !== 'map-file') continue\n if (row.tag !== TAG) continue\n\n const meta = parseDescription(row.description)\n // Suppress the MinIO entry only once Martin actually serves the published\n // table — otherwise the file appears to vanish during the publish→restart\n // gap. Un-publish drops the table immediately, so the MinIO row reappears\n // on next reload with no extra plumbing.\n if (meta?.tiledTable && publishedTilesInCatalog.has(meta.tiledTable)) continue\n\n // Only ever the presigned URL the server minted for this session. Rebuilding\n // the object path here would require the bucket to allow anonymous reads.\n const sourceUrl = row.url\n if (!sourceUrl) continue\n\n const name = row.name?.replace(/\\.geojson$/i, '') || `Dataset ${row.id}`\n const id = `org-minio-${row.id}`\n let cached: AllGeoJSON | null = null\n\n const
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/core/components/viewers/map/datasets/src/minioDatasets.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { DatasetGroup } from '../../../../../types/dbTypes'\nimport { layerColorByName } from '../../utils/stringToColour'\n\nimport type { Dataset } from '../../../../../types/datasetTypes'\nimport type { AllGeoJSON } from '@turf/turf'\n\n/**\n * Hydrates uploaded GeoJSON datasets persisted via \"Add Dataset\". Looks up File\n * rows tagged `organizational-dataset` and builds Dataset entries whose\n * `getFeatures` lazy-loads the GeoJSON on first render.\n */\n\ninterface OrgDatasetDescription {\n bucket?: string\n geometryType?: 'points' | 'lines' | 'polygons'\n layerStyles?: Record<string, Record<string, string | number>>\n tiledTable?: string\n tiledAt?: string\n featuresIngested?: number\n featuresSkipped?: number\n minZoom?: number\n}\n\ninterface RawFileRow {\n id: number\n type?: string | null\n tag?: string | null\n name?: string | null\n /** Presigned, expiring download URL minted per request by /api/files. */\n url?: string | null\n description?: string | null\n uploadedAt?: string | Date | null\n countrySubdivision?: string | null\n municipality?: string | null\n}\n\nconst TAG = 'organizational-dataset'\n\nfunction parseDescription(value: string | null | undefined): OrgDatasetDescription | null {\n if (!value) return null\n try {\n const parsed = JSON.parse(value)\n return typeof parsed === 'object' && parsed !== null ? parsed as OrgDatasetDescription : null\n }\n catch {\n return null\n }\n}\n\nfunction withBbox(url: string, bbox: [number, number, number, number]): string {\n return `${url}${url.includes('?') ? '&' : '?'}bbox=${bbox.map(value => value.toFixed(6)).join(',')}`\n}\n\nexport async function fetchOrganizationalMinioDatasets(\n organizationId: number,\n publishedTilesInCatalog: ReadonlySet<string> = new Set(),\n): Promise<Dataset[]> {\n let rows: RawFileRow[] = []\n try {\n const res = await fetch('/api/files')\n if (!res.ok) {\n console.warn(`fetchOrganizationalMinioDatasets: /api/files returned ${res.status}`)\n return []\n }\n const body = await res.json()\n rows = Array.isArray(body?.files) ? body.files : []\n }\n catch (err) {\n console.warn('fetchOrganizationalMinioDatasets: /api/files request failed', err)\n return []\n }\n\n const datasets: Dataset[] = []\n for (const row of rows) {\n if (row.type !== 'map-file') continue\n if (row.tag !== TAG) continue\n\n const meta = parseDescription(row.description)\n // Suppress the MinIO entry only once Martin actually serves the published\n // table — otherwise the file appears to vanish during the publish→restart\n // gap. Un-publish drops the table immediately, so the MinIO row reappears\n // on next reload with no extra plumbing.\n if (meta?.tiledTable && publishedTilesInCatalog.has(meta.tiledTable)) continue\n\n // Only ever the presigned URL the server minted for this session. Rebuilding\n // the object path here would require the bucket to allow anonymous reads.\n const sourceUrl = row.url\n if (!sourceUrl) continue\n\n const name = row.name?.replace(/\\.geojson$/i, '') || `Dataset ${row.id}`\n const id = `org-minio-${row.id}`\n const viewport = typeof meta?.minZoom === 'number' ? { minZoom: meta.minZoom } : undefined\n let cached: AllGeoJSON | null = null\n\n const fetchGeoJson = async (url: string): Promise<AllGeoJSON> => {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch GeoJSON from ${url}: ${response.status}`)\n }\n return await response.json() as AllGeoJSON\n }\n\n const getFeatures: Dataset['getFeatures'] = async (options) => {\n if (viewport && options?.bbox) return fetchGeoJson(withBbox(sourceUrl, options.bbox))\n cached ??= await fetchGeoJson(sourceUrl)\n return cached\n }\n\n const getFields = async () => []\n\n datasets.push({\n id,\n // Stamped so the map's org-visibility filter can tell whose dataset this\n // is. Without it every rebuilt dataset is dropped for non-admin viewers.\n organization: organizationId,\n name,\n type: 'Organizational',\n publisher: 'Organizational',\n license: 'Unknown',\n contact: 'Unknown',\n description: `Uploaded ${row.uploadedAt ?? ''}`.trim(),\n dateReleased: typeof row.uploadedAt === 'string' ? row.uploadedAt : '',\n dateUpdated: typeof row.uploadedAt === 'string' ? row.uploadedAt : '',\n countrySubdivision: row.countrySubdivision ?? '',\n municipality: row.municipality ?? '',\n sourceUrl,\n url: sourceUrl,\n clickable: true,\n properties: {},\n getFeatures,\n getFields,\n viewport,\n dataManagementSystem: 'other',\n datasetType: 'GeoJSON',\n group: DatasetGroup.Organizational,\n layerColor: layerColorByName(id),\n layerType: meta?.geometryType === 'lines'\n ? 'line'\n : meta?.geometryType === 'points'\n ? 'circle'\n : meta?.geometryType === 'polygons'\n ? 'fill'\n : undefined,\n })\n }\n\n return datasets\n}\n"],"mappings":"AAGA,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AAmCjC,MAAM,MAAM;AAEZ,SAAS,iBAAiB,OAAgE;AACxF,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,WAAO,OAAO,WAAW,YAAY,WAAW,OAAO,SAAkC;AAAA,EAC3F,SACM;AACJ,WAAO;AAAA,EACT;AACF;AAEA,SAAS,SAAS,KAAa,MAAgD;AAC7E,SAAO,GAAG,GAAG,GAAG,IAAI,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,cAAsC,OAAO,YAAY;AAC7D,UAAI,aAAY,mCAAS,MAAM,QAAO,aAAa,SAAS,WAAW,QAAQ,IAAI,CAAC;AACpF,yCAAW,MAAM,aAAa,SAAS;AACvC,aAAO;AAAA,IACT;AAEA,UAAM,YAAY,YAAY,CAAC;AAE/B,aAAS,KAAK;AAAA,MACZ;AAAA;AAAA;AAAA,MAGA,cAAc;AAAA,MACd;AAAA,MACA,MAAM;AAAA,MACN,WAAW;AAAA,MACX,SAAS;AAAA,MACT,SAAS;AAAA,MACT,aAAa,aAAY,SAAI,eAAJ,YAAkB,EAAE,GAAG,KAAK;AAAA,MACrD,cAAc,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;AAAA,MACpE,aAAa,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;AAAA,MACnE,qBAAoB,SAAI,uBAAJ,YAA0B;AAAA,MAC9C,eAAc,SAAI,iBAAJ,YAAoB;AAAA,MAClC;AAAA,MACA,KAAK;AAAA,MACL,WAAW;AAAA,MACX,YAAY,CAAC;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,sBAAsB;AAAA,MACtB,aAAa;AAAA,MACb,OAAO,aAAa;AAAA,MACpB,YAAY,iBAAiB,EAAE;AAAA,MAC/B,YAAW,6BAAM,kBAAiB,UAC9B,UACA,6BAAM,kBAAiB,WACrB,YACA,6BAAM,kBAAiB,aACrB,SACA;AAAA,IACV,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Geocoder.d.ts","sourceRoot":"","sources":["../../../../../../src/core/components/viewers/map/src/Geocoder.tsx"],"names":[],"mappings":"AASA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"Geocoder.d.ts","sourceRoot":"","sources":["../../../../../../src/core/components/viewers/map/src/Geocoder.tsx"],"names":[],"mappings":"AASA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAuC9B,UAAU,aAAa;IACrB,QAAQ,CAAC,EAAE,CAAC,WAAW,EAAE,GAAG,KAAK,IAAI,CAAA;IACrC,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAC/B,QAAQ,EACR,qBAA4B,EAC5B,cAAsB,EACtB,kBAAkB,EAClB,WAAW,GACZ,EAAE,aAAa,qBAiRf"}
|
|
@@ -34,6 +34,15 @@ import { Input } from "../../../ui/Input";
|
|
|
34
34
|
import { LoadingSpinner } from "../../../ui/LoadingSpinner";
|
|
35
35
|
import { Separator } from "../../../ui/Separator";
|
|
36
36
|
import { fetchSuggestions, parseLocation, handleLocationSelect, buildingToFeature } from "../utils/geocoder";
|
|
37
|
+
import { labelsFromParams, labelsFromPlace, writeLocationParams } from "../utils/urlLocation/locationParams";
|
|
38
|
+
function labelsFor(feature, type) {
|
|
39
|
+
var _a, _b;
|
|
40
|
+
const props = (_a = feature.properties) != null ? _a : {};
|
|
41
|
+
const address = String((_b = props.label) != null ? _b : "").split(",")[0].trim();
|
|
42
|
+
const place = type === "dbBuilding" ? { municipality: props.municipality, countrySubdivision: props.countrySubdivision, address } : labelsFromPlace(props, address);
|
|
43
|
+
const { country } = labelsFromParams(new URL(window.location.href).searchParams);
|
|
44
|
+
return __spreadValues({ country }, Object.fromEntries(Object.entries(place).filter(([, value]) => value)));
|
|
45
|
+
}
|
|
37
46
|
function Geocoder({
|
|
38
47
|
onSelect,
|
|
39
48
|
showDatabaseBuildings = true,
|
|
@@ -123,38 +132,32 @@ function Geocoder({
|
|
|
123
132
|
};
|
|
124
133
|
}, [alwaysExpanded]);
|
|
125
134
|
const handleSelectSuggestion = (feature, type = "") => {
|
|
126
|
-
var _a;
|
|
135
|
+
var _a, _b, _c, _d;
|
|
127
136
|
setQuery("");
|
|
128
137
|
setSuggestions([]);
|
|
129
138
|
setBuildingResults([]);
|
|
130
139
|
if (!alwaysExpanded) {
|
|
131
140
|
setFocused(false);
|
|
132
141
|
}
|
|
133
|
-
const
|
|
142
|
+
const syncUrl = () => {
|
|
143
|
+
if (map) writeLocationParams(map, labelsFor(feature, type));
|
|
144
|
+
};
|
|
145
|
+
const addressData = handleLocationSelect(feature, map, type, { onMoveEnd: syncUrl });
|
|
134
146
|
const address2 = addressData.formatted_address || ((_a = feature.properties) == null ? void 0 : _a.label) || "";
|
|
135
147
|
setAddress(address2);
|
|
136
148
|
setSelectedAddress(addressData);
|
|
137
149
|
if (onSelect) onSelect(addressData);
|
|
138
|
-
if (mapDispatch && currentLocation) {
|
|
150
|
+
if (mapDispatch && currentLocation && addressData.coordinates) {
|
|
139
151
|
const [lng, lat] = addressData.coordinates;
|
|
140
|
-
const
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
152
|
+
const labels = labelsFor(feature, type);
|
|
153
|
+
const newCurrentLocation = __spreadProps(__spreadValues({}, currentLocation), {
|
|
154
|
+
municipality: (_b = labels.municipality) != null ? _b : "",
|
|
155
|
+
countrySubdivision: (_c = labels.countrySubdivision) != null ? _c : "",
|
|
156
|
+
address: (_d = labels.address) != null ? _d : "",
|
|
157
|
+
lng,
|
|
158
|
+
lat
|
|
159
|
+
});
|
|
145
160
|
mapDispatch({ type: "UPDATE_LOCATION", payload: { currentLocation: newCurrentLocation } });
|
|
146
|
-
if (municipality || countrySubdivision) {
|
|
147
|
-
const url = new URL(window.location.href);
|
|
148
|
-
if (municipality) url.searchParams.set("municipality", municipality);
|
|
149
|
-
else url.searchParams.delete("municipality");
|
|
150
|
-
if (countrySubdivision) url.searchParams.set("countrySubdivision", countrySubdivision);
|
|
151
|
-
else url.searchParams.delete("countrySubdivision");
|
|
152
|
-
url.searchParams.set("address", parts[0]);
|
|
153
|
-
url.searchParams.set("lng", lng.toString());
|
|
154
|
-
url.searchParams.set("lat", lat.toString());
|
|
155
|
-
url.searchParams.set("zoom", "18");
|
|
156
|
-
window.history.replaceState({}, "", url.toString());
|
|
157
|
-
}
|
|
158
161
|
}
|
|
159
162
|
};
|
|
160
163
|
const handleExpand = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/core/components/viewers/map/src/Geocoder.tsx"],"sourcesContent":["'use client'\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\n// Dependencies\nimport { Search } from 'lucide-react'\nimport { usePathname } from 'next/navigation'\nimport { useTranslations } from 'next-intl'\nimport * as React from 'react'\n\n// Context\nimport { useBuildings } from '../../../../hooks/buildings/buildings'\nimport { useGeocodingRuntimeConfig } from '../../../../hooks/useGeocodingRuntimeConfig'\nimport { MapContext } from '../../../../store'\n\n// Utility functions\n\n// Import the shadcn components\nimport { Button } from '../../../ui/Button'\nimport { Command, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator } from '../../../ui/Command'\nimport { Input } from '../../../ui/Input'\nimport { LoadingSpinner } from '../../../ui/LoadingSpinner'\nimport { Separator } from '../../../ui/Separator'\n\n// Icons\n\n// Building data hook\n\n\nimport { fetchSuggestions, parseLocation, handleLocationSelect, buildingToFeature } from '../utils/geocoder'\n\nimport type { CurrentLocation } from '../../../../types/map'\n\n\ninterface GeocoderProps {\n onSelect?: (addressData: any) => void\n showDatabaseBuildings?: boolean\n alwaysExpanded?: boolean\n geocodeEarthApiKey?: string\n geocoderUrl?: string\n}\n\nexport default function Geocoder({\n onSelect,\n showDatabaseBuildings = true,\n alwaysExpanded = false,\n geocodeEarthApiKey,\n geocoderUrl,\n}: GeocoderProps) {\n useGeocodingRuntimeConfig({ geocodeEarthApiKey, geocoderUrl })\n\n // Translation\n const t = useTranslations('Geocoder')\n\n const [address, setAddress] = React.useState<string>('')\n const [query, setQuery] = React.useState('')\n const [suggestions, setSuggestions] = React.useState([])\n const [buildingResults, setBuildingResults] = React.useState([])\n const [focused, setFocused] = React.useState(alwaysExpanded)\n const [selectedAddress, setSelectedAddress] = React.useState(null)\n const [isExpanded, setIsExpanded] = React.useState(alwaysExpanded)\n const [loading, setLoading] = React.useState(false)\n\n const pathname = usePathname()\n\n const suggestionsRef = React.useRef(null)\n const inputRef = React.useRef(null)\n const debounceRef = React.useRef(null)\n\n const { dispatch: mapDispatch, state: mapState } = React.useContext(MapContext)\n const { map, currentLocation, organizationCountry } = mapState.map\n\n // Fetch buildings data from API only if showDatabaseBuildings is true\n const { buildings, isLoading: isBuildingsLoading } = useBuildings()\n\n // Filter buildings based on search query\n const filterBuildings = React.useCallback((searchQuery) => {\n if (!showDatabaseBuildings || !buildings || !searchQuery || searchQuery.length < 3) return []\n\n const lowerQuery = searchQuery.toLowerCase()\n\n if (Array.isArray(buildings) && buildings.length > 0) {\n return buildings.filter((building) => {\n return (\n (building.buildingName && building.buildingName.toLowerCase().includes(lowerQuery))\n || (building.buildingAddress && building.buildingAddress.toLowerCase().includes(lowerQuery))\n || (building.buildingMunicipality && building.buildingMunicipality.toLowerCase().includes(lowerQuery))\n || (building.buildingCountrySubdivision && building.buildingCountrySubdivision.toLowerCase().includes(lowerQuery))\n )\n }).slice(0, 3) // Limit to 3 results\n }\n return []\n }, [buildings, showDatabaseBuildings])\n\n // Debounce the API request to avoid rate limiting and excessive requests\n React.useEffect(() => {\n if (debounceRef.current) {\n clearTimeout(debounceRef.current)\n }\n\n const fetchDebounced = async () => {\n if (!query || query.length < 3) {\n setSuggestions([])\n setBuildingResults([])\n setLoading(false)\n return\n }\n\n setLoading(true)\n try {\n // Filter buildings from our database only if enabled\n if (showDatabaseBuildings) {\n const filteredBuildings = filterBuildings(query)\n setBuildingResults(filteredBuildings)\n }\n\n // Fetch geocoding suggestions\n const geocodeResults = await fetchSuggestions(query, organizationCountry)\n\n // Deduplicate geocode results based on name and region\n const deduplicatedResults = geocodeResults.reduce((acc, feature) => {\n const location = parseLocation(feature)\n // Create a unique key based on name and region (case-insensitive)\n const key = `${location.name?.toLowerCase() || ''}_${location.region?.toLowerCase() || ''}`\n\n // Only add if we haven't seen this combination before\n if (!acc.seen.has(key)) {\n acc.seen.add(key)\n acc.features.push(feature)\n }\n\n return acc\n }, { seen: new Set(), features: [] })\n\n setSuggestions(deduplicatedResults.features)\n }\n catch (error) {\n console.error('Error fetching suggestions:', error)\n setSuggestions([])\n }\n finally {\n setLoading(false)\n }\n }\n\n debounceRef.current = setTimeout(() => { void fetchDebounced() }, 300) // Increased debounce time for better API rate limiting\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current)\n }\n }, [query, filterBuildings, showDatabaseBuildings])\n\n // Handle click outside to close suggestions\n React.useEffect(() => {\n const handleClickOutside = (event) => {\n if (suggestionsRef.current && !suggestionsRef.current.contains(event.target)\n && inputRef.current && !inputRef.current.contains(event.target) // Don't close if alwaysExpanded is true\n && !alwaysExpanded) {\n setFocused(false)\n }\n }\n\n document.addEventListener('mousedown', handleClickOutside)\n return () => {\n document.removeEventListener('mousedown', handleClickOutside)\n }\n }, [alwaysExpanded])\n\n // Handle suggestion selection\n const handleSelectSuggestion = (feature, type = '') => {\n setQuery('') // Clear the input field\n setSuggestions([])\n setBuildingResults([])\n if (!alwaysExpanded) {\n setFocused(false)\n }\n\n // handleLocationSelect will automatically remove any existing marker and add a new one\n const addressData = handleLocationSelect(feature, map, type)\n\n const address = addressData.formatted_address || feature.properties?.label || ''\n setAddress(address)\n setSelectedAddress(addressData)\n\n if (onSelect) onSelect(addressData)\n\n if (mapDispatch && currentLocation) {\n const [lng, lat] = addressData.coordinates\n const props = addressData.properties || {}\n const parts = address.split(',').map(p => p.trim())\n // Read structured properties (provider-agnostic) instead of parsing label tokens,\n // which only matched Geocode Earth's \"…, ON, Canada\" abbreviation format and broke\n // on the Photon/Nominatim fallback.\n const countrySubdivision: string = props.region_a || props.region || ''\n const municipality: string = props.locality || props.neighbourhood || props.county || ''\n\n const newCurrentLocation: CurrentLocation = { ...currentLocation, municipality, countrySubdivision, longitude: lng, latitude: lat, address: parts[0] }\n mapDispatch({ type: 'UPDATE_LOCATION', payload: { currentLocation: newCurrentLocation } })\n if (municipality || countrySubdivision) {\n const url = new URL(window.location.href)\n // Write each field only when present, so an empty param doesn't shadow the\n // organization fallback MapViewer applies on reload.\n if (municipality) url.searchParams.set('municipality', municipality)\n else url.searchParams.delete('municipality')\n if (countrySubdivision) url.searchParams.set('countrySubdivision', countrySubdivision)\n else url.searchParams.delete('countrySubdivision')\n url.searchParams.set('address', parts[0])\n url.searchParams.set('lng', lng.toString())\n url.searchParams.set('lat', lat.toString())\n url.searchParams.set('zoom', '18')\n window.history.replaceState({}, '', url.toString())\n }\n }\n }\n\n // Handle expand of menubar to display search input\n const handleExpand = () => {\n if (alwaysExpanded) return // Don't allow toggling if always expanded\n\n setIsExpanded(!isExpanded)\n if (isExpanded) {\n setFocused(false)\n setQuery('') // clear input and suggestions when collapsed\n setSuggestions([])\n setBuildingResults([])\n }\n else {\n setFocused(true)\n setTimeout(() => {\n inputRef.current?.focus()\n }, 100) // Small delay to ensure the input is rendered\n }\n }\n\n return (\n <Command>\n {/* Search input + button */}\n <div className={`flex flex-row justify-start items-center w-full h-auto `}>\n {!alwaysExpanded && (\n <Button\n variant=\"ghost\"\n size=\"icon\"\n onClick={handleExpand}\n className=\"opacity-70 w-6 justify-end hover:opacity-100 transition-opacity duration-200 hover:bg-transparent\"\n >\n <Search />\n </Button>\n )}\n {alwaysExpanded && (\n <Search className=\"h-4 w-4 opacity-50\" />\n )}\n <Input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={e => setQuery(e.target.value)}\n onFocus={() => setFocused(true)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n inputRef.current?.blur()\n }\n }}\n placeholder={alwaysExpanded ? t('placeholder1') : t('placeholder2')}\n className={`border-none focus-visible:ring-transparent text-sm transition-all ease-in-out duration-200 ${\n alwaysExpanded || isExpanded ? 'w-full' : 'w-0 p-0'\n }`}\n />\n </div>\n\n {focused && (loading || buildingResults.length > 0 || suggestions.length > 0) && (\n <div ref={suggestionsRef}>\n <Separator />\n <CommandList>\n {!loading && buildingResults.length === 0 && suggestions.length === 0 && query.length >= 3 && (\n <CommandEmpty>{showDatabaseBuildings ? t('noResults') : t('noAddresses')}</CommandEmpty>\n )}\n\n {loading && (\n <CommandEmpty><LoadingSpinner /></CommandEmpty>\n )}\n\n {/* Database Buildings section - only show if enabled */}\n {showDatabaseBuildings && !loading && buildingResults.length > 0 && (\n <CommandGroup heading={t('buildingHeader')}>\n {buildingResults.map((building) => {\n const buildingFeature = buildingToFeature(building)\n\n return (\n <CommandItem\n key={`building-${building.id}`}\n onSelect={() => handleSelectSuggestion(buildingFeature, 'dbBuilding')}\n className=\"cursor-pointer\"\n >\n <div className=\"font-medium\">{building.buildingName}</div>\n <div className=\"text-sm text-muted-foreground\">\n {building.buildingAddress}\n </div>\n </CommandItem>\n )\n })}\n </CommandGroup>\n )}\n\n {/* Separator between sections if both have results */}\n {showDatabaseBuildings && buildingResults.length > 0 && suggestions.length > 0 && (\n <CommandSeparator />\n )}\n\n {/* Geocoder suggestions section */}\n {!loading && suggestions.length > 0 && (\n <CommandGroup heading={showDatabaseBuildings ? t('suggestionsHeader') : undefined}>\n {suggestions.map((feature) => {\n const location = parseLocation(feature)\n const uniqueKey = feature.properties?.gid\n || `${feature.properties?.name}-${feature.geometry?.coordinates?.[0]}-${feature.geometry?.coordinates?.[1]}`\n\n return (\n <CommandItem\n key={uniqueKey}\n onSelect={() => handleSelectSuggestion(feature)}\n className=\"cursor-pointer\"\n >\n <div className=\"font-medium\">{location.name}</div>\n <div className=\"text-sm text-muted-foreground\">{location.region}</div>\n </CommandItem>\n )\n })}\n </CommandGroup>\n )}\n </CommandList>\n </div>\n )}\n </Command>\n )\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8OU,SAQM,KARN;AAxOV,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC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0BAAgB,IAAI,CAAC,aAAa;AACjC,gBAAM,kBAAkB,kBAAkB,QAAQ;AAElD,iBACE;AAAA,YAAC;AAAA;AAAA,cAEC,UAAU,MAAM,uBAAuB,iBAAiB,YAAY;AAAA,cACpE,WAAU;AAAA,cAEV;AAAA,oCAAC,SAAI,WAAU,eAAe,mBAAS,cAAa;AAAA,gBACpD,oBAAC,SAAI,WAAU,iCACZ,mBAAS,iBACZ;AAAA;AAAA;AAAA,YAPK,YAAY,SAAS,EAAE;AAAA,UAQ9B;AAAA,QAEJ,CAAC,GACH;AAAA,QAID,yBAAyB,gBAAgB,SAAS,KAAK,YAAY,SAAS,KAC3E,oBAAC,oBAAiB;AAAA,QAInB,CAAC,WAAW,YAAY,SAAS,KAChC,oBAAC,gBAAa,SAAS,wBAAwB,EAAE,mBAAmB,IAAI,QACrE,sBAAY,IAAI,CAAC,YAAY;AAxTlD;AAyTsB,gBAAM,WAAW,cAAc,OAAO;AACtC,gBAAM,cAAY,aAAQ,eAAR,mBAAoB,QACjC,IAAG,aAAQ,eAAR,mBAAoB,IAAI,KAAI,mBAAQ,aAAR,mBAAkB,gBAAlB,mBAAgC,EAAE,KAAI,mBAAQ,aAAR,mBAAkB,gBAAlB,mBAAgC,EAAE;AAE5G,iBACE;AAAA,YAAC;AAAA;AAAA,cAEC,UAAU,MAAM,uBAAuB,OAAO;AAAA,cAC9C,WAAU;AAAA,cAEV;AAAA,oCAAC,SAAI,WAAU,eAAe,mBAAS,MAAK;AAAA,gBAC5C,oBAAC,SAAI,WAAU,iCAAiC,mBAAS,QAAO;AAAA;AAAA;AAAA,YAL3D;AAAA,UAMP;AAAA,QAEJ,CAAC,GACH;AAAA,SAEJ;AAAA,OACF;AAAA,KAEJ;AAER;","names":["address"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/core/components/viewers/map/src/Geocoder.tsx"],"sourcesContent":["'use client'\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\n// Dependencies\nimport { Search } from 'lucide-react'\nimport { usePathname } from 'next/navigation'\nimport { useTranslations } from 'next-intl'\nimport * as React from 'react'\n\n// Context\nimport { useBuildings } from '../../../../hooks/buildings/buildings'\nimport { useGeocodingRuntimeConfig } from '../../../../hooks/useGeocodingRuntimeConfig'\nimport { MapContext } from '../../../../store'\n\n// Utility functions\n\n// Import the shadcn components\nimport { Button } from '../../../ui/Button'\nimport { Command, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator } from '../../../ui/Command'\nimport { Input } from '../../../ui/Input'\nimport { LoadingSpinner } from '../../../ui/LoadingSpinner'\nimport { Separator } from '../../../ui/Separator'\n\n// Icons\n\n// Building data hook\n\n\nimport { fetchSuggestions, parseLocation, handleLocationSelect, buildingToFeature } from '../utils/geocoder'\nimport { labelsFromParams, labelsFromPlace, writeLocationParams } from '../utils/urlLocation/locationParams'\n\nimport type { CurrentLocation } from '../../../../types/map'\nimport type { LocationLabels } from '../utils/urlLocation/locationParams'\nimport type { Feature } from 'geojson'\n\nfunction labelsFor(feature: Feature, type: string): LocationLabels {\n const props = feature.properties ?? {}\n const address = String(props.label ?? '').split(',')[0].trim()\n const place = type === 'dbBuilding'\n ? { municipality: props.municipality, countrySubdivision: props.countrySubdivision, address }\n : labelsFromPlace(props, address)\n const { country } = labelsFromParams(new URL(window.location.href).searchParams)\n return { country, ...Object.fromEntries(Object.entries(place).filter(([, value]) => value)) }\n}\n\n\ninterface GeocoderProps {\n onSelect?: (addressData: any) => void\n showDatabaseBuildings?: boolean\n alwaysExpanded?: boolean\n geocodeEarthApiKey?: string\n geocoderUrl?: string\n}\n\nexport default function Geocoder({\n onSelect,\n showDatabaseBuildings = true,\n alwaysExpanded = false,\n geocodeEarthApiKey,\n geocoderUrl,\n}: GeocoderProps) {\n useGeocodingRuntimeConfig({ geocodeEarthApiKey, geocoderUrl })\n\n // Translation\n const t = useTranslations('Geocoder')\n\n const [address, setAddress] = React.useState<string>('')\n const [query, setQuery] = React.useState('')\n const [suggestions, setSuggestions] = React.useState([])\n const [buildingResults, setBuildingResults] = React.useState([])\n const [focused, setFocused] = React.useState(alwaysExpanded)\n const [selectedAddress, setSelectedAddress] = React.useState(null)\n const [isExpanded, setIsExpanded] = React.useState(alwaysExpanded)\n const [loading, setLoading] = React.useState(false)\n\n const pathname = usePathname()\n\n const suggestionsRef = React.useRef(null)\n const inputRef = React.useRef(null)\n const debounceRef = React.useRef(null)\n\n const { dispatch: mapDispatch, state: mapState } = React.useContext(MapContext)\n const { map, currentLocation, organizationCountry } = mapState.map\n\n // Fetch buildings data from API only if showDatabaseBuildings is true\n const { buildings, isLoading: isBuildingsLoading } = useBuildings()\n\n // Filter buildings based on search query\n const filterBuildings = React.useCallback((searchQuery) => {\n if (!showDatabaseBuildings || !buildings || !searchQuery || searchQuery.length < 3) return []\n\n const lowerQuery = searchQuery.toLowerCase()\n\n if (Array.isArray(buildings) && buildings.length > 0) {\n return buildings.filter((building) => {\n return (\n (building.buildingName && building.buildingName.toLowerCase().includes(lowerQuery))\n || (building.buildingAddress && building.buildingAddress.toLowerCase().includes(lowerQuery))\n || (building.buildingMunicipality && building.buildingMunicipality.toLowerCase().includes(lowerQuery))\n || (building.buildingCountrySubdivision && building.buildingCountrySubdivision.toLowerCase().includes(lowerQuery))\n )\n }).slice(0, 3) // Limit to 3 results\n }\n return []\n }, [buildings, showDatabaseBuildings])\n\n // Debounce the API request to avoid rate limiting and excessive requests\n React.useEffect(() => {\n if (debounceRef.current) {\n clearTimeout(debounceRef.current)\n }\n\n const fetchDebounced = async () => {\n if (!query || query.length < 3) {\n setSuggestions([])\n setBuildingResults([])\n setLoading(false)\n return\n }\n\n setLoading(true)\n try {\n // Filter buildings from our database only if enabled\n if (showDatabaseBuildings) {\n const filteredBuildings = filterBuildings(query)\n setBuildingResults(filteredBuildings)\n }\n\n // Fetch geocoding suggestions\n const geocodeResults = await fetchSuggestions(query, organizationCountry)\n\n // Deduplicate geocode results based on name and region\n const deduplicatedResults = geocodeResults.reduce((acc, feature) => {\n const location = parseLocation(feature)\n // Create a unique key based on name and region (case-insensitive)\n const key = `${location.name?.toLowerCase() || ''}_${location.region?.toLowerCase() || ''}`\n\n // Only add if we haven't seen this combination before\n if (!acc.seen.has(key)) {\n acc.seen.add(key)\n acc.features.push(feature)\n }\n\n return acc\n }, { seen: new Set(), features: [] })\n\n setSuggestions(deduplicatedResults.features)\n }\n catch (error) {\n console.error('Error fetching suggestions:', error)\n setSuggestions([])\n }\n finally {\n setLoading(false)\n }\n }\n\n debounceRef.current = setTimeout(() => { void fetchDebounced() }, 300) // Increased debounce time for better API rate limiting\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current)\n }\n }, [query, filterBuildings, showDatabaseBuildings])\n\n // Handle click outside to close suggestions\n React.useEffect(() => {\n const handleClickOutside = (event) => {\n if (suggestionsRef.current && !suggestionsRef.current.contains(event.target)\n && inputRef.current && !inputRef.current.contains(event.target) // Don't close if alwaysExpanded is true\n && !alwaysExpanded) {\n setFocused(false)\n }\n }\n\n document.addEventListener('mousedown', handleClickOutside)\n return () => {\n document.removeEventListener('mousedown', handleClickOutside)\n }\n }, [alwaysExpanded])\n\n // Handle suggestion selection\n const handleSelectSuggestion = (feature, type = '') => {\n setQuery('') // Clear the input field\n setSuggestions([])\n setBuildingResults([])\n if (!alwaysExpanded) {\n setFocused(false)\n }\n\n const syncUrl = () => { if (map) writeLocationParams(map, labelsFor(feature, type)) }\n // handleLocationSelect will automatically remove any existing marker and add a new one\n const addressData = handleLocationSelect(feature, map, type, { onMoveEnd: syncUrl })\n\n const address = addressData.formatted_address || feature.properties?.label || ''\n setAddress(address)\n setSelectedAddress(addressData)\n\n if (onSelect) onSelect(addressData)\n\n if (mapDispatch && currentLocation && addressData.coordinates) {\n const [lng, lat] = addressData.coordinates\n const labels = labelsFor(feature, type)\n const newCurrentLocation: CurrentLocation = {\n ...currentLocation,\n municipality: labels.municipality ?? '',\n countrySubdivision: labels.countrySubdivision ?? '',\n address: labels.address ?? '',\n lng,\n lat,\n }\n mapDispatch({ type: 'UPDATE_LOCATION', payload: { currentLocation: newCurrentLocation } })\n }\n }\n\n // Handle expand of menubar to display search input\n const handleExpand = () => {\n if (alwaysExpanded) return // Don't allow toggling if always expanded\n\n setIsExpanded(!isExpanded)\n if (isExpanded) {\n setFocused(false)\n setQuery('') // clear input and suggestions when collapsed\n setSuggestions([])\n setBuildingResults([])\n }\n else {\n setFocused(true)\n setTimeout(() => {\n inputRef.current?.focus()\n }, 100) // Small delay to ensure the input is rendered\n }\n }\n\n return (\n <Command>\n {/* Search input + button */}\n <div className={`flex flex-row justify-start items-center w-full h-auto `}>\n {!alwaysExpanded && (\n <Button\n variant=\"ghost\"\n size=\"icon\"\n onClick={handleExpand}\n className=\"opacity-70 w-6 justify-end hover:opacity-100 transition-opacity duration-200 hover:bg-transparent\"\n >\n <Search />\n </Button>\n )}\n {alwaysExpanded && (\n <Search className=\"h-4 w-4 opacity-50\" />\n )}\n <Input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={e => setQuery(e.target.value)}\n onFocus={() => setFocused(true)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n inputRef.current?.blur()\n }\n }}\n placeholder={alwaysExpanded ? t('placeholder1') : t('placeholder2')}\n className={`border-none focus-visible:ring-transparent text-sm transition-all ease-in-out duration-200 ${\n alwaysExpanded || isExpanded ? 'w-full' : 'w-0 p-0'\n }`}\n />\n </div>\n\n {focused && (loading || buildingResults.length > 0 || suggestions.length > 0) && (\n <div ref={suggestionsRef}>\n <Separator />\n <CommandList>\n {!loading && buildingResults.length === 0 && suggestions.length === 0 && query.length >= 3 && (\n <CommandEmpty>{showDatabaseBuildings ? t('noResults') : t('noAddresses')}</CommandEmpty>\n )}\n\n {loading && (\n <CommandEmpty><LoadingSpinner /></CommandEmpty>\n )}\n\n {/* Database Buildings section - only show if enabled */}\n {showDatabaseBuildings && !loading && buildingResults.length > 0 && (\n <CommandGroup heading={t('buildingHeader')}>\n {buildingResults.map((building) => {\n const buildingFeature = buildingToFeature(building)\n\n return (\n <CommandItem\n key={`building-${building.id}`}\n onSelect={() => handleSelectSuggestion(buildingFeature, 'dbBuilding')}\n className=\"cursor-pointer\"\n >\n <div className=\"font-medium\">{building.buildingName}</div>\n <div className=\"text-sm text-muted-foreground\">\n {building.buildingAddress}\n </div>\n </CommandItem>\n )\n })}\n </CommandGroup>\n )}\n\n {/* Separator between sections if both have results */}\n {showDatabaseBuildings && buildingResults.length > 0 && suggestions.length > 0 && (\n <CommandSeparator />\n )}\n\n {/* Geocoder suggestions section */}\n {!loading && suggestions.length > 0 && (\n <CommandGroup heading={showDatabaseBuildings ? t('suggestionsHeader') : undefined}>\n {suggestions.map((feature) => {\n const location = parseLocation(feature)\n const uniqueKey = feature.properties?.gid\n || `${feature.properties?.name}-${feature.geometry?.coordinates?.[0]}-${feature.geometry?.coordinates?.[1]}`\n\n return (\n <CommandItem\n key={uniqueKey}\n onSelect={() => handleSelectSuggestion(feature)}\n className=\"cursor-pointer\"\n >\n <div className=\"font-medium\">{location.name}</div>\n <div className=\"text-sm text-muted-foreground\">{location.region}</div>\n </CommandItem>\n )\n })}\n </CommandGroup>\n )}\n </CommandList>\n </div>\n )}\n </Command>\n )\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8OU,SAQM,KARN;AAxOV,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAChC,YAAY,WAAW;AAGvB,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,kBAAkB;AAK3B,SAAS,cAAc;AACvB,SAAS,SAAS,aAAa,cAAc,cAAc,aAAa,wBAAwB;AAChG,SAAS,aAAa;AACtB,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;AAO1B,SAAS,kBAAkB,eAAe,sBAAsB,yBAAyB;AACzF,SAAS,kBAAkB,iBAAiB,2BAA2B;AAMvE,SAAS,UAAU,SAAkB,MAA8B;AArCnE;AAsCE,QAAM,SAAQ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AAAA,QAEJ,CAAC,GACH;AAAA,QAID,yBAAyB,gBAAgB,SAAS,KAAK,YAAY,SAAS,KAC3E,oBAAC,oBAAiB;AAAA,QAInB,CAAC,WAAW,YAAY,SAAS,KAChC,oBAAC,gBAAa,SAAS,wBAAwB,EAAE,mBAAmB,IAAI,QACrE,sBAAY,IAAI,CAAC,YAAY;AAxTlD;AAyTsB,gBAAM,WAAW,cAAc,OAAO;AACtC,gBAAM,cAAY,aAAQ,eAAR,mBAAoB,QACjC,IAAG,aAAQ,eAAR,mBAAoB,IAAI,KAAI,mBAAQ,aAAR,mBAAkB,gBAAlB,mBAAgC,EAAE,KAAI,mBAAQ,aAAR,mBAAkB,gBAAlB,mBAAgC,EAAE;AAE5G,iBACE;AAAA,YAAC;AAAA;AAAA,cAEC,UAAU,MAAM,uBAAuB,OAAO;AAAA,cAC9C,WAAU;AAAA,cAEV;AAAA,oCAAC,SAAI,WAAU,eAAe,mBAAS,MAAK;AAAA,gBAC5C,oBAAC,SAAI,WAAU,iCAAiC,mBAAS,QAAO;AAAA;AAAA;AAAA,YAL3D;AAAA,UAMP;AAAA,QAEJ,CAAC,GACH;AAAA,SAEJ;AAAA,OACF;AAAA,KAEJ;AAER;","names":["address"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAa9B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAA;AAWtE,eAAO,MAAM,sBAAsB,2iBAOzB,CAAA;AAEV,eAAO,MAAM,wBAAwB,gFAI3B,CAAA;AAsHV,eAAO,MAAM,YAAY,GAAI,+BAA+B;IAAE,YAAY,CAAC,EAAE,YAAY,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,sBA4GhH,CAAA"}
|
|
@@ -21,11 +21,12 @@ var __spreadValues = (a, b) => {
|
|
|
21
21
|
};
|
|
22
22
|
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
23
23
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
24
|
-
import { useSearchParams
|
|
24
|
+
import { useSearchParams } from "next/navigation";
|
|
25
25
|
import * as React from "react";
|
|
26
26
|
import { Source, Layer } from "react-map-gl/maplibre";
|
|
27
27
|
import { MapContext } from "../../../../../../../store/Map/context";
|
|
28
28
|
import { maptilerKeyForRequest } from "../../../../utils/mapStyleSpec";
|
|
29
|
+
import { replaceUrlParams } from "../../../../utils/urlLocation/locationParams";
|
|
29
30
|
import { hexToRgba, buildSubdivisionUrl } from "./countryLayerUtils";
|
|
30
31
|
import { useCameraSubdivision } from "./useCameraSubdivision";
|
|
31
32
|
import { useSubdivisionHover } from "./useSubdivisionHover";
|
|
@@ -168,7 +169,6 @@ const CountryLayer = ({ organization, maptilerKey }) => {
|
|
|
168
169
|
const { state: mapState, dispatch: mapDispatch } = React.useContext(MapContext);
|
|
169
170
|
const { map, currentLocation } = mapState.map;
|
|
170
171
|
const searchParams = useSearchParams();
|
|
171
|
-
const router = useRouter();
|
|
172
172
|
const countryCode = ((organization == null ? void 0 : organization.country) || "CA").toUpperCase();
|
|
173
173
|
const borderColor = hexToRgba((organization == null ? void 0 : organization.mainColor) || DEFAULT_BORDER_COLOR, 0.7);
|
|
174
174
|
const subdivisionUrl = buildSubdivisionUrl(countryCode);
|
|
@@ -210,10 +210,11 @@ const CountryLayer = ({ organization, maptilerKey }) => {
|
|
|
210
210
|
currentLocation: __spreadProps(__spreadValues({}, currentLocation != null ? currentLocation : {}), { countrySubdivision: code })
|
|
211
211
|
}
|
|
212
212
|
});
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
213
|
+
replaceUrlParams((params) => {
|
|
214
|
+
params.set("countrySubdivision", code);
|
|
215
|
+
return params;
|
|
216
|
+
});
|
|
217
|
+
}, [currentLocation, mapDispatch]);
|
|
217
218
|
useCameraSubdivision({
|
|
218
219
|
map,
|
|
219
220
|
layerId: SUBDIVISION_FILL_ID,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.tsx"],"sourcesContent":["\"use client\"\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { useSearchParams, useRouter } from 'next/navigation'\nimport * as React from 'react'\nimport { Source, Layer } from 'react-map-gl/maplibre'\n\nimport { MapContext } from '../../../../../../../store/Map/context'\n\nimport { maptilerKeyForRequest } from '../../../../utils/mapStyleSpec'\n\nimport { hexToRgba, buildSubdivisionUrl } from './countryLayerUtils'\nimport { useCameraSubdivision } from './useCameraSubdivision'\nimport { useSubdivisionHover } from './useSubdivisionHover'\n\nimport type { Organization } from '../../../../../../../types/dbTypes'\n\nconst DEFAULT_BORDER_COLOR = '#73cee2'\nconst BOUNDARIES_SOURCE_ID = 'openmaptiles-boundaries'\nconst SUBDIVISION_SOURCE_ID = 'admin-subdivisions-source'\nconst SUBDIVISION_FILL_ID = 'admin-subdivisions-fill'\nconst SUBDIVISION_LINE_ID = 'admin-subdivisions-line'\nconst SUBDIVISION_LINE_MAX_ZOOM = 10\n\nconst HOVERED = ['boolean', ['feature-state', 'hover'], false] as const\n\nexport const SUBDIVISION_LINE_WIDTH = [\n 'interpolate', ['linear'], ['zoom'],\n 4, ['case', HOVERED, 0.5, 0.5],\n 8, ['case', HOVERED, 1.4, 1.4],\n 10, ['case', HOVERED, 3, 1.7],\n 14, ['case', HOVERED, 4.6, 2.4],\n 15, ['case', HOVERED, 5, 2.4],\n] as const\n// The border only helps while picking a subdivision; past zoom 9 the fill still hit-tests without it.\nexport const SUBDIVISION_LINE_OPACITY = [\n 'interpolate', ['linear'], ['zoom'],\n 9, 1,\n 9.5, 0,\n] as const\n\nconst GLOBAL_LAYER_IDS = [\n 'global-borders-country',\n 'global-labels-country',\n 'global-labels-state',\n 'global-labels-city',\n] as const\n\nfunction addGlobalBorderLayer(map: any, color: string, maptilerKey?: string) {\n const key = maptilerKeyForRequest(maptilerKey)\n if (!key) return\n\n try {\n if (!map.getSource(BOUNDARIES_SOURCE_ID)) {\n map.addSource(BOUNDARIES_SOURCE_ID, {\n type: 'vector',\n url: `https://api.maptiler.com/tiles/v3/tiles.json?key=${key}`,\n })\n }\n\n // Country borders — visible at all zooms, slightly thinner up close where states take over.\n if (!map.getLayer('global-borders-country')) {\n map.addLayer({\n id: 'global-borders-country',\n type: 'line',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'boundary',\n filter: ['all', ['==', 'admin_level', 2], ['==', 'maritime', 0]],\n layout: { 'line-cap': 'round', 'line-join': 'round' },\n paint: {\n 'line-color': color,\n 'line-width': { base: 1, stops: [[0, 0.8], [4, 1.4], [10, 1.4], [14, 1]] },\n },\n })\n }\n\n // Country labels — small/global up to zoom ~6, gone by 8.\n if (!map.getLayer('global-labels-country')) {\n map.addLayer({\n id: 'global-labels-country',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['==', 'class', 'country'],\n minzoom: 1,\n maxzoom: 8,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[1, 10], [4, 13], [6, 16]] },\n 'text-letter-spacing': 0.1,\n 'text-max-width': 8,\n 'text-transform': 'uppercase',\n },\n paint: {\n 'text-color': '#ffffff',\n 'text-halo-color': 'rgba(0,0,0,0.7)',\n 'text-halo-width': 1.2,\n 'text-opacity': { base: 1, stops: [[5, 1], [7, 0]] },\n },\n })\n }\n\n // State / province labels — cover zoom 3–8.\n if (!map.getLayer('global-labels-state')) {\n map.addLayer({\n id: 'global-labels-state',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['in', 'class', 'state', 'province'],\n minzoom: 3,\n maxzoom: 9,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[3, 9], [6, 12], [8, 14]] },\n 'text-letter-spacing': 0.05,\n 'text-max-width': 8,\n },\n paint: {\n 'text-color': '#e8e8e8',\n 'text-halo-color': 'rgba(0,0,0,0.6)',\n 'text-halo-width': 1,\n 'text-opacity': { base: 1, stops: [[3, 0], [4, 1], [8, 1], [9, 0]] },\n },\n })\n }\n\n // Major city labels (rank ≤ 4 = most prominent cities) — appear when zoomed in past country level.\n if (!map.getLayer('global-labels-city')) {\n map.addLayer({\n id: 'global-labels-city',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['in', 'class', 'city', 'town'],\n minzoom: 5,\n maxzoom: 13,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[5, 10], [9, 13], [12, 15]] },\n 'text-max-width': 8,\n },\n paint: {\n 'text-color': '#dcdcdc',\n 'text-halo-color': 'rgba(0,0,0,0.7)',\n 'text-halo-width': 1.1,\n },\n })\n }\n } catch {\n // style may be in a transitional state\n }\n}\n\nexport const CountryLayer = ({ organization, maptilerKey }: { organization?: Organization; maptilerKey?: string }) => {\n const { state: mapState, dispatch: mapDispatch } = React.useContext(MapContext)\n const { map, currentLocation } = mapState.map\n const searchParams = useSearchParams()\n const router = useRouter()\n\n const countryCode = (organization?.country || 'CA').toUpperCase()\n const borderColor = hexToRgba((organization?.mainColor as string) || DEFAULT_BORDER_COLOR, 0.7)\n const subdivisionUrl = buildSubdivisionUrl(countryCode)\n\n // Re-added on every style swap: setStyle drops imperatively added layers.\n React.useEffect(() => {\n if (!map) return\n const addNow = () => addGlobalBorderLayer(map, borderColor, maptilerKey)\n if (map.isStyleLoaded()) addNow()\n map.on('styledata', addNow)\n return () => {\n try {\n map.off('styledata', addNow)\n for (const id of GLOBAL_LAYER_IDS) {\n if (map.getLayer(id)) map.removeLayer(id)\n }\n } catch {\n // map may be destroyed\n }\n }\n }, [map, borderColor, maptilerKey])\n\n // If the org already has a fixed subdivision or municipality, lock them in and skip camera tracking\n const orgHasLocation = !!(organization?.countrySubdivision || organization?.municipality)\n\n // A selected building owns the location params; camera tracking would overwrite them on the first pan.\n const buildingOwnsLocation = !!searchParams.get('buildingId')\n\n // When org has fixed location values, push them into currentLocation once\n React.useEffect(() => {\n if (!orgHasLocation) return\n mapDispatch({\n type: 'UPDATE_LOCATION',\n payload: {\n currentLocation: {\n ...(currentLocation ?? {}),\n countrySubdivision: organization?.countrySubdivision ?? currentLocation?.countrySubdivision,\n municipality: organization?.municipality ?? currentLocation?.municipality,\n } as any,\n },\n })\n\n }, [orgHasLocation])\n\n const commitSubdivision = React.useCallback((code: string) => {\n if (code === (currentLocation?.countrySubdivision || null)) return\n\n mapDispatch({\n type: 'UPDATE_LOCATION',\n payload: {\n currentLocation: { ...(currentLocation ?? {}), countrySubdivision: code } as any,\n },\n })\n\n const params = new URLSearchParams(searchParams.toString())\n params.set('countrySubdivision', code)\n router.replace(`?${params.toString()}`, { scroll: false })\n }, [currentLocation, mapDispatch, router, searchParams])\n\n useCameraSubdivision({\n map,\n layerId: SUBDIVISION_FILL_ID,\n sourceId: SUBDIVISION_SOURCE_ID,\n enabled: !orgHasLocation && !buildingOwnsLocation,\n onResolve: commitSubdivision,\n })\n\n useSubdivisionHover({\n map,\n layerId: SUBDIVISION_FILL_ID,\n sourceId: SUBDIVISION_SOURCE_ID,\n enabled: !orgHasLocation,\n })\n\n if (orgHasLocation) return null\n\n return (\n <Source\n id={SUBDIVISION_SOURCE_ID}\n type=\"geojson\"\n data={subdivisionUrl}\n generateId\n >\n {/* Zero opacity, never visible: this is what hit-tests the camera target and the pointer. */}\n <Layer\n id={SUBDIVISION_FILL_ID}\n type=\"fill\"\n paint={{ 'fill-color': borderColor, 'fill-opacity': 0 }}\n />\n <Layer\n id={SUBDIVISION_LINE_ID}\n type=\"line\"\n maxzoom={SUBDIVISION_LINE_MAX_ZOOM}\n layout={{ 'line-cap': 'round', 'line-join': 'round' }}\n paint={{\n 'line-color': borderColor,\n 'line-width': SUBDIVISION_LINE_WIDTH as never,\n 'line-opacity': SUBDIVISION_LINE_OPACITY as never,\n }}\n />\n </Source>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkPI,SAOE,KAPF;AA7OJ,SAAS,iBAAiB,iBAAiB;AAC3C,YAAY,WAAW;AACvB,SAAS,QAAQ,aAAa;AAE9B,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AAEtC,SAAS,WAAW,2BAA2B;AAC/C,SAAS,4BAA4B;AACrC,SAAS,2BAA2B;AAIpC,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,MAAM,UAAU,CAAC,WAAW,CAAC,iBAAiB,OAAO,GAAG,KAAK;AAEtD,MAAM,yBAAyB;AAAA,EACpC;AAAA,EAAe,CAAC,QAAQ;AAAA,EAAG,CAAC,MAAM;AAAA,EAClC;AAAA,EAAG,CAAC,QAAQ,SAAS,KAAK,GAAG;AAAA,EAC7B;AAAA,EAAG,CAAC,QAAQ,SAAS,KAAK,GAAG;AAAA,EAC7B;AAAA,EAAI,CAAC,QAAQ,SAAS,GAAG,GAAG;AAAA,EAC5B;AAAA,EAAI,CAAC,QAAQ,SAAS,KAAK,GAAG;AAAA,EAC9B;AAAA,EAAI,CAAC,QAAQ,SAAS,GAAG,GAAG;AAC9B;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7B,WAAW;AAAA,EACb,CAAC;AAED,sBAAoB;AAAA,IAClB;AAAA,IACA,SAAS;AAAA,IACT,UAAU;AAAA,IACV,SAAS,CAAC;AAAA,EACZ,CAAC;AAED,MAAI,eAAgB,QAAO;AAE3B,SACE;AAAA,IAAC;AAAA;AAAA,MACC,IAAI;AAAA,MACJ,MAAK;AAAA,MACL,MAAM;AAAA,MACN,YAAU;AAAA,MAGV;AAAA;AAAA,UAAC;AAAA;AAAA,YACC,IAAI;AAAA,YACJ,MAAK;AAAA,YACL,OAAO,EAAE,cAAc,aAAa,gBAAgB,EAAE;AAAA;AAAA,QACxD;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,IAAI;AAAA,YACJ,MAAK;AAAA,YACL,SAAS;AAAA,YACT,QAAQ,EAAE,YAAY,SAAS,aAAa,QAAQ;AAAA,YACpD,OAAO;AAAA,cACL,cAAc;AAAA,cACd,cAAc;AAAA,cACd,gBAAgB;AAAA,YAClB;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/CountryLayer/index.tsx"],"sourcesContent":["\"use client\"\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { useSearchParams } from 'next/navigation'\nimport * as React from 'react'\nimport { Source, Layer } from 'react-map-gl/maplibre'\n\nimport { MapContext } from '../../../../../../../store/Map/context'\n\nimport { maptilerKeyForRequest } from '../../../../utils/mapStyleSpec'\n\nimport { replaceUrlParams } from '../../../../utils/urlLocation/locationParams'\n\nimport { hexToRgba, buildSubdivisionUrl } from './countryLayerUtils'\nimport { useCameraSubdivision } from './useCameraSubdivision'\nimport { useSubdivisionHover } from './useSubdivisionHover'\n\nimport type { Organization } from '../../../../../../../types/dbTypes'\n\nconst DEFAULT_BORDER_COLOR = '#73cee2'\nconst BOUNDARIES_SOURCE_ID = 'openmaptiles-boundaries'\nconst SUBDIVISION_SOURCE_ID = 'admin-subdivisions-source'\nconst SUBDIVISION_FILL_ID = 'admin-subdivisions-fill'\nconst SUBDIVISION_LINE_ID = 'admin-subdivisions-line'\nconst SUBDIVISION_LINE_MAX_ZOOM = 10\n\nconst HOVERED = ['boolean', ['feature-state', 'hover'], false] as const\n\nexport const SUBDIVISION_LINE_WIDTH = [\n 'interpolate', ['linear'], ['zoom'],\n 4, ['case', HOVERED, 0.5, 0.5],\n 8, ['case', HOVERED, 1.4, 1.4],\n 10, ['case', HOVERED, 3, 1.7],\n 14, ['case', HOVERED, 4.6, 2.4],\n 15, ['case', HOVERED, 5, 2.4],\n] as const\n// The border only helps while picking a subdivision; past zoom 9 the fill still hit-tests without it.\nexport const SUBDIVISION_LINE_OPACITY = [\n 'interpolate', ['linear'], ['zoom'],\n 9, 1,\n 9.5, 0,\n] as const\n\nconst GLOBAL_LAYER_IDS = [\n 'global-borders-country',\n 'global-labels-country',\n 'global-labels-state',\n 'global-labels-city',\n] as const\n\nfunction addGlobalBorderLayer(map: any, color: string, maptilerKey?: string) {\n const key = maptilerKeyForRequest(maptilerKey)\n if (!key) return\n\n try {\n if (!map.getSource(BOUNDARIES_SOURCE_ID)) {\n map.addSource(BOUNDARIES_SOURCE_ID, {\n type: 'vector',\n url: `https://api.maptiler.com/tiles/v3/tiles.json?key=${key}`,\n })\n }\n\n // Country borders — visible at all zooms, slightly thinner up close where states take over.\n if (!map.getLayer('global-borders-country')) {\n map.addLayer({\n id: 'global-borders-country',\n type: 'line',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'boundary',\n filter: ['all', ['==', 'admin_level', 2], ['==', 'maritime', 0]],\n layout: { 'line-cap': 'round', 'line-join': 'round' },\n paint: {\n 'line-color': color,\n 'line-width': { base: 1, stops: [[0, 0.8], [4, 1.4], [10, 1.4], [14, 1]] },\n },\n })\n }\n\n // Country labels — small/global up to zoom ~6, gone by 8.\n if (!map.getLayer('global-labels-country')) {\n map.addLayer({\n id: 'global-labels-country',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['==', 'class', 'country'],\n minzoom: 1,\n maxzoom: 8,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[1, 10], [4, 13], [6, 16]] },\n 'text-letter-spacing': 0.1,\n 'text-max-width': 8,\n 'text-transform': 'uppercase',\n },\n paint: {\n 'text-color': '#ffffff',\n 'text-halo-color': 'rgba(0,0,0,0.7)',\n 'text-halo-width': 1.2,\n 'text-opacity': { base: 1, stops: [[5, 1], [7, 0]] },\n },\n })\n }\n\n // State / province labels — cover zoom 3–8.\n if (!map.getLayer('global-labels-state')) {\n map.addLayer({\n id: 'global-labels-state',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['in', 'class', 'state', 'province'],\n minzoom: 3,\n maxzoom: 9,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[3, 9], [6, 12], [8, 14]] },\n 'text-letter-spacing': 0.05,\n 'text-max-width': 8,\n },\n paint: {\n 'text-color': '#e8e8e8',\n 'text-halo-color': 'rgba(0,0,0,0.6)',\n 'text-halo-width': 1,\n 'text-opacity': { base: 1, stops: [[3, 0], [4, 1], [8, 1], [9, 0]] },\n },\n })\n }\n\n // Major city labels (rank ≤ 4 = most prominent cities) — appear when zoomed in past country level.\n if (!map.getLayer('global-labels-city')) {\n map.addLayer({\n id: 'global-labels-city',\n type: 'symbol',\n source: BOUNDARIES_SOURCE_ID,\n 'source-layer': 'place',\n filter: ['in', 'class', 'city', 'town'],\n minzoom: 5,\n maxzoom: 13,\n layout: {\n 'text-field': ['coalesce', ['get', 'name:latin'], ['get', 'name']],\n 'text-font': ['Noto Sans Regular'],\n 'text-size': { base: 1, stops: [[5, 10], [9, 13], [12, 15]] },\n 'text-max-width': 8,\n },\n paint: {\n 'text-color': '#dcdcdc',\n 'text-halo-color': 'rgba(0,0,0,0.7)',\n 'text-halo-width': 1.1,\n },\n })\n }\n } catch {\n // style may be in a transitional state\n }\n}\n\nexport const CountryLayer = ({ organization, maptilerKey }: { organization?: Organization; maptilerKey?: string }) => {\n const { state: mapState, dispatch: mapDispatch } = React.useContext(MapContext)\n const { map, currentLocation } = mapState.map\n const searchParams = useSearchParams()\n\n const countryCode = (organization?.country || 'CA').toUpperCase()\n const borderColor = hexToRgba((organization?.mainColor as string) || DEFAULT_BORDER_COLOR, 0.7)\n const subdivisionUrl = buildSubdivisionUrl(countryCode)\n\n // Re-added on every style swap: setStyle drops imperatively added layers.\n React.useEffect(() => {\n if (!map) return\n const addNow = () => addGlobalBorderLayer(map, borderColor, maptilerKey)\n if (map.isStyleLoaded()) addNow()\n map.on('styledata', addNow)\n return () => {\n try {\n map.off('styledata', addNow)\n for (const id of GLOBAL_LAYER_IDS) {\n if (map.getLayer(id)) map.removeLayer(id)\n }\n } catch {\n // map may be destroyed\n }\n }\n }, [map, borderColor, maptilerKey])\n\n // If the org already has a fixed subdivision or municipality, lock them in and skip camera tracking\n const orgHasLocation = !!(organization?.countrySubdivision || organization?.municipality)\n\n // A selected building owns the location params; camera tracking would overwrite them on the first pan.\n const buildingOwnsLocation = !!searchParams.get('buildingId')\n\n // When org has fixed location values, push them into currentLocation once\n React.useEffect(() => {\n if (!orgHasLocation) return\n mapDispatch({\n type: 'UPDATE_LOCATION',\n payload: {\n currentLocation: {\n ...(currentLocation ?? {}),\n countrySubdivision: organization?.countrySubdivision ?? currentLocation?.countrySubdivision,\n municipality: organization?.municipality ?? currentLocation?.municipality,\n } as any,\n },\n })\n\n }, [orgHasLocation])\n\n const commitSubdivision = React.useCallback((code: string) => {\n if (code === (currentLocation?.countrySubdivision || null)) return\n\n mapDispatch({\n type: 'UPDATE_LOCATION',\n payload: {\n currentLocation: { ...(currentLocation ?? {}), countrySubdivision: code } as any,\n },\n })\n\n replaceUrlParams(params => {\n params.set('countrySubdivision', code)\n return params\n })\n }, [currentLocation, mapDispatch])\n\n useCameraSubdivision({\n map,\n layerId: SUBDIVISION_FILL_ID,\n sourceId: SUBDIVISION_SOURCE_ID,\n enabled: !orgHasLocation && !buildingOwnsLocation,\n onResolve: commitSubdivision,\n })\n\n useSubdivisionHover({\n map,\n layerId: SUBDIVISION_FILL_ID,\n sourceId: SUBDIVISION_SOURCE_ID,\n enabled: !orgHasLocation,\n })\n\n if (orgHasLocation) return null\n\n return (\n <Source\n id={SUBDIVISION_SOURCE_ID}\n type=\"geojson\"\n data={subdivisionUrl}\n generateId\n >\n {/* Zero opacity, never visible: this is what hit-tests the camera target and the pointer. */}\n <Layer\n id={SUBDIVISION_FILL_ID}\n type=\"fill\"\n paint={{ 'fill-color': borderColor, 'fill-opacity': 0 }}\n />\n <Layer\n id={SUBDIVISION_LINE_ID}\n type=\"line\"\n maxzoom={SUBDIVISION_LINE_MAX_ZOOM}\n layout={{ 'line-cap': 'round', 'line-join': 'round' }}\n paint={{\n 'line-color': borderColor,\n 'line-width': SUBDIVISION_LINE_WIDTH as never,\n 'line-opacity': SUBDIVISION_LINE_OPACITY as never,\n }}\n />\n </Source>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoPI,SAOE,KAPF;AA/OJ,SAAS,uBAAuB;AAChC,YAAY,WAAW;AACvB,SAAS,QAAQ,aAAa;AAE9B,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB;AAEjC,SAAS,WAAW,2BAA2B;AAC/C,SAAS,4BAA4B;AACrC,SAAS,2BAA2B;AAIpC,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,MAAM,UAAU,CAAC,WAAW,CAAC,iBAAiB,OAAO,GAAG,KAAK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AC1E;AAAA,IACF,CAAC;AAED,qBAAiB,YAAU;AACzB,aAAO,IAAI,sBAAsB,IAAI;AACrC,aAAO;AAAA,IACT,CAAC;AAAA,EACH,GAAG,CAAC,iBAAiB,WAAW,CAAC;AAEjC,uBAAqB;AAAA,IACnB;AAAA,IACA,SAAS;AAAA,IACT,UAAU;AAAA,IACV,SAAS,CAAC,kBAAkB,CAAC;AAAA,IAC7B,WAAW;AAAA,EACb,CAAC;AAED,sBAAoB;AAAA,IAClB;AAAA,IACA,SAAS;AAAA,IACT,UAAU;AAAA,IACV,SAAS,CAAC;AAAA,EACZ,CAAC;AAED,MAAI,eAAgB,QAAO;AAE3B,SACE;AAAA,IAAC;AAAA;AAAA,MACC,IAAI;AAAA,MACJ,MAAK;AAAA,MACL,MAAM;AAAA,MACN,YAAU;AAAA,MAGV;AAAA;AAAA,UAAC;AAAA;AAAA,YACC,IAAI;AAAA,YACJ,MAAK;AAAA,YACL,OAAO,EAAE,cAAc,aAAa,gBAAgB,EAAE;AAAA;AAAA,QACxD;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,IAAI;AAAA,YACJ,MAAK;AAAA,YACL,SAAS;AAAA,YACT,QAAQ,EAAE,YAAY,SAAS,aAAa,QAAQ;AAAA,YACpD,OAAO;AAAA,cACL,cAAc;AAAA,cACd,cAAc;AAAA,cACd,gBAAgB;AAAA,YAClB;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
|
|
@@ -53,7 +53,7 @@ const FileModelLayer = ({
|
|
|
53
53
|
const modelsWithChangedCoords = loadedModels.filter((model) => {
|
|
54
54
|
if (!currentFileIds.has(model.file.id)) return false;
|
|
55
55
|
const updated = currentModelFiles.find((f) => f.id === model.file.id);
|
|
56
|
-
return updated && (updated.lat !== model.file.lat || updated.lng !== model.file.lng || updated.rotation !== model.file.rotation || updated.elevation !== model.file.elevation || updated.
|
|
56
|
+
return updated && (updated.lat !== model.file.lat || updated.lng !== model.file.lng || updated.rotation !== model.file.rotation || updated.elevation !== model.file.elevation || updated.fileScale !== model.file.fileScale);
|
|
57
57
|
});
|
|
58
58
|
for (const model of [...modelsToRemove, ...modelsWithChangedCoords]) {
|
|
59
59
|
model.cleanUpFunction();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/FileLayer/FileModelLayer/FileModelLayer.tsx"],"sourcesContent":["\"use client\"\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport * as React from 'react'\nimport * as THREE from 'three'\n\nimport { MapContext, FilesContext } from '../../../../../../../../store'\nimport { ndcOfEvent } from '../../../../../utils/layerRaycast'\nimport { CustomModelLayer } from '../utils/CustomModelLayer'\n\nimport type { DbFile } from '../../../../../../../../types/dbTypes'\nimport type { ModelAnimationControls } from '../utils/CustomModelLayer'\n\ntype LoadedModelFiles = {\n file: DbFile\n cleanUpFunction: () => void\n hitTest: (ndcX: number, ndcY: number) => boolean\n animation: ModelAnimationControls\n}\n\ninterface FileModelLayerProps {\n tempPositionsRef?: React.MutableRefObject<Record<string, { lat: number; lng: number }>>\n editingFileIdRef?: React.MutableRefObject<string | null>\n tempRotationsRef?: React.MutableRefObject<Record<string, number>>\n tempElevationsRef?: React.MutableRefObject<Record<string, number>>\n tempScalesRef?: React.MutableRefObject<Record<string, number>>\n /** Called when the user right-clicks on a rendered 3D mesh, with the model's playback if it has clips. */\n onContextMenu?: (file: DbFile, clientX: number, clientY: number, animation: ModelAnimationControls) => void\n}\n\nexport const FileModelLayer = ({\n tempPositionsRef,\n editingFileIdRef,\n tempRotationsRef,\n tempElevationsRef,\n tempScalesRef,\n onContextMenu,\n}: FileModelLayerProps) => {\n const { state: mapState } = React.useContext(MapContext)\n const { map } = mapState.map\n const { state: fileState } = React.useContext(FilesContext)\n const { files: globalFileState, mapFileIds } = fileState.files\n\n const is3DModelFile = (extension?: string | null): boolean => {\n if (!extension) return false\n const ext = extension.toLowerCase()\n return ['glb', 'gltf', 'fbx', 'obj', 'collada'].includes(ext)\n }\n\n const mapFiles = React.useMemo(\n () => globalFileState.filter(file => is3DModelFile(file.extension) && mapFileIds.includes(file.id) && !!file.url),\n [globalFileState, mapFileIds]\n )\n\n const [loadedModels, setLoadedModels] = React.useState<LoadedModelFiles[]>([])\n const rendererRef = React.useRef<THREE.WebGLRenderer | null>(null)\n\n // Stable refs so the canvas listener never needs to be re-registered\n const loadedModelsRef = React.useRef<LoadedModelFiles[]>([])\n const onContextMenuRef = React.useRef(onContextMenu)\n loadedModelsRef.current = loadedModels\n onContextMenuRef.current = onContextMenu\n\n // ── Layer management ───────────────────────────────────────────────────────\n React.useEffect(() => {\n if (!map) return\n if (!rendererRef.current) {\n rendererRef.current = new THREE.WebGLRenderer({\n canvas: map.getCanvas(),\n context: map.getCanvas().getContext('webgl') as WebGLRenderingContext,\n antialias: true,\n })\n }\n const currentModelFiles = mapFiles.filter(file => {\n const ext = file.extension?.toLowerCase()\n return ext === 'glb' || ext === 'gltf' || ext === 'fbx' || ext === 'obj' || ext === 'collada'\n })\n const loadedIds = new Set(loadedModels.map(model => model.file.id))\n const currentFileIds = new Set(currentModelFiles.map(f => f.id))\n\n const modelsToRemove = loadedModels.filter(model => !currentFileIds.has(model.file.id))\n\n const modelsWithChangedCoords = loadedModels.filter(model => {\n if (!currentFileIds.has(model.file.id)) return false\n const updated = currentModelFiles.find(f => f.id === model.file.id)\n return updated && (\n updated.lat !== model.file.lat ||\n updated.lng !== model.file.lng ||\n updated.rotation !== model.file.rotation ||\n updated.elevation !== model.file.elevation ||\n updated.
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/FileLayer/FileModelLayer/FileModelLayer.tsx"],"sourcesContent":["\"use client\"\n\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport * as React from 'react'\nimport * as THREE from 'three'\n\nimport { MapContext, FilesContext } from '../../../../../../../../store'\nimport { ndcOfEvent } from '../../../../../utils/layerRaycast'\nimport { CustomModelLayer } from '../utils/CustomModelLayer'\n\nimport type { DbFile } from '../../../../../../../../types/dbTypes'\nimport type { ModelAnimationControls } from '../utils/CustomModelLayer'\n\ntype LoadedModelFiles = {\n file: DbFile\n cleanUpFunction: () => void\n hitTest: (ndcX: number, ndcY: number) => boolean\n animation: ModelAnimationControls\n}\n\ninterface FileModelLayerProps {\n tempPositionsRef?: React.MutableRefObject<Record<string, { lat: number; lng: number }>>\n editingFileIdRef?: React.MutableRefObject<string | null>\n tempRotationsRef?: React.MutableRefObject<Record<string, number>>\n tempElevationsRef?: React.MutableRefObject<Record<string, number>>\n tempScalesRef?: React.MutableRefObject<Record<string, number>>\n /** Called when the user right-clicks on a rendered 3D mesh, with the model's playback if it has clips. */\n onContextMenu?: (file: DbFile, clientX: number, clientY: number, animation: ModelAnimationControls) => void\n}\n\nexport const FileModelLayer = ({\n tempPositionsRef,\n editingFileIdRef,\n tempRotationsRef,\n tempElevationsRef,\n tempScalesRef,\n onContextMenu,\n}: FileModelLayerProps) => {\n const { state: mapState } = React.useContext(MapContext)\n const { map } = mapState.map\n const { state: fileState } = React.useContext(FilesContext)\n const { files: globalFileState, mapFileIds } = fileState.files\n\n const is3DModelFile = (extension?: string | null): boolean => {\n if (!extension) return false\n const ext = extension.toLowerCase()\n return ['glb', 'gltf', 'fbx', 'obj', 'collada'].includes(ext)\n }\n\n const mapFiles = React.useMemo(\n () => globalFileState.filter(file => is3DModelFile(file.extension) && mapFileIds.includes(file.id) && !!file.url),\n [globalFileState, mapFileIds]\n )\n\n const [loadedModels, setLoadedModels] = React.useState<LoadedModelFiles[]>([])\n const rendererRef = React.useRef<THREE.WebGLRenderer | null>(null)\n\n // Stable refs so the canvas listener never needs to be re-registered\n const loadedModelsRef = React.useRef<LoadedModelFiles[]>([])\n const onContextMenuRef = React.useRef(onContextMenu)\n loadedModelsRef.current = loadedModels\n onContextMenuRef.current = onContextMenu\n\n // ── Layer management ───────────────────────────────────────────────────────\n React.useEffect(() => {\n if (!map) return\n if (!rendererRef.current) {\n rendererRef.current = new THREE.WebGLRenderer({\n canvas: map.getCanvas(),\n context: map.getCanvas().getContext('webgl') as WebGLRenderingContext,\n antialias: true,\n })\n }\n const currentModelFiles = mapFiles.filter(file => {\n const ext = file.extension?.toLowerCase()\n return ext === 'glb' || ext === 'gltf' || ext === 'fbx' || ext === 'obj' || ext === 'collada'\n })\n const loadedIds = new Set(loadedModels.map(model => model.file.id))\n const currentFileIds = new Set(currentModelFiles.map(f => f.id))\n\n const modelsToRemove = loadedModels.filter(model => !currentFileIds.has(model.file.id))\n\n const modelsWithChangedCoords = loadedModels.filter(model => {\n if (!currentFileIds.has(model.file.id)) return false\n const updated = currentModelFiles.find(f => f.id === model.file.id)\n return updated && (\n updated.lat !== model.file.lat ||\n updated.lng !== model.file.lng ||\n updated.rotation !== model.file.rotation ||\n updated.elevation !== model.file.elevation ||\n updated.fileScale !== model.file.fileScale\n )\n })\n\n for (const model of [...modelsToRemove, ...modelsWithChangedCoords]) {\n model.cleanUpFunction()\n }\n\n const staleIds = new Set(modelsWithChangedCoords.map(m => m.file.id))\n\n const filesNotLoaded = currentModelFiles.filter(\n file => !loadedIds.has(file.id) || staleIds.has(file.id)\n )\n\n const newLoadedModels = loadedModels\n .filter(model => currentFileIds.has(model.file.id) && !staleIds.has(model.file.id))\n\n for (const file of filesNotLoaded) {\n const { cleanup, hitTest, animation } = CustomModelLayer(\n file,\n map,\n rendererRef.current,\n tempPositionsRef,\n editingFileIdRef,\n tempRotationsRef,\n tempElevationsRef,\n tempScalesRef,\n )\n newLoadedModels.push({ file, cleanUpFunction: cleanup, hitTest, animation })\n }\n\n setLoadedModels(newLoadedModels)\n }, [mapFiles, map])\n\n // ── Canvas right-click → raycasting ───────────────────────────────────────\n React.useEffect(() => {\n if (!map) return\n const canvas = map.getCanvas()\n\n const handleContextMenu = (e: MouseEvent) => {\n // Only handle clicks that land directly on the WebGL canvas (not on HTML\n // marker overlays — those have their own onContextMenu handlers)\n if (e.target !== canvas) return\n\n const models = loadedModelsRef.current\n if (models.length === 0) return\n\n const { ndcX, ndcY } = ndcOfEvent(e, canvas.getBoundingClientRect())\n\n for (const model of models) {\n if (model.hitTest(ndcX, ndcY)) {\n e.preventDefault()\n e.stopPropagation()\n onContextMenuRef.current?.(model.file, e.clientX, e.clientY, model.animation)\n break\n }\n }\n }\n\n // Use capture phase so we see the event before MapLibre's own handlers\n canvas.addEventListener('contextmenu', handleContextMenu, true)\n return () => canvas.removeEventListener('contextmenu', handleContextMenu, true)\n }, [map])\n\n // Teardown: remove model layers + dispose the shared renderer on unmount / map\n // change, else the WebGLRenderer + its scenes leak across viewer switches.\n React.useEffect(() => {\n return () => {\n for (const model of loadedModelsRef.current) {\n try { model.cleanUpFunction() } catch { /* layer or map may already be gone */ }\n }\n if (rendererRef.current) {\n rendererRef.current.dispose()\n rendererRef.current = null\n }\n }\n }, [map])\n\n return null\n}\n"],"mappings":";AAKA,YAAY,WAAW;AACvB,YAAY,WAAW;AAEvB,SAAS,YAAY,oBAAoB;AACzC,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AAsB1B,MAAM,iBAAiB,CAAC;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAA2B;AACzB,QAAM,EAAE,OAAO,SAAS,IAAI,MAAM,WAAW,UAAU;AACvD,QAAM,EAAE,IAAI,IAAI,SAAS;AACzB,QAAM,EAAE,OAAO,UAAU,IAAI,MAAM,WAAW,YAAY;AAC1D,QAAM,EAAE,OAAO,iBAAiB,WAAW,IAAI,UAAU;AAEzD,QAAM,gBAAgB,CAAC,cAAuC;AAC5D,QAAI,CAAC,UAAW,QAAO;AACvB,UAAM,MAAM,UAAU,YAAY;AAClC,WAAO,CAAC,OAAO,QAAQ,OAAO,OAAO,SAAS,EAAE,SAAS,GAAG;AAAA,EAC9D;AAEA,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,QAAQ,MAAM,IAAI,GAAG;AAC7B,YAAE,eAAe;AACjB,YAAE,gBAAgB;AAClB,iCAAiB,YAAjB,0CAA2B,MAAM,MAAM,EAAE,SAAS,EAAE,SAAS,MAAM;AACnE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,WAAO,iBAAiB,eAAe,mBAAmB,IAAI;AAC9D,WAAO,MAAM,OAAO,oBAAoB,eAAe,mBAAmB,IAAI;AAAA,EAChF,GAAG,CAAC,GAAG,CAAC;AAIR,QAAM,UAAU,MAAM;AACpB,WAAO,MAAM;AACX,iBAAW,SAAS,gBAAgB,SAAS;AAC3C,YAAI;AAAE,gBAAM,gBAAgB;AAAA,QAAE,SAAQ;AAAA,QAAyC;AAAA,MACjF;AACA,UAAI,YAAY,SAAS;AACvB,oBAAY,QAAQ,QAAQ;AAC5B,oBAAY,UAAU;AAAA,MACxB;AAAA,IACF;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AAER,SAAO;AACT;","names":[]}
|
package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.js
CHANGED
|
@@ -161,7 +161,7 @@ const CustomModelLayer = (modelFile, map, renderer, tempPositionsRef, editingFil
|
|
|
161
161
|
const modelOrigin = [lng, lat];
|
|
162
162
|
const terrainAltitude = isEditing ? (_c = map.queryTerrainElevation([lng, lat])) != null ? _c : cachedTerrainElev : cachedTerrainElev;
|
|
163
163
|
const altitude = terrainAltitude + fileElevation;
|
|
164
|
-
const fileScale = isEditing && (tempScalesRef == null ? void 0 : tempScalesRef.current[modelFileKey]) !== void 0 ? tempScalesRef.current[modelFileKey] : (_d = modelFile.
|
|
164
|
+
const fileScale = isEditing && (tempScalesRef == null ? void 0 : tempScalesRef.current[modelFileKey]) !== void 0 ? tempScalesRef.current[modelFileKey] : (_d = modelFile.fileScale) != null ? _d : 1;
|
|
165
165
|
_m.fromArray(args.defaultProjectionData.mainMatrix);
|
|
166
166
|
writeModelMatrix(_l, modelOrigin, altitude).scale(_scaleVec.setScalar(fileScale));
|
|
167
167
|
this.camera.projectionMatrix.multiplyMatrices(_m, _l);
|
package/dist/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { type CustomLayerInterface, type LngLatLike, type Map } from 'maplibre-gl'\nimport * as THREE from 'three'\nimport { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'\n\nimport { applyAnimationTo, initialState, withClip, withPlaying, withSpeed } from '../../../../../../shared/placement/modelAnimation'\nimport { hitTestLayerScene } from '../../../../../utils/layerRaycast'\nimport { writeModelMatrix } from '../../../../../utils/modelMatrix'\nimport { disposeThreeScene } from '../../disposeThreeScene'\n\nimport type { DbFile } from '../../../../../../../../types/dbTypes'\nimport type { AnimationState } from '../../../../../../shared/placement/modelAnimation'\n\ntype TempPositionsRef = React.MutableRefObject<Record<string, { lat: number; lng: number }>>\ntype TempRotationsRef = React.MutableRefObject<Record<string, number>>\ntype TempElevationsRef = React.MutableRefObject<Record<string, number>>\ntype TempScalesRef = React.MutableRefObject<Record<string, number>>\ntype EditingFileIdRef = React.MutableRefObject<string | null>\n\nfunction resolveModelCoordinates(file: DbFile): { lng: number, lat: number } {\n if (typeof file.lng === 'number' && typeof file.lat === 'number') {\n return { lng: file.lng, lat: file.lat }\n }\n\n const rawPosition = file.position as unknown\n if (rawPosition && typeof rawPosition === 'object') {\n const pos = rawPosition as { lng?: number, lat?: number }\n if (typeof pos.lng === 'number' && typeof pos.lat === 'number') {\n return { lng: pos.lng, lat: pos.lat }\n }\n }\n\n if (typeof rawPosition === 'string') {\n try {\n const parsed = JSON.parse(rawPosition) as { lng?: number, lat?: number }\n if (typeof parsed.lng === 'number' && typeof parsed.lat === 'number') {\n return { lng: parsed.lng, lat: parsed.lat }\n }\n }\n catch {\n // Ignore malformed legacy position payloads.\n }\n }\n\n return { lng: 0, lat: 0 }\n}\n\n/** Playback for a loaded model's clips, so the map's animation card drives the same state the BIM one does. */\nexport interface ModelAnimationControls {\n getClips(): string[]\n getAnimation(): AnimationState | null\n setClip(clipIndex: number): void\n setPlaying(playing: boolean): void\n setSpeed(speed: number): void\n}\n\nexport interface ModelLayerHandle {\n cleanup: () => void\n remove: () => void\n hitTest: (ndcX: number, ndcY: number) => boolean\n animation: ModelAnimationControls\n}\n\nexport const CustomModelLayer = (\n modelFile: DbFile,\n map: Map,\n renderer: THREE.WebGLRenderer,\n tempPositionsRef?: TempPositionsRef,\n editingFileIdRef?: EditingFileIdRef,\n tempRotationsRef?: TempRotationsRef,\n tempElevationsRef?: TempElevationsRef,\n tempScalesRef?: TempScalesRef,\n): ModelLayerHandle => {\n let components = null\n let customLayer: CustomLayerInterface | null = null\n let clips: THREE.AnimationClip[] = []\n let animation: AnimationState | null = null\n let mixerRef: THREE.AnimationMixer | null = null\n\n const noControls: ModelAnimationControls = {\n getClips: () => [],\n getAnimation: () => null,\n setClip: () => {},\n setPlaying: () => {},\n setSpeed: () => {},\n }\n\n if (!map || !modelFile) {\n return { cleanup: () => {}, remove: () => {}, hitTest: () => false, animation: noControls }\n }\n\n const modelFileKey = String(modelFile.id)\n\n // Refs into the layer's camera and scene so raycasting can read the last\n // rendered frame's transform without entering the render loop.\n let cameraRef: THREE.Camera | null = null\n let sceneRef: THREE.Scene | null = null\n\n\n const createCustomLayer = (): CustomLayerInterface => {\n // Track last applied rotation so we can apply delta increments (same as BimLayer)\n let lastAppliedRotation = modelFile.rotation ?? 0\n // Layer-removed-mid-load guard + reused per-frame matrices\n let disposed = false\n const _m = new THREE.Matrix4()\n const _l = new THREE.Matrix4()\n const _scaleVec = new THREE.Vector3()\n // Render-on-demand: cache terrain elevation off the per-frame path and only\n // keep repainting while the camera recently moved or an animation is playing,\n // so an idle map with a placed model stops re-rendering instead of pinning the\n // main thread (this was the freeze after a flyTo to high zoom).\n let cachedTerrainElev = 0\n let lastMoveTime = performance.now()\n const SETTLE_MS = 1000\n let onMapMove: (() => void) | undefined\n let onMapMoveEnd: (() => void) | undefined\n const recomputeTerrainElev = () => {\n const { lng, lat } = resolveModelCoordinates(modelFile)\n if (!(lng === 0 && lat === 0)) {\n const e = map.queryTerrainElevation([lng, lat])\n if (e !== null && e !== undefined) cachedTerrainElev = e\n }\n }\n\n return {\n id: `model-${modelFile.id}`,\n type: 'custom',\n renderingMode: '3d',\n onAdd(map, gl) {\n this.camera = new THREE.Camera()\n this.scene = new THREE.Scene()\n this.renderer = renderer\n\n // Expose to closure for raycasting\n cameraRef = this.camera as THREE.Camera\n sceneRef = this.scene as THREE.Scene\n\n const scene = this.scene as THREE.Scene\n\n // Apply initial rotation\n if (lastAppliedRotation !== 0) {\n scene.rotateY(lastAppliedRotation * (Math.PI / 180))\n }\n\n // Lighting to match OBC library setup\n scene.background = null\n scene.fog = new THREE.Fog(0x20_29_32, 10, 200)\n scene.add(new THREE.AmbientLight(0xFF_FF_FF, 1))\n scene.add(new THREE.HemisphereLight(0xFF_FF_BB, 0x08_08_20, 0.5))\n\n const sun = new THREE.DirectionalLight(0xFF_FF_FF, 1.5)\n sun.position.set(0, -70, 100).normalize()\n sun.castShadow = true\n sun.shadow.mapSize.set(2048, 2048)\n scene.add(sun)\n\n const fill = new THREE.DirectionalLight(0xFF_FF_FF, 1)\n fill.position.set(0, 70, 100).normalize()\n scene.add(fill)\n\n this.renderer.toneMapping = THREE.ACESFilmicToneMapping\n this.renderer.autoClear = false\n this.clock = new THREE.Clock()\n\n const loader = new GLTFLoader()\n loader.load(\n modelFile.url!,\n (gltf) => {\n // Layer was removed before the async load resolved — don't attach to a\n // dead scene; let the gltf be GC'd (no GPU upload happened yet).\n if (disposed) return\n gltf.scene.scale.setScalar(1)\n\n clips = gltf.animations ?? []\n animation = initialState(clips.length)\n if (animation) {\n this.mixer = new THREE.AnimationMixer(gltf.scene)\n mixerRef = this.mixer\n applyAnimationTo(this.mixer, clips, animation)\n }\n\n scene.add(gltf.scene)\n // Open the settle window so the just-loaded model paints, then idle.\n lastMoveTime = performance.now()\n recomputeTerrainElev()\n map.triggerRepaint()\n },\n undefined,\n (error) => { console.error('Error loading model:', error) },\n )\n\n // Track camera movement for render-on-demand: keep repainting only\n // during/just-after movement; refresh cached terrain elevation on settle.\n onMapMove = () => { lastMoveTime = performance.now() }\n onMapMoveEnd = () => {\n lastMoveTime = performance.now()\n recomputeTerrainElev()\n map.triggerRepaint()\n }\n map.on('move', onMapMove)\n map.on('moveend', onMapMoveEnd)\n },\n\n render(gl, args) {\n if (map.getZoom() < 15.5) return\n\n const isEditing = editingFileIdRef?.current === modelFileKey\n\n // ── Position ──────────────────────────────────────────────────────────\n let lng: number\n let lat: number\n if (isEditing && tempPositionsRef?.current[modelFileKey]) {\n const tp = tempPositionsRef.current[modelFileKey]\n lng = tp.lng\n lat = tp.lat\n } else {\n const coords = resolveModelCoordinates(modelFile)\n lng = coords.lng\n lat = coords.lat\n }\n\n if (lng === 0 && lat === 0) return\n\n // ── Rotation (delta-increment, same pattern as BimLayer) ──────────────\n const targetRotation = (isEditing && tempRotationsRef?.current[modelFileKey] !== undefined)\n ? tempRotationsRef.current[modelFileKey]\n : (modelFile.rotation ?? 0)\n\n if (targetRotation !== lastAppliedRotation) {\n ;(this.scene as THREE.Scene).rotateY(\n (targetRotation - lastAppliedRotation) * (Math.PI / 180)\n )\n lastAppliedRotation = targetRotation\n }\n\n // ── Elevation ─────────────────────────────────────────────────────────\n const fileElevation = (isEditing && tempElevationsRef?.current[modelFileKey] !== undefined)\n ? tempElevationsRef.current[modelFileKey]\n : (modelFile.elevation ?? 0)\n\n const modelOrigin = [lng, lat] as LngLatLike\n // Cached terrain elevation (refreshed on moveend); query live only while\n // editing this model's position. Keeps queryTerrainElevation off the hot\n // path — the per-frame query drove the high-zoom freeze.\n const terrainAltitude = isEditing\n ? (map.queryTerrainElevation([lng, lat]) ?? cachedTerrainElev)\n : cachedTerrainElev\n const altitude = terrainAltitude + fileElevation\n\n const fileScale = (isEditing && tempScalesRef?.current[modelFileKey] !== undefined)\n ? tempScalesRef.current[modelFileKey]\n : (modelFile.scale ?? 1)\n\n _m.fromArray(args.defaultProjectionData.mainMatrix)\n writeModelMatrix(_l, modelOrigin, altitude).scale(_scaleVec.setScalar(fileScale))\n this.camera.projectionMatrix.multiplyMatrices(_m, _l)\n\n if (this.mixer) {\n this.mixer.update((this.clock as THREE.Clock).getDelta())\n }\n\n this.renderer.resetState()\n this.renderer.render(this.scene, this.camera)\n\n // Render-on-demand: keep the frame loop alive only while an animation is\n // playing, the camera recently moved (settle window), or this model is\n // being edited. Idle static model ⇒ no self-scheduled repaints ⇒ no freeze.\n if (animation?.playing || isEditing || performance.now() - lastMoveTime < SETTLE_MS) {\n map.triggerRepaint()\n }\n },\n\n onRemove() {\n disposed = true\n if (onMapMove) map.off('move', onMapMove)\n if (onMapMoveEnd) map.off('moveend', onMapMoveEnd)\n // Stop + release the animation mixer so it isn't left running/holding the\n // scene after removal.\n if (this.mixer) {\n ;(this.mixer as THREE.AnimationMixer).stopAllAction()\n this.mixer = null\n }\n mixerRef = null\n clips = []\n animation = null\n if (this.scene) disposeThreeScene(this.scene as THREE.Scene)\n cameraRef = null\n sceneRef = null\n this.renderer = null\n this.camera = null\n this.scene = null\n },\n }\n }\n\n const hitTest = (ndcX: number, ndcY: number): boolean => hitTestLayerScene(cameraRef, sceneRef, ndcX, ndcY)\n\n customLayer = createCustomLayer()\n\n if (!map.getLayer(customLayer.id)) {\n map.addLayer(customLayer)\n }\n\n const removeLayer = () => {\n if (customLayer && map.getLayer(customLayer.id)) {\n map.removeLayer(customLayer.id)\n }\n }\n\n const cleanup = () => {\n removeLayer()\n components = null\n customLayer = null\n }\n\n const commit = (next: AnimationState | null) => {\n if (!next || !mixerRef) return\n animation = next\n applyAnimationTo(mixerRef, clips, next)\n map.triggerRepaint()\n }\n\n const controls: ModelAnimationControls = {\n getClips: () => clips.map((clip, index) => clip.name || `Clip ${index + 1}`),\n getAnimation: () => animation,\n setClip: clipIndex => commit(animation && withClip(animation, clipIndex, clips.length)),\n setPlaying: playing => commit(animation && withPlaying(animation, playing)),\n setSpeed: speed => commit(animation && withSpeed(animation, speed)),\n }\n\n return { cleanup, remove: removeLayer, hitTest, animation: controls }\n}\n"],"mappings":"AAIA,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAE3B,SAAS,kBAAkB,cAAc,UAAU,aAAa,iBAAiB;AACjF,SAAS,yBAAyB;AAClC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAWlC,SAAS,wBAAwB,MAA4C;AAC3E,MAAI,OAAO,KAAK,QAAQ,YAAY,OAAO,KAAK,QAAQ,UAAU;AAChE,WAAO,EAAE,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI;AAAA,EACxC;AAEA,QAAM,cAAc,KAAK;AACzB,MAAI,eAAe,OAAO,gBAAgB,UAAU;AAClD,UAAM,MAAM;AACZ,QAAI,OAAO,IAAI,QAAQ,YAAY,OAAO,IAAI,QAAQ,UAAU;AAC9D,aAAO,EAAE,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI;AAAA,IACtC;AAAA,EACF;AAEA,MAAI,OAAO,gBAAgB,UAAU;AACnC,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,WAAW;AACrC,UAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,QAAQ,UAAU;AACpE,eAAO,EAAE,KAAK,OAAO,KAAK,KAAK,OAAO,IAAI;AAAA,MAC5C;AAAA,IACF,SACM;AAAA,IAEN;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,GAAG,KAAK,EAAE;AAC1B;AAkBO,MAAM,mBAAmB,CAC9B,WACA,KACA,UACA,kBACA,kBACA,kBACA,mBACA,kBACqB;AACrB,MAAI,aAAa;AACjB,MAAI,cAA2C;AAC/C,MAAI,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C/C,UAAI,YAAY,YAAY,EAAE;AAAA,IAChC;AAAA,EACF;AAEA,QAAM,UAAU,MAAM;AACpB,gBAAY;AACZ,iBAAa;AACb,kBAAc;AAAA,EAChB;AAEA,QAAM,SAAS,CAAC,SAAgC;AAC9C,QAAI,CAAC,QAAQ,CAAC,SAAU;AACxB,gBAAY;AACZ,qBAAiB,UAAU,OAAO,IAAI;AACtC,QAAI,eAAe;AAAA,EACrB;AAEA,QAAM,WAAmC;AAAA,IACvC,UAAU,MAAM,MAAM,IAAI,CAAC,MAAM,UAAU,KAAK,QAAQ,QAAQ,QAAQ,CAAC,EAAE;AAAA,IAC3E,cAAc,MAAM;AAAA,IACpB,SAAS,eAAa,OAAO,aAAa,SAAS,WAAW,WAAW,MAAM,MAAM,CAAC;AAAA,IACtF,YAAY,aAAW,OAAO,aAAa,YAAY,WAAW,OAAO,CAAC;AAAA,IAC1E,UAAU,WAAS,OAAO,aAAa,UAAU,WAAW,KAAK,CAAC;AAAA,EACpE;AAEA,SAAO,EAAE,SAAS,QAAQ,aAAa,SAAS,WAAW,SAAS;AACtE;","names":["map","_a"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/FileLayer/utils/CustomModelLayer.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (C) 2025 Collab Digital Twins\n\nimport { type CustomLayerInterface, type LngLatLike, type Map } from 'maplibre-gl'\nimport * as THREE from 'three'\nimport { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'\n\nimport { applyAnimationTo, initialState, withClip, withPlaying, withSpeed } from '../../../../../../shared/placement/modelAnimation'\nimport { hitTestLayerScene } from '../../../../../utils/layerRaycast'\nimport { writeModelMatrix } from '../../../../../utils/modelMatrix'\nimport { disposeThreeScene } from '../../disposeThreeScene'\n\nimport type { DbFile } from '../../../../../../../../types/dbTypes'\nimport type { AnimationState } from '../../../../../../shared/placement/modelAnimation'\n\ntype TempPositionsRef = React.MutableRefObject<Record<string, { lat: number; lng: number }>>\ntype TempRotationsRef = React.MutableRefObject<Record<string, number>>\ntype TempElevationsRef = React.MutableRefObject<Record<string, number>>\ntype TempScalesRef = React.MutableRefObject<Record<string, number>>\ntype EditingFileIdRef = React.MutableRefObject<string | null>\n\nfunction resolveModelCoordinates(file: DbFile): { lng: number, lat: number } {\n if (typeof file.lng === 'number' && typeof file.lat === 'number') {\n return { lng: file.lng, lat: file.lat }\n }\n\n const rawPosition = file.position as unknown\n if (rawPosition && typeof rawPosition === 'object') {\n const pos = rawPosition as { lng?: number, lat?: number }\n if (typeof pos.lng === 'number' && typeof pos.lat === 'number') {\n return { lng: pos.lng, lat: pos.lat }\n }\n }\n\n if (typeof rawPosition === 'string') {\n try {\n const parsed = JSON.parse(rawPosition) as { lng?: number, lat?: number }\n if (typeof parsed.lng === 'number' && typeof parsed.lat === 'number') {\n return { lng: parsed.lng, lat: parsed.lat }\n }\n }\n catch {\n // Ignore malformed legacy position payloads.\n }\n }\n\n return { lng: 0, lat: 0 }\n}\n\n/** Playback for a loaded model's clips, so the map's animation card drives the same state the BIM one does. */\nexport interface ModelAnimationControls {\n getClips(): string[]\n getAnimation(): AnimationState | null\n setClip(clipIndex: number): void\n setPlaying(playing: boolean): void\n setSpeed(speed: number): void\n}\n\nexport interface ModelLayerHandle {\n cleanup: () => void\n remove: () => void\n hitTest: (ndcX: number, ndcY: number) => boolean\n animation: ModelAnimationControls\n}\n\nexport const CustomModelLayer = (\n modelFile: DbFile,\n map: Map,\n renderer: THREE.WebGLRenderer,\n tempPositionsRef?: TempPositionsRef,\n editingFileIdRef?: EditingFileIdRef,\n tempRotationsRef?: TempRotationsRef,\n tempElevationsRef?: TempElevationsRef,\n tempScalesRef?: TempScalesRef,\n): ModelLayerHandle => {\n let components = null\n let customLayer: CustomLayerInterface | null = null\n let clips: THREE.AnimationClip[] = []\n let animation: AnimationState | null = null\n let mixerRef: THREE.AnimationMixer | null = null\n\n const noControls: ModelAnimationControls = {\n getClips: () => [],\n getAnimation: () => null,\n setClip: () => {},\n setPlaying: () => {},\n setSpeed: () => {},\n }\n\n if (!map || !modelFile) {\n return { cleanup: () => {}, remove: () => {}, hitTest: () => false, animation: noControls }\n }\n\n const modelFileKey = String(modelFile.id)\n\n // Refs into the layer's camera and scene so raycasting can read the last\n // rendered frame's transform without entering the render loop.\n let cameraRef: THREE.Camera | null = null\n let sceneRef: THREE.Scene | null = null\n\n\n const createCustomLayer = (): CustomLayerInterface => {\n // Track last applied rotation so we can apply delta increments (same as BimLayer)\n let lastAppliedRotation = modelFile.rotation ?? 0\n // Layer-removed-mid-load guard + reused per-frame matrices\n let disposed = false\n const _m = new THREE.Matrix4()\n const _l = new THREE.Matrix4()\n const _scaleVec = new THREE.Vector3()\n // Render-on-demand: cache terrain elevation off the per-frame path and only\n // keep repainting while the camera recently moved or an animation is playing,\n // so an idle map with a placed model stops re-rendering instead of pinning the\n // main thread (this was the freeze after a flyTo to high zoom).\n let cachedTerrainElev = 0\n let lastMoveTime = performance.now()\n const SETTLE_MS = 1000\n let onMapMove: (() => void) | undefined\n let onMapMoveEnd: (() => void) | undefined\n const recomputeTerrainElev = () => {\n const { lng, lat } = resolveModelCoordinates(modelFile)\n if (!(lng === 0 && lat === 0)) {\n const e = map.queryTerrainElevation([lng, lat])\n if (e !== null && e !== undefined) cachedTerrainElev = e\n }\n }\n\n return {\n id: `model-${modelFile.id}`,\n type: 'custom',\n renderingMode: '3d',\n onAdd(map, gl) {\n this.camera = new THREE.Camera()\n this.scene = new THREE.Scene()\n this.renderer = renderer\n\n // Expose to closure for raycasting\n cameraRef = this.camera as THREE.Camera\n sceneRef = this.scene as THREE.Scene\n\n const scene = this.scene as THREE.Scene\n\n // Apply initial rotation\n if (lastAppliedRotation !== 0) {\n scene.rotateY(lastAppliedRotation * (Math.PI / 180))\n }\n\n // Lighting to match OBC library setup\n scene.background = null\n scene.fog = new THREE.Fog(0x20_29_32, 10, 200)\n scene.add(new THREE.AmbientLight(0xFF_FF_FF, 1))\n scene.add(new THREE.HemisphereLight(0xFF_FF_BB, 0x08_08_20, 0.5))\n\n const sun = new THREE.DirectionalLight(0xFF_FF_FF, 1.5)\n sun.position.set(0, -70, 100).normalize()\n sun.castShadow = true\n sun.shadow.mapSize.set(2048, 2048)\n scene.add(sun)\n\n const fill = new THREE.DirectionalLight(0xFF_FF_FF, 1)\n fill.position.set(0, 70, 100).normalize()\n scene.add(fill)\n\n this.renderer.toneMapping = THREE.ACESFilmicToneMapping\n this.renderer.autoClear = false\n this.clock = new THREE.Clock()\n\n const loader = new GLTFLoader()\n loader.load(\n modelFile.url!,\n (gltf) => {\n // Layer was removed before the async load resolved — don't attach to a\n // dead scene; let the gltf be GC'd (no GPU upload happened yet).\n if (disposed) return\n gltf.scene.scale.setScalar(1)\n\n clips = gltf.animations ?? []\n animation = initialState(clips.length)\n if (animation) {\n this.mixer = new THREE.AnimationMixer(gltf.scene)\n mixerRef = this.mixer\n applyAnimationTo(this.mixer, clips, animation)\n }\n\n scene.add(gltf.scene)\n // Open the settle window so the just-loaded model paints, then idle.\n lastMoveTime = performance.now()\n recomputeTerrainElev()\n map.triggerRepaint()\n },\n undefined,\n (error) => { console.error('Error loading model:', error) },\n )\n\n // Track camera movement for render-on-demand: keep repainting only\n // during/just-after movement; refresh cached terrain elevation on settle.\n onMapMove = () => { lastMoveTime = performance.now() }\n onMapMoveEnd = () => {\n lastMoveTime = performance.now()\n recomputeTerrainElev()\n map.triggerRepaint()\n }\n map.on('move', onMapMove)\n map.on('moveend', onMapMoveEnd)\n },\n\n render(gl, args) {\n if (map.getZoom() < 15.5) return\n\n const isEditing = editingFileIdRef?.current === modelFileKey\n\n // ── Position ──────────────────────────────────────────────────────────\n let lng: number\n let lat: number\n if (isEditing && tempPositionsRef?.current[modelFileKey]) {\n const tp = tempPositionsRef.current[modelFileKey]\n lng = tp.lng\n lat = tp.lat\n } else {\n const coords = resolveModelCoordinates(modelFile)\n lng = coords.lng\n lat = coords.lat\n }\n\n if (lng === 0 && lat === 0) return\n\n // ── Rotation (delta-increment, same pattern as BimLayer) ──────────────\n const targetRotation = (isEditing && tempRotationsRef?.current[modelFileKey] !== undefined)\n ? tempRotationsRef.current[modelFileKey]\n : (modelFile.rotation ?? 0)\n\n if (targetRotation !== lastAppliedRotation) {\n ;(this.scene as THREE.Scene).rotateY(\n (targetRotation - lastAppliedRotation) * (Math.PI / 180)\n )\n lastAppliedRotation = targetRotation\n }\n\n // ── Elevation ─────────────────────────────────────────────────────────\n const fileElevation = (isEditing && tempElevationsRef?.current[modelFileKey] !== undefined)\n ? tempElevationsRef.current[modelFileKey]\n : (modelFile.elevation ?? 0)\n\n const modelOrigin = [lng, lat] as LngLatLike\n // Cached terrain elevation (refreshed on moveend); query live only while\n // editing this model's position. Keeps queryTerrainElevation off the hot\n // path — the per-frame query drove the high-zoom freeze.\n const terrainAltitude = isEditing\n ? (map.queryTerrainElevation([lng, lat]) ?? cachedTerrainElev)\n : cachedTerrainElev\n const altitude = terrainAltitude + fileElevation\n\n const fileScale = (isEditing && tempScalesRef?.current[modelFileKey] !== undefined)\n ? tempScalesRef.current[modelFileKey]\n : (modelFile.fileScale ?? 1)\n\n _m.fromArray(args.defaultProjectionData.mainMatrix)\n writeModelMatrix(_l, modelOrigin, altitude).scale(_scaleVec.setScalar(fileScale))\n this.camera.projectionMatrix.multiplyMatrices(_m, _l)\n\n if (this.mixer) {\n this.mixer.update((this.clock as THREE.Clock).getDelta())\n }\n\n this.renderer.resetState()\n this.renderer.render(this.scene, this.camera)\n\n // Render-on-demand: keep the frame loop alive only while an animation is\n // playing, the camera recently moved (settle window), or this model is\n // being edited. Idle static model ⇒ no self-scheduled repaints ⇒ no freeze.\n if (animation?.playing || isEditing || performance.now() - lastMoveTime < SETTLE_MS) {\n map.triggerRepaint()\n }\n },\n\n onRemove() {\n disposed = true\n if (onMapMove) map.off('move', onMapMove)\n if (onMapMoveEnd) map.off('moveend', onMapMoveEnd)\n // Stop + release the animation mixer so it isn't left running/holding the\n // scene after removal.\n if (this.mixer) {\n ;(this.mixer as THREE.AnimationMixer).stopAllAction()\n this.mixer = null\n }\n mixerRef = null\n clips = []\n animation = null\n if (this.scene) disposeThreeScene(this.scene as THREE.Scene)\n cameraRef = null\n sceneRef = null\n this.renderer = null\n this.camera = null\n this.scene = null\n },\n }\n }\n\n const hitTest = (ndcX: number, ndcY: number): boolean => hitTestLayerScene(cameraRef, sceneRef, ndcX, ndcY)\n\n customLayer = createCustomLayer()\n\n if (!map.getLayer(customLayer.id)) {\n map.addLayer(customLayer)\n }\n\n const removeLayer = () => {\n if (customLayer && map.getLayer(customLayer.id)) {\n map.removeLayer(customLayer.id)\n }\n }\n\n const cleanup = () => {\n removeLayer()\n components = null\n customLayer = null\n }\n\n const commit = (next: AnimationState | null) => {\n if (!next || !mixerRef) return\n animation = next\n applyAnimationTo(mixerRef, clips, next)\n map.triggerRepaint()\n }\n\n const controls: ModelAnimationControls = {\n getClips: () => clips.map((clip, index) => clip.name || `Clip ${index + 1}`),\n getAnimation: () => animation,\n setClip: clipIndex => commit(animation && withClip(animation, clipIndex, clips.length)),\n setPlaying: playing => commit(animation && withPlaying(animation, playing)),\n setSpeed: speed => commit(animation && withSpeed(animation, speed)),\n }\n\n return { cleanup, remove: removeLayer, hitTest, animation: controls }\n}\n"],"mappings":"AAIA,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAE3B,SAAS,kBAAkB,cAAc,UAAU,aAAa,iBAAiB;AACjF,SAAS,yBAAyB;AAClC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAWlC,SAAS,wBAAwB,MAA4C;AAC3E,MAAI,OAAO,KAAK,QAAQ,YAAY,OAAO,KAAK,QAAQ,UAAU;AAChE,WAAO,EAAE,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI;AAAA,EACxC;AAEA,QAAM,cAAc,KAAK;AACzB,MAAI,eAAe,OAAO,gBAAgB,UAAU;AAClD,UAAM,MAAM;AACZ,QAAI,OAAO,IAAI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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/index.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../../../../src/core/components/viewers/map/src/MapLayers/src/OpenDataLayer/src/index.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAkc/B,eAAO,MAAM,cAAc,yBA8K1B,CAAC"}
|