| 1 |
import React from "react"; |
| 2 |
|
| 3 |
import { |
| 4 |
__experimentalFontAppearanceControl as WPFontAppearanceControl, |
| 5 |
useBlockEditContext, |
| 6 |
} from "@wordpress/block-editor"; |
| 7 |
import { useDispatch, useSelect } from "@wordpress/data"; |
| 8 |
|
| 9 |
import type { FontAppearanceControlProps, FontAppearanceValue } from "./types"; |
| 10 |
|
| 11 |
const DEFAULT_FONT_APPEARANCE: FontAppearanceValue = { |
| 12 |
fontStyle: "normal", |
| 13 |
fontWeight: "400", |
| 14 |
}; |
| 15 |
|
| 16 |
function normalizeFontAppearance( |
| 17 |
value: unknown, |
| 18 |
defaultValue: FontAppearanceValue, |
| 19 |
): FontAppearanceValue { |
| 20 |
if (value && typeof value === "object") { |
| 21 |
const appearance = value as FontAppearanceValue; |
| 22 |
|
| 23 |
return { |
| 24 |
fontStyle: appearance.fontStyle || defaultValue.fontStyle, |
| 25 |
fontWeight: appearance.fontWeight || defaultValue.fontWeight, |
| 26 |
}; |
| 27 |
} |
| 28 |
|
| 29 |
return defaultValue; |
| 30 |
} |
| 31 |
|
| 32 |
const FontAppearanceControl: React.FC<FontAppearanceControlProps> = ({ |
| 33 |
attrKey, |
| 34 |
label, |
| 35 |
defaultValue = DEFAULT_FONT_APPEARANCE, |
| 36 |
onAttributesUpdate = () => null, |
| 37 |
hasFontStyles = true, |
| 38 |
hasFontWeights = true, |
| 39 |
fontFamilyFaces, |
| 40 |
}) => { |
| 41 |
const { clientId } = useBlockEditContext(); |
| 42 |
const { updateBlockAttributes } = useDispatch("core/block-editor") as any; |
| 43 |
|
| 44 |
const attributes = useSelect( |
| 45 |
(select) => { |
| 46 |
const blockEditorStore = select("core/block-editor") as any; |
| 47 |
|
| 48 |
return blockEditorStore?.getBlockAttributes?.(clientId) ?? {}; |
| 49 |
}, |
| 50 |
[clientId], |
| 51 |
) as Record<string, any>; |
| 52 |
|
| 53 |
const currentValue = normalizeFontAppearance( |
| 54 |
attributes[attrKey], |
| 55 |
defaultValue, |
| 56 |
); |
| 57 |
|
| 58 |
const setAttributes = (newAttributes: Record<string, any>) => { |
| 59 |
updateBlockAttributes(clientId, newAttributes); |
| 60 |
onAttributesUpdate(newAttributes); |
| 61 |
}; |
| 62 |
|
| 63 |
return ( |
| 64 |
<WPFontAppearanceControl |
| 65 |
__next40pxDefaultSize |
| 66 |
label={label} |
| 67 |
value={currentValue} |
| 68 |
onChange={(newValue) => |
| 69 |
setAttributes({ |
| 70 |
[attrKey]: |
| 71 |
normalizeFontAppearance(newValue, defaultValue) ?? defaultValue, |
| 72 |
}) |
| 73 |
} |
| 74 |
hasFontStyles={hasFontStyles} |
| 75 |
hasFontWeights={hasFontWeights} |
| 76 |
fontFamilyFaces={fontFamilyFaces} |
| 77 |
/> |
| 78 |
); |
| 79 |
}; |
| 80 |
|
| 81 |
export default FontAppearanceControl; |
| 82 |
|