mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 20:37:21 +00:00
changed media settings to new form
This commit is contained in:
@@ -2,7 +2,7 @@ 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 { FormContextOverride, useFieldContext } from "./Form";
|
||||
import { getLabel, getMultiSchemaMatched } from "./utils";
|
||||
|
||||
export type AnyOfFieldRootProps = {
|
||||
@@ -30,7 +30,7 @@ export const useAnyOfContext = () => {
|
||||
return ctx;
|
||||
};
|
||||
|
||||
export const Root = ({ path = "", schema: _schema, children }: AnyOfFieldRootProps) => {
|
||||
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}`;
|
||||
@@ -58,7 +58,7 @@ export const Root = ({ path = "", schema: _schema, children }: AnyOfFieldRootPro
|
||||
);
|
||||
};
|
||||
|
||||
export const Select = () => {
|
||||
const Select = () => {
|
||||
const { selected, select, path, schema, selectSchema } = useAnyOfContext();
|
||||
|
||||
function handleSelect(e: ChangeEvent<HTMLInputElement>) {
|
||||
@@ -80,17 +80,13 @@ export const Select = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export const Field = ({ name, label, ...props }: Partial<FormFieldProps>) => {
|
||||
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}
|
||||
/>
|
||||
<FormContextOverride path={path} schema={selectedSchema} overrideData>
|
||||
<FormField key={`${path}_${selected}`} name={""} label={false} {...props} />
|
||||
</FormContextOverride>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ 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 { get, isEqual } from "lodash-es";
|
||||
import * as immutable from "object-path-immutable";
|
||||
import {
|
||||
type ComponentPropsWithoutRef,
|
||||
@@ -37,6 +37,7 @@ export type FormContext<Data> = {
|
||||
setValue: (pointer: string, value: any) => void;
|
||||
deleteValue: (pointer: string) => void;
|
||||
errors: JsonError[];
|
||||
dirty: boolean;
|
||||
schema: JSONSchema;
|
||||
lib: Draft2019;
|
||||
};
|
||||
@@ -48,7 +49,7 @@ export function Form<
|
||||
Data = Schema extends JSONSchema ? FromSchema<JSONSchema> : any
|
||||
>({
|
||||
schema,
|
||||
initialValues,
|
||||
initialValues: _initialValues,
|
||||
initialOpts,
|
||||
children,
|
||||
onChange,
|
||||
@@ -57,9 +58,9 @@ export function Form<
|
||||
...props
|
||||
}: FormProps<Schema, Data>) {
|
||||
const lib = new Draft2019(schema);
|
||||
const [data, setData] = useState<Partial<Data>>(
|
||||
initialValues ?? lib.getTemplate(undefined, schema, initialOpts)
|
||||
);
|
||||
const initialValues = _initialValues ?? lib.getTemplate(undefined, schema, initialOpts);
|
||||
const [data, setData] = useState<Partial<Data>>(initialValues);
|
||||
const [dirty, setDirty] = useState<boolean>(false);
|
||||
const formRef = useRef<HTMLFormElement | null>(null);
|
||||
const [errors, setErrors] = useState<JsonError[]>([]);
|
||||
|
||||
@@ -72,10 +73,11 @@ export function Form<
|
||||
|
||||
function setValue(pointer: string, value: any) {
|
||||
const normalized = normalizePath(pointer);
|
||||
console.log("setValue", { pointer, normalized, value });
|
||||
//console.log("setValue", { pointer, normalized, value });
|
||||
const key = normalized.substring(2).replace(/\//g, ".");
|
||||
setData((prev) => {
|
||||
const changed = immutable.set(prev, key, value);
|
||||
onChange?.(changed, key, value);
|
||||
//console.log("changed", prev, changed, { key, value });
|
||||
return changed;
|
||||
});
|
||||
@@ -86,12 +88,15 @@ export function Form<
|
||||
const key = normalized.substring(2).replace(/\//g, ".");
|
||||
setData((prev) => {
|
||||
const changed = immutable.del(prev, key);
|
||||
onChange?.(changed, key, undefined);
|
||||
//console.log("changed", prev, changed, { key });
|
||||
return changed;
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setDirty(!isEqual(initialValues, data));
|
||||
|
||||
if (validateOn === "change") {
|
||||
validate();
|
||||
}
|
||||
@@ -107,6 +112,7 @@ export function Form<
|
||||
|
||||
const context = {
|
||||
data: data ?? {},
|
||||
dirty,
|
||||
setData,
|
||||
setValue,
|
||||
deleteValue,
|
||||
@@ -194,3 +200,8 @@ export function useFieldContext(name: string) {
|
||||
required
|
||||
};
|
||||
}
|
||||
|
||||
export function Subscribe({ children }: { children: (ctx: FormContext<any>) => ReactNode }) {
|
||||
const ctx = useFormContext();
|
||||
return children(ctx);
|
||||
}
|
||||
@@ -36,10 +36,10 @@ export const ObjectField = ({
|
||||
if (!schema) return;
|
||||
|
||||
if (schema.anyOf || schema.oneOf) {
|
||||
return <AnyOfField key={pointer} path={pointer} schema={schema} />;
|
||||
return <AnyOfField key={pointer} path={pointer} />;
|
||||
}
|
||||
|
||||
return <Field key={pointer} name={pointer} schema={schema} />;
|
||||
return <Field key={pointer} name={pointer} />;
|
||||
})}
|
||||
</FieldWrapper>
|
||||
);
|
||||
@@ -1,98 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,2 +1,6 @@
|
||||
export { TypeboxValidator, type ValueError } from "./validators/tb-validator";
|
||||
export { CfValidator, type OutputUnit } from "./validators/cf-validator";
|
||||
export * from "./Field";
|
||||
export * from "./Form";
|
||||
export * from "./ObjectField";
|
||||
export * from "./ArrayField";
|
||||
export * from "./AnyOfField";
|
||||
export * from "./FieldWrapper";
|
||||
|
||||
@@ -122,7 +122,7 @@ export function normalizePath(path: string) {
|
||||
}
|
||||
|
||||
export function prefixPointer(pointer: string, prefix: string) {
|
||||
return pointer.replace("#/", `#/${prefix}/`);
|
||||
return pointer.replace("#/", `#/${prefix}/`).replace(/\/\//g, "/");
|
||||
}
|
||||
|
||||
export function getParentPointer(pointer: string) {
|
||||
@@ -1,11 +0,0 @@
|
||||
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 };
|
||||
@@ -1,11 +0,0 @@
|
||||
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 };
|
||||
@@ -1,192 +0,0 @@
|
||||
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
|
||||
};
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user