| 1 |
import { memo } from "@wordpress/element"; |
| 2 |
import { useDeviceType } from "../../controls/controls"; |
| 3 |
import { Button } from "@wordpress/components"; |
| 4 |
import { ResetIcon } from "../../icons/icons"; |
| 5 |
|
| 6 |
const ResetButton = ({ |
| 7 |
attributes, |
| 8 |
setAttributes, |
| 9 |
attributesKey, |
| 10 |
defaultValue, |
| 11 |
value, |
| 12 |
setCurrentValue = () => {}, |
| 13 |
setCustomReset = false, |
| 14 |
}) => { |
| 15 |
const deviceType = useDeviceType(); |
| 16 |
// Ranger single value and multiple device value. |
| 17 |
const defaultValueOrDevice = defaultValue?.device ? defaultValue?.device?.[deviceType] : defaultValue.value; |
| 18 |
|
| 19 |
const activeResetButton = () => { |
| 20 |
// If unit is not present, treat it as not changed |
| 21 |
const hasUnit = typeof attributes?.unit === "object" && typeof defaultValue?.unit === "object"; |
| 22 |
const isUnitDifferent = hasUnit && defaultValue.unit?.[deviceType] !== attributes.unit?.[deviceType]; |
| 23 |
|
| 24 |
const isValueDifferent = defaultValue?.device?.[deviceType] !== parseInt(value); |
| 25 |
|
| 26 |
if (isUnitDifferent || isValueDifferent) { |
| 27 |
return "active"; |
| 28 |
} |
| 29 |
|
| 30 |
return ""; |
| 31 |
}; |
| 32 |
|
| 33 |
// Set default value function and reset. |
| 34 |
const setDefault = () => { |
| 35 |
if (setCustomReset) { |
| 36 |
// return { value: defaultValue?.value, unit: defaultValue?.unit }; |
| 37 |
return setCurrentValue(defaultValueOrDevice); |
| 38 |
} |
| 39 |
// It's multiple device (desktop/tablet/mobile). |
| 40 |
if ( !setCustomReset && attributes.device) { |
| 41 |
setAttributes({ |
| 42 |
[attributesKey]: { |
| 43 |
...attributes, |
| 44 |
device: { |
| 45 |
...attributes.device, |
| 46 |
[deviceType]: defaultValue.value, |
| 47 |
}, |
| 48 |
unit: { |
| 49 |
...attributes.unit, |
| 50 |
[deviceType]: defaultValue.unit, |
| 51 |
}, |
| 52 |
}, |
| 53 |
}); |
| 54 |
} |
| 55 |
|
| 56 |
// It's single device (desktop) |
| 57 |
if ("object" === typeof attributes) { |
| 58 |
if ("number" === typeof attributes.value) { |
| 59 |
setAttributes({ |
| 60 |
[attributesKey]: { |
| 61 |
...attributes, |
| 62 |
value: defaultValue.value, |
| 63 |
}, |
| 64 |
}); |
| 65 |
} |
| 66 |
} else { |
| 67 |
setAttributes({ [attributesKey]: defaultValue }); |
| 68 |
} |
| 69 |
|
| 70 |
setCurrentValue(defaultValueOrDevice); |
| 71 |
}; |
| 72 |
|
| 73 |
return ( |
| 74 |
<Button |
| 75 |
className={`sp-smart-post-header-control-reset ${activeResetButton()}`} |
| 76 |
onClick={() => setDefault()} |
| 77 |
aria-label="Reset to default value" |
| 78 |
> |
| 79 |
<ResetIcon /> |
| 80 |
</Button> |
| 81 |
); |
| 82 |
}; |
| 83 |
|
| 84 |
export default memo(ResetButton); |
| 85 |
|