2022-09-02 20:53:00 +00:00
|
|
|
import { useCallback, useMemo, useRef } from 'react';
|
2022-03-30 00:01:34 +00:00
|
|
|
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
|
|
|
|
import { useDataProvider } from '@vegaprotocol/react-helpers';
|
2022-08-26 15:39:40 +00:00
|
|
|
import { positionsMetricsDataProvider as dataProvider } from './positions-data-providers';
|
|
|
|
import type { Position } from './positions-data-providers';
|
2022-09-02 20:53:00 +00:00
|
|
|
import { Positions } from './positions';
|
|
|
|
import { useClosePosition } from '../';
|
2022-03-30 00:01:34 +00:00
|
|
|
|
|
|
|
interface PositionsManagerProps {
|
|
|
|
partyId: string;
|
|
|
|
}
|
|
|
|
|
2022-09-02 20:53:00 +00:00
|
|
|
const getSymbols = (positions: Position[]) =>
|
|
|
|
Array.from(new Set(positions.map((position) => position.assetSymbol))).sort();
|
|
|
|
|
2022-03-30 00:01:34 +00:00
|
|
|
export const PositionsManager = ({ partyId }: PositionsManagerProps) => {
|
|
|
|
const variables = useMemo(() => ({ partyId }), [partyId]);
|
2022-09-02 20:53:00 +00:00
|
|
|
const assetSymbols = useRef<string[] | undefined>();
|
|
|
|
const { submit, TransactionDialog } = useClosePosition();
|
|
|
|
const onClose = useCallback(
|
|
|
|
(position: Position) => {
|
|
|
|
submit(position);
|
|
|
|
},
|
|
|
|
[submit]
|
|
|
|
);
|
2022-08-26 15:39:40 +00:00
|
|
|
const update = useCallback(({ data }: { data: Position[] | null }) => {
|
2022-09-02 20:53:00 +00:00
|
|
|
if (data?.length) {
|
|
|
|
const newAssetSymbols = getSymbols(data);
|
|
|
|
if (
|
|
|
|
!newAssetSymbols.every(
|
|
|
|
(symbol) =>
|
|
|
|
assetSymbols.current && assetSymbols.current.includes(symbol)
|
|
|
|
)
|
|
|
|
) {
|
|
|
|
return false;
|
|
|
|
}
|
2022-08-16 07:18:55 +00:00
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}, []);
|
2022-08-26 15:39:40 +00:00
|
|
|
const { data, error, loading } = useDataProvider<Position[], never>({
|
|
|
|
dataProvider,
|
|
|
|
update,
|
|
|
|
variables,
|
|
|
|
});
|
2022-03-30 00:01:34 +00:00
|
|
|
return (
|
2022-09-02 20:53:00 +00:00
|
|
|
<>
|
|
|
|
<AsyncRenderer loading={loading} error={error} data={assetSymbols}>
|
|
|
|
{data &&
|
|
|
|
getSymbols(data)?.map((assetSymbol) => (
|
|
|
|
<Positions
|
|
|
|
partyId={partyId}
|
|
|
|
assetSymbol={assetSymbol}
|
|
|
|
key={assetSymbol}
|
|
|
|
onClose={onClose}
|
|
|
|
/>
|
|
|
|
))}
|
|
|
|
</AsyncRenderer>
|
|
|
|
<TransactionDialog>
|
|
|
|
<p>Your position was not closed! This is still not implemented. </p>
|
|
|
|
</TransactionDialog>
|
|
|
|
</>
|
2022-03-30 00:01:34 +00:00
|
|
|
);
|
|
|
|
};
|