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

fix(278): Group parameters in the configuration panel #975

Merged
merged 1 commit into from
Apr 3, 2024
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 @@ -104,6 +104,7 @@ private void generatePropertiesSchema(ObjectNode parent) throws Exception {
var property = (ObjectNode) propertyEntry.getValue();
var propertySchema = answerProperties.withObject("/" + propertyName);
if (property.has("displayName")) propertySchema.put("title", property.get("displayName").asText());
if (property.has("group")) propertySchema.put("group", property.get("group").asText());
if (property.has("description")) propertySchema.put("description", property.get("description").asText());
var propertyType = "string";
if (property.has("type")) {
Expand Down
7 changes: 4 additions & 3 deletions packages/ui/src/components/Form/CustomAutoField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ jest.mock('uniforms', () => {
};
});

import { BoolField, DateField, ListField, NestField, RadioField, TextField } from '@kaoto-next/uniforms-patternfly';
import { BoolField, DateField, ListField, RadioField, TextField } from '@kaoto-next/uniforms-patternfly';
import { AutoFieldProps } from 'uniforms';
import { CustomAutoField } from './CustomAutoField';
import { OneOfField } from './OneOf/OneOfField';
import { CustomNestField } from './customField/CustomNestField';
import { DisabledField } from './customField/DisabledField';
import { TypeaheadField } from './customField/TypeaheadField';
import { OneOfField } from './OneOf/OneOfField';

describe('CustomAutoField', () => {
it('should return `OneOfField` if `props.oneOf` is an array with a length > 0', () => {
Expand Down Expand Up @@ -138,7 +139,7 @@ describe('CustomAutoField', () => {

const result = CustomAutoField(props);

expect(result).toBe(NestField);
expect(result).toBe(CustomNestField);
});

it('should return `TextField` if `props.fieldType` is `String`', () => {
Expand Down
13 changes: 3 additions & 10 deletions packages/ui/src/components/Form/CustomAutoField.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
import {
BoolField,
DateField,
ListField,
LongTextField,
NestField,
RadioField,
TextField,
} from '@kaoto-next/uniforms-patternfly';
import { BoolField, DateField, ListField, LongTextField, RadioField, TextField } from '@kaoto-next/uniforms-patternfly';
import { createAutoField } from 'uniforms';
import { getValue } from '../../utils';
import { OneOfField } from './OneOf/OneOfField';
import { BeanReferenceField } from './bean/BeanReferenceField';
import { CustomNestField } from './customField/CustomNestField';
import { DisabledField } from './customField/DisabledField';
import { TypeaheadField } from './customField/TypeaheadField';
import { ExpressionAwareNestField } from './expression/ExpressionAwareNestField';
Expand Down Expand Up @@ -55,7 +48,7 @@ export const CustomAutoField = createAutoField((props) => {
case Number:
return TextField;
case Object:
return NestField;
return CustomNestField;
case String:
/* catalog preprocessor put 'string' as a type and the javaType as a schema $comment */
if (comment?.startsWith('class:')) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.custom-nestfield-spacing {
display: grid;
gap: var(--pf-v5-c-form--GridGap);
}
132 changes: 132 additions & 0 deletions packages/ui/src/components/Form/customField/CustomNestField.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { act } from 'react-dom/test-utils';

import { AutoField } from '@kaoto-next/uniforms-patternfly';

import { AutoForm } from 'uniforms';
import { CustomAutoFieldDetector } from '../CustomAutoField';
import { SchemaService } from '../schema.service';
import { CustomNestField } from './CustomNestField';

describe('CustomNestField', () => {
const mockSchema = {
title: 'Test',
type: 'object',
additionalProperties: false,
properties: {
parameters: {
type: 'object',
title: 'Endpoint Properties',
description: 'Endpoint properties description',
properties: {
timerName: {
title: 'Timer Name',
group: 'common',
description: 'The name of the timer',
type: 'string',
},
pattern: {
title: 'Pattern',
group: 'advanced',
description:
'Allows you to specify a custom Date pattern to use for setting the time option using URI syntax.',
type: 'string',
},
secret: {
title: 'Secret',
group: 'secret',
description: 'The secret',
type: 'string',
},
},
},
},
};

const schemaService = new SchemaService();
const schemaBridge = schemaService.getSchemaBridge(mockSchema);

it('should render the component', () => {
render(
<AutoField.componentDetectorContext.Provider value={CustomAutoFieldDetector}>
<AutoForm schema={schemaBridge!}>
<CustomNestField name="parameters" />
</AutoForm>
</AutoField.componentDetectorContext.Provider>,
);
const inputTimerElement = screen
.getAllByRole('textbox')
.filter((textbox) => textbox.getAttribute('label') === 'Timer Name');
expect(inputTimerElement).toHaveLength(1);
const inputPatternElement = screen
.getAllByRole('textbox')
.filter((textbox) => textbox.getAttribute('label') === 'Pattern');
expect(inputPatternElement).toHaveLength(0);
const advancedProperties = screen.getByRole('button', { name: 'advanced properties' });
const secretProperties = screen.getByRole('button', { name: 'secret properties' });
expect(advancedProperties).toBeInTheDocument();
expect(secretProperties).toBeInTheDocument();
});

it('should display the advanced properties', async () => {
render(
<AutoField.componentDetectorContext.Provider value={CustomAutoFieldDetector}>
<AutoForm schema={schemaBridge!}>
<CustomNestField name="parameters" />
</AutoForm>
</AutoField.componentDetectorContext.Provider>,
);
const buttonElement = screen.getByRole('button', { name: 'advanced properties' });
await act(async () => {
fireEvent.click(buttonElement);
});
const inputPatternElement = screen
.getAllByRole('textbox')
.filter((textbox) => textbox.getAttribute('label') === 'Pattern');
expect(inputPatternElement).toHaveLength(1);
});
});

describe('CustomNestField', () => {
const mockSchema = {
title: 'Test',
type: 'object',
additionalProperties: false,
properties: {
parameters: {
type: 'object',
title: 'Endpoint Properties',
description: 'Endpoint properties description',
properties: {
timerName: {
title: 'Timer Name',
description: 'The name of the timer',
type: 'string',
},
},
},
},
};

const schemaService = new SchemaService();
const schemaBridge = schemaService.getSchemaBridge(mockSchema);

it('should not render the advanced properties button if no advanced properties are provided', () => {
render(
<AutoField.componentDetectorContext.Provider value={CustomAutoFieldDetector}>
<AutoForm schema={schemaBridge!}>
<CustomNestField name="parameters" />
</AutoForm>
</AutoField.componentDetectorContext.Provider>,
);
const inputTimerElement = screen
.getAllByRole('textbox')
.filter((textbox) => textbox.getAttribute('label') === 'Timer Name');
expect(inputTimerElement).toHaveLength(1);

const advancedButton = screen
.getAllByRole('button')
.filter((button) => button.textContent === 'advanced properties');
expect(advancedButton).toHaveLength(0);
});
});
92 changes: 92 additions & 0 deletions packages/ui/src/components/Form/customField/CustomNestField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { Card, CardBody, CardHeader, CardTitle, ExpandableSection } from '@patternfly/react-core';
import { useMemo } from 'react';
import { HTMLFieldProps, connectField, filterDOMProps } from 'uniforms';
import { getValue } from '../../../utils';
import { CustomAutoField } from '../CustomAutoField';
import './CustomNestField.scss';

export type CustomNestFieldProps = HTMLFieldProps<
object,
HTMLDivElement,
{ properties?: Record<string, unknown>; helperText?: string; itemProps?: object }
>;

export const CustomNestField = connectField(
({
children,
error,
errorMessage,
fields,
itemProps,
label,
name,
showInlineError,
disabled,
...props
}: CustomNestFieldProps) => {
const propertiesArray = useMemo(() => {
return Object.entries(props.properties ?? {}).reduce(
(acc, [name, definition]) => {
const group: string = getValue(definition, 'group', '');
if (group === '' || group === 'common' || group === 'producer' || group === 'consumer') {
acc.common.push(name);
} else if (group.includes('advanced')) {
acc.groups['advanced'] ??= [];
acc.groups['advanced'].push(name);
} else {
acc.groups[group] ??= [];
acc.groups[group].push(name);
}
return acc;
},
{ common: [], groups: {} } as { common: string[]; groups: Record<string, string[]> },
);
}, [props.properties]);

return (
<Card data-testid={'nest-field'} {...filterDOMProps(props)}>
<CardHeader>
<CardTitle>{label}</CardTitle>
</CardHeader>
<CardBody className="custom-nestfield-spacing">
{propertiesArray.common.map((field) => (
<CustomAutoField key={field} name={field} />
))}
</CardBody>

{Object.entries(propertiesArray.groups).map(([groupName, groupFields]) => (
<ExpandableSection
toggleText={`${groupName} properties`}
toggleId="expandable-section-toggle"
contentId="expandable-section-content"
>
<CardBody className="custom-nestfield-spacing">
{groupFields.map((field) => (
<CustomAutoField key={field} name={field} />
))}
</CardBody>
</ExpandableSection>
))}
</Card>
);
},
);
Copy link
Member

@lordrip lordrip Mar 30, 2024

Choose a reason for hiding this comment

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

After checking it, I think it's a good approach, but there's still an open question for the future, not exactly related to this PR which is "how to identify components in consumer or producer mode", so we can filter such properties.

I tinkered a bit with your idea and I have a proposal, please let me know what you think:

import { Card, CardBody, CardHeader, CardTitle, ExpandableSection } from '@patternfly/react-core';
import { HTMLFieldProps, connectField, filterDOMProps } from 'uniforms';
import { getValue } from '../../../utils';
import { CustomAutoField } from '../CustomAutoField';
import './CustomNestField.scss';

export type CustomNestFieldProps = HTMLFieldProps<
  object,
  HTMLDivElement,
  { properties?: Record<string, unknown>; helperText?: string; itemProps?: object }
>;

export const CustomNestField = connectField(
  ({
    children,
    error,
    errorMessage,
    fields,
    itemProps,
    label,
    name,
    showInlineError,
    disabled,
    ...props
  }: CustomNestFieldProps) => {
    const propertiesArray = Object.entries(props.properties ?? {}).reduce(
      (acc, [name, definition]) => {
        let labels: string = getValue(definition, 'labels', '');
        if (labels === '' || labels === 'common' || labels === 'producer' || labels === 'consumer') {
          acc.common.push(name);
          return acc;
        }

        if (labels.includes('advanced')) {
          acc.groups['advanced'] ??= [];
          acc.groups['advanced'].push(name);
          return acc;
        }

        acc.groups[labels] ??= [];
        acc.groups[labels].push(name);
        return acc;
      },
      { common: [], groups: {} } as { common: string[]; groups: Record<string, string[]> },
    );

    return (
      <Card data-testid={'nest-field'} {...filterDOMProps(props)} isExpanded>
        <CardHeader>
          <CardTitle>{label}</CardTitle>
        </CardHeader>
        <CardBody className="custom-nestfield-spacing">
          {propertiesArray.common.map((field) => (
            <CustomAutoField key={field} name={field} />
          ))}
        </CardBody>

        {Object.entries(propertiesArray.groups).map(([groupName, groupFields]) => (
          <ExpandableSection toggleText={`${groupName} properties`}>
            <CardBody className="custom-nestfield-spacing">
              {groupFields.map((field) => (
                <CustomAutoField key={field} name={field} />
              ))}
            </CardBody>
          </ExpandableSection>
        ))}
      </Card>
    );
  },
);

The difference here is that we iterate over the labels to create the groups dynamically, this way, for amqp we show other groups:
image

It's not a final idea, since we would need to decorate the expandable titles with sentence case, and maybe there are other rough edges.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Seems like there are quite many groups, but this is I suppose only the case for handful of connectors with large number of config properties, so even though for AMQP this looks like too many config dropdowns, this probably would be OK for most of the connectors.

The one thing that comes to my mind is how would we deduplicate the properties in the config, as in this solution one property could appear in more than one dropdown if I'm not mistaking.

Copy link
Contributor

@lhein lhein Apr 2, 2024

Choose a reason for hiding this comment

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

Nope, each parameter can be only in one group which is determined by the catalog attribute "group".
Also keep in mind to use the attribute "label" for the group names.

Example:

 "group": "logging", "label": "consumer,logging",

Copy link
Member

Choose a reason for hiding this comment

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

Got it, I think it's possible to adjust it to match that, I'm just curious to know @tplevko opinion on the approach 😃

Copy link
Contributor

Choose a reason for hiding this comment

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

hmm...actually I am not sure label is a good idea. that sounds more like tags

Loading
Loading