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

Try: deal with duplicate color slugs #65597

Closed
wants to merge 4 commits into from
Closed
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
18 changes: 11 additions & 7 deletions packages/block-editor/src/components/global-styles/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import { _x } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { getValueFromVariable, getPresetVariableFromValue } from './utils';
import {
getUniqueByProperty,
getValueFromVariable,
getPresetVariableFromValue,
} from './utils';
import { getValueFromObjectPath, setImmutably } from '../../utils/object';
import { GlobalStylesContext } from './context';
import { unlock } from '../../lock-unlock';
Expand Down Expand Up @@ -408,7 +412,7 @@ export function useColorsPerOrigin( settings ) {
'Theme',
'Indicates this palette comes from the theme.'
),
colors: themeColors,
colors: getUniqueByProperty( themeColors, 'slug' ),
} );
}
if (
Expand All @@ -421,7 +425,7 @@ export function useColorsPerOrigin( settings ) {
'Default',
'Indicates this palette comes from WordPress.'
),
colors: defaultColors,
colors: getUniqueByProperty( defaultColors, 'slug' ),
} );
}
if ( customColors && customColors.length ) {
Expand All @@ -430,7 +434,7 @@ export function useColorsPerOrigin( settings ) {
'Custom',
'Indicates this palette is created by the user.'
),
colors: customColors,
colors: getUniqueByProperty( customColors, 'slug' ),
} );
}
return result;
Expand All @@ -456,7 +460,7 @@ export function useGradientsPerOrigin( settings ) {
'Theme',
'Indicates this palette comes from the theme.'
),
gradients: themeGradients,
gradients: getUniqueByProperty( themeGradients, 'slug' ),
} );
}
if (
Expand All @@ -469,7 +473,7 @@ export function useGradientsPerOrigin( settings ) {
'Default',
'Indicates this palette comes from WordPress.'
),
gradients: defaultGradients,
gradients: getUniqueByProperty( defaultGradients, 'slug' ),
} );
}
if ( customGradients && customGradients.length ) {
Expand All @@ -478,7 +482,7 @@ export function useGradientsPerOrigin( settings ) {
'Custom',
'Indicates this palette is created by the user.'
),
gradients: customGradients,
gradients: getUniqueByProperty( customGradients, 'slug' ),
} );
}
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,39 +63,43 @@ const { kebabCase } = unlock( componentsPrivateApis );
* @return {Array<Object>} An array of style declarations.
*/
function getPresetsDeclarations( blockPresets = {}, mergedSettings ) {
return PRESET_METADATA.reduce(
( declarations, { path, valueKey, valueFunc, cssVarInfix } ) => {
const presetByOrigin = getValueFromObjectPath(
blockPresets,
path,
[]
);
[ 'default', 'theme', 'custom' ].forEach( ( origin ) => {
if ( presetByOrigin[ origin ] ) {
presetByOrigin[ origin ].forEach( ( value ) => {
if ( valueKey && ! valueFunc ) {
declarations.push(
`--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }: ${ value[ valueKey ] }`
);
} else if (
valueFunc &&
typeof valueFunc === 'function'
) {
declarations.push(
`--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }: ${ valueFunc( value, mergedSettings ) }`
);
}
} );
const declarationsMap = new Map();
for ( const {
path,
valueKey,
valueFunc,
cssVarInfix,
} of PRESET_METADATA ) {
const presetByOrigin = getValueFromObjectPath( blockPresets, path, [] );
for ( const origin of [ 'default', 'theme', 'custom' ] ) {
const presets = presetByOrigin[ origin ];
if ( ! presets ) {
continue;
}
for ( const value of presets ) {
const key = `--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }`;
let declarationValue;

if ( valueKey && ! valueFunc ) {
declarationValue = value[ valueKey ];
} else if ( typeof valueFunc === 'function' ) {
declarationValue = valueFunc( value, mergedSettings );
}
} );

return declarations;
},
[]
/*
* Overwrite any duplicates.
* See corresponding frontend method: WP_Theme_JSON_Gutenberg::get_settings_slugs.
*/
if ( declarationValue ) {
declarationsMap.set( key, declarationValue );
}
}
}
}
return Array.from(
declarationsMap,
( [ key, value ] ) => `${ key }: ${ value }`
);
}

Expand Down
16 changes: 16 additions & 0 deletions packages/block-editor/src/components/global-styles/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -613,3 +613,19 @@ export function getResolvedValue( ruleValue, tree ) {

return resolvedValue;
}

/**
* Returns a unique collection of objects by specific property,
* preferring the last occurrence of each property value..
*
* @param {Array<Object>} collection A collection of items.
* @param {string} property The property to use for uniqueness.
* @return {Array<Object>} The filtered collection.
*/
export function getUniqueByProperty( collection, property ) {
return Array.from(
new Map(
collection.map( ( item ) => [ item[ property ], item ] )
).values()
);
}
49 changes: 47 additions & 2 deletions packages/components/src/palette-edit/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,14 @@ import type {

const DEFAULT_COLOR = '#000';

function NameInput( { value, onChange, label }: NameInputProps ) {
function NameInput( { value, onChange, label, className }: NameInputProps ) {
return (
<NameInputControl
label={ label }
hideLabelFromVision
value={ value }
onChange={ onChange }
className={ className }
/>
);
}
Expand Down Expand Up @@ -196,6 +197,7 @@ function Option< T extends PaletteElement >( {
popoverProps: receivedPopoverProps,
slugPrefix,
isGradient,
isDuplicate,
}: OptionProps< T > ) {
const value = isGradient ? element.gradient : element.color;
const [ isEditingColor, setIsEditingColor ] = useState( false );
Expand Down Expand Up @@ -231,6 +233,10 @@ function Option< T extends PaletteElement >( {
<FlexItem>
{ ! canOnlyChangeValues ? (
<NameInput
className={ clsx(
'components-palette-edit__name-input',
{ 'is-duplicate': isDuplicate }
) }
label={
isGradient
? __( 'Gradient name' )
Expand Down Expand Up @@ -306,7 +312,13 @@ function PaletteEditListView< T extends PaletteElement >( {
onChange( deduplicateElementSlugs( updatedElements ) ),
100
);

const isDuplicate = useCallback(
( optionElement: PaletteElement ) =>
elements.filter(
( element ) => element.slug === optionElement.slug
).length > 1,
[ elements ]
);
return (
<VStack spacing={ 3 }>
<ItemGroup isRounded>
Expand All @@ -316,6 +328,7 @@ function PaletteEditListView< T extends PaletteElement >( {
canOnlyChangeValues={ canOnlyChangeValues }
key={ index }
element={ element }
isDuplicate={ isDuplicate( element ) }
onChange={ ( newElement ) => {
debounceOnChange(
elements.map(
Expand Down Expand Up @@ -387,6 +400,22 @@ export function PaletteEdit( {
}: PaletteEditProps ) {
const isGradient = !! gradients;
const elements = isGradient ? gradients : colors;
const duplicateSlugs = elements?.length
? elements.filter( ( element, index ) => {
const slug = element.slug;
return (
!! slug &&
elements.findIndex( ( otherElement, otherIndex ) => {
return (
otherIndex !== index &&
otherElement.slug === slug &&
otherElement.slug !== undefined
);
} ) !== -1
);
} )
: [];

const [ isEditing, setIsEditing ] = useState( false );
const [ editingElement, setEditingElement ] = useState<
number | null | undefined
Expand Down Expand Up @@ -615,6 +644,22 @@ export function PaletteEdit( {
disableCustomColors
/>
) ) }
{ ! canOnlyChangeValues &&
! isEditing &&
duplicateSlugs?.length > 0 && (
<div className="components-palette-edit__warning">
Some items in this palette have identical names.
To prevent styles conflicts, give each item a
unique name.
<Button
className="components-palette-edit__edit_palette_button"
variant="link"
onClick={ () => setIsEditing( true ) }
>
{ __( 'Edit this palette.' ) }
</Button>
</div>
) }
</PaletteEditContents>
) }
{ ! hasElements && emptyMessage && (
Expand Down
12 changes: 12 additions & 0 deletions packages/components/src/palette-edit/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,15 @@
width: 100%;
}
}
.components-palette-edit__warning {
margin: $grid-unit-20 0 $grid-unit-10 0;
padding: $grid-unit-10 $grid-unit-15;
border-left: 4px solid $alert-yellow;
background-color: lighten($alert-yellow, 35%);
.components-palette-edit__edit_palette_button {
margin-left: $grid-unit-05;
}
}
.components-palette-edit__name-input.is-duplicate {
border: 1px solid $alert-red;
}
2 changes: 2 additions & 0 deletions packages/components/src/palette-edit/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export type NameInputProps = {
label: string;
onChange: ( nextName?: PaletteElement[ 'name' ] ) => void;
value: PaletteElement[ 'name' ];
className?: string;
};

export type OptionProps< T extends Color | Gradient > = {
Expand All @@ -120,6 +121,7 @@ export type OptionProps< T extends Color | Gradient > = {
onRemove: MouseEventHandler< HTMLButtonElement >;
popoverProps?: PaletteEditProps[ 'popoverProps' ];
slugPrefix: string;
isDuplicate: boolean;
};

export type PaletteEditListViewProps< T extends Color | Gradient > = {
Expand Down
Loading