| 1 |
import { memo } from "@wordpress/element"; |
| 2 |
import { Button } from "@wordpress/components"; |
| 3 |
import { useDeviceType } from "../../controls/controls"; |
| 4 |
|
| 5 |
const Units = ({ attributes, setAttributes, attributesKey, units, onUnitChange = false }) => { |
| 6 |
const deviceType = useDeviceType(); |
| 7 |
// Set unit function. |
| 8 |
const setUnit = (newValue) => { |
| 9 |
if (onUnitChange) { |
| 10 |
return onUnitChange({ unit: newValue, deviceType: deviceType }); |
| 11 |
} |
| 12 |
if ("undefined" === typeof attributes.unit && attributes?.device?.[deviceType]) { |
| 13 |
// if (onUnitChange) { |
| 14 |
// return onUnitChange({ unit: newValue, deviceType: deviceType }); |
| 15 |
// } |
| 16 |
setAttributes({ |
| 17 |
[attributesKey]: { |
| 18 |
...attributes, |
| 19 |
unit: { |
| 20 |
...attributes?.unit, |
| 21 |
[deviceType]: newValue.toLowerCase(), |
| 22 |
}, |
| 23 |
}, |
| 24 |
}); |
| 25 |
} else if (attributes.unit?.[deviceType]) { |
| 26 |
// if (onUnitChange) { |
| 27 |
// return onUnitChange({ unit: newValue, deviceType: deviceType }); |
| 28 |
// } |
| 29 |
setAttributes({ |
| 30 |
[attributesKey]: { |
| 31 |
...attributes, |
| 32 |
unit: { |
| 33 |
...attributes.unit, |
| 34 |
[deviceType]: newValue.toLowerCase(), |
| 35 |
}, |
| 36 |
}, |
| 37 |
}); |
| 38 |
} else { |
| 39 |
// if (onUnitChange) { |
| 40 |
// return onUnitChange({ unit: newValue, deviceType: deviceType || "Desktop" }); |
| 41 |
// } |
| 42 |
setAttributes({ |
| 43 |
[attributesKey]: { |
| 44 |
...attributes, |
| 45 |
unit: newValue.toLowerCase(), |
| 46 |
}, |
| 47 |
}); |
| 48 |
} |
| 49 |
}; |
| 50 |
|
| 51 |
const activeUnitValue = () => { |
| 52 |
if (typeof attributes.unit === "object" && attributes.unit?.[deviceType]) { |
| 53 |
return attributes.unit?.[deviceType]; |
| 54 |
} else if (typeof attributes.unit === "string") { |
| 55 |
return attributes.unit.toLowerCase(); |
| 56 |
} |
| 57 |
return ""; |
| 58 |
}; |
| 59 |
|
| 60 |
return ( |
| 61 |
<div className="sp-smart-post-units"> |
| 62 |
<span>{"object" !== typeof attributes?.unit ? attributes?.unit : attributes.unit?.[deviceType]}</span> |
| 63 |
<div className="sp-smart-post-units-btn"> |
| 64 |
{units?.map((item, i) => ( |
| 65 |
<Button |
| 66 |
className={activeUnitValue() === item.toLowerCase() ? "active" : ""} |
| 67 |
key={i} |
| 68 |
value={item} |
| 69 |
onClick={(e) => setUnit(e.target.value)} |
| 70 |
> |
| 71 |
{" "} |
| 72 |
{item.toLowerCase()}{" "} |
| 73 |
</Button> |
| 74 |
))} |
| 75 |
</div> |
| 76 |
</div> |
| 77 |
); |
| 78 |
}; |
| 79 |
|
| 80 |
export default memo(Units); |
| 81 |
|