61 lines
2.2 KiB
TypeScript
61 lines
2.2 KiB
TypeScript
import { useState } from 'react'
|
|
import type { DatasetCreateResponse, VectorSelectionBBox } from '../types'
|
|
import { formatError } from '../lib/formatError'
|
|
import { datasetsApi } from '../services/api'
|
|
|
|
interface UseMapSelectionDatasetOptions {
|
|
selectedProjectId: string | null
|
|
selectedDataset: DatasetCreateResponse | null
|
|
isVectorDatasetType: (datasetType: string) => boolean
|
|
loadProjectData: (projectId: string) => Promise<unknown>
|
|
loadDatasetDetails: (projectId: string, dataset: DatasetCreateResponse) => Promise<void>
|
|
setMapLayerVisible: (visible: boolean) => void
|
|
}
|
|
|
|
export function useMapSelectionDataset({
|
|
selectedProjectId,
|
|
selectedDataset,
|
|
isVectorDatasetType,
|
|
loadProjectData,
|
|
loadDatasetDetails,
|
|
setMapLayerVisible,
|
|
}: UseMapSelectionDatasetOptions) {
|
|
const [selectionDatasetSaving, setSelectionDatasetSaving] = useState(false)
|
|
const [selectionDatasetError, setSelectionDatasetError] = useState<string | null>(null)
|
|
const [latestSelectionDataset, setLatestSelectionDataset] = useState<DatasetCreateResponse | null>(null)
|
|
|
|
const deriveMapSelectionDataset = async (bbox: VectorSelectionBBox, areaId?: string) => {
|
|
if (!selectedProjectId || !selectedDataset || !isVectorDatasetType(selectedDataset.dataset_type)) {
|
|
setSelectionDatasetError('Select a vector dataset before saving the area as a dataset.')
|
|
return null
|
|
}
|
|
setSelectionDatasetSaving(true)
|
|
setSelectionDatasetError(null)
|
|
try {
|
|
const derived = await datasetsApi.deriveVectorSelection(selectedProjectId, selectedDataset.id, {
|
|
bbox: { ...bbox, crs: 'EPSG:4326' },
|
|
area_id: areaId,
|
|
limit: 250,
|
|
output_name: `${selectedDataset.name.replace(/\.(geo)?json$/i, '')}-selection-dataset`,
|
|
})
|
|
setLatestSelectionDataset(derived)
|
|
await loadProjectData(selectedProjectId)
|
|
await loadDatasetDetails(selectedProjectId, derived)
|
|
setMapLayerVisible(true)
|
|
return derived
|
|
} catch (error) {
|
|
setSelectionDatasetError(formatError(error, 'Failed to save area as dataset'))
|
|
return null
|
|
} finally {
|
|
setSelectionDatasetSaving(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
selectionDatasetSaving,
|
|
selectionDatasetError,
|
|
latestSelectionDataset,
|
|
deriveMapSelectionDataset,
|
|
}
|
|
}
|