11import React , { useState } from "react"
22import { Flex , TextSmall , TextMicro , Button } from "@netdata/netdata-ui"
33
4- const CustomPeriodForm = ( { onAdd, onCancel } ) => {
5- const [ label , setLabel ] = useState ( "" )
6- const [ offsetDays , setOffsetDays ] = useState ( "" )
7- const [ offsetHours , setOffsetHours ] = useState ( "" )
4+ const normalizeInitialValues = initialValues => {
5+ const { label = "" , offsetSeconds = 0 } = initialValues || { }
86
9- const generateLabel = ( days , hours ) => {
10- const rtf = new Intl . RelativeTimeFormat ( "en" , { numeric : "always" } )
7+ const days = Math . floor ( offsetSeconds / ( 24 * 60 * 60 ) )
8+ const hours = Math . floor ( ( offsetSeconds % ( 24 * 60 * 60 ) ) / ( 60 * 60 ) )
9+ return { label, days : days ? days . toString ( ) : "" , hours : hours ? hours . toString ( ) : "" }
10+ }
1111
12- if ( days > 0 && hours === 0 ) {
13- return rtf . format ( - days , "day" )
14- }
15- if ( hours > 0 && days === 0 ) {
16- return rtf . format ( - hours , "hour" )
17- }
18- if ( days > 0 && hours > 0 ) {
19- return rtf . format ( - days , "day" )
20- }
21- return ""
12+ const generateLabel = ( days , hours ) => {
13+ const rtf = new Intl . RelativeTimeFormat ( "en" , { numeric : "always" } )
14+
15+ if ( days > 0 && hours === 0 ) {
16+ return rtf . format ( - days , "day" )
2217 }
18+ if ( hours > 0 && days === 0 ) {
19+ return rtf . format ( - hours , "hour" )
20+ }
21+ if ( days > 0 && hours > 0 ) {
22+ return `${ rtf . format ( - days , "day" ) } and ${ rtf . format ( - hours , "hour" ) } `
23+ }
24+ return ""
25+ }
26+
27+ const CustomPeriodForm = ( { onSubmit, onCancel, initialValues } ) => {
28+ const normalizedValues = normalizeInitialValues ( initialValues )
29+
30+ const [ label , setLabel ] = useState ( normalizedValues . label )
31+ const [ offsetDays , setOffsetDays ] = useState ( normalizedValues . days )
32+ const [ offsetHours , setOffsetHours ] = useState ( normalizedValues . hours )
2333
2434 const handleAdd = ( ) => {
2535 const days = parseInt ( offsetDays ) || 0
@@ -32,12 +42,12 @@ const CustomPeriodForm = ({ onAdd, onCancel }) => {
3242 if ( ! finalLabel ) return
3343
3444 const customPeriod = {
35- id : `custom_${ Date . now ( ) } ` ,
45+ id : initialValues . id || `custom_${ Date . now ( ) } ` ,
3646 label : finalLabel ,
3747 offsetSeconds,
3848 }
3949
40- onAdd ( customPeriod )
50+ onSubmit ( customPeriod )
4151 }
4252
4353 return (
@@ -103,7 +113,7 @@ const CustomPeriodForm = ({ onAdd, onCancel }) => {
103113 </ Flex >
104114
105115 < Flex gap = { 2 } >
106- < Button tiny label = " Add" onClick = { handleAdd } />
116+ < Button tiny label = { initialValues ? "Update" : " Add"} onClick = { handleAdd } />
107117 < Button tiny label = "Cancel" onClick = { onCancel } />
108118 </ Flex >
109119 </ Flex >
0 commit comments