Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
agnlez committed Oct 9, 2023
1 parent 5fef549 commit f21dcac
Show file tree
Hide file tree
Showing 13 changed files with 104 additions and 99 deletions.
36 changes: 6 additions & 30 deletions app/hooks/cost-surface/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useSession } from 'next-auth/react';
import { CostSurface } from 'types/api/cost-surface';
import { Project } from 'types/api/project';

import { API } from 'services/api';
import { API, JSONAPI } from 'services/api';
import UPLOADS from 'services/uploads';

export function useProjectCostSurfaces<T = CostSurface[]>(
Expand All @@ -15,42 +15,18 @@ export function useProjectCostSurfaces<T = CostSurface[]>(
) {
const { data: session } = useSession();

const mockData: CostSurface[] = [
{
id: 'b7454579-c48e-4e2f-8438-833280cb65d8',
name: 'Brazil 15 k Cost Surface',
isCustom: true,
scenarioUsageCount: 3,
},
{
id: 'rfjghhrtersdtbkjshfw',
name: 'Cost Surface Rwanda B',
isCustom: true,
scenarioUsageCount: 0,
},
{
id: '23275455HGVVCMSJHDFk',
name: 'Cost Surface Rwanda C',
isCustom: true,
scenarioUsageCount: 0,
},
];

return useQuery({
queryKey: ['cost-surfaces', pid],
queryFn: async () =>
API.request<CostSurface[]>({
JSONAPI.request<{ data: CostSurface[] }>({
method: 'GET',
// !TODO: change this to the correct endpoint
url: `/projects/${pid}/protected-areas`,
url: `/projects/${pid}/cost-surface`,
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
params,
}).then(({ data }) => mockData),
// TODO: enable this when the endpoint is ready
enabled: true,
// enabled: Boolean(pid),
}).then(({ data }) => data?.data),
enabled: Boolean(pid),
...queryOptions,
});
}
Expand All @@ -69,7 +45,7 @@ export function useEditProjectCostSurface() {
}) => {
// TODO: change this to the correct endpoint
return API.patch<CostSurface>(
`projects/${projectId}/cost-surfaces/${costSurfaceId}`,
`projects/${projectId}/cost-surface/${costSurfaceId}`,
{
...body,
},
Expand Down
24 changes: 6 additions & 18 deletions app/hooks/map/constants.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React from 'react';

import { useAppSelector } from 'store/hooks';

import chroma from 'chroma-js';
import { FaSquare } from 'react-icons/fa';

Expand Down Expand Up @@ -313,22 +315,6 @@ export const LEGEND_LAYERS = {
visibility: true,
},
}),
// 'features-highlight': () => ({
// id: 'features-highlight',
// name: 'Selected Features',
// icon: (
// <Icon
// icon={HEXAGON_SVG}
// className="mt-0.5 h-3.5 w-3.5 stroke-current stroke-2"
// style={{ color: COLORS.highlightFeatures }}
// />
// ),
// settingsManager: {
// opacity: true,
// visibility: true,
// },
// }),

