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(core): add support for <optgroup> tag #4374

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ should change the heading of the (upcoming) version to include a major version b

-->

# 5.23.0
Copy link
Member

Choose a reason for hiding this comment

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

This will now be 5.24.0 since we just released 5.23.0


## @rjsf/core

- Updated `SelectWidget` to support `<optgroup>` through `ui:options` `optgroup`. Fixes [#1813]

## Dev / docs / playground

- Updated `samples/widgets` to show `optgroup` usage (`selectWidgetOptions3`)

# 5.22.4

## @rjsf/utils
Expand Down
46 changes: 34 additions & 12 deletions packages/core/src/components/widgets/SelectWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function SelectWidget<T = any, S extends StrictRJSFSchema = RJSFSchema, F extend
onFocus,
placeholder,
}: WidgetProps<T, S, F>) {
const { enumOptions, enumDisabled, emptyValue: optEmptyVal } = options;
const { enumOptions, enumDisabled, emptyValue: optEmptyVal, optgroups } = options;
const emptyValue = multiple ? [] : '';

const handleFocus = useCallback(
Expand Down Expand Up @@ -67,7 +67,37 @@ function SelectWidget<T = any, S extends StrictRJSFSchema = RJSFSchema, F extend
);

const selectedIndexes = enumOptionsIndexForValue<S>(value, enumOptions, multiple);
const showPlaceholderOption = !multiple && schema.default === undefined;

let opts = null
if (optgroups) {
let enumOptionFromValue = new Map()
enumOptions.forEach((enumOption, i) => {
enumOptionFromValue.set(enumOption.value, [enumOption, i])
})
opts = Object.keys(optgroups).map(optgroup => {
return (
<optgroup key={optgroup} label={optgroup}>{optgroups[optgroup].map(value => {
if (!enumOptionFromValue.has(value)) return null
const disabled = enumDisabled && enumDisabled.indexOf(value) !== -1;
let [{ label }, i] = enumOptionFromValue.get(value)
return (
<option key={i} value={String(i)} disabled={disabled}>
{label}
</option>
);
Comment on lines +81 to +87
Copy link
Member

Choose a reason for hiding this comment

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

Duplicate code here, minus the let line, which really should be const since you don't change anything

Copy link
Member

@heath-freenome heath-freenome Nov 15, 2024

Choose a reason for hiding this comment

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

Using the suggestion below, this would look like:

          if (!enumOptionFromValue.has(value)) {
            return null;
          }
          const [{ label }, i] = enumOptionFromValue.get(value);
          return <Option key={i} enumDisabled={enumDisabled} index={i} value={value} label={label} />;

})}</optgroup>
)
})
} else {
opts = Array.isArray(enumOptions) && enumOptions.map(({ value, label }, i) => {
const disabled = enumDisabled && enumDisabled.indexOf(value) !== -1;
return (
<option key={i} value={String(i)} disabled={disabled}>
{label}
</option>
);
Comment on lines +93 to +98
Copy link
Member

Choose a reason for hiding this comment

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

This is duplicate code to what is above. Consider creating a new component at the top of the file to render it and use it here and above

Copy link
Member

@heath-freenome heath-freenome Nov 15, 2024

Choose a reason for hiding this comment

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

Something like a helper component in the file:

interface OptionProps {
  enumDisabled?: UIOptionsType['enumDisabled'];
  value: EnumOptionsType['value'];
  label: EnumOptionsType['label'];
  index: number;
}

function Option(props: OptionProps) {
  const { enumDisabled, index, label, value } = props;
  const disabled = enumDisabled && enumDisabled.indexOf(value) !== -1;
  return (
    <option value={String(index)} disabled={disabled}>
      {label}
    </option>
  );
}

Then this would look like:

Array.isArray(enumOptions) && enumOptions.map(({ value, label }, i) => {
      return <Option key={i} enumDisabled={enumDisabled} index={i} value={value} label={label} />;

});
}

return (
<select
Expand All @@ -84,16 +114,8 @@ function SelectWidget<T = any, S extends StrictRJSFSchema = RJSFSchema, F extend
onChange={handleChange}
aria-describedby={ariaDescribedByIds<T>(id)}
>
{showPlaceholderOption && <option value=''>{placeholder}</option>}
{Array.isArray(enumOptions) &&
enumOptions.map(({ value, label }, i) => {
const disabled = enumDisabled && enumDisabled.indexOf(value) !== -1;
return (
<option key={i} value={String(i)} disabled={disabled}>
{label}
</option>
);
})}
{!multiple && schema.default === undefined && <option value=''>{placeholder}</option>}
{opts}
</select>
);
}
Expand Down
26 changes: 26 additions & 0 deletions packages/docs/docs/api-reference/uiSchema.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,32 @@ render(<Form schema={schema} uiSchema={uiSchema} validator={validator} />, docum

This property allows you to reorder the properties that are shown for a particular object. See [Objects](../json-schema/objects.md) for more information.

### optgroup

To leverage `<optgroup>` inside a select to group `<options>`, you can specify how to organize the options using the `optgroups` key inside your uiSchema.

```tsx
import { Form } from '@rjsf/core';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';

const schema: RJSFSchema = {
type: 'string',
enum: ['lorem', 'ipsum', 'dolorem', 'alpha', 'beta', 'gamma']
};

const uiSchema: UiSchema = {
'ui:options': {
optgroups: {
lipsum: ['lorem', 'ipsum', 'dolorem'],
greek: ['alpha', 'beta', 'gamma']
}
},
};

render(<Form schema={schema} uiSchema={uiSchema} validator={validator} />, document.getElementById('app'));
```

### placeholder

You can add placeholder text to an input by using the `ui:placeholder` uiSchema directive:
Expand Down
13 changes: 13 additions & 0 deletions packages/playground/src/samples/widgets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ const widgets: Sample = {
},
],
},
selectWidgetOptions3: {
title: 'Custom select widget with options grouped by optgroups',
type: 'string',
enum: ['foo', 'bar'],
},
},
},
uiSchema: {
Expand Down Expand Up @@ -196,6 +201,14 @@ const widgets: Sample = {
backgroundColor: 'pink',
},
},
selectWidgetOptions3: {
'ui:options': {
'optgroups': {
'lipsum': ['foo'],
'dolorem': ['bar']
}
}
}
},
formData: {
stringFormats: {
Expand Down