CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/components/number-input.tsx
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { useEffect, useState } from "react";
7
import { Col, Row, Input } from "antd";
8
9
interface Props {
10
number: number;
11
min?: number;
12
max?: number;
13
on_change: (n: number) => void;
14
unit?: string;
15
disabled?: boolean;
16
}
17
18
export function NumberInput(props: Props) {
19
const [number, setNumber] = useState<string>(`${props.number}`);
20
21
useEffect(() => {
22
setNumber(`${number}`);
23
}, [props.number]);
24
25
function saveChange(e?) {
26
e?.preventDefault();
27
let m = parseInt(number);
28
if (!isFinite(m)) {
29
m = props.number;
30
}
31
if (props.min != null && m < props.min) {
32
m = props.min;
33
} else if (props.max != null && m > props.max) {
34
m = props.max;
35
}
36
setNumber(`${m}`);
37
props.on_change(m);
38
}
39
40
return (
41
<Row gutter={16}>
42
<Col xs={16}>
43
<Input
44
type="text"
45
value={number}
46
onChange={(e) => setNumber(e.target.value)}
47
onBlur={saveChange}
48
onKeyDown={(e) => {
49
if (e.keyCode === 27) {
50
// reset back to its original value.
51
setNumber(`${props.number}`);
52
} else if (e.keyCode === 13) {
53
saveChange();
54
}
55
}}
56
disabled={props.disabled}
57
/>
58
</Col>
59
<Col xs={8} className="lighten">
60
{props.unit ? `${props.unit}` : ""}
61
</Col>
62
</Row>
63
);
64
}
65
66