/ client / src / components / filamentImportModal.tsx
filamentImportModal.tsx
 1  import { useTranslate } from "@refinedev/core";
 2  import { Form, Modal, Select } from "antd";
 3  import { Trans } from "react-i18next";
 4  import { formatFilamentLabel } from "../pages/spools/functions";
 5  import { searchMatches } from "../utils/filtering";
 6  import { ExternalFilament, useGetExternalDBFilaments } from "../utils/queryExternalDB";
 7  
 8  export function FilamentImportModal(props: {
 9    isOpen: boolean;
10    onImport: (filament: ExternalFilament) => void;
11    onClose: () => void;
12  }) {
13    const [form] = Form.useForm();
14    const t = useTranslate();
15  
16    const externalFilaments = useGetExternalDBFilaments();
17    const filamentOptions =
18      externalFilaments.data?.map((item) => {
19        return {
20          label: formatFilamentLabel(
21            item.name,
22            item.diameter,
23            item.manufacturer,
24            item.material,
25            item.weight,
26            item.spool_type,
27          ),
28          value: item.id,
29          item: item,
30        };
31      }) ?? [];
32    filamentOptions.sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: "base" }));
33  
34    return (
35      <Modal
36        title={t("filament.form.import_external")}
37        open={props.isOpen}
38        onOk={() => form.submit()}
39        onCancel={() => props.onClose()}
40      >
41        <Form
42          layout="vertical"
43          form={form}
44          onFinish={(values) => {
45            const filament = filamentOptions.find((item) => item.value === values.filament)?.item;
46            if (!filament) {
47              throw new Error("Filament not found");
48            }
49            props.onImport(filament);
50            props.onClose();
51            form.resetFields();
52          }}
53        >
54          <p>
55            <Trans
56              i18nKey={"filament.form.import_external_description"}
57              components={{
58                br: <br />,
59              }}
60            />
61          </p>
62          <Form.Item name="filament" rules={[{ required: true }]}>
63            <Select
64              options={filamentOptions}
65              showSearch
66              filterOption={(input, option) => typeof option?.label === "string" && searchMatches(input, option?.label)}
67            />
68          </Form.Item>
69        </Form>
70      </Modal>
71    );
72  }