diff --git a/.eslintrc.js b/.eslintrc.js index c6404f79817f4..b5c735ca8b029 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -29,13 +29,8 @@ const developmentFiles = [ 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', }, @@ -53,23 +48,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.', }, { @@ -77,7 +78,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`', }, { @@ -97,67 +99,63 @@ 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.', }, ], }, overrides: [ { files: [ 'packages/**/*.js' ], - excludedFiles: [ - '**/*.@(android|ios|native).js', - ...developmentFiles, - ], + excludedFiles: [ '**/*.@(android|ios|native).js', ...developmentFiles ], rules: { 'import/no-extraneous-dependencies': 'error', }, }, { files: [ 'packages/**/*.js' ], - excludedFiles: [ - 'packages/block-library/src/*/save.js', - ...developmentFiles, - ], + excludedFiles: [ 'packages/block-library/src/*/save.js', ...developmentFiles ], rules: { - 'react/forbid-elements': [ 'error', { - forbid: [ - [ 'button', 'Button' ], - [ '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: [ + [ 'button', 'Button' ], + [ 'circle', 'Circle' ], + [ 'g', 'G' ], + [ 'path', 'Path' ], + [ 'polygon', 'Polygon' ], + [ 'rect', 'Rect' ], + [ 'svg', 'SVG' ], + ].map( ( [ element, componentName ] ) => { + return { + element, + message: `use cross-platform <${ componentName } /> component instead.`, + }; + } ), + }, + ], }, }, { - 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/babel.config.js b/babel.config.js index 83d78a0eeadb6..f950b6603a512 100644 --- a/babel.config.js +++ b/babel.config.js @@ -3,9 +3,6 @@ module.exports = function( api ) { return { presets: [ '@wordpress/babel-preset-default' ], - plugins: [ - 'babel-plugin-emotion', - 'babel-plugin-inline-json-import', - ], + plugins: [ 'babel-plugin-emotion', 'babel-plugin-inline-json-import' ], }; }; diff --git a/bin/api-docs/are-readmes-unstaged.js b/bin/api-docs/are-readmes-unstaged.js index 19c7eeba8d162..b3f5c36e9e9b0 100644 --- a/bin/api-docs/are-readmes-unstaged.js +++ b/bin/api-docs/are-readmes-unstaged.js @@ -12,17 +12,24 @@ const execSync = require( 'child_process' ).execSync; */ const getPackages = require( './packages' ); -const getUnstagedFiles = () => execSync( 'git diff --name-only', { encoding: 'utf8' } ).split( '\n' ).filter( ( element ) => '' !== element ); -const readmeFiles = getPackages().map( ( [ packageName ] ) => join( 'packages', packageName, 'README.md' ) ); +const getUnstagedFiles = () => + execSync( 'git diff --name-only', { encoding: 'utf8' } ) + .split( '\n' ) + .filter( ( element ) => '' !== element ); +const readmeFiles = getPackages().map( ( [ packageName ] ) => + join( 'packages', packageName, 'README.md' ) +); const unstagedReadmes = getUnstagedFiles().filter( ( element ) => readmeFiles.includes( element ) ); if ( unstagedReadmes.length > 0 ) { process.exitCode = 1; - process.stdout.write( chalk.red( - '\n', - 'Some API docs may be out of date:', - unstagedReadmes.toString(), - 'Either stage them or continue with --no-verify.', - '\n' - ) ); + process.stdout.write( + chalk.red( + '\n', + 'Some API docs may be out of date:', + unstagedReadmes.toString(), + 'Either stage them or continue with --no-verify.', + '\n' + ) + ); } diff --git a/bin/api-docs/packages.js b/bin/api-docs/packages.js index dcc583fe65d0e..71c2bed2bb14b 100644 --- a/bin/api-docs/packages.js +++ b/bin/api-docs/packages.js @@ -7,10 +7,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', diff --git a/bin/api-docs/update-readmes.js b/bin/api-docs/update-readmes.js index fd66e6cbf39d0..98a7a491619e3 100755 --- a/bin/api-docs/update-readmes.js +++ b/bin/api-docs/update-readmes.js @@ -24,7 +24,7 @@ getPackages().forEach( ( entry ) => { `--use-token "${ token }"`, '--ignore "/unstable|experimental/i"', ], - { shell: true }, + { shell: true } ); if ( status !== 0 ) { diff --git a/bin/commander.js b/bin/commander.js index 7662f65ae8c01..b532ee1d86522 100755 --- a/bin/commander.js +++ b/bin/commander.js @@ -54,13 +54,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 ) ); @@ -120,7 +126,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 ) + ); } ); } @@ -134,7 +143,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 ) + ); } ); } @@ -156,7 +168,10 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { const stableTag = previousReadmeFileContent.match( STABLE_TAG_REGEX )[ 0 ]; // Delete everything - runShellScript( 'find . -maxdepth 1 -not -name ".svn" -not -name "." -not -name ".." -exec rm -rf {} +', svnWorkingDirectoryPath ); + runShellScript( + 'find . -maxdepth 1 -not -name ".svn" -not -name "." -not -name ".." -exec rm -rf {} +', + svnWorkingDirectoryPath + ); // Update the content using the plugin ZIP const gutenbergZipPath = gitWorkingDirectoryPath + '/gutenberg.zip'; @@ -170,15 +185,24 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { ); // 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' ); } ); @@ -197,7 +221,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' ); } ); @@ -211,7 +245,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( @@ -227,7 +261,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' ); } ); @@ -240,18 +277,17 @@ async function updateThePluginStableVersion( version, abortMessage ) { */ async function runCleanLocalCloneStep( abortMessage ) { await runStep( 'Cleaning the temporary folder', abortMessage, async () => { - await Promise.all( [ - gitWorkingDirectoryPath, - svnWorkingDirectoryPath, - ].map( async ( directoryPath ) => { - if ( fs.existsSync( directoryPath ) ) { - await rimraf( directoryPath, ( err ) => { - if ( err ) { - throw err; - } - } ); - } - } ) ); + await Promise.all( + [ gitWorkingDirectoryPath, svnWorkingDirectoryPath ].map( async ( directoryPath ) => { + if ( fs.existsSync( directoryPath ) ) { + await rimraf( directoryPath, ( err ) => { + if ( err ) { + throw err; + } + } ); + } + } ) + ); } ); } @@ -274,23 +310,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 { @@ -331,15 +371,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( @@ -386,7 +440,10 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa }; 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.' ); // Update the content of the readme.txt file @@ -395,7 +452,8 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa const newReadmeContent = readmeFileContent.substr( 0, readmeFileContent.indexOf( '== Changelog ==' ) ) + '== Changelog ==\n\n' + - `To read the changelog for Gutenberg ${ version }, please navigate to the release page.` + '\n'; + `To read the changelog for Gutenberg ${ version }, please navigate to the release page.` + + '\n'; fs.writeFileSync( readmePath, newReadmeContent ); // Update the content of the changelog.txt file @@ -411,7 +469,8 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa const newChangelogContent = '== Changelog ==\n\n' + versionHeader + - changelog + '\n\n' + + changelog + + '\n\n' + changelogFileContent.substr( lastDifferentVersionMatch.index ); fs.writeFileSync( changelogPath, newChangelogContent ); @@ -451,7 +510,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 ) + ); } ); } @@ -504,7 +565,13 @@ async function runPushGitChangesStep( releaseBranch, abortMessage ) { * * @return {Object} Github release object. */ -async function runGithubReleaseStep( version, versionLabel, changelog, isPrerelease, abortMessage ) { +async function runGithubReleaseStep( + version, + versionLabel, + changelog, + isPrerelease, + abortMessage +) { let octokit; let release; await runStep( 'Creating the GitHub release', abortMessage, async () => { @@ -514,11 +581,16 @@ async function runGithubReleaseStep( version, versionLabel, changelog, isPrerele abortMessage ); - 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 { 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, @@ -594,19 +666,21 @@ async function releasePlugin( isRC = true ) { let abortMessage = 'Aborting!'; await askForConfirmationToContinue( 'Ready to go? ' ); - const { changelog } = await inquirer.prompt( [ { - type: 'editor', - name: 'changelog', - message: 'Please provide the CHANGELOG of the release (markdown)', - } ] ); + const { changelog } = await inquirer.prompt( [ + { + type: 'editor', + name: 'changelog', + message: 'Please provide the CHANGELOG of the release (markdown)', + }, + ] ); // Cloning the Git repository 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, changelog, abortMessage ); @@ -619,11 +693,23 @@ 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, changelog, isRC, abortMessage ); - abortMessage = 'Aborting! Make sure to manually cherry-pick the ' + success( commitHash ) + ' commit to the master branch.'; + const release = await runGithubReleaseStep( + version, + versionLabel, + changelog, + isRC, + abortMessage + ); + 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.'; } @@ -632,9 +718,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 ); @@ -642,10 +732,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 ); } @@ -664,13 +756,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!' ); @@ -685,7 +779,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 ); @@ -693,8 +787,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." ); } ); @@ -713,7 +807,11 @@ async function runWordPressReleaseBranchSyncStep( abortMessage ) { // Creating the release branch await simpleGit.checkout( wordpressReleaseBranch ); - console.log( '>> The local release branch ' + success( wordpressReleaseBranch ) + ' has been successfully checked out.' ); + console.log( + '>> The local release branch ' + + success( wordpressReleaseBranch ) + + ' has been successfully checked out.' + ); await askForConfirmationToContinue( `The branch is ready for sync with the latest plugin release changes applied to "${ pluginReleaseBranch }". Proceed?`, @@ -723,8 +821,14 @@ async function runWordPressReleaseBranchSyncStep( abortMessage ) { await simpleGit.raw( [ 'rm', '-r', '.' ] ); await simpleGit.raw( [ 'checkout', `origin/${ pluginReleaseBranch }`, '--', '.' ] ); - await simpleGit.commit( `Merge changes published in the Gutenberg plugin "${ pluginReleaseBranch }" branch` ); - console.log( '>> The local WordPress release branch ' + success( wordpressReleaseBranch ) + ' has been successfully synced.' ); + await simpleGit.commit( + `Merge changes published in the Gutenberg plugin "${ pluginReleaseBranch }" branch` + ); + console.log( + '>> The local WordPress release branch ' + + success( wordpressReleaseBranch ) + + ' has been successfully synced.' + ); } ); return { @@ -740,66 +844,67 @@ async function runWordPressReleaseBranchSyncStep( abortMessage ) { * @param {string} abortMessage Abort Message. */ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { - const changelogFiles = await glob( path.resolve( gitWorkingDirectoryPath, 'packages/*/CHANGELOG.md' ) ); - const processedPackages = await Promise.all( changelogFiles.map( async ( changelogFile ) => { - const fileStream = fs.createReadStream( changelogFile ); - - const lines = readline.createInterface( { - input: fileStream, - } ); - - let changesDetected = false; - let versionBump = null; - for await ( const line of lines ) { - // Detect unpublished changes first. - if ( line.startsWith( '## Master' ) ) { - changesDetected = true; - continue; - } - - // Skip all lines until unpublished changes found. - if ( ! changesDetected ) { - continue; - } - - // A previous published version detected. Stop processing. - if ( line.startsWith( '## ' ) ) { - break; - } - - // A major version bump required. Stop processing. - if ( line.startsWith( '### Breaking Change' ) ) { - versionBump = 'major'; - break; - } - - // A minor version bump required. Proceed to the next line. - if ( line.startsWith( '### New Feature' ) || line.startsWith( '### Deprecation' ) ) { - versionBump = 'minor'; - continue; - } - - // A version bump required. Found new changelog section. - if ( versionBump !== 'minor' && line.startsWith( '### ' ) ) { - versionBump = minimumVersionBump; + const changelogFiles = await glob( + path.resolve( gitWorkingDirectoryPath, 'packages/*/CHANGELOG.md' ) + ); + const processedPackages = await Promise.all( + changelogFiles.map( async ( changelogFile ) => { + const fileStream = fs.createReadStream( changelogFile ); + + const lines = readline.createInterface( { + input: fileStream, + } ); + + let changesDetected = false; + let versionBump = null; + for await ( const line of lines ) { + // Detect unpublished changes first. + if ( line.startsWith( '## Master' ) ) { + changesDetected = true; + continue; + } + + // Skip all lines until unpublished changes found. + if ( ! changesDetected ) { + continue; + } + + // A previous published version detected. Stop processing. + if ( line.startsWith( '## ' ) ) { + break; + } + + // A major version bump required. Stop processing. + if ( line.startsWith( '### Breaking Change' ) ) { + versionBump = 'major'; + break; + } + + // A minor version bump required. Proceed to the next line. + if ( line.startsWith( '### New Feature' ) || line.startsWith( '### Deprecation' ) ) { + versionBump = 'minor'; + continue; + } + + // A version bump required. Found new changelog section. + if ( versionBump !== 'minor' && line.startsWith( '### ' ) ) { + versionBump = minimumVersionBump; + } } - } - const packageName = `@wordpress/${ changelogFile.split( '/' ).reverse()[ 1 ] }`; - const { version } = readJSONFile( changelogFile.replace( 'CHANGELOG.md', 'package.json' ) ); - const nextVersion = ( versionBump !== null ) ? - semver.inc( version, versionBump ) : - null; - - return { - changelogFile, - packageName, - version, - nextVersion, - }; - } ) ); + const packageName = `@wordpress/${ changelogFile.split( '/' ).reverse()[ 1 ] }`; + const { version } = readJSONFile( changelogFile.replace( 'CHANGELOG.md', 'package.json' ) ); + const nextVersion = versionBump !== null ? semver.inc( version, versionBump ) : null; + + return { + changelogFile, + packageName, + version, + nextVersion, + }; + } ) + ); - const changelogsToUpdate = processedPackages. - filter( ( { nextVersion } ) => nextVersion ); + const changelogsToUpdate = processedPackages.filter( ( { nextVersion } ) => nextVersion ); if ( changelogsToUpdate.length === 0 ) { console.log( '>> No changes in CHANGELOG files detected.' ); @@ -810,15 +915,14 @@ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { const publishDate = new Date().toISOString().split( 'T' )[ 0 ]; await Promise.all( - changelogsToUpdate - .map( async ( { changelogFile, packageName, nextVersion, version } ) => { - const content = await fs.promises.readFile( changelogFile, 'utf8' ); - await fs.promises.writeFile( changelogFile, content.replace( - '## Master', - `## Master\n\n## ${ nextVersion } (${ publishDate })` - ) ); - console.log( ` - ${ packageName }: ${ version } -> ${ nextVersion }` ); - } ) + changelogsToUpdate.map( async ( { changelogFile, packageName, nextVersion, version } ) => { + const content = await fs.promises.readFile( changelogFile, 'utf8' ); + await fs.promises.writeFile( + changelogFile, + content.replace( '## Master', `## Master\n\n## ${ nextVersion } (${ publishDate })` ) + ); + console.log( ` - ${ packageName }: ${ version } -> ${ nextVersion }` ); + } ) ); await askForConfirmationToContinue( @@ -868,7 +972,7 @@ program console.log( chalk.bold( '💃 Time to publish WordPress packages to npm 🕺\n\n' ), 'Welcome! This tool is going to help you with prepublish to npm steps for the next stable version of WordPress packages.\n', - 'To perform a release you\'ll have to be a member of the WordPress Team on npm.\n' + "To perform a release you'll have to be a member of the WordPress Team on npm.\n" ); await prepublishPackages( 'minor' ); diff --git a/bin/generate-public-grammar.js b/bin/generate-public-grammar.js index c56ec4398a894..28f8b43859a98 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 d0f1d1c809984..622b712a97f3f 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.join( PACKAGES_DIR, 'base-styles' ) ], - 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 17006dbdc8638..8eceb6c6dbbe5 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 d76e171d46b21..3df510f1ac106 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 b307029dcd568..8518e66f3a2a8 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 b80b117daa59e..6505954143e33 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/docs/tool/are-data-files-unstaged.js b/docs/tool/are-data-files-unstaged.js index 5591de0ae6d62..14e91df6038c0 100644 --- a/docs/tool/are-data-files-unstaged.js +++ b/docs/tool/are-data-files-unstaged.js @@ -11,17 +11,25 @@ const execSync = require( 'child_process' ).execSync; */ const getPackages = require( './packages' ); -const getUnstagedFiles = () => execSync( 'git diff --name-only', { encoding: 'utf8' } ).split( '\n' ).filter( ( element ) => '' !== element ); -const readmeFiles = getPackages().map( ( [ packageName ] ) => `docs/designers-developers/developers/data/data-${ packageName.replace( '/', '-' ) }.md` ); +const getUnstagedFiles = () => + execSync( 'git diff --name-only', { encoding: 'utf8' } ) + .split( '\n' ) + .filter( ( element ) => '' !== element ); +const readmeFiles = getPackages().map( + ( [ packageName ] ) => + `docs/designers-developers/developers/data/data-${ packageName.replace( '/', '-' ) }.md` +); const unstagedReadmes = getUnstagedFiles().filter( ( element ) => readmeFiles.includes( element ) ); if ( unstagedReadmes.length > 0 ) { process.exitCode = 1; - process.stdout.write( chalk.red( - '\n', - 'Some API docs may be out of date:', - unstagedReadmes.toString(), - 'Either stage them or continue with --no-verify.', - '\n' - ) ); + process.stdout.write( + chalk.red( + '\n', + 'Some API docs may be out of date:', + unstagedReadmes.toString(), + 'Either stage them or continue with --no-verify.', + '\n' + ) + ); } diff --git a/docs/tool/index.js b/docs/tool/index.js index cd0e8223f9a6b..074162266c364 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/packages.js b/docs/tool/packages.js index 57d3d42b104b1..558a3e62c43c2 100644 --- a/docs/tool/packages.js +++ b/docs/tool/packages.js @@ -1,8 +1,11 @@ const packages = [ - [ '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', @@ -17,10 +20,19 @@ const packages = [ module.exports = function() { return packages.map( ( 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`, + }, + ]; } return entry; } ); diff --git a/docs/tool/update-data.js b/docs/tool/update-data.js index 4a5d231e3c601..63b66bbfe8fc7 100644 --- a/docs/tool/update-data.js +++ b/docs/tool/update-data.js @@ -20,12 +20,15 @@ getPackages().forEach( ( entry ) => { join( __dirname, '..', '..', 'node_modules', '.bin', 'docgen' ).replace( / /g, '\\ ' ), [ target, - `--output docs/designers-developers/developers/data/data-${ packageName.replace( '/', '-' ) }.md`, + `--output docs/designers-developers/developers/data/data-${ packageName.replace( + '/', + '-' + ) }.md`, '--to-token', `--use-token "${ token }"`, '--ignore "/unstable|experimental/i"', ], - { shell: true }, + { shell: true } ); if ( status !== 0 ) { diff --git a/package-lock.json b/package-lock.json index df74159a429cc..81bc0e14a35a6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10514,6 +10514,7 @@ "eslint-plugin-jest": "^22.15.1", "eslint-plugin-jsdoc": "^15.8.0", "eslint-plugin-jsx-a11y": "^6.2.3", + "eslint-plugin-prettier": "^3.1.2", "eslint-plugin-react": "^7.14.3", "eslint-plugin-react-hooks": "^1.6.1", "globals": "^12.0.0", @@ -18025,6 +18026,15 @@ } } }, + "eslint-plugin-prettier": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.1.2.tgz", + "integrity": "sha512-GlolCC9y3XZfv3RQfwGew7NnuFDKsfI4lbvRK+PIIo23SFH+LemGs4cKwzAaRa+Mdb+lQO/STaIayno8T5sJJA==", + "dev": true, + "requires": { + "prettier-linter-helpers": "^1.0.0" + } + }, "eslint-plugin-react": { "version": "7.14.3", "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz", @@ -18796,6 +18806,12 @@ "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", "dev": true }, + "fast-diff": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", + "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "dev": true + }, "fast-glob": { "version": "2.2.7", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-2.2.7.tgz", @@ -19486,7 +19502,7 @@ }, "node-pre-gyp": { "version": "0.12.0", - "resolved": "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz", + "resolved": false, "integrity": "sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A==", "dev": true, "optional": true, @@ -19505,7 +19521,7 @@ }, "nopt": { "version": "4.0.1", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.1.tgz", + "resolved": false, "integrity": "sha1-0NRoWv1UFRk8jHUFYC0NF81kR00=", "dev": true, "optional": true, @@ -27278,7 +27294,7 @@ "dependencies": { "clone-deep": { "version": "0.2.4", - "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-0.2.4.tgz", + "resolved": "http://registry.npmjs.org/clone-deep/-/clone-deep-0.2.4.tgz", "integrity": "sha1-TnPdCen7lxzDhnDF3O2cGJZIHMY=", "dev": true, "requires": { @@ -27312,7 +27328,7 @@ "dependencies": { "kind-of": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-2.0.1.tgz", + "resolved": "http://registry.npmjs.org/kind-of/-/kind-of-2.0.1.tgz", "integrity": "sha1-AY7HpM5+OobLkUG+UZ0kyPqpgbU=", "dev": true, "requires": { @@ -31478,6 +31494,15 @@ "integrity": "sha512-mqAC2r1NDmRjG+z3KCJ/i61tycKlmADIjxnDhQab+KBxSAGbF/W7/zwB2guy/ypIeKrrftNsIYkNZZQKf3vJcg==", "dev": true }, + "prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "requires": { + "fast-diff": "^1.1.2" + } + }, "pretty-error": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz", diff --git a/package.json b/package.json index 2124fac1debc7..38f2036891596 100644 --- a/package.json +++ b/package.json @@ -241,6 +241,7 @@ "wp-scripts lint-style" ], "*.js": [ + "wp-scripts format-js", "wp-scripts lint-js" ], "{docs/{toc.json,tool/*.js},packages/{*/README.md,*/src/{actions,selectors}.js,components/src/*/**/README.md}}": [ diff --git a/packages/a11y/src/addContainer.js b/packages/a11y/src/addContainer.js index 3db5637d13942..edd733a6626a6 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 b972687dbafce..4e5e9841118b1 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 e2677bbf6a9b3..31c1a57e261ab 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 46dd6e279fa3b..ba9a39633d84e 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 1dccbbd5012a0..e41c5640cc8c8 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 ce64106bf903c..9435b1d861661 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 8135ca3e32066..7ad35afa99b29 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 1f768a78ad215..2fcd95118e45b 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 a39a315c92f90..8a3a34715a631 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 190795bd8a98c..0e9c62a93adc4 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 535adb8d88a76..a25ec7992ff94 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -72,33 +72,32 @@ 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 - // Return early if fetch errors. If fetch error, there is most likely no - // network connection. Unfortunately fetch just throws a TypeError and - // the message might depend on the browser. - .then( - ( value ) => - Promise.resolve( value ) - .then( checkStatus ) - .catch( ( response ) => parseAndThrowError( response, parse ) ) - .then( ( response ) => parseResponseAndNormalizeError( response, parse ) ), - () => { - throw { - code: 'fetch_error', - message: __( 'You are probably offline.' ), - }; - } - ); + return ( + responsePromise + // Return early if fetch errors. If fetch error, there is most likely no + // network connection. Unfortunately fetch just throws a TypeError and + // the message might depend on the browser. + .then( + ( value ) => + Promise.resolve( value ) + .then( checkStatus ) + .catch( ( response ) => parseAndThrowError( response, parse ) ) + .then( ( response ) => parseResponseAndNormalizeError( response, parse ) ), + () => { + throw { + code: 'fetch_error', + message: __( 'You are probably offline.' ), + }; + } + ) + ); }; let fetchHandler = defaultFetchHandler; @@ -135,7 +134,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/middlewares/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/fetch-all-middleware.js index 5bc17b5413d32..f0ef36977d6c2 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 d7771bf6f9b1c..87304712e4b21 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 6772aaf3ded73..4d617cd0683c5 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 c6ee6c67b4afb..ef24a3dea9312 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 bb02e3dfe64af..5a141c8141304 100644 --- a/packages/api-fetch/src/middlewares/preloading.js +++ b/packages/api-fetch/src/middlewares/preloading.js @@ -16,23 +16,27 @@ export function getStablePath( path ) { } // '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( '&' ) + ); } function createPreloadingMiddleware( preloadedData ) { @@ -49,11 +53,7 @@ function createPreloadingMiddleware( preloadedData ) { if ( parse && 'GET' === method && cache[ path ] ) { return Promise.resolve( cache[ path ].body ); - } else if ( - 'OPTIONS' === method && - cache[ method ] && - cache[ method ][ path ] - ) { + } else if ( 'OPTIONS' === method && cache[ method ] && cache[ method ][ path ] ) { return Promise.resolve( cache[ method ][ path ] ); } } 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 b73eeba15e14b..f0b2c035a646a 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 06a63c8d5f149..42c00696e1849 100644 --- a/packages/api-fetch/src/middlewares/test/preloading.js +++ b/packages/api-fetch/src/middlewares/test/preloading.js @@ -73,10 +73,7 @@ describe( 'Preloading Middleware', () => { expect( value ).toEqual( body ); } ); - describe.each( [ - [ 'GET' ], - [ 'OPTIONS' ], - ] )( '%s', ( method ) => { + describe.each( [ [ 'GET' ], [ 'OPTIONS' ] ] )( '%s', ( method ) => { describe.each( [ [ 'all empty', {} ], [ 'method empty', { [ method ]: {} } ], diff --git a/packages/api-fetch/src/test/index.js b/packages/api-fetch/src/test/index.js index 001483b8b2361..05c327da6ee6f 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( { @@ -162,9 +170,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 ); @@ -172,9 +182,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( { @@ -184,9 +196,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 bb7b79ce2f825..518a7fd5e66f8 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 1225d5c6637d8..32512f62094ec 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 8fc73f4e03965..02bffeab830dd 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 ad0cde941aecb..6764c1ff82294 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 52ae1dcc5b913..32554aa065693 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 c6ec1e3c9a71a..5a9bc8133da81 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'; @@ -68,10 +67,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 7604e3956b6d2..110340e13639e 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 577c3cb15e0dc..9b78e608dae7b 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 942c4fda0c7c7..4e765c0ab125d 100644 --- a/packages/block-directory/src/components/downloadable-block-header/index.js +++ b/packages/block-directory/src/components/downloadable-block-header/index.js @@ -13,17 +13,17 @@ import BlockRatings from '../block-ratings'; function DownloadableBlockHeader( { icon, title, rating, ratingCount, onClick } ) { return (
    - { - icon.match( /\.(jpeg|jpg|gif|png)(?:\?.*)?$/ ) !== null ? - // translators: %s: Name of the plugin e.g: "Akismet". - { : - - - - } + { icon.match( /\.(jpeg|jpg|gif|png)(?:\?.*)?$/ ) !== null ? ( + // translators: %s: Name of the plugin e.g: "Akismet". + { + ) : ( + + + + ) }
    - + { title } diff --git a/packages/block-directory/src/components/downloadable-block-header/test/fixtures/index.js b/packages/block-directory/src/components/downloadable-block-header/test/fixtures/index.js index 469105aea680f..1ee6046052ffb 100644 --- a/packages/block-directory/src/components/downloadable-block-header/test/fixtures/index.js +++ b/packages/block-directory/src/components/downloadable-block-header/test/fixtures/index.js @@ -17,4 +17,7 @@ const pluginBase = { }; export const pluginWithIcon = { ...pluginBase, icon: 'block-default' }; -export const pluginWithImg = { ...pluginBase, icon: 'https://ps.w.org/listicles/assets/icon-128x128.png' }; +export const pluginWithImg = { + ...pluginBase, + icon: 'https://ps.w.org/listicles/assets/icon-128x128.png', +}; 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 5119d1316267a..54224e34a66c9 100644 --- a/packages/block-directory/src/components/downloadable-block-info/index.js +++ b/packages/block-directory/src/components/downloadable-block-info/index.js @@ -8,19 +8,19 @@ 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 + ) }
    - { - // translators: %s: Humanized date of last update e.g: "2 months ago". - sprintf( __( 'Updated %s' ), humanizedUpdated ) - } + { // translators: %s: Humanized date of last update e.g: "2 months ago". + sprintf( __( 'Updated %s' ), 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 c5bd8b8f0244e..3eb69eba7d2d7 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 315403267a56c..36b952f3ecc5d 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 0936ee3eea6f2..f49e96654acc2 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/plugins/inserter-menu-downloadable-blocks-panel/index.js b/packages/block-directory/src/plugins/inserter-menu-downloadable-blocks-panel/index.js index 9fb2cc8105dc0..b91a3692b6d29 100644 --- a/packages/block-directory/src/plugins/inserter-menu-downloadable-blocks-panel/index.js +++ b/packages/block-directory/src/plugins/inserter-menu-downloadable-blocks-panel/index.js @@ -21,26 +21,24 @@ function InserterMenuDownloadableBlocksPanel() { return ( <__experimentalInserterMenuExtension> - { - ( { onSelect, onHover, filterValue, hasItems } ) => { - if ( hasItems || ! filterValue ) { - return null; - } - - if ( debouncedFilterValue !== filterValue ) { - debouncedSetFilterValue( filterValue ); - } - - return ( - - ); + { ( { onSelect, onHover, filterValue, hasItems } ) => { + if ( hasItems || ! filterValue ) { + return null; } - } + + if ( debouncedFilterValue !== filterValue ) { + debouncedSetFilterValue( filterValue ); + } + + return ( + + ); + } } ); } diff --git a/packages/block-directory/src/store/controls.js b/packages/block-directory/src/store/controls.js index fbd187b7bbf41..5f38d65759c5c 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 a8644e8fc1a60..d6387476f5466 100644 --- a/packages/block-directory/src/store/reducer.js +++ b/packages/block-directory/src/store/reducer.js @@ -11,18 +11,21 @@ import { combineReducers } from '@wordpress/data'; * * @return {Object} Updated state. */ -export const downloadableBlocks = ( state = { - results: {}, - filterValue: undefined, - isRequestingDownloadableBlocks: true, -}, action ) => { +export const downloadableBlocks = ( + state = { + results: {}, + filterValue: undefined, + isRequestingDownloadableBlocks: true, + }, + 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, { @@ -42,19 +45,24 @@ export const downloadableBlocks = ( state = { * * @return {Object} Updated state. */ -export const blockManagement = ( state = { - installedBlockTypes: [], -}, action ) => { +export const blockManagement = ( + state = { + installedBlockTypes: [], + }, + action +) => { switch ( action.type ) { - 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 885257ea72ee8..a1b0d7dfd05be 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-directory/src/store/test/reducer.js b/packages/block-directory/src/store/test/reducer.js index f221a3bfa023d..b2eaa6b667e0a 100644 --- a/packages/block-directory/src/store/test/reducer.js +++ b/packages/block-directory/src/store/test/reducer.js @@ -6,11 +6,7 @@ import deepFreeze from 'deep-freeze'; /** * Internal dependencies */ -import { - downloadableBlocks, - blockManagement, - hasPermission, -} from '../reducer'; +import { downloadableBlocks, blockManagement, hasPermission } from '../reducer'; import { installedItem, downloadableBlock } from './fixtures'; describe( 'state', () => { @@ -36,7 +32,7 @@ describe( 'state', () => { expect( state.isRequestingDownloadableBlocks ).toBe( false ); } ); - it( 'should set user\'s search term and save results', () => { + it( "should set user's search term and save results", () => { const state = downloadableBlocks( undefined, { type: 'RECEIVE_DOWNLOADABLE_BLOCKS', filterValue: downloadableBlock.title, diff --git a/packages/block-directory/src/store/test/selectors.js b/packages/block-directory/src/store/test/selectors.js index b907328e3a420..11a019d011f7e 100644 --- a/packages/block-directory/src/store/test/selectors.js +++ b/packages/block-directory/src/store/test/selectors.js @@ -1,9 +1,7 @@ /** * Internal dependencies */ -import { - getInstalledBlockTypes, -} from '../selectors'; +import { getInstalledBlockTypes } from '../selectors'; describe( 'selectors', () => { describe( 'getInstalledBlockTypes', () => { diff --git a/packages/block-editor/src/components/alignment-toolbar/index.js b/packages/block-editor/src/components/alignment-toolbar/index.js index 40dfa28c0ce88..96c8f33f0faa0 100644 --- a/packages/block-editor/src/components/alignment-toolbar/index.js +++ b/packages/block-editor/src/components/alignment-toolbar/index.js @@ -50,7 +50,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 03662cfdabe81..bdf3cd0f7c8d4 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 c95279a104db2..2deea11805450 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 afc69d7e5273a..058e189c0a440 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,10 +67,7 @@ export default compose( [ }; } ), withDispatch( ( dispatch, props, { select } ) => { - const { - clientIds, - blocks, - } = props; + const { clientIds, blocks } = props; const { removeBlocks, @@ -101,9 +95,7 @@ export default compose( [ return; } - const { - getGroupingBlockName, - } = select( 'core/blocks' ); + const { getGroupingBlockName } = select( 'core/blocks' ); const groupingBlockName = getGroupingBlockName(); @@ -113,10 +105,7 @@ export default compose( [ if ( ! newBlocks ) { return; } - replaceBlocks( - clientIds, - newBlocks - ); + replaceBlocks( clientIds, newBlocks ); }, onUngroup() { @@ -130,10 +119,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 b3ac1df33142c..eb677bb0a2a5e 100644 --- a/packages/block-editor/src/components/block-alignment-toolbar/index.js +++ b/packages/block-editor/src/components/block-alignment-toolbar/index.js @@ -45,7 +45,13 @@ 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 ); } @@ -62,16 +68,14 @@ 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, - role: isCollapsed ? 'menuitemradio' : undefined, - onClick: applyOrUnset( control ), - }; - } ) - } + controls={ enabledControls.map( ( control ) => { + return { + ...BLOCK_ALIGNMENTS_CONTROLS[ control ], + isActive: value === control, + role: isCollapsed ? 'menuitemradio' : undefined, + onClick: applyOrUnset( control ), + }; + } ) } /> ); } @@ -88,5 +92,5 @@ export default compose( return { wideControlsEnabled: settings.alignWide, }; - } ), + } ) )( BlockAlignmentToolbar ); diff --git a/packages/block-editor/src/components/block-breadcrumb/index.js b/packages/block-editor/src/components/block-breadcrumb/index.js index adc96ba4eb2d5..fb2072938dc9d 100644 --- a/packages/block-editor/src/components/block-breadcrumb/index.js +++ b/packages/block-editor/src/components/block-breadcrumb/index.js @@ -18,11 +18,9 @@ import BlockTitle from '../block-title'; const BlockBreadcrumb = function() { const { selectBlock, clearSelectedBlock } = useDispatch( 'core/block-editor' ); const { clientId, parents, hasSelection } = useSelect( ( select ) => { - const { - getSelectionStart, - getSelectedBlockClientId, - getBlockParents, - } = select( 'core/block-editor' ); + const { getSelectionStart, getSelectedBlockClientId, getBlockParents } = select( + 'core/block-editor' + ); const selectedBlockClientId = getSelectedBlockClientId(); return { parents: getBlockParents( selectedBlockClientId ), @@ -37,7 +35,11 @@ const BlockBreadcrumb = function() { */ /* eslint-disable jsx-a11y/no-redundant-roles */ return ( -
      +
      • ( - + { - const { - getBlockAttributes, - getSelectedBlockClientId, - } = select( 'core/block-editor' ); + const { getBlockAttributes, getSelectedBlockClientId } = select( 'core/block-editor' ); const { caption } = getBlockAttributes( clientId ); const isBlockSelected = getSelectedBlockClientId() === clientId; 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 ed5e030c7fd4f..861370f6e3edf 100644 --- a/packages/block-editor/src/components/block-compare/block-view.js +++ b/packages/block-editor/src/components/block-compare/block-view.js @@ -9,9 +9,7 @@ const BlockView = ( { title, rawContent, renderedContent, action, actionText, cl

        { title }

        -
        - { rawContent } -
        +
        { rawContent }
        { renderedContent } @@ -19,7 +17,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 18638255508ec..f1e4d21fc992d 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 { '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 657f326f44ce9..755722983351b 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 b5851d57a51fb..f361aad805414 100644 --- a/packages/block-editor/src/components/block-draggable/index.js +++ b/packages/block-editor/src/components/block-draggable/index.js @@ -11,26 +11,24 @@ import { useSelect, useDispatch } from '@wordpress/data'; import { useEffect, useRef } from '@wordpress/element'; const BlockDraggable = ( { children, clientIds } ) => { - const { - srcRootClientId, - index, - isDraggable, - } = useSelect( ( select ) => { - const { - getBlockIndex, - getBlockRootClientId, - getTemplateLock, - } = select( 'core/block-editor' ); - const normalizedClientIds = castArray( clientIds ); - const rootClientId = normalizedClientIds.length === 1 ? getBlockRootClientId( normalizedClientIds[ 0 ] ) : null; - const templateLock = rootClientId ? getTemplateLock( rootClientId ) : null; + const { srcRootClientId, index, isDraggable } = useSelect( + ( select ) => { + const { getBlockIndex, getBlockRootClientId, getTemplateLock } = select( + 'core/block-editor' + ); + const normalizedClientIds = castArray( clientIds ); + const rootClientId = + normalizedClientIds.length === 1 ? getBlockRootClientId( normalizedClientIds[ 0 ] ) : null; + const templateLock = rootClientId ? getTemplateLock( rootClientId ) : null; - return { - index: getBlockIndex( normalizedClientIds[ 0 ], rootClientId ), - srcRootClientId: rootClientId, - isDraggable: normalizedClientIds.length === 1 && 'all' !== templateLock, - }; - }, [ clientIds ] ); + return { + index: getBlockIndex( normalizedClientIds[ 0 ], rootClientId ), + srcRootClientId: rootClientId, + isDraggable: normalizedClientIds.length === 1 && 'all' !== templateLock, + }; + }, + [ clientIds ] + ); const isDragging = useRef( false ); const { startDraggingBlocks, stopDraggingBlocks } = useDispatch( 'core/block-editor' ); @@ -69,14 +67,12 @@ const BlockDraggable = ( { children, clientIds } ) => { isDragging.current = false; } } > - { - ( { 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 d78cb7521a4bc..2501f32f38943 100644 --- a/packages/block-editor/src/components/block-drop-zone/index.js +++ b/packages/block-editor/src/components/block-drop-zone/index.js @@ -2,11 +2,7 @@ * WordPress dependencies */ import { __unstableUseDropZone as useDropZone } from '@wordpress/components'; -import { - pasteHandler, - getBlockTransforms, - findTransform, -} from '@wordpress/blocks'; +import { pasteHandler, getBlockTransforms, findTransform } from '@wordpress/blocks'; import { useDispatch, useSelect } from '@wordpress/data'; import { useEffect, useState, useCallback } from '@wordpress/element'; @@ -35,12 +31,9 @@ export default function useBlockDropZone( { element, rootClientId } ) { const [ clientId, setClientId ] = useState( null ); function selector( select ) { - const { - getBlockIndex, - getClientIdsOfDescendants, - getSettings, - getTemplateLock, - } = select( 'core/block-editor' ); + const { getBlockIndex, getClientIdsOfDescendants, getSettings, getTemplateLock } = select( + 'core/block-editor' + ); return { getBlockIndex, blockIndex: getBlockIndex( clientId, rootClientId ), @@ -57,61 +50,81 @@ export default function useBlockDropZone( { element, rootClientId } ) { hasUploadPermissions, isLockedAll, } = useSelect( selector, [ rootClientId, clientId ] ); - const { - insertBlocks, - updateBlockAttributes, - moveBlockToPosition, - } = useDispatch( 'core/block-editor' ); - - const onFilesDrop = useCallback( ( files ) => { - if ( ! hasUploadPermissions ) { - return; - } + const { insertBlocks, updateBlockAttributes, moveBlockToPosition } = useDispatch( + 'core/block-editor' + ); - const transformation = findTransform( - getBlockTransforms( 'from' ), - ( transform ) => transform.type === 'files' && transform.isMatch( files ) - ); - - if ( transformation ) { - const blocks = transformation.transform( files, updateBlockAttributes ); - insertBlocks( blocks, blockIndex, rootClientId ); - } - }, [ hasUploadPermissions, updateBlockAttributes, insertBlocks, blockIndex, rootClientId ] ); - - const onHTMLDrop = useCallback( ( HTML ) => { - const blocks = pasteHandler( { HTML, mode: 'BLOCKS' } ); + const onFilesDrop = useCallback( + ( files ) => { + if ( ! hasUploadPermissions ) { + return; + } - if ( blocks.length ) { - insertBlocks( blocks, blockIndex, rootClientId ); - } - }, [ insertBlocks, blockIndex, rootClientId ] ); + const transformation = findTransform( + getBlockTransforms( 'from' ), + ( transform ) => transform.type === 'files' && transform.isMatch( files ) + ); - const onDrop = useCallback( ( event ) => { - const { srcRootClientId, srcClientId, srcIndex, type } = parseDropEvent( event ); + if ( transformation ) { + const blocks = transformation.transform( files, updateBlockAttributes ); + insertBlocks( blocks, blockIndex, rootClientId ); + } + }, + [ hasUploadPermissions, updateBlockAttributes, insertBlocks, blockIndex, rootClientId ] + ); - 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 ); - }; - const isSameBlock = ( src, dst ) => src === dst; - const isSrcBlockAnAncestorOfDstBlock = ( src, dst ) => getClientIdsOfDescendants( [ src ] ).some( ( id ) => id === dst ); + const onHTMLDrop = useCallback( + ( HTML ) => { + const blocks = pasteHandler( { HTML, mode: 'BLOCKS' } ); - if ( ! isBlockDropType( type ) || - isSameBlock( srcClientId, clientId ) || - isSrcBlockAnAncestorOfDstBlock( srcClientId, clientId || rootClientId ) ) { - return; - } + if ( blocks.length ) { + insertBlocks( blocks, blockIndex, rootClientId ); + } + }, + [ insertBlocks, blockIndex, rootClientId ] + ); + + const onDrop = useCallback( + ( event ) => { + 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 ); + }; + const isSameBlock = ( src, dst ) => src === dst; + const isSrcBlockAnAncestorOfDstBlock = ( src, dst ) => + getClientIdsOfDescendants( [ src ] ).some( ( id ) => id === dst ); + + if ( + ! isBlockDropType( type ) || + isSameBlock( srcClientId, clientId ) || + isSrcBlockAnAncestorOfDstBlock( srcClientId, clientId || rootClientId ) + ) { + return; + } - const dstIndex = clientId ? getBlockIndex( clientId, rootClientId ) : undefined; - const positionIndex = blockIndex; - // 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, rootClientId ) ? positionIndex - 1 : positionIndex; - moveBlockToPosition( srcClientId, srcRootClientId, rootClientId, insertIndex ); - }, [ getClientIdsOfDescendants, getBlockIndex, clientId, blockIndex, moveBlockToPosition, rootClientId ] ); + const dstIndex = clientId ? getBlockIndex( clientId, rootClientId ) : undefined; + const positionIndex = blockIndex; + // 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, rootClientId ) + ? positionIndex - 1 + : positionIndex; + moveBlockToPosition( srcClientId, srcRootClientId, rootClientId, insertIndex ); + }, + [ + getClientIdsOfDescendants, + getBlockIndex, + clientId, + blockIndex, + moveBlockToPosition, + rootClientId, + ] + ); const { position } = useDropZone( { element, @@ -129,7 +142,7 @@ export default function useBlockDropZone( { element, rootClientId } ) { const offset = y - rect.top; const target = Array.from( element.current.children ).find( ( blockEl ) => { - return blockEl.offsetTop + ( blockEl.offsetHeight / 2 ) > offset; + return blockEl.offsetTop + blockEl.offsetHeight / 2 > offset; } ); if ( ! target ) { diff --git a/packages/block-editor/src/components/block-edit/context.js b/packages/block-editor/src/components/block-edit/context.js index 08f2ac9f1dd6b..0a619f91b12cc 100644 --- a/packages/block-editor/src/components/block-edit/context.js +++ b/packages/block-editor/src/components/block-edit/context.js @@ -39,18 +39,16 @@ export function useBlockEditContext() { * * @return {WPComponent} 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 @@ -62,10 +60,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 9094435159485..3172916c870a9 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 8a4d0ad8350e9..2577ad3e0733e 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 403a5cd87898e..9953cebf01cc8 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 d09ce608cc14b..0a24f55ce2471 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-icon/index.js b/packages/block-editor/src/components/block-icon/index.js index 508d48a2211c1..b20642c6dc9ae 100644 --- a/packages/block-editor/src/components/block-icon/index.js +++ b/packages/block-editor/src/components/block-icon/index.js @@ -12,24 +12,26 @@ 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 4dddda5ecce8f..5708c21d86318 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 8c74330ad34d4..36b0144530977 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 8f58075cfa04c..7aa3cdea1f088 100644 --- a/packages/block-editor/src/components/block-inspector/index.js +++ b/packages/block-editor/src/components/block-inspector/index.js @@ -3,10 +3,7 @@ */ import { __ } from '@wordpress/i18n'; import { getBlockType, getUnregisteredTypeHandlerName } from '@wordpress/blocks'; -import { - PanelBody, - __experimentalSlotFillConsumer, -} from '@wordpress/components'; +import { PanelBody, __experimentalSlotFillConsumer } from '@wordpress/components'; import { withSelect } from '@wordpress/data'; /** @@ -53,13 +50,8 @@ const BlockInspector = ( { { hasBlockStyles && (
        - - + +
        @@ -85,20 +77,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 6515eea231b4e..d4309fac24d37 100644 --- a/packages/block-editor/src/components/block-list-appender/index.js +++ b/packages/block-editor/src/components/block-list-appender/index.js @@ -49,10 +49,7 @@ function BlockListAppender( { // Fallback in the case no renderAppender has been provided and the // default block can't be inserted. appender = ( - + ); } @@ -78,11 +75,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-appender/index.native.js b/packages/block-editor/src/components/block-list-appender/index.native.js index 2a77fe797d132..f5c9d3bf75e92 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 @@ -28,9 +28,7 @@ function BlockListAppender( { } if ( CustomAppender ) { - return ( - - ); + return ; } if ( canInsertDefaultBlock ) { @@ -49,11 +47,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-footer/index.js b/packages/block-editor/src/components/block-list-footer/index.js index 3beba29d90b0a..5cbfb49f934ac 100644 --- a/packages/block-editor/src/components/block-list-footer/index.js +++ b/packages/block-editor/src/components/block-list-footer/index.js @@ -3,7 +3,9 @@ */ import { createSlotFill } from '@wordpress/components'; -const { Fill: __experimentalBlockListFooter, Slot } = createSlotFill( '__experimentalBlockListFooter' ); +const { Fill: __experimentalBlockListFooter, Slot } = createSlotFill( + '__experimentalBlockListFooter' +); __experimentalBlockListFooter.Slot = Slot; 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 f9a83feaafb3c..c2ea261387c3a 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 */ @@ -9,13 +8,22 @@ import TextareaAutosize from 'react-autosize-textarea'; */ import { useEffect, useState } from '@wordpress/element'; import { useSelect, useDispatch } from '@wordpress/data'; -import { getBlockAttributes, getBlockContent, getBlockType, isValidBlockContent, getSaveContent } from '@wordpress/blocks'; +import { + getBlockAttributes, + getBlockContent, + getBlockType, + isValidBlockContent, + getSaveContent, +} from '@wordpress/blocks'; function BlockHTML( { clientId } ) { const [ html, setHtml ] = useState( '' ); - const { block } = useSelect( ( select ) => ( { - block: select( 'core/block-editor' ).getBlock( clientId ), - } ), [ clientId ] ); + const { block } = useSelect( + ( select ) => ( { + block: select( 'core/block-editor' ).getBlock( clientId ), + } ), + [ clientId ] + ); const { updateBlock } = useDispatch( 'core/block-editor' ); const onChange = () => { const blockType = getBlockType( block.name ); 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 0a541263bbb36..8a91289eddeaf 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 = [ @@ -48,11 +50,14 @@ export class BlockInvalidWarning extends Component { <> - { - // translators: Button to fix block content - _x( 'Resolve', 'imperative verb' ) - } + , hasHTMLBlock && (
    @@ -197,11 +196,7 @@ function BlockPopover( { ) } { showEmptyBlockSideInserter && (
    - +
    ) } @@ -231,11 +226,16 @@ function wrapperSelector( select ) { const { __experimentalMoverDirection } = getBlockListSettings( rootClientId ) || {}; // Get Block List Settings for all ancestors of the current Block clientId - const ancestorBlockListSettings = __experimentalGetBlockListSettingsForBlocks( blockParentsClientIds ); + const ancestorBlockListSettings = __experimentalGetBlockListSettingsForBlocks( + blockParentsClientIds + ); // Find the index of the first Block with the `captureDescendantsToolbars` prop defined // This will be the top most ancestor because getBlockParents() returns tree from top -> bottom - const topmostAncestorWithCaptureDescendantsToolbarsIndex = findIndex( ancestorBlockListSettings, [ '__experimentalCaptureToolbars', true ] ); + const topmostAncestorWithCaptureDescendantsToolbarsIndex = findIndex( ancestorBlockListSettings, [ + '__experimentalCaptureToolbars', + true, + ] ); let capturingClientId; diff --git a/packages/block-editor/src/components/block-list/block.js b/packages/block-editor/src/components/block-list/block.js index a0ebc634abb52..ff038162acecb 100644 --- a/packages/block-editor/src/components/block-list/block.js +++ b/packages/block-editor/src/components/block-list/block.js @@ -9,11 +9,7 @@ import { animated } from 'react-spring/web.cjs'; * WordPress dependencies */ import { useRef, useEffect, useLayoutEffect, useState, useContext } from '@wordpress/element'; -import { - focus, - isTextField, - placeCaretAtHorizontalEdge, -} from '@wordpress/dom'; +import { focus, isTextField, placeCaretAtHorizontalEdge } from '@wordpress/dom'; import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes'; import { getBlockType, @@ -24,11 +20,7 @@ import { } from '@wordpress/blocks'; import { withFilters } from '@wordpress/components'; import { __, sprintf } from '@wordpress/i18n'; -import { - withDispatch, - withSelect, - useSelect, -} from '@wordpress/data'; +import { withDispatch, withSelect, useSelect } from '@wordpress/data'; import { withViewportMatch } from '@wordpress/viewport'; import { compose, pure, ifCondition } from '@wordpress/compose'; @@ -157,14 +149,16 @@ function BlockListBlock( { } isMounting.current = false; - }, [ - isSelected, - isMultiSelecting, - isNavigationMode, - ] ); + }, [ isSelected, isMultiSelecting, isNavigationMode ] ); // Block Reordering animation - const animationStyle = useMovingAnimation( wrapper, isSelected || isPartOfMultiSelection, isSelected || isFirstMultiSelected, enableAnimation, animateOnChange ); + const animationStyle = useMovingAnimation( + wrapper, + isSelected || isPartOfMultiSelection, + isSelected || isFirstMultiSelected, + enableAnimation, + animateOnChange + ); // Other event handlers @@ -214,12 +208,10 @@ function BlockListBlock( { // If the block is selected and we're typing the block should not appear. // Empty paragraph blocks should always show up as unselected. - const showEmptyBlockSideInserter = ! isNavigationMode && isSelected && isEmptyDefaultBlock && isValid; + const showEmptyBlockSideInserter = + ! isNavigationMode && isSelected && isEmptyDefaultBlock && isValid; const shouldAppearSelected = - ! isFocusMode && - ! showEmptyBlockSideInserter && - isSelected && - ! isTypingWithinBlock; + ! isFocusMode && ! showEmptyBlockSideInserter && isSelected && ! isTypingWithinBlock; const isDragging = isDraggingBlocks && ( isSelected || isPartOfMultiSelection ); @@ -301,27 +293,20 @@ function BlockListBlock( { role="group" { ...wrapperProps } style={ - wrapperProps && wrapperProps.style ? - { - ...wrapperProps.style, - ...animationStyle, - } : - animationStyle + wrapperProps && wrapperProps.style + ? { + ...wrapperProps.style, + ...animationStyle, + } + : animationStyle } > { isValid && blockEdit } - { isValid && mode === 'html' && ( - - ) } + { isValid && mode === 'html' && } { ! isValid && [ - , -
    - { getSaveElement( blockType, attributes ) } -
    , + , +
    { getSaveElement( blockType, attributes ) }
    , ] }
    { !! hasError && } @@ -329,74 +314,69 @@ function BlockListBlock( { ); } -const applyWithSelect = withSelect( - ( select, { clientId, rootClientId, isLargeViewport } ) => { - const { - isBlockSelected, - isAncestorMultiSelected, - isBlockMultiSelected, - isFirstMultiSelectedBlock, - getLastMultiSelectedBlockClientId, - isTyping, - getBlockMode, - isSelectionEnabled, - getSelectedBlocksInitialCaretPosition, - getSettings, - hasSelectedInnerBlock, - getTemplateLock, - __unstableGetBlockWithoutInnerBlocks, - isNavigationMode, - } = select( 'core/block-editor' ); - - const block = __unstableGetBlockWithoutInnerBlocks( clientId ); - const isSelected = isBlockSelected( clientId ); - const { focusMode, isRTL } = getSettings(); - const templateLock = getTemplateLock( rootClientId ); - const checkDeep = true; - - // "ancestor" is the more appropriate label due to "deep" check - const isAncestorOfSelectedBlock = hasSelectedInnerBlock( clientId, checkDeep ); - - // The fallback to `{}` is a temporary fix. - // This function should never be called when a block is not present in the state. - // It happens now because the order in withSelect rendering is not correct. - const { name, attributes, isValid } = block || {}; +const applyWithSelect = withSelect( ( select, { clientId, rootClientId, isLargeViewport } ) => { + const { + isBlockSelected, + isAncestorMultiSelected, + isBlockMultiSelected, + isFirstMultiSelectedBlock, + getLastMultiSelectedBlockClientId, + isTyping, + getBlockMode, + isSelectionEnabled, + getSelectedBlocksInitialCaretPosition, + getSettings, + hasSelectedInnerBlock, + getTemplateLock, + __unstableGetBlockWithoutInnerBlocks, + isNavigationMode, + } = select( 'core/block-editor' ); - return { - isMultiSelected: isBlockMultiSelected( clientId ), - isPartOfMultiSelection: - isBlockMultiSelected( clientId ) || isAncestorMultiSelected( clientId ), - isFirstMultiSelected: isFirstMultiSelectedBlock( clientId ), - isLastMultiSelected: getLastMultiSelectedBlockClientId() === clientId, - - // We only care about this prop when the block is selected - // Thus to avoid unnecessary rerenders we avoid updating the prop if the block is not selected. - isTypingWithinBlock: - ( isSelected || isAncestorOfSelectedBlock ) && isTyping(), - - mode: getBlockMode( clientId ), - isSelectionEnabled: isSelectionEnabled(), - initialPosition: isSelected ? getSelectedBlocksInitialCaretPosition() : null, - isEmptyDefaultBlock: - name && isUnmodifiedDefaultBlock( { name, attributes } ), - isLocked: !! templateLock, - isFocusMode: focusMode && isLargeViewport, - isNavigationMode: isNavigationMode(), - isRTL, - - // Users of the editor.BlockListBlock filter used to be able to access the block prop - // Ideally these blocks would rely on the clientId prop only. - // This is kept for backward compatibility reasons. - block, - - name, - attributes, - isValid, - isSelected, - isAncestorOfSelectedBlock, - }; - } -); + const block = __unstableGetBlockWithoutInnerBlocks( clientId ); + const isSelected = isBlockSelected( clientId ); + const { focusMode, isRTL } = getSettings(); + const templateLock = getTemplateLock( rootClientId ); + const checkDeep = true; + + // "ancestor" is the more appropriate label due to "deep" check + const isAncestorOfSelectedBlock = hasSelectedInnerBlock( clientId, checkDeep ); + + // The fallback to `{}` is a temporary fix. + // This function should never be called when a block is not present in the state. + // It happens now because the order in withSelect rendering is not correct. + const { name, attributes, isValid } = block || {}; + + return { + isMultiSelected: isBlockMultiSelected( clientId ), + isPartOfMultiSelection: isBlockMultiSelected( clientId ) || isAncestorMultiSelected( clientId ), + isFirstMultiSelected: isFirstMultiSelectedBlock( clientId ), + isLastMultiSelected: getLastMultiSelectedBlockClientId() === clientId, + + // We only care about this prop when the block is selected + // Thus to avoid unnecessary rerenders we avoid updating the prop if the block is not selected. + isTypingWithinBlock: ( isSelected || isAncestorOfSelectedBlock ) && isTyping(), + + mode: getBlockMode( clientId ), + isSelectionEnabled: isSelectionEnabled(), + initialPosition: isSelected ? getSelectedBlocksInitialCaretPosition() : null, + isEmptyDefaultBlock: name && isUnmodifiedDefaultBlock( { name, attributes } ), + isLocked: !! templateLock, + isFocusMode: focusMode && isLargeViewport, + isNavigationMode: isNavigationMode(), + isRTL, + + // Users of the editor.BlockListBlock filter used to be able to access the block prop + // Ideally these blocks would rely on the clientId prop only. + // This is kept for backward compatibility reasons. + block, + + name, + attributes, + isValid, + isSelected, + isAncestorOfSelectedBlock, + }; +} ); const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { const { @@ -421,17 +401,13 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { }, onInsertDefaultBlockAfter() { const { clientId, rootClientId } = ownProps; - const { - getBlockIndex, - } = select( 'core/block-editor' ); + const { getBlockIndex } = select( 'core/block-editor' ); const index = getBlockIndex( clientId, rootClientId ); insertDefaultBlock( {}, rootClientId, index + 1 ); }, onInsertBlocksAfter( blocks ) { const { clientId, rootClientId } = ownProps; - const { - getBlockIndex, - } = select( 'core/block-editor' ); + const { getBlockIndex } = select( 'core/block-editor' ); const index = getBlockIndex( clientId, rootClientId ); insertBlocks( blocks, index + 1, rootClientId ); }, @@ -440,10 +416,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { }, onMerge( forward ) { const { clientId } = ownProps; - const { - getPreviousBlockClientId, - getNextBlockClientId, - } = select( 'core/block-editor' ); + const { getPreviousBlockClientId, getNextBlockClientId } = select( 'core/block-editor' ); if ( forward ) { const nextBlockClientId = getNextBlockClientId( clientId ); @@ -458,10 +431,7 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { } }, onReplace( blocks, indexToSelect ) { - if ( - blocks.length && - ! isUnmodifiedDefaultBlock( blocks[ blocks.length - 1 ] ) - ) { + if ( blocks.length && ! isUnmodifiedDefaultBlock( blocks[ blocks.length - 1 ] ) ) { __unstableMarkLastChangeAsPersistent(); } replaceBlocks( [ ownProps.clientId ], blocks, indexToSelect ); diff --git a/packages/block-editor/src/components/block-list/block.native.js b/packages/block-editor/src/components/block-list/block.native.js index ee70886738af9..c9ff195971111 100644 --- a/packages/block-editor/src/components/block-list/block.native.js +++ b/packages/block-editor/src/components/block-list/block.native.js @@ -1,11 +1,7 @@ /** * External dependencies */ -import { - View, - Text, - TouchableWithoutFeedback, -} from 'react-native'; +import { View, Text, TouchableWithoutFeedback } from 'react-native'; /** * WordPress dependencies @@ -89,13 +85,15 @@ class BlockListBlock extends Component { isRootListInnerBlockHolder, } = this.props; - const fullSolidBorderStyle = { // define style for full border + const fullSolidBorderStyle = { + // define style for full border ...styles.fullSolidBordered, ...getStylesFromColorScheme( styles.solidBorderColor, styles.solidBorderColorDark ), }; - if ( hasChildren ) { // if block has children apply style for selected parent - return { ...styles.selectedParent, ...fullSolidBorderStyle }; + if ( hasChildren ) { + // if block has children apply style for selected parent + return { ...styles.selectedParent, ...fullSolidBorderStyle }; } // apply semi border selected style when screen is in vertical position @@ -130,20 +128,23 @@ class BlockListBlock extends Component { return hasChildren ? styles.neutral : styles.full; } - if ( isParentSelected ) { // parent of a block is selected - const dashedBorderStyle = { // define style for dashed border + if ( isParentSelected ) { + // parent of a block is selected + const dashedBorderStyle = { + // define style for dashed border ...styles.dashedBordered, ...getStylesFromColorScheme( styles.dashedBorderColor, styles.dashedBorderColorDark ), }; // return apply childOfSelected or childOfSelectedLeaf // margins depending if block has children or not - return hasChildren ? - { ...styles.childOfSelected, ...dashedBorderStyle } : - { ...styles.childOfSelectedLeaf, ...dashedBorderStyle }; + return hasChildren + ? { ...styles.childOfSelected, ...dashedBorderStyle } + : { ...styles.childOfSelectedLeaf, ...dashedBorderStyle }; } - if ( isAncestorSelected ) { // ancestor of a block is selected + if ( isAncestorSelected ) { + // ancestor of a block is selected return { ...styles.descendantOfSelectedLeaf, ...( hasChildren && styles.marginHorizontalNone ), @@ -156,10 +157,7 @@ class BlockListBlock extends Component { } applyBlockStyle() { - const { - isSelected, - isDimmed, - } = this.props; + const { isSelected, isDimmed } = this.props; return [ isSelected ? this.applySelectedBlockStyle() : this.applyUnSelectedBlockStyle(), @@ -168,10 +166,7 @@ class BlockListBlock extends Component { } applyToolbarStyle() { - const { - hasChildren, - isUnregisteredBlock, - } = this.props; + const { hasChildren, isUnregisteredBlock } = this.props; if ( ! hasChildren || isUnregisteredBlock ) { return styles.neutralToolbar; @@ -197,8 +192,8 @@ class BlockListBlock extends Component { return ( <> - { showFloatingToolbar && - ( + { showFloatingToolbar && ( + - ) } + ) } - { isValid ? this.getBlockForType() : } - { isSelected && } + { isValid ? ( + this.getBlockForType() + ) : ( + + ) } + + { isSelected && } + @@ -245,9 +246,7 @@ export default compose( [ getBlockCount, } = select( 'core/block-editor' ); - const { - getGroupingBlockName, - } = select( 'core/blocks' ); + const { getGroupingBlockName } = select( 'core/blocks' ); const order = getBlockIndex( clientId, rootClientId ); const isSelected = isBlockSelected( clientId ); @@ -273,7 +272,9 @@ export default compose( [ const commonAncestor = getLowestCommonAncestorWithSelectedBlock( clientId ); const commonAncestorIndex = parents.indexOf( commonAncestor ) - 1; - const firstToSelectId = commonAncestor ? parents[ commonAncestorIndex ] : parents[ parents.length - 1 ]; + const firstToSelectId = commonAncestor + ? parents[ commonAncestorIndex ] + : parents[ parents.length - 1 ]; const hasChildren = ! isUnregisteredBlock && !! getBlockCount( clientId ); const hasParent = !! parentId; @@ -284,8 +285,14 @@ export default compose( [ const selectedParents = selectedBlockClientId ? getBlockParents( selectedBlockClientId ) : []; const isDescendantSelected = selectedParents.includes( clientId ); const isDescendantOfParentSelected = selectedParents.includes( parentId ); - const isTouchable = isSelected || isDescendantOfParentSelected || isParentSelected || parentId === ''; - const isDimmed = ! isSelected && isSelectedBlockNested && ! isAncestorSelected && ! isDescendantSelected && ( isDescendantOfParentSelected || rootBlockId === clientId ); + const isTouchable = + isSelected || isDescendantOfParentSelected || isParentSelected || parentId === ''; + const isDimmed = + ! isSelected && + isSelectedBlockNested && + ! isAncestorSelected && + ! isDescendantSelected && + ( isDescendantOfParentSelected || rootBlockId === clientId ); const isInnerBlockHolder = name === getGroupingBlockName(); const isRootListInnerBlockHolder = ! isSelectedBlockNested && isInnerBlockHolder; @@ -325,10 +332,7 @@ export default compose( [ return { mergeBlocks( forward ) { const { clientId } = ownProps; - const { - getPreviousBlockClientId, - getNextBlockClientId, - } = select( 'core/block-editor' ); + const { getPreviousBlockClientId, getNextBlockClientId } = select( 'core/block-editor' ); if ( forward ) { const nextBlockClientId = getNextBlockClientId( clientId ); diff --git a/packages/block-editor/src/components/block-list/breadcrumb.js b/packages/block-editor/src/components/block-list/breadcrumb.js index 2f0c4f28bd918..77fa495db9951 100644 --- a/packages/block-editor/src/components/block-list/breadcrumb.js +++ b/packages/block-editor/src/components/block-list/breadcrumb.js @@ -26,20 +26,17 @@ import BlockTitle from '../block-title'; * @return {WPComponent} The component to be rendered. */ function BlockBreadcrumb( { clientId, rootClientId, moverDirection, ...props } ) { - const selected = useSelect( ( select ) => { - const { - __unstableGetBlockWithoutInnerBlocks, - getBlockIndex, - } = select( 'core/block-editor' ); - const index = getBlockIndex( clientId, rootClientId ); - const { name, attributes } = __unstableGetBlockWithoutInnerBlocks( clientId ); - return { index, name, attributes }; - }, [ clientId, rootClientId ] ); + const selected = useSelect( + ( select ) => { + const { __unstableGetBlockWithoutInnerBlocks, getBlockIndex } = select( 'core/block-editor' ); + const index = getBlockIndex( clientId, rootClientId ); + const { name, attributes } = __unstableGetBlockWithoutInnerBlocks( clientId ); + return { index, name, attributes }; + }, + [ clientId, rootClientId ] + ); const { index, name, attributes } = selected; - const { - setNavigationMode, - removeBlock, - } = useDispatch( 'core/block-editor' ); + const { setNavigationMode, removeBlock } = useDispatch( 'core/block-editor' ); const ref = useRef(); // Focus the breadcrumb in navigation mode. diff --git a/packages/block-editor/src/components/block-list/breadcrumb.native.js b/packages/block-editor/src/components/block-list/breadcrumb.native.js index ae5d615f43b87..33a9b3ace7c7e 100644 --- a/packages/block-editor/src/components/block-list/breadcrumb.native.js +++ b/packages/block-editor/src/components/block-list/breadcrumb.native.js @@ -24,14 +24,23 @@ const BlockBreadcrumb = ( { clientId, blockIcon, rootClientId, rootBlockIcon } ) {/* Open BottomSheet with markup */} } + onPress={ () => { + /* Open BottomSheet with markup */ + } } disabled={ true } /* Disable temporarily since onPress function is empty */ > - { rootClientId && rootBlockIcon && ( - [ , - , - ] - ) } + { rootClientId && + rootBlockIcon && [ + , + + + , + ] } { - const { - getBlockRootClientId, - getBlockName, - } = select( 'core/block-editor' ); + const { getBlockRootClientId, getBlockName } = select( 'core/block-editor' ); const blockName = getBlockName( clientId ); const blockType = getBlockType( blockName ); diff --git a/packages/block-editor/src/components/block-list/index.js b/packages/block-editor/src/components/block-list/index.js index 1fd0f8afa9fc5..48d05a5f629b6 100644 --- a/packages/block-editor/src/components/block-list/index.js +++ b/packages/block-editor/src/components/block-list/index.js @@ -56,10 +56,7 @@ function BlockList( { selectedBlockClientId: getSelectedBlockClientId(), multiSelectedBlockClientIds: getMultiSelectedBlockClientIds(), hasMultiSelection: hasMultiSelection(), - enableAnimation: ( - ! isTyping() && - getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD - ), + enableAnimation: ! isTyping() && getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD, }; } @@ -80,17 +77,11 @@ function BlockList( { } ); return ( - + { blockClientIds.map( ( clientId, index ) => { - const isBlockInSelection = hasMultiSelection ? - multiSelectedBlockClientIds.includes( clientId ) : - selectedBlockClientId === clientId; + const isBlockInSelection = hasMultiSelection + ? multiSelectedBlockClientIds.includes( clientId ) + : selectedBlockClientId === clientId; return ( diff --git a/packages/block-editor/src/components/block-list/index.native.js b/packages/block-editor/src/components/block-list/index.native.js index 6d871a8305e99..df1a9f1d7e2b6 100644 --- a/packages/block-editor/src/components/block-list/index.native.js +++ b/packages/block-editor/src/components/block-list/index.native.js @@ -34,7 +34,9 @@ export class BlockList extends Component { this.onCaretVerticalPositionChange = this.onCaretVerticalPositionChange.bind( this ); this.scrollViewInnerRef = this.scrollViewInnerRef.bind( this ); this.addBlockToEndOfPost = this.addBlockToEndOfPost.bind( this ); - this.shouldFlatListPreventAutomaticScroll = this.shouldFlatListPreventAutomaticScroll.bind( this ); + this.shouldFlatListPreventAutomaticScroll = this.shouldFlatListPreventAutomaticScroll.bind( + this + ); this.shouldShowInnerBlockAppender = this.shouldShowInnerBlockAppender.bind( this ); } @@ -43,7 +45,12 @@ export class BlockList extends Component { } onCaretVerticalPositionChange( targetId, caretY, previousCaretY ) { - KeyboardAwareFlatList.handleCaretVerticalPositionChange( this.scrollViewRef, targetId, caretY, previousCaretY ); + KeyboardAwareFlatList.handleCaretVerticalPositionChange( + this.scrollViewRef, + targetId, + caretY, + previousCaretY + ); } scrollViewInnerRef( ref ) { @@ -59,7 +66,7 @@ export class BlockList extends Component { const willShowInsertionPoint = shouldShowInsertionPointBefore(); // call without the client_id argument since this is the appender return ( - 0 ); + const { blockClientIds, renderAppender } = this.props; + return renderAppender && blockClientIds.length > 0; } render() { @@ -89,10 +93,7 @@ export class BlockList extends Component { } = this.props; return ( - + - ) - } - + ) } ); } @@ -146,7 +145,9 @@ export class BlockList extends Component { onCaretVerticalPositionChange={ this.onCaretVerticalPositionChange } isSmallScreen={ ! this.props.isFullyBordered } /> - { ! this.shouldShowInnerBlockAppender() && shouldShowInsertionPointAfter( clientId ) && } + { ! this.shouldShowInnerBlockAppender() && shouldShowInsertionPointAfter( clientId ) && ( + + ) } ); @@ -156,9 +157,11 @@ export class BlockList extends Component { const paragraphBlock = createBlock( 'core/paragraph' ); return ( <> - { - this.addBlockToEndOfPost( paragraphBlock ); - } } > + { + this.addBlockToEndOfPost( paragraphBlock ); + } } + > <__experimentalBlockListFooter.Slot /> @@ -186,22 +189,18 @@ export default compose( [ return ( blockInsertionPointIsVisible && insertionPoint.rootClientId === rootClientId && - ( - // if list is empty, show the insertion point (via the default appender) - blockClientIds.length === 0 || + // if list is empty, show the insertion point (via the default appender) + ( blockClientIds.length === 0 || // or if the insertion point is right before the denoted block - blockClientIds[ insertionPoint.index ] === clientId - ) + blockClientIds[ insertionPoint.index ] === clientId ) ); }; const shouldShowInsertionPointAfter = ( clientId ) => { return ( blockInsertionPointIsVisible && insertionPoint.rootClientId === rootClientId && - // if the insertion point is at the end of the list blockClientIds.length === insertionPoint.index && - // and the denoted block is the last one on the list, show the indicator at the end of the block blockClientIds[ insertionPoint.index - 1 ] === clientId ); @@ -221,11 +220,7 @@ export default compose( [ }; } ), withDispatch( ( dispatch ) => { - const { - insertBlock, - replaceBlock, - clearSelectedBlock, - } = dispatch( 'core/block-editor' ); + const { insertBlock, replaceBlock, clearSelectedBlock } = dispatch( 'core/block-editor' ); return { clearSelectedBlock, diff --git a/packages/block-editor/src/components/block-list/insertion-point.js b/packages/block-editor/src/components/block-list/insertion-point.js index 7ca4d53ca065c..3ff506db3631e 100644 --- a/packages/block-editor/src/components/block-list/insertion-point.js +++ b/packages/block-editor/src/components/block-list/insertion-point.js @@ -19,22 +19,25 @@ import { getClosestTabbable } from '../writing-flow'; import { getBlockDOMNode } from '../../utils/dom'; function Indicator( { clientId } ) { - const showInsertionPoint = useSelect( ( select ) => { - const { - getBlockIndex, - getBlockInsertionPoint, - isBlockInsertionPointVisible, - getBlockRootClientId, - } = select( 'core/block-editor' ); - const rootClientId = getBlockRootClientId( clientId ); - const blockIndex = getBlockIndex( clientId, rootClientId ); - const insertionPoint = getBlockInsertionPoint(); - return ( - isBlockInsertionPointVisible() && - insertionPoint.index === blockIndex && - insertionPoint.rootClientId === rootClientId - ); - }, [ clientId ] ); + const showInsertionPoint = useSelect( + ( select ) => { + const { + getBlockIndex, + getBlockInsertionPoint, + isBlockInsertionPointVisible, + getBlockRootClientId, + } = select( 'core/block-editor' ); + const rootClientId = getBlockRootClientId( clientId ); + const blockIndex = getBlockIndex( clientId, rootClientId ); + const insertionPoint = getBlockInsertionPoint(); + return ( + isBlockInsertionPointVisible() && + insertionPoint.index === blockIndex && + insertionPoint.rootClientId === rootClientId + ); + }, + [ clientId ] + ); if ( ! showInsertionPoint ) { return null; @@ -104,7 +107,7 @@ export default function InsertionPoint( { } const targetRect = target.getBoundingClientRect(); - const isReverse = clientY < targetRect.top + ( targetRect.height / 2 ); + const isReverse = clientY < targetRect.top + targetRect.height / 2; const blockNode = getBlockDOMNode( inserterClientId ); const container = isReverse ? containerRef.current : blockNode; const closest = getClosestTabbable( blockNode, true, container ); @@ -115,46 +118,50 @@ export default function InsertionPoint( { } } - return <> - { ! isMultiSelecting && ( isInserterShown || isInserterForced ) && -
    - - { /* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */ } -
    setIsInserterForced( true ) } - onBlur={ () => setIsInserterForced( false ) } - onClick={ focusClosestTabbable } - // While ideally it would be enough to capture the - // bubbling focus event from the Inserter, due to the - // characteristics of click focusing of `button`s in - // Firefox and Safari, it is not reliable. - // - // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus - tabIndex={ -1 } - className={ classnames( - 'block-editor-block-list__insertion-point-inserter', - { - // Hide the inserter above the selected block. - 'is-inserter-hidden': inserterClientId === selectedBlockClientId, - } - ) } + return ( + <> + { ! isMultiSelecting && ( isInserterShown || isInserterForced ) && ( + - -
    +
    + + { /* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */ } +
    setIsInserterForced( true ) } + onBlur={ () => setIsInserterForced( false ) } + onClick={ focusClosestTabbable } + // While ideally it would be enough to capture the + // bubbling focus event from the Inserter, due to the + // characteristics of click focusing of `button`s in + // Firefox and Safari, it is not reliable. + // + // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus + tabIndex={ -1 } + className={ classnames( 'block-editor-block-list__insertion-point-inserter', { + // Hide the inserter above the selected block. + 'is-inserter-hidden': inserterClientId === selectedBlockClientId, + } ) } + > + +
    +
    + + ) } +
    + { children }
    - } -
    - { children } -
    - ; + + ); } 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 a9a2741514783..5f19827ba6840 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 @@ -15,13 +15,19 @@ import { withPreferredColorScheme } from '@wordpress/compose'; import styles from './style.scss'; const BlockInsertionPoint = ( { getStylesFromColorScheme } ) => { - const lineStyle = getStylesFromColorScheme( styles.lineStyleAddHere, styles.lineStyleAddHereDark ); - const labelStyle = getStylesFromColorScheme( styles.labelStyleAddHere, styles.labelStyleAddHereDark ); + const lineStyle = getStylesFromColorScheme( + styles.lineStyleAddHere, + styles.lineStyleAddHereDark + ); + const labelStyle = getStylesFromColorScheme( + styles.labelStyleAddHere, + styles.labelStyleAddHereDark + ); return ( - + - { __( 'ADD BLOCK HERE' ) } + { __( 'ADD BLOCK HERE' ) } ); 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 afa36bb40304d..8c53827772575 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/nav-up-icon.js b/packages/block-editor/src/components/block-list/nav-up-icon.js index 8fa1c8d20bd76..a1878c28df241 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/root-container.js b/packages/block-editor/src/components/block-list/root-container.js index 84985f8fd7c07..38f7c0e6e0a12 100644 --- a/packages/block-editor/src/components/block-list/root-container.js +++ b/packages/block-editor/src/components/block-list/root-container.js @@ -18,11 +18,9 @@ export const Context = createContext(); export const BlockNodes = createContext(); function selector( select ) { - const { - getSelectedBlockClientId, - hasMultiSelection, - isMultiSelecting, - } = select( 'core/block-editor' ); + const { getSelectedBlockClientId, hasMultiSelection, isMultiSelecting } = select( + 'core/block-editor' + ); return { selectedBlockClientId: getSelectedBlockClientId(), @@ -47,11 +45,7 @@ function onDragStart( event ) { } function RootContainer( { children, className }, ref ) { - const { - selectedBlockClientId, - hasMultiSelection, - isMultiSelecting, - } = useSelect( selector, [] ); + const { selectedBlockClientId, hasMultiSelection, isMultiSelecting } = useSelect( selector, [] ); const { selectBlock } = useDispatch( 'core/block-editor' ); const onSelectionStart = useMultiSelection( ref ); @@ -83,15 +77,8 @@ function RootContainer( { children, className }, ref ) { > -
    - - { children } - +
    + { children }
    diff --git a/packages/block-editor/src/components/block-list/subdirectory-icon.js b/packages/block-editor/src/components/block-list/subdirectory-icon.js index 9da2bc4a1c88a..f024c51880e4b 100644 --- a/packages/block-editor/src/components/block-list/subdirectory-icon.js +++ b/packages/block-editor/src/components/block-list/subdirectory-icon.js @@ -12,7 +12,6 @@ const Subdirectory = ( { ...extraProps } ) => ( { ...extraProps } > - ) -; - + +); export default Subdirectory; diff --git a/packages/block-editor/src/components/block-list/use-multi-selection.js b/packages/block-editor/src/components/block-list/use-multi-selection.js index a0ba7de65a0f0..001a7e28af84f 100644 --- a/packages/block-editor/src/components/block-list/use-multi-selection.js +++ b/packages/block-editor/src/components/block-list/use-multi-selection.js @@ -56,15 +56,13 @@ function selector( select ) { } function toggleRichText( container, toggle ) { - Array - .from( container.querySelectorAll( '.rich-text' ) ) - .forEach( ( node ) => { - if ( toggle ) { - node.setAttribute( 'contenteditable', true ); - } else { - node.removeAttribute( 'contenteditable' ); - } - } ); + Array.from( container.querySelectorAll( '.rich-text' ) ).forEach( ( node ) => { + if ( toggle ) { + node.setAttribute( 'contenteditable', true ); + } else { + node.removeAttribute( 'contenteditable' ); + } + } ); } export default function useMultiSelection( ref ) { @@ -76,12 +74,9 @@ export default function useMultiSelection( ref ) { getBlockParents, selectedBlockClientId, } = useSelect( selector, [] ); - const { - startMultiSelect, - stopMultiSelect, - multiSelect, - selectBlock, - } = useDispatch( 'core/block-editor' ); + const { startMultiSelect, stopMultiSelect, multiSelect, selectBlock } = useDispatch( + 'core/block-editor' + ); const rafId = useRef(); const startClientId = useRef(); const anchorElement = useRef(); @@ -102,10 +97,7 @@ export default function useMultiSelection( ref ) { const blockNode = getBlockDOMNode( selectedBlockClientId ); const { startContainer, endContainer } = selection.getRangeAt( 0 ); - if ( - ! blockNode.contains( startContainer ) || - ! blockNode.contains( endContainer ) - ) { + if ( ! blockNode.contains( startContainer ) || ! blockNode.contains( endContainer ) ) { selection.removeAllRanges(); } } @@ -147,46 +139,49 @@ export default function useMultiSelection( ref ) { selectedBlockClientId, ] ); - const onSelectionChange = useCallback( ( { isSelectionEnd } ) => { - const selection = window.getSelection(); + const onSelectionChange = useCallback( + ( { isSelectionEnd } ) => { + const selection = window.getSelection(); - // If no selection is found, end multi selection and enable all rich - // text areas. - if ( ! selection.rangeCount || selection.isCollapsed ) { - toggleRichText( ref.current, true ); - return; - } + // If no selection is found, end multi selection and enable all rich + // text areas. + if ( ! selection.rangeCount || selection.isCollapsed ) { + toggleRichText( ref.current, true ); + return; + } - const clientId = getBlockClientId( selection.focusNode ); - const isSingularSelection = startClientId.current === clientId; + const clientId = getBlockClientId( selection.focusNode ); + const isSingularSelection = startClientId.current === clientId; - if ( isSingularSelection ) { - selectBlock( clientId ); + if ( isSingularSelection ) { + selectBlock( clientId ); - // If the selection is complete (on mouse up), and no multiple - // blocks have been selected, set focus back to the anchor element - // if the anchor element contains the selection. Additionally, rich - // text elements that were previously disabled can now be enabled - // again. - if ( isSelectionEnd ) { - toggleRichText( ref.current, true ); + // If the selection is complete (on mouse up), and no multiple + // blocks have been selected, set focus back to the anchor element + // if the anchor element contains the selection. Additionally, rich + // text elements that were previously disabled can now be enabled + // again. + if ( isSelectionEnd ) { + toggleRichText( ref.current, true ); - if ( selection.rangeCount ) { - const { commonAncestorContainer } = selection.getRangeAt( 0 ); + if ( selection.rangeCount ) { + const { commonAncestorContainer } = selection.getRangeAt( 0 ); - if ( anchorElement.current.contains( commonAncestorContainer ) ) { - anchorElement.current.focus(); + if ( anchorElement.current.contains( commonAncestorContainer ) ) { + anchorElement.current.focus(); + } } } - } - } else { - const startPath = [ ...getBlockParents( startClientId.current ), startClientId.current ]; - const endPath = [ ...getBlockParents( clientId ), clientId ]; - const depth = Math.min( startPath.length, endPath.length ) - 1; + } else { + const startPath = [ ...getBlockParents( startClientId.current ), startClientId.current ]; + const endPath = [ ...getBlockParents( clientId ), clientId ]; + const depth = Math.min( startPath.length, endPath.length ) - 1; - multiSelect( startPath[ depth ], endPath[ depth ] ); - } - }, [ selectBlock, getBlockParents, multiSelect ] ); + multiSelect( startPath[ depth ], endPath[ depth ] ); + } + }, + [ selectBlock, getBlockParents, multiSelect ] + ); /** * Handles a mouseup event to end the current mouse multi-selection. @@ -204,39 +199,45 @@ export default function useMultiSelection( ref ) { }, [ onSelectionChange, stopMultiSelect ] ); // Only clean up when unmounting, these are added and cleaned up elsewhere. - useEffect( () => () => { - document.removeEventListener( 'selectionchange', onSelectionChange ); - window.removeEventListener( 'mouseup', onSelectionEnd ); - window.cancelAnimationFrame( rafId.current ); - }, [ onSelectionChange, onSelectionEnd ] ); + useEffect( + () => () => { + document.removeEventListener( 'selectionchange', onSelectionChange ); + window.removeEventListener( 'mouseup', onSelectionEnd ); + window.cancelAnimationFrame( rafId.current ); + }, + [ onSelectionChange, onSelectionEnd ] + ); /** * Binds event handlers to the document for tracking a pending multi-select * in response to a mousedown event occurring in a rendered block. */ - return useCallback( ( clientId ) => { - if ( ! isSelectionEnabled ) { - return; - } + return useCallback( + ( clientId ) => { + if ( ! isSelectionEnabled ) { + return; + } - startClientId.current = clientId; - anchorElement.current = document.activeElement; - startMultiSelect(); - - // `onSelectionStart` is called after `mousedown` and `mouseleave` - // (from a block). The selection ends when `mouseup` happens anywhere - // in the window. - document.addEventListener( 'selectionchange', onSelectionChange ); - window.addEventListener( 'mouseup', onSelectionEnd ); - - // Removing the contenteditable attributes within the block editor is - // essential for selection to work across editable areas. The edible - // hosts are removed, allowing selection to be extended outside the - // DOM element. `startMultiSelect` sets a flag in the store so the rich - // text components are updated, but the rerender may happen very slowly, - // especially in Safari for the blocks that are asynchonously rendered. - // To ensure the browser instantly removes the selection boundaries, we - // remove the contenteditable attributes manually. - toggleRichText( ref.current, false ); - }, [ isSelectionEnabled, startMultiSelect, onSelectionEnd ] ); + startClientId.current = clientId; + anchorElement.current = document.activeElement; + startMultiSelect(); + + // `onSelectionStart` is called after `mousedown` and `mouseleave` + // (from a block). The selection ends when `mouseup` happens anywhere + // in the window. + document.addEventListener( 'selectionchange', onSelectionChange ); + window.addEventListener( 'mouseup', onSelectionEnd ); + + // Removing the contenteditable attributes within the block editor is + // essential for selection to work across editable areas. The edible + // hosts are removed, allowing selection to be extended outside the + // DOM element. `startMultiSelect` sets a flag in the store so the rich + // text components are updated, but the rerender may happen very slowly, + // especially in Safari for the blocks that are asynchonously rendered. + // To ensure the browser instantly removes the selection boundaries, we + // remove the contenteditable attributes manually. + toggleRichText( ref.current, false ); + }, + [ isSelectionEnabled, startMultiSelect, onSelectionEnd ] + ); } diff --git a/packages/block-editor/src/components/block-mobile-toolbar/index.native.js b/packages/block-editor/src/components/block-mobile-toolbar/index.native.js index 4be16304d9937..43a34c0466b54 100644 --- a/packages/block-editor/src/components/block-mobile-toolbar/index.native.js +++ b/packages/block-editor/src/components/block-mobile-toolbar/index.native.js @@ -19,11 +19,7 @@ import styles from './style.scss'; import BlockMover from '../block-mover'; import { BlockSettingsButton } from '../block-settings'; -const BlockMobileToolbar = ( { - clientId, - onDelete, - order, -} ) => ( +const BlockMobileToolbar = ( { clientId, onDelete, order } ) => ( @@ -32,13 +28,11 @@ const BlockMobileToolbar = ( { { - const { - getBlockIndex, - } = select( 'core/block-editor' ); + const { getBlockIndex } = select( 'core/block-editor' ); return { order: getBlockIndex( clientId ), @@ -64,5 +56,5 @@ export default compose( removeBlock( clientId, rootClientId ); }, }; - } ), + } ) )( BlockMobileToolbar ); diff --git a/packages/block-editor/src/components/block-mover/icons.js b/packages/block-editor/src/components/block-mover/icons.js index f3b575bd57a86..a55400d965e02 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 rightArrow = ( 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 ea5bb8c36d8fe..aebd0f76baa3a 100644 --- a/packages/block-editor/src/components/block-mover/index.js +++ b/packages/block-editor/src/components/block-mover/index.js @@ -45,7 +45,21 @@ export class BlockMover extends Component { } render() { - const { onMoveUp, onMoveDown, __experimentalOrientation: orientation, isRTL, isFirst, isLast, clientIds, blockType, firstIndex, isLocked, instanceId, isHidden, rootClientId } = this.props; + const { + onMoveUp, + onMoveDown, + __experimentalOrientation: orientation, + isRTL, + isFirst, + isLast, + clientIds, + blockType, + firstIndex, + isLocked, + instanceId, + isHidden, + rootClientId, + } = this.props; const { isFocused } = this.state; const blocksCount = castArray( clientIds ).length; if ( isLocked || ( isFirst && isLast && ! rootClientId ) ) { @@ -87,7 +101,12 @@ 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 ( - +
    { showNestedBlocks && !! block.innerBlocks && !! block.innerBlocks.length && ( diff --git a/packages/block-editor/src/components/block-pattern-picker/index.js b/packages/block-editor/src/components/block-pattern-picker/index.js index 5e2080b4cea3e..7a967afef4e66 100644 --- a/packages/block-editor/src/components/block-pattern-picker/index.js +++ b/packages/block-editor/src/components/block-pattern-picker/index.js @@ -22,19 +22,12 @@ function BlockPatternPicker( { } ); 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 */ } - { ! RichText.isEmpty( caption ) && } + { ! RichText.isEmpty( caption ) && ( + + ) } ); }, @@ -199,9 +215,14 @@ const deprecated = [ align: true, }, save( { attributes } ) { - const { images, columns = defaultColumnsNumber( attributes ), imageCrop, linkTo } = attributes; + const { + images, + columns = defaultColumnsNumber( attributes ), + imageCrop, + linkTo, + } = attributes; return ( -
      +
        { images.map( ( image ) => { let href; @@ -289,18 +310,18 @@ const deprecated = [ }, }, isEligible( { images, ids } ) { - return images && + return ( + images && images.length > 0 && - ( - ( ! ids && images ) || + ( ( ! ids && images ) || ( ids && images && ids.length !== images.length ) || some( images, ( id, index ) => { if ( ! id && ids[ index ] !== null ) { return true; } return parseInt( id, 10 ) !== ids[ index ]; - } ) - ); + } ) ) + ); }, migrate( attributes ) { return { @@ -317,9 +338,14 @@ const deprecated = [ align: true, }, save( { attributes } ) { - const { images, columns = defaultColumnsNumber( attributes ), imageCrop, linkTo } = attributes; + const { + images, + columns = defaultColumnsNumber( attributes ), + imageCrop, + linkTo, + } = attributes; return ( -
          +
            { images.map( ( image ) => { let href; @@ -332,7 +358,15 @@ const deprecated = [ break; } - const img = {; + const img = ( + { + ); return (
          • @@ -392,13 +426,19 @@ const deprecated = [ align: true, }, save( { attributes } ) { - const { images, columns = defaultColumnsNumber( attributes ), align, imageCrop, linkTo } = attributes; + const { + images, + columns = defaultColumnsNumber( attributes ), + align, + imageCrop, + linkTo, + } = attributes; const className = classnames( `columns-${ columns }`, { alignnone: align === 'none', 'is-cropped': imageCrop, } ); return ( -
            +
            { images.map( ( image ) => { let href; diff --git a/packages/block-library/src/gallery/edit.js b/packages/block-library/src/gallery/edit.js index 9d7b57c77c8b6..6ff5f20e92eb7 100644 --- a/packages/block-library/src/gallery/edit.js +++ b/packages/block-library/src/gallery/edit.js @@ -1,17 +1,7 @@ /** * External dependencies */ -import { - every, - filter, - find, - forEach, - get, - isEmpty, - map, - reduce, - some, -} from 'lodash'; +import { every, filter, find, forEach, get, isEmpty, map, reduce, some } from 'lodash'; /** * WordPress dependencies @@ -24,10 +14,7 @@ import { ToggleControl, withNotices, } from '@wordpress/components'; -import { - MediaPlaceholder, - InspectorControls, -} from '@wordpress/block-editor'; +import { MediaPlaceholder, InspectorControls } from '@wordpress/block-editor'; import { Component, Platform } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { getBlobByURL, isBlobURL, revokeBlobURL } from '@wordpress/blob'; @@ -93,7 +80,9 @@ class GalleryEdit extends Component { setAttributes( attributes ) { if ( attributes.ids ) { - throw new Error( 'The "ids" attribute should not be changed directly. It is managed automatically when "images" attribute changes' ); + throw new Error( + 'The "ids" attribute should not be changed directly. It is managed automatically when "images" attribute changes' + ); } if ( attributes.images ) { @@ -155,9 +144,7 @@ class GalleryEdit extends Component { } selectCaption( newImage, images, attachmentCaptions ) { - const currentImage = find( - images, { id: newImage.id } - ); + const currentImage = find( images, { id: newImage.id } ); const currentImageCaption = currentImage ? currentImage.caption : newImage.caption; @@ -165,12 +152,10 @@ class GalleryEdit extends Component { return currentImageCaption; } - const attachment = find( - attachmentCaptions, { id: newImage.id } - ); + const attachment = find( attachmentCaptions, { id: newImage.id } ); // if the attachment caption is updated - if ( attachment && ( attachment.caption !== newImage.caption ) ) { + if ( attachment && attachment.caption !== newImage.caption ) { return newImage.caption; } @@ -180,14 +165,12 @@ class GalleryEdit extends Component { onSelectImages( newImages ) { const { columns, images, sizeSlug } = this.props.attributes; const { attachmentCaptions } = this.state; - this.setState( - { - attachmentCaptions: newImages.map( ( newImage ) => ( { - id: newImage.id, - caption: newImage.caption, - } ) ), - } - ); + this.setState( { + attachmentCaptions: newImages.map( ( newImage ) => ( { + id: newImage.id, + caption: newImage.caption, + } ) ), + } ); this.setAttributes( { images: newImages.map( ( newImage ) => ( { ...pickRelevantMediaFiles( newImage, sizeSlug ), @@ -226,7 +209,9 @@ class GalleryEdit extends Component { } setImageAttributes( index, attributes ) { - const { attributes: { images } } = this.props; + const { + attributes: { images }, + } = this.props; const { setAttributes } = this; if ( ! images[ index ] ) { return; @@ -246,16 +231,16 @@ class GalleryEdit extends Component { getImagesSizeOptions() { const { imageSizes, resizedImages } = this.props; return map( - filter( - imageSizes, - ( { slug } ) => some( resizedImages, ( sizes ) => ( sizes[ slug ] ) ) - ), + filter( imageSizes, ( { slug } ) => some( resizedImages, ( sizes ) => sizes[ slug ] ) ), ( { name, slug } ) => ( { value: slug, label: name } ) ); } updateImagesSize( sizeSlug ) { - const { attributes: { images }, resizedImages } = this.props; + const { + attributes: { images }, + resizedImages, + } = this.props; const updatedImages = map( images, ( image ) => { if ( ! image.id ) { @@ -276,7 +261,8 @@ class GalleryEdit extends Component { const { images } = attributes; if ( Platform.OS === 'web' && - images && images.length > 0 && + images && + images.length > 0 && every( images, ( { url } ) => isBlobURL( url ) ) ) { const filesList = map( images, ( { url } ) => getBlobByURL( url ) ); @@ -300,12 +286,7 @@ class GalleryEdit extends Component { } render() { - const { - attributes, - className, - isSelected, - noticeUI, - } = this.props; + const { attributes, className, isSelected, noticeUI } = this.props; const { columns = defaultColumnsNumber( attributes ), imageCrop, @@ -346,23 +327,25 @@ class GalleryEdit extends Component { const imageSizeOptions = this.getImagesSizeOptions(); const shouldShowSizeOptions = hasImages && ! isEmpty( imageSizeOptions ); // This is needed to fix a separator fence-post issue on mobile. - const mobileLinkToProps = shouldShowSizeOptions ? - MOBILE_CONTROL_PROPS : - MOBILE_CONTROL_PROPS_SEPARATOR_NONE; + const mobileLinkToProps = shouldShowSizeOptions + ? MOBILE_CONTROL_PROPS + : MOBILE_CONTROL_PROPS_SEPARATOR_NONE; return ( <> - { images.length > 1 && } + { images.length > 1 && ( + + ) } { const { getMedia } = select( 'core' ); const { getSettings } = select( 'core/block-editor' ); - const { - imageSizes, - mediaUpload, - } = getSettings(); + const { imageSizes, mediaUpload } = getSettings(); let resizedImages = {}; if ( isSelected ) { - resizedImages = reduce( ids, ( currentResizedImages, id ) => { - if ( ! id ) { - return currentResizedImages; - } - const image = getMedia( id ); - const sizes = reduce( imageSizes, ( currentSizes, size ) => { - const defaultUrl = get( image, [ 'sizes', size.slug, 'url' ] ); - const mediaDetailsUrl = get( image, [ 'media_details', 'sizes', size.slug, 'source_url' ] ); + resizedImages = reduce( + ids, + ( currentResizedImages, id ) => { + if ( ! id ) { + return currentResizedImages; + } + const image = getMedia( id ); + const sizes = reduce( + imageSizes, + ( currentSizes, size ) => { + const defaultUrl = get( image, [ 'sizes', size.slug, 'url' ] ); + const mediaDetailsUrl = get( image, [ + 'media_details', + 'sizes', + size.slug, + 'source_url', + ] ); + return { + ...currentSizes, + [ size.slug ]: defaultUrl || mediaDetailsUrl, + }; + }, + {} + ); return { - ...currentSizes, - [ size.slug ]: defaultUrl || mediaDetailsUrl, + ...currentResizedImages, + [ parseInt( id, 10 ) ]: sizes, }; - }, {} ); - return { - ...currentResizedImages, - [ parseInt( id, 10 ) ]: sizes, - }; - }, {} ); + }, + {} + ); } return { diff --git a/packages/block-library/src/gallery/gallery-image.js b/packages/block-library/src/gallery/gallery-image.js index 99dce175a58a6..6aa51e5233b43 100644 --- a/packages/block-library/src/gallery/gallery-image.js +++ b/packages/block-library/src/gallery/gallery-image.js @@ -64,7 +64,8 @@ class GalleryImage extends Component { onRemoveImage( event ) { if ( this.container === document.activeElement && - this.props.isSelected && [ BACKSPACE, DELETE ].indexOf( event.keyCode ) !== -1 + this.props.isSelected && + [ BACKSPACE, DELETE ].indexOf( event.keyCode ) !== -1 ) { event.stopPropagation(); event.preventDefault(); @@ -91,7 +92,22 @@ class GalleryImage extends Component { } render() { - const { url, alt, id, linkTo, link, isFirstItem, isLastItem, isSelected, caption, onRemove, onMoveForward, onMoveBackward, setAttributes, 'aria-label': ariaLabel } = this.props; + const { + url, + alt, + id, + linkTo, + link, + isFirstItem, + isLastItem, + isSelected, + caption, + onRemove, + onMoveForward, + onMoveBackward, + setAttributes, + 'aria-label': ariaLabel, + } = this.props; let href; diff --git a/packages/block-library/src/gallery/gallery-image.native.js b/packages/block-library/src/gallery/gallery-image.native.js index d1976bc42ea2d..38031aabe1db3 100644 --- a/packages/block-library/src/gallery/gallery-image.native.js +++ b/packages/block-library/src/gallery/gallery-image.native.js @@ -77,7 +77,7 @@ class GalleryImage extends Component { if ( this.state.isUploadInProgress ) { requestImageUploadCancelDialog( id ); - } else if ( ( this.state.didUploadFail ) || ( id && ! isURL( url ) ) ) { + } else if ( this.state.didUploadFail || ( id && ! isURL( url ) ) ) { requestImageFailedRetryDialog( id ); } } @@ -148,34 +148,46 @@ class GalleryImage extends Component { renderContent( params ) { const { - url, isFirstItem, isLastItem, isSelected, caption, onRemove, - onMoveForward, onMoveBackward, 'aria-label': ariaLabel, - isCropped, getStylesFromColorScheme } = this.props; + url, + isFirstItem, + isLastItem, + isSelected, + caption, + onRemove, + onMoveForward, + onMoveBackward, + 'aria-label': ariaLabel, + isCropped, + getStylesFromColorScheme, + } = this.props; const { isUploadInProgress, captionSelected } = this.state; const { isUploadFailed, retryMessage } = params; const resizeMode = isCropped ? 'cover' : 'contain'; - const imageStyle = [ style.image, { resizeMode }, + const imageStyle = [ + style.image, + { resizeMode }, isUploadInProgress ? style.imageUploading : undefined, ]; - const overlayStyle = compose( style.overlay, - isSelected ? style.overlaySelected : undefined, - ); + const overlayStyle = compose( style.overlay, isSelected ? style.overlaySelected : undefined ); - const captionPlaceholderStyle = getStylesFromColorScheme( style.captionPlaceholder, style.captionPlaceholderDark ); + const captionPlaceholderStyle = getStylesFromColorScheme( + style.captionPlaceholder, + style.captionPlaceholderDark + ); const shouldShowCaptionEditable = ! isUploadFailed && isSelected; - const shouldShowCaptionExpanded = ! isUploadFailed && ( ! isSelected && !! caption ); + const shouldShowCaptionExpanded = ! isUploadFailed && ! isSelected && !! caption; - const captionContainerStyle = shouldShowCaptionExpanded ? - style.captionExpandedContainer : - style.captionContainer; + const captionContainerStyle = shouldShowCaptionExpanded + ? style.captionExpandedContainer + : style.captionContainer; - const captionStyle = shouldShowCaptionExpanded ? - style.captionExpanded : - getStylesFromColorScheme( style.caption, style.captionDark ); + const captionStyle = shouldShowCaptionExpanded + ? style.captionExpanded + : getStylesFromColorScheme( style.caption, style.captionDark ); return ( <> @@ -199,7 +211,7 @@ class GalleryImage extends Component { <> { isSelected && ( - +