import React from "react";
import { useTranslation } from "react-i18next";
import { Field } from "react-final-form";
import Label from "../ui/formUtils/Label";
import Hint from "../ui/formUtils/Hint";
import Slider from "../ui/Slider";
import ActionList from "./ActionList";
import { itemTemplates } from "./";
export const getFormFieldComponent = (type) => {
if (type in itemTemplates) {
return itemTemplates[type].form;
}
return () => null;
};
const getDefaultActionsFromItem = (item) => {
if (item.type in itemTemplates) {
const actions = itemTemplates[item.type].defaultActions;
if (typeof actions === "function") {
return actions(item);
}
return actions;
}
return [];
};
const getAvailableActionsFromItem = (item) => {
if (item.type in itemTemplates) {
const actions = itemTemplates[item.type].availableActions;
if (typeof actions === "function") {
return actions(item);
}
return actions;
}
return [];
};
const getExcludedFields = (types) => {
return types.reduce((excluded, type) => {
return Object.assign(excluded, itemTemplates[type].excludeFields || {});
}, {});
};
const ItemForm = ({ items, types, extraExcludeFields = {} }) => {
const { t } = useTranslation();
let FieldsComponent;
const oneType = types.length === 1;
if (items.length === 1) {
FieldsComponent = getFormFieldComponent(items[0].type);
} else {
if (oneType) {
FieldsComponent = getFormFieldComponent(types[0]);
} else {
FieldsComponent = () => null;
}
}
const defaultActions = React.useMemo(() => {
if (oneType) {
return getDefaultActionsFromItem(items[0]);
}
return undefined;
}, [items, oneType]);
const availableActions = React.useMemo(() => {
if (oneType) {
return getAvailableActionsFromItem(items[0]);
}
return [];
}, [items, oneType]);
// Merge extra excluded fields and all item excluded fields
const excludeFields = { ...getExcludedFields(types), ...extraExcludeFields };
let initialValues;
// Set initial values to item values only if one element selected
// Empty object otherwise
if (items.length === 1) {
initialValues = { ...items[0] };
if (items.length === 1) {
initialValues.actions = (initialValues.actions || defaultActions).map(
(action) => {
if (typeof action === "string") {
return { name: action };
}
return action;
}
);
}
} else {
initialValues = {};
}
return (
<>
{!excludeFields.locked && (
)}
{!excludeFields.rotation && (
)}
{!excludeFields.layer && (
)}