Skip to content

Commit

Permalink
Just a commit to explore adding a private selector to mimic get_theme…
Browse files Browse the repository at this point in the history
…_file_uri (would be extracted into a new PR)

Haven't worked out global styles yet. CSS rules might need to be injected into the DOM???
  • Loading branch information
ramonjd committed Apr 30, 2024
1 parent 1779316 commit a8714f5
Show file tree
Hide file tree
Showing 16 changed files with 145 additions and 101 deletions.
2 changes: 1 addition & 1 deletion .wp-env.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"core": "WordPress/WordPress",
"plugins": [ "." ],
"themes": [ "./test/emptytheme" ],
"themes": [ "./test/emptytheme", "./test/emptytheme-child" ],
"env": {
"tests": {
"mappings": {
Expand Down
3 changes: 0 additions & 3 deletions lib/block-supports/background.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ function gutenberg_get_background_support_styles( $background_styles = array() )
* "theme" source implies relative path to the theme directory
*/
if ( ! empty( $background_styles['backgroundImage']['url'] ) && is_string( $background_styles['backgroundImage']['url'] ) && 'theme' === $background_image_source ) {
if ( ! str_starts_with( $background_styles['backgroundImage']['url'], '/' ) ) {
$background_styles['backgroundImage']['url'] = '/' . $background_styles['backgroundImage']['url'];
}
$background_styles['backgroundImage']['url'] = esc_url( get_theme_file_uri( $background_styles['backgroundImage']['url'] ) );
}
return gutenberg_style_engine_get_styles( array( 'background' => $background_styles ) );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { TOOLSPANEL_DROPDOWNMENU_PROPS } from './utils';
import { setImmutably } from '../../utils/object';
import MediaReplaceFlow from '../media-replace-flow';
import { store as blockEditorStore } from '../../store';
import { unlock } from '../../lock-unlock';

const IMAGE_BACKGROUND_TYPE = 'image';
const DEFAULT_CONTROLS = {
Expand Down Expand Up @@ -201,6 +202,23 @@ function BackgroundImageToolsPanelItem( {
...inheritedValue?.background?.backgroundImage,
};

const { backgroundImageURL } = useSelect(
( select ) => {
const { getThemeFileURI } = unlock( select( blockEditorStore ) );
let file = url;
if (
!! style?.background?.backgroundImage?.url &&
style?.background?.backgroundImage?.source === 'theme'
) {
file = getThemeFileURI( style.background.backgroundImage.url );
}
return {
backgroundImageURL: file,
};
},
[ url ]
);

const replaceContainerRef = useRef();

const { createErrorNotice } = useDispatch( noticesStore );
Expand Down Expand Up @@ -295,15 +313,15 @@ function BackgroundImageToolsPanelItem( {
>
<MediaReplaceFlow
mediaId={ id }
mediaURL={ url }
mediaURL={ backgroundImageURL }
allowedTypes={ [ IMAGE_BACKGROUND_TYPE ] }
accept="image/*"
onSelect={ onSelectMedia }
name={
<InspectorImagePreview
label={ title }
filename={ title || __( 'Untitled' ) }
url={ url }
url={ backgroundImageURL }
/>
}
variant="secondary"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,7 @@ export function getStylesDeclarations(
selector = '',
useRootPaddingAlign,
tree = {},
isTemplate = true,
editorSettings
isTemplate = true
) {
const { kebabCase } = unlock( componentsPrivateApis );
const isRoot = ROOT_BLOCK_SELECTOR === selector;
Expand Down Expand Up @@ -401,17 +400,13 @@ export function getStylesDeclarations(
*/
if ( !! blockStyles?.background ) {
blockStyles = setBackgroundStyleDefaults( blockStyles, {
...editorSettings,
selector,
} );
}

// The goal is to move everything to server side generated engine styles
// This is temporary as we absorb more and more styles into the engine.
const extraRules = getCSSRules( blockStyles, {
...editorSettings,
isRoot,
} );
const extraRules = getCSSRules( blockStyles );
extraRules.forEach( ( rule ) => {
// Don't output padding properties if padding variables are set or if we're not editing a full template.
if (
Expand Down Expand Up @@ -794,8 +789,7 @@ export const toStyles = (
hasBlockGapSupport,
hasFallbackGapSupport,
disableLayoutStyles = false,
isTemplate = true,
editorSettings = {}
isTemplate = true
) => {
const nodesWithStyles = getNodesWithStyles( tree, blockSelectors );
const nodesWithSettings = getNodesWithSettings( tree, blockSelectors );
Expand Down Expand Up @@ -905,8 +899,7 @@ export const toStyles = (
styleVariations,
styleVariationSelector,
useRootPaddingAlign,
tree,
editorSettings
tree
);
if ( styleVariationDeclarations.length ) {
ruleset += `${ styleVariationSelector }{${ styleVariationDeclarations.join(
Expand Down Expand Up @@ -954,8 +947,7 @@ export const toStyles = (
selector,
useRootPaddingAlign,
tree,
isTemplate,
editorSettings
isTemplate
);
if ( declarations?.length ) {
ruleset += `:where(${ selector }){${ declarations.join(
Expand Down Expand Up @@ -1217,17 +1209,12 @@ export function useGlobalStylesOutputWithConfig( mergedConfig = {} ) {
const hasBlockGapSupport = blockGap !== null;
const hasFallbackGapSupport = ! hasBlockGapSupport; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback styles support.

const { stylesheetURI, templateURI, disableLayoutStyles } = useSelect(
( select ) => {
const _settings = select( blockEditorStore ).getSettings();
return {
stylesheetURI:
_settings?.__experimentalCurrentTheme?.stylesheetURI,
templateURI: _settings?.__experimentalCurrentTheme?.templateURI,
disableLayoutStyles: !! _settings.disableLayoutStyles,
};
}
);
const { disableLayoutStyles } = useSelect( ( select ) => {
const _settings = select( blockEditorStore ).getSettings();
return {
disableLayoutStyles: !! _settings.disableLayoutStyles,
};
} );

const blockContext = useContext( BlockContext );

Expand Down Expand Up @@ -1257,12 +1244,9 @@ export function useGlobalStylesOutputWithConfig( mergedConfig = {} ) {
hasBlockGapSupport,
hasFallbackGapSupport,
disableLayoutStyles,
isTemplate,
{
stylesheetURI,
templateURI,
}
isTemplate
);
console.log( 'globalStyles', globalStyles );
const svgs = toSvgFilters( updatedConfig, blockSelectors );

const styles = [
Expand Down Expand Up @@ -1310,8 +1294,6 @@ export function useGlobalStylesOutputWithConfig( mergedConfig = {} ) {
disableLayoutStyles,
isTemplate,
getBlockStyles,
stylesheetURI,
templateURI,
] );
}

Expand Down
64 changes: 38 additions & 26 deletions packages/block-editor/src/hooks/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
hasBackgroundImageValue,
} from '../components/global-styles/background-panel';
import { ROOT_BLOCK_SELECTOR } from '../components/global-styles/utils';
import { unlock } from '../lock-unlock';

export const BACKGROUND_SUPPORT_KEY = 'background';

Expand Down Expand Up @@ -72,32 +73,6 @@ export function setBackgroundStyleDefaults( blockStyles, options ) {
const backgroundImage = blockStyles?.background?.backgroundImage;
const newBackgroundStyles = {};

/* if (
backgroundImage?.source === 'theme' &&
!! backgroundImage?.url &&
!! options?.stylesheetURI &&
!! options?.templateURI
) {
const activeThemeImageResource = `${ options.stylesheetURI }${
backgroundImage.url.startsWith( '/' )
? backgroundImage.url
: `/${ backgroundImage.url }`
}`;
const parentThemeImageResource = `${ options.templateURI }${
backgroundImage.url.startsWith( '/' )
? backgroundImage.url
: `/${ backgroundImage.url }`
}`;
newBackgroundStyles.backgroundImage = {
...backgroundImage,
url: `${ encodeURI(
safeDecodeURI( activeThemeImageResource )
) }, ${ encodeURI( safeDecodeURI( parentThemeImageResource ) ) }`,
};
}*/

// Set block background defaults.
if ( options?.selector !== ROOT_BLOCK_SELECTOR && !! backgroundImage ) {
if ( ! blockStyles?.background?.backgroundSize ) {
Expand Down Expand Up @@ -202,7 +177,44 @@ export function BackgroundImagePanel( {
);
}

function useBlockProps( { name, style } ) {
const { backgroundImageURL } = useSelect(
( select ) => {
const { getThemeFileURI } = unlock( select( blockEditorStore ) );
let file;
if (
!! style?.background?.backgroundImage?.url &&
style?.background?.backgroundImage?.source === 'theme'
) {
file = getThemeFileURI( style.background.backgroundImage.url );
}
return {
backgroundImageURL: file,
};
},
[ style?.background?.backgroundImage ]
);

if (
! hasBackgroundSupport( name, 'backgroundImage' ) ||
! backgroundImageURL
) {
return;
}

return {
style: {
// @TODO this should be backgroundImage. How to do that?
// Also, maybe consider reinstating https://github.com/WordPress/gutenberg/blob/fc98542a7dbba194bb4096d49cd0bd093b63f43e/packages/block-editor/src/hooks/background.js#L82
background: `url( '${ encodeURI(
safeDecodeURI( backgroundImageURL )
) }' )`,
},
};
}

export default {
attributeKeys: [ 'style' ],
hasSupport: hasBackgroundSupport,
useBlockProps,
};
2 changes: 2 additions & 0 deletions packages/block-editor/src/hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from './utils';
import './compat';
import align from './align';
import background from './background';
import './lock';
import anchor from './anchor';
import ariaLabel from './aria-label';
Expand Down Expand Up @@ -48,6 +49,7 @@ createBlockEditFilter(
);
createBlockListBlockFilter( [
align,
background,
textAlign,
style,
color,
Expand Down
16 changes: 4 additions & 12 deletions packages/block-editor/src/hooks/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ const hasStyleSupport = ( nameOrType ) =>
*
* @return {Object} Flattened CSS variables declaration.
*/
export function getInlineStyles( styles = {}, options ) {
export function getInlineStyles( styles = {} ) {
const output = {};
// The goal is to move everything to server side generated engine styles
// This is temporary as we absorb more and more styles into the engine.
getCSSRules( styles, options ).forEach( ( rule ) => {
getCSSRules( styles ).forEach( ( rule ) => {
output[ rule.key ] = rule.value;
} );

Expand Down Expand Up @@ -287,15 +287,13 @@ export function omitStyle( style, paths, preserveReference = false ) {
* @param {Object|string} blockNameOrType Block type.
* @param {Object} attributes Block attributes.
* @param {?Record<string, string[]>} skipPaths An object of keys and paths to skip serialization.
* @param {Object} editorSettings Current editor settings.
* @return {Object} Filtered props applied to save element.
*/
export function addSaveProps(
props,
blockNameOrType,
attributes,
skipPaths = skipSerializationPathsSave,
editorSettings
) {
if ( ! hasStyleSupport( blockNameOrType ) ) {
return props;
Expand Down Expand Up @@ -325,13 +323,11 @@ export function addSaveProps(
* Only applies to background styles for now.
*/
if ( !! style.background ) {
style = setBackgroundStyleDefaults( style, editorSettings );
style = setBackgroundStyleDefaults( style );
}

props.style = {
...getInlineStyles( style, {
...editorSettings,
} ),
...getInlineStyles( style ),
...props.style,
};

Expand Down Expand Up @@ -481,10 +477,6 @@ function useBlockProps( { name, style } ) {
name,
{ style },
skipSerializationPathsEdit,
{
stylesheetURI,
templateURI,
}
);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/block-editor/src/private-apis.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { useFlashEditableBlocks } from './components/use-flash-editable-blocks';
import {
selectBlockPatternsKey,
reusableBlocksSelectKey,
getThemeFileURIKey,
} from './store/private-keys';
import { requiresWrapperOnCopy } from './components/writing-flow/utils';
import { PrivateRichText } from './components/rich-text/';
Expand Down Expand Up @@ -76,4 +77,5 @@ lock( privateApis, {
requiresWrapperOnCopy,
PrivateRichText,
reusableBlocksSelectKey,
getThemeFileURIKey,
} );
1 change: 1 addition & 0 deletions packages/block-editor/src/store/private-keys.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export const selectBlockPatternsKey = Symbol( 'selectBlockPatternsKey' );
export const reusableBlocksSelectKey = Symbol( 'reusableBlocksSelect' );
export const getThemeFileURIKey = Symbol( 'getThemeFileURI' );
10 changes: 10 additions & 0 deletions packages/block-editor/src/store/private-selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { unlock } from '../lock-unlock';
import {
selectBlockPatternsKey,
reusableBlocksSelectKey,
getThemeFileURIKey,
} from './private-keys';

export { getBlockSettings } from './get-block-settings';
Expand Down Expand Up @@ -388,6 +389,15 @@ export const getReusableBlocks = createRegistrySelector(
}
);

export const getThemeFileURI = createRegistrySelector(
( select ) => ( state, file ) => {
const getThemeFileURISelect = state.settings[ getThemeFileURIKey ];
return getThemeFileURISelect
? getThemeFileURISelect( select, file )
: '';
}
);

/**
* Returns the element of the last element that had focus when focus left the editor canvas.
*
Expand Down
4 changes: 4 additions & 0 deletions packages/core-data/src/private-selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,7 @@ export const getBlockPatternsForPostType = createRegistrySelector(
() => [ select( STORE_NAME ).getBlockPatterns() ]
)
);

export function getThemeFileURI( state: State, file: string ) {
return state.themeFileURIs?.[ file ];
}
Loading

0 comments on commit a8714f5

Please sign in to comment.