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/next/components/misc/select-with-default.tsx
Views: 687
1
import { Button, Select } from "antd";
2
import { CSSProperties, ReactNode, useState } from "react";
3
import { keys } from "lodash";
4
import { is_array } from "@cocalc/util/misc";
5
6
const { Option } = Select;
7
8
interface Props {
9
value?: string;
10
defaultValue?: string;
11
initialValue?: string;
12
onChange: (string) => void;
13
options: { [value: string]: ReactNode } | string[];
14
style?: CSSProperties;
15
}
16
17
export default function SelectWithDefault({
18
value,
19
defaultValue,
20
initialValue,
21
onChange,
22
options,
23
style,
24
}: Props) {
25
const [val, setVal] = useState<string>(
26
value ?? initialValue ?? defaultValue ?? keys(options)[0] ?? ""
27
);
28
29
const v: ReactNode[] = [];
30
if (is_array(options)) {
31
// @ts-ignore
32
for (const value of options) {
33
v.push(
34
<Option key={value} value={value}>
35
{value}
36
</Option>
37
);
38
}
39
} else {
40
for (const value in options) {
41
v.push(
42
<Option key={value} value={value}>
43
{options[value]}
44
</Option>
45
);
46
}
47
}
48
49
return (
50
<div style={{ width: "100%" }}>
51
<Select
52
showSearch
53
value={val}
54
onChange={(value) => {
55
onChange(value);
56
setVal(value);
57
}}
58
style={{ width: "30ex", maxWidth: "100%", ...style }}
59
>
60
{v}
61
</Select>
62
{defaultValue != null && (
63
<Button
64
type="dashed"
65
disabled={(value ?? val) == defaultValue}
66
style={{ marginLeft: "5px" }}
67
onClick={() => {
68
onChange(defaultValue);
69
setVal(defaultValue);
70
}}
71
>
72
{(value ?? val) == defaultValue ? (
73
"Default"
74
) : (
75
<>Changed from {is_array(options) ? defaultValue : options[defaultValue]}</>
76
)}
77
</Button>
78
)}
79
</div>
80
);
81
}
82
83