Skip to content
Open
Show file tree
Hide file tree
Changes from 13 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
25 changes: 25 additions & 0 deletions packages/block-library/src/code/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { __ } from '@wordpress/i18n';
import { RichText, useBlockProps } from '@wordpress/block-editor';
import { createBlock, getDefaultBlockName } from '@wordpress/blocks';
import { useEffect, useState } from '@wordpress/element';

export default function CodeEdit( {
attributes,
Expand All @@ -13,6 +14,29 @@ export default function CodeEdit( {
mergeBlocks,
} ) {
const blockProps = useBlockProps();
const [ supportsBreakSpaces, setSupportsBreakSpaces ] = useState( false );

// Check if the browser supports 'break-spaces' in CSS.
useEffect( () => {
const isSupported =
typeof CSS !== 'undefined' &&
// eslint-disable-next-line no-undef
CSS.supports &&
// eslint-disable-next-line no-undef
CSS.supports( 'white-space', 'break-spaces' );
setSupportsBreakSpaces( isSupported );
}, [] );

/**
* If the browser supports 'break-spaces', we can use it for better
* handling of whitespace in code blocks. Otherwise, we fall back to
* 'pre-wrap', which is more widely supported.
*
* @constant
* @type {string}
*/
const whiteSpaceStyle = supportsBreakSpaces ? 'break-spaces' : 'pre-wrap';

return (
<pre { ...blockProps }>
<RichText
Expand All @@ -29,6 +53,7 @@ export default function CodeEdit( {
__unstableOnSplitAtDoubleLineEnd={ () =>
insertBlocksAfter( createBlock( getDefaultBlockName() ) )
}
style={ { whiteSpace: whiteSpaceStyle } }
/>
</pre>
);
Expand Down
4 changes: 4 additions & 0 deletions packages/block-library/src/code/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@
direction: ltr;
text-align: initial;
/*!rtl:end:ignore*/

@supports (white-space: break-spaces) {
white-space: break-spaces;
}
}
}
Loading