Added custom date picker BOD-246
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
import { Input, Popover } from "antd";
|
||||
import React, { useEffect, useState, forwardRef } from "react";
|
||||
|
||||
const FormInputNUmberCalculator = (
|
||||
{ value: formValue, onChange: formOnChange },
|
||||
ref
|
||||
) => {
|
||||
const [value, setValue] = useState(formValue);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [history, setHistory] = useState([]);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const key = e.target.value;
|
||||
switch (key) {
|
||||
case "/":
|
||||
case "*":
|
||||
case "+":
|
||||
case "-":
|
||||
return;
|
||||
default:
|
||||
setValue(key);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e) => {
|
||||
const { key } = e;
|
||||
|
||||
let action;
|
||||
switch (key) {
|
||||
case "/":
|
||||
case "*":
|
||||
case "+":
|
||||
case "-":
|
||||
action = key;
|
||||
break;
|
||||
case "Enter":
|
||||
action = "=";
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
const val = parseFloat(value);
|
||||
setValue(null);
|
||||
if (!isNaN(val)) {
|
||||
setHistory([...history, val, action]);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (value !== formValue && formOnChange) formOnChange(value);
|
||||
}, [formOnChange, value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (history.length > 2) {
|
||||
const subTotal = history.reduce((acc, val, idx) => {
|
||||
if (idx === 0) {
|
||||
return val;
|
||||
}
|
||||
switch (val) {
|
||||
case "/":
|
||||
case "*":
|
||||
case "+":
|
||||
case "-":
|
||||
return acc;
|
||||
|
||||
default:
|
||||
//Weve got math on our hands. Find the last operator, and apply it accordingly.
|
||||
switch (history[idx - 1]) {
|
||||
case "/":
|
||||
return acc / val;
|
||||
case "*":
|
||||
return acc * val;
|
||||
case "+":
|
||||
return acc + val;
|
||||
case "-":
|
||||
return acc - val;
|
||||
default:
|
||||
return acc;
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
setTotal(subTotal);
|
||||
if (history[history.length - 1] === "=") setValue(subTotal);
|
||||
}
|
||||
}, [history]);
|
||||
|
||||
const popContent = (
|
||||
<div style={{ display: "flex", flexDirection: "column" }}>
|
||||
History
|
||||
{history.map((h, idx) => (
|
||||
<div style={{ marginLeft: "auto" }} key={idx}>
|
||||
{h}
|
||||
</div>
|
||||
))}
|
||||
<div>{total}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Popover content={popContent} visible={history.length > 0}>
|
||||
<Input
|
||||
ref={ref}
|
||||
value={value}
|
||||
defaultValue={value}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onBlur={(e) => setHistory([])}
|
||||
/>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default forwardRef(FormInputNUmberCalculator);
|
||||
Reference in New Issue
Block a user