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

Extract a BorderPanel component as a reusable component between Global Styles and Block Inspector #48636

Merged
merged 4 commits into from
Mar 2, 2023
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
285 changes: 285 additions & 0 deletions packages/block-editor/src/components/global-styles/border-panel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
/**
* WordPress dependencies
*/
import {
__experimentalBorderBoxControl as BorderBoxControl,
__experimentalHasSplitBorders as hasSplitBorders,
__experimentalIsDefinedBorder as isDefinedBorder,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
} from '@wordpress/components';
import { useCallback, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import BorderRadiusControl from '../border-radius-control';
import { useColorsPerOrigin } from './hooks';
import { getValueFromVariable } from './utils';

export function useHasBorderPanel( settings ) {
const controls = [
useHasBorderColorControl( settings ),
useHasBorderRadiusControl( settings ),
useHasBorderStyleControl( settings ),
useHasBorderWidthControl( settings ),
];

return controls.some( Boolean );
}

function useHasBorderColorControl( settings ) {
return settings?.border?.color;
}

function useHasBorderRadiusControl( settings ) {
return settings?.border?.radius;
}

function useHasBorderStyleControl( settings ) {
return settings?.border?.style;
}

function useHasBorderWidthControl( settings ) {
return settings?.border?.width;
}

function applyFallbackStyle( border ) {
if ( ! border ) {
return border;
}

if ( ! border.style && ( border.color || border.width ) ) {
return { ...border, style: 'solid' };
}

return border;
}

function applyAllFallbackStyles( border ) {
if ( ! border ) {
return border;
}

if ( hasSplitBorders( border ) ) {
return {
top: applyFallbackStyle( border.top ),
right: applyFallbackStyle( border.right ),
bottom: applyFallbackStyle( border.bottom ),
left: applyFallbackStyle( border.left ),
};
}

return applyFallbackStyle( border );
}

function BorderToolsPanel( {
resetAllFilter,
onChange,
value,
panelId,
children,
} ) {
const resetAll = () => {
const updatedValue = resetAllFilter( value );
onChange( updatedValue );
};

return (
<ToolsPanel
label={ __( 'Border' ) }
resetAll={ resetAll }
panelId={ panelId }
>
{ children }
</ToolsPanel>
);
}

const DEFAULT_CONTROLS = {
radius: true,
color: true,
width: true,
};

export default function BorderPanel( {
as: Wrapper = BorderToolsPanel,
value,
onChange,
inheritedValue = value,
settings,
panelId,
defaultControls = DEFAULT_CONTROLS,
} ) {
const colors = useColorsPerOrigin( settings );
const decodeValue = ( rawValue ) =>
getValueFromVariable( { settings }, '', rawValue );
const encodeColorValue = ( colorValue ) => {
const allColors = colors.flatMap(
( { colors: originColors } ) => originColors
);
const colorObject = allColors.find(
( { color } ) => color === colorValue
);
return colorObject
? 'var:preset|color|' + colorObject.slug
: colorValue;
};
const decodeColorValue = useCallback(
( colorValue ) => {
const allColors = colors.flatMap(
( { colors: originColors } ) => originColors
);
const colorObject = allColors.find(
( { slug } ) => colorValue === 'var:preset|color|' + slug
);
return colorObject ? colorObject.color : colorValue;
},
[ colors ]
);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note that I have to encode/decode colors every time in this component. Personally, I think that shouldn't happen in this component but instead it should be built-in in the lower level components BorderBoxControl... until ColorPalette because they all receive the "colors" presets as argument.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Basically right now, if a user picks a "red" color from a palette, or picks a "red" color with the same value as a custom color, they are considered the same and automatically switched to "palette" colors. The problem is that the user intention might be different.

  • If I pick a palette color, I expect the value to update as I update the palettes
  • If I pick a custom color, I expect the value to be static.

This behavior is broken now and the value is always dynamic but this is how it works in trunk too, so I kept it as is.

const border = useMemo( () => {
if ( hasSplitBorders( inheritedValue?.border ) ) {
const borderValue = { ...inheritedValue?.border };
[ 'top', 'right', 'bottom', 'left' ].forEach( ( side ) => {
borderValue[ side ] = {
...borderValue[ side ],
color: decodeColorValue( borderValue[ side ]?.color ),
};
} );
return borderValue;
}
return {
...inheritedValue?.border,
color: inheritedValue?.border?.color
? decodeColorValue( inheritedValue?.border?.color )
: undefined,
};
}, [ inheritedValue?.border, decodeColorValue ] );
const setBorder = ( newBorder ) =>
onChange( { ...value, border: newBorder } );
const showBorderColor = useHasBorderColorControl( settings );
const showBorderStyle = useHasBorderStyleControl( settings );
const showBorderWidth = useHasBorderWidthControl( settings );

// Border radius.
const showBorderRadius = useHasBorderRadiusControl( settings );
const borderRadiusValues = decodeValue( border?.radius );
const setBorderRadius = ( newBorderRadius ) =>
setBorder( { ...border, radius: newBorderRadius } );
const hasBorderRadius = () => {
const borderValues = value?.border?.radius;
if ( typeof borderValues === 'object' ) {
return Object.entries( borderValues ).some( Boolean );
}
return !! borderValues;
};

const resetBorder = () => {
if ( hasBorderRadius() ) {
return setBorder( { radius: value?.border?.radius } );
}

setBorder( undefined );
};

const onBorderChange = ( newBorder ) => {
// Ensure we have a visible border style when a border width or
// color is being selected.
const newBorderWithStyle = applyAllFallbackStyles( newBorder );

// As we can't conditionally generate styles based on if other
// style properties have been set we need to force split border
// definitions for user set border styles. Border radius is derived
// from the same property i.e. `border.radius` if it is a string
// that is used. The longhand border radii styles are only generated
// if that property is an object.
//
// For borders (color, style, and width) those are all properties on
// the `border` style property. This means if the theme.json defined
// split borders and the user condenses them into a flat border or
// vice-versa we'd get both sets of styles which would conflict.
const updatedBorder = ! hasSplitBorders( newBorderWithStyle )
? {
top: newBorderWithStyle,
right: newBorderWithStyle,
bottom: newBorderWithStyle,
left: newBorderWithStyle,
}
: {
color: null,
style: null,
width: null,
...newBorderWithStyle,
};

[ 'top', 'right', 'bottom', 'left' ].forEach( ( side ) => {
updatedBorder[ side ] = {
...updatedBorder[ side ],
color: encodeColorValue( updatedBorder[ side ]?.color ),
};
} );

// As radius is maintained separately to color, style, and width
// maintain its value. Undefined values here will be cleaned when
// global styles are saved.
setBorder( { radius: border?.radius, ...updatedBorder } );
};

const resetAllFilter = useCallback( ( previousValue ) => {
return {
...previousValue,
border: undefined,
};
}, [] );

const showBorderByDefault =
defaultControls?.color || defaultControls?.width;

return (
<Wrapper
resetAllFilter={ resetAllFilter }
value={ value }
onChange={ onChange }
panelId={ panelId }
>
{ ( showBorderWidth || showBorderColor ) && (
<ToolsPanelItem
hasValue={ () => isDefinedBorder( value?.border ) }
label={ __( 'Border' ) }
onDeselect={ () => resetBorder() }
isShownByDefault={ showBorderByDefault }
panelId={ panelId }
>
<BorderBoxControl
colors={ colors }
enableAlpha={ true }
enableStyle={ showBorderStyle }
onChange={ onBorderChange }
popoverOffset={ 40 }
popoverPlacement="left-start"
value={ border }
__experimentalIsRenderedInSidebar={ true }
size={ '__unstable-large' }
/>
</ToolsPanelItem>
) }
{ showBorderRadius && (
<ToolsPanelItem
hasValue={ hasBorderRadius }
label={ __( 'Radius' ) }
onDeselect={ () => setBorderRadius( undefined ) }
isShownByDefault={ defaultControls.radius }
panelId={ panelId }
>
<BorderRadiusControl
values={ borderRadiusValues }
onChange={ ( newValue ) => {
setBorderRadius( newValue || undefined );
} }
/>
</ToolsPanelItem>
) }
</Wrapper>
);
}
62 changes: 62 additions & 0 deletions packages/block-editor/src/components/global-styles/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { get, set } from 'lodash';
import { useContext, useCallback, useMemo } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { store as blocksStore } from '@wordpress/blocks';
import { _x } from '@wordpress/i18n';

/**
* Internal dependencies
Expand Down Expand Up @@ -303,6 +304,67 @@ export function useSettingsForBlockElement(
};
}

[ 'radius', 'color', 'style', 'width' ].forEach( ( key ) => {
if (
! supportedStyles.includes(
'border' + key.charAt( 0 ).toUpperCase() + key.slice( 1 )
)
) {
updatedSettings.border = {
...updatedSettings.border,
[ key ]: false,
};
}
} );

return updatedSettings;
}, [ parentSettings, supportedStyles, supports ] );
}

export function useColorsPerOrigin( settings ) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This hook already exists but it's dependent on useSetting. I updated it here to have one that is independent of any context... Hopefully by the time we finish these refactors, we should be able to remove the other one.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually I managed to use this in the other one to avoid duplication.

const customColors = settings?.color?.palette?.custom;
const themeColors = settings?.color?.palette?.theme;
const defaultColors = settings?.color?.palette?.default;
const shouldDisplayDefaultColors = settings?.color?.defaultPalette;

return useMemo( () => {
const result = [];
if ( themeColors && themeColors.length ) {
result.push( {
name: _x(
'Theme',
'Indicates this palette comes from the theme.'
),
colors: themeColors,
} );
}
if (
shouldDisplayDefaultColors &&
defaultColors &&
defaultColors.length
) {
result.push( {
name: _x(
'Default',
'Indicates this palette comes from WordPress.'
),
colors: defaultColors,
} );
}
if ( customColors && customColors.length ) {
result.push( {
name: _x(
'Custom',
'Indicates this palette is created by the user.'
),
colors: customColors,
} );
}
return result;
}, [
customColors,
themeColors,
defaultColors,
shouldDisplayDefaultColors,
] );
}
2 changes: 2 additions & 0 deletions packages/block-editor/src/components/global-styles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {
useGlobalSetting,
useGlobalStyle,
useSettingsForBlockElement,
useColorsPerOrigin,
} from './hooks';
export { useGlobalStylesOutput } from './use-global-styles-output';
export { GlobalStylesContext } from './context';
Expand All @@ -14,3 +15,4 @@ export {
default as DimensionsPanel,
useHasDimensionsPanel,
} from './dimensions-panel';
export { default as BorderPanel, useHasBorderPanel } from './border-panel';
Loading