From ddca4d8478d159118d2bfb4f564dce741d51afea Mon Sep 17 00:00:00 2001 From: kshitijrajsharma Date: Thu, 8 Oct 2026 09:21:42 +0200 Subject: [PATCH 01/45] fix(search): add description to the search endpoint on predictions --- backend/predictions/views.py | 6 ++-- backend/tests/test_prediction_search.py | 47 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 backend/tests/test_prediction_search.py diff --git a/backend/predictions/views.py b/backend/predictions/views.py index fdf304f3c..2d9026ffe 100644 --- a/backend/predictions/views.py +++ b/backend/predictions/views.py @@ -87,8 +87,9 @@ class PredictionViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PredictionSerializer authentication_classes = [OsmAuthentication] permission_classes = [PublishedReadOrAuthenticatedWrite, IsOwnerOrAdminOrReadOnly] - filter_backends = [DjangoFilterBackend, filters.OrderingFilter] + filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ["local_model_stac_id", "user", "status", "visibility"] + search_fields = ["description"] ordering_fields = ["submitted_at", "last_polled_at"] throttle_scope = "prediction_submit" @@ -351,6 +352,7 @@ class PublicPredictionViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PredictionSerializer authentication_classes: list = [] permission_classes = [AllowAny] - filter_backends = [DjangoFilterBackend, filters.OrderingFilter] + filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ["local_model_stac_id"] + search_fields = ["description"] ordering_fields = ["submitted_at"] diff --git a/backend/tests/test_prediction_search.py b/backend/tests/test_prediction_search.py new file mode 100644 index 000000000..272516638 --- /dev/null +++ b/backend/tests/test_prediction_search.py @@ -0,0 +1,47 @@ +import pytest +from rest_framework.test import APIClient + +from accounts.models import OsmUser +from predictions.models import Prediction +from shared.enums import Visibility + +_SQUARE = {"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]} + + +@pytest.fixture +def owner(db) -> OsmUser: + return OsmUser.objects.create(osm_id=51, username="gita") + + +def _prediction(owner: OsmUser, description: str, visibility: str = Visibility.PRIVATE) -> Prediction: + return Prediction.objects.create( + local_model_stac_id="dinov3s-buildings", + image_uri="https://tile.example.com/{z}/{x}/{y}.png", + geometry=_SQUARE, + zoom=19, + user=owner, + description=description, + visibility=visibility, + ) + + +def test_prediction_search_matches_description_and_hides_others_private_rows(owner: OsmUser) -> None: + _prediction(owner, "Banepa buildings after the flood") + _prediction(owner, "Kathmandu solid waste") + _prediction(OsmUser.objects.create(osm_id=52, username="hari"), "Banepa private survey") + client = APIClient() + client.force_authenticate(user=owner) + + response = client.get("/api/v1/predictions/?search=BANEPA") + + assert [row["description"] for row in response.json()["results"]] == ["Banepa buildings after the flood"] + + +def test_public_prediction_search_only_returns_public_rows(owner: OsmUser) -> None: + _prediction(owner, "Banepa buildings", visibility=Visibility.PUBLIC) + _prediction(owner, "Kathmandu solid waste", visibility=Visibility.PUBLIC) + _prediction(owner, "Private waste audit") + + response = APIClient().get("/api/v1/public-predictions/?search=waste") + + assert [row["description"] for row in response.json()["results"]] == ["Kathmandu solid waste"] From 955f5e474c17c72863d488e9ef77343b1e70d5db Mon Sep 17 00:00:00 2001 From: shittu adewale Date: Thu, 8 Oct 2026 09:28:44 +0100 Subject: [PATCH 02/45] feat: add category mapping and tooltips for advanced settings, and cache GeoJSON results using React Query --- .../src/app/routes/map-request-result.tsx | 11 +--- frontend/src/app/routes/try-fair.tsx | 1 - .../layouts/navbar/device-navbars.tsx | 7 +-- .../src/components/layouts/navbar/navbar.tsx | 4 +- .../ui-contents/try-fair-contents.ts | 1 + .../components/advanced-settings-panel.tsx | 7 ++- .../try-fair/components/try-fair-sidebar.tsx | 4 +- .../map-requests/map-request-result-map.tsx | 61 ++++++++----------- .../overview/map-requests-table.tsx | 18 ++++-- .../user-profile/hooks/use-predictions.ts | 9 +++ frontend/src/types/api.ts | 1 + frontend/src/types/ui-contents.ts | 1 + 12 files changed, 66 insertions(+), 59 deletions(-) diff --git a/frontend/src/app/routes/map-request-result.tsx b/frontend/src/app/routes/map-request-result.tsx index 40df41e5f..219a0f3d1 100644 --- a/frontend/src/app/routes/map-request-result.tsx +++ b/frontend/src/app/routes/map-request-result.tsx @@ -27,12 +27,7 @@ const getPredictionName = (prediction: TOfflinePrediction): string => prediction.local_model_stac_id || `Prediction #${prediction.id}`; -/** Best-effort feature label derived from the model id (e.g. "…-buildings"). */ -const getFeatureMapped = (prediction: TOfflinePrediction): string => { - const slug = prediction.local_model_stac_id ?? ""; - const last = slug.split("-").pop() ?? ""; - return last ? last.charAt(0).toUpperCase() + last.slice(1) : "—"; -}; + /** Info card shown over the map — styled like the Try fAIr sidebar. */ const ResultInfoCard = ({ @@ -205,7 +200,7 @@ export const MapRequestResultPage = () => {
@@ -224,7 +219,7 @@ export const MapRequestResultPage = () => { > { selectedModel, selectedModelId, }); - const predictionClassStyle = useMemo( () => getPredictionClassStyle(modelForMapping), [modelForMapping], diff --git a/frontend/src/components/layouts/navbar/device-navbars.tsx b/frontend/src/components/layouts/navbar/device-navbars.tsx index b89dc11c0..8d1ce1d26 100644 --- a/frontend/src/components/layouts/navbar/device-navbars.tsx +++ b/frontend/src/components/layouts/navbar/device-navbars.tsx @@ -6,7 +6,7 @@ import { UserProfile } from "@/components/layouts/navbar/user-profile"; import { AUTH_PROVIDER, IS_DEV } from "@/config"; import { APP_TOUR_IDS } from "@/constants/site-tour"; import { StartMappingNavlinks } from "@/features/try-fair/components/try-fair-nav-links"; -import { UserNotifications } from "@/features/user-profile/components/notifications/user-notifications"; +// import { UserNotifications } from "@/features/user-profile/components/notifications/user-notifications"; import { DownloadResultButton } from "@/features/user-profile/components/map-requests/download-result-button"; import { APPLICATION_ROUTES } from "@/constants"; import { useLocation } from "react-router-dom"; @@ -87,7 +87,6 @@ export const DesktopAuthSection = ({ }: AuthSectionProps) => { const { pathname } = useLocation(); const { - isMapRequests: isMapRequestsPage, showDownloadResult, showDashboardLink, } = useNavbarState(); @@ -105,7 +104,7 @@ export const DesktopAuthSection = ({ if (showHankoBar) { return ( <> - {isAuthenticated && } + {/* {isAuthenticated && } */} {dashboardButton} {showDownloadResult && }
{isTryFairPage && } - {!isTryFairPage && !isMapRequestsPage && } + {/* {!isTryFairPage && !isMapRequestsPage && } */} {dashboardButton} {showDownloadResult && } diff --git a/frontend/src/components/layouts/navbar/navbar.tsx b/frontend/src/components/layouts/navbar/navbar.tsx index bb1238c94..5b4658543 100644 --- a/frontend/src/components/layouts/navbar/navbar.tsx +++ b/frontend/src/components/layouts/navbar/navbar.tsx @@ -9,7 +9,7 @@ import { APPLICATION_ROUTES, SHARED_CONTENT } from "@/constants"; import { useAuth } from "@/app/providers/auth-provider"; import { useLocation, useNavigate } from "react-router-dom"; import { useState } from "react"; -import { UserNotifications } from "@/features/user-profile/components/notifications/user-notifications"; +// import { UserNotifications } from "@/features/user-profile/components/notifications/user-notifications"; import { AUTH_PROVIDER, FRONTEND_URL } from "@/config"; import "@hotosm/ui/dist/components/tool-menu/tool-menu.js"; import { Divider } from "@/components/ui/divider"; @@ -119,7 +119,7 @@ export const NavBar = () => {
{showDashboardLink && } - {isAuthenticated && } + {/* {isAuthenticated && } */} {showDownloadResult && }
- {!isTryFairPage && ( + {!isTryFairPage && !isMapRequestResult &&(
{
- {!isTryFairPage && !isProfilePage && ( + {!isTryFairPage && !isProfilePage && !isMapRequestResult && ( )}
diff --git a/frontend/src/features/try-fair/components/imagery/__tests__/choose-imagery-source.test.tsx b/frontend/src/features/try-fair/components/imagery/__tests__/choose-imagery-source.test.tsx index 19e766ea7..e2354fdb9 100644 --- a/frontend/src/features/try-fair/components/imagery/__tests__/choose-imagery-source.test.tsx +++ b/frontend/src/features/try-fair/components/imagery/__tests__/choose-imagery-source.test.tsx @@ -64,4 +64,17 @@ describe("ImagerySourceToggle", () => { expect(handleChange).toHaveBeenCalledWith(ImagerySource.CUSTOM); }); + + it("should hide Custom Imagery when it is not enabled for the mapping mode", () => { + render( + , + ); + + expect(screen.queryByText("Custom Imagery")).not.toBeInTheDocument(); + expect(screen.getAllByRole("radio")).toHaveLength(1); + }); }); diff --git a/frontend/src/features/try-fair/components/imagery/__tests__/imagery-location-modal.test.tsx b/frontend/src/features/try-fair/components/imagery/__tests__/imagery-location-modal.test.tsx index d94f007ff..47b2cd82d 100644 --- a/frontend/src/features/try-fair/components/imagery/__tests__/imagery-location-modal.test.tsx +++ b/frontend/src/features/try-fair/components/imagery/__tests__/imagery-location-modal.test.tsx @@ -146,6 +146,19 @@ describe.each([false, true])( expect(screen.getByText("XYZ Tile Server URL")).toBeInTheDocument(); }); + it("should hide Custom Imagery when it is unavailable in Basic mode", () => { + render( + , + ); + + expect(screen.queryByText("Custom Imagery")).not.toBeInTheDocument(); + }); + it("should return to the model picker when opened from it", () => { const onBackToModelPicker = vi.fn(); diff --git a/frontend/src/features/try-fair/components/imagery/choose-imagery-source.tsx b/frontend/src/features/try-fair/components/imagery/choose-imagery-source.tsx index 26663aad2..5344f987d 100644 --- a/frontend/src/features/try-fair/components/imagery/choose-imagery-source.tsx +++ b/frontend/src/features/try-fair/components/imagery/choose-imagery-source.tsx @@ -8,10 +8,12 @@ import { IMAGERY_SOURCES } from "@/features/try-fair/utils/common"; */ export const ImagerySourceToggle = ({ expanded = false, + isCustomImageryEnabled = true, value, onChange, }: { expanded?: boolean; + isCustomImageryEnabled?: boolean; value: ImagerySource; onChange: (source: ImagerySource) => void; }) => ( @@ -24,7 +26,10 @@ export const ImagerySourceToggle = ({ : "flex items-center max-w-[500px] w-full mx-auto md:flex-row flex-col justify-center gap-3" } > - {IMAGERY_SOURCES.map((source) => { + {IMAGERY_SOURCES.filter( + (source) => + source.value !== ImagerySource.CUSTOM || isCustomImageryEnabled, + ).map((source) => { const isSelected = value === source.value; return (
); @@ -170,10 +204,10 @@ export const MapRequestResultPage = () => { prediction.bbox ?? (prediction.geometry ? getGeoJSONFeatureBounds({ - type: "Feature", - geometry: prediction.geometry, - properties: {}, - }) + type: "Feature", + geometry: prediction.geometry, + properties: {}, + }) : null); return ( @@ -203,6 +237,9 @@ export const MapRequestResultPage = () => { featureMapped={prediction?.category ?? '-'} outputType={outputType} onOutputTypeChange={setOutputType} + zoom={prediction.zoom} + params={prediction.params} + className="max-h-[calc(92vh-2rem)] overflow-y-auto" /> )} @@ -222,6 +259,8 @@ export const MapRequestResultPage = () => { featureMapped={prediction?.category ?? ''} outputType={outputType} onOutputTypeChange={setOutputType} + zoom={prediction.zoom} + params={prediction.params} className="w-full shadow-none" /> diff --git a/frontend/src/features/try-fair/api/user-state.ts b/frontend/src/features/try-fair/api/user-state.ts new file mode 100644 index 000000000..39885f4a3 --- /dev/null +++ b/frontend/src/features/try-fair/api/user-state.ts @@ -0,0 +1,41 @@ +import { API_ENDPOINTS, apiClient } from "@/services"; +import type { BBOX } from "@/types"; +import { useMutation } from "@tanstack/react-query"; + +export type UserState = { + state: { + type: string; + prediction_id: number; + name: string; + model: { + id: string; + title: string; + }; + imagery: { + name: string; + url: string; + }; + zoom: number; + bbox: BBOX; + }; +}; + +export type SavedUserState = UserState & { + pid: number; + timestamp: string; +}; + +const saveUserState = async (payload: UserState): Promise => { + const res = await apiClient.post( + API_ENDPOINTS.SAVE_USER_STATE, + payload, + ); + return res.data; +}; + +export const useSaveUserState = () => { + return useMutation({ + mutationFn: saveUserState, + mutationKey: ["user-state"], + }); +}; diff --git a/frontend/src/features/user-profile/api/user-state.ts b/frontend/src/features/user-profile/api/user-state.ts new file mode 100644 index 000000000..08e375741 --- /dev/null +++ b/frontend/src/features/user-profile/api/user-state.ts @@ -0,0 +1,26 @@ +import { UserState } from "@/features/try-fair/api/user-state"; +import { API_ENDPOINTS, apiClient } from "@/services"; +import { useQuery } from "@tanstack/react-query"; + + +export type SavedUserState = UserState & { + "count": number; + "next": number | null; + "previous": number | null; + "results": UserState[]; +}; + +const getUserState = async (): Promise => { + const res = await apiClient.get( + API_ENDPOINTS.SAVE_USER_STATE, + + ); + return res.data; +}; + +export const useGetUserStates = () => { + return useQuery({ + queryFn: getUserState, + queryKey: ["user-state"], + }); +}; diff --git a/frontend/src/features/user-profile/components/overview/recent-activities.tsx b/frontend/src/features/user-profile/components/overview/recent-activities.tsx index 1ca2f11fe..621415e28 100644 --- a/frontend/src/features/user-profile/components/overview/recent-activities.tsx +++ b/frontend/src/features/user-profile/components/overview/recent-activities.tsx @@ -1,6 +1,7 @@ import { ChevronDownIcon } from "@/components/ui/icons"; import { cn } from "@/utils"; import { OverviewEmptyState } from "./overview-empty-state"; +import { useGetUserStates } from "@/features/user-profile/api/user-state"; export const RecentActivities = ({ showFilter = false, @@ -10,6 +11,8 @@ export const RecentActivities = ({ showFilter?: boolean; className?: string; }) => { + const { data } = useGetUserStates() + console.log(data) return (
)} +
+ {data?.results?.map((item) => ( +
+

{item.state.name}

+

{item.state.type}

- + +
+ ))} +
+ + {/* */}
); }; diff --git a/frontend/src/services/api-routes.ts b/frontend/src/services/api-routes.ts index 95aa3fffe..4aa9369ad 100644 --- a/frontend/src/services/api-routes.ts +++ b/frontend/src/services/api-routes.ts @@ -142,5 +142,9 @@ export const API_ENDPOINTS = { // Map large area MAP_LARGE_AREA_REQUEST: "/predictions/submit/", + SAVE_USER_STATE: "/user-state/", + GET_USER_STATE: "/user-state/", + EDIT_USER_STATE: (pid: number) => `/user-state/${pid}/`, + // Base }; From be478baffdd211abf7d4529958ee305122bcaa8a Mon Sep 17 00:00:00 2001 From: shittu adewale Date: Fri, 9 Oct 2026 19:12:58 +0100 Subject: [PATCH 05/45] feat: enhance project sharing and autosave functionality --- frontend/src/app/router.tsx | 14 ++ .../app/routes/__tests__/projects.test.tsx | 97 +++++++++++ frontend/src/app/routes/try-fair.tsx | 114 +++++++++++-- .../app/routes/try-fair/try-fair-projects.tsx | 71 ++++++++ .../layouts/navbar/hooks/use-navbar-state.tsx | 3 +- frontend/src/constants/routes.ts | 1 + .../components/skeletons/table-skeleton.tsx | 9 +- .../src/features/try-fair/api/user-state.ts | 55 ++++++- .../mapping-project-autosave.test.tsx | 152 ++++++++++++++++++ .../components/mapping-project-autosave.tsx | 55 +++++++ .../__tests__/share-project-modal.test.tsx | 55 +++++++ .../components/modals/share-project-modal.tsx | 17 +- .../components/model-picker-modal.tsx | 10 +- .../__tests__/recent-imageries.test.tsx | 44 ++++- .../hooks/__tests__/use-fair-predict.test.tsx | 69 ++++++++ .../__tests__/use-try-fair-params.test.tsx | 16 ++ .../try-fair/hooks/use-fair-predict.tsx | 40 +++-- .../hooks/use-imagery-mapping-model.ts | 10 +- .../try-fair/hooks/use-try-fair-params.tsx | 9 ++ .../try-fair/utils/restore-project.ts | 32 ++++ .../features/user-profile/api/user-state.ts | 31 +++- .../map-requests/download-result-button.tsx | 2 +- .../components/overview/recent-activities.tsx | 98 +++++++++-- frontend/src/services/api-routes.ts | 1 + 24 files changed, 943 insertions(+), 62 deletions(-) create mode 100644 frontend/src/app/routes/__tests__/projects.test.tsx create mode 100644 frontend/src/app/routes/try-fair/try-fair-projects.tsx create mode 100644 frontend/src/features/try-fair/components/__tests__/mapping-project-autosave.test.tsx create mode 100644 frontend/src/features/try-fair/components/mapping-project-autosave.tsx create mode 100644 frontend/src/features/try-fair/components/modals/__tests__/share-project-modal.test.tsx create mode 100644 frontend/src/features/try-fair/hooks/__tests__/use-fair-predict.test.tsx create mode 100644 frontend/src/features/try-fair/utils/restore-project.ts diff --git a/frontend/src/app/router.tsx b/frontend/src/app/router.tsx index fbff62264..5f5ea53df 100644 --- a/frontend/src/app/router.tsx +++ b/frontend/src/app/router.tsx @@ -77,6 +77,20 @@ const router = createBrowserRouter([ /** * Try fAIr route ends. */ + { + path: APPLICATION_ROUTES.TRY_FAIR_PROJECT, + lazy: async () => { + const { TryFairProjectPage } = + await import("@/app/routes/try-fair/try-fair-projects"); + return { + Component: () => ( + + + + ), + }; + }, + }, /** * Map Request result (full-screen, protected) route. diff --git a/frontend/src/app/routes/__tests__/projects.test.tsx b/frontend/src/app/routes/__tests__/projects.test.tsx new file mode 100644 index 000000000..957286706 --- /dev/null +++ b/frontend/src/app/routes/__tests__/projects.test.tsx @@ -0,0 +1,97 @@ +import { cleanup, render, renderHook, screen } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { PropsWithChildren } from "react"; +import { TryFairProjectPage } from "../try-fair/try-fair-projects"; +import { useGetUserState } from "@/features/user-profile/api/user-state"; + +const get = vi.hoisted(() => vi.fn()); +vi.mock("@/services", () => ({ + apiClient: { get }, + API_ENDPOINTS: { GET_SINGLE_USER_STATE: (pid: string) => `/user-state/${pid}/` }, +})); +vi.mock("../try-fair", () => ({ + TryFairPage: () => { + const { search } = useLocation(); + return
Mapping workspace{search}
; + }, +})); +vi.mock("@/components/seo", () => ({ Head: () => null })); +vi.mock("@/components/ui/spinner", () => ({ Spinner: () => null })); + +const createWrapper = () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 } }, + }); + return ({ children }: PropsWithChildren) => ( + {children} + ); +}; + +const renderProject = () => render( + + + } /> + + , + { wrapper: createWrapper() }, +); + +describe("Saved Try fAIr project", () => { + beforeEach(() => { + get.mockReset(); + }); + afterEach(cleanup); + + it("waits for the saved state before mounting the workspace", () => { + get.mockReturnValue(new Promise(() => {})); + renderProject(); + expect(screen.getByRole("status", { name: "Loading mapping project" })).toBeInTheDocument(); + expect(screen.queryByText("Mapping workspace")).not.toBeInTheDocument(); + }); + + it("fetches by the route pid and opens the workspace on success", async () => { + get.mockResolvedValue({ data: { + pid: 42, + state: { + type: "mapping", + category: "trees", + model: { id: "tree-model", title: "Trees" }, + imagery: { name: "Survey", url: "https://example.com/tilejson.json" }, + zoom: 19, + bbox: [85.5, 27.6, 85.52, 27.63], + url_params: { + model: "tree-model", selectedModelId: "tree-model", feature: "trees", + mode: "imagery", output: "points", resolution: "mid", confidence: 0.42, + mappingMode: "advanced", imagery: "https://example.com/tilejson.json", + imageryType: "TileJSON", oamItem: null, chooseLocation: false, + }, + }, + } }); + renderProject(); + expect(await screen.findByText("Mapping workspace")).toBeInTheDocument(); + expect(get).toHaveBeenCalledWith("/user-state/42/", { + signal: expect.any(AbortSignal), + }); + const search = new URLSearchParams(screen.getByTestId("restored-search").textContent ?? ""); + expect(search.get("model")).toBe("tree-model"); + expect(search.get("feature")).toBe("trees"); + expect(search.get("imagery")).toBe("https://example.com/tilejson.json"); + expect(search.get("confidence")).toBe("0.42"); + expect(search.get("mappingMode")).toBe("advanced"); + }); + + it("shows an error instead of the workspace when fetching fails", async () => { + get.mockRejectedValue(new Error("Not found")); + renderProject(); + expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load this mapping project"); + expect(screen.queryByText("Mapping workspace")).not.toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Start a new mapping project" })).toHaveAttribute("href", "/try-fair"); + }); + + it("does not fetch a saved state without a pid", () => { + renderHook(() => useGetUserState(), { wrapper: createWrapper() }); + expect(get).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/routes/try-fair.tsx b/frontend/src/app/routes/try-fair.tsx index e24e5f93a..e8d5e504a 100644 --- a/frontend/src/app/routes/try-fair.tsx +++ b/frontend/src/app/routes/try-fair.tsx @@ -45,11 +45,20 @@ import { useRecentImageries } from "@/features/try-fair/hooks/use-recent-imageri import type { RecentImageryEntry } from "@/features/try-fair/hooks/use-recent-imageries"; import { getPredictionClassStyle } from "@/features/try-fair/utils/prediction-classes"; import { useAuth } from "@/app/providers/auth-provider"; +import { useParams } from "react-router-dom"; +import { MappingProjectAutosave } from "@/features/try-fair/components/mapping-project-autosave"; +import type { SavedUserState } from "@/features/try-fair/api/user-state"; -export const TryFairPage = () => { - const { map, mapContainerRef } = useMapInstance(false, false); +export const TryFairPage = ({ initialProject }: { initialProject?: SavedUserState }) => { + const { map, mapContainerRef } = useMapInstance( + false, false, "default", undefined, initialProject?.state.bbox, + ); const { isSmallViewport } = useScreenSize(); - const { isAuthenticated } = useAuth(); + const { isAuthenticated, user } = useAuth(); + const { pid: projectId } = useParams(); + const [hasSuccessfulPrediction, setHasSuccessfulPrediction] = useState( + initialProject?.state.type === "mapping", + ); const { showSigninModal, @@ -76,6 +85,7 @@ export const TryFairPage = () => { useTryFairTour(isSmallViewport); const { + urlState, modelId, selectedModelId, outputType, @@ -104,6 +114,10 @@ export const TryFairPage = () => { const isChooseLocationOpen = Boolean(chooseLocation); + useEffect(() => { + if (mode === ModelType.DEMO) setHasSuccessfulPrediction(false); + }, [mode]); + const { recentImageries, addRecentImagery, clearRecentImageries } = useRecentImageries(); @@ -121,6 +135,7 @@ export const TryFairPage = () => { [models, modelId], ); const { + selectedImagery, imageryBounds, imageryCenter, predictionImageUri, @@ -139,6 +154,7 @@ export const TryFairPage = () => { const { modelForMapping, + modelsReady, mappingModelId, imageryModelId, modelUri, @@ -173,12 +189,15 @@ export const TryFairPage = () => { } }, [imageryModelId, selectedModelId, setSelectedModelId]); - const [latestBBox, setLatestBBox] = useState(null); + const [latestBBox, setLatestBBox] = useState(initialProject?.state.bbox ?? null); - const [latestGridZoom, setLatestGridZoom] = useState(null); + const [latestGridZoom, setLatestGridZoom] = useState(initialProject?.state.zoom ?? null); const [parameterOverrides, setParameterOverrides] = useState< Record - >({}); + >(() => Object.fromEntries( + Object.entries(initialProject?.state.params ?? {}) + .filter(([key]) => key !== "confidence_threshold"), + )); const paramValues = useMemo( () => ({ ...defaultParamValues, ...parameterOverrides }), [defaultParamValues, parameterOverrides], @@ -186,11 +205,39 @@ export const TryFairPage = () => { const isParametersDefault = hasDefaultParameters && Object.keys(parameterOverrides).length === 0; + const previousMappingModel = useRef(initialProject?.state.model.id); useEffect(() => { - setParameterOverrides({}); + if (!mappingModelId) return; + if (previousMappingModel.current && previousMappingModel.current !== mappingModelId) { + setParameterOverrides({}); + } + previousMappingModel.current = mappingModelId; }, [mappingModelId]); + + // Keep the saved AOI centered while imagery metadata loads. A new imagery + // selection releases this override and uses that imagery's normal center. + const restoredCenter = useMemo<[number, number] | undefined>(() => { + const saved = initialProject?.state; + if (!saved?.bbox) return undefined; + const original = saved.url_params; + const sameImagery = original + ? mode === original.mode && imageryUrl === original.imagery && oamItemId === original.oamItem + : mode === ModelType.IMAGERY && imageryUrl === saved.imagery.url; + if (!sameImagery) return undefined; + const [w, s, e, n] = saved.bbox; + return [(w + e) / 2, (s + n) / 2]; + }, [initialProject, mode, imageryUrl, oamItemId]); // Snapshot of the current prediction inputs vs what was last submitted, - const lastPredictedInputsRef = useRef(null); + const restoredPrediction = initialProject?.state.prediction_result; + const lastPredictedInputsRef = useRef( + restoredPrediction ? JSON.stringify({ + mappingModelId: restoredPrediction.modelId, + bbox: restoredPrediction.bbox, + gridZoom: restoredPrediction.gridZoom, + resolution: restoredPrediction.resolution, + paramValues: restoredPrediction.params, + }) : null, + ); const predictionInputsSnapshot = useMemo(() => { if (!latestBBox || !mappingModelId) return null; @@ -284,7 +331,8 @@ export const TryFairPage = () => { predictionGridZoom, clearPredictions, cancelPrediction, - } = useFairPredict(); + result: predictionResult, + } = useFairPredict(initialProject?.state.prediction_result ?? null); const handleCancelPrediction = useCallback(() => { cancelPrediction(); @@ -390,6 +438,9 @@ export const TryFairPage = () => { params: apiParams, }, { + onSuccess: () => { + if (mode === ModelType.IMAGERY) setHasSuccessfulPrediction(true); + }, onError: (error) => { if ((error as { code?: string }).code === "ERR_CANCELED") return; showErrorToast(error ?? "An Error Occured."); @@ -411,6 +462,7 @@ export const TryFairPage = () => { closeGuidedTour, recordMapRun, hasNoModelsForFeature, + mode, ]); const isMapButtonDisabled = @@ -514,6 +566,48 @@ export const TryFairPage = () => { return ( <> + {isAuthenticated && ( + + )} {/* Model picker dialog – rendered at page level so it's not trapped inside MobileDrawer */} { !isPredicting && Boolean(predictions && !predictions.features.length) } - imageryCenter={imageryCenter} + imageryCenter={restoredCenter ?? imageryCenter} resolution={resolution} isPredicting={isPredicting} preImageryUrl={preImageryUrl} diff --git a/frontend/src/app/routes/try-fair/try-fair-projects.tsx b/frontend/src/app/routes/try-fair/try-fair-projects.tsx new file mode 100644 index 000000000..7135b325b --- /dev/null +++ b/frontend/src/app/routes/try-fair/try-fair-projects.tsx @@ -0,0 +1,71 @@ +import { Head } from "@/components/seo"; +import { Spinner } from "@/components/ui/spinner"; +import { APPLICATION_ROUTES } from "@/constants/routes"; +import { useGetUserState } from "@/features/user-profile/api/user-state"; +import { Link, useParams, useSearchParams } from "react-router-dom"; +import { useEffect, useState } from "react"; +import type { SavedUserState } from "@/features/try-fair/api/user-state"; +import { getProjectSearchParams } from "@/features/try-fair/utils/restore-project"; +import { useStartMappingStore } from "@/features/try-fair/utils/start-mapping-store"; +import { ModelType } from "@/enums"; +import { TryFairPage } from "../try-fair"; + +export const TryFairProjectPage = () => { + const { pid } = useParams(); + const { data, isPending, isError } = useGetUserState(pid); + + if (isPending) { + return ( +
+ + +
+ ); + } + + if (isError || !data) { + return ( +
+ +

+ Couldn't load this mapping project. It may be unavailable or you may + not have access. +

+ + Start a new mapping project + +
+ ); + } + + return ; +}; + +const RestoreProject = ({ saved }: { saved: SavedUserState }) => { + // Freeze the initial snapshot: autosave cache updates must not reset live edits. + const [initialProject] = useState(saved); + const [ready, setReady] = useState(false); + const [, setSearchParams] = useSearchParams(); + + useEffect(() => { + if (ready) return; + const search = getProjectSearchParams(initialProject); + const store = useStartMappingStore.getState(); + store.setSeletedImagery(null); + store.setPredictions(null); + store.setPredictionBBox(null); + store.setPredictionGridZoom(null); + store.setCurrentModelType( + search.get("mode") === ModelType.DEMO ? ModelType.DEMO : ModelType.IMAGERY, + ); + setSearchParams(search, { replace: true }); + setReady(true); + }, [initialProject, ready, setSearchParams]); + + if (!ready) return ; + return ; +}; diff --git a/frontend/src/components/layouts/navbar/hooks/use-navbar-state.tsx b/frontend/src/components/layouts/navbar/hooks/use-navbar-state.tsx index 3e2922f37..13a4d7bba 100644 --- a/frontend/src/components/layouts/navbar/hooks/use-navbar-state.tsx +++ b/frontend/src/components/layouts/navbar/hooks/use-navbar-state.tsx @@ -9,7 +9,8 @@ export function useNavbarState() { const { pathname } = useLocation(); const { isAuthenticated } = useAuth(); - const isTryFair = isUnder(pathname, APPLICATION_ROUTES.TRY_FAIR); + const isTryFair = isUnder(pathname, APPLICATION_ROUTES.TRY_FAIR) || + Boolean(matchPath(APPLICATION_ROUTES.TRY_FAIR_PROJECT, pathname)); const isProfile = isUnder(pathname, APPLICATION_ROUTES.PROFILE_BASE); const isMapRequests = isUnder(pathname, APPLICATION_ROUTES.MAP_REQUEST_BASE); const isMapRequestResult = Boolean( diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.ts index 0e2f6367c..375be16f1 100644 --- a/frontend/src/constants/routes.ts +++ b/frontend/src/constants/routes.ts @@ -68,6 +68,7 @@ export const APPLICATION_ROUTES = { MAP_REQUEST_RESULT: "/map-requests/:id", TRY_FAIR: "/try-fair", + TRY_FAIR_PROJECT: "/try-fair/:pid", // Published AI Predictions AI_PREDICTIONS: "/ai-predictions", diff --git a/frontend/src/features/models/components/skeletons/table-skeleton.tsx b/frontend/src/features/models/components/skeletons/table-skeleton.tsx index 06761ebe8..953b00a1e 100644 --- a/frontend/src/features/models/components/skeletons/table-skeleton.tsx +++ b/frontend/src/features/models/components/skeletons/table-skeleton.tsx @@ -1,12 +1,15 @@ import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table"; -const TableSkeleton = () => { +const TableSkeleton = ({ rows = 15, columns = 6 }: { + rows?: number; + columns?: number; +}) => { return ( - {Array.from({ length: 15 }).map((_, rowIdx) => ( + {Array.from({ length: rows }).map((_, rowIdx) => ( - {Array.from({ length: 6 }).map((_, colIdx) => ( + {Array.from({ length: columns }).map((_, colIdx) => (
diff --git a/frontend/src/features/try-fair/api/user-state.ts b/frontend/src/features/try-fair/api/user-state.ts index 39885f4a3..f274376ad 100644 --- a/frontend/src/features/try-fair/api/user-state.ts +++ b/frontend/src/features/try-fair/api/user-state.ts @@ -1,11 +1,29 @@ import { API_ENDPOINTS, apiClient } from "@/services"; import type { BBOX } from "@/types"; -import { useMutation } from "@tanstack/react-query"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import type { useTryFairParams } from "@/features/try-fair/hooks/use-try-fair-params"; +import type { PredictResult } from "@/features/try-fair/hooks/use-fair-predict"; + +export type MappingUserState = { + state: { + type: "mapping"; + category: string; + name: string; + model: { id: string; title: string }; + imagery: { name: string; url: string }; + zoom: number | null; + bbox: BBOX | null; + url_params: ReturnType["urlState"]; + params: Record; + prediction_result?: PredictResult | null; + }; +}; export type UserState = { state: { type: string; - prediction_id: number; + prediction_id?: number; + category?: string; name: string; model: { id: string; @@ -15,8 +33,11 @@ export type UserState = { name: string; url: string; }; - zoom: number; - bbox: BBOX; + zoom: number | null; + bbox: BBOX | null; + url_params?: MappingUserState["state"]["url_params"]; + params?: MappingUserState["state"]["params"]; + prediction_result?: PredictResult | null; }; }; @@ -34,8 +55,34 @@ const saveUserState = async (payload: UserState): Promise => { }; export const useSaveUserState = () => { + const queryClient = useQueryClient(); return useMutation({ mutationFn: saveUserState, mutationKey: ["user-state"], + onSuccess: (saved) => { + queryClient.setQueryData(["user-state", String(saved.pid)], saved); + queryClient.invalidateQueries({ queryKey: ["user-state"], exact: true }); + }, + }); +}; + +export const useUpdateUserState = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ pid, payload }: { + pid: number; + payload: MappingUserState; + }) => { + const { data } = await apiClient.patch( + API_ENDPOINTS.EDIT_USER_STATE(pid), + payload, + ); + return data; + }, + mutationKey: ["update-user-state"], + onSuccess: (saved) => { + queryClient.setQueryData(["user-state", String(saved.pid)], saved); + queryClient.invalidateQueries({ queryKey: ["user-state"], exact: true }); + }, }); }; diff --git a/frontend/src/features/try-fair/components/__tests__/mapping-project-autosave.test.tsx b/frontend/src/features/try-fair/components/__tests__/mapping-project-autosave.test.tsx new file mode 100644 index 000000000..9e74d5e89 --- /dev/null +++ b/frontend/src/features/try-fair/components/__tests__/mapping-project-autosave.test.tsx @@ -0,0 +1,152 @@ +import { act, cleanup, render } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { PropsWithChildren } from "react"; +import { MappingProjectAutosave } from "../mapping-project-autosave"; +import type { MappingUserState } from "../../api/user-state"; +import { ModelType, TryFairMapOutputType, TryFairResolution } from "@/enums"; + +const { post, patch } = vi.hoisted(() => ({ post: vi.fn(), patch: vi.fn() })); +vi.mock("@/services", () => ({ + apiClient: { post, patch }, + API_ENDPOINTS: { + SAVE_USER_STATE: "/user-state/", + EDIT_USER_STATE: (pid: number) => `/user-state/${pid}/`, + }, +})); + +const payload: MappingUserState = { + state: { + type: "mapping", + category: "buildings", + name: "Building mapping", + model: { id: "buildings", title: "Buildings" }, + imagery: { name: "Demo Imagery", url: "https://example.com/tiles.json" }, + zoom: 19, + bbox: [85.5, 27.6, 85.52, 27.63], + params: { confidence_threshold: 0.7, simplify_m: 0.9626 }, + prediction_result: { + predictions: { type: "FeatureCollection", features: [] }, + bbox: [85.5, 27.6, 85.52, 27.63], + gridZoom: 19, + modelId: "buildings", + imageUri: "https://example.com/{z}/{x}/{y}.png", + resolution: TryFairResolution.LOW, + params: { confidence_threshold: 0.7, simplify_m: 0.9626 }, + }, + url_params: { + model: "buildings", + output: TryFairMapOutputType.POLYGON, + resolution: TryFairResolution.LOW, + confidence: 0.7, + feature: "buildings", + mode: ModelType.DEMO, + mappingMode: "basic", + imagery: null, + imageryType: null, + oamItem: null, + chooseLocation: false, + selectedModelId: null, + }, + }, +}; +const changed: MappingUserState = { + state: { ...payload.state, category: "trees", params: { confidence_threshold: 0 } }, +}; + +const wrapper = () => { + const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } }); + return ({ children }: PropsWithChildren) => ( + {children} + ); +}; +const tick = async () => { + await act(async () => { await vi.advanceTimersByTimeAsync(800); }); +}; + +describe("MappingProjectAutosave", () => { + beforeEach(() => { + vi.useFakeTimers(); + post.mockReset(); + patch.mockReset(); + post.mockResolvedValue({ data: { ...payload, pid: 42 } }); + patch.mockResolvedValue({ data: { ...changed, pid: 42 } }); + }); + afterEach(() => { + cleanup(); + vi.useRealTimers(); + }); + + it("creates only after a successful prediction enables saving, then updates that pid", async () => { + const view = render(, { wrapper: wrapper() }); + await tick(); + expect(post).not.toHaveBeenCalled(); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledExactlyOnceWith("/user-state/", payload); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledTimes(1); + expect(patch).toHaveBeenCalledExactlyOnceWith("/user-state/42/", changed); + }); + + it("updates an existing project without creating a new record", async () => { + render(, { wrapper: wrapper() }); + await tick(); + expect(post).not.toHaveBeenCalled(); + expect(patch).toHaveBeenCalledExactlyOnceWith("/user-state/42/", payload); + }); + + it("does not patch during restoration but saves subsequent edits to the existing pid", async () => { + const view = render( + , + { wrapper: wrapper() }, + ); + await tick(); + expect(post).not.toHaveBeenCalled(); + expect(patch).not.toHaveBeenCalled(); + view.rerender(); + await tick(); + expect(patch).toHaveBeenCalledExactlyOnceWith("/user-state/42/", changed); + expect(post).not.toHaveBeenCalled(); + }); + + it("keeps edits made during creation and saves them after receiving the pid", async () => { + let finish: (value: unknown) => void = () => {}; + post.mockReturnValue(new Promise((resolve) => { finish = resolve; })); + const view = render(, { wrapper: wrapper() }); + await tick(); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledTimes(1); + expect(patch).not.toHaveBeenCalled(); + await act(async () => { finish({ data: { ...payload, pid: 42 } }); }); + await tick(); + await tick(); + expect(patch).toHaveBeenCalledExactlyOnceWith("/user-state/42/", changed); + }); + + it("retains the created pid while another model is loading", async () => { + const view = render(, { wrapper: wrapper() }); + await tick(); + view.rerender(); + await tick(); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledTimes(1); + expect(patch).toHaveBeenCalledExactlyOnceWith("/user-state/42/", changed); + }); + + it("does not repeat unchanged saves or loop on a failed save", async () => { + post.mockRejectedValue(new Error("Offline")); + const view = render(, { wrapper: wrapper() }); + await tick(); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledTimes(1); + post.mockResolvedValue({ data: { ...changed, pid: 42 } }); + view.rerender(); + await tick(); + expect(post).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/src/features/try-fair/components/mapping-project-autosave.tsx b/frontend/src/features/try-fair/components/mapping-project-autosave.tsx new file mode 100644 index 000000000..8282d84e5 --- /dev/null +++ b/frontend/src/features/try-fair/components/mapping-project-autosave.tsx @@ -0,0 +1,55 @@ +import { useEffect, useRef, useState } from "react"; +import { + type MappingUserState, + useSaveUserState, + useUpdateUserState, +} from "@/features/try-fair/api/user-state"; + +/** Mounted only for a signed-in user; starts saving after a successful prediction. */ +export const MappingProjectAutosave = ({ + enabled, + initialPid, + payload, + skipInitialSave = false, +}: { + enabled: boolean; + initialPid?: number; + payload: MappingUserState | null; + skipInitialSave?: boolean; +}) => { + const [pid, setPid] = useState(initialPid); + const lastAttempt = useRef(null); + const { mutateAsync: create, isPending: isCreating } = useSaveUserState(); + const { mutateAsync: update, isPending: isUpdating } = useUpdateUserState(); + const snapshot = JSON.stringify(payload); + const isPending = isCreating || isUpdating; + + useEffect(() => { + if (!enabled || !payload || isPending || lastAttempt.current === snapshot) return; + if (skipInitialSave && lastAttempt.current === null) { + lastAttempt.current = snapshot; + return; + } + + const timer = window.setTimeout(async () => { + lastAttempt.current = snapshot; + try { + if (pid !== undefined) { + await update({ pid, payload }); + } else { + const saved = await create(payload); + setPid(saved.pid); + } + } catch { + // Keep mapping usable. A subsequent change can try saving again; + // never repeatedly submit the same failing snapshot. + } + }, 750); + + return () => window.clearTimeout(timer); + // Compare the serialized value so unrelated page renders don't restart the timer. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [enabled, snapshot, pid, isPending, create, update, skipInitialSave]); + + return null; +}; diff --git a/frontend/src/features/try-fair/components/modals/__tests__/share-project-modal.test.tsx b/frontend/src/features/try-fair/components/modals/__tests__/share-project-modal.test.tsx new file mode 100644 index 000000000..8ccfa32c7 --- /dev/null +++ b/frontend/src/features/try-fair/components/modals/__tests__/share-project-modal.test.tsx @@ -0,0 +1,55 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ShareProjectModal } from "../share-project-modal"; + +const copyToClipboard = vi.fn(); + +vi.mock("@/hooks/use-clipboard", () => ({ + default: () => ({ copyToClipboard, isCopied: false }), +})); + +vi.mock("@/components/ui/dialog/dialog", () => ({ + default: ({ isOpened, children }: { isOpened: boolean; children: React.ReactNode }) => + isOpened ?
{children}
: null, +})); + +describe("ShareProjectModal", () => { + beforeEach(() => copyToClipboard.mockClear()); + afterEach(cleanup); + + it("shares a protected project through the public Try fAIr route", () => { + render( + + + , + ); + + expect(screen.getByText(/\/try-fair\?model=tree-model&mode=imagery#map$/)) + .toBeInTheDocument(); + + fireEvent.click(screen.getByText("Copy link").closest("sl-button")!); + + expect(copyToClipboard).toHaveBeenCalledWith( + `${window.location.origin}/try-fair?model=tree-model&mode=imagery#map`, + ); + }); + + it("keeps the public Try fAIr URL unchanged", () => { + render( + + + , + ); + + fireEvent.click(screen.getByText("Copy link").closest("sl-button")!); + + expect(copyToClipboard).toHaveBeenCalledWith( + `${window.location.origin}/try-fair?model=building-model`, + ); + }); +}); diff --git a/frontend/src/features/try-fair/components/modals/share-project-modal.tsx b/frontend/src/features/try-fair/components/modals/share-project-modal.tsx index 3322ba6ed..3182d89dc 100644 --- a/frontend/src/features/try-fair/components/modals/share-project-modal.tsx +++ b/frontend/src/features/try-fair/components/modals/share-project-modal.tsx @@ -5,6 +5,8 @@ import { SHOELACE_SIZES } from "@/enums"; import { useStartMappingStore } from "@/features/try-fair/utils/start-mapping-store"; import useCopyToClipboard from "@/hooks/use-clipboard"; import { CheckIcon } from "@/components/ui/icons"; +import { APPLICATION_ROUTES } from "@/constants"; +import { matchPath, useLocation } from "react-router-dom"; interface ShareProjectModalProps { isOpened?: boolean; @@ -22,9 +24,20 @@ export const ShareProjectModal: React.FC = ({ const isOpened = externalIsOpened ?? storeIsOpened; const { copyToClipboard, isCopied } = useCopyToClipboard(); + const location = useLocation(); + const sharePath = matchPath( + APPLICATION_ROUTES.TRY_FAIR_PROJECT, + location.pathname, + ) + ? APPLICATION_ROUTES.TRY_FAIR + : location.pathname; const currentUrl = - typeof window !== "undefined" ? encodeURI(window.location.href) : ""; + typeof window !== "undefined" + ? encodeURI( + `${window.location.origin}${sharePath}${location.search}${location.hash}`, + ) + : ""; const handleClose = () => { if (externalCloseDialog) { @@ -93,7 +106,7 @@ export const ShareProjectModal: React.FC = ({

- Anyone with this link can open the same session — model, imagery, + Anyone with this link can open the same project — model, imagery, resolution and parameters will all be restored.

diff --git a/frontend/src/features/try-fair/components/model-picker-modal.tsx b/frontend/src/features/try-fair/components/model-picker-modal.tsx index b07a3899b..53808c10e 100644 --- a/frontend/src/features/try-fair/components/model-picker-modal.tsx +++ b/frontend/src/features/try-fair/components/model-picker-modal.tsx @@ -194,6 +194,14 @@ export const ModelPickerContent = ({ ); }, [selectedModel, currentModelType, mode]); + // A new browser selection supersedes any unapplied recent-list choice. + useEffect(() => { + if (!stagedImagery) return; + setStagedChoice(null); + setImageryPanelView("preview"); + setActiveTab(TAB_CHOOSE); + }, [stagedImagery]); + // Imagery currently shown (staged selection, else the applied imagery). const activeImagerySelection = stagedChoice?.type === "imagery" && stagedChoice.entry @@ -240,8 +248,6 @@ export const ModelPickerContent = ({ : (selectedModel?.id ?? null); const stagedChoiceKey = stagedChoice ? getChoiceKey(stagedChoice) : null; const stagedImageryKey = stagedImagery?.tileUrl ?? null; - const activeSelectionKey = - stagedChoiceKey ?? stagedImageryKey ?? appliedSelectionKey; const hasStagedFeatureChange = stagedFeatureSlug !== null && stagedFeatureSlug !== feature; const hasUnappliedChanges = diff --git a/frontend/src/features/try-fair/components/model-picker/__tests__/recent-imageries.test.tsx b/frontend/src/features/try-fair/components/model-picker/__tests__/recent-imageries.test.tsx index 15861c9c6..064b4452b 100644 --- a/frontend/src/features/try-fair/components/model-picker/__tests__/recent-imageries.test.tsx +++ b/frontend/src/features/try-fair/components/model-picker/__tests__/recent-imageries.test.tsx @@ -13,6 +13,7 @@ import { useRecentImageries } from "@/features/try-fair/hooks/use-recent-imageri import type { RecentImageryEntry } from "@/features/try-fair/hooks/use-recent-imageries"; import { useStartMappingStore } from "@/features/try-fair/utils/start-mapping-store"; import { ImagerySource, ModelType, TileServiceType } from "@/enums"; +import type { ImagerySelection } from "@/features/try-fair/types/imagery-types"; vi.mock("@/features/try-fair/hooks/use-try-fair-params", () => ({ useTryFairParams: () => ({ mode: "imagery", setChooseLocation: vi.fn() }), @@ -26,7 +27,16 @@ vi.mock("@/features/try-fair/api/features-to-map", () => ({ vi.mock( "@/features/try-fair/components/model-picker/imagery-preview-card", () => ({ - ImageryPreviewCard: () =>

Imagery preview

, + ImageryPreviewCard: ({ selectedImagery, onChangeImagery }: { + selectedImagery: ImagerySelection; + onChangeImagery: () => void; + }) => ( +
+

Imagery preview

+ {selectedImagery.tileUrl} + +
+ ), }), ); vi.mock("@/components/ui/button", () => ({ @@ -92,6 +102,38 @@ afterEach(() => { }); describe("Recent imagery", () => { + it("replaces an unapplied recent choice with the newer browser selection", () => { + const onApplyRecentImagery = vi.fn(); + const onApplyStagedImagery = vi.fn(); + const onChooseImagery = vi.fn(); + const props = { + selectedModel: null, + models: [], + onSelect: vi.fn(), + recentImageries: [entry], + onClearRecentImageries: vi.fn(), + onApplyRecentImagery, + onApplyStagedImagery, + onChooseImagery, + }; + const view = render(); + fireEvent.click(screen.getByRole("button", { name: "Recent" })); + fireEvent.click(screen.getByRole("button", { name: /Test imagery/ })); + fireEvent.click(screen.getByRole("button", { name: "Change" })); + expect(onChooseImagery).toHaveBeenCalledOnce(); + + const browserSelection: ImagerySelection = { + ...entry.selection, + tileUrl: "https://example.com/new/{z}/{x}/{y}.png", + }; + view.rerender(); + expect(screen.getByTestId("preview-url")).toHaveTextContent(browserSelection.tileUrl); + expect(onApplyStagedImagery).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Apply" })); + expect(onApplyStagedImagery).toHaveBeenCalledWith(browserSelection); + expect(onApplyRecentImagery).not.toHaveBeenCalled(); + }); + it("labels the back button with its destination and returns to the preview", () => { render(); fireEvent.click(screen.getByRole("button", { name: "Recent" })); diff --git a/frontend/src/features/try-fair/hooks/__tests__/use-fair-predict.test.tsx b/frontend/src/features/try-fair/hooks/__tests__/use-fair-predict.test.tsx new file mode 100644 index 000000000..affbd3a7b --- /dev/null +++ b/frontend/src/features/try-fair/hooks/__tests__/use-fair-predict.test.tsx @@ -0,0 +1,69 @@ +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { PropsWithChildren } from "react"; +import { useFairPredict, type PredictResult } from "../use-fair-predict"; +import { runPredict, type BaseModelStacItem } from "../../api/stac"; +import { TryFairResolution } from "@/enums"; + +vi.mock("../../api/stac", () => ({ runPredict: vi.fn() })); + +const saved: PredictResult = { + predictions: { + type: "FeatureCollection", + features: [{ type: "Feature", geometry: { type: "Point", coordinates: [85.51, 27.61] }, properties: { confidence: 0.9 } }], + }, + bbox: [85.5, 27.6, 85.52, 27.63], + gridZoom: 19, + modelId: "buildings", + imageUri: "https://example.com/{z}/{x}/{y}.png", + resolution: TryFairResolution.LOW, + params: { confidence_threshold: 0.7 }, +}; + +const wrapper = () => { + const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } }); + return ({ children }: PropsWithChildren) => ( + {children} + ); +}; + +describe("saved prediction results", () => { + beforeEach(() => { vi.clearAllMocks(); }); + afterEach(cleanup); + + it("restores predictions, bounds, and grid zoom without running prediction", () => { + const { result } = renderHook(() => useFairPredict(saved), { wrapper: wrapper() }); + expect(result.current.predictions).toEqual(saved.predictions); + expect(result.current.predictionBBox).toEqual(saved.bbox); + expect(result.current.predictionGridZoom).toBe(19); + expect(runPredict).not.toHaveBeenCalled(); + }); + + it("does not resurrect saved results after imagery or model selection clears them", () => { + const { result, rerender } = renderHook(() => useFairPredict(saved), { wrapper: wrapper() }); + act(() => result.current.clearPredictions()); + rerender(); + expect(result.current.result).toBeNull(); + expect(result.current.predictions).toBeNull(); + }); + + it("stores successful results with the inputs used to produce them", async () => { + vi.mocked(runPredict).mockResolvedValue(saved.predictions); + const model = { + id: "buildings", + assets: { "mlm:inference-endpoint": { href: "https://example.com/predict" } }, + } as BaseModelStacItem; + const { result } = renderHook(() => useFairPredict(), { wrapper: wrapper() }); + act(() => result.current.predict({ + model, + modelUri: "model.onnx", + imageUri: saved.imageUri, + bbox: saved.bbox, + gridZoom: saved.gridZoom, + resolution: saved.resolution, + params: saved.params, + })); + await waitFor(() => expect(result.current.result).toEqual(saved)); + }); +}); diff --git a/frontend/src/features/try-fair/hooks/__tests__/use-try-fair-params.test.tsx b/frontend/src/features/try-fair/hooks/__tests__/use-try-fair-params.test.tsx index 33f6f0890..cd02a1f87 100644 --- a/frontend/src/features/try-fair/hooks/__tests__/use-try-fair-params.test.tsx +++ b/frontend/src/features/try-fair/hooks/__tests__/use-try-fair-params.test.tsx @@ -58,6 +58,8 @@ describe("useTryFairParams", () => { imageryType: "XYZ", oamItem: "item-123", chooseLocation: "true", + mappingMode: "advanced", + selectedModelId: "chosen-model", }), }); @@ -74,6 +76,20 @@ describe("useTryFairParams", () => { expect(result.current.oamItemId).toBe("item-123"); expect(result.current.chooseLocation).toBe(true); expect(result.current.isParametersDefault).toBe(false); + expect(result.current.urlState).toEqual({ + model: "custom-model", + output: "points", + resolution: "mid", + confidence: 0.85, + feature: "roads", + mode: "imagery", + imagery: "https://example.com/tiles/{z}/{x}/{y}.png", + imageryType: "XYZ", + oamItem: "item-123", + chooseLocation: true, + mappingMode: "advanced", + selectedModelId: "chosen-model", + }); }); it("should handle chooseLocation state updates correctly", () => { diff --git a/frontend/src/features/try-fair/hooks/use-fair-predict.tsx b/frontend/src/features/try-fair/hooks/use-fair-predict.tsx index 85ef6d11e..bd0748368 100644 --- a/frontend/src/features/try-fair/hooks/use-fair-predict.tsx +++ b/frontend/src/features/try-fair/hooks/use-fair-predict.tsx @@ -3,11 +3,15 @@ import { BaseModelStacItem, runPredict } from "../api/stac"; import { TryFairResolution } from "@/enums/try-fair"; import { BBOX } from "@/types"; import { TRY_FAIR_RESOLUTION_ZOOM } from "@/features/try-fair/utils/common"; -import { useRef } from "react"; -type PredictResult = { +import { useCallback, useRef, useState } from "react"; +export type PredictResult = { predictions: GeoJSON.FeatureCollection; bbox: BBOX; - gridZoom: number | undefined; + gridZoom: number; + modelId: string; + imageUri: string; + resolution: TryFairResolution; + params: Record; }; type PredictArgs = { @@ -22,9 +26,10 @@ type PredictArgs = { params: Record; }; -export const useFairPredict = () => { +export const useFairPredict = (initialResult: PredictResult | null = null) => { const abortControllerRef = useRef(null); - const { mutate, isPending, data, error, reset } = useMutation< + const [result, setResult] = useState(initialResult); + const { mutate, isPending, error, reset } = useMutation< PredictResult, Error, PredictArgs @@ -57,23 +62,38 @@ export const useFairPredict = () => { }, controller.signal, ); - return { predictions, bbox, gridZoom }; + return { + predictions, + bbox, + gridZoom: gridZoom ?? TRY_FAIR_RESOLUTION_ZOOM[resolution], + modelId: model.id, + imageUri, + resolution, + params, + }; } finally { if (abortControllerRef.current === controller) { abortControllerRef.current = null; } } }, + onSuccess: setResult, }); + const clearPredictions = useCallback(() => { + setResult(null); + reset(); + }, [reset]); + return { predict: mutate, isPredicting: isPending, - predictions: data?.predictions ?? null, - predictionBBox: data?.bbox ?? null, - predictionGridZoom: data?.gridZoom ?? null, + result, + predictions: result?.predictions ?? null, + predictionBBox: result?.bbox ?? null, + predictionGridZoom: result?.gridZoom ?? null, error: error?.message ?? null, - clearPredictions: reset, + clearPredictions, cancelPrediction: () => abortControllerRef.current?.abort(), }; }; diff --git a/frontend/src/features/try-fair/hooks/use-imagery-mapping-model.ts b/frontend/src/features/try-fair/hooks/use-imagery-mapping-model.ts index d6660f186..1f39c692f 100644 --- a/frontend/src/features/try-fair/hooks/use-imagery-mapping-model.ts +++ b/frontend/src/features/try-fair/hooks/use-imagery-mapping-model.ts @@ -46,11 +46,10 @@ export const useImageryMappingModel = ({ ...(apiBaseModels?.results ?? []), ...(apiLocalModels?.results ?? []), ]; - return ( - apiModels.find((model) => model.stac_item_id === selectedModelId) ?? - apiModels[0] ?? - null - ); + if (selectedModelId) { + return apiModels.find((model) => model.stac_item_id === selectedModelId) ?? null; + } + return apiModels[0] ?? null; }, [apiBaseModels, apiLocalModels, selectedModelId]); const modelForMapping = isImageryMode @@ -81,6 +80,7 @@ export const useImageryMappingModel = ({ }, [confidence, inferenceParams]); return { + modelsReady: !isImageryMode || (hasLoadedApiBaseModels && hasLoadedApiLocalModels), modelForMapping, mappingModelId, imageryModelId: isImageryMode ? mappingModelId : null, diff --git a/frontend/src/features/try-fair/hooks/use-try-fair-params.tsx b/frontend/src/features/try-fair/hooks/use-try-fair-params.tsx index 4e8e93e06..b499b8cf8 100644 --- a/frontend/src/features/try-fair/hooks/use-try-fair-params.tsx +++ b/frontend/src/features/try-fair/hooks/use-try-fair-params.tsx @@ -158,6 +158,15 @@ export const useTryFairParams = () => { }); return { + /** Complete URL-backed state, including effective defaults and preferences. */ + urlState: { + ...params, + output: outputType, + resolution, + confidence, + mode, + mappingMode, + }, modelId: params.model, selectedModelId: params.selectedModelId, selectedModel, diff --git a/frontend/src/features/try-fair/utils/restore-project.ts b/frontend/src/features/try-fair/utils/restore-project.ts new file mode 100644 index 000000000..ff7c4e0eb --- /dev/null +++ b/frontend/src/features/try-fair/utils/restore-project.ts @@ -0,0 +1,32 @@ +import { ModelType } from "@/enums"; +import type { SavedUserState } from "@/features/try-fair/api/user-state"; +import { TRY_FAIR_PARAM_DEFAULTS } from "@/features/try-fair/hooks/use-try-fair-params"; +import { TRY_FAIR_RESOLUTION_ZOOM } from "./common"; +import { getTileServerTypeFromURL } from "@/utils/regex-utils"; + +/** Older saved activities lack url_params; restore their model and imagery too. */ +export const getProjectSearchParams = ({ state }: SavedUserState) => { + const resolution = Object.entries(TRY_FAIR_RESOLUTION_ZOOM) + .find(([, zoom]) => zoom === state.zoom)?.[0]; + const values = { + ...TRY_FAIR_PARAM_DEFAULTS, + model: state.model.id, + selectedModelId: state.model.id, + feature: state.category ?? TRY_FAIR_PARAM_DEFAULTS.feature, + mode: ModelType.IMAGERY, + resolution: resolution ?? TRY_FAIR_PARAM_DEFAULTS.resolution, + confidence: typeof state.params?.confidence_threshold === "number" + ? state.params.confidence_threshold + : TRY_FAIR_PARAM_DEFAULTS.confidence, + imagery: state.imagery.url, + imageryType: getTileServerTypeFromURL(state.imagery.url), + oamItem: null, + chooseLocation: false, + ...state.url_params, + }; + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(values)) { + if (value !== null) search.set(key, String(value)); + } + return search; +}; diff --git a/frontend/src/features/user-profile/api/user-state.ts b/frontend/src/features/user-profile/api/user-state.ts index 08e375741..094ebd1ff 100644 --- a/frontend/src/features/user-profile/api/user-state.ts +++ b/frontend/src/features/user-profile/api/user-state.ts @@ -1,13 +1,13 @@ -import { UserState } from "@/features/try-fair/api/user-state"; +import type { SavedUserState as UserStateRecord } from "@/features/try-fair/api/user-state"; import { API_ENDPOINTS, apiClient } from "@/services"; -import { useQuery } from "@tanstack/react-query"; +import { skipToken, useQuery } from "@tanstack/react-query"; -export type SavedUserState = UserState & { - "count": number; - "next": number | null; - "previous": number | null; - "results": UserState[]; +export type SavedUserState = { + count: number; + next: string | null; + previous: string | null; + results: UserStateRecord[]; }; const getUserState = async (): Promise => { @@ -24,3 +24,20 @@ export const useGetUserStates = () => { queryKey: ["user-state"], }); }; + +/** Fetch a saved mapping project by its user-state pid, not its prediction ID. */ +export const useGetUserState = (pid?: string) => { + return useQuery({ + queryKey: ["user-state", pid], + queryFn: pid + ? async ({ signal }) => { + const { data } = await apiClient.get( + API_ENDPOINTS.GET_SINGLE_USER_STATE(pid), + { signal }, + ); + return data; + } + : skipToken, + refetchOnWindowFocus: false, + }); +}; diff --git a/frontend/src/features/user-profile/components/map-requests/download-result-button.tsx b/frontend/src/features/user-profile/components/map-requests/download-result-button.tsx index 1d51d8d98..8c408bd6a 100644 --- a/frontend/src/features/user-profile/components/map-requests/download-result-button.tsx +++ b/frontend/src/features/user-profile/components/map-requests/download-result-button.tsx @@ -31,7 +31,7 @@ export const DownloadResultButton = ({ className }: { className?: string }) => { return ( + APPLICATION_ROUTES.TRY_FAIR_PROJECT.replace( + ":pid", + String(pid), + ); + +const columns: ColumnDef[] = [ + { + accessorKey: "state.name", + header: "Name", + cell: ({ row }) => ( + + {row.original.state.name} + + ), + }, + { + accessorKey: "state.type", + header: "Type", + cell: ({ row }) => { + const { type, category } = row.original.state; + const label = category || type; + const Icon = label === "mapping" || label === "prediction" + ? MapIcon + : getFeatureIcon(label); + return ( + + + ); + }, + }, + { + id: "actions", + header: () => Open mapping project, + cell: ({ row }) => ( + event.stopPropagation()} + className="ml-auto flex size-8 items-center justify-center rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary" + > +