Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backport-changelog/6.9/10190.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
https://github.com/WordPress/wordpress-develop/pull/10190

* https://github.com/WordPress/gutenberg/pull/71904
4 changes: 2 additions & 2 deletions docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ Introduce new sections and organize content to help visitors (and search engines

- **Name:** core/heading
- **Category:** text
- **Supports:** __unstablePasteTextInline, align (full, wide), anchor, className, color (background, gradients, link, text), interactivity (clientNavigation), spacing (margin, padding), splitting, typography (fontSize, lineHeight)
- **Supports:** __unstablePasteTextInline, align (full, wide), anchor, className, color (background, gradients, link, text), interactivity (clientNavigation), spacing (margin, padding), splitting, typography (fitText, fontSize, lineHeight)
- **Attributes:** content, level, levelOptions, placeholder, textAlign

## Home Link
Expand Down Expand Up @@ -581,7 +581,7 @@ Start with the basic building block of all narrative. ([Source](https://github.c

- **Name:** core/paragraph
- **Category:** text
- **Supports:** __unstablePasteTextInline, anchor, color (background, gradients, link, text), interactivity (clientNavigation), spacing (margin, padding), splitting, typography (fontSize, lineHeight), ~~className~~
- **Supports:** __unstablePasteTextInline, anchor, color (background, gradients, link, text), interactivity (clientNavigation), spacing (margin, padding), splitting, typography (fitText, fontSize, lineHeight), ~~className~~
- **Attributes:** align, content, direction, dropCap, placeholder

## Pattern Placeholder
Expand Down
4 changes: 4 additions & 0 deletions lib/block-supports/typography.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ function gutenberg_typography_get_preset_inline_style_value( $style_value, $css_
* @return string Filtered block content.
*/
function gutenberg_render_typography_support( $block_content, $block ) {
if ( ! empty( $block['attrs']['fitText'] ) ) {
wp_enqueue_script_module( '@wordpress/block-editor/utils/fit-text-frontend' );
}

if ( ! isset( $block['attrs']['style']['typography']['fontSize'] ) ) {
return $block_content;
}
Expand Down
3 changes: 3 additions & 0 deletions packages/block-editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
"module": "build-module/index.js",
"react-native": "src/index",
"wpScript": true,
"wpScriptModuleExports": {
"./utils/fit-text-frontend": "./build-module/utils/fit-text-frontend.js"
},
"sideEffects": [
"build-style/**",
"src/**/*.scss",
Expand Down
268 changes: 268 additions & 0 deletions packages/block-editor/src/hooks/fit-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,268 @@
/**
* WordPress dependencies
*/
import { addFilter } from '@wordpress/hooks';
import { hasBlockSupport } from '@wordpress/blocks';
import { useEffect, useCallback } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import {
ToggleControl,
__experimentalToolsPanelItem as ToolsPanelItem,
} from '@wordpress/components';

/**
* Internal dependencies
*/
import { optimizeFitText } from '../utils/fit-text-utils';
import { store as blockEditorStore } from '../store';
import { useBlockElement } from '../components/block-list/use-block-props/use-block-refs';
import InspectorControls from '../components/inspector-controls';

export const FIT_TEXT_SUPPORT_KEY = 'typography.fitText';

/**
* Filters registered block settings, extending attributes to include
* the `fitText` attribute.
*
* @param {Object} settings Original block settings.
* @return {Object} Filtered block settings.
*/
function addAttributes( settings ) {
if ( ! hasBlockSupport( settings, FIT_TEXT_SUPPORT_KEY ) ) {
return settings;
}

// Allow blocks to specify their own attribute definition.
if ( settings.attributes?.fitText ) {
return settings;
}

// Add fitText attribute.
return {
...settings,
attributes: {
...settings.attributes,
fitText: {
type: 'boolean',
},
},
};
}

/**
* Custom hook to handle fit text functionality in the editor.
*
* @param {Object} props Component props.
* @param {?boolean} props.fitText Fit text attribute.
* @param {string} props.name Block name.
* @param {string} props.clientId Block client ID.
*/
function useFitText( { fitText, name, clientId } ) {
const hasFitTextSupport = hasBlockSupport( name, FIT_TEXT_SUPPORT_KEY );
const blockElement = useBlockElement( clientId );

// Monitor block attribute changes
// Any attribute may change the available space.
const blockAttributes = useSelect(
( select ) => {
if ( ! clientId ) {
return;
}
return select( blockEditorStore ).getBlockAttributes( clientId );
},
[ clientId ]
);

const applyFitText = useCallback( () => {
if ( ! blockElement || ! hasFitTextSupport || ! fitText ) {
return;
}

// Get or create style element with unique ID
const styleId = `fit-text-${ clientId }`;
let styleElement = blockElement.ownerDocument.getElementById( styleId );
if ( ! styleElement ) {
styleElement = blockElement.ownerDocument.createElement( 'style' );
styleElement.id = styleId;
blockElement.ownerDocument.head.appendChild( styleElement );
}

const blockSelector = `#block-${ clientId }`;

const applyStylesFn = ( css ) => {
styleElement.textContent = css;
};

optimizeFitText( blockElement, blockSelector, applyStylesFn );
}, [ blockElement, clientId, hasFitTextSupport, fitText ] );

useEffect( () => {
if (
! fitText ||
! blockElement ||
! clientId ||
! hasFitTextSupport
) {
return;
}

// Apply initially
applyFitText();

// Store current element value for cleanup
const currentElement = blockElement;

// Watch for size changes
let resizeObserver;
if ( window.ResizeObserver && currentElement.parentElement ) {
resizeObserver = new window.ResizeObserver( applyFitText );
resizeObserver.observe( currentElement.parentElement );
}

// Cleanup function
return () => {
if ( resizeObserver ) {
resizeObserver.disconnect();
}

const styleId = `fit-text-${ clientId }`;
const styleElement =
currentElement.ownerDocument.getElementById( styleId );
if ( styleElement ) {
styleElement.remove();
}
};
}, [ fitText, clientId, applyFitText, blockElement, hasFitTextSupport ] );

// Trigger fit text recalculation when content changes
useEffect( () => {
if ( fitText && blockElement && hasFitTextSupport ) {
// Small delay to ensure DOM has updated after content changes
const timer = setTimeout( () => {
if ( blockElement ) {
applyFitText();
}
}, 1000 );

return () => clearTimeout( timer );
}
}, [
blockAttributes,
fitText,
applyFitText,
blockElement,
hasFitTextSupport,
] );
}

/**
* Fit text control component for the typography panel.
*
* @param {Object} props Component props.
* @param {string} props.clientId Block client ID.
* @param {Function} props.setAttributes Function to set block attributes.
* @param {string} props.name Block name.
* @param {boolean} props.fitText Whether fit text is enabled.
*/
export function FitTextControl( {
clientId,
fitText = false,
setAttributes,
name,
} ) {
if ( ! hasBlockSupport( name, FIT_TEXT_SUPPORT_KEY ) ) {
return null;
}
return (
<InspectorControls group="typography">
<ToolsPanelItem
hasValue={ () => fitText }
label={ __( 'Fit text' ) }
onDeselect={ () => setAttributes( { fitText: undefined } ) }
resetAllFilter={ () => ( { fitText: undefined } ) }
panelId={ clientId }
>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Fit text' ) }
checked={ fitText }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
checked={ fitText }
checked={ !! fitText }

This can be undefined and causes the error @scruffian mentioned.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I wrongly assumed there was a default value set up.

onChange={ () =>
setAttributes( { fitText: ! fitText || undefined } )
}
help={
fitText
? __( 'Text will resize to fit its container.' )
: __( 'Resize text to fit its container.' )
}
/>
</ToolsPanelItem>
</InspectorControls>
);
}

/**
* Override props applied to the block element on save.
*
* @param {Object} props Additional props applied to the block element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
* @return {Object} Filtered props applied to the block element.
*/
function addSaveProps( props, blockType, attributes ) {
if ( ! hasBlockSupport( blockType, FIT_TEXT_SUPPORT_KEY ) ) {
return props;
}

const { fitText } = attributes;

if ( ! fitText ) {
return props;
}

// Add CSS class for frontend detection and styling
const className = props.className
? `${ props.className } has-fit-text`
: 'has-fit-text';

return {
...props,
className,
};
}
/**
* Override props applied to the block element in the editor.
*
* @param {Object} props Component props including block attributes.
* @param {string} props.name Block name.
* @param {boolean} props.fitText Whether fit text is enabled.
* @param {string} props.clientId Block client ID.
* @return {Object} Filtered props applied to the block element.
*/
function useBlockProps( { name, fitText, clientId } ) {
useFitText( { fitText, name, clientId } );
if ( ! fitText || ! hasBlockSupport( name, FIT_TEXT_SUPPORT_KEY ) ) {
return {};
}
return {
className: 'has-fit-text',
};
}

addFilter(
'blocks.registerBlockType',
'core/fit-text/addAttribute',
addAttributes
);

const hasFitTextSupport = ( blockNameOrType ) => {
return hasBlockSupport( blockNameOrType, FIT_TEXT_SUPPORT_KEY );
};

export default {
useBlockProps,
addSaveProps,
attributeKeys: [ 'fitText' ],
hasSupport: hasFitTextSupport,
edit: FitTextControl,
};
4 changes: 4 additions & 0 deletions packages/block-editor/src/hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import duotone from './duotone';
import fontFamily from './font-family';
import fontSize from './font-size';
import textAlign from './text-align';
import fitText from './fit-text';
import border from './border';
import position from './position';
import blockStyleVariation from './block-style-variation';
Expand All @@ -42,6 +43,7 @@ createBlockEditFilter(
customClassName,
style,
duotone,
fitText,
position,
layout,
contentLockUI,
Expand All @@ -60,6 +62,7 @@ createBlockListBlockFilter( [
duotone,
fontFamily,
fontSize,
fitText,
border,
position,
blockStyleVariation,
Expand All @@ -72,6 +75,7 @@ createBlockSaveFilter( [
ariaLabel,
customClassName,
border,
fitText,
color,
style,
fontFamily,
Expand Down
2 changes: 2 additions & 0 deletions packages/block-editor/src/hooks/typography.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { LINE_HEIGHT_SUPPORT_KEY } from './line-height';
import { FONT_FAMILY_SUPPORT_KEY } from './font-family';
import { FONT_SIZE_SUPPORT_KEY } from './font-size';
import { TEXT_ALIGN_SUPPORT_KEY } from './text-align';
import { FIT_TEXT_SUPPORT_KEY } from './fit-text';
import { cleanEmptyObject } from './utils';
import { store as blockEditorStore } from '../store';

Expand Down Expand Up @@ -47,6 +48,7 @@ export const TYPOGRAPHY_SUPPORT_KEYS = [
WRITING_MODE_SUPPORT_KEY,
TEXT_TRANSFORM_SUPPORT_KEY,
LETTER_SPACING_SUPPORT_KEY,
FIT_TEXT_SUPPORT_KEY,
];

function styleToAttributes( style ) {
Expand Down
Loading