import { useDisclosure, useFocusTrap } from "@mantine/hooks"; import type { TObject } from "core/utils"; import { omit } from "lodash-es"; import { useRef, useState } from "react"; import { TbCirclePlus, TbVariable } from "react-icons/tb"; import { useLocation } from "wouter"; import { useBknd } from "../../../client/BkndProvider"; import { Button } from "../../../components/buttons/Button"; import * as Formy from "../../../components/form/Formy"; import { JsonSchemaForm, type JsonSchemaFormRef } from "../../../components/form/json-schema/JsonSchemaForm"; import { Dropdown } from "../../../components/overlay/Dropdown"; import { Modal } from "../../../components/overlay/Modal"; export type SettingsNewModalProps = { schema: TObject; uiSchema?: object; anyOfValues?: Record; path: string[]; prefixPath: string; generateKey?: string | ((formData: any) => string); }; export const SettingNewModal = ({ schema, uiSchema = {}, anyOfValues, path, prefixPath, generateKey }: SettingsNewModalProps) => { const [location, navigate] = useLocation(); const [formSchema, setFormSchema] = useState(schema); const [submitting, setSubmitting] = useState(false); const { actions } = useBknd(); const [opened, { open, close }] = useDisclosure(false); const isGeneratedKey = generateKey !== undefined; const isStaticGeneratedKey = typeof generateKey === "string"; const [newKey, setNewKey] = useState(isStaticGeneratedKey ? generateKey : ""); const focusTrap = useFocusTrap(!isGeneratedKey); const formRef = useRef(null); const isAnyOf = "anyOf" in schema; function handleFormChange(data) { if (generateKey && typeof generateKey === "function") { handleKeyNameChange({ target: { value: generateKey(data) } }); } console.log("form change", data); } function handleKeyNameChange(e) { const v = String(e.target.value); if (v.length > 0 && !/^[a-zA-Z_][a-zA-Z0-9_ ]*$/.test(v)) { console.log("no match", v); return; } setNewKey(v.toLowerCase().replace(/ /g, "_").replace(/__+/g, "_")); } async function handleSave() { if (formRef.current?.validateForm()) { setSubmitting(true); const data = formRef.current?.formData(); const [module, ...restOfPath] = path; const addPath = [...restOfPath, newKey].join("."); if (await actions.add(module as any, addPath, data)) { setTimeout(() => { navigate(prefixPath + newKey, { replace: true }); }, 500); } else { setSubmitting(false); } } console.log("valid?", formRef.current?.validateForm()); console.log("data", newKey, formRef.current?.formData()); } const anyOfItems = isAnyOf ? (schema.anyOf as any[])!.map((item) => { const key = item.title; const label = anyOfValues?.[key]?.label || key; const icon = anyOfValues?.[key]?.icon; return { label, icon, onClick: () => { setFormSchema(item); open(); } }; }) : []; return ( <>
{isAnyOf ? ( ) : ( )}
{[...path, newKey].join(".")}
{isGeneratedKey && (
generated
)}
); };