1+ import cloneDeep from 'lodash/cloneDeep'
12import { useEffect , useRef } from 'react'
23
4+ const CSS_COMPONENT = 'color: DodgerBlue'
5+ const CSS_DATE = 'color: SlateGray;'
6+
37export interface UseLogReturn {
48 log : < T > ( value : T ) => void
59}
610
7- export const useLog = ( ) : UseLogReturn => {
11+ interface PrintProps < T > {
12+ value : T
13+ label : string
14+ group ?: string
15+ type ?: PrintTypes
16+ }
17+
18+ export enum PrintTypes {
19+ Mount = 'Mount' ,
20+ Unmount = 'Unmount' ,
21+ BeforeUnmount = 'Before unmount' ,
22+ Change = 'Change' ,
23+ }
24+
25+ export function useLog ( ) : UseLogReturn {
26+ const componentName = ( function getComponentName ( ) {
27+ try {
28+ throw new Error ( )
29+ } catch ( error ) {
30+ if ( error instanceof Error ) {
31+ const re = / ( \w + ) @ | a t ( \w + ) \( / g
32+
33+ re . exec ( error ?. stack ?? '' )
34+ re . exec ( error ?. stack ?? '' )
35+ const m = re . exec ( error ?. stack ?? '' ) ?? [ ]
36+
37+ return String ( m [ 1 ] || m [ 2 ] )
38+ }
39+
40+ return ''
41+ }
42+ } ) ( )
43+
44+ const getGroupLabel = ( type : PrintTypes ) : string => {
45+ return `${ String ( type ) } ${
46+ componentName ? 'in %c<' + String ( componentName ) + ' /> ' : '%c'
47+ } %c@ ${ new Date ( ) . toLocaleTimeString ( ) } `
48+ }
49+
50+ function print < T > ( {
51+ value,
52+ label,
53+ type = PrintTypes . Change ,
54+ group = getGroupLabel ( type ) ,
55+ } : PrintProps < T > ) : void {
56+ console . group ( group , CSS_COMPONENT , CSS_DATE )
57+ console . log ( `${ label } : ${ String ( value ) } ` )
58+ console . groupEnd ( )
59+ }
60+
861 function log < T > ( value : T ) : void {
62+ const clonedValue = cloneDeep ( value )
63+
964 return ( ( ) => {
1065 const isUnmounting = useRef ( false )
1166 useEffect ( ( ) => {
@@ -15,19 +70,35 @@ export const useLog = (): UseLogReturn => {
1570 } , [ ] )
1671
1772 useEffect ( ( ) => {
18- console . log ( `On mount: ${ String ( value ) } ` )
73+ print ( {
74+ label : 'On mount' ,
75+ value : clonedValue ,
76+ type : PrintTypes . Mount ,
77+ } )
1978
2079 return ( ) => {
21- console . log ( `On unmount: ${ String ( value ) } ` )
80+ print ( {
81+ label : 'On unmount' ,
82+ value : clonedValue ,
83+ type : PrintTypes . Unmount ,
84+ } )
2285 }
2386 } , [ ] )
2487
2588 useEffect ( ( ) => {
26- console . log ( `On change: ${ String ( value ) } ` )
89+ print ( {
90+ label : 'On change' ,
91+ value : clonedValue ,
92+ type : PrintTypes . Change ,
93+ } )
2794
2895 return ( ) => {
2996 if ( isUnmounting . current ) {
30- console . log ( `Before unmount: ${ String ( value ) } ` )
97+ print ( {
98+ label : 'Before unmount' ,
99+ value : clonedValue ,
100+ type : PrintTypes . BeforeUnmount ,
101+ } )
31102 }
32103 }
33104 } , [ value ] )
0 commit comments