Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add oneOf renderer #42

Merged
merged 14 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@
"@testing-library/react": "^14.2.1",
"@testing-library/user-event": "^14.5.2",
"@types/lodash.isempty": "^4.4.9",
"@types/lodash.merge": "^4.6.9",
"@types/lodash.startcase": "^4.4.9",
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"@typescript-eslint/eslint-plugin": "^6.14.0",
Expand All @@ -95,5 +97,11 @@
"typescript": "^5.2.2",
"vite": "^5.0.12",
"vitest": "^1.2.2"
},
"dependencies": {
"@types/lodash-es": "^4.17.12",
"lodash-es": "^4.17.21",
"lodash.merge": "^4.6.2",
"lodash.startcase": "^4.4.0"
}
}
45 changes: 42 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 67 additions & 0 deletions src/common/ControlLabelRenderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { JsonSchema } from "@jsonforms/core"
import { ControlUISchema, LabelDescription } from "../ui-schema"
import { Typography } from "antd"
import { assertNever } from "./assert-never"

export function ControlLabelRenderer({
DrewHoo marked this conversation as resolved.
Show resolved Hide resolved
uischema,
schema,
}: {
uischema: ControlUISchema
schema: JsonSchema
}) {
const controlUISchema: ControlUISchema = uischema
const text = getUiSchemaLabel(controlUISchema)

if (!text && !schema.title) {
return null
}

if (!text && schema.title) {
return <Typography.Title>{schema.title}</Typography.Title>
}

if (typeof controlUISchema.label === "object" && controlUISchema.label.type) {
const labelType = controlUISchema.label.type
switch (labelType) {
case "Text":
return (
<Typography.Text {...controlUISchema.label.textProps}>
{text}
</Typography.Text>
)

case "Title":
return (
<Typography.Title {...controlUISchema.label.titleProps}>
{text}
</Typography.Title>
)
default:
try {
assertNever(labelType)
} catch (e) {
console.error(
`Invalid value configured in Control UI Schema for label.type: '${labelType as string}'`,
)
}
}
}
return <Typography.Title>{text}</Typography.Title>
}

