tabletop-commander/components/schema/template-editor.tsx
2024-03-19 14:49:50 -06:00

76 lines
2.3 KiB
TypeScript

import { FC, useCallback } from "react";
import { useObjectStateWrapper } from "@/hooks/useObjectState";
import { TEMPLATE_TYPES } from "@/constants/TemplateTypes";
import { SchemaEditAtom } from "@/recoil/atoms/schema";
import { useRecoilState } from "recoil";
import { Icon } from "@/components/Icon";
interface IProps {
templateKey: string;
update: (arg0: string, arg1: Template) => void;
template: Template;
}
export const TemplateEditor: FC<IProps> = (
{ templateKey, update, template },
) => {
const [schema, setSchema] = useRecoilState(SchemaEditAtom);
const updateTemplate = useCallback(
(t: Template | ((arg: Template) => Template)) => {
update(templateKey, typeof t === "function" ? t(template) : t);
},
[templateKey, update, template],
);
const { bindProperty } = useObjectStateWrapper(
template,
updateTemplate,
);
const deleteTemplate = useCallback(() => {
setSchema((s: Schema) => {
const templates = { ...s.schema };
delete templates[templateKey];
return {
...s,
schema: templates,
};
});
}, [setSchema, templateKey]);
return (
<li className="odd:bg-black/50 p-2">
<p className="font-bold">{templateKey}</p>
<div className="flex items-center justify-between">
<div className="flex items-center gap-4 pl-2">
<label className="w-min">
Type:
<input
type="text"
{...bindProperty("type", { disallowSpaces: true })}
list="type-editor-type-list"
/>
<datalist id="type-editor-type-list">
{Object.keys(TEMPLATE_TYPES).map((k) => (
<option key={"templatetype" + k} value={k}>{k}</option>
))}
{Object.keys(schema.types).map((k) => (
<option key={"schematype" + k} value={k}>{k}</option>
))}
</datalist>
</label>
<textarea {...bindProperty("display")} cols={30} rows={10}></textarea>
</div>
<button
className="no-default"
onClick={deleteTemplate}
>
<Icon
icon="Trash"
className="svg-red-700 hover:svg-red-500 trash-can w-6 h-6"
/>
</button>
</div>
</li>
);
};