| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { WPElement } from '@wordpress/element'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Internal dependencies. |
| 8 |
*/ |
| 9 |
import { useFeatureSettings } from '../provider'; |
| 10 |
import Control from './control'; |
| 11 |
|
| 12 |
/** |
| 13 |
* Feature settings component. |
| 14 |
* |
| 15 |
* @param {object} props Component props. |
| 16 |
* @param {string} props.feature Feature slug. |
| 17 |
* @param {Array} props.settingsSchema Feature settings schema. |
| 18 |
* @returns {WPElement} Feature settings component. |
| 19 |
*/ |
| 20 |
export default ({ feature, settingsSchema }) => { |
| 21 |
const { getFeature, settings, setSettings, syncedSettings } = useFeatureSettings(); |
| 22 |
|
| 23 |
const { isAvailable } = getFeature(feature); |
| 24 |
|
| 25 |
/** |
| 26 |
* Change event handler. |
| 27 |
* |
| 28 |
* @param {string} key Setting key. |
| 29 |
* @param {string|boolean} value Setting value. |
| 30 |
*/ |
| 31 |
const onChange = (key, value) => { |
| 32 |
setSettings({ |
| 33 |
...settings, |
| 34 |
[feature]: { |
| 35 |
...settings[feature], |
| 36 |
[key]: value, |
| 37 |
}, |
| 38 |
}); |
| 39 |
}; |
| 40 |
|
| 41 |
return settingsSchema.map((s) => { |
| 42 |
const { |
| 43 |
default: defaultValue, |
| 44 |
disabled, |
| 45 |
help, |
| 46 |
key, |
| 47 |
label, |
| 48 |
options, |
| 49 |
requires_feature, |
| 50 |
requires_sync, |
| 51 |
type, |
| 52 |
} = s; |
| 53 |
|
| 54 |
/** |
| 55 |
* Current control value. If no setting value is set, use the |
| 56 |
* setting's default value. |
| 57 |
*/ |
| 58 |
let value = |
| 59 |
typeof settings[feature]?.[key] !== 'undefined' ? settings[feature][key] : defaultValue; |
| 60 |
|
| 61 |
/** |
| 62 |
* If the feature is unavailable, the active toggle should be off. |
| 63 |
*/ |
| 64 |
if (key === 'active' && !isAvailable) { |
| 65 |
value = false; |
| 66 |
} |
| 67 |
|
| 68 |
return ( |
| 69 |
<Control |
| 70 |
disabled={disabled || !isAvailable} |
| 71 |
key={key} |
| 72 |
help={help} |
| 73 |
label={label} |
| 74 |
name={key} |
| 75 |
onChange={(value) => onChange(key, value)} |
| 76 |
options={options} |
| 77 |
syncedValue={syncedSettings?.[feature]?.[key]} |
| 78 |
requiresFeature={requires_feature} |
| 79 |
requiresSync={requires_sync} |
| 80 |
type={type} |
| 81 |
value={value} |
| 82 |
/> |
| 83 |
); |
| 84 |
}); |
| 85 |
}; |
| 86 |
|