function getUiSchemaLabel(uischema: ControlUISchema): string | undefined {
const label = uischema.label
if (!label) {
return undefined
}
if (
(label as LabelDescription).text &&
(label as LabelDescription).show !== false
) {
return (label as LabelDescription).text
}
if (typeof label === "string") {
return label
}
}
5 changes: 3 additions & 2 deletions src/common/StorybookAntDJsonForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import {
import { UISchema } from "../ui-schema"
import { AntDJsonForm } from "./AntDJsonForm"
import { useState } from "react"
import { JSONSchema } from "json-schema-to-ts"

type Props = {
data?: Record<string, unknown>
jsonSchema: JsonSchema7
jsonSchema: JSONSchema
rendererRegistryEntries: JsonFormsRendererRegistryEntry[]
uiSchema?: UISchema
uiSchemaRegistryEntries?: JsonFormsUISchemaRegistryEntry[]
Expand All @@ -35,7 +36,7 @@ export function StorybookAntDJsonForm({
return (
<AntDJsonForm
uiSchema={uiSchema}
jsonSchema={jsonSchema}
jsonSchema={jsonSchema as JsonSchema7}
data={data}
updateData={(newData) => updateData(newData)}
uiSchemaRegistryEntries={uiSchemaRegistryEntries}
Expand Down
18 changes: 18 additions & 0 deletions src/common/usePreviousValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect, useState } from "react"

/**
* Hook that returns the what was passed in the previous render.
* On the first render, returns undefined. Eventually
* "catches up" to the current value.
*/
export function usePreviousValue<T>(value: T): T | undefined {
const [prev, setPrev] = useState<T | undefined>(undefined)

useEffect(() => {
if (value !== prev) {
setPrev(value)
}
}, [value, prev])

return prev
}
1 change: 0 additions & 1 deletion src/controls/BooleanControl.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ test("handles onChange event correctly", async () => {
},
data: { name: false },
onChange: (result) => {
console.log(result)
updateData(result)
},
})
Expand Down
172 changes: 172 additions & 0 deletions src/controls/combinators/CombinatorSchemaSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import {
Radio,
RadioChangeEvent,
Select,
Space,
Switch,
Typography,
} from "antd"
import { OneOfControlOptions } from "../../ui-schema"
import merge from "lodash.merge"
import { useEffect, useState } from "react"
import {
CombinatorRendererProps,
CombinatorSubSchemaRenderInfo,
JsonSchema,
createDefaultValue,
} from "@jsonforms/core"
import { usePreviousValue } from "../../common/usePreviousValue"
import { shouldUseRadioGroupSwitcher } from "./utils"

type CombinatorSchemaSwitcherProps = {
renderInfos: CombinatorSubSchemaRenderInfo[]
setSelectedIndex: (index: number) => void
selectedIndex: number
} & Pick<
CombinatorRendererProps,
| "data"
| "handleChange"
| "path"
| "rootSchema"
| "uischema"
| "config"
| "indexOfFittingSchema"
>

export function CombinatorSchemaSwitcher({
renderInfos,
indexOfFittingSchema,
config,
uischema,
setSelectedIndex,
selectedIndex,
rootSchema,
path,
handleChange,
data,
}: CombinatorSchemaSwitcherProps) {
const appliedUiSchemaOptions: OneOfControlOptions = merge(
{},
config,
uischema.options as Record<string, unknown>,
) as OneOfControlOptions
const oneOfOptionType = appliedUiSchemaOptions.optionType
const prevSelectedIndex = usePreviousValue(selectedIndex)
const [dataForPreviousSchemas, setDataForPreviousSchemas] = useState<
Record<number, unknown>
>({})

useEffect(() => {
if (
selectedIndex !== prevSelectedIndex &&
prevSelectedIndex !== undefined
) {
setDataForPreviousSchemas({
...dataForPreviousSchemas,
[prevSelectedIndex]: data as unknown,
})
if (dataForPreviousSchemas[selectedIndex]) {
handleChange(path, dataForPreviousSchemas[selectedIndex])
} else {
handleCombinatorTypeChange({
handleChange,
combinatorIndex: selectedIndex,
renderInfos,
path,
rootSchema,
})
}
}
}, [
data,
dataForPreviousSchemas,
handleChange,
renderInfos,
path,
prevSelectedIndex,
rootSchema,
selectedIndex,
])

const options = renderInfos.map((renderInfo, index) => ({
label: renderInfo.label,
value: index,
}))

if (shouldUseRadioGroupSwitcher(oneOfOptionType)) {
return (
<Radio.Group
{...(oneOfOptionType === "button" && {
optionType: "button",
buttonStyle: "solid",
})}
options={options}
onChange={(e: RadioChangeEvent) => {
const combinatorIndex = e.target.value as number
setSelectedIndex(combinatorIndex)
}}
value={selectedIndex}
/>
)
}
if (oneOfOptionType === "dropdown") {
return (
<Select
options={options}
onChange={(combinatorIndex: number) =>
setSelectedIndex(combinatorIndex)
}
defaultValue={selectedIndex}
/>
)
}
if (oneOfOptionType === "toggle") {
DrewHoo marked this conversation as resolved.
Show resolved Hide resolved
return (
<Space>
<Switch
onChange={(value: boolean) => {
const combinatorIndex = value === false ? 0 : 1
setSelectedIndex(combinatorIndex)
}}
defaultChecked={indexOfFittingSchema === 1}
/>
{appliedUiSchemaOptions.toggleLabel && (
<Typography.Text>
{appliedUiSchemaOptions.toggleLabel}
</Typography.Text>
)}
</Space>
)
}
}

type HandleCombinatorTypeChangeArgs = {
handleChange: (path: string, data: unknown) => void
renderInfos: CombinatorSubSchemaRenderInfo[]
combinatorIndex: number
path: string
rootSchema: JsonSchema
}

function handleCombinatorTypeChange({
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write a test for the default value bug

handleChange,
renderInfos,
combinatorIndex,
path,
rootSchema,
}: HandleCombinatorTypeChangeArgs) {
const newSchema = renderInfos[combinatorIndex]?.schema
let newData
if (newSchema?.type === "object") {
// const typeDiscriminator = newSchema.properties?.type?.default

newData = {
...createDefaultValue(newSchema, rootSchema),
// ...(typeDiscriminator ? { type: typeDiscriminator } : {}),
} as unknown
} else {
newData = createDefaultValue(newSchema, rootSchema) as unknown
}

handleChange(path, newData)
}
Loading