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

Block Editor: Add useEditorFeature hook to simplify access to editor features #21646

Merged
merged 2 commits into from
Apr 24, 2020
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
14 changes: 14 additions & 0 deletions lib/compat.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ function register_block_type_from_metadata( $path, $args = array() ) {
}
}

/**
* Extends block editor settings to determine whether to use drop cap feature.
*
* @param array $settings Default editor settings.
*
* @return array Filtered editor settings.
*/
function gutenberg_extend_settings_drop_cap( $settings ) {
$settings['__experimentalDisableDropCap'] = false;
return $settings;
}
add_filter( 'block_editor_settings', 'gutenberg_extend_settings_drop_cap' );


/**
* Extends block editor settings to include a list of image dimensions per size.
*
Expand Down
1 change: 1 addition & 0 deletions packages/block-editor/src/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,4 @@ export { default as WritingFlow } from './writing-flow';

export { default as BlockEditorProvider } from './provider';
export { default as useSimulatedMediaQuery } from './use-simulated-media-query';
export { default as __experimentalUseEditorFeature } from './use-editor-feature';
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ import { ZERO } from '@wordpress/keycodes';
/**
* Internal dependencies
*/
import useEditorFeature from '../use-editor-feature';
import {
BASE_DEFAULT_VALUE,
RESET_VALUE,
STEP,
useIsLineHeightControlsDisabled,
isLineHeightDefined,
} from './utils';

