Skip to content

Commit

Permalink
feat(closepositions): hook up close positions to tradebox close posit…
Browse files Browse the repository at this point in the history
…ion dialog (#407)

* functional

* Remove flag

* fix chart tvwidget error

* Remove unnecessary change

* review comments

* update strings

* review comments
  • Loading branch information
moo-onthelawn authored Apr 5, 2024
1 parent a9e523f commit ff19947
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 69 deletions.
5 changes: 4 additions & 1 deletion src/components/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@ const TableRoot = <TableRowData extends object | CustomRowConfig, TableRowKey ex
key={row.key}
item={row}
state={state}
hasRowAction={!!(props.onRowAction)}
// shouldRowRender={props.shouldRowRender}
{...props.getRowAttributes?.(row.value!)}
withGradientCardRows={props.withGradientCardRows}
Expand Down Expand Up @@ -539,6 +540,7 @@ export const TableRow = <TableRowData extends object>({
children,
state,
// shouldRowRender,
hasRowAction,
withGradientCardRows,
withFocusStickyRows,
withScrollSnapRows,
Expand All @@ -548,14 +550,15 @@ export const TableRow = <TableRowData extends object>({
children: React.ReactNode;
state: TableState<TableRowData>;
// shouldRowRender?: (prevRowData: TableRowData, currentRowData: TableRowData) => boolean;
hasRowAction?: boolean;
withGradientCardRows?: boolean;
withFocusStickyRows?: boolean;
withScrollSnapRows?: boolean;
}) => {
const ref = React.useRef<HTMLTableRowElement>(null);
const selectionManager = state.selectionManager;
const isSelected = selectionManager.isSelected(item.key);
const isClickable = selectionManager.selectionBehavior === 'toggle';
const isClickable = selectionManager.selectionBehavior === 'toggle' && hasRowAction;

const { rowProps, isPressed } = useTableRow(
{
Expand Down
17 changes: 16 additions & 1 deletion src/hooks/useCurrentMarketId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ import { useEffect, useMemo } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { useMatch, useNavigate } from 'react-router-dom';

import { SubaccountPosition } from '@/constants/abacus';
import { TradeBoxDialogTypes } from '@/constants/dialogs';
import { LocalStorageKey } from '@/constants/localStorage';
import { DEFAULT_MARKETID } from '@/constants/markets';
import { AppRoute } from '@/constants/routes';

import { useLocalStorage } from '@/hooks/useLocalStorage';

import { getOpenPositions, getPositionDetails } from '@/state/accountSelectors';
import { getSelectedNetwork } from '@/state/appSelectors';
import { closeDialogInTradeBox } from '@/state/dialogs';
import { closeDialogInTradeBox, openDialogInTradeBox } from '@/state/dialogs';
import { getActiveTradeBoxDialog } from '@/state/dialogsSelectors';
import { setCurrentMarketId } from '@/state/perpetuals';
import { getMarketIds } from '@/state/perpetualsSelectors';

Expand All @@ -22,8 +26,10 @@ export const useCurrentMarketId = () => {
const { marketId } = match?.params ?? {};
const dispatch = useDispatch();
const selectedNetwork = useSelector(getSelectedNetwork);
const openPositions = useSelector(getOpenPositions, shallowEqual);
const marketIds = useSelector(getMarketIds, shallowEqual);
const hasMarketIds = marketIds.length > 0;
const activeTradeBoxDialog = useSelector(getActiveTradeBoxDialog);

const [lastViewedMarket, setLastViewedMarket] = useLocalStorage({
key: LocalStorageKey.LastViewedMarket,
Expand Down Expand Up @@ -60,6 +66,15 @@ export const useCurrentMarketId = () => {
setLastViewedMarket(marketId);
dispatch(setCurrentMarketId(marketId));
dispatch(closeDialogInTradeBox());
if (activeTradeBoxDialog) {
// Reopen active trade box dialog with cleared values
if (
activeTradeBoxDialog.type === TradeBoxDialogTypes.ClosePosition &&
openPositions?.find((position: SubaccountPosition) => position.id === marketId)
) {
dispatch(openDialogInTradeBox(activeTradeBoxDialog));
}
}
}
}
}, [hasMarketIds, marketId]);
Expand Down
4 changes: 0 additions & 4 deletions src/lib/testFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ class TestFlags {
return this.queryParams.address;
}

get closePositionsFromPositionsTable() {
return !!this.queryParams.closepositions;
}

get configureSlTpFromPositionsTable() {
return !!this.queryParams.sltp;
}
Expand Down
7 changes: 4 additions & 3 deletions src/pages/portfolio/Overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { ContentSectionHeader } from '@/components/ContentSectionHeader';
import { PositionsTable, PositionsTableColumnKey } from '@/views/tables/PositionsTable';

import {
calculateShouldRenderActionsInPositionsTable,
calculateShouldRenderTriggersInPositionsTable,
} from '@/state/accountCalculators';

Expand All @@ -26,7 +25,8 @@ export const Overview = () => {
const navigate = useNavigate();

const shouldRenderTriggers = useSelector(calculateShouldRenderTriggersInPositionsTable);
const shouldRenderActions = useSelector(calculateShouldRenderActionsInPositionsTable);
// TODO: CT-503
// const shouldRenderActions = useSelector(calculateShouldRenderActionsInPositionsTable);

return (
<div>
Expand Down Expand Up @@ -55,7 +55,8 @@ export const Overview = () => {
PositionsTableColumnKey.RealizedPnl,
PositionsTableColumnKey.AverageOpenAndClose,
shouldRenderTriggers && PositionsTableColumnKey.Triggers,
shouldRenderActions && PositionsTableColumnKey.Actions,
// TODO: CT-503 re-enable when close positions dialog is created
// shouldRenderActions && PositionsTableColumnKey.Actions,
].filter(isTruthy)
}
currentRoute={AppRoute.Portfolio}
Expand Down
7 changes: 4 additions & 3 deletions src/pages/portfolio/Positions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { ContentSectionHeader } from '@/components/ContentSectionHeader';
import { PositionsTable, PositionsTableColumnKey } from '@/views/tables/PositionsTable';

import {
calculateShouldRenderActionsInPositionsTable,
calculateShouldRenderTriggersInPositionsTable,
} from '@/state/accountCalculators';

Expand All @@ -24,7 +23,8 @@ export const Positions = () => {
const navigate = useNavigate();

const shouldRenderTriggers = useSelector(calculateShouldRenderTriggersInPositionsTable);
const shouldRenderActions = useSelector(calculateShouldRenderActionsInPositionsTable);
// TODO: CT-503
// const shouldRenderActions = useSelector(calculateShouldRenderActionsInPositionsTable);

return (
<AttachedExpandingSection>
Expand All @@ -49,7 +49,8 @@ export const Positions = () => {
PositionsTableColumnKey.RealizedPnl,
PositionsTableColumnKey.AverageOpenAndClose,
shouldRenderTriggers && PositionsTableColumnKey.Triggers,
shouldRenderActions && PositionsTableColumnKey.Actions,
// TODO: CT-503 re-enable when close positions dialog is created
// shouldRenderActions && PositionsTableColumnKey.Actions,
].filter(isTruthy)
}
currentRoute={`${AppRoute.Portfolio}/${PortfolioRoute.Positions}`}
Expand Down
55 changes: 27 additions & 28 deletions src/pages/trade/HorizontalPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,36 +112,35 @@ export const HorizontalPanel = ({ isOpen = true, setIsOpen }: ElementProps) => {

tag: showCurrentMarket ? null : shortenNumberForDisplay(numTotalPositions),

content: showCurrentMarket ? (
content: isTablet ? (
<PositionInfo showNarrowVariation={isTablet} />
) : (
<>
<PositionsTable
columnKeys={
isTablet
? [
PositionsTableColumnKey.Details,
PositionsTableColumnKey.IndexEntry,
PositionsTableColumnKey.PnL,
]
: [
PositionsTableColumnKey.Market,
PositionsTableColumnKey.Side,
PositionsTableColumnKey.Size,
PositionsTableColumnKey.Leverage,
PositionsTableColumnKey.LiquidationAndOraclePrice,
testFlags.isolatedMargin && PositionsTableColumnKey.Margin,
PositionsTableColumnKey.UnrealizedPnl,
PositionsTableColumnKey.RealizedPnl,
PositionsTableColumnKey.AverageOpenAndClose,
shouldRenderTriggers && PositionsTableColumnKey.Triggers,
shouldRenderActions && PositionsTableColumnKey.Actions,
].filter(isTruthy)
}
onNavigate={() => setView(PanelView.CurrentMarket)}
navigateToOrders={onViewOrders}
/>
</>
<PositionsTable
currentMarket={showCurrentMarket ? currentMarketId : undefined}
columnKeys={
isTablet
? [
PositionsTableColumnKey.Details,
PositionsTableColumnKey.IndexEntry,
PositionsTableColumnKey.PnL,
]
: [
PositionsTableColumnKey.Market,
PositionsTableColumnKey.Side,
PositionsTableColumnKey.Size,
PositionsTableColumnKey.Leverage,
PositionsTableColumnKey.LiquidationAndOraclePrice,
testFlags.isolatedMargin && PositionsTableColumnKey.Margin,
PositionsTableColumnKey.UnrealizedPnl,
PositionsTableColumnKey.RealizedPnl,
PositionsTableColumnKey.AverageOpenAndClose,
shouldRenderTriggers && PositionsTableColumnKey.Triggers,
shouldRenderActions && PositionsTableColumnKey.Actions,
].filter(isTruthy)
}
onNavigate={() => setView(PanelView.CurrentMarket)}
navigateToOrders={onViewOrders}
/>
),
},
{
Expand Down
4 changes: 1 addition & 3 deletions src/state/accountCalculators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,5 @@ export const calculateShouldRenderTriggersInPositionsTable = createSelector(
*/
export const calculateShouldRenderActionsInPositionsTable = createSelector(
[calculateIsAccountViewOnly],
(isAccountViewOnly: boolean) =>
!isAccountViewOnly &&
(testFlags.closePositionsFromPositionsTable || testFlags.configureSlTpFromPositionsTable)
(isAccountViewOnly: boolean) => !isAccountViewOnly
);
3 changes: 1 addition & 2 deletions src/views/PositionInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { NumberSign, USD_DECIMALS } from '@/constants/numbers';

import { useBreakpoints, useStringGetter } from '@/hooks';

import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins';

import { Button } from '@/components/Button';
Expand Down Expand Up @@ -63,7 +62,7 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo
const currentMarketAssetData = useSelector(getCurrentMarketAssetData, shallowEqual);
const currentMarketConfigs = useSelector(getCurrentMarketConfig, shallowEqual);
const activeDialog = useSelector(getActiveDialog, shallowEqual);
const activeTradeBoxDialog = useSelector(getActiveTradeBoxDialog, shallowEqual);
const activeTradeBoxDialog = useSelector(getActiveTradeBoxDialog);
const currentMarketPosition = useSelector(getCurrentMarketPositionData, shallowEqual);
const isLoading = useSelector(calculateIsAccountLoading);

Expand Down
29 changes: 19 additions & 10 deletions src/views/tables/PositionsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ type ElementProps = {
columnKeys: PositionsTableColumnKey[];
columnWidths?: Partial<Record<PositionsTableColumnKey, ColumnSize>>;
currentRoute?: string;
currentMarket?: string;
onNavigate?: () => void;
navigateToOrders: (market: string) => void;
};
Expand All @@ -348,6 +349,7 @@ export const PositionsTable = ({
columnKeys,
columnWidths,
currentRoute,
currentMarket,
onNavigate,
navigateToOrders,
withGradientCardRows,
Expand All @@ -359,9 +361,12 @@ export const PositionsTable = ({
const isAccountViewOnly = useSelector(calculateIsAccountViewOnly);
const perpetualMarkets = useSelector(getPerpetualMarkets, shallowEqual) || {};
const assets = useSelector(getAssets, shallowEqual) || {};
const openPositions = useSelector(getExistingOpenPositions, shallowEqual) || [];
const openOrders = useSelector(getSubaccountOpenOrders, shallowEqual) || [];

const openPositions = useSelector(getExistingOpenPositions, shallowEqual) || [];
const marketPosition = openPositions.find((position) => position.id == currentMarket);
const positions = currentMarket ? (marketPosition ? [marketPosition] : []) : openPositions;

const stopLossOrders: SubaccountOrder[] = [];
const takeProfitOrders: SubaccountOrder[] = [];

Expand All @@ -375,7 +380,7 @@ export const PositionsTable = ({

const positionsData = useMemo(
() =>
openPositions.map((position: SubaccountPosition) => ({
positions.map((position: SubaccountPosition) => ({
tickSizeDecimals:
perpetualMarkets?.[position.id]?.configs?.tickSizeDecimals || USD_DECIMALS,
asset: assets?.[position.assetId],
Expand All @@ -384,12 +389,12 @@ export const PositionsTable = ({
takeProfitOrders: takeProfitOrders.filter((order) => order.marketId === position.id),
...position,
})),
[openPositions, perpetualMarkets, assets, openOrders]
[positions, perpetualMarkets, assets, openOrders]
);

return (
<Styled.Table
key="positions"
key={currentMarket ?? 'positions'}
label="Positions"
defaultSortDescriptor={{
column: 'market',
Expand All @@ -406,12 +411,16 @@ export const PositionsTable = ({
})
)}
getRowKey={(row: PositionTableRow) => row.id}
onRowAction={(market: string) => {
navigate(`${AppRoute.Trade}/${market}`, {
state: { from: currentRoute },
});
onNavigate?.();
}}
onRowAction={
currentMarket
? null
: (market: string) => {
navigate(`${AppRoute.Trade}/${market}`, {
state: { from: currentRoute },
});
onNavigate?.();
}
}
getRowAttributes={(row: PositionTableRow) => ({
'data-side': row.side.current,
})}
Expand Down
Loading

0 comments on commit ff19947

Please sign in to comment.