Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/next/components/misc/select-with-default.tsx
Views: 687
import { Button, Select } from "antd";1import { CSSProperties, ReactNode, useState } from "react";2import { keys } from "lodash";3import { is_array } from "@cocalc/util/misc";45const { Option } = Select;67interface Props {8value?: string;9defaultValue?: string;10initialValue?: string;11onChange: (string) => void;12options: { [value: string]: ReactNode } | string[];13style?: CSSProperties;14}1516export default function SelectWithDefault({17value,18defaultValue,19initialValue,20onChange,21options,22style,23}: Props) {24const [val, setVal] = useState<string>(25value ?? initialValue ?? defaultValue ?? keys(options)[0] ?? ""26);2728const v: ReactNode[] = [];29if (is_array(options)) {30// @ts-ignore31for (const value of options) {32v.push(33<Option key={value} value={value}>34{value}35</Option>36);37}38} else {39for (const value in options) {40v.push(41<Option key={value} value={value}>42{options[value]}43</Option>44);45}46}4748return (49<div style={{ width: "100%" }}>50<Select51showSearch52value={val}53onChange={(value) => {54onChange(value);55setVal(value);56}}57style={{ width: "30ex", maxWidth: "100%", ...style }}58>59{v}60</Select>61{defaultValue != null && (62<Button63type="dashed"64disabled={(value ?? val) == defaultValue}65style={{ marginLeft: "5px" }}66onClick={() => {67onChange(defaultValue);68setVal(defaultValue);69}}70>71{(value ?? val) == defaultValue ? (72"Default"73) : (74<>Changed from {is_array(options) ? defaultValue : options[defaultValue]}</>75)}76</Button>77)}78</div>79);80}818283