import { withJsonFormsControlProps } from '@jsonforms/react';
import { rankWith } from '@jsonforms/core';
import { Autocomplete, TextField } from '@mui/material';
import { useEffect, useState } from 'react';
// Custom renderer that fetches data for dataSource option
const DataSourceControl = (props) => {
const { data, path, handleChange, uischema, label } = props;
const [options, setOptions] = useState([]);
const { dataSource, exclude } = uischema.options || {};
useEffect(() => {
if (dataSource === 'countries') {
// Fetch countries and apply exclude filters
fetch('https://api.enterprise.uphold.com/core/countries', {
headers: {
'Authorization': `Bearer ${accessToken}` // Your OAuth2 access token
}
})
.then((res) => res.json())
.then((countries) => {
// Apply exclude filter if specified
const filtered = exclude?.restrictions
? countries.filter((country) =>
!exclude.restrictions.some((r) =>
country.restrictions?.some((cr) => cr.scope === r.scope)
)
)
: countries;
setOptions(filtered.map((c) => ({ value: c.code, label: c.name })));
});
}
}, [dataSource, exclude]);
return (
<Autocomplete
options={options}
value={options.find((o) => o.value === data) || null}
onChange={(_, selected) => handleChange(path, selected?.value)}
getOptionLabel={(option) => option.label}
renderInput={(params) => <TextField {...params} label={label} />}
/>
);
};
// Tester: use this renderer when dataSource is present
const dataSourceTester = rankWith(10, (uischema) =>
uischema.options?.dataSource ? true : false
);
// Export for use with JsonForms
export const dataSourceRenderer = {
tester: dataSourceTester,
renderer: withJsonFormsControlProps(DataSourceControl),
};