All files / libs/lti/components/src/lib/grants/OutcomeWaterfallChart OutcomeWaterfallChart.tsx

10.71% Statements 6/56
0% Branches 0/45
0% Functions 0/21
10.71% Lines 6/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453                                                                          51x 51x   51x     51x                                                                                                                                                                                             51x                                                                                                                           51x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { css, useTheme } from '@emotion/react';
import { memo, useMemo } from 'react';
import { FormattedMessage, useIntl, type IntlShape } from 'react-intl';
import { Bar, BarChart, useXAxisScale, useYAxisScale, XAxis } from 'recharts';
 
import { Group, Stack, Typography, useColorSchemeContext } from '@allshares/studio-design-system';
import { type LtiGrantWithUser } from '@amalia/lti/types';
 
import { WaterfallXAxisTick } from './WaterfallXAxisTick';
 
interface OutcomeWaterfallChartProps {
  readonly grantsForUser: LtiGrantWithUser;
}
 
type OutcomeWaterfallChartLabelPosition = 'bottom' | 'top';
 
type OutcomeWaterfallChartDatum = {
  readonly name: string;
  readonly offset: number;
  readonly allocationShares: number;
  readonly redeemedShares: number;
  readonly earnedShares: number;
  readonly remainingUnearnedShares: number;
  readonly labelValue: number;
  readonly labelAnchorValue: number;
  readonly labelPosition: OutcomeWaterfallChartLabelPosition;
  readonly connectorValue: number | null;
};
 
interface OutcomeWaterfallChartAnnotationsProps {
  readonly chartData: OutcomeWaterfallChartDatum[];
  readonly formatNumber: IntlShape['formatNumber'];
  readonly barSize: number;
  readonly labelColor: string;
  readonly connectorColor: string;
}
 
const WATERFALL_BAR_SIZE = 40;
const WATERFALL_LABEL_OFFSET = 10;
 
const formatOutcomeWaterfallChartLabel = (value: number, formatNumber: IntlShape['formatNumber']) =>
  value < 0 ? formatNumber(-Math.abs(value)) : formatNumber(value);
 
const OutcomeWaterfallChartAnnotations = memo(function OutcomeWaterfallChartAnnotations({
  chartData,
  formatNumber,
  barSize,
  labelColor,
  connectorColor,
}: OutcomeWaterfallChartAnnotationsProps) {
  const theme = useTheme();
  const xScale = useXAxisScale();
  const yScale = useYAxisScale();
 
  const chartCoordinates = useMemo(
    () =>
      chartData.map((datum) => {
        const centerX = xScale?.(datum.name, { position: 'middle' });
        const labelY = yScale?.(datum.labelAnchorValue);
        const connectorY = datum.connectorValue === null ? null : yScale?.(datum.connectorValue);
 
        if (
          centerX === undefined ||
          labelY === undefined ||
          (datum.connectorValue !== null && connectorY === undefined)
        ) {
          return null;
        }
 
        return {
          centerX,
          labelY,
          connectorY,
        };
      }),
    [chartData, xScale, yScale],
  );
 
  return (
    <g
      aria-hidden
      pointerEvents="none"
    >
      {chartData.slice(0, -1).map((datum, index) => {
        const currentCoordinates = chartCoordinates[index];
        const nextCoordinates = chartCoordinates[index + 1];
 
        if (!currentCoordinates || !nextCoordinates || currentCoordinates.connectorY === null) {
          return null;
        }
 
        return (
          <line
            key={`${datum.name}-connector`}
            className="outcome-waterfall-chart-connector"
            shapeRendering="crispEdges"
            stroke={connectorColor}
            strokeWidth={0.3}
            x1={currentCoordinates.centerX + barSize / 2}
            x2={nextCoordinates.centerX - barSize / 2}
            y1={currentCoordinates.connectorY}
            y2={currentCoordinates.connectorY}
          />
        );
      })}
 
      {chartData.map((datum, index) => {
        const coordinates = chartCoordinates[index];
 
        if (!coordinates) {
          return null;
        }
 
        return (
          <text
            key={`${datum.name}-label`}
            className="outcome-waterfall-chart-label"
            dominantBaseline={datum.labelPosition === 'top' ? 'text-after-edge' : 'hanging'}
            textAnchor="middle"
            x={coordinates.centerX}
            css={css`
              ${theme.ds.typographies.bodySmallMedium}
              fill: ${labelColor};
            `}
            y={
              datum.labelPosition === 'top'
                ? coordinates.labelY - WATERFALL_LABEL_OFFSET
                : coordinates.labelY + WATERFALL_LABEL_OFFSET
            }
          >
            {formatOutcomeWaterfallChartLabel(datum.labelValue, formatNumber)}
          </text>
        );
      })}
    </g>
  );
});
 