export default function LineHeightControl( { value: lineHeight, onChange } ) {
// Don't render the controls if disabled by editor settings
const isDisabled = useIsLineHeightControlsDisabled();
const isDisabled = useEditorFeature(
'__experimentalDisableCustomLineHeight'
);
Copy link
Contributor

Choose a reason for hiding this comment

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

I like the API a lot, and the fact that we can implement any heuristics to get the value of that config in the hook without changing how the API is used.

I'm not sure yet about the naming. useEditorFeature, useEditorSetting, useEditorConfig ? How will it scale to nested configs like typography, colors? Why is __experimentalDisableCustomLineHeight a top level config and not nested under "typography" (same for drop cap).

cc @mtias @aduth @mcsf and others.

Copy link

Choose a reason for hiding this comment

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

I like the API a lot, and the fact that we can implement any heuristics to get the value of that config in the hook without changing how the API is used.

🤘

Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure yet about the naming. useEditorFeature, useEditorSetting, useEditorConfig ?

If the thing we're referring to here is the same thing we assign via <Editor settings={ ... } />, or block_editor_settings filter, I'd very much like to see "setting" or "settings" as part of the name.

How will it scale to nested configs like typography, colors? Why is __experimentalDisableCustomLineHeight a top level config and not nested under "typography" (same for drop cap).

Do we have nested settings? Can we not? 😛

Copy link
Member Author

Choose a reason for hiding this comment

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

If we fly with useSetting then we need those nested groups to make it all easier. We discussed groups like typography, colors so far. I'm sure we need more. The only question is whether we name it feature, setting, support or whatever :)

Copy link
Contributor

Choose a reason for hiding this comment

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

for context, this hook is supposed to get its values from the "config" property in the proposed format in the end. #21583 (comment)

This config is probably going to end up in the block-editor getSettings selector somehow, I haven't give it much though yet about how, whether it's just 1 - 1 or if there's some intermediate mapping that happens.

I don't think the block-editor settings and the "config" of a block-editor are the exact same things, block-editor can have more settings and themes can have more "config" though.

Copy link
Member Author

@gziolo gziolo Apr 17, 2020

Choose a reason for hiding this comment

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

It feels like all we need is proper namespacing to make it easy to inject all settings from the theme.json config. Wherever we have duplication, we can find a nice way to migrate it behind the scenes before sending it to the front.

To give an example, the following would still work on PHP side:

$settings = array(
    'disableCustomColors'    => get_theme_support( 'disable-custom-colors' ),
    'disableCustomFontSizes' => get_theme_support( 'disable-custom-font-sizes' ),		
);

You could also override it with theme.json:

{ 
    "config": {
        "colors": {
            "disableCustomColors": false
        },
        "typography": {
            "disableCustomFontSizes": false
        }
    }
}

The challenge would be to pick what takes precedence, theme.json or get_theme_support here, or the top-level disableCustomFontSizes vs typography. disableCustomFontSizes. Before sending it to the client, we would remove duplicates from the top-level using some conflict resolution strategy.

On the client, we need to keep old settings for backward compatibility but I would solve it by doing internal mapping in the getSettings selector:

const mappings = {
    disableCustomColors: 'colors.disableCustomColors',
    disableCustomFontSizes: 'typography.disableCustomFontSizes',
};

I hope I didn't miss anything.

if ( isDisabled ) {
return null;
}
Expand Down
20 changes: 0 additions & 20 deletions packages/block-editor/src/components/line-height-control/utils.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';

export const BASE_DEFAULT_VALUE = 1.5;
export const STEP = 0.1;
/**
Expand All @@ -17,21 +12,6 @@ export const STEP = 0.1;
*/
export const RESET_VALUE = '';

/**
* Retrieves whether custom lineHeight controls should be disabled from editor settings.
*
* @return {boolean} Whether lineHeight controls should be disabled.
*/
export function useIsLineHeightControlsDisabled() {
const isDisabled = useSelect( ( select ) => {
const { getSettings } = select( 'core/block-editor' );

return !! getSettings().__experimentalDisableCustomLineHeight;
}, [] );

return isDisabled;
}

/**
* Determines if the lineHeight attribute has been properly defined.
*
Expand Down
20 changes: 6 additions & 14 deletions packages/block-editor/src/components/unit-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@
* WordPress dependencies
*/
import { __experimentalUnitControl as BaseUnitControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';

/**
* Internal dependencies
*/
import useEditorFeature from '../use-editor-feature';

const { __defaultUnits } = BaseUnitControl;

export default function UnitControl( { units: unitsProp, ...props } ) {
const settings = useCustomUnitsSettings();
const settings = useEditorFeature( '__experimentalDisableCustomUnits' );
const isDisabled = !! settings;

// Adjust units based on add_theme_support( 'experimental-custom-units' );
Expand All @@ -34,18 +38,6 @@ export default function UnitControl( { units: unitsProp, ...props } ) {
// Hoisting statics from the BaseUnitControl
UnitControl.__defaultUnits = __defaultUnits;

/**
* Hook that retrieves the 'experimental-custom-units' setting from add_theme_support()
*/
function useCustomUnitsSettings() {
const settings = useSelect( ( select ) => {
const { getSettings } = select( 'core/block-editor' );
return getSettings().__experimentalDisableCustomUnits;
}, [] );

return settings;
}

/**
* Filters available units based on values defined by settings.
*
Expand Down
24 changes: 24 additions & 0 deletions packages/block-editor/src/components/use-editor-feature/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';

/**
* Hook that retrieves the setting for the given editor feature.
*
* @param {string} featureName The name of the feature.
*
* @return {any} Returns the value defined for the setting.
*/
export default function useEditorFeature( featureName ) {
const setting = useSelect(
( select ) => {
const { getSettings } = select( 'core/block-editor' );

return getSettings()[ featureName ];
},
[ featureName ]
);

return setting;
}
70 changes: 46 additions & 24 deletions packages/block-library/src/paragraph/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
RichText,
__experimentalBlock as Block,
getFontSize,
__experimentalUseEditorFeature as useEditorFeature,
} from '@wordpress/block-editor';
import { createBlock } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
Expand Down Expand Up @@ -55,9 +56,21 @@ function ParagraphRTLToolbar( { direction, setDirection } ) {
);
}

function useDropCapMinimumHeight( isDropCap, deps ) {
function useDropCap( isDropCap, fontSize, styleFontSize ) {
const isDisabled = useEditorFeature( '__experimentalDisableDropCap' );

const [ minimumHeight, setMinimumHeight ] = useState();

const { fontSizes } = useSelect( ( select ) =>
select( 'core/block-editor' ).getSettings()
);

const fontSizeObject = getFontSize( fontSizes, fontSize, styleFontSize );
useEffect( () => {
if ( isDisabled ) {
return;
}

const element = querySelector( PARAGRAPH_DROP_CAP_SELECTOR );
if ( isDropCap && element ) {
setMinimumHeight(
Expand All @@ -66,8 +79,15 @@ function useDropCapMinimumHeight( isDropCap, deps ) {
} else if ( minimumHeight ) {
setMinimumHeight( undefined );
}
}, [ isDropCap, minimumHeight, setMinimumHeight, ...deps ] );
return minimumHeight;
}, [
isDisabled,
isDropCap,
minimumHeight,
setMinimumHeight,
fontSizeObject.size,
] );

return [ ! isDisabled, minimumHeight ];
}

function ParagraphBlock( {
Expand All @@ -85,14 +105,12 @@ function ParagraphBlock( {
fontSize,
style,
} = attributes;
const { fontSizes } = useSelect( ( select ) =>
select( 'core/block-editor' ).getSettings()
);
const ref = useRef();
const fontSizeObject = getFontSize( fontSizes, fontSize, style?.fontSize );
const dropCapMinimumHeight = useDropCapMinimumHeight( dropCap, [
fontSizeObject.size,
] );
const [ isDropCapEnabled, dropCapMinimumHeight ] = useDropCap(
dropCap,
fontSize,
style?.fontSize
);

const styles = {
direction,
Expand All @@ -116,20 +134,24 @@ function ParagraphBlock( {
/>
</BlockControls>
<InspectorControls>
<PanelBody title={ __( 'Text settings' ) }>
<ToggleControl
label={ __( 'Drop cap' ) }
checked={ !! dropCap }
onChange={ () =>
setAttributes( { dropCap: ! dropCap } )
}
help={
dropCap
? __( 'Showing large initial letter.' )
: __( 'Toggle to show a large initial letter.' )
}
/>
</PanelBody>
{ isDropCapEnabled && (
<PanelBody title={ __( 'Text settings' ) }>
<ToggleControl
label={ __( 'Drop cap' ) }
checked={ !! dropCap }
onChange={ () =>
setAttributes( { dropCap: ! dropCap } )
}
help={
dropCap
? __( 'Showing large initial letter.' )
: __(
'Toggle to show a large initial letter.'
)
}
/>
</PanelBody>
) }
</InspectorControls>
<RichText
ref={ ref }
Expand Down
25 changes: 13 additions & 12 deletions packages/editor/src/components/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,19 @@ class EditorProvider extends Component {
) {
return {
...pick( settings, [
'__experimentalBlockDirectory',
'__experimentalBlockPatterns',
'__experimentalDisableCustomUnits',
'__experimentalDisableCustomLineHeight',
'__experimentalDisableDropCap',
'__experimentalEnableLegacyWidgetBlock',
'__experimentalEnableFullSiteEditing',
'__experimentalEnableFullSiteEditingDemo',
'__experimentalGlobalStylesUserEntityId',
'__experimentalGlobalStylesBase',
'__experimentalPreferredStyleVariations',
'alignWide',
'allowedBlockTypes',
'__experimentalPreferredStyleVariations',
'availableLegacyWidgets',
'bodyPlaceholder',
'codeEditingEnabled',
Expand All @@ -111,27 +121,18 @@ class EditorProvider extends Component {
'disableCustomGradients',
'focusMode',
'fontSizes',
'gradients',
'hasFixedToolbar',
'hasPermissionsToManageWidgets',
'imageSizes',
'imageDimensions',
'isRTL',
'maxWidth',
'onUpdateDefaultBlockStyles',
'styles',
'template',
'templateLock',
'titlePlaceholder',
'onUpdateDefaultBlockStyles',
'__experimentalDisableCustomUnits',
'__experimentalEnableLegacyWidgetBlock',
'__experimentalBlockDirectory',
'__experimentalEnableFullSiteEditing',
'__experimentalEnableFullSiteEditingDemo',
'__experimentalGlobalStylesUserEntityId',
'__experimentalGlobalStylesBase',
'__experimentalDisableCustomLineHeight',
'__experimentalBlockPatterns',
'gradients',
] ),
mediaUpload: hasUploadPermissions ? mediaUpload : undefined,
__experimentalReusableBlocks: reusableBlocks,
Expand Down