11import { useEffect , useRef } from "react" ;
22import { isTypeDescriptor } from "@finos/vuu-utils" ;
33import { KeyedColumnDescriptor } from "@finos/vuu-datagrid-types" ;
4+ import {
5+ getMovingValueDirection ,
6+ isValidNumber ,
7+ valueChangeDirection ,
8+ } from "@finos/vuu-utils" ;
49
510const INITIAL_VALUE = [ undefined , undefined , undefined , undefined ] ;
611
7- type valueChangeDirection = "up1" | "up2" | "down1" | "down2" | "" ;
8-
9- export const UP1 = "up1" ;
10- export const UP2 = "up2" ;
11- export const DOWN1 = "down1" ;
12- export const DOWN2 = "down2" ;
13-
1412type State = [ string , unknown , KeyedColumnDescriptor , valueChangeDirection ] ;
1513
16- const isValidNumber = ( n : unknown ) : n is number =>
17- typeof n === "number" && isFinite ( n ) ;
18-
19- export default function useDirection (
14+ export function useDirection (
2015 key : string ,
2116 value : unknown ,
2217 column : KeyedColumnDescriptor
2318) {
2419 const ref = useRef < State > ( ) ;
2520 const [ prevKey , prevValue , prevColumn , prevDirection ] =
2621 ref . current || INITIAL_VALUE ;
22+
23+ const { type : dataType } = column ;
24+ const decimals = isTypeDescriptor ( dataType )
25+ ? dataType . formatting ?. decimals
26+ : undefined ;
27+
2728 const direction =
2829 key === prevKey &&
2930 isValidNumber ( value ) &&
3031 isValidNumber ( prevValue ) &&
3132 column === prevColumn
32- ? getDirection ( value , column , prevDirection , prevValue )
33+ ? getMovingValueDirection ( value , prevDirection , prevValue , decimals )
3334 : "" ;
3435
3536 useEffect ( ( ) => {
@@ -38,55 +39,3 @@ export default function useDirection(
3839
3940 return direction ;
4041}
41-
42- function getDirection (
43- newValue : number ,
44- column : KeyedColumnDescriptor ,
45- direction ?: valueChangeDirection ,
46- prevValue ?: number
47- ) : valueChangeDirection {
48- if (
49- ! isFinite ( newValue ) ||
50- prevValue === undefined ||
51- direction === undefined
52- ) {
53- return "" ;
54- } else {
55- let diff = newValue - prevValue ;
56- if ( diff ) {
57- // make sure there is still a diff when reduced to number of decimals to be displayed
58- const { type : dataType } = column ;
59- const decimals =
60- isTypeDescriptor ( dataType ) && dataType . formatting ?. decimals ;
61- if ( typeof decimals === "number" ) {
62- diff = + newValue . toFixed ( decimals ) - + prevValue . toFixed ( decimals ) ;
63- }
64- }
65-
66- if ( diff ) {
67- if ( direction === "" ) {
68- if ( diff < 0 ) {
69- return DOWN1 ;
70- } else {
71- return UP1 ;
72- }
73- } else if ( diff > 0 ) {
74- if ( direction === DOWN1 || direction === DOWN2 || direction === UP2 ) {
75- return UP1 ;
76- } else {
77- return UP2 ;
78- }
79- } else if (
80- direction === UP1 ||
81- direction === UP2 ||
82- direction === DOWN2
83- ) {
84- return DOWN1 ;
85- } else {
86- return DOWN2 ;
87- }
88- } else {
89- return "" ;
90- }
91- }
92- }
0 commit comments