const buildOutcomeWaterfallChartData = ({
  allocationLabel,
  redemptionLabel,
  provisionalEarnedSharesLabel,
  nbShares,
  employmentAdjustment,
  outcomeNbShares,
}: {
  readonly allocationLabel: string;
  readonly redemptionLabel: string;
  readonly provisionalEarnedSharesLabel: string;
  readonly nbShares: number;
  readonly employmentAdjustment: number | null;
  readonly outcomeNbShares: number | null;
}): OutcomeWaterfallChartDatum[] => {
  const redeemedShares = employmentAdjustment ?? 0;
  const postRedemptionShares = Math.max(nbShares - redeemedShares, 0);
  const earnedShares = Math.min(outcomeNbShares ?? 0, postRedemptionShares);
  const remainingUnearnedShares = Math.max(postRedemptionShares - earnedShares, 0);
 
  const redemptionLabelPosition = nbShares - redeemedShares <= nbShares * 0.1 ? 'top' : 'bottom';
 
  return [
    {
      name: allocationLabel,
      offset: 0,
      allocationShares: nbShares,
      redeemedShares: 0,
      earnedShares: 0,
      remainingUnearnedShares: 0,
      labelValue: nbShares,
      labelAnchorValue: nbShares,
      labelPosition: 'top',
      connectorValue: nbShares,
    },
    employmentAdjustment !== null && {
      name: redemptionLabel,
      offset: postRedemptionShares,
      allocationShares: 0,
      redeemedShares,
      earnedShares: 0,
      remainingUnearnedShares: 0,
      labelValue: -redeemedShares,
      labelAnchorValue: redemptionLabelPosition === 'top' ? nbShares : postRedemptionShares,
      labelPosition: redemptionLabelPosition,
      connectorValue: postRedemptionShares,
    },
    {
      name: provisionalEarnedSharesLabel,
      offset: 0,
      allocationShares: 0,
      redeemedShares: 0,
      earnedShares,
      remainingUnearnedShares,
      labelValue: earnedShares,
      labelAnchorValue: postRedemptionShares,
      labelPosition: 'top',
      connectorValue: null,
    },
  ].filter(Boolean);
};
 
