import { FC, useCallback, useEffect, useState } from 'react' import AnimatedPageContainer from '../AnimatedPageContainer'; import { TypeEditor } from './type-editor'; import { useObjectState, useObjectStateWrapper } from '../../hooks/useObjectState'; import { FieldTypes, Schema, Template, TypeType } from '../../types/schema'; import { useInput } from '../../hooks/useInput'; import { useRecoilState } from 'recoil'; import { SchemaEditAtom } from '../../recoil/atoms/schema'; import { GameSystemsService } from '../../services/game-systems'; import { SchemaViewer } from './schema-viewer'; import { TemplateEditor } from './template-editor'; import { Icon } from '../Icon'; export const SchemaBuilder: FC = () => { const [schema, setSchema] = useRecoilState(SchemaEditAtom); const { update: updateSchema } = useObjectStateWrapper(schema, setSchema); const { value: typeName, bind: bindTypeName, reset: resetTypeName } = useInput(''); const [pageNumber, setPageNumber] = useState(0); const [lastSaved, setLastSaved] = useState(schema); const fetchSchema = useCallback(async () => { const result = await GameSystemsService.getSchema('286f4c18-d280-444b-8d7e-9a3dd09f64ef') if (result.status !== 200) return; const fetchedSchema = await result.json(); // if (fetchedSchema.name === schema.name) return; if (!fetchedSchema.templates) fetchedSchema.templates = {} setSchema(fetchedSchema); setLastSaved(fetchedSchema); }, [setSchema]) useEffect(() => { fetchSchema(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const [selectedType, setSelectedType] = useState(''); const saveType = useCallback((name: string, type: TypeType) => { updateSchema(e => ({ types: { ...e.types, [name]: type } })); resetTypeName(); setPageNumber(0); setSelectedType(''); }, [resetTypeName, updateSchema]); const saveSchema = useCallback(() => { GameSystemsService.saveSchema(schema); setLastSaved(schema); }, [schema]) const selectTypeForEdit = useCallback((typeKey: string) => { setSelectedType(typeKey); setPageNumber(1); }, []) const { value: templateName, bind: bindTemplateName, reset: resetTemplateName } = useInput('', { disallowSpaces: true }); const addTemplate = useCallback(() => { updateSchema(s => ({ templates: { ...s.templates, [templateName]: { publishable: false, type: FieldTypes.any } } })); resetTemplateName(); }, [resetTemplateName, templateName, updateSchema]) const updateTemplate = useCallback((key: string, template: Template) => { updateSchema(s => ({ templates: { ...s.templates, [key]: template } })) }, [updateSchema]) const deleteType = useCallback((key: string) => { updateSchema(s => { const types = { ...s.types }; delete types[key]; return { types } }) }, [updateSchema]) return (

Add a template

    {Object.entries(schema.templates).map(([templateKey, template]) => ( ))}

Add a type

    {Object.keys(schema.types).map(t => (
  • {t}
  • ))}
) }