// ANALYSIS
['features-abundance']: (options: {
items: {
Expand Down Expand Up @@ -366,7 +352,7 @@ export const LEGEND_LAYERS = {
},
'cost-surface': (options: {
items: { id: CostSurface['id']; name: CostSurface['name']; min?: number; max?: number }[];
onChangeVisibility: () => void;
onChangeVisibility: (id: CostSurface['id']) => void;
}) => {
const { items, onChangeVisibility } = options;

Expand All @@ -388,7 +374,9 @@ export const LEGEND_LAYERS = {
value: `${max}`,
},
],
onChangeVisibility,
onChangeVisibility: () => {
onChangeVisibility?.(id);
},
}));
},
'lock-available': (options) => {
Expand Down
2 changes: 1 addition & 1 deletion app/layout/project/navigation/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const useInventoryItems = (): SubMenuItem[] => {
const { showCS } = useFeatureFlags();
const { query, route } = useRouter();
const { pid, tab } = query as { pid: string; tab: string };
const isProjectRoute = route.startsWith('/projects/[pid]');
const isProjectRoute = route.startsWith('/projects/[pid]') && !route.includes('/scenarios');

return [
{
Expand Down
2 changes: 1 addition & 1 deletion app/layout/project/navigation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const Navigation = (): JSX.Element => {
const { query, route } = useRouter();
const { pid, sid, tab } = query as { pid: string; sid: string; tab: string };

const isProjectRoute = route.startsWith('/projects/[pid]');
const isProjectRoute = route.startsWith('/projects/[pid]') && !route.includes('/scenarios');
const isScenarioRoute = route.startsWith('/projects/[pid]/scenarios/') && !route.endsWith('/new');

const { addToast } = useToasts();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,8 @@ const RowItem = ({
>
<span className="inline-flex">{name}</span>
<div className="mt-1.5 text-xs text-gray-400">
Currently in use in
<span className="rounded bg-blue-600 bg-opacity-10 px-1 text-blue-600">
{scenarios}
</span>{' '}
Currently in use in{' '}
<span className="rounded bg-blue-600 bg-opacity-10 px-1 text-blue-600">{scenarios}</span>{' '}
scenarios.
</div>
</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function bulkDeleteCostSurfaceFromProject(
pid: Project['id'];
csid: CostSurface['id'];
}) => {
return PROJECTS.delete(`/${pid}/cost-surfaces/${csid}`, {
return PROJECTS.delete(`/${pid}/cost-surface/${csid}`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { useState, useCallback, useEffect, ChangeEvent } from 'react';
import { useState, useCallback, useEffect, ChangeEvent, useMemo } from 'react';

import { useRouter } from 'next/router';

import { useAppDispatch, useAppSelector } from 'store/hooks';
import { setSelectedCostSurfaces as setVisibleCostSurface } from 'store/slices/projects/[id]';
import {
setLayerSettings,
setSelectedCostSurfaces as setVisibleCostSurface,
} from 'store/slices/projects/[id]';

import { orderBy } from 'lodash';

import { useProjectCostSurfaces } from 'hooks/cost-surface';

Expand All @@ -22,9 +27,11 @@ const COST_SURFACE_TABLE_COLUMNS = [

const InventoryPanelCostSurface = ({ noData: noDataMessage }: { noData: string }): JSX.Element => {
const dispatch = useAppDispatch();
const { selectedCostSurface: visibleCostSurface, search } = useAppSelector(
(state) => state['/projects/[id]']
);
const {
selectedCostSurface: visibleCostSurface,
search,
layerSettings,
} = useAppSelector((state) => state['/projects/[id]']);

const { query } = useRouter();
const { pid } = query as { pid: string };
Expand All @@ -38,21 +45,28 @@ const InventoryPanelCostSurface = ({ noData: noDataMessage }: { noData: string }
pid,
{
...filters,
search,
...(search?.length > 0 && { search }),
},
{
select: (data) =>
data?.map((cs) => ({
id: cs.id,
name: cs.name,
isCustom: cs.isCustom,
scenarioUsageCount: cs.scenarioUsageCount,
})),
data
.filter(({ isDefault }) => !isDefault)
.map((cs) => ({
...cs,
isCustom: !cs.isDefault,
})),
keepPreviousData: true,
placeholderData: [],
}
);

const sortedCostSurfaces = useMemo(() => {
if (filters.sort === '-name') return orderBy(allProjectCostSurfacesQuery.data, 'name', 'desc');

// the API assumes the default sort is ascending
return orderBy(allProjectCostSurfacesQuery.data, 'name', 'asc');
}, [filters, allProjectCostSurfacesQuery.data]);

const costSurfaceIds = allProjectCostSurfacesQuery.data?.map((cs) => cs.id);

const handleSelectAll = useCallback(
Expand Down Expand Up @@ -81,13 +95,24 @@ const InventoryPanelCostSurface = ({ noData: noDataMessage }: { noData: string }

const toggleSeeOnMap = useCallback(
(costSurfaceId: CostSurface['id']) => {
costSurfaceIds.forEach((id) => {
dispatch(
setLayerSettings({
id,
settings: {
visibility: id !== costSurfaceId ? false : !layerSettings[costSurfaceId]?.visibility,
},
})
);
});

if (costSurfaceId === visibleCostSurface) {
dispatch(setVisibleCostSurface(null));
} else {
dispatch(setVisibleCostSurface(costSurfaceId));
}
},
[dispatch, visibleCostSurface]
[dispatch, visibleCostSurface, layerSettings, costSurfaceIds]
);

const handleSort = useCallback(
Expand All @@ -104,7 +129,7 @@ const InventoryPanelCostSurface = ({ noData: noDataMessage }: { noData: string }

const displayBulkActions = selectedCostSurfaceIds.length > 0;

const data: DataItem[] = allProjectCostSurfacesQuery.data?.map((cs) => ({
const data: DataItem[] = sortedCostSurfaces?.map((cs) => ({
...cs,
name: cs.name,
scenarios: cs.scenarioUsageCount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const DeleteModal = ({
addToast(
'delete-bulk-project-cost-surfaces',
<>
<h2 className="font-medium">Error!</h2>
<h2 className="font-medium">Error</h2>
<p className="text-sm">Something went wrong deleting the cost surfaces.</p>
</>,
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ const EditModal = ({

const formRef = useRef<FormProps<FormValues>['form']>(null);

const allProjectCostSurfacesQuery = useProjectCostSurfaces(pid, {});
const allProjectCostSurfacesQuery = useProjectCostSurfaces(
pid,
{},
{
select: (data) => data.find(({ id }) => id === costSurfaceId),
}
);

const editProjectCostSurfaceMutation = useEditProjectCostSurface();

Expand All @@ -53,7 +59,7 @@ const EditModal = ({
addToast(
'success-edit-cost-surfaces',
<>
<h2 className="font-medium">Success!</h2>
<h2 className="font-medium">Success</h2>
<p className="text-sm">Cost surface edited</p>
</>,
{
Expand Down Expand Up @@ -82,7 +88,7 @@ const EditModal = ({
return (
<FormRFF<FormValues>
initialValues={{
name: allProjectCostSurfacesQuery.data?.[0]?.name,
name: allProjectCostSurfacesQuery.data?.name,
}}
ref={formRef}
onSubmit={onEditSubmit}
Expand Down
44 changes: 27 additions & 17 deletions app/layout/projects/show/map/legend/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { useRouter } from 'next/router';

import { useAppDispatch, useAppSelector } from 'store/hooks';
import { setSelectedFeatures, setLayerSettings } from 'store/slices/projects/[id]';
import {
setSelectedFeatures,
setLayerSettings,
setSelectedCostSurfaces as setVisibleCostSurface,
} from 'store/slices/projects/[id]';

import chroma from 'chroma-js';

Expand All @@ -11,6 +15,7 @@ import { COLORS, LEGEND_LAYERS } from 'hooks/map/constants';
import { useScenario } from 'hooks/scenarios';
import { useProjectWDPAs } from 'hooks/wdpa';

import { CostSurface } from 'types/api/cost-surface';
import { Feature } from 'types/api/feature';
import { Scenario } from 'types/api/scenario';
import { WDPA } from 'types/api/wdpa';
Expand Down Expand Up @@ -40,27 +45,32 @@ export const useCostSurfaceLegend = () => {
const dispatch = useAppDispatch();
const { layerSettings, selectedCostSurface } = useAppSelector((state) => state['/projects/[id]']);

const costSurfaceQuery = useProjectCostSurfaces(
pid,
{},
{
select: (data) => data.map(({ id, name }) => ({ id, name })),
}
);
const costSurfaceQuery = useProjectCostSurfaces(pid, {});

const costSurfaceIds = costSurfaceQuery.data?.map((cs) => cs.id);

if (!costSurfaceQuery.data?.length) return [];

return LEGEND_LAYERS['cost-surface']({
items: costSurfaceQuery.data,
onChangeVisibility: () => {
dispatch(
setLayerSettings({
id: selectedCostSurface,
settings: {
visibility: !layerSettings[selectedCostSurface]?.visibility,
},
})
);
onChangeVisibility: (costSurfaceId: CostSurface['id']) => {
costSurfaceIds.forEach((id) => {
dispatch(
setLayerSettings({
id,
settings: {
visibility:
id !== costSurfaceId ? false : !layerSettings[costSurfaceId]?.visibility || true,
},
})
);
});

if (costSurfaceId === selectedCostSurface) {
dispatch(setVisibleCostSurface(null));
} else {
dispatch(setVisibleCostSurface(costSurfaceId));
}
},
});
};
Expand Down
Loading

0 comments on commit f21dcac

Please sign in to comment.