mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-17 04:46:05 +00:00
initial json schema form implementation
This commit is contained in:
@@ -3,9 +3,10 @@ import { forwardRef, useEffect, useState } from "react";
|
||||
|
||||
export const BooleanInputMantine = forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
(props, ref) => {
|
||||
const [checked, setChecked] = useState(Boolean(props.value));
|
||||
const [checked, setChecked] = useState(Boolean(props.value ?? props.defaultValue));
|
||||
|
||||
useEffect(() => {
|
||||
console.log("value change", props.value);
|
||||
setChecked(Boolean(props.value));
|
||||
}, [props.value]);
|
||||
|
||||
|
||||
@@ -1,25 +1,37 @@
|
||||
import { getBrowser } from "core/utils";
|
||||
import type { Field } from "data";
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
|
||||
import {
|
||||
type ElementType,
|
||||
forwardRef,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
useState
|
||||
} from "react";
|
||||
import { TbCalendar, TbChevronDown, TbInfoCircle } from "react-icons/tb";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { IconButton } from "ui/components/buttons/IconButton";
|
||||
import { useEvent } from "ui/hooks/use-event";
|
||||
|
||||
export const Group: React.FC<React.ComponentProps<"div"> & { error?: boolean }> = ({
|
||||
export const Group = <E extends ElementType = "div">({
|
||||
error,
|
||||
as,
|
||||
...props
|
||||
}) => (
|
||||
<div
|
||||
{...props}
|
||||
className={twMerge(
|
||||
"flex flex-col gap-1.5",
|
||||
}: React.ComponentProps<E> & { error?: boolean; as?: E }) => {
|
||||
const Tag = as || "div";
|
||||
|
||||
error && "text-red-500",
|
||||
props.className
|
||||
)}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Tag
|
||||
{...props}
|
||||
className={twMerge(
|
||||
"flex flex-col gap-1.5",
|
||||
as === "fieldset" && "border border-primary/10 p-3 rounded-md",
|
||||
error && "text-red-500",
|
||||
props.className
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const formElementFactory = (element: string, props: any) => {
|
||||
switch (element) {
|
||||
@@ -34,7 +46,21 @@ export const formElementFactory = (element: string, props: any) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const Label: React.FC<React.ComponentProps<"label">> = (props) => <label {...props} />;
|
||||
export const Label = <E extends ElementType = "label">({
|
||||
as,
|
||||
...props
|
||||
}: React.ComponentProps<E> & { as?: E }) => {
|
||||
const Tag = as || "label";
|
||||
return <Tag {...props} />;
|
||||
};
|
||||
|
||||
export const Help: React.FC<React.ComponentProps<"div">> = ({ className, ...props }) => (
|
||||
<div {...props} className={twMerge("text-sm text-primary/50", className)} />
|
||||
);
|
||||
|
||||
export const ErrorMessage: React.FC<React.ComponentProps<"div">> = ({ className, ...props }) => (
|
||||
<div {...props} className={twMerge("text-sm text-red-500", className)} />
|
||||
);
|
||||
|
||||
export const FieldLabel: React.FC<React.ComponentProps<"label"> & { field: Field }> = ({
|
||||
field,
|
||||
@@ -145,20 +171,45 @@ export const BooleanInput = forwardRef<HTMLInputElement, React.ComponentProps<"i
|
||||
}
|
||||
);
|
||||
|
||||
export const Select = forwardRef<HTMLSelectElement, React.ComponentProps<"select">>(
|
||||
(props, ref) => (
|
||||
<div className="flex w-full relative">
|
||||
<select
|
||||
{...props}
|
||||
ref={ref}
|
||||
className={twMerge(
|
||||
"bg-muted/40 focus:bg-muted rounded-md py-2.5 px-4 outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50",
|
||||
"appearance-none h-11 w-full",
|
||||
"border-r-8 border-r-transparent",
|
||||
props.className
|
||||
)}
|
||||
/>
|
||||
export const Select = forwardRef<
|
||||
HTMLSelectElement,
|
||||
React.ComponentProps<"select"> & {
|
||||
options?: { value: string; label: string }[] | (string | number)[];
|
||||
}
|
||||
>(({ children, options, ...props }, ref) => (
|
||||
<div className="flex w-full relative">
|
||||
<select
|
||||
{...props}
|
||||
ref={ref}
|
||||
className={twMerge(
|
||||
"bg-muted/40 focus:bg-muted rounded-md py-2.5 px-4 outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50",
|
||||
"appearance-none h-11 w-full",
|
||||
!props.multiple && "border-r-8 border-r-transparent",
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
{options ? (
|
||||
<>
|
||||
{!props.required && <option value="" />}
|
||||
{options
|
||||
.map((o, i) => {
|
||||
if (typeof o !== "object") {
|
||||
return { value: o, label: String(o) };
|
||||
}
|
||||
return o;
|
||||
})
|
||||
.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</select>
|
||||
{!props.multiple && (
|
||||
<TbChevronDown className="absolute right-3 top-0 bottom-0 h-full opacity-70" size={18} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Switch } from "@mantine/core";
|
||||
import { autoFormatString } from "core/utils";
|
||||
import { type JSONSchema, useFieldContext, useFormContext } from "json-schema-form-react";
|
||||
import type { ComponentPropsWithoutRef } from "react";
|
||||
import * as Formy from "ui/components/form/Formy";
|
||||
|
||||
// make a local version of JSONSchema that is always an object
|
||||
export type FieldProps = JSONSchema & {
|
||||
name: string;
|
||||
defaultValue?: any;
|
||||
hidden?: boolean;
|
||||
overrides?: ComponentPropsWithoutRef<"input">;
|
||||
};
|
||||
|
||||
export function Field(p: FieldProps) {
|
||||
const { schema, defaultValue, required } = useFieldContext(p.name);
|
||||
const props = {
|
||||
...(typeof schema === "object" ? schema : {}),
|
||||
defaultValue,
|
||||
required,
|
||||
...p
|
||||
} as FieldProps;
|
||||
console.log("schema", p.name, schema, defaultValue);
|
||||
|
||||
const field = renderField(props);
|
||||
const label = props.title
|
||||
? props.title
|
||||
: autoFormatString(
|
||||
props.name?.includes(".") ? (props.name.split(".").pop() as string) : props.name
|
||||
);
|
||||
|
||||
return p.hidden ? (
|
||||
field
|
||||
) : (
|
||||
<Formy.Group>
|
||||
<Formy.Label>
|
||||
{label}
|
||||
{props.required ? " *" : ""}
|
||||
</Formy.Label>
|
||||
{field}
|
||||
{props.description ? <Formy.Help>{props.description}</Formy.Help> : null}
|
||||
</Formy.Group>
|
||||
);
|
||||
}
|
||||
|
||||
function isType(_type: JSONSchema["type"], _compare: JSONSchema["type"]) {
|
||||
if (!_type || !_compare) return false;
|
||||
const type = Array.isArray(_type) ? _type : [_type];
|
||||
const compare = Array.isArray(_compare) ? _compare : [_compare];
|
||||
return compare.some((t) => type.includes(t));
|
||||
}
|
||||
|
||||
function renderField(props: FieldProps) {
|
||||
//console.log("renderField", props.name, props);
|
||||
const common = {
|
||||
name: props.name,
|
||||
defaultValue: typeof props.defaultValue !== "undefined" ? props.defaultValue : props.default
|
||||
} as any;
|
||||
|
||||
if (props.hidden) {
|
||||
common.type = "hidden";
|
||||
}
|
||||
|
||||
if (isType(props.type, "boolean")) {
|
||||
return (
|
||||
<div className="flex flex-row">
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
id={props.id}
|
||||
defaultChecked={props.defaultValue}
|
||||
name={props.name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
} else if (isType(props.type, ["number", "integer"])) {
|
||||
return <Formy.Input type="number" {...common} />;
|
||||
}
|
||||
|
||||
return <Formy.Input type="text" {...common} />;
|
||||
}
|
||||
|
||||
export function AutoForm({ schema, prefix = "" }: { schema: JSONSchema; prefix?: string }) {
|
||||
const required = schema.required ?? [];
|
||||
const properties = schema.properties ?? {};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/*<pre>{JSON.stringify(schema, null, 2)}</pre>;*/}
|
||||
<div>
|
||||
{Object.keys(properties).map((name) => {
|
||||
const field = properties[name];
|
||||
const _name = `${prefix ? prefix + "." : ""}${name}`;
|
||||
return <Field key={_name} name={_name} {...(field as any)} />;
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
2
app/src/ui/components/form/json-schema-form/index.ts
Normal file
2
app/src/ui/components/form/json-schema-form/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { TypeboxValidator, type ValueError } from "./validators/tb-validator";
|
||||
export { CfValidator, type OutputUnit } from "./validators/cf-validator";
|
||||
@@ -0,0 +1,11 @@
|
||||
import { type Schema as JsonSchema, type OutputUnit, Validator } from "@cfworker/json-schema";
|
||||
import type { Validator as TValidator } from "json-schema-form-react";
|
||||
|
||||
export class CfValidator implements TValidator<OutputUnit> {
|
||||
async validate(schema: JsonSchema, data: any) {
|
||||
const result = new Validator(schema).validate(data);
|
||||
return result.errors;
|
||||
}
|
||||
}
|
||||
|
||||
export type { OutputUnit };
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ValueError } from "@sinclair/typebox/value";
|
||||
import { type TSchema, Value } from "core/utils";
|
||||
import type { Validator } from "json-schema-form-react";
|
||||
|
||||
export class TypeboxValidator implements Validator<ValueError> {
|
||||
async validate(schema: TSchema, data: any) {
|
||||
return Value.Check(schema, data) ? [] : [...Value.Errors(schema, data)];
|
||||
}
|
||||
}
|
||||
|
||||
export type { ValueError };
|
||||
192
app/src/ui/components/form/json-schema-form2/Form.tsx
Normal file
192
app/src/ui/components/form/json-schema-form2/Form.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
import { Draft2019, type JsonError, type JsonSchema as LibJsonSchema } from "json-schema-library";
|
||||
import type { JSONSchema as $JSONSchema, FromSchema } from "json-schema-to-ts";
|
||||
import {
|
||||
type ComponentPropsWithoutRef,
|
||||
type FormEvent,
|
||||
createContext,
|
||||
startTransition,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState
|
||||
} from "react";
|
||||
import { flatten, getFormTarget, isRequired, normalizePath, unflatten } from "./utils";
|
||||
|
||||
type JSONSchema = Exclude<$JSONSchema, boolean>;
|
||||
type TFormData = Record<string, string>;
|
||||
|
||||
export type FormProps<
|
||||
Schema extends JSONSchema = JSONSchema,
|
||||
Data = Schema extends JSONSchema ? FromSchema<JSONSchema> : any
|
||||
> = Omit<ComponentPropsWithoutRef<"form">, "onChange"> & {
|
||||
schema: Schema;
|
||||
validateOn?: "change" | "submit";
|
||||
initialValues?: Partial<Data>;
|
||||
onChange?: (data: Partial<Data>, name: string, value: any) => void;
|
||||
hiddenSubmit?: boolean;
|
||||
};
|
||||
|
||||
export type FormContext = {
|
||||
data: TFormData;
|
||||
setData: (data: TFormData) => void;
|
||||
errors: JsonError[];
|
||||
schema: JSONSchema;
|
||||
lib: Draft2019;
|
||||
select: (pointer: string, choice: number | undefined) => void;
|
||||
selections: Record<string, number | undefined>;
|
||||
};
|
||||
|
||||
const FormContext = createContext<FormContext>(undefined!);
|
||||
|
||||
export function Form<
|
||||
Schema extends JSONSchema = JSONSchema,
|
||||
Data = Schema extends JSONSchema ? FromSchema<JSONSchema> : any
|
||||
>({
|
||||
schema: _schema,
|
||||
initialValues: _initialValues,
|
||||
children,
|
||||
onChange,
|
||||
validateOn = "submit",
|
||||
hiddenSubmit = true,
|
||||
...props
|
||||
}: FormProps<Schema, Data>) {
|
||||
const schema = useMemo(() => _schema, [JSON.stringify(_schema)]);
|
||||
const initialValues = useMemo(
|
||||
() => (_initialValues ? flatten(_initialValues) : {}),
|
||||
[JSON.stringify(_initialValues)]
|
||||
);
|
||||
|
||||
const [data, setData] = useState<TFormData>(initialValues);
|
||||
const [errors, setErrors] = useState<JsonError[]>([]);
|
||||
const [selections, setSelections] = useState<Record<string, number | undefined>>({});
|
||||
const lib = new Draft2019(schema);
|
||||
const formRef = useRef<HTMLFormElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
console.log("setting", initialValues);
|
||||
if (formRef.current) {
|
||||
Object.entries(initialValues).forEach(([name, value]) => {
|
||||
const pointer = normalizePath(name);
|
||||
const input = formRef.current?.elements.namedItem(pointer);
|
||||
if (input && "value" in input) {
|
||||
input.value = value as any;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [initialValues]);
|
||||
|
||||
async function handleChange(e: FormEvent<HTMLFormElement>) {
|
||||
const target = getFormTarget(e);
|
||||
if (!target) return;
|
||||
const name = normalizePath(target.name);
|
||||
|
||||
startTransition(() => {
|
||||
const newData = { ...data, [name]: target.value };
|
||||
setData(newData);
|
||||
|
||||
const actual = unflatten(newData, schema, selections);
|
||||
if (validateOn === "change") {
|
||||
validate(actual);
|
||||
}
|
||||
|
||||
onChange?.(actual, name, target.value);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const actual = unflatten(data, schema, selections);
|
||||
const { data: newData, errors } = validate(actual);
|
||||
setData(newData);
|
||||
console.log("submit", newData, errors);
|
||||
return false;
|
||||
}
|
||||
|
||||
function validate(_data?: object) {
|
||||
const actual = _data ?? unflatten(data, schema, selections);
|
||||
const errors = lib.validate(actual);
|
||||
console.log("validate", actual, errors);
|
||||
setErrors(errors);
|
||||
return {
|
||||
data: actual,
|
||||
errors
|
||||
};
|
||||
}
|
||||
|
||||
function select(pathOrPointer: string, choice: number | undefined) {
|
||||
setSelections((prev) => ({ ...prev, [normalizePath(pathOrPointer)]: choice }));
|
||||
}
|
||||
|
||||
const context = {
|
||||
data,
|
||||
setData,
|
||||
select,
|
||||
selections,
|
||||
errors,
|
||||
schema,
|
||||
lib
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<form {...props} ref={formRef} onChange={handleChange} onSubmit={handleSubmit}>
|
||||
<FormContext.Provider value={context}>{children}</FormContext.Provider>
|
||||
{hiddenSubmit && (
|
||||
<button style={{ visibility: "hidden" }} type="submit">
|
||||
Submit
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
<pre>{JSON.stringify(data, null, 2)}</pre>
|
||||
<pre>{JSON.stringify(unflatten(data, schema, selections), null, 2)}</pre>
|
||||
<pre>{JSON.stringify(errors, null, 2)}</pre>
|
||||
<pre>{JSON.stringify(selections, null, 2)}</pre>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function useFormContext() {
|
||||
return useContext(FormContext);
|
||||
}
|
||||
|
||||
export function useFieldContext(name: string) {
|
||||
const { data, setData, lib, schema, errors: formErrors, select, selections } = useFormContext();
|
||||
const pointer = normalizePath(name);
|
||||
//console.log("pointer", pointer);
|
||||
const value = data[pointer];
|
||||
const errors = formErrors.filter((error) => error.data.pointer === pointer);
|
||||
const fieldSchema = pointer === "#/" ? (schema as LibJsonSchema) : lib.getSchema({ pointer });
|
||||
const required = isRequired(pointer, schema);
|
||||
|
||||
return {
|
||||
value,
|
||||
setValue: (value: any) => setData({ ...data, [name]: value }),
|
||||
errors,
|
||||
schema: fieldSchema,
|
||||
pointer,
|
||||
required,
|
||||
select,
|
||||
selections
|
||||
};
|
||||
}
|
||||
|
||||
export function usePrefixContext(prefix: string) {
|
||||
const { data, setData, lib, schema, errors: formErrors, select, selections } = useFormContext();
|
||||
const pointer = normalizePath(prefix);
|
||||
const value = Object.fromEntries(Object.entries(data).filter(([key]) => key.startsWith(prefix)));
|
||||
const errors = formErrors.filter((error) => error.data.pointer.startsWith(pointer));
|
||||
const fieldSchema = pointer === "#/" ? (schema as LibJsonSchema) : lib.getSchema({ pointer });
|
||||
const required = isRequired(pointer, schema);
|
||||
|
||||
return {
|
||||
value,
|
||||
//setValue: (value: any) => setData({ ...data, [name]: value }),
|
||||
errors,
|
||||
schema: fieldSchema,
|
||||
pointer,
|
||||
required,
|
||||
select,
|
||||
selections
|
||||
};
|
||||
}
|
||||
198
app/src/ui/components/form/json-schema-form2/utils.ts
Normal file
198
app/src/ui/components/form/json-schema-form2/utils.ts
Normal file
@@ -0,0 +1,198 @@
|
||||
import { autoFormatString } from "core/utils";
|
||||
import { Draft2019, type JsonSchema } from "json-schema-library";
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import type { JSONSchemaType } from "json-schema-to-ts/lib/types/definitions/jsonSchema";
|
||||
import { set } from "lodash-es";
|
||||
import type { FormEvent } from "react";
|
||||
|
||||
export function getFormTarget(e: FormEvent<HTMLFormElement>) {
|
||||
const form = e.currentTarget;
|
||||
const target = e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
|
||||
|
||||
// check if target has attribute "data-ignore" set
|
||||
// also check if target is within a "data-ignore" element
|
||||
|
||||
if (
|
||||
!target ||
|
||||
!form.contains(target) ||
|
||||
!target.name ||
|
||||
target.hasAttribute("data-ignore") ||
|
||||
target.closest("[data-ignore]")
|
||||
) {
|
||||
return; // Ignore events from outside the form
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export function flatten(obj: any, parentKey = "", result: any = {}): any {
|
||||
for (const key in obj) {
|
||||
if (key in obj) {
|
||||
const newKey = parentKey ? `${parentKey}/${key}` : "#/" + key;
|
||||
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
|
||||
flatten(obj[key], newKey, result);
|
||||
} else if (Array.isArray(obj[key])) {
|
||||
obj[key].forEach((item, index) => {
|
||||
const arrayKey = `${newKey}.${index}`;
|
||||
if (typeof item === "object" && item !== null) {
|
||||
flatten(item, arrayKey, result);
|
||||
} else {
|
||||
result[arrayKey] = item;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
result[newKey] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// @todo: make sure it's in the right order
|
||||
export function unflatten(
|
||||
obj: Record<string, string>,
|
||||
schema: JSONSchema,
|
||||
selections?: Record<string, number | undefined>
|
||||
) {
|
||||
const result = {};
|
||||
const lib = new Draft2019(schema as any);
|
||||
for (const pointer in obj) {
|
||||
const required = isRequired(pointer, schema);
|
||||
let subschema = lib.getSchema({ pointer });
|
||||
console.log("subschema", pointer, subschema, selections);
|
||||
if (!subschema) {
|
||||
throw new Error(`"${pointer}" not found in schema`);
|
||||
}
|
||||
|
||||
// if subschema starts with "anyOf" or "oneOf"
|
||||
if (subschema.anyOf || subschema.oneOf) {
|
||||
const selected = selections?.[pointer];
|
||||
if (selected !== undefined) {
|
||||
subschema = subschema.anyOf ? subschema.anyOf[selected] : subschema.oneOf![selected];
|
||||
}
|
||||
}
|
||||
|
||||
const value = coerce(obj[pointer], subschema as any, { required });
|
||||
|
||||
set(result, pointer.substring(2).replace(/\//g, "."), value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function coerce(
|
||||
value: any,
|
||||
schema: Exclude<JSONSchema, boolean>,
|
||||
opts?: { required?: boolean }
|
||||
) {
|
||||
if (!value && typeof opts?.required === "boolean" && !opts.required) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
switch (schema.type) {
|
||||
case "string":
|
||||
return String(value);
|
||||
case "integer":
|
||||
case "number":
|
||||
return Number(value);
|
||||
case "boolean":
|
||||
return ["true", "1", 1, "on"].includes(value);
|
||||
case "null":
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* normalizes any path to a full json pointer
|
||||
*
|
||||
* examples: in -> out
|
||||
* description -> #/description
|
||||
* #/description -> #/description
|
||||
* /description -> #/description
|
||||
* nested/property -> #/nested/property
|
||||
* nested.property -> #/nested/property
|
||||
* nested.property[0] -> #/nested/property/0
|
||||
* nested.property[0].name -> #/nested/property/0/name
|
||||
* @param path
|
||||
*/
|
||||
export function normalizePath(path: string) {
|
||||
return path.startsWith("#/")
|
||||
? path
|
||||
: `#/${path.replace(/#?\/?/, "").replace(/\./g, "/").replace(/\[/g, "/").replace(/\]/g, "")}`;
|
||||
}
|
||||
|
||||
export function getParentPointer(pointer: string) {
|
||||
return pointer.substring(0, pointer.lastIndexOf("/"));
|
||||
}
|
||||
|
||||
export function isRequired(pointer: string, schema: JSONSchema, data?: any) {
|
||||
if (pointer === "#/") {
|
||||
return false;
|
||||
}
|
||||
const lib = new Draft2019(schema as any);
|
||||
|
||||
const childSchema = lib.getSchema({ pointer, data });
|
||||
if (typeof childSchema === "object" && ("const" in childSchema || "enum" in childSchema)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const parentPointer = getParentPointer(pointer);
|
||||
const parentSchema = lib.getSchema({ pointer: parentPointer, data });
|
||||
const required = parentSchema?.required?.includes(pointer.split("/").pop()!);
|
||||
|
||||
console.log("isRequired", {
|
||||
pointer,
|
||||
parentPointer,
|
||||
parent: parentSchema ? JSON.parse(JSON.stringify(parentSchema)) : null,
|
||||
required
|
||||
});
|
||||
|
||||
return !!required;
|
||||
}
|
||||
|
||||
type TType = JSONSchemaType | JSONSchemaType[] | readonly JSONSchemaType[] | undefined;
|
||||
export function isType(_type: TType, _compare: TType) {
|
||||
if (!_type || !_compare) return false;
|
||||
const type = Array.isArray(_type) ? _type : [_type];
|
||||
const compare = Array.isArray(_compare) ? _compare : [_compare];
|
||||
return compare.some((t) => type.includes(t));
|
||||
}
|
||||
|
||||
export function getLabel(name: string, schema: JSONSchema) {
|
||||
if (typeof schema === "object" && "title" in schema) return schema.title;
|
||||
const label = name.includes("/") ? (name.split("/").pop() ?? "") : name;
|
||||
return autoFormatString(label);
|
||||
}
|
||||
|
||||
export function getMultiSchema(schema: JSONSchema): Exclude<JSONSchema, boolean>[] | undefined {
|
||||
if (!schema || typeof schema !== "object") return;
|
||||
return (schema.anyOf ?? schema.oneOf) as any;
|
||||
}
|
||||
|
||||
export function getMultiSchemaMatched(
|
||||
schema: JsonSchema,
|
||||
data: any
|
||||
): [number, Exclude<JSONSchema, boolean>[], Exclude<JSONSchema, boolean> | undefined] {
|
||||
const multiSchema = getMultiSchema(schema);
|
||||
if (!multiSchema) return [-1, [], undefined];
|
||||
const index = multiSchema.findIndex((subschema) => {
|
||||
const lib = new Draft2019(subschema as any);
|
||||
return lib.validate(data, subschema).length === 0;
|
||||
});
|
||||
if (index === -1) return [-1, multiSchema, undefined];
|
||||
|
||||
return [index, multiSchema, multiSchema[index]];
|
||||
}
|
||||
|
||||
export function removeKeyRecursively<Given extends object>(obj: Given, keyToRemove: string): Given {
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => removeKeyRecursively(item, keyToRemove)) as any;
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj)
|
||||
.filter(([key]) => key !== keyToRemove)
|
||||
.map(([key, value]) => [key, removeKeyRecursively(value, keyToRemove)])
|
||||
) as any;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
115
app/src/ui/components/form/json-schema-form3/AnyOfField.tsx
Normal file
115
app/src/ui/components/form/json-schema-form3/AnyOfField.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import { type ChangeEvent, type ReactNode, createContext, useContext, useState } from "react";
|
||||
import * as Formy from "ui/components/form/Formy";
|
||||
import { FieldComponent, Field as FormField, type FieldProps as FormFieldProps } from "./Field";
|
||||
import { useFieldContext } from "./Form";
|
||||
import { getLabel, getMultiSchemaMatched } from "./utils";
|
||||
|
||||
export type AnyOfFieldRootProps = {
|
||||
path?: string;
|
||||
schema?: Exclude<JSONSchema, boolean>;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export type AnyOfFieldContext = {
|
||||
path: string;
|
||||
schema: Exclude<JSONSchema, boolean>;
|
||||
schemas?: JSONSchema[];
|
||||
selectedSchema?: Exclude<JSONSchema, boolean>;
|
||||
selected: number | null;
|
||||
select: (index: number | null) => void;
|
||||
options: string[];
|
||||
selectSchema: any;
|
||||
};
|
||||
|
||||
const AnyOfContext = createContext<AnyOfFieldContext>(undefined!);
|
||||
|
||||
export const useAnyOfContext = () => {
|
||||
const ctx = useContext(AnyOfContext);
|
||||
if (!ctx) throw new Error("useAnyOfContext: no context");
|
||||
return ctx;
|
||||
};
|
||||
|
||||
export const Root = ({ path = "", schema: _schema, children }: AnyOfFieldRootProps) => {
|
||||
const { setValue, pointer, lib, value, ...ctx } = useFieldContext(path);
|
||||
const schema = _schema ?? ctx.schema;
|
||||
if (!schema) return `AnyOfField(${path}): no schema ${pointer}`;
|
||||
const [matchedIndex, schemas = []] = getMultiSchemaMatched(schema, value);
|
||||
const [selected, setSelected] = useState<number | null>(matchedIndex > -1 ? matchedIndex : null);
|
||||
const options = schemas.map((s, i) => s.title ?? `Option ${i + 1}`);
|
||||
const selectSchema = {
|
||||
enum: options
|
||||
};
|
||||
|
||||
const selectedSchema =
|
||||
selected !== null ? (schemas[selected] as Exclude<JSONSchema, boolean>) : undefined;
|
||||
|
||||
function select(index: number | null) {
|
||||
setValue(pointer, index !== null ? lib.getTemplate(undefined, schemas[index]) : undefined);
|
||||
setSelected(index);
|
||||
}
|
||||
|
||||
return (
|
||||
<AnyOfContext.Provider
|
||||
value={{ selected, select, options, selectSchema, path, schema, schemas, selectedSchema }}
|
||||
>
|
||||
{children}
|
||||
</AnyOfContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const Select = () => {
|
||||
const { selected, select, path, schema, selectSchema } = useAnyOfContext();
|
||||
|
||||
function handleSelect(e: ChangeEvent<HTMLInputElement>) {
|
||||
console.log("selected", e.target.value);
|
||||
const i = e.target.value ? Number(e.target.value) : null;
|
||||
select(i);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Formy.Label>{getLabel(path, schema)}</Formy.Label>
|
||||
<FieldComponent
|
||||
schema={selectSchema as any}
|
||||
onChange={handleSelect}
|
||||
value={selected ?? undefined}
|
||||
className="h-8 py-1"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const Field = ({ name, label, ...props }: Partial<FormFieldProps>) => {
|
||||
const { selected, selectedSchema, path } = useAnyOfContext();
|
||||
if (selected === null) return null;
|
||||
return (
|
||||
<FormField
|
||||
key={`${path}_${selected}`}
|
||||
schema={selectedSchema}
|
||||
name={path}
|
||||
label={false}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const AnyOf = {
|
||||
Root,
|
||||
Select,
|
||||
Field,
|
||||
useContext: useAnyOfContext
|
||||
};
|
||||
|
||||
export const AnyOfField = (props: Omit<AnyOfFieldRootProps, "children">) => {
|
||||
return (
|
||||
<fieldset>
|
||||
<AnyOf.Root {...props}>
|
||||
<legend className="flex flex-row gap-2 items-center py-2">
|
||||
<AnyOf.Select />
|
||||
</legend>
|
||||
<AnyOf.Field />
|
||||
</AnyOf.Root>
|
||||
</fieldset>
|
||||
);
|
||||
};
|
||||
101
app/src/ui/components/form/json-schema-form3/ArrayField.tsx
Normal file
101
app/src/ui/components/form/json-schema-form3/ArrayField.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { IconLibraryPlus, IconTrash } from "@tabler/icons-react";
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import { Button } from "ui/components/buttons/Button";
|
||||
import { IconButton } from "ui/components/buttons/IconButton";
|
||||
import * as Formy from "ui/components/form/Formy";
|
||||
import { Dropdown } from "ui/components/overlay/Dropdown";
|
||||
import { FieldComponent } from "./Field";
|
||||
import { FieldWrapper } from "./FieldWrapper";
|
||||
import { useFieldContext } from "./Form";
|
||||
import { coerce, getMultiSchema, getMultiSchemaMatched } from "./utils";
|
||||
|
||||
export const ArrayField = ({
|
||||
path = "",
|
||||
schema: _schema
|
||||
}: { path?: string; schema?: Exclude<JSONSchema, boolean> }) => {
|
||||
const { setValue, value, pointer, required, ...ctx } = useFieldContext(path);
|
||||
const schema = _schema ?? ctx.schema;
|
||||
if (!schema || typeof schema === "undefined") return `ArrayField(${path}): no schema ${pointer}`;
|
||||
|
||||
const itemsMultiSchema = getMultiSchema(schema.items);
|
||||
|
||||
function handleAdd(template?: any) {
|
||||
const currentIndex = value?.length ?? 0;
|
||||
const newPointer = `${path}/${currentIndex}`.replace(/\/+/g, "/");
|
||||
setValue(newPointer, template ?? ctx.lib.getTemplate(undefined, schema!.items));
|
||||
}
|
||||
|
||||
function handleUpdate(pointer: string, value: any) {
|
||||
setValue(pointer, value);
|
||||
}
|
||||
|
||||
function handleDelete(pointer: string) {
|
||||
return () => {
|
||||
ctx.deleteValue(pointer);
|
||||
};
|
||||
}
|
||||
|
||||
const Wrapper = ({ children }) => (
|
||||
<FieldWrapper pointer={path} schema={schema} wrapper="fieldset">
|
||||
{children}
|
||||
</FieldWrapper>
|
||||
);
|
||||
|
||||
if (schema.uniqueItems && typeof schema.items === "object" && "enum" in schema.items) {
|
||||
return (
|
||||
<Wrapper>
|
||||
<Formy.Select
|
||||
required
|
||||
options={schema.items.enum}
|
||||
multiple
|
||||
value={value}
|
||||
className="h-auto"
|
||||
onChange={(e) => {
|
||||
const selected = Array.from(e.target.selectedOptions).map((o) => o.value);
|
||||
console.log("selected", selected);
|
||||
setValue(pointer, selected);
|
||||
}}
|
||||
/>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Wrapper>
|
||||
{value?.map((v, index: number) => {
|
||||
const pointer = `${path}/${index}`.replace(/\/+/g, "/");
|
||||
const [, , subschema] = getMultiSchemaMatched(schema.items, v);
|
||||
return (
|
||||
<div key={pointer} className="flex flex-row gap-2">
|
||||
<FieldComponent
|
||||
name={pointer}
|
||||
schema={subschema!}
|
||||
value={v}
|
||||
onChange={(e) => {
|
||||
handleUpdate(pointer, coerce(e.target.value, subschema!));
|
||||
}}
|
||||
className="w-full"
|
||||
/>
|
||||
<IconButton Icon={IconTrash} onClick={handleDelete(pointer)} size="sm" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{itemsMultiSchema ? (
|
||||
<Dropdown
|
||||
dropdownWrapperProps={{
|
||||
className: "min-w-0"
|
||||
}}
|
||||
items={itemsMultiSchema.map((s, i) => ({
|
||||
label: s!.title ?? `Option ${i + 1}`,
|
||||
onClick: () => handleAdd(ctx.lib.getTemplate(undefined, s!))
|
||||
}))}
|
||||
onClickItem={console.log}
|
||||
>
|
||||
<Button IconLeft={IconLibraryPlus}>Add</Button>
|
||||
</Dropdown>
|
||||
) : (
|
||||
<Button onClick={() => handleAdd()}>Add</Button>
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
93
app/src/ui/components/form/json-schema-form3/Field.tsx
Normal file
93
app/src/ui/components/form/json-schema-form3/Field.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import type { ChangeEvent, ComponentPropsWithoutRef } from "react";
|
||||
import * as Formy from "ui/components/form/Formy";
|
||||
import { ArrayField } from "./ArrayField";
|
||||
import { FieldWrapper } from "./FieldWrapper";
|
||||
import { useFieldContext } from "./Form";
|
||||
import { ObjectField } from "./ObjectField";
|
||||
import { coerce, isType } from "./utils";
|
||||
|
||||
export type FieldProps = {
|
||||
name: string;
|
||||
schema?: Exclude<JSONSchema, boolean>;
|
||||
onChange?: (e: ChangeEvent<any>) => void;
|
||||
label?: string | false;
|
||||
hidden?: boolean;
|
||||
};
|
||||
|
||||
export const Field = ({ name, schema: _schema, onChange, label: _label, hidden }: FieldProps) => {
|
||||
const { pointer, value, errors, setValue, required, ...ctx } = useFieldContext(name);
|
||||
const schema = _schema ?? ctx.schema;
|
||||
if (!schema) return `"${name}" (${pointer}) has no schema`;
|
||||
|
||||
if (isType(schema.type, "object")) {
|
||||
return <ObjectField path={name} schema={schema} />;
|
||||
}
|
||||
|
||||
if (isType(schema.type, "array")) {
|
||||
return <ArrayField path={name} schema={schema} />;
|
||||
}
|
||||
|
||||
const disabled = schema.readOnly ?? "const" in schema ?? false;
|
||||
//console.log("field", name, disabled, schema, ctx.schema, _schema);
|
||||
|
||||
function handleChange(e: ChangeEvent<HTMLInputElement>) {
|
||||
// don't remove for now, causes issues in anyOf
|
||||
/*const value = coerce(e.target.value, schema as any);
|
||||
setValue(pointer, value as any);*/
|
||||
|
||||
const value = coerce(e.target.value, schema as any, { required });
|
||||
//console.log("handleChange", pointer, e.target.value, { value });
|
||||
if (!value && !required) {
|
||||
ctx.deleteValue(pointer);
|
||||
} else {
|
||||
setValue(pointer, value);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<FieldWrapper
|
||||
pointer={pointer}
|
||||
label={_label}
|
||||
required={required}
|
||||
errors={errors}
|
||||
schema={schema}
|
||||
debug={{ value }}
|
||||
hidden={hidden}
|
||||
>
|
||||
<FieldComponent
|
||||
schema={schema}
|
||||
name={pointer}
|
||||
placeholder={pointer}
|
||||
required={required}
|
||||
disabled={disabled}
|
||||
value={value}
|
||||
onChange={onChange ?? handleChange}
|
||||
/>
|
||||
</FieldWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export const FieldComponent = ({
|
||||
schema,
|
||||
...props
|
||||
}: { schema: JSONSchema } & ComponentPropsWithoutRef<"input">) => {
|
||||
if (!schema || typeof schema === "boolean") return null;
|
||||
//console.log("field", props.name, props.disabled);
|
||||
|
||||
if (schema.enum) {
|
||||
if (!Array.isArray(schema.enum)) return null;
|
||||
let options = schema.enum;
|
||||
if (schema.enum.every((v) => typeof v === "string")) {
|
||||
options = schema.enum.map((v, i) => ({ value: i, label: v }));
|
||||
}
|
||||
|
||||
return <Formy.Select {...(props as any)} options={options} />;
|
||||
}
|
||||
|
||||
if (isType(schema.type, ["number", "integer"])) {
|
||||
return <Formy.Input type="number" {...props} value={props.value ?? ""} />;
|
||||
}
|
||||
|
||||
return <Formy.Input {...props} value={props.value ?? ""} />;
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Popover } from "@mantine/core";
|
||||
import { IconBug } from "@tabler/icons-react";
|
||||
import type { JsonError } from "json-schema-library";
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import { Children, type ReactElement, type ReactNode, cloneElement } from "react";
|
||||
import { IconButton } from "ui/components/buttons/IconButton";
|
||||
import { JsonViewer } from "ui/components/code/JsonViewer";
|
||||
import * as Formy from "ui/components/form/Formy";
|
||||
import { getLabel } from "./utils";
|
||||
|
||||
export type FieldwrapperProps = {
|
||||
pointer: string;
|
||||
label?: string | false;
|
||||
required?: boolean;
|
||||
errors?: JsonError[];
|
||||
schema?: Exclude<JSONSchema, boolean>;
|
||||
debug?: object;
|
||||
wrapper?: "group" | "fieldset";
|
||||
hidden?: boolean;
|
||||
children: ReactElement | ReactNode;
|
||||
};
|
||||
|
||||
export function FieldWrapper({
|
||||
pointer,
|
||||
label: _label,
|
||||
required,
|
||||
errors = [],
|
||||
schema,
|
||||
debug = {},
|
||||
wrapper,
|
||||
hidden,
|
||||
children
|
||||
}: FieldwrapperProps) {
|
||||
const examples = schema?.examples || [];
|
||||
const examplesId = `${pointer}-examples`;
|
||||
const description = schema?.description;
|
||||
const label =
|
||||
typeof _label !== "undefined" ? _label : schema ? getLabel(pointer, schema) : pointer;
|
||||
|
||||
return (
|
||||
<Formy.Group
|
||||
error={errors.length > 0}
|
||||
as={wrapper === "fieldset" ? "fieldset" : "div"}
|
||||
className={hidden ? "hidden" : "relative"}
|
||||
>
|
||||
<div className="absolute right-0 top-0">
|
||||
<Popover>
|
||||
<Popover.Target>
|
||||
<IconButton Icon={IconBug} size="xs" className="opacity-30" />
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown>
|
||||
<JsonViewer
|
||||
json={{ ...debug, pointer, required, schema, errors }}
|
||||
expand={6}
|
||||
className="p-0"
|
||||
/>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{label && (
|
||||
<Formy.Label as={wrapper === "fieldset" ? "legend" : "label"}>
|
||||
{label} {required ? "*" : ""}
|
||||
</Formy.Label>
|
||||
)}
|
||||
<div className="flex flex-row gap-2">
|
||||
<div className="flex flex-1 flex-col gap-3">
|
||||
{children}
|
||||
{/*{Children.count(children) === 1
|
||||
? cloneElement(children, {
|
||||
list: examples.length > 0 ? examplesId : undefined
|
||||
})
|
||||
: children}
|
||||
{examples.length > 0 && (
|
||||
<datalist id={examplesId}>
|
||||
{examples.map((e, i) => (
|
||||
<option key={i} value={e as any} />
|
||||
))}
|
||||
</datalist>
|
||||
)}*/}
|
||||
</div>
|
||||
</div>
|
||||
{description && <Formy.Help>{description}</Formy.Help>}
|
||||
{errors.length > 0 && (
|
||||
<Formy.ErrorMessage>{errors.map((e) => e.message).join(", ")}</Formy.ErrorMessage>
|
||||
)}
|
||||
</Formy.Group>
|
||||
);
|
||||
}
|
||||
196
app/src/ui/components/form/json-schema-form3/Form.tsx
Normal file
196
app/src/ui/components/form/json-schema-form3/Form.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
import { Draft2019, type JsonError } from "json-schema-library";
|
||||
import type { TemplateOptions as LibTemplateOptions } from "json-schema-library/dist/lib/getTemplate";
|
||||
import type { JsonSchema as LibJsonSchema } from "json-schema-library/dist/lib/types";
|
||||
import type { JSONSchema as $JSONSchema, FromSchema } from "json-schema-to-ts";
|
||||
import { get } from "lodash-es";
|
||||
import * as immutable from "object-path-immutable";
|
||||
import {
|
||||
type ComponentPropsWithoutRef,
|
||||
type FormEvent,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState
|
||||
} from "react";
|
||||
import { Field } from "./Field";
|
||||
import { isRequired, normalizePath, prefixPointer } from "./utils";
|
||||
|
||||
type JSONSchema = Exclude<$JSONSchema, boolean>;
|
||||
|
||||
export type FormProps<
|
||||
Schema extends JSONSchema = JSONSchema,
|
||||
Data = Schema extends JSONSchema ? FromSchema<JSONSchema> : any
|
||||
> = Omit<ComponentPropsWithoutRef<"form">, "onChange"> & {
|
||||
schema: Schema;
|
||||
validateOn?: "change" | "submit";
|
||||
initialValues?: Partial<Data>;
|
||||
initialOpts?: LibTemplateOptions;
|
||||
onChange?: (data: Partial<Data>, name: string, value: any) => void;
|
||||
hiddenSubmit?: boolean;
|
||||
};
|
||||
|
||||
export type FormContext<Data> = {
|
||||
data: Data;
|
||||
setData: (data: Data) => void;
|
||||
setValue: (pointer: string, value: any) => void;
|
||||
deleteValue: (pointer: string) => void;
|
||||
errors: JsonError[];
|
||||
schema: JSONSchema;
|
||||
lib: Draft2019;
|
||||
};
|
||||
|
||||
const FormContext = createContext<FormContext<any>>(undefined!);
|
||||
|
||||
export function Form<
|
||||
Schema extends JSONSchema = JSONSchema,
|
||||
Data = Schema extends JSONSchema ? FromSchema<JSONSchema> : any
|
||||
>({
|
||||
schema,
|
||||
initialValues,
|
||||
initialOpts,
|
||||
children,
|
||||
onChange,
|
||||
validateOn = "submit",
|
||||
hiddenSubmit = true,
|
||||
...props
|
||||
}: FormProps<Schema, Data>) {
|
||||
const lib = new Draft2019(schema);
|
||||
const [data, setData] = useState<Partial<Data>>(
|
||||
initialValues ?? lib.getTemplate(undefined, schema, initialOpts)
|
||||
);
|
||||
const formRef = useRef<HTMLFormElement | null>(null);
|
||||
const [errors, setErrors] = useState<JsonError[]>([]);
|
||||
|
||||
async function handleChange(e: FormEvent<HTMLFormElement>) {}
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
}
|
||||
|
||||
function setValue(pointer: string, value: any) {
|
||||
const normalized = normalizePath(pointer);
|
||||
console.log("setValue", { pointer, normalized, value });
|
||||
const key = normalized.substring(2).replace(/\//g, ".");
|
||||
setData((prev) => {
|
||||
const changed = immutable.set(prev, key, value);
|
||||
//console.log("changed", prev, changed, { key, value });
|
||||
return changed;
|
||||
});
|
||||
}
|
||||
|
||||
function deleteValue(pointer: string) {
|
||||
const normalized = normalizePath(pointer);
|
||||
const key = normalized.substring(2).replace(/\//g, ".");
|
||||
setData((prev) => {
|
||||
const changed = immutable.del(prev, key);
|
||||
//console.log("changed", prev, changed, { key });
|
||||
return changed;
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (validateOn === "change") {
|
||||
validate();
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
function validate(_data?: Partial<Data>) {
|
||||
const actual = _data ?? data;
|
||||
const errors = lib.validate(actual, schema);
|
||||
//console.log("errors", errors);
|
||||
setErrors(errors);
|
||||
return { data: actual, errors };
|
||||
}
|
||||
|
||||
const context = {
|
||||
data: data ?? {},
|
||||
setData,
|
||||
setValue,
|
||||
deleteValue,
|
||||
errors,
|
||||
schema,
|
||||
lib
|
||||
} as any;
|
||||
//console.log("context", context);
|
||||
|
||||
return (
|
||||
<>
|
||||
<form {...props} ref={formRef} onChange={handleChange} onSubmit={handleSubmit}>
|
||||
<FormContext.Provider value={context}>
|
||||
{children ? children : <Field name="" />}
|
||||
</FormContext.Provider>
|
||||
{hiddenSubmit && (
|
||||
<button style={{ visibility: "hidden" }} type="submit">
|
||||
Submit
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
<pre>{JSON.stringify(data, null, 2)}</pre>
|
||||
<pre>{JSON.stringify(errors, null, 2)}</pre>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function useFormContext() {
|
||||
return useContext(FormContext);
|
||||
}
|
||||
|
||||
export function FormContextOverride({
|
||||
children,
|
||||
overrideData,
|
||||
path,
|
||||
...overrides
|
||||
}: Partial<FormContext<any>> & { children: ReactNode; path?: string; overrideData?: boolean }) {
|
||||
const ctx = useFormContext();
|
||||
const additional: Partial<FormContext<any>> = {};
|
||||
|
||||
// this makes a local schema down the three
|
||||
// especially useful for AnyOf, since it doesn't need to fully validate (e.g. pattern)
|
||||
if (overrideData && path) {
|
||||
const pointer = normalizePath(path);
|
||||
const value =
|
||||
pointer === "#/" ? ctx.data : get(ctx.data, pointer.substring(2).replace(/\//g, "."));
|
||||
|
||||
additional.data = value;
|
||||
additional.setValue = (pointer: string, value: any) => {
|
||||
ctx.setValue(prefixPointer(pointer, path), value);
|
||||
};
|
||||
additional.deleteValue = (pointer: string) => {
|
||||
ctx.deleteValue(prefixPointer(pointer, path));
|
||||
};
|
||||
}
|
||||
|
||||
const context = {
|
||||
...ctx,
|
||||
...overrides,
|
||||
...additional
|
||||
};
|
||||
|
||||
return <FormContext.Provider value={context}>{children}</FormContext.Provider>;
|
||||
}
|
||||
|
||||
export function useFieldContext(name: string) {
|
||||
const { data, lib, schema, errors: formErrors, ...rest } = useFormContext();
|
||||
const pointer = normalizePath(name);
|
||||
const isRootPointer = pointer === "#/";
|
||||
//console.log("pointer", pointer);
|
||||
const value = isRootPointer ? data : get(data, pointer.substring(2).replace(/\//g, "."));
|
||||
const errors = formErrors.filter((error) => error.data.pointer.startsWith(pointer));
|
||||
const fieldSchema = isRootPointer
|
||||
? (schema as LibJsonSchema)
|
||||
: lib.getSchema({ pointer, data, schema });
|
||||
const required = isRequired(pointer, schema, data);
|
||||
|
||||
return {
|
||||
...rest,
|
||||
lib,
|
||||
value,
|
||||
errors,
|
||||
schema: fieldSchema,
|
||||
pointer,
|
||||
required
|
||||
};
|
||||
}
|
||||
46
app/src/ui/components/form/json-schema-form3/ObjectField.tsx
Normal file
46
app/src/ui/components/form/json-schema-form3/ObjectField.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import { AnyOfField } from "./AnyOfField";
|
||||
import { Field } from "./Field";
|
||||
import { FieldWrapper, type FieldwrapperProps } from "./FieldWrapper";
|
||||
import { useFieldContext } from "./Form";
|
||||
|
||||
export type ObjectFieldProps = {
|
||||
path?: string;
|
||||
schema?: Exclude<JSONSchema, boolean>;
|
||||
label?: string | false;
|
||||
wrapperProps?: Partial<FieldwrapperProps>;
|
||||
};
|
||||
|
||||
export const ObjectField = ({
|
||||
path = "",
|
||||
schema: _schema,
|
||||
label: _label,
|
||||
wrapperProps = {}
|
||||
}: ObjectFieldProps) => {
|
||||
const { errors, ...ctx } = useFieldContext(path);
|
||||
const schema = _schema ?? ctx.schema;
|
||||
if (!schema) return "ObjectField: no schema";
|
||||
const properties = schema.properties ?? {};
|
||||
|
||||
return (
|
||||
<FieldWrapper
|
||||
pointer={path}
|
||||
errors={errors}
|
||||
schema={schema}
|
||||
wrapper="fieldset"
|
||||
{...wrapperProps}
|
||||
>
|
||||
{Object.keys(properties).map((prop) => {
|
||||
const schema = properties[prop];
|
||||
const pointer = `${path}/${prop}`.replace(/\/+/g, "/");
|
||||
if (!schema) return;
|
||||
|
||||
if (schema.anyOf || schema.oneOf) {
|
||||
return <AnyOfField key={pointer} path={pointer} schema={schema} />;
|
||||
}
|
||||
|
||||
return <Field key={pointer} name={pointer} schema={schema} />;
|
||||
})}
|
||||
</FieldWrapper>
|
||||
);
|
||||
};
|
||||
202
app/src/ui/components/form/json-schema-form3/utils.ts
Normal file
202
app/src/ui/components/form/json-schema-form3/utils.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import { autoFormatString } from "core/utils";
|
||||
import { Draft2019, type JsonSchema } from "json-schema-library";
|
||||
import type { JSONSchema } from "json-schema-to-ts";
|
||||
import type { JSONSchemaType } from "json-schema-to-ts/lib/types/definitions/jsonSchema";
|
||||
import { set } from "lodash-es";
|
||||
import type { FormEvent } from "react";
|
||||
|
||||
export function getFormTarget(e: FormEvent<HTMLFormElement>) {
|
||||
const form = e.currentTarget;
|
||||
const target = e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
|
||||
|
||||
// check if target has attribute "data-ignore" set
|
||||
// also check if target is within a "data-ignore" element
|
||||
|
||||
if (
|
||||
!target ||
|
||||
!form.contains(target) ||
|
||||
!target.name ||
|
||||
target.hasAttribute("data-ignore") ||
|
||||
target.closest("[data-ignore]")
|
||||
) {
|
||||
return; // Ignore events from outside the form
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export function flatten(obj: any, parentKey = "", result: any = {}): any {
|
||||
for (const key in obj) {
|
||||
if (key in obj) {
|
||||
const newKey = parentKey ? `${parentKey}/${key}` : "#/" + key;
|
||||
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
|
||||
flatten(obj[key], newKey, result);
|
||||
} else if (Array.isArray(obj[key])) {
|
||||
obj[key].forEach((item, index) => {
|
||||
const arrayKey = `${newKey}.${index}`;
|
||||
if (typeof item === "object" && item !== null) {
|
||||
flatten(item, arrayKey, result);
|
||||
} else {
|
||||
result[arrayKey] = item;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
result[newKey] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// @todo: make sure it's in the right order
|
||||
export function unflatten(
|
||||
obj: Record<string, string>,
|
||||
schema: JSONSchema,
|
||||
selections?: Record<string, number | undefined>
|
||||
) {
|
||||
const result = {};
|
||||
const lib = new Draft2019(schema as any);
|
||||
for (const pointer in obj) {
|
||||
const required = isRequired(pointer, schema);
|
||||
let subschema = lib.getSchema({ pointer });
|
||||
console.log("subschema", pointer, subschema, selections);
|
||||
if (!subschema) {
|
||||
throw new Error(`"${pointer}" not found in schema`);
|
||||
}
|
||||
|
||||
// if subschema starts with "anyOf" or "oneOf"
|
||||
if (subschema.anyOf || subschema.oneOf) {
|
||||
const selected = selections?.[pointer];
|
||||
if (selected !== undefined) {
|
||||
subschema = subschema.anyOf ? subschema.anyOf[selected] : subschema.oneOf![selected];
|
||||
}
|
||||
}
|
||||
|
||||
const value = coerce(obj[pointer], subschema as any, { required });
|
||||
|
||||
set(result, pointer.substring(2).replace(/\//g, "."), value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function coerce(
|
||||
value: any,
|
||||
schema: Exclude<JSONSchema, boolean>,
|
||||
opts?: { required?: boolean }
|
||||
) {
|
||||
if (!value && typeof opts?.required === "boolean" && !opts.required) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
switch (schema.type) {
|
||||
case "string":
|
||||
return String(value);
|
||||
case "integer":
|
||||
case "number":
|
||||
return Number(value);
|
||||
case "boolean":
|
||||
return ["true", "1", 1, "on"].includes(value);
|
||||
case "null":
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* normalizes any path to a full json pointer
|
||||
*
|
||||
* examples: in -> out
|
||||
* description -> #/description
|
||||
* #/description -> #/description
|
||||
* /description -> #/description
|
||||
* nested/property -> #/nested/property
|
||||
* nested.property -> #/nested/property
|
||||
* nested.property[0] -> #/nested/property/0
|
||||
* nested.property[0].name -> #/nested/property/0/name
|
||||
* @param path
|
||||
*/
|
||||
export function normalizePath(path: string) {
|
||||
return path.startsWith("#/")
|
||||
? path
|
||||
: `#/${path.replace(/#?\/?/, "").replace(/\./g, "/").replace(/\[/g, "/").replace(/\]/g, "")}`;
|
||||
}
|
||||
|
||||
export function prefixPointer(pointer: string, prefix: string) {
|
||||
return pointer.replace("#/", `#/${prefix}/`);
|
||||
}
|
||||
|
||||
export function getParentPointer(pointer: string) {
|
||||
return pointer.substring(0, pointer.lastIndexOf("/"));
|
||||
}
|
||||
|
||||
export function isRequired(pointer: string, schema: JSONSchema, data?: any) {
|
||||
if (pointer === "#/") {
|
||||
return false;
|
||||
}
|
||||
const lib = new Draft2019(schema as any);
|
||||
|
||||
const childSchema = lib.getSchema({ pointer, data });
|
||||
if (typeof childSchema === "object" && ("const" in childSchema || "enum" in childSchema)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const parentPointer = getParentPointer(pointer);
|
||||
const parentSchema = lib.getSchema({ pointer: parentPointer, data });
|
||||
const required = parentSchema?.required?.includes(pointer.split("/").pop()!);
|
||||
|
||||
/*console.log("isRequired", {
|
||||
pointer,
|
||||
parentPointer,
|
||||
parent: parentSchema ? JSON.parse(JSON.stringify(parentSchema)) : null,
|
||||
required
|
||||
});*/
|
||||
|
||||
return !!required;
|
||||
}
|
||||
|
||||
type TType = JSONSchemaType | JSONSchemaType[] | readonly JSONSchemaType[] | undefined;
|
||||
export function isType(_type: TType, _compare: TType) {
|
||||
if (!_type || !_compare) return false;
|
||||
const type = Array.isArray(_type) ? _type : [_type];
|
||||
const compare = Array.isArray(_compare) ? _compare : [_compare];
|
||||
return compare.some((t) => type.includes(t));
|
||||
}
|
||||
|
||||
export function getLabel(name: string, schema: JSONSchema) {
|
||||
if (typeof schema === "object" && "title" in schema) return schema.title;
|
||||
const label = name.includes("/") ? (name.split("/").pop() ?? "") : name;
|
||||
return autoFormatString(label);
|
||||
}
|
||||
|
||||
export function getMultiSchema(schema: JSONSchema): Exclude<JSONSchema, boolean>[] | undefined {
|
||||
if (!schema || typeof schema !== "object") return;
|
||||
return (schema.anyOf ?? schema.oneOf) as any;
|
||||
}
|
||||
|
||||
export function getMultiSchemaMatched(
|
||||
schema: JsonSchema,
|
||||
data: any
|
||||
): [number, Exclude<JSONSchema, boolean>[], Exclude<JSONSchema, boolean> | undefined] {
|
||||
const multiSchema = getMultiSchema(schema);
|
||||
if (!multiSchema) return [-1, [], undefined];
|
||||
const index = multiSchema.findIndex((subschema) => {
|
||||
const lib = new Draft2019(subschema as any);
|
||||
return lib.validate(data, subschema).length === 0;
|
||||
});
|
||||
if (index === -1) return [-1, multiSchema, undefined];
|
||||
|
||||
return [index, multiSchema, multiSchema[index]];
|
||||
}
|
||||
|
||||
export function removeKeyRecursively<Given extends object>(obj: Given, keyToRemove: string): Given {
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => removeKeyRecursively(item, keyToRemove)) as any;
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj)
|
||||
.filter(([key]) => key !== keyToRemove)
|
||||
.map(([key, value]) => [key, removeKeyRecursively(value, keyToRemove)])
|
||||
) as any;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
Reference in New Issue
Block a user