trellis
Version:
Agentic State Engine — event-sourced causal graph with branching, decision traces, and realtime sync for AI-native applications
65 lines (63 loc) • 1.45 kB
JavaScript
import {
createFormCore,
formSchemaFrom
} from "../../chunk-25WAHQHF.js";
import "../../chunk-2ESYSVXG.js";
// src/forms/react/index.ts
import {
createContext,
createElement,
useContext,
useRef,
useSyncExternalStore
} from "react";
var FormContext = createContext(null);
function useForm(schema, initialValues) {
const ref = useRef(null);
if (ref.current === null) {
ref.current = createFormCore(formSchemaFrom(schema), initialValues ?? {});
}
const core = ref.current;
const state = useSyncExternalStore(
core.subscribe,
() => core.state,
() => core.state
);
return {
state,
actions: core.actions,
field: core.field,
subscribe: core.subscribe
};
}
function useFormContext() {
const form = useContext(FormContext);
if (!form) {
throw new Error(
"useFormContext / <Field> must be used inside a <Form> provider"
);
}
return form;
}
function Form({ schema, initialValues, onSubmit, children }) {
const form = useForm(schema, initialValues);
const handleSubmit = (e) => {
e.preventDefault();
if (onSubmit) void form.actions.submit(onSubmit);
};
return createElement(
FormContext.Provider,
{ value: form },
createElement("form", { onSubmit: handleSubmit }, children(form))
);
}
function Field({ name, children }) {
const form = useFormContext();
return children(form.field(name));
}
export {
Field,
Form,
useForm,
useFormContext
};