Skip to content

Test using patterProperties in interactive component #2112

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
5,603 changes: 5,603 additions & 0 deletions openrpc.json

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@
"@metamask/profile-sync-controller": "^16.0.0",
"@metamask/sdk": "^0.32.0",
"@rjsf/core": "^5.24.10",
"@rjsf/utils": "^5.24.8",
"@rjsf/validator-ajv8": "^5.24.8",
"@rjsf/utils": "^5.24.12",
"@rjsf/validator-ajv8": "^5.24.12",
"@sentry/browser": "^8.51.0",
"@types/react": "^18.3.3",
"clsx": "^2.1.1",
Expand Down
50 changes: 36 additions & 14 deletions src/components/ParserOpenRPC/InteractiveBox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import global from '../global.module.scss'
import { BaseInputTemplate } from '@site/src/components/ParserOpenRPC/InteractiveBox/templates/BaseInputTemplate'
import { ArrayFieldTemplate } from '@site/src/components/ParserOpenRPC/InteractiveBox/templates/ArrayFieldTemplate'
import { ObjectFieldTemplate } from '@site/src/components/ParserOpenRPC/InteractiveBox/templates/ObjectFieldTemplate'
import { WrapIfAdditionalTemplate } from '@site/src/components/ParserOpenRPC/InteractiveBox/templates/WrapIfAdditionalTemplate'
import { ConditionalField } from '@site/src/components/ParserOpenRPC/InteractiveBox/fields/ConditionalField'
import { DropdownWidget } from '@site/src/components/ParserOpenRPC/InteractiveBox/widgets/DropdownWidget'
import { SelectWidget } from '@site/src/components/ParserOpenRPC/InteractiveBox/widgets/SelectWidget'
Expand All @@ -29,6 +28,7 @@ import { AddButton } from '@site/src/components/ParserOpenRPC/InteractiveBox/but
import ClearIcon from '@site/static/img/icons/clear-icon.svg'
import ResetIcon from '@site/static/img/icons/reset-icon.svg'
import SubmitIcon from '@site/static/img/icons/submit-icon.svg'
import { WrapIfAdditionalTemplate } from '@site/src/components/ParserOpenRPC/InteractiveBox/templates/WrapIfAdditionalTemplate'

interface InteractiveBoxProps {
params: MethodParam[]
Expand Down Expand Up @@ -161,14 +161,35 @@ export default function InteractiveBox({
}
}, [examples, metaMaskAccount])

// ---------------- CHECKPOINT 1 ----------------
// Build the schema that will be supplied to RJSF.
// If a parameter schema contains `patternProperties` but does not explicitly
// allow additional properties, we inject `additionalProperties: true` so that
// RJSF`s `canExpand` helper recognises it as dynamic and enables the "Add" UI.
const schema: RJSFSchema = {
components: {
schemas: components,
},
type: 'object',
// @ts-ignore
properties: Object.fromEntries(params.map(({ name, schema }) => [name, schema])),
// @ts-ignore – the OpenRPC param list isn't strictly typed for RJSF here.
properties: Object.fromEntries(
params.map(({ name, schema }) => {
let patchedSchema: any = { ...schema }
if (patchedSchema.patternProperties && patchedSchema.additionalProperties === undefined) {
// Attempt to infer a sensible schema for additional properties. If the
// sole patternProperty specifies an object, default to object {}; otherwise fallback to string.
let inferredAdditional: any = { type: 'string', default: 'New Value' }
const singlePattern: any = Object.values(patchedSchema.patternProperties)[0]
if (singlePattern && singlePattern.type === 'object') {
inferredAdditional = { type: 'object', default: {} }
}
patchedSchema = { ...patchedSchema, additionalProperties: inferredAdditional }
}
return [name, patchedSchema]
})
),
}

const uiSchema: UiSchema = {
'ui:globalOptions': {
label: false,
Expand Down Expand Up @@ -221,7 +242,8 @@ export default function InteractiveBox({
const dereferenceSchema = async () => {
try {
if (schema) {
setParsedSchema((await $RefParser.dereference(schema)) as RJSFSchema)
const deref = (await $RefParser.dereference(schema)) as RJSFSchema
setParsedSchema(deref)
}
} catch (error) {
console.error('Error of parsing schema:', error)
Expand All @@ -231,11 +253,13 @@ export default function InteractiveBox({
}, [])

const onChangeHandler = data => {
const validData = removeEmptyArrays(data, params)
if (isOpen) {
setCurrentFormData(validData)
onParamChange(validData)
}
setCurrentFormData(data.formData)
}

const handleBlur = () => {
const cleaned = removeEmptyArrays(currentFormData, params)
setCurrentFormData(cleaned)
onParamChange(cleaned)
}

const cloneAndSetNullIfExists = (obj, key) => {
Expand Down Expand Up @@ -320,10 +344,8 @@ export default function InteractiveBox({
validator={validator}
liveValidate={isOpen}
noHtml5Validate
onChange={data => {
const orderData = sortObjectKeysByArray(data.formData, params)
onChangeHandler(orderData)
}}
onChange={onChangeHandler}
onBlur={handleBlur}
templates={templates}
uiSchema={uiSchema}
widgets={widgets}
Expand Down Expand Up @@ -364,7 +386,7 @@ export default function InteractiveBox({
</button>
<button
className={clsx(global.primaryBtn, styles.footerButtonRight)}
onClick={closeComplexTypeView}>
onClick={handleSubmitAndClose}>
Save
</button>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import { Tooltip } from '@site/src/components/Tooltip'
import debounce from 'lodash.debounce'
import { ParserOpenRPCContext } from '@site/src/components/ParserOpenRPC'

interface ExtendedInputProps extends BaseInputTemplateProps {
interface ExtendedInputProps extends Omit<BaseInputTemplateProps, 'onBlur'> {
isArray?: boolean
onBlur?: (id: string, value: any) => void
[key: string]: any
}

export const BaseInputTemplate = ({
Expand All @@ -17,11 +19,13 @@ export const BaseInputTemplate = ({
value = '',
disabled,
onChange,
onBlur,
rawErrors,
hideError,
required,
formContext,
isArray,
...rest
}: ExtendedInputProps) => {
const isNumber = schema.type === 'number' || schema.type === 'integer'
const [isFocused, setIsFocused] = useState(false)
Expand Down Expand Up @@ -54,6 +58,11 @@ export const BaseInputTemplate = ({
}
}, [value, isFormReseted, currentFormData])

// RJSF uses lowercase "autofocus"; React expects camelCase "autoFocus".
// Extract it so we can map correctly and avoid passing an invalid DOM prop.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { autofocus, ...inputRest } = rest

return (
<div className={isArray ? styles.arrayItemRow : styles.tableRow}>
{!isArray && (
Expand Down Expand Up @@ -91,9 +100,12 @@ export const BaseInputTemplate = ({
onFocus={() => {
setIsFocused(true)
}}
onBlur={() => {
onBlur={_e => {
setIsFocused(false)
onBlur?.(id, inputValue)
}}
autoFocus={autofocus}
{...inputRest}
/>
<span className={styles.tableColumnType}>
{schema.type}
Expand Down
Loading
Loading