import { TranslatedString } from "@gnu-taler/taler-util";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { FormProvider, UIFormProps } from "./FormProvider.js";
import { LabelWithTooltipMaybeRequired } from "./InputLine.js";
import { RenderAllFieldsByUiConfig, UIFormField } from "./forms.js";
import { useField } from "./useField.js";
function Option({
label,
disabled,
isFirst,
isLast,
isSelected,
onClick,
}: {
label: TranslatedString;
isFirst?: boolean;
isLast?: boolean;
isSelected?: boolean;
disabled?: boolean;
onClick: () => void;
}): VNode {
let clazz = "relative flex border p-4 focus:outline-none disabled:text-grey";
if (isFirst) {
clazz += " rounded-tl-md rounded-tr-md ";
}
if (isLast) {
clazz += " rounded-bl-md rounded-br-md ";
}
if (isSelected) {
clazz += " z-10 border-indigo-200 bg-indigo-50 ";
} else {
clazz += " border-gray-200";
}
if (disabled) {
clazz +=
" cursor-not-allowed bg-gray-50 text-gray-500 ring-gray-200 text-gray";
} else {
clazz += " cursor-pointer";
}
return (
);
}
export function noHandlerPropsAndNoContextForField(
field: string | number | symbol,
): never {
throw Error(
`Field ${field.toString()} doesn't have handler and is not in a form provider context.`,
);
}
export function InputArray(
props: {
fields: UIFormField[];
labelField: string;
} & UIFormProps,
): VNode {
const { fields, labelField, name, label, required, tooltip } = props;
// const { value, onChange, state } = useField(name);
//FIXME: remove deprecated
const fieldCtx = useField(props.name);
if (!props.handler && !fieldCtx) {
throw Error("");
}
const { value, onChange, state } =
props.handler ?? fieldCtx ?? noHandlerPropsAndNoContextForField(props.name);
const list = (value ?? []) as Array>;
const [selectedIndex, setSelected] = useState(undefined);
const selected =
selectedIndex === undefined ? undefined : list[selectedIndex];
return (
{list.map((v, idx) => {
return (
{selectedIndex !== undefined && (
/**
* This form provider act as a substate of the parent form
* Consider creating an InnerFormProvider since not every feature is expected
*/
{
// current state is ignored
// the state is defined by the parent form
// elements should be present in the state object since this is expected to be an array
//@ts-ignore
// return state.elements[selectedIndex];
return {}
}}
onSubmit={(v) => {
const newValue = [...list];
newValue.splice(selectedIndex, 1, v);
onChange(newValue as any);
setSelected(undefined);
}}
onUpdate={(v) => {
const newValue = [...list];
newValue.splice(selectedIndex, 1, v);
onChange(newValue as any);
}}
>