export const OutcomeWaterfallChart = memo(function OutcomeWaterfallChart({
  grantsForUser,
}: OutcomeWaterfallChartProps) {
  const { formatMessage, formatNumber } = useIntl();
  const theme = useTheme();
  const { colorScheme } = useColorSchemeContext();
 
  const allocationColor = theme.ds.colors.primary[50];
  const earnedSharesColor = theme.ds.colors.primary[400];
  const annotationColor = colorScheme === 'dark' ? theme.ds.colors.gray[400] : theme.ds.colors.gray[800];
  const connectorColor = colorScheme === 'dark' ? theme.ds.colors.gray[200] : theme.ds.colors.gray[500];
 
  const chartData = useMemo(
    () =>
      buildOutcomeWaterfallChartData({
        allocationLabel: formatMessage({ defaultMessage: 'Allocation' }),
        redemptionLabel: formatMessage({ defaultMessage: 'Redemption' }),
        provisionalEarnedSharesLabel: formatMessage({ defaultMessage: 'Prov. earned shares' }),
        nbShares: grantsForUser.nbShares,
        employmentAdjustment: grantsForUser.employmentAdjustment,
        outcomeNbShares: grantsForUser.outcomeNbShares,
      }),
    [formatMessage, grantsForUser.nbShares, grantsForUser.employmentAdjustment, grantsForUser.outcomeNbShares],
  );
 
  return (
    <Stack
      gap={32}
      css={css`
        padding: 24px 72px 40px 72px;
      `}
    >
      <BarChart
        barSize={WATERFALL_BAR_SIZE}
        data={chartData}
        margin={{ top: 30, right: 20, bottom: 0, left: 0 }}
        style={{ width: '350px', height: '160px', aspectRatio: 1 }}
      >
        <XAxis
          dataKey="name"
          interval={0}
          padding={{ left: -(WATERFALL_BAR_SIZE - 10), right: -(WATERFALL_BAR_SIZE - 10) }}
          shapeRendering="crispEdges"
          tick={<WaterfallXAxisTick />}
          tickLine={false}
          axisLine={{
            stroke: colorScheme === 'dark' ? theme.ds.colors.gray[200] : theme.ds.colors.gray[500],
            strokeWidth: 0.3,
          }}
        />
        <Bar
          dataKey="offset"
          fill="transparent"
          isAnimationActive={false}
          stackId="waterfall"
        />
        <Bar
          dataKey="allocationShares"
          fill={allocationColor}
          isAnimationActive={false}
          stackId="waterfall"
        />
        <Bar
          dataKey="redeemedShares"
          fill={allocationColor}
          isAnimationActive={false}
          stackId="waterfall"
        />
        <Bar
          dataKey="earnedShares"
          fill={earnedSharesColor}
          isAnimationActive={false}
          stackId="waterfall"
        />
        <Bar
          dataKey="remainingUnearnedShares"
          fill={allocationColor}
          isAnimationActive={false}
          stackId="waterfall"
        />
        <OutcomeWaterfallChartAnnotations
          barSize={WATERFALL_BAR_SIZE}
          chartData={chartData}
          connectorColor={connectorColor}
          formatNumber={formatNumber}
          labelColor={annotationColor}
        />
      </BarChart>
      <Stack
        css={css`
          width: 360px;
        `}
      >
        <Typography
          variant="bodyXsmallRegular"
          css={(theme) => css`
            color: ${theme.ds.colors.gray[500]};
            margin-bottom: 8px;
            place-self: flex-end;
          `}
        >
          <FormattedMessage defaultMessage="Shares" />
        </Typography>
        <Group
          align="center"
          gap={8}
          css={css`
            margin-bottom: 4px;
            padding: 6px 0px 6px 0px;
          `}
        >
          <div
            css={(theme) => css`
              background-color: ${allocationColor};
              width: 12px;
              height: 12px;
              flex-shrink: 0;
              border-radius: 1.6px;
              outline: 1px solid ${theme.ds.colors.gray[100]};
              outline-offset: -1px;
            `}
          />
          <Typography
            variant="bodyBaseRegular"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[800]};
              flex: 1;
            `}
          >
            <FormattedMessage defaultMessage="Potential" />
          </Typography>
          <Typography
            variant="bodyBaseRegular"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[800]};
            `}
          >
            {formatNumber(grantsForUser.nbShares - (grantsForUser.employmentAdjustment ?? 0))}
          </Typography>
        </Group>
        <Group
          align="center"
          gap={8}
          css={css`
            padding: 6px 0px 6px 0px;
          `}
        >
          <div
            css={(theme) => css`
              width: 12px;
              flex-shrink: 0;
              height: stretch;
              border-left: 1px solid ${theme.ds.colors.gray[50]};
            `}
          />
          <Typography
            variant="bodyBaseRegular"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[600]};
              flex: 1;
            `}
          >
            <FormattedMessage defaultMessage="Allocation" />
          </Typography>
          <Typography
            variant="bodyBaseRegular"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[600]};
            `}
          >
            {formatNumber(grantsForUser.nbShares)}
          </Typography>
        </Group>
        {grantsForUser.employmentAdjustment !== null && (
          <Group
            align="center"
            gap={8}
            css={css`
              padding: 6px 0px 6px 0px;
            `}
          >
            <div
              css={(theme) => css`
                width: 12px;
                flex-shrink: 0;
                height: stretch;
                border-left: 1px solid ${theme.ds.colors.gray[50]};
              `}
            />
            <Typography
              variant="bodyBaseRegular"
              css={(theme) => css`
                color: ${theme.ds.colors.gray[600]};
                flex: 1;
              `}
            >
              <FormattedMessage defaultMessage="Leaver redemption" />
            </Typography>
            <Typography
              variant="bodyBaseRegular"
              css={(theme) => css`
                color: ${theme.ds.colors.gray[600]};
              `}
            >
              {formatNumber(grantsForUser.employmentAdjustment)}
            </Typography>
          </Group>
        )}
        <Group
          align="center"
          gap={8}
          css={css`
            margin-top: 16px;
            padding: 6px 0px 6px 0px;
          `}
        >
          <div
            css={css`
              background-color: ${earnedSharesColor};
              width: 12px;
              height: 12px;
              border-radius: 1.6px;
              flex-shrink: 0;
            `}
          />
          <Typography
            variant="bodyBaseMedium"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[800]};
              flex: 1;
            `}
          >
            <FormattedMessage defaultMessage="Provisional earned shares" />
          </Typography>
          <Typography
            variant="bodyBaseMedium"
            css={(theme) => css`
              color: ${theme.ds.colors.gray[800]};
            `}
          >
            {formatNumber(
              Math.min(
                grantsForUser.outcomeNbShares ?? 0,
                grantsForUser.nbShares - (grantsForUser.employmentAdjustment ?? 0),
              ),
            )}
          </Typography>
        </Group>
      </Stack>
    </Stack>
  );
});