diff --git a/dev-test/config.yml b/dev-test/config.yml
index 7a2f4ccc..6eb9615b 100644
--- a/dev-test/config.yml
+++ b/dev-test/config.yml
@@ -18,7 +18,14 @@ collections: # A list of collections the CMS should be able to edit
create: true # Allow users to create new documents in this collection
fields: # The fields each document in this collection have
- { label: 'Title', name: 'title', widget: 'string', tagname: 'h1' }
- - { label: 'Publish Date', name: 'date', widget: 'datetime', dateFormat: 'YYYY-MM-DD', timeFormat: 'HH:mm', format: 'YYYY-MM-DD HH:mm' }
+ - {
+ label: 'Publish Date',
+ name: 'date',
+ widget: 'datetime',
+ dateFormat: 'YYYY-MM-DD',
+ timeFormat: 'HH:mm',
+ format: 'YYYY-MM-DD HH:mm',
+ }
- label: 'Cover Image'
name: 'image'
widget: 'image'
@@ -92,6 +99,13 @@ collections: # A list of collections the CMS should be able to edit
- { label: 'Image', name: 'image', widget: 'image' }
- { label: 'File', name: 'file', widget: 'file' }
- { label: 'Select', name: 'select', widget: 'select', options: ['a', 'b', 'c'] }
+ - {
+ label: 'Select multiple',
+ name: 'select_multiple',
+ widget: 'select',
+ options: ['a', 'b', 'c'],
+ multiple: true,
+ }
- { label: 'Hidden', name: 'hidden', widget: 'hidden', default: 'hidden' }
- label: 'Object'
name: 'object'
diff --git a/packages/netlify-cms-core/src/components/Editor/EditorControlPane/Widget.js b/packages/netlify-cms-core/src/components/Editor/EditorControlPane/Widget.js
index e9740a35..002e0ad0 100644
--- a/packages/netlify-cms-core/src/components/Editor/EditorControlPane/Widget.js
+++ b/packages/netlify-cms-core/src/components/Editor/EditorControlPane/Widget.js
@@ -1,7 +1,7 @@
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
-import { Map } from 'immutable';
+import { Map, List } from 'immutable';
import ValidationErrorTypes from 'Constants/validationErrorTypes';
const truthy = () => ({ error: false });
@@ -10,7 +10,8 @@ const isEmpty = value =>
value === null ||
value === undefined ||
(value.hasOwnProperty('length') && value.length === 0) ||
- (value.constructor === Object && Object.keys(value).length === 0);
+ (value.constructor === Object && Object.keys(value).length === 0) ||
+ (List.isList(value) && value.size === 0);
export default class Widget extends Component {
static propTypes = {
diff --git a/packages/netlify-cms-widget-select/package.json b/packages/netlify-cms-widget-select/package.json
index dd657f51..b91bb888 100644
--- a/packages/netlify-cms-widget-select/package.json
+++ b/packages/netlify-cms-widget-select/package.json
@@ -23,6 +23,8 @@
},
"devDependencies": {
"cross-env": "^5.2.0",
+ "jest-dom": "^2.1.1",
+ "react-testing-library": "^5.3.0",
"webpack": "^4.16.1",
"webpack-cli": "^3.1.0"
},
diff --git a/packages/netlify-cms-widget-select/src/SelectControl.js b/packages/netlify-cms-widget-select/src/SelectControl.js
index 4a3b2e31..3a53dabf 100644
--- a/packages/netlify-cms-widget-select/src/SelectControl.js
+++ b/packages/netlify-cms-widget-select/src/SelectControl.js
@@ -1,20 +1,20 @@
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
-import { Map } from 'immutable';
+import { Map, List, fromJS } from 'immutable';
import { find } from 'lodash';
import Select from 'react-select';
import { colors } from 'netlify-cms-ui-default';
const styles = {
- control: provided => ({
- ...provided,
+ control: styles => ({
+ ...styles,
border: 0,
boxShadow: 'none',
padding: '9px 0 9px 12px',
}),
- option: (provided, state) => ({
- ...provided,
+ option: (styles, state) => ({
+ ...styles,
backgroundColor: state.isSelected
? `${colors.active}`
: state.isFocused
@@ -22,12 +22,44 @@ const styles = {
: 'transparent',
paddingLeft: '22px',
}),
- menu: provided => ({ ...provided, right: 0 }),
- container: provided => ({ ...provided, padding: '0 !important' }),
- indicatorSeparator: () => ({ display: 'none' }),
- dropdownIndicator: provided => ({ ...provided, color: `${colors.controlLabel}` }),
+ menu: styles => ({ ...styles, right: 0, zIndex: 2 }),
+ container: styles => ({ ...styles, padding: '0 !important' }),
+ indicatorSeparator: (styles, state) =>
+ state.hasValue && state.selectProps.isClearable
+ ? { ...styles, backgroundColor: `${colors.textFieldBorder}` }
+ : { display: 'none' },
+ dropdownIndicator: styles => ({ ...styles, color: `${colors.controlLabel}` }),
+ clearIndicator: styles => ({ ...styles, color: `${colors.controlLabel}` }),
+ multiValue: styles => ({
+ ...styles,
+ backgroundColor: colors.background,
+ }),
+ multiValueLabel: styles => ({
+ ...styles,
+ color: colors.textLead,
+ fontWeight: 500,
+ }),
+ multiValueRemove: styles => ({
+ ...styles,
+ color: colors.controlLabel,
+ ':hover': {
+ color: colors.errorText,
+ backgroundColor: colors.errorBackground,
+ },
+ }),
};
+function optionToString(option) {
+ return option && option.value ? option.value : '';
+}
+
+function convertToOption(raw) {
+ if (typeof raw === 'string') {
+ return { label: raw, value: raw };
+ }
+ return Map.isMap(raw) ? raw.toJS() : raw;
+}
+
export default class SelectControl extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
@@ -49,33 +81,48 @@ export default class SelectControl extends React.Component {
}),
};
- static defaultProps = {
- value: '',
+ handleChange = selectedOption => {
+ const { onChange } = this.props;
+
+ if (Array.isArray(selectedOption)) {
+ onChange(fromJS(selectedOption.map(optionToString)));
+ } else {
+ onChange(optionToString(selectedOption));
+ }
};
- handleChange = selectedOption => {
- this.props.onChange(selectedOption['value']);
+ getSelectedValue = ({ value, options, isMultiple }) => {
+ if (isMultiple) {
+ const selectedOptions = List.isList(value) ? value.toJS() : value;
+
+ if (!selectedOptions || !Array.isArray(selectedOptions)) {
+ return null;
+ }
+
+ return selectedOptions
+ .filter(i => options.find(o => o.value === (i.value || i)))
+ .map(convertToOption);
+ } else {
+ return find(options, ['value', value]) || null;
+ }
};
render() {
const { field, value, forID, classNameWrapper, setActiveStyle, setInactiveStyle } = this.props;
const fieldOptions = field.get('options');
+ const isMultiple = field.get('multiple', false);
+ const isClearable = !field.get('required', true) || isMultiple;
if (!fieldOptions) {
return
Error rendering select control for {field.get('name')}: No options
;
}
- const options = [
- ...(field.get('default', false) ? [] : [{ label: '', value: '' }]),
- ...fieldOptions.map(option => {
- if (typeof option === 'string') {
- return { label: option, value: option };
- }
- return Map.isMap(option) ? option.toJS() : option;
- }),
- ];
-
- const selectedValue = find(options, ['value', value]);
+ const options = [...fieldOptions.map(convertToOption)];
+ const selectedValue = this.getSelectedValue({
+ options,
+ value,
+ isMultiple,
+ });
return (
);
}
diff --git a/packages/netlify-cms-widget-select/src/__tests__/select.spec.js b/packages/netlify-cms-widget-select/src/__tests__/select.spec.js
new file mode 100644
index 00000000..44ca472b
--- /dev/null
+++ b/packages/netlify-cms-widget-select/src/__tests__/select.spec.js
@@ -0,0 +1,118 @@
+import React from 'react';
+import { fromJS } from 'immutable';
+import { render, fireEvent } from 'react-testing-library';
+import 'react-testing-library/cleanup-after-each';
+import 'jest-dom/extend-expect';
+import { SelectControl } from '../';
+
+const options = [
+ { value: 'Foo', label: 'Foo' },
+ { value: 'Bar', label: 'Bar' },
+ { value: 'Baz', label: 'Baz' },
+];
+
+class SelectController extends React.Component {
+ state = {
+ value: this.props.defaultValue,
+ };
+
+ handleOnChange = jest.fn(value => {
+ this.setState({ value });
+ });
+
+ componentDidUpdate() {
+ this.props.onStateChange(this.state);
+ }
+
+ render() {
+ return this.props.children({
+ value: this.state.value,
+ handleOnChange: this.handleOnChange,
+ });
+ }
+}
+
+function setup({ field, defaultValue }) {
+ let renderArgs;
+ const stateChangeSpy = jest.fn();
+ const setActiveSpy = jest.fn();
+ const setInactiveSpy = jest.fn();
+
+ const helpers = render(
+
+ {({ value, handleOnChange }) => {
+ renderArgs = { value, onChangeSpy: handleOnChange };
+ return (
+
+ );
+ }}
+ ,
+ );
+
+ const input = helpers.container.querySelector('input');
+
+ return {
+ ...helpers,
+ ...renderArgs,
+ stateChangeSpy,
+ setActiveSpy,
+ setInactiveSpy,
+ input,
+ };
+}
+
+describe('Select widget', () => {
+ it('should call onChange with correct selectedItem', () => {
+ const field = fromJS({ options });
+ const { getByText, input, onChangeSpy } = setup({ field });
+
+ fireEvent.focus(input);
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.click(getByText('Foo'));
+
+ expect(onChangeSpy).toHaveBeenCalledTimes(1);
+ expect(onChangeSpy).toHaveBeenCalledWith(options[0].value);
+ });
+
+ it('should respect value', () => {
+ const field = fromJS({ options });
+ const { getByText } = setup({ field, defaultValue: options[2].value });
+
+ expect(getByText('Baz')).toBeInTheDocument();
+ });
+
+ describe('with multiple', () => {
+ it('should call onChange with correct selectedItem', () => {
+ const field = fromJS({ options, multiple: true });
+ const { getByText, input, onChangeSpy } = setup({ field });
+
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.click(getByText('Foo'));
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.click(getByText('Baz'));
+
+ expect(onChangeSpy).toHaveBeenCalledTimes(2);
+ expect(onChangeSpy).toHaveBeenCalledWith(fromJS([options[0].value]));
+ expect(onChangeSpy).toHaveBeenCalledWith(fromJS([options[0].value, options[2].value]));
+ });
+
+ it('should respect value', () => {
+ const field = fromJS({ options, multiple: true });
+ const { getByText } = setup({
+ field,
+ defaultValue: fromJS([options[1].value, options[2].value]),
+ });
+
+ expect(getByText('Bar')).toBeInTheDocument();
+ expect(getByText('Baz')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/website/content/docs/widgets/select.md b/website/content/docs/widgets/select.md
index 8a31b796..52eef2de 100644
--- a/website/content/docs/widgets/select.md
+++ b/website/content/docs/widgets/select.md
@@ -3,16 +3,17 @@ label: "Select"
title: select
---
-The select widget allows you to pick a single string value from a dropdown menu.
+The select widget allows you to pick a string value from a dropdown menu.
- **Name:** `select`
-- **UI:** HTML select input
-- **Data type:** string
+- **UI:** select input
+- **Data type:** string or array
- **Options:**
- `default`: accepts a string; defaults to an empty string
- `options`: (**required**) a list of options for the dropdown menu; can be listed in two ways:
- string values: the label displayed in the dropdown is the value saved in the file
- object with `label` and `value` fields: the label displays in the dropdown; the value is saved in the file
+ - `multiple`: accepts a boolean; defaults to `false`
- **Example** (options as strings):
```yaml
- label: "Align Content"
@@ -30,4 +31,12 @@ The select widget allows you to pick a single string value from a dropdown menu.
- { label: "Paris", value: "CDG" }
- { label: "Tokyo", value: "HND" }
```
+- **Example** (multiple):
+ ```yaml
+ - label: "Tags"
+ name: "tags"
+ widget: "select"
+ multiple: true
+ options: ["Design", "UX", "Dev"]
+ ```
diff --git a/yarn.lock b/yarn.lock
index c3c9ea6e..0790b183 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1487,6 +1487,11 @@
resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-1.1.0.tgz#50c1e2260ac0ed9439a181de3725a0168d59c48a"
integrity sha512-LAQ1d4OPfSJ/BMbI2DuizmYrrkD9JMaTdi2hQTlI53lQ4kRQPyZQRS4CYQ7O66bnBBnP/oYdRxbk++X0xuFU6A==
+"@sheerun/mutationobserver-shim@^0.3.2":
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/@sheerun/mutationobserver-shim/-/mutationobserver-shim-0.3.2.tgz#8013f2af54a2b7d735f71560ff360d3a8176a87b"
+ integrity sha512-vTCdPp/T/Q3oSqwHmZ5Kpa9oI7iLtGl3RQaA/NyLHikvcrPxACkkKVr/XzkSPJWXHRhKGzVvb0urJsbMlRxi1Q==
+
"@types/blob-util@1.3.3":
version "1.3.3"
resolved "https://registry.yarnpkg.com/@types/blob-util/-/blob-util-1.3.3.tgz#adba644ae34f88e1dd9a5864c66ad651caaf628a"
@@ -3717,6 +3722,16 @@ css@^2.2.1:
source-map-resolve "^0.5.1"
urix "^0.1.0"
+css@^2.2.3:
+ version "2.2.4"
+ resolved "https://registry.yarnpkg.com/css/-/css-2.2.4.tgz#c646755c73971f2bba6a601e2cf2fd71b1298929"
+ integrity sha512-oUnjmWpy0niI3x/mPL8dVEI1l7MnG3+HHyRPHf+YFSbK+svOhXpmSOcDURUh2aOCgl2grzrOPt1nHLuCVFULLw==
+ dependencies:
+ inherits "^2.0.3"
+ source-map "^0.6.1"
+ source-map-resolve "^0.5.2"
+ urix "^0.1.0"
+
cssesc@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-0.1.0.tgz#c814903e45623371a0477b40109aaafbeeaddbb4"
@@ -4147,6 +4162,15 @@ dom-serializer@0:
domelementtype "~1.1.1"
entities "~1.1.1"
+dom-testing-library@^3.12.0:
+ version "3.12.4"
+ resolved "https://registry.yarnpkg.com/dom-testing-library/-/dom-testing-library-3.12.4.tgz#393fd104563464c91c8db1b80c5b7feb1d766c72"
+ integrity sha512-0+HwCOhnFitZBenJFAUGiiCOmk72i5ui34sjf+i5oBFiOwe/3Jx4wNiPAjL/qAJmK76o0z50o7nRHutzSgvzgg==
+ dependencies:
+ "@sheerun/mutationobserver-shim" "^0.3.2"
+ pretty-format "^23.6.0"
+ wait-for-expect "^1.0.0"
+
dom-walk@^0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/dom-walk/-/dom-walk-0.1.1.tgz#672226dc74c8f799ad35307df936aba11acd6018"
@@ -6798,6 +6822,16 @@ jest-diff@^23.2.0:
jest-get-type "^22.1.0"
pretty-format "^23.2.0"
+jest-diff@^23.6.0:
+ version "23.6.0"
+ resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-23.6.0.tgz#1500f3f16e850bb3d71233408089be099f610c7d"
+ integrity sha512-Gz9l5Ov+X3aL5L37IT+8hoCUsof1CVYBb2QEkOupK64XyRR3h+uRpYIm97K7sY8diFxowR8pIGEdyfMKTixo3g==
+ dependencies:
+ chalk "^2.0.1"
+ diff "^3.2.0"
+ jest-get-type "^22.1.0"
+ pretty-format "^23.6.0"
+
jest-docblock@^23.2.0:
version "23.2.0"
resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-23.2.0.tgz#f085e1f18548d99fdd69b20207e6fd55d91383a7"
@@ -6805,6 +6839,19 @@ jest-docblock@^23.2.0:
dependencies:
detect-newline "^2.1.0"
+jest-dom@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/jest-dom/-/jest-dom-2.1.1.tgz#c75515ef31147bd9684c860b0cba9605638fd4dd"
+ integrity sha512-jE1LRnP/wVGdQy6sVJ+dPwMq6rXXuvYTnzWEb8hDwfxhQesoaaukJzZaZYi14JPpdmhrncdpUsZpagN7HjuTsw==
+ dependencies:
+ chalk "^2.4.1"
+ css "^2.2.3"
+ jest-diff "^23.6.0"
+ jest-matcher-utils "^23.6.0"
+ lodash "^4.17.11"
+ pretty-format "^23.6.0"
+ redent "^2.0.0"
+
jest-each@^23.4.0:
version "23.4.0"
resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-23.4.0.tgz#2fa9edd89daa1a4edc9ff9bf6062a36b71345143"
@@ -6891,6 +6938,15 @@ jest-matcher-utils@^23.2.0:
jest-get-type "^22.1.0"
pretty-format "^23.2.0"
+jest-matcher-utils@^23.6.0:
+ version "23.6.0"
+ resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-23.6.0.tgz#726bcea0c5294261a7417afb6da3186b4b8cac80"
+ integrity sha512-rosyCHQfBcol4NsckTn01cdelzWLU9Cq7aaigDf8VwwpIRvWE/9zLgX2bON+FkEW69/0UuYslUe22SOdEf2nog==
+ dependencies:
+ chalk "^2.0.1"
+ jest-get-type "^22.1.0"
+ pretty-format "^23.6.0"
+
jest-message-util@^23.4.0:
version "23.4.0"
resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-23.4.0.tgz#17610c50942349508d01a3d1e0bda2c079086a9f"
@@ -9201,6 +9257,14 @@ pretty-format@^23.2.0:
ansi-regex "^3.0.0"
ansi-styles "^3.2.0"
+pretty-format@^23.6.0:
+ version "23.6.0"
+ resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-23.6.0.tgz#5eaac8eeb6b33b987b7fe6097ea6a8a146ab5760"
+ integrity sha512-zf9NV1NSlDLDjycnwm6hpFATCGl/K1lt0R/GdkAK2O5LN/rwJoB+Mh93gGJjut4YbmecbfgLWVGSTCr0Ewvvbw==
+ dependencies:
+ ansi-regex "^3.0.0"
+ ansi-styles "^3.2.0"
+
private@^0.1.6, private@^0.1.8:
version "0.1.8"
resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff"
@@ -9740,6 +9804,13 @@ react-test-renderer@^16.0.0:
prop-types "^15.6.0"
react-is "^16.4.2"
+react-testing-library@^5.3.0:
+ version "5.3.0"
+ resolved "https://registry.yarnpkg.com/react-testing-library/-/react-testing-library-5.3.0.tgz#b88124441d8756438137b705eb26a99410de69cc"
+ integrity sha512-hUXurQC8b828s2Fyuyuibz1PvPbGWb5vSIDCb1ihcGVjzBP9OGnsAm6Dhpu7XqC1o/68KJ/5/QdkeiTDxS9gpw==
+ dependencies:
+ dom-testing-library "^3.12.0"
+
react-textarea-autosize@^7.0.0:
version "7.0.4"
resolved "https://registry.yarnpkg.com/react-textarea-autosize/-/react-textarea-autosize-7.0.4.tgz#4e4be649b544a88713e7b5043f76950f35d3d503"
@@ -10926,7 +10997,7 @@ source-list-map@^2.0.0:
resolved "https://registry.yarnpkg.com/source-list-map/-/source-list-map-2.0.0.tgz#aaa47403f7b245a92fbc97ea08f250d6087ed085"
integrity sha512-I2UmuJSRr/T8jisiROLU3A3ltr+swpniSmNPI4Ml3ZCX6tVnDsuZzK7F2hl5jTqbZBWCEKlj5HRQiPExXLgE8A==
-source-map-resolve@^0.5.0, source-map-resolve@^0.5.1:
+source-map-resolve@^0.5.0, source-map-resolve@^0.5.1, source-map-resolve@^0.5.2:
version "0.5.2"
resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259"
integrity sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==
@@ -12262,6 +12333,11 @@ w3c-hr-time@^1.0.1:
dependencies:
browser-process-hrtime "^0.1.2"
+wait-for-expect@^1.0.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/wait-for-expect/-/wait-for-expect-1.1.0.tgz#6607375c3f79d32add35cd2c87ce13f351a3d453"
+ integrity sha512-vQDokqxyMyknfX3luCDn16bSaRcOyH6gGuUXMIbxBLeTo6nWuEWYqMTT9a+44FmW8c2m6TRWBdNvBBjA1hwEKg==
+
wait-on@2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/wait-on/-/wait-on-2.1.0.tgz#3c4ace1f57266ca5be7fa25e0c15803b889ca46a"