Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import type {
RankedTester,
} from '@jsonforms/core';

import { useCallback, useState } from 'react';
import { useCallback, useRef, useState } from 'react';

import {
Button,
Expand All @@ -46,32 +46,75 @@ import {
Hidden,
Tab,
Tabs,
Typography,
} from '@mui/material';

import {
and,
createCombinatorRenderInfos,
decode,
isOneOfControl,
rankWith,
schemaMatches,
} from '@jsonforms/core';
import { JsonFormsDispatch } from '@jsonforms/react';

import { keys } from 'lodash';
import isEmpty from 'lodash/isEmpty';

import { useEntityWorkflow_Editing } from 'src/context/Workflow';
import CombinatorProperties from 'src/forms/overrides/material/complex/CombinatorProperties';
import { INJECTED } from 'src/forms/renderers/OAuth/shared';
import {
discriminator,
getDiscriminator,
getDiscriminatorDefaultValue,
} from 'src/forms/shared';
import { withCustomJsonFormsOneOfDiscriminatorProps } from 'src/services/jsonforms/JsonFormsContext';
import { logRocketEvent } from 'src/services/shared';
import { hasOwnProperty } from 'src/utils/misc-utils';

const renderer = 'Custom_MaterialOneOfRenderer_Discriminator';

export interface OwnOneOfProps extends OwnPropsOfControl {
indexOfFittingSchema?: number;
}

// Customization: do not prompt user if they are:
// only the discriminator is changing
// ex: first click of authentication (usually will only contain discriminator)
// only the discriminator is changing and others are blank or INJECTED
// ex: clicks after the first of authentication
// ex: any click off a tab that is for oAuth
// the data is totally empty (ex: parsers)
function skipTabChangePrompt(data: any, prop: string): boolean {
// No data at all - we can skip
if (isEmpty(data)) {
return true;
}

for (const key in data) {
// If it is the discriminator we can ignore
if (key === prop) {
continue;
}

const value = data[key];

// Check if value is a non-null object - recurse into it
if (typeof value === 'object' && value !== null) {
if (!skipTabChangePrompt(value, prop)) {
return false;
}
}
// For non-object values, check if they're non-empty and not INJECTED
else if (value !== '' && value !== INJECTED) {
return false;
}
}

return true;
}

export const Custom_MaterialOneOfRenderer_Discriminator = ({
handleChange,
schema,
Expand All @@ -86,7 +129,11 @@ export const Custom_MaterialOneOfRenderer_Discriminator = ({
uischemas,
data,
enabled,
required,
}: CombinatorRendererProps) => {
const isEdit = useEntityWorkflow_Editing();

const defaultDiscriminator = useRef(true);
const [open, setOpen] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(
indexOfFittingSchema || 0
Expand All @@ -97,8 +144,9 @@ export const Custom_MaterialOneOfRenderer_Discriminator = ({
setOpen(false);
}, [setOpen]);

const possibleSchemas = (schema as JsonSchema).oneOf as JsonSchema[];
Copy link
Member Author

Choose a reason for hiding this comment

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

Need to pull this out now so we can reference it down below during defaulting.

const oneOfRenderInfos = createCombinatorRenderInfos(
(schema as JsonSchema).oneOf as JsonSchema[],
possibleSchemas,
rootSchema,
'oneOf',
uischema,
Expand All @@ -108,12 +156,40 @@ export const Custom_MaterialOneOfRenderer_Discriminator = ({

const discriminatorProperty = getDiscriminator(schema);

// Customization: Run through the elements and clear out the ones without elements
oneOfRenderInfos.map((renderer) => {
const { uischema: rendererUischema } = renderer as any;

rendererUischema.elements = rendererUischema.elements.filter(
(el: any) => el !== null
(el: any) => {
// Remove any that are missing elements or somehow don't have scope (should never happen)
if (el === null || !el.scope) return false;

// We now want to try to hide the input that is rendering the discriminator
// since we are rendering the tabs this is just duplicating information
// This is not supported out of the box https://jsonforms.discourse.group/t/use-default-uischema-and-only-apply-rule-to-one-field/1742
// So we have to look at the pathSegments and filter our the one that matches the discriminator
// This should be safe according to JSONForms https://jsonforms.discourse.group/t/hiding-a-specific-path-when-rendering-a-complex-oneof/2795

const pathSegments = el.scope?.split('/');
if (pathSegments && pathSegments.length > 0) {
// Get the last segment as that should match property names
// based on `isRequired` in jsonforms/packages/core/src/mappers/renderer.ts
const renderOneOfOption =
decode(pathSegments[pathSegments.length - 1]) !==
discriminatorProperty;

logRocketEvent('JsonForms', {
renderer,
renderOneOfOption,
});

return renderOneOfOption;
}

return true;
}
);

return renderer;
});

Expand All @@ -140,38 +216,78 @@ export const Custom_MaterialOneOfRenderer_Discriminator = ({
const handleTabChange = useCallback(
(_event: any, newOneOfIndex: number) => {
setNewSelectedIndex(newOneOfIndex);
// Customization: do not prompt user if they are only
// overwriting the discriminator as it is a single property.
const keysInData = keys(data);
if (
(keysInData.length === 1 &&
keysInData[0] === discriminatorProperty) ||
isEmpty(data)
) {

// Customization: Skip prompting when changing tab
if (skipTabChangePrompt(data, discriminatorProperty)) {
logRocketEvent('JsonForms', {
renderer,
skippingTabChangePrompt: true,
});
openNewTab(newOneOfIndex);
} else {
setOpen(true);
return;
}

setOpen(true);
},
[setOpen, setSelectedIndex, data]
);

// Customization : Need to handle defaulting for Pydantic schemas
// They will return an `enum` with a single value and that will not
// be defaulted properly unless it is rendered. Since we are hiding the
// discriminator now we need to make sure it is set
if (defaultDiscriminator.current) {
if (
!isEdit &&
required &&
!hasOwnProperty(data, discriminatorProperty)
) {
const defaultVal = getDiscriminatorDefaultValue(
possibleSchemas?.[selectedIndex]?.properties,
discriminatorProperty
);

logRocketEvent('JsonForms', {
renderer,
defaultingDiscriminatorProperty: true,
defaultVal,
});

defaultDiscriminator.current = false;

handleChange(path, {
[discriminatorProperty]: defaultVal?.[discriminatorProperty],
});
}
}

const singleOption = oneOfRenderInfos.length === 1;

return (
<Hidden xsUp={!visible}>
<CombinatorProperties
schema={schema}
combinatorKeyword="oneOf"
path={path}
/>
<Tabs value={selectedIndex} onChange={handleTabChange}>
{oneOfRenderInfos.map((oneOfRenderInfo) => (
<Tab
key={oneOfRenderInfo.label}
label={oneOfRenderInfo.label}
disabled={!enabled}
/>
))}
</Tabs>
{singleOption ? (
// TODO (jsonforms) - we have wanted to hide this but some
// connectors work better with it showing (ex: materialize-iceberg)
// so we left it in for now.
<Typography sx={{ fontWeight: 500, fontSize: 14 }}>
{oneOfRenderInfos[0].label}
</Typography>
) : (
<Tabs value={selectedIndex} onChange={handleTabChange}>
{oneOfRenderInfos.map((oneOfRenderInfo) => (
<Tab
key={oneOfRenderInfo.label}
label={oneOfRenderInfo.label}
disabled={!enabled}
/>
))}
</Tabs>
)}
{oneOfRenderInfos.map(
(oneOfRenderInfo, oneOfIndex) =>
selectedIndex === oneOfIndex && (
Expand Down
12 changes: 6 additions & 6 deletions src/forms/renderers/OAuth/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,17 +262,17 @@ const OAuthproviderRenderer = ({
{showAuthenticated ? (
<Chip
disabled={!enabled || loading}
label={
<FormattedMessage id="oauth.authenticated" />
}
label={intl.formatMessage({
id: 'oauth.authenticated',
})}
color="success"
onDelete={setConfigToDefault}
/>
) : (
<Chip
label={
<FormattedMessage id="oauth.unauthenticated" />
}
label={intl.formatMessage({
id: 'oauth.unauthenticated',
})}
color="warning"
/>
)}
Expand Down
10 changes: 5 additions & 5 deletions src/forms/shared.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Schema } from 'src/types';

import { createDefaultValue } from '@jsonforms/core';

import { forIn } from 'lodash';
Expand All @@ -11,14 +13,12 @@ export const getDiscriminator = (schema: any) => {
export const getDiscriminatorDefaultValue = (
tabSchemaProps: any,
discriminatorProperty: string
) => {
): Schema => {
// Go through all the props and set them into the object.
// If it is the discriminator then try to set the default
// value, then the const, and finally default to an empty string.
// If it is any other value then go ahead and create the value
const defaultVal: {
[k: string]: any;
} = {};
const defaultVal: Schema = {};
forIn(tabSchemaProps, (val: any, key: string) => {
defaultVal[key] =
key === discriminatorProperty
Expand All @@ -34,7 +34,7 @@ export const getDiscriminatorDefaultValue = (
// a schema. However, when we edit a schema we can end up with an option that
// contains errors. The NetSuite connector Authentication is what caught this. the
// `user_pass` option contains two fields that are encrypted and so they are empty
// during edit. This mean that JsonForms would not find the
// during edit. This mean that JsonForms would not find them
export const getDiscriminatorIndex = (schema: any, data: any, keyword: any) => {
const discriminatorProperty = getDiscriminator(schema);

Expand Down
5 changes: 5 additions & 0 deletions src/pages/dev/TestJsonForms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ const TestJsonForms = () => {
3. Open the browser console to see details related
to the state, schema, and ui schema.
</Box>
<Box>
Due to how the UI manages things during edit. The
oAuth &quot;Authenticated&quot; chip will always
show as authenticated.
</Box>
</AlertBox>

<JsonForms
Expand Down
1 change: 1 addition & 0 deletions src/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type KnownEvents =
| 'Auth'
| 'DataPlaneGateway'
| 'EndpointConfig'
| 'JsonForms'
| 'MonacoEditor'
| 'ResetInvalidSetting'
| 'SkimProjections'
Expand Down