Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Font size presets UI #63057

Open
wants to merge 18 commits into
base: trunk
Choose a base branch
from
Open
Prev Previous commit
Next Next commit
removes font size custom ordering
  • Loading branch information
matiasbenedetto committed Jul 1, 2024
commit a8cc36b0f54ba58c3a11fb6bdff25f640117d9d9
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';
import { __, sprintf } from '@wordpress/i18n';
import {
__experimentalParseQuantityAndUnitFromRawValue as parseQuantityAndUnitFromRawValue,
__experimentalItemGroup as ItemGroup,
__experimentalVStack as VStack,
__experimentalHStack as HStack,
Expand All @@ -22,49 +21,13 @@ import Subtitle from '../subtitle';
import { NavigationButtonAsItem } from '../navigation-button';
import { getNewIndexFromPresets } from '../utils';

/**
* Coefficients to normalize font sizes to pixels.
*
* em/rm on units are bases the default font size of 16px.
* Viewport units are based on a 1920x1080 screen.
*/
const NORMALIZED_FONT_SIZE_COEFFICIENT = {
px: 1,
em: 16,
rem: 16,
vw: 19.2,
vh: 10.8,
};

/*
* Normalize a font size value to a specific unit.
*
* @param {string} size The font size value to normalize.
* @return {string} The normalized font size value.
*/
function normalizeFontSize( size ) {
const [ quantity, unit ] = parseQuantityAndUnitFromRawValue( size );
const normalizedSize =
quantity * ( NORMALIZED_FONT_SIZE_COEFFICIENT[ unit ] ?? 1 );
if ( isNaN( normalizedSize ) || isNaN( quantity ) ) {
return 1;
}
return normalizedSize;
}

function FontSizes() {
const [ fontSizes, setFontSizes ] = useGlobalSetting(
'typography.fontSizes'
);

// Get the font sizes from the theme or use the default ones.
const sizes = fontSizes.theme ?? fontSizes.default ?? [];
const normalizedSizes = sizes
.map( ( fontSize ) => ( {
...fontSize,
normalizedSize: normalizeFontSize( fontSize.size ),
} ) )
.sort( ( a, b ) => a.normalizedSize - b.normalizedSize );

const handleAddFontSize = () => {
const index = getNewIndexFromPresets( sizes, 'custom-' );
Expand All @@ -90,7 +53,7 @@ function FontSizes() {
/>
</HStack>
<ItemGroup isBordered isSeparated>
{ normalizedSizes.map( ( size ) => (
{ sizes.map( ( size ) => (
<NavigationButtonAsItem
key={ size.slug }
path={ '/typography/font-sizes/' + size.slug }
Expand Down
Loading