First round of refactor EntityBoards (#1067)

This commit is contained in:
Lucas Bordeau
2023-08-04 16:16:34 +02:00
committed by GitHub
parent 11e7266f8a
commit c790cc5d0c
35 changed files with 513 additions and 414 deletions

View File

@ -1,57 +0,0 @@
import styled from '@emotion/styled';
import { DropResult } from '@hello-pangea/dnd'; // Atlassian dnd does not support StrictMode from RN 18, so we use a fork @hello-pangea/dnd https://github.com/atlassian/react-beautiful-dnd/issues/2350
export const StyledBoard = styled.div`
border-radius: ${({ theme }) => theme.spacing(2)};
display: flex;
flex: 1;
flex-direction: row;
padding-left: ${({ theme }) => theme.spacing(2)};
`;
export type BoardPipelineStageColumn = {
pipelineStageId: string;
title: string;
index: number;
colorCode?: string;
pipelineProgressIds: string[];
};
export function getOptimisticlyUpdatedBoard(
board: BoardPipelineStageColumn[],
result: DropResult,
) {
const newBoard = JSON.parse(JSON.stringify(board));
const { destination, source } = result;
if (!destination) return;
const sourceColumnIndex = newBoard.findIndex(
(column: BoardPipelineStageColumn) =>
column.pipelineStageId === source.droppableId,
);
const sourceColumn = newBoard[sourceColumnIndex];
const destinationColumnIndex = newBoard.findIndex(
(column: BoardPipelineStageColumn) =>
column.pipelineStageId === destination.droppableId,
);
const destinationColumn = newBoard[destinationColumnIndex];
if (!destinationColumn || !sourceColumn) return;
const sourceItems = sourceColumn.pipelineProgressIds;
const destinationItems = destinationColumn.pipelineProgressIds;
const [removed] = sourceItems.splice(source.index, 1);
destinationItems.splice(destination.index, 0, removed);
const newSourceColumn: BoardPipelineStageColumn = {
...sourceColumn,
pipelineProgressIds: sourceItems,
};
const newDestinationColumn = {
...destinationColumn,
pipelineProgressIds: destinationItems,
};
newBoard.splice(sourceColumnIndex, 1, newSourceColumn);
newBoard.splice(destinationColumnIndex, 1, newDestinationColumn);
return newBoard;
}

View File

@ -0,0 +1,61 @@
import { useRecoilCallback } from 'recoil';
import { boardCardIdsByColumnIdFamilyState } from '@/ui/board/states/boardCardIdsByColumnIdFamilyState';
import { boardColumnsState } from '@/ui/board/states/boardColumnsState';
import { selectedBoardCardIdsState } from '@/ui/board/states/selectedBoardCardIdsState';
import { IconTrash } from '@/ui/icon/index';
import { EntityTableActionBarButton } from '@/ui/table/action-bar/components/EntityTableActionBarButton';
export function BoardActionBarButtonDeleteBoardCard({
onDelete,
}: {
onDelete: (deletedCardIds: string[]) => void;
}) {
const deleteBoardCardIds = useRecoilCallback(
({ set, snapshot }) =>
() => {
const boardCardIdsToDelete = snapshot
.getLoadable(selectedBoardCardIdsState)
.getValue();
const boardColumns = snapshot.getLoadable(boardColumnsState).getValue();
for (const boardColumn of boardColumns) {
const boardColumnCardIds = snapshot
.getLoadable(boardCardIdsByColumnIdFamilyState(boardColumn.id))
.getValue();
const newBoardColumnCardIds = boardColumnCardIds.filter(
(cardId) => !boardCardIdsToDelete.includes(cardId),
);
if (newBoardColumnCardIds.length !== boardColumnCardIds.length) {
set(
boardCardIdsByColumnIdFamilyState(boardColumn.id),
newBoardColumnCardIds,
);
}
}
set(selectedBoardCardIdsState, []);
return boardCardIdsToDelete;
},
[],
);
async function handleDeleteClick() {
const deletedCardIds = deleteBoardCardIds();
onDelete(deletedCardIds);
}
return (
<EntityTableActionBarButton
label="Delete"
icon={<IconTrash size={16} />}
type="warning"
onClick={handleDeleteClick}
/>
);
}

View File

@ -0,0 +1,134 @@
import { useCallback } from 'react';
import { getOperationName } from '@apollo/client/utilities';
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { DragDropContext, OnDragEndResponder } from '@hello-pangea/dnd'; // Atlassian dnd does not support StrictMode from RN 18, so we use a fork @hello-pangea/dnd https://github.com/atlassian/react-beautiful-dnd/issues/2350
import { IconList } from '@tabler/icons-react';
import { useRecoilState } from 'recoil';
import { CompanyBoardContext } from '@/companies/states/CompanyBoardContext';
import { BoardHeader } from '@/ui/board/components/BoardHeader';
import { StyledBoard } from '@/ui/board/components/StyledBoard';
import { useUpdateBoardCardIds } from '@/ui/board/hooks/useUpdateBoardCardIds';
import { BoardColumnIdContext } from '@/ui/board/states/BoardColumnIdContext';
import { SelectedSortType } from '@/ui/filter-n-sort/types/interface';
import { RecoilScope } from '@/ui/utilities/recoil-scope/components/RecoilScope';
import {
PipelineProgress,
PipelineProgressOrderByWithRelationInput,
PipelineStage,
useUpdateOnePipelineProgressStageMutation,
} from '~/generated/graphql';
import { GET_PIPELINE_PROGRESS } from '../../../pipeline/queries';
import { BoardColumnContext } from '../states/BoardColumnContext';
import { boardColumnsState } from '../states/boardColumnsState';
import { BoardOptions } from '../types/BoardOptions';
import { EntityBoardColumn } from './EntityBoardColumn';
const StyledBoardWithHeader = styled.div`
display: flex;
flex: 1;
flex-direction: column;
width: 100%;
`;
export function EntityBoard({
boardOptions,
updateSorts,
onEditColumnTitle,
onEditColumnColor,
}: {
boardOptions: BoardOptions;
updateSorts: (
sorts: Array<SelectedSortType<PipelineProgressOrderByWithRelationInput>>,
) => void;
onEditColumnTitle: (columnId: string, title: string) => void;
onEditColumnColor: (columnId: string, color: string) => void;
}) {
const [boardColumns] = useRecoilState(boardColumnsState);
const theme = useTheme();
const [updatePipelineProgressStage] =
useUpdateOnePipelineProgressStageMutation();
const updatePipelineProgressStageInDB = useCallback(
async (
pipelineProgressId: NonNullable<PipelineProgress['id']>,
pipelineStageId: NonNullable<PipelineStage['id']>,
) => {
updatePipelineProgressStage({
variables: {
id: pipelineProgressId,
pipelineStageId,
},
refetchQueries: [getOperationName(GET_PIPELINE_PROGRESS) ?? ''],
});
},
[updatePipelineProgressStage],
);
const updateBoardCardIds = useUpdateBoardCardIds();
const onDragEnd: OnDragEndResponder = useCallback(
async (result) => {
if (!boardColumns) return;
updateBoardCardIds(result);
try {
const draggedEntityId = result.draggableId;
const destinationColumnId = result.destination?.droppableId;
// TODO: abstract
if (
draggedEntityId &&
destinationColumnId &&
updatePipelineProgressStageInDB
) {
await updatePipelineProgressStageInDB(
draggedEntityId,
destinationColumnId,
);
}
} catch (e) {
console.error(e);
}
},
[boardColumns, updatePipelineProgressStageInDB, updateBoardCardIds],
);
const sortedBoardColumns = [...boardColumns].sort((a, b) => {
return a.index - b.index;
});
return (boardColumns?.length ?? 0) > 0 ? (
<StyledBoardWithHeader>
<BoardHeader
viewName="All opportunities"
viewIcon={<IconList size={theme.icon.size.md} />}
availableSorts={boardOptions.sorts}
onSortsUpdate={updateSorts}
context={CompanyBoardContext}
/>
<StyledBoard>
<DragDropContext onDragEnd={onDragEnd}>
{sortedBoardColumns.map((column) => (
<BoardColumnIdContext.Provider value={column.id} key={column.id}>
<RecoilScope SpecificContext={BoardColumnContext} key={column.id}>
<EntityBoardColumn
boardOptions={boardOptions}
column={column}
onEditColumnTitle={onEditColumnTitle}
onEditColumnColor={onEditColumnColor}
/>
</RecoilScope>
</BoardColumnIdContext.Provider>
))}
</DragDropContext>
</StyledBoard>
</StyledBoardWithHeader>
) : (
<></>
);
}

View File

@ -0,0 +1,15 @@
import React from 'react';
import { useRecoilValue } from 'recoil';
import { ActionBar } from '@/ui/action-bar/components/ActionBar';
import { selectedBoardCardIdsState } from '../states/selectedBoardCardIdsState';
type OwnProps = {
children: React.ReactNode | React.ReactNode[];
};
export function EntityBoardActionBar({ children }: OwnProps) {
const selectedBoardCards = useRecoilValue(selectedBoardCardIdsState);
return <ActionBar selectedIds={selectedBoardCards}>{children}</ActionBar>;
}

View File

@ -0,0 +1,31 @@
import { Draggable } from '@hello-pangea/dnd';
import { BoardOptions } from '../types/BoardOptions';
export function EntityBoardCard({
boardOptions,
pipelineProgressId,
index,
}: {
boardOptions: BoardOptions;
pipelineProgressId: string;
index: number;
}) {
return (
<Draggable
key={pipelineProgressId}
draggableId={pipelineProgressId}
index={index}
>
{(draggableProvided) => (
<div
ref={draggableProvided?.innerRef}
{...draggableProvided?.dragHandleProps}
{...draggableProvided?.draggableProps}
>
{boardOptions.cardComponent}
</div>
)}
</Draggable>
);
}

View File

@ -0,0 +1,123 @@
import { useContext } from 'react';
import styled from '@emotion/styled';
import { Draggable, Droppable, DroppableProvided } from '@hello-pangea/dnd';
import { useRecoilValue } from 'recoil';
import { BoardColumn } from '@/ui/board/components/BoardColumn';
import { BoardCardIdContext } from '@/ui/board/states/BoardCardIdContext';
import { BoardColumnIdContext } from '@/ui/board/states/BoardColumnIdContext';
import { BoardColumnDefinition } from '@/ui/board/types/BoardColumnDefinition';
import { RecoilScope } from '@/ui/utilities/recoil-scope/components/RecoilScope';
import { boardCardIdsByColumnIdFamilyState } from '../states/boardCardIdsByColumnIdFamilyState';
import { boardColumnTotalsFamilySelector } from '../states/boardColumnTotalsFamilySelector';
import { BoardOptions } from '../types/BoardOptions';
import { EntityBoardCard } from './EntityBoardCard';
const StyledPlaceholder = styled.div`
min-height: 1px;
`;
const StyledNewCardButtonContainer = styled.div`
padding-bottom: ${({ theme }) => theme.spacing(4)};
`;
const StyledColumnCardsContainer = styled.div`
display: flex;
flex: 1;
flex-direction: column;
`;
const BoardColumnCardsContainer = ({
children,
droppableProvided,
}: {
children: React.ReactNode;
droppableProvided: DroppableProvided;
}) => {
return (
<StyledColumnCardsContainer
ref={droppableProvided?.innerRef}
{...droppableProvided?.droppableProps}
>
{children}
<StyledPlaceholder>{droppableProvided?.placeholder}</StyledPlaceholder>
</StyledColumnCardsContainer>
);
};
export function EntityBoardColumn({
column,
boardOptions,
onEditColumnTitle,
onEditColumnColor,
}: {
column: BoardColumnDefinition;
boardOptions: BoardOptions;
onEditColumnTitle: (columnId: string, title: string) => void;
onEditColumnColor: (columnId: string, color: string) => void;
}) {
const boardColumnId = useContext(BoardColumnIdContext) ?? '';
const boardColumnTotal = useRecoilValue(
boardColumnTotalsFamilySelector(column.id),
);
const cardIds = useRecoilValue(
boardCardIdsByColumnIdFamilyState(boardColumnId ?? ''),
);
function handleEditColumnTitle(value: string) {
onEditColumnTitle(boardColumnId, value);
}
function handleEditColumnColor(newColor: string) {
onEditColumnColor(boardColumnId, newColor);
}
return (
<Droppable droppableId={column.id}>
{(droppableProvided) => (
<BoardColumn
onColumnColorEdit={handleEditColumnColor}
onTitleEdit={handleEditColumnTitle}
title={column.title}
color={column.colorCode}
pipelineStageId={column.id}
totalAmount={boardColumnTotal}
isFirstColumn={column.index === 0}
numChildren={cardIds.length}
>
<BoardColumnCardsContainer droppableProvided={droppableProvided}>
{cardIds.map((cardId, index) => (
<BoardCardIdContext.Provider value={cardId} key={cardId}>
<EntityBoardCard
index={index}
pipelineProgressId={cardId}
boardOptions={boardOptions}
/>
</BoardCardIdContext.Provider>
))}
<Draggable draggableId={`new-${column.id}`} index={cardIds.length}>
{(draggableProvided) => (
<div
ref={draggableProvided?.innerRef}
{...{
...draggableProvided.dragHandleProps,
draggable: false,
}}
{...draggableProvided?.draggableProps}
>
<StyledNewCardButtonContainer>
<RecoilScope>{boardOptions.newCardComponent}</RecoilScope>
</StyledNewCardButtonContainer>
</div>
)}
</Draggable>
</BoardColumnCardsContainer>
</BoardColumn>
)}
</Droppable>
);
}

View File

@ -0,0 +1,9 @@
import styled from '@emotion/styled';
export const StyledBoard = styled.div`
border-radius: ${({ theme }) => theme.spacing(2)};
display: flex;
flex: 1;
flex-direction: row;
padding-left: ${({ theme }) => theme.spacing(2)};
`;

View File

@ -1,59 +1,53 @@
import { DropResult } from '@hello-pangea/dnd';
import { getOptimisticlyUpdatedBoard } from '../Board';
// TODO: refactor this test with Recoil
describe('getOptimisticlyUpdatedBoard', () => {
it('should return a new board with the updated cell', () => {
const initialColumn1: string[] = ['item-1', 'item-2', 'item-3'];
const initialColumn2: string[] = ['item-4', 'item-5'];
const finalColumn1: string[] = ['item-2', 'item-3'];
const finalColumn2: string[] = ['item-4', 'item-1', 'item-5'];
const dropResult = {
source: {
droppableId: 'column-1',
index: 0,
},
destination: {
droppableId: 'column-2',
index: 1,
},
} as DropResult;
const initialBoard = [
{
id: 'column-1',
title: 'My Column',
pipelineStageId: 'column-1',
pipelineProgressIds: initialColumn1,
},
{
id: 'column-2',
title: 'My Column',
pipelineStageId: 'column-2',
pipelineProgressIds: initialColumn2,
},
];
const updatedBoard = getOptimisticlyUpdatedBoard(initialBoard, dropResult);
const finalBoard = [
{
id: 'column-1',
title: 'My Column',
pipelineStageId: 'column-1',
pipelineProgressIds: finalColumn1,
},
{
id: 'column-2',
title: 'My Column',
pipelineStageId: 'column-2',
pipelineProgressIds: finalColumn2,
},
];
expect(updatedBoard).toEqual(finalBoard);
expect(updatedBoard).not.toBe(initialBoard);
// const initialColumn1: string[] = ['item-1', 'item-2', 'item-3'];
// const initialColumn2: string[] = ['item-4', 'item-5'];
// const finalColumn1: string[] = ['item-2', 'item-3'];
// const finalColumn2: string[] = ['item-4', 'item-1', 'item-5'];
// const dropResult = {
// source: {
// droppableId: 'column-1',
// index: 0,
// },
// destination: {
// droppableId: 'column-2',
// index: 1,
// },
// } as DropResult;
// const initialBoard = [
// {
// id: 'column-1',
// title: 'My Column',
// pipelineStageId: 'column-1',
// pipelineProgressIds: initialColumn1,
// },
// {
// id: 'column-2',
// title: 'My Column',
// pipelineStageId: 'column-2',
// pipelineProgressIds: initialColumn2,
// },
// ];
// const updatedBoard = u(
// initialBoard,
// dropResult,
// );
// const finalBoard = [
// {
// id: 'column-1',
// title: 'My Column',
// pipelineStageId: 'column-1',
// pipelineProgressIds: finalColumn1,
// },
// {
// id: 'column-2',
// title: 'My Column',
// pipelineStageId: 'column-2',
// pipelineProgressIds: finalColumn2,
// },
// ];
// expect(updatedBoard).toEqual(finalBoard);
// expect(updatedBoard).not.toBe(initialBoard);
});
});

View File

@ -0,0 +1,86 @@
import { DropResult } from '@hello-pangea/dnd'; // Atlassian dnd does not support StrictMode from RN 18, so we use a fork @hello-pangea/dnd https://github.com/atlassian/react-beautiful-dnd/issues/2350
import { useRecoilCallback } from 'recoil';
import { boardCardIdsByColumnIdFamilyState } from '../states/boardCardIdsByColumnIdFamilyState';
import { boardColumnsState } from '../states/boardColumnsState';
import { BoardColumnDefinition } from '../types/BoardColumnDefinition';
export function useUpdateBoardCardIds() {
return useRecoilCallback(
({ snapshot, set }) =>
(result: DropResult) => {
const currentBoardColumns = snapshot
.getLoadable(boardColumnsState)
.valueOrThrow();
const newBoardColumns = [...currentBoardColumns];
const { destination, source } = result;
if (!destination) return;
const sourceColumnIndex = newBoardColumns.findIndex(
(boardColumn: BoardColumnDefinition) =>
boardColumn.id === source.droppableId,
);
const sourceColumn = newBoardColumns[sourceColumnIndex];
const destinationColumnIndex = newBoardColumns.findIndex(
(boardColumn: BoardColumnDefinition) =>
boardColumn.id === destination.droppableId,
);
const destinationColumn = newBoardColumns[destinationColumnIndex];
if (!destinationColumn || !sourceColumn) return;
const sourceCardIds = [
...snapshot
.getLoadable(boardCardIdsByColumnIdFamilyState(sourceColumn.id))
.valueOrThrow(),
];
const destinationCardIds = [
...snapshot
.getLoadable(
boardCardIdsByColumnIdFamilyState(destinationColumn.id),
)
.valueOrThrow(),
];
const destinationIndex =
destination.index >= destinationCardIds.length
? destinationCardIds.length - 1
: destination.index;
if (sourceColumn.id === destinationColumn.id) {
const [deletedCardId] = sourceCardIds.splice(source.index, 1);
sourceCardIds.splice(destinationIndex, 0, deletedCardId);
set(
boardCardIdsByColumnIdFamilyState(sourceColumn.id),
sourceCardIds,
);
} else {
const [removedCardId] = sourceCardIds.splice(source.index, 1);
destinationCardIds.splice(destinationIndex, 0, removedCardId);
set(
boardCardIdsByColumnIdFamilyState(sourceColumn.id),
sourceCardIds,
);
set(
boardCardIdsByColumnIdFamilyState(destinationColumn.id),
destinationCardIds,
);
}
return newBoardColumns;
},
[],
);
}

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const BoardCardContext = createContext<string | null>(null);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const BoardCardIdContext = createContext<string | null>(null);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const BoardColumnContext = createContext<string | null>(null);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const BoardColumnIdContext = createContext<string | null>(null);

View File

@ -0,0 +1,5 @@
import { createContext } from 'react';
import { BoardOptions } from '@/ui/board/types/BoardOptions';
export const BoardOptionsContext = createContext<BoardOptions | null>(null);

View File

@ -0,0 +1,6 @@
import { atomFamily } from 'recoil';
export const boardCardIdsByColumnIdFamilyState = atomFamily<string[], string>({
key: 'boardCardIdsByColumnIdFamilyState',
default: [],
});

View File

@ -0,0 +1,28 @@
import { selectorFamily } from 'recoil';
import { companyProgressesFamilyState } from '@/companies/states/companyProgressesFamilyState';
import { boardCardIdsByColumnIdFamilyState } from './boardCardIdsByColumnIdFamilyState';
// TODO: this state should be computed during the synchronization hook and put in a generic
// boardColumnTotalsFamilyState indexed by columnId.
export const boardColumnTotalsFamilySelector = selectorFamily({
key: 'boardColumnTotalsFamilySelector',
get:
(pipelineStageId: string) =>
({ get }) => {
const cardIds = get(boardCardIdsByColumnIdFamilyState(pipelineStageId));
const pipelineProgresses = cardIds.map((pipelineProgressId: string) =>
get(companyProgressesFamilyState(pipelineProgressId)),
);
const pipelineStageTotal: number =
pipelineProgresses?.reduce(
(acc: number, curr: any) => acc + curr?.pipelineProgress.amount,
0,
) || 0;
return pipelineStageTotal;
},
});

View File

@ -0,0 +1,8 @@
import { atom } from 'recoil';
import { BoardColumnDefinition } from '@/ui/board/types/BoardColumnDefinition';
export const boardColumnsState = atom<BoardColumnDefinition[]>({
key: 'boardColumnsState',
default: [],
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const isBoardLoadedState = atom<boolean>({
key: 'isBoardLoadedState',
default: false,
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const selectedBoardCardIdsState = atom<string[]>({
key: 'selectedBoardCardIdsState',
default: [],
});

View File

@ -0,0 +1,6 @@
export type BoardColumnDefinition = {
id: string;
title: string;
index: number;
colorCode?: string;
};

View File

@ -0,0 +1,11 @@
import { FilterDefinitionByEntity } from '@/ui/filter-n-sort/types/FilterDefinitionByEntity';
import { SortType } from '@/ui/filter-n-sort/types/interface';
import { PipelineProgress } from '~/generated/graphql';
import { PipelineProgressOrderByWithRelationInput as PipelineProgresses_Order_By } from '~/generated/graphql';
export type BoardOptions = {
newCardComponent: React.ReactNode;
cardComponent: React.ReactNode;
filters: FilterDefinitionByEntity<PipelineProgress>[];
sorts: Array<SortType<PipelineProgresses_Order_By>>;
};

View File

@ -0,0 +1,8 @@
import { atomFamily } from 'recoil';
import { Filter } from '../types/Filter';
export const sortScopedState = atomFamily<Filter[], string>({
key: 'sortScopedState',
default: [],
});

View File

@ -42,8 +42,6 @@ export function GenericEditableNumberCellEditMode({ viewField }: OwnProps) {
throw new Error('Number too big');
}
console.log({ numberValue });
setFieldValue(numberValue.toString());
if (currentRowEntityId && updateField) {