| 1 |
import { __ } from "@wordpress/i18n"; |
| 2 |
import { useSettings } from "@wordpress/block-editor"; |
| 3 |
import { FontSizePicker } from "@wordpress/components"; |
| 4 |
|
| 5 |
import TypographyPanelItem, { |
| 6 |
TypographyControlProps, |
| 7 |
} from "./TypographyPanelItem"; |
| 8 |
|
| 9 |
interface FontSize { |
| 10 |
name?: string; |
| 11 |
slug: string; |
| 12 |
size: string | number; |
| 13 |
} |
| 14 |
|
| 15 |
const PRESET_FONT_SIZE = /^var\(--wp--preset--font-size--([^)]+)\)$/; |
| 16 |
|
| 17 |
/** |
| 18 |
* A theme size is stored as its preset variable, the way the editor's own |
| 19 |
* controls do, so the block follows the theme (fluid sizes included) instead |
| 20 |
* of freezing whatever the preset measured at the time. Custom sizes are |
| 21 |
* stored as typed. |
| 22 |
*/ |
| 23 |
function toPickerValue(fontSize: string, fontSizes: FontSize[]) { |
| 24 |
const preset = fontSize.match(PRESET_FONT_SIZE); |
| 25 |
if (!preset) { |
| 26 |
return fontSize || undefined; |
| 27 |
} |
| 28 |
|
| 29 |
const match = fontSizes.find(size => size.slug === preset[1]); |
| 30 |
return match ? String(match.size) : undefined; |
| 31 |
} |
| 32 |
|
| 33 |
function fromPickerValue( |
| 34 |
newSize: string | number | undefined, |
| 35 |
selected?: FontSize |
| 36 |
) { |
| 37 |
if (newSize === undefined || newSize === "") { |
| 38 |
return ""; |
| 39 |
} |
| 40 |
|
| 41 |
return selected?.slug |
| 42 |
? `var(--wp--preset--font-size--${selected.slug})` |
| 43 |
: String(newSize); |
| 44 |
} |
| 45 |
|
| 46 |
export default function FontSizeControl({ |
| 47 |
label = __("Size", "tableberg"), |
| 48 |
value, |
| 49 |
onChange, |
| 50 |
onDeselect, |
| 51 |
resetAllFilter, |
| 52 |
isShownByDefault = true, |
| 53 |
isSingleColumn, |
| 54 |
panelId, |
| 55 |
}: TypographyControlProps) { |
| 56 |
const [fontSizes, customFontSize] = useSettings( |
| 57 |
"typography.fontSizes", |
| 58 |
"typography.customFontSize" |
| 59 |
); |
| 60 |
const sizes: FontSize[] = Array.isArray(fontSizes) ? fontSizes : []; |
| 61 |
|
| 62 |
return ( |
| 63 |
<TypographyPanelItem |
| 64 |
label={label} |
| 65 |
hasValue={() => !!value} |
| 66 |
onDeselect={onDeselect ?? (() => onChange(""))} |
| 67 |
resetAllFilter={resetAllFilter} |
| 68 |
isShownByDefault={isShownByDefault} |
| 69 |
isSingleColumn={isSingleColumn} |
| 70 |
panelId={panelId} |
| 71 |
> |
| 72 |
<FontSizePicker |
| 73 |
__next40pxDefaultSize |
| 74 |
withReset={false} |
| 75 |
fontSizes={sizes} |
| 76 |
disableCustomFontSizes={customFontSize === false} |
| 77 |
value={toPickerValue(value, sizes)} |
| 78 |
onChange={(newSize, selected) => |
| 79 |
onChange(fromPickerValue(newSize, selected)) |
| 80 |
} |
| 81 |
/> |
| 82 |
</TypographyPanelItem> |
| 83 |
); |
| 84 |
} |
| 85 |
|