diff --git a/.eslintrc.js b/.eslintrc.js index 43e259b40c7b7e..5a16c00205a860 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -18,13 +18,8 @@ const majorMinorRegExp = escapeRegExp( version.replace( /\.\d+$/, '' ) ) + '(\\. module.exports = { root: true, - extends: [ - 'plugin:@wordpress/eslint-plugin/recommended', - 'plugin:eslint-comments/recommended', - ], - plugins: [ - 'import', - ], + extends: [ 'plugin:@wordpress/eslint-plugin/recommended', 'plugin:eslint-comments/recommended' ], + plugins: [ 'import' ], globals: { wp: 'off', }, @@ -42,23 +37,29 @@ module.exports = { message: 'Path access on WordPress dependencies is not allowed.', }, { - selector: 'ImportDeclaration[source.value=/^react-spring(?!\\u002Fweb\.cjs)/]', + selector: 'ImportDeclaration[source.value=/^react-spring(?!\\u002Fweb.cjs)/]', message: 'The react-spring dependency must specify CommonJS bundle: react-spring/web.cjs', }, { - selector: 'CallExpression[callee.name="deprecated"] Property[key.name="version"][value.value=/' + majorMinorRegExp + '/]', + selector: + 'CallExpression[callee.name="deprecated"] Property[key.name="version"][value.value=/' + + majorMinorRegExp + + '/]', message: 'Deprecated functions must be removed before releasing this version.', }, { - selector: 'CallExpression[callee.name=/^(__|_n|_nx|_x)$/]:not([arguments.0.type=/^Literal|BinaryExpression$/])', + selector: + 'CallExpression[callee.name=/^(__|_n|_nx|_x)$/]:not([arguments.0.type=/^Literal|BinaryExpression$/])', message: 'Translate function arguments must be string literals.', }, { - selector: 'CallExpression[callee.name=/^(_n|_nx|_x)$/]:not([arguments.1.type=/^Literal|BinaryExpression$/])', + selector: + 'CallExpression[callee.name=/^(_n|_nx|_x)$/]:not([arguments.1.type=/^Literal|BinaryExpression$/])', message: 'Translate function arguments must be string literals.', }, { - selector: 'CallExpression[callee.name=_nx]:not([arguments.3.type=/^Literal|BinaryExpression$/])', + selector: + 'CallExpression[callee.name=_nx]:not([arguments.3.type=/^Literal|BinaryExpression$/])', message: 'Translate function arguments must be string literals.', }, { @@ -66,7 +67,8 @@ module.exports = { message: 'Use ellipsis character (…) in place of three dots', }, { - selector: 'ImportDeclaration[source.value="redux"] Identifier.imported[name="combineReducers"]', + selector: + 'ImportDeclaration[source.value="redux"] Identifier.imported[name="combineReducers"]', message: 'Use `combineReducers` from `@wordpress/data`', }, { @@ -86,32 +88,40 @@ module.exports = { // for UUID generation, for which we already have a higher-order // component: `withInstanceId`. selector: 'CallExpression[callee.object.name="Math"][callee.property.name="random"]', - message: 'Do not use Math.random() to generate unique IDs; use withInstanceId instead. (If you’re not generating unique IDs: ignore this message.)', + message: + 'Do not use Math.random() to generate unique IDs; use withInstanceId instead. (If you’re not generating unique IDs: ignore this message.)', }, { - selector: 'CallExpression[callee.name="withDispatch"] > :function > BlockStatement > :not(VariableDeclaration,ReturnStatement)', - message: 'withDispatch must return an object with consistent keys. Avoid performing logic in `mapDispatchToProps`.', + selector: + 'CallExpression[callee.name="withDispatch"] > :function > BlockStatement > :not(VariableDeclaration,ReturnStatement)', + message: + 'withDispatch must return an object with consistent keys. Avoid performing logic in `mapDispatchToProps`.', }, { - selector: 'LogicalExpression[operator="&&"][left.property.name="length"][right.type="JSXElement"]', - message: 'Avoid truthy checks on length property rendering, as zero length is rendered verbatim.', + selector: + 'LogicalExpression[operator="&&"][left.property.name="length"][right.type="JSXElement"]', + message: + 'Avoid truthy checks on length property rendering, as zero length is rendered verbatim.', + }, + ], + 'react/forbid-elements': [ + 'error', + { + forbid: [ + [ 'circle', 'Circle' ], + [ 'g', 'G' ], + [ 'path', 'Path' ], + [ 'polygon', 'Polygon' ], + [ 'rect', 'Rect' ], + [ 'svg', 'SVG' ], + ].map( ( [ element, componentName ] ) => { + return { + element, + message: `use cross-platform <${ componentName }> component instead.`, + }; + } ), }, ], - 'react/forbid-elements': [ 'error', { - forbid: [ - [ 'circle', 'Circle' ], - [ 'g', 'G' ], - [ 'path', 'Path' ], - [ 'polygon', 'Polygon' ], - [ 'rect', 'Rect' ], - [ 'svg', 'SVG' ], - ].map( ( [ element, componentName ] ) => { - return { - element, - message: `use cross-platform <${ componentName }> component instead.`, - }; - } ), - } ], }, overrides: [ { @@ -127,18 +137,12 @@ module.exports = { ], }, { - files: [ - 'packages/jest*/**/*.js', - ], - extends: [ - 'plugin:@wordpress/eslint-plugin/test-unit', - ], + files: [ 'packages/jest*/**/*.js' ], + extends: [ 'plugin:@wordpress/eslint-plugin/test-unit' ], }, { files: [ 'packages/e2e-test*/**/*.js' ], - extends: [ - 'plugin:@wordpress/eslint-plugin/test-e2e', - ], + extends: [ 'plugin:@wordpress/eslint-plugin/test-e2e' ], }, ], }; diff --git a/bin/commander.js b/bin/commander.js index dcc863872f034d..cc574e6d678a9f 100755 --- a/bin/commander.js +++ b/bin/commander.js @@ -48,13 +48,19 @@ function readJSONFile( fileName ) { * @param {boolean} isDefault Default reply. * @param {string} abortMessage Abort message. */ -async function askForConfirmationToContinue( message, isDefault = true, abortMessage = 'Aborting.' ) { - const { isReady } = await inquirer.prompt( [ { - type: 'confirm', - name: 'isReady', - default: isDefault, - message, - } ] ); +async function askForConfirmationToContinue( + message, + isDefault = true, + abortMessage = 'Aborting.' +) { + const { isReady } = await inquirer.prompt( [ + { + type: 'confirm', + name: 'isReady', + default: isDefault, + message, + }, + ] ); if ( ! isReady ) { console.log( error( '\n' + abortMessage ) ); @@ -113,7 +119,10 @@ async function runGitRepositoryCloneStep( abortMessage ) { console.log( '>> Cloning the Git repository' ); const simpleGit = SimpleGit(); await simpleGit.clone( gitRepoURL, gitWorkingDirectoryPath ); - console.log( '>> The Gutenberg Git repository has been successfully cloned in the following temporary folder: ' + success( gitWorkingDirectoryPath ) ); + console.log( + '>> The Gutenberg Git repository has been successfully cloned in the following temporary folder: ' + + success( gitWorkingDirectoryPath ) + ); } ); } @@ -127,7 +136,10 @@ async function runSvnRepositoryCloneStep( abortMessage ) { await runStep( 'Fetching the SVN repository', abortMessage, async () => { console.log( '>> Fetching the SVN repository' ); runShellScript( 'svn checkout ' + svnRepoURL + '/trunk ' + svnWorkingDirectoryPath ); - console.log( '>> The Gutenberg SVN repository has been successfully fetched in the following temporary folder: ' + success( svnWorkingDirectoryPath ) ); + console.log( + '>> The Gutenberg SVN repository has been successfully fetched in the following temporary folder: ' + + success( svnWorkingDirectoryPath ) + ); } ); } @@ -144,7 +156,10 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { console.log( '>> Replacing trunk content using the new plugin ZIP' ); // Delete everything except readme.txt and changelog.txt - runShellScript( 'find . -maxdepth 1 -not -name "changelog.txt" -not -name "readme.txt" -not -name ".svn" -not -name "." -not -name ".." -exec rm -rf {} +', svnWorkingDirectoryPath ); + runShellScript( + 'find . -maxdepth 1 -not -name "changelog.txt" -not -name "readme.txt" -not -name ".svn" -not -name "." -not -name ".." -exec rm -rf {} +', + svnWorkingDirectoryPath + ); // Update the content using the plugin ZIP const gutenbergZipPath = gitWorkingDirectoryPath + '/gutenberg.zip'; @@ -158,7 +173,8 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { const newReadmeContent = readmeFileContent.substr( 0, readmeFileContent.indexOf( '== Changelog ==' ) ) + '== Changelog ==\n\n' + - changelog + '\n'; + changelog + + '\n'; fs.writeFileSync( readmePath, newReadmeContent ); // Update the content of the changelog.txt file @@ -166,21 +182,32 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { const changelogFileContent = fs.readFileSync( changelogPath, 'utf8' ); const newChangelogContent = '== Changelog ==\n\n' + - '= ' + version + ' =\n\n' + + '= ' + + version + + ' =\n\n' + changelog + changelogFileContent.substr( changelogFileContent.indexOf( '== Changelog ==' ) + 16 ); fs.writeFileSync( changelogPath, newChangelogContent ); // Commit the content changes - runShellScript( "svn st | grep '^\?' | awk '{print $2}' | xargs svn add", svnWorkingDirectoryPath ); - runShellScript( "svn st | grep '^!' | awk '{print $2}' | xargs svn rm", svnWorkingDirectoryPath ); + runShellScript( + "svn st | grep '^?' | awk '{print $2}' | xargs svn add", + svnWorkingDirectoryPath + ); + runShellScript( + "svn st | grep '^!' | awk '{print $2}' | xargs svn rm", + svnWorkingDirectoryPath + ); await askForConfirmationToContinue( 'Trunk content has been updated, please check the SVN diff. Commit the changes?', true, abortMessage ); - runShellScript( 'svn commit -m "Committing Gutenberg version ' + version + '"', svnWorkingDirectoryPath ); + runShellScript( + 'svn commit -m "Committing Gutenberg version ' + version + '"', + svnWorkingDirectoryPath + ); console.log( '>> Trunk has been successfully updated' ); } ); @@ -199,7 +226,17 @@ async function runSvnTagStep( version, abortMessage ) { true, abortMessage ); - runShellScript( 'svn cp ' + svnRepoURL + '/trunk ' + svnRepoURL + '/tags/' + version + ' -m "Tagging Gutenberg version ' + version + '"' ); + runShellScript( + 'svn cp ' + + svnRepoURL + + '/trunk ' + + svnRepoURL + + '/tags/' + + version + + ' -m "Tagging Gutenberg version ' + + version + + '"' + ); console.log( '>> The SVN ' + success( version ) + ' tag has been successfully created' ); } ); @@ -213,7 +250,7 @@ async function runSvnTagStep( version, abortMessage ) { */ async function updateThePluginStableVersion( version, abortMessage ) { // Updating the content of the svn - await runStep( 'Updating the plugin\'s stable version', abortMessage, async () => { + await runStep( "Updating the plugin's stable version", abortMessage, async () => { const readmePath = svnWorkingDirectoryPath + '/readme.txt'; const readmeFileContent = fs.readFileSync( readmePath, 'utf8' ); const newReadmeContent = readmeFileContent.replace( @@ -229,7 +266,10 @@ async function updateThePluginStableVersion( version, abortMessage ) { abortMessage ); - runShellScript( 'svn commit -m "Releasing Gutenberg version ' + version + '"', svnWorkingDirectoryPath ); + runShellScript( + 'svn commit -m "Releasing Gutenberg version ' + version + '"', + svnWorkingDirectoryPath + ); console.log( '>> Stable version updated successfully' ); } ); @@ -266,23 +306,27 @@ async function runReleaseBranchCreationStep( abortMessage ) { // Follow the WordPress version guidelines to compute the version to be used // By default, increase the "minor" number but if we reach 9, bump to the next major. if ( parsedVersion.minor === 9 ) { - version = ( parsedVersion.major + 1 ) + '.0.0-rc.1'; + version = parsedVersion.major + 1 + '.0.0-rc.1'; releaseBranch = 'release/' + ( parsedVersion.major + 1 ) + '.0'; - versionLabel = ( parsedVersion.major + 1 ) + '.0.0 RC1'; + versionLabel = parsedVersion.major + 1 + '.0.0 RC1'; } else { version = parsedVersion.major + '.' + ( parsedVersion.minor + 1 ) + '.0-rc.1'; releaseBranch = 'release/' + parsedVersion.major + '.' + ( parsedVersion.minor + 1 ); versionLabel = parsedVersion.major + '.' + ( parsedVersion.minor + 1 ) + '.0 RC1'; } await askForConfirmationToContinue( - 'The Plugin version to be used is ' + success( version ) + '. Proceed with the creation of the release branch?', + 'The Plugin version to be used is ' + + success( version ) + + '. Proceed with the creation of the release branch?', true, abortMessage ); // Creating the release branch await simpleGit.checkoutLocalBranch( releaseBranch ); - console.log( '>> The local release branch ' + success( releaseBranch ) + ' has been successfully created.' ); + console.log( + '>> The local release branch ' + success( releaseBranch ) + ' has been successfully created.' + ); } ); return { @@ -310,15 +354,29 @@ async function runReleaseBranchCheckoutStep( abortMessage ) { // Creating the release branch await simpleGit.checkout( releaseBranch ); - console.log( '>> The local release branch ' + success( releaseBranch ) + ' has been successfully checked out.' ); + console.log( + '>> The local release branch ' + + success( releaseBranch ) + + ' has been successfully checked out.' + ); const releaseBranchPackageJson = readJSONFile( packageJsonPath ); const releaseBranchParsedVersion = semver.parse( releaseBranchPackageJson.version ); if ( releaseBranchParsedVersion.prerelease && releaseBranchParsedVersion.prerelease.length ) { - version = releaseBranchParsedVersion.major + '.' + releaseBranchParsedVersion.minor + '.' + releaseBranchParsedVersion.patch; + version = + releaseBranchParsedVersion.major + + '.' + + releaseBranchParsedVersion.minor + + '.' + + releaseBranchParsedVersion.patch; } else { - version = releaseBranchParsedVersion.major + '.' + releaseBranchParsedVersion.minor + '.' + ( releaseBranchParsedVersion.patch + 1 ); + version = + releaseBranchParsedVersion.major + + '.' + + releaseBranchParsedVersion.minor + + '.' + + ( releaseBranchParsedVersion.patch + 1 ); } await askForConfirmationToContinue( @@ -364,7 +422,10 @@ async function runBumpPluginVersionAndCommitStep( version, abortMessage ) { }; fs.writeFileSync( packageLockPath, JSON.stringify( newPackageLock, null, '\t' ) + '\n' ); const content = fs.readFileSync( pluginFilePath, 'utf8' ); - fs.writeFileSync( pluginFilePath, content.replace( ' * Version: ' + packageJson.version, ' * Version: ' + version ) ); + fs.writeFileSync( + pluginFilePath, + content.replace( ' * Version: ' + packageJson.version, ' * Version: ' + version ) + ); console.log( '>> The plugin version has been updated successfully.' ); // Commit the version bump @@ -373,11 +434,7 @@ async function runBumpPluginVersionAndCommitStep( version, abortMessage ) { true, abortMessage ); - await simpleGit.add( [ - packageJsonPath, - packageLockPath, - pluginFilePath, - ] ); + await simpleGit.add( [ packageJsonPath, packageLockPath, pluginFilePath ] ); const commitData = await simpleGit.commit( 'Bump plugin version to ' + version ); commitHash = commitData.commit; console.log( '>> The plugin version bump has been commited successfully.' ); @@ -401,7 +458,9 @@ async function runPluginZIPCreationStep( abortMessage ) { ); runShellScript( '/bin/bash bin/build-plugin-zip.sh', gitWorkingDirectoryPath ); - console.log( '>> The plugin ZIP has been built successfully. Path: ' + success( gutenbergZipPath ) ); + console.log( + '>> The plugin ZIP has been built successfully. Path: ' + success( gutenbergZipPath ) + ); } ); } @@ -462,17 +521,24 @@ async function runGithubReleaseStep( version, versionLabel, isPrerelease, abortM true, abortMessage ); - const { changelog } = await inquirer.prompt( [ { - type: 'editor', - name: 'changelog', - message: 'Please provide the CHANGELOG of the release (markdown)', - } ] ); - - const { token } = await inquirer.prompt( [ { - type: 'input', - name: 'token', - message: 'Please provide a GitHub personal authentication token. Navigate to ' + success( 'https://github.com/settings/tokens/new?scopes=repo,admin:org,write:packages' ) + ' to create one.', - } ] ); + const { changelog } = await inquirer.prompt( [ + { + type: 'editor', + name: 'changelog', + message: 'Please provide the CHANGELOG of the release (markdown)', + }, + ] ); + + const { token } = await inquirer.prompt( [ + { + type: 'input', + name: 'token', + message: + 'Please provide a GitHub personal authentication token. Navigate to ' + + success( 'https://github.com/settings/tokens/new?scopes=repo,admin:org,write:packages' ) + + ' to create one.', + }, + ] ); octokit = new Octokit( { auth: token, @@ -552,9 +618,9 @@ async function releasePlugin( isRC = true ) { await runGitRepositoryCloneStep( abortMessage ); // Creating the release branch - const { version, versionLabel, releaseBranch } = isRC ? - await runReleaseBranchCreationStep( abortMessage ) : - await runReleaseBranchCheckoutStep( abortMessage ); + const { version, versionLabel, releaseBranch } = isRC + ? await runReleaseBranchCreationStep( abortMessage ) + : await runReleaseBranchCheckoutStep( abortMessage ); // Bumping the version and commit. const commitHash = await runBumpPluginVersionAndCommitStep( version, abortMessage ); @@ -567,11 +633,17 @@ async function releasePlugin( isRC = true ) { // Push the local changes await runPushGitChangesStep( releaseBranch, abortMessage ); - abortMessage = 'Aborting! Make sure to ' + isRC ? 'remove' : 'reset' + ' the remote release branch and remove the git tag.'; + abortMessage = + 'Aborting! Make sure to ' + isRC + ? 'remove' + : 'reset' + ' the remote release branch and remove the git tag.'; // Creating the GitHub Release const release = await runGithubReleaseStep( version, versionLabel, isRC, abortMessage ); - abortMessage = 'Aborting! Make sure to manually cherry-pick the ' + success( commitHash ) + ' commit to the master branch.'; + abortMessage = + 'Aborting! Make sure to manually cherry-pick the ' + + success( commitHash ) + + ' commit to the master branch.'; if ( ! isRC ) { abortMessage += ' Make sure to perform the SVN release manually as well.'; } @@ -580,9 +652,13 @@ async function releasePlugin( isRC = true ) { await runCherrypickBumpCommitIntoMasterStep( commitHash, abortMessage ); if ( ! isRC ) { - abortMessage = 'Aborting! The GitHub release is done. Make sure to perform the SVN release manually.'; + abortMessage = + 'Aborting! The GitHub release is done. Make sure to perform the SVN release manually.'; - await askForConfirmationToContinue( 'The GitHub release is complete. Proceed with the SVN release? ', abortMessage ); + await askForConfirmationToContinue( + 'The GitHub release is complete. Proceed with the SVN release? ', + abortMessage + ); // Fetching the SVN repository await runSvnRepositoryCloneStep( abortMessage ); @@ -590,10 +666,12 @@ async function releasePlugin( isRC = true ) { // Updating the SVN trunk content await runUpdateTrunkContentStep( version, release.body, abortMessage ); - abortMessage = 'Aborting! The GitHub release is done, SVN trunk updated. Make sure to create the SVN tag and update the stable version manually.'; + abortMessage = + 'Aborting! The GitHub release is done, SVN trunk updated. Make sure to create the SVN tag and update the stable version manually.'; await runSvnTagStep( version, abortMessage ); - abortMessage = 'Aborting! The GitHub release is done, SVN tagged. Make sure to update the stable version manually.'; + abortMessage = + 'Aborting! The GitHub release is done, SVN tagged. Make sure to update the stable version manually.'; await updateThePluginStableVersion( version, abortMessage ); } @@ -612,13 +690,15 @@ program chalk.bold( '💃 Time to release Gutenberg 🕺\n\n' ), 'Welcome! This tool is going to help you release a new RC version of the Gutenberg Plugin.\n', 'It goes through different steps : creating the release branch, bumping the plugin version, tagging and creating the GitHub release, building the ZIP...\n', - 'To perform a release you\'ll have to be a member of the Gutenberg Core Team.\n' + "To perform a release you'll have to be a member of the Gutenberg Core Team.\n" ); const release = await releasePlugin( true ); console.log( - '\n>> 🎉 The Gutenberg version ' + success( release.name ) + ' has been successfully released.\n', + '\n>> 🎉 The Gutenberg version ' + + success( release.name ) + + ' has been successfully released.\n', 'You can access the GitHub release here: ' + success( release.html_url ) + '\n', 'Thanks for performing the release!' ); @@ -633,7 +713,7 @@ program chalk.bold( '💃 Time to release Gutenberg 🕺\n\n' ), 'Welcome! This tool is going to help you release a new stable version of the Gutenberg Plugin.\n', 'It goes through different steps : bumping the plugin version, tagging and creating the GitHub release, building the ZIP, pushing the release to the SVN repository...\n', - 'To perform a release you\'ll have to be a member of the Gutenberg Core Team.\n' + "To perform a release you'll have to be a member of the Gutenberg Core Team.\n" ); const release = await releasePlugin( false ); @@ -641,8 +721,8 @@ program console.log( '\n>> 🎉 The Gutenberg ' + success( release.name ) + ' has been successfully released.\n', 'You can access the GitHub release here: ' + success( release.html_url ) + '\n', - 'In a few minutes, you\'ll be able to update the plugin from the WordPress repository.\n', - 'Thanks for performing the release! and don\'t forget to publish the release post.' + "In a few minutes, you'll be able to update the plugin from the WordPress repository.\n", + "Thanks for performing the release! and don't forget to publish the release post." ); } ); diff --git a/bin/generate-public-grammar.js b/bin/generate-public-grammar.js index c56ec4398a8941..28f8b43859a988 100755 --- a/bin/generate-public-grammar.js +++ b/bin/generate-public-grammar.js @@ -2,7 +2,10 @@ const parser = require( '../node_modules/pegjs/lib/parser.js' ); const fs = require( 'fs' ); const path = require( 'path' ); -const grammarSource = fs.readFileSync( './packages/block-serialization-spec-parser/grammar.pegjs', 'utf8' ); +const grammarSource = fs.readFileSync( + './packages/block-serialization-spec-parser/grammar.pegjs', + 'utf8' +); const grammar = parser.parse( grammarSource ); function escape( text ) { @@ -15,12 +18,7 @@ function escape( text ) { } function isGroup( expression ) { - return [ - 'choice', - 'action', - 'labeled', - 'sequence', - ].indexOf( expression.type ) >= 0; + return [ 'choice', 'action', 'labeled', 'sequence' ].indexOf( expression.type ) >= 0; } function flattenUnary( expression ) { @@ -40,11 +38,13 @@ function flatten( expression ) { return '"' + escape( expression.value ) + '"'; case 'class': return ( - '[' + ( expression.inverted ? '^' : '' ) + - expression.parts.map( ( part ) => - escape( Array.isArray( part ) ? part.join( '-' ) : part ) - ).join( '' ) + - ']' + ( expression.ignoreCase ? 'i' : '' ) + '[' + + ( expression.inverted ? '^' : '' ) + + expression.parts + .map( ( part ) => escape( Array.isArray( part ) ? part.join( '-' ) : part ) ) + .join( '' ) + + ']' + + ( expression.ignoreCase ? 'i' : '' ) ); // Unary @@ -80,11 +80,12 @@ function flatten( expression ) { return `
${ expression.rules.map( flatten ).join( '' ) }
`; case 'rule': expression.expression.isRuleTop = true; - const displayName = expression.expression.type === 'named' ? - expression.expression.name : ''; - return `
${ displayName }
` + + const displayName = expression.expression.type === 'named' ? expression.expression.name : ''; + return ( + `
${ displayName }
` + `
${ expression.name }
= ` + - `${ flatten( expression.expression ) }
`; + `${ flatten( expression.expression ) }` + ); default: throw new Error( JSON.stringify( expression ) ); @@ -92,8 +93,10 @@ function flatten( expression ) { } fs.writeFileSync( - path.join( __dirname, '..', 'docs', 'grammar.md' ), ` + path.join( __dirname, '..', 'docs', 'grammar.md' ), + ` # Block Grammar ${ flatten( grammar ) } -` ); +` +); diff --git a/bin/packages/build-worker.js b/bin/packages/build-worker.js index 7e3e636c013a1d..54ce50e4907e86 100644 --- a/bin/packages/build-worker.js +++ b/bin/packages/build-worker.js @@ -95,17 +95,10 @@ const BUILD_TASK_BY_EXTENSION = { const builtSass = await renderSass( { file, includePaths: [ path.resolve( __dirname, '../../assets/stylesheets' ) ], - data: ( - [ - 'colors', - 'breakpoints', - 'variables', - 'mixins', - 'animations', - 'z-index', - ].map( ( imported ) => `@import "${ imported }";` ).join( ' ' ) + - contents - ), + data: + [ 'colors', 'breakpoints', 'variables', 'mixins', 'animations', 'z-index' ] + .map( ( imported ) => `@import "${ imported }";` ) + .join( ' ' ) + contents, } ); const result = await postcss( require( './post-css-config' ) ).process( builtSass.css, { @@ -127,7 +120,10 @@ const BUILD_TASK_BY_EXTENSION = { async '.js'( file ) { for ( const [ environment, buildDir ] of Object.entries( JS_ENVIRONMENTS ) ) { const destPath = getBuildPath( file, buildDir ); - const babelOptions = getBabelConfig( environment, file.replace( PACKAGES_DIR, '@wordpress' ) ); + const babelOptions = getBabelConfig( + environment, + file.replace( PACKAGES_DIR, '@wordpress' ) + ); const [ , transformed ] = await Promise.all( [ makeDir( path.dirname( destPath ) ), @@ -136,7 +132,10 @@ const BUILD_TASK_BY_EXTENSION = { await Promise.all( [ writeFile( destPath + '.map', JSON.stringify( transformed.map ) ), - writeFile( destPath, transformed.code + '\n//# sourceMappingURL=' + path.basename( destPath ) + '.map' ), + writeFile( + destPath, + transformed.code + '\n//# sourceMappingURL=' + path.basename( destPath ) + '.map' + ), ] ); } }, diff --git a/bin/packages/build.js b/bin/packages/build.js index 17006dbdc8638a..8eceb6c6dbbe59 100755 --- a/bin/packages/build.js +++ b/bin/packages/build.js @@ -37,7 +37,7 @@ function getPackageName( file ) { * @return {Transform} Stream transform instance. */ function createStyleEntryTransform() { - const packages = new Set; + const packages = new Set(); return new Transform( { objectMode: true, @@ -73,7 +73,7 @@ function createStyleEntryTransform() { * @return {Transform} Stream transform instance. */ function createBlockJsonEntryTransform() { - const blocks = new Set; + const blocks = new Set(); return new Transform( { objectMode: true, @@ -109,9 +109,7 @@ if ( files.length ) { stream = new Readable( { encoding: 'utf8' } ); files.forEach( ( file ) => stream.push( file ) ); stream.push( null ); - stream = stream - .pipe( createStyleEntryTransform() ) - .pipe( createBlockJsonEntryTransform() ); + stream = stream.pipe( createStyleEntryTransform() ).pipe( createBlockJsonEntryTransform() ); } else { const bar = new ProgressBar( 'Build Progress: [:bar] :percent', { width: 30, @@ -121,15 +119,8 @@ if ( files.length ) { bar.tick( 0 ); - stream = glob.stream( [ - `${ PACKAGES_DIR }/*/src/**/*.js`, - `${ PACKAGES_DIR }/*/src/*.scss`, - ], { - ignore: [ - `**/benchmark/**`, - `**/{__mocks__,__tests__,test}/**`, - `**/{storybook,stories}/**`, - ], + stream = glob.stream( [ `${ PACKAGES_DIR }/*/src/**/*.js`, `${ PACKAGES_DIR }/*/src/*.scss` ], { + ignore: [ `**/benchmark/**`, `**/{__mocks__,__tests__,test}/**`, `**/{storybook,stories}/**` ], onlyFiles: true, } ); @@ -137,11 +128,9 @@ if ( files.length ) { // but should wait until worker processing below. // // See: https://nodejs.org/api/stream.html#stream_two_reading_modes - stream - .pause() - .on( 'data', ( file ) => { - bar.total = files.push( file ); - } ); + stream.pause().on( 'data', ( file ) => { + bar.total = files.push( file ); + } ); onFileComplete = () => { bar.tick(); @@ -154,27 +143,29 @@ let ended = false, complete = 0; stream - .on( 'data', ( file ) => worker( file, ( error ) => { - onFileComplete(); - - if ( error ) { - // If an error occurs, the process can't be ended immediately since - // other workers are likely pending. Optimally, it would end at the - // earliest opportunity (after the current round of workers has had - // the chance to complete), but this is not made directly possible - // through `worker-farm`. Instead, ensure at least that when the - // process does exit, it exits with a non-zero code to reflect the - // fact that an error had occurred. - process.exitCode = 1; - - console.error( error ); - } - - if ( ended && ++complete === files.length ) { - workerFarm.end( worker ); - } - } ) ) - .on( 'end', () => ended = true ) + .on( 'data', ( file ) => + worker( file, ( error ) => { + onFileComplete(); + + if ( error ) { + // If an error occurs, the process can't be ended immediately since + // other workers are likely pending. Optimally, it would end at the + // earliest opportunity (after the current round of workers has had + // the chance to complete), but this is not made directly possible + // through `worker-farm`. Instead, ensure at least that when the + // process does exit, it exits with a non-zero code to reflect the + // fact that an error had occurred. + process.exitCode = 1; + + console.error( error ); + } + + if ( ended && ++complete === files.length ) { + workerFarm.end( worker ); + } + } ) + ) + .on( 'end', () => ( ended = true ) ) .resume(); /* eslint-enable no-console */ diff --git a/bin/packages/get-babel-config.js b/bin/packages/get-babel-config.js index d76e171d46b214..3df510f1ac1066 100644 --- a/bin/packages/get-babel-config.js +++ b/bin/packages/get-babel-config.js @@ -6,9 +6,11 @@ module.exports = function( environment = '', file ) { * The caller options can only be 'boolean', 'string', or 'number' by design: * https://github.com/babel/babel/blob/bd0c62dc0c30cf16a4d4ef0ddf21d386f673815c/packages/babel-core/src/config/validation/option-assertions.js#L122 */ - const callerOpts = { caller: { - name: `WP_BUILD_${ environment.toUpperCase() }`, - } }; + const callerOpts = { + caller: { + name: `WP_BUILD_${ environment.toUpperCase() }`, + }, + }; switch ( environment ) { case 'main': // to be merged as a presetEnv option diff --git a/bin/packages/watch.js b/bin/packages/watch.js index b307029dcd568f..8518e66f3a2a83 100644 --- a/bin/packages/watch.js +++ b/bin/packages/watch.js @@ -27,7 +27,12 @@ const exists = ( filename ) => { // and files with a suffix of .test or .spec (e.g. blocks.test.js), // and deceitful source-like files, such as editor swap files. const isSourceFile = ( filename ) => { - return ! [ /\/(benchmark|__mocks__|__tests__|test|storybook|stories)\/.+.js$/, /.\.(spec|test)\.js$/ ].some( ( regex ) => regex.test( filename ) ) && /.\.(js|json|scss)$/.test( filename ); + return ( + ! [ + /\/(benchmark|__mocks__|__tests__|test|storybook|stories)\/.+.js$/, + /.\.(spec|test)\.js$/, + ].some( ( regex ) => regex.test( filename ) ) && /.\.(js|json|scss)$/.test( filename ) + ); }; const rebuild = ( filename ) => filesToBuild.set( filename, true ); @@ -42,7 +47,7 @@ getPackages().forEach( ( p ) => { } const filePath = path.resolve( srcDir, filename ); - if ( ( event === 'update' ) && exists( filePath ) ) { + if ( event === 'update' && exists( filePath ) ) { // eslint-disable-next-line no-console console.log( chalk.green( '->' ), `${ event }: ${ filename }` ); rebuild( filePath ); @@ -52,9 +57,9 @@ getPackages().forEach( ( p ) => { fs.unlinkSync( buildFile ); process.stdout.write( chalk.red( ' \u2022 ' ) + - path.relative( path.resolve( srcDir, '..', '..' ), buildFile ) + - ' (deleted)' + - '\n' + path.relative( path.resolve( srcDir, '..', '..' ), buildFile ) + + ' (deleted)' + + '\n' ); } catch ( e ) {} } diff --git a/bin/process-git-diff.js b/bin/process-git-diff.js index b80b117daa59e4..6505954143e332 100644 --- a/bin/process-git-diff.js +++ b/bin/process-git-diff.js @@ -28,7 +28,10 @@ const hasNonOptionalDiff = !! ( process.argv[ 2 ] || '' ) // Strip individual diffs of optional-only. .replace( /@@ .+ @@\n(-.+\n\+.+,\n)?\+.+\"optional\": true,?\n/gm, '' ) // If no more line diffs remain after above, remove diff heading for file. - .replace( /diff --git a\/package-lock.json b\/package-lock.json\nindex \w+..\w+ \d+\n--- a\/package-lock.json\n\+\+\+ b\/package-lock.json\n(?!@@)/, '' ); + .replace( + /diff --git a\/package-lock.json b\/package-lock.json\nindex \w+..\w+ \d+\n--- a\/package-lock.json\n\+\+\+ b\/package-lock.json\n(?!@@)/, + '' + ); // Exit with error code if, after replace, changes still exist. process.exit( hasNonOptionalDiff ? 1 : 0 ); diff --git a/bin/update-readmes.js b/bin/update-readmes.js index df420007de3970..288f4774b1063c 100755 --- a/bin/update-readmes.js +++ b/bin/update-readmes.js @@ -13,10 +13,13 @@ const packages = [ 'block-serialization-default-parser', 'blocks', 'compose', - [ 'core-data', { - 'Autogenerated actions': 'src/actions.js', - 'Autogenerated selectors': 'src/selectors.js', - } ], + [ + 'core-data', + { + 'Autogenerated actions': 'src/actions.js', + 'Autogenerated selectors': 'src/selectors.js', + }, + ], 'data', 'data-controls', 'date', @@ -59,7 +62,7 @@ packages.forEach( ( entry ) => { `--use-token "${ token }"`, '--ignore "/unstable|experimental/i"', ], - { shell: true }, + { shell: true } ); if ( status !== 0 ) { diff --git a/docs/tool/index.js b/docs/tool/index.js index cd0e8223f9a6b7..074162266c364c 100644 --- a/docs/tool/index.js +++ b/docs/tool/index.js @@ -18,4 +18,7 @@ const manifestOutput = path.resolve( __dirname, '../manifest-devhub.json' ); execFileSync( 'node', [ join( __dirname, 'update-data.js' ) ] ); // Process TOC file and generate manifest handbook -fs.writeFileSync( manifestOutput, JSON.stringify( getRootManifest( tocFileInput ), undefined, '\t' ) ); +fs.writeFileSync( + manifestOutput, + JSON.stringify( getRootManifest( tocFileInput ), undefined, '\t' ) +); diff --git a/docs/tool/update-data.js b/docs/tool/update-data.js index 59a45ac4d599b7..8cba8d9288603f 100644 --- a/docs/tool/update-data.js +++ b/docs/tool/update-data.js @@ -5,10 +5,13 @@ const { join } = require( 'path' ); const spawnSync = require( 'child_process' ).spawnSync; const modules = [ - [ 'core', { - 'Autogenerated actions': 'packages/core-data/src/actions.js', - 'Autogenerated selectors': 'packages/core-data/src/selectors.js', - } ], + [ + 'core', + { + 'Autogenerated actions': 'packages/core-data/src/actions.js', + 'Autogenerated selectors': 'packages/core-data/src/selectors.js', + }, + ], 'core/annotations', 'core/blocks', 'core/block-editor', @@ -21,10 +24,16 @@ const modules = [ modules.forEach( ( entry ) => { if ( ! Array.isArray( entry ) ) { - entry = [ entry, { - 'Autogenerated actions': `packages/${ entry.replace( 'core/', '' ) }/src/store/actions.js`, - 'Autogenerated selectors': `packages/${ entry.replace( 'core/', '' ) }/src/store/selectors.js`, - } ]; + entry = [ + entry, + { + 'Autogenerated actions': `packages/${ entry.replace( 'core/', '' ) }/src/store/actions.js`, + 'Autogenerated selectors': `packages/${ entry.replace( + 'core/', + '' + ) }/src/store/selectors.js`, + }, + ]; } const [ namespace, targets ] = entry; @@ -36,12 +45,15 @@ modules.forEach( ( entry ) => { join( __dirname, '..', '..', 'node_modules', '.bin', 'docgen' ), [ target, - `--output docs/designers-developers/developers/data/data-${ namespace.replace( '/', '-' ) }.md`, + `--output docs/designers-developers/developers/data/data-${ namespace.replace( + '/', + '-' + ) }.md`, '--to-token', `--use-token "${ token }"`, '--ignore "/unstable|experimental/i"', ], - { shell: true }, + { shell: true } ); if ( status !== 0 ) { diff --git a/packages/a11y/src/addContainer.js b/packages/a11y/src/addContainer.js index 38fa59001ec305..cb9e069082a315 100644 --- a/packages/a11y/src/addContainer.js +++ b/packages/a11y/src/addContainer.js @@ -12,19 +12,20 @@ const addContainer = function( ariaLive ) { container.id = 'a11y-speak-' + ariaLive; container.className = 'a11y-speak-region'; - container.setAttribute( 'style', ( + container.setAttribute( + 'style', 'position: absolute;' + - 'margin: -1px;' + - 'padding: 0;' + - 'height: 1px;' + - 'width: 1px;' + - 'overflow: hidden;' + - 'clip: rect(1px, 1px, 1px, 1px);' + - '-webkit-clip-path: inset(50%);' + - 'clip-path: inset(50%);' + - 'border: 0;' + - 'word-wrap: normal !important;' - ) ); + 'margin: -1px;' + + 'padding: 0;' + + 'height: 1px;' + + 'width: 1px;' + + 'overflow: hidden;' + + 'clip: rect(1px, 1px, 1px, 1px);' + + '-webkit-clip-path: inset(50%);' + + 'clip-path: inset(50%);' + + 'border: 0;' + + 'word-wrap: normal !important;' + ); container.setAttribute( 'aria-live', ariaLive ); container.setAttribute( 'aria-relevant', 'additions text' ); container.setAttribute( 'aria-atomic', 'true' ); diff --git a/packages/a11y/src/index.native.js b/packages/a11y/src/index.native.js index b972687dbafce3..4e5e9841118b17 100644 --- a/packages/a11y/src/index.native.js +++ b/packages/a11y/src/index.native.js @@ -14,8 +14,6 @@ export const speak = function( message, ariaLive ) { message = filterMessage( message ); //TODO: Use native module to speak message if ( 'assertive' === ariaLive ) { - } else { - } }; diff --git a/packages/annotations/src/block/index.js b/packages/annotations/src/block/index.js index e2677bbf6a9b3a..31c1a57e261ab1 100644 --- a/packages/annotations/src/block/index.js +++ b/packages/annotations/src/block/index.js @@ -12,12 +12,16 @@ import { withSelect } from '@wordpress/data'; */ const addAnnotationClassName = ( OriginalComponent ) => { return withSelect( ( select, { clientId } ) => { - const annotations = select( 'core/annotations' ).__experimentalGetAnnotationsForBlock( clientId ); + const annotations = select( 'core/annotations' ).__experimentalGetAnnotationsForBlock( + clientId + ); return { - className: annotations.map( ( annotation ) => { - return 'is-annotated-by-' + annotation.source; - } ).join( ' ' ), + className: annotations + .map( ( annotation ) => { + return 'is-annotated-by-' + annotation.source; + } ) + .join( ' ' ), }; } )( OriginalComponent ); }; diff --git a/packages/annotations/src/format/annotation.js b/packages/annotations/src/format/annotation.js index 46dd6e279fa3ba..ba9a39633d84e4 100644 --- a/packages/annotations/src/format/annotation.js +++ b/packages/annotations/src/format/annotation.js @@ -34,7 +34,8 @@ export function applyAnnotations( record, annotations = [] ) { record = applyFormat( record, { - type: FORMAT_NAME, attributes: { + type: FORMAT_NAME, + attributes: { className, id, }, @@ -98,7 +99,11 @@ function retrieveAnnotationPositions( formats ) { * @param {Function} actions.removeAnnotation Function to remove an annotation from the state. * @param {Function} actions.updateAnnotationRange Function to update an annotation range in the state. */ -function updateAnnotationsWithPositions( annotations, positions, { removeAnnotation, updateAnnotationRange } ) { +function updateAnnotationsWithPositions( + annotations, + positions, + { removeAnnotation, updateAnnotationRange } +) { annotations.forEach( ( currentAnnotation ) => { const position = positions[ currentAnnotation.id ]; // If we cannot find an annotation, delete it. @@ -128,9 +133,15 @@ export const annotation = { edit() { return null; }, - __experimentalGetPropsForEditableTreePreparation( select, { richTextIdentifier, blockClientId } ) { + __experimentalGetPropsForEditableTreePreparation( + select, + { richTextIdentifier, blockClientId } + ) { return { - annotations: select( STORE_KEY ).__experimentalGetAnnotationsForRichText( blockClientId, richTextIdentifier ), + annotations: select( STORE_KEY ).__experimentalGetAnnotationsForRichText( + blockClientId, + richTextIdentifier + ), }; }, __experimentalCreatePrepareEditableTree( { annotations } ) { @@ -155,7 +166,10 @@ export const annotation = { const positions = retrieveAnnotationPositions( formats ); const { removeAnnotation, updateAnnotationRange, annotations } = props; - updateAnnotationsWithPositions( annotations, positions, { removeAnnotation, updateAnnotationRange } ); + updateAnnotationsWithPositions( annotations, positions, { + removeAnnotation, + updateAnnotationRange, + } ); }; }, }; diff --git a/packages/annotations/src/format/index.js b/packages/annotations/src/format/index.js index 1dccbbd5012a0c..e41c5640cc8c83 100644 --- a/packages/annotations/src/format/index.js +++ b/packages/annotations/src/format/index.js @@ -1,9 +1,7 @@ /** * WordPress dependencies */ -import { - registerFormatType, -} from '@wordpress/rich-text'; +import { registerFormatType } from '@wordpress/rich-text'; /** * Internal dependencies diff --git a/packages/annotations/src/index.js b/packages/annotations/src/index.js index ce64106bf903cf..9435b1d8616616 100644 --- a/packages/annotations/src/index.js +++ b/packages/annotations/src/index.js @@ -4,4 +4,3 @@ import './store'; import './format'; import './block'; - diff --git a/packages/annotations/src/store/actions.js b/packages/annotations/src/store/actions.js index 8135ca3e32066b..7ad35afa99b295 100644 --- a/packages/annotations/src/store/actions.js +++ b/packages/annotations/src/store/actions.js @@ -25,7 +25,14 @@ import uuid from 'uuid/v4'; * * @return {Object} Action object. */ -export function __experimentalAddAnnotation( { blockClientId, richTextIdentifier = null, range = null, selector = 'range', source = 'default', id = uuid() } ) { +export function __experimentalAddAnnotation( { + blockClientId, + richTextIdentifier = null, + range = null, + selector = 'range', + source = 'default', + id = uuid(), +} ) { const action = { type: 'ANNOTATION_ADD', id, diff --git a/packages/annotations/src/store/reducer.js b/packages/annotations/src/store/reducer.js index 1f768a78ad2157..2fcd95118e45b4 100644 --- a/packages/annotations/src/store/reducer.js +++ b/packages/annotations/src/store/reducer.js @@ -25,9 +25,9 @@ function filterWithReference( collection, predicate ) { * @return {boolean} Whether the given annotation is valid. */ function isValidAnnotationRange( annotation ) { - return isNumber( annotation.start ) && - isNumber( annotation.end ) && - annotation.start <= annotation.end; + return ( + isNumber( annotation.start ) && isNumber( annotation.end ) && annotation.start <= annotation.end + ); } /** diff --git a/packages/annotations/src/store/selectors.js b/packages/annotations/src/store/selectors.js index a39a315c92f907..8a3a34715a6310 100644 --- a/packages/annotations/src/store/selectors.js +++ b/packages/annotations/src/store/selectors.js @@ -29,9 +29,7 @@ export const __experimentalGetAnnotationsForBlock = createSelector( return annotation.selector === 'block'; } ); }, - ( state, blockClientId ) => [ - get( state, blockClientId, EMPTY_ARRAY ), - ] + ( state, blockClientId ) => [ get( state, blockClientId, EMPTY_ARRAY ) ] ); export const __experimentalGetAllAnnotationsForBlock = function( state, blockClientId ) { @@ -52,21 +50,22 @@ export const __experimentalGetAllAnnotationsForBlock = function( state, blockCli */ export const __experimentalGetAnnotationsForRichText = createSelector( ( state, blockClientId, richTextIdentifier ) => { - return get( state, blockClientId, [] ).filter( ( annotation ) => { - return annotation.selector === 'range' && - richTextIdentifier === annotation.richTextIdentifier; - } ).map( ( annotation ) => { - const { range, ...other } = annotation; + return get( state, blockClientId, [] ) + .filter( ( annotation ) => { + return ( + annotation.selector === 'range' && richTextIdentifier === annotation.richTextIdentifier + ); + } ) + .map( ( annotation ) => { + const { range, ...other } = annotation; - return { - ...range, - ...other, - }; - } ); + return { + ...range, + ...other, + }; + } ); }, - ( state, blockClientId ) => [ - get( state, blockClientId, EMPTY_ARRAY ), - ] + ( state, blockClientId ) => [ get( state, blockClientId, EMPTY_ARRAY ) ] ); /** diff --git a/packages/annotations/src/store/test/reducer.js b/packages/annotations/src/store/test/reducer.js index 190795bd8a98cf..0e9c62a93adc4d 100644 --- a/packages/annotations/src/store/test/reducer.js +++ b/packages/annotations/src/store/test/reducer.js @@ -23,18 +23,6 @@ describe( 'annotations', () => { } ); expect( state ).toEqual( { - blockClientId: [ { - id: 'annotationId', - blockClientId: 'blockClientId', - richTextIdentifier: 'identifier', - source: 'default', - selector: 'block', - } ], - } ); - } ); - - it( 'allows an annotation to be removed', () => { - const state = annotations( { blockClientId: [ { id: 'annotationId', @@ -44,10 +32,27 @@ describe( 'annotations', () => { selector: 'block', }, ], - }, { - type: 'ANNOTATION_REMOVE', - annotationId: 'annotationId', } ); + } ); + + it( 'allows an annotation to be removed', () => { + const state = annotations( + { + blockClientId: [ + { + id: 'annotationId', + blockClientId: 'blockClientId', + richTextIdentifier: 'identifier', + source: 'default', + selector: 'block', + }, + ], + }, + { + type: 'ANNOTATION_REMOVE', + annotationId: 'annotationId', + } + ); expect( state ).toEqual( { blockClientId: [] } ); } ); @@ -67,17 +72,16 @@ describe( 'annotations', () => { source: 'other-source', selector: 'block', }; - const state = annotations( { - blockClientId: [ - annotation1, - ], - blockClientId2: [ - annotation2, - ], - }, { - type: 'ANNOTATION_REMOVE_SOURCE', - source: 'default', - } ); + const state = annotations( + { + blockClientId: [ annotation1 ], + blockClientId2: [ annotation2 ], + }, + { + type: 'ANNOTATION_REMOVE_SOURCE', + source: 'default', + } + ); expect( state ).toEqual( { blockClientId: [], @@ -117,26 +121,29 @@ describe( 'annotations', () => { } ); it( 'moves annotations when said action is dispatched', () => { - const state = annotations( { - blockClientId: [ - { - id: 'annotationId', - blockClientId: 'blockClientId', - richTextIdentifier: 'identifier', - source: 'default', - selector: 'range', - range: { - start: 0, - end: 100, + const state = annotations( + { + blockClientId: [ + { + id: 'annotationId', + blockClientId: 'blockClientId', + richTextIdentifier: 'identifier', + source: 'default', + selector: 'range', + range: { + start: 0, + end: 100, + }, }, - }, - ], - }, { - type: 'ANNOTATION_UPDATE_RANGE', - annotationId: 'annotationId', - start: 50, - end: 75, - } ); + ], + }, + { + type: 'ANNOTATION_UPDATE_RANGE', + annotationId: 'annotationId', + start: 50, + end: 75, + } + ); expect( state ).toEqual( { blockClientId: [ diff --git a/packages/api-fetch/src/index.js b/packages/api-fetch/src/index.js index dc7dda91fa1e60..aeb794fb9c19be 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -67,15 +67,12 @@ const defaultFetchHandler = ( nextOptions ) => { headers[ 'Content-Type' ] = 'application/json'; } - const responsePromise = window.fetch( - url || path, - { - ...DEFAULT_OPTIONS, - ...remainingOptions, - body, - headers, - } - ); + const responsePromise = window.fetch( url || path, { + ...DEFAULT_OPTIONS, + ...remainingOptions, + body, + headers, + } ); return responsePromise .then( checkStatus ) @@ -117,7 +114,8 @@ function apiFetch( options ) { } // If the nonce is invalid, refresh it and try again. - window.fetch( apiFetch.nonceEndpoint ) + window + .fetch( apiFetch.nonceEndpoint ) .then( checkStatus ) .then( ( data ) => data.text() ) .then( ( text ) => { diff --git a/packages/api-fetch/src/index.native.js b/packages/api-fetch/src/index.native.js index 802ac8f7c42aea..8d0a4012ffc320 100644 --- a/packages/api-fetch/src/index.native.js +++ b/packages/api-fetch/src/index.native.js @@ -1,4 +1,3 @@ - function apiFetch( options ) { // eslint-disable-next-line no-console console.warn( 'apiFetch called with options', options ); diff --git a/packages/api-fetch/src/middlewares/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/fetch-all-middleware.js index 5bc17b5413d326..f0ef36977d6c2c 100644 --- a/packages/api-fetch/src/middlewares/fetch-all-middleware.js +++ b/packages/api-fetch/src/middlewares/fetch-all-middleware.js @@ -11,18 +11,19 @@ const modifyQuery = ( { path, url, ...options }, queryArgs ) => ( { } ); // Duplicates parsing functionality from apiFetch. -const parseResponse = ( response ) => response.json ? - response.json() : - Promise.reject( response ); +const parseResponse = ( response ) => + response.json ? response.json() : Promise.reject( response ); const parseLinkHeader = ( linkHeader ) => { if ( ! linkHeader ) { return {}; } const match = linkHeader.match( /<([^>]+)>; rel="next"/ ); - return match ? { - next: match[ 1 ], - } : {}; + return match + ? { + next: match[ 1 ], + } + : {}; }; const getNextPageUrl = ( response ) => { diff --git a/packages/api-fetch/src/middlewares/http-v1.js b/packages/api-fetch/src/middlewares/http-v1.js index d7771bf6f9b1c2..87304712e4b218 100644 --- a/packages/api-fetch/src/middlewares/http-v1.js +++ b/packages/api-fetch/src/middlewares/http-v1.js @@ -3,11 +3,7 @@ * * @type {Set} */ -const OVERRIDE_METHODS = new Set( [ - 'PATCH', - 'PUT', - 'DELETE', -] ); +const OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] ); /** * Default request method. diff --git a/packages/api-fetch/src/middlewares/media-upload.js b/packages/api-fetch/src/middlewares/media-upload.js index b7a14d6b5b050a..6cc7c363648fd7 100644 --- a/packages/api-fetch/src/middlewares/media-upload.js +++ b/packages/api-fetch/src/middlewares/media-upload.js @@ -6,10 +6,7 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { - parseAndThrowError, - parseResponseAndNormalizeError, -} from '../utils/response'; +import { parseAndThrowError, parseResponseAndNormalizeError } from '../utils/response'; /** * Middleware handling media upload failures and retries. @@ -37,18 +34,17 @@ function mediaUploadMiddleware( options, next ) { method: 'POST', data: { action: 'create-image-subsizes' }, parse: false, - } ) - .catch( () => { - if ( retries < maxRetries ) { - return postProcess( attachmentId ); - } - next( { - path: `/wp/v2/media/${ attachmentId }?force=true`, - method: 'DELETE', - } ); - - return Promise.reject(); + } ).catch( () => { + if ( retries < maxRetries ) { + return postProcess( attachmentId ); + } + next( { + path: `/wp/v2/media/${ attachmentId }?force=true`, + method: 'DELETE', } ); + + return Promise.reject(); + } ); }; return next( { ...options, parse: false } ) @@ -59,7 +55,9 @@ function mediaUploadMiddleware( options, next ) { if ( options.parse !== false ) { return Promise.reject( { code: 'post_process', - message: __( 'Media upload failed. If this is a photo or a large image, please scale it down and try again.' ), + message: __( + 'Media upload failed. If this is a photo or a large image, please scale it down and try again.' + ), } ); } diff --git a/packages/api-fetch/src/middlewares/namespace-endpoint.js b/packages/api-fetch/src/middlewares/namespace-endpoint.js index c6ee6c67b4afbb..ef24a3dea93120 100644 --- a/packages/api-fetch/src/middlewares/namespace-endpoint.js +++ b/packages/api-fetch/src/middlewares/namespace-endpoint.js @@ -2,10 +2,7 @@ const namespaceAndEndpointMiddleware = ( options, next ) => { let path = options.path; let namespaceTrimmed, endpointTrimmed; - if ( - typeof options.namespace === 'string' && - typeof options.endpoint === 'string' - ) { + if ( typeof options.namespace === 'string' && typeof options.endpoint === 'string' ) { namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' ); endpointTrimmed = options.endpoint.replace( /^\//, '' ); if ( endpointTrimmed ) { diff --git a/packages/api-fetch/src/middlewares/preloading.js b/packages/api-fetch/src/middlewares/preloading.js index 4de356243b7366..9fa328ab72ea32 100644 --- a/packages/api-fetch/src/middlewares/preloading.js +++ b/packages/api-fetch/src/middlewares/preloading.js @@ -8,23 +8,27 @@ const createPreloadingMiddleware = ( preloadedData ) => ( options, next ) => { } // 'b=1&c=2&a=5' - return base + '?' + query - // [ 'b=1', 'c=2', 'a=5' ] - .split( '&' ) - // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ] - .map( function( entry ) { - return entry.split( '=' ); - } ) - // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ] - .sort( function( a, b ) { - return a[ 0 ].localeCompare( b[ 0 ] ); - } ) - // [ 'a=5', 'b=1', 'c=2' ] - .map( function( pair ) { - return pair.join( '=' ); - } ) - // 'a=5&b=1&c=2' - .join( '&' ); + return ( + base + + '?' + + query + // [ 'b=1', 'c=2', 'a=5' ] + .split( '&' ) + // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ] + .map( function( entry ) { + return entry.split( '=' ); + } ) + // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ] + .sort( function( a, b ) { + return a[ 0 ].localeCompare( b[ 0 ] ); + } ) + // [ 'a=5', 'b=1', 'c=2' ] + .map( function( pair ) { + return pair.join( '=' ); + } ) + // 'a=5&b=1&c=2' + .join( '&' ) + ); } const { parse = true } = options; diff --git a/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js index b73eeba15e14b9..f0b2c035a646ab 100644 --- a/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js +++ b/packages/api-fetch/src/middlewares/test/fetch-all-middleware.js @@ -29,9 +29,9 @@ describe( 'Fetch All Middleware', () => { status: 200, headers: { get() { - return options.url === '/posts?per_page=100' ? - '; rel="next"' : - ''; + return options.url === '/posts?per_page=100' + ? '; rel="next"' + : ''; }, }, json() { diff --git a/packages/api-fetch/src/middlewares/test/preloading.js b/packages/api-fetch/src/middlewares/test/preloading.js index e2d8a1f4d0c68d..b3e50f049b6b0e 100644 --- a/packages/api-fetch/src/middlewares/test/preloading.js +++ b/packages/api-fetch/src/middlewares/test/preloading.js @@ -25,29 +25,26 @@ describe( 'Preloading Middleware', () => { } ); } ); - describe.each( [ - [ 'GET' ], - [ 'OPTIONS' ], - ] )( '%s', ( method ) => { - describe.each( [ - [ 'all empty', {} ], - [ 'method empty', { [ method ]: {} } ], - ] )( '%s', ( label, preloadedData ) => { - it( 'should move to the next middleware if no preloaded data', () => { - const prelooadingMiddleware = createPreloadingMiddleware( preloadedData ); - const requestOptions = { - method, - path: 'wp/v2/posts', - }; + describe.each( [ [ 'GET' ], [ 'OPTIONS' ] ] )( '%s', ( method ) => { + describe.each( [ [ 'all empty', {} ], [ 'method empty', { [ method ]: {} } ] ] )( + '%s', + ( label, preloadedData ) => { + it( 'should move to the next middleware if no preloaded data', () => { + const prelooadingMiddleware = createPreloadingMiddleware( preloadedData ); + const requestOptions = { + method, + path: 'wp/v2/posts', + }; - const callback = ( options ) => { - expect( options ).toBe( requestOptions ); - return true; - }; + const callback = ( options ) => { + expect( options ).toBe( requestOptions ); + return true; + }; - const ret = prelooadingMiddleware( requestOptions, callback ); - expect( ret ).toBe( true ); - } ); - } ); + const ret = prelooadingMiddleware( requestOptions, callback ); + expect( ret ).toBe( true ); + } ); + } + ); } ); } ); diff --git a/packages/api-fetch/src/test/index.js b/packages/api-fetch/src/test/index.js index 1becd96d965769..7a951abd17e5f8 100644 --- a/packages/api-fetch/src/test/index.js +++ b/packages/api-fetch/src/test/index.js @@ -25,12 +25,14 @@ describe( 'apiFetch', () => { } ); it( 'should call the API properly', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 200, - json() { - return Promise.resolve( { message: 'ok' } ); - }, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 200, + json() { + return Promise.resolve( { message: 'ok' } ); + }, + } ) + ); return apiFetch( { path: '/random' } ).then( ( body ) => { expect( body ).toEqual( { message: 'ok' } ); @@ -103,15 +105,17 @@ describe( 'apiFetch', () => { } ); it( 'should return the error message properly', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 400, - json() { - return Promise.resolve( { - code: 'bad_request', - message: 'Bad Request', - } ); - }, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 400, + json() { + return Promise.resolve( { + code: 'bad_request', + message: 'Bad Request', + } ); + }, + } ) + ); return apiFetch( { path: '/random' } ).catch( ( body ) => { expect( body ).toEqual( { @@ -122,9 +126,11 @@ describe( 'apiFetch', () => { } ); it( 'should return invalid JSON error if no json response', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 200, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 200, + } ) + ); return apiFetch( { path: '/random' } ).catch( ( body ) => { expect( body ).toEqual( { @@ -135,12 +141,14 @@ describe( 'apiFetch', () => { } ); it( 'should return invalid JSON error if response is not valid', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 200, - json() { - return Promise.reject(); - }, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 200, + json() { + return Promise.reject(); + }, + } ) + ); return apiFetch( { path: '/random' } ).catch( ( body ) => { expect( body ).toEqual( { @@ -151,9 +159,11 @@ describe( 'apiFetch', () => { } ); it( 'should return null if response has no content status code', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 204, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 204, + } ) + ); return apiFetch( { path: '/random' } ).catch( ( body ) => { expect( body ).toEqual( null ); @@ -161,9 +171,11 @@ describe( 'apiFetch', () => { } ); it( 'should not try to parse the response', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 200, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 200, + } ) + ); return apiFetch( { path: '/random', parse: false } ).then( ( response ) => { expect( response ).toEqual( { @@ -173,9 +185,11 @@ describe( 'apiFetch', () => { } ); it( 'should not try to parse the error', () => { - window.fetch.mockReturnValue( Promise.resolve( { - status: 400, - } ) ); + window.fetch.mockReturnValue( + Promise.resolve( { + status: 400, + } ) + ); return apiFetch( { path: '/random', parse: false } ).catch( ( response ) => { expect( response ).toEqual( { diff --git a/packages/api-fetch/src/utils/response.js b/packages/api-fetch/src/utils/response.js index bb7b79ce2f8254..518a7fd5e66f81 100644 --- a/packages/api-fetch/src/utils/response.js +++ b/packages/api-fetch/src/utils/response.js @@ -33,10 +33,9 @@ const parseJsonAndNormalizeError = ( response ) => { throw invalidJsonError; } - return response.json() - .catch( () => { - throw invalidJsonError; - } ); + return response.json().catch( () => { + throw invalidJsonError; + } ); }; /** @@ -48,8 +47,9 @@ const parseJsonAndNormalizeError = ( response ) => { * @return {Promise} Parsed response. */ export const parseResponseAndNormalizeError = ( response, shouldParseResponse = true ) => { - return Promise.resolve( parseResponse( response, shouldParseResponse ) ) - .catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) ); + return Promise.resolve( parseResponse( response, shouldParseResponse ) ).catch( ( res ) => + parseAndThrowError( res, shouldParseResponse ) + ); }; export function parseAndThrowError( response, shouldParseResponse = true ) { @@ -57,14 +57,12 @@ export function parseAndThrowError( response, shouldParseResponse = true ) { throw response; } - return parseJsonAndNormalizeError( response ) - .then( ( error ) => { - const unknownError = { - code: 'unknown_error', - message: __( 'An unknown error occurred.' ), - }; + return parseJsonAndNormalizeError( response ).then( ( error ) => { + const unknownError = { + code: 'unknown_error', + message: __( 'An unknown error occurred.' ), + }; - throw error || unknownError; - } ); + throw error || unknownError; + } ); } - diff --git a/packages/autop/src/index.js b/packages/autop/src/index.js index 1225d5c6637d8c..32512f62094eca 100644 --- a/packages/autop/src/index.js +++ b/packages/autop/src/index.js @@ -6,42 +6,42 @@ const htmlSplitRegex = ( () => { /* eslint-disable no-multi-spaces */ const comments = - '!' + // Start of comment, after the <. - '(?:' + // Unroll the loop: Consume everything until --> is found. - '-(?!->)' + // Dash not followed by end of comment. - '[^\\-]*' + // Consume non-dashes. - ')*' + // Loop possessively. - '(?:-->)?'; // End of comment. If not found, match all input. + '!' + // Start of comment, after the <. + '(?:' + // Unroll the loop: Consume everything until --> is found. + '-(?!->)' + // Dash not followed by end of comment. + '[^\\-]*' + // Consume non-dashes. + ')*' + // Loop possessively. + '(?:-->)?'; // End of comment. If not found, match all input. const cdata = '!\\[CDATA\\[' + // Start of comment, after the <. - '[^\\]]*' + // Consume non-]. - '(?:' + // Unroll the loop: Consume everything until ]]> is found. - '](?!]>)' + // One ] not followed by end of comment. - '[^\\]]*' + // Consume non-]. - ')*?' + // Loop possessively. - '(?:]]>)?'; // End of comment. If not found, match all input. + '[^\\]]*' + // Consume non-]. + '(?:' + // Unroll the loop: Consume everything until ]]> is found. + '](?!]>)' + // One ] not followed by end of comment. + '[^\\]]*' + // Consume non-]. + ')*?' + // Loop possessively. + '(?:]]>)?'; // End of comment. If not found, match all input. const escaped = - '(?=' + // Is the element escaped? - '!--' + + '(?=' + // Is the element escaped? + '!--' + '|' + - '!\\[CDATA\\[' + + '!\\[CDATA\\[' + ')' + - '((?=!-)' + // If yes, which type? - comments + + '((?=!-)' + // If yes, which type? + comments + '|' + - cdata + + cdata + ')'; const regex = - '(' + // Capture the entire match. - '<' + // Find start of element. - '(' + // Conditional expression follows. - escaped + // Find end of escaped element. - '|' + // ... else ... - '[^>]*>?' + // Find end of normal element. - ')' + + '(' + // Capture the entire match. + '<' + // Find start of element. + '(' + // Conditional expression follows. + escaped + // Find end of escaped element. + '|' + // ... else ... + '[^>]*>?' + // Find end of normal element. + ')' + ')'; return new RegExp( regex ); @@ -166,13 +166,14 @@ export function autop( text, br = true ) { // Change multiple
s into two line breaks, which will turn into paragraphs. text = text.replace( /\s*/g, '\n\n' ); - const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; + const allBlocks = + '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags. - text = text.replace( new RegExp( '(<' + allBlocks + '[\\s\/>])', 'g' ), '\n\n$1' ); + text = text.replace( new RegExp( '(<' + allBlocks + '[\\s/>])', 'g' ), '\n\n$1' ); // Add a double line break below block-level closing tags. - text = text.replace( new RegExp( '(<\/' + allBlocks + '>)', 'g' ), '$1\n\n' ); + text = text.replace( new RegExp( '()', 'g' ), '$1\n\n' ); // Standardize newline characters to "\n". text = text.replace( /\r\n|\r/g, '\n' ); @@ -233,7 +234,7 @@ export function autop( text, br = true ) { text = text.replace( /

([^<]+)<\/(div|address|form)>/g, '

$1

' ); // If an opening or closing block element tag is wrapped in a

, unwrap it. - text = text.replace( new RegExp( '

\\s*(<\/?' + allBlocks + '[^>]*>)\\s*<\/p>', 'g' ), '$1' ); + text = text.replace( new RegExp( '

\\s*(]*>)\\s*

', 'g' ), '$1' ); // In some cases
  • may get wrapped in

    , fix them. text = text.replace( /

    (/g, '$1' ); @@ -243,28 +244,30 @@ export function autop( text, br = true ) { text = text.replace( /<\/blockquote><\/p>/g, '

    ' ); // If an opening or closing block element tag is preceded by an opening

    tag, remove it. - text = text.replace( new RegExp( '

    \\s*(<\/?' + allBlocks + '[^>]*>)', 'g' ), '$1' ); + text = text.replace( new RegExp( '

    \\s*(]*>)', 'g' ), '$1' ); // If an opening or closing block element tag is followed by a closing

    tag, remove it. - text = text.replace( new RegExp( '(<\/?' + allBlocks + '[^>]*>)\\s*<\/p>', 'g' ), '$1' ); + text = text.replace( new RegExp( '(]*>)\\s*

    ', 'g' ), '$1' ); // Optionally insert line breaks. if ( br ) { // Replace newlines that shouldn't be touched with a placeholder. - text = text.replace( /<(script|style).*?<\/\\1>/g, ( match ) => match[ 0 ].replace( /\n/g, '' ) ); + text = text.replace( /<(script|style).*?<\/\\1>/g, ( match ) => + match[ 0 ].replace( /\n/g, '' ) + ); // Normalize
    text = text.replace( /
    |/g, '
    ' ); // Replace any new line characters that aren't preceded by a
    with a
    . - text = text.replace( /(
    )?\s*\n/g, ( a, b ) => b ? a : '
    \n' ); + text = text.replace( /(
    )?\s*\n/g, ( a, b ) => ( b ? a : '
    \n' ) ); // Replace newline placeholders with newlines. text = text.replace( //g, '\n' ); } // If a
    tag is after an opening or closing block tag, remove it. - text = text.replace( new RegExp( '(<\/?' + allBlocks + '[^>]*>)\\s*
    ', 'g' ), '$1' ); + text = text.replace( new RegExp( '(]*>)\\s*
    ', 'g' ), '$1' ); // If a
    tag is before a subset of opening or closing block tags, remove it. text = text.replace( /
    (\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, '$1' ); @@ -301,7 +304,8 @@ export function autop( text, br = true ) { * @return {string} The content with stripped paragraph tags. */ export function removep( html ) { - const blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure'; + const blocklist = + 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure'; const blocklist1 = blocklist + '|div|p'; const blocklist2 = blocklist + '|pre'; const preserve = []; @@ -373,7 +377,10 @@ export function removep( html ) { html = html.replace( /caption\]\n\n+\[caption/g, 'caption]\n\n[caption' ); // Pad block elements tags with a line break. - html = html.replace( new RegExp( '\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), '\n<$1>' ); + html = html.replace( + new RegExp( '\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), + '\n<$1>' + ); html = html.replace( new RegExp( '\\s*\\s*', 'g' ), '\n' ); // Indent
  • ,
    and
    tags. diff --git a/packages/autop/src/test/index.test.js b/packages/autop/src/test/index.test.js index 8fc73f4e039651..02bffeab830dde 100644 --- a/packages/autop/src/test/index.test.js +++ b/packages/autop/src/test/index.test.js @@ -1,10 +1,7 @@ /** * Internal dependencies */ -import { - autop, - removep, -} from '../'; +import { autop, removep } from '../'; test( 'empty string', () => { expect( autop( '' ) ).toBe( '' ); @@ -81,13 +78,16 @@ done = 0; expect( autop( str ).trim() ).toBe( expected ); // Make sure HTML breaks are maintained if manually inserted - str = 'Look at this code\n\n
    Line1
    Line2
    Line3
    Line4\nActual Line 2\nActual Line 3
    \n\nCool, huh?'; - expected = '

    Look at this code

    \n
    Line1
    Line2
    Line3
    Line4\nActual Line 2\nActual Line 3
    \n

    Cool, huh?

    '; + str = + 'Look at this code\n\n
    Line1
    Line2
    Line3
    Line4\nActual Line 2\nActual Line 3
    \n\nCool, huh?'; + expected = + '

    Look at this code

    \n
    Line1
    Line2
    Line3
    Line4\nActual Line 2\nActual Line 3
    \n

    Cool, huh?

    '; expect( autop( str ).trim() ).toBe( expected ); } ); test( 'skip input elements', () => { - const str = 'Username:
    Password: '; + const str = + 'Username:
    Password: '; expect( autop( str ).trim() ).toBe( '

    ' + str + '

    ' ); } ); @@ -133,7 +133,8 @@ Paragraph two.`; Paragraph two.`; - const expected = '

    Paragraph one.

    \n' + // line breaks only after

    + const expected = + '

    Paragraph one.

    \n' + // line breaks only after

    '

    Paragraph one.

    \n' + // line breaks only after

    + const shortcodeExpected = + '

    Paragraph one.

    \n' + // line breaks only after

    '

    [video width="720" height="480" mp4="http://domain.tld/wp-content/uploads/2013/12/xyz.mp4"]' + '' + '' + @@ -193,7 +195,8 @@ test( 'param embed elements', () => { Paragraph two.`; - const expected1 = '

    Paragraph one.

    \n' + // line breaks only after

    + const expected1 = + '

    Paragraph one.

    \n' + // line breaks only after

    '

    ' + '' + '' + @@ -228,7 +231,8 @@ Paragraph two.`; Paragraph two.`; - const expected2 = '

    Paragraph one.

    \n' + // line breaks only after block tags + const expected2 = + '

    Paragraph one.

    \n' + // line breaks only after block tags '
    \n' + '' + '' + @@ -251,7 +255,8 @@ Paragraph two.`; } ); test( 'skip select option elements', () => { - const str = 'Country: '; + const str = + 'Country: '; expect( autop( str ).trim() ).toBe( '

    ' + str + '

    ' ); } ); @@ -399,14 +404,8 @@ test( 'that autop treats inline elements as inline', () => { test( 'element sanity', () => { [ - [ - 'Hello ', - '

    Hello

    \n', - ], - [ - 'Hello ', - '

    Hello

    \n', - ], + [ 'Hello ', '

    Hello

    \n' ], + [ 'Hello ', '

    Hello

    \n' ], [ 'Hello ', '

    Hello

    \n', diff --git a/packages/babel-plugin-makepot/src/index.js b/packages/babel-plugin-makepot/src/index.js index ad0cde941aecb8..6764c1ff822946 100644 --- a/packages/babel-plugin-makepot/src/index.js +++ b/packages/babel-plugin-makepot/src/index.js @@ -93,10 +93,7 @@ const REGEXP_TRANSLATOR_COMMENT = /^\s*translators:\s*([\s\S]+)/im; function getNodeAsString( node ) { switch ( node.type ) { case 'BinaryExpression': - return ( - getNodeAsString( node.left ) + - getNodeAsString( node.right ) - ); + return getNodeAsString( node.left ) + getNodeAsString( node.right ); case 'StringLiteral': return node.value; @@ -134,7 +131,10 @@ function getExtractedComment( path, _originalNodeLine ) { const match = commentNode.value.match( REGEXP_TRANSLATOR_COMMENT ); if ( match ) { // Extract text from matched translator prefix - comment = match[ 1 ].split( '\n' ).map( ( text ) => text.trim() ).join( ' ' ); + comment = match[ 1 ] + .split( '\n' ) + .map( ( text ) => text.trim() ) + .join( ' ' ); // False return indicates to Lodash to break iteration return false; @@ -178,10 +178,7 @@ function isValidTranslationKey( key ) { * @return {boolean} Whether valid translation keys match. */ function isSameTranslation( a, b ) { - return isEqual( - pick( a, VALID_TRANSLATION_KEYS ), - pick( b, VALID_TRANSLATION_KEYS ) - ); + return isEqual( pick( a, VALID_TRANSLATION_KEYS ), pick( b, VALID_TRANSLATION_KEYS ) ); } module.exports = function() { @@ -240,11 +237,15 @@ module.exports = function() { }; for ( const key in baseData.headers ) { - baseData.translations[ '' ][ '' ].msgstr.push( `${ key }: ${ baseData.headers[ key ] };\n` ); + baseData.translations[ '' ][ '' ].msgstr.push( + `${ key }: ${ baseData.headers[ key ] };\n` + ); } // Attempt to exract nplurals from header - const pluralsMatch = ( baseData.headers[ 'plural-forms' ] || '' ).match( /nplurals\s*=\s*(\d+);/ ); + const pluralsMatch = ( baseData.headers[ 'plural-forms' ] || '' ).match( + /nplurals\s*=\s*(\d+);/ + ); if ( pluralsMatch ) { nplurals = parseInt( pluralsMatch[ 1 ], 10 ); } @@ -260,7 +261,9 @@ module.exports = function() { // Assign file reference comment, ensuring consistent pathname // reference between Win32 and POSIX const { filename } = this.file.opts; - const pathname = relative( '.', filename ).split( sep ).join( '/' ); + const pathname = relative( '.', filename ) + .split( sep ) + .join( '/' ); translation.comments = { reference: pathname + ':' + path.node.loc.start.line, }; @@ -294,34 +297,42 @@ module.exports = function() { const files = Object.keys( strings ).sort(); // Combine translations from each file grouped by context - const translations = reduce( files, ( memo, file ) => { - for ( const context in strings[ file ] ) { - // Within the same file, sort translations by line - const sortedTranslations = sortBy( - strings[ file ][ context ], - 'comments.reference' - ); - - forEach( sortedTranslations, ( translation ) => { - const { msgctxt = '', msgid } = translation; - if ( ! memo.hasOwnProperty( msgctxt ) ) { - memo[ msgctxt ] = {}; - } - - // Merge references if translation already exists - if ( isSameTranslation( translation, memo[ msgctxt ][ msgid ] ) ) { - translation.comments.reference = uniq( [ - memo[ msgctxt ][ msgid ].comments.reference, - translation.comments.reference, - ].join( '\n' ).split( '\n' ) ).join( '\n' ); - } - - memo[ msgctxt ][ msgid ] = translation; - } ); - } - - return memo; - }, {} ); + const translations = reduce( + files, + ( memo, file ) => { + for ( const context in strings[ file ] ) { + // Within the same file, sort translations by line + const sortedTranslations = sortBy( + strings[ file ][ context ], + 'comments.reference' + ); + + forEach( sortedTranslations, ( translation ) => { + const { msgctxt = '', msgid } = translation; + if ( ! memo.hasOwnProperty( msgctxt ) ) { + memo[ msgctxt ] = {}; + } + + // Merge references if translation already exists + if ( isSameTranslation( translation, memo[ msgctxt ][ msgid ] ) ) { + translation.comments.reference = uniq( + [ + memo[ msgctxt ][ msgid ].comments.reference, + translation.comments.reference, + ] + .join( '\n' ) + .split( '\n' ) + ).join( '\n' ); + } + + memo[ msgctxt ][ msgid ] = translation; + } ); + } + + return memo; + }, + {} + ); // Merge translations from individual files into headers const data = merge( {}, baseData, { translations } ); diff --git a/packages/babel-plugin-makepot/test/index.js b/packages/babel-plugin-makepot/test/index.js index 52ae1dcc5b9134..32554aa0656939 100644 --- a/packages/babel-plugin-makepot/test/index.js +++ b/packages/babel-plugin-makepot/test/index.js @@ -74,7 +74,9 @@ describe( 'babel-plugin', () => { } ); it( 'should traverse up parents until it encounters comment', () => { - const comment = getCommentFromString( "// translators: Greeting\nconst string = __( 'Hello world' );" ); + const comment = getCommentFromString( + "// translators: Greeting\nconst string = __( 'Hello world' );" + ); expect( comment ).toBe( 'Greeting' ); } ); @@ -86,7 +88,9 @@ describe( 'babel-plugin', () => { } ); it( 'should use multi-line comment starting many lines previous', () => { - const comment = getCommentFromString( "/* translators: Long comment\nspanning multiple \nlines */\nconst string = __( 'Hello world' );" ); + const comment = getCommentFromString( + "/* translators: Long comment\nspanning multiple \nlines */\nconst string = __( 'Hello world' );" + ); expect( comment ).toBe( 'Long comment spanning multiple lines' ); } ); diff --git a/packages/babel-preset-default/index.js b/packages/babel-preset-default/index.js index a1343706b03b8b..d7b198ec4d45c1 100644 --- a/packages/babel-preset-default/index.js +++ b/packages/babel-preset-default/index.js @@ -1,8 +1,7 @@ module.exports = function( api ) { let wpBuildOpts = {}; - const isWPBuild = ( name ) => [ 'WP_BUILD_MAIN', 'WP_BUILD_MODULE' ].some( - ( buildName ) => name === buildName - ); + const isWPBuild = ( name ) => + [ 'WP_BUILD_MAIN', 'WP_BUILD_MODULE' ].some( ( buildName ) => name === buildName ); const isTestEnv = api.env() === 'test'; @@ -65,10 +64,13 @@ module.exports = function( api ) { isDefault: false, }, ], - [ require.resolve( '@babel/plugin-transform-react-jsx' ), { - pragma: 'createElement', - pragmaFrag: 'Fragment', - } ], + [ + require.resolve( '@babel/plugin-transform-react-jsx' ), + { + pragma: 'createElement', + pragmaFrag: 'Fragment', + }, + ], require.resolve( '@babel/plugin-proposal-async-generator-functions' ), maybeGetPluginTransformRuntime(), ].filter( Boolean ), diff --git a/packages/blob/src/test/index.js b/packages/blob/src/test/index.js index 7604e3956b6d26..110340e13639e2 100644 --- a/packages/blob/src/test/index.js +++ b/packages/blob/src/test/index.js @@ -1,9 +1,7 @@ /** * Internal dependencies */ -import { - isBlobURL, -} from '../'; +import { isBlobURL } from '../'; describe( 'isBlobURL', () => { it( 'returns true if the url starts with "blob:"', () => { diff --git a/packages/block-directory/src/components/block-ratings/stars.js b/packages/block-directory/src/components/block-ratings/stars.js index 577c3cb15e0dc2..9b78e608dae7ba 100644 --- a/packages/block-directory/src/components/block-ratings/stars.js +++ b/packages/block-directory/src/components/block-ratings/stars.js @@ -9,9 +9,7 @@ import { times } from 'lodash'; import { __, sprintf } from '@wordpress/i18n'; import { Icon } from '@wordpress/components'; -function Stars( { - rating, -} ) { +function Stars( { rating } ) { const stars = Math.round( rating / 0.5 ) * 0.5; const fullStarCount = Math.floor( rating ); @@ -20,9 +18,15 @@ function Stars( { return (
    - { times( fullStarCount, ( i ) => ) } - { times( halfStarCount, ( i ) => ) } - { times( emptyStarCount, ( i ) => ) } + { times( fullStarCount, ( i ) => ( + + ) ) } + { times( halfStarCount, ( i ) => ( + + ) ) } + { times( emptyStarCount, ( i ) => ( + + ) ) }
    ); } diff --git a/packages/block-directory/src/components/downloadable-block-header/index.js b/packages/block-directory/src/components/downloadable-block-header/index.js index 7a9225d57f0cff..474a519c001705 100644 --- a/packages/block-directory/src/components/downloadable-block-header/index.js +++ b/packages/block-directory/src/components/downloadable-block-header/index.js @@ -13,16 +13,16 @@ import BlockRatings from '../block-ratings'; function DownloadableBlockHeader( { icon, title, rating, ratingCount, onClick } ) { return (
    - { - icon.match( /\.(jpeg|jpg|gif|png)$/ ) !== null ? - block icon : - - - - } + { icon.match( /\.(jpeg|jpg|gif|png)$/ ) !== null ? ( + block icon + ) : ( + + + + ) }
    - + { title } diff --git a/packages/block-directory/src/components/downloadable-block-info/index.js b/packages/block-directory/src/components/downloadable-block-info/index.js index 4dbbd8f691ffa7..832186499401bd 100644 --- a/packages/block-directory/src/components/downloadable-block-info/index.js +++ b/packages/block-directory/src/components/downloadable-block-info/index.js @@ -8,15 +8,20 @@ import { __, _n, sprintf } from '@wordpress/i18n'; function DownloadableBlockInfo( { description, activeInstalls, humanizedUpdated } ) { return ( -

    - { description } -

    +

    { description }

    - { sprintf( _n( '%d active installation', '%d active installations', activeInstalls ), activeInstalls ) } + + { sprintf( + _n( '%d active installation', '%d active installations', activeInstalls ), + activeInstalls + ) }
    - { humanizedUpdated } + + + { humanizedUpdated } +
    diff --git a/packages/block-directory/src/components/downloadable-block-list-item/index.js b/packages/block-directory/src/components/downloadable-block-list-item/index.js index c5bd8b8f0244e0..3eb69eba7d2d70 100644 --- a/packages/block-directory/src/components/downloadable-block-list-item/index.js +++ b/packages/block-directory/src/components/downloadable-block-list-item/index.js @@ -5,10 +5,7 @@ import DownloadableBlockHeader from '../downloadable-block-header'; import DownloadableBlockAuthorInfo from '../downloadable-block-author-info'; import DownloadableBlockInfo from '../downloadable-block-info'; -function DownloadableBlockListItem( { - item, - onClick, -} ) { +function DownloadableBlockListItem( { item, onClick } ) { const { icon, title, diff --git a/packages/block-directory/src/components/downloadable-blocks-list/index.js b/packages/block-directory/src/components/downloadable-blocks-list/index.js index 315403267a56c3..36b952f3ecc5da 100644 --- a/packages/block-directory/src/components/downloadable-blocks-list/index.js +++ b/packages/block-directory/src/components/downloadable-blocks-list/index.js @@ -27,22 +27,23 @@ function DownloadableBlocksList( { items, onHover = noop, children, downloadAndI */ /* eslint-disable jsx-a11y/no-redundant-roles */
      - { items && items.map( ( item ) => - { - downloadAndInstallBlock( item ); - onHover( null ); - } } - onFocus={ () => onHover( item ) } - onMouseEnter={ () => onHover( item ) } - onMouseLeave={ () => onHover( null ) } - onBlur={ () => onHover( null ) } - item={ item } - /> - ) } + { items && + items.map( ( item ) => ( + { + downloadAndInstallBlock( item ); + onHover( null ); + } } + onFocus={ () => onHover( item ) } + onMouseEnter={ () => onHover( item ) } + onMouseLeave={ () => onHover( null ) } + onBlur={ () => onHover( null ) } + item={ item } + /> + ) ) } { children }
    /* eslint-enable jsx-a11y/no-redundant-roles */ @@ -59,49 +60,44 @@ export default compose( return { downloadAndInstallBlock: ( item ) => { const onDownloadError = () => { - createErrorNotice( - __( 'Block previews can’t load.' ), - { - id: DOWNLOAD_ERROR_NOTICE_ID, - actions: [ - { - label: __( 'Retry' ), - onClick: () => { - removeNotice( DOWNLOAD_ERROR_NOTICE_ID ); - downloadBlock( item, onSuccess, onDownloadError ); - }, + createErrorNotice( __( 'Block previews can’t load.' ), { + id: DOWNLOAD_ERROR_NOTICE_ID, + actions: [ + { + label: __( 'Retry' ), + onClick: () => { + removeNotice( DOWNLOAD_ERROR_NOTICE_ID ); + downloadBlock( item, onSuccess, onDownloadError ); }, - ], - } ); + }, + ], + } ); }; const onSuccess = () => { const createdBlock = onSelect( item ); const onInstallBlockError = () => { - createErrorNotice( - __( 'Block previews can\'t install.' ), - { - id: INSTALL_ERROR_NOTICE_ID, - actions: [ - { - label: __( 'Retry' ), - onClick: () => { - removeNotice( INSTALL_ERROR_NOTICE_ID ); - installBlock( item, noop, onInstallBlockError ); - }, + createErrorNotice( __( "Block previews can't install." ), { + id: INSTALL_ERROR_NOTICE_ID, + actions: [ + { + label: __( 'Retry' ), + onClick: () => { + removeNotice( INSTALL_ERROR_NOTICE_ID ); + installBlock( item, noop, onInstallBlockError ); }, - { - label: __( 'Remove' ), - onClick: () => { - removeNotice( INSTALL_ERROR_NOTICE_ID ); - removeBlocks( createdBlock.clientId ); - unregisterBlockType( item.name ); - }, + }, + { + label: __( 'Remove' ), + onClick: () => { + removeNotice( INSTALL_ERROR_NOTICE_ID ); + removeBlocks( createdBlock.clientId ); + unregisterBlockType( item.name ); }, - ], - } - ); + }, + ], + } ); }; installBlock( item, noop, onInstallBlockError ); @@ -110,5 +106,5 @@ export default compose( downloadBlock( item, onSuccess, onDownloadError ); }, }; - } ), + } ) )( DownloadableBlocksList ); diff --git a/packages/block-directory/src/components/downloadable-blocks-panel/index.js b/packages/block-directory/src/components/downloadable-blocks-panel/index.js index 0936ee3eea6f23..f49e96654acc27 100644 --- a/packages/block-directory/src/components/downloadable-blocks-panel/index.js +++ b/packages/block-directory/src/components/downloadable-blocks-panel/index.js @@ -12,9 +12,21 @@ import { Spinner, withSpokenMessages } from '@wordpress/components'; */ import DownloadableBlocksList from '../downloadable-blocks-list'; -function DownloadableBlocksPanel( { downloadableItems, onSelect, onHover, hasPermission, isLoading, isWaiting, debouncedSpeak } ) { +function DownloadableBlocksPanel( { + downloadableItems, + onSelect, + onHover, + hasPermission, + isLoading, + isWaiting, + debouncedSpeak, +} ) { if ( ! hasPermission ) { - debouncedSpeak( __( 'No blocks found in your library. Please contact your site administrator to install new blocks.' ) ); + debouncedSpeak( + __( + 'No blocks found in your library. Please contact your site administrator to install new blocks.' + ) + ); return (

    { __( 'No blocks found in your library.' ) } @@ -41,7 +53,11 @@ function DownloadableBlocksPanel( { downloadableItems, onSelect, onHover, hasPer } const resultsFoundMessage = sprintf( - _n( 'No blocks found in your library. We did find %d block available for download.', 'No blocks found in your library. We did find %d blocks available for download.', downloadableItems.length ), + _n( + 'No blocks found in your library. We did find %d block available for download.', + 'No blocks found in your library. We did find %d blocks available for download.', + downloadableItems.length + ), downloadableItems.length ); @@ -51,7 +67,11 @@ function DownloadableBlocksPanel( { downloadableItems, onSelect, onHover, hasPer

    { __( 'No blocks found in your library. These blocks can be downloaded and installed:' ) }

    - + ); } diff --git a/packages/block-directory/src/store/controls.js b/packages/block-directory/src/store/controls.js index fbd187b7bbf417..5f38d65759c5cf 100644 --- a/packages/block-directory/src/store/controls.js +++ b/packages/block-directory/src/store/controls.js @@ -118,7 +118,7 @@ const controls = { return registry.dispatch( storeName )[ dispatcherName ]( ...args ); } ), API_FETCH( { request } ) { - return wpApiFetch( { ... request } ); + return wpApiFetch( { ...request } ); }, LOAD_ASSETS( { assets } ) { return new Promise( ( resolve, reject ) => { @@ -128,20 +128,28 @@ const controls = { forEach( assets, ( asset ) => { if ( asset.match( /\.js$/ ) !== null ) { scriptsCount++; - loadScript( asset, () => { - scriptsCount--; - if ( scriptsCount === 0 ) { - return resolve( scriptsCount ); - } - }, reject ); + loadScript( + asset, + () => { + scriptsCount--; + if ( scriptsCount === 0 ) { + return resolve( scriptsCount ); + } + }, + reject + ); } else { loadStyle( asset ); } } ); } else { - loadScript( assets.editor_script, () => { - return resolve( 0 ); - }, reject ); + loadScript( + assets.editor_script, + () => { + return resolve( 0 ); + }, + reject + ); loadStyle( assets.style ); } } ); diff --git a/packages/block-directory/src/store/reducer.js b/packages/block-directory/src/store/reducer.js index 8dc4f3438c318f..9eb707cfe74deb 100644 --- a/packages/block-directory/src/store/reducer.js +++ b/packages/block-directory/src/store/reducer.js @@ -11,20 +11,23 @@ import { combineReducers } from '@wordpress/data'; * * @return {Object} Updated state. */ -export const downloadableBlocks = ( state = { - results: {}, - hasPermission: true, - filterValue: undefined, - isRequestingDownloadableBlocks: true, - installedBlockTypes: [], -}, action ) => { +export const downloadableBlocks = ( + state = { + results: {}, + hasPermission: true, + filterValue: undefined, + isRequestingDownloadableBlocks: true, + installedBlockTypes: [], + }, + action +) => { switch ( action.type ) { - case 'FETCH_DOWNLOADABLE_BLOCKS' : + case 'FETCH_DOWNLOADABLE_BLOCKS': return { ...state, isRequestingDownloadableBlocks: true, }; - case 'RECEIVE_DOWNLOADABLE_BLOCKS' : + case 'RECEIVE_DOWNLOADABLE_BLOCKS': return { ...state, results: Object.assign( {}, state.results, { @@ -33,22 +36,24 @@ export const downloadableBlocks = ( state = { hasPermission: true, isRequestingDownloadableBlocks: false, }; - case 'SET_INSTALL_BLOCKS_PERMISSION' : + case 'SET_INSTALL_BLOCKS_PERMISSION': return { ...state, items: action.hasPermission ? state.items : [], hasPermission: action.hasPermission, }; - case 'ADD_INSTALLED_BLOCK_TYPE' : + case 'ADD_INSTALLED_BLOCK_TYPE': return { ...state, installedBlockTypes: [ ...state.installedBlockTypes, action.item ], }; - case 'REMOVE_INSTALLED_BLOCK_TYPE' : + case 'REMOVE_INSTALLED_BLOCK_TYPE': return { ...state, - installedBlockTypes: state.installedBlockTypes.filter( ( blockType ) => blockType.name !== action.item.name ), + installedBlockTypes: state.installedBlockTypes.filter( + ( blockType ) => blockType.name !== action.item.name + ), }; } return state; diff --git a/packages/block-directory/src/store/resolvers.js b/packages/block-directory/src/store/resolvers.js index 885257ea72ee8b..a1b0d7dfd05bea 100644 --- a/packages/block-directory/src/store/resolvers.js +++ b/packages/block-directory/src/store/resolvers.js @@ -7,10 +7,14 @@ import { camelCase, mapKeys } from 'lodash'; * Internal dependencies */ import { apiFetch } from './controls'; -import { fetchDownloadableBlocks, receiveDownloadableBlocks, setInstallBlocksPermission } from './actions'; +import { + fetchDownloadableBlocks, + receiveDownloadableBlocks, + setInstallBlocksPermission, +} from './actions'; export default { - * getDownloadableBlocks( filterValue ) { + *getDownloadableBlocks( filterValue ) { if ( ! filterValue ) { return; } @@ -20,9 +24,11 @@ export default { const results = yield apiFetch( { path: `__experimental/block-directory/search?term=${ filterValue }`, } ); - const blocks = results.map( ( result ) => mapKeys( result, ( value, key ) => { - return camelCase( key ); - } ) ); + const blocks = results.map( ( result ) => + mapKeys( result, ( value, key ) => { + return camelCase( key ); + } ) + ); yield receiveDownloadableBlocks( blocks, filterValue ); } catch ( error ) { @@ -31,7 +37,7 @@ export default { } } }, - * hasInstallBlocksPermission() { + *hasInstallBlocksPermission() { try { yield apiFetch( { path: `__experimental/block-directory/search?term=`, diff --git a/packages/block-editor/src/components/alignment-toolbar/index.js b/packages/block-editor/src/components/alignment-toolbar/index.js index aa0233ae0f7518..a0aad52e720d65 100644 --- a/packages/block-editor/src/components/alignment-toolbar/index.js +++ b/packages/block-editor/src/components/alignment-toolbar/index.js @@ -49,7 +49,7 @@ export function AlignmentToolbar( props ) { label={ label } controls={ alignmentControls.map( ( control ) => { const { align } = control; - const isActive = ( value === align ); + const isActive = value === align; return { ...control, diff --git a/packages/block-editor/src/components/alignment-toolbar/test/index.js b/packages/block-editor/src/components/alignment-toolbar/test/index.js index 03662cfdabe812..bdf3cd0f7c8d41 100644 --- a/packages/block-editor/src/components/alignment-toolbar/test/index.js +++ b/packages/block-editor/src/components/alignment-toolbar/test/index.js @@ -66,9 +66,7 @@ describe( 'AlignmentToolbar', () => { expect( customControls ).toHaveLength( 2 ); // should correctly call on change when right alignment is pressed (active alignment) - const rightControl = customControls.find( - ( { align } ) => align === 'custom-right' - ); + const rightControl = customControls.find( ( { align } ) => align === 'custom-right' ); expect( rightControl.title ).toBe( 'My custom right' ); rightControl.onClick(); expect( onChangeSpy ).toHaveBeenCalledTimes( 1 ); @@ -76,9 +74,7 @@ describe( 'AlignmentToolbar', () => { onChangeSpy.mockClear(); // should correctly call on change when right alignment is pressed (inactive alignment) - const leftControl = customControls.find( - ( { align } ) => align === 'custom-left' - ); + const leftControl = customControls.find( ( { align } ) => align === 'custom-left' ); expect( leftControl.title ).toBe( 'My custom left' ); leftControl.onClick(); expect( onChangeSpy ).toHaveBeenCalledTimes( 1 ); diff --git a/packages/block-editor/src/components/autocomplete/index.js b/packages/block-editor/src/components/autocomplete/index.js index c95279a104db24..2deea118054500 100644 --- a/packages/block-editor/src/components/autocomplete/index.js +++ b/packages/block-editor/src/components/autocomplete/index.js @@ -33,16 +33,11 @@ export function withFilteredAutocompleters( Autocomplete ) { 'editor.Autocomplete.completers', // Provide copies so filters may directly modify them. completers.map( clone ), - props.blockName, + props.blockName ); } - return ( - - ); + return ; }; } diff --git a/packages/block-editor/src/components/block-actions/index.js b/packages/block-editor/src/components/block-actions/index.js index 82f12e6e256048..6aa4aed0deee86 100644 --- a/packages/block-editor/src/components/block-actions/index.js +++ b/packages/block-editor/src/components/block-actions/index.js @@ -55,10 +55,7 @@ export default compose( [ ); } ); - const canInsertDefaultBlock = canInsertBlockType( - getDefaultBlockName(), - rootClientId - ); + const canInsertDefaultBlock = canInsertBlockType( getDefaultBlockName(), rootClientId ); return { blocks, @@ -70,21 +67,11 @@ export default compose( [ }; } ), withDispatch( ( dispatch, props, { select } ) => { - const { - clientIds, - rootClientId, - blocks, - isLocked, - canDuplicate, - } = props; + const { clientIds, rootClientId, blocks, isLocked, canDuplicate } = props; - const { - insertBlocks, - multiSelect, - removeBlocks, - insertDefaultBlock, - replaceBlocks, - } = dispatch( 'core/block-editor' ); + const { insertBlocks, multiSelect, removeBlocks, insertDefaultBlock, replaceBlocks } = dispatch( + 'core/block-editor' + ); return { onDuplicate() { @@ -95,16 +82,9 @@ export default compose( [ const { getBlockIndex } = select( 'core/block-editor' ); const lastSelectedIndex = getBlockIndex( last( castArray( clientIds ) ), rootClientId ); const clonedBlocks = blocks.map( ( block ) => cloneBlock( block ) ); - insertBlocks( - clonedBlocks, - lastSelectedIndex + 1, - rootClientId - ); + insertBlocks( clonedBlocks, lastSelectedIndex + 1, rootClientId ); if ( clonedBlocks.length > 1 ) { - multiSelect( - first( clonedBlocks ).clientId, - last( clonedBlocks ).clientId - ); + multiSelect( first( clonedBlocks ).clientId, last( clonedBlocks ).clientId ); } }, onRemove() { @@ -131,9 +111,7 @@ export default compose( [ return; } - const { - getGroupingBlockName, - } = select( 'core/blocks' ); + const { getGroupingBlockName } = select( 'core/blocks' ); const groupingBlockName = getGroupingBlockName(); @@ -143,10 +121,7 @@ export default compose( [ if ( ! newBlocks ) { return; } - replaceBlocks( - clientIds, - newBlocks - ); + replaceBlocks( clientIds, newBlocks ); }, onUngroup() { @@ -160,10 +135,7 @@ export default compose( [ return; } - replaceBlocks( - clientIds, - innerBlocks - ); + replaceBlocks( clientIds, innerBlocks ); }, }; } ), diff --git a/packages/block-editor/src/components/block-alignment-toolbar/index.js b/packages/block-editor/src/components/block-alignment-toolbar/index.js index e766504f0d9f4d..1589b8589af525 100644 --- a/packages/block-editor/src/components/block-alignment-toolbar/index.js +++ b/packages/block-editor/src/components/block-alignment-toolbar/index.js @@ -38,14 +38,20 @@ const DEFAULT_CONTROLS = [ 'left', 'center', 'right', 'wide', 'full' ]; const DEFAULT_CONTROL = 'center'; const WIDE_CONTROLS = [ 'wide', 'full' ]; -export function BlockAlignmentToolbar( { value, onChange, controls = DEFAULT_CONTROLS, isCollapsed = true, wideControlsEnabled = false } ) { +export function BlockAlignmentToolbar( { + value, + onChange, + controls = DEFAULT_CONTROLS, + isCollapsed = true, + wideControlsEnabled = false, +} ) { function applyOrUnset( align ) { return () => onChange( value === align ? undefined : align ); } - const enabledControls = wideControlsEnabled ? - controls : - controls.filter( ( control ) => WIDE_CONTROLS.indexOf( control ) === -1 ); + const enabledControls = wideControlsEnabled + ? controls + : controls.filter( ( control ) => WIDE_CONTROLS.indexOf( control ) === -1 ); const activeAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[ value ]; const defaultAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[ DEFAULT_CONTROL ]; @@ -55,15 +61,13 @@ export function BlockAlignmentToolbar( { value, onChange, controls = DEFAULT_CON isCollapsed={ isCollapsed } icon={ activeAlignmentControl ? activeAlignmentControl.icon : defaultAlignmentControl.icon } label={ __( 'Change alignment' ) } - controls={ - enabledControls.map( ( control ) => { - return { - ...BLOCK_ALIGNMENTS_CONTROLS[ control ], - isActive: value === control, - onClick: applyOrUnset( control ), - }; - } ) - } + controls={ enabledControls.map( ( control ) => { + return { + ...BLOCK_ALIGNMENTS_CONTROLS[ control ], + isActive: value === control, + onClick: applyOrUnset( control ), + }; + } ) } /> ); } @@ -80,5 +84,5 @@ export default compose( return { wideControlsEnabled: settings.alignWide, }; - } ), + } ) )( BlockAlignmentToolbar ); diff --git a/packages/block-editor/src/components/block-compare/block-view.js b/packages/block-editor/src/components/block-compare/block-view.js index 274c2896d98a9e..36db21bad5f738 100644 --- a/packages/block-editor/src/components/block-compare/block-view.js +++ b/packages/block-editor/src/components/block-compare/block-view.js @@ -7,7 +7,9 @@ const BlockView = ( { title, rawContent, renderedContent, action, actionText, cl return (
    -

    { title }

    +

    + { title } +

    { rawContent } @@ -19,7 +21,9 @@ const BlockView = ( { title, rawContent, renderedContent, action, actionText, cl
    - +
    ); diff --git a/packages/block-editor/src/components/block-compare/index.js b/packages/block-editor/src/components/block-compare/index.js index 1b294649e9c627..9706c358026813 100644 --- a/packages/block-editor/src/components/block-compare/index.js +++ b/packages/block-editor/src/components/block-compare/index.js @@ -27,7 +27,11 @@ class BlockCompare extends Component { 'editor-block-compare__removed block-editor-block-compare__removed': item.removed, } ); - return { item.value }; + return ( + + { item.value } + + ); } ); } @@ -43,8 +47,12 @@ class BlockCompare extends Component { const newBlocks = castArray( block ); // Get converted block details - const newContent = newBlocks.map( ( item ) => getSaveContent( item.name, item.attributes, item.innerBlocks ) ); - const renderedContent = newBlocks.map( ( item ) => getSaveElement( item.name, item.attributes, item.innerBlocks ) ); + const newContent = newBlocks.map( ( item ) => + getSaveContent( item.name, item.attributes, item.innerBlocks ) + ); + const renderedContent = newBlocks.map( ( item ) => + getSaveElement( item.name, item.attributes, item.innerBlocks ) + ); return { rawContent: newContent.join( '' ), diff --git a/packages/block-editor/src/components/block-compare/test/block-view.js b/packages/block-editor/src/components/block-compare/test/block-view.js index 657f326f44ce9b..755722983351b4 100644 --- a/packages/block-editor/src/components/block-compare/test/block-view.js +++ b/packages/block-editor/src/components/block-compare/test/block-view.js @@ -11,7 +11,16 @@ import BlockView from '../block-view'; describe( 'BlockView', () => { test( 'should match snapshot', () => { - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper ).toMatchSnapshot(); } ); diff --git a/packages/block-editor/src/components/block-draggable/index.js b/packages/block-editor/src/components/block-draggable/index.js index 8818d58be9c2d2..9e78ccf99a231f 100644 --- a/packages/block-editor/src/components/block-draggable/index.js +++ b/packages/block-editor/src/components/block-draggable/index.js @@ -4,7 +4,15 @@ import { Draggable } from '@wordpress/components'; import { withSelect } from '@wordpress/data'; -const BlockDraggable = ( { children, clientId, rootClientId, blockElementId, index, onDragStart, onDragEnd } ) => { +const BlockDraggable = ( { + children, + clientId, + rootClientId, + blockElementId, + index, + onDragStart, + onDragEnd, +} ) => { const transferData = { type: 'block', srcIndex: index, @@ -19,14 +27,12 @@ const BlockDraggable = ( { children, clientId, rootClientId, blockElementId, ind onDragStart={ onDragStart } onDragEnd={ onDragEnd } > - { - ( { onDraggableStart, onDraggableEnd } ) => { - return children( { - onDraggableStart, - onDraggableEnd, - } ); - } - } + { ( { onDraggableStart, onDraggableEnd } ) => { + return children( { + onDraggableStart, + onDraggableEnd, + } ); + } } ); }; diff --git a/packages/block-editor/src/components/block-drop-zone/index.js b/packages/block-editor/src/components/block-drop-zone/index.js index adac488e4c3d7f..a34422523919af 100644 --- a/packages/block-editor/src/components/block-drop-zone/index.js +++ b/packages/block-editor/src/components/block-drop-zone/index.js @@ -6,15 +6,8 @@ import classnames from 'classnames'; /** * WordPress dependencies */ -import { - DropZone, - withFilters, -} from '@wordpress/components'; -import { - pasteHandler, - getBlockTransforms, - findTransform, -} from '@wordpress/blocks'; +import { DropZone, withFilters } from '@wordpress/components'; +import { pasteHandler, getBlockTransforms, findTransform } from '@wordpress/blocks'; import { Component } from '@wordpress/element'; import { withDispatch, withSelect } from '@wordpress/data'; import { compose } from '@wordpress/compose'; @@ -58,7 +51,7 @@ class BlockDropZone extends Component { const { clientId, rootClientId, getBlockIndex } = this.props; if ( clientId !== undefined ) { const index = getBlockIndex( clientId, rootClientId ); - return ( position && position.y === 'top' ) ? index : index + 1; + return position && position.y === 'top' ? index : index + 1; } } @@ -84,21 +77,29 @@ class BlockDropZone extends Component { } onDrop( event, position ) { - const { rootClientId: dstRootClientId, clientId: dstClientId, getClientIdsOfDescendants, getBlockIndex } = this.props; + const { + rootClientId: dstRootClientId, + clientId: dstClientId, + getClientIdsOfDescendants, + getBlockIndex, + } = this.props; const { srcRootClientId, srcClientId, srcIndex, type } = parseDropEvent( event ); const isBlockDropType = ( dropType ) => dropType === 'block'; const isSameLevel = ( srcRoot, dstRoot ) => { // Note that rootClientId of top-level blocks will be undefined OR a void string, // so we also need to account for that case separately. - return ( srcRoot === dstRoot ) || ( ! srcRoot === true && ! dstRoot === true ); + return srcRoot === dstRoot || ( ! srcRoot === true && ! dstRoot === true ); }; const isSameBlock = ( src, dst ) => src === dst; - const isSrcBlockAnAncestorOfDstBlock = ( src, dst ) => getClientIdsOfDescendants( [ src ] ).some( ( id ) => id === dst ); + const isSrcBlockAnAncestorOfDstBlock = ( src, dst ) => + getClientIdsOfDescendants( [ src ] ).some( ( id ) => id === dst ); - if ( ! isBlockDropType( type ) || + if ( + ! isBlockDropType( type ) || isSameBlock( srcClientId, dstClientId ) || - isSrcBlockAnAncestorOfDstBlock( srcClientId, dstClientId || dstRootClientId ) ) { + isSrcBlockAnAncestorOfDstBlock( srcClientId, dstClientId || dstRootClientId ) + ) { return; } @@ -106,7 +107,10 @@ class BlockDropZone extends Component { const positionIndex = this.getInsertIndex( position ); // If the block is kept at the same level and moved downwards, // subtract to account for blocks shifting upward to occupy its old position. - const insertIndex = dstIndex && srcIndex < dstIndex && isSameLevel( srcRootClientId, dstRootClientId ) ? positionIndex - 1 : positionIndex; + const insertIndex = + dstIndex && srcIndex < dstIndex && isSameLevel( srcRootClientId, dstRootClientId ) + ? positionIndex - 1 + : positionIndex; this.props.moveBlockToPosition( srcClientId, srcRootClientId, insertIndex ); } @@ -136,11 +140,9 @@ class BlockDropZone extends Component { export default compose( withDispatch( ( dispatch, ownProps ) => { - const { - insertBlocks, - updateBlockAttributes, - moveBlockToPosition, - } = dispatch( 'core/block-editor' ); + const { insertBlocks, updateBlockAttributes, moveBlockToPosition } = dispatch( + 'core/block-editor' + ); return { insertBlocks( blocks, index ) { @@ -158,7 +160,9 @@ export default compose( }; } ), withSelect( ( select, { rootClientId } ) => { - const { getClientIdsOfDescendants, getTemplateLock, getBlockIndex } = select( 'core/block-editor' ); + const { getClientIdsOfDescendants, getTemplateLock, getBlockIndex } = select( + 'core/block-editor' + ); return { isLockedAll: getTemplateLock( rootClientId ) === 'all', getClientIdsOfDescendants, diff --git a/packages/block-editor/src/components/block-edit/context.js b/packages/block-editor/src/components/block-edit/context.js index 863cdc3e5d6fa5..443624522e2146 100644 --- a/packages/block-editor/src/components/block-edit/context.js +++ b/packages/block-editor/src/components/block-edit/context.js @@ -29,18 +29,16 @@ export { Provider as BlockEditContextProvider }; * * @return {Component} Enhanced component with injected context as props. */ -export const withBlockEditContext = ( mapContextToProps ) => createHigherOrderComponent( ( OriginalComponent ) => { - return ( props ) => ( - - { ( context ) => ( - - ) } - - ); -}, 'withBlockEditContext' ); +export const withBlockEditContext = ( mapContextToProps ) => + createHigherOrderComponent( ( OriginalComponent ) => { + return ( props ) => ( + + { ( context ) => ( + + ) } + + ); + }, 'withBlockEditContext' ); /** * A Higher Order Component used to render conditionally the wrapped @@ -52,10 +50,6 @@ export const withBlockEditContext = ( mapContextToProps ) => createHigherOrderCo */ export const ifBlockEditSelected = createHigherOrderComponent( ( OriginalComponent ) => { return ( props ) => ( - - { ( { isSelected } ) => isSelected && ( - - ) } - + { ( { isSelected } ) => isSelected && } ); }, 'ifBlockEditSelected' ); diff --git a/packages/block-editor/src/components/block-edit/edit.js b/packages/block-editor/src/components/block-edit/edit.js index c7e0ba97e305ed..9ee82889bd89ed 100644 --- a/packages/block-editor/src/components/block-edit/edit.js +++ b/packages/block-editor/src/components/block-edit/edit.js @@ -18,9 +18,9 @@ export const Edit = ( props ) => { } // Generate a class name for the block's editable form - const generatedClassName = hasBlockSupport( blockType, 'className', true ) ? - getBlockDefaultClassName( name ) : - null; + const generatedClassName = hasBlockSupport( blockType, 'className', true ) + ? getBlockDefaultClassName( name ) + : null; const className = classnames( generatedClassName, attributes.className ); // `edit` and `save` are functions or components describing the markup diff --git a/packages/block-editor/src/components/block-edit/edit.native.js b/packages/block-editor/src/components/block-edit/edit.native.js index 8a4d0ad8350e99..2577ad3e0733e7 100644 --- a/packages/block-editor/src/components/block-edit/edit.native.js +++ b/packages/block-editor/src/components/block-edit/edit.native.js @@ -14,9 +14,7 @@ export const Edit = ( props ) => { const Component = blockType.edit; - return ( - - ); + return ; }; export default withFilters( 'editor.BlockEdit' )( Edit ); diff --git a/packages/block-editor/src/components/block-edit/index.js b/packages/block-editor/src/components/block-edit/index.js index 63c475a50692ff..59c4df9e3543f4 100644 --- a/packages/block-editor/src/components/block-edit/index.js +++ b/packages/block-editor/src/components/block-edit/index.js @@ -21,10 +21,7 @@ class BlockEdit extends Component { // It is important to return the same object if props haven't changed // to avoid unnecessary rerenders. // See https://reactjs.org/docs/context.html#caveats. - this.propsToContext = memize( - this.propsToContext.bind( this ), - { maxSize: 1 } - ); + this.propsToContext = memize( this.propsToContext.bind( this ), { maxSize: 1 } ); } propsToContext( name, isSelected, clientId, onFocus, onCaretVerticalPositionChange ) { @@ -33,7 +30,13 @@ class BlockEdit extends Component { render() { const { name, isSelected, clientId, onFocus, onCaretVerticalPositionChange } = this.props; - const value = this.propsToContext( name, isSelected, clientId, onFocus, onCaretVerticalPositionChange ); + const value = this.propsToContext( + name, + isSelected, + clientId, + onFocus, + onCaretVerticalPositionChange + ); return ( diff --git a/packages/block-editor/src/components/block-edit/test/edit.js b/packages/block-editor/src/components/block-edit/test/edit.js index d09ce608cc14bf..0a24f55ce2471e 100644 --- a/packages/block-editor/src/components/block-edit/test/edit.js +++ b/packages/block-editor/src/components/block-edit/test/edit.js @@ -7,11 +7,7 @@ import { noop } from 'lodash'; /** * WordPress dependencies */ -import { - registerBlockType, - unregisterBlockType, - getBlockTypes, -} from '@wordpress/blocks'; +import { registerBlockType, unregisterBlockType, getBlockTypes } from '@wordpress/blocks'; /** * Internal dependencies @@ -70,9 +66,7 @@ describe( 'Edit', () => { title: 'block title', } ); - const wrapper = shallow( - - ); + const wrapper = shallow( ); expect( wrapper.find( edit ).hasClass( 'wp-block-test-block' ) ).toBe( true ); expect( wrapper.find( edit ).hasClass( 'my-class' ) ).toBe( true ); diff --git a/packages/block-editor/src/components/block-editor-keyboard-shortcuts/index.js b/packages/block-editor/src/components/block-editor-keyboard-shortcuts/index.js index 7e9a433182eba6..32cb5df78d78b5 100644 --- a/packages/block-editor/src/components/block-editor-keyboard-shortcuts/index.js +++ b/packages/block-editor/src/components/block-editor-keyboard-shortcuts/index.js @@ -97,18 +97,30 @@ class BlockEditorKeyboardShortcuts extends Component { shortcuts={ { // Prevents bookmark all Tabs shortcut in Chrome when devtools are closed. // Prevents reposition Chrome devtools pane shortcut when devtools are open. - [ shortcuts.duplicate.raw ]: flow( preventDefault, onDuplicate ), + [ shortcuts.duplicate.raw ]: flow( + preventDefault, + onDuplicate + ), // Does not clash with any known browser/native shortcuts, but preventDefault // is used to prevent any obscure unknown shortcuts from triggering. - [ shortcuts.removeBlock.raw ]: flow( preventDefault, onRemove ), + [ shortcuts.removeBlock.raw ]: flow( + preventDefault, + onRemove + ), // Prevent 'view recently closed tabs' in Opera using preventDefault. - [ shortcuts.insertBefore.raw ]: flow( preventDefault, onInsertBefore ), + [ shortcuts.insertBefore.raw ]: flow( + preventDefault, + onInsertBefore + ), // Does not clash with any known browser/native shortcuts, but preventDefault // is used to prevent any obscure unknown shortcuts from triggering. - [ shortcuts.insertAfter.raw ]: flow( preventDefault, onInsertAfter ), + [ shortcuts.insertAfter.raw ]: flow( + preventDefault, + onInsertAfter + ), } } /> ) } @@ -141,11 +153,7 @@ export default compose( [ }; } ), withDispatch( ( dispatch ) => { - const { - clearSelectedBlock, - multiSelect, - removeBlocks, - } = dispatch( 'core/block-editor' ); + const { clearSelectedBlock, multiSelect, removeBlocks } = dispatch( 'core/block-editor' ); return { clearSelectedBlock, diff --git a/packages/block-editor/src/components/block-icon/index.js b/packages/block-editor/src/components/block-icon/index.js index 4d6106214df7d8..51a4a45282f387 100644 --- a/packages/block-editor/src/components/block-icon/index.js +++ b/packages/block-editor/src/components/block-icon/index.js @@ -12,24 +12,28 @@ import { Path, Icon, SVG } from '@wordpress/components'; export default function BlockIcon( { icon, showColors = false, className } ) { if ( get( icon, [ 'src' ] ) === 'block-default' ) { icon = { - src: , + src: ( + + + + ), }; } const renderedIcon = ; - const style = showColors ? { - backgroundColor: icon && icon.background, - color: icon && icon.foreground, - } : {}; + const style = showColors + ? { + backgroundColor: icon && icon.background, + color: icon && icon.foreground, + } + : {}; return ( { renderedIcon } diff --git a/packages/block-editor/src/components/block-icon/index.native.js b/packages/block-editor/src/components/block-icon/index.native.js index 4dddda5ecce8f0..5708c21d863189 100644 --- a/packages/block-editor/src/components/block-icon/index.native.js +++ b/packages/block-editor/src/components/block-icon/index.native.js @@ -12,19 +12,21 @@ import { Path, Icon, SVG } from '@wordpress/components'; export default function BlockIcon( { icon, showColors = false } ) { if ( get( icon, [ 'src' ] ) === 'block-default' ) { icon = { - src: , + src: ( + + + + ), }; } const renderedIcon = ; - const style = showColors ? { - backgroundColor: icon && icon.background, - color: icon && icon.foreground, - } : {}; + const style = showColors + ? { + backgroundColor: icon && icon.background, + color: icon && icon.foreground, + } + : {}; - return ( - - { renderedIcon } - - ); + return { renderedIcon }; } diff --git a/packages/block-editor/src/components/block-icon/test/index.js b/packages/block-editor/src/components/block-icon/test/index.js index 8c74330ad34d49..36b01445309776 100644 --- a/packages/block-editor/src/components/block-icon/test/index.js +++ b/packages/block-editor/src/components/block-icon/test/index.js @@ -39,7 +39,9 @@ describe( 'BlockIcon', () => { } ); it( 'adds background and foreground styles when colors are enabled', () => { - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper.find( 'span' ).prop( 'style' ) ).toEqual( { backgroundColor: 'white', diff --git a/packages/block-editor/src/components/block-inspector/index.js b/packages/block-editor/src/components/block-inspector/index.js index 77d71584cda917..758e9de8034a29 100644 --- a/packages/block-editor/src/components/block-inspector/index.js +++ b/packages/block-editor/src/components/block-inspector/index.js @@ -55,29 +55,28 @@ const BlockInspector = ( { { hasBlockStyles && (
    - - + +
    ) } -
    +
    + +
    - { ( fills ) => ! isEmpty( fills ) && ( - - { fills } - - ) } + { ( fills ) => + ! isEmpty( fills ) && ( + + { fills } + + ) + }
    @@ -85,20 +84,20 @@ const BlockInspector = ( { ); }; -export default withSelect( - ( select ) => { - const { getSelectedBlockClientId, getSelectedBlockCount, getBlockName } = select( 'core/block-editor' ); - const { getBlockStyles } = select( 'core/blocks' ); - const selectedBlockClientId = getSelectedBlockClientId(); - const selectedBlockName = selectedBlockClientId && getBlockName( selectedBlockClientId ); - const blockType = selectedBlockClientId && getBlockType( selectedBlockName ); - const blockStyles = selectedBlockClientId && getBlockStyles( selectedBlockName ); - return { - count: getSelectedBlockCount(), - hasBlockStyles: blockStyles && blockStyles.length > 0, - selectedBlockName, - selectedBlockClientId, - blockType, - }; - } -)( BlockInspector ); +export default withSelect( ( select ) => { + const { getSelectedBlockClientId, getSelectedBlockCount, getBlockName } = select( + 'core/block-editor' + ); + const { getBlockStyles } = select( 'core/blocks' ); + const selectedBlockClientId = getSelectedBlockClientId(); + const selectedBlockName = selectedBlockClientId && getBlockName( selectedBlockClientId ); + const blockType = selectedBlockClientId && getBlockType( selectedBlockName ); + const blockStyles = selectedBlockClientId && getBlockStyles( selectedBlockName ); + return { + count: getSelectedBlockCount(), + hasBlockStyles: blockStyles && blockStyles.length > 0, + selectedBlockName, + selectedBlockClientId, + blockType, + }; +} )( BlockInspector ); diff --git a/packages/block-editor/src/components/block-list-appender/index.js b/packages/block-editor/src/components/block-list-appender/index.js index ddc22b3b928bbf..1fed6fbfac7578 100644 --- a/packages/block-editor/src/components/block-list-appender/index.js +++ b/packages/block-editor/src/components/block-list-appender/index.js @@ -61,20 +61,13 @@ function BlockListAppender( { // default block can't be inserted. return (
    - +
    ); } export default withSelect( ( select, { rootClientId } ) => { - const { - getBlockOrder, - canInsertBlockType, - getTemplateLock, - } = select( 'core/block-editor' ); + const { getBlockOrder, canInsertBlockType, getTemplateLock } = select( 'core/block-editor' ); return { isLocked: !! getTemplateLock( rootClientId ), diff --git a/packages/block-editor/src/components/block-list-appender/index.native.js b/packages/block-editor/src/components/block-list-appender/index.native.js index 6d8fb4e6cee976..b5dff1b57b0437 100644 --- a/packages/block-editor/src/components/block-list-appender/index.native.js +++ b/packages/block-editor/src/components/block-list-appender/index.native.js @@ -27,9 +27,7 @@ function BlockListAppender( { } if ( CustomAppender ) { - return ( - - ); + return ; } if ( canInsertDefaultBlock ) { @@ -47,11 +45,7 @@ function BlockListAppender( { } export default withSelect( ( select, { rootClientId } ) => { - const { - getBlockOrder, - canInsertBlockType, - getTemplateLock, - } = select( 'core/block-editor' ); + const { getBlockOrder, canInsertBlockType, getTemplateLock } = select( 'core/block-editor' ); return { isLocked: !! getTemplateLock( rootClientId ), diff --git a/packages/block-editor/src/components/block-list/block-async-mode-provider.js b/packages/block-editor/src/components/block-list/block-async-mode-provider.js index aaa2e709db92c6..d4eadfbc96c1b9 100644 --- a/packages/block-editor/src/components/block-list/block-async-mode-provider.js +++ b/packages/block-editor/src/components/block-list/block-async-mode-provider.js @@ -1,10 +1,7 @@ /** * WordPress dependencies */ -import { - __experimentalAsyncModeProvider as AsyncModeProvider, - useSelect, -} from '@wordpress/data'; +import { __experimentalAsyncModeProvider as AsyncModeProvider, useSelect } from '@wordpress/data'; const BlockAsyncModeProvider = ( { children, clientId, isBlockInSelection } ) => { const isParentOfSelectedBlock = useSelect( ( select ) => { @@ -13,11 +10,7 @@ const BlockAsyncModeProvider = ( { children, clientId, isBlockInSelection } ) => const isSyncModeForced = isBlockInSelection || isParentOfSelectedBlock; - return ( - - { children } - - ); + return { children }; }; export default BlockAsyncModeProvider; diff --git a/packages/block-editor/src/components/block-list/block-html.js b/packages/block-editor/src/components/block-list/block-html.js index ce70122701828e..d9f0bd7f8f9483 100644 --- a/packages/block-editor/src/components/block-list/block-html.js +++ b/packages/block-editor/src/components/block-list/block-html.js @@ -1,4 +1,3 @@ - /** * External dependencies */ @@ -10,7 +9,13 @@ import { isEqual } from 'lodash'; */ import { Component } from '@wordpress/element'; import { compose } from '@wordpress/compose'; -import { getBlockAttributes, getBlockContent, getBlockType, isValidBlockContent, getSaveContent } from '@wordpress/blocks'; +import { + getBlockAttributes, + getBlockContent, + getBlockType, + isValidBlockContent, + getSaveContent, +} from '@wordpress/blocks'; import { withSelect, withDispatch } from '@wordpress/data'; export class BlockHTML extends Component { @@ -71,7 +76,11 @@ export default compose( [ } ) ), withDispatch( ( dispatch ) => ( { onChange( clientId, attributes, originalContent, isValid ) { - dispatch( 'core/block-editor' ).updateBlock( clientId, { attributes, originalContent, isValid } ); + dispatch( 'core/block-editor' ).updateBlock( clientId, { + attributes, + originalContent, + isValid, + } ); }, } ) ), ] )( BlockHTML ); diff --git a/packages/block-editor/src/components/block-list/block-invalid-warning.js b/packages/block-editor/src/components/block-list/block-invalid-warning.js index f28c4224058356..8ce9fcf8d03d32 100644 --- a/packages/block-editor/src/components/block-list/block-invalid-warning.js +++ b/packages/block-editor/src/components/block-list/block-invalid-warning.js @@ -4,11 +4,7 @@ import { __, _x } from '@wordpress/i18n'; import { Button, Modal } from '@wordpress/components'; import { Component } from '@wordpress/element'; -import { - getBlockType, - createBlock, - rawHandler, -} from '@wordpress/blocks'; +import { getBlockType, createBlock, rawHandler } from '@wordpress/blocks'; import { compose } from '@wordpress/compose'; import { withDispatch, withSelect } from '@wordpress/data'; @@ -36,7 +32,13 @@ export class BlockInvalidWarning extends Component { } render() { - const { convertToHTML, convertToBlocks, convertToClassic, attemptBlockRecovery, block } = this.props; + const { + convertToHTML, + convertToBlocks, + convertToClassic, + attemptBlockRecovery, + block, + } = this.props; const hasHTMLBlock = !! getBlockType( 'core/html' ); const { compare } = this.state; const hiddenActions = [ @@ -49,10 +51,8 @@ export class BlockInvalidWarning extends Component { - { - // translators: Button to fix block content - _x( 'Resolve', 'imperative verb' ) - } + { // translators: Button to fix block content + _x( 'Resolve', 'imperative verb' ) } , hasHTMLBlock && (
    ); } } export default withSelect( ( select, { clientId, rootClientId } ) => { - const { - getBlockIndex, - getBlockInsertionPoint, - isBlockInsertionPointVisible, - } = select( 'core/block-editor' ); + const { getBlockIndex, getBlockInsertionPoint, isBlockInsertionPointVisible } = select( + 'core/block-editor' + ); const blockIndex = getBlockIndex( clientId, rootClientId ); const insertionPoint = getBlockInsertionPoint(); - const showInsertionPoint = ( + const showInsertionPoint = isBlockInsertionPointVisible() && insertionPoint.index === blockIndex && - insertionPoint.rootClientId === rootClientId - ); + insertionPoint.rootClientId === rootClientId; return { showInsertionPoint }; } )( BlockInsertionPoint ); diff --git a/packages/block-editor/src/components/block-list/insertion-point.native.js b/packages/block-editor/src/components/block-list/insertion-point.native.js index d6caa88f407fba..caa7ec96ff1c05 100644 --- a/packages/block-editor/src/components/block-list/insertion-point.native.js +++ b/packages/block-editor/src/components/block-list/insertion-point.native.js @@ -20,27 +20,24 @@ const BlockInsertionPoint = ( { showInsertionPoint } ) => { } return ( - + - { __( 'ADD BLOCK HERE' ) } + { __( 'ADD BLOCK HERE' ) } ); }; export default withSelect( ( select, { clientId, rootClientId } ) => { - const { - getBlockIndex, - getBlockInsertionPoint, - isBlockInsertionPointVisible, - } = select( 'core/block-editor' ); + const { getBlockIndex, getBlockInsertionPoint, isBlockInsertionPointVisible } = select( + 'core/block-editor' + ); const blockIndex = getBlockIndex( clientId, rootClientId ); const insertionPoint = getBlockInsertionPoint(); - const showInsertionPoint = ( + const showInsertionPoint = isBlockInsertionPointVisible() && insertionPoint.index === blockIndex && - insertionPoint.rootClientId === rootClientId - ); + insertionPoint.rootClientId === rootClientId; return { showInsertionPoint }; } )( BlockInsertionPoint ); diff --git a/packages/block-editor/src/components/block-list/moving-animation.js b/packages/block-editor/src/components/block-list/moving-animation.js index afa36bb40304d2..8c538277725753 100644 --- a/packages/block-editor/src/components/block-list/moving-animation.js +++ b/packages/block-editor/src/components/block-list/moving-animation.js @@ -44,7 +44,13 @@ const getAbsolutePosition = ( element ) => { * * @return {Object} Style object. */ -function useMovingAnimation( ref, isSelected, adjustScrolling, enableAnimation, triggerAnimationOnChange ) { +function useMovingAnimation( + ref, + isSelected, + adjustScrolling, + enableAnimation, + triggerAnimationOnChange +) { const prefersReducedMotion = useReducedMotion() || ! enableAnimation; const [ triggeredAnimation, triggerAnimation ] = useReducer( counterReducer, 0 ); const [ finishedAnimation, endAnimation ] = useReducer( counterReducer, 0 ); @@ -80,11 +86,15 @@ function useMovingAnimation( ref, isSelected, adjustScrolling, enableAnimation, const newTransform = { x: previous ? previous.left - destination.left : 0, y: previous ? previous.top - destination.top : 0, - scrollTop: previous && scrollContainer ? scrollContainer.scrollTop - previous.top + destination.top : 0, + scrollTop: + previous && scrollContainer + ? scrollContainer.scrollTop - previous.top + destination.top + : 0, }; - ref.current.style.transform = newTransform.x === 0 && newTransform.y === 0 ? - undefined : - `translate3d(${ newTransform.x }px,${ newTransform.y }px,0)`; + ref.current.style.transform = + newTransform.x === 0 && newTransform.y === 0 + ? undefined + : `translate3d(${ newTransform.x }px,${ newTransform.y }px,0)`; triggerAnimation(); setTransform( newTransform ); }, [ triggerAnimationOnChange ] ); @@ -109,25 +119,17 @@ function useMovingAnimation( ref, isSelected, adjustScrolling, enableAnimation, } ); // Dismiss animations if disabled. - return prefersReducedMotion ? - {} : - { - transformOrigin: 'center', - transform: interpolate( - [ - animationProps.x, - animationProps.y, - ], - ( x, y ) => x === 0 && y === 0 ? undefined : `translate3d(${ x }px,${ y }px,0)` - ), - zIndex: interpolate( - [ - animationProps.x, - animationProps.y, - ], - ( x, y ) => ! isSelected || ( x === 0 && y === 0 ) ? undefined : `1` - ), - }; + return prefersReducedMotion + ? {} + : { + transformOrigin: 'center', + transform: interpolate( [ animationProps.x, animationProps.y ], ( x, y ) => + x === 0 && y === 0 ? undefined : `translate3d(${ x }px,${ y }px,0)` + ), + zIndex: interpolate( [ animationProps.x, animationProps.y ], ( x, y ) => + ! isSelected || ( x === 0 && y === 0 ) ? undefined : `1` + ), + }; } export default useMovingAnimation; diff --git a/packages/block-editor/src/components/block-list/multi-controls.js b/packages/block-editor/src/components/block-list/multi-controls.js index e4dd88aeda030f..2cee3e43d8ed7c 100644 --- a/packages/block-editor/src/components/block-list/multi-controls.js +++ b/packages/block-editor/src/components/block-list/multi-controls.js @@ -8,26 +8,16 @@ import { withSelect } from '@wordpress/data'; */ import BlockMover from '../block-mover'; -function BlockListMultiControls( { - multiSelectedBlockClientIds, - isSelecting, -} ) { +function BlockListMultiControls( { multiSelectedBlockClientIds, isSelecting } ) { if ( isSelecting ) { return null; } - return ( - - ); + return ; } export default withSelect( ( select ) => { - const { - getMultiSelectedBlockClientIds, - isMultiSelecting, - } = select( 'core/block-editor' ); + const { getMultiSelectedBlockClientIds, isMultiSelecting } = select( 'core/block-editor' ); const clientIds = getMultiSelectedBlockClientIds(); return { diff --git a/packages/block-editor/src/components/block-list/nav-up-icon.js b/packages/block-editor/src/components/block-list/nav-up-icon.js index 8fa1c8d20bd761..a1878c28df2419 100644 --- a/packages/block-editor/src/components/block-list/nav-up-icon.js +++ b/packages/block-editor/src/components/block-list/nav-up-icon.js @@ -3,6 +3,16 @@ */ import { SVG, Path } from '@wordpress/components'; -const NavigateUp = ; +const NavigateUp = ( + + + + +); export default NavigateUp; diff --git a/packages/block-editor/src/components/block-list/test/block-html.js b/packages/block-editor/src/components/block-list/test/block-html.js index 442e55de3f5bba..e3d876382585c6 100644 --- a/packages/block-editor/src/components/block-list/test/block-html.js +++ b/packages/block-editor/src/components/block-list/test/block-html.js @@ -27,7 +27,9 @@ describe( 'BlockHTML', () => { describe( 'block content', () => { it( 'use originalContent for an invalid block', () => { - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper.state( 'html' ) ).toBe( 'test' ); } ); diff --git a/packages/block-editor/src/components/block-mover/drag-handle.js b/packages/block-editor/src/components/block-mover/drag-handle.js index 86551bf4be0e30..c2d466dafa1b6c 100644 --- a/packages/block-editor/src/components/block-mover/drag-handle.js +++ b/packages/block-editor/src/components/block-mover/drag-handle.js @@ -8,12 +8,23 @@ import classnames from 'classnames'; */ import BlockDraggable from '../block-draggable'; -export const IconDragHandle = ( { isVisible, className, icon, onDragStart, onDragEnd, blockElementId, clientId } ) => { +export const IconDragHandle = ( { + isVisible, + className, + icon, + onDragStart, + onDragEnd, + blockElementId, + clientId, +} ) => { if ( ! isVisible ) { return null; } - const dragHandleClassNames = classnames( 'editor-block-mover__control-drag-handle block-editor-block-mover__control-drag-handle', className ); + const dragHandleClassNames = classnames( + 'editor-block-mover__control-drag-handle block-editor-block-mover__control-drag-handle', + className + ); return ( - { - ( { onDraggableStart, onDraggableEnd } ) => ( - - ) } + { ( { onDraggableStart, onDraggableEnd } ) => ( + + ) } ); }; diff --git a/packages/block-editor/src/components/block-mover/icons.js b/packages/block-editor/src/components/block-mover/icons.js index 06bf5601f439db..dd1d0ca06d3120 100644 --- a/packages/block-editor/src/components/block-mover/icons.js +++ b/packages/block-editor/src/components/block-mover/icons.js @@ -17,8 +17,10 @@ export const downArrow = ( export const dragHandle = ( - + C8.4,6,8,6.4,8,7s0.4,1,1,1s1-0.4,1-1S9.6,6,9,6z M9,10c-0.6,0-1,0.4-1,1s0.4,1,1,1s1-0.4,1-1S9.6,10,9,10z" + /> ); diff --git a/packages/block-editor/src/components/block-mover/index.js b/packages/block-editor/src/components/block-mover/index.js index dd09dc1c86b7c5..9575485d3d6547 100644 --- a/packages/block-editor/src/components/block-mover/index.js +++ b/packages/block-editor/src/components/block-mover/index.js @@ -44,7 +44,23 @@ export class BlockMover extends Component { } render() { - const { onMoveUp, onMoveDown, isFirst, isLast, isDraggable, onDragStart, onDragEnd, clientIds, blockElementId, blockType, firstIndex, isLocked, instanceId, isHidden, rootClientId } = this.props; + const { + onMoveUp, + onMoveDown, + isFirst, + isLast, + isDraggable, + onDragStart, + onDragEnd, + clientIds, + blockElementId, + blockType, + firstIndex, + isLocked, + instanceId, + isHidden, + rootClientId, + } = this.props; const { isFocused } = this.state; const blocksCount = castArray( clientIds ).length; if ( isLocked || ( isFirst && isLast && ! rootClientId ) ) { @@ -56,7 +72,11 @@ export class BlockMover extends Component { // to an unfocused state (body as active element) without firing blur on, // the rendering parent, leaving it unable to react to focus out. return ( -
    +
    - - { - getBlockMoverDescription( - blocksCount, - blockType && blockType.title, - firstIndex, - isFirst, - isLast, - -1, - ) - } + + { getBlockMoverDescription( + blocksCount, + blockType && blockType.title, + firstIndex, + isFirst, + isLast, + -1 + ) } - - { - getBlockMoverDescription( - blocksCount, - blockType && blockType.title, - firstIndex, - isFirst, - isLast, - 1, - ) - } + + { getBlockMoverDescription( + blocksCount, + blockType && blockType.title, + firstIndex, + isFirst, + isLast, + 1 + ) }
    ); @@ -117,7 +139,13 @@ export class BlockMover extends Component { export default compose( withSelect( ( select, { clientIds } ) => { - const { getBlock, getBlockIndex, getTemplateLock, getBlockRootClientId, getBlockOrder } = select( 'core/block-editor' ); + const { + getBlock, + getBlockIndex, + getTemplateLock, + getBlockRootClientId, + getBlockOrder, + } = select( 'core/block-editor' ); const normalizedClientIds = castArray( clientIds ); const firstClientId = first( normalizedClientIds ); const block = getBlock( firstClientId ); @@ -142,5 +170,5 @@ export default compose( onMoveUp: partial( moveBlocksUp, clientIds, rootClientId ), }; } ), - withInstanceId, + withInstanceId )( BlockMover ); diff --git a/packages/block-editor/src/components/block-mover/index.native.js b/packages/block-editor/src/components/block-mover/index.native.js index 40bc4d550b7ab6..1e0cf94fc99949 100644 --- a/packages/block-editor/src/components/block-mover/index.native.js +++ b/packages/block-editor/src/components/block-mover/index.native.js @@ -27,14 +27,15 @@ const BlockMover = ( { return ( <> { - const { getBlockIndex, getTemplateLock, getBlockRootClientId, getBlockOrder } = select( 'core/block-editor' ); + const { getBlockIndex, getTemplateLock, getBlockRootClientId, getBlockOrder } = select( + 'core/block-editor' + ); const normalizedClientIds = castArray( clientIds ); const firstClientId = first( normalizedClientIds ); const rootClientId = getBlockRootClientId( firstClientId ); @@ -86,5 +90,5 @@ export default compose( onMoveUp: partial( moveBlocksUp, clientIds, rootClientId ), }; } ), - withInstanceId, + withInstanceId )( BlockMover ); diff --git a/packages/block-editor/src/components/block-mover/mover-description.js b/packages/block-editor/src/components/block-mover/mover-description.js index 44174ce85534ca..a663fddfe79eea 100644 --- a/packages/block-editor/src/components/block-mover/mover-description.js +++ b/packages/block-editor/src/components/block-mover/mover-description.js @@ -18,7 +18,7 @@ import { __, _n, sprintf } from '@wordpress/i18n'; * @return {string} Label for the block movement controls. */ export function getBlockMoverDescription( selectedCount, type, firstIndex, isFirst, isLast, dir ) { - const position = ( firstIndex + 1 ); + const position = firstIndex + 1; if ( selectedCount > 1 ) { return getMultiBlockMoverDescription( selectedCount, firstIndex, isFirst, isLast, dir ); @@ -36,7 +36,7 @@ export function getBlockMoverDescription( selectedCount, type, firstIndex, isFir __( 'Move %1$s block from position %2$d down to position %3$d' ), type, position, - ( position + 1 ) + position + 1 ); } @@ -53,14 +53,17 @@ export function getBlockMoverDescription( selectedCount, type, firstIndex, isFir __( 'Move %1$s block from position %2$d up to position %3$d' ), type, position, - ( position - 1 ) + position - 1 ); } if ( dir < 0 && isFirst ) { // moving up, and is the first item // translators: %s: Type of block (i.e. Text, Image etc) - return sprintf( __( 'Block %s is at the beginning of the content and can’t be moved up' ), type ); + return sprintf( + __( 'Block %s is at the beginning of the content and can’t be moved up' ), + type + ); } } @@ -77,7 +80,7 @@ export function getBlockMoverDescription( selectedCount, type, firstIndex, isFir * @return {string} Label for the block movement controls. */ export function getMultiBlockMoverDescription( selectedCount, firstIndex, isFirst, isLast, dir ) { - const position = ( firstIndex + 1 ); + const position = firstIndex + 1; if ( dir < 0 && isFirst ) { return __( 'Blocks cannot be moved up as they are already at the top' ); diff --git a/packages/block-editor/src/components/block-mover/test/index.js b/packages/block-editor/src/components/block-mover/test/index.js index 48809ae7905669..c7496763b1084c 100644 --- a/packages/block-editor/src/components/block-mover/test/index.js +++ b/packages/block-editor/src/components/block-mover/test/index.js @@ -28,7 +28,8 @@ describe( 'BlockMover', () => { clientIds={ selectedClientIds } blockType={ blockType } firstIndex={ 0 } - instanceId={ 1 } /> + instanceId={ 1 } + /> ); expect( blockMover.hasClass( 'block-editor-block-mover' ) ).toBe( true ); @@ -111,11 +112,7 @@ describe( 'BlockMover', () => { it( 'should not render the drag handle if block is not draggable', () => { const blockMover = shallow( - + ); const dragHandler = blockMover.childAt( 1 ); expect( dragHandler.type().name ).toBe( 'IconDragHandle' ); diff --git a/packages/block-editor/src/components/block-mover/test/mover-description.js b/packages/block-editor/src/components/block-mover/test/mover-description.js index 63fa6ad52a3ba5..6ec250c5adfe2d 100644 --- a/packages/block-editor/src/components/block-mover/test/mover-description.js +++ b/packages/block-editor/src/components/block-mover/test/mover-description.js @@ -11,102 +11,59 @@ describe( 'block mover', () => { const type = 'TestType'; it( 'Should generate a title for the first item moving up', () => { - expect( getBlockMoverDescription( - 1, - type, - 0, - true, - false, - dirUp, - ) ).toBe( + expect( getBlockMoverDescription( 1, type, 0, true, false, dirUp ) ).toBe( `Block ${ type } is at the beginning of the content and can’t be moved up` ); } ); it( 'Should generate a title for the last item moving down', () => { - expect( getBlockMoverDescription( - 1, - type, - 3, - false, - true, - dirDown, - ) ).toBe( `Block ${ type } is at the end of the content and can’t be moved down` ); + expect( getBlockMoverDescription( 1, type, 3, false, true, dirDown ) ).toBe( + `Block ${ type } is at the end of the content and can’t be moved down` + ); } ); it( 'Should generate a title for the second item moving up', () => { - expect( getBlockMoverDescription( - 1, - type, - 1, - false, - false, - dirUp, - ) ).toBe( `Move ${ type } block from position 2 up to position 1` ); + expect( getBlockMoverDescription( 1, type, 1, false, false, dirUp ) ).toBe( + `Move ${ type } block from position 2 up to position 1` + ); } ); it( 'Should generate a title for the second item moving down', () => { - expect( getBlockMoverDescription( - 1, - type, - 1, - false, - false, - dirDown, - ) ).toBe( `Move ${ type } block from position 2 down to position 3` ); + expect( getBlockMoverDescription( 1, type, 1, false, false, dirDown ) ).toBe( + `Move ${ type } block from position 2 down to position 3` + ); } ); it( 'Should generate a title for the only item in the list', () => { - expect( getBlockMoverDescription( - 1, - type, - 0, - true, - true, - dirDown, - ) ).toBe( `Block ${ type } is the only block, and cannot be moved` ); + expect( getBlockMoverDescription( 1, type, 0, true, true, dirDown ) ).toBe( + `Block ${ type } is the only block, and cannot be moved` + ); } ); } ); describe( 'getMultiBlockMoverDescription', () => { it( 'Should generate a title moving multiple blocks up', () => { - expect( getMultiBlockMoverDescription( - 4, - 1, - false, - true, - dirUp, - ) ).toBe( 'Move 4 blocks from position 2 up by one place' ); + expect( getMultiBlockMoverDescription( 4, 1, false, true, dirUp ) ).toBe( + 'Move 4 blocks from position 2 up by one place' + ); } ); it( 'Should generate a title moving multiple blocks down', () => { - expect( getMultiBlockMoverDescription( - 4, - 0, - true, - false, - dirDown, - ) ).toBe( 'Move 4 blocks from position 1 down by one place' ); + expect( getMultiBlockMoverDescription( 4, 0, true, false, dirDown ) ).toBe( + 'Move 4 blocks from position 1 down by one place' + ); } ); it( 'Should generate a title for a selection of blocks at the top', () => { - expect( getMultiBlockMoverDescription( - 4, - 1, - true, - true, - dirUp, - ) ).toBe( 'Blocks cannot be moved up as they are already at the top' ); + expect( getMultiBlockMoverDescription( 4, 1, true, true, dirUp ) ).toBe( + 'Blocks cannot be moved up as they are already at the top' + ); } ); it( 'Should generate a title for a selection of blocks at the bottom', () => { - expect( getMultiBlockMoverDescription( - 4, - 2, - false, - true, - dirDown, - ) ).toBe( 'Blocks cannot be moved down as they are already at the bottom' ); + expect( getMultiBlockMoverDescription( 4, 2, false, true, dirDown ) ).toBe( + 'Blocks cannot be moved down as they are already at the bottom' + ); } ); } ); } ); diff --git a/packages/block-editor/src/components/block-navigation/dropdown.js b/packages/block-editor/src/components/block-navigation/dropdown.js index b53dd49bdf4bdc..881b8c5e1be19c 100644 --- a/packages/block-editor/src/components/block-navigation/dropdown.js +++ b/packages/block-editor/src/components/block-navigation/dropdown.js @@ -20,18 +20,19 @@ const MenuIcon = ( function BlockNavigationDropdown( { hasBlocks, isDisabled } ) { const isEnabled = hasBlocks && ! isDisabled; - return ( + return ( ( <> - { isEnabled && - } + { isEnabled && ( + + ) } ) } - renderContent={ ( { onClose } ) => ( - - ) } + renderContent={ ( { onClose } ) => } /> ); } diff --git a/packages/block-editor/src/components/block-navigation/index.js b/packages/block-editor/src/components/block-navigation/index.js index f6b82955cb2673..a0be48f14dd609 100644 --- a/packages/block-editor/src/components/block-navigation/index.js +++ b/packages/block-editor/src/components/block-navigation/index.js @@ -21,19 +21,19 @@ function BlockNavigation( { rootBlock, rootBlocks, selectedBlockClientId, select return null; } - const hasHierarchy = ( - rootBlock && ( - rootBlock.clientId !== selectedBlockClientId || - ( rootBlock.innerBlocks && rootBlock.innerBlocks.length !== 0 ) - ) - ); + const hasHierarchy = + rootBlock && + ( rootBlock.clientId !== selectedBlockClientId || + ( rootBlock.innerBlocks && rootBlock.innerBlocks.length !== 0 ) ); return ( -

    { __( 'Block navigation' ) }

    +

    + { __( 'Block navigation' ) } +

    { hasHierarchy && ( { - const { - getSelectedBlockClientId, - getBlockHierarchyRootClientId, - getBlock, - getBlocks, - } = select( 'core/block-editor' ); + const { getSelectedBlockClientId, getBlockHierarchyRootClientId, getBlock, getBlocks } = select( + 'core/block-editor' + ); const selectedBlockClientId = getSelectedBlockClientId(); return { rootBlocks: getBlocks(), - rootBlock: selectedBlockClientId ? getBlock( getBlockHierarchyRootClientId( selectedBlockClientId ) ) : null, + rootBlock: selectedBlockClientId + ? getBlock( getBlockHierarchyRootClientId( selectedBlockClientId ) ) + : null, selectedBlockClientId, }; } ), diff --git a/packages/block-editor/src/components/block-navigation/list.js b/packages/block-editor/src/components/block-navigation/list.js index a0910caf5b41cc..546fc41eeaa5c0 100644 --- a/packages/block-editor/src/components/block-navigation/list.js +++ b/packages/block-editor/src/components/block-navigation/list.js @@ -60,14 +60,19 @@ export default function BlockNavigationList( {
  • { showNestedBlocks && !! block.innerBlocks && !! block.innerBlocks.length && ( diff --git a/packages/block-editor/src/components/block-preview/index.js b/packages/block-editor/src/components/block-preview/index.js index 8a6692a422a6f7..05ac9ce4748890 100644 --- a/packages/block-editor/src/components/block-preview/index.js +++ b/packages/block-editor/src/components/block-preview/index.js @@ -44,17 +44,19 @@ function ScaledBlockPreview( { blocks, viewportWidth, padding = 0 } ) { let containerElementRect = containerElement.getBoundingClientRect(); containerElementRect = { - width: containerElementRect.width - ( padding * 2 ), - height: containerElementRect.height - ( padding * 2 ), + width: containerElementRect.width - padding * 2, + height: containerElementRect.height - padding * 2, left: containerElementRect.left, top: containerElementRect.top, }; const scaledElementRect = previewElement.getBoundingClientRect(); const scale = containerElementRect.width / scaledElementRect.width || 1; - const offsetX = ( -( scaledElementRect.left - containerElementRect.left ) * scale ) + padding; - const offsetY = ( containerElementRect.height > scaledElementRect.height * scale ) ? - ( ( containerElementRect.height - ( scaledElementRect.height * scale ) ) / 2 ) + padding : 0; + const offsetX = -( scaledElementRect.left - containerElementRect.left ) * scale + padding; + const offsetY = + containerElementRect.height > scaledElementRect.height * scale + ? ( containerElementRect.height - scaledElementRect.height * scale ) / 2 + padding + : 0; setPreviewScale( scale ); setPosition( { x: offsetX, y: offsetY } ); @@ -109,17 +111,12 @@ export function BlockPreview( { blocks, viewportWidth = 700, padding, settings } const [ recompute, triggerRecompute ] = useReducer( ( state ) => state + 1, 0 ); useLayoutEffect( triggerRecompute, [ blocks ] ); return ( - - { - /* - * The key prop is used to force recomputing the preview - * by remounting the component, ScaledBlockPreview is not meant to - * be rerendered. - */ - } + + { /* + * The key prop is used to force recomputing the preview + * by remounting the component, ScaledBlockPreview is not meant to + * be rerendered. + */ } ); } diff --git a/packages/block-editor/src/components/block-settings-menu/block-html-convert-button.js b/packages/block-editor/src/components/block-settings-menu/block-html-convert-button.js index 3527d7d0d460c0..339b6cdbd11e79 100644 --- a/packages/block-editor/src/components/block-settings-menu/block-html-convert-button.js +++ b/packages/block-editor/src/components/block-settings-menu/block-html-convert-button.js @@ -16,13 +16,14 @@ export default compose( return { block, - shouldRender: ( block && block.name === 'core/html' ), + shouldRender: block && block.name === 'core/html', }; } ), withDispatch( ( dispatch, { block } ) => ( { - onClick: () => dispatch( 'core/block-editor' ).replaceBlocks( - block.clientId, - rawHandler( { HTML: getBlockContent( block ) } ), - ), - } ) ), + onClick: () => + dispatch( 'core/block-editor' ).replaceBlocks( + block.clientId, + rawHandler( { HTML: getBlockContent( block ) } ) + ), + } ) ) )( BlockConvertButton ); diff --git a/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js b/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js index d36ab6974e2760..018c7419d89c14 100644 --- a/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js +++ b/packages/block-editor/src/components/block-settings-menu/block-mode-toggle.js @@ -12,14 +12,18 @@ import { getBlockType, hasBlockSupport } from '@wordpress/blocks'; import { withSelect, withDispatch } from '@wordpress/data'; import { compose } from '@wordpress/compose'; -export function BlockModeToggle( { blockType, mode, onToggleMode, small = false, isCodeEditingEnabled = true } ) { +export function BlockModeToggle( { + blockType, + mode, + onToggleMode, + small = false, + isCodeEditingEnabled = true, +} ) { if ( ! hasBlockSupport( blockType, 'html', true ) || ! isCodeEditingEnabled ) { return null; } - const label = mode === 'visual' ? - __( 'Edit as HTML' ) : - __( 'Edit visually' ); + const label = mode === 'visual' ? __( 'Edit as HTML' ) : __( 'Edit visually' ); return ( ( { - onClick: () => dispatch( 'core/block-editor' ).replaceBlocks( - block.clientId, - rawHandler( { HTML: serialize( block ) } ) - ), - } ) ), + onClick: () => + dispatch( 'core/block-editor' ).replaceBlocks( + block.clientId, + rawHandler( { HTML: serialize( block ) } ) + ), + } ) ) )( BlockConvertButton ); diff --git a/packages/block-editor/src/components/block-settings-menu/index.js b/packages/block-editor/src/components/block-settings-menu/index.js index e4f7219d1a3803..41798d33d88ca8 100644 --- a/packages/block-editor/src/components/block-settings-menu/index.js +++ b/packages/block-editor/src/components/block-settings-menu/index.js @@ -7,12 +7,7 @@ import { castArray, flow } from 'lodash'; * WordPress dependencies */ import { __, _n } from '@wordpress/i18n'; -import { - Toolbar, - DropdownMenu, - MenuGroup, - MenuItem, -} from '@wordpress/components'; +import { Toolbar, DropdownMenu, MenuGroup, MenuItem } from '@wordpress/components'; /** * Internal dependencies @@ -56,23 +51,16 @@ export function BlockSettingsMenu( { clientIds } ) { { ( { onClose } ) => ( <> - <__experimentalBlockSettingsMenuFirstItem.Slot - fillProps={ { onClose } } - /> - { count === 1 && ( - - ) } - { count === 1 && ( - - ) } + <__experimentalBlockSettingsMenuFirstItem.Slot fillProps={ { onClose } } /> + { count === 1 && } + { count === 1 && } { canDuplicate && ( @@ -83,7 +71,10 @@ export function BlockSettingsMenu( { clientIds } ) { <> @@ -91,7 +82,10 @@ export function BlockSettingsMenu( { clientIds } ) { @@ -100,10 +94,7 @@ export function BlockSettingsMenu( { clientIds } ) { ) } { count === 1 && ( - + ) } <__experimentalBlockSettingsMenuPluginsExtension.Slot fillProps={ { clientIds, onClose } } @@ -113,7 +104,10 @@ export function BlockSettingsMenu( { clientIds } ) { { ! isLocked && ( diff --git a/packages/block-editor/src/components/block-settings-menu/test/block-mode-toggle.js b/packages/block-editor/src/components/block-settings-menu/test/block-mode-toggle.js index d8bfef8771b878..f789f7c4066f78 100644 --- a/packages/block-editor/src/components/block-settings-menu/test/block-mode-toggle.js +++ b/packages/block-editor/src/components/block-settings-menu/test/block-mode-toggle.js @@ -25,10 +25,7 @@ describe( 'BlockModeToggle', () => { it( 'should render the HTML mode button', () => { const wrapper = getShallowRenderOutput( - + ); const text = wrapper.props.children; @@ -37,10 +34,7 @@ describe( 'BlockModeToggle', () => { it( 'should render the Visual mode button', () => { const wrapper = getShallowRenderOutput( - + ); const text = wrapper.props.children; diff --git a/packages/block-editor/src/components/block-settings/button.native.js b/packages/block-editor/src/components/block-settings/button.native.js index ab2e1601a88800..5225e8bb988c44 100644 --- a/packages/block-editor/src/components/block-settings/button.native.js +++ b/packages/block-editor/src/components/block-settings/button.native.js @@ -7,12 +7,13 @@ import { withDispatch } from '@wordpress/data'; const { Fill, Slot } = createSlotFill( 'SettingsToolbarButton' ); -const SettingsButton = ( { openGeneralSidebar } ) => +const SettingsButton = ( { openGeneralSidebar } ) => ( ; + /> +); const SettingsButtonFill = ( props ) => ( diff --git a/packages/block-editor/src/components/block-settings/container.native.js b/packages/block-editor/src/components/block-settings/container.native.js index 1b59377f29161c..d91c8aa9c129c8 100644 --- a/packages/block-editor/src/components/block-settings/container.native.js +++ b/packages/block-editor/src/components/block-settings/container.native.js @@ -20,16 +20,14 @@ function BottomSheetSettings( { editorSidebarOpened, closeGeneralSidebar, ...pro contentStyle={ styles.content } { ...props } > - + ); } export default compose( [ withSelect( ( select ) => { - const { - isEditorSidebarOpened, - } = select( 'core/edit-post' ); + const { isEditorSidebarOpened } = select( 'core/edit-post' ); return { editorSidebarOpened: isEditorSidebarOpened(), @@ -42,5 +40,4 @@ export default compose( [ closeGeneralSidebar, }; } ), -] -)( BottomSheetSettings ); +] )( BottomSheetSettings ); diff --git a/packages/block-editor/src/components/block-styles/index.js b/packages/block-editor/src/components/block-styles/index.js index 25a2fd7b235cd2..12556fde3bf24e 100644 --- a/packages/block-editor/src/components/block-styles/index.js +++ b/packages/block-editor/src/components/block-styles/index.js @@ -103,11 +103,9 @@ function BlockStyles( { return (
    updateClassName( style ) } onKeyDown={ ( event ) => { if ( ENTER === event.keyCode || SPACE === event.keyCode ) { @@ -125,12 +123,12 @@ function BlockStyles( {
    diff --git a/packages/block-editor/src/components/block-styles/test/index.js b/packages/block-editor/src/components/block-styles/test/index.js index 639d92ed4aeaa3..b2e26781d6becd 100644 --- a/packages/block-editor/src/components/block-styles/test/index.js +++ b/packages/block-editor/src/components/block-styles/test/index.js @@ -5,40 +5,28 @@ import { getActiveStyle, replaceActiveStyle } from '../'; describe( 'getActiveStyle', () => { it( 'Should return the undefined if no active style', () => { - const styles = [ - { name: 'small' }, - { name: 'big' }, - ]; + const styles = [ { name: 'small' }, { name: 'big' } ]; const className = 'custom-className'; expect( getActiveStyle( styles, className ) ).toBeUndefined(); } ); it( 'Should return the default style if no active style', () => { - const styles = [ - { name: 'small' }, - { name: 'big', isDefault: true }, - ]; + const styles = [ { name: 'small' }, { name: 'big', isDefault: true } ]; const className = 'custom-className'; expect( getActiveStyle( styles, className ).name ).toBe( 'big' ); } ); it( 'Should return the active style', () => { - const styles = [ - { name: 'small' }, - { name: 'big', isDefault: true }, - ]; + const styles = [ { name: 'small' }, { name: 'big', isDefault: true } ]; const className = 'this-is-custom is-style-small'; expect( getActiveStyle( styles, className ).name ).toBe( 'small' ); } ); it( 'Should return the first active style', () => { - const styles = [ - { name: 'small' }, - { name: 'big', isDefault: true }, - ]; + const styles = [ { name: 'small' }, { name: 'big', isDefault: true } ]; const className = 'this-is-custom is-style-small is-style-big'; expect( getActiveStyle( styles, className ).name ).toBe( 'small' ); @@ -51,8 +39,9 @@ describe( 'replaceActiveStyle', () => { const newStyle = { name: 'small' }; const className = 'custom-class'; - expect( replaceActiveStyle( className, activeStyle, newStyle ) ) - .toBe( 'custom-class is-style-small' ); + expect( replaceActiveStyle( className, activeStyle, newStyle ) ).toBe( + 'custom-class is-style-small' + ); } ); it( 'Should add the new style if no active style (no existing class)', () => { @@ -60,8 +49,7 @@ describe( 'replaceActiveStyle', () => { const newStyle = { name: 'small' }; const className = ''; - expect( replaceActiveStyle( className, activeStyle, newStyle ) ) - .toBe( 'is-style-small' ); + expect( replaceActiveStyle( className, activeStyle, newStyle ) ).toBe( 'is-style-small' ); } ); it( 'Should add the new style if no active style (unassigned default)', () => { @@ -69,8 +57,7 @@ describe( 'replaceActiveStyle', () => { const newStyle = { name: 'small' }; const className = ''; - expect( replaceActiveStyle( className, activeStyle, newStyle ) ) - .toBe( 'is-style-small' ); + expect( replaceActiveStyle( className, activeStyle, newStyle ) ).toBe( 'is-style-small' ); } ); it( 'Should replace the previous active style', () => { @@ -78,7 +65,8 @@ describe( 'replaceActiveStyle', () => { const newStyle = { name: 'small' }; const className = 'custom-class is-style-large'; - expect( replaceActiveStyle( className, activeStyle, newStyle ) ) - .toBe( 'custom-class is-style-small' ); + expect( replaceActiveStyle( className, activeStyle, newStyle ) ).toBe( + 'custom-class is-style-small' + ); } ); } ); diff --git a/packages/block-editor/src/components/block-switcher/index.js b/packages/block-editor/src/components/block-switcher/index.js index 4f3510e4ebbb2e..3995aaab564e47 100644 --- a/packages/block-editor/src/components/block-switcher/index.js +++ b/packages/block-editor/src/components/block-switcher/index.js @@ -8,7 +8,13 @@ import { castArray, filter, first, mapKeys, orderBy, uniq, map } from 'lodash'; */ import { __, _n, sprintf } from '@wordpress/i18n'; import { Dropdown, IconButton, Toolbar, PanelBody, Path, SVG } from '@wordpress/components'; -import { getBlockType, getPossibleBlockTransformations, switchToBlockType, cloneBlock, getBlockFromExample } from '@wordpress/blocks'; +import { + getBlockType, + getPossibleBlockTransformations, + switchToBlockType, + cloneBlock, + getBlockFromExample, +} from '@wordpress/blocks'; import { Component } from '@wordpress/element'; import { DOWN } from '@wordpress/keycodes'; import { withSelect, withDispatch } from '@wordpress/data'; @@ -95,18 +101,13 @@ export class BlockSwitcher extends Component { onToggle(); } }; - const label = ( - 1 === blocks.length ? - __( 'Change block type or style' ) : - sprintf( - _n( - 'Change type of %d block', - 'Change type of %d blocks', + const label = + 1 === blocks.length + ? __( 'Change block type or style' ) + : sprintf( + _n( 'Change type of %d block', 'Change type of %d blocks', blocks.length ), blocks.length - ), - blocks.length - ) - ); + ); return ( @@ -118,37 +119,37 @@ export class BlockSwitcher extends Component { label={ label } tooltip={ label } onKeyDown={ openOnArrowDown } - icon={ ( + icon={ <> - + + + - ) } + } /> ); } } renderContent={ ( { onClose } ) => ( <> - { ( hasBlockStyles || possibleBlockTransformations.length !== 0 ) && + { ( hasBlockStyles || possibleBlockTransformations.length !== 0 ) && (
    - { hasBlockStyles && - + { hasBlockStyles && ( + - } - { possibleBlockTransformations.length !== 0 && - + ) } + { possibleBlockTransformations.length !== 0 && ( + ( { id: destinationBlockType.name, @@ -161,25 +162,30 @@ export class BlockSwitcher extends Component { } } /> - } + ) }
    - } - { ( hoveredClassName !== null ) && + ) } + { hoveredClassName !== null && (
    -
    { __( 'Preview' ) }
    +
    + { __( 'Preview' ) } +
    - } + ) } ) } /> @@ -189,7 +195,9 @@ export class BlockSwitcher extends Component { export default compose( withSelect( ( select, { clientIds } ) => { - const { getBlocksByClientId, getBlockRootClientId, getInserterItems } = select( 'core/block-editor' ); + const { getBlocksByClientId, getBlockRootClientId, getInserterItems } = select( + 'core/block-editor' + ); const { getBlockStyles } = select( 'core/blocks' ); const rootClientId = getBlockRootClientId( first( castArray( clientIds ) ) ); const blocks = getBlocksByClientId( clientIds ); @@ -208,5 +216,5 @@ export default compose( switchToBlockType( blocks, name ) ); }, - } ) ), + } ) ) )( BlockSwitcher ); diff --git a/packages/block-editor/src/components/block-switcher/multi-blocks-switcher.js b/packages/block-editor/src/components/block-switcher/multi-blocks-switcher.js index 8adae420dab998..369f7c1e79d7e3 100644 --- a/packages/block-editor/src/components/block-switcher/multi-blocks-switcher.js +++ b/packages/block-editor/src/components/block-switcher/multi-blocks-switcher.js @@ -12,17 +12,13 @@ export function MultiBlocksSwitcher( { isMultiBlockSelection, selectedBlockClien if ( ! isMultiBlockSelection ) { return null; } - return ( - - ); + return ; } -export default withSelect( - ( select ) => { - const selectedBlockClientIds = select( 'core/block-editor' ).getMultiSelectedBlockClientIds(); - return { - isMultiBlockSelection: selectedBlockClientIds.length > 1, - selectedBlockClientIds, - }; - } -)( MultiBlocksSwitcher ); +export default withSelect( ( select ) => { + const selectedBlockClientIds = select( 'core/block-editor' ).getMultiSelectedBlockClientIds(); + return { + isMultiBlockSelection: selectedBlockClientIds.length > 1, + selectedBlockClientIds, + }; +} )( MultiBlocksSwitcher ); diff --git a/packages/block-editor/src/components/block-switcher/test/index.js b/packages/block-editor/src/components/block-switcher/test/index.js index 544d403872206b..0eb2640fc1daff 100644 --- a/packages/block-editor/src/components/block-switcher/test/index.js +++ b/packages/block-editor/src/components/block-switcher/test/index.js @@ -51,7 +51,7 @@ describe( 'BlockSwitcher', () => { registerBlockType( 'core/heading', { category: 'common', title: 'Heading', - edit: () => { }, + edit: () => {}, save: () => {}, transforms: { to: [ @@ -73,14 +73,16 @@ describe( 'BlockSwitcher', () => { registerBlockType( 'core/paragraph', { category: 'common', title: 'Paragraph', - edit: () => { }, + edit: () => {}, save: () => {}, transforms: { - to: [ { - type: 'block', - blocks: [ 'core/heading' ], - transform: () => {}, - } ], + to: [ + { + type: 'block', + blocks: [ 'core/heading' ], + transform: () => {}, + }, + ], }, } ); } ); @@ -97,9 +99,7 @@ describe( 'BlockSwitcher', () => { } ); test( 'should render switcher with blocks', () => { - const blocks = [ - headingBlock1, - ]; + const blocks = [ headingBlock1 ]; const inserterItems = [ { name: 'core/heading', frecency: 1 }, { name: 'core/paragraph', frecency: 1 }, @@ -135,9 +135,7 @@ describe( 'BlockSwitcher', () => { } ); describe( 'Dropdown', () => { - const blocks = [ - headingBlock1, - ]; + const blocks = [ headingBlock1 ]; const inserterItems = [ { name: 'core/quote', frecency: 1 }, @@ -149,7 +147,13 @@ describe( 'BlockSwitcher', () => { const onTransformStub = jest.fn(); const getDropdown = () => { - const blockSwitcher = shallow( ); + const blockSwitcher = shallow( + + ); return blockSwitcher.find( 'Dropdown' ); }; @@ -170,7 +174,11 @@ describe( 'BlockSwitcher', () => { } ); test( 'should simulate a keydown event, which should call onToggle and open transform toggle.', () => { - const toggleClosed = shallow( getDropdown().props().renderToggle( { onToggle: onToggleStub, isOpen: false } ) ); + const toggleClosed = shallow( + getDropdown() + .props() + .renderToggle( { onToggle: onToggleStub, isOpen: false } ) + ); const iconButtonClosed = toggleClosed.find( 'ForwardRef(IconButton)' ); iconButtonClosed.simulate( 'keydown', mockKeyDown ); @@ -179,7 +187,11 @@ describe( 'BlockSwitcher', () => { } ); test( 'should simulate a click event, which should call onToggle.', () => { - const toggleOpen = shallow( getDropdown().props().renderToggle( { onToggle: onToggleStub, isOpen: true } ) ); + const toggleOpen = shallow( + getDropdown() + .props() + .renderToggle( { onToggle: onToggleStub, isOpen: true } ) + ); const iconButtonOpen = toggleOpen.find( 'ForwardRef(IconButton)' ); iconButtonOpen.simulate( 'keydown', mockKeyDown ); @@ -191,7 +203,13 @@ describe( 'BlockSwitcher', () => { describe( '.renderContent', () => { test( 'should create the transform items for the chosen block. A heading block will have 3 items', () => { const onCloseStub = jest.fn(); - const content = shallow(
    { getDropdown().props().renderContent( { onClose: onCloseStub } ) }
    ); + const content = shallow( +
    + { getDropdown() + .props() + .renderContent( { onClose: onCloseStub } ) } +
    + ); const blockList = content.find( 'BlockTypesList' ); expect( blockList.prop( 'items' ) ).toHaveLength( 1 ); } ); diff --git a/packages/block-editor/src/components/block-switcher/test/multi-blocks-switcher.js b/packages/block-editor/src/components/block-switcher/test/multi-blocks-switcher.js index 30199f6c598529..5e99eaba7f675d 100644 --- a/packages/block-editor/src/components/block-switcher/test/multi-blocks-switcher.js +++ b/packages/block-editor/src/components/block-switcher/test/multi-blocks-switcher.js @@ -11,9 +11,7 @@ import { MultiBlocksSwitcher } from '../multi-blocks-switcher'; describe( 'MultiBlocksSwitcher', () => { test( 'should return null when the selection is not a multi block selection.', () => { const isMultiBlockSelection = false; - const selectedBlockClientIds = [ - 'clientid', - ]; + const selectedBlockClientIds = [ 'clientid' ]; const wrapper = shallow( { test( 'should return a BlockSwitcher element matching the snapshot.', () => { const isMultiBlockSelection = true; - const selectedBlockClientIds = [ - 'clientid-1', - 'clientid-2', - ]; + const selectedBlockClientIds = [ 'clientid-1', 'clientid-2' ]; const wrapper = shallow( { - const { - getBlockMode, - getSelectedBlockClientIds, - isBlockValid, - } = select( 'core/block-editor' ); + const { getBlockMode, getSelectedBlockClientIds, isBlockValid } = select( 'core/block-editor' ); const blockClientIds = getSelectedBlockClientIds(); return { diff --git a/packages/block-editor/src/components/block-toolbar/index.native.js b/packages/block-editor/src/components/block-toolbar/index.native.js index 7442025c276521..37de9105d89ff7 100644 --- a/packages/block-editor/src/components/block-toolbar/index.native.js +++ b/packages/block-editor/src/components/block-toolbar/index.native.js @@ -33,11 +33,7 @@ export const BlockToolbar = ( { blockClientIds, isValid, mode } ) => { }; export default withSelect( ( select ) => { - const { - getBlockMode, - getSelectedBlockClientIds, - isBlockValid, - } = select( 'core/block-editor' ); + const { getBlockMode, getSelectedBlockClientIds, isBlockValid } = select( 'core/block-editor' ); const blockClientIds = getSelectedBlockClientIds(); return { diff --git a/packages/block-editor/src/components/block-types-list/index.js b/packages/block-editor/src/components/block-types-list/index.js index 8c2de6772dd8ef..aef0d28da01bb5 100644 --- a/packages/block-editor/src/components/block-types-list/index.js +++ b/packages/block-editor/src/components/block-types-list/index.js @@ -16,23 +16,24 @@ function BlockTypesList( { items, onSelect, onHover = () => {}, children } ) { */ /* eslint-disable jsx-a11y/no-redundant-roles */
      - { items && items.map( ( item ) => - { - onSelect( item ); - onHover( null ); - } } - onFocus={ () => onHover( item ) } - onMouseEnter={ () => onHover( item ) } - onMouseLeave={ () => onHover( null ) } - onBlur={ () => onHover( null ) } - isDisabled={ item.isDisabled } - title={ item.title } - /> - ) } + { items && + items.map( ( item ) => ( + { + onSelect( item ); + onHover( null ); + } } + onFocus={ () => onHover( item ) } + onMouseEnter={ () => onHover( item ) } + onMouseLeave={ () => onHover( null ) } + onBlur={ () => onHover( null ) } + isDisabled={ item.isDisabled } + title={ item.title } + /> + ) ) } { children }
    /* eslint-enable jsx-a11y/no-redundant-roles */ diff --git a/packages/block-editor/src/components/block-vertical-alignment-toolbar/icons.js b/packages/block-editor/src/components/block-vertical-alignment-toolbar/icons.js index 4642eddb367c71..f71194c254d898 100644 --- a/packages/block-editor/src/components/block-vertical-alignment-toolbar/icons.js +++ b/packages/block-editor/src/components/block-vertical-alignment-toolbar/icons.js @@ -13,8 +13,7 @@ export const alignBottom = ( export const alignCenter = ( - + ); diff --git a/packages/block-editor/src/components/block-vertical-alignment-toolbar/index.js b/packages/block-editor/src/components/block-vertical-alignment-toolbar/index.js index 22206984dc2706..530b4bb70a42be 100644 --- a/packages/block-editor/src/components/block-vertical-alignment-toolbar/index.js +++ b/packages/block-editor/src/components/block-vertical-alignment-toolbar/index.js @@ -27,7 +27,12 @@ const BLOCK_ALIGNMENTS_CONTROLS = { const DEFAULT_CONTROLS = [ 'top', 'center', 'bottom' ]; const DEFAULT_CONTROL = 'top'; -export function BlockVerticalAlignmentToolbar( { value, onChange, controls = DEFAULT_CONTROLS, isCollapsed = true } ) { +export function BlockVerticalAlignmentToolbar( { + value, + onChange, + controls = DEFAULT_CONTROLS, + isCollapsed = true, +} ) { function applyOrUnset( align ) { return () => onChange( value === align ? undefined : align ); } @@ -40,15 +45,13 @@ export function BlockVerticalAlignmentToolbar( { value, onChange, controls = DEF isCollapsed={ isCollapsed } icon={ activeAlignment ? activeAlignment.icon : defaultAlignmentControl.icon } label={ _x( 'Change vertical alignment', 'Block vertical alignment setting label' ) } - controls={ - controls.map( ( control ) => { - return { - ...BLOCK_ALIGNMENTS_CONTROLS[ control ], - isActive: value === control, - onClick: applyOrUnset( control ), - }; - } ) - } + controls={ controls.map( ( control ) => { + return { + ...BLOCK_ALIGNMENTS_CONTROLS[ control ], + isActive: value === control, + onClick: applyOrUnset( control ), + }; + } ) } /> ); } diff --git a/packages/block-editor/src/components/block-vertical-alignment-toolbar/test/index.js b/packages/block-editor/src/components/block-vertical-alignment-toolbar/test/index.js index 6840e35ba6331c..aadcfd991d1e39 100644 --- a/packages/block-editor/src/components/block-vertical-alignment-toolbar/test/index.js +++ b/packages/block-editor/src/components/block-vertical-alignment-toolbar/test/index.js @@ -12,7 +12,9 @@ describe( 'BlockVerticalAlignmentToolbar', () => { const alignment = 'top'; const onChange = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); const controls = wrapper.props().controls; @@ -25,7 +27,9 @@ describe( 'BlockVerticalAlignmentToolbar', () => { } ); it( 'should call onChange with undefined, when the control is already active', () => { - const activeControl = controls.find( ( { title } ) => title.toLowerCase().includes( alignment ) ); + const activeControl = controls.find( ( { title } ) => + title.toLowerCase().includes( alignment ) + ); activeControl.onClick(); expect( activeControl.isActive ).toBe( true ); @@ -35,7 +39,9 @@ describe( 'BlockVerticalAlignmentToolbar', () => { it( 'should call onChange with alignment value when the control is inactive', () => { // note "middle" alias for "center" - const inactiveCenterControl = controls.find( ( { title } ) => title.toLowerCase().includes( 'middle' ) ); + const inactiveCenterControl = controls.find( ( { title } ) => + title.toLowerCase().includes( 'middle' ) + ); inactiveCenterControl.onClick(); diff --git a/packages/block-editor/src/components/caption/index.native.js b/packages/block-editor/src/components/caption/index.native.js index 68e965524c8b87..a72949545d2b1f 100644 --- a/packages/block-editor/src/components/caption/index.native.js +++ b/packages/block-editor/src/components/caption/index.native.js @@ -11,8 +11,18 @@ import { compose } from '@wordpress/compose'; import { withDispatch, withSelect } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; -const Caption = ( { accessible, accessibilityLabel, onBlur, onChange, onFocus, isSelected, shouldDisplay, text } ) => ( - ( + { - const { - getBlockAttributes, - getSelectedBlockClientId, - } = select( 'core/block-editor' ); + const { getBlockAttributes, getSelectedBlockClientId } = select( 'core/block-editor' ); const { caption } = getBlockAttributes( clientId ); - const accessibilityLabel = accessibilityLabelCreator ? accessibilityLabelCreator( caption ) : undefined; + const accessibilityLabel = accessibilityLabelCreator + ? accessibilityLabelCreator( caption ) + : undefined; const isBlockSelected = getSelectedBlockClientId() === clientId; // We'll render the caption so that the soft keyboard is not forced to close on Android diff --git a/packages/block-editor/src/components/color-palette/control.js b/packages/block-editor/src/components/color-palette/control.js index 6a2da23b527c67..3eda95753ed2f9 100644 --- a/packages/block-editor/src/components/color-palette/control.js +++ b/packages/block-editor/src/components/color-palette/control.js @@ -15,35 +15,22 @@ import { getColorObjectByColorValue } from '../colors'; // translators: first %s: The type of color (e.g. background color), second %s: the color name or value (e.g. red or #ff0000) const colorIndicatorAriaLabel = __( '(current %s: %s)' ); -export function ColorPaletteControl( { - colors, - disableCustomColors, - label, - onChange, - value, -} ) { +export function ColorPaletteControl( { colors, disableCustomColors, label, onChange, value } ) { const colorObject = getColorObjectByColorValue( colors, value ); const colorName = colorObject && colorObject.name; const ariaLabel = sprintf( colorIndicatorAriaLabel, label.toLowerCase(), colorName || value ); return ( - + { label } - { value && ( - - ) } + { value && } ); diff --git a/packages/block-editor/src/components/color-palette/with-color-context.js b/packages/block-editor/src/components/color-palette/with-color-context.js index 1c32141f2a3f13..7b9f7c613f2bc5 100644 --- a/packages/block-editor/src/components/color-palette/with-color-context.js +++ b/packages/block-editor/src/components/color-palette/with-color-context.js @@ -1,4 +1,3 @@ - /** * External dependencies */ @@ -11,20 +10,19 @@ import { createHigherOrderComponent } from '@wordpress/compose'; import { withSelect } from '@wordpress/data'; export default createHigherOrderComponent( - withSelect( - ( select, ownProps ) => { - const settings = select( 'core/block-editor' ).getSettings(); - const colors = ownProps.colors === undefined ? - settings.colors : ownProps.colors; + withSelect( ( select, ownProps ) => { + const settings = select( 'core/block-editor' ).getSettings(); + const colors = ownProps.colors === undefined ? settings.colors : ownProps.colors; - const disableCustomColors = ownProps.disableCustomColors === undefined ? - settings.disableCustomColors : ownProps.disableCustomColors; - return { - colors, - disableCustomColors, - hasColorsToChoose: ! isEmpty( colors ) || ! disableCustomColors, - }; - } - ), + const disableCustomColors = + ownProps.disableCustomColors === undefined + ? settings.disableCustomColors + : ownProps.disableCustomColors; + return { + colors, + disableCustomColors, + hasColorsToChoose: ! isEmpty( colors ) || ! disableCustomColors, + }; + } ), 'withColorContext' ); diff --git a/packages/block-editor/src/components/colors/index.js b/packages/block-editor/src/components/colors/index.js index f6b6fac984db89..2172d3e13be655 100644 --- a/packages/block-editor/src/components/colors/index.js +++ b/packages/block-editor/src/components/colors/index.js @@ -3,7 +3,4 @@ export { getColorObjectByAttributeValues, getColorObjectByColorValue, } from './utils'; -export { - createCustomColorsHOC, - default as withColors, -} from './with-colors'; +export { createCustomColorsHOC, default as withColors } from './with-colors'; diff --git a/packages/block-editor/src/components/colors/test/utils.js b/packages/block-editor/src/components/colors/test/utils.js index 8eb370394aae83..2402a6b9ddd9c6 100644 --- a/packages/block-editor/src/components/colors/test/utils.js +++ b/packages/block-editor/src/components/colors/test/utils.js @@ -10,38 +10,32 @@ import { describe( 'color utils', () => { describe( 'getColorObjectByAttributeValues', () => { it( 'should return the custom color object when there is no definedColor', () => { - const colors = [ - { slug: 'red' }, - { slug: 'green' }, - { slug: 'blue' }, - ]; + const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, undefined, customColor ) ).toEqual( { color: customColor } ); + expect( getColorObjectByAttributeValues( colors, undefined, customColor ) ).toEqual( { + color: customColor, + } ); } ); it( 'should return the custom color object when definedColor was not found', () => { - const colors = [ - { slug: 'red' }, - { slug: 'green' }, - { slug: 'blue' }, - ]; + const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; const definedColor = 'purple'; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { color: customColor } ); + expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { + color: customColor, + } ); } ); it( 'should return the found color object', () => { - const colors = [ - { slug: 'red' }, - { slug: 'green' }, - { slug: 'blue' }, - ]; + const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; const definedColor = 'blue'; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { slug: 'blue' } ); + expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { + slug: 'blue', + } ); } ); } ); @@ -63,7 +57,10 @@ describe( 'color utils', () => { { slug: 'blue', color: '#0000ff' }, ]; - expect( getColorObjectByColorValue( colors, '#00ff00' ) ).toEqual( { slug: 'green', color: '#00ff00' } ); + expect( getColorObjectByColorValue( colors, '#00ff00' ) ).toEqual( { + slug: 'green', + color: '#00ff00', + } ); } ); } ); @@ -77,7 +74,9 @@ describe( 'color utils', () => { } ); it( 'should return a class name with the color slug in kebab case', () => { - expect( getColorClassName( 'background', 'Light Purple' ) ).toBe( 'has-light-purple-background' ); + expect( getColorClassName( 'background', 'Light Purple' ) ).toBe( + 'has-light-purple-background' + ); } ); } ); } ); diff --git a/packages/block-editor/src/components/colors/test/with-colors.js b/packages/block-editor/src/components/colors/test/with-colors.js index 07c19ce0c11e7a..779ae78d64210a 100644 --- a/packages/block-editor/src/components/colors/test/with-colors.js +++ b/packages/block-editor/src/components/colors/test/with-colors.js @@ -10,20 +10,20 @@ import { createCustomColorsHOC } from '../with-colors'; describe( 'createCustomColorsHOC', () => { it( 'provides the the wrapped component with color values and setter functions as props', () => { - const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' } ] ); - const EnhancedComponent = withCustomColors( 'backgroundColor' )( () => ( -
    - ) ); + const withCustomColors = createCustomColorsHOC( [ + { name: 'Red', slug: 'red', color: 'ff0000' }, + ] ); + const EnhancedComponent = withCustomColors( 'backgroundColor' )( () =>
    ); - const wrapper = shallow( - - ); + const wrapper = shallow( ); expect( wrapper.dive() ).toMatchSnapshot(); } ); it( 'setting the color to a value in the provided custom color array updated the backgroundColor attribute', () => { - const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' } ] ); + const withCustomColors = createCustomColorsHOC( [ + { name: 'Red', slug: 'red', color: 'ff0000' }, + ] ); const EnhancedComponent = withCustomColors( 'backgroundColor' )( ( props ) => ( ) ); @@ -35,11 +35,16 @@ describe( 'createCustomColorsHOC', () => { ); wrapper.find( 'button' ).simulate( 'click' ); - expect( setAttributes ).toHaveBeenCalledWith( { backgroundColor: 'red', customBackgroundColor: undefined } ); + expect( setAttributes ).toHaveBeenCalledWith( { + backgroundColor: 'red', + customBackgroundColor: undefined, + } ); } ); it( 'setting the color to a value not in the provided custom color array updates customBackgroundColor attribute', () => { - const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' } ] ); + const withCustomColors = createCustomColorsHOC( [ + { name: 'Red', slug: 'red', color: 'ff0000' }, + ] ); const EnhancedComponent = withCustomColors( 'backgroundColor' )( ( props ) => ( ) ); @@ -51,6 +56,9 @@ describe( 'createCustomColorsHOC', () => { ); wrapper.find( 'button' ).simulate( 'click' ); - expect( setAttributes ).toHaveBeenCalledWith( { backgroundColor: undefined, customBackgroundColor: '000000' } ); + expect( setAttributes ).toHaveBeenCalledWith( { + backgroundColor: undefined, + customBackgroundColor: '000000', + } ); } ); } ); diff --git a/packages/block-editor/src/components/colors/utils.js b/packages/block-editor/src/components/colors/utils.js index 764b02acde2822..f32f23da79c558 100644 --- a/packages/block-editor/src/components/colors/utils.js +++ b/packages/block-editor/src/components/colors/utils.js @@ -68,8 +68,5 @@ export function getColorClassName( colorContextName, colorSlug ) { * @return {string} String with the color value of the most readable color. */ export function getMostReadableColor( colors, colorValue ) { - return tinycolor.mostReadable( - colorValue, - map( colors, 'color' ) - ).toHexString(); + return tinycolor.mostReadable( colorValue, map( colors, 'color' ) ).toHexString(); } diff --git a/packages/block-editor/src/components/colors/with-colors.js b/packages/block-editor/src/components/colors/with-colors.js index b6f33b1b8590f7..e33a1b59bee552 100644 --- a/packages/block-editor/src/components/colors/with-colors.js +++ b/packages/block-editor/src/components/colors/with-colors.js @@ -13,7 +13,12 @@ import { compose, createHigherOrderComponent } from '@wordpress/compose'; /** * Internal dependencies */ -import { getColorClassName, getColorObjectByColorValue, getColorObjectByAttributeValues, getMostReadableColor } from './utils'; +import { + getColorClassName, + getColorObjectByColorValue, + getColorObjectByAttributeValues, + getMostReadableColor, +} from './utils'; const DEFAULT_COLORS = []; @@ -25,9 +30,11 @@ const DEFAULT_COLORS = []; * * @return {Function} The higher order component. */ -const withCustomColorPalette = ( colorsArray ) => createHigherOrderComponent( ( WrappedComponent ) => ( props ) => ( - -), 'withCustomColorPalette' ); +const withCustomColorPalette = ( colorsArray ) => + createHigherOrderComponent( + ( WrappedComponent ) => ( props ) => , + 'withCustomColorPalette' + ); /** * Higher order component factory for injecting the editor colors as the @@ -35,12 +42,13 @@ const withCustomColorPalette = ( colorsArray ) => createHigherOrderComponent( ( * * @return {Function} The higher order component. */ -const withEditorColorPalette = () => withSelect( ( select ) => { - const settings = select( 'core/block-editor' ).getSettings(); - return { - colors: get( settings, [ 'colors' ], DEFAULT_COLORS ), - }; -} ); +const withEditorColorPalette = () => + withSelect( ( select ) => { + const settings = select( 'core/block-editor' ).getSettings(); + return { + colors: get( settings, [ 'colors' ], DEFAULT_COLORS ), + }; + } ); /** * Helper function used with `createHigherOrderComponent` to create @@ -52,12 +60,16 @@ const withEditorColorPalette = () => withSelect( ( select ) => { * @return {Component} The component that can be used as a HOC. */ function createColorHOC( colorTypes, withColorPalette ) { - const colorMap = reduce( colorTypes, ( colorObject, colorType ) => { - return { - ...colorObject, - ...( isString( colorType ) ? { [ colorType ]: kebabCase( colorType ) } : colorType ), - }; - }, {} ); + const colorMap = reduce( + colorTypes, + ( colorObject, colorType ) => { + return { + ...colorObject, + ...( isString( colorType ) ? { [ colorType ]: kebabCase( colorType ) } : colorType ), + }; + }, + {} + ); return compose( [ withColorPalette, @@ -80,50 +92,62 @@ function createColorHOC( colorTypes, withColorPalette ) { } createSetters() { - return reduce( colorMap, ( settersAccumulator, colorContext, colorAttributeName ) => { - const upperFirstColorAttributeName = upperFirst( colorAttributeName ); - const customColorAttributeName = `custom${ upperFirstColorAttributeName }`; - settersAccumulator[ `set${ upperFirstColorAttributeName }` ] = - this.createSetColor( colorAttributeName, customColorAttributeName ); - return settersAccumulator; - }, {} ); + return reduce( + colorMap, + ( settersAccumulator, colorContext, colorAttributeName ) => { + const upperFirstColorAttributeName = upperFirst( colorAttributeName ); + const customColorAttributeName = `custom${ upperFirstColorAttributeName }`; + settersAccumulator[ `set${ upperFirstColorAttributeName }` ] = this.createSetColor( + colorAttributeName, + customColorAttributeName + ); + return settersAccumulator; + }, + {} + ); } createSetColor( colorAttributeName, customColorAttributeName ) { return ( colorValue ) => { const colorObject = getColorObjectByColorValue( this.props.colors, colorValue ); this.props.setAttributes( { - [ colorAttributeName ]: colorObject && colorObject.slug ? colorObject.slug : undefined, - [ customColorAttributeName ]: colorObject && colorObject.slug ? undefined : colorValue, + [ colorAttributeName ]: + colorObject && colorObject.slug ? colorObject.slug : undefined, + [ customColorAttributeName ]: + colorObject && colorObject.slug ? undefined : colorValue, } ); }; } static getDerivedStateFromProps( { attributes, colors }, previousState ) { - return reduce( colorMap, ( newState, colorContext, colorAttributeName ) => { - const colorObject = getColorObjectByAttributeValues( - colors, - attributes[ colorAttributeName ], - attributes[ `custom${ upperFirst( colorAttributeName ) }` ], - ); - - const previousColorObject = previousState[ colorAttributeName ]; - const previousColor = get( previousColorObject, [ 'color' ] ); - /** - * The "and previousColorObject" condition checks that a previous color object was already computed. - * At the start previousColorObject and colorValue are both equal to undefined - * bus as previousColorObject does not exist we should compute the object. - */ - if ( previousColor === colorObject.color && previousColorObject ) { - newState[ colorAttributeName ] = previousColorObject; - } else { - newState[ colorAttributeName ] = { - ...colorObject, - class: getColorClassName( colorContext, colorObject.slug ), - }; - } - return newState; - }, {} ); + return reduce( + colorMap, + ( newState, colorContext, colorAttributeName ) => { + const colorObject = getColorObjectByAttributeValues( + colors, + attributes[ colorAttributeName ], + attributes[ `custom${ upperFirst( colorAttributeName ) }` ] + ); + + const previousColorObject = previousState[ colorAttributeName ]; + const previousColor = get( previousColorObject, [ 'color' ] ); + /** + * The "and previousColorObject" condition checks that a previous color object was already computed. + * At the start previousColorObject and colorValue are both equal to undefined + * bus as previousColorObject does not exist we should compute the object. + */ + if ( previousColor === colorObject.color && previousColorObject ) { + newState[ colorAttributeName ] = previousColorObject; + } else { + newState[ colorAttributeName ] = { + ...colorObject, + class: getColorClassName( colorContext, colorObject.slug ), + }; + } + return newState; + }, + {} + ); } render() { @@ -169,7 +193,10 @@ function createColorHOC( colorTypes, withColorPalette ) { export function createCustomColorsHOC( colorsArray ) { return ( ...colorTypes ) => { const withColorPalette = withCustomColorPalette( colorsArray ); - return createHigherOrderComponent( createColorHOC( colorTypes, withColorPalette ), 'withCustomColors' ); + return createHigherOrderComponent( + createColorHOC( colorTypes, withColorPalette ), + 'withCustomColors' + ); }; } diff --git a/packages/block-editor/src/components/contrast-checker/index.js b/packages/block-editor/src/components/contrast-checker/index.js index 308572e55531aa..a7947e54ab4111 100644 --- a/packages/block-editor/src/components/contrast-checker/index.js +++ b/packages/block-editor/src/components/contrast-checker/index.js @@ -11,10 +11,20 @@ import { __ } from '@wordpress/i18n'; import { Notice } from '@wordpress/components'; import { useEffect } from '@wordpress/element'; -function ContrastCheckerMessage( { tinyBackgroundColor, tinyTextColor, backgroundColor, textColor } ) { - const msg = tinyBackgroundColor.getBrightness() < tinyTextColor.getBrightness() ? - __( 'This color combination may be hard for people to read. Try using a darker background color and/or a brighter text color.' ) : - __( 'This color combination may be hard for people to read. Try using a brighter background color and/or a darker text color.' ); +function ContrastCheckerMessage( { + tinyBackgroundColor, + tinyTextColor, + backgroundColor, + textColor, +} ) { + const msg = + tinyBackgroundColor.getBrightness() < tinyTextColor.getBrightness() + ? __( + 'This color combination may be hard for people to read. Try using a darker background color and/or a brighter text color.' + ) + : __( + 'This color combination may be hard for people to read. Try using a brighter background color and/or a darker text color.' + ); useEffect( () => { speak( __( 'This color combination may be hard for people to read.' ) ); }, [ backgroundColor, textColor ] ); @@ -42,11 +52,13 @@ function ContrastChecker( { const tinyTextColor = tinycolor( textColor || fallbackTextColor ); const hasTransparency = tinyBackgroundColor.getAlpha() !== 1 || tinyTextColor.getAlpha() !== 1; - if ( hasTransparency || tinycolor.isReadable( - tinyBackgroundColor, - tinyTextColor, - { level: 'AA', size: ( isLargeText || ( isLargeText !== false && fontSize >= 24 ) ? 'large' : 'small' ) } - ) ) { + if ( + hasTransparency || + tinycolor.isReadable( tinyBackgroundColor, tinyTextColor, { + level: 'AA', + size: isLargeText || ( isLargeText !== false && fontSize >= 24 ) ? 'large' : 'small', + } ) + ) { return null; } diff --git a/packages/block-editor/src/components/contrast-checker/test/index.js b/packages/block-editor/src/components/contrast-checker/test/index.js index eca63c0e7b97d8..aa5bad47541c6d 100644 --- a/packages/block-editor/src/components/contrast-checker/test/index.js +++ b/packages/block-editor/src/components/contrast-checker/test/index.js @@ -23,7 +23,8 @@ describe( 'ContrastChecker', () => { textColor={ textColor } isLargeText={ isLargeText } fallbackBackgroundColor={ fallbackBackgroundColor } - fallbackTextColor={ fallbackTextColor } /> + fallbackTextColor={ fallbackTextColor } + /> ); test( 'should render null when no colors are provided', () => { @@ -41,7 +42,8 @@ describe( 'ContrastChecker', () => { textColor={ sameShade } isLargeText={ isLargeText } fallbackBackgroundColor={ fallbackBackgroundColor } - fallbackTextColor={ fallbackTextColor } /> + fallbackTextColor={ fallbackTextColor } + /> ); expect( componentWrapper ).toMatchSnapshot(); @@ -54,7 +56,8 @@ describe( 'ContrastChecker', () => { textColor={ sameShade } isLargeText={ isLargeText } fallbackBackgroundColor={ fallbackBackgroundColor } - fallbackTextColor={ fallbackTextColor } /> + fallbackTextColor={ fallbackTextColor } + /> ); expect( componentWrapper.html() ).toBeNull(); @@ -67,7 +70,8 @@ describe( 'ContrastChecker', () => { textColor={ colorWithTransparency } isLargeText={ isLargeText } fallbackBackgroundColor={ fallbackBackgroundColor } - fallbackTextColor={ fallbackTextColor } /> + fallbackTextColor={ fallbackTextColor } + /> ); expect( componentWrapper.html() ).toBeNull(); @@ -82,7 +86,8 @@ describe( 'ContrastChecker', () => { textColor={ sameShade } isLargeText={ ! isLargeText } fallbackBackgroundColor={ fallbackBackgroundColor } - fallbackTextColor={ fallbackTextColor } /> + fallbackTextColor={ fallbackTextColor } + /> ); expect( componentWrapper ).toMatchSnapshot(); @@ -90,21 +95,13 @@ describe( 'ContrastChecker', () => { test( 'should take into consideration wherever text is large or not', () => { const componentWrapperSmallText = mount( - + ); expect( componentWrapperSmallText ).toMatchSnapshot(); const componentWrapperLargeText = mount( - + ); expect( componentWrapperLargeText.html() ).toBeNull(); @@ -112,21 +109,13 @@ describe( 'ContrastChecker', () => { test( 'should take into consideration the font size passed', () => { const componentWrapperSmallFontSize = mount( - + ); expect( componentWrapperSmallFontSize ).toMatchSnapshot(); const componentWrapperLargeText = mount( - + ); expect( componentWrapperLargeText.html() ).toBeNull(); @@ -161,7 +150,8 @@ describe( 'ContrastChecker', () => { + fallbackTextColor={ fallbackTextColor } + /> ); expect( componentWrapper.html() ).toBeNull(); @@ -169,9 +159,7 @@ describe( 'ContrastChecker', () => { test( 'should render messages when the textColor is valid, but the fallback backgroundColor conflicts.', () => { const componentWrapper = mount( - + ); expect( componentWrapper ).toMatchSnapshot(); diff --git a/packages/block-editor/src/components/copy-handler/index.js b/packages/block-editor/src/components/copy-handler/index.js index 75b2db4098858e..809148b4fad122 100644 --- a/packages/block-editor/src/components/copy-handler/index.js +++ b/packages/block-editor/src/components/copy-handler/index.js @@ -16,11 +16,9 @@ function CopyHandler( { children, onCopy, onCut } ) { export default compose( [ withDispatch( ( dispatch, ownProps, { select } ) => { - const { - getBlocksByClientId, - getSelectedBlockClientIds, - hasMultiSelection, - } = select( 'core/block-editor' ); + const { getBlocksByClientId, getSelectedBlockClientIds, hasMultiSelection } = select( + 'core/block-editor' + ); const { removeBlocks } = dispatch( 'core/block-editor' ); const onCopy = ( event ) => { diff --git a/packages/block-editor/src/components/default-block-appender/index.js b/packages/block-editor/src/components/default-block-appender/index.js index 3baf90e4406097..f7fee861b6947d 100644 --- a/packages/block-editor/src/components/default-block-appender/index.js +++ b/packages/block-editor/src/components/default-block-appender/index.js @@ -74,7 +74,9 @@ export function DefaultBlockAppender( { export default compose( withState( { hovered: false } ), withSelect( ( select, ownProps ) => { - const { getBlockCount, getBlockName, isBlockValid, getSettings, getTemplateLock } = select( 'core/block-editor' ); + const { getBlockCount, getBlockName, isBlockValid, getSettings, getTemplateLock } = select( + 'core/block-editor' + ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); const isLastBlockDefault = getBlockName( ownProps.lastBlockClientId ) === getDefaultBlockName(); @@ -89,10 +91,7 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { - insertDefaultBlock, - startTyping, - } = dispatch( 'core/block-editor' ); + const { insertDefaultBlock, startTyping } = dispatch( 'core/block-editor' ); return { onAppend() { @@ -102,5 +101,5 @@ export default compose( startTyping(); }, }; - } ), + } ) )( DefaultBlockAppender ); diff --git a/packages/block-editor/src/components/default-block-appender/index.native.js b/packages/block-editor/src/components/default-block-appender/index.native.js index 4f361376f6d581..7f6390d1fa2aad 100644 --- a/packages/block-editor/src/components/default-block-appender/index.native.js +++ b/packages/block-editor/src/components/default-block-appender/index.native.js @@ -29,17 +29,13 @@ export function DefaultBlockAppender( { return null; } - const value = typeof placeholder === 'string' ? decodeEntities( placeholder ) : __( 'Start writing…' ); + const value = + typeof placeholder === 'string' ? decodeEntities( placeholder ) : __( 'Start writing…' ); return ( - + - {} } - /> + {} } /> ); @@ -47,7 +43,9 @@ export function DefaultBlockAppender( { export default compose( withSelect( ( select, ownProps ) => { - const { getBlockCount, getBlockName, isBlockValid, getTemplateLock } = select( 'core/block-editor' ); + const { getBlockCount, getBlockName, isBlockValid, getTemplateLock } = select( + 'core/block-editor' + ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); const isLastBlockDefault = getBlockName( ownProps.lastBlockClientId ) === getDefaultBlockName(); @@ -59,10 +57,7 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { - insertDefaultBlock, - startTyping, - } = dispatch( 'core/block-editor' ); + const { insertDefaultBlock, startTyping } = dispatch( 'core/block-editor' ); return { onAppend() { @@ -72,5 +67,5 @@ export default compose( startTyping(); }, }; - } ), + } ) )( DefaultBlockAppender ); diff --git a/packages/block-editor/src/components/default-block-appender/test/index.js b/packages/block-editor/src/components/default-block-appender/test/index.js index 80517843ee661e..4035827b2d2d13 100644 --- a/packages/block-editor/src/components/default-block-appender/test/index.js +++ b/packages/block-editor/src/components/default-block-appender/test/index.js @@ -40,7 +40,9 @@ describe( 'DefaultBlockAppender', () => { it( 'should optionally show without prompt', () => { const onAppend = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); const input = wrapper.find( 'TextareaAutosize' ); expect( input.prop( 'value' ) ).toEqual( '' ); diff --git a/packages/block-editor/src/components/default-style-picker/index.js b/packages/block-editor/src/components/default-style-picker/index.js index 7be972419f67bb..011e2061b6112c 100644 --- a/packages/block-editor/src/components/default-style-picker/index.js +++ b/packages/block-editor/src/components/default-style-picker/index.js @@ -12,35 +12,24 @@ import { SelectControl } from '@wordpress/components'; import { useSelect } from '@wordpress/data'; export default function DefaultStylePicker( { blockName } ) { - const { - preferredStyle, - onUpdatePreferredStyleVariations, - styles, - } = useSelect( + const { preferredStyle, onUpdatePreferredStyleVariations, styles } = useSelect( ( select ) => { const settings = select( 'core/block-editor' ).getSettings(); const preferredStyleVariations = settings.__experimentalPreferredStyleVariations; return { - preferredStyle: get( - preferredStyleVariations, - [ 'value', blockName ] - ), - onUpdatePreferredStyleVariations: get( - preferredStyleVariations, - [ 'onChange' ], - null - ), + preferredStyle: get( preferredStyleVariations, [ 'value', blockName ] ), + onUpdatePreferredStyleVariations: get( preferredStyleVariations, [ 'onChange' ], null ), styles: select( 'core/blocks' ).getBlockStyles( blockName ), }; }, [ blockName ] ); const selectOptions = useMemo( - () => ( [ + () => [ { label: __( 'Not set' ), value: '' }, ...styles.map( ( { label, name } ) => ( { label, value: name } ) ), - ] ), - [ styles ], + ], + [ styles ] ); const selectOnChange = useCallback( ( blockStyle ) => { @@ -49,12 +38,14 @@ export default function DefaultStylePicker( { blockName } ) { [ blockName, onUpdatePreferredStyleVariations ] ); - return onUpdatePreferredStyleVariations && ( - + return ( + onUpdatePreferredStyleVariations && ( + + ) ); } diff --git a/packages/block-editor/src/components/font-sizes/font-size-picker.js b/packages/block-editor/src/components/font-sizes/font-size-picker.js index e2dbe3dba8134b..57bf783fd6bef8 100644 --- a/packages/block-editor/src/components/font-sizes/font-size-picker.js +++ b/packages/block-editor/src/components/font-sizes/font-size-picker.js @@ -4,16 +4,11 @@ import { FontSizePicker } from '@wordpress/components'; import { withSelect } from '@wordpress/data'; -export default withSelect( - ( select ) => { - const { - disableCustomFontSizes, - fontSizes, - } = select( 'core/block-editor' ).getSettings(); +export default withSelect( ( select ) => { + const { disableCustomFontSizes, fontSizes } = select( 'core/block-editor' ).getSettings(); - return { - disableCustomFontSizes, - fontSizes, - }; - } -)( FontSizePicker ); + return { + disableCustomFontSizes, + fontSizes, + }; +} )( FontSizePicker ); diff --git a/packages/block-editor/src/components/font-sizes/with-font-sizes.js b/packages/block-editor/src/components/font-sizes/with-font-sizes.js index f64fe8d4f76006..c89b31214f544b 100644 --- a/packages/block-editor/src/components/font-sizes/with-font-sizes.js +++ b/packages/block-editor/src/components/font-sizes/with-font-sizes.js @@ -27,14 +27,20 @@ import { getFontSize, getFontSizeClass } from './utils'; */ export default ( ...fontSizeNames ) => { /* - * Computes an object whose key is the font size attribute name as passed in the array, - * and the value is the custom font size attribute name. - * Custom font size is automatically compted by appending custom followed by the font size attribute name in with the first letter capitalized. - */ - const fontSizeAttributeNames = reduce( fontSizeNames, ( fontSizeAttributeNamesAccumulator, fontSizeAttributeName ) => { - fontSizeAttributeNamesAccumulator[ fontSizeAttributeName ] = `custom${ upperFirst( fontSizeAttributeName ) }`; - return fontSizeAttributeNamesAccumulator; - }, {} ); + * Computes an object whose key is the font size attribute name as passed in the array, + * and the value is the custom font size attribute name. + * Custom font size is automatically compted by appending custom followed by the font size attribute name in with the first letter capitalized. + */ + const fontSizeAttributeNames = reduce( + fontSizeNames, + ( fontSizeAttributeNamesAccumulator, fontSizeAttributeName ) => { + fontSizeAttributeNamesAccumulator[ fontSizeAttributeName ] = `custom${ upperFirst( + fontSizeAttributeName + ) }`; + return fontSizeAttributeNamesAccumulator; + }, + {} + ); return createHigherOrderComponent( compose( [ @@ -55,20 +61,29 @@ export default ( ...fontSizeNames ) => { } createSetters() { - return reduce( fontSizeAttributeNames, ( settersAccumulator, customFontSizeAttributeName, fontSizeAttributeName ) => { - const upperFirstFontSizeAttributeName = upperFirst( fontSizeAttributeName ); - settersAccumulator[ `set${ upperFirstFontSizeAttributeName }` ] = - this.createSetFontSize( fontSizeAttributeName, customFontSizeAttributeName ); - return settersAccumulator; - }, {} ); + return reduce( + fontSizeAttributeNames, + ( settersAccumulator, customFontSizeAttributeName, fontSizeAttributeName ) => { + const upperFirstFontSizeAttributeName = upperFirst( fontSizeAttributeName ); + settersAccumulator[ + `set${ upperFirstFontSizeAttributeName }` + ] = this.createSetFontSize( fontSizeAttributeName, customFontSizeAttributeName ); + return settersAccumulator; + }, + {} + ); } createSetFontSize( fontSizeAttributeName, customFontSizeAttributeName ) { return ( fontSizeValue ) => { - const fontSizeObject = find( this.props.fontSizes, { size: Number( fontSizeValue ) } ); + const fontSizeObject = find( this.props.fontSizes, { + size: Number( fontSizeValue ), + } ); this.props.setAttributes( { - [ fontSizeAttributeName ]: fontSizeObject && fontSizeObject.slug ? fontSizeObject.slug : undefined, - [ customFontSizeAttributeName ]: fontSizeObject && fontSizeObject.slug ? undefined : fontSizeValue, + [ fontSizeAttributeName ]: + fontSizeObject && fontSizeObject.slug ? fontSizeObject.slug : undefined, + [ customFontSizeAttributeName ]: + fontSizeObject && fontSizeObject.slug ? undefined : fontSizeValue, } ); }; } @@ -78,10 +93,16 @@ export default ( ...fontSizeNames ) => { if ( previousState[ fontSizeAttributeName ] ) { // if new font size is name compare with the previous slug if ( attributes[ fontSizeAttributeName ] ) { - return attributes[ fontSizeAttributeName ] !== previousState[ fontSizeAttributeName ].slug; + return ( + attributes[ fontSizeAttributeName ] !== + previousState[ fontSizeAttributeName ].slug + ); } // if font size is not named, update when the font size value changes. - return previousState[ fontSizeAttributeName ].size !== attributes[ customFontSizeAttributeName ]; + return ( + previousState[ fontSizeAttributeName ].size !== + attributes[ customFontSizeAttributeName ] + ); } // in this case we need to build the font size object return true; diff --git a/packages/block-editor/src/components/gradient-picker/control.js b/packages/block-editor/src/components/gradient-picker/control.js index 73609ffdf17e27..9af0d246c6333a 100644 --- a/packages/block-editor/src/components/gradient-picker/control.js +++ b/packages/block-editor/src/components/gradient-picker/control.js @@ -1,4 +1,3 @@ - /** * External dependencies */ @@ -17,15 +16,8 @@ import GradientPicker from './'; export default function( { className, ...props } ) { return ( - - - { __( 'Gradient Presets' ) } - + + { __( 'Gradient Presets' ) } ( - select( 'core/block-editor' ).getSettings().gradients - ) ); - return ( - <__experimentalGradientPicker - { ...props } - gradients={ gradients } - /> + const gradients = useSelect( + ( select ) => select( 'core/block-editor' ).getSettings().gradients ); + return <__experimentalGradientPicker { ...props } gradients={ gradients } />; } export default function( props ) { - const ComponentToUse = props.gradients ? - __experimentalGradientPicker : - GradientPickerWithGradients; - return ( ); + const ComponentToUse = props.gradients + ? __experimentalGradientPicker + : GradientPickerWithGradients; + return ; } diff --git a/packages/block-editor/src/components/ignore-nested-events/index.js b/packages/block-editor/src/components/ignore-nested-events/index.js index 2592ba3abd0527..a6b025d13c8cea 100644 --- a/packages/block-editor/src/components/ignore-nested-events/index.js +++ b/packages/block-editor/src/components/ignore-nested-events/index.js @@ -66,33 +66,34 @@ export class IgnoreNestedEvents extends Component { render() { const { childHandledEvents = [], forwardedRef, tagName = 'div', ...props } = this.props; - const eventHandlers = reduce( [ - ...childHandledEvents, - ...Object.keys( props ), - ], ( result, key ) => { - // Try to match prop key as event handler - const match = key.match( /^on([A-Z][a-zA-Z]+?)(Handled)?$/ ); - if ( match ) { - const isHandledProp = !! match[ 2 ]; - if ( isHandledProp ) { - // Avoid assigning through the invalid prop key. This - // assumes mutation of shallow clone by above spread. - delete props[ key ]; + const eventHandlers = reduce( + [ ...childHandledEvents, ...Object.keys( props ) ], + ( result, key ) => { + // Try to match prop key as event handler + const match = key.match( /^on([A-Z][a-zA-Z]+?)(Handled)?$/ ); + if ( match ) { + const isHandledProp = !! match[ 2 ]; + if ( isHandledProp ) { + // Avoid assigning through the invalid prop key. This + // assumes mutation of shallow clone by above spread. + delete props[ key ]; + } + + // Re-map the prop to the local proxy handler to check whether + // the event has already been handled. + const proxiedPropName = 'on' + match[ 1 ]; + result[ proxiedPropName ] = this.proxyEvent; + + // Assign event -> propName into an instance variable, so as to + // avoid re-renders which could be incurred either by setState + // or in mapping values to a newly created function. + this.eventMap[ match[ 1 ].toLowerCase() ] = proxiedPropName; } - // Re-map the prop to the local proxy handler to check whether - // the event has already been handled. - const proxiedPropName = 'on' + match[ 1 ]; - result[ proxiedPropName ] = this.proxyEvent; - - // Assign event -> propName into an instance variable, so as to - // avoid re-renders which could be incurred either by setState - // or in mapping values to a newly created function. - this.eventMap[ match[ 1 ].toLowerCase() ] = proxiedPropName; - } - - return result; - }, {} ); + return result; + }, + {} + ); return createElement( tagName, { ref: forwardedRef, ...props, ...eventHandlers } ); } diff --git a/packages/block-editor/src/components/ignore-nested-events/test/index.js b/packages/block-editor/src/components/ignore-nested-events/test/index.js index 56ded3e4df3407..5724cc07b7a839 100644 --- a/packages/block-editor/src/components/ignore-nested-events/test/index.js +++ b/packages/block-editor/src/components/ignore-nested-events/test/index.js @@ -10,9 +10,7 @@ import { IgnoreNestedEvents } from '../'; describe( 'IgnoreNestedEvents', () => { it( 'passes props to its rendered div', () => { - const wrapper = mount( - - ); + const wrapper = mount( ); expect( wrapper.find( 'div' ) ).toHaveLength( 1 ); expect( wrapper.prop( 'className' ) ).toBe( 'foo' ); @@ -27,7 +25,10 @@ describe( 'IgnoreNestedEvents', () => { ); - wrapper.find( 'div' ).last().simulate( 'click' ); + wrapper + .find( 'div' ) + .last() + .simulate( 'click' ); expect( spyInner ).toHaveBeenCalled(); expect( spyOuter ).not.toHaveBeenCalled(); diff --git a/packages/block-editor/src/components/index.js b/packages/block-editor/src/components/index.js index a31f3829ca360c..45b188e008a53a 100644 --- a/packages/block-editor/src/components/index.js +++ b/packages/block-editor/src/components/index.js @@ -43,8 +43,12 @@ export { default as withColorContext } from './color-palette/with-color-context' * Content Related Components */ -export { default as __experimentalBlockSettingsMenuFirstItem } from './block-settings-menu/block-settings-menu-first-item'; -export { default as __experimentalBlockSettingsMenuPluginsExtension } from './block-settings-menu/block-settings-menu-plugins-extension'; +export { + default as __experimentalBlockSettingsMenuFirstItem, +} from './block-settings-menu/block-settings-menu-first-item'; +export { + default as __experimentalBlockSettingsMenuPluginsExtension, +} from './block-settings-menu/block-settings-menu-plugins-extension'; export { default as __experimentalInserterMenuExtension } from './inserter-menu-extension'; export { default as BlockEditorKeyboardShortcuts } from './block-editor-keyboard-shortcuts'; export { default as BlockInspector } from './block-inspector'; diff --git a/packages/block-editor/src/components/inner-blocks/button-block-appender.js b/packages/block-editor/src/components/inner-blocks/button-block-appender.js index af4f355e861efa..7ace23249e4922 100644 --- a/packages/block-editor/src/components/inner-blocks/button-block-appender.js +++ b/packages/block-editor/src/components/inner-blocks/button-block-appender.js @@ -5,9 +5,7 @@ import BaseButtonBlockAppender from '../button-block-appender'; import withClientId from './with-client-id'; export const ButtonBlockAppender = ( { clientId } ) => { - return ( - - ); + return ; }; export default withClientId( ButtonBlockAppender ); diff --git a/packages/block-editor/src/components/inner-blocks/default-block-appender.js b/packages/block-editor/src/components/inner-blocks/default-block-appender.js index 1aa6dbc8548b89..7fe26a960bffb8 100644 --- a/packages/block-editor/src/components/inner-blocks/default-block-appender.js +++ b/packages/block-editor/src/components/inner-blocks/default-block-appender.js @@ -19,10 +19,7 @@ import withClientId from './with-client-id'; export const DefaultBlockAppender = ( { clientId, lastBlockClientId } ) => { return ( - + ); }; @@ -30,9 +27,7 @@ export const DefaultBlockAppender = ( { clientId, lastBlockClientId } ) => { export default compose( [ withClientId, withSelect( ( select, { clientId } ) => { - const { - getBlockOrder, - } = select( 'core/block-editor' ); + const { getBlockOrder } = select( 'core/block-editor' ); const blockClientIds = getBlockOrder( clientId ); diff --git a/packages/block-editor/src/components/inner-blocks/index.js b/packages/block-editor/src/components/inner-blocks/index.js index 35e1bf10b47ca2..6280fd153fdf8d 100644 --- a/packages/block-editor/src/components/inner-blocks/index.js +++ b/packages/block-editor/src/components/inner-blocks/index.js @@ -76,7 +76,7 @@ class InnerBlocks extends Component { // Synchronize with templates. If the next set differs, replace. const nextBlocks = synchronizeBlocksWithTemplate( innerBlocks, template ); - if ( ! isEqual( nextBlocks, innerBlocks ) ) { + if ( ! isEqual( nextBlocks, innerBlocks ) ) { replaceInnerBlocks( nextBlocks ); } } @@ -121,18 +121,16 @@ class InnerBlocks extends Component { return (
    - { ! templateInProcess && ( - isPlaceholder ? + { ! templateInProcess && + ( isPlaceholder ? ( : - - ) } + ) : ( + + ) ) }
    ); } @@ -157,20 +155,24 @@ InnerBlocks = compose( [ return { block, blockListSettings: getBlockListSettings( clientId ), - hasOverlay: block.name !== 'core/template' && ! isBlockSelected( clientId ) && ! hasSelectedInnerBlock( clientId, true ), + hasOverlay: + block.name !== 'core/template' && + ! isBlockSelected( clientId ) && + ! hasSelectedInnerBlock( clientId, true ), parentLock: getTemplateLock( rootClientId ), }; } ), withDispatch( ( dispatch, ownProps ) => { - const { - replaceInnerBlocks, - updateBlockListSettings, - } = dispatch( 'core/block-editor' ); + const { replaceInnerBlocks, updateBlockListSettings } = dispatch( 'core/block-editor' ); const { block, clientId, templateInsertUpdatesSelection = true } = ownProps; return { replaceInnerBlocks( blocks ) { - replaceInnerBlocks( clientId, blocks, block.innerBlocks.length === 0 && templateInsertUpdatesSelection ); + replaceInnerBlocks( + clientId, + blocks, + block.innerBlocks.length === 0 && templateInsertUpdatesSelection + ); }, updateNestedSettings( settings ) { dispatch( updateBlockListSettings( clientId, settings ) ); @@ -183,9 +185,7 @@ InnerBlocks = compose( [ InnerBlocks.DefaultBlockAppender = DefaultBlockAppender; InnerBlocks.ButtonBlockAppender = ButtonBlockAppender; -InnerBlocks.Content = withBlockContentContext( - ( { BlockContent } ) => -); +InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ); /** * @see https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inner-blocks/README.md diff --git a/packages/block-editor/src/components/inner-blocks/index.native.js b/packages/block-editor/src/components/inner-blocks/index.native.js index 2b6a6c9320c923..d3d02c4d4d8701 100644 --- a/packages/block-editor/src/components/inner-blocks/index.native.js +++ b/packages/block-editor/src/components/inner-blocks/index.native.js @@ -34,10 +34,7 @@ class InnerBlocks extends Component { } getTemplateLock() { - const { - templateLock, - parentLock, - } = this.props; + const { templateLock, parentLock } = this.props; return templateLock === undefined ? parentLock : templateLock; } @@ -80,17 +77,13 @@ class InnerBlocks extends Component { // Synchronize with templates. If the next set differs, replace. const nextBlocks = synchronizeBlocksWithTemplate( innerBlocks, template ); - if ( ! isEqual( nextBlocks, innerBlocks ) ) { + if ( ! isEqual( nextBlocks, innerBlocks ) ) { replaceInnerBlocks( nextBlocks ); } } updateNestedSettings() { - const { - blockListSettings, - allowedBlocks, - updateNestedSettings, - } = this.props; + const { blockListSettings, allowedBlocks, updateNestedSettings } = this.props; const newSettings = { allowedBlocks, @@ -115,15 +108,14 @@ class InnerBlocks extends Component { return ( <> - { ! templateInProcess && ( - isPlaceholder ? - null : + { ! templateInProcess && + ( isPlaceholder ? null : ( - ) } + ) ) } ); } @@ -147,20 +139,24 @@ InnerBlocks = compose( [ return { block, blockListSettings: getBlockListSettings( clientId ), - hasOverlay: block.name !== 'core/template' && ! isBlockSelected( clientId ) && ! hasSelectedInnerBlock( clientId, true ), + hasOverlay: + block.name !== 'core/template' && + ! isBlockSelected( clientId ) && + ! hasSelectedInnerBlock( clientId, true ), parentLock: getTemplateLock( rootClientId ), }; } ), withDispatch( ( dispatch, ownProps ) => { - const { - replaceInnerBlocks, - updateBlockListSettings, - } = dispatch( 'core/block-editor' ); + const { replaceInnerBlocks, updateBlockListSettings } = dispatch( 'core/block-editor' ); const { block, clientId, templateInsertUpdatesSelection = true } = ownProps; return { replaceInnerBlocks( blocks ) { - replaceInnerBlocks( clientId, blocks, block.innerBlocks.length === 0 && templateInsertUpdatesSelection ); + replaceInnerBlocks( + clientId, + blocks, + block.innerBlocks.length === 0 && templateInsertUpdatesSelection + ); }, updateNestedSettings( settings ) { dispatch( updateBlockListSettings( clientId, settings ) ); @@ -173,9 +169,7 @@ InnerBlocks = compose( [ InnerBlocks.DefaultBlockAppender = DefaultBlockAppender; InnerBlocks.ButtonBlockAppender = ButtonBlockAppender; -InnerBlocks.Content = withBlockContentContext( - ( { BlockContent } ) => -); +InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ); /** * @see https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inner-blocks/README.md diff --git a/packages/block-editor/src/components/inner-blocks/template-picker.js b/packages/block-editor/src/components/inner-blocks/template-picker.js index 8afc65a34e25eb..7981999a7c5fe5 100644 --- a/packages/block-editor/src/components/inner-blocks/template-picker.js +++ b/packages/block-editor/src/components/inner-blocks/template-picker.js @@ -9,18 +9,14 @@ import classnames from 'classnames'; import { __ } from '@wordpress/i18n'; import { Button, IconButton, Placeholder } from '@wordpress/components'; -function InnerBlocksTemplatePicker( { - options, - onSelect, - allowSkip, -} ) { +function InnerBlocksTemplatePicker( { options, onSelect, allowSkip } ) { const classes = classnames( 'block-editor-inner-blocks__template-picker', { 'has-many-options': options.length > 4, } ); - const instructions = allowSkip ? - __( 'Select a layout to start with, or make one yourself.' ) : - __( 'Select a layout to start with.' ); + const instructions = allowSkip + ? __( 'Select a layout to start with, or make one yourself.' ) + : __( 'Select a layout to start with.' ); return ( - { - /* - * Disable reason: The `list` ARIA role is redundant but - * Safari+VoiceOver won't announce the list otherwise. - */ - /* eslint-disable jsx-a11y/no-redundant-roles */ - } + { /* + * Disable reason: The `list` ARIA role is redundant but + * Safari+VoiceOver won't announce the list otherwise. + */ + /* eslint-disable jsx-a11y/no-redundant-roles */ }
      { options.map( ( templateOption, index ) => (
    • @@ -52,10 +46,7 @@ function InnerBlocksTemplatePicker( { { /* eslint-enable jsx-a11y/no-redundant-roles */ } { allowSkip && (
      -
      diff --git a/packages/block-editor/src/components/inner-blocks/test/index.js b/packages/block-editor/src/components/inner-blocks/test/index.js index 19bfd1bc383d7c..ac242fe9ddb112 100644 --- a/packages/block-editor/src/components/inner-blocks/test/index.js +++ b/packages/block-editor/src/components/inner-blocks/test/index.js @@ -50,11 +50,9 @@ describe( 'InnerBlocks', () => { } ); const saved = renderToString( - getSaveElement( - 'core/fruit', - { fruit: 'Bananas' }, - [ createBlock( 'core/fruit', { fruit: 'Apples' } ) ], - ) + getSaveElement( 'core/fruit', { fruit: 'Bananas' }, [ + createBlock( 'core/fruit', { fruit: 'Apples' } ), + ] ) ); expect( saved ).toMatchSnapshot(); @@ -94,11 +92,9 @@ describe( 'InnerBlocks', () => { title: 'block title', }; registerBlockType( 'core/test-block', blockType ); - const block = createBlock( - 'core/test-block', - { content: 'Invalid' }, - [ createBlock( 'core/test-block' ) ] - ); + const block = createBlock( 'core/test-block', { content: 'Invalid' }, [ + createBlock( 'core/test-block' ), + ] ); block.isValid = false; block.originalContent = 'Original'; diff --git a/packages/block-editor/src/components/inner-blocks/with-client-id.js b/packages/block-editor/src/components/inner-blocks/with-client-id.js index 35672ba1681f25..ad3d1abe67c77a 100644 --- a/packages/block-editor/src/components/inner-blocks/with-client-id.js +++ b/packages/block-editor/src/components/inner-blocks/with-client-id.js @@ -14,7 +14,8 @@ import { createHigherOrderComponent } from '@wordpress/compose'; import { withBlockEditContext } from '../block-edit/context'; const withClientId = createHigherOrderComponent( - ( WrappedComponent ) => withBlockEditContext( ( context ) => pick( context, [ 'clientId' ] ) )( WrappedComponent ), + ( WrappedComponent ) => + withBlockEditContext( ( context ) => pick( context, [ 'clientId' ] ) )( WrappedComponent ), 'withClientId' ); diff --git a/packages/block-editor/src/components/inserter-list-item/index.js b/packages/block-editor/src/components/inserter-list-item/index.js index a4af815ac36446..b07c06a7d0dc76 100644 --- a/packages/block-editor/src/components/inserter-list-item/index.js +++ b/packages/block-editor/src/components/inserter-list-item/index.js @@ -8,28 +8,21 @@ import classnames from 'classnames'; */ import BlockIcon from '../block-icon'; -function InserterListItem( { - icon, - onClick, - isDisabled, - title, - className, - ...props -} ) { - const itemIconStyle = icon ? { - backgroundColor: icon.background, - color: icon.foreground, - } : {}; +function InserterListItem( { icon, onClick, isDisabled, title, className, ...props } ) { + const itemIconStyle = icon + ? { + backgroundColor: icon.background, + color: icon.foreground, + } + : {}; return (
    @@ -68,5 +66,5 @@ export default compose( } }, }; - } ), + } ) )( InserterWithShortcuts ); diff --git a/packages/block-editor/src/components/inserter/child-blocks.js b/packages/block-editor/src/components/inserter/child-blocks.js index 53590af3a1ee72..36cb283dc1d9c7 100644 --- a/packages/block-editor/src/components/inserter/child-blocks.js +++ b/packages/block-editor/src/components/inserter/child-blocks.js @@ -27,17 +27,13 @@ function ChildBlocks( { rootBlockIcon, rootBlockTitle, items, ...props } ) { export default compose( ifCondition( ( { items } ) => items && items.length > 0 ), withSelect( ( select, { rootClientId } ) => { - const { - getBlockType, - } = select( 'core/blocks' ); - const { - getBlockName, - } = select( 'core/block-editor' ); + const { getBlockType } = select( 'core/blocks' ); + const { getBlockName } = select( 'core/block-editor' ); const rootBlockName = getBlockName( rootClientId ); const rootBlockType = getBlockType( rootBlockName ); return { rootBlockTitle: rootBlockType && rootBlockType.title, rootBlockIcon: rootBlockType && rootBlockType.icon, }; - } ), + } ) )( ChildBlocks ); diff --git a/packages/block-editor/src/components/inserter/index.js b/packages/block-editor/src/components/inserter/index.js index 5abb1ae4ef9230..9d70dddf2bdcd6 100644 --- a/packages/block-editor/src/components/inserter/index.js +++ b/packages/block-editor/src/components/inserter/index.js @@ -54,10 +54,7 @@ class Inserter extends Component { * @return {WPElement} Dropdown toggle element. */ renderToggle( { onToggle, isOpen } ) { - const { - disabled, - renderToggle = defaultRenderToggle, - } = this.props; + const { disabled, renderToggle = defaultRenderToggle } = this.props; return renderToggle( { onToggle, isOpen, disabled } ); } diff --git a/packages/block-editor/src/components/inserter/index.native.js b/packages/block-editor/src/components/inserter/index.native.js index 4c06402af38214..7cd9b3ec1f5a18 100644 --- a/packages/block-editor/src/components/inserter/index.native.js +++ b/packages/block-editor/src/components/inserter/index.native.js @@ -17,7 +17,7 @@ import InserterMenu from './menu'; const defaultRenderToggle = ( { onToggle, disabled, style } ) => ( ) } + icon={ } onClick={ onToggle } extraProps={ { hint: __( 'Double tap to add a block' ) } } isDisabled={ disabled } @@ -53,11 +53,7 @@ class Inserter extends Component { * @return {WPElement} Dropdown toggle element. */ renderToggle( { onToggle, isOpen } ) { - const { - disabled, - renderToggle = defaultRenderToggle, - getStylesFromColorScheme, - } = this.props; + const { disabled, renderToggle = defaultRenderToggle, getStylesFromColorScheme } = this.props; const style = getStylesFromColorScheme( styles.addBlockButton, styles.addBlockButtonDark ); return renderToggle( { onToggle, isOpen, disabled, style } ); } @@ -100,11 +96,9 @@ class Inserter extends Component { export default compose( [ withSelect( ( select, { clientId, isAppender, rootClientId } ) => { - const { - getInserterItems, - getBlockRootClientId, - getBlockSelectionEnd, - } = select( 'core/block-editor' ); + const { getInserterItems, getBlockRootClientId, getBlockSelectionEnd } = select( + 'core/block-editor' + ); let destinationRootClientId = rootClientId; if ( ! destinationRootClientId && ! clientId && ! isAppender ) { diff --git a/packages/block-editor/src/components/inserter/menu.js b/packages/block-editor/src/components/inserter/menu.js index 7522c553698653..f2a80056f15d45 100644 --- a/packages/block-editor/src/components/inserter/menu.js +++ b/packages/block-editor/src/components/inserter/menu.js @@ -23,11 +23,7 @@ import classnames from 'classnames'; */ import { __, _n, _x, sprintf } from '@wordpress/i18n'; import { Component, createRef } from '@wordpress/element'; -import { - PanelBody, - withSpokenMessages, - Tip, -} from '@wordpress/components'; +import { PanelBody, withSpokenMessages, Tip } from '@wordpress/components'; import { getCategories, isReusableBlock, @@ -69,7 +65,11 @@ export const searchItems = ( items, searchTerm ) => { return items.filter( ( item ) => { const itemCategory = find( categories, { slug: item.category } ); - return matchSearch( item.title ) || some( item.keywords, matchSearch ) || ( itemCategory && matchSearch( itemCategory.title ) ); + return ( + matchSearch( item.title ) || + some( item.keywords, matchSearch ) || + ( itemCategory && matchSearch( itemCategory.title ) ) + ); } ); }; @@ -162,10 +162,7 @@ export class InserterMenu extends Component { } ); } else { this.setState( { - openPanels: [ - ...this.state.openPanels, - panel, - ], + openPanels: [ ...this.state.openPanels, panel ], } ); this.props.setTimeout( () => { @@ -190,9 +187,7 @@ export class InserterMenu extends Component { openPanels.push( 'reusable' ); } if ( filteredItems.length > 0 ) { - openPanels = openPanels.concat( - Object.keys( itemsPerCategory ) - ); + openPanels = openPanels.concat( Object.keys( itemsPerCategory ) ); } return openPanels; } @@ -236,9 +231,12 @@ export class InserterMenu extends Component { ), } ); - const resultCount = Object.keys( itemsPerCategory ).reduce( ( accumulator, currentCategorySlug ) => { - return accumulator + itemsPerCategory[ currentCategorySlug ].length; - }, 0 ); + const resultCount = Object.keys( itemsPerCategory ).reduce( + ( accumulator, currentCategorySlug ) => { + return accumulator + itemsPerCategory[ currentCategorySlug ].length; + }, + 0 + ); const resultsFoundMessage = sprintf( _n( '%d result found.', '%d results found.', resultCount ), @@ -267,7 +265,8 @@ export class InserterMenu extends Component { } = this.state; const isPanelOpen = ( panel ) => openPanels.indexOf( panel ) !== -1; - const hasItems = ! isEmpty( suggestedItems ) || ! isEmpty( reusableItems ) || ! isEmpty( itemsPerCategory ); + const hasItems = + ! isEmpty( suggestedItems ) || ! isEmpty( reusableItems ) || ! isEmpty( itemsPerCategory ); const hoveredItemBlockType = hoveredItem ? getBlockType( hoveredItem.name ) : null; const hasHelpPanel = hasItems && showInserterHelpPanel; @@ -286,7 +285,10 @@ export class InserterMenu extends Component { onKeyDown={ this.onKeyDown } >
    -
    '; const blockNode = wrapper.firstChild; expect( hasInnerBlocksContext( blockNode ) ).toBe( true ); diff --git a/packages/block-editor/src/utils/transform-styles/ast/parse.js b/packages/block-editor/src/utils/transform-styles/ast/parse.js index 11e8d22a378475..7febb35619250f 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/parse.js +++ b/packages/block-editor/src/utils/transform-styles/ast/parse.js @@ -163,7 +163,7 @@ export default function( css, options ) { let c; accumulator = accumulator || []; // eslint-disable-next-line no-cond-assign - while ( c = comment() ) { + while ( ( c = comment() ) ) { if ( c !== false ) { accumulator.push( c ); } @@ -273,7 +273,7 @@ export default function( css, options ) { // declarations let decl; // eslint-disable-next-line no-cond-assign - while ( decl = declaration() ) { + while ( ( decl = declaration() ) ) { if ( decl !== false ) { decls.push( decl ); comments( decls ); @@ -296,7 +296,7 @@ export default function( css, options ) { const pos = position(); // eslint-disable-next-line no-cond-assign - while ( m = match( /^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/ ) ) { + while ( ( m = match( /^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/ ) ) ) { vals.push( m[ 1 ] ); match( /^,\s*/ ); } @@ -339,7 +339,7 @@ export default function( css, options ) { let frame; let frames = comments(); // eslint-disable-next-line no-cond-assign - while ( frame = keyframe() ) { + while ( ( frame = keyframe() ) ) { frames.push( frame ); frames = frames.concat( comments() ); } @@ -483,7 +483,7 @@ export default function( css, options ) { // declarations let decl; // eslint-disable-next-line no-cond-assign - while ( decl = declaration() ) { + while ( ( decl = declaration() ) ) { decls.push( decl ); decls = decls.concat( comments() ); } @@ -550,7 +550,7 @@ export default function( css, options ) { // declarations let decl; // eslint-disable-next-line no-cond-assign - while ( decl = declaration() ) { + while ( ( decl = declaration() ) ) { decls.push( decl ); decls = decls.concat( comments() ); } @@ -610,17 +610,19 @@ export default function( css, options ) { return; } - return atkeyframes() || - atmedia() || - atcustommedia() || - atsupports() || - atimport() || - atcharset() || - atnamespace() || - atdocument() || - atpage() || - athost() || - atfontface(); + return ( + atkeyframes() || + atmedia() || + atcustommedia() || + atsupports() || + atimport() || + atcharset() || + atnamespace() || + atdocument() || + atpage() || + athost() || + atfontface() + ); } /** diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js index 6b3f0468c5ad65..e238cc97777f21 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js @@ -36,9 +36,7 @@ inherits( Compiler, Base ); */ Compiler.prototype.compile = function( node ) { - return node.stylesheet - .rules.map( this.visit, this ) - .join( '' ); + return node.stylesheet.rules.map( this.visit, this ).join( '' ); }; /** @@ -62,10 +60,12 @@ Compiler.prototype.import = function( node ) { */ Compiler.prototype.media = function( node ) { - return this.emit( '@media ' + node.media, node.position ) + - this.emit( '{' ) + - this.mapVisit( node.rules ) + - this.emit( '}' ); + return ( + this.emit( '@media ' + node.media, node.position ) + + this.emit( '{' ) + + this.mapVisit( node.rules ) + + this.emit( '}' ) + ); }; /** @@ -75,10 +75,12 @@ Compiler.prototype.media = function( node ) { Compiler.prototype.document = function( node ) { const doc = '@' + ( node.vendor || '' ) + 'document ' + node.document; - return this.emit( doc, node.position ) + - this.emit( '{' ) + - this.mapVisit( node.rules ) + - this.emit( '}' ); + return ( + this.emit( doc, node.position ) + + this.emit( '{' ) + + this.mapVisit( node.rules ) + + this.emit( '}' ) + ); }; /** @@ -102,10 +104,12 @@ Compiler.prototype.namespace = function( node ) { */ Compiler.prototype.supports = function( node ) { - return this.emit( '@supports ' + node.supports, node.position ) + - this.emit( '{' ) + - this.mapVisit( node.rules ) + - this.emit( '}' ); + return ( + this.emit( '@supports ' + node.supports, node.position ) + + this.emit( '{' ) + + this.mapVisit( node.rules ) + + this.emit( '}' ) + ); }; /** @@ -113,13 +117,12 @@ Compiler.prototype.supports = function( node ) { */ Compiler.prototype.keyframes = function( node ) { - return this.emit( '@' + - ( node.vendor || '' ) + - 'keyframes ' + - node.name, node.position ) + - this.emit( '{' ) + - this.mapVisit( node.keyframes ) + - this.emit( '}' ); + return ( + this.emit( '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, node.position ) + + this.emit( '{' ) + + this.mapVisit( node.keyframes ) + + this.emit( '}' ) + ); }; /** @@ -129,10 +132,12 @@ Compiler.prototype.keyframes = function( node ) { Compiler.prototype.keyframe = function( node ) { const decls = node.declarations; - return this.emit( node.values.join( ',' ), node.position ) + - this.emit( '{' ) + - this.mapVisit( decls ) + - this.emit( '}' ); + return ( + this.emit( node.values.join( ',' ), node.position ) + + this.emit( '{' ) + + this.mapVisit( decls ) + + this.emit( '}' ) + ); }; /** @@ -140,14 +145,14 @@ Compiler.prototype.keyframe = function( node ) { */ Compiler.prototype.page = function( node ) { - const sel = node.selectors.length ? - node.selectors.join( ', ' ) : - ''; + const sel = node.selectors.length ? node.selectors.join( ', ' ) : ''; - return this.emit( '@page ' + sel, node.position ) + - this.emit( '{' ) + - this.mapVisit( node.declarations ) + - this.emit( '}' ); + return ( + this.emit( '@page ' + sel, node.position ) + + this.emit( '{' ) + + this.mapVisit( node.declarations ) + + this.emit( '}' ) + ); }; /** @@ -155,10 +160,12 @@ Compiler.prototype.page = function( node ) { */ Compiler.prototype[ 'font-face' ] = function( node ) { - return this.emit( '@font-face', node.position ) + - this.emit( '{' ) + - this.mapVisit( node.declarations ) + - this.emit( '}' ); + return ( + this.emit( '@font-face', node.position ) + + this.emit( '{' ) + + this.mapVisit( node.declarations ) + + this.emit( '}' ) + ); }; /** @@ -166,10 +173,12 @@ Compiler.prototype[ 'font-face' ] = function( node ) { */ Compiler.prototype.host = function( node ) { - return this.emit( '@host', node.position ) + - this.emit( '{' ) + - this.mapVisit( node.rules ) + - this.emit( '}' ); + return ( + this.emit( '@host', node.position ) + + this.emit( '{' ) + + this.mapVisit( node.rules ) + + this.emit( '}' ) + ); }; /** @@ -190,10 +199,12 @@ Compiler.prototype.rule = function( node ) { return ''; } - return this.emit( node.selectors.join( ',' ), node.position ) + - this.emit( '{' ) + - this.mapVisit( decls ) + - this.emit( '}' ); + return ( + this.emit( node.selectors.join( ',' ), node.position ) + + this.emit( '{' ) + + this.mapVisit( decls ) + + this.emit( '}' ) + ); }; /** diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js index cc15526e14946e..ec9194af5bb2f6 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js @@ -74,14 +74,9 @@ Compiler.prototype.import = function( node ) { Compiler.prototype.media = function( node ) { return ( this.emit( '@media ' + node.media, node.position ) + - this.emit( - ' {\n' + this.indent( 1 ) - ) + + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.rules, '\n\n' ) + - this.emit( - this.indent( -1 ) + - '\n}' - ) + this.emit( this.indent( -1 ) + '\n}' ) ); }; @@ -94,16 +89,9 @@ Compiler.prototype.document = function( node ) { return ( this.emit( doc, node.position ) + - this.emit( - ' ' + - ' {\n' + - this.indent( 1 ) - ) + + this.emit( ' ' + ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.rules, '\n\n' ) + - this.emit( - this.indent( -1 ) + - '\n}' - ) + this.emit( this.indent( -1 ) + '\n}' ) ); }; @@ -130,15 +118,9 @@ Compiler.prototype.namespace = function( node ) { Compiler.prototype.supports = function( node ) { return ( this.emit( '@supports ' + node.supports, node.position ) + - this.emit( - ' {\n' + - this.indent( 1 ) - ) + + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.rules, '\n\n' ) + - this.emit( - this.indent( -1 ) + - '\n}' - ) + this.emit( this.indent( -1 ) + '\n}' ) ); }; @@ -149,15 +131,9 @@ Compiler.prototype.supports = function( node ) { Compiler.prototype.keyframes = function( node ) { return ( this.emit( '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, node.position ) + - this.emit( - ' {\n' + - this.indent( 1 ) - ) + + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.keyframes, '\n' ) + - this.emit( - this.indent( -1 ) + - '}' - ) + this.emit( this.indent( -1 ) + '}' ) ); }; @@ -171,16 +147,9 @@ Compiler.prototype.keyframe = function( node ) { return ( this.emit( this.indent() ) + this.emit( node.values.join( ', ' ), node.position ) + - this.emit( - ' {\n' + - this.indent( 1 ) - ) + + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( decls, '\n' ) + - this.emit( - this.indent( -1 ) + - '\n' + - this.indent() + '}\n' - ) + this.emit( this.indent( -1 ) + '\n' + this.indent() + '}\n' ) ); }; @@ -189,16 +158,16 @@ Compiler.prototype.keyframe = function( node ) { */ Compiler.prototype.page = function( node ) { - const sel = node.selectors.length ? - node.selectors.join( ', ' ) + ' ' : - ''; - - return this.emit( '@page ' + sel, node.position ) + - this.emit( '{\n' ) + - this.emit( this.indent( 1 ) ) + - this.mapVisit( node.declarations, '\n' ) + - this.emit( this.indent( -1 ) ) + - this.emit( '\n}' ); + const sel = node.selectors.length ? node.selectors.join( ', ' ) + ' ' : ''; + + return ( + this.emit( '@page ' + sel, node.position ) + + this.emit( '{\n' ) + + this.emit( this.indent( 1 ) ) + + this.mapVisit( node.declarations, '\n' ) + + this.emit( this.indent( -1 ) ) + + this.emit( '\n}' ) + ); }; /** @@ -206,12 +175,14 @@ Compiler.prototype.page = function( node ) { */ Compiler.prototype[ 'font-face' ] = function( node ) { - return this.emit( '@font-face ', node.position ) + - this.emit( '{\n' ) + - this.emit( this.indent( 1 ) ) + - this.mapVisit( node.declarations, '\n' ) + - this.emit( this.indent( -1 ) ) + - this.emit( '\n}' ); + return ( + this.emit( '@font-face ', node.position ) + + this.emit( '{\n' ) + + this.emit( this.indent( 1 ) ) + + this.mapVisit( node.declarations, '\n' ) + + this.emit( this.indent( -1 ) ) + + this.emit( '\n}' ) + ); }; /** @@ -221,15 +192,9 @@ Compiler.prototype[ 'font-face' ] = function( node ) { Compiler.prototype.host = function( node ) { return ( this.emit( '@host', node.position ) + - this.emit( - ' {\n' + - this.indent( 1 ) - ) + + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.rules, '\n\n' ) + - this.emit( - this.indent( -1 ) + - '\n}' - ) + this.emit( this.indent( -1 ) + '\n}' ) ); }; @@ -252,14 +217,21 @@ Compiler.prototype.rule = function( node ) { return ''; } - return this.emit( node.selectors.map( function( s ) { - return indent + s; - } ).join( ',\n' ), node.position ) + - this.emit( ' {\n' ) + - this.emit( this.indent( 1 ) ) + - this.mapVisit( decls, '\n' ) + - this.emit( this.indent( -1 ) ) + - this.emit( '\n' + this.indent() + '}' ); + return ( + this.emit( + node.selectors + .map( function( s ) { + return indent + s; + } ) + .join( ',\n' ), + node.position + ) + + this.emit( ' {\n' ) + + this.emit( this.indent( 1 ) ) + + this.mapVisit( decls, '\n' ) + + this.emit( this.indent( -1 ) ) + + this.emit( '\n' + this.indent() + '}' ) + ); }; /** @@ -267,9 +239,11 @@ Compiler.prototype.rule = function( node ) { */ Compiler.prototype.declaration = function( node ) { - return this.emit( this.indent() ) + - this.emit( node.property + ': ' + node.value, node.position ) + - this.emit( ';' ); + return ( + this.emit( this.indent() ) + + this.emit( node.property + ': ' + node.value, node.position ) + + this.emit( ';' ) + ); }; /** diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js index 2dcc4d4475f02b..cd702d1b1304f4 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js @@ -23,9 +23,7 @@ import Identity from './identity'; export default function( node, options ) { options = options || {}; - const compiler = options.compress ? - new Compressed( options ) : - new Identity( options ); + const compiler = options.compress ? new Compressed( options ) : new Identity( options ); const code = compiler.compile( node ); return code; diff --git a/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js b/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js index 4516fffa2196dc..ab9c5a6aa3d67a 100644 --- a/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js +++ b/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js @@ -76,14 +76,7 @@ function processURL( baseURL ) { const URL = getResourcePath( meta.value, baseURL ); return { ...meta, - newUrl: - 'url(' + - meta.before + - meta.quote + - URL + - meta.quote + - meta.after + - ')', + newUrl: 'url(' + meta.before + meta.quote + URL + meta.quote + meta.after + ')', }; }; } diff --git a/packages/block-editor/src/utils/transform-styles/transforms/wrap.js b/packages/block-editor/src/utils/transform-styles/transforms/wrap.js index d7fe709138fa83..e9cfafac5740fb 100644 --- a/packages/block-editor/src/utils/transform-styles/transforms/wrap.js +++ b/packages/block-editor/src/utils/transform-styles/transforms/wrap.js @@ -15,9 +15,11 @@ const wrap = ( namespace, ignore = [] ) => ( node ) => { } // Anything other than a root tag is always prefixed. - {if ( ! selector.match( IS_ROOT_TAG ) ) { - return namespace + ' ' + selector; - }} + { + if ( ! selector.match( IS_ROOT_TAG ) ) { + return namespace + ' ' + selector; + } + } // HTML and Body elements cannot be contained within our container so lets extract their styles. return selector.replace( /^(body|html|:root)/, namespace ); diff --git a/packages/block-library/src/archives/edit.js b/packages/block-library/src/archives/edit.js index 6909b70ccc4271..ec238f465086e6 100644 --- a/packages/block-library/src/archives/edit.js +++ b/packages/block-library/src/archives/edit.js @@ -1,11 +1,7 @@ /** * WordPress dependencies */ -import { - PanelBody, - ToggleControl, - Disabled, -} from '@wordpress/components'; +import { PanelBody, ToggleControl, Disabled } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; import { InspectorControls } from '@wordpress/block-editor'; import ServerSideRender from '@wordpress/server-side-render'; diff --git a/packages/block-library/src/archives/icon.js b/packages/block-library/src/archives/icon.js index 074a16c79458fc..78626491dd52f7 100644 --- a/packages/block-library/src/archives/icon.js +++ b/packages/block-library/src/archives/icon.js @@ -4,5 +4,7 @@ import { Path, SVG } from '@wordpress/components'; export default ( - + + + ); diff --git a/packages/block-library/src/audio/edit.js b/packages/block-library/src/audio/edit.js index 15387acbd90c7a..03d08ab7cbe887 100644 --- a/packages/block-library/src/audio/edit.js +++ b/packages/block-library/src/audio/edit.js @@ -50,12 +50,7 @@ class AudioEdit extends Component { } componentDidMount() { - const { - attributes, - mediaUpload, - noticeOperations, - setAttributes, - } = this.props; + const { attributes, mediaUpload, noticeOperations, setAttributes } = this.props; const { id, src = '' } = attributes; if ( ! id && isBlobURL( src ) ) { @@ -92,9 +87,7 @@ class AudioEdit extends Component { // the editing UI. if ( newSrc !== src ) { // Check if there's an embed block that handles this URL. - const embedBlock = createUpgradedEmbedBlock( - { attributes: { url: newSrc } } - ); + const embedBlock = createUpgradedEmbedBlock( { attributes: { url: newSrc } } ); if ( undefined !== embedBlock ) { this.props.onReplace( embedBlock ); return; @@ -112,7 +105,9 @@ class AudioEdit extends Component { } getAutoplayHelp( checked ) { - return checked ? __( 'Note: Autoplaying audio may cause usability issues for some visitors.' ) : null; + return checked + ? __( 'Note: Autoplaying audio may cause usability issues for some visitors.' ) + : null; } render() { @@ -180,7 +175,9 @@ class AudioEdit extends Component { label={ __( 'Preload' ) } value={ undefined !== preload ? preload : 'none' } // `undefined` is required for the preload attribute to be unset. - onChange={ ( value ) => setAttributes( { preload: ( 'none' !== value ) ? value : undefined } ) } + onChange={ ( value ) => + setAttributes( { preload: 'none' !== value ? value : undefined } ) + } options={ [ { value: 'auto', label: __( 'Auto' ) }, { value: 'metadata', label: __( 'Metadata' ) }, diff --git a/packages/block-library/src/audio/icon.js b/packages/block-library/src/audio/icon.js index 4b871506bf4788..d1ebfc6b7fd43b 100644 --- a/packages/block-library/src/audio/icon.js +++ b/packages/block-library/src/audio/icon.js @@ -3,4 +3,9 @@ */ import { Path, SVG } from '@wordpress/components'; -export default ; +export default ( + + + + +); diff --git a/packages/block-library/src/audio/save.js b/packages/block-library/src/audio/save.js index 13b32be648abb5..4704875e58f00e 100644 --- a/packages/block-library/src/audio/save.js +++ b/packages/block-library/src/audio/save.js @@ -8,8 +8,16 @@ export default function save( { attributes } ) { return (
    -
    ); } diff --git a/packages/block-library/src/block/edit-panel/index.js b/packages/block-library/src/block/edit-panel/index.js index 0bc064d25203c7..201e4b5a02cbee 100644 --- a/packages/block-library/src/block/edit-panel/index.js +++ b/packages/block-library/src/block/edit-panel/index.js @@ -31,7 +31,11 @@ class ReusableBlockEditPanel extends Component { this.titleField.current.select(); } // Move focus back to the Edit button after pressing the Escape key or Save. - if ( ( prevProps.isEditing || prevProps.isSaving ) && ! this.props.isEditing && ! this.props.isSaving ) { + if ( + ( prevProps.isEditing || prevProps.isSaving ) && + ! this.props.isEditing && + ! this.props.isSaving + ) { this.editButton.current.focus(); } } @@ -57,11 +61,9 @@ class ReusableBlockEditPanel extends Component { return ( <> - { ( ! isEditing && ! isSaving ) && ( + { ! isEditing && ! isSaving && (
    - - { title } - + { title }
    diff --git a/packages/block-library/src/button/icon.js b/packages/block-library/src/button/icon.js index 6e18a60a648fe3..73208af2f03f84 100644 --- a/packages/block-library/src/button/icon.js +++ b/packages/block-library/src/button/icon.js @@ -4,5 +4,10 @@ import { G, Path, SVG } from '@wordpress/components'; export default ( - + + + + + + ); diff --git a/packages/block-library/src/button/save.js b/packages/block-library/src/button/save.js index bcf18ffc293242..716b16ba391f2d 100644 --- a/packages/block-library/src/button/save.js +++ b/packages/block-library/src/button/save.js @@ -6,10 +6,7 @@ import classnames from 'classnames'; /** * WordPress dependencies */ -import { - RichText, - getColorClassName, -} from '@wordpress/block-editor'; +import { RichText, getColorClassName } from '@wordpress/block-editor'; export default function save( { attributes } ) { const { @@ -27,7 +24,8 @@ export default function save( { attributes } ) { } = attributes; const textClass = getColorClassName( 'color', textColor ); - const backgroundClass = ! customGradient && getColorClassName( 'background-color', backgroundColor ); + const backgroundClass = + ! customGradient && getColorClassName( 'background-color', backgroundColor ); const buttonClasses = classnames( 'wp-block-button__link', { 'has-text-color': textColor || customTextColor, diff --git a/packages/block-library/src/calendar/edit.js b/packages/block-library/src/calendar/edit.js index 243387c6dec399..40591744776ee1 100644 --- a/packages/block-library/src/calendar/edit.js +++ b/packages/block-library/src/calendar/edit.js @@ -7,9 +7,7 @@ import memoize from 'memize'; /** * WordPress dependencies */ -import { - Disabled, -} from '@wordpress/components'; +import { Disabled } from '@wordpress/components'; import { Component } from '@wordpress/element'; import { withSelect } from '@wordpress/data'; import ServerSideRender from '@wordpress/server-side-render'; @@ -17,14 +15,10 @@ import ServerSideRender from '@wordpress/server-side-render'; class CalendarEdit extends Component { constructor() { super( ...arguments ); - this.getYearMonth = memoize( - this.getYearMonth.bind( this ), - { maxSize: 1 } - ); - this.getServerSideAttributes = memoize( - this.getServerSideAttributes.bind( this ), - { maxSize: 1 } - ); + this.getYearMonth = memoize( this.getYearMonth.bind( this ), { maxSize: 1 } ); + this.getServerSideAttributes = memoize( this.getServerSideAttributes.bind( this ), { + maxSize: 1, + } ); } getYearMonth( date ) { @@ -50,10 +44,7 @@ class CalendarEdit extends Component { ); @@ -65,16 +56,12 @@ export default withSelect( ( select ) => { if ( ! coreEditorSelect ) { return; } - const { - getEditedPostAttribute, - } = coreEditorSelect; + const { getEditedPostAttribute } = coreEditorSelect; const postType = getEditedPostAttribute( 'type' ); // Dates are used to overwrite year and month used on the calendar. // This overwrite should only happen for 'post' post types. // For other post types the calendar always displays the current month. return { - date: postType === 'post' ? - getEditedPostAttribute( 'date' ) : - undefined, + date: postType === 'post' ? getEditedPostAttribute( 'date' ) : undefined, }; } )( CalendarEdit ); diff --git a/packages/block-library/src/calendar/icon.js b/packages/block-library/src/calendar/icon.js index 023a1902171d04..c89c33a333ea53 100644 --- a/packages/block-library/src/calendar/icon.js +++ b/packages/block-library/src/calendar/icon.js @@ -4,5 +4,10 @@ import { G, Path, SVG } from '@wordpress/components'; export default ( - + + + + + + ); diff --git a/packages/block-library/src/categories/edit.js b/packages/block-library/src/categories/edit.js index 9020c33d484788..d578448cf8bbc1 100644 --- a/packages/block-library/src/categories/edit.js +++ b/packages/block-library/src/categories/edit.js @@ -86,21 +86,20 @@ class CategoriesEdit extends Component { return (
  • - { this.renderCategoryName( category ) } - { showPostCounts && - - { ' ' }({ category.count }) - - } - - { - showHierarchy && - !! childCategories.length && ( -
      - { childCategories.map( ( childCategory ) => this.renderCategoryListItem( childCategory, level + 1 ) ) } -
    - ) - } + + { this.renderCategoryName( category ) } + + { showPostCounts && ( + ({ category.count }) + ) } + + { showHierarchy && !! childCategories.length && ( +
      + { childCategories.map( ( childCategory ) => + this.renderCategoryListItem( childCategory, level + 1 ) + ) } +
    + ) }
  • ); } @@ -131,16 +130,13 @@ class CategoriesEdit extends Component { , showHierarchy && - !! childCategories.length && ( - childCategories.map( ( childCategory ) => this.renderCategoryDropdownItem( childCategory, level + 1 ) ) - ), + !! childCategories.length && + childCategories.map( ( childCategory ) => + this.renderCategoryDropdownItem( childCategory, level + 1 ) + ), ]; } @@ -174,10 +170,7 @@ class CategoriesEdit extends Component { return ( <> { inspectorControls } - + @@ -188,11 +181,7 @@ class CategoriesEdit extends Component { <> { inspectorControls }
    - { - displayAsDropdown ? - this.renderCategoryDropdown() : - this.renderCategoryList() - } + { displayAsDropdown ? this.renderCategoryDropdown() : this.renderCategoryList() }
    ); diff --git a/packages/block-library/src/categories/icon.js b/packages/block-library/src/categories/icon.js index fb89fbd4ce1a13..fd3b10a6c25486 100644 --- a/packages/block-library/src/categories/icon.js +++ b/packages/block-library/src/categories/icon.js @@ -4,5 +4,10 @@ import { SVG, Path } from '@wordpress/components'; export default ( - + + + + + + ); diff --git a/packages/block-library/src/classic/edit.js b/packages/block-library/src/classic/edit.js index 2ce77409e8e0f3..e273f9a39b6218 100644 --- a/packages/block-library/src/classic/edit.js +++ b/packages/block-library/src/classic/edit.js @@ -52,7 +52,10 @@ export default class ClassicEdit extends Component { } componentDidUpdate( prevProps ) { - const { clientId, attributes: { content } } = this.props; + const { + clientId, + attributes: { content }, + } = this.props; const editor = window.tinymce.get( `editor-${ clientId }` ); @@ -76,7 +79,10 @@ export default class ClassicEdit extends Component { } onSetup( editor ) { - const { attributes: { content }, setAttributes } = this.props; + const { + attributes: { content }, + setAttributes, + } = this.props; const { ref } = this; let bookmark; @@ -189,7 +195,7 @@ export default class ClassicEdit extends Component {
    this.ref = ref } + ref={ ( ref ) => ( this.ref = ref ) } className="block-library-classic__toolbar" onClick={ this.focus } data-placeholder={ __( 'Classic' ) } diff --git a/packages/block-library/src/classic/icon.js b/packages/block-library/src/classic/icon.js index 4193982d2aa449..a46f4943b0c600 100644 --- a/packages/block-library/src/classic/icon.js +++ b/packages/block-library/src/classic/icon.js @@ -4,5 +4,19 @@ import { Path, Rect, SVG } from '@wordpress/components'; export default ( - + + + + + + + + + + + + + + + ); diff --git a/packages/block-library/src/code/edit.native.js b/packages/block-library/src/code/edit.native.js index d8641b2270d20a..09c2a8f8dd2d55 100644 --- a/packages/block-library/src/code/edit.native.js +++ b/packages/block-library/src/code/edit.native.js @@ -40,7 +40,7 @@ export function CodeEdit( props ) { isSelected={ props.isSelected } onFocus={ onFocus } onBlur={ onBlur } - fontFamily={ ( styles.blockCode.fontFamily ) } + fontFamily={ styles.blockCode.fontFamily } placeholderTextColor={ placeholderStyle.color } /> diff --git a/packages/block-library/src/code/icon.js b/packages/block-library/src/code/icon.js index 35e809693a36ba..9a43a87b75b602 100644 --- a/packages/block-library/src/code/icon.js +++ b/packages/block-library/src/code/icon.js @@ -4,5 +4,8 @@ import { Path, SVG } from '@wordpress/components'; export default ( - + + + + ); diff --git a/packages/block-library/src/code/index.js b/packages/block-library/src/code/index.js index e23a740b9d5e66..7c551b7462ac0c 100644 --- a/packages/block-library/src/code/index.js +++ b/packages/block-library/src/code/index.js @@ -22,11 +22,16 @@ export const settings = { icon, example: { attributes: { - content: __( '// A "block" is the abstract term used' ) + '\n' + - __( '// to describe units of markup that,' ) + '\n' + - __( '// when composed together, form the' ) + '\n' + - __( '// content or layout of a page.' ) + '\n' + - __( 'registerBlockType( name, settings );' ), + content: + __( '// A "block" is the abstract term used' ) + + '\n' + + __( '// to describe units of markup that,' ) + + '\n' + + __( '// when composed together, form the' ) + + '\n' + + __( '// content or layout of a page.' ) + + '\n' + + __( 'registerBlockType( name, settings );' ), }, }, supports: { diff --git a/packages/block-library/src/code/save.js b/packages/block-library/src/code/save.js index 21d74669c854b9..1438c3174aa1c4 100644 --- a/packages/block-library/src/code/save.js +++ b/packages/block-library/src/code/save.js @@ -1,3 +1,7 @@ export default function save( { attributes } ) { - return
    { attributes.content }
    ; + return ( +
    +			{ attributes.content }
    +		
    + ); } diff --git a/packages/block-library/src/code/transforms.js b/packages/block-library/src/code/transforms.js index 180a95bc9b4c54..585df87c0f7fa1 100644 --- a/packages/block-library/src/code/transforms.js +++ b/packages/block-library/src/code/transforms.js @@ -12,11 +12,10 @@ const transforms = { }, { type: 'raw', - isMatch: ( node ) => ( + isMatch: ( node ) => node.nodeName === 'PRE' && node.children.length === 1 && - node.firstChild.nodeName === 'CODE' - ), + node.firstChild.nodeName === 'CODE', schema: { pre: { children: { diff --git a/packages/block-library/src/column/edit.js b/packages/block-library/src/column/edit.js index 72f359f33da599..c87588877ef5e8 100644 --- a/packages/block-library/src/column/edit.js +++ b/packages/block-library/src/column/edit.js @@ -29,30 +29,17 @@ import { getRedistributedColumnWidths, } from '../columns/utils'; -function ColumnEdit( { - attributes, - className, - updateAlignment, - updateWidth, - hasChildBlocks, -} ) { +function ColumnEdit( { attributes, className, updateAlignment, updateWidth, hasChildBlocks } ) { const { verticalAlignment, width } = attributes; - const classes = classnames( - className, - 'block-core-columns', - { - [ `is-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, - } - ); + const classes = classnames( className, 'block-core-columns', { + [ `is-vertically-aligned-${ verticalAlignment }` ]: verticalAlignment, + } ); return (
    - + @@ -69,11 +56,7 @@ function ColumnEdit( { - ) } + renderAppender={ hasChildBlocks ? undefined : () => } />
    ); @@ -114,12 +97,11 @@ export default compose( // The occupied width is calculated as the sum of the new width // and the total width of blocks _not_ in the adjacent set. - const occupiedWidth = width + getTotalColumnsWidth( - difference( columns, [ - find( columns, { clientId } ), - ...adjacentColumns, - ] ) - ); + const occupiedWidth = + width + + getTotalColumnsWidth( + difference( columns, [ find( columns, { clientId } ), ...adjacentColumns ] ) + ); // Compute _all_ next column widths, in case the updated column // is in the middle of a set of columns which don't yet have diff --git a/packages/block-library/src/column/icon.js b/packages/block-library/src/column/icon.js index 080d796121d01a..c7d61beb03a1f9 100644 --- a/packages/block-library/src/column/icon.js +++ b/packages/block-library/src/column/icon.js @@ -4,5 +4,8 @@ import { Path, SVG } from '@wordpress/components'; export default ( - + + + + ); diff --git a/packages/block-library/src/column/index.js b/packages/block-library/src/column/index.js index 250ce0bad65a42..61deb5ffff228f 100644 --- a/packages/block-library/src/column/index.js +++ b/packages/block-library/src/column/index.js @@ -38,4 +38,3 @@ export const settings = { edit, save, }; - diff --git a/packages/block-library/src/columns/deprecated.js b/packages/block-library/src/columns/deprecated.js index a344f72eaf69f3..10d296df2b34c2 100644 --- a/packages/block-library/src/columns/deprecated.js +++ b/packages/block-library/src/columns/deprecated.js @@ -8,9 +8,7 @@ import classnames from 'classnames'; * WordPress dependencies */ import { createBlock } from '@wordpress/blocks'; -import { - InnerBlocks, -} from '@wordpress/block-editor'; +import { InnerBlocks } from '@wordpress/block-editor'; /** * Given an HTML string for a deprecated columns inner block, returns the @@ -51,9 +49,9 @@ export default [ // Columns block and a deprecation is the unlikely case due to // its subsequent migration, optimize for the `false` condition // by performing a naive, inaccurate pass at inner blocks. - const isFastPassEligible = innerBlocks.some( ( innerBlock ) => ( + const isFastPassEligible = innerBlocks.some( ( innerBlock ) => /layout-column-\d+/.test( innerBlock.originalContent ) - ) ); + ); if ( ! isFastPassEligible ) { return false; @@ -61,9 +59,9 @@ export default [ // Only if the fast pass is considered eligible is the more // accurate, durable, slower condition performed. - return innerBlocks.some( ( innerBlock ) => ( - getDeprecatedLayoutColumn( innerBlock.originalContent ) !== undefined - ) ); + return innerBlocks.some( + ( innerBlock ) => getDeprecatedLayoutColumn( innerBlock.originalContent ) !== undefined + ); }, migrate( attributes, innerBlocks ) { const columns = innerBlocks.reduce( ( accumulator, innerBlock ) => { @@ -83,14 +81,11 @@ export default [ return accumulator; }, [] ); - const migratedInnerBlocks = columns.map( ( columnBlocks ) => ( + const migratedInnerBlocks = columns.map( ( columnBlocks ) => createBlock( 'core/column', {}, columnBlocks ) - ) ); + ); - return [ - omit( attributes, [ 'columns' ] ), - migratedInnerBlocks, - ]; + return [ omit( attributes, [ 'columns' ] ), migratedInnerBlocks ]; }, save( { attributes } ) { const { columns } = attributes; diff --git a/packages/block-library/src/columns/edit.js b/packages/block-library/src/columns/edit.js index 48f35e90b2d9ce..342e1730924eff 100644 --- a/packages/block-library/src/columns/edit.js +++ b/packages/block-library/src/columns/edit.js @@ -8,12 +8,7 @@ import { dropRight, times } from 'lodash'; * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { - PanelBody, - RangeControl, - SVG, - Path, -} from '@wordpress/components'; +import { PanelBody, RangeControl, SVG, Path } from '@wordpress/components'; import { InspectorControls, InnerBlocks, @@ -55,40 +50,65 @@ const ALLOWED_BLOCKS = [ 'core/column' ]; const TEMPLATE_OPTIONS = [ { title: __( 'Two columns; equal split' ), - icon: , - template: [ - [ 'core/column' ], - [ 'core/column' ], - ], + icon: ( + + + + ), + template: [ [ 'core/column' ], [ 'core/column' ] ], }, { title: __( 'Two columns; one-third, two-thirds split' ), - icon: , - template: [ - [ 'core/column', { width: 33.33 } ], - [ 'core/column', { width: 66.66 } ], - ], + icon: ( + + + + ), + template: [ [ 'core/column', { width: 33.33 } ], [ 'core/column', { width: 66.66 } ] ], }, { title: __( 'Two columns; two-thirds, one-third split' ), - icon: , - template: [ - [ 'core/column', { width: 66.66 } ], - [ 'core/column', { width: 33.33 } ], - ], + icon: ( + + + + ), + template: [ [ 'core/column', { width: 66.66 } ], [ 'core/column', { width: 33.33 } ] ], }, { title: __( 'Three columns; equal split' ), - icon: , - template: [ - [ 'core/column' ], - [ 'core/column' ], - [ 'core/column' ], - ], + icon: ( + + + + ), + template: [ [ 'core/column' ], [ 'core/column' ], [ 'core/column' ] ], }, { title: __( 'Three columns; wide center column' ), - icon: , + icon: ( + + + + ), template: [ [ 'core/column', { width: 25 } ], [ 'core/column', { width: 50 } ], @@ -105,13 +125,7 @@ const TEMPLATE_OPTIONS = [ */ const DEFAULT_COLUMNS = 2; -export function ColumnsEdit( { - attributes, - className, - updateAlignment, - updateColumns, - clientId, -} ) { +export function ColumnsEdit( { attributes, className, updateAlignment, updateColumns, clientId } ) { const { verticalAlignment } = attributes; const { count } = useSelect( ( select ) => { @@ -177,7 +191,8 @@ export function ColumnsEdit( { __experimentalAllowTemplateOptionSkip template={ showTemplateSelector ? null : template } templateLock="all" - allowedBlocks={ ALLOWED_BLOCKS } /> + allowedBlocks={ ALLOWED_BLOCKS } + />
    ); diff --git a/packages/block-library/src/columns/icon.js b/packages/block-library/src/columns/icon.js index f45aba71242c40..f0ad66955bdaed 100644 --- a/packages/block-library/src/columns/icon.js +++ b/packages/block-library/src/columns/icon.js @@ -4,5 +4,10 @@ import { G, Path, SVG } from '@wordpress/components'; export default ( - + + + + + + ); diff --git a/packages/block-library/src/columns/index.js b/packages/block-library/src/columns/index.js index 990d94d45521cb..ea80c75f2b39ab 100644 --- a/packages/block-library/src/columns/index.js +++ b/packages/block-library/src/columns/index.js @@ -19,7 +19,9 @@ export { metadata, name }; export const settings = { title: __( 'Columns' ), icon, - description: __( 'Add a block that displays content in multiple columns, then add whatever content blocks you’d like.' ), + description: __( + 'Add a block that displays content in multiple columns, then add whatever content blocks you’d like.' + ), supports: { align: [ 'wide', 'full' ], html: false, @@ -32,7 +34,8 @@ export const settings = { { name: 'core/paragraph', attributes: { - content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et eros eu felis.', + content: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et eros eu felis.', }, }, { @@ -55,13 +58,17 @@ export const settings = { { name: 'core/paragraph', attributes: { - content: __( 'Etiam et egestas lorem. Vivamus sagittis sit amet dolor quis lobortis. Integer sed fermentum arcu, id vulputate lacus. Etiam fermentum sem eu quam hendrerit.' ), + content: __( + 'Etiam et egestas lorem. Vivamus sagittis sit amet dolor quis lobortis. Integer sed fermentum arcu, id vulputate lacus. Etiam fermentum sem eu quam hendrerit.' + ), }, }, { name: 'core/paragraph', attributes: { - content: __( 'Nam risus massa, ullamcorper consectetur eros fermentum, porta aliquet ligula. Sed vel mauris nec enim.' ), + content: __( + 'Nam risus massa, ullamcorper consectetur eros fermentum, porta aliquet ligula. Sed vel mauris nec enim.' + ), }, }, ], diff --git a/packages/block-library/src/columns/test/utils.js b/packages/block-library/src/columns/test/utils.js index b89a63e2e01533..b33d9db5fc6ea8 100644 --- a/packages/block-library/src/columns/test/utils.js +++ b/packages/block-library/src/columns/test/utils.js @@ -97,10 +97,7 @@ describe( 'getTotalColumnsWidth', () => { } ); describe( 'implicit width', () => { - const blocks = [ - { clientId: 'a', attributes: {} }, - { clientId: 'b', attributes: {} }, - ]; + const blocks = [ { clientId: 'a', attributes: {} }, { clientId: 'b', attributes: {} } ]; it( 'returns the sum total of columns width', () => { const widths = getTotalColumnsWidth( blocks ); @@ -128,10 +125,7 @@ describe( 'getColumnWidths', () => { } ); describe( 'implicit width', () => { - const blocks = [ - { clientId: 'a', attributes: {} }, - { clientId: 'b', attributes: {} }, - ]; + const blocks = [ { clientId: 'a', attributes: {} }, { clientId: 'b', attributes: {} } ]; it( 'returns the column widths', () => { const widths = getColumnWidths( blocks ); @@ -171,10 +165,7 @@ describe( 'getRedistributedColumnWidths', () => { } ); describe( 'implicit width', () => { - const blocks = [ - { clientId: 'a', attributes: {} }, - { clientId: 'b', attributes: {} }, - ]; + const blocks = [ { clientId: 'a', attributes: {} }, { clientId: 'b', attributes: {} } ]; it( 'should equally distribute to available width', () => { const widths = getRedistributedColumnWidths( blocks, 60 ); diff --git a/packages/block-library/src/columns/utils.js b/packages/block-library/src/columns/utils.js index a6773d469c98f7..3db69d1b82cd8a 100644 --- a/packages/block-library/src/columns/utils.js +++ b/packages/block-library/src/columns/utils.js @@ -28,9 +28,7 @@ export const getColumnsTemplate = memoize( ( columns ) => { * @return {number} Value rounded to standard precision. */ export const toWidthPrecision = ( value ) => - Number.isFinite( value ) ? - parseFloat( value.toFixed( 2 ) ) : - undefined; + Number.isFinite( value ) ? parseFloat( value.toFixed( 2 ) ) : undefined; /** * Returns the considered adjacent to that of the specified `clientId` for @@ -105,14 +103,17 @@ export function getColumnWidths( blocks, totalBlockCount = blocks.length ) { * * @return {Object} Redistributed column widths. */ -export function getRedistributedColumnWidths( blocks, availableWidth, totalBlockCount = blocks.length ) { +export function getRedistributedColumnWidths( + blocks, + availableWidth, + totalBlockCount = blocks.length +) { const totalWidth = getTotalColumnsWidth( blocks, totalBlockCount ); const difference = availableWidth - totalWidth; const adjustment = difference / blocks.length; - return mapValues( - getColumnWidths( blocks, totalBlockCount ), - ( width ) => toWidthPrecision( width + adjustment ), + return mapValues( getColumnWidths( blocks, totalBlockCount ), ( width ) => + toWidthPrecision( width + adjustment ) ); } @@ -138,9 +139,11 @@ export function hasExplicitColumnWidths( blocks ) { * @return {WPBlock[]} blocks Mapped block objects. */ export function getMappedColumnWidths( blocks, widths ) { - return blocks.map( ( block ) => merge( {}, block, { - attributes: { - width: widths[ block.clientId ], - }, - } ) ); + return blocks.map( ( block ) => + merge( {}, block, { + attributes: { + width: widths[ block.clientId ], + }, + } ) + ); } diff --git a/packages/block-library/src/cover/deprecated.js b/packages/block-library/src/cover/deprecated.js index ef1a854918af14..baa82e425ef6bf 100644 --- a/packages/block-library/src/cover/deprecated.js +++ b/packages/block-library/src/cover/deprecated.js @@ -8,10 +8,7 @@ import classnames from 'classnames'; * WordPress dependencies */ import { createBlock } from '@wordpress/blocks'; -import { - RichText, - getColorClassName, -} from '@wordpress/block-editor'; +import { RichText, getColorClassName } from '@wordpress/block-editor'; import { __ } from '@wordpress/i18n'; /** @@ -84,9 +81,7 @@ const deprecated = [ url, } = attributes; const overlayColorClass = getColorClassName( 'background-color', overlayColor ); - const style = backgroundType === IMAGE_BACKGROUND_TYPE ? - backgroundImageStyles( url ) : - {}; + const style = backgroundType === IMAGE_BACKGROUND_TYPE ? backgroundImageStyles( url ) : {}; if ( ! overlayColorClass ) { style.backgroundColor = customOverlayColor; } @@ -94,25 +89,17 @@ const deprecated = [ style.backgroundPosition = `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`; } - const classes = classnames( - dimRatioToClass( dimRatio ), - overlayColorClass, - { - 'has-background-dim': dimRatio !== 0, - 'has-parallax': hasParallax, - [ `has-${ contentAlign }-content` ]: contentAlign !== 'center', - }, - ); + const classes = classnames( dimRatioToClass( dimRatio ), overlayColorClass, { + 'has-background-dim': dimRatio !== 0, + 'has-parallax': hasParallax, + [ `has-${ contentAlign }-content` ]: contentAlign !== 'center', + } ); return (
    - { VIDEO_BACKGROUND_TYPE === backgroundType && url && (