diff --git a/.eslintrc.js b/.eslintrc.js index b5c735ca8b029b..9f7da03674a7df 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -14,7 +14,8 @@ const { version } = require( './package' ); * * @type {string} */ -const majorMinorRegExp = escapeRegExp( version.replace( /\.\d+$/, '' ) ) + '(\\.\\d+)?'; +const majorMinorRegExp = + escapeRegExp( version.replace( /\.\d+$/, '' ) ) + '(\\.\\d+)?'; /** * The list of patterns matching files used only for development purposes. @@ -29,7 +30,10 @@ const developmentFiles = [ module.exports = { root: true, - extends: [ 'plugin:@wordpress/eslint-plugin/recommended', 'plugin:eslint-comments/recommended' ], + extends: [ + 'plugin:@wordpress/eslint-plugin/recommended', + 'plugin:eslint-comments/recommended', + ], plugins: [ 'import' ], globals: { wp: 'off', @@ -44,37 +48,46 @@ module.exports = { // we'll get a `SyntaxError` (Invalid regular expression: \ at end of pattern) // here. That's why we use \\u002F in the regexes below. { - selector: 'ImportDeclaration[source.value=/^@wordpress\\u002F.+\\u002F/]', - message: 'Path access on WordPress dependencies is not allowed.', + selector: + 'ImportDeclaration[source.value=/^@wordpress\\u002F.+\\u002F/]', + message: + 'Path access on WordPress dependencies is not allowed.', }, { - selector: 'ImportDeclaration[source.value=/^react-spring(?!\\u002Fweb.cjs)/]', - message: 'The react-spring dependency must specify CommonJS bundle: react-spring/web.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 + '/]', - message: 'Deprecated functions must be removed before releasing this version.', + message: + 'Deprecated functions must be removed before releasing this version.', }, { selector: 'CallExpression[callee.name=/^(__|_n|_nx|_x)$/]:not([arguments.0.type=/^Literal|BinaryExpression$/])', - message: 'Translate function arguments must be string literals.', + message: + 'Translate function arguments must be string literals.', }, { selector: 'CallExpression[callee.name=/^(_n|_nx|_x)$/]:not([arguments.1.type=/^Literal|BinaryExpression$/])', - message: 'Translate function arguments must be string literals.', + message: + 'Translate function arguments must be string literals.', }, { selector: 'CallExpression[callee.name=_nx]:not([arguments.3.type=/^Literal|BinaryExpression$/])', - message: 'Translate function arguments must be string literals.', + message: + 'Translate function arguments must be string literals.', }, { - selector: 'CallExpression[callee.name=/^(__|_x|_n|_nx)$/] Literal[value=/\\.{3}/]', + selector: + 'CallExpression[callee.name=/^(__|_x|_n|_nx)$/] Literal[value=/\\.{3}/]', message: 'Use ellipsis character (โ€ฆ) in place of three dots', }, { @@ -83,22 +96,26 @@ module.exports = { message: 'Use `combineReducers` from `@wordpress/data`', }, { - selector: 'ImportDeclaration[source.value="lodash"] Identifier.imported[name="memoize"]', + selector: + 'ImportDeclaration[source.value="lodash"] Identifier.imported[name="memoize"]', message: 'Use memize instead of Lodashโ€™s memoize', }, { - selector: 'CallExpression[callee.object.name="page"][callee.property.name="waitFor"]', + selector: + 'CallExpression[callee.object.name="page"][callee.property.name="waitFor"]', message: 'Prefer page.waitForSelector instead.', }, { selector: 'JSXAttribute[name.name="id"][value.type="Literal"]', - message: 'Do not use string literals for IDs; use withInstanceId instead.', + message: + 'Do not use string literals for IDs; use withInstanceId instead.', }, { // Discourage the usage of `Math.random()` as it's a code smell // for UUID generation, for which we already have a higher-order // component: `withInstanceId`. - selector: 'CallExpression[callee.object.name="Math"][callee.property.name="random"]', + 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.)', }, @@ -119,14 +136,20 @@ module.exports = { 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', diff --git a/bin/api-docs/are-readmes-unstaged.js b/bin/api-docs/are-readmes-unstaged.js index b3f5c36e9e9b0e..c466d55bfb2e03 100644 --- a/bin/api-docs/are-readmes-unstaged.js +++ b/bin/api-docs/are-readmes-unstaged.js @@ -19,7 +19,9 @@ const getUnstagedFiles = () => const readmeFiles = getPackages().map( ( [ packageName ] ) => join( 'packages', packageName, 'README.md' ) ); -const unstagedReadmes = getUnstagedFiles().filter( ( element ) => readmeFiles.includes( element ) ); +const unstagedReadmes = getUnstagedFiles().filter( ( element ) => + readmeFiles.includes( element ) +); if ( unstagedReadmes.length > 0 ) { process.exitCode = 1; diff --git a/bin/api-docs/update-readmes.js b/bin/api-docs/update-readmes.js index 98a7a491619e34..ab1805c3fdeccd 100755 --- a/bin/api-docs/update-readmes.js +++ b/bin/api-docs/update-readmes.js @@ -16,7 +16,14 @@ getPackages().forEach( ( entry ) => { // Each target operates over the same file, so it needs to be processed synchronously, // as to make sure the processes don't overwrite each other. const { status, stderr } = spawnSync( - join( __dirname, '..', '..', 'node_modules', '.bin', 'docgen' ).replace( / /g, '\\ ' ), + join( + __dirname, + '..', + '..', + 'node_modules', + '.bin', + 'docgen' + ).replace( / /g, '\\ ' ), [ join( 'packages', packageName, path ), `--output packages/${ packageName }/README.md`, diff --git a/bin/commander.js b/bin/commander.js index b532ee1d865226..788019da2148b8 100755 --- a/bin/commander.js +++ b/bin/commander.js @@ -22,7 +22,8 @@ const uuid = require( 'uuid/v4' ); const gitRepoOwner = 'WordPress'; const gitRepoURL = 'https://github.com/' + gitRepoOwner + '/gutenberg.git'; const svnRepoURL = 'https://plugins.svn.wordpress.org/gutenberg'; -const releasePageURLPrefix = 'https://github.com/WordPress/gutenberg/releases/tag/'; +const releasePageURLPrefix = + 'https://github.com/WordPress/gutenberg/releases/tag/'; // Working Directories const gitWorkingDirectoryPath = path.join( os.tmpdir(), uuid() ); @@ -86,7 +87,11 @@ async function runStep( name, abortMessage, handler ) { await handler(); } catch ( exception ) { console.log( - error( 'The following error happened during the "' + warning( name ) + '" step:' ) + '\n\n', + error( + 'The following error happened during the "' + + warning( name ) + + '" step:' + ) + '\n\n', exception, error( '\n\n' + abortMessage ) ); @@ -142,7 +147,9 @@ async function runSvnRepositoryCloneStep( abortMessage ) { // Cloning the repository await runStep( 'Fetching the SVN repository', abortMessage, async () => { console.log( '>> Fetching the SVN repository' ); - runShellScript( 'svn checkout ' + svnRepoURL + '/trunk ' + svnWorkingDirectoryPath ); + runShellScript( + 'svn checkout ' + svnRepoURL + '/trunk ' + svnWorkingDirectoryPath + ); console.log( '>> The Gutenberg SVN repository has been successfully fetched in the following temporary folder: ' + success( svnWorkingDirectoryPath ) @@ -165,7 +172,9 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { const readmePath = svnWorkingDirectoryPath + '/readme.txt'; const previousReadmeFileContent = fs.readFileSync( readmePath, 'utf8' ); - const stableTag = previousReadmeFileContent.match( STABLE_TAG_REGEX )[ 0 ]; + const stableTag = previousReadmeFileContent.match( + STABLE_TAG_REGEX + )[ 0 ]; // Delete everything runShellScript( @@ -175,7 +184,9 @@ async function runUpdateTrunkContentStep( version, changelog, abortMessage ) { // Update the content using the plugin ZIP const gutenbergZipPath = gitWorkingDirectoryPath + '/gutenberg.zip'; - runShellScript( 'unzip ' + gutenbergZipPath + ' -d ' + svnWorkingDirectoryPath ); + runShellScript( + 'unzip ' + gutenbergZipPath + ' -d ' + svnWorkingDirectoryPath + ); // Replace the stable tag placeholder with the existing stable tag on the SVN repository. const newReadmeFileContent = fs.readFileSync( readmePath, 'utf8' ); @@ -233,7 +244,11 @@ async function runSvnTagStep( version, abortMessage ) { '"' ); - console.log( '>> The SVN ' + success( version ) + ' tag has been successfully created' ); + console.log( + '>> The SVN ' + + success( version ) + + ' tag has been successfully created' + ); } ); } @@ -245,29 +260,33 @@ 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 () => { - const readmePath = svnWorkingDirectoryPath + '/readme.txt'; - const readmeFileContent = fs.readFileSync( readmePath, 'utf8' ); - const newReadmeContent = readmeFileContent.replace( - STABLE_TAG_REGEX, - 'Stable tag: ' + version + '\n' - ); - fs.writeFileSync( readmePath, newReadmeContent ); + 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( + STABLE_TAG_REGEX, + 'Stable tag: ' + version + '\n' + ); + fs.writeFileSync( readmePath, newReadmeContent ); - // Commit the content changes - await askForConfirmationToContinue( - 'The stable version is updated in the readme.txt file. Commit the changes?', - true, - abortMessage - ); + // Commit the content changes + await askForConfirmationToContinue( + 'The stable version is updated in the readme.txt file. Commit the changes?', + true, + 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' ); - } ); + console.log( '>> Stable version updated successfully' ); + } + ); } /** @@ -278,15 +297,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; - } - } ); + [ gitWorkingDirectoryPath, svnWorkingDirectoryPath ].map( + async ( directoryPath ) => { + if ( fs.existsSync( directoryPath ) ) { + await rimraf( directoryPath, ( err ) => { + if ( err ) { + throw err; + } + } ); + } } - } ) + ) ); } ); } @@ -314,9 +335,21 @@ async function runReleaseBranchCreationStep( abortMessage ) { releaseBranch = 'release/' + ( parsedVersion.major + 1 ) + '.0'; 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'; + 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 ' + @@ -329,7 +362,9 @@ async function runReleaseBranchCreationStep( abortMessage ) { // Creating the release branch await simpleGit.checkoutLocalBranch( releaseBranch ); console.log( - '>> The local release branch ' + success( releaseBranch ) + ' has been successfully created.' + '>> The local release branch ' + + success( releaseBranch ) + + ' has been successfully created.' ); } ); @@ -352,7 +387,9 @@ const findReleaseBranchName = ( packageJsonPath ) => { const masterPackageJson = readJSONFile( packageJsonPath ); const masterParsedVersion = semver.parse( masterPackageJson.version ); - return 'release/' + masterParsedVersion.major + '.' + masterParsedVersion.minor; + return ( + 'release/' + masterParsedVersion.major + '.' + masterParsedVersion.minor + ); }; /** @@ -364,44 +401,55 @@ const findReleaseBranchName = ( packageJsonPath ) => { */ async function runReleaseBranchCheckoutStep( abortMessage ) { let releaseBranch, version; - await runStep( 'Getting into the release branch', abortMessage, async () => { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - const packageJsonPath = gitWorkingDirectoryPath + '/package.json'; - releaseBranch = findReleaseBranchName( packageJsonPath ); + await runStep( + 'Getting into the release branch', + abortMessage, + async () => { + const simpleGit = SimpleGit( gitWorkingDirectoryPath ); + const packageJsonPath = gitWorkingDirectoryPath + '/package.json'; + releaseBranch = findReleaseBranchName( packageJsonPath ); + + // Creating the release branch + await simpleGit.checkout( releaseBranch ); + console.log( + '>> The local release branch ' + + success( releaseBranch ) + + ' has been successfully checked out.' + ); - // Creating the release branch - await simpleGit.checkout( releaseBranch ); - console.log( - '>> The local release branch ' + - success( releaseBranch ) + - ' has been successfully checked out.' - ); + const releaseBranchPackageJson = readJSONFile( packageJsonPath ); + const releaseBranchParsedVersion = semver.parse( + releaseBranchPackageJson.version + ); - const releaseBranchPackageJson = readJSONFile( packageJsonPath ); - const releaseBranchParsedVersion = semver.parse( releaseBranchPackageJson.version ); + if ( + releaseBranchParsedVersion.prerelease && + releaseBranchParsedVersion.prerelease.length + ) { + version = + releaseBranchParsedVersion.major + + '.' + + releaseBranchParsedVersion.minor + + '.' + + releaseBranchParsedVersion.patch; + } else { + version = + releaseBranchParsedVersion.major + + '.' + + releaseBranchParsedVersion.minor + + '.' + + ( releaseBranchParsedVersion.patch + 1 ); + } - if ( releaseBranchParsedVersion.prerelease && releaseBranchParsedVersion.prerelease.length ) { - version = - releaseBranchParsedVersion.major + - '.' + - releaseBranchParsedVersion.minor + - '.' + - releaseBranchParsedVersion.patch; - } else { - version = - releaseBranchParsedVersion.major + - '.' + - releaseBranchParsedVersion.minor + - '.' + - ( releaseBranchParsedVersion.patch + 1 ); + await askForConfirmationToContinue( + 'The Version to release is ' + + success( version ) + + '. Proceed?', + true, + abortMessage + ); } - - await askForConfirmationToContinue( - 'The Version to release is ' + success( version ) + '. Proceed?', - true, - abortMessage - ); - } ); + ); return { version, @@ -420,7 +468,11 @@ async function runReleaseBranchCheckoutStep( abortMessage ) { * * @return {string} hash of the version bump commit. */ -async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessage ) { +async function runBumpPluginVersionAndCommitStep( + version, + changelog, + abortMessage +) { let commitHash; await runStep( 'Updating the plugin version', abortMessage, async () => { const simpleGit = SimpleGit( gitWorkingDirectoryPath ); @@ -433,16 +485,25 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa ...packageJson, version, }; - fs.writeFileSync( packageJsonPath, JSON.stringify( newPackageJson, null, '\t' ) + '\n' ); + fs.writeFileSync( + packageJsonPath, + JSON.stringify( newPackageJson, null, '\t' ) + '\n' + ); const newPackageLock = { ...packageLock, version, }; - fs.writeFileSync( packageLockPath, JSON.stringify( newPackageLock, null, '\t' ) + '\n' ); + 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 ) + content.replace( + ' * Version: ' + packageJson.version, + ' * Version: ' + version + ) ); console.log( '>> The plugin version has been updated successfully.' ); @@ -450,7 +511,10 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa const readmePath = gitWorkingDirectoryPath + '/readme.txt'; const readmeFileContent = fs.readFileSync( readmePath, 'utf8' ); const newReadmeContent = - readmeFileContent.substr( 0, readmeFileContent.indexOf( '== Changelog ==' ) ) + + readmeFileContent.substr( + 0, + readmeFileContent.indexOf( '== Changelog ==' ) + ) + '== Changelog ==\n\n' + `To read the changelog for Gutenberg ${ version }, please navigate to the release page.` + '\n'; @@ -462,9 +526,13 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa const changelogFileContent = fs.readFileSync( changelogPath, 'utf8' ); const versionHeader = '= ' + version + ' =\n\n'; const regexToSearch = /=\s([0-9]+\.[0-9]+\.[0-9]+)(-rc\.[0-9]+)?\s=\n\n/g; - let lastDifferentVersionMatch = regexToSearch.exec( changelogFileContent ); + let lastDifferentVersionMatch = regexToSearch.exec( + changelogFileContent + ); if ( lastDifferentVersionMatch[ 1 ] === stableVersion ) { - lastDifferentVersionMatch = regexToSearch.exec( changelogFileContent ); + lastDifferentVersionMatch = regexToSearch.exec( + changelogFileContent + ); } const newChangelogContent = '== Changelog ==\n\n' + @@ -487,9 +555,13 @@ async function runBumpPluginVersionAndCommitStep( version, changelog, abortMessa readmePath, changelogPath, ] ); - const commitData = await simpleGit.commit( 'Bump plugin version to ' + version ); + const commitData = await simpleGit.commit( + 'Bump plugin version to ' + version + ); commitHash = commitData.commit; - console.log( '>> The plugin version bump has been committed successfully.' ); + console.log( + '>> The plugin version bump has been committed successfully.' + ); } ); return commitHash; @@ -508,10 +580,14 @@ async function runPluginZIPCreationStep( abortMessage ) { true, abortMessage ); - runShellScript( '/bin/bash bin/build-plugin-zip.sh', gitWorkingDirectoryPath ); + runShellScript( + '/bin/bash bin/build-plugin-zip.sh', + gitWorkingDirectoryPath + ); console.log( - '>> The plugin ZIP has been built successfully. Path: ' + success( gutenbergZipPath ) + '>> The plugin ZIP has been built successfully. Path: ' + + success( gutenbergZipPath ) ); } ); } @@ -531,7 +607,11 @@ async function runCreateGitTagStep( version, abortMessage ) { abortMessage ); await simpleGit.addTag( 'v' + version ); - console.log( '>> The ' + success( 'v' + version ) + ' tag has been created successfully.' ); + console.log( + '>> The ' + + success( 'v' + version ) + + ' tag has been created successfully.' + ); } ); } @@ -542,16 +622,20 @@ async function runCreateGitTagStep( version, abortMessage ) { * @param {string} abortMessage Abort message. */ async function runPushGitChangesStep( releaseBranch, abortMessage ) { - await runStep( 'Pushing the release branch and the tag', abortMessage, async () => { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await askForConfirmationToContinue( - 'The release branch and the tag are going to be pushed to the remote repository. Continue?', - true, - abortMessage - ); - await simpleGit.push( 'origin', releaseBranch ); - await simpleGit.pushTags( 'origin' ); - } ); + await runStep( + 'Pushing the release branch and the tag', + abortMessage, + async () => { + const simpleGit = SimpleGit( gitWorkingDirectoryPath ); + await askForConfirmationToContinue( + 'The release branch and the tag are going to be pushed to the remote repository. Continue?', + true, + abortMessage + ); + await simpleGit.push( 'origin', releaseBranch ); + await simpleGit.pushTags( 'origin' ); + } + ); } /** @@ -587,7 +671,9 @@ async function runGithubReleaseStep( 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' ) + + success( + 'https://github.com/settings/tokens/new?scopes=repo,admin:org,write:packages' + ) + ' to create one.', }, ] ); @@ -608,7 +694,8 @@ async function runGithubReleaseStep( console.log( '>> The GitHub release has been created.' ); } ); - abortMessage = abortMessage + ' Make sure to remove the the GitHub release as well.'; + abortMessage = + abortMessage + ' Make sure to remove the the GitHub release as well.'; // Uploading the Gutenberg Zip to the release await runStep( 'Uploading the plugin ZIP', abortMessage, async () => { @@ -626,7 +713,10 @@ async function runGithubReleaseStep( console.log( '>> The plugin ZIP has been successfully uploaded.' ); } ); - console.log( '>> The GitHub release is available here: ' + success( release.html_url ) ); + console.log( + '>> The GitHub release is available here: ' + + success( release.html_url ) + ); return release; } @@ -637,21 +727,28 @@ async function runGithubReleaseStep( * @param {string} commitHash Commit to cherry-pick. * @param {string} abortMessage Abort message. */ -async function runCherrypickBumpCommitIntoMasterStep( commitHash, abortMessage ) { - await runStep( 'Cherry-picking the bump commit into master', abortMessage, async () => { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - await askForConfirmationToContinue( - 'The plugin is now released. Proceed with the version bump in the master branch?', - true, - abortMessage - ); - await simpleGit.fetch(); - await simpleGit.reset( 'hard' ); - await simpleGit.checkout( 'master' ); - await simpleGit.pull( 'origin', 'master' ); - await simpleGit.raw( [ 'cherry-pick', commitHash ] ); - await simpleGit.push( 'origin', 'master' ); - } ); +async function runCherrypickBumpCommitIntoMasterStep( + commitHash, + abortMessage +) { + await runStep( + 'Cherry-picking the bump commit into master', + abortMessage, + async () => { + const simpleGit = SimpleGit( gitWorkingDirectoryPath ); + await askForConfirmationToContinue( + 'The plugin is now released. Proceed with the version bump in the master branch?', + true, + abortMessage + ); + await simpleGit.fetch(); + await simpleGit.reset( 'hard' ); + await simpleGit.checkout( 'master' ); + await simpleGit.pull( 'origin', 'master' ); + await simpleGit.raw( [ 'cherry-pick', commitHash ] ); + await simpleGit.push( 'origin', 'master' ); + } + ); } /** @@ -683,7 +780,11 @@ async function releasePlugin( isRC = true ) { : await runReleaseBranchCheckoutStep( abortMessage ); // Bumping the version and commit. - const commitHash = await runBumpPluginVersionAndCommitStep( version, changelog, abortMessage ); + const commitHash = await runBumpPluginVersionAndCommitStep( + version, + changelog, + abortMessage + ); // Plugin ZIP creation await runPluginZIPCreationStep(); @@ -711,7 +812,8 @@ async function releasePlugin( isRC = true ) { success( commitHash ) + ' commit to the master branch.'; if ( ! isRC ) { - abortMessage += ' Make sure to perform the SVN release manually as well.'; + abortMessage += + ' Make sure to perform the SVN release manually as well.'; } // Cherry-picking the bump commit into master @@ -750,7 +852,9 @@ async function releasePlugin( isRC = true ) { program .command( 'release-plugin-rc' ) .alias( 'rc' ) - .description( 'Release an RC version of the plugin (supports only rc.1 for now)' ) + .description( + 'Release an RC version of the plugin (supports only rc.1 for now)' + ) .action( async () => { console.log( chalk.bold( '๐Ÿ’ƒ Time to release Gutenberg ๐Ÿ•บ\n\n' ), @@ -765,7 +869,9 @@ program '\n>> ๐ŸŽ‰ The Gutenberg version ' + success( release.name ) + ' has been successfully released.\n', - 'You can access the GitHub release here: ' + success( release.html_url ) + '\n', + 'You can access the GitHub release here: ' + + success( release.html_url ) + + '\n', 'Thanks for performing the release!' ); } ); @@ -785,8 +891,12 @@ program const release = await releasePlugin( false ); 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', + '\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." ); @@ -800,36 +910,47 @@ program */ async function runWordPressReleaseBranchSyncStep( abortMessage ) { const wordpressReleaseBranch = 'wp/trunk'; - await runStep( 'Getting into the WordPress release branch', abortMessage, async () => { - const simpleGit = SimpleGit( gitWorkingDirectoryPath ); - const packageJsonPath = gitWorkingDirectoryPath + '/package.json'; - const pluginReleaseBranch = findReleaseBranchName( packageJsonPath ); + await runStep( + 'Getting into the WordPress release branch', + abortMessage, + async () => { + const simpleGit = SimpleGit( gitWorkingDirectoryPath ); + const packageJsonPath = gitWorkingDirectoryPath + '/package.json'; + const pluginReleaseBranch = findReleaseBranchName( + packageJsonPath + ); - // Creating the release branch - await simpleGit.checkout( wordpressReleaseBranch ); - console.log( - '>> The local release branch ' + - success( wordpressReleaseBranch ) + - ' has been successfully checked out.' - ); + // Creating the release branch + await simpleGit.checkout( wordpressReleaseBranch ); + 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?`, - true, - abortMessage - ); + await askForConfirmationToContinue( + `The branch is ready for sync with the latest plugin release changes applied to "${ pluginReleaseBranch }". Proceed?`, + true, + 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.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.' + ); + } + ); return { releaseBranch: wordpressReleaseBranch, @@ -881,7 +1002,10 @@ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { } // A minor version bump required. Proceed to the next line. - if ( line.startsWith( '### New Feature' ) || line.startsWith( '### Deprecation' ) ) { + if ( + line.startsWith( '### New Feature' ) || + line.startsWith( '### Deprecation' ) + ) { versionBump = 'minor'; continue; } @@ -891,9 +1015,16 @@ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { 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; + 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, @@ -904,25 +1035,39 @@ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { } ) ); - const changelogsToUpdate = processedPackages.filter( ( { nextVersion } ) => nextVersion ); + const changelogsToUpdate = processedPackages.filter( + ( { nextVersion } ) => nextVersion + ); if ( changelogsToUpdate.length === 0 ) { console.log( '>> No changes in CHANGELOG files detected.' ); return; } - console.log( '>> Recommended version bumps based on the changes detected in CHANGELOG files:' ); + console.log( + '>> Recommended version bumps based on the changes detected in CHANGELOG files:' + ); 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( @@ -933,7 +1078,9 @@ async function updatePackageChangelogs( minimumVersionBump, abortMessage ) { const simpleGit = SimpleGit( gitWorkingDirectoryPath ); await simpleGit.add( './*' ); await simpleGit.commit( 'Update changelog files' ); - console.log( '>> Changelog files changes have been committed successfully.' ); + console.log( + '>> Changelog files changes have been committed successfully.' + ); } /** @@ -952,7 +1099,9 @@ async function prepublishPackages( minimumVersionBump ) { await runGitRepositoryCloneStep( abortMessage ); // Checking out the WordPress release branch and doing sync with the last plugin release. - const { releaseBranch } = await runWordPressReleaseBranchSyncStep( abortMessage ); + const { releaseBranch } = await runWordPressReleaseBranchSyncStep( + abortMessage + ); await updatePackageChangelogs( minimumVersionBump, abortMessage ); @@ -967,7 +1116,9 @@ async function prepublishPackages( minimumVersionBump ) { program .command( 'prepublish-packages-stable' ) .alias( 'npm-stable' ) - .description( 'Prepublish to npm steps for the next stable version of WordPress packages' ) + .description( + 'Prepublish to npm steps for the next stable version of WordPress packages' + ) .action( async () => { console.log( chalk.bold( '๐Ÿ’ƒ Time to publish WordPress packages to npm ๐Ÿ•บ\n\n' ), diff --git a/bin/generate-public-grammar.js b/bin/generate-public-grammar.js index 28f8b43859a988..0c2bc74fc42241 100755 --- a/bin/generate-public-grammar.js +++ b/bin/generate-public-grammar.js @@ -18,7 +18,11 @@ 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 ) { @@ -41,7 +45,11 @@ function flatten( expression ) { '[' + ( expression.inverted ? '^' : '' ) + expression.parts - .map( ( part ) => escape( Array.isArray( part ) ? part.join( '-' ) : part ) ) + .map( ( part ) => + escape( + Array.isArray( part ) ? part.join( '-' ) : part + ) + ) .join( '' ) + ']' + ( expression.ignoreCase ? 'i' : '' ) @@ -80,7 +88,10 @@ function flatten( expression ) { return `
${ expression.rules.map( flatten ).join( '' ) }
`; case 'rule': expression.expression.isRuleTop = true; - const displayName = expression.expression.type === 'named' ? expression.expression.name : ''; + const displayName = + expression.expression.type === 'named' + ? expression.expression.name + : ''; return ( `
${ displayName }
` + `
${ expression.name }
= ` + diff --git a/bin/packages/build-worker.js b/bin/packages/build-worker.js index 622b712a97f3f0..e7f2b6f058fbda 100644 --- a/bin/packages/build-worker.js +++ b/bin/packages/build-worker.js @@ -84,8 +84,14 @@ function getBuildPath( file, buildFolder ) { */ const BUILD_TASK_BY_EXTENSION = { async '.scss'( file ) { - const outputFile = getBuildPath( file.replace( '.scss', '.css' ), 'build-style' ); - const outputFileRTL = getBuildPath( file.replace( '.scss', '-rtl.css' ), 'build-style' ); + const outputFile = getBuildPath( + file.replace( '.scss', '.css' ), + 'build-style' + ); + const outputFileRTL = getBuildPath( + file.replace( '.scss', '-rtl.css' ), + 'build-style' + ); const [ , contents ] = await Promise.all( [ makeDir( path.dirname( outputFile ) ), @@ -96,20 +102,33 @@ const BUILD_TASK_BY_EXTENSION = { file, includePaths: [ path.join( PACKAGES_DIR, 'base-styles' ) ], data: - [ 'colors', 'breakpoints', 'variables', 'mixins', 'animations', 'z-index' ] + [ + 'colors', + 'breakpoints', + 'variables', + 'mixins', + 'animations', + 'z-index', + ] .map( ( imported ) => `@import "${ imported }";` ) .join( ' ' ) + contents, } ); - const result = await postcss( require( './post-css-config' ) ).process( builtSass.css, { - from: 'src/app.css', - to: 'dest/app.css', - } ); - - const resultRTL = await postcss( [ require( 'rtlcss' )() ] ).process( result.css, { - from: 'src/app.css', - to: 'dest/app.css', - } ); + const result = await postcss( require( './post-css-config' ) ).process( + builtSass.css, + { + from: 'src/app.css', + to: 'dest/app.css', + } + ); + + const resultRTL = await postcss( [ require( 'rtlcss' )() ] ).process( + result.css, + { + from: 'src/app.css', + to: 'dest/app.css', + } + ); await Promise.all( [ writeFile( outputFile, result.css ), @@ -118,7 +137,9 @@ const BUILD_TASK_BY_EXTENSION = { }, async '.js'( file ) { - for ( const [ environment, buildDir ] of Object.entries( JS_ENVIRONMENTS ) ) { + for ( const [ environment, buildDir ] of Object.entries( + JS_ENVIRONMENTS + ) ) { const destPath = getBuildPath( file, buildDir ); const babelOptions = getBabelConfig( environment, @@ -131,10 +152,16 @@ const BUILD_TASK_BY_EXTENSION = { ] ); await Promise.all( [ - writeFile( destPath + '.map', JSON.stringify( transformed.map ) ), + writeFile( + destPath + '.map', + JSON.stringify( transformed.map ) + ), writeFile( destPath, - transformed.code + '\n//# sourceMappingURL=' + path.basename( destPath ) + '.map' + transformed.code + + '\n//# sourceMappingURL=' + + path.basename( destPath ) + + '.map' ), ] ); } diff --git a/bin/packages/build.js b/bin/packages/build.js index 8eceb6c6dbbe59..8d1a0c9cc17875 100755 --- a/bin/packages/build.js +++ b/bin/packages/build.js @@ -57,7 +57,9 @@ function createStyleEntryTransform() { } packages.add( packageName ); - const entries = await glob( path.resolve( PACKAGES_DIR, packageName, 'src/*.scss' ) ); + const entries = await glob( + path.resolve( PACKAGES_DIR, packageName, 'src/*.scss' ) + ); entries.forEach( ( entry ) => this.push( entry ) ); callback(); }, @@ -78,7 +80,9 @@ function createBlockJsonEntryTransform() { return new Transform( { objectMode: true, async transform( file, encoding, callback ) { - const matches = /block-library[\/\\]src[\/\\](.*)[\/\\]block.json$/.exec( file ); + const matches = /block-library[\/\\]src[\/\\](.*)[\/\\]block.json$/.exec( + file + ); const blockName = matches ? matches[ 1 ] : undefined; // Only block.json files in the block-library folder are subject to this transform. @@ -109,7 +113,9 @@ 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, @@ -119,10 +125,17 @@ if ( files.length ) { bar.tick( 0 ); - stream = glob.stream( [ `${ PACKAGES_DIR }/*/src/**/*.js`, `${ PACKAGES_DIR }/*/src/*.scss` ], { - ignore: [ `**/benchmark/**`, `**/{__mocks__,__tests__,test}/**`, `**/{storybook,stories}/**` ], - onlyFiles: true, - } ); + stream = glob.stream( + [ `${ PACKAGES_DIR }/*/src/**/*.js`, `${ PACKAGES_DIR }/*/src/*.scss` ], + { + ignore: [ + `**/benchmark/**`, + `**/{__mocks__,__tests__,test}/**`, + `**/{storybook,stories}/**`, + ], + onlyFiles: true, + } + ); // Pause to avoid data flow which would begin on the `data` event binding, // but should wait until worker processing below. diff --git a/bin/packages/watch.js b/bin/packages/watch.js index 8518e66f3a2a83..8d5e650f6bac3c 100644 --- a/bin/packages/watch.js +++ b/bin/packages/watch.js @@ -31,7 +31,8 @@ const isSourceFile = ( filename ) => { ! [ /\/(benchmark|__mocks__|__tests__|test|storybook|stories)\/.+.js$/, /.\.(spec|test)\.js$/, - ].some( ( regex ) => regex.test( filename ) ) && /.\.(js|json|scss)$/.test( filename ) + ].some( ( regex ) => regex.test( filename ) ) && + /.\.(js|json|scss)$/.test( filename ) ); }; @@ -41,29 +42,44 @@ getPackages().forEach( ( p ) => { const srcDir = path.resolve( p, 'src' ); try { fs.accessSync( srcDir, fs.F_OK ); - watch( path.resolve( p, 'src' ), { recursive: true }, ( event, filename ) => { - if ( ! isSourceFile( filename ) ) { - return; - } + watch( + path.resolve( p, 'src' ), + { recursive: true }, + ( event, filename ) => { + if ( ! isSourceFile( filename ) ) { + return; + } - const filePath = path.resolve( srcDir, filename ); - if ( event === 'update' && exists( filePath ) ) { - // eslint-disable-next-line no-console - console.log( chalk.green( '->' ), `${ event }: ${ filename }` ); - rebuild( filePath ); - } else { - const buildFile = path.resolve( srcDir, '..', 'build', filename ); - try { - fs.unlinkSync( buildFile ); - process.stdout.write( - chalk.red( ' \u2022 ' ) + - path.relative( path.resolve( srcDir, '..', '..' ), buildFile ) + - ' (deleted)' + - '\n' + const filePath = path.resolve( srcDir, filename ); + if ( event === 'update' && exists( filePath ) ) { + // eslint-disable-next-line no-console + console.log( + chalk.green( '->' ), + `${ event }: ${ filename }` + ); + rebuild( filePath ); + } else { + const buildFile = path.resolve( + srcDir, + '..', + 'build', + filename ); - } catch ( e ) {} + try { + fs.unlinkSync( buildFile ); + process.stdout.write( + chalk.red( ' \u2022 ' ) + + path.relative( + path.resolve( srcDir, '..', '..' ), + buildFile + ) + + ' (deleted)' + + '\n' + ); + } catch ( e ) {} + } } - } ); + ); } catch ( e ) { // doesn't exist } diff --git a/docs/tool/are-data-files-unstaged.js b/docs/tool/are-data-files-unstaged.js index 14e91df6038c03..38f659ec9bb0c7 100644 --- a/docs/tool/are-data-files-unstaged.js +++ b/docs/tool/are-data-files-unstaged.js @@ -17,9 +17,14 @@ const getUnstagedFiles = () => .filter( ( element ) => '' !== element ); const readmeFiles = getPackages().map( ( [ packageName ] ) => - `docs/designers-developers/developers/data/data-${ packageName.replace( '/', '-' ) }.md` + `docs/designers-developers/developers/data/data-${ packageName.replace( + '/', + '-' + ) }.md` +); +const unstagedReadmes = getUnstagedFiles().filter( ( element ) => + readmeFiles.includes( element ) ); -const unstagedReadmes = getUnstagedFiles().filter( ( element ) => readmeFiles.includes( element ) ); if ( unstagedReadmes.length > 0 ) { process.exitCode = 1; diff --git a/docs/tool/manifest.js b/docs/tool/manifest.js index adf9ff6488ff51..90c050388a0c50 100644 --- a/docs/tool/manifest.js +++ b/docs/tool/manifest.js @@ -85,9 +85,13 @@ function generateRootManifestFromTOCItems( items, parent = null ) { parent, } ); if ( Array.isArray( children ) && children.length ) { - pageItems = pageItems.concat( generateRootManifestFromTOCItems( children, slug ) ); + pageItems = pageItems.concat( + generateRootManifestFromTOCItems( children, slug ) + ); } else if ( children === '{{components}}' ) { - pageItems = pageItems.concat( getComponentManifest( componentPaths ) ); + pageItems = pageItems.concat( + getComponentManifest( componentPaths ) + ); } else if ( children === '{{packages}}' ) { pageItems = pageItems.concat( getPackageManifest( packagePaths ) ); } diff --git a/docs/tool/update-data.js b/docs/tool/update-data.js index 63b66bbfe8fc76..89f0fc614f1c50 100644 --- a/docs/tool/update-data.js +++ b/docs/tool/update-data.js @@ -17,7 +17,14 @@ getPackages().forEach( ( entry ) => { // until docgen provides a way to update many tokens at once, we need to make sure // the output file is updated before starting the second pass for the next token. const { status, stderr } = spawnSync( - join( __dirname, '..', '..', 'node_modules', '.bin', 'docgen' ).replace( / /g, '\\ ' ), + join( + __dirname, + '..', + '..', + 'node_modules', + '.bin', + 'docgen' + ).replace( / /g, '\\ ' ), [ target, `--output docs/designers-developers/developers/data/data-${ packageName.replace( diff --git a/packages/a11y/src/index.js b/packages/a11y/src/index.js index cb79e767bb9c36..97d10c65920202 100644 --- a/packages/a11y/src/index.js +++ b/packages/a11y/src/index.js @@ -15,7 +15,9 @@ import filterMessage from './filterMessage'; */ export const setup = function() { const containerPolite = document.getElementById( 'a11y-speak-polite' ); - const containerAssertive = document.getElementById( 'a11y-speak-assertive' ); + const containerAssertive = document.getElementById( + 'a11y-speak-assertive' + ); if ( containerPolite === null ) { addContainer( 'polite' ); @@ -56,7 +58,9 @@ export const speak = function( message, ariaLive ) { message = filterMessage( message ); const containerPolite = document.getElementById( 'a11y-speak-polite' ); - const containerAssertive = document.getElementById( 'a11y-speak-assertive' ); + const containerAssertive = document.getElementById( + 'a11y-speak-assertive' + ); if ( containerAssertive && 'assertive' === ariaLive ) { containerAssertive.textContent = message; diff --git a/packages/a11y/src/test/addContainer.test.js b/packages/a11y/src/test/addContainer.test.js index e6c722078f74f3..6ebf062237c9c0 100644 --- a/packages/a11y/src/test/addContainer.test.js +++ b/packages/a11y/src/test/addContainer.test.js @@ -13,7 +13,9 @@ describe( 'addContainer', () => { expect( container.id ).toBe( 'a11y-speak-polite' ); expect( container.getAttribute( 'style' ) ).not.toBeNull(); expect( container.getAttribute( 'aria-live' ) ).toBe( 'polite' ); - expect( container.getAttribute( 'aria-relevant' ) ).toBe( 'additions text' ); + expect( container.getAttribute( 'aria-relevant' ) ).toBe( + 'additions text' + ); expect( container.getAttribute( 'aria-atomic' ) ).toBe( 'true' ); } ); } ); @@ -27,7 +29,9 @@ describe( 'addContainer', () => { expect( container.id ).toBe( 'a11y-speak-assertive' ); expect( container.getAttribute( 'style' ) ).not.toBeNull(); expect( container.getAttribute( 'aria-live' ) ).toBe( 'assertive' ); - expect( container.getAttribute( 'aria-relevant' ) ).toBe( 'additions text' ); + expect( container.getAttribute( 'aria-relevant' ) ).toBe( + 'additions text' + ); expect( container.getAttribute( 'aria-atomic' ) ).toBe( 'true' ); } ); } ); @@ -41,7 +45,9 @@ describe( 'addContainer', () => { expect( container.id ).toBe( 'a11y-speak-polite' ); expect( container.getAttribute( 'style' ) ).not.toBeNull(); expect( container.getAttribute( 'aria-live' ) ).toBe( 'polite' ); - expect( container.getAttribute( 'aria-relevant' ) ).toBe( 'additions text' ); + expect( container.getAttribute( 'aria-relevant' ) ).toBe( + 'additions text' + ); expect( container.getAttribute( 'aria-atomic' ) ).toBe( 'true' ); } ); } ); diff --git a/packages/a11y/src/test/index.test.js b/packages/a11y/src/test/index.test.js index 08c9489bed2ae3..9888f9adb3a145 100644 --- a/packages/a11y/src/test/index.test.js +++ b/packages/a11y/src/test/index.test.js @@ -53,7 +53,9 @@ describe( 'speak', () => { it( 'should set the textcontent of the assertive aria-live region', () => { speak( 'assertive message', 'assertive' ); expect( containerPolite.textContent ).toBe( '' ); - expect( containerAssertive.textContent ).toBe( 'assertive message' ); + expect( containerAssertive.textContent ).toBe( + 'assertive message' + ); } ); } ); @@ -72,13 +74,17 @@ describe( 'speak', () => { afterEach( () => { setup(); - containerAssertive = document.getElementById( 'a11y-speak-assertive' ); + containerAssertive = document.getElementById( + 'a11y-speak-assertive' + ); } ); it( 'should set the textcontent of the polite aria-live region', () => { speak( 'message', 'assertive' ); expect( containerPolite.textContent ).toBe( 'message' ); - expect( document.getElementById( 'a11y-speak-assertive' ) ).toBe( null ); + expect( document.getElementById( 'a11y-speak-assertive' ) ).toBe( + null + ); } ); } ); @@ -91,20 +97,29 @@ describe( 'speak', () => { afterEach( () => { setup(); containerPolite = document.getElementById( 'a11y-speak-polite' ); - containerAssertive = document.getElementById( 'a11y-speak-assertive' ); + containerAssertive = document.getElementById( + 'a11y-speak-assertive' + ); } ); it( 'should set the textcontent of the polite aria-live region', () => { - expect( document.getElementById( 'a11y-speak-polite' ) ).toBe( null ); - expect( document.getElementById( 'a11y-speak-assertive' ) ).toBe( null ); + expect( document.getElementById( 'a11y-speak-polite' ) ).toBe( + null + ); + expect( document.getElementById( 'a11y-speak-assertive' ) ).toBe( + null + ); } ); } ); describe( 'setup when the elements already exist', () => { it( 'should not create the aria live regions again', () => { - const before = document.getElementsByClassName( 'a11y-speak-region' ).length; + const before = document.getElementsByClassName( + 'a11y-speak-region' + ).length; setup(); - const after = document.getElementsByClassName( 'a11y-speak-region' ).length; + const after = document.getElementsByClassName( 'a11y-speak-region' ) + .length; expect( before ).toBe( after ); } ); diff --git a/packages/annotations/src/block/index.js b/packages/annotations/src/block/index.js index 31c1a57e261ab1..c27c170b2d64a1 100644 --- a/packages/annotations/src/block/index.js +++ b/packages/annotations/src/block/index.js @@ -12,9 +12,9 @@ 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 @@ -26,4 +26,8 @@ const addAnnotationClassName = ( OriginalComponent ) => { } )( OriginalComponent ); }; -addFilter( 'editor.BlockListBlock', 'core/annotations', addAnnotationClassName ); +addFilter( + 'editor.BlockListBlock', + 'core/annotations', + addAnnotationClassName +); diff --git a/packages/annotations/src/format/annotation.js b/packages/annotations/src/format/annotation.js index ba9a39633d84e4..9ce2a2bd6d456f 100644 --- a/packages/annotations/src/format/annotation.js +++ b/packages/annotations/src/format/annotation.js @@ -69,7 +69,9 @@ function retrieveAnnotationPositions( formats ) { formats.forEach( ( characterFormats, i ) => { characterFormats = characterFormats || []; - characterFormats = characterFormats.filter( ( format ) => format.type === FORMAT_NAME ); + characterFormats = characterFormats.filter( + ( format ) => format.type === FORMAT_NAME + ); characterFormats.forEach( ( format ) => { let { id } = format.attributes; id = id.replace( ANNOTATION_ATTRIBUTE_PREFIX, '' ); @@ -116,7 +118,11 @@ function updateAnnotationsWithPositions( const { start, end } = currentAnnotation; if ( start !== position.start || end !== position.end ) { - updateAnnotationRange( currentAnnotation.id, position.start, position.end ); + updateAnnotationRange( + currentAnnotation.id, + position.start, + position.end + ); } } ); } @@ -138,7 +144,9 @@ export const annotation = { { richTextIdentifier, blockClientId } ) { return { - annotations: select( STORE_KEY ).__experimentalGetAnnotationsForRichText( + annotations: select( + STORE_KEY + ).__experimentalGetAnnotationsForRichText( blockClientId, richTextIdentifier ), @@ -157,14 +165,20 @@ export const annotation = { }, __experimentalGetPropsForEditableTreeChangeHandler( dispatch ) { return { - removeAnnotation: dispatch( STORE_KEY ).__experimentalRemoveAnnotation, - updateAnnotationRange: dispatch( STORE_KEY ).__experimentalUpdateAnnotationRange, + removeAnnotation: dispatch( STORE_KEY ) + .__experimentalRemoveAnnotation, + updateAnnotationRange: dispatch( STORE_KEY ) + .__experimentalUpdateAnnotationRange, }; }, __experimentalCreateOnChangeEditableValue( props ) { return ( formats ) => { const positions = retrieveAnnotationPositions( formats ); - const { removeAnnotation, updateAnnotationRange, annotations } = props; + const { + removeAnnotation, + updateAnnotationRange, + annotations, + } = props; updateAnnotationsWithPositions( annotations, positions, { removeAnnotation, diff --git a/packages/annotations/src/store/actions.js b/packages/annotations/src/store/actions.js index 7ad35afa99b295..f5d5b8cf208e55 100644 --- a/packages/annotations/src/store/actions.js +++ b/packages/annotations/src/store/actions.js @@ -72,7 +72,11 @@ export function __experimentalRemoveAnnotation( annotationId ) { * * @return {Object} Action object. */ -export function __experimentalUpdateAnnotationRange( annotationId, start, end ) { +export function __experimentalUpdateAnnotationRange( + annotationId, + start, + end +) { return { type: 'ANNOTATION_UPDATE_RANGE', annotationId, diff --git a/packages/annotations/src/store/reducer.js b/packages/annotations/src/store/reducer.js index 2fcd95118e45b4..0756c3f3d8eac5 100644 --- a/packages/annotations/src/store/reducer.js +++ b/packages/annotations/src/store/reducer.js @@ -15,7 +15,9 @@ import { get, isNumber, mapValues } from 'lodash'; function filterWithReference( collection, predicate ) { const filteredCollection = collection.filter( predicate ); - return collection.length === filteredCollection.length ? collection : filteredCollection; + return collection.length === filteredCollection.length + ? collection + : filteredCollection; } /** @@ -26,7 +28,9 @@ function filterWithReference( collection, predicate ) { */ function isValidAnnotationRange( annotation ) { return ( - isNumber( annotation.start ) && isNumber( annotation.end ) && annotation.start <= annotation.end + isNumber( annotation.start ) && + isNumber( annotation.end ) && + annotation.start <= annotation.end ); } @@ -51,7 +55,10 @@ export function annotations( state = {}, action ) { range: action.range, }; - if ( newAnnotation.selector === 'range' && ! isValidAnnotationRange( newAnnotation.range ) ) { + if ( + newAnnotation.selector === 'range' && + ! isValidAnnotationRange( newAnnotation.range ) + ) { return state; } @@ -59,43 +66,54 @@ export function annotations( state = {}, action ) { return { ...state, - [ blockClientId ]: [ ...previousAnnotationsForBlock, newAnnotation ], + [ blockClientId ]: [ + ...previousAnnotationsForBlock, + newAnnotation, + ], }; case 'ANNOTATION_REMOVE': return mapValues( state, ( annotationsForBlock ) => { - return filterWithReference( annotationsForBlock, ( annotation ) => { - return annotation.id !== action.annotationId; - } ); + return filterWithReference( + annotationsForBlock, + ( annotation ) => { + return annotation.id !== action.annotationId; + } + ); } ); case 'ANNOTATION_UPDATE_RANGE': return mapValues( state, ( annotationsForBlock ) => { let hasChangedRange = false; - const newAnnotations = annotationsForBlock.map( ( annotation ) => { - if ( annotation.id === action.annotationId ) { - hasChangedRange = true; - return { - ...annotation, - range: { - start: action.start, - end: action.end, - }, - }; - } + const newAnnotations = annotationsForBlock.map( + ( annotation ) => { + if ( annotation.id === action.annotationId ) { + hasChangedRange = true; + return { + ...annotation, + range: { + start: action.start, + end: action.end, + }, + }; + } - return annotation; - } ); + return annotation; + } + ); return hasChangedRange ? newAnnotations : annotationsForBlock; } ); case 'ANNOTATION_REMOVE_SOURCE': return mapValues( state, ( annotationsForBlock ) => { - return filterWithReference( annotationsForBlock, ( annotation ) => { - return annotation.source !== action.source; - } ); + return filterWithReference( + annotationsForBlock, + ( annotation ) => { + return annotation.source !== action.source; + } + ); } ); } diff --git a/packages/annotations/src/store/selectors.js b/packages/annotations/src/store/selectors.js index 8a3a34715a6310..fa7b97e259ab77 100644 --- a/packages/annotations/src/store/selectors.js +++ b/packages/annotations/src/store/selectors.js @@ -32,7 +32,10 @@ export const __experimentalGetAnnotationsForBlock = createSelector( ( state, blockClientId ) => [ get( state, blockClientId, EMPTY_ARRAY ) ] ); -export const __experimentalGetAllAnnotationsForBlock = function( state, blockClientId ) { +export const __experimentalGetAllAnnotationsForBlock = function( + state, + blockClientId +) { return get( state, blockClientId, EMPTY_ARRAY ); }; @@ -53,7 +56,8 @@ export const __experimentalGetAnnotationsForRichText = createSelector( return get( state, blockClientId, [] ) .filter( ( annotation ) => { return ( - annotation.selector === 'range' && richTextIdentifier === annotation.richTextIdentifier + annotation.selector === 'range' && + richTextIdentifier === annotation.richTextIdentifier ); } ) .map( ( annotation ) => { diff --git a/packages/api-fetch/src/index.js b/packages/api-fetch/src/index.js index a25ec7992ff948..9e7edc985709ed 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -14,7 +14,10 @@ import namespaceEndpointMiddleware from './middlewares/namespace-endpoint'; import httpV1Middleware from './middlewares/http-v1'; import userLocaleMiddleware from './middlewares/user-locale'; import mediaUploadMiddleware from './middlewares/media-upload'; -import { parseResponseAndNormalizeError, parseAndThrowError } from './utils/response'; +import { + parseResponseAndNormalizeError, + parseAndThrowError, +} from './utils/response'; /** * Default set of header values which should be sent with every request unless @@ -88,8 +91,12 @@ const defaultFetchHandler = ( nextOptions ) => { ( value ) => Promise.resolve( value ) .then( checkStatus ) - .catch( ( response ) => parseAndThrowError( response, parse ) ) - .then( ( response ) => parseResponseAndNormalizeError( response, parse ) ), + .catch( ( response ) => + parseAndThrowError( response, parse ) + ) + .then( ( response ) => + parseResponseAndNormalizeError( response, parse ) + ), () => { throw { code: 'fetch_error', diff --git a/packages/api-fetch/src/middlewares/fetch-all-middleware.js b/packages/api-fetch/src/middlewares/fetch-all-middleware.js index f0ef36977d6c2c..2fa1b3b3629aab 100644 --- a/packages/api-fetch/src/middlewares/fetch-all-middleware.js +++ b/packages/api-fetch/src/middlewares/fetch-all-middleware.js @@ -32,8 +32,10 @@ const getNextPageUrl = ( response ) => { }; const requestContainsUnboundedQuery = ( options ) => { - const pathIsUnbounded = options.path && options.path.indexOf( 'per_page=-1' ) !== -1; - const urlIsUnbounded = options.url && options.url.indexOf( 'per_page=-1' ) !== -1; + const pathIsUnbounded = + options.path && options.path.indexOf( 'per_page=-1' ) !== -1; + const urlIsUnbounded = + options.url && options.url.indexOf( 'per_page=-1' ) !== -1; return pathIsUnbounded || urlIsUnbounded; }; diff --git a/packages/api-fetch/src/middlewares/media-upload.js b/packages/api-fetch/src/middlewares/media-upload.js index 4d617cd0683c5d..5668c18cfbd792 100644 --- a/packages/api-fetch/src/middlewares/media-upload.js +++ b/packages/api-fetch/src/middlewares/media-upload.js @@ -6,7 +6,10 @@ 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. @@ -49,8 +52,14 @@ function mediaUploadMiddleware( options, next ) { return next( { ...options, parse: false } ) .catch( ( response ) => { - const attachmentId = response.headers.get( 'x-wp-upload-attachment-id' ); - if ( response.status >= 500 && response.status < 600 && attachmentId ) { + const attachmentId = response.headers.get( + 'x-wp-upload-attachment-id' + ); + if ( + response.status >= 500 && + response.status < 600 && + attachmentId + ) { return postProcess( attachmentId ).catch( () => { if ( options.parse !== false ) { return Promise.reject( { @@ -66,7 +75,9 @@ function mediaUploadMiddleware( options, next ) { } return parseAndThrowError( response, options.parse ); } ) - .then( ( response ) => parseResponseAndNormalizeError( response, options.parse ) ); + .then( ( response ) => + parseResponseAndNormalizeError( response, options.parse ) + ); } export default mediaUploadMiddleware; diff --git a/packages/api-fetch/src/middlewares/namespace-endpoint.js b/packages/api-fetch/src/middlewares/namespace-endpoint.js index ef24a3dea93120..406c12926dd976 100644 --- a/packages/api-fetch/src/middlewares/namespace-endpoint.js +++ b/packages/api-fetch/src/middlewares/namespace-endpoint.js @@ -2,7 +2,10 @@ 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 5a141c81413047..573a6c80b384ea 100644 --- a/packages/api-fetch/src/middlewares/preloading.js +++ b/packages/api-fetch/src/middlewares/preloading.js @@ -53,7 +53,11 @@ 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/root-url.js b/packages/api-fetch/src/middlewares/root-url.js index 92b50523642fcc..8d2ad636285476 100644 --- a/packages/api-fetch/src/middlewares/root-url.js +++ b/packages/api-fetch/src/middlewares/root-url.js @@ -20,7 +20,10 @@ const createRootURLMiddleware = ( rootURL ) => ( options, next ) => { // API root may already include query parameter prefix if site is // configured to use plain permalinks. - if ( 'string' === typeof apiRoot && -1 !== apiRoot.indexOf( '?' ) ) { + if ( + 'string' === typeof apiRoot && + -1 !== apiRoot.indexOf( '?' ) + ) { path = path.replace( '?', '&' ); } diff --git a/packages/api-fetch/src/middlewares/test/preloading.js b/packages/api-fetch/src/middlewares/test/preloading.js index 42c00696e1849d..167e2e4eb32d65 100644 --- a/packages/api-fetch/src/middlewares/test/preloading.js +++ b/packages/api-fetch/src/middlewares/test/preloading.js @@ -36,7 +36,9 @@ describe( 'Preloading Middleware', () => { body, }, }; - const preloadingMiddleware = createPreloadingMiddleware( preloadedData ); + const preloadingMiddleware = createPreloadingMiddleware( + preloadedData + ); const requestOptions = { method: 'GET', path: 'wp/v2/posts', @@ -54,7 +56,9 @@ describe( 'Preloading Middleware', () => { 'wp/v2/demo-reverse-alphabetical?foo=bar&baz=quux': { body }, 'wp/v2/demo-alphabetical?baz=quux&foo=bar': { body }, }; - const preloadingMiddleware = createPreloadingMiddleware( preloadedData ); + const preloadingMiddleware = createPreloadingMiddleware( + preloadedData + ); let requestOptions = { method: 'GET', @@ -79,7 +83,9 @@ describe( 'Preloading Middleware', () => { [ 'method empty', { [ method ]: {} } ], ] )( '%s', ( label, preloadedData ) => { it( 'should move to the next middleware if no preloaded data', () => { - const prelooadingMiddleware = createPreloadingMiddleware( preloadedData ); + const prelooadingMiddleware = createPreloadingMiddleware( + preloadedData + ); const requestOptions = { method, path: 'wp/v2/posts', diff --git a/packages/api-fetch/src/middlewares/test/root-url.js b/packages/api-fetch/src/middlewares/test/root-url.js index 3480cddc532b06..921e6af8bb01e9 100644 --- a/packages/api-fetch/src/middlewares/test/root-url.js +++ b/packages/api-fetch/src/middlewares/test/root-url.js @@ -14,7 +14,9 @@ describe( 'Root URL middleware', () => { path: '/wp/v2/posts', }; const callback = ( options ) => { - expect( options.url ).toBe( 'http://wp.org/wp-admin/rest/wp/v2/posts' ); + expect( options.url ).toBe( + 'http://wp.org/wp-admin/rest/wp/v2/posts' + ); }; rootURLMiddleware( requestOptions, callback ); diff --git a/packages/api-fetch/src/middlewares/test/user-locale.js b/packages/api-fetch/src/middlewares/test/user-locale.js index 03dc9136ee20e0..9626819f3e0860 100644 --- a/packages/api-fetch/src/middlewares/test/user-locale.js +++ b/packages/api-fetch/src/middlewares/test/user-locale.js @@ -73,7 +73,9 @@ describe( 'User locale middleware', () => { }; const callback = ( options ) => { - expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=user' ); + expect( options.url ).toBe( + 'http://wp.org/wp-json/wp/v2/posts?_locale=user' + ); }; userLocaleMiddleware( requestOptions, callback ); @@ -88,7 +90,9 @@ describe( 'User locale middleware', () => { }; const callback = ( options ) => { - expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=user' ); + expect( options.url ).toBe( + 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=user' + ); }; userLocaleMiddleware( requestOptions, callback ); @@ -103,7 +107,9 @@ describe( 'User locale middleware', () => { }; const callback = ( options ) => { - expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?_locale=foo' ); + expect( options.url ).toBe( + 'http://wp.org/wp-json/wp/v2/posts?_locale=foo' + ); }; userLocaleMiddleware( requestOptions, callback ); @@ -118,7 +124,9 @@ describe( 'User locale middleware', () => { }; const callback = ( options ) => { - expect( options.url ).toBe( 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo' ); + expect( options.url ).toBe( + 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo' + ); }; userLocaleMiddleware( requestOptions, callback ); diff --git a/packages/api-fetch/src/middlewares/user-locale.js b/packages/api-fetch/src/middlewares/user-locale.js index 22fd232caf91b1..8debbde8d994a7 100644 --- a/packages/api-fetch/src/middlewares/user-locale.js +++ b/packages/api-fetch/src/middlewares/user-locale.js @@ -4,11 +4,17 @@ import { addQueryArgs, hasQueryArg } from '@wordpress/url'; function userLocaleMiddleware( options, next ) { - if ( typeof options.url === 'string' && ! hasQueryArg( options.url, '_locale' ) ) { + if ( + typeof options.url === 'string' && + ! hasQueryArg( options.url, '_locale' ) + ) { options.url = addQueryArgs( options.url, { _locale: 'user' } ); } - if ( typeof options.path === 'string' && ! hasQueryArg( options.path, '_locale' ) ) { + if ( + typeof options.path === 'string' && + ! hasQueryArg( options.path, '_locale' ) + ) { options.path = addQueryArgs( options.path, { _locale: 'user' } ); } diff --git a/packages/api-fetch/src/test/index.js b/packages/api-fetch/src/test/index.js index 05c327da6ee6f8..26431fb69a5937 100644 --- a/packages/api-fetch/src/test/index.js +++ b/packages/api-fetch/src/test/index.js @@ -50,14 +50,17 @@ describe( 'apiFetch', () => { body, } ); - expect( window.fetch ).toHaveBeenCalledWith( '/wp/v2/media?_locale=user', { - credentials: 'include', - headers: { - Accept: 'application/json, */*;q=0.1', - }, - method: 'POST', - body, - } ); + expect( window.fetch ).toHaveBeenCalledWith( + '/wp/v2/media?_locale=user', + { + credentials: 'include', + headers: { + Accept: 'application/json, */*;q=0.1', + }, + method: 'POST', + body, + } + ); } ); it( 'should fetch with a JSON body', () => { @@ -72,15 +75,18 @@ describe( 'apiFetch', () => { data: {}, } ); - expect( window.fetch ).toHaveBeenCalledWith( '/wp/v2/posts?_locale=user', { - body: '{}', - credentials: 'include', - headers: { - Accept: 'application/json, */*;q=0.1', - 'Content-Type': 'application/json', - }, - method: 'POST', - } ); + expect( window.fetch ).toHaveBeenCalledWith( + '/wp/v2/posts?_locale=user', + { + body: '{}', + credentials: 'include', + headers: { + Accept: 'application/json, */*;q=0.1', + 'Content-Type': 'application/json', + }, + method: 'POST', + } + ); } ); it( 'should respect developer-provided options', () => { @@ -93,15 +99,18 @@ describe( 'apiFetch', () => { credentials: 'omit', } ); - expect( window.fetch ).toHaveBeenCalledWith( '/wp/v2/posts?_locale=user', { - body: '{}', - credentials: 'omit', - headers: { - Accept: 'application/json, */*;q=0.1', - 'Content-Type': 'application/json', - }, - method: 'POST', - } ); + expect( window.fetch ).toHaveBeenCalledWith( + '/wp/v2/posts?_locale=user', + { + body: '{}', + credentials: 'omit', + headers: { + Accept: 'application/json, */*;q=0.1', + 'Content-Type': 'application/json', + }, + method: 'POST', + } + ); } ); it( 'should return the error message properly', () => { @@ -188,11 +197,13 @@ describe( 'apiFetch', () => { } ) ); - return apiFetch( { path: '/random', parse: false } ).then( ( response ) => { - expect( response ).toEqual( { - status: 200, - } ); - } ); + return apiFetch( { path: '/random', parse: false } ).then( + ( response ) => { + expect( response ).toEqual( { + status: 200, + } ); + } + ); } ); it( 'should not try to parse the error', () => { @@ -202,11 +213,13 @@ describe( 'apiFetch', () => { } ) ); - return apiFetch( { path: '/random', parse: false } ).catch( ( response ) => { - expect( response ).toEqual( { - status: 400, - } ); - } ); + return apiFetch( { path: '/random', parse: false } ).catch( + ( response ) => { + expect( response ).toEqual( { + status: 400, + } ); + } + ); } ); it( 'should not use the default fetch handler when using a custom fetch handler', () => { diff --git a/packages/api-fetch/src/utils/response.js b/packages/api-fetch/src/utils/response.js index 518a7fd5e66f81..d28413862b6c63 100644 --- a/packages/api-fetch/src/utils/response.js +++ b/packages/api-fetch/src/utils/response.js @@ -46,10 +46,13 @@ const parseJsonAndNormalizeError = ( response ) => { * * @return {Promise} Parsed response. */ -export const parseResponseAndNormalizeError = ( response, shouldParseResponse = true ) => { - return Promise.resolve( parseResponse( response, shouldParseResponse ) ).catch( ( res ) => - parseAndThrowError( res, shouldParseResponse ) - ); +export const parseResponseAndNormalizeError = ( + response, + shouldParseResponse = true +) => { + return Promise.resolve( + parseResponse( response, shouldParseResponse ) + ).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) ); }; export function parseAndThrowError( response, shouldParseResponse = true ) { diff --git a/packages/autop/src/index.js b/packages/autop/src/index.js index 32512f62094eca..3a0fc7fa73600e 100644 --- a/packages/autop/src/index.js +++ b/packages/autop/src/index.js @@ -92,7 +92,10 @@ function replaceInHtmlTags( haystack, replacePairs ) { for ( let j = 0; j < needles.length; j++ ) { const needle = needles[ j ]; if ( -1 !== textArr[ i ].indexOf( needle ) ) { - textArr[ i ] = textArr[ i ].replace( new RegExp( needle, 'g' ), replacePairs[ needle ] ); + textArr[ i ] = textArr[ i ].replace( + new RegExp( needle, 'g' ), + replacePairs[ needle ] + ); changed = true; // After one strtr() break out of the foreach loop and look at next element. break; @@ -170,10 +173,16 @@ export function autop( text, br = true ) { '(?: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( '()', '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' ); @@ -231,10 +240,16 @@ export function autop( text, br = true ) { text = text.replace( /

\s*<\/p>/g, '' ); // Add a closing

inside

,
, or
tag if missing. - text = text.replace( /

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

$1

' ); + 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*(]*>)\\s*

', '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' ); @@ -244,10 +259,16 @@ 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*(]*>)', '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( '(]*>)\\s*

    ', 'g' ), '$1' ); + text = text.replace( + new RegExp( '(]*>)\\s*

    ', 'g' ), + '$1' + ); // Optionally insert line breaks. if ( br ) { @@ -260,17 +281,25 @@ export function autop( text, br = true ) { 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( '(]*>)\\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' ); + text = text.replace( + /
    (\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, + '$1' + ); text = text.replace( /\n<\/p>$/g, '

    ' ); // Replace placeholder
     tags with their original content.
    @@ -318,7 +347,9 @@ export function removep( html ) {
     
     	// Protect script and style tags.
     	if ( html.indexOf( ']*>[\s\S]*?<\/\1>/g, function( match ) {
    +		html = html.replace( /<(script|style)[^>]*>[\s\S]*?<\/\1>/g, function(
    +			match
    +		) {
     			preserve.push( match );
     			return '';
     		} );
    @@ -338,13 +369,21 @@ export function removep( html ) {
     	if ( html.indexOf( '[caption' ) !== -1 ) {
     		preserveBr = true;
     		html = html.replace( /\[caption[\s\S]+?\[\/caption\]/g, function( a ) {
    -			return a.replace( /]*)>/g, '' ).replace( /[\r\n\t]+/, '' );
    +			return a
    +				.replace( /]*)>/g, '' )
    +				.replace( /[\r\n\t]+/, '' );
     		} );
     	}
     
     	// Normalize white space characters before and after block tags.
    -	html = html.replace( new RegExp( '\\s*\\s*', 'g' ), '\n' );
    -	html = html.replace( new RegExp( '\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g' ), '\n<$1>' );
    +	html = html.replace(
    +		new RegExp( '\\s*\\s*', 'g' ),
    +		'\n'
    +	);
    +	html = html.replace(
    +		new RegExp( '\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g' ),
    +		'\n<$1>'
    +	);
     
     	// Mark 

    if it has any attributes. html = html.replace( /(

    ]+>[\s\S]*?)<\/p>/g, '$1' ); @@ -373,7 +412,10 @@ export function removep( html ) { html = html.replace( /<\/div>\s*/g, '

  • \n' ); // Fix line breaks around caption shortcodes. - html = html.replace( /\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n' ); + html = html.replace( + /\s*\[caption([^\[]+)\[\/caption\]\s*/gi, + '\n\n[caption$1[/caption]\n\n' + ); html = html.replace( /caption\]\n\n+\[caption/g, 'caption]\n\n[caption' ); // Pad block elements tags with a line break. @@ -381,7 +423,10 @@ export function removep( html ) { new RegExp( '\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), '\n<$1>' ); - html = html.replace( new RegExp( '\\s*\\s*', 'g' ), '\n' ); + html = html.replace( + new RegExp( '\\s*\\s*', 'g' ), + '\n' + ); // Indent
  • ,
    and
    tags. html = html.replace( /<((li|dt|dd)[^>]*)>/g, ' \t<$1>' ); diff --git a/packages/autop/src/test/index.test.js b/packages/autop/src/test/index.test.js index 02bffeab830dde..0c5d86d6d0a2b3 100644 --- a/packages/autop/src/test/index.test.js +++ b/packages/autop/src/test/index.test.js @@ -405,7 +405,10 @@ test( 'that autop treats inline elements as inline', () => { test( 'element sanity', () => { [ [ 'Hello ', '

    Hello

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

    Hello

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

    Hello

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

    Hello

    \n', @@ -481,7 +484,8 @@ test( 'that text before blocks is peed', () => { } ); test( 'that autop doses not add extra closing p in figure', () => { - const content1 = '
    Caption
    '; + const content1 = + '
    Caption
    '; const expected1 = content1; const content2 = `
    @@ -497,8 +501,10 @@ test( 'that autop doses not add extra closing p in figure', () => { } ); test( 'that autop correctly adds a start and end tag when followed by a div', () => { - const content = 'Testing autop with a div\n
    content
    '; - const expected = '

    Testing autop with a div

    \n
    content
    '; + const content = + 'Testing autop with a div\n
    content
    '; + const expected = + '

    Testing autop with a div

    \n
    content
    '; expect( autop( content ).trim() ).toBe( expected ); } ); diff --git a/packages/babel-plugin-import-jsx-pragma/index.js b/packages/babel-plugin-import-jsx-pragma/index.js index 273df752611c15..a7dd3a2d381556 100644 --- a/packages/babel-plugin-import-jsx-pragma/index.js +++ b/packages/babel-plugin-import-jsx-pragma/index.js @@ -48,7 +48,9 @@ module.exports = function( babel ) { } const { scopeVariable } = getOptions( state ); - state.hasUndeclaredScopeVariable = ! path.scope.hasBinding( scopeVariable ); + state.hasUndeclaredScopeVariable = ! path.scope.hasBinding( + scopeVariable + ); }, JSXFragment( path, state ) { if ( state.hasUndeclaredScopeVariableFrag ) { @@ -60,18 +62,27 @@ module.exports = function( babel ) { return; } - state.hasUndeclaredScopeVariableFrag = ! path.scope.hasBinding( scopeVariableFrag ); + state.hasUndeclaredScopeVariableFrag = ! path.scope.hasBinding( + scopeVariableFrag + ); }, Program: { exit( path, state ) { - const { scopeVariable, scopeVariableFrag, source, isDefault } = getOptions( state ); + const { + scopeVariable, + scopeVariableFrag, + source, + isDefault, + } = getOptions( state ); let scopeVariableSpecifier; let scopeVariableFragSpecifier; if ( state.hasUndeclaredScopeVariable ) { if ( isDefault ) { - scopeVariableSpecifier = t.importDefaultSpecifier( t.identifier( scopeVariable ) ); + scopeVariableSpecifier = t.importDefaultSpecifier( + t.identifier( scopeVariable ) + ); } else { scopeVariableSpecifier = t.importSpecifier( t.identifier( scopeVariable ), diff --git a/packages/babel-plugin-import-jsx-pragma/test/index.js b/packages/babel-plugin-import-jsx-pragma/test/index.js index c3e098476db3d2..bcd915f1b5dad1 100644 --- a/packages/babel-plugin-import-jsx-pragma/test/index.js +++ b/packages/babel-plugin-import-jsx-pragma/test/index.js @@ -24,7 +24,8 @@ describe( 'babel-plugin-import-jsx-pragma', () => { } ); it( 'does nothing if the scope variable is already defined', () => { - const original = 'const React = require("react");\n\nlet foo = ;'; + const original = + 'const React = require("react");\n\nlet foo = ;'; const string = getTransformedCode( original ); expect( string ).toBe( original ); @@ -52,7 +53,9 @@ describe( 'babel-plugin-import-jsx-pragma', () => { isDefault: false, } ); - expect( string ).toBe( 'import { createElement } from "@wordpress/element";\n' + original ); + expect( string ).toBe( + 'import { createElement } from "@wordpress/element";\n' + original + ); } ); it( 'adds import for scope variable even when defined inside the local scope', () => { @@ -64,7 +67,9 @@ describe( 'babel-plugin-import-jsx-pragma', () => { isDefault: false, } ); - expect( string ).toBe( 'import { createElement } from "@wordpress/element";\n' + original ); + expect( string ).toBe( + 'import { createElement } from "@wordpress/element";\n' + original + ); } ); it( 'does nothing if the outer scope variable is already defined when using custom options', () => { @@ -81,7 +86,8 @@ describe( 'babel-plugin-import-jsx-pragma', () => { } ); it( 'adds only Fragment when required', () => { - const original = 'const {\n createElement\n} = wp.element;\nlet foo = <>;'; + const original = + 'const {\n createElement\n} = wp.element;\nlet foo = <>;'; const string = getTransformedCode( original, { scopeVariable: 'createElement', scopeVariableFrag: 'Fragment', @@ -95,7 +101,8 @@ describe( 'babel-plugin-import-jsx-pragma', () => { } ); it( 'adds only createElement when required', () => { - const original = 'const {\n Fragment\n} = wp.element;\nlet foo = <>;'; + const original = + 'const {\n Fragment\n} = wp.element;\nlet foo = <>;'; const string = getTransformedCode( original, { scopeVariable: 'createElement', scopeVariableFrag: 'Fragment', diff --git a/packages/babel-plugin-makepot/src/index.js b/packages/babel-plugin-makepot/src/index.js index 6764c1ff822946..507c988be91bb8 100644 --- a/packages/babel-plugin-makepot/src/index.js +++ b/packages/babel-plugin-makepot/src/index.js @@ -33,7 +33,16 @@ */ const { po } = require( 'gettext-parser' ); -const { pick, reduce, uniq, forEach, sortBy, isEqual, merge, isEmpty } = require( 'lodash' ); +const { + pick, + reduce, + uniq, + forEach, + sortBy, + isEqual, + merge, + isEmpty, +} = require( 'lodash' ); const { relative, sep } = require( 'path' ); const { writeFileSync } = require( 'fs' ); @@ -178,7 +187,10 @@ 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() { @@ -200,20 +212,24 @@ module.exports = function() { } // Skip unhandled functions - const functionKeys = ( state.opts.functions || DEFAULT_FUNCTIONS )[ name ]; + const functionKeys = ( state.opts.functions || + DEFAULT_FUNCTIONS )[ name ]; if ( ! functionKeys ) { return; } // Assign translation keys by argument position - const translation = path.node.arguments.reduce( ( memo, arg, i ) => { - const key = functionKeys[ i ]; - if ( isValidTranslationKey( key ) ) { - memo[ key ] = getNodeAsString( arg ); - } - - return memo; - }, {} ); + const translation = path.node.arguments.reduce( + ( memo, arg, i ) => { + const key = functionKeys[ i ]; + if ( isValidTranslationKey( key ) ) { + memo[ key ] = getNodeAsString( arg ); + } + + return memo; + }, + {} + ); // Can only assign translation with usable msgid if ( ! translation.msgid ) { @@ -243,9 +259,9 @@ module.exports = function() { } // 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 ); } @@ -253,7 +269,9 @@ module.exports = function() { // Create empty msgstr or array of empty msgstr by nplurals if ( translation.msgid_plural ) { - translation.msgstr = Array.from( Array( nplurals ) ).map( () => '' ); + translation.msgstr = Array.from( Array( nplurals ) ).map( + () => '' + ); } else { translation.msgstr = ''; } @@ -307,26 +325,41 @@ module.exports = function() { 'comments.reference' ); - forEach( sortedTranslations, ( translation ) => { - const { msgctxt = '', msgid } = translation; - if ( ! memo.hasOwnProperty( msgctxt ) ) { - memo[ msgctxt ] = {}; + 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; } - - // 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; @@ -342,7 +375,10 @@ module.exports = function() { // Babel loader doesn't expose these entry points and async // write may hit file lock (need queue). const compiled = po.compile( data ); - writeFileSync( state.opts.output || DEFAULT_OUTPUT, compiled ); + writeFileSync( + state.opts.output || DEFAULT_OUTPUT, + compiled + ); this.hasPendingWrite = false; }, }, diff --git a/packages/babel-plugin-makepot/test/index.js b/packages/babel-plugin-makepot/test/index.js index 32554aa0656939..7a5e46d3a2212e 100644 --- a/packages/babel-plugin-makepot/test/index.js +++ b/packages/babel-plugin-makepot/test/index.js @@ -56,19 +56,25 @@ describe( 'babel-plugin', () => { } it( 'should not return translator comment on same line but after call expression', () => { - const comment = getCommentFromString( "__( 'Hello world' ); // translators: Greeting" ); + const comment = getCommentFromString( + "__( 'Hello world' ); // translators: Greeting" + ); expect( comment ).toBeUndefined(); } ); it( 'should return translator comment on leading comments', () => { - const comment = getCommentFromString( "// translators: Greeting\n__( 'Hello world' );" ); + const comment = getCommentFromString( + "// translators: Greeting\n__( 'Hello world' );" + ); expect( comment ).toBe( 'Greeting' ); } ); it( 'should be case insensitive to translator prefix', () => { - const comment = getCommentFromString( "// TrANslAtORs: Greeting\n__( 'Hello world' );" ); + const comment = getCommentFromString( + "// TrANslAtORs: Greeting\n__( 'Hello world' );" + ); expect( comment ).toBe( 'Greeting' ); } ); @@ -82,7 +88,9 @@ describe( 'babel-plugin', () => { } ); it( 'should not consider comment if it does not end on same or previous line', () => { - const comment = getCommentFromString( "// translators: Greeting\n\n__( 'Hello world' );" ); + const comment = getCommentFromString( + "// translators: Greeting\n\n__( 'Hello world' );" + ); expect( comment ).toBeUndefined(); } ); @@ -121,7 +129,9 @@ describe( 'babel-plugin', () => { } ); it( 'should be a concatenated binary expression string value', () => { - const string = getNodeAsStringFromArgument( '__( "hello" + " world" );' ); + const string = getNodeAsStringFromArgument( + '__( "hello" + " world" );' + ); expect( string ).toBe( 'hello world' ); } ); diff --git a/packages/babel-preset-default/index.js b/packages/babel-preset-default/index.js index 5a9bc8133da814..15454ecb36fd65 100644 --- a/packages/babel-preset-default/index.js +++ b/packages/babel-preset-default/index.js @@ -1,7 +1,9 @@ module.exports = function( api ) { let wpBuildOpts = {}; const isWPBuild = ( name ) => - [ 'WP_BUILD_MAIN', 'WP_BUILD_MODULE' ].some( ( buildName ) => name === buildName ); + [ 'WP_BUILD_MAIN', 'WP_BUILD_MODULE' ].some( + ( buildName ) => name === buildName + ); const isTestEnv = api.env() === 'test'; @@ -74,7 +76,9 @@ module.exports = function( api ) { pragmaFrag: 'Fragment', }, ], - require.resolve( '@babel/plugin-proposal-async-generator-functions' ), + require.resolve( + '@babel/plugin-proposal-async-generator-functions' + ), maybeGetPluginTransformRuntime(), ].filter( Boolean ), }; diff --git a/packages/babel-preset-default/test/index.js b/packages/babel-preset-default/test/index.js index 0be3197b9541cd..2e37f8d0f5ea25 100644 --- a/packages/babel-preset-default/test/index.js +++ b/packages/babel-preset-default/test/index.js @@ -12,7 +12,9 @@ import babelPresetDefault from '../'; describe( 'Babel preset default', () => { test( 'transpilation works properly', () => { - const input = readFileSync( path.join( __dirname, '/fixtures/input.js' ) ); + const input = readFileSync( + path.join( __dirname, '/fixtures/input.js' ) + ); const output = transform( input, { configFile: false, diff --git a/packages/block-directory/src/components/block-ratings/index.js b/packages/block-directory/src/components/block-ratings/index.js index ff4b8111fc7d84..c55cace300028c 100644 --- a/packages/block-directory/src/components/block-ratings/index.js +++ b/packages/block-directory/src/components/block-ratings/index.js @@ -15,7 +15,10 @@ export const BlockRatings = ( { rating, ratingCount } ) => ( className="block-directory-block-ratings__rating-count" aria-label={ // translators: %d: number of ratings (number). - sprintf( _n( '%d total rating', '%d total ratings', ratingCount ), ratingCount ) + sprintf( + _n( '%d total rating', '%d total ratings', ratingCount ), + ratingCount + ) } > ({ ratingCount }) diff --git a/packages/block-directory/src/components/block-ratings/stars.js b/packages/block-directory/src/components/block-ratings/stars.js index 9b78e608dae7ba..63ec7126fea00e 100644 --- a/packages/block-directory/src/components/block-ratings/stars.js +++ b/packages/block-directory/src/components/block-ratings/stars.js @@ -19,13 +19,25 @@ function Stars( { rating } ) { return (
    { times( fullStarCount, ( i ) => ( - + ) ) } { times( halfStarCount, ( i ) => ( - + ) ) } { times( emptyStarCount, ( i ) => ( - + ) ) }
    ); diff --git a/packages/block-directory/src/components/downloadable-block-author-info/index.js b/packages/block-directory/src/components/downloadable-block-author-info/index.js index b422f1360416c1..5c27144430e109 100644 --- a/packages/block-directory/src/components/downloadable-block-author-info/index.js +++ b/packages/block-directory/src/components/downloadable-block-author-info/index.js @@ -4,7 +4,11 @@ import { Fragment } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; -function DownloadableBlockAuthorInfo( { author, authorBlockCount, authorBlockRating } ) { +function DownloadableBlockAuthorInfo( { + author, + authorBlockCount, + authorBlockRating, +} ) { return ( 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 4e765c0ab125d7..78ab2962e60ce8 100644 --- a/packages/block-directory/src/components/downloadable-block-header/index.js +++ b/packages/block-directory/src/components/downloadable-block-header/index.js @@ -10,12 +10,21 @@ import { __, sprintf } from '@wordpress/i18n'; import { BlockIcon } from '@wordpress/block-editor'; import BlockRatings from '../block-ratings'; -function DownloadableBlockHeader( { icon, title, rating, ratingCount, onClick } ) { +function DownloadableBlockHeader( { + icon, + title, + rating, + ratingCount, + onClick, +} ) { return (
    { icon.match( /\.(jpeg|jpg|gif|png)(?:\?.*)?$/ ) !== null ? ( // translators: %s: Name of the plugin e.g: "Akismet". - { + { ) : ( @@ -23,7 +32,10 @@ function DownloadableBlockHeader( { icon, title, rating, ratingCount, onClick } ) }
    - + { 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 1ee6046052ffb1..db09e7df68d30a 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 @@ -1,7 +1,8 @@ const pluginBase = { name: 'boxer/boxer', title: 'Boxer', - description: 'Boxer is a Block that puts your WordPress posts into boxes on a page.', + description: + 'Boxer is a Block that puts your WordPress posts into boxes on a page.', id: 'boxer-block', rating: 5, rating_count: 1, diff --git a/packages/block-directory/src/components/downloadable-block-header/test/index.js b/packages/block-directory/src/components/downloadable-block-header/test/index.js index 6c8d044cd8f87b..96ba6247170cb9 100644 --- a/packages/block-directory/src/components/downloadable-block-header/test/index.js +++ b/packages/block-directory/src/components/downloadable-block-header/test/index.js @@ -30,14 +30,19 @@ describe( 'DownloadableBlockHeader', () => { describe( 'icon rendering', () => { test( 'should render an tag', () => { const wrapper = getContainer( pluginWithImg ); - expect( wrapper.find( 'img' ).prop( 'src' ) ).toEqual( pluginWithImg.icon ); + expect( wrapper.find( 'img' ).prop( 'src' ) ).toEqual( + pluginWithImg.icon + ); } ); test( 'should render an tag if icon URL has query string', () => { - const iconURLwithQueryString = pluginWithImg.icon + '?rev=2011672&test=234234'; + const iconURLwithQueryString = + pluginWithImg.icon + '?rev=2011672&test=234234'; const plugin = { ...pluginWithImg, icon: iconURLwithQueryString }; const wrapper = getContainer( plugin ); - expect( wrapper.find( 'img' ).prop( 'src' ) ).toEqual( plugin.icon ); + expect( wrapper.find( 'img' ).prop( 'src' ) ).toEqual( + plugin.icon + ); } ); test( 'should render a component', () => { 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 54224e34a66c97..8d647313db6a19 100644 --- a/packages/block-directory/src/components/downloadable-block-info/index.js +++ b/packages/block-directory/src/components/downloadable-block-info/index.js @@ -5,15 +5,25 @@ import { Fragment } from '@wordpress/element'; import { Icon } from '@wordpress/components'; import { __, _n, sprintf } from '@wordpress/i18n'; -function DownloadableBlockInfo( { description, activeInstalls, humanizedUpdated } ) { +function DownloadableBlockInfo( { + description, + activeInstalls, + humanizedUpdated, +} ) { return ( -

    { description }

    +

    + { description } +

    { sprintf( - _n( '%d active installation', '%d active installations', activeInstalls ), + _n( + '%d active installation', + '%d active installations', + activeInstalls + ), activeInstalls ) }
    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 36b952f3ecc5da..b63c40d34871f3 100644 --- a/packages/block-directory/src/components/downloadable-blocks-list/index.js +++ b/packages/block-directory/src/components/downloadable-blocks-list/index.js @@ -6,7 +6,10 @@ import { noop } from 'lodash'; /** * WordPress dependencies */ -import { getBlockMenuDefaultClassName, unregisterBlockType } from '@wordpress/blocks'; +import { + getBlockMenuDefaultClassName, + unregisterBlockType, +} from '@wordpress/blocks'; import { withDispatch } from '@wordpress/data'; import { compose } from '@wordpress/compose'; import { __ } from '@wordpress/i18n'; @@ -19,7 +22,12 @@ import DownloadableBlockListItem from '../downloadable-block-list-item'; const DOWNLOAD_ERROR_NOTICE_ID = 'block-download-error'; const INSTALL_ERROR_NOTICE_ID = 'block-install-error'; -function DownloadableBlocksList( { items, onHover = noop, children, downloadAndInstallBlock } ) { +function DownloadableBlocksList( { + items, + onHover = noop, + children, + downloadAndInstallBlock, +} ) { return ( /* * Disable reason: The `list` ARIA role is redundant but @@ -52,7 +60,9 @@ function DownloadableBlocksList( { items, onHover = noop, children, downloadAndI export default compose( withDispatch( ( dispatch, props ) => { - const { installBlock, downloadBlock } = dispatch( 'core/block-directory' ); + const { installBlock, downloadBlock } = dispatch( + 'core/block-directory' + ); const { createErrorNotice, removeNotice } = dispatch( 'core/notices' ); const { removeBlocks } = dispatch( 'core/block-editor' ); const { onSelect } = props; @@ -67,7 +77,11 @@ export default compose( label: __( 'Retry' ), onClick: () => { removeNotice( DOWNLOAD_ERROR_NOTICE_ID ); - downloadBlock( item, onSuccess, onDownloadError ); + downloadBlock( + item, + onSuccess, + onDownloadError + ); }, }, ], @@ -78,26 +92,39 @@ export default compose( 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 ); 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 f49e96654acc27..29d7cbb29ecac0 100644 --- a/packages/block-directory/src/components/downloadable-blocks-panel/index.js +++ b/packages/block-directory/src/components/downloadable-blocks-panel/index.js @@ -31,7 +31,9 @@ function DownloadableBlocksPanel( {

    { __( 'No blocks found in your library.' ) }
    - { __( 'Please contact your site administrator to install new blocks.' ) } + { __( + 'Please contact your site administrator to install new blocks.' + ) }

    ); } @@ -65,7 +67,9 @@ function DownloadableBlocksPanel( { return (

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

    ( { storeName, selectorName, args } ) => { - return registry.select( storeName )[ selectorName ]( ...args ); - } ), - DISPATCH: createRegistryControl( ( registry ) => ( { storeName, dispatcherName, args } ) => { - return registry.dispatch( storeName )[ dispatcherName ]( ...args ); - } ), + SELECT: createRegistryControl( + ( registry ) => ( { storeName, selectorName, args } ) => { + return registry.select( storeName )[ selectorName ]( ...args ); + } + ), + DISPATCH: createRegistryControl( + ( registry ) => ( { storeName, dispatcherName, args } ) => { + return registry.dispatch( storeName )[ dispatcherName ]( ...args ); + } + ), API_FETCH( { request } ) { return wpApiFetch( { ...request } ); }, diff --git a/packages/block-directory/src/store/reducer.js b/packages/block-directory/src/store/reducer.js index d6387476f54662..c0993c56dfaf64 100644 --- a/packages/block-directory/src/store/reducer.js +++ b/packages/block-directory/src/store/reducer.js @@ -55,7 +55,10 @@ export const blockManagement = ( case 'ADD_INSTALLED_BLOCK_TYPE': return { ...state, - installedBlockTypes: [ ...state.installedBlockTypes, action.item ], + installedBlockTypes: [ + ...state.installedBlockTypes, + action.item, + ], }; case 'REMOVE_INSTALLED_BLOCK_TYPE': return { diff --git a/packages/block-directory/src/store/test/fixtures/index.js b/packages/block-directory/src/store/test/fixtures/index.js index bbbfbdaa6f9ed0..0f7cc95dc8a6b4 100644 --- a/packages/block-directory/src/store/test/fixtures/index.js +++ b/packages/block-directory/src/store/test/fixtures/index.js @@ -1,7 +1,8 @@ export const downloadableBlock = { name: 'boxer/boxer', title: 'Boxer', - description: 'Boxer is a Block that puts your WordPress posts into boxes on a page.', + description: + 'Boxer is a Block that puts your WordPress posts into boxes on a page.', id: 'boxer-block', rating: 5, ratingCount: 1, diff --git a/packages/block-directory/src/store/test/reducer.js b/packages/block-directory/src/store/test/reducer.js index b2eaa6b667e0a1..b10edec5845a85 100644 --- a/packages/block-directory/src/store/test/reducer.js +++ b/packages/block-directory/src/store/test/reducer.js @@ -39,7 +39,9 @@ describe( 'state', () => { downloadableBlocks: [ downloadableBlock ], } ); expect( state.results ).toHaveProperty( downloadableBlock.title ); - expect( state.results[ downloadableBlock.title ] ).toHaveLength( 1 ); + expect( state.results[ downloadableBlock.title ] ).toHaveLength( + 1 + ); // It should append to the results const updatedState = downloadableBlocks( state, { diff --git a/packages/block-editor/src/components/alignment-toolbar/index.js b/packages/block-editor/src/components/alignment-toolbar/index.js index 96c8f33f0faa06..9a880f4e67dd35 100644 --- a/packages/block-editor/src/components/alignment-toolbar/index.js +++ b/packages/block-editor/src/components/alignment-toolbar/index.js @@ -41,7 +41,10 @@ export function AlignmentToolbar( props ) { return () => onChange( value === align ? undefined : align ); } - const activeAlignment = find( alignmentControls, ( control ) => control.align === value ); + const activeAlignment = find( + alignmentControls, + ( control ) => control.align === value + ); return ( { const alignment = 'left'; const onChangeSpy = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); const controls = wrapper.props().controls; @@ -34,7 +36,9 @@ describe( 'AlignmentToolbar', () => { } ); test( 'should call on change a new value when the control is not active', () => { - const inactiveControl = controls.find( ( { align } ) => align === 'center' ); + const inactiveControl = controls.find( + ( { align } ) => align === 'center' + ); inactiveControl.onClick(); expect( inactiveControl.isActive ).toBe( false ); @@ -66,7 +70,9 @@ 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 ); @@ -74,7 +80,9 @@ 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/block-actions/index.js b/packages/block-editor/src/components/block-actions/index.js index 058e189c0a4406..b26ca15f2590b3 100644 --- a/packages/block-editor/src/components/block-actions/index.js +++ b/packages/block-editor/src/components/block-actions/index.js @@ -55,7 +55,10 @@ export default compose( [ ); } ); - const canInsertDefaultBlock = canInsertBlockType( getDefaultBlockName(), rootClientId ); + const canInsertDefaultBlock = canInsertBlockType( + getDefaultBlockName(), + rootClientId + ); return { blocks, @@ -100,7 +103,10 @@ export default compose( [ const groupingBlockName = getGroupingBlockName(); // Activate the `transform` on `core/group` which does the conversion - const newBlocks = switchToBlockType( blocks, groupingBlockName ); + const newBlocks = switchToBlockType( + blocks, + groupingBlockName + ); if ( ! newBlocks ) { return; 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 eb677bb0a2a5ef..84a7c6160d34d5 100644 --- a/packages/block-editor/src/components/block-alignment-toolbar/index.js +++ b/packages/block-editor/src/components/block-alignment-toolbar/index.js @@ -58,15 +58,22 @@ export function BlockAlignmentToolbar( { const enabledControls = wideControlsEnabled ? controls - : controls.filter( ( control ) => WIDE_CONTROLS.indexOf( control ) === -1 ); + : controls.filter( + ( control ) => WIDE_CONTROLS.indexOf( control ) === -1 + ); const activeAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[ value ]; - const defaultAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[ DEFAULT_CONTROL ]; + const defaultAlignmentControl = + BLOCK_ALIGNMENTS_CONTROLS[ DEFAULT_CONTROL ]; return ( { return { diff --git a/packages/block-editor/src/components/block-alignment-toolbar/test/index.js b/packages/block-editor/src/components/block-alignment-toolbar/test/index.js index b92ab806746ecf..976aa7d4abd896 100644 --- a/packages/block-editor/src/components/block-alignment-toolbar/test/index.js +++ b/packages/block-editor/src/components/block-alignment-toolbar/test/index.js @@ -12,7 +12,9 @@ describe( 'BlockAlignmentToolbar', () => { const alignment = 'left'; const onChange = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); const controls = wrapper.props().controls; @@ -25,7 +27,9 @@ describe( 'BlockAlignmentToolbar', () => { } ); test( 'should call onChange with undefined, when the control is already active', () => { - const activeControl = controls.find( ( { title } ) => title === 'Align left' ); + const activeControl = controls.find( + ( { title } ) => title === 'Align left' + ); activeControl.onClick(); expect( activeControl.isActive ).toBe( true ); @@ -34,7 +38,9 @@ describe( 'BlockAlignmentToolbar', () => { } ); test( 'should call onChange with alignment value when the control is inactive', () => { - const inactiveCenterControl = controls.find( ( { title } ) => title === 'Align center' ); + const inactiveCenterControl = controls.find( + ( { title } ) => title === 'Align center' + ); inactiveCenterControl.onClick(); expect( inactiveCenterControl.isActive ).toBe( false ); diff --git a/packages/block-editor/src/components/block-breadcrumb/index.js b/packages/block-editor/src/components/block-breadcrumb/index.js index fb2072938dc9d8..e1c7b7436cdf35 100644 --- a/packages/block-editor/src/components/block-breadcrumb/index.js +++ b/packages/block-editor/src/components/block-breadcrumb/index.js @@ -16,11 +16,15 @@ import BlockTitle from '../block-title'; * @return {WPElement} Block Breadcrumb. */ const BlockBreadcrumb = function() { - const { selectBlock, clearSelectedBlock } = useDispatch( 'core/block-editor' ); + 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 ), @@ -41,7 +45,11 @@ const BlockBreadcrumb = function() { aria-label={ __( 'Block breadcrumb' ) } >
  • { hasSelection && ( @@ -67,7 +75,10 @@ const BlockBreadcrumb = function() {
  • ) ) } { !! clientId && ( -
  • +
  • ) } diff --git a/packages/block-editor/src/components/block-caption/index.native.js b/packages/block-editor/src/components/block-caption/index.native.js index 8b0be70c676f60..818bc3b41c0ab0 100644 --- a/packages/block-editor/src/components/block-caption/index.native.js +++ b/packages/block-editor/src/components/block-caption/index.native.js @@ -36,13 +36,16 @@ const BlockCaption = ( { export default compose( [ withSelect( ( select, { clientId } ) => { - const { getBlockAttributes, getSelectedBlockClientId } = select( 'core/block-editor' ); + const { getBlockAttributes, getSelectedBlockClientId } = select( + 'core/block-editor' + ); const { caption } = getBlockAttributes( clientId ); const isBlockSelected = getSelectedBlockClientId() === clientId; // We'll render the caption so that the soft keyboard is not forced to close on Android // but still hide it by setting its display style to none. See wordpress-mobile/gutenberg-mobile#1221 - const shouldDisplay = ! RichText.isEmpty( caption ) > 0 || isBlockSelected; + const shouldDisplay = + ! RichText.isEmpty( caption ) > 0 || isBlockSelected; return { shouldDisplay, diff --git a/packages/block-editor/src/components/block-card/index.js b/packages/block-editor/src/components/block-card/index.js index f060612622804e..674d437d9c7a3e 100644 --- a/packages/block-editor/src/components/block-card/index.js +++ b/packages/block-editor/src/components/block-card/index.js @@ -8,8 +8,12 @@ function BlockCard( { blockType } ) {
    -
    { blockType.title }
    -
    { blockType.description }
    +
    + { blockType.title } +
    +
    + { blockType.description } +
    ); 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 861370f6e3edf0..7bb45a4402f241 100644 --- a/packages/block-editor/src/components/block-compare/block-view.js +++ b/packages/block-editor/src/components/block-compare/block-view.js @@ -3,13 +3,24 @@ */ import { Button } from '@wordpress/components'; -const BlockView = ( { title, rawContent, renderedContent, action, actionText, className } ) => { +const BlockView = ( { + title, + rawContent, + renderedContent, + action, + actionText, + className, +} ) => { return (
    -

    { title }

    +

    + { title } +

    -
    { rawContent }
    +
    + { rawContent } +
    { renderedContent } diff --git a/packages/block-editor/src/components/block-compare/index.js b/packages/block-editor/src/components/block-compare/index.js index f1e4d21fc992d2..f80ca412ce5114 100644 --- a/packages/block-editor/src/components/block-compare/index.js +++ b/packages/block-editor/src/components/block-compare/index.js @@ -61,10 +61,19 @@ class BlockCompare extends Component { } render() { - const { block, onKeep, onConvert, convertor, convertButtonText } = this.props; + const { + block, + onKeep, + onConvert, + convertor, + convertButtonText, + } = this.props; const original = this.getOriginalContent( block ); const converted = this.getConvertedContent( convertor( block ) ); - const difference = this.getDifference( original.rawContent, converted.rawContent ); + const difference = this.getDifference( + original.rawContent, + converted.rawContent + ); return (
    diff --git a/packages/block-editor/src/components/block-draggable/index.js b/packages/block-editor/src/components/block-draggable/index.js index f361aad8054140..dd87e2c5a08fd6 100644 --- a/packages/block-editor/src/components/block-draggable/index.js +++ b/packages/block-editor/src/components/block-draggable/index.js @@ -13,24 +13,33 @@ 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 { + 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; + 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, + isDraggable: + normalizedClientIds.length === 1 && 'all' !== templateLock, }; }, [ clientIds ] ); const isDragging = useRef( false ); - const { startDraggingBlocks, stopDraggingBlocks } = useDispatch( 'core/block-editor' ); + const { startDraggingBlocks, stopDraggingBlocks } = useDispatch( + 'core/block-editor' + ); // Stop dragging blocks if the block draggable is unmounted useEffect( () => { 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 2501f32f389437..6f15cb0284af04 100644 --- a/packages/block-editor/src/components/block-drop-zone/index.js +++ b/packages/block-editor/src/components/block-drop-zone/index.js @@ -2,7 +2,11 @@ * 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'; @@ -19,7 +23,10 @@ const parseDropEvent = ( event ) => { } try { - result = Object.assign( result, JSON.parse( event.dataTransfer.getData( 'text' ) ) ); + result = Object.assign( + result, + JSON.parse( event.dataTransfer.getData( 'text' ) ) + ); } catch ( err ) { return result; } @@ -31,9 +38,12 @@ 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 ), @@ -50,9 +60,11 @@ export default function useBlockDropZone( { element, rootClientId } ) { hasUploadPermissions, isLockedAll, } = useSelect( selector, [ rootClientId, clientId ] ); - const { insertBlocks, updateBlockAttributes, moveBlockToPosition } = useDispatch( - 'core/block-editor' - ); + const { + insertBlocks, + updateBlockAttributes, + moveBlockToPosition, + } = useDispatch( 'core/block-editor' ); const onFilesDrop = useCallback( ( files ) => { @@ -62,15 +74,25 @@ export default function useBlockDropZone( { element, rootClientId } ) { const transformation = findTransform( getBlockTransforms( 'from' ), - ( transform ) => transform.type === 'files' && transform.isMatch( files ) + ( transform ) => + transform.type === 'files' && transform.isMatch( files ) ); if ( transformation ) { - const blocks = transformation.transform( files, updateBlockAttributes ); + const blocks = transformation.transform( + files, + updateBlockAttributes + ); insertBlocks( blocks, blockIndex, rootClientId ); } }, - [ hasUploadPermissions, updateBlockAttributes, insertBlocks, blockIndex, rootClientId ] + [ + hasUploadPermissions, + updateBlockAttributes, + insertBlocks, + blockIndex, + rootClientId, + ] ); const onHTMLDrop = useCallback( @@ -86,35 +108,57 @@ export default function useBlockDropZone( { element, rootClientId } ) { const onDrop = useCallback( ( event ) => { - const { srcRootClientId, srcClientId, srcIndex, type } = parseDropEvent( 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 ); + return ( + srcRoot === dstRoot || + ( ! srcRoot === true && ! dstRoot === true ) + ); }; const isSameBlock = ( src, dst ) => src === dst; const isSrcBlockAnAncestorOfDstBlock = ( src, dst ) => - getClientIdsOfDescendants( [ src ] ).some( ( id ) => id === dst ); + getClientIdsOfDescendants( [ src ] ).some( + ( id ) => id === dst + ); if ( ! isBlockDropType( type ) || isSameBlock( srcClientId, clientId ) || - isSrcBlockAnAncestorOfDstBlock( srcClientId, clientId || rootClientId ) + isSrcBlockAnAncestorOfDstBlock( + srcClientId, + clientId || rootClientId + ) ) { return; } - const dstIndex = clientId ? getBlockIndex( clientId, rootClientId ) : undefined; + 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 ) + dstIndex && + srcIndex < dstIndex && + isSameLevel( srcRootClientId, rootClientId ) ? positionIndex - 1 : positionIndex; - moveBlockToPosition( srcClientId, srcRootClientId, rootClientId, insertIndex ); + moveBlockToPosition( + srcClientId, + srcRootClientId, + rootClientId, + insertIndex + ); }, [ getClientIdsOfDescendants, @@ -141,9 +185,13 @@ export default function useBlockDropZone( { element, rootClientId } ) { const rect = element.current.getBoundingClientRect(); const offset = y - rect.top; - const target = Array.from( element.current.children ).find( ( blockEl ) => { - return blockEl.offsetTop + blockEl.offsetHeight / 2 > offset; - } ); + const target = Array.from( element.current.children ).find( + ( blockEl ) => { + return ( + blockEl.offsetTop + blockEl.offsetHeight / 2 > offset + ); + } + ); if ( ! target ) { return; diff --git a/packages/block-editor/src/components/block-edit/context.js b/packages/block-editor/src/components/block-edit/context.js index 0a619f91b12ccb..0ab6570bd5da0b 100644 --- a/packages/block-editor/src/components/block-edit/context.js +++ b/packages/block-editor/src/components/block-edit/context.js @@ -44,7 +44,10 @@ export const withBlockEditContext = ( mapContextToProps ) => return ( props ) => ( { ( context ) => ( - + ) } ); @@ -58,8 +61,15 @@ export const withBlockEditContext = ( mapContextToProps ) => * * @return {WPComponent} Component which renders only when the BlockEdit is selected. */ -export const ifBlockEditSelected = createHigherOrderComponent( ( OriginalComponent ) => { - return ( props ) => ( - { ( { isSelected } ) => isSelected && } - ); -}, 'ifBlockEditSelected' ); +export const ifBlockEditSelected = createHigherOrderComponent( + ( OriginalComponent ) => { + return ( props ) => ( + + { ( { 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 3172916c870a90..c31095753d2065 100644 --- a/packages/block-editor/src/components/block-edit/edit.js +++ b/packages/block-editor/src/components/block-edit/edit.js @@ -7,7 +7,11 @@ import classnames from 'classnames'; * WordPress dependencies */ import { withFilters } from '@wordpress/components'; -import { getBlockDefaultClassName, hasBlockSupport, getBlockType } from '@wordpress/blocks'; +import { + getBlockDefaultClassName, + hasBlockSupport, + getBlockType, +} from '@wordpress/blocks'; export const Edit = ( props ) => { const { attributes = {}, name } = props; diff --git a/packages/block-editor/src/components/block-edit/index.js b/packages/block-editor/src/components/block-edit/index.js index 9953cebf01cc8e..3057ff3b4cf72b 100644 --- a/packages/block-editor/src/components/block-edit/index.js +++ b/packages/block-editor/src/components/block-edit/index.js @@ -21,15 +21,35 @@ 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 ) { - return { name, isSelected, clientId, onFocus, onCaretVerticalPositionChange }; + propsToContext( + name, + isSelected, + clientId, + onFocus, + onCaretVerticalPositionChange + ) { + return { + name, + isSelected, + clientId, + onFocus, + onCaretVerticalPositionChange, + }; } render() { - const { name, isSelected, clientId, onFocus, onCaretVerticalPositionChange } = this.props; + const { + name, + isSelected, + clientId, + onFocus, + onCaretVerticalPositionChange, + } = this.props; const value = this.propsToContext( name, isSelected, 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 0a24f55ce2471e..0b07eb03b2aad6 100644 --- a/packages/block-editor/src/components/block-edit/test/edit.js +++ b/packages/block-editor/src/components/block-edit/test/edit.js @@ -7,7 +7,11 @@ import { noop } from 'lodash'; /** * WordPress dependencies */ -import { registerBlockType, unregisterBlockType, getBlockTypes } from '@wordpress/blocks'; +import { + registerBlockType, + unregisterBlockType, + getBlockTypes, +} from '@wordpress/blocks'; /** * Internal dependencies @@ -66,9 +70,13 @@ 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( '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 b20642c6dc9ae7..5e953264fc99c3 100644 --- a/packages/block-editor/src/components/block-icon/index.js +++ b/packages/block-editor/src/components/block-icon/index.js @@ -31,7 +31,9 @@ export default function BlockIcon( { icon, showColors = false, className } ) { 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 36b01445309776..f7e2317b4e2d4b 100644 --- a/packages/block-editor/src/components/block-icon/test/index.js +++ b/packages/block-editor/src/components/block-icon/test/index.js @@ -17,7 +17,9 @@ describe( 'BlockIcon', () => { it( 'renders a Icon', () => { const wrapper = shallow( ); - expect( wrapper.containsMatchingElement( ) ).toBe( true ); + expect( + wrapper.containsMatchingElement( ) + ).toBe( true ); } ); it( 'renders a span without the has-colors classname', () => { @@ -33,14 +35,19 @@ describe( 'BlockIcon', () => { } ); it( 'skips adding background and foreground styles when colors are not enabled', () => { - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper.find( 'span' ).prop( 'style' ) ).toEqual( {} ); } ); it( 'adds background and foreground styles when colors are enabled', () => { const wrapper = shallow( - + ); expect( wrapper.find( 'span' ).prop( 'style' ) ).toEqual( { diff --git a/packages/block-editor/src/components/block-inspector/index.js b/packages/block-editor/src/components/block-inspector/index.js index 7aa3cdea1f088f..0f7fededfb6f9b 100644 --- a/packages/block-editor/src/components/block-inspector/index.js +++ b/packages/block-editor/src/components/block-inspector/index.js @@ -2,8 +2,14 @@ * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { getBlockType, getUnregisteredTypeHandlerName } from '@wordpress/blocks'; -import { PanelBody, __experimentalSlotFillConsumer } from '@wordpress/components'; +import { + getBlockType, + getUnregisteredTypeHandlerName, +} from '@wordpress/blocks'; +import { + PanelBody, + __experimentalSlotFillConsumer, +} from '@wordpress/components'; import { withSelect } from '@wordpress/data'; /** @@ -28,13 +34,18 @@ const BlockInspector = ( { return ; } - const isSelectedBlockUnregistered = selectedBlockName === getUnregisteredTypeHandlerName(); + const isSelectedBlockUnregistered = + selectedBlockName === getUnregisteredTypeHandlerName(); /* * If the selected block is of an unregistered type, avoid showing it as an actual selection * because we want the user to focus on the unregistered block warning, not block settings. */ - if ( ! blockType || ! selectedBlockClientId || isSelectedBlockUnregistered ) { + if ( + ! blockType || + ! selectedBlockClientId || + isSelectedBlockUnregistered + ) { if ( showNoBlockSelectedMessage ) { return ( @@ -66,7 +77,9 @@ const BlockInspector = ( { title={ __( 'Advanced' ) } initialOpen={ false } > - + ) } @@ -78,14 +91,19 @@ const BlockInspector = ( { }; export default withSelect( ( select ) => { - const { getSelectedBlockClientId, getSelectedBlockCount, getBlockName } = select( - 'core/block-editor' - ); + 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 ); + const selectedBlockName = + selectedBlockClientId && getBlockName( selectedBlockClientId ); + const blockType = + selectedBlockClientId && getBlockType( selectedBlockName ); + const blockStyles = + selectedBlockClientId && getBlockStyles( selectedBlockName ); return { count: getSelectedBlockCount(), hasBlockStyles: blockStyles && blockStyles.length > 0, 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 d4309fac24d378..bd226053c6e9b8 100644 --- a/packages/block-editor/src/components/block-list-appender/index.js +++ b/packages/block-editor/src/components/block-list-appender/index.js @@ -49,7 +49,10 @@ function BlockListAppender( { // Fallback in the case no renderAppender has been provided and the // default block can't be inserted. appender = ( - + ); } @@ -75,11 +78,16 @@ 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 ), blockClientIds: getBlockOrder( rootClientId ), - canInsertDefaultBlock: canInsertBlockType( getDefaultBlockName(), rootClientId ), + canInsertDefaultBlock: canInsertBlockType( + getDefaultBlockName(), + rootClientId + ), }; } )( BlockListAppender ); 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 f5c9d3bf75e928..6b33b1f5c08b7e 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 @@ -47,11 +47,16 @@ 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 ), blockClientIds: getBlockOrder( rootClientId ), - canInsertDefaultBlock: canInsertBlockType( getDefaultBlockName(), rootClientId ), + canInsertDefaultBlock: canInsertBlockType( + getDefaultBlockName(), + rootClientId + ), }; } )( BlockListAppender ); 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 c2ea261387c3a5..b8f684b62f309f 100644 --- a/packages/block-editor/src/components/block-list/block-html.js +++ b/packages/block-editor/src/components/block-list/block-html.js @@ -27,13 +27,23 @@ function BlockHTML( { clientId } ) { const { updateBlock } = useDispatch( 'core/block-editor' ); const onChange = () => { const blockType = getBlockType( block.name ); - const attributes = getBlockAttributes( blockType, html, block.attributes ); + const attributes = getBlockAttributes( + blockType, + html, + block.attributes + ); // If html is empty we reset the block to the default HTML and mark it as valid to avoid triggering an error const content = html ? html : getSaveContent( blockType, attributes ); - const isValid = html ? isValidBlockContent( blockType, attributes, content ) : true; + const isValid = html + ? isValidBlockContent( blockType, attributes, content ) + : true; - updateBlock( clientId, { attributes, originalContent: content, isValid } ); + updateBlock( clientId, { + attributes, + originalContent: content, + isValid, + } ); // Ensure the state is updated if we reset so it displays the default content if ( ! html ) { 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 8a91289eddeaf6..1fa98168e96ed5 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 @@ -42,8 +42,14 @@ export class BlockInvalidWarning extends Component { const hasHTMLBlock = !! getBlockType( 'core/html' ); const { compare } = this.state; const hiddenActions = [ - { title: __( 'Convert to Classic Block' ), onClick: convertToClassic }, - { title: __( 'Attempt Block Recovery' ), onClick: attemptBlockRecovery }, + { + title: __( 'Convert to Classic Block' ), + onClick: convertToClassic, + }, + { + title: __( 'Attempt Block Recovery' ), + onClick: attemptBlockRecovery, + }, ]; return ( @@ -60,14 +66,20 @@ export class BlockInvalidWarning extends Component { _x( 'Resolve', 'imperative verb' ) } , hasHTMLBlock && ( - ), ] } secondaryActions={ hiddenActions } > - { __( 'This block contains unexpected or invalid content.' ) } + { __( + 'This block contains unexpected or invalid content.' + ) } { compare && ( setIsToolbarForced( true ), [] ), - { bindGlobal: true, eventName: 'keydown', isDisabled: ! canFocusHiddenToolbar } + { + bindGlobal: true, + eventName: 'keydown', + isDisabled: ! canFocusHiddenToolbar, + } ); if ( @@ -141,7 +146,9 @@ function BlockPopover( { // left corner. For the side inserter, pop out towards the left, and // position in the right corner. // To do: refactor `Popover` to make this prop clearer. - const popoverPosition = showEmptyBlockSideInserter ? 'top left right' : 'top right left'; + const popoverPosition = showEmptyBlockSideInserter + ? 'top left right' + : 'top right left'; return ( setIsToolbarForced( false ) } shouldAnchorIncludePadding > @@ -170,11 +181,17 @@ function BlockPopover( { // // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus tabIndex={ -1 } - className={ classnames( 'block-editor-block-list__block-popover-inserter', { - 'is-visible': isInserterShown, - } ) } + className={ classnames( + 'block-editor-block-list__block-popover-inserter', + { + 'is-visible': isInserterShown, + } + ) } > - +
    ) } { ( shouldShowContextualToolbar || isToolbarForced ) && ( @@ -196,7 +213,11 @@ function BlockPopover( { ) } { showEmptyBlockSideInserter && (
    - +
    ) } @@ -214,16 +235,19 @@ function wrapperSelector( select ) { __experimentalGetBlockListSettingsForBlocks, } = select( 'core/block-editor' ); - const clientId = getSelectedBlockClientId() || getFirstMultiSelectedBlockClientId(); + const clientId = + getSelectedBlockClientId() || getFirstMultiSelectedBlockClientId(); if ( ! clientId ) { return; } const rootClientId = getBlockRootClientId( clientId ); - const { name, attributes = {}, isValid } = __unstableGetBlockWithoutInnerBlocks( clientId ) || {}; + const { name, attributes = {}, isValid } = + __unstableGetBlockWithoutInnerBlocks( clientId ) || {}; const blockParentsClientIds = getBlockParents( clientId ); - const { __experimentalMoverDirection } = getBlockListSettings( rootClientId ) || {}; + const { __experimentalMoverDirection } = + getBlockListSettings( rootClientId ) || {}; // Get Block List Settings for all ancestors of the current Block clientId const ancestorBlockListSettings = __experimentalGetBlockListSettingsForBlocks( @@ -232,15 +256,18 @@ function wrapperSelector( select ) { // 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; if ( topmostAncestorWithCaptureDescendantsToolbarsIndex !== -1 ) { - capturingClientId = blockParentsClientIds[ topmostAncestorWithCaptureDescendantsToolbarsIndex ]; + capturingClientId = + blockParentsClientIds[ + topmostAncestorWithCaptureDescendantsToolbarsIndex + ]; } return { @@ -250,7 +277,8 @@ function wrapperSelector( select ) { align: attributes.align, isValid, moverDirection: __experimentalMoverDirection, - isEmptyDefaultBlock: name && isUnmodifiedDefaultBlock( { name, attributes } ), + isEmptyDefaultBlock: + name && isUnmodifiedDefaultBlock( { name, attributes } ), capturingClientId, }; } diff --git a/packages/block-editor/src/components/block-list/block.js b/packages/block-editor/src/components/block-list/block.js index ff038162acecbb..3fb84e824f1082 100644 --- a/packages/block-editor/src/components/block-list/block.js +++ b/packages/block-editor/src/components/block-list/block.js @@ -8,7 +8,13 @@ import { animated } from 'react-spring/web.cjs'; /** * WordPress dependencies */ -import { useRef, useEffect, useLayoutEffect, useState, useContext } from '@wordpress/element'; +import { + useRef, + useEffect, + useLayoutEffect, + useState, + useContext, +} from '@wordpress/element'; import { focus, isTextField, placeCaretAtHorizontalEdge } from '@wordpress/dom'; import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes'; import { @@ -125,7 +131,11 @@ function BlockListBlock( { .find( wrapper.current ) .filter( isTextField ) // Exclude inner blocks - .filter( ( node ) => ! ignoreInnerBlocks || isInsideRootBlock( wrapper.current, node ) ); + .filter( + ( node ) => + ! ignoreInnerBlocks || + isInsideRootBlock( wrapper.current, node ) + ); // If reversed (e.g. merge via backspace), use the last in the set of // tabbables. @@ -211,9 +221,13 @@ function BlockListBlock( { const showEmptyBlockSideInserter = ! isNavigationMode && isSelected && isEmptyDefaultBlock && isValid; const shouldAppearSelected = - ! isFocusMode && ! showEmptyBlockSideInserter && isSelected && ! isTypingWithinBlock; + ! isFocusMode && + ! showEmptyBlockSideInserter && + isSelected && + ! isTypingWithinBlock; - const isDragging = isDraggingBlocks && ( isSelected || isPartOfMultiSelection ); + const isDragging = + isDraggingBlocks && ( isSelected || isPartOfMultiSelection ); // Determine whether the block has props to apply to the wrapper. if ( blockType.getEditWrapperProps ) { @@ -237,7 +251,8 @@ function BlockListBlock( { 'is-reusable': isReusableBlock( blockType ), 'is-dragging': isDragging, 'is-typing': isTypingWithinBlock, - 'is-focused': isFocusMode && ( isSelected || isAncestorOfSelectedBlock ), + 'is-focused': + isFocusMode && ( isSelected || isAncestorOfSelectedBlock ), 'is-focus-mode': isFocusMode, 'has-child-selected': isAncestorOfSelectedBlock, 'is-block-collapsed': isAligned, @@ -303,10 +318,17 @@ function BlockListBlock( { > { isValid && blockEdit } - { isValid && mode === 'html' && } + { isValid && mode === 'html' && ( + + ) } { ! isValid && [ - , -
    { getSaveElement( blockType, attributes ) }
    , + , +
    + { getSaveElement( blockType, attributes ) } +
    , ] }
    { !! hasError && } @@ -314,69 +336,81 @@ 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' ); + + 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, - }; -} ); + 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 { @@ -416,7 +450,9 @@ 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 ); @@ -424,14 +460,19 @@ const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => { mergeBlocks( clientId, nextBlockClientId ); } } else { - const previousBlockClientId = getPreviousBlockClientId( clientId ); + const previousBlockClientId = getPreviousBlockClientId( + clientId + ); if ( previousBlockClientId ) { mergeBlocks( previousBlockClientId, clientId ); } } }, 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 c9ff1959711111..9092826676b3d2 100644 --- a/packages/block-editor/src/components/block-list/block.native.js +++ b/packages/block-editor/src/components/block-list/block.native.js @@ -63,7 +63,9 @@ class BlockListBlock extends Component { onReplace={ this.props.onReplace } insertBlocksAfter={ this.insertBlocksAfter } mergeBlocks={ this.props.mergeBlocks } - onCaretVerticalPositionChange={ this.props.onCaretVerticalPositionChange } + onCaretVerticalPositionChange={ + this.props.onCaretVerticalPositionChange + } clientId={ this.props.clientId } /> ); @@ -88,7 +90,10 @@ class BlockListBlock extends Component { const fullSolidBorderStyle = { // define style for full border ...styles.fullSolidBordered, - ...getStylesFromColorScheme( styles.solidBorderColor, styles.solidBorderColorDark ), + ...getStylesFromColorScheme( + styles.solidBorderColor, + styles.solidBorderColorDark + ), }; if ( hasChildren ) { @@ -133,7 +138,10 @@ class BlockListBlock extends Component { const dashedBorderStyle = { // define style for dashed border ...styles.dashedBordered, - ...getStylesFromColorScheme( styles.dashedBorderColor, styles.dashedBorderColorDark ), + ...getStylesFromColorScheme( + styles.dashedBorderColor, + styles.dashedBorderColorDark + ), }; // return apply childOfSelected or childOfSelectedLeaf @@ -160,7 +168,9 @@ class BlockListBlock extends Component { const { isSelected, isDimmed } = this.props; return [ - isSelected ? this.applySelectedBlockStyle() : this.applyUnSelectedBlockStyle(), + isSelected + ? this.applySelectedBlockStyle() + : this.applyUnSelectedBlockStyle(), isDimmed && styles.dimmed, ]; } @@ -188,7 +198,11 @@ class BlockListBlock extends Component { isTouchable, } = this.props; - const accessibilityLabel = getAccessibleBlockLabel( blockType, attributes, order + 1 ); + const accessibilityLabel = getAccessibleBlockLabel( + blockType, + attributes, + order + 1 + ); return ( <> @@ -197,7 +211,9 @@ class BlockListBlock extends Component { this.props.onSelect( parentId ) } + onClick={ () => + this.props.onSelect( parentId ) + } icon={ NavigateUpSVG } /> @@ -218,10 +234,15 @@ class BlockListBlock extends Component { { isValid ? ( this.getBlockForType() ) : ( - + ) } - { isSelected && } + { isSelected && ( + + ) } @@ -270,23 +291,37 @@ export default compose( [ const selectedBlockClientId = getSelectedBlockClientId(); - const commonAncestor = getLowestCommonAncestorWithSelectedBlock( clientId ); + const commonAncestor = getLowestCommonAncestorWithSelectedBlock( + clientId + ); const commonAncestorIndex = parents.indexOf( commonAncestor ) - 1; const firstToSelectId = commonAncestor ? parents[ commonAncestorIndex ] : parents[ parents.length - 1 ]; - const hasChildren = ! isUnregisteredBlock && !! getBlockCount( clientId ); + const hasChildren = + ! isUnregisteredBlock && !! getBlockCount( clientId ); const hasParent = !! parentId; - const isParentSelected = selectedBlockClientId && selectedBlockClientId === parentId; - const isAncestorSelected = selectedBlockClientId && parents.includes( selectedBlockClientId ); - const isSelectedBlockNested = !! getBlockRootClientId( selectedBlockClientId ); + const isParentSelected = + selectedBlockClientId && selectedBlockClientId === parentId; + const isAncestorSelected = + selectedBlockClientId && parents.includes( selectedBlockClientId ); + const isSelectedBlockNested = !! getBlockRootClientId( + selectedBlockClientId + ); - const selectedParents = selectedBlockClientId ? getBlockParents( selectedBlockClientId ) : []; + const selectedParents = selectedBlockClientId + ? getBlockParents( selectedBlockClientId ) + : []; const isDescendantSelected = selectedParents.includes( clientId ); - const isDescendantOfParentSelected = selectedParents.includes( parentId ); + const isDescendantOfParentSelected = selectedParents.includes( + parentId + ); const isTouchable = - isSelected || isDescendantOfParentSelected || isParentSelected || parentId === ''; + isSelected || + isDescendantOfParentSelected || + isParentSelected || + parentId === ''; const isDimmed = ! isSelected && isSelectedBlockNested && @@ -295,7 +330,8 @@ export default compose( [ ( isDescendantOfParentSelected || rootBlockId === clientId ); const isInnerBlockHolder = name === getGroupingBlockName(); - const isRootListInnerBlockHolder = ! isSelectedBlockNested && isInnerBlockHolder; + const isRootListInnerBlockHolder = + ! isSelectedBlockNested && isInnerBlockHolder; return { icon, @@ -332,7 +368,10 @@ 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 ); @@ -340,7 +379,9 @@ export default compose( [ mergeBlocks( clientId, nextBlockClientId ); } } else { - const previousBlockClientId = getPreviousBlockClientId( clientId ); + const previousBlockClientId = getPreviousBlockClientId( + clientId + ); if ( previousBlockClientId ) { mergeBlocks( previousBlockClientId, clientId ); } diff --git a/packages/block-editor/src/components/block-list/breadcrumb.js b/packages/block-editor/src/components/block-list/breadcrumb.js index 77fa495db99519..a47db75152663e 100644 --- a/packages/block-editor/src/components/block-list/breadcrumb.js +++ b/packages/block-editor/src/components/block-list/breadcrumb.js @@ -25,18 +25,30 @@ import BlockTitle from '../block-title'; * * @return {WPComponent} The component to be rendered. */ -function BlockBreadcrumb( { clientId, rootClientId, moverDirection, ...props } ) { +function BlockBreadcrumb( { + clientId, + rootClientId, + moverDirection, + ...props +} ) { const selected = useSelect( ( select ) => { - const { __unstableGetBlockWithoutInnerBlocks, getBlockIndex } = select( 'core/block-editor' ); + const { + __unstableGetBlockWithoutInnerBlocks, + getBlockIndex, + } = select( 'core/block-editor' ); const index = getBlockIndex( clientId, rootClientId ); - const { name, attributes } = __unstableGetBlockWithoutInnerBlocks( clientId ); + 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. @@ -54,7 +66,12 @@ function BlockBreadcrumb( { clientId, rootClientId, moverDirection, ...props } ) } const blockType = getBlockType( name ); - const label = getAccessibleBlockLabel( blockType, attributes, index + 1, moverDirection ); + const label = getAccessibleBlockLabel( + blockType, + attributes, + index + 1, + moverDirection + ); return (
    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 33a9b3ace7c7e6..37d26abe1cff55 100644 --- a/packages/block-editor/src/components/block-list/breadcrumb.native.js +++ b/packages/block-editor/src/components/block-list/breadcrumb.native.js @@ -19,7 +19,12 @@ import SubdirectorSVG from './subdirectory-icon'; import styles from './breadcrumb.scss'; -const BlockBreadcrumb = ( { clientId, blockIcon, rootClientId, rootBlockIcon } ) => { +const BlockBreadcrumb = ( { + clientId, + blockIcon, + rootClientId, + rootBlockIcon, +} ) => { return ( { /* Open BottomSheet with markup */ } } - disabled={ true } /* Disable temporarily since onPress function is empty */ + disabled={ + true + } /* Disable temporarily since onPress function is empty */ > { rootClientId && rootBlockIcon && [ @@ -41,7 +48,11 @@ const BlockBreadcrumb = ( { clientId, blockIcon, 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 48d05a5f629b6a..ffb5320faa1aae 100644 --- a/packages/block-editor/src/components/block-list/index.js +++ b/packages/block-editor/src/components/block-list/index.js @@ -56,7 +56,9 @@ function BlockList( { selectedBlockClientId: getSelectedBlockClientId(), multiSelectedBlockClientIds: getMultiSelectedBlockClientIds(), hasMultiSelection: hasMultiSelection(), - enableAnimation: ! isTyping() && getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD, + enableAnimation: + ! isTyping() && + getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD, }; } @@ -77,14 +79,23 @@ function BlockList( { } ); return ( - + { blockClientIds.map( ( clientId, index ) => { const isBlockInSelection = hasMultiSelection ? multiSelectedBlockClientIds.includes( clientId ) : selectedBlockClientId === clientId; return ( - + ); @@ -104,7 +121,9 @@ function BlockList( { <__experimentalBlockListFooter.Slot /> 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 df1a9f1d7e2b6e..c3e39232598e8f 100644 --- a/packages/block-editor/src/components/block-list/index.native.js +++ b/packages/block-editor/src/components/block-list/index.native.js @@ -11,7 +11,10 @@ import { Component } from '@wordpress/element'; import { withDispatch, withSelect } from '@wordpress/data'; import { compose, withPreferredColorScheme } from '@wordpress/compose'; import { createBlock } from '@wordpress/blocks'; -import { KeyboardAwareFlatList, ReadableContentView } from '@wordpress/components'; +import { + KeyboardAwareFlatList, + ReadableContentView, +} from '@wordpress/components'; /** * Internal dependencies @@ -30,14 +33,20 @@ export class BlockList extends Component { this.renderItem = this.renderItem.bind( this ); this.renderBlockListFooter = this.renderBlockListFooter.bind( this ); - this.renderDefaultBlockAppender = this.renderDefaultBlockAppender.bind( this ); - this.onCaretVerticalPositionChange = this.onCaretVerticalPositionChange.bind( this ); + this.renderDefaultBlockAppender = this.renderDefaultBlockAppender.bind( + this + ); + 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.shouldShowInnerBlockAppender = this.shouldShowInnerBlockAppender.bind( this ); + this.shouldShowInnerBlockAppender = this.shouldShowInnerBlockAppender.bind( + this + ); } addBlockToEndOfPost( newBlock ) { @@ -93,9 +102,14 @@ export class BlockList extends Component { } = this.props; return ( - + { this.shouldShowInnerBlockAppender() && ( @@ -136,18 +156,23 @@ export class BlockList extends Component { return ( - { shouldShowInsertionPointBefore( clientId ) && } + { shouldShowInsertionPointBefore( clientId ) && ( + + ) } - { ! this.shouldShowInnerBlockAppender() && shouldShowInsertionPointAfter( clientId ) && ( - - ) } + { ! this.shouldShowInnerBlockAppender() && + shouldShowInsertionPointAfter( clientId ) && ( + + ) } ); @@ -220,7 +245,9 @@ 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 3ff506db3631ec..11ef726060509a 100644 --- a/packages/block-editor/src/components/block-list/insertion-point.js +++ b/packages/block-editor/src/components/block-list/insertion-point.js @@ -43,7 +43,9 @@ function Indicator( { clientId } ) { return null; } - return
    ; + return ( +
    + ); } export default function InsertionPoint( { @@ -69,9 +71,11 @@ export default function InsertionPoint( { const rect = event.target.getBoundingClientRect(); const offset = event.clientY - rect.top; - const element = Array.from( event.target.children ).find( ( blockEl ) => { - return blockEl.offsetTop > offset; - } ); + const element = Array.from( event.target.children ).find( + ( blockEl ) => { + return blockEl.offsetTop > offset; + } + ); if ( ! element ) { return; @@ -85,7 +89,10 @@ export default function InsertionPoint( { const elementRect = element.getBoundingClientRect(); - if ( event.clientX > elementRect.right || event.clientX < elementRect.left ) { + if ( + event.clientX > elementRect.right || + event.clientX < elementRect.left + ) { if ( isInserterShown ) { setIsInserterShown( false ); } @@ -149,17 +156,28 @@ export default function InsertionPoint( { // // 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, - } ) } + className={ classnames( + 'block-editor-block-list__insertion-point-inserter', + { + // Hide the inserter above the selected block. + 'is-inserter-hidden': + inserterClientId === + selectedBlockClientId, + } + ) } >
    ) } -
    +
    { children }
    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 8c538277725753..6af4ba78ea6348 100644 --- a/packages/block-editor/src/components/block-list/moving-animation.js +++ b/packages/block-editor/src/components/block-list/moving-animation.js @@ -6,7 +6,12 @@ import { useSpring, interpolate } from 'react-spring/web.cjs'; /** * WordPress dependencies */ -import { useState, useLayoutEffect, useReducer, useMemo } from '@wordpress/element'; +import { + useState, + useLayoutEffect, + useReducer, + useMemo, +} from '@wordpress/element'; import { useReducedMotion } from '@wordpress/compose'; import { getScrollContainer } from '@wordpress/dom'; @@ -52,9 +57,16 @@ function useMovingAnimation( triggerAnimationOnChange ) { const prefersReducedMotion = useReducedMotion() || ! enableAnimation; - const [ triggeredAnimation, triggerAnimation ] = useReducer( counterReducer, 0 ); + const [ triggeredAnimation, triggerAnimation ] = useReducer( + counterReducer, + 0 + ); const [ finishedAnimation, endAnimation ] = useReducer( counterReducer, 0 ); - const [ transform, setTransform ] = useState( { x: 0, y: 0, scrollTop: 0 } ); + const [ transform, setTransform ] = useState( { + x: 0, + y: 0, + scrollTop: 0, + } ); const previous = ref.current ? getAbsolutePosition( ref.current ) : null; const scrollContainer = useMemo( () => { @@ -76,7 +88,8 @@ function useMovingAnimation( // just move directly to the final scroll position ref.current.style.transform = 'none'; const destination = getAbsolutePosition( ref.current ); - scrollContainer.scrollTop = scrollContainer.scrollTop - previous.top + destination.top; + scrollContainer.scrollTop = + scrollContainer.scrollTop - previous.top + destination.top; } return; @@ -112,7 +125,12 @@ function useMovingAnimation( config: { mass: 5, tension: 2000, friction: 200 }, immediate: prefersReducedMotion, onFrame: ( props ) => { - if ( adjustScrolling && scrollContainer && ! prefersReducedMotion && props.y ) { + if ( + adjustScrolling && + scrollContainer && + ! prefersReducedMotion && + props.y + ) { scrollContainer.scrollTop = transform.scrollTop + props.y; } }, @@ -123,11 +141,17 @@ function useMovingAnimation( ? {} : { transformOrigin: 'center', - transform: interpolate( [ animationProps.x, animationProps.y ], ( x, y ) => - x === 0 && y === 0 ? undefined : `translate3d(${ x }px,${ y }px,0)` + 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` + zIndex: interpolate( + [ animationProps.x, animationProps.y ], + ( x, y ) => + ! isSelected || ( x === 0 && y === 0 ) ? undefined : `1` ), }; } 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 a1878c28df2419..ae1d897660af7b 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 @@ -4,7 +4,12 @@ import { SVG, Path } from '@wordpress/components'; const NavigateUp = ( - + -
    - { children } +
    + + { children } +
    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 001a7e28af84f8..1e77f8711a51de 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,13 +56,15 @@ 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 ) { @@ -74,9 +76,12 @@ 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(); @@ -95,9 +100,14 @@ export default function useMultiSelection( ref ) { if ( selection.rangeCount && ! selection.isCollapsed ) { const blockNode = getBlockDOMNode( selectedBlockClientId ); - const { startContainer, endContainer } = selection.getRangeAt( 0 ); - - if ( ! blockNode.contains( startContainer ) || ! blockNode.contains( endContainer ) ) { + const { startContainer, endContainer } = selection.getRangeAt( + 0 + ); + + if ( + ! blockNode.contains( startContainer ) || + ! blockNode.contains( endContainer ) + ) { selection.removeAllRanges(); } } @@ -165,15 +175,24 @@ export default function useMultiSelection( ref ) { toggleRichText( ref.current, true ); if ( selection.rangeCount ) { - const { commonAncestorContainer } = selection.getRangeAt( 0 ); - - if ( anchorElement.current.contains( commonAncestorContainer ) ) { + const { + commonAncestorContainer, + } = selection.getRangeAt( 0 ); + + if ( + anchorElement.current.contains( + commonAncestorContainer + ) + ) { anchorElement.current.focus(); } } } } else { - const startPath = [ ...getBlockParents( startClientId.current ), startClientId.current ]; + const startPath = [ + ...getBlockParents( startClientId.current ), + startClientId.current, + ]; const endPath = [ ...getBlockParents( clientId ), clientId ]; const depth = Math.min( startPath.length, endPath.length ) - 1; @@ -201,7 +220,10 @@ export default function useMultiSelection( ref ) { // Only clean up when unmounting, these are added and cleaned up elsewhere. useEffect( () => () => { - document.removeEventListener( 'selectionchange', onSelectionChange ); + document.removeEventListener( + 'selectionchange', + onSelectionChange + ); window.removeEventListener( 'mouseup', onSelectionEnd ); window.cancelAnimationFrame( rafId.current ); }, diff --git a/packages/block-editor/src/components/block-mobile-toolbar/index.js b/packages/block-editor/src/components/block-mobile-toolbar/index.js index 689e455d833885..968b645ce72f3f 100644 --- a/packages/block-editor/src/components/block-mobile-toolbar/index.js +++ b/packages/block-editor/src/components/block-mobile-toolbar/index.js @@ -16,7 +16,10 @@ function BlockMobileToolbar( { clientId, moverDirection } ) { return (
    - +
    ); } diff --git a/packages/block-editor/src/components/block-mover/icons.js b/packages/block-editor/src/components/block-mover/icons.js index a55400d965e025..1ebd7922cd4b44 100644 --- a/packages/block-editor/src/components/block-mover/icons.js +++ b/packages/block-editor/src/components/block-mover/icons.js @@ -4,19 +4,34 @@ import { Path, SVG } from '@wordpress/components'; export const leftArrow = ( - + ); export const rightArrow = ( - + ); export const dragHandle = ( - + ); @@ -65,15 +69,21 @@ const BlockMover = ( { export default compose( withSelect( ( select, { clientIds } ) => { - const { getBlockIndex, getTemplateLock, getBlockRootClientId, getBlockOrder } = select( - 'core/block-editor' - ); + const { + getBlockIndex, + getTemplateLock, + getBlockRootClientId, + getBlockOrder, + } = select( 'core/block-editor' ); const normalizedClientIds = castArray( clientIds ); const firstClientId = first( normalizedClientIds ); const rootClientId = getBlockRootClientId( firstClientId ); const blockOrder = getBlockOrder( rootClientId ); const firstIndex = getBlockIndex( firstClientId, rootClientId ); - const lastIndex = getBlockIndex( last( normalizedClientIds ), rootClientId ); + const lastIndex = getBlockIndex( + last( normalizedClientIds ), + rootClientId + ); return { firstIndex, @@ -84,7 +94,9 @@ export default compose( }; } ), withDispatch( ( dispatch, { clientIds, rootClientId } ) => { - const { moveBlocksDown, moveBlocksUp } = dispatch( 'core/block-editor' ); + const { moveBlocksDown, moveBlocksUp } = dispatch( + 'core/block-editor' + ); return { onMoveDown: partial( moveBlocksDown, clientIds, rootClientId ), onMoveUp: partial( moveBlocksUp, clientIds, rootClientId ), diff --git a/packages/block-editor/src/components/block-mover/mover-description.js b/packages/block-editor/src/components/block-mover/mover-description.js index 0cb24cf263c724..88e67e5ff4a715 100644 --- a/packages/block-editor/src/components/block-mover/mover-description.js +++ b/packages/block-editor/src/components/block-mover/mover-description.js @@ -48,12 +48,21 @@ export function getBlockMoverDescription( }; if ( selectedCount > 1 ) { - return getMultiBlockMoverDescription( selectedCount, firstIndex, isFirst, isLast, dir ); + return getMultiBlockMoverDescription( + selectedCount, + firstIndex, + isFirst, + isLast, + dir + ); } if ( isFirst && isLast ) { // translators: %s: Type of block (i.e. Text, Image etc) - return sprintf( __( 'Block %s is the only block, and cannot be moved' ), type ); + return sprintf( + __( 'Block %s is the only block, and cannot be moved' ), + type + ); } if ( dir > 0 && ! isLast ) { @@ -63,7 +72,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'down' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position - __( 'Move %1$s block from position %2$d down to position %3$d' ), + __( + 'Move %1$s block from position %2$d down to position %3$d' + ), type, position, position + 1 @@ -73,7 +84,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'left' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position - __( 'Move %1$s block from position %2$d left to position %3$d' ), + __( + 'Move %1$s block from position %2$d left to position %3$d' + ), type, position, position + 1 @@ -83,7 +96,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'right' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position - __( 'Move %1$s block from position %2$d right to position %3$d' ), + __( + 'Move %1$s block from position %2$d right to position %3$d' + ), type, position, position + 1 @@ -98,7 +113,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'down' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the end of the content and canโ€™t be moved down' ), + __( + 'Block %1$s is at the end of the content and canโ€™t be moved down' + ), type ); } @@ -106,7 +123,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'left' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the end of the content and canโ€™t be moved left' ), + __( + 'Block %1$s is at the end of the content and canโ€™t be moved left' + ), type ); } @@ -114,7 +133,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'right' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the end of the content and canโ€™t be moved right' ), + __( + 'Block %1$s is at the end of the content and canโ€™t be moved right' + ), type ); } @@ -137,7 +158,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'left' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position - __( 'Move %1$s block from position %2$d left to position %3$d' ), + __( + 'Move %1$s block from position %2$d left to position %3$d' + ), type, position, position - 1 @@ -147,7 +170,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'right' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position - __( 'Move %1$s block from position %2$d right to position %3$d' ), + __( + 'Move %1$s block from position %2$d right to position %3$d' + ), type, position, position - 1 @@ -162,7 +187,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'up' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the beginning of the content and canโ€™t be moved up' ), + __( + 'Block %1$s is at the beginning of the content and canโ€™t be moved up' + ), type ); } @@ -170,7 +197,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'left' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the beginning of the content and canโ€™t be moved left' ), + __( + 'Block %1$s is at the beginning of the content and canโ€™t be moved left' + ), type ); } @@ -178,7 +207,9 @@ export function getBlockMoverDescription( if ( movementDirection === 'right' ) { return sprintf( // translators: 1: Type of block (i.e. Text, Image etc) - __( 'Block %1$s is at the beginning of the content and canโ€™t be moved right' ), + __( + 'Block %1$s is at the beginning of the content and canโ€™t be moved right' + ), type ); } @@ -197,7 +228,13 @@ export function getBlockMoverDescription( * * @return {string} Label for the block movement controls. */ -export function getMultiBlockMoverDescription( selectedCount, firstIndex, isFirst, isLast, dir ) { +export function getMultiBlockMoverDescription( + selectedCount, + firstIndex, + isFirst, + isLast, + dir +) { const position = firstIndex + 1; if ( dir < 0 && isFirst ) { @@ -205,7 +242,9 @@ export function getMultiBlockMoverDescription( selectedCount, firstIndex, isFirs } if ( dir > 0 && isLast ) { - return __( 'Blocks cannot be moved down as they are already at the bottom' ); + return __( + 'Blocks cannot be moved down as they are already at the bottom' + ); } if ( dir < 0 && ! isFirst ) { diff --git a/packages/block-editor/src/components/block-mover/test/index.js b/packages/block-editor/src/components/block-mover/test/index.js index e413dc6e8680bd..0f78a8250bee47 100644 --- a/packages/block-editor/src/components/block-mover/test/index.js +++ b/packages/block-editor/src/components/block-mover/test/index.js @@ -35,7 +35,9 @@ describe( 'BlockMover', () => { instanceId={ 1 } /> ); - expect( blockMover.hasClass( 'block-editor-block-mover' ) ).toBe( true ); + expect( blockMover.hasClass( 'block-editor-block-mover' ) ).toBe( + true + ); const moveUp = blockMover.childAt( 0 ); const drag = blockMover.childAt( 1 ); @@ -51,7 +53,8 @@ describe( 'BlockMover', () => { label: 'Move up', icon: chevronUp, 'aria-disabled': undefined, - 'aria-describedby': 'block-editor-block-mover__up-description-1', + 'aria-describedby': + 'block-editor-block-mover__up-description-1', } ); expect( moveDown.props() ).toMatchObject( { className: 'block-editor-block-mover__control', @@ -59,10 +62,15 @@ describe( 'BlockMover', () => { label: 'Move down', icon: chevronDown, 'aria-disabled': undefined, - 'aria-describedby': 'block-editor-block-mover__down-description-1', + 'aria-describedby': + 'block-editor-block-mover__down-description-1', } ); - expect( moveUpDesc.text() ).toBe( 'Move 2 blocks from position 1 up by one place' ); - expect( moveDownDesc.text() ).toBe( 'Move 2 blocks from position 1 down by one place' ); + expect( moveUpDesc.text() ).toBe( + 'Move 2 blocks from position 1 up by one place' + ); + expect( moveDownDesc.text() ).toBe( + 'Move 2 blocks from position 1 down by one place' + ); } ); it( 'should render the up arrow with a onMoveUp callback', () => { diff --git a/packages/block-editor/src/components/block-mover/test/mover-description.js b/packages/block-editor/src/components/block-mover/test/mover-description.js index 03e04c87927907..6098dc5619e0a0 100644 --- a/packages/block-editor/src/components/block-mover/test/mover-description.js +++ b/packages/block-editor/src/components/block-mover/test/mover-description.js @@ -1,7 +1,10 @@ /** * Internal dependencies */ -import { getBlockMoverDescription, getMultiBlockMoverDescription } from '../mover-description'; +import { + getBlockMoverDescription, + getMultiBlockMoverDescription, +} from '../mover-description'; describe( 'block mover', () => { const negativeDirection = -1, @@ -11,81 +14,190 @@ describe( 'block mover', () => { const label = 'Header: Some Header Text'; it( 'generates a title for the first item moving up', () => { - expect( getBlockMoverDescription( 1, label, 0, true, false, negativeDirection ) ).toBe( + expect( + getBlockMoverDescription( + 1, + label, + 0, + true, + false, + negativeDirection + ) + ).toBe( `Block ${ label } is at the beginning of the content and canโ€™t be moved up` ); } ); it( 'generates a title for the last item moving down', () => { - expect( getBlockMoverDescription( 1, label, 3, false, true, positiveDirection ) ).toBe( + expect( + getBlockMoverDescription( + 1, + label, + 3, + false, + true, + positiveDirection + ) + ).toBe( `Block ${ label } is at the end of the content and canโ€™t be moved down` ); } ); it( 'generates a title for the second item moving up', () => { - expect( getBlockMoverDescription( 1, label, 1, false, false, negativeDirection ) ).toBe( - `Move ${ label } block from position 2 up to position 1` - ); + expect( + getBlockMoverDescription( + 1, + label, + 1, + false, + false, + negativeDirection + ) + ).toBe( `Move ${ label } block from position 2 up to position 1` ); } ); it( 'generates a title for the second item moving down', () => { - expect( getBlockMoverDescription( 1, label, 1, false, false, positiveDirection ) ).toBe( + expect( + getBlockMoverDescription( + 1, + label, + 1, + false, + false, + positiveDirection + ) + ).toBe( `Move ${ label } block from position 2 down to position 3` ); } ); it( 'generates a title for the only item in the list', () => { - expect( getBlockMoverDescription( 1, label, 0, true, true, positiveDirection ) ).toBe( - `Block ${ label } is the only block, and cannot be moved` - ); + expect( + getBlockMoverDescription( + 1, + label, + 0, + true, + true, + positiveDirection + ) + ).toBe( `Block ${ label } is the only block, and cannot be moved` ); } ); it( 'indicates that the block can be moved left when the orientation is horizontal and the direction is negative', () => { expect( - getBlockMoverDescription( 1, label, 1, false, false, negativeDirection, 'horizontal' ) - ).toBe( `Move ${ label } block from position 2 left to position 1` ); + getBlockMoverDescription( + 1, + label, + 1, + false, + false, + negativeDirection, + 'horizontal' + ) + ).toBe( + `Move ${ label } block from position 2 left to position 1` + ); } ); it( 'indicates that the block can be moved right when the orientation is horizontal and the direction is positive', () => { expect( - getBlockMoverDescription( 1, label, 1, false, false, positiveDirection, 'horizontal' ) - ).toBe( `Move ${ label } block from position 2 right to position 3` ); + getBlockMoverDescription( + 1, + label, + 1, + false, + false, + positiveDirection, + 'horizontal' + ) + ).toBe( + `Move ${ label } block from position 2 right to position 3` + ); } ); it( 'indicates that the block cannot be moved left when the orientation is horizontal and the block is the first block', () => { expect( - getBlockMoverDescription( 1, label, 0, true, false, negativeDirection, 'horizontal' ) - ).toBe( `Block ${ label } is at the beginning of the content and canโ€™t be moved left` ); + getBlockMoverDescription( + 1, + label, + 0, + true, + false, + negativeDirection, + 'horizontal' + ) + ).toBe( + `Block ${ label } is at the beginning of the content and canโ€™t be moved left` + ); } ); it( 'indicates that the block cannot be moved right when the orientation is horizontal and the block is the last block', () => { expect( - getBlockMoverDescription( 1, label, 3, false, true, positiveDirection, 'horizontal' ) - ).toBe( `Block ${ label } is at the end of the content and canโ€™t be moved right` ); + getBlockMoverDescription( + 1, + label, + 3, + false, + true, + positiveDirection, + 'horizontal' + ) + ).toBe( + `Block ${ label } is at the end of the content and canโ€™t be moved right` + ); } ); } ); describe( 'getMultiBlockMoverDescription', () => { it( 'generates a title moving multiple blocks up', () => { - expect( getMultiBlockMoverDescription( 4, 1, false, true, negativeDirection ) ).toBe( - 'Move 4 blocks from position 2 up by one place' - ); + expect( + getMultiBlockMoverDescription( + 4, + 1, + false, + true, + negativeDirection + ) + ).toBe( 'Move 4 blocks from position 2 up by one place' ); } ); it( 'generates a title moving multiple blocks down', () => { - expect( getMultiBlockMoverDescription( 4, 0, true, false, positiveDirection ) ).toBe( - 'Move 4 blocks from position 1 down by one place' - ); + expect( + getMultiBlockMoverDescription( + 4, + 0, + true, + false, + positiveDirection + ) + ).toBe( 'Move 4 blocks from position 1 down by one place' ); } ); it( 'generates a title for a selection of blocks at the top', () => { - expect( getMultiBlockMoverDescription( 4, 1, true, true, negativeDirection ) ).toBe( + expect( + getMultiBlockMoverDescription( + 4, + 1, + true, + true, + negativeDirection + ) + ).toBe( 'Blocks cannot be moved up as they are already at the top' ); } ); it( 'generates a title for a selection of blocks at the bottom', () => { - expect( getMultiBlockMoverDescription( 4, 2, false, true, positiveDirection ) ).toBe( + expect( + getMultiBlockMoverDescription( + 4, + 2, + false, + true, + positiveDirection + ) + ).toBe( 'Blocks cannot be moved down as they are already at the bottom' ); } ); diff --git a/packages/block-editor/src/components/block-navigation/dropdown.js b/packages/block-editor/src/components/block-navigation/dropdown.js index 92b810b5291573..24ebb27244dc92 100644 --- a/packages/block-editor/src/components/block-navigation/dropdown.js +++ b/packages/block-editor/src/components/block-navigation/dropdown.js @@ -13,16 +13,25 @@ import { useCallback } from '@wordpress/element'; import BlockNavigation from './'; const MenuIcon = ( - + ); function BlockNavigationDropdownToggle( { isEnabled, onToggle, isOpen } ) { - useShortcut( 'core/edit-post/toggle-block-navigation', useCallback( onToggle, [ onToggle ] ), { - bindGlobal: true, - isDisabled: ! isEnabled, - } ); + useShortcut( + 'core/edit-post/toggle-block-navigation', + useCallback( onToggle, [ onToggle ] ), + { + bindGlobal: true, + isDisabled: ! isEnabled, + } + ); const shortcut = useSelect( ( select ) => select( 'core/keyboard-shortcuts' ).getShortcutRepresentation( @@ -45,16 +54,24 @@ function BlockNavigationDropdownToggle( { isEnabled, onToggle, isOpen } ) { } function BlockNavigationDropdown( { isDisabled } ) { - const hasBlocks = useSelect( ( select ) => !! select( 'core/block-editor' ).getBlockCount(), [] ); + const hasBlocks = useSelect( + ( select ) => !! select( 'core/block-editor' ).getBlockCount(), + [] + ); const isEnabled = hasBlocks && ! isDisabled; return ( ( - + + ) } + renderContent={ ( { onClose } ) => ( + ) } - renderContent={ ( { onClose } ) => } /> ); } diff --git a/packages/block-editor/src/components/block-navigation/index.js b/packages/block-editor/src/components/block-navigation/index.js index 957072d6571f31..4d25ffda1bb01e 100644 --- a/packages/block-editor/src/components/block-navigation/index.js +++ b/packages/block-editor/src/components/block-navigation/index.js @@ -16,7 +16,12 @@ import { __ } from '@wordpress/i18n'; */ import BlockNavigationList from './list'; -function BlockNavigation( { rootBlock, rootBlocks, selectedBlockClientId, selectBlock } ) { +function BlockNavigation( { + rootBlock, + rootBlocks, + selectedBlockClientId, + selectBlock, +} ) { if ( ! rootBlocks || rootBlocks.length === 0 ) { return null; } @@ -27,8 +32,13 @@ function BlockNavigation( { rootBlock, rootBlocks, selectedBlockClientId, select ( rootBlock.innerBlocks && rootBlock.innerBlocks.length !== 0 ) ); return ( - -

    { __( 'Block navigation' ) }

    + +

    + { __( 'Block navigation' ) } +

    { hasHierarchy && ( { - const { getSelectedBlockClientId, getBlockHierarchyRootClientId, getBlock, getBlocks } = select( - 'core/block-editor' - ); + const { + getSelectedBlockClientId, + getBlockHierarchyRootClientId, + getBlock, + getBlocks, + } = select( 'core/block-editor' ); const selectedBlockClientId = getSelectedBlockClientId(); return { rootBlocks: getBlocks(), rootBlock: selectedBlockClientId - ? getBlock( getBlockHierarchyRootClientId( selectedBlockClientId ) ) + ? getBlock( + getBlockHierarchyRootClientId( selectedBlockClientId ) + ) : null, selectedBlockClientId, }; diff --git a/packages/block-editor/src/components/block-navigation/list.js b/packages/block-editor/src/components/block-navigation/list.js index 53b91d79dc284b..32c8eba5049e89 100644 --- a/packages/block-editor/src/components/block-navigation/list.js +++ b/packages/block-editor/src/components/block-navigation/list.js @@ -8,7 +8,10 @@ import classnames from 'classnames'; * WordPress dependencies */ import { Button } from '@wordpress/components'; -import { __experimentalGetBlockLabel as getBlockLabel, getBlockType } from '@wordpress/blocks'; +import { + __experimentalGetBlockLabel as getBlockLabel, + getBlockType, +} from '@wordpress/blocks'; import { __ } from '@wordpress/i18n'; /** @@ -44,28 +47,37 @@ export default function BlockNavigationList( {
  • - { showNestedBlocks && !! block.innerBlocks && !! block.innerBlocks.length && ( - - ) } + { 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 7a967afef4e663..160bc280a06667 100644 --- a/packages/block-editor/src/components/block-pattern-picker/index.js +++ b/packages/block-editor/src/components/block-pattern-picker/index.js @@ -22,13 +22,21 @@ 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 */ } -
      +
        { patterns.map( ( pattern ) => (
      • diff --git a/packages/block-editor/src/components/button-block-appender/index.native.js b/packages/block-editor/src/components/button-block-appender/index.native.js index 290d3192ae70d5..070993d3d9848f 100644 --- a/packages/block-editor/src/components/button-block-appender/index.native.js +++ b/packages/block-editor/src/components/button-block-appender/index.native.js @@ -15,10 +15,17 @@ import { Button, Dashicon } from '@wordpress/components'; import Inserter from '../inserter'; import styles from './styles.scss'; -function ButtonBlockAppender( { rootClientId, getStylesFromColorScheme, showSeparator } ) { +function ButtonBlockAppender( { + rootClientId, + getStylesFromColorScheme, + showSeparator, +} ) { const appenderStyle = { ...styles.appender, - ...getStylesFromColorScheme( styles.appenderLight, styles.appenderDark ), + ...getStylesFromColorScheme( + styles.appenderLight, + styles.appenderDark + ), }; const addBlockButtonStyle = getStylesFromColorScheme( styles.addBlockButton, diff --git a/packages/block-editor/src/components/caption/index.native.js b/packages/block-editor/src/components/caption/index.native.js index 75be2714dc00d7..4669f1b8a4c3e8 100644 --- a/packages/block-editor/src/components/caption/index.native.js +++ b/packages/block-editor/src/components/caption/index.native.js @@ -25,7 +25,9 @@ const Caption = ( { } ) => ( { const settings = select( 'core/block-editor' ).getSettings(); - const colors = ownProps.colors === undefined ? settings.colors : ownProps.colors; + const colors = + ownProps.colors === undefined ? settings.colors : ownProps.colors; const disableCustomColors = ownProps.disableCustomColors === undefined diff --git a/packages/block-editor/src/components/colors-gradients/control.js b/packages/block-editor/src/components/colors-gradients/control.js index a46f244b33a33f..e91250ca77f2d0 100644 --- a/packages/block-editor/src/components/colors-gradients/control.js +++ b/packages/block-editor/src/components/colors-gradients/control.js @@ -38,7 +38,14 @@ const colorsAndGradientKeys = [ 'disableCustomGradients', ]; -function VisualLabel( { colors, gradients, label, currentTab, colorValue, gradientValue } ) { +function VisualLabel( { + colors, + gradients, + label, + currentTab, + colorValue, + gradientValue, +} ) { let value, ariaLabel; if ( currentTab === 'color' ) { if ( colorValue ) { @@ -49,15 +56,23 @@ function VisualLabel( { colors, gradients, label, currentTab, colorValue, gradie } } else if ( currentTab === 'gradient' && gradientValue ) { value = gradientValue; - const gradientObject = __experimentalGetGradientObjectByGradientValue( gradients, value ); + const gradientObject = __experimentalGetGradientObjectByGradientValue( + gradients, + value + ); const gradientName = gradientObject && gradientObject.name; - ariaLabel = sprintf( gradientIndicatorAriaLabel, gradientName || value ); + ariaLabel = sprintf( + gradientIndicatorAriaLabel, + gradientName || value + ); } return ( <> { label } - { !! value && } + { !! value && ( + + ) } ); } @@ -74,9 +89,11 @@ function ColorGradientControlInner( { colorValue, gradientValue, } ) { - const canChooseAColor = onColorChange && ( ! isEmpty( colors ) || ! disableCustomColors ); + const canChooseAColor = + onColorChange && ( ! isEmpty( colors ) || ! disableCustomColors ); const canChooseAGradient = - onGradientChange && ( ! isEmpty( gradients ) || ! disableCustomGradients ); + onGradientChange && + ( ! isEmpty( gradients ) || ! disableCustomGradients ); const [ currentTab, setCurrentTab ] = useState( gradientValue ? 'gradient' : !! canChooseAColor && 'color' ); @@ -85,7 +102,12 @@ function ColorGradientControlInner( { return null; } return ( - +
        @@ -155,11 +177,17 @@ function ColorGradientControlSelect( props ) { const settings = select( 'core/block-editor' ).getSettings(); return pick( settings, colorsAndGradientKeys ); } ); - return ; + return ( + + ); } function ColorGradientControl( props ) { - if ( every( colorsAndGradientKeys, ( key ) => props.hasOwnProperty( key ) ) ) { + if ( + every( colorsAndGradientKeys, ( key ) => props.hasOwnProperty( key ) ) + ) { return ; } return ; diff --git a/packages/block-editor/src/components/colors-gradients/panel-color-gradient-settings.js b/packages/block-editor/src/components/colors-gradients/panel-color-gradient-settings.js index f86802b0cd68a6..6c36cd10e7a45a 100644 --- a/packages/block-editor/src/components/colors-gradients/panel-color-gradient-settings.js +++ b/packages/block-editor/src/components/colors-gradients/panel-color-gradient-settings.js @@ -34,7 +34,13 @@ const colorsAndGradientKeys = [ const Indicators = ( { colors, gradients, settings } ) => { return settings.map( ( - { colorValue, gradientValue, label, colors: availableColors, gradients: availableGradients }, + { + colorValue, + gradientValue, + label, + colors: availableColors, + gradients: availableGradients, + }, index ) => { if ( ! colorValue && ! gradientValue ) { @@ -42,7 +48,10 @@ const Indicators = ( { colors, gradients, settings } ) => { } let ariaLabel; if ( colorValue ) { - const colorObject = getColorObjectByColorValue( availableColors || colors, colorValue ); + const colorObject = getColorObjectByColorValue( + availableColors || colors, + colorValue + ); ariaLabel = sprintf( colorIndicatorAriaLabel, label.toLowerCase(), @@ -92,8 +101,10 @@ export const PanelColorGradientSettingsInner = ( { ( setting ) => isEmpty( setting.colors ) && isEmpty( setting.gradients ) && - ( setting.disableCustomColors === undefined || setting.disableCustomColors ) && - ( setting.disableCustomGradients === undefined || setting.disableCustomGradients ) + ( setting.disableCustomColors === undefined || + setting.disableCustomColors ) && + ( setting.disableCustomGradients === undefined || + setting.disableCustomGradients ) ) ) { return null; @@ -102,12 +113,19 @@ export const PanelColorGradientSettingsInner = ( { const titleElement = ( { title } - + ); return ( @@ -133,11 +151,17 @@ const PanelColorGradientSettingsSelect = ( props ) => { const settings = select( 'core/block-editor' ).getSettings(); return pick( settings, colorsAndGradientKeys ); } ); - return ; + return ( + + ); }; const PanelColorGradientSettings = ( props ) => { - if ( every( colorsAndGradientKeys, ( key ) => props.hasOwnProperty( key ) ) ) { + if ( + every( colorsAndGradientKeys, ( key ) => props.hasOwnProperty( key ) ) + ) { return ; } return ; diff --git a/packages/block-editor/src/components/colors-gradients/test/control.js b/packages/block-editor/src/components/colors-gradients/test/control.js index 1fbee94b7a5920..b3396bb0ce2e7f 100644 --- a/packages/block-editor/src/components/colors-gradients/test/control.js +++ b/packages/block-editor/src/components/colors-gradients/test/control.js @@ -11,11 +11,15 @@ import ColorGradientControl from '../control'; const getButtonWithTestPredicate = ( text ) => ( element ) => { return ( - element.type === 'button' && element.children[ 0 ] === text && element.children.length === 1 + element.type === 'button' && + element.children[ 0 ] === text && + element.children.length === 1 ); }; -const getButtonWithAriaLabelStartPredicate = ( ariaLabelStart ) => ( element ) => { +const getButtonWithAriaLabelStartPredicate = ( ariaLabelStart ) => ( + element +) => { return ( element.type === 'button' && element.props[ 'aria-label' ] && @@ -41,12 +45,14 @@ describe( 'ColorPaletteControl', () => { ] } gradients={ [ { - gradient: 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%', + gradient: + 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%', name: 'Vivid cyan blue to vivid purple', slug: 'vivid-cyan-blue-to-vivid-purple', }, { - gradient: 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', + gradient: + 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', name: 'Light green cyan to vivid green cyan', slug: 'light-green-cyan-to-vivid-green-cyan', }, @@ -60,8 +66,12 @@ describe( 'ColorPaletteControl', () => { } ); // Is showing the two tab buttons. - expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( 1 ); - expect( wrapper.root.findAll( gradientTabButtonPredicate ) ).toHaveLength( 1 ); + expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( + 1 + ); + expect( + wrapper.root.findAll( gradientTabButtonPredicate ) + ).toHaveLength( 1 ); // Is showing the two predefined Colors. expect( @@ -75,9 +85,9 @@ describe( 'ColorPaletteControl', () => { ).toHaveLength( 2 ); // Is showing the custom color picker. - expect( wrapper.root.findAll( getButtonWithTestPredicate( 'Custom Color' ) ) ).toHaveLength( - 1 - ); + expect( + wrapper.root.findAll( getButtonWithTestPredicate( 'Custom Color' ) ) + ).toHaveLength( 1 ); } ); it( 'renders the color picker and does not render tabs if it is only possible to select a color', async () => { @@ -102,18 +112,24 @@ describe( 'ColorPaletteControl', () => { } ); // Is not showing the two tab buttons. - expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( 0 ); - expect( wrapper.root.findAll( gradientTabButtonPredicate ) ).toHaveLength( 0 ); + expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( + 0 + ); + expect( + wrapper.root.findAll( gradientTabButtonPredicate ) + ).toHaveLength( 0 ); // Is showing the two predefined Colors. - expect( wrapper.root.findAll( getButtonWithAriaLabelStartPredicate( 'Color:' ) ) ).toHaveLength( - 2 - ); + expect( + wrapper.root.findAll( + getButtonWithAriaLabelStartPredicate( 'Color:' ) + ) + ).toHaveLength( 2 ); // Is showing the custom color picker. - expect( wrapper.root.findAll( getButtonWithTestPredicate( 'Custom Color' ) ) ).toHaveLength( - 1 - ); + expect( + wrapper.root.findAll( getButtonWithTestPredicate( 'Custom Color' ) ) + ).toHaveLength( 1 ); } ); it( 'renders the gradient picker and does not render tabs if it is only possible to select a gradient', async () => { @@ -127,12 +143,14 @@ describe( 'ColorPaletteControl', () => { colors={ [] } gradients={ [ { - gradient: 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%', + gradient: + 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%', name: 'Vivid cyan blue to vivid purple', slug: 'vivid-cyan-blue-to-vivid-purple', }, { - gradient: 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', + gradient: + 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', name: 'Light green cyan to vivid green cyan', slug: 'light-green-cyan-to-vivid-green-cyan', }, @@ -146,12 +164,18 @@ describe( 'ColorPaletteControl', () => { } ); // Is not showing the two tab buttons. - expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( 0 ); - expect( wrapper.root.findAll( gradientTabButtonPredicate ) ).toHaveLength( 0 ); + expect( wrapper.root.findAll( colorTabButtonPredicate ) ).toHaveLength( + 0 + ); + expect( + wrapper.root.findAll( gradientTabButtonPredicate ) + ).toHaveLength( 0 ); // Is showing the two predefined Gradients. expect( - wrapper.root.findAll( getButtonWithAriaLabelStartPredicate( 'Gradient:' ) ) + wrapper.root.findAll( + getButtonWithAriaLabelStartPredicate( 'Gradient:' ) + ) ).toHaveLength( 2 ); // Is showing the custom gradient picker. @@ -160,7 +184,9 @@ describe( 'ColorPaletteControl', () => { ( element ) => element.props && element.props.className && - element.props.className.includes( 'components-custom-gradient-picker' ) + element.props.className.includes( + 'components-custom-gradient-picker' + ) ).length ).toBeGreaterThanOrEqual( 1 ); } ); diff --git a/packages/block-editor/src/components/colors/test/utils.js b/packages/block-editor/src/components/colors/test/utils.js index 2402a6b9ddd9c6..1ed18cef831c8d 100644 --- a/packages/block-editor/src/components/colors/test/utils.js +++ b/packages/block-editor/src/components/colors/test/utils.js @@ -10,30 +10,60 @@ import { describe( 'color utils', () => { describe( 'getColorObjectByAttributeValues', () => { it( 'should return the custom color object when there is no definedColor', () => { - const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; + const colors = [ + { slug: 'red' }, + { slug: 'green' }, + { slug: 'blue' }, + ]; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, undefined, customColor ) ).toEqual( { + expect( + getColorObjectByAttributeValues( + colors, + undefined, + customColor + ) + ).toEqual( { color: customColor, } ); } ); it( 'should return the custom color object when definedColor was not found', () => { - const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; + const colors = [ + { slug: 'red' }, + { slug: 'green' }, + { slug: 'blue' }, + ]; const definedColor = 'purple'; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { + expect( + getColorObjectByAttributeValues( + colors, + definedColor, + customColor + ) + ).toEqual( { color: customColor, } ); } ); it( 'should return the found color object', () => { - const colors = [ { slug: 'red' }, { slug: 'green' }, { slug: 'blue' } ]; + const colors = [ + { slug: 'red' }, + { slug: 'green' }, + { slug: 'blue' }, + ]; const definedColor = 'blue'; const customColor = '#ffffff'; - expect( getColorObjectByAttributeValues( colors, definedColor, customColor ) ).toEqual( { + expect( + getColorObjectByAttributeValues( + colors, + definedColor, + customColor + ) + ).toEqual( { slug: 'blue', } ); } ); @@ -47,7 +77,9 @@ describe( 'color utils', () => { { slug: 'blue', color: '#0000ff' }, ]; - expect( getColorObjectByColorValue( colors, '#ffffff' ) ).toBeUndefined(); + expect( + getColorObjectByColorValue( colors, '#ffffff' ) + ).toBeUndefined(); } ); it( 'should return a color object for the given color value', () => { @@ -66,11 +98,15 @@ describe( 'color utils', () => { describe( 'getColorClassName', () => { it( 'should return undefined if colorContextName is missing', () => { - expect( getColorClassName( undefined, 'Light Purple' ) ).toBeUndefined(); + expect( + getColorClassName( undefined, 'Light Purple' ) + ).toBeUndefined(); } ); it( 'should return undefined if colorSlug is missing', () => { - expect( getColorClassName( 'background', undefined ) ).toBeUndefined(); + expect( + getColorClassName( 'background', undefined ) + ).toBeUndefined(); } ); it( 'should return a class name with the color slug in kebab case', () => { diff --git a/packages/block-editor/src/components/colors/test/with-colors.js b/packages/block-editor/src/components/colors/test/with-colors.js index 779ae78d64210a..acbc8659953ce0 100644 --- a/packages/block-editor/src/components/colors/test/with-colors.js +++ b/packages/block-editor/src/components/colors/test/with-colors.js @@ -13,9 +13,13 @@ describe( 'createCustomColorsHOC', () => { const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' }, ] ); - const EnhancedComponent = withCustomColors( 'backgroundColor' )( () =>
        ); + const EnhancedComponent = withCustomColors( 'backgroundColor' )( () => ( +
        + ) ); - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper.dive() ).toMatchSnapshot(); } ); @@ -24,14 +28,21 @@ describe( 'createCustomColorsHOC', () => { const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' }, ] ); - const EnhancedComponent = withCustomColors( 'backgroundColor' )( ( props ) => ( - + const EnhancedComponent = withCustomColors( + 'backgroundColor' + )( ( props ) => ( + ) ); const setAttributes = jest.fn(); const wrapper = mount( - + ); wrapper.find( 'button' ).simulate( 'click' ); @@ -45,14 +56,21 @@ describe( 'createCustomColorsHOC', () => { const withCustomColors = createCustomColorsHOC( [ { name: 'Red', slug: 'red', color: 'ff0000' }, ] ); - const EnhancedComponent = withCustomColors( 'backgroundColor' )( ( props ) => ( - + const EnhancedComponent = withCustomColors( + 'backgroundColor' + )( ( props ) => ( + ) ); const setAttributes = jest.fn(); const wrapper = mount( - + ); wrapper.find( 'button' ).simulate( 'click' ); diff --git a/packages/block-editor/src/components/colors/use-colors.js b/packages/block-editor/src/components/colors/use-colors.js index 375f6cbddfe523..8ff23ec2ab8d64 100644 --- a/packages/block-editor/src/components/colors/use-colors.js +++ b/packages/block-editor/src/components/colors/use-colors.js @@ -61,22 +61,28 @@ const ColorPanel = ( { > { contrastCheckers && ( Array.isArray( contrastCheckers ) - ? contrastCheckers.map( ( { backgroundColor, textColor, ...rest } ) => { - backgroundColor = resolveContrastCheckerColor( - backgroundColor, - colorSettings, - detectedBackgroundColor - ); - textColor = resolveContrastCheckerColor( textColor, colorSettings, detectedColor ); - return ( - - ); - } ) + ? contrastCheckers.map( + ( { backgroundColor, textColor, ...rest } ) => { + backgroundColor = resolveContrastCheckerColor( + backgroundColor, + colorSettings, + detectedBackgroundColor + ); + textColor = resolveContrastCheckerColor( + textColor, + colorSettings, + detectedColor + ); + return ( + + ); + } + ) : map( colorSettings, ( { value } ) => { let { backgroundColor, textColor } = contrastCheckers; backgroundColor = resolveContrastCheckerColor( @@ -98,7 +104,9 @@ const ColorPanel = ( { /> ); } ) ) } - { typeof panelChildren === 'function' ? panelChildren( colorSettings ) : panelChildren } + { typeof panelChildren === 'function' + ? panelChildren( colorSettings ) + : panelChildren } ); const InspectorControlsColorPanel = ( props ) => ( @@ -127,11 +135,14 @@ export default function __experimentalUseColors( const { clientId } = useBlockEditContext(); const { attributes, settingsColors } = useSelect( ( select ) => { - const { getBlockAttributes, getSettings } = select( 'core/block-editor' ); + const { getBlockAttributes, getSettings } = select( + 'core/block-editor' + ); const colors = getSettings().colors; return { attributes: getBlockAttributes( clientId ), - settingsColors: ! colors || colors === true ? DEFAULT_COLORS : colors, + settingsColors: + ! colors || colors === true ? DEFAULT_COLORS : colors, }; }, [ clientId ] @@ -145,7 +156,14 @@ export default function __experimentalUseColors( const createComponent = useMemo( () => memoize( - ( name, property, className, color, colorValue, customColor ) => ( { + ( + name, + property, + className, + color, + colorValue, + customColor + ) => ( { children, className: componentClassName = '', style: componentStyle = {}, @@ -161,10 +179,18 @@ export default function __experimentalUseColors( } return cloneElement( child, { - className: classnames( componentClassName, child.props.className, { - [ `has-${ kebabCase( color ) }-${ kebabCase( property ) }` ]: color, - [ className || `has-${ kebabCase( name ) }` ]: color || customColor, - } ), + className: classnames( + componentClassName, + child.props.className, + { + [ `has-${ kebabCase( color ) }-${ kebabCase( + property + ) }` ]: color, + [ className || + `has-${ kebabCase( name ) }` ]: + color || customColor, + } + ), style: { ...colorStyle, ...componentStyle, @@ -180,12 +206,20 @@ export default function __experimentalUseColors( () => memoize( ( name, colors ) => ( newColor ) => { - const color = colors.find( ( _color ) => _color.color === newColor ); + const color = colors.find( + ( _color ) => _color.color === newColor + ); setAttributes( { - [ color ? camelCase( `custom ${ name }` ) : name ]: undefined, + [ color + ? camelCase( `custom ${ name }` ) + : name ]: undefined, } ); setAttributes( { - [ color ? name : camelCase( `custom ${ name }` ) ]: color ? color.slug : newColor, + [ color + ? name + : camelCase( `custom ${ name }` ) ]: color + ? color.slug + : newColor, } ); }, { @@ -204,7 +238,9 @@ export default function __experimentalUseColors( } let needsBackgroundColor = false; let needsColor = false; - for ( const { backgroundColor, textColor } of castArray( contrastCheckers ) ) { + for ( const { backgroundColor, textColor } of castArray( + contrastCheckers + ) ) { if ( ! needsBackgroundColor ) { needsBackgroundColor = backgroundColor === true; } @@ -217,19 +253,23 @@ export default function __experimentalUseColors( } if ( needsColor ) { - setDetectedColor( getComputedStyle( textColorTargetRef.current ).color ); + setDetectedColor( + getComputedStyle( textColorTargetRef.current ).color + ); } if ( needsBackgroundColor ) { let backgroundColorNode = backgroundColorTargetRef.current; - let backgroundColor = getComputedStyle( backgroundColorNode ).backgroundColor; + let backgroundColor = getComputedStyle( backgroundColorNode ) + .backgroundColor; while ( backgroundColor === 'rgba(0, 0, 0, 0)' && backgroundColorNode.parentNode && backgroundColorNode.parentNode.nodeType === Node.ELEMENT_NODE ) { backgroundColorNode = backgroundColorNode.parentNode; - backgroundColor = getComputedStyle( backgroundColorNode ).backgroundColor; + backgroundColor = getComputedStyle( backgroundColorNode ) + .backgroundColor; } setDetectedBackgroundColor( backgroundColor ); @@ -270,7 +310,9 @@ export default function __experimentalUseColors( const customColor = attributes[ camelCase( `custom ${ name }` ) ]; // We memoize the non-primitives to avoid unnecessary updates // when they are used as props for other components. - const _color = customColor ? undefined : colors.find( ( __color ) => __color.slug === color ); + const _color = customColor + ? undefined + : colors.find( ( __color ) => __color.slug === color ); acc[ componentName ] = createComponent( name, property, @@ -280,12 +322,16 @@ export default function __experimentalUseColors( customColor ); acc[ componentName ].displayName = componentName; - acc[ componentName ].color = customColor ? customColor : _color && _color.color; + acc[ componentName ].color = customColor + ? customColor + : _color && _color.color; acc[ componentName ].slug = color; acc[ componentName ].setColor = createSetColor( name, colors ); colorSettings[ componentName ] = { - value: _color ? _color.color : attributes[ camelCase( `custom ${ name }` ) ], + value: _color + ? _color.color + : attributes[ camelCase( `custom ${ name }` ) ], onChange: acc[ componentName ].setColor, label: panelLabel, colors, @@ -314,7 +360,15 @@ export default function __experimentalUseColors( return { ...components, ColorPanel: , - InspectorControlsColorPanel: , + InspectorControlsColorPanel: ( + + ), }; - }, [ attributes, setAttributes, detectedColor, detectedBackgroundColor, ...deps ] ); + }, [ + attributes, + setAttributes, + detectedColor, + detectedBackgroundColor, + ...deps, + ] ); } diff --git a/packages/block-editor/src/components/colors/utils.js b/packages/block-editor/src/components/colors/utils.js index f32f23da79c558..903d7033eedee9 100644 --- a/packages/block-editor/src/components/colors/utils.js +++ b/packages/block-editor/src/components/colors/utils.js @@ -16,7 +16,11 @@ import tinycolor from 'tinycolor2'; * the color object exactly as set by the theme or editor defaults is returned. * Otherwise, an object that just sets the color is defined. */ -export const getColorObjectByAttributeValues = ( colors, definedColor, customColor ) => { +export const getColorObjectByAttributeValues = ( + colors, + definedColor, + customColor +) => { if ( definedColor ) { const colorObj = find( colors, { slug: definedColor } ); @@ -68,5 +72,7 @@ export function getColorClassName( colorContextName, colorSlug ) { * @return {string} String with the color value of the most readable color. */ export function getMostReadableColor( colors, colorValue ) { - return tinycolor.mostReadable( colorValue, map( colors, 'color' ) ).toHexString(); + return tinycolor + .mostReadable( colorValue, map( colors, 'color' ) ) + .toHexString(); } diff --git a/packages/block-editor/src/components/colors/with-colors.js b/packages/block-editor/src/components/colors/with-colors.js index 8aa46c957ddaac..6bd4a66d5c40eb 100644 --- a/packages/block-editor/src/components/colors/with-colors.js +++ b/packages/block-editor/src/components/colors/with-colors.js @@ -32,7 +32,9 @@ const DEFAULT_COLORS = []; */ const withCustomColorPalette = ( colorsArray ) => createHigherOrderComponent( - ( WrappedComponent ) => ( props ) => , + ( WrappedComponent ) => ( props ) => ( + + ), 'withCustomColorPalette' ); @@ -65,7 +67,9 @@ function createColorHOC( colorTypes, withColorPalette ) { ( colorObject, colorType ) => { return { ...colorObject, - ...( isString( colorType ) ? { [ colorType ]: kebabCase( colorType ) } : colorType ), + ...( isString( colorType ) + ? { [ colorType ]: kebabCase( colorType ) } + : colorType ), }; }, {} @@ -80,7 +84,9 @@ function createColorHOC( colorTypes, withColorPalette ) { this.setters = this.createSetters(); this.colorUtils = { - getMostReadableColor: this.getMostReadableColor.bind( this ), + getMostReadableColor: this.getMostReadableColor.bind( + this + ), }; this.state = {}; @@ -94,10 +100,18 @@ function createColorHOC( colorTypes, withColorPalette ) { createSetters() { return reduce( colorMap, - ( settersAccumulator, colorContext, colorAttributeName ) => { - const upperFirstColorAttributeName = upperFirst( colorAttributeName ); + ( + settersAccumulator, + colorContext, + colorAttributeName + ) => { + const upperFirstColorAttributeName = upperFirst( + colorAttributeName + ); const customColorAttributeName = `custom${ upperFirstColorAttributeName }`; - settersAccumulator[ `set${ upperFirstColorAttributeName }` ] = this.createSetColor( + settersAccumulator[ + `set${ upperFirstColorAttributeName }` + ] = this.createSetColor( colorAttributeName, customColorAttributeName ); @@ -109,39 +123,64 @@ function createColorHOC( colorTypes, withColorPalette ) { createSetColor( colorAttributeName, customColorAttributeName ) { return ( colorValue ) => { - const colorObject = getColorObjectByColorValue( this.props.colors, colorValue ); + const colorObject = getColorObjectByColorValue( + this.props.colors, + colorValue + ); this.props.setAttributes( { [ colorAttributeName ]: - colorObject && colorObject.slug ? colorObject.slug : undefined, + colorObject && colorObject.slug + ? colorObject.slug + : undefined, [ customColorAttributeName ]: - colorObject && colorObject.slug ? undefined : colorValue, + colorObject && colorObject.slug + ? undefined + : colorValue, } ); }; } - static getDerivedStateFromProps( { attributes, colors }, previousState ) { + static getDerivedStateFromProps( + { attributes, colors }, + previousState + ) { return reduce( colorMap, ( newState, colorContext, colorAttributeName ) => { const colorObject = getColorObjectByAttributeValues( colors, attributes[ colorAttributeName ], - attributes[ `custom${ upperFirst( colorAttributeName ) }` ] + attributes[ + `custom${ upperFirst( + colorAttributeName + ) }` + ] ); - const previousColorObject = previousState[ colorAttributeName ]; - const previousColor = get( previousColorObject, [ 'color' ] ); + const previousColorObject = + previousState[ colorAttributeName ]; + const previousColor = get( previousColorObject, [ + 'color', + ] ); /** * The "and previousColorObject" condition checks that a previous color object was already computed. * At the start previousColorObject and colorValue are both equal to undefined * bus as previousColorObject does not exist we should compute the object. */ - if ( previousColor === colorObject.color && previousColorObject ) { - newState[ colorAttributeName ] = previousColorObject; + if ( + previousColor === colorObject.color && + previousColorObject + ) { + newState[ + colorAttributeName + ] = previousColorObject; } else { newState[ colorAttributeName ] = { ...colorObject, - class: getColorClassName( colorContext, colorObject.slug ), + class: getColorClassName( + colorContext, + colorObject.slug + ), }; } return newState; @@ -226,5 +265,8 @@ export function createCustomColorsHOC( colorsArray ) { */ export default function withColors( ...colorTypes ) { const withColorPalette = withEditorColorPalette(); - return createHigherOrderComponent( createColorHOC( colorTypes, withColorPalette ), 'withColors' ); + return createHigherOrderComponent( + createColorHOC( colorTypes, withColorPalette ), + 'withColors' + ); } diff --git a/packages/block-editor/src/components/contrast-checker/index.js b/packages/block-editor/src/components/contrast-checker/index.js index a497bcff15c17a..e75eb24278dd9b 100644 --- a/packages/block-editor/src/components/contrast-checker/index.js +++ b/packages/block-editor/src/components/contrast-checker/index.js @@ -45,18 +45,27 @@ function ContrastChecker( { isLargeText, textColor, } ) { - if ( ! ( backgroundColor || fallbackBackgroundColor ) || ! ( textColor || fallbackTextColor ) ) { + if ( + ! ( backgroundColor || fallbackBackgroundColor ) || + ! ( textColor || fallbackTextColor ) + ) { return null; } - const tinyBackgroundColor = tinycolor( backgroundColor || fallbackBackgroundColor ); + const tinyBackgroundColor = tinycolor( + backgroundColor || fallbackBackgroundColor + ); const tinyTextColor = tinycolor( textColor || fallbackTextColor ); - const hasTransparency = tinyBackgroundColor.getAlpha() !== 1 || tinyTextColor.getAlpha() !== 1; + const hasTransparency = + tinyBackgroundColor.getAlpha() !== 1 || tinyTextColor.getAlpha() !== 1; if ( hasTransparency || tinycolor.isReadable( tinyBackgroundColor, tinyTextColor, { level: 'AA', - size: isLargeText || ( isLargeText !== false && fontSize >= 24 ) ? 'large' : 'small', + size: + isLargeText || ( isLargeText !== false && fontSize >= 24 ) + ? 'large' + : 'small', } ) ) { return null; diff --git a/packages/block-editor/src/components/contrast-checker/test/index.js b/packages/block-editor/src/components/contrast-checker/test/index.js index 5db1977b3b17c1..8d358437e4d9c5 100644 --- a/packages/block-editor/src/components/contrast-checker/test/index.js +++ b/packages/block-editor/src/components/contrast-checker/test/index.js @@ -114,7 +114,11 @@ describe( 'ContrastChecker', () => { test( 'should take into consideration wherever text is large or not', () => { const wrapperSmallText = mount( - + ); expect( @@ -127,7 +131,11 @@ describe( 'ContrastChecker', () => { ); const wrapperLargeText = mount( - + ); expect( wrapperLargeText.html() ).toBeNull(); @@ -135,7 +143,11 @@ describe( 'ContrastChecker', () => { test( 'should take into consideration the font size passed', () => { const wrapperSmallFontSize = mount( - + ); expect( @@ -148,7 +160,11 @@ describe( 'ContrastChecker', () => { ); const wrapperLargeText = mount( - + ); expect( wrapperLargeText.html() ).toBeNull(); @@ -199,7 +215,10 @@ describe( 'ContrastChecker', () => { test( 'should render messages when the textColor is valid, but the fallback backgroundColor conflicts.', () => { const wrapper = mount( - + ); expect( diff --git a/packages/block-editor/src/components/copy-handler/index.js b/packages/block-editor/src/components/copy-handler/index.js index 8de1ed7ac8065e..be6e03097a4671 100644 --- a/packages/block-editor/src/components/copy-handler/index.js +++ b/packages/block-editor/src/components/copy-handler/index.js @@ -28,7 +28,9 @@ export default compose( [ getSettings, } = select( 'core/block-editor' ); const { removeBlocks, replaceBlocks } = dispatch( 'core/block-editor' ); - const { __experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML } = getSettings(); + const { + __experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML, + } = getSettings(); return { handler( event ) { @@ -47,7 +49,9 @@ export default compose( [ event.preventDefault(); if ( event.type === 'copy' || event.type === 'cut' ) { - const blocks = getBlocksByClientId( selectedBlockClientIds ); + const blocks = getBlocksByClientId( + selectedBlockClientIds + ); const serialized = serialize( blocks ); event.clipboardData.setData( 'text/plain', serialized ); diff --git a/packages/block-editor/src/components/default-block-appender/index.js b/packages/block-editor/src/components/default-block-appender/index.js index 4aaad580ff3868..865f9a76f226e1 100644 --- a/packages/block-editor/src/components/default-block-appender/index.js +++ b/packages/block-editor/src/components/default-block-appender/index.js @@ -29,7 +29,9 @@ export function DefaultBlockAppender( { return null; } - const value = decodeEntities( placeholder ) || __( 'Start writing or type / to choose a block' ); + const value = + decodeEntities( placeholder ) || + __( 'Start writing or type / to choose a block' ); // The appender "button" is in-fact a text field so as to support // transitions by WritingFlow occurring by arrow key press. WritingFlow @@ -59,19 +61,29 @@ export function DefaultBlockAppender( { onFocus={ onAppend } value={ showPrompt ? value : '' } /> - +
        ); } export default compose( withSelect( ( select, ownProps ) => { - const { getBlockCount, getBlockName, isBlockValid, getSettings, getTemplateLock } = select( - 'core/block-editor' - ); + const { + getBlockCount, + getBlockName, + isBlockValid, + getSettings, + getTemplateLock, + } = select( 'core/block-editor' ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); - const isLastBlockDefault = getBlockName( ownProps.lastBlockClientId ) === getDefaultBlockName(); + const isLastBlockDefault = + getBlockName( ownProps.lastBlockClientId ) === + getDefaultBlockName(); const isLastBlockValid = isBlockValid( ownProps.lastBlockClientId ); const { bodyPlaceholder } = getSettings(); @@ -83,7 +95,9 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { insertDefaultBlock, startTyping } = dispatch( 'core/block-editor' ); + const { insertDefaultBlock, startTyping } = dispatch( + 'core/block-editor' + ); return { onAppend() { diff --git a/packages/block-editor/src/components/default-block-appender/index.native.js b/packages/block-editor/src/components/default-block-appender/index.native.js index 7f6390d1fa2aad..726c060241d63e 100644 --- a/packages/block-editor/src/components/default-block-appender/index.native.js +++ b/packages/block-editor/src/components/default-block-appender/index.native.js @@ -30,11 +30,16 @@ export function DefaultBlockAppender( { } const value = - typeof placeholder === 'string' ? decodeEntities( placeholder ) : __( 'Start writingโ€ฆ' ); + typeof placeholder === 'string' + ? decodeEntities( placeholder ) + : __( 'Start writingโ€ฆ' ); return ( - + {} } /> @@ -43,12 +48,17 @@ export function DefaultBlockAppender( { export default compose( withSelect( ( select, ownProps ) => { - const { getBlockCount, getBlockName, isBlockValid, getTemplateLock } = select( - 'core/block-editor' - ); + const { + getBlockCount, + getBlockName, + isBlockValid, + getTemplateLock, + } = select( 'core/block-editor' ); const isEmpty = ! getBlockCount( ownProps.rootClientId ); - const isLastBlockDefault = getBlockName( ownProps.lastBlockClientId ) === getDefaultBlockName(); + const isLastBlockDefault = + getBlockName( ownProps.lastBlockClientId ) === + getDefaultBlockName(); const isLastBlockValid = isBlockValid( ownProps.lastBlockClientId ); return { @@ -57,7 +67,9 @@ export default compose( }; } ), withDispatch( ( dispatch, ownProps ) => { - const { insertDefaultBlock, startTyping } = dispatch( 'core/block-editor' ); + const { insertDefaultBlock, startTyping } = dispatch( + 'core/block-editor' + ); return { onAppend() { diff --git a/packages/block-editor/src/components/default-block-appender/test/index.js b/packages/block-editor/src/components/default-block-appender/test/index.js index 4035827b2d2d13..407adb838f9aae 100644 --- a/packages/block-editor/src/components/default-block-appender/test/index.js +++ b/packages/block-editor/src/components/default-block-appender/test/index.js @@ -22,14 +22,18 @@ describe( 'DefaultBlockAppender', () => { it( 'should match snapshot', () => { const onAppend = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); expect( wrapper ).toMatchSnapshot(); } ); it( 'should append a default block when input focused', () => { const onAppend = jest.fn(); - const wrapper = shallow( ); + const wrapper = shallow( + + ); wrapper.find( 'TextareaAutosize' ).simulate( 'focus' ); @@ -41,7 +45,11 @@ describe( 'DefaultBlockAppender', () => { it( 'should optionally show without prompt', () => { const onAppend = jest.fn(); const wrapper = shallow( - + ); const input = wrapper.find( 'TextareaAutosize' ); diff --git a/packages/block-editor/src/components/default-style-picker/index.js b/packages/block-editor/src/components/default-style-picker/index.js index 011e2061b6112c..5880d8bd5850b3 100644 --- a/packages/block-editor/src/components/default-style-picker/index.js +++ b/packages/block-editor/src/components/default-style-picker/index.js @@ -12,13 +12,25 @@ import { SelectControl } from '@wordpress/components'; import { useSelect } from '@wordpress/data'; export default function DefaultStylePicker( { blockName } ) { - const { preferredStyle, onUpdatePreferredStyleVariations, styles } = useSelect( + const { + preferredStyle, + onUpdatePreferredStyleVariations, + styles, + } = useSelect( ( select ) => { const settings = select( 'core/block-editor' ).getSettings(); - const preferredStyleVariations = settings.__experimentalPreferredStyleVariations; + const preferredStyleVariations = + settings.__experimentalPreferredStyleVariations; return { - preferredStyle: get( preferredStyleVariations, [ 'value', blockName ] ), - onUpdatePreferredStyleVariations: get( preferredStyleVariations, [ 'onChange' ], null ), + preferredStyle: get( preferredStyleVariations, [ + 'value', + blockName, + ] ), + onUpdatePreferredStyleVariations: get( + preferredStyleVariations, + [ 'onChange' ], + null + ), styles: select( 'core/blocks' ).getBlockStyles( blockName ), }; }, diff --git a/packages/block-editor/src/components/font-sizes/font-size-picker.js b/packages/block-editor/src/components/font-sizes/font-size-picker.js index 57bf783fd6bef8..9200924ad22be8 100644 --- a/packages/block-editor/src/components/font-sizes/font-size-picker.js +++ b/packages/block-editor/src/components/font-sizes/font-size-picker.js @@ -5,7 +5,9 @@ import { FontSizePicker } from '@wordpress/components'; import { withSelect } from '@wordpress/data'; export default withSelect( ( select ) => { - const { disableCustomFontSizes, fontSizes } = select( 'core/block-editor' ).getSettings(); + const { disableCustomFontSizes, fontSizes } = select( + 'core/block-editor' + ).getSettings(); return { disableCustomFontSizes, diff --git a/packages/block-editor/src/components/font-sizes/utils.js b/packages/block-editor/src/components/font-sizes/utils.js index 09de76dcf7f6aa..17f3cfe680dc75 100644 --- a/packages/block-editor/src/components/font-sizes/utils.js +++ b/packages/block-editor/src/components/font-sizes/utils.js @@ -14,7 +14,11 @@ import { find, kebabCase } from 'lodash'; * @return {?string} If fontSizeAttribute is set and an equal slug is found in fontSizes it returns the font size object for that slug. * Otherwise, an object with just the size value based on customFontSize is returned. */ -export const getFontSize = ( fontSizes, fontSizeAttribute, customFontSizeAttribute ) => { +export const getFontSize = ( + fontSizes, + fontSizeAttribute, + customFontSizeAttribute +) => { if ( fontSizeAttribute ) { const fontSizeObject = find( fontSizes, { slug: fontSizeAttribute } ); if ( fontSizeObject ) { diff --git a/packages/block-editor/src/components/font-sizes/with-font-sizes.js b/packages/block-editor/src/components/font-sizes/with-font-sizes.js index c89b31214f544b..4476484d30a3d6 100644 --- a/packages/block-editor/src/components/font-sizes/with-font-sizes.js +++ b/packages/block-editor/src/components/font-sizes/with-font-sizes.js @@ -34,9 +34,9 @@ export default ( ...fontSizeNames ) => { const fontSizeAttributeNames = reduce( fontSizeNames, ( fontSizeAttributeNamesAccumulator, fontSizeAttributeName ) => { - fontSizeAttributeNamesAccumulator[ fontSizeAttributeName ] = `custom${ upperFirst( + fontSizeAttributeNamesAccumulator[ fontSizeAttributeName - ) }`; + ] = `custom${ upperFirst( fontSizeAttributeName ) }`; return fontSizeAttributeNamesAccumulator; }, {} @@ -45,7 +45,9 @@ export default ( ...fontSizeNames ) => { return createHigherOrderComponent( compose( [ withSelect( ( select ) => { - const { fontSizes } = select( 'core/block-editor' ).getSettings(); + const { fontSizes } = select( + 'core/block-editor' + ).getSettings(); return { fontSizes, }; @@ -63,44 +65,68 @@ export default ( ...fontSizeNames ) => { createSetters() { return reduce( fontSizeAttributeNames, - ( settersAccumulator, customFontSizeAttributeName, fontSizeAttributeName ) => { - const upperFirstFontSizeAttributeName = upperFirst( fontSizeAttributeName ); + ( + settersAccumulator, + customFontSizeAttributeName, + fontSizeAttributeName + ) => { + const upperFirstFontSizeAttributeName = upperFirst( + fontSizeAttributeName + ); settersAccumulator[ `set${ upperFirstFontSizeAttributeName }` - ] = this.createSetFontSize( fontSizeAttributeName, customFontSizeAttributeName ); + ] = this.createSetFontSize( + fontSizeAttributeName, + customFontSizeAttributeName + ); return settersAccumulator; }, {} ); } - createSetFontSize( fontSizeAttributeName, customFontSizeAttributeName ) { + createSetFontSize( + fontSizeAttributeName, + customFontSizeAttributeName + ) { return ( fontSizeValue ) => { const fontSizeObject = find( this.props.fontSizes, { size: Number( fontSizeValue ), } ); this.props.setAttributes( { [ fontSizeAttributeName ]: - fontSizeObject && fontSizeObject.slug ? fontSizeObject.slug : undefined, + fontSizeObject && fontSizeObject.slug + ? fontSizeObject.slug + : undefined, [ customFontSizeAttributeName ]: - fontSizeObject && fontSizeObject.slug ? undefined : fontSizeValue, + fontSizeObject && fontSizeObject.slug + ? undefined + : fontSizeValue, } ); }; } - static getDerivedStateFromProps( { attributes, fontSizes }, previousState ) { - const didAttributesChange = ( customFontSizeAttributeName, fontSizeAttributeName ) => { + static getDerivedStateFromProps( + { attributes, fontSizes }, + previousState + ) { + const didAttributesChange = ( + customFontSizeAttributeName, + fontSizeAttributeName + ) => { if ( previousState[ fontSizeAttributeName ] ) { // if new font size is name compare with the previous slug if ( attributes[ fontSizeAttributeName ] ) { return ( attributes[ fontSizeAttributeName ] !== - previousState[ fontSizeAttributeName ].slug + previousState[ fontSizeAttributeName ] + .slug ); } // if font size is not named, update when the font size value changes. return ( - previousState[ fontSizeAttributeName ].size !== + previousState[ fontSizeAttributeName ] + .size !== attributes[ customFontSizeAttributeName ] ); } @@ -108,14 +134,27 @@ export default ( ...fontSizeNames ) => { return true; }; - if ( ! some( fontSizeAttributeNames, didAttributesChange ) ) { + if ( + ! some( + fontSizeAttributeNames, + didAttributesChange + ) + ) { return null; } const newState = reduce( - pickBy( fontSizeAttributeNames, didAttributesChange ), - ( newStateAccumulator, customFontSizeAttributeName, fontSizeAttributeName ) => { - const fontSizeAttributeValue = attributes[ fontSizeAttributeName ]; + pickBy( + fontSizeAttributeNames, + didAttributesChange + ), + ( + newStateAccumulator, + customFontSizeAttributeName, + fontSizeAttributeName + ) => { + const fontSizeAttributeValue = + attributes[ fontSizeAttributeName ]; const fontSizeObject = getFontSize( fontSizes, fontSizeAttributeValue, @@ -123,7 +162,9 @@ export default ( ...fontSizeNames ) => { ); newStateAccumulator[ fontSizeAttributeName ] = { ...fontSizeObject, - class: getFontSizeClass( fontSizeAttributeValue ), + class: getFontSizeClass( + fontSizeAttributeValue + ), }; return newStateAccumulator; }, diff --git a/packages/block-editor/src/components/gradient-picker/control.js b/packages/block-editor/src/components/gradient-picker/control.js index 843d0d98d20e35..f57802aada39b1 100644 --- a/packages/block-editor/src/components/gradient-picker/control.js +++ b/packages/block-editor/src/components/gradient-picker/control.js @@ -35,7 +35,12 @@ export default function( { return null; } return ( - + { label } ; diff --git a/packages/block-editor/src/components/gradients/index.js b/packages/block-editor/src/components/gradients/index.js index 9fed4ff267ec8f..988ca37da2cfe3 100644 --- a/packages/block-editor/src/components/gradients/index.js +++ b/packages/block-editor/src/components/gradients/index.js @@ -26,13 +26,19 @@ function getGradientValueBySlug( gradients, slug ) { return gradient && gradient.gradient; } -export function __experimentalGetGradientObjectByGradientValue( gradients, value ) { +export function __experimentalGetGradientObjectByGradientValue( + gradients, + value +) { const gradient = find( gradients, [ 'gradient', value ] ); return gradient; } function getGradientSlugByValue( gradients, value ) { - const gradient = __experimentalGetGradientObjectByGradientValue( gradients, value ); + const gradient = __experimentalGetGradientObjectByGradientValue( + gradients, + value + ); return gradient && gradient.slug; } @@ -44,7 +50,9 @@ export function __experimentalUseGradient( { const { gradients, gradient, customGradient } = useSelect( ( select ) => { - const { getBlockAttributes, getSettings } = select( 'core/block-editor' ); + const { getBlockAttributes, getSettings } = select( + 'core/block-editor' + ); const attributes = getBlockAttributes( clientId ); return { gradient: attributes[ gradientAttribute ], diff --git a/packages/block-editor/src/components/image-size-control/index.js b/packages/block-editor/src/components/image-size-control/index.js index af4e40b3a37baf..1637c6c6115327 100644 --- a/packages/block-editor/src/components/image-size-control/index.js +++ b/packages/block-editor/src/components/image-size-control/index.js @@ -7,7 +7,12 @@ import { isEmpty, noop } from 'lodash'; * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { Button, ButtonGroup, SelectControl, TextControl } from '@wordpress/components'; +import { + Button, + ButtonGroup, + SelectControl, + TextControl, +} from '@wordpress/components'; import { Component } from '@wordpress/element'; class ImageSizeControl extends Component { @@ -53,7 +58,9 @@ class ImageSizeControl extends Component { ) } { isResizable && (
        -

        { __( 'Image Dimensions' ) }

        +

        + { __( 'Image Dimensions' ) } +

        onChange( { width: parseInt( value, 10 ) } ) } + onChange={ ( value ) => + onChange( { width: parseInt( value, 10 ) } ) + } /> onChange( { height: parseInt( value, 10 ) } ) } + onChange={ ( value ) => + onChange( { + height: parseInt( value, 10 ), + } ) + } />
        { [ 25, 50, 75, 100 ].map( ( scale ) => { - const scaledWidth = Math.round( imageWidth * ( scale / 100 ) ); - const scaledHeight = Math.round( imageHeight * ( scale / 100 ) ); + const scaledWidth = Math.round( + imageWidth * ( scale / 100 ) + ); + const scaledHeight = Math.round( + imageHeight * ( scale / 100 ) + ); - const isCurrent = width === scaledWidth && height === scaledHeight; + const isCurrent = + width === scaledWidth && + height === scaledHeight; return ( diff --git a/packages/block-editor/src/components/index.native.js b/packages/block-editor/src/components/index.native.js index 59c30699c588f1..0227ceabcc6470 100644 --- a/packages/block-editor/src/components/index.native.js +++ b/packages/block-editor/src/components/index.native.js @@ -18,7 +18,11 @@ export { __unstableRichTextInputEvent, } from './rich-text'; export { default as MediaPlaceholder } from './media-placeholder'; -export { default as MediaUpload, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO } from './media-upload'; +export { + default as MediaUpload, + MEDIA_TYPE_IMAGE, + MEDIA_TYPE_VIDEO, +} from './media-upload'; export { default as MediaUploadProgress } from './media-upload-progress'; export { default as MediaEdit } from './media-edit'; export { default as URLInput } from './url-input'; diff --git a/packages/block-editor/src/components/inner-blocks/button-block-appender.js b/packages/block-editor/src/components/inner-blocks/button-block-appender.js index 8a61844b67d8ff..5823a5e42c7b0c 100644 --- a/packages/block-editor/src/components/inner-blocks/button-block-appender.js +++ b/packages/block-editor/src/components/inner-blocks/button-block-appender.js @@ -5,7 +5,12 @@ import BaseButtonBlockAppender from '../button-block-appender'; import withClientId from './with-client-id'; export const ButtonBlockAppender = ( { clientId, showSeparator } ) => { - return ; + return ( + + ); }; export default withClientId( ButtonBlockAppender ); diff --git a/packages/block-editor/src/components/inner-blocks/default-block-appender.js b/packages/block-editor/src/components/inner-blocks/default-block-appender.js index 2b2774609cb126..4874704148e918 100644 --- a/packages/block-editor/src/components/inner-blocks/default-block-appender.js +++ b/packages/block-editor/src/components/inner-blocks/default-block-appender.js @@ -17,7 +17,10 @@ import withClientId from './with-client-id'; export const DefaultBlockAppender = ( { clientId, lastBlockClientId } ) => { return ( - + ); }; diff --git a/packages/block-editor/src/components/inner-blocks/index.js b/packages/block-editor/src/components/inner-blocks/index.js index b749922ae0478f..c8a54479d420df 100644 --- a/packages/block-editor/src/components/inner-blocks/index.js +++ b/packages/block-editor/src/components/inner-blocks/index.js @@ -10,7 +10,10 @@ import classnames from 'classnames'; import { withViewportMatch } from '@wordpress/viewport'; import { Component } from '@wordpress/element'; import { withSelect, withDispatch } from '@wordpress/data'; -import { synchronizeBlocksWithTemplate, withBlockContentContext } from '@wordpress/blocks'; +import { + synchronizeBlocksWithTemplate, + withBlockContentContext, +} from '@wordpress/blocks'; import isShallowEqual from '@wordpress/is-shallow-equal'; import { compose } from '@wordpress/compose'; @@ -76,7 +79,10 @@ class InnerBlocks extends Component { this.updateNestedSettings(); // Only synchronize innerBlocks with template if innerBlocks are empty or a locking all exists directly on the block. if ( innerBlocks.length === 0 || templateLock === 'all' ) { - const hasTemplateChanged = ! isEqual( template, prevProps.template ); + const hasTemplateChanged = ! isEqual( + template, + prevProps.template + ); if ( hasTemplateChanged ) { this.synchronizeBlocksWithTemplate(); } @@ -101,7 +107,10 @@ class InnerBlocks extends Component { const { innerBlocks } = block; // Synchronize with templates. If the next set differs, replace. - const nextBlocks = synchronizeBlocksWithTemplate( innerBlocks, template ); + const nextBlocks = synchronizeBlocksWithTemplate( + innerBlocks, + template + ); if ( ! isEqual( nextBlocks, innerBlocks ) ) { replaceInnerBlocks( nextBlocks ); } @@ -121,8 +130,10 @@ class InnerBlocks extends Component { const newSettings = { allowedBlocks, - templateLock: templateLock === undefined ? parentLock : templateLock, - __experimentalCaptureToolbars: __experimentalCaptureToolbars || false, + templateLock: + templateLock === undefined ? parentLock : templateLock, + __experimentalCaptureToolbars: + __experimentalCaptureToolbars || false, __experimentalMoverDirection, __experimentalUIParts, }; @@ -149,7 +160,9 @@ class InnerBlocks extends Component { return (
        - { ! templateInProcess && } + { ! templateInProcess && ( + + ) }
        ); } @@ -191,14 +204,20 @@ InnerBlocks = compose( [ __unstableMarkNextChangeAsNotPersistent, updateBlockListSettings, } = dispatch( 'core/block-editor' ); - const { block, clientId, templateInsertUpdatesSelection = true } = ownProps; + const { + block, + clientId, + templateInsertUpdatesSelection = true, + } = ownProps; return { replaceInnerBlocks( blocks ) { replaceInnerBlocks( clientId, blocks, - block.innerBlocks.length === 0 && templateInsertUpdatesSelection && blocks.length !== 0 + block.innerBlocks.length === 0 && + templateInsertUpdatesSelection && + blocks.length !== 0 ); }, __unstableMarkNextChangeAsNotPersistent, @@ -213,7 +232,9 @@ InnerBlocks = compose( [ InnerBlocks.DefaultBlockAppender = DefaultBlockAppender; InnerBlocks.ButtonBlockAppender = ButtonBlockAppender; -InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ); +InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ( + +) ); /** * @see https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inner-blocks/README.md diff --git a/packages/block-editor/src/components/inner-blocks/index.native.js b/packages/block-editor/src/components/inner-blocks/index.native.js index 7f591edeaa59ce..6ff8468565921c 100644 --- a/packages/block-editor/src/components/inner-blocks/index.native.js +++ b/packages/block-editor/src/components/inner-blocks/index.native.js @@ -8,7 +8,10 @@ import { pick, isEqual } from 'lodash'; */ import { Component } from '@wordpress/element'; import { withSelect, withDispatch } from '@wordpress/data'; -import { synchronizeBlocksWithTemplate, withBlockContentContext } from '@wordpress/blocks'; +import { + synchronizeBlocksWithTemplate, + withBlockContentContext, +} from '@wordpress/blocks'; import isShallowEqual from '@wordpress/is-shallow-equal'; import { compose } from '@wordpress/compose'; @@ -59,7 +62,10 @@ class InnerBlocks extends Component { this.updateNestedSettings(); // only synchronize innerBlocks with template if innerBlocks are empty or a locking all exists if ( innerBlocks.length === 0 || this.getTemplateLock() === 'all' ) { - const hasTemplateChanged = ! isEqual( template, prevProps.template ); + const hasTemplateChanged = ! isEqual( + template, + prevProps.template + ); if ( hasTemplateChanged ) { this.synchronizeBlocksWithTemplate(); } @@ -76,14 +82,21 @@ class InnerBlocks extends Component { const { innerBlocks } = block; // Synchronize with templates. If the next set differs, replace. - const nextBlocks = synchronizeBlocksWithTemplate( innerBlocks, template ); + const nextBlocks = synchronizeBlocksWithTemplate( + innerBlocks, + template + ); if ( ! isEqual( nextBlocks, innerBlocks ) ) { replaceInnerBlocks( nextBlocks ); } } updateNestedSettings() { - const { blockListSettings, allowedBlocks, updateNestedSettings } = this.props; + const { + blockListSettings, + allowedBlocks, + updateNestedSettings, + } = this.props; const newSettings = { allowedBlocks, @@ -140,15 +153,22 @@ InnerBlocks = compose( [ }; } ), withDispatch( ( dispatch, ownProps ) => { - const { replaceInnerBlocks, updateBlockListSettings } = dispatch( 'core/block-editor' ); - const { block, clientId, templateInsertUpdatesSelection = true } = ownProps; + const { replaceInnerBlocks, updateBlockListSettings } = dispatch( + 'core/block-editor' + ); + const { + block, + clientId, + templateInsertUpdatesSelection = true, + } = ownProps; return { replaceInnerBlocks( blocks ) { replaceInnerBlocks( clientId, blocks, - block.innerBlocks.length === 0 && templateInsertUpdatesSelection + block.innerBlocks.length === 0 && + templateInsertUpdatesSelection ); }, updateNestedSettings( settings ) { @@ -162,7 +182,9 @@ InnerBlocks = compose( [ InnerBlocks.DefaultBlockAppender = DefaultBlockAppender; InnerBlocks.ButtonBlockAppender = ButtonBlockAppender; -InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ); +InnerBlocks.Content = withBlockContentContext( ( { BlockContent } ) => ( + +) ); /** * @see https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inner-blocks/README.md diff --git a/packages/block-editor/src/components/inner-blocks/with-client-id.js b/packages/block-editor/src/components/inner-blocks/with-client-id.js index ad3d1abe67c77a..6a49c22abe3e30 100644 --- a/packages/block-editor/src/components/inner-blocks/with-client-id.js +++ b/packages/block-editor/src/components/inner-blocks/with-client-id.js @@ -15,7 +15,9 @@ import { withBlockEditContext } from '../block-edit/context'; const withClientId = createHigherOrderComponent( ( WrappedComponent ) => - withBlockEditContext( ( context ) => pick( context, [ 'clientId' ] ) )( WrappedComponent ), + withBlockEditContext( ( context ) => pick( context, [ 'clientId' ] ) )( + WrappedComponent + ), 'withClientId' ); diff --git a/packages/block-editor/src/components/inserter-list-item/index.js b/packages/block-editor/src/components/inserter-list-item/index.js index c0d1a5d90019bc..b4c8e40cf5efea 100644 --- a/packages/block-editor/src/components/inserter-list-item/index.js +++ b/packages/block-editor/src/components/inserter-list-item/index.js @@ -13,7 +13,14 @@ import { Button } from '@wordpress/components'; */ import BlockIcon from '../block-icon'; -function InserterListItem( { icon, onClick, isDisabled, title, className, ...props } ) { +function InserterListItem( { + icon, + onClick, + isDisabled, + title, + className, + ...props +} ) { const itemIconStyle = icon ? { backgroundColor: icon.background, @@ -24,7 +31,10 @@ function InserterListItem( { icon, onClick, isDisabled, title, className, ...pro return (
      • ); diff --git a/packages/block-editor/src/components/inserter/index.js b/packages/block-editor/src/components/inserter/index.js index 1fe3b55f11b815..dcef449c56e810 100644 --- a/packages/block-editor/src/components/inserter/index.js +++ b/packages/block-editor/src/components/inserter/index.js @@ -19,11 +19,20 @@ import { plusCircle } from '@wordpress/icons'; */ import InserterMenu from './menu'; -const defaultRenderToggle = ( { onToggle, disabled, isOpen, blockTitle, hasSingleBlockType } ) => { +const defaultRenderToggle = ( { + onToggle, + disabled, + isOpen, + blockTitle, + hasSingleBlockType, +} ) => { let label; if ( hasSingleBlockType ) { // translators: %s: the name of the block when there is only one - label = sprintf( _x( 'Add %s', 'directly add the only allowed block' ), blockTitle ); + label = sprintf( + _x( 'Add %s', 'directly add the only allowed block' ), + blockTitle + ); } else { label = _x( 'Add block', 'Generic label for block inserter button' ); } @@ -77,7 +86,13 @@ class Inserter extends Component { renderToggle = defaultRenderToggle, } = this.props; - return renderToggle( { onToggle, isOpen, disabled, blockTitle, hasSingleBlockType } ); + return renderToggle( { + onToggle, + isOpen, + disabled, + blockTitle, + hasSingleBlockType, + } ); } /** @@ -111,7 +126,11 @@ class Inserter extends Component { } render() { - const { position, hasSingleBlockType, insertOnlyAllowedBlock } = this.props; + const { + position, + hasSingleBlockType, + insertOnlyAllowedBlock, + } = this.props; if ( hasSingleBlockType ) { return this.renderToggle( { onToggle: insertOnlyAllowedBlock } ); @@ -134,18 +153,24 @@ class Inserter extends Component { export default compose( [ withSelect( ( select, { clientId, rootClientId } ) => { - const { getBlockRootClientId, hasInserterItems, __experimentalGetAllowedBlocks } = select( - 'core/block-editor' + const { + getBlockRootClientId, + hasInserterItems, + __experimentalGetAllowedBlocks, + } = select( 'core/block-editor' ); + const { __experimentalGetBlockPatterns: getBlockPatterns } = select( + 'core/blocks' ); - const { __experimentalGetBlockPatterns: getBlockPatterns } = select( 'core/blocks' ); - rootClientId = rootClientId || getBlockRootClientId( clientId ) || undefined; + rootClientId = + rootClientId || getBlockRootClientId( clientId ) || undefined; const allowedBlocks = __experimentalGetAllowedBlocks( rootClientId ); const hasSingleBlockType = size( allowedBlocks ) === 1 && - size( getBlockPatterns( allowedBlocks[ 0 ].name, 'inserter' ) ) === 0; + size( getBlockPatterns( allowedBlocks[ 0 ].name, 'inserter' ) ) === + 0; let allowedBlockType = false; if ( hasSingleBlockType ) { @@ -175,9 +200,11 @@ export default compose( [ } function getInsertionIndex() { - const { getBlockIndex, getBlockSelectionEnd, getBlockOrder } = select( - 'core/block-editor' - ); + const { + getBlockIndex, + getBlockSelectionEnd, + getBlockOrder, + } = select( 'core/block-editor' ); // If the clientId is defined, we insert at the position of the block. if ( clientId ) { @@ -198,11 +225,19 @@ export default compose( [ const blockToInsert = createBlock( allowedBlockType.name ); - insertBlock( blockToInsert, getInsertionIndex(), rootClientId, selectBlockOnInsert ); + insertBlock( + blockToInsert, + getInsertionIndex(), + rootClientId, + selectBlockOnInsert + ); if ( ! selectBlockOnInsert ) { // translators: %s: the name of the block that has been added - const message = sprintf( __( '%s block added' ), allowedBlockType.title ); + const message = sprintf( + __( '%s block added' ), + allowedBlockType.title + ); speak( message ); } }, diff --git a/packages/block-editor/src/components/inserter/index.native.js b/packages/block-editor/src/components/inserter/index.native.js index 2c9436237db78e..49530fdd4049d6 100644 --- a/packages/block-editor/src/components/inserter/index.native.js +++ b/packages/block-editor/src/components/inserter/index.native.js @@ -2,7 +2,12 @@ * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { Dropdown, ToolbarButton, Dashicon, Picker } from '@wordpress/components'; +import { + Dropdown, + ToolbarButton, + Dashicon, + Picker, +} from '@wordpress/components'; import { Component } from '@wordpress/element'; import { withSelect } from '@wordpress/data'; import { compose, withPreferredColorScheme } from '@wordpress/compose'; @@ -18,7 +23,9 @@ import BlockInsertionPoint from '../block-list/insertion-point'; const defaultRenderToggle = ( { onToggle, disabled, style, onLongPress } ) => ( } + icon={ + + } onClick={ onToggle } extraProps={ { hint: __( 'Double tap to add a block' ), @@ -74,7 +81,11 @@ export class Inserter extends Component { const { isAnyBlockSelected, isSelectedBlockReplaceable } = this.props; if ( isAnyBlockSelected ) { if ( isSelectedBlockReplaceable ) { - return [ addBeforeOption, replaceCurrentOption, addAfterOption ]; + return [ + addBeforeOption, + replaceCurrentOption, + addAfterOption, + ]; } return [ addBeforeOption, addAfterOption ]; } @@ -82,7 +93,11 @@ export class Inserter extends Component { } getInsertionIndex( insertionType ) { - const { insertionIndexDefault, insertionIndexBefore, insertionIndexAfter } = this.props; + const { + insertionIndexDefault, + insertionIndexBefore, + insertionIndexAfter, + } = this.props; if ( insertionType === 'before' || insertionType === 'replace' ) { return insertionIndexBefore; } @@ -132,7 +147,10 @@ export class Inserter extends Component { if ( showSeparator && isOpen ) { return ; } - const style = getStylesFromColorScheme( styles.addBlockButton, styles.addBlockButtonDark ); + const style = getStylesFromColorScheme( + styles.addBlockButton, + styles.addBlockButtonDark + ); const onPress = () => { this.setState( @@ -155,7 +173,9 @@ export class Inserter extends Component { this.setState( { destinationRootClientId: this.props.destinationRootClientId, - shouldReplaceBlock: this.shouldReplaceBlock( insertionType ), + shouldReplaceBlock: this.shouldReplaceBlock( + insertionType + ), insertionIndex: this.getInsertionIndex( insertionType ), }, onToggle @@ -192,7 +212,11 @@ export class Inserter extends Component { */ renderContent( { onClose, isOpen } ) { const { clientId, isAppender } = this.props; - const { destinationRootClientId, shouldReplaceBlock, insertionIndex } = this.state; + const { + destinationRootClientId, + shouldReplaceBlock, + insertionIndex, + } = this.state; return ( item.name.split( '/' )[ 0 ]; // Copied over from the Columns block. It seems like it should become part of public API. const createBlocksFromInnerBlocksTemplate = ( innerBlocksTemplate ) => { - return map( innerBlocksTemplate, ( [ name, attributes, innerBlocks = [] ] ) => - createBlock( name, attributes, createBlocksFromInnerBlocksTemplate( innerBlocks ) ) + return map( + innerBlocksTemplate, + ( [ name, attributes, innerBlocks = [] ] ) => + createBlock( + name, + attributes, + createBlocksFromInnerBlocksTemplate( innerBlocks ) + ) ); }; @@ -116,9 +136,13 @@ export class InserterMenu extends Component { this.props.setTimeout( () => { // We need a generic way to access the panel's container - scrollIntoView( this.panels[ panel ], this.inserterResults.current, { - alignWithTop: true, - } ); + scrollIntoView( + this.panels[ panel ], + this.inserterResults.current, + { + alignWithTop: true, + } + ); } ); } }; @@ -152,25 +176,46 @@ export class InserterMenu extends Component { } filter( filterValue = '' ) { - const { categories, collections, debouncedSpeak, items, rootChildBlocks } = this.props; + const { + categories, + collections, + debouncedSpeak, + items, + rootChildBlocks, + } = this.props; - const filteredItems = searchItems( items, categories, collections, filterValue ); + const filteredItems = searchItems( + items, + categories, + collections, + filterValue + ); - const childItems = filter( filteredItems, ( { name } ) => includes( rootChildBlocks, name ) ); + const childItems = filter( filteredItems, ( { name } ) => + includes( rootChildBlocks, name ) + ); let suggestedItems = []; if ( ! filterValue ) { - const maxSuggestedItems = this.props.maxSuggestedItems || MAX_SUGGESTED_ITEMS; - suggestedItems = filter( items, ( item ) => item.utility > 0 ).slice( 0, maxSuggestedItems ); + const maxSuggestedItems = + this.props.maxSuggestedItems || MAX_SUGGESTED_ITEMS; + suggestedItems = filter( + items, + ( item ) => item.utility > 0 + ).slice( 0, maxSuggestedItems ); } const reusableItems = filter( filteredItems, { category: 'reusable' } ); const getCategoryIndex = ( item ) => { - return findIndex( categories, ( category ) => category.slug === item.category ); + return findIndex( + categories, + ( category ) => category.slug === item.category + ); }; const itemsPerCategory = flow( - ( itemList ) => filter( itemList, ( item ) => item.category !== 'reusable' ), + ( itemList ) => + filter( itemList, ( item ) => item.category !== 'reusable' ), ( itemList ) => sortBy( itemList, getCategoryIndex ), ( itemList ) => groupBy( itemList, 'category' ) )( filteredItems ); @@ -205,7 +250,9 @@ export class InserterMenu extends Component { const resultCount = Object.keys( itemsPerCategory ).reduce( ( accumulator, currentCategorySlug ) => { - return accumulator + itemsPerCategory[ currentCategorySlug ].length; + return ( + accumulator + itemsPerCategory[ currentCategorySlug ].length + ); }, 0 ); @@ -218,7 +265,12 @@ export class InserterMenu extends Component { } onKeyDown( event ) { - if ( includes( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ], event.keyCode ) ) { + if ( + includes( + [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ], + event.keyCode + ) + ) { // Stop the key event from propagating up to ObserveTyping.startTypingInTextField. event.stopPropagation(); } @@ -249,7 +301,9 @@ export class InserterMenu extends Component { ! isEmpty( reusableItems ) || ! isEmpty( itemsPerCategory ) || ! isEmpty( itemsPerCollection ); - const hoveredItemBlockType = hoveredItem ? getBlockType( hoveredItem.name ) : null; + const hoveredItemBlockType = hoveredItem + ? getBlockType( hoveredItem.name ) + : null; const hasHelpPanel = hasItems && showInserterHelpPanel; // Disable reason (no-autofocus): The inserter menu is a modal display, not one which @@ -312,7 +366,8 @@ export class InserterMenu extends Component { ) } { map( categories, ( category ) => { - const categoryItems = itemsPerCategory[ category.slug ]; + const categoryItems = + itemsPerCategory[ category.slug ]; if ( ! categoryItems || ! categoryItems.length ) { return null; } @@ -322,7 +377,9 @@ export class InserterMenu extends Component { title={ category.title } icon={ category.icon } opened={ isPanelOpen( category.slug ) } - onToggle={ this.onTogglePanel( category.slug ) } + onToggle={ this.onTogglePanel( + category.slug + ) } ref={ this.bindPanel( category.slug ) } > { - const collectionItems = itemsPerCollection[ namespace ]; - if ( ! collectionItems || ! collectionItems.length ) { + const collectionItems = + itemsPerCollection[ namespace ]; + if ( + ! collectionItems || + ! collectionItems.length + ) { return null; } @@ -374,7 +435,9 @@ export class InserterMenu extends Component { /> { __( 'Manage all reusable blocks' ) } @@ -410,23 +473,37 @@ export class InserterMenu extends Component {
        { hoveredItem && ( <> - { ! isReusableBlock( hoveredItem ) && } + { ! isReusableBlock( hoveredItem ) && ( + + ) }
        - { isReusableBlock( hoveredItem ) || hoveredItemBlockType.example ? ( + { isReusableBlock( hoveredItem ) || + hoveredItemBlockType.example ? (
        @@ -455,12 +532,16 @@ export class InserterMenu extends Component { ) }

        - { __( 'Browse through the library to learn more about what each block does.' ) } + { __( + 'Browse through the library to learn more about what each block does.' + ) }

        { __experimentalCreateInterpolateElement( - __( 'While writing, you can press / to quickly insert new blocks.' ), + __( + 'While writing, you can press / to quickly insert new blocks.' + ), { kbd: } ) } @@ -475,42 +556,57 @@ export class InserterMenu extends Component { } export default compose( - withSelect( ( select, { clientId, isAppender, rootClientId, showInserterHelpPanel } ) => { - const { - getInserterItems, - getBlockName, - getBlockRootClientId, - getBlockSelectionEnd, - getSettings, - } = select( 'core/block-editor' ); - const { getCategories, getCollections, getChildBlockNames } = select( 'core/blocks' ); - - let destinationRootClientId = rootClientId; - if ( ! destinationRootClientId && ! clientId && ! isAppender ) { - const end = getBlockSelectionEnd(); - if ( end ) { - destinationRootClientId = getBlockRootClientId( end ) || undefined; + withSelect( + ( + select, + { clientId, isAppender, rootClientId, showInserterHelpPanel } + ) => { + const { + getInserterItems, + getBlockName, + getBlockRootClientId, + getBlockSelectionEnd, + getSettings, + } = select( 'core/block-editor' ); + const { + getCategories, + getCollections, + getChildBlockNames, + } = select( 'core/blocks' ); + + let destinationRootClientId = rootClientId; + if ( ! destinationRootClientId && ! clientId && ! isAppender ) { + const end = getBlockSelectionEnd(); + if ( end ) { + destinationRootClientId = + getBlockRootClientId( end ) || undefined; + } } - } - const destinationRootBlockName = getBlockName( destinationRootClientId ); - - const { - showInserterHelpPanel: showInserterHelpPanelSetting, - __experimentalFetchReusableBlocks: fetchReusableBlocks, - } = getSettings(); + const destinationRootBlockName = getBlockName( + destinationRootClientId + ); - return { - categories: getCategories(), - collections: getCollections(), - rootChildBlocks: getChildBlockNames( destinationRootBlockName ), - items: getInserterItems( destinationRootClientId ), - showInserterHelpPanel: showInserterHelpPanel && showInserterHelpPanelSetting, - destinationRootClientId, - fetchReusableBlocks, - }; - } ), + const { + showInserterHelpPanel: showInserterHelpPanelSetting, + __experimentalFetchReusableBlocks: fetchReusableBlocks, + } = getSettings(); + + return { + categories: getCategories(), + collections: getCollections(), + rootChildBlocks: getChildBlockNames( destinationRootBlockName ), + items: getInserterItems( destinationRootClientId ), + showInserterHelpPanel: + showInserterHelpPanel && showInserterHelpPanelSetting, + destinationRootClientId, + fetchReusableBlocks, + }; + } + ), withDispatch( ( dispatch, ownProps, { select } ) => { - const { showInsertionPoint, hideInsertionPoint } = dispatch( 'core/block-editor' ); + const { showInsertionPoint, hideInsertionPoint } = dispatch( + 'core/block-editor' + ); // To avoid duplication, getInsertionIndex is extracted and used in two event handlers // This breaks the withDispatch not containing any logic rule. @@ -518,7 +614,11 @@ export default compose( // it's fine to extract it. // eslint-disable-next-line no-restricted-syntax function getInsertionIndex() { - const { getBlockIndex, getBlockSelectionEnd, getBlockOrder } = select( 'core/block-editor' ); + const { + getBlockIndex, + getBlockSelectionEnd, + getBlockOrder, + } = select( 'core/block-editor' ); const { clientId, destinationRootClientId, isAppender } = ownProps; // If the clientId is defined, we insert at the position of the block. @@ -543,7 +643,9 @@ export default compose( }, hideInsertionPoint, onSelect( item ) { - const { replaceBlocks, insertBlock } = dispatch( 'core/block-editor' ); + const { replaceBlocks, insertBlock } = dispatch( + 'core/block-editor' + ); const { getSelectedBlock } = select( 'core/block-editor' ); const { isAppender, @@ -558,7 +660,11 @@ export default compose( createBlocksFromInnerBlocksTemplate( innerBlocks ) ); - if ( ! isAppender && selectedBlock && isUnmodifiedDefaultBlock( selectedBlock ) ) { + if ( + ! isAppender && + selectedBlock && + isUnmodifiedDefaultBlock( selectedBlock ) + ) { replaceBlocks( selectedBlock.clientId, insertedBlock ); } else { insertBlock( @@ -570,7 +676,10 @@ export default compose( if ( ! selectBlockOnInsert ) { // translators: %s: the name of the block that has been added - const message = sprintf( __( '%s block added' ), title ); + const message = sprintf( + __( '%s block added' ), + title + ); speak( message ); } } diff --git a/packages/block-editor/src/components/inserter/menu.native.js b/packages/block-editor/src/components/inserter/menu.native.js index df48da04dca2a6..27573aeca96a7a 100644 --- a/packages/block-editor/src/components/inserter/menu.native.js +++ b/packages/block-editor/src/components/inserter/menu.native.js @@ -9,7 +9,11 @@ import { FlatList, View, Text, TouchableHighlight } from 'react-native'; import { Component } from '@wordpress/element'; import { createBlock } from '@wordpress/blocks'; import { withDispatch, withSelect } from '@wordpress/data'; -import { withInstanceId, compose, withPreferredColorScheme } from '@wordpress/compose'; +import { + withInstanceId, + compose, + withPreferredColorScheme, +} from '@wordpress/compose'; import { BottomSheet, Icon } from '@wordpress/components'; /** @@ -38,14 +42,18 @@ export class InserterMenu extends Component { calculateNumberOfColumns() { const bottomSheetWidth = BottomSheet.getWidth(); - const { paddingLeft: itemPaddingLeft, paddingRight: itemPaddingRight } = styles.modalItem; + const { + paddingLeft: itemPaddingLeft, + paddingRight: itemPaddingRight, + } = styles.modalItem; const { paddingLeft: containerPaddingLeft, paddingRight: containerPaddingRight, } = styles.content; const { width: itemWidth } = styles.modalIconWrapper; const itemTotalWidth = itemWidth + itemPaddingLeft + itemPaddingRight; - const containerTotalWidth = bottomSheetWidth - ( containerPaddingLeft + containerPaddingRight ); + const containerTotalWidth = + bottomSheetWidth - ( containerPaddingLeft + containerPaddingRight ); return Math.floor( containerTotalWidth / itemTotalWidth ); } @@ -70,7 +78,10 @@ export class InserterMenu extends Component { styles.modalIconWrapper, styles.modalIconWrapperDark ); - const modalIconStyle = getStylesFromColorScheme( styles.modalIcon, styles.modalIconDark ); + const modalIconStyle = getStylesFromColorScheme( + styles.modalIcon, + styles.modalIconDark + ); const modalItemLabelStyle = getStylesFromColorScheme( styles.modalItemLabel, styles.modalItemLabelDark @@ -90,7 +101,9 @@ export class InserterMenu extends Component { keyboardShouldPersistTaps="always" numColumns={ this.state.numberOfColumns } data={ this.props.items } - ItemSeparatorComponent={ () => } + ItemSeparatorComponent={ () => ( + + ) } keyExtractor={ ( item ) => item.name } renderItem={ ( { item } ) => ( - { item.title } + + { item.title } + ) } @@ -135,12 +150,17 @@ export default compose( if ( ! destinationRootClientId && ! clientId && ! isAppender ) { const end = getBlockSelectionEnd(); if ( end ) { - destinationRootClientId = getBlockRootClientId( end ) || undefined; + destinationRootClientId = + getBlockRootClientId( end ) || undefined; } } - const destinationRootBlockName = getBlockName( destinationRootClientId ); + const destinationRootBlockName = getBlockName( + destinationRootClientId + ); - const { __experimentalShouldInsertAtTheTop: shouldInsertAtTheTop } = getSettings(); + const { + __experimentalShouldInsertAtTheTop: shouldInsertAtTheTop, + } = getSettings(); return { rootChildBlocks: getChildBlockNames( destinationRootBlockName ), @@ -163,7 +183,9 @@ export default compose( return { showInsertionPoint() { if ( ownProps.shouldReplaceBlock ) { - const { getBlockOrder, getBlockCount } = select( 'core/block-editor' ); + const { getBlockOrder, getBlockCount } = select( + 'core/block-editor' + ); const count = getBlockCount(); if ( count === 1 ) { @@ -172,14 +194,17 @@ export default compose( clearSelectedBlock(); resetBlocks( [] ); } else { - const blockToReplace = getBlockOrder( ownProps.destinationRootClientId )[ - ownProps.insertionIndex - ]; + const blockToReplace = getBlockOrder( + ownProps.destinationRootClientId + )[ ownProps.insertionIndex ]; removeBlock( blockToReplace, false ); } } - showInsertionPoint( ownProps.destinationRootClientId, ownProps.insertionIndex ); + showInsertionPoint( + ownProps.destinationRootClientId, + ownProps.insertionIndex + ); }, hideInsertionPoint, onSelect( item ) { @@ -187,12 +212,20 @@ export default compose( const insertedBlock = createBlock( name, initialAttributes ); - insertBlock( insertedBlock, ownProps.insertionIndex, ownProps.destinationRootClientId ); + insertBlock( + insertedBlock, + ownProps.insertionIndex, + ownProps.destinationRootClientId + ); ownProps.onSelect(); }, insertDefaultBlock() { - insertDefaultBlock( {}, ownProps.destinationRootClientId, ownProps.insertionIndex ); + insertDefaultBlock( + {}, + ownProps.destinationRootClientId, + ownProps.insertionIndex + ); }, }; } ), diff --git a/packages/block-editor/src/components/inserter/search-items.js b/packages/block-editor/src/components/inserter/search-items.js index 0b3264410011ed..18e5179380421b 100644 --- a/packages/block-editor/src/components/inserter/search-items.js +++ b/packages/block-editor/src/components/inserter/search-items.js @@ -1,7 +1,15 @@ /** * External dependencies */ -import { deburr, differenceWith, find, get, intersectionWith, isEmpty, words } from 'lodash'; +import { + deburr, + differenceWith, + find, + get, + intersectionWith, + isEmpty, + words, +} from 'lodash'; /** * Converts the search term into a list of normalized terms. @@ -31,7 +39,8 @@ const removeMatchingTerms = ( unmatchedTerms, unprocessedTerms ) => { return differenceWith( unmatchedTerms, normalizeSearchTerm( unprocessedTerms ), - ( unmatchedTerm, unprocessedTerm ) => unprocessedTerm.includes( unmatchedTerm ) + ( unmatchedTerm, unprocessedTerm ) => + unprocessedTerm.includes( unmatchedTerm ) ); }; @@ -53,40 +62,51 @@ export const searchItems = ( items, categories, collections, searchTerm ) => { } return items - .filter( ( { name, title, category, keywords = [], patterns = [] } ) => { - let unmatchedTerms = removeMatchingTerms( normalizedSearchTerms, title ); + .filter( + ( { name, title, category, keywords = [], patterns = [] } ) => { + let unmatchedTerms = removeMatchingTerms( + normalizedSearchTerms, + title + ); - if ( unmatchedTerms.length === 0 ) { - return true; - } + if ( unmatchedTerms.length === 0 ) { + return true; + } - unmatchedTerms = removeMatchingTerms( unmatchedTerms, keywords.join( ' ' ) ); + unmatchedTerms = removeMatchingTerms( + unmatchedTerms, + keywords.join( ' ' ) + ); - if ( unmatchedTerms.length === 0 ) { - return true; - } + if ( unmatchedTerms.length === 0 ) { + return true; + } - unmatchedTerms = removeMatchingTerms( - unmatchedTerms, - get( find( categories, { slug: category } ), [ 'title' ] ) - ); + unmatchedTerms = removeMatchingTerms( + unmatchedTerms, + get( find( categories, { slug: category } ), [ 'title' ] ) + ); - const itemCollection = collections[ name.split( '/' )[ 0 ] ]; - if ( itemCollection ) { - unmatchedTerms = removeMatchingTerms( unmatchedTerms, itemCollection.title ); - } + const itemCollection = collections[ name.split( '/' )[ 0 ] ]; + if ( itemCollection ) { + unmatchedTerms = removeMatchingTerms( + unmatchedTerms, + itemCollection.title + ); + } + + if ( unmatchedTerms.length === 0 ) { + return true; + } + + unmatchedTerms = removeMatchingTerms( + unmatchedTerms, + patterns.map( ( pattern ) => pattern.title ).join( ' ' ) + ); - if ( unmatchedTerms.length === 0 ) { - return true; + return unmatchedTerms.length === 0; } - - unmatchedTerms = removeMatchingTerms( - unmatchedTerms, - patterns.map( ( pattern ) => pattern.title ).join( ' ' ) - ); - - return unmatchedTerms.length === 0; - } ) + ) .map( ( item ) => { if ( isEmpty( item.patterns ) ) { return item; @@ -97,7 +117,8 @@ export const searchItems = ( items, categories, collections, searchTerm ) => { intersectionWith( normalizedSearchTerms, normalizeSearchTerm( pattern.title ), - ( termToMatch, labelTerm ) => labelTerm.includes( termToMatch ) + ( termToMatch, labelTerm ) => + labelTerm.includes( termToMatch ) ).length > 0 ); } ); diff --git a/packages/block-editor/src/components/inserter/test/menu.js b/packages/block-editor/src/components/inserter/test/menu.js index cea1b1e4a64e69..70881f2f30ce3a 100644 --- a/packages/block-editor/src/components/inserter/test/menu.js +++ b/packages/block-editor/src/components/inserter/test/menu.js @@ -22,7 +22,9 @@ const DEFAULT_PROPS = { }; const getWrapperForProps = ( propOverrides ) => { - return TestUtils.renderIntoDocument( ); + return TestUtils.renderIntoDocument( + + ); }; const initializeMenuDefaultStateAndReturnElement = ( propOverrides ) => { @@ -43,19 +45,23 @@ const initializeAllClosedMenuStateAndReturnElement = ( propOverrides ) => { }; const assertNoResultsMessageToBePresent = ( element ) => { - const noResultsMessage = element.querySelector( '.block-editor-inserter__no-results' ); + const noResultsMessage = element.querySelector( + '.block-editor-inserter__no-results' + ); expect( noResultsMessage.textContent ).toEqual( 'No blocks found.' ); }; const assertNoResultsMessageNotToBePresent = ( element ) => { - const noResultsMessage = element.querySelector( '.block-editor-inserter__no-results' ); + const noResultsMessage = element.querySelector( + '.block-editor-inserter__no-results' + ); expect( noResultsMessage ).toBe( null ); }; const assertOpenedPanels = ( element, expectedOpen = 0 ) => { - expect( element.querySelectorAll( '.components-panel__body.is-opened ' ) ).toHaveLength( - expectedOpen - ); + expect( + element.querySelectorAll( '.components-panel__body.is-opened ' ) + ).toHaveLength( expectedOpen ); }; const getTabButtonWithContent = ( element, content ) => { @@ -70,8 +76,12 @@ const getTabButtonWithContent = ( element, content ) => { }; const performSearchWithText = ( element, searchText ) => { - const searchElement = element.querySelector( '.block-editor-inserter__search' ); - TestUtils.Simulate.change( searchElement, { target: { value: searchText } } ); + const searchElement = element.querySelector( + '.block-editor-inserter__search' + ); + TestUtils.Simulate.change( searchElement, { + target: { value: searchText }, + } ); }; describe( 'InserterMenu', () => { @@ -84,8 +94,12 @@ describe( 'InserterMenu', () => { } ); it( 'should show nothing if there are no items', () => { - const element = initializeMenuDefaultStateAndReturnElement( { items: [] } ); - const visibleBlocks = element.querySelector( '.block-editor-block-types-list__item' ); + const element = initializeMenuDefaultStateAndReturnElement( { + items: [], + } ); + const visibleBlocks = element.querySelector( + '.block-editor-block-types-list__item' + ); expect( visibleBlocks ).toBe( null ); @@ -94,7 +108,9 @@ describe( 'InserterMenu', () => { it( 'should show only high utility items in the suggested tab', () => { const element = initializeMenuDefaultStateAndReturnElement(); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 3 ); expect( visibleBlocks[ 0 ].textContent ).toEqual( 'Text' ); expect( visibleBlocks[ 1 ].textContent ).toEqual( 'Advanced Text' ); @@ -102,8 +118,12 @@ describe( 'InserterMenu', () => { } ); it( 'should limit the number of items shown in the suggested tab', () => { - const element = initializeMenuDefaultStateAndReturnElement( { maxSuggestedItems: 2 } ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__list-item' ); + const element = initializeMenuDefaultStateAndReturnElement( { + maxSuggestedItems: 2, + } ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__list-item' + ); expect( visibleBlocks ).toHaveLength( 2 ); } ); @@ -115,7 +135,9 @@ describe( 'InserterMenu', () => { assertOpenedPanels( element, 1 ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 2 ); expect( visibleBlocks[ 0 ].textContent ).toBe( 'YouTube' ); @@ -132,7 +154,9 @@ describe( 'InserterMenu', () => { assertOpenedPanels( element, 1 ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 1 ); expect( visibleBlocks[ 0 ].textContent ).toBe( 'My reusable block' ); @@ -142,13 +166,18 @@ describe( 'InserterMenu', () => { it( 'should show the common category blocks', () => { const element = initializeAllClosedMenuStateAndReturnElement(); - const commonBlocksTab = getTabButtonWithContent( element, 'Common blocks' ); + const commonBlocksTab = getTabButtonWithContent( + element, + 'Common blocks' + ); TestUtils.Simulate.click( commonBlocksTab ); assertOpenedPanels( element, 1 ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 3 ); expect( visibleBlocks[ 0 ].textContent ).toBe( 'Text' ); @@ -178,13 +207,17 @@ describe( 'InserterMenu', () => { assertOpenedPanels( element, 3 ); - const matchingCategories = element.querySelectorAll( '.components-panel__body-toggle' ); + const matchingCategories = element.querySelectorAll( + '.components-panel__body-toggle' + ); expect( matchingCategories ).toHaveLength( 3 ); expect( matchingCategories[ 0 ].textContent ).toBe( 'Common blocks' ); expect( matchingCategories[ 1 ].textContent ).toBe( 'Embeds' ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 5 ); expect( visibleBlocks[ 0 ].textContent ).toBe( 'Text' ); @@ -200,13 +233,17 @@ describe( 'InserterMenu', () => { assertOpenedPanels( element, 3 ); - const matchingCategories = element.querySelectorAll( '.components-panel__body-toggle' ); + const matchingCategories = element.querySelectorAll( + '.components-panel__body-toggle' + ); expect( matchingCategories ).toHaveLength( 3 ); expect( matchingCategories[ 0 ].textContent ).toBe( 'Common blocks' ); expect( matchingCategories[ 1 ].textContent ).toBe( 'Embeds' ); - const visibleBlocks = element.querySelectorAll( '.block-editor-block-types-list__item-title' ); + const visibleBlocks = element.querySelectorAll( + '.block-editor-block-types-list__item-title' + ); expect( visibleBlocks ).toHaveLength( 5 ); expect( visibleBlocks[ 0 ].textContent ).toBe( 'Text' ); diff --git a/packages/block-editor/src/components/inserter/test/search-items.js b/packages/block-editor/src/components/inserter/test/search-items.js index cbedd580b10a50..e53a524ea90b6b 100644 --- a/packages/block-editor/src/components/inserter/test/search-items.js +++ b/packages/block-editor/src/components/inserter/test/search-items.js @@ -30,60 +30,74 @@ describe( 'normalizeSearchTerm', () => { } ); it( 'should extract only words', () => { - expect( normalizeSearchTerm( ' Mรฉdia & Text Tag-Cloud > 123' ) ).toEqual( [ - 'media', - 'text', - 'tag', - 'cloud', - '123', - ] ); + expect( + normalizeSearchTerm( ' Mรฉdia & Text Tag-Cloud > 123' ) + ).toEqual( [ 'media', 'text', 'tag', 'cloud', '123' ] ); } ); } ); describe( 'searchItems', () => { it( 'should return back all items when no terms detected', () => { - expect( searchItems( items, categories, collections, ' - ? * ' ) ).toBe( items ); + expect( searchItems( items, categories, collections, ' - ? * ' ) ).toBe( + items + ); } ); it( 'should search items using the title ignoring case', () => { - expect( searchItems( items, categories, collections, 'TEXT' ) ).toEqual( [ - textItem, - advancedTextItem, - textEmbedItem, - ] ); + expect( + searchItems( items, categories, collections, 'TEXT' ) + ).toEqual( [ textItem, advancedTextItem, textEmbedItem ] ); } ); it( 'should search items using the keywords and partial terms', () => { - expect( searchItems( items, categories, collections, 'GOOGL' ) ).toEqual( [ youtubeItem ] ); + expect( + searchItems( items, categories, collections, 'GOOGL' ) + ).toEqual( [ youtubeItem ] ); } ); it( 'should search items using the categories', () => { - expect( searchItems( items, categories, collections, 'LAYOUT' ) ).toEqual( [ moreItem ] ); + expect( + searchItems( items, categories, collections, 'LAYOUT' ) + ).toEqual( [ moreItem ] ); } ); it( 'should ignore a leading slash on a search term', () => { - expect( searchItems( items, categories, collections, '/GOOGL' ) ).toEqual( [ youtubeItem ] ); + expect( + searchItems( items, categories, collections, '/GOOGL' ) + ).toEqual( [ youtubeItem ] ); } ); it( 'should match words using the mix of the title, category and keywords', () => { - expect( searchItems( items, categories, collections, 'youtube embed video' ) ).toEqual( [ - youtubeItem, - ] ); + expect( + searchItems( items, categories, collections, 'youtube embed video' ) + ).toEqual( [ youtubeItem ] ); } ); it( 'should match words using also patterns and return all matched patterns', () => { - const filteredItems = searchItems( items, categories, collections, 'pattern' ); + const filteredItems = searchItems( + items, + categories, + collections, + 'pattern' + ); expect( filteredItems ).toHaveLength( 1 ); expect( filteredItems[ 0 ].patterns ).toHaveLength( 3 ); } ); it( 'should match words using also patterns and filter out unmatched patterns', () => { - const filteredItems = searchItems( items, categories, collections, 'patterns two three' ); + const filteredItems = searchItems( + items, + categories, + collections, + 'patterns two three' + ); expect( filteredItems ).toHaveLength( 1 ); expect( filteredItems[ 0 ].patterns ).toHaveLength( 2 ); expect( filteredItems[ 0 ].patterns[ 0 ].title ).toBe( 'Pattern Two' ); - expect( filteredItems[ 0 ].patterns[ 1 ].title ).toBe( 'Pattern Three' ); + expect( filteredItems[ 0 ].patterns[ 1 ].title ).toBe( + 'Pattern Three' + ); } ); } ); diff --git a/packages/block-editor/src/components/keyboard-shortcuts/index.js b/packages/block-editor/src/components/keyboard-shortcuts/index.js index bd2994402572f8..3259707632cd94 100644 --- a/packages/block-editor/src/components/keyboard-shortcuts/index.js +++ b/packages/block-editor/src/components/keyboard-shortcuts/index.js @@ -13,7 +13,9 @@ import { __ } from '@wordpress/i18n'; function KeyboardShortcuts() { // Shortcuts Logic const { clientIds, rootBlocksClientIds } = useSelect( ( select ) => { - const { getSelectedBlockClientIds, getBlockOrder } = select( 'core/block-editor' ); + const { getSelectedBlockClientIds, getBlockOrder } = select( + 'core/block-editor' + ); return { clientIds: getSelectedBlockClientIds(), rootBlocksClientIds: getBlockOrder(), @@ -101,7 +103,10 @@ function KeyboardShortcuts() { useCallback( ( event ) => { event.preventDefault(); - multiSelect( first( rootBlocksClientIds ), last( rootBlocksClientIds ) ); + multiSelect( + first( rootBlocksClientIds ), + last( rootBlocksClientIds ) + ); }, [ rootBlocksClientIds, multiSelect ] ) @@ -150,7 +155,9 @@ function KeyboardShortcutsRegister() { registerShortcut( { name: 'core/block-editor/insert-before', category: 'block', - description: __( 'Insert a new block before the selected block(s).' ), + description: __( + 'Insert a new block before the selected block(s).' + ), keyCombination: { modifier: 'primaryAlt', character: 't', @@ -160,7 +167,9 @@ function KeyboardShortcutsRegister() { registerShortcut( { name: 'core/block-editor/insert-after', category: 'block', - description: __( 'Insert a new block after the selected block(s).' ), + description: __( + 'Insert a new block after the selected block(s).' + ), keyCombination: { modifier: 'primaryAlt', character: 'y', @@ -184,7 +193,9 @@ function KeyboardShortcutsRegister() { registerShortcut( { name: 'core/block-editor/select-all', category: 'selection', - description: __( 'Select all text when typing. Press again to select all blocks.' ), + description: __( + 'Select all text when typing. Press again to select all blocks.' + ), keyCombination: { modifier: 'primary', character: 'a', diff --git a/packages/block-editor/src/components/link-control/index.js b/packages/block-editor/src/components/link-control/index.js index 4128be67048b92..cda7986a9f8c44 100644 --- a/packages/block-editor/src/components/link-control/index.js +++ b/packages/block-editor/src/components/link-control/index.js @@ -9,7 +9,13 @@ import { noop, startsWith } from 'lodash'; */ import { Button, ExternalLink, VisuallyHidden } from '@wordpress/components'; import { __, sprintf } from '@wordpress/i18n'; -import { useRef, useCallback, useState, Fragment, useEffect } from '@wordpress/element'; +import { + useRef, + useCallback, + useState, + Fragment, + useEffect, +} from '@wordpress/element'; import { safeDecodeURI, filterURLForDisplay, @@ -84,19 +90,30 @@ import LinkControlSearchInput from './search-input'; * * @param {WPLinkControlProps} props Component props. */ -function LinkControl( { value, settings, onChange = noop, showInitialSuggestions } ) { +function LinkControl( { + value, + settings, + onChange = noop, + showInitialSuggestions, +} ) { const wrapperNode = useRef(); const instanceId = useInstanceId( LinkControl ); - const [ inputValue, setInputValue ] = useState( ( value && value.url ) || '' ); - const [ isEditingLink, setIsEditingLink ] = useState( ! value || ! value.url ); + const [ inputValue, setInputValue ] = useState( + ( value && value.url ) || '' + ); + const [ isEditingLink, setIsEditingLink ] = useState( + ! value || ! value.url + ); const isEndingEditWithFocus = useRef( false ); const { fetchSearchSuggestions } = useSelect( ( select ) => { const { getSettings } = select( 'core/block-editor' ); return { - fetchSearchSuggestions: getSettings().__experimentalFetchLinkSuggestions, + fetchSearchSuggestions: getSettings() + .__experimentalFetchLinkSuggestions, }; }, [] ); - const displayURL = ( value && filterURLForDisplay( safeDecodeURI( value.url ) ) ) || ''; + const displayURL = + ( value && filterURLForDisplay( safeDecodeURI( value.url ) ) ) || ''; useEffect( () => { // When `isEditingLink` is set to `false`, a focus loss could occur @@ -115,7 +132,8 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions // Prefer to focus a natural focusable descendent of the wrapper, // but settle for the wrapper if there are no other options. const nextFocusTarget = - focus.focusable.find( wrapperNode.current )[ 0 ] || wrapperNode.current; + focus.focusable.find( wrapperNode.current )[ 0 ] || + wrapperNode.current; nextFocusTarget.focus(); } @@ -187,7 +205,8 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions */ function stopEditing() { isEndingEditWithFocus.current = - !! wrapperNode.current && wrapperNode.current.contains( document.activeElement ); + !! wrapperNode.current && + wrapperNode.current.contains( document.activeElement ); setIsEditingLink( false ); } @@ -201,9 +220,15 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions const isTel = protocol.includes( 'tel' ); const handleManualEntry = - isInternal || isMailto || isTel || isURL( val ) || ( val && val.includes( 'www.' ) ); - - return handleManualEntry ? handleDirectEntry( val, args ) : handleEntitySearch( val, args ); + isInternal || + isMailto || + isTel || + isURL( val ) || + ( val && val.includes( 'www.' ) ); + + return handleManualEntry + ? handleDirectEntry( val, args ) + : handleEntitySearch( val, args ); }, [ handleDirectEntry, fetchSearchSuggestions ] ); @@ -217,9 +242,12 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions isLoading, isInitialSuggestions, } ) => { - const resultsListClasses = classnames( 'block-editor-link-control__search-results', { - 'is-loading': isLoading, - } ); + const resultsListClasses = classnames( + 'block-editor-link-control__search-results', + { + 'is-loading': isLoading, + } + ); const manualLinkEntryTypes = [ 'url', 'mailto', 'tel', 'internal' ]; const searchResultsLabelId = isInitialSuggestions @@ -258,14 +286,19 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions { suggestions.map( ( suggestion, index ) => ( { stopEditing(); onChange( { ...value, ...suggestion } ); } } isSelected={ index === selectedSuggestion } - isURL={ manualLinkEntryTypes.includes( suggestion.type.toLowerCase() ) } + isURL={ manualLinkEntryTypes.includes( + suggestion.type.toLowerCase() + ) } searchTerm={ inputValue } /> ) ) } @@ -275,7 +308,11 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions }; return ( -
        +
        { isEditingLink || ! value ? ( ) : ( -

        +

        { __( 'Currently selected' ) }:

        { value && value.title && ( - { displayURL } + + { displayURL } + ) } @@ -321,7 +366,11 @@ function LinkControl( { value, settings, onChange = noop, showInitialSuggestions { __( 'Edit' ) }
        - +
        ) }
        diff --git a/packages/block-editor/src/components/link-control/search-item.js b/packages/block-editor/src/components/link-control/search-item.js index bc7062fae35046..a3c4fb37f4eb5d 100644 --- a/packages/block-editor/src/components/link-control/search-item.js +++ b/packages/block-editor/src/components/link-control/search-item.js @@ -29,19 +29,30 @@ export const LinkControlSearchItem = ( { } ) } > { isURL && ( - + ) } - + - + { ! isURL && ( safeDecodeURI( suggestion.url ) || '' ) } { isURL && __( 'Press ENTER to add this link' ) } { suggestion.type && ( - { suggestion.type } + + { suggestion.type } + ) } ); diff --git a/packages/block-editor/src/components/link-control/settings-drawer.js b/packages/block-editor/src/components/link-control/settings-drawer.js index 0df4b5bb919802..0df253d11a1ebc 100644 --- a/packages/block-editor/src/components/link-control/settings-drawer.js +++ b/packages/block-editor/src/components/link-control/settings-drawer.js @@ -16,7 +16,11 @@ const defaultSettings = [ }, ]; -const LinkControlSettingsDrawer = ( { value, onChange = noop, settings = defaultSettings } ) => { +const LinkControlSettingsDrawer = ( { + value, + onChange = noop, + settings = defaultSettings, +} ) => { if ( ! settings || ! settings.length ) { return null; } @@ -40,7 +44,9 @@ const LinkControlSettingsDrawer = ( { value, onChange = noop, settings = default return (
        - { __( 'Currently selected link settings' ) } + + { __( 'Currently selected link settings' ) } + { theSettings }
        ); diff --git a/packages/block-editor/src/components/link-control/test/fixtures/index.js b/packages/block-editor/src/components/link-control/test/fixtures/index.js index 3af7a7d85f8ebb..b470155977a30b 100644 --- a/packages/block-editor/src/components/link-control/test/fixtures/index.js +++ b/packages/block-editor/src/components/link-control/test/fixtures/index.js @@ -36,8 +36,13 @@ export const fauxEntitySuggestions = [ ]; /* eslint-disable no-unused-vars */ -export const fetchFauxEntitySuggestions = ( val = '', { perPage = null } = {} ) => { - const suggestions = perPage ? take( fauxEntitySuggestions, perPage ) : fauxEntitySuggestions; +export const fetchFauxEntitySuggestions = ( + val = '', + { perPage = null } = {} +) => { + const suggestions = perPage + ? take( fauxEntitySuggestions, perPage ) + : fauxEntitySuggestions; return Promise.resolve( suggestions ); }; /* eslint-enable no-unused-vars */ diff --git a/packages/block-editor/src/components/link-control/test/index.js b/packages/block-editor/src/components/link-control/test/index.js index 73ce1ca49d891a..44424efe334295 100644 --- a/packages/block-editor/src/components/link-control/test/index.js +++ b/packages/block-editor/src/components/link-control/test/index.js @@ -57,7 +57,9 @@ describe( 'Basic rendering', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); expect( searchInput ).not.toBeNull(); expect( container.innerHTML ).toMatchSnapshot(); @@ -82,7 +84,9 @@ describe( 'Searching for a link', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { @@ -123,7 +127,9 @@ describe( 'Searching for a link', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { @@ -134,11 +140,16 @@ describe( 'Searching for a link', () => { await eventLoopTick(); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - const searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); - const firstSearchResultItemHTML = first( searchResultElements ).innerHTML; + const searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); + const firstSearchResultItemHTML = first( searchResultElements ) + .innerHTML; const lastSearchResultItemHTML = last( searchResultElements ).innerHTML; - expect( searchResultElements ).toHaveLength( fauxEntitySuggestions.length ); + expect( searchResultElements ).toHaveLength( + fauxEntitySuggestions.length + ); // Sanity check that a search suggestion shows up corresponding to the data expect( firstSearchResultItemHTML ).toEqual( @@ -149,10 +160,15 @@ describe( 'Searching for a link', () => { ); // The fallback URL suggestion should not be shown when input is not URL-like - expect( lastSearchResultItemHTML ).not.toEqual( expect.stringContaining( 'URL' ) ); + expect( lastSearchResultItemHTML ).not.toEqual( + expect.stringContaining( 'URL' ) + ); } ); - it.each( [ [ 'couldbeurlorentitysearchterm' ], [ 'ThisCouldAlsoBeAValidURL' ] ] )( + it.each( [ + [ 'couldbeurlorentitysearchterm' ], + [ 'ThisCouldAlsoBeAValidURL' ], + ] )( 'should display a URL suggestion as a default fallback for the search term "%s" which could potentially be a valid url.', async ( searchTerm ) => { act( () => { @@ -160,30 +176,42 @@ describe( 'Searching for a link', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { - Simulate.change( searchInput, { target: { value: searchTerm } } ); + Simulate.change( searchInput, { + target: { value: searchTerm }, + } ); } ); // fetchFauxEntitySuggestions resolves on next "tick" of event loop await eventLoopTick(); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - const searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); - const lastSearchResultItemHTML = last( searchResultElements ).innerHTML; + const searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); + const lastSearchResultItemHTML = last( searchResultElements ) + .innerHTML; const additionalDefaultFallbackURLSuggestionLength = 1; // We should see a search result for each of the expect search suggestions // plus 1 additional one for the fallback URL suggestion expect( searchResultElements ).toHaveLength( - fauxEntitySuggestions.length + additionalDefaultFallbackURLSuggestionLength + fauxEntitySuggestions.length + + additionalDefaultFallbackURLSuggestionLength ); // The last item should be a URL search suggestion - expect( lastSearchResultItemHTML ).toEqual( expect.stringContaining( searchTerm ) ); - expect( lastSearchResultItemHTML ).toEqual( expect.stringContaining( 'URL' ) ); + expect( lastSearchResultItemHTML ).toEqual( + expect.stringContaining( searchTerm ) + ); + expect( lastSearchResultItemHTML ).toEqual( + expect.stringContaining( 'URL' ) + ); expect( lastSearchResultItemHTML ).toEqual( expect.stringContaining( 'Press ENTER to add this link' ) ); @@ -212,10 +240,14 @@ describe( 'Searching for a link', () => { await eventLoopTick(); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); + searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); // Check we have definitely rendered some suggestions - expect( searchResultElements ).toHaveLength( fauxEntitySuggestions.length ); + expect( searchResultElements ).toHaveLength( + fauxEntitySuggestions.length + ); // Grab the reset button now it's available const resetUI = container.querySelector( '[aria-label="Reset"]' ); @@ -227,7 +259,9 @@ describe( 'Searching for a link', () => { await eventLoopTick(); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); + searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); searchInput = container.querySelector( 'input[aria-label="URL"]' ); expect( searchInput.value ).toBe( '' ); @@ -248,24 +282,37 @@ describe( 'Manual link entry', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { - Simulate.change( searchInput, { target: { value: searchTerm } } ); + Simulate.change( searchInput, { + target: { value: searchTerm }, + } ); } ); // fetchFauxEntitySuggestions resolves on next "tick" of event loop await eventLoopTick(); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - const searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); - const firstSearchResultItemHTML = searchResultElements[ 0 ].innerHTML; + const searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); + const firstSearchResultItemHTML = + searchResultElements[ 0 ].innerHTML; const expectedResultsLength = 1; - expect( searchResultElements ).toHaveLength( expectedResultsLength ); - expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( searchTerm ) ); - expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( 'URL' ) ); + expect( searchResultElements ).toHaveLength( + expectedResultsLength + ); + expect( firstSearchResultItemHTML ).toEqual( + expect.stringContaining( searchTerm ) + ); + expect( firstSearchResultItemHTML ).toEqual( + expect.stringContaining( 'URL' ) + ); expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( 'Press ENTER to add this link' ) ); @@ -285,11 +332,15 @@ describe( 'Manual link entry', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { - Simulate.change( searchInput, { target: { value: searchTerm } } ); + Simulate.change( searchInput, { + target: { value: searchTerm }, + } ); } ); // fetchFauxEntitySuggestions resolves on next "tick" of event loop @@ -299,12 +350,19 @@ describe( 'Manual link entry', () => { const searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); - const firstSearchResultItemHTML = searchResultElements[ 0 ].innerHTML; + const firstSearchResultItemHTML = + searchResultElements[ 0 ].innerHTML; const expectedResultsLength = 1; - expect( searchResultElements ).toHaveLength( expectedResultsLength ); - expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( searchTerm ) ); - expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( searchType ) ); + expect( searchResultElements ).toHaveLength( + expectedResultsLength + ); + expect( firstSearchResultItemHTML ).toEqual( + expect.stringContaining( searchTerm ) + ); + expect( firstSearchResultItemHTML ).toEqual( + expect.stringContaining( searchType ) + ); expect( firstSearchResultItemHTML ).toEqual( expect.stringContaining( 'Press ENTER to add this link' ) ); @@ -324,11 +382,17 @@ describe( 'Default search suggestions', () => { await eventLoopTick(); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // TODO: select these by aria relationship to autocomplete rather than arbitary selector. - const searchResultsWrapper = container.querySelector( '[role="listbox"]' ); - const initialSearchResultElements = searchResultsWrapper.querySelectorAll( '[role="option"]' ); + const searchResultsWrapper = container.querySelector( + '[role="listbox"]' + ); + const initialSearchResultElements = searchResultsWrapper.querySelectorAll( + '[role="option"]' + ); const searchResultsLabel = container.querySelector( `#${ searchResultsWrapper.getAttribute( 'aria-labelledby' ) }` @@ -344,7 +408,9 @@ describe( 'Default search suggestions', () => { expect( mockFetchSearchSuggestions ).toHaveBeenCalledTimes( 1 ); // Verify the search results already display the initial suggestions - expect( initialSearchResultElements ).toHaveLength( expectedResultsLength ); + expect( initialSearchResultElements ).toHaveLength( + expectedResultsLength + ); expect( searchResultsLabel.innerHTML ).toEqual( 'Recently updated' ); } ); @@ -357,7 +423,10 @@ describe( 'Default search suggestions', () => { // act( () => { render( - , + , container ); } ); @@ -381,7 +450,9 @@ describe( 'Default search suggestions', () => { await eventLoopTick(); - searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); + searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); expect( searchResultElements ).toHaveLength( 0 ); @@ -398,7 +469,9 @@ describe( 'Default search suggestions', () => { await eventLoopTick(); - searchResultElements = container.querySelectorAll( '[role="listbox"] [role="option"]' ); + searchResultElements = container.querySelectorAll( + '[role="listbox"] [role="option"]' + ); expect( searchResultElements ).toHaveLength( 3 ); @@ -428,10 +501,16 @@ describe( 'Selecting links', () => { '.block-editor-link-control__search-item.is-current' ); const currentLinkHTML = currentLink.innerHTML; - const currentLinkAnchor = currentLink.querySelector( `[href="${ selectedLink.url }"]` ); + const currentLinkAnchor = currentLink.querySelector( + `[href="${ selectedLink.url }"]` + ); - expect( currentLinkHTML ).toEqual( expect.stringContaining( selectedLink.title ) ); - expect( currentLinkHTML ).toEqual( expect.stringContaining( selectedLink.type ) ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( selectedLink.title ) + ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( selectedLink.type ) + ); expect( currentLinkHTML ).toEqual( expect.stringContaining( 'Edit' ) ); expect( currentLinkAnchor ).not.toBeNull(); } ); @@ -442,7 +521,12 @@ describe( 'Selecting links', () => { const LinkControlConsumer = () => { const [ link, setLink ] = useState( selectedLink ); - return setLink( suggestion ) } />; + return ( + setLink( suggestion ) } + /> + ); }; act( () => { @@ -460,8 +544,12 @@ describe( 'Selecting links', () => { Simulate.click( currentLinkBtn ); } ); - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); - currentLinkUI = container.querySelector( '.block-editor-link-control__search-item.is-current' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); + currentLinkUI = container.querySelector( + '.block-editor-link-control__search-item.is-current' + ); // We should be back to showing the search input expect( searchInput ).not.toBeNull(); @@ -489,7 +577,10 @@ describe( 'Selecting links', () => { const [ link, setLink ] = useState(); return ( - setLink( suggestion ) } /> + setLink( suggestion ) } + /> ); }; @@ -498,11 +589,15 @@ describe( 'Selecting links', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); // Simulate searching for a term act( () => { - Simulate.change( searchInput, { target: { value: searchTerm } } ); + Simulate.change( searchInput, { + target: { value: searchTerm }, + } ); } ); // fetchFauxEntitySuggestions resolves on next "tick" of event loop @@ -524,11 +619,17 @@ describe( 'Selecting links', () => { '.block-editor-link-control__search-item.is-current' ); const currentLinkHTML = currentLink.innerHTML; - const currentLinkAnchor = currentLink.querySelector( `[href="${ selectedLink.url }"]` ); + const currentLinkAnchor = currentLink.querySelector( + `[href="${ selectedLink.url }"]` + ); // Check that this suggestion is now shown as selected - expect( currentLinkHTML ).toEqual( expect.stringContaining( selectedLink.title ) ); - expect( currentLinkHTML ).toEqual( expect.stringContaining( 'Edit' ) ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( selectedLink.title ) + ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( 'Edit' ) + ); expect( currentLinkAnchor ).not.toBeNull(); } ); @@ -554,7 +655,10 @@ describe( 'Selecting links', () => { const [ link, setLink ] = useState(); return ( - setLink( suggestion ) } /> + setLink( suggestion ) } + /> ); }; @@ -563,12 +667,16 @@ describe( 'Selecting links', () => { } ); // Search Input UI - const searchInput = container.querySelector( 'input[aria-label="URL"]' ); + const searchInput = container.querySelector( + 'input[aria-label="URL"]' + ); const form = container.querySelector( 'form' ); // Simulate searching for a term act( () => { - Simulate.change( searchInput, { target: { value: searchTerm } } ); + Simulate.change( searchInput, { + target: { value: searchTerm }, + } ); } ); //fetchFauxEntitySuggestions resolves on next "tick" of event loop @@ -591,7 +699,9 @@ describe( 'Selecting links', () => { ); // We should have highlighted the first item using the keyboard - expect( selectedSearchResultElement ).toEqual( firstSearchSuggestion ); + expect( selectedSearchResultElement ).toEqual( + firstSearchSuggestion + ); // Only entity searches contain more than 1 suggestion if ( type === 'entity' ) { @@ -605,7 +715,9 @@ describe( 'Selecting links', () => { ); // We should have highlighted the first item using the keyboard - expect( selectedSearchResultElement ).toEqual( secondSearchSuggestion ); + expect( selectedSearchResultElement ).toEqual( + secondSearchSuggestion + ); // Check we can go back up via up arrow act( () => { @@ -617,7 +729,9 @@ describe( 'Selecting links', () => { ); // We should be back to highlighting the first search result again - expect( selectedSearchResultElement ).toEqual( firstSearchSuggestion ); + expect( selectedSearchResultElement ).toEqual( + firstSearchSuggestion + ); } // Commit the selected item as the current link @@ -633,13 +747,21 @@ describe( 'Selecting links', () => { '.block-editor-link-control__search-item.is-current' ); const currentLinkHTML = currentLink.innerHTML; - const currentLinkAnchor = currentLink.querySelector( `[href="${ selectedLink.url }"]` ); + const currentLinkAnchor = currentLink.querySelector( + `[href="${ selectedLink.url }"]` + ); // Make sure focus is retained after submission. - expect( container.contains( document.activeElement ) ).toBe( true ); + expect( container.contains( document.activeElement ) ).toBe( + true + ); - expect( currentLinkHTML ).toEqual( expect.stringContaining( selectedLink.title ) ); - expect( currentLinkHTML ).toEqual( expect.stringContaining( 'Edit' ) ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( selectedLink.title ) + ); + expect( currentLinkHTML ).toEqual( + expect.stringContaining( 'Edit' ) + ); expect( currentLinkAnchor ).not.toBeNull(); } ); @@ -661,13 +783,21 @@ describe( 'Addition Settings UI', () => { render( , container ); } ); - const newTabSettingLabel = Array.from( container.querySelectorAll( 'label' ) ).find( - ( label ) => label.innerHTML && label.innerHTML.includes( expectedSettingText ) + const newTabSettingLabel = Array.from( + container.querySelectorAll( 'label' ) + ).find( + ( label ) => + label.innerHTML && + label.innerHTML.includes( expectedSettingText ) ); expect( newTabSettingLabel ).not.toBeUndefined(); // find() returns "undefined" if not found - const newTabSettingLabelForAttr = newTabSettingLabel.getAttribute( 'for' ); - const newTabSettingInput = container.querySelector( `#${ newTabSettingLabelForAttr }` ); + const newTabSettingLabelForAttr = newTabSettingLabel.getAttribute( + 'for' + ); + const newTabSettingInput = container.querySelector( + `#${ newTabSettingLabelForAttr }` + ); expect( newTabSettingInput ).not.toBeNull(); expect( newTabSettingInput.checked ).toBe( false ); } ); @@ -686,7 +816,9 @@ describe( 'Addition Settings UI', () => { }, ]; - const customSettingsLabelsText = customSettings.map( ( setting ) => setting.title ); + const customSettingsLabelsText = customSettings.map( + ( setting ) => setting.title + ); const LinkControlConsumer = () => { const [ link ] = useState( selectedLink ); @@ -704,19 +836,26 @@ describe( 'Addition Settings UI', () => { } ); // Grab the elements using user perceivable DOM queries - const settingsLegend = Array.from( container.querySelectorAll( 'legend' ) ).find( + const settingsLegend = Array.from( + container.querySelectorAll( 'legend' ) + ).find( ( legend ) => - legend.innerHTML && legend.innerHTML.includes( 'Currently selected link settings' ) + legend.innerHTML && + legend.innerHTML.includes( 'Currently selected link settings' ) ); const settingsFieldset = settingsLegend.closest( 'fieldset' ); - const settingControlsLabels = Array.from( settingsFieldset.querySelectorAll( 'label' ) ); + const settingControlsLabels = Array.from( + settingsFieldset.querySelectorAll( 'label' ) + ); const settingControlsInputs = settingControlsLabels.map( ( label ) => { - return settingsFieldset.querySelector( `#${ label.getAttribute( 'for' ) }` ); + return settingsFieldset.querySelector( + `#${ label.getAttribute( 'for' ) }` + ); } ); - const settingControlLabelsText = Array.from( settingControlsLabels ).map( - ( label ) => label.innerHTML - ); + const settingControlLabelsText = Array.from( + settingControlsLabels + ).map( ( label ) => label.innerHTML ); // Check we have the correct number of controls expect( settingControlsLabels ).toHaveLength( 2 ); diff --git a/packages/block-editor/src/components/media-edit/index.native.js b/packages/block-editor/src/components/media-edit/index.native.js index c82927a9facca5..fd10c10e2ef5b1 100644 --- a/packages/block-editor/src/components/media-edit/index.native.js +++ b/packages/block-editor/src/components/media-edit/index.native.js @@ -2,7 +2,10 @@ * External dependencies */ import React from 'react'; -import { requestMediaEditor, mediaSources } from 'react-native-gutenberg-bridge'; +import { + requestMediaEditor, + mediaSources, +} from 'react-native-gutenberg-bridge'; /** * WordPress dependencies @@ -75,7 +78,10 @@ export class MediaEdit extends React.Component { /> ); - return this.props.render( { open: this.onPickerPresent, mediaOptions } ); + return this.props.render( { + open: this.onPickerPresent, + mediaOptions, + } ); } } diff --git a/packages/block-editor/src/components/media-placeholder/index.js b/packages/block-editor/src/components/media-placeholder/index.js index 9d28a65d65e4b2..1874c431a83d02 100644 --- a/packages/block-editor/src/components/media-placeholder/index.js +++ b/packages/block-editor/src/components/media-placeholder/index.js @@ -7,7 +7,13 @@ import classnames from 'classnames'; /** * WordPress dependencies */ -import { Button, FormFileUpload, Placeholder, DropZone, withFilters } from '@wordpress/components'; +import { + Button, + FormFileUpload, + Placeholder, + DropZone, + withFilters, +} from '@wordpress/components'; import { __ } from '@wordpress/i18n'; import { Component } from '@wordpress/element'; import { compose } from '@wordpress/compose'; @@ -23,7 +29,10 @@ import URLPopover from '../url-popover'; const InsertFromURLPopover = ( { src, onChange, onSubmit, onClose } ) => ( - + { - return allowedType === 'image' || startsWith( allowedType, 'image/' ); + return ( + allowedType === 'image' || startsWith( allowedType, 'image/' ) + ); } ); } @@ -72,7 +83,10 @@ export class MediaPlaceholder extends Component { } componentDidUpdate( prevProps ) { - if ( get( prevProps.value, [ 'src' ], '' ) !== get( this.props.value, [ 'src' ], '' ) ) { + if ( + get( prevProps.value, [ 'src' ], '' ) !== + get( this.props.value, [ 'src' ], '' ) + ) { this.setState( { src: get( this.props.value, [ 'src' ], '' ) } ); } } @@ -151,7 +165,9 @@ export class MediaPlaceholder extends Component { let title = labels.title; if ( ! mediaUpload && ! onSelectURL ) { - instructions = __( 'To edit this block, you need permission to upload media.' ); + instructions = __( + 'To edit this block, you need permission to upload media.' + ); } if ( instructions === undefined || title === undefined ) { @@ -161,7 +177,9 @@ export class MediaPlaceholder extends Component { const isVideo = isOneType && 'video' === allowedTypes[ 0 ]; if ( instructions === undefined && mediaUpload ) { - instructions = __( 'Upload a media file or pick one from your media library.' ); + instructions = __( + 'Upload a media file or pick one from your media library.' + ); if ( isAudio ) { instructions = __( @@ -191,9 +209,13 @@ export class MediaPlaceholder extends Component { } } - const placeholderClassName = classnames( 'block-editor-media-placeholder', className, { - 'is-appender': isAppender, - } ); + const placeholderClassName = classnames( + 'block-editor-media-placeholder', + className, + { + 'is-appender': isAppender, + } + ); return ( ; + return ( + + ); } renderCancelLink() { @@ -285,7 +312,9 @@ export class MediaPlaceholder extends Component { multiple={ multiple } onSelect={ onSelect } allowedTypes={ allowedTypes } - value={ isArray( value ) ? value.map( ( { id } ) => id ) : value.id } + value={ + isArray( value ) ? value.map( ( { id } ) => id ) : value.id + } render={ ( { open } ) => { return ( ) @@ -27,6 +31,8 @@ const SkipToSelectedBlock = ( { selectedBlockClientId } ) => { export default withSelect( ( select ) => { return { - selectedBlockClientId: select( 'core/block-editor' ).getBlockSelectionStart(), + selectedBlockClientId: select( + 'core/block-editor' + ).getBlockSelectionStart(), }; } )( SkipToSelectedBlock ); diff --git a/packages/block-editor/src/components/tool-selector/index.js b/packages/block-editor/src/components/tool-selector/index.js index 818c09b30a40d9..1b9b7e0e5a0b2b 100644 --- a/packages/block-editor/src/components/tool-selector/index.js +++ b/packages/block-editor/src/components/tool-selector/index.js @@ -1,19 +1,36 @@ /** * WordPress dependencies */ -import { Dropdown, Button, MenuItemsChoice, SVG, Path, NavigableMenu } from '@wordpress/components'; +import { + Dropdown, + Button, + MenuItemsChoice, + SVG, + Path, + NavigableMenu, +} from '@wordpress/components'; import { __ } from '@wordpress/i18n'; import { useSelect, useDispatch } from '@wordpress/data'; import { useViewportMatch } from '@wordpress/compose'; const editIcon = ( - + ); const selectIcon = ( - + ); diff --git a/packages/block-editor/src/components/typewriter/index.js b/packages/block-editor/src/components/typewriter/index.js index ab46c5b0764f45..b9b2e18ea61040 100644 --- a/packages/block-editor/src/components/typewriter/index.js +++ b/packages/block-editor/src/components/typewriter/index.js @@ -18,12 +18,18 @@ class Typewriter extends Component { this.ref = createRef(); this.onKeyDown = this.onKeyDown.bind( this ); - this.addSelectionChangeListener = this.addSelectionChangeListener.bind( this ); - this.computeCaretRectOnSelectionChange = this.computeCaretRectOnSelectionChange.bind( this ); + this.addSelectionChangeListener = this.addSelectionChangeListener.bind( + this + ); + this.computeCaretRectOnSelectionChange = this.computeCaretRectOnSelectionChange.bind( + this + ); this.maintainCaretPosition = this.maintainCaretPosition.bind( this ); this.computeCaretRect = this.computeCaretRect.bind( this ); this.onScrollResize = this.onScrollResize.bind( this ); - this.isSelectionEligibleForScroll = this.isSelectionEligibleForScroll.bind( this ); + this.isSelectionEligibleForScroll = this.isSelectionEligibleForScroll.bind( + this + ); } componentDidMount() { @@ -36,7 +42,10 @@ class Typewriter extends Component { componentWillUnmount() { window.removeEventListener( 'scroll', this.onScrollResize, true ); window.removeEventListener( 'resize', this.onScrollResize, true ); - document.removeEventListener( 'selectionchange', this.computeCaretRectOnSelectionChange ); + document.removeEventListener( + 'selectionchange', + this.computeCaretRectOnSelectionChange + ); if ( this.onScrollResize.rafId ) { window.cancelAnimationFrame( this.onScrollResize.rafId ); @@ -61,7 +70,10 @@ class Typewriter extends Component { * event. Also removes the listener, so it acts as a one-time listener. */ computeCaretRectOnSelectionChange() { - document.removeEventListener( 'selectionchange', this.computeCaretRectOnSelectionChange ); + document.removeEventListener( + 'selectionchange', + this.computeCaretRectOnSelectionChange + ); this.computeCaretRect(); } @@ -91,7 +103,9 @@ class Typewriter extends Component { } isLastEditableNode() { - const editableNodes = this.ref.current.querySelectorAll( '[contenteditable="true"]' ); + const editableNodes = this.ref.current.querySelectorAll( + '[contenteditable="true"]' + ); const lastEditableNode = editableNodes[ editableNodes.length - 1 ]; return lastEditableNode === document.activeElement; } @@ -143,11 +157,16 @@ class Typewriter extends Component { } const windowScroll = scrollContainer === document.body; - const scrollY = windowScroll ? window.scrollY : scrollContainer.scrollTop; - const scrollContainerY = windowScroll ? 0 : scrollContainer.getBoundingClientRect().top; + const scrollY = windowScroll + ? window.scrollY + : scrollContainer.scrollTop; + const scrollContainerY = windowScroll + ? 0 + : scrollContainer.getBoundingClientRect().top; const relativeScrollPosition = windowScroll ? this.caretRect.top / window.innerHeight - : ( this.caretRect.top - scrollContainerY ) / ( window.innerHeight - scrollContainerY ); + : ( this.caretRect.top - scrollContainerY ) / + ( window.innerHeight - scrollContainerY ); // If the scroll position is at the start, the active editable element // is the last one, and the caret is positioned within the initial @@ -165,13 +184,16 @@ class Typewriter extends Component { return; } - const scrollContainerHeight = windowScroll ? window.innerHeight : scrollContainer.clientHeight; + const scrollContainerHeight = windowScroll + ? window.innerHeight + : scrollContainer.clientHeight; // Abort if the target scroll position would scroll the caret out of // view. if ( // The caret is under the lower fold. - this.caretRect.top + this.caretRect.height > scrollContainerY + scrollContainerHeight || + this.caretRect.top + this.caretRect.height > + scrollContainerY + scrollContainerHeight || // The caret is above the upper fold. this.caretRect.top < scrollContainerY ) { @@ -192,7 +214,10 @@ class Typewriter extends Component { * maintained. */ addSelectionChangeListener() { - document.addEventListener( 'selectionchange', this.computeCaretRectOnSelectionChange ); + document.addEventListener( + 'selectionchange', + this.computeCaretRectOnSelectionChange + ); } onKeyDown( event ) { diff --git a/packages/block-editor/src/components/ungroup-button/icon.js b/packages/block-editor/src/components/ungroup-button/icon.js index 18fec5c1c94bfa..d71219e4696662 100644 --- a/packages/block-editor/src/components/ungroup-button/icon.js +++ b/packages/block-editor/src/components/ungroup-button/icon.js @@ -4,7 +4,12 @@ import { SVG, Path } from '@wordpress/components'; const UngroupSVG = ( - + { - const { getSelectedBlockClientId, getBlock } = select( 'core/block-editor' ); + const { getSelectedBlockClientId, getBlock } = select( + 'core/block-editor' + ); const { getGroupingBlockName } = select( 'core/blocks' ); diff --git a/packages/block-editor/src/components/url-input/button.js b/packages/block-editor/src/components/url-input/button.js index 51d8844c446e3d..e262dce201b3ed 100644 --- a/packages/block-editor/src/components/url-input/button.js +++ b/packages/block-editor/src/components/url-input/button.js @@ -44,7 +44,10 @@ class URLInputButton extends Component { isPressed={ !! url } /> { expanded && ( -
        +
        ) } diff --git a/packages/block-editor/src/components/url-input/index.js b/packages/block-editor/src/components/url-input/index.js index 474699a9083603..2ef7b911877c73 100644 --- a/packages/block-editor/src/components/url-input/index.js +++ b/packages/block-editor/src/components/url-input/index.js @@ -11,7 +11,13 @@ import scrollIntoView from 'dom-scroll-into-view'; import { __, sprintf, _n } from '@wordpress/i18n'; import { Component, createRef } from '@wordpress/element'; import { UP, DOWN, ENTER, TAB } from '@wordpress/keycodes'; -import { BaseControl, Button, Spinner, withSpokenMessages, Popover } from '@wordpress/components'; +import { + BaseControl, + Button, + Spinner, + withSpokenMessages, + Popover, +} from '@wordpress/components'; import { withInstanceId, withSafeTimeout, compose } from '@wordpress/compose'; import { withSelect } from '@wordpress/data'; import { isURL } from '@wordpress/url'; @@ -32,7 +38,10 @@ class URLInput extends Component { this.bindSuggestionNode = this.bindSuggestionNode.bind( this ); this.autocompleteRef = props.autocompleteRef || createRef(); this.inputRef = createRef(); - this.updateSuggestions = throttle( this.updateSuggestions.bind( this ), 200 ); + this.updateSuggestions = throttle( + this.updateSuggestions.bind( this ), + 200 + ); this.suggestionNodes = []; @@ -50,12 +59,20 @@ class URLInput extends Component { // only have to worry about scrolling selected suggestion into view // when already expanded - if ( showSuggestions && selectedSuggestion !== null && ! this.scrollingIntoView ) { + if ( + showSuggestions && + selectedSuggestion !== null && + ! this.scrollingIntoView + ) { this.scrollingIntoView = true; - scrollIntoView( this.suggestionNodes[ selectedSuggestion ], this.autocompleteRef.current, { - onlyScrollIfNeeded: true, - } ); + scrollIntoView( + this.suggestionNodes[ selectedSuggestion ], + this.autocompleteRef.current, + { + onlyScrollIfNeeded: true, + } + ); this.props.setTimeout( () => { this.scrollingIntoView = false; @@ -85,7 +102,10 @@ class URLInput extends Component { shouldShowInitialSuggestions() { const { suggestions } = this.state; - const { __experimentalShowInitialSuggestions = false, value } = this.props; + const { + __experimentalShowInitialSuggestions = false, + value, + } = this.props; return ( ! this.isUpdatingSuggestions && __experimentalShowInitialSuggestions && @@ -162,7 +182,10 @@ class URLInput extends Component { 'assertive' ); } else { - this.props.debouncedSpeak( __( 'No results.' ), 'assertive' ); + this.props.debouncedSpeak( + __( 'No results.' ), + 'assertive' + ); } this.isUpdatingSuggestions = false; } ) @@ -190,7 +213,12 @@ class URLInput extends Component { } onKeyDown( event ) { - const { showSuggestions, selectedSuggestion, suggestions, loading } = this.state; + const { + showSuggestions, + selectedSuggestion, + suggestions, + loading, + } = this.state; // If the suggestions are not shown or loading, we shouldn't handle the arrow keys // We shouldn't preventDefault to allow block arrow keys navigation @@ -216,12 +244,17 @@ class URLInput extends Component { // When DOWN is pressed, if the caret is not at the end of the text, move it to the // last position. case DOWN: { - if ( this.props.value.length !== event.target.selectionStart ) { + if ( + this.props.value.length !== event.target.selectionStart + ) { event.stopPropagation(); event.preventDefault(); // Set the input caret to the last position - event.target.setSelectionRange( this.props.value.length, this.props.value.length ); + event.target.setSelectionRange( + this.props.value.length, + this.props.value.length + ); } break; } @@ -230,7 +263,9 @@ class URLInput extends Component { return; } - const suggestion = this.state.suggestions[ this.state.selectedSuggestion ]; + const suggestion = this.state.suggestions[ + this.state.selectedSuggestion + ]; switch ( event.keyCode ) { case UP: { @@ -248,7 +283,8 @@ class URLInput extends Component { event.stopPropagation(); event.preventDefault(); const nextIndex = - selectedSuggestion === null || selectedSuggestion === suggestions.length - 1 + selectedSuggestion === null || + selectedSuggestion === suggestions.length - 1 ? 0 : selectedSuggestion + 1; this.setState( { @@ -289,7 +325,11 @@ class URLInput extends Component { } static getDerivedStateFromProps( - { value, disableSuggestions, __experimentalShowInitialSuggestions = false }, + { + value, + disableSuggestions, + __experimentalShowInitialSuggestions = false, + }, { showSuggestions } ) { let shouldShowSuggestions = showSuggestions; @@ -323,7 +363,12 @@ class URLInput extends Component { __experimentalShowInitialSuggestions = false, } = this.props; - const { showSuggestions, suggestions, selectedSuggestion, loading } = this.state; + const { + showSuggestions, + suggestions, + selectedSuggestion, + loading, + } = this.state; const id = `url-input-control-${ instanceId }`; @@ -391,33 +436,50 @@ class URLInput extends Component { isLoading: loading, handleSuggestionClick: this.handleOnClick, isInitialSuggestions: - __experimentalShowInitialSuggestions && ! ( value && value.length ), + __experimentalShowInitialSuggestions && + ! ( value && value.length ), } ) } - { ! isFunction( renderSuggestions ) && showSuggestions && !! suggestions.length && ( - -
        - { suggestions.map( ( suggestion, index ) => ( - - ) ) } -
        -
        - ) } +
        + { suggestions.map( ( suggestion, index ) => ( + + ) ) } +
        + + ) } ); /* eslint-enable jsx-a11y/no-autofocus */ @@ -439,7 +501,8 @@ export default compose( } const { getSettings } = select( 'core/block-editor' ); return { - __experimentalFetchLinkSuggestions: getSettings().__experimentalFetchLinkSuggestions, + __experimentalFetchLinkSuggestions: getSettings() + .__experimentalFetchLinkSuggestions, }; } ) )( URLInput ); diff --git a/packages/block-editor/src/components/url-input/index.native.js b/packages/block-editor/src/components/url-input/index.native.js index 7be5c954a9eddf..f08fff246b6f18 100644 --- a/packages/block-editor/src/components/url-input/index.native.js +++ b/packages/block-editor/src/components/url-input/index.native.js @@ -8,7 +8,12 @@ import { TextInput } from 'react-native'; */ import { __ } from '@wordpress/i18n'; -export default function URLInput( { value = '', autoFocus = true, onChange, ...extraProps } ) { +export default function URLInput( { + value = '', + autoFocus = true, + onChange, + ...extraProps +} ) { /* eslint-disable jsx-a11y/no-autofocus */ return ( { const clickEditLink = ( wrapper ) => - wrapper.find( 'ForwardRef(Button).components-toolbar__control' ).simulate( 'click' ); + wrapper + .find( 'ForwardRef(Button).components-toolbar__control' ) + .simulate( 'click' ); it( 'should have a valid class name in the wrapper tag', () => { const wrapper = shallow( ); - expect( wrapper.hasClass( 'block-editor-url-input__button' ) ).toBe( true ); + expect( wrapper.hasClass( 'block-editor-url-input__button' ) ).toBe( + true + ); } ); it( 'should have isPressed props set to false when url prop not defined', () => { const wrapper = shallow( ); - expect( wrapper.find( 'ForwardRef(Button)' ).prop( 'isPressed' ) ).toBe( false ); + expect( wrapper.find( 'ForwardRef(Button)' ).prop( 'isPressed' ) ).toBe( + false + ); } ); it( 'should have isPressed prop set to true if url prop defined', () => { const wrapper = shallow( ); - expect( wrapper.find( 'ForwardRef(Button)' ).prop( 'isPressed' ) ).toBe( true ); + expect( wrapper.find( 'ForwardRef(Button)' ).prop( 'isPressed' ) ).toBe( + true + ); } ); it( 'should have hidden form by default', () => { const wrapper = shallow( ); @@ -65,13 +73,19 @@ describe( 'URLInputButton', () => { it( 'should close the form when user submits it', () => { const wrapper = TestUtils.renderIntoDocument( ); const buttonElement = () => - TestUtils.scryRenderedDOMComponentsWithClass( wrapper, 'components-toolbar__control' ); - const formElement = () => TestUtils.scryRenderedDOMComponentsWithTag( wrapper, 'form' ); + TestUtils.scryRenderedDOMComponentsWithClass( + wrapper, + 'components-toolbar__control' + ); + const formElement = () => + TestUtils.scryRenderedDOMComponentsWithTag( wrapper, 'form' ); TestUtils.Simulate.click( buttonElement().shift() ); expect( wrapper.state.expanded ).toBe( true ); TestUtils.Simulate.submit( formElement().shift() ); expect( wrapper.state.expanded ).toBe( false ); - // eslint-disable-next-line react/no-find-dom-node - ReactDOM.unmountComponentAtNode( ReactDOM.findDOMNode( wrapper ).parentNode ); + ReactDOM.unmountComponentAtNode( + // eslint-disable-next-line react/no-find-dom-node + ReactDOM.findDOMNode( wrapper ).parentNode + ); } ); } ); diff --git a/packages/block-editor/src/components/url-popover/image-url-input-ui.js b/packages/block-editor/src/components/url-popover/image-url-input-ui.js index af251e1dc2becf..5263dbe57c74c6 100644 --- a/packages/block-editor/src/components/url-popover/image-url-input-ui.js +++ b/packages/block-editor/src/components/url-popover/image-url-input-ui.js @@ -64,7 +64,11 @@ const ImageURLInputUI = ( { }; const stopPropagationRelevantKeys = ( event ) => { - if ( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( event.keyCode ) > -1 ) { + if ( + [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( + event.keyCode + ) > -1 + ) { // Stop the key event from propagating up to ObserveTyping.startTypingInTextField. event.stopPropagation(); } @@ -137,7 +141,10 @@ const ImageURLInputUI = ( { // LinkContainer. Detect clicks on autocomplete suggestions using a ref here, and // return to avoid the popover being closed. const autocompleteElement = autocompleteRef.current; - if ( autocompleteElement && autocompleteElement.contains( event.target ) ) { + if ( + autocompleteElement && + autocompleteElement.contains( event.target ) + ) { return; } setIsOpen( false ); @@ -243,8 +250,10 @@ const ImageURLInputUI = ( { const linkEditorValue = urlInput !== null ? urlInput : url; - const urlLabel = ( find( getLinkDestinations(), [ 'linkDestination', linkDestination ] ) || {} ) - .title; + const urlLabel = ( + find( getLinkDestinations(), [ 'linkDestination', linkDestination ] ) || + {} + ).title; return ( <> @@ -300,7 +309,11 @@ const ImageURLInputUI = ( { onEditLinkClick={ startEditLink } urlLabel={ urlLabel } /> -
        ); diff --git a/packages/block-editor/src/components/url-popover/test/index.js b/packages/block-editor/src/components/url-popover/test/index.js index b8000d1837b9ac..af157935104356 100644 --- a/packages/block-editor/src/components/url-popover/test/index.js +++ b/packages/block-editor/src/components/url-popover/test/index.js @@ -26,7 +26,9 @@ describe( 'URLPopover', () => { ); - const toggleButton = wrapper.find( '.block-editor-url-popover__settings-toggle' ); + const toggleButton = wrapper.find( + '.block-editor-url-popover__settings-toggle' + ); expect( toggleButton ).toHaveLength( 1 ); toggleButton.simulate( 'click' ); diff --git a/packages/block-editor/src/components/video-player/gridicon-play.native.js b/packages/block-editor/src/components/video-player/gridicon-play.native.js index 89b88c4377ecb5..037cdfd36272c7 100644 --- a/packages/block-editor/src/components/video-player/gridicon-play.native.js +++ b/packages/block-editor/src/components/video-player/gridicon-play.native.js @@ -5,6 +5,9 @@ import { Path, SVG } from '@wordpress/components'; export default ( - + ); diff --git a/packages/block-editor/src/components/video-player/index.native.js b/packages/block-editor/src/components/video-player/index.native.js index d20884cd113c8e..a409c1d4ad99fc 100644 --- a/packages/block-editor/src/components/video-player/index.native.js +++ b/packages/block-editor/src/components/video-player/index.native.js @@ -59,9 +59,14 @@ class Video extends Component { if ( ! supported ) { Alert.alert( __( 'Problem opening the video' ), - __( 'No application can handle this request. Please install a Web browser.' ) + __( + 'No application can handle this request. Please install a Web browser.' + ) + ); + window.console.warn( + 'No application found that can open the video with URL: ' + + url ); - window.console.warn( 'No application found that can open the video with URL: ' + url ); } else { return Linking.openURL( url ); } @@ -71,7 +76,10 @@ class Video extends Component { __( 'Problem opening the video' ), __( 'An unknown error occurred. Please try again.' ) ); - window.console.error( 'An error occurred while opening the video URL: ' + url, err ); + window.console.error( + 'An error occurred while opening the video URL: ' + url, + err + ); } ); } @@ -110,7 +118,11 @@ class Video extends Component { style={ [ style, styles.overlayContainer ] } > - + ) } diff --git a/packages/block-editor/src/components/warning/index.js b/packages/block-editor/src/components/warning/index.js index 23048b121518af..9c5765ff9cf5e0 100644 --- a/packages/block-editor/src/components/warning/index.js +++ b/packages/block-editor/src/components/warning/index.js @@ -19,7 +19,10 @@ function Warning( { className, actions, children, secondaryActions } ) { { Children.count( actions ) > 0 && (
        { Children.map( actions, ( action, i ) => ( - + { action } ) ) } diff --git a/packages/block-editor/src/components/warning/index.native.js b/packages/block-editor/src/components/warning/index.native.js index cd9567c93dd2fc..cda7f13a68405d 100644 --- a/packages/block-editor/src/components/warning/index.native.js +++ b/packages/block-editor/src/components/warning/index.native.js @@ -26,12 +26,21 @@ function Warning( { } ) { icon = icon && normalizeIconObject( icon ); const internalIconClass = 'warning-icon' + '-' + preferredColorScheme; - const titleStyle = getStylesFromColorScheme( styles.title, styles.titleDark ); - const messageStyle = getStylesFromColorScheme( styles.message, styles.messageDark ); + const titleStyle = getStylesFromColorScheme( + styles.title, + styles.titleDark + ); + const messageStyle = getStylesFromColorScheme( + styles.message, + styles.messageDark + ); return ( { icon && ( diff --git a/packages/block-editor/src/components/warning/test/index.js b/packages/block-editor/src/components/warning/test/index.js index 15357407a810dc..b8fcdbee4e4900 100644 --- a/packages/block-editor/src/components/warning/test/index.js +++ b/packages/block-editor/src/components/warning/test/index.js @@ -19,24 +19,34 @@ describe( 'Warning', () => { const wrapper = shallow( ); expect( wrapper.hasClass( 'block-editor-warning' ) ).toBe( true ); - expect( wrapper.find( '.block-editor-warning__actions' ) ).toHaveLength( 0 ); - expect( wrapper.find( '.block-editor-warning__hidden' ) ).toHaveLength( 0 ); + expect( wrapper.find( '.block-editor-warning__actions' ) ).toHaveLength( + 0 + ); + expect( wrapper.find( '.block-editor-warning__hidden' ) ).toHaveLength( + 0 + ); } ); it( 'should show child error message element', () => { - const wrapper = shallow( }>Message ); + const wrapper = shallow( + }>Message + ); const actions = wrapper.find( '.block-editor-warning__actions' ); const action = actions.childAt( 0 ); expect( actions ).toHaveLength( 1 ); - expect( action.hasClass( 'block-editor-warning__action' ) ).toBe( true ); + expect( action.hasClass( 'block-editor-warning__action' ) ).toBe( + true + ); expect( action.childAt( 0 ).type() ).toBe( 'button' ); } ); it( 'should show hidden actions', () => { const wrapper = shallow( - Message + + Message + ); const actions = wrapper.find( '.block-editor-warning__secondary' ); diff --git a/packages/block-editor/src/components/writing-flow/index.js b/packages/block-editor/src/components/writing-flow/index.js index ff842db5acd79a..91b0dcfe274ecb 100644 --- a/packages/block-editor/src/components/writing-flow/index.js +++ b/packages/block-editor/src/components/writing-flow/index.js @@ -18,7 +18,15 @@ import { placeCaretAtVerticalEdge, isEntirelySelected, } from '@wordpress/dom'; -import { UP, DOWN, LEFT, RIGHT, TAB, isKeyboardEvent, ESCAPE } from '@wordpress/keycodes'; +import { + UP, + DOWN, + LEFT, + RIGHT, + TAB, + isKeyboardEvent, + ESCAPE, +} from '@wordpress/keycodes'; import { useSelect, useDispatch } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; @@ -49,7 +57,10 @@ const { getSelection, getComputedStyle } = window; * * @return {boolean} Whether element is a tabbable text field. */ -const isTabbableTextField = overEvery( [ isTextField, focus.tabbable.isTabbableIndex ] ); +const isTabbableTextField = overEvery( [ + isTextField, + focus.tabbable.isTabbableIndex, +] ); /** * Returns true if the element should consider edge navigation upon a keyboard @@ -97,7 +108,9 @@ export function getClosestTabbable( target, isReverse, containerElement ) { // Consider as candidates those focusables after the current target. // It's assumed this can only be reached if the target is focusable // (on its keydown event), so no need to verify it exists in the set. - focusableNodes = focusableNodes.slice( focusableNodes.indexOf( target ) + 1 ); + focusableNodes = focusableNodes.slice( + focusableNodes.indexOf( target ) + 1 + ); function isTabCandidate( node, i, array ) { // Not a candidate if the node is not tabbable. @@ -129,7 +142,11 @@ export function getClosestTabbable( target, isReverse, containerElement ) { // In case of block focus stop, check to see if there's a better // text field candidate within. - for ( let offset = 1, nextNode; ( nextNode = array[ i + offset ] ); offset++ ) { + for ( + let offset = 1, nextNode; + ( nextNode = array[ i + offset ] ); + offset++ + ) { // Abort if no longer testing descendents of focus stop. if ( ! node.contains( nextNode ) ) { break; @@ -225,9 +242,12 @@ export default function WritingFlow( { children } ) { blockSelectionStart, isMultiSelecting, } = useSelect( selector, [] ); - const { multiSelect, selectBlock, clearSelectedBlock, setNavigationMode } = useDispatch( - 'core/block-editor' - ); + const { + multiSelect, + selectBlock, + clearSelectedBlock, + setNavigationMode, + } = useDispatch( 'core/block-editor' ); function onMouseDown( event ) { verticalRect.current = null; @@ -236,7 +256,10 @@ export default function WritingFlow( { children } ) { if ( isNavigationMode && selectedBlockClientId && - isInsideRootBlock( getBlockDOMNode( selectedBlockClientId ), event.target ) + isInsideRootBlock( + getBlockDOMNode( selectedBlockClientId ), + event.target + ) ) { setNavigationMode( false ); } @@ -274,12 +297,17 @@ export default function WritingFlow( { children } ) { : selectionAfterEndClientId; if ( nextSelectionEndClientId ) { - multiSelect( selectionStartClientId || selectedBlockClientId, nextSelectionEndClientId ); + multiSelect( + selectionStartClientId || selectedBlockClientId, + nextSelectionEndClientId + ); } } function moveSelection( isReverse ) { - const focusedBlockClientId = isReverse ? selectedFirstClientId : selectedLastClientId; + const focusedBlockClientId = isReverse + ? selectedFirstClientId + : selectedLastClientId; if ( focusedBlockClientId ) { selectBlock( focusedBlockClientId ); @@ -298,7 +326,11 @@ export default function WritingFlow( { children } ) { * @return {boolean} Whether field is at edge for tab transition. */ function isTabbableEdge( target, isReverse ) { - const closestTabbable = getClosestTabbable( target, isReverse, container.current ); + const closestTabbable = getClosestTabbable( + target, + isReverse, + container.current + ); return ! closestTabbable || ! isInSameBlock( target, closestTabbable ); } @@ -315,14 +347,17 @@ export default function WritingFlow( { children } ) { const isVertical = isUp || isDown; const isNav = isHorizontal || isVertical; const isShift = event.shiftKey; - const hasModifier = isShift || event.ctrlKey || event.altKey || event.metaKey; + const hasModifier = + isShift || event.ctrlKey || event.altKey || event.metaKey; const isNavEdge = isVertical ? isVerticalEdge : isHorizontalEdge; // In navigation mode, tab and arrows navigate from block to block. if ( isNavigationMode ) { const navigateUp = ( isTab && isShift ) || isUp; const navigateDown = ( isTab && ! isShift ) || isDown; - const focusedBlockUid = navigateUp ? selectionBeforeEndClientId : selectionAfterEndClientId; + const focusedBlockUid = navigateUp + ? selectionBeforeEndClientId + : selectionAfterEndClientId; if ( navigateDown || navigateUp ) { if ( focusedBlockUid ) { @@ -382,7 +417,11 @@ export default function WritingFlow( { children } ) { } else if ( isEscape ) { setNavigationMode( true ); } - } else if ( hasMultiSelection && isTab && target === multiSelectionContainer.current ) { + } else if ( + hasMultiSelection && + isTab && + target === multiSelectionContainer.current + ) { // See comment above. noCapture.current = true; @@ -422,7 +461,11 @@ export default function WritingFlow( { children } ) { // have been set by the browser earlier in this call stack. We // need check the previous result, otherwise all blocks will be // selected right away. - if ( target.isContentEditable ? entirelySelected.current : isEntirelySelected( target ) ) { + if ( + target.isContentEditable + ? entirelySelected.current + : isEntirelySelected( target ) + ) { multiSelect( first( blocks ), last( blocks ) ); event.preventDefault(); } @@ -458,7 +501,8 @@ export default function WritingFlow( { children } ) { ( ( isReverse && selectionBeforeEndClientId ) || ( ! isReverse && selectionAfterEndClientId ) ) && ( hasMultiSelection || - ( isTabbableEdge( target, isReverse ) && isNavEdge( target, isReverse ) ) ) + ( isTabbableEdge( target, isReverse ) && + isNavEdge( target, isReverse ) ) ) ) { // Shift key is down, and there is multi selection or we're at // the end of the current block. @@ -470,10 +514,18 @@ export default function WritingFlow( { children } ) { moveSelection( isReverse ); event.preventDefault(); } else if ( isVertical && isVerticalEdge( target, isReverse ) ) { - const closestTabbable = getClosestTabbable( target, isReverse, container.current ); + const closestTabbable = getClosestTabbable( + target, + isReverse, + container.current + ); if ( closestTabbable ) { - placeCaretAtVerticalEdge( closestTabbable, isReverse, verticalRect.current ); + placeCaretAtVerticalEdge( + closestTabbable, + isReverse, + verticalRect.current + ); event.preventDefault(); } } else if ( @@ -481,7 +533,11 @@ export default function WritingFlow( { children } ) { getSelection().isCollapsed && isHorizontalEdge( target, isReverseDir ) ) { - const closestTabbable = getClosestTabbable( target, isReverseDir, container.current ); + const closestTabbable = getClosestTabbable( + target, + isReverseDir, + container.current + ); placeCaretAtHorizontalEdge( closestTabbable, isReverseDir ); event.preventDefault(); } @@ -518,11 +574,19 @@ export default function WritingFlow( { children } ) { hasMultiSelection={ hasMultiSelection } multiSelectionContainer={ multiSelectionContainer } /> -
        +
        { it( 'should return true if vertically navigating input without modifier', () => { [ UP, DOWN ].forEach( ( keyCode ) => { - const result = isNavigationCandidate( elements.input, keyCode, false ); + const result = isNavigationCandidate( + elements.input, + keyCode, + false + ); expect( result ).toBe( true ); } ); @@ -27,7 +31,11 @@ describe( 'isNavigationCandidate', () => { it( 'should return false if vertically navigating input with modifier', () => { [ UP, DOWN ].forEach( ( keyCode ) => { - const result = isNavigationCandidate( elements.input, keyCode, true ); + const result = isNavigationCandidate( + elements.input, + keyCode, + true + ); expect( result ).toBe( false ); } ); @@ -35,7 +43,11 @@ describe( 'isNavigationCandidate', () => { it( 'should return false if horizontally navigating input', () => { [ LEFT, RIGHT ].forEach( ( keyCode ) => { - const result = isNavigationCandidate( elements.input, keyCode, false ); + const result = isNavigationCandidate( + elements.input, + keyCode, + false + ); expect( result ).toBe( false ); } ); @@ -43,7 +55,11 @@ describe( 'isNavigationCandidate', () => { it( 'should return true if horizontally navigating non-input', () => { [ LEFT, RIGHT ].forEach( ( keyCode ) => { - const result = isNavigationCandidate( elements.contentEditable, keyCode, false ); + const result = isNavigationCandidate( + elements.contentEditable, + keyCode, + false + ); expect( result ).toBe( true ); } ); diff --git a/packages/block-editor/src/hooks/align.js b/packages/block-editor/src/hooks/align.js index cb74d4b99bbe44..cfded941725ecc 100644 --- a/packages/block-editor/src/hooks/align.js +++ b/packages/block-editor/src/hooks/align.js @@ -9,7 +9,11 @@ import { assign, get, has, includes, without } from 'lodash'; */ import { createHigherOrderComponent } from '@wordpress/compose'; import { addFilter } from '@wordpress/hooks'; -import { getBlockSupport, getBlockType, hasBlockSupport } from '@wordpress/blocks'; +import { + getBlockSupport, + getBlockType, + hasBlockSupport, +} from '@wordpress/blocks'; import { useSelect } from '@wordpress/data'; /** @@ -62,7 +66,10 @@ export function getValidAlignments( validAlignments = []; } - if ( ! hasWideEnabled || ( blockAlign === true && ! hasWideBlockSupport ) ) { + if ( + ! hasWideEnabled || + ( blockAlign === true && ! hasWideBlockSupport ) + ) { return without( validAlignments, ...WIDE_ALIGNMENTS ); } @@ -113,7 +120,11 @@ export const withToolbarControls = createHigherOrderComponent( const updateAlignment = ( nextAlign ) => { if ( ! nextAlign ) { const blockType = getBlockType( props.name ); - const blockDefaultAlign = get( blockType, [ 'attributes', 'align', 'default' ] ); + const blockDefaultAlign = get( blockType, [ + 'attributes', + 'align', + 'default', + ] ); if ( blockDefaultAlign ) { nextAlign = ''; } @@ -143,33 +154,36 @@ export const withToolbarControls = createHigherOrderComponent( * @param {Function} BlockListBlock Original component * @return {Function} Wrapped component */ -export const withDataAlign = createHigherOrderComponent( ( BlockListBlock ) => ( props ) => { - const { name, attributes } = props; - const { align } = attributes; - const hasWideEnabled = useSelect( - ( select ) => !! select( 'core/block-editor' ).getSettings().alignWide, - [] - ); +export const withDataAlign = createHigherOrderComponent( + ( BlockListBlock ) => ( props ) => { + const { name, attributes } = props; + const { align } = attributes; + const hasWideEnabled = useSelect( + ( select ) => + !! select( 'core/block-editor' ).getSettings().alignWide, + [] + ); - // If an alignment is not assigned, there's no need to go through the - // effort to validate or assign its value. - if ( align === undefined ) { - return ; - } + // If an alignment is not assigned, there's no need to go through the + // effort to validate or assign its value. + if ( align === undefined ) { + return ; + } - const validAlignments = getValidAlignments( - getBlockSupport( name, 'align' ), - hasBlockSupport( name, 'alignWide', true ), - hasWideEnabled - ); + const validAlignments = getValidAlignments( + getBlockSupport( name, 'align' ), + hasBlockSupport( name, 'alignWide', true ), + hasWideEnabled + ); - let wrapperProps = props.wrapperProps; - if ( includes( validAlignments, align ) ) { - wrapperProps = { ...wrapperProps, 'data-align': align }; - } + let wrapperProps = props.wrapperProps; + if ( includes( validAlignments, align ) ) { + wrapperProps = { ...wrapperProps, 'data-align': align }; + } - return ; -} ); + return ; + } +); /** * Override props assigned to save component to inject alignment class name if @@ -198,7 +212,23 @@ export function addAssignedAlign( props, blockType, attributes ) { return props; } -addFilter( 'blocks.registerBlockType', 'core/align/addAttribute', addAttribute ); -addFilter( 'editor.BlockListBlock', 'core/editor/align/with-data-align', withDataAlign ); -addFilter( 'editor.BlockEdit', 'core/editor/align/with-toolbar-controls', withToolbarControls ); -addFilter( 'blocks.getSaveContent.extraProps', 'core/align/addAssignedAlign', addAssignedAlign ); +addFilter( + 'blocks.registerBlockType', + 'core/align/addAttribute', + addAttribute +); +addFilter( + 'editor.BlockListBlock', + 'core/editor/align/with-data-align', + withDataAlign +); +addFilter( + 'editor.BlockEdit', + 'core/editor/align/with-toolbar-controls', + withToolbarControls +); +addFilter( + 'blocks.getSaveContent.extraProps', + 'core/align/addAssignedAlign', + addAssignedAlign +); diff --git a/packages/block-editor/src/hooks/anchor.js b/packages/block-editor/src/hooks/anchor.js index a9177646a84dee..f9aeab08ab95e9 100644 --- a/packages/block-editor/src/hooks/anchor.js +++ b/packages/block-editor/src/hooks/anchor.js @@ -60,45 +60,55 @@ export function addAttribute( settings ) { * * @return {WPComponent} Wrapped component. */ -export const withInspectorControl = createHigherOrderComponent( ( BlockEdit ) => { - return ( props ) => { - const hasAnchor = hasBlockSupport( props.name, 'anchor' ); +export const withInspectorControl = createHigherOrderComponent( + ( BlockEdit ) => { + return ( props ) => { + const hasAnchor = hasBlockSupport( props.name, 'anchor' ); - if ( hasAnchor && props.isSelected ) { - return ( - <> - - - - { __( - 'Enter a word or two โ€”ย without spaces โ€”ย to make a unique web address just for this heading, called an โ€œanchor.โ€ Then, youโ€™ll be able to link directly to this section of your page.' - ) } + if ( hasAnchor && props.isSelected ) { + return ( + <> + + + + { __( + 'Enter a word or two โ€”ย without spaces โ€”ย to make a unique web address just for this heading, called an โ€œanchor.โ€ Then, youโ€™ll be able to link directly to this section of your page.' + ) } - - { __( 'Learn more about anchors' ) } - - - } - value={ props.attributes.anchor || '' } - onChange={ ( nextValue ) => { - nextValue = nextValue.replace( ANCHOR_REGEX, '-' ); - props.setAttributes( { - anchor: nextValue, - } ); - } } - /> - - - ); - } + + { __( 'Learn more about anchors' ) } + + + } + value={ props.attributes.anchor || '' } + onChange={ ( nextValue ) => { + nextValue = nextValue.replace( + ANCHOR_REGEX, + '-' + ); + props.setAttributes( { + anchor: nextValue, + } ); + } } + /> + + + ); + } - return ; - }; -}, 'withInspectorControl' ); + return ; + }; + }, + 'withInspectorControl' +); /** * Override props assigned to save component to inject anchor ID, if block @@ -120,5 +130,13 @@ export function addSaveProps( extraProps, blockType, attributes ) { } addFilter( 'blocks.registerBlockType', 'core/anchor/attribute', addAttribute ); -addFilter( 'editor.BlockEdit', 'core/editor/anchor/with-inspector-control', withInspectorControl ); -addFilter( 'blocks.getSaveContent.extraProps', 'core/anchor/save-props', addSaveProps ); +addFilter( + 'editor.BlockEdit', + 'core/editor/anchor/with-inspector-control', + withInspectorControl +); +addFilter( + 'blocks.getSaveContent.extraProps', + 'core/anchor/save-props', + addSaveProps +); diff --git a/packages/block-editor/src/hooks/custom-class-name.js b/packages/block-editor/src/hooks/custom-class-name.js index 982e97f36af8b9..df461c178072d1 100644 --- a/packages/block-editor/src/hooks/custom-class-name.js +++ b/packages/block-editor/src/hooks/custom-class-name.js @@ -10,7 +10,11 @@ import classnames from 'classnames'; import { addFilter } from '@wordpress/hooks'; import { TextControl } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; -import { hasBlockSupport, parseWithAttributeSchema, getSaveContent } from '@wordpress/blocks'; +import { + hasBlockSupport, + parseWithAttributeSchema, + getSaveContent, +} from '@wordpress/blocks'; import { createHigherOrderComponent } from '@wordpress/compose'; /** @@ -47,32 +51,44 @@ export function addAttribute( settings ) { * * @return {WPComponent} Wrapped component. */ -export const withInspectorControl = createHigherOrderComponent( ( BlockEdit ) => { - return ( props ) => { - const hasCustomClassName = hasBlockSupport( props.name, 'customClassName', true ); - if ( hasCustomClassName && props.isSelected ) { - return ( - <> - - - { - props.setAttributes( { - className: nextValue !== '' ? nextValue : undefined, - } ); - } } - help={ __( 'Separate multiple classes with spaces.' ) } - /> - - +export const withInspectorControl = createHigherOrderComponent( + ( BlockEdit ) => { + return ( props ) => { + const hasCustomClassName = hasBlockSupport( + props.name, + 'customClassName', + true ); - } + if ( hasCustomClassName && props.isSelected ) { + return ( + <> + + + { + props.setAttributes( { + className: + nextValue !== '' + ? nextValue + : undefined, + } ); + } } + help={ __( + 'Separate multiple classes with spaces.' + ) } + /> + + + ); + } - return ; - }; -}, 'withInspectorControl' ); + return ; + }; + }, + 'withInspectorControl' +); /** * Override props assigned to save component to inject anchor ID, if block @@ -86,8 +102,14 @@ export const withInspectorControl = createHigherOrderComponent( ( BlockEdit ) => * @return {Object} Filtered props applied to save element. */ export function addSaveProps( extraProps, blockType, attributes ) { - if ( hasBlockSupport( blockType, 'customClassName', true ) && attributes.className ) { - extraProps.className = classnames( extraProps.className, attributes.className ); + if ( + hasBlockSupport( blockType, 'customClassName', true ) && + attributes.className + ) { + extraProps.className = classnames( + extraProps.className, + attributes.className + ); } return extraProps; @@ -132,7 +154,9 @@ export function addParsedDifference( blockAttributes, blockType, innerHTML ) { // attributes, with the exception of `className`. This will determine // the default set of classes. From there, any difference in innerHTML // can be considered as custom classes. - const attributesSansClassName = omit( blockAttributes, [ 'className' ] ); + const attributesSansClassName = omit( blockAttributes, [ + 'className', + ] ); const serialized = getSaveContent( blockType, attributesSansClassName ); const defaultClasses = getHTMLRootElementClasses( serialized ); const actualClasses = getHTMLRootElementClasses( innerHTML ); @@ -148,13 +172,21 @@ export function addParsedDifference( blockAttributes, blockType, innerHTML ) { return blockAttributes; } -addFilter( 'blocks.registerBlockType', 'core/custom-class-name/attribute', addAttribute ); +addFilter( + 'blocks.registerBlockType', + 'core/custom-class-name/attribute', + addAttribute +); addFilter( 'editor.BlockEdit', 'core/editor/custom-class-name/with-inspector-control', withInspectorControl ); -addFilter( 'blocks.getSaveContent.extraProps', 'core/custom-class-name/save-props', addSaveProps ); +addFilter( + 'blocks.getSaveContent.extraProps', + 'core/custom-class-name/save-props', + addSaveProps +); addFilter( 'blocks.getBlockAttributes', 'core/custom-class-name/addParsedDifference', diff --git a/packages/block-editor/src/hooks/custom-class-name.native.js b/packages/block-editor/src/hooks/custom-class-name.native.js index 6677ac95612935..4edfd96db65c28 100644 --- a/packages/block-editor/src/hooks/custom-class-name.native.js +++ b/packages/block-editor/src/hooks/custom-class-name.native.js @@ -8,7 +8,11 @@ import classnames from 'classnames'; * WordPress dependencies */ import { addFilter } from '@wordpress/hooks'; -import { hasBlockSupport, getSaveContent, parseWithAttributeSchema } from '@wordpress/blocks'; +import { + hasBlockSupport, + getSaveContent, + parseWithAttributeSchema, +} from '@wordpress/blocks'; /** * Filters registered block settings, extending attributes with anchor using ID @@ -43,8 +47,14 @@ export function addAttribute( settings ) { * @return {Object} Filtered props applied to save element. */ export function addSaveProps( extraProps, blockType, attributes ) { - if ( hasBlockSupport( blockType, 'customClassName', true ) && attributes.className ) { - extraProps.className = classnames( extraProps.className, attributes.className ); + if ( + hasBlockSupport( blockType, 'customClassName', true ) && + attributes.className + ) { + extraProps.className = classnames( + extraProps.className, + attributes.className + ); } return extraProps; @@ -93,9 +103,10 @@ export function addParsedDifference( blockAttributes, blockType, innerHTML ) { const parsedClasses = getHTMLRootElementClasses( innerHTML ); const customClasses = difference( parsedClasses, classes ); - const filteredClassName = compact( [ blockAttributes.className, ...customClasses ] ).join( - ' ' - ); + const filteredClassName = compact( [ + blockAttributes.className, + ...customClasses, + ] ).join( ' ' ); if ( filteredClassName ) { blockAttributes.className = filteredClassName; @@ -107,8 +118,16 @@ export function addParsedDifference( blockAttributes, blockType, innerHTML ) { return blockAttributes; } -addFilter( 'blocks.registerBlockType', 'core/custom-class-name/attribute', addAttribute ); -addFilter( 'blocks.getSaveContent.extraProps', 'core/custom-class-name/save-props', addSaveProps ); +addFilter( + 'blocks.registerBlockType', + 'core/custom-class-name/attribute', + addAttribute +); +addFilter( + 'blocks.getSaveContent.extraProps', + 'core/custom-class-name/save-props', + addSaveProps +); addFilter( 'blocks.getBlockAttributes', 'core/custom-class-name/addParsedDifference', diff --git a/packages/block-editor/src/hooks/test/align.js b/packages/block-editor/src/hooks/test/align.js index 05b0d4cfb32f0e..9242cff172eabb 100644 --- a/packages/block-editor/src/hooks/test/align.js +++ b/packages/block-editor/src/hooks/test/align.js @@ -8,13 +8,22 @@ import renderer, { act } from 'react-test-renderer'; * WordPress dependencies */ import { applyFilters } from '@wordpress/hooks'; -import { getBlockTypes, registerBlockType, unregisterBlockType } from '@wordpress/blocks'; +import { + getBlockTypes, + registerBlockType, + unregisterBlockType, +} from '@wordpress/blocks'; /** * Internal dependencies */ import BlockEditorProvider from '../../components/provider'; -import { getValidAlignments, withToolbarControls, withDataAlign, addAssignedAlign } from '../align'; +import { + getValidAlignments, + withToolbarControls, + withDataAlign, + addAssignedAlign, +} from '../align'; describe( 'align', () => { const blockSettings = { @@ -30,7 +39,10 @@ describe( 'align', () => { } ); describe( 'addAttribute()', () => { - const filterRegisterBlockType = applyFilters.bind( null, 'blocks.registerBlockType' ); + const filterRegisterBlockType = applyFilters.bind( + null, + 'blocks.registerBlockType' + ); it( 'should do nothing if the block settings does not define align support', () => { const settings = filterRegisterBlockType( blockSettings ); @@ -56,57 +68,93 @@ describe( 'align', () => { } ); it( 'should return all custom aligns set', () => { - expect( getValidAlignments( [ 'left', 'right' ] ) ).toEqual( [ 'left', 'right' ] ); + expect( getValidAlignments( [ 'left', 'right' ] ) ).toEqual( [ + 'left', + 'right', + ] ); } ); it( 'should return all aligns if block defines align support as true', () => { - expect( getValidAlignments( true ) ).toEqual( [ 'left', 'center', 'right', 'wide', 'full' ] ); + expect( getValidAlignments( true ) ).toEqual( [ + 'left', + 'center', + 'right', + 'wide', + 'full', + ] ); } ); it( 'should return all aligns except wide if wide align explicitly false on the block', () => { - expect( getValidAlignments( true, false, true ) ).toEqual( [ 'left', 'center', 'right' ] ); - - expect( getValidAlignments( true, false, false ) ).toEqual( [ 'left', 'center', 'right' ] ); - } ); - - it( 'should return all aligns except wide if wide align is not supported by the theme', () => { - expect( getValidAlignments( true, true, false ) ).toEqual( [ 'left', 'center', 'right' ] ); - - expect( getValidAlignments( true, false, false ) ).toEqual( [ 'left', 'center', 'right' ] ); - } ); + expect( getValidAlignments( true, false, true ) ).toEqual( [ + 'left', + 'center', + 'right', + ] ); - it( 'should not remove wide aligns if they are not supported by the block and were set using an array in supports align', () => { - expect( getValidAlignments( [ 'left', 'right', 'wide', 'full' ], false, true ) ).toEqual( [ + expect( getValidAlignments( true, false, false ) ).toEqual( [ 'left', + 'center', 'right', - 'wide', - 'full', ] ); } ); - it( 'should remove wide aligns if they are not supported by the theme and were set using an array in supports align', () => { - expect( getValidAlignments( [ 'left', 'right', 'wide', 'full' ], true, false ) ).toEqual( [ + it( 'should return all aligns except wide if wide align is not supported by the theme', () => { + expect( getValidAlignments( true, true, false ) ).toEqual( [ 'left', + 'center', 'right', ] ); - expect( getValidAlignments( [ 'left', 'right', 'wide', 'full' ], false, false ) ).toEqual( [ + expect( getValidAlignments( true, false, false ) ).toEqual( [ 'left', + 'center', 'right', ] ); } ); + + it( 'should not remove wide aligns if they are not supported by the block and were set using an array in supports align', () => { + expect( + getValidAlignments( + [ 'left', 'right', 'wide', 'full' ], + false, + true + ) + ).toEqual( [ 'left', 'right', 'wide', 'full' ] ); + } ); + + it( 'should remove wide aligns if they are not supported by the theme and were set using an array in supports align', () => { + expect( + getValidAlignments( + [ 'left', 'right', 'wide', 'full' ], + true, + false + ) + ).toEqual( [ 'left', 'right' ] ); + + expect( + getValidAlignments( + [ 'left', 'right', 'wide', 'full' ], + false, + false + ) + ).toEqual( [ 'left', 'right' ] ); + } ); } ); describe( 'withToolbarControls', () => { it( 'should do nothing if no valid alignments', () => { registerBlockType( 'core/foo', blockSettings ); - const EnhancedComponent = withToolbarControls( ( { wrapperProps } ) => ( -
        - ) ); + const EnhancedComponent = withToolbarControls( + ( { wrapperProps } ) =>
        + ); const wrapper = renderer.create( - + ); // when there's only one child, `rendered` in the tree is an object not an array. expect( wrapper.toTree().rendered ).toBeInstanceOf( Object ); @@ -121,12 +169,16 @@ describe( 'align', () => { }, } ); - const EnhancedComponent = withToolbarControls( ( { wrapperProps } ) => ( -
        - ) ); + const EnhancedComponent = withToolbarControls( + ( { wrapperProps } ) =>
        + ); const wrapper = renderer.create( - + ); expect( wrapper.toTree().rendered ).toHaveLength( 2 ); } ); @@ -149,7 +201,10 @@ describe( 'align', () => { let wrapper; act( () => { wrapper = renderer.create( - + { let wrapper; act( () => { wrapper = renderer.create( - + { let wrapper; act( () => { wrapper = renderer.create( - + { }; describe( 'addAttribute()', () => { - const registerBlockType = applyFilters.bind( null, 'blocks.registerBlockType' ); + const registerBlockType = applyFilters.bind( + null, + 'blocks.registerBlockType' + ); it( 'should do nothing if the block settings do not define anchor support', () => { const settings = registerBlockType( blockSettings ); @@ -54,16 +57,26 @@ describe( 'anchor', () => { }, } ); - expect( settings.attributes.anchor ).toEqual( { type: 'string', default: 'testAnchor' } ); + expect( settings.attributes.anchor ).toEqual( { + type: 'string', + default: 'testAnchor', + } ); } ); } ); describe( 'addSaveProps', () => { - const getSaveContentExtraProps = applyFilters.bind( null, 'blocks.getSaveContent.extraProps' ); + const getSaveContentExtraProps = applyFilters.bind( + null, + 'blocks.getSaveContent.extraProps' + ); it( 'should do nothing if the block settings do not define anchor support', () => { const attributes = { anchor: 'foo' }; - const extraProps = getSaveContentExtraProps( {}, blockSettings, attributes ); + const extraProps = getSaveContentExtraProps( + {}, + blockSettings, + attributes + ); expect( extraProps ).not.toHaveProperty( 'id' ); } ); diff --git a/packages/block-editor/src/hooks/test/custom-class-name.js b/packages/block-editor/src/hooks/test/custom-class-name.js index b00b634efd5b76..8429a657859bde 100644 --- a/packages/block-editor/src/hooks/test/custom-class-name.js +++ b/packages/block-editor/src/hooks/test/custom-class-name.js @@ -22,7 +22,10 @@ describe( 'custom className', () => { }; describe( 'addAttribute()', () => { - const addAttribute = applyFilters.bind( null, 'blocks.registerBlockType' ); + const addAttribute = applyFilters.bind( + null, + 'blocks.registerBlockType' + ); it( 'should do nothing if the block settings disable custom className support', () => { const settings = addAttribute( { @@ -43,7 +46,10 @@ describe( 'custom className', () => { } ); describe( 'addSaveProps', () => { - const addSaveProps = applyFilters.bind( null, 'blocks.getSaveContent.extraProps' ); + const addSaveProps = applyFilters.bind( + null, + 'blocks.getSaveContent.extraProps' + ); it( 'should do nothing if the block settings do not define custom className support', () => { const attributes = { className: 'foo' }; @@ -63,7 +69,11 @@ describe( 'custom className', () => { it( 'should inject the custom className', () => { const attributes = { className: 'bar' }; - const extraProps = addSaveProps( { className: 'foo' }, blockSettings, attributes ); + const extraProps = addSaveProps( + { className: 'foo' }, + blockSettings, + attributes + ); expect( extraProps.className ).toBe( 'foo bar' ); } ); @@ -77,14 +87,19 @@ describe( 'custom className', () => { } ); it( 'return an array of parsed classes from inner HTML', () => { - const classes = getHTMLRootElementClasses( '
        ' ); + const classes = getHTMLRootElementClasses( + '
        ' + ); expect( classes ).toEqual( [ 'foo', 'bar' ] ); } ); } ); describe( 'addParsedDifference', () => { - const addParsedDifference = applyFilters.bind( null, 'blocks.getBlockAttributes' ); + const addParsedDifference = applyFilters.bind( + null, + 'blocks.getBlockAttributes' + ); it( 'should do nothing if the block settings do not define custom className support', () => { const attributes = addParsedDifference( @@ -112,7 +127,11 @@ describe( 'custom className', () => { } ); it( 'should assign as undefined if there are no classes', () => { - const attributes = addParsedDifference( {}, blockSettings, '
        ' ); + const attributes = addParsedDifference( + {}, + blockSettings, + '
        ' + ); expect( attributes.className ).toBeUndefined(); } ); @@ -138,7 +157,11 @@ describe( 'custom className', () => { } ); it( 'should remove the custom class from an element originally without a class', () => { - const attributes = addParsedDifference( { className: 'foo' }, blockSettings, '
        ' ); + const attributes = addParsedDifference( + { className: 'foo' }, + blockSettings, + '
        ' + ); expect( attributes.className ).toBeUndefined(); } ); diff --git a/packages/block-editor/src/hooks/test/generated-class-name.js b/packages/block-editor/src/hooks/test/generated-class-name.js index f06a1fcd1b6dd1..1bf447c48ce12c 100644 --- a/packages/block-editor/src/hooks/test/generated-class-name.js +++ b/packages/block-editor/src/hooks/test/generated-class-name.js @@ -22,7 +22,10 @@ describe( 'generated className', () => { }; describe( 'addSaveProps', () => { - const addSaveProps = applyFilters.bind( null, 'blocks.getSaveContent.extraProps' ); + const addSaveProps = applyFilters.bind( + null, + 'blocks.getSaveContent.extraProps' + ); it( 'should do nothing if the block settings do not define generated className support', () => { const attributes = { className: 'foo' }; @@ -42,7 +45,11 @@ describe( 'generated className', () => { it( 'should inject the generated className', () => { const attributes = { className: 'bar' }; - const extraProps = addSaveProps( { className: 'foo' }, blockSettings, attributes ); + const extraProps = addSaveProps( + { className: 'foo' }, + blockSettings, + attributes + ); expect( extraProps.className ).toBe( 'wp-block-chicken-ribs foo' ); } ); diff --git a/packages/block-editor/src/store/actions.js b/packages/block-editor/src/store/actions.js index 3c4f017912076b..a9162f4b6d7728 100644 --- a/packages/block-editor/src/store/actions.js +++ b/packages/block-editor/src/store/actions.js @@ -6,7 +6,12 @@ import { castArray, first, get, includes, last, some } from 'lodash'; /** * WordPress dependencies */ -import { getDefaultBlockName, createBlock, hasBlockSupport, cloneBlock } from '@wordpress/blocks'; +import { + getDefaultBlockName, + createBlock, + hasBlockSupport, + cloneBlock, +} from '@wordpress/blocks'; import { speak } from '@wordpress/a11y'; import { __ } from '@wordpress/i18n'; @@ -170,7 +175,11 @@ export function* selectPreviousBlock( clientId ) { * @param {string} clientId Block client ID. */ export function* selectNextBlock( clientId ) { - const nextBlockClientId = yield select( 'core/block-editor', 'getNextBlockClientId', clientId ); + const nextBlockClientId = yield select( + 'core/block-editor', + 'getNextBlockClientId', + clientId + ); if ( nextBlockClientId ) { yield selectBlock( nextBlockClientId ); @@ -262,7 +271,8 @@ function getBlocksWithDefaultStylesApplied( blocks, blockEditorSettings ) { ...block, attributes: { ...attributes, - className: `${ className || '' } is-style-${ blockStyle }`.trim(), + className: `${ className || + '' } is-style-${ blockStyle }`.trim(), }, }; } ); @@ -364,7 +374,11 @@ export function* moveBlockToPosition( toRootClientId = '', index ) { - const templateLock = yield select( 'core/block-editor', 'getTemplateLock', fromRootClientId ); + const templateLock = yield select( + 'core/block-editor', + 'getTemplateLock', + fromRootClientId + ); // If locking is equal to all on the original clientId (fromRootClientId), // it is not possible to move the block to any other position. @@ -391,7 +405,11 @@ export function* moveBlockToPosition( return; } - const blockName = yield select( 'core/block-editor', 'getBlockName', clientId ); + const blockName = yield select( + 'core/block-editor', + 'getBlockName', + clientId + ); const canInsertBlock = yield select( 'core/block-editor', @@ -417,7 +435,12 @@ export function* moveBlockToPosition( * * @return {Object} Action object. */ -export function insertBlock( block, index, rootClientId, updateSelection = true ) { +export function insertBlock( + block, + index, + rootClientId, + updateSelection = true +) { return insertBlocks( [ block ], index, rootClientId, updateSelection ); } @@ -432,7 +455,12 @@ export function insertBlock( block, index, rootClientId, updateSelection = true * * @return {Object} Action object. */ -export function* insertBlocks( blocks, index, rootClientId, updateSelection = true ) { +export function* insertBlocks( + blocks, + index, + rootClientId, + updateSelection = true +) { blocks = getBlocksWithDefaultStylesApplied( castArray( blocks ), yield select( 'core/block-editor', 'getSettings' ) @@ -544,8 +572,16 @@ export function* removeBlocks( clientIds, selectPrevious = true ) { } clientIds = castArray( clientIds ); - const rootClientId = yield select( 'core/block-editor', 'getBlockRootClientId', clientIds[ 0 ] ); - const isLocked = yield select( 'core/block-editor', 'getTemplateLock', rootClientId ); + const rootClientId = yield select( + 'core/block-editor', + 'getBlockRootClientId', + clientIds[ 0 ] + ); + const isLocked = yield select( + 'core/block-editor', + 'getTemplateLock', + rootClientId + ); if ( isLocked ) { return; } @@ -588,7 +624,11 @@ export function removeBlock( clientId, selectPrevious ) { * * @return {Object} Action object. */ -export function replaceInnerBlocks( rootClientId, blocks, updateSelection = true ) { +export function replaceInnerBlocks( + rootClientId, + blocks, + updateSelection = true +) { return { type: 'REPLACE_INNER_BLOCKS', rootClientId, @@ -690,7 +730,12 @@ export function exitFormattedText() { * * @return {Object} Action object. */ -export function selectionChange( clientId, attributeKey, startOffset, endOffset ) { +export function selectionChange( + clientId, + attributeKey, + startOffset, + endOffset +) { return { type: 'SELECTION_CHANGE', clientId, @@ -822,7 +867,9 @@ export function* setNavigationMode( isNavigationMode = true ) { ); } else { speak( - __( 'You are currently in edit mode. To return to the navigation mode, press Escape.' ) + __( + 'You are currently in edit mode. To return to the navigation mode, press Escape.' + ) ); } } @@ -836,15 +883,28 @@ export function* duplicateBlocks( clientIds ) { if ( ! clientIds && ! clientIds.length ) { return; } - const blocks = yield select( 'core/block-editor', 'getBlocksByClientId', clientIds ); - const rootClientId = yield select( 'core/block-editor', 'getBlockRootClientId', clientIds[ 0 ] ); + const blocks = yield select( + 'core/block-editor', + 'getBlocksByClientId', + clientIds + ); + const rootClientId = yield select( + 'core/block-editor', + 'getBlockRootClientId', + clientIds[ 0 ] + ); // Return early if blocks don't exist. if ( some( blocks, ( block ) => ! block ) ) { return; } const blockNames = blocks.map( ( block ) => block.name ); // Return early if blocks don't support multipe usage. - if ( some( blockNames, ( blockName ) => ! hasBlockSupport( blockName, 'multiple', true ) ) ) { + if ( + some( + blockNames, + ( blockName ) => ! hasBlockSupport( blockName, 'multiple', true ) + ) + ) { return; } @@ -857,7 +917,10 @@ export function* duplicateBlocks( clientIds ) { const clonedBlocks = blocks.map( ( block ) => cloneBlock( block ) ); yield insertBlocks( clonedBlocks, lastSelectedIndex + 1, rootClientId ); if ( clonedBlocks.length > 1 ) { - yield multiSelect( first( clonedBlocks ).clientId, last( clonedBlocks ).clientId ); + yield multiSelect( + first( clonedBlocks ).clientId, + last( clonedBlocks ).clientId + ); } } @@ -870,8 +933,16 @@ export function* insertBeforeBlock( clientId ) { if ( ! clientId ) { return; } - const rootClientId = yield select( 'core/block-editor', 'getBlockRootClientId', clientId ); - const isLocked = yield select( 'core/block-editor', 'getTemplateLock', rootClientId ); + const rootClientId = yield select( + 'core/block-editor', + 'getBlockRootClientId', + clientId + ); + const isLocked = yield select( + 'core/block-editor', + 'getTemplateLock', + rootClientId + ); if ( isLocked ) { return; } @@ -894,8 +965,16 @@ export function* insertAfterBlock( clientId ) { if ( ! clientId ) { return; } - const rootClientId = yield select( 'core/block-editor', 'getBlockRootClientId', clientId ); - const isLocked = yield select( 'core/block-editor', 'getTemplateLock', rootClientId ); + const rootClientId = yield select( + 'core/block-editor', + 'getBlockRootClientId', + clientId + ); + const isLocked = yield select( + 'core/block-editor', + 'getTemplateLock', + rootClientId + ); if ( isLocked ) { return; } diff --git a/packages/block-editor/src/store/array.js b/packages/block-editor/src/store/array.js index e2a9f7f8c7d07c..3a2977eb152aec 100644 --- a/packages/block-editor/src/store/array.js +++ b/packages/block-editor/src/store/array.js @@ -13,7 +13,11 @@ import { castArray } from 'lodash'; * @return {Array} Result. */ export function insertAt( array, elements, index ) { - return [ ...array.slice( 0, index ), ...castArray( elements ), ...array.slice( index ) ]; + return [ + ...array.slice( 0, index ), + ...castArray( elements ), + ...array.slice( index ), + ]; } /** @@ -29,5 +33,9 @@ export function insertAt( array, elements, index ) { export function moveTo( array, from, to, count = 1 ) { const withoutMovedElements = [ ...array ]; withoutMovedElements.splice( from, count ); - return insertAt( withoutMovedElements, array.slice( from, from + count ), to ); + return insertAt( + withoutMovedElements, + array.slice( from, from + count ), + to + ); } diff --git a/packages/block-editor/src/store/controls.js b/packages/block-editor/src/store/controls.js index 5012ab244c21c8..3a64e045f69666 100644 --- a/packages/block-editor/src/store/controls.js +++ b/packages/block-editor/src/store/controls.js @@ -22,9 +22,11 @@ export function select( storeName, selectorName, ...args ) { } const controls = { - SELECT: createRegistryControl( ( registry ) => ( { storeName, selectorName, args } ) => { - return registry.select( storeName )[ selectorName ]( ...args ); - } ), + SELECT: createRegistryControl( + ( registry ) => ( { storeName, selectorName, args } ) => { + return registry.select( storeName )[ selectorName ]( ...args ); + } + ), }; export default controls; diff --git a/packages/block-editor/src/store/defaults.js b/packages/block-editor/src/store/defaults.js index c2d98c889d542e..a0ab78569c5083 100644 --- a/packages/block-editor/src/store/defaults.js +++ b/packages/block-editor/src/store/defaults.js @@ -157,27 +157,32 @@ export const SETTINGS_DEFAULTS = { gradients: [ { name: __( 'Vivid cyan blue to vivid purple' ), - gradient: 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)', + gradient: + 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)', slug: 'vivid-cyan-blue-to-vivid-purple', }, { name: __( 'Light green cyan to vivid green cyan' ), - gradient: 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', + gradient: + 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)', slug: 'light-green-cyan-to-vivid-green-cyan', }, { name: __( 'Luminous vivid amber to luminous vivid orange' ), - gradient: 'linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)', + gradient: + 'linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)', slug: 'luminous-vivid-amber-to-luminous-vivid-orange', }, { name: __( 'Luminous vivid orange to vivid red' ), - gradient: 'linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)', + gradient: + 'linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)', slug: 'luminous-vivid-orange-to-vivid-red', }, { name: __( 'Very light gray to cyan bluish gray' ), - gradient: 'linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%)', + gradient: + 'linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%)', slug: 'very-light-gray-to-cyan-bluish-gray', }, { @@ -188,12 +193,14 @@ export const SETTINGS_DEFAULTS = { }, { name: __( 'Blush light purple' ), - gradient: 'linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%)', + gradient: + 'linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%)', slug: 'blush-light-purple', }, { name: __( 'Blush bordeaux' ), - gradient: 'linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%)', + gradient: + 'linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%)', slug: 'blush-bordeaux', }, { @@ -210,12 +217,14 @@ export const SETTINGS_DEFAULTS = { }, { name: __( 'Electric grass' ), - gradient: 'linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%)', + gradient: + 'linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%)', slug: 'electric-grass', }, { name: __( 'Midnight' ), - gradient: 'linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%)', + gradient: + 'linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%)', slug: 'midnight', }, ], diff --git a/packages/block-editor/src/store/effects.js b/packages/block-editor/src/store/effects.js index 4e2ce7d2b17835..b01e37b1e76dd8 100644 --- a/packages/block-editor/src/store/effects.js +++ b/packages/block-editor/src/store/effects.js @@ -56,7 +56,9 @@ export function validateBlocksToTemplate( action, store ) { // Unlocked templates are considered always valid because they act // as default values only. const isBlocksValidToTemplate = - ! template || templateLock !== 'all' || doBlocksMatchTemplate( action.blocks, template ); + ! template || + templateLock !== 'all' || + doBlocksMatchTemplate( action.blocks, template ); // Update if validity has changed. if ( isBlocksValidToTemplate !== isValidTemplate( state ) ) { @@ -81,8 +83,10 @@ export default { const blockB = getBlock( state, clientIdB ); const blockBType = getBlockType( blockB.name ); const { clientId, attributeKey, offset } = getSelectionStart( state ); - const selectedBlockType = clientId === clientIdA ? blockAType : blockBType; - const attributeDefinition = selectedBlockType.attributes[ attributeKey ]; + const selectedBlockType = + clientId === clientIdA ? blockAType : blockBType; + const attributeDefinition = + selectedBlockType.attributes[ attributeKey ]; const canRestoreTextSelection = ( clientId === clientIdA || clientId === clientIdB ) && attributeKey !== undefined && @@ -143,7 +147,9 @@ export default { // We can only merge blocks with similar types // thus, we transform the block to merge first const blocksWithTheSameType = - blockA.name === blockB.name ? [ cloneB ] : switchToBlockType( cloneB, blockA.name ); + blockA.name === blockB.name + ? [ cloneB ] + : switchToBlockType( cloneB, blockA.name ); // If the block types can not match, do nothing if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) { @@ -159,7 +165,9 @@ export default { if ( canRestoreTextSelection ) { const newAttributeKey = findKey( updatedAttributes, - ( v ) => typeof v === 'string' && v.indexOf( START_OF_SELECTED_AREA ) !== -1 + ( v ) => + typeof v === 'string' && + v.indexOf( START_OF_SELECTED_AREA ) !== -1 ); const convertedHtml = updatedAttributes[ newAttributeKey ]; const { @@ -173,7 +181,9 @@ export default { multilineWrapperTags, preserveWhiteSpace, } ); - const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA ); + const newOffset = convertedValue.text.indexOf( + START_OF_SELECTED_AREA + ); const newValue = remove( convertedValue, newOffset, newOffset + 1 ); const newHtml = toHTMLString( { value: newValue, @@ -183,7 +193,14 @@ export default { updatedAttributes[ newAttributeKey ] = newHtml; - dispatch( selectionChange( blockA.clientId, newAttributeKey, newOffset, newOffset ) ); + dispatch( + selectionChange( + blockA.clientId, + newAttributeKey, + newOffset, + newOffset + ) + ); } dispatch( @@ -208,7 +225,10 @@ export default { /* translators: %s: number of selected blocks */ speak( - sprintf( _n( '%s block selected.', '%s blocks selected.', blockCount ), blockCount ), + sprintf( + _n( '%s block selected.', '%s blocks selected.', blockCount ), + blockCount + ), 'assertive' ); }, @@ -216,7 +236,10 @@ export default { const state = getState(); const blocks = getBlocks( state ); const template = getTemplate( state ); - const updatedBlockList = synchronizeBlocksWithTemplate( blocks, template ); + const updatedBlockList = synchronizeBlocksWithTemplate( + blocks, + template + ); return resetBlocks( updatedBlockList ); }, diff --git a/packages/block-editor/src/store/reducer.js b/packages/block-editor/src/store/reducer.js index 16ca9cd6cd16c7..45a5dc63cea04d 100644 --- a/packages/block-editor/src/store/reducer.js +++ b/packages/block-editor/src/store/reducer.js @@ -254,7 +254,10 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { switch ( action.type ) { case 'RESET_BLOCKS': - newState.cache = mapValues( flattenBlocks( action.blocks ), () => ( {} ) ); + newState.cache = mapValues( + flattenBlocks( action.blocks ), + () => ( {} ) + ); break; case 'RECEIVE_BLOCKS': case 'INSERT_BLOCKS': { @@ -264,7 +267,9 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { } newState.cache = { ...newState.cache, - ...fillKeysWithEmptyObject( getBlocksWithParentsClientIds( updatedBlockUids ) ), + ...fillKeysWithEmptyObject( + getBlocksWithParentsClientIds( updatedBlockUids ) + ), }; break; } @@ -272,7 +277,9 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { case 'UPDATE_BLOCK_ATTRIBUTES': newState.cache = { ...newState.cache, - ...fillKeysWithEmptyObject( getBlocksWithParentsClientIds( [ action.clientId ] ) ), + ...fillKeysWithEmptyObject( + getBlocksWithParentsClientIds( [ action.clientId ] ) + ), }; break; case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': @@ -283,14 +290,19 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { newState.cache = { ...omit( newState.cache, action.replacedClientIds ), ...omit( parentClientIds, action.replacedClientIds ), - ...fillKeysWithEmptyObject( keys( flattenBlocks( action.blocks ) ) ), + ...fillKeysWithEmptyObject( + keys( flattenBlocks( action.blocks ) ) + ), }; break; case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': newState.cache = { ...omit( newState.cache, action.removedClientIds ), ...fillKeysWithEmptyObject( - difference( getBlocksWithParentsClientIds( action.clientIds ), action.clientIds ) + difference( + getBlocksWithParentsClientIds( action.clientIds ), + action.clientIds + ) ), }; break; @@ -304,7 +316,9 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { } newState.cache = { ...newState.cache, - ...fillKeysWithEmptyObject( getBlocksWithParentsClientIds( updatedBlockUids ) ), + ...fillKeysWithEmptyObject( + getBlocksWithParentsClientIds( updatedBlockUids ) + ), }; break; } @@ -316,7 +330,9 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { } newState.cache = { ...newState.cache, - ...fillKeysWithEmptyObject( getBlocksWithParentsClientIds( updatedBlockUids ) ), + ...fillKeysWithEmptyObject( + getBlocksWithParentsClientIds( updatedBlockUids ) + ), }; break; } @@ -332,7 +348,9 @@ const withBlockCache = ( reducer ) => ( state = {}, action ) => { newState.cache = { ...newState.cache, - ...fillKeysWithEmptyObject( getBlocksWithParentsClientIds( updatedBlockUids ) ), + ...fillKeysWithEmptyObject( + getBlocksWithParentsClientIds( updatedBlockUids ) + ), }; } } @@ -358,14 +376,20 @@ function withPersistentBlockChange( reducer ) { let nextState = reducer( state, action ); const isExplicitPersistentChange = - action.type === 'MARK_LAST_CHANGE_AS_PERSISTENT' || markNextChangeAsNotPersistent; + action.type === 'MARK_LAST_CHANGE_AS_PERSISTENT' || + markNextChangeAsNotPersistent; // Defer to previous state value (or default) unless changing or // explicitly marking as persistent. if ( state === nextState && ! isExplicitPersistentChange ) { - markNextChangeAsNotPersistent = action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT'; + markNextChangeAsNotPersistent = + action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT'; - const nextIsPersistentChange = get( state, [ 'isPersistentChange' ], true ); + const nextIsPersistentChange = get( + state, + [ 'isPersistentChange' ], + true + ); if ( state.isPersistentChange === nextIsPersistentChange ) { return state; } @@ -387,7 +411,8 @@ function withPersistentBlockChange( reducer ) { // would have qualified as one which would have been ignored or not // have resulted in a changed state. lastAction = action; - markNextChangeAsNotPersistent = action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT'; + markNextChangeAsNotPersistent = + action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT'; return nextState; }; @@ -563,17 +588,20 @@ const withSaveReusableBlock = ( reducer ) => ( state, action ) => { state = { ...state }; - state.attributes = mapValues( state.attributes, ( attributes, clientId ) => { - const { name } = state.byClientId[ clientId ]; - if ( name === 'core/block' && attributes.ref === id ) { - return { - ...attributes, - ref: updatedId, - }; - } + state.attributes = mapValues( + state.attributes, + ( attributes, clientId ) => { + const { name } = state.byClientId[ clientId ]; + if ( name === 'core/block' && attributes.ref === id ) { + return { + ...attributes, + ref: updatedId, + }; + } - return attributes; - } ); + return attributes; + } + ); } return reducer( state, action ); @@ -660,7 +688,10 @@ export const blocks = flow( case 'UPDATE_BLOCK': // Ignore updates if block isn't known or there are no attribute changes. - if ( ! state[ action.clientId ] || ! action.updates.attributes ) { + if ( + ! state[ action.clientId ] || + ! action.updates.attributes + ) { return state; } @@ -683,7 +714,10 @@ export const blocks = flow( action.attributes, ( result, value, key ) => { if ( value !== result[ key ] ) { - result = getMutateSafeObject( state[ action.clientId ], result ); + result = getMutateSafeObject( + state[ action.clientId ], + result + ); result[ key ] = value; } @@ -735,18 +769,29 @@ export const blocks = flow( case 'INSERT_BLOCKS': { const { rootClientId = '' } = action; const subState = state[ rootClientId ] || []; - const mappedBlocks = mapBlockOrder( action.blocks, rootClientId ); + const mappedBlocks = mapBlockOrder( + action.blocks, + rootClientId + ); const { index = subState.length } = action; return { ...state, ...mappedBlocks, - [ rootClientId ]: insertAt( subState, mappedBlocks[ rootClientId ], index ), + [ rootClientId ]: insertAt( + subState, + mappedBlocks[ rootClientId ], + index + ), }; } case 'MOVE_BLOCK_TO_POSITION': { - const { fromRootClientId = '', toRootClientId = '', clientId } = action; + const { + fromRootClientId = '', + toRootClientId = '', + clientId, + } = action; const { index = state[ toRootClientId ].length } = action; // Moving inside the same parent block @@ -755,15 +800,26 @@ export const blocks = flow( const fromIndex = subState.indexOf( clientId ); return { ...state, - [ toRootClientId ]: moveTo( state[ toRootClientId ], fromIndex, index ), + [ toRootClientId ]: moveTo( + state[ toRootClientId ], + fromIndex, + index + ), }; } // Moving from a parent block to another return { ...state, - [ fromRootClientId ]: without( state[ fromRootClientId ], clientId ), - [ toRootClientId ]: insertAt( state[ toRootClientId ], clientId, index ), + [ fromRootClientId ]: without( + state[ fromRootClientId ], + clientId + ), + [ toRootClientId ]: insertAt( + state[ toRootClientId ], + clientId, + index + ), }; } @@ -772,7 +828,10 @@ export const blocks = flow( const firstClientId = first( clientIds ); const subState = state[ rootClientId ]; - if ( ! subState.length || firstClientId === first( subState ) ) { + if ( + ! subState.length || + firstClientId === first( subState ) + ) { return state; } @@ -780,7 +839,12 @@ export const blocks = flow( return { ...state, - [ rootClientId ]: moveTo( subState, firstIndex, firstIndex - 1, clientIds.length ), + [ rootClientId ]: moveTo( + subState, + firstIndex, + firstIndex - 1, + clientIds.length + ), }; } @@ -798,7 +862,12 @@ export const blocks = flow( return { ...state, - [ rootClientId ]: moveTo( subState, firstIndex, firstIndex + 1, clientIds.length ), + [ rootClientId ]: moveTo( + subState, + firstIndex, + firstIndex + 1, + clientIds.length + ), }; } @@ -811,7 +880,8 @@ export const blocks = flow( const mappedBlocks = mapBlockOrder( action.blocks ); return flow( [ - ( nextState ) => omit( nextState, action.replacedClientIds ), + ( nextState ) => + omit( nextState, action.replacedClientIds ), ( nextState ) => ( { ...nextState, ...omit( mappedBlocks, '' ), @@ -822,10 +892,15 @@ export const blocks = flow( subState, ( result, clientId ) => { if ( clientId === clientIds[ 0 ] ) { - return [ ...result, ...mappedBlocks[ '' ] ]; + return [ + ...result, + ...mappedBlocks[ '' ], + ]; } - if ( clientIds.indexOf( clientId ) === -1 ) { + if ( + clientIds.indexOf( clientId ) === -1 + ) { result.push( clientId ); } @@ -844,7 +919,9 @@ export const blocks = flow( // Remove deleted blocks from other blocks' orderings ( nextState ) => - mapValues( nextState, ( subState ) => without( subState, ...action.removedClientIds ) ), + mapValues( nextState, ( subState ) => + without( subState, ...action.removedClientIds ) + ), ] )( state ); } @@ -867,7 +944,10 @@ export const blocks = flow( case 'INSERT_BLOCKS': return { ...state, - ...mapBlockParents( action.blocks, action.rootClientId || '' ), + ...mapBlockParents( + action.blocks, + action.rootClientId || '' + ), }; case 'MOVE_BLOCK_TO_POSITION': { @@ -880,7 +960,10 @@ export const blocks = flow( case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': return { ...omit( state, action.replacedClientIds ), - ...mapBlockParents( action.blocks, state[ action.clientIds[ 0 ] ] ), + ...mapBlockParents( + action.blocks, + state[ action.clientIds[ 0 ] ] + ), }; case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': @@ -998,7 +1081,8 @@ function selection( state = {}, action ) { return state; } - const indexToSelect = action.indexToSelect || action.blocks.length - 1; + const indexToSelect = + action.indexToSelect || action.blocks.length - 1; const blockToSelect = action.blocks[ indexToSelect ]; if ( ! blockToSelect ) { @@ -1130,7 +1214,10 @@ export function blocksMode( state = {}, action ) { const { clientId } = action; return { ...state, - [ clientId ]: state[ clientId ] && state[ clientId ] === 'html' ? 'visual' : 'html', + [ clientId ]: + state[ clientId ] && state[ clientId ] === 'html' + ? 'visual' + : 'html', }; } @@ -1226,7 +1313,9 @@ export function preferences( state = PREFERENCES_DEFAULTS, action ) { ...prevState.insertUsage, [ id ]: { time: action.time, - count: prevState.insertUsage[ id ] ? prevState.insertUsage[ id ].count + 1 : 1, + count: prevState.insertUsage[ id ] + ? prevState.insertUsage[ id ].count + 1 + : 1, insert, }, }, diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js index fda8b2a117578e..5b64c3955f7b85 100644 --- a/packages/block-editor/src/store/selectors.js +++ b/packages/block-editor/src/store/selectors.js @@ -22,7 +22,12 @@ import createSelector from 'rememo'; /** * WordPress dependencies */ -import { getBlockType, getBlockTypes, hasBlockSupport, parse } from '@wordpress/blocks'; +import { + getBlockType, + getBlockTypes, + hasBlockSupport, + parse, +} from '@wordpress/blocks'; import { SVG, Rect, G, Path } from '@wordpress/components'; /** @@ -192,9 +197,15 @@ export const __unstableGetBlockWithoutInnerBlocks = createSelector( */ export const getBlocks = createSelector( ( state, rootClientId ) => { - return map( getBlockOrder( state, rootClientId ), ( clientId ) => getBlock( state, clientId ) ); + return map( getBlockOrder( state, rootClientId ), ( clientId ) => + getBlock( state, clientId ) + ); }, - ( state ) => [ state.blocks.byClientId, state.blocks.order, state.blocks.attributes ] + ( state ) => [ + state.blocks.byClientId, + state.blocks.order, + state.blocks.attributes, + ] ); /** @@ -209,7 +220,10 @@ export const getBlocks = createSelector( export const getClientIdsOfDescendants = ( state, clientIds ) => flatMap( clientIds, ( clientId ) => { const descendants = getBlockOrder( state, clientId ); - return [ ...descendants, ...getClientIdsOfDescendants( state, descendants ) ]; + return [ + ...descendants, + ...getClientIdsOfDescendants( state, descendants ), + ]; } ); /** @@ -223,7 +237,10 @@ export const getClientIdsOfDescendants = ( state, clientIds ) => export const getClientIdsWithDescendants = createSelector( ( state ) => { const topLevelIds = getBlockOrder( state ); - return [ ...topLevelIds, ...getClientIdsOfDescendants( state, topLevelIds ) ]; + return [ + ...topLevelIds, + ...getClientIdsOfDescendants( state, topLevelIds ), + ]; }, ( state ) => [ state.blocks.order ] ); @@ -266,8 +283,14 @@ export const getGlobalBlockCount = createSelector( */ export const getBlocksByClientId = createSelector( ( state, clientIds ) => - map( castArray( clientIds ), ( clientId ) => getBlock( state, clientId ) ), - ( state ) => [ state.blocks.byClientId, state.blocks.order, state.blocks.attributes ] + map( castArray( clientIds ), ( clientId ) => + getBlock( state, clientId ) + ), + ( state ) => [ + state.blocks.byClientId, + state.blocks.order, + state.blocks.attributes, + ] ); /** @@ -340,7 +363,8 @@ export function getBlockSelectionEnd( state ) { * @return {number} Number of blocks selected in the post. */ export function getSelectedBlockCount( state ) { - const multiSelectedBlockCount = getMultiSelectedBlockClientIds( state ).length; + const multiSelectedBlockCount = getMultiSelectedBlockClientIds( state ) + .length; if ( multiSelectedBlockCount ) { return multiSelectedBlockCount; @@ -358,7 +382,10 @@ export function getSelectedBlockCount( state ) { */ export function hasSelectedBlock( state ) { const { selectionStart, selectionEnd } = state; - return !! selectionStart.clientId && selectionStart.clientId === selectionEnd.clientId; + return ( + !! selectionStart.clientId && + selectionStart.clientId === selectionEnd.clientId + ); } /** @@ -403,7 +430,9 @@ export function getSelectedBlock( state ) { * @return {?string} Root client ID, if exists */ export function getBlockRootClientId( state, clientId ) { - return state.blocks.parents[ clientId ] !== undefined ? state.blocks.parents[ clientId ] : null; + return state.blocks.parents[ clientId ] !== undefined + ? state.blocks.parents[ clientId ] + : null; } /** @@ -458,7 +487,10 @@ export function getBlockHierarchyRootClientId( state, clientId ) { export function getLowestCommonAncestorWithSelectedBlock( state, clientId ) { const selectedId = getSelectedBlockClientId( state ); const clientParents = [ ...getBlockParents( state, clientId ), clientId ]; - const selectedParents = [ ...getBlockParents( state, selectedId ), selectedId ]; + const selectedParents = [ + ...getBlockParents( state, selectedId ), + selectedId, + ]; let lowestCommonAncestor; @@ -587,7 +619,10 @@ export const getSelectedBlockClientIds = createSelector( ( state ) => { const { selectionStart, selectionEnd } = state; - if ( selectionStart.clientId === undefined || selectionEnd.clientId === undefined ) { + if ( + selectionStart.clientId === undefined || + selectionEnd.clientId === undefined + ) { return EMPTY_ARRAY; } @@ -598,7 +633,10 @@ export const getSelectedBlockClientIds = createSelector( // Retrieve root client ID to aid in retrieving relevant nested block // order, being careful to allow the falsey empty string top-level root // by explicitly testing against null. - const rootClientId = getBlockRootClientId( state, selectionStart.clientId ); + const rootClientId = getBlockRootClientId( + state, + selectionStart.clientId + ); if ( rootClientId === null ) { return EMPTY_ARRAY; } @@ -613,7 +651,11 @@ export const getSelectedBlockClientIds = createSelector( return blockOrder.slice( startIndex, endIndex + 1 ); }, - ( state ) => [ state.blocks.order, state.selectionStart.clientId, state.selectionEnd.clientId ] + ( state ) => [ + state.blocks.order, + state.selectionStart.clientId, + state.selectionEnd.clientId, + ] ); /** @@ -644,12 +686,16 @@ export function getMultiSelectedBlockClientIds( state ) { */ export const getMultiSelectedBlocks = createSelector( ( state ) => { - const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds( state ); + const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds( + state + ); if ( ! multiSelectedBlockClientIds.length ) { return EMPTY_ARRAY; } - return multiSelectedBlockClientIds.map( ( clientId ) => getBlock( state, clientId ) ); + return multiSelectedBlockClientIds.map( ( clientId ) => + getBlock( state, clientId ) + ); }, ( state ) => [ ...getSelectedBlockClientIds.getDependants( state ), @@ -730,7 +776,11 @@ export const isAncestorMultiSelected = createSelector( } return isMultiSelected; }, - ( state ) => [ state.blocks.order, state.selectionStart.clientId, state.selectionEnd.clientId ] + ( state ) => [ + state.blocks.order, + state.selectionStart.clientId, + state.selectionEnd.clientId, + ] ); /** * Returns the client ID of the block which begins the multi-selection set, or @@ -1040,7 +1090,11 @@ export function getTemplateLock( state, rootClientId ) { * * @return {boolean} Whether the given block type is allowed to be inserted. */ -const canInsertBlockTypeUnmemoized = ( state, blockName, rootClientId = null ) => { +const canInsertBlockTypeUnmemoized = ( + state, + blockName, + rootClientId = null +) => { const checkAllowList = ( list, item, defaultResult = null ) => { if ( isBoolean( list ) ) { return list; @@ -1064,7 +1118,11 @@ const canInsertBlockTypeUnmemoized = ( state, blockName, rootClientId = null ) = const { allowedBlockTypes } = getSettings( state ); - const isBlockAllowedInEditor = checkAllowList( allowedBlockTypes, blockName, true ); + const isBlockAllowedInEditor = checkAllowList( + allowedBlockTypes, + blockName, + true + ); if ( ! isBlockAllowedInEditor ) { return false; } @@ -1075,12 +1133,20 @@ const canInsertBlockTypeUnmemoized = ( state, blockName, rootClientId = null ) = } const parentBlockListSettings = getBlockListSettings( state, rootClientId ); - const parentAllowedBlocks = get( parentBlockListSettings, [ 'allowedBlocks' ] ); - const hasParentAllowedBlock = checkAllowList( parentAllowedBlocks, blockName ); + const parentAllowedBlocks = get( parentBlockListSettings, [ + 'allowedBlocks', + ] ); + const hasParentAllowedBlock = checkAllowList( + parentAllowedBlocks, + blockName + ); const blockAllowedParentBlocks = blockType.parent; const parentName = getBlockName( state, rootClientId ); - const hasBlockAllowedParent = checkAllowList( blockAllowedParentBlocks, parentName ); + const hasBlockAllowedParent = checkAllowList( + blockAllowedParentBlocks, + parentName + ); if ( hasParentAllowedBlock !== null && hasBlockAllowedParent !== null ) { return hasParentAllowedBlock || hasBlockAllowedParent; @@ -1220,9 +1286,15 @@ export const getInserterItems = createSelector( let isDisabled = false; if ( ! hasBlockSupport( blockType.name, 'multiple', true ) ) { - isDisabled = some( getBlocksByClientId( state, getClientIdsWithDescendants( state ) ), { - name: blockType.name, - } ); + isDisabled = some( + getBlocksByClientId( + state, + getClientIdsWithDescendants( state ) + ), + { + name: blockType.name, + } + ); } const isContextual = isArray( blockType.parent ); @@ -1243,7 +1315,11 @@ export const getInserterItems = createSelector( patterns: inserterPatterns, example: blockType.example, isDisabled, - utility: calculateUtility( blockType.category, count, isContextual ), + utility: calculateUtility( + blockType.category, + count, + isContextual + ), frecency: calculateFrecency( time, count ), }; }; @@ -1251,10 +1327,15 @@ export const getInserterItems = createSelector( const buildReusableBlockInserterItem = ( reusableBlock ) => { const id = `core/block/${ reusableBlock.id }`; - const referencedBlocks = __experimentalGetParsedReusableBlock( state, reusableBlock.id ); + const referencedBlocks = __experimentalGetParsedReusableBlock( + state, + reusableBlock.id + ); let referencedBlockType; if ( referencedBlocks.length === 1 ) { - referencedBlockType = getBlockType( referencedBlocks[ 0 ].name ); + referencedBlockType = getBlockType( + referencedBlocks[ 0 ].name + ); } const { time, count = 0 } = getInsertUsage( state, id ) || {}; @@ -1266,7 +1347,9 @@ export const getInserterItems = createSelector( name: 'core/block', initialAttributes: { ref: reusableBlock.id }, title: reusableBlock.title, - icon: referencedBlockType ? referencedBlockType.icon : templateIcon, + icon: referencedBlockType + ? referencedBlockType.icon + : templateIcon, category: 'reusable', keywords: [], isDisabled: false, @@ -1276,7 +1359,9 @@ export const getInserterItems = createSelector( }; const blockTypeInserterItems = getBlockTypes() - .filter( ( blockType ) => canIncludeBlockTypeInInserter( state, blockType, rootClientId ) ) + .filter( ( blockType ) => + canIncludeBlockTypeInInserter( state, blockType, rootClientId ) + ) .map( buildBlockTypeInserterItem ); const reusableBlockInserterItems = canInsertBlockTypeUnmemoized( @@ -1410,7 +1495,9 @@ export function isLastBlockChangePersistent( state ) { */ export const __experimentalGetBlockListSettingsForBlocks = createSelector( ( state, clientIds ) => { - return filter( state.blockListSettings, ( value, key ) => clientIds.includes( key ) ); + return filter( state.blockListSettings, ( value, key ) => + clientIds.includes( key ) + ); }, ( state ) => [ state.blockListSettings ] ); @@ -1425,7 +1512,10 @@ export const __experimentalGetBlockListSettingsForBlocks = createSelector( */ export const __experimentalGetParsedReusableBlock = createSelector( ( state, ref ) => { - const reusableBlock = find( getReusableBlocks( state ), ( block ) => block.id === ref ); + const reusableBlock = find( + getReusableBlocks( state ), + ( block ) => block.id === ref + ); if ( ! reusableBlock ) { return null; } @@ -1474,7 +1564,11 @@ export function __experimentalGetLastBlockAttributeChanges( state ) { * @return {Array} Reusable blocks */ function getReusableBlocks( state ) { - return get( state, [ 'settings', '__experimentalReusableBlocks' ], EMPTY_ARRAY ); + return get( + state, + [ 'settings', '__experimentalReusableBlocks' ], + EMPTY_ARRAY + ); } /** diff --git a/packages/block-editor/src/store/test/actions.js b/packages/block-editor/src/store/test/actions.js index 7275ae298bf737..3cad986cd639be 100644 --- a/packages/block-editor/src/store/test/actions.js +++ b/packages/block-editor/src/store/test/actions.js @@ -177,7 +177,10 @@ describe( 'actions', () => { }, ]; - const replaceBlockGenerator = replaceBlocks( [ 'chicken' ], blocks ); + const replaceBlockGenerator = replaceBlocks( + [ 'chicken' ], + blocks + ); expect( replaceBlockGenerator.next().value ).toEqual( { args: [], @@ -225,7 +228,10 @@ describe( 'actions', () => { }, ]; - const replaceBlockGenerator = replaceBlocks( [ 'chicken' ], blocks ); + const replaceBlockGenerator = replaceBlocks( + [ 'chicken' ], + blocks + ); // Skip getSettings select. replaceBlockGenerator.next(); @@ -280,7 +286,12 @@ describe( 'actions', () => { }; const index = 5; - const insertBlockGenerator = insertBlock( block, index, 'testclientid', true ); + const insertBlockGenerator = insertBlock( + block, + index, + 'testclientid', + true + ); // Skip getSettings select. insertBlockGenerator.next(); @@ -322,7 +333,12 @@ describe( 'actions', () => { }; const blocks = [ ribsBlock, chickenBlock, chickenRibsBlock ]; - const insertBlocksGenerator = insertBlocks( blocks, 5, 'testrootid', false ); + const insertBlocksGenerator = insertBlocks( + blocks, + 5, + 'testrootid', + false + ); expect( insertBlocksGenerator.next().value ).toEqual( { args: [], @@ -366,9 +382,15 @@ describe( 'actions', () => { value: { type: 'INSERT_BLOCKS', blocks: [ - { ...ribsBlock, attributes: { className: 'is-style-squared' } }, + { + ...ribsBlock, + attributes: { className: 'is-style-squared' }, + }, chickenBlock, - { ...chickenRibsBlock, attributes: { className: 'is-style-colorful' } }, + { + ...chickenRibsBlock, + attributes: { className: 'is-style-colorful' }, + }, ], index: 5, rootClientId: 'testrootid', @@ -388,7 +410,12 @@ describe( 'actions', () => { }; const blocks = [ ribsWithStyleBlock ]; - const insertBlocksGenerator = insertBlocks( blocks, 5, 'testrootid', false ); + const insertBlocksGenerator = insertBlocks( + blocks, + 5, + 'testrootid', + false + ); expect( insertBlocksGenerator.next().value ).toEqual( { args: [], @@ -416,7 +443,12 @@ describe( 'actions', () => { done: true, value: { type: 'INSERT_BLOCKS', - blocks: [ { ...ribsWithStyleBlock, attributes: { className: 'is-style-colorful' } } ], + blocks: [ + { + ...ribsWithStyleBlock, + attributes: { className: 'is-style-colorful' }, + }, + ], index: 5, rootClientId: 'testrootid', time: expect.any( Number ), @@ -439,7 +471,12 @@ describe( 'actions', () => { }; const blocks = [ ribsBlock, chickenBlock, chickenRibsBlock ]; - const insertBlocksGenerator = insertBlocks( blocks, 5, 'testrootid', false ); + const insertBlocksGenerator = insertBlocks( + blocks, + 5, + 'testrootid', + false + ); // Skip getSettings select. insertBlocksGenerator.next(); @@ -489,7 +526,12 @@ describe( 'actions', () => { }; const blocks = [ ribsBlock, chickenBlock ]; - const insertBlocksGenerator = insertBlocks( blocks, 5, 'testrootid', false ); + const insertBlocksGenerator = insertBlocks( + blocks, + 5, + 'testrootid', + false + ); // Skip getSettings select. insertBlocksGenerator.next(); @@ -535,7 +577,9 @@ describe( 'actions', () => { it( 'should return MERGE_BLOCKS action', () => { const firstBlockClientId = 'blockA'; const secondBlockClientId = 'blockB'; - expect( mergeBlocks( firstBlockClientId, secondBlockClientId ) ).toEqual( { + expect( + mergeBlocks( firstBlockClientId, secondBlockClientId ) + ).toEqual( { type: 'MERGE_BLOCKS', blocks: [ firstBlockClientId, secondBlockClientId ], } ); @@ -564,7 +608,12 @@ describe( 'actions', () => { describe( 'moveBlockToPosition', () => { it( 'should yield MOVE_BLOCK_TO_POSITION action if locking is insert and move is not changing the root block', () => { - const moveBlockToPositionGenerator = moveBlockToPosition( 'chicken', 'ribs', 'ribs', 5 ); + const moveBlockToPositionGenerator = moveBlockToPosition( + 'chicken', + 'ribs', + 'ribs', + 5 + ); expect( moveBlockToPositionGenerator.next().value ).toEqual( { args: [ 'ribs' ], @@ -573,7 +622,9 @@ describe( 'actions', () => { type: 'SELECT', } ); - expect( moveBlockToPositionGenerator.next( 'insert' ).value ).toEqual( { + expect( + moveBlockToPositionGenerator.next( 'insert' ).value + ).toEqual( { type: 'MOVE_BLOCK_TO_POSITION', fromRootClientId: 'ribs', toRootClientId: 'ribs', @@ -585,7 +636,12 @@ describe( 'actions', () => { } ); it( 'should not yield MOVE_BLOCK_TO_POSITION action if locking is all', () => { - const moveBlockToPositionGenerator = moveBlockToPosition( 'chicken', 'ribs', 'ribs', 5 ); + const moveBlockToPositionGenerator = moveBlockToPosition( + 'chicken', + 'ribs', + 'ribs', + 5 + ); expect( moveBlockToPositionGenerator.next().value ).toEqual( { args: [ 'ribs' ], @@ -643,7 +699,10 @@ describe( 'actions', () => { type: 'SELECT', } ); - expect( moveBlockToPositionGenerator.next( 'myblock/chicken-block' ).value ).toEqual( { + expect( + moveBlockToPositionGenerator.next( 'myblock/chicken-block' ) + .value + ).toEqual( { args: [ 'myblock/chicken-block', 'chicken-ribs' ], selectorName: 'canInsertBlockType', storeName: 'core/block-editor', @@ -686,7 +745,10 @@ describe( 'actions', () => { type: 'SELECT', } ); - expect( moveBlockToPositionGenerator.next( 'myblock/chicken-block' ).value ).toEqual( { + expect( + moveBlockToPositionGenerator.next( 'myblock/chicken-block' ) + .value + ).toEqual( { args: [ 'myblock/chicken-block', 'chicken-ribs' ], selectorName: 'canInsertBlockType', storeName: 'core/block-editor', @@ -810,7 +872,9 @@ describe( 'actions', () => { } ); it( 'should return the UPDATE_BLOCK_LIST_SETTINGS action with the passed settings', () => { - expect( updateBlockListSettings( 'chicken', { chicken: 'ribs' } ) ).toEqual( { + expect( + updateBlockListSettings( 'chicken', { chicken: 'ribs' } ) + ).toEqual( { type: 'UPDATE_BLOCK_LIST_SETTINGS', clientId: 'chicken', settings: { chicken: 'ribs' }, diff --git a/packages/block-editor/src/store/test/array.js b/packages/block-editor/src/store/test/array.js index 46481229dd6c2b..f88b6f858725d6 100644 --- a/packages/block-editor/src/store/test/array.js +++ b/packages/block-editor/src/store/test/array.js @@ -7,12 +7,23 @@ describe( 'array', () => { describe( 'insertAt', () => { it( 'should insert a unique item at a given position', () => { const array = [ 'a', 'b', 'd' ]; - expect( insertAt( array, 'c', 2 ) ).toEqual( [ 'a', 'b', 'c', 'd' ] ); + expect( insertAt( array, 'c', 2 ) ).toEqual( [ + 'a', + 'b', + 'c', + 'd', + ] ); } ); it( 'should insert multiple items at a given position', () => { const array = [ 'a', 'b', 'e' ]; - expect( insertAt( array, [ 'c', 'd' ], 2 ) ).toEqual( [ 'a', 'b', 'c', 'd', 'e' ] ); + expect( insertAt( array, [ 'c', 'd' ], 2 ) ).toEqual( [ + 'a', + 'b', + 'c', + 'd', + 'e', + ] ); } ); } ); @@ -29,7 +40,13 @@ describe( 'array', () => { it( 'should move multiple items to a given position', () => { const array = [ 'a', 'c', 'd', 'b', 'e' ]; - expect( moveTo( array, 1, 2, 2 ) ).toEqual( [ 'a', 'b', 'c', 'd', 'e' ] ); + expect( moveTo( array, 1, 2, 2 ) ).toEqual( [ + 'a', + 'b', + 'c', + 'd', + 'e', + ] ); } ); } ); } ); diff --git a/packages/block-editor/src/store/test/effects.js b/packages/block-editor/src/store/test/effects.js index 763df14573f827..9b8702bb3342c5 100644 --- a/packages/block-editor/src/store/test/effects.js +++ b/packages/block-editor/src/store/test/effects.js @@ -70,7 +70,10 @@ describe( 'effects', () => { const dispatch = jest.fn(); const getState = () => ( {} ); - handler( mergeBlocks( blockA.clientId, blockB.clientId ), { dispatch, getState } ); + handler( mergeBlocks( blockA.clientId, blockB.clientId ), { + dispatch, + getState, + } ); expect( dispatch ).toHaveBeenCalledTimes( 1 ); expect( dispatch ).toHaveBeenCalledWith( selectBlock( 'chicken' ) ); @@ -83,7 +86,10 @@ describe( 'effects', () => { }, merge( attributes, attributesToMerge ) { return { - content: attributes.content + ' ' + attributesToMerge.content, + content: + attributes.content + + ' ' + + attributesToMerge.content, }; }, save: noop, @@ -113,11 +119,19 @@ describe( 'effects', () => { offset: 0, }, } ); - handler( mergeBlocks( blockA.clientId, blockB.clientId ), { dispatch, getState } ); + handler( mergeBlocks( blockA.clientId, blockB.clientId ), { + dispatch, + getState, + } ); expect( dispatch ).toHaveBeenCalledTimes( 2 ); expect( dispatch ).toHaveBeenCalledWith( - selectionChange( blockA.clientId, 'content', 'chicken'.length + 1, 'chicken'.length + 1 ) + selectionChange( + blockA.clientId, + 'content', + 'chicken'.length + 1, + 'chicken'.length + 1 + ) ); const lastCall = dispatch.mock.calls[ 1 ]; expect( lastCall ).toHaveLength( 1 ); @@ -132,7 +146,9 @@ describe( 'effects', () => { }, ] ); - expect( Array.from( lastCallArgument ) ).toEqual( Array.from( expectedGenerator ) ); + expect( Array.from( lastCallArgument ) ).toEqual( + Array.from( expectedGenerator ) + ); } ); it( 'should not merge the blocks have different types without transformation', () => { @@ -142,7 +158,10 @@ describe( 'effects', () => { }, merge( attributes, attributesToMerge ) { return { - content: attributes.content + ' ' + attributesToMerge.content, + content: + attributes.content + + ' ' + + attributesToMerge.content, }; }, save: noop, @@ -173,7 +192,10 @@ describe( 'effects', () => { offset: 0, }, } ); - handler( mergeBlocks( blockA.clientId, blockB.clientId ), { dispatch, getState } ); + handler( mergeBlocks( blockA.clientId, blockB.clientId ), { + dispatch, + getState, + } ); expect( dispatch ).not.toHaveBeenCalled(); } ); @@ -187,7 +209,10 @@ describe( 'effects', () => { }, merge( attributes, attributesToMerge ) { return { - content: attributes.content + ' ' + attributesToMerge.content, + content: + attributes.content + + ' ' + + attributesToMerge.content, }; }, save: noop, @@ -240,11 +265,19 @@ describe( 'effects', () => { offset: 0, }, } ); - handler( mergeBlocks( blockA.clientId, blockB.clientId ), { dispatch, getState } ); + handler( mergeBlocks( blockA.clientId, blockB.clientId ), { + dispatch, + getState, + } ); expect( dispatch ).toHaveBeenCalledTimes( 2 ); expect( dispatch ).toHaveBeenCalledWith( - selectionChange( blockA.clientId, 'content', 'chicken'.length + 1, 'chicken'.length + 1 ) + selectionChange( + blockA.clientId, + 'content', + 'chicken'.length + 1, + 'chicken'.length + 1 + ) ); const expectedGenerator = replaceBlocks( [ 'chicken', 'ribs' ], @@ -259,7 +292,9 @@ describe( 'effects', () => { const lastCall = dispatch.mock.calls[ 1 ]; expect( lastCall ).toHaveLength( 1 ); const [ lastCallArgument ] = lastCall; - expect( Array.from( lastCallArgument ) ).toEqual( Array.from( expectedGenerator ) ); + expect( Array.from( lastCallArgument ) ).toEqual( + Array.from( expectedGenerator ) + ); } ); } ); diff --git a/packages/block-editor/src/store/test/reducer.js b/packages/block-editor/src/store/test/reducer.js index 64cf99b2718eed..8610a1b8a3f31c 100644 --- a/packages/block-editor/src/store/test/reducer.js +++ b/packages/block-editor/src/store/test/reducer.js @@ -7,7 +7,11 @@ import deepFreeze from 'deep-freeze'; /** * WordPress dependencies */ -import { registerBlockType, unregisterBlockType, createBlock } from '@wordpress/blocks'; +import { + registerBlockType, + unregisterBlockType, + createBlock, +} from '@wordpress/blocks'; /** * Internal dependencies @@ -58,7 +62,9 @@ describe( 'state', () => { clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189', }; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( false ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( false ); } ); it( 'should return false if last action was not updating block attributes', () => { @@ -74,7 +80,9 @@ describe( 'state', () => { clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189', }; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( false ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( false ); } ); it( 'should return false if not updating the same block', () => { @@ -93,7 +101,9 @@ describe( 'state', () => { }, }; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( false ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( false ); } ); it( 'should return false if not updating the same block attributes', () => { @@ -112,7 +122,9 @@ describe( 'state', () => { }, }; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( false ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( false ); } ); it( 'should return false if no previous action', () => { @@ -125,7 +137,9 @@ describe( 'state', () => { }; const previousAction = undefined; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( false ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( false ); } ); it( 'should return true if updating the same block attributes', () => { @@ -144,7 +158,9 @@ describe( 'state', () => { }, }; - expect( isUpdatingSameBlockAttribute( action, previousAction ) ).toBe( true ); + expect( + isUpdatingSameBlockAttribute( action, previousAction ) + ).toBe( true ); } ); } ); @@ -276,7 +292,9 @@ describe( 'state', () => { [ newChildBlockId ]: {}, }, } ); - expect( state.cache.chicken ).not.toBe( existingState.cache.chicken ); + expect( state.cache.chicken ).not.toBe( + existingState.cache.chicken + ); } ); it( 'can insert a child block', () => { @@ -354,7 +372,9 @@ describe( 'state', () => { [ newChildBlockId ]: {}, }, } ); - expect( state.cache.chicken ).not.toBe( existingState.cache.chicken ); + expect( state.cache.chicken ).not.toBe( + existingState.cache.chicken + ); } ); it( 'can replace multiple child blocks', () => { @@ -470,7 +490,11 @@ describe( 'state', () => { }, order: { '': [ 'chicken' ], - chicken: [ newChildBlockId1, newChildBlockId2, newChildBlockId3 ], + chicken: [ + newChildBlockId1, + newChildBlockId2, + newChildBlockId3, + ], [ newChildBlockId1 ]: [], [ newChildBlockId2 ]: [], [ newChildBlockId3 ]: [], @@ -579,7 +603,9 @@ describe( 'state', () => { } ); // the cache key of the parent should be updated - expect( existingState.cache.chicken ).not.toBe( state.cache.chicken ); + expect( existingState.cache.chicken ).not.toBe( + state.cache.chicken + ); } ); } ); @@ -605,7 +631,9 @@ describe( 'state', () => { } ); expect( Object.keys( state.byClientId ) ).toHaveLength( 1 ); - expect( values( state.byClientId )[ 0 ].clientId ).toBe( 'bananas' ); + expect( values( state.byClientId )[ 0 ].clientId ).toBe( + 'bananas' + ); expect( state.order ).toEqual( { '': [ 'bananas' ], bananas: [], @@ -623,7 +651,9 @@ describe( 'state', () => { blocks: [ { clientId: 'bananas', - innerBlocks: [ { clientId: 'apples', innerBlocks: [] } ], + innerBlocks: [ + { clientId: 'apples', innerBlocks: [] }, + ], }, ], } ); @@ -703,7 +733,9 @@ describe( 'state', () => { } ); expect( Object.keys( state.byClientId ) ).toHaveLength( 1 ); - expect( values( state.byClientId )[ 0 ].name ).toBe( 'core/freeform' ); + expect( values( state.byClientId )[ 0 ].name ).toBe( + 'core/freeform' + ); expect( values( state.byClientId )[ 0 ].clientId ).toBe( 'wings' ); expect( state.order ).toEqual( { '': [ 'wings' ], @@ -762,14 +794,17 @@ describe( 'state', () => { it( 'should replace the nested block', () => { const nestedBlock = createBlock( 'core/test-block' ); - const wrapperBlock = createBlock( 'core/test-block', {}, [ nestedBlock ] ); + const wrapperBlock = createBlock( 'core/test-block', {}, [ + nestedBlock, + ] ); const replacementBlock = createBlock( 'core/test-block' ); const original = blocks( undefined, { type: 'RESET_BLOCKS', blocks: [ wrapperBlock ], } ); - const originalWrapperBlockCacheKey = original.cache[ wrapperBlock.clientId ]; + const originalWrapperBlockCacheKey = + original.cache[ wrapperBlock.clientId ]; const state = blocks( original, { type: 'REPLACE_BLOCKS', @@ -777,9 +812,12 @@ describe( 'state', () => { blocks: [ replacementBlock ], } ); - const newWrapperBlockCacheKey = state.cache[ wrapperBlock.clientId ]; + const newWrapperBlockCacheKey = + state.cache[ wrapperBlock.clientId ]; - expect( newWrapperBlockCacheKey ).not.toBe( originalWrapperBlockCacheKey ); + expect( newWrapperBlockCacheKey ).not.toBe( + originalWrapperBlockCacheKey + ); expect( state.order ).toEqual( { '': [ wrapperBlock.clientId ], @@ -823,9 +861,15 @@ describe( 'state', () => { } ); expect( Object.keys( replacedState.byClientId ) ).toHaveLength( 1 ); - expect( values( originalState.byClientId )[ 0 ].name ).toBe( 'core/test-block' ); - expect( values( replacedState.byClientId )[ 0 ].name ).toBe( 'core/freeform' ); - expect( values( replacedState.byClientId )[ 0 ].clientId ).toBe( 'chicken' ); + expect( values( originalState.byClientId )[ 0 ].name ).toBe( + 'core/test-block' + ); + expect( values( replacedState.byClientId )[ 0 ].name ).toBe( + 'core/freeform' + ); + expect( values( replacedState.byClientId )[ 0 ].clientId ).toBe( + 'chicken' + ); expect( replacedState.order ).toEqual( { '': [ 'chicken' ], chicken: [], @@ -833,7 +877,9 @@ describe( 'state', () => { expect( replacedState.cache ).toEqual( { chicken: {}, } ); - expect( originalState.cache.chicken ).not.toBe( replacedState.cache.chicken ); + expect( originalState.cache.chicken ).not.toBe( + replacedState.cache.chicken + ); const nestedBlock = { clientId: 'chicken', @@ -841,7 +887,9 @@ describe( 'state', () => { attributes: {}, innerBlocks: [], }; - const wrapperBlock = createBlock( 'core/test-block', {}, [ nestedBlock ] ); + const wrapperBlock = createBlock( 'core/test-block', {}, [ + nestedBlock, + ] ); const replacementNestedBlock = { clientId: 'chicken', name: 'core/freeform', @@ -866,8 +914,12 @@ describe( 'state', () => { [ replacementNestedBlock.clientId ]: [], } ); - expect( originalNestedState.byClientId.chicken.name ).toBe( 'core/test-block' ); - expect( replacedNestedState.byClientId.chicken.name ).toBe( 'core/freeform' ); + expect( originalNestedState.byClientId.chicken.name ).toBe( + 'core/test-block' + ); + expect( replacedNestedState.byClientId.chicken.name ).toBe( + 'core/freeform' + ); } ); it( 'should update the block', () => { @@ -976,7 +1028,10 @@ describe( 'state', () => { it( 'should move the nested block up', () => { const movedBlock = createBlock( 'core/test-block' ); const siblingBlock = createBlock( 'core/test-block' ); - const wrapperBlock = createBlock( 'core/test-block', {}, [ siblingBlock, movedBlock ] ); + const wrapperBlock = createBlock( 'core/test-block', {}, [ + siblingBlock, + movedBlock, + ] ); const original = blocks( undefined, { type: 'RESET_BLOCKS', blocks: [ wrapperBlock ], @@ -989,14 +1044,19 @@ describe( 'state', () => { expect( state.order ).toEqual( { '': [ wrapperBlock.clientId ], - [ wrapperBlock.clientId ]: [ movedBlock.clientId, siblingBlock.clientId ], + [ wrapperBlock.clientId ]: [ + movedBlock.clientId, + siblingBlock.clientId, + ], [ movedBlock.clientId ]: [], [ siblingBlock.clientId ]: [], } ); expect( state.cache[ wrapperBlock.clientId ] ).not.toBe( original.cache[ wrapperBlock.clientId ] ); - expect( state.cache[ movedBlock.clientId ] ).toBe( original.cache[ movedBlock.clientId ] ); + expect( state.cache[ movedBlock.clientId ] ).toBe( + original.cache[ movedBlock.clientId ] + ); expect( state.cache[ siblingBlock.clientId ] ).toBe( original.cache[ siblingBlock.clientId ] ); @@ -1031,7 +1091,11 @@ describe( 'state', () => { clientIds: [ 'ribs', 'veggies' ], } ); - expect( state.order[ '' ] ).toEqual( [ 'ribs', 'veggies', 'chicken' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'ribs', + 'veggies', + 'chicken', + ] ); } ); it( 'should move multiple nested blocks up', () => { @@ -1121,7 +1185,10 @@ describe( 'state', () => { it( 'should move the nested block down', () => { const movedBlock = createBlock( 'core/test-block' ); const siblingBlock = createBlock( 'core/test-block' ); - const wrapperBlock = createBlock( 'core/test-block', {}, [ movedBlock, siblingBlock ] ); + const wrapperBlock = createBlock( 'core/test-block', {}, [ + movedBlock, + siblingBlock, + ] ); const original = blocks( undefined, { type: 'RESET_BLOCKS', blocks: [ wrapperBlock ], @@ -1134,7 +1201,10 @@ describe( 'state', () => { expect( state.order ).toEqual( { '': [ wrapperBlock.clientId ], - [ wrapperBlock.clientId ]: [ siblingBlock.clientId, movedBlock.clientId ], + [ wrapperBlock.clientId ]: [ + siblingBlock.clientId, + movedBlock.clientId, + ], [ movedBlock.clientId ]: [], [ siblingBlock.clientId ]: [], } ); @@ -1169,7 +1239,11 @@ describe( 'state', () => { clientIds: [ 'chicken', 'ribs' ], } ); - expect( state.order[ '' ] ).toEqual( [ 'veggies', 'chicken', 'ribs' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'veggies', + 'chicken', + 'ribs', + ] ); } ); it( 'should move multiple nested blocks down', () => { @@ -1320,7 +1394,9 @@ describe( 'state', () => { it( 'should cascade remove to include inner blocks', () => { const block = createBlock( 'core/test-block', {}, [ - createBlock( 'core/test-block', {}, [ createBlock( 'core/test-block' ) ] ), + createBlock( 'core/test-block', {}, [ + createBlock( 'core/test-block' ), + ] ), ] ); const original = blocks( undefined, { @@ -1372,7 +1448,11 @@ describe( 'state', () => { } ); expect( Object.keys( state.byClientId ) ).toHaveLength( 3 ); - expect( state.order[ '' ] ).toEqual( [ 'kumquat', 'persimmon', 'loquat' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'kumquat', + 'persimmon', + 'loquat', + ] ); } ); it( 'should move block to lower index', () => { @@ -1405,7 +1485,11 @@ describe( 'state', () => { index: 0, } ); - expect( state.order[ '' ] ).toEqual( [ 'ribs', 'chicken', 'veggies' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'ribs', + 'chicken', + 'veggies', + ] ); } ); it( 'should move block to higher index', () => { @@ -1438,7 +1522,11 @@ describe( 'state', () => { index: 2, } ); - expect( state.order[ '' ] ).toEqual( [ 'chicken', 'veggies', 'ribs' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'chicken', + 'veggies', + 'ribs', + ] ); } ); it( 'should not move block if passed same index', () => { @@ -1471,7 +1559,11 @@ describe( 'state', () => { index: 1, } ); - expect( state.order[ '' ] ).toEqual( [ 'chicken', 'ribs', 'veggies' ] ); + expect( state.order[ '' ] ).toEqual( [ + 'chicken', + 'ribs', + 'veggies', + ] ); } ); describe( 'blocks', () => { @@ -1502,7 +1594,9 @@ describe( 'state', () => { ], }, ]; - const original = deepFreeze( actions.reduce( blocks, undefined ) ); + const original = deepFreeze( + actions.reduce( blocks, undefined ) + ); const state = blocks( original, { type: 'RESET_BLOCKS', @@ -1817,7 +1911,9 @@ describe( 'state', () => { describe( 'isIgnoredChange', () => { it( 'should consider received blocks as ignored change', () => { - const resetState = blocks( undefined, { type: 'random action' } ); + const resetState = blocks( undefined, { + type: 'random action', + } ); const state = blocks( resetState, { type: 'RECEIVE_BLOCKS', blocks: [ @@ -2302,7 +2398,10 @@ describe( 'state', () => { type: 'TOGGLE_BLOCK_MODE', clientId: 'chicken', }; - const value = blocksMode( deepFreeze( { chicken: 'html' } ), action ); + const value = blocksMode( + deepFreeze( { chicken: 'html' } ), + action + ); expect( value ).toEqual( { chicken: 'visual' } ); } ); diff --git a/packages/block-editor/src/store/test/selectors.js b/packages/block-editor/src/store/test/selectors.js index 8faaa591edd386..782cacd7d24f75 100644 --- a/packages/block-editor/src/store/test/selectors.js +++ b/packages/block-editor/src/store/test/selectors.js @@ -159,7 +159,10 @@ describe( 'selectors', () => { }, }; - const name = getBlockName( state, 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' ); + const name = getBlockName( + state, + 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' + ); expect( name ).toBe( null ); } ); @@ -186,7 +189,10 @@ describe( 'selectors', () => { }, }; - const name = getBlockName( state, 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' ); + const name = getBlockName( + state, + 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' + ); expect( name ).toBe( 'core/paragraph' ); } ); @@ -307,8 +313,18 @@ describe( 'selectors', () => { }; expect( getBlocks( state ) ).toEqual( [ - { clientId: 123, name: 'core/paragraph', attributes: {}, innerBlocks: [] }, - { clientId: 23, name: 'core/heading', attributes: {}, innerBlocks: [] }, + { + clientId: 123, + name: 'core/paragraph', + attributes: {}, + innerBlocks: [], + }, + { + clientId: 23, + name: 'core/heading', + attributes: {}, + innerBlocks: [], + }, ] ); } ); } ); @@ -319,20 +335,38 @@ describe( 'selectors', () => { blocks: { byClientId: { 'uuid-2': { clientId: 'uuid-2', name: 'core/image' }, - 'uuid-4': { clientId: 'uuid-4', name: 'core/paragraph' }, - 'uuid-6': { clientId: 'uuid-6', name: 'core/paragraph' }, + 'uuid-4': { + clientId: 'uuid-4', + name: 'core/paragraph', + }, + 'uuid-6': { + clientId: 'uuid-6', + name: 'core/paragraph', + }, 'uuid-8': { clientId: 'uuid-8', name: 'core/block' }, - 'uuid-10': { clientId: 'uuid-10', name: 'core/columns' }, + 'uuid-10': { + clientId: 'uuid-10', + name: 'core/columns', + }, 'uuid-12': { clientId: 'uuid-12', name: 'core/column' }, 'uuid-14': { clientId: 'uuid-14', name: 'core/column' }, 'uuid-16': { clientId: 'uuid-16', name: 'core/quote' }, 'uuid-18': { clientId: 'uuid-18', name: 'core/block' }, - 'uuid-20': { clientId: 'uuid-20', name: 'core/gallery' }, + 'uuid-20': { + clientId: 'uuid-20', + name: 'core/gallery', + }, 'uuid-22': { clientId: 'uuid-22', name: 'core/block' }, - 'uuid-24': { clientId: 'uuid-24', name: 'core/columns' }, + 'uuid-24': { + clientId: 'uuid-24', + name: 'core/columns', + }, 'uuid-26': { clientId: 'uuid-26', name: 'core/column' }, 'uuid-28': { clientId: 'uuid-28', name: 'core/column' }, - 'uuid-30': { clientId: 'uuid-30', name: 'core/paragraph' }, + 'uuid-30': { + clientId: 'uuid-30', + name: 'core/paragraph', + }, }, attributes: { 'uuid-2': {}, @@ -384,7 +418,9 @@ describe( 'selectors', () => { }, }, }; - expect( getClientIdsOfDescendants( state, [ 'uuid-10' ] ) ).toEqual( [ + expect( + getClientIdsOfDescendants( state, [ 'uuid-10' ] ) + ).toEqual( [ 'uuid-12', 'uuid-14', 'uuid-16', @@ -403,20 +439,38 @@ describe( 'selectors', () => { blocks: { byClientId: { 'uuid-2': { clientId: 'uuid-2', name: 'core/image' }, - 'uuid-4': { clientId: 'uuid-4', name: 'core/paragraph' }, - 'uuid-6': { clientId: 'uuid-6', name: 'core/paragraph' }, + 'uuid-4': { + clientId: 'uuid-4', + name: 'core/paragraph', + }, + 'uuid-6': { + clientId: 'uuid-6', + name: 'core/paragraph', + }, 'uuid-8': { clientId: 'uuid-8', name: 'core/block' }, - 'uuid-10': { clientId: 'uuid-10', name: 'core/columns' }, + 'uuid-10': { + clientId: 'uuid-10', + name: 'core/columns', + }, 'uuid-12': { clientId: 'uuid-12', name: 'core/column' }, 'uuid-14': { clientId: 'uuid-14', name: 'core/column' }, 'uuid-16': { clientId: 'uuid-16', name: 'core/quote' }, 'uuid-18': { clientId: 'uuid-18', name: 'core/block' }, - 'uuid-20': { clientId: 'uuid-20', name: 'core/gallery' }, + 'uuid-20': { + clientId: 'uuid-20', + name: 'core/gallery', + }, 'uuid-22': { clientId: 'uuid-22', name: 'core/block' }, - 'uuid-24': { clientId: 'uuid-24', name: 'core/columns' }, + 'uuid-24': { + clientId: 'uuid-24', + name: 'core/columns', + }, 'uuid-26': { clientId: 'uuid-26', name: 'core/column' }, 'uuid-28': { clientId: 'uuid-28', name: 'core/column' }, - 'uuid-30': { clientId: 'uuid-30', name: 'core/paragraph' }, + 'uuid-30': { + clientId: 'uuid-30', + name: 'core/paragraph', + }, }, attributes: { 'uuid-2': {}, @@ -547,8 +601,12 @@ describe( 'selectors', () => { it( 'should return false if multi-selection', () => { const state = { - selectionStart: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, - selectionEnd: { clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189' }, + selectionStart: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, + selectionEnd: { + clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189', + }, }; expect( hasSelectedBlock( state ) ).toBe( false ); @@ -556,8 +614,12 @@ describe( 'selectors', () => { it( 'should return true if singular selection', () => { const state = { - selectionStart: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, - selectionEnd: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, + selectionStart: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, + selectionEnd: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, }; expect( hasSelectedBlock( state ) ).toBe( true ); @@ -605,7 +667,9 @@ describe( 'selectors', () => { }, }; expect( getGlobalBlockCount( emptyState ) ).toBe( 0 ); - expect( getGlobalBlockCount( emptyState, 'core/heading' ) ).toBe( 0 ); + expect( getGlobalBlockCount( emptyState, 'core/heading' ) ).toBe( + 0 + ); } ); } ); @@ -949,7 +1013,11 @@ describe( 'selectors', () => { selectionEnd: { clientId: 4 }, }; - expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ 4, 3, 2 ] ); + expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ + 4, + 3, + 2, + ] ); } ); it( 'should return selected block clientIds if there is multi selection (nested context)', () => { @@ -975,7 +1043,11 @@ describe( 'selectors', () => { selectionEnd: { clientId: 9 }, }; - expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ 9, 8, 7 ] ); + expect( getMultiSelectedBlockClientIds( state ) ).toEqual( [ + 9, + 8, + 7, + ] ); } ); } ); @@ -992,7 +1064,9 @@ describe( 'selectors', () => { selectionEnd: {}, }; - expect( getMultiSelectedBlocks( state ) ).toBe( getMultiSelectedBlocks( state ) ); + expect( getMultiSelectedBlocks( state ) ).toBe( + getMultiSelectedBlocks( state ) + ); } ); } ); @@ -1142,7 +1216,9 @@ describe( 'selectors', () => { }, }; - expect( getPreviousBlockClientId( state, 56, '123' ) ).toEqual( 456 ); + expect( getPreviousBlockClientId( state, 56, '123' ) ).toEqual( + 456 + ); } ); it( 'should return null for the first block', () => { @@ -1460,8 +1536,12 @@ describe( 'selectors', () => { it( 'should return false if singular selection', () => { const state = { - selectionStart: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, - selectionEnd: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, + selectionStart: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, + selectionEnd: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, }; expect( hasMultiSelection( state ) ).toBe( false ); @@ -1469,8 +1549,12 @@ describe( 'selectors', () => { it( 'should return true if multi-selection', () => { const state = { - selectionStart: { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1' }, - selectionEnd: { clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189' }, + selectionStart: { + clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', + }, + selectionEnd: { + clientId: '9db792c6-a25a-495d-adbd-97d56a4c4189', + }, }; expect( hasMultiSelection( state ) ).toBe( true ); @@ -1811,7 +1895,9 @@ describe( 'selectors', () => { allowedBlockTypes: [], }, }; - expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( false ); + expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( + false + ); } ); it( 'should allow blocks that are allowed by the editor', () => { @@ -1825,7 +1911,9 @@ describe( 'selectors', () => { allowedBlockTypes: [ 'core/test-block-a' ], }, }; - expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( true ); + expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( + true + ); } ); it( 'should deny blocks when the editor has a template lock', () => { @@ -1839,7 +1927,9 @@ describe( 'selectors', () => { templateLock: 'all', }, }; - expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( false ); + expect( canInsertBlockType( state, 'core/test-block-a' ) ).toBe( + false + ); } ); it( 'should deny blocks that restrict parent from being inserted into the root', () => { @@ -1851,7 +1941,9 @@ describe( 'selectors', () => { blockListSettings: {}, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-c' ) ).toBe( false ); + expect( canInsertBlockType( state, 'core/test-block-c' ) ).toBe( + false + ); } ); it( 'should deny blocks that restrict parent from being inserted into a restricted parent', () => { @@ -1867,7 +1959,9 @@ describe( 'selectors', () => { blockListSettings: {}, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-c', 'block1' ) ).toBe( false ); + expect( + canInsertBlockType( state, 'core/test-block-c', 'block1' ) + ).toBe( false ); } ); it( 'should allow blocks that restrict parent to be inserted into an allowed parent', () => { @@ -1883,7 +1977,9 @@ describe( 'selectors', () => { blockListSettings: {}, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-c', 'block1' ) ).toBe( true ); + expect( + canInsertBlockType( state, 'core/test-block-c', 'block1' ) + ).toBe( true ); } ); it( 'should deny restricted blocks from being inserted into a block that restricts allowedBlocks', () => { @@ -1903,7 +1999,9 @@ describe( 'selectors', () => { }, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-b', 'block1' ) ).toBe( false ); + expect( + canInsertBlockType( state, 'core/test-block-b', 'block1' ) + ).toBe( false ); } ); it( 'should allow allowed blocks to be inserted into a block that restricts allowedBlocks', () => { @@ -1923,7 +2021,9 @@ describe( 'selectors', () => { }, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-b', 'block1' ) ).toBe( true ); + expect( + canInsertBlockType( state, 'core/test-block-b', 'block1' ) + ).toBe( true ); } ); it( 'should prioritise parent over allowedBlocks', () => { @@ -1943,7 +2043,9 @@ describe( 'selectors', () => { }, settings: {}, }; - expect( canInsertBlockType( state, 'core/test-block-c', 'block1' ) ).toBe( true ); + expect( + canInsertBlockType( state, 'core/test-block-c', 'block1' ) + ).toBe( true ); } ); it( 'should deny blocks that restrict parent to core/post-content when not in editor root', () => { @@ -1959,7 +2061,9 @@ describe( 'selectors', () => { blockListSettings: {}, settings: {}, }; - expect( canInsertBlockType( state, 'core/post-content-child', 'block1' ) ).toBe( false ); + expect( + canInsertBlockType( state, 'core/post-content-child', 'block1' ) + ).toBe( false ); } ); it( 'should allow blocks that restrict parent to core/post-content when in editor root', () => { @@ -1971,7 +2075,9 @@ describe( 'selectors', () => { blockListSettings: {}, settings: {}, }; - expect( canInsertBlockType( state, 'core/post-content-child' ) ).toBe( true ); + expect( + canInsertBlockType( state, 'core/post-content-child' ) + ).toBe( true ); } ); } ); @@ -2004,7 +2110,9 @@ describe( 'selectors', () => { blockListSettings: {}, }; const items = getInserterItems( state ); - const testBlockAItem = items.find( ( item ) => item.id === 'core/test-block-a' ); + const testBlockAItem = items.find( + ( item ) => item.id === 'core/test-block-a' + ); expect( testBlockAItem ).toEqual( { id: 'core/test-block-a', name: 'core/test-block-a', @@ -2020,7 +2128,9 @@ describe( 'selectors', () => { utility: 0, frecency: 0, } ); - const reusableBlockItem = items.find( ( item ) => item.id === 'core/block/1' ); + const reusableBlockItem = items.find( + ( item ) => item.id === 'core/block/1' + ); expect( reusableBlockItem ).toEqual( { id: 'core/block/1', name: 'core/block', @@ -2072,7 +2182,9 @@ describe( 'selectors', () => { }, blockListSettings: {}, }; - const itemIDs = getInserterItems( state ).map( ( item ) => item.id ); + const itemIDs = getInserterItems( state ).map( + ( item ) => item.id + ); expect( itemIDs ).toEqual( [ 'core/post-content-child', 'core/block/2', @@ -2140,7 +2252,10 @@ describe( 'selectors', () => { }; const firstBlockFirstCall = getInserterItems( state, 'block3' ); - const firstBlockSecondCall = getInserterItems( stateSecondBlockRestricted, 'block3' ); + const firstBlockSecondCall = getInserterItems( + stateSecondBlockRestricted, + 'block3' + ); expect( firstBlockFirstCall ).toBe( firstBlockSecondCall ); expect( firstBlockFirstCall.map( ( item ) => item.id ) ).toEqual( [ 'core/test-block-b', @@ -2151,7 +2266,10 @@ describe( 'selectors', () => { ] ); const secondBlockFirstCall = getInserterItems( state, 'block4' ); - const secondBlockSecondCall = getInserterItems( stateSecondBlockRestricted, 'block4' ); + const secondBlockSecondCall = getInserterItems( + stateSecondBlockRestricted, + 'block4' + ); expect( secondBlockFirstCall.map( ( item ) => item.id ) ).toEqual( [ 'core/test-block-b', 'core/test-freeform', @@ -2159,14 +2277,19 @@ describe( 'selectors', () => { 'core/block/1', 'core/block/2', ] ); - expect( secondBlockSecondCall.map( ( item ) => item.id ) ).toEqual( [ 'core/test-block-b' ] ); + expect( + secondBlockSecondCall.map( ( item ) => item.id ) + ).toEqual( [ 'core/test-block-b' ] ); } ); it( 'should set isDisabled when a block with `multiple: false` has been used', () => { const state = { blocks: { byClientId: { - block1: { clientId: 'block1', name: 'core/test-block-b' }, + block1: { + clientId: 'block1', + name: 'core/test-block-b', + }, }, attributes: { block1: { attribute: {} }, @@ -2185,7 +2308,9 @@ describe( 'selectors', () => { settings: {}, }; const items = getInserterItems( state ); - const testBlockBItem = items.find( ( item ) => item.id === 'core/test-block-b' ); + const testBlockBItem = items.find( + ( item ) => item.id === 'core/test-block-b' + ); expect( testBlockBItem.isDisabled ).toBe( true ); } ); @@ -2205,7 +2330,9 @@ describe( 'selectors', () => { settings: {}, }; const items = getInserterItems( state ); - const testBlockBItem = items.find( ( item ) => item.id === 'core/test-block-b' ); + const testBlockBItem = items.find( + ( item ) => item.id === 'core/test-block-b' + ); expect( testBlockBItem.utility ).toBe( INSERTER_UTILITY_LOW ); } ); @@ -2227,8 +2354,12 @@ describe( 'selectors', () => { settings: {}, }; const items = getInserterItems( state ); - const reusableBlock2Item = items.find( ( item ) => item.id === 'core/test-block-b' ); - expect( reusableBlock2Item.utility ).toBe( INSERTER_UTILITY_MEDIUM ); + const reusableBlock2Item = items.find( + ( item ) => item.id === 'core/test-block-b' + ); + expect( reusableBlock2Item.utility ).toBe( + INSERTER_UTILITY_MEDIUM + ); expect( reusableBlock2Item.frecency ).toBe( 2.5 ); } ); @@ -2258,7 +2389,9 @@ describe( 'selectors', () => { settings: {}, }; const items = getInserterItems( state, 'block1' ); - const testBlockCItem = items.find( ( item ) => item.id === 'core/test-block-c' ); + const testBlockCItem = items.find( + ( item ) => item.id === 'core/test-block-c' + ); expect( testBlockCItem.utility ).toBe( INSERTER_UTILITY_HIGH ); } ); } ); @@ -2364,7 +2497,9 @@ describe( 'selectors', () => { blockListSettings: {}, }; - expect( getBlockListSettings( state, 'chicken' ) ).toBe( undefined ); + expect( getBlockListSettings( state, 'chicken' ) ).toBe( + undefined + ); } ); } ); @@ -2389,19 +2524,25 @@ describe( 'selectors', () => { }, }; - const targetBlocksClientIds = [ 'test-1-dummy-clientId', 'test-3-dummy-clientId' ]; + const targetBlocksClientIds = [ + 'test-1-dummy-clientId', + 'test-3-dummy-clientId', + ]; - expect( __experimentalGetBlockListSettingsForBlocks( state, targetBlocksClientIds ) ).toEqual( - [ - { - setting1: false, - }, - { - setting1: true, - setting2: false, - }, - ] - ); + expect( + __experimentalGetBlockListSettingsForBlocks( + state, + targetBlocksClientIds + ) + ).toEqual( [ + { + setting1: false, + }, + { + setting1: true, + setting2: false, + }, + ] ); } ); it( 'should return empty array if settings for the blocks donโ€™t exist', () => { @@ -2418,11 +2559,17 @@ describe( 'selectors', () => { }, }; - const targetBlocksClientIds = [ 'test-1-dummy-clientId', 'test-3-dummy-clientId' ]; + const targetBlocksClientIds = [ + 'test-1-dummy-clientId', + 'test-3-dummy-clientId', + ]; - expect( __experimentalGetBlockListSettingsForBlocks( state, targetBlocksClientIds ) ).toEqual( - [] - ); + expect( + __experimentalGetBlockListSettingsForBlocks( + state, + targetBlocksClientIds + ) + ).toEqual( [] ); } ); } ); @@ -2467,7 +2614,9 @@ describe( 'selectors', () => { selectionEnd: {}, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'd' ) ).not.toBeDefined(); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'd' ) + ).not.toBeDefined(); } ); it( 'should not be defined if selected block has no parent', () => { @@ -2477,7 +2626,9 @@ describe( 'selectors', () => { selectionEnd: { clientId: 'b' }, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'b' ) ).toBe( 'b' ); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'b' ) + ).toBe( 'b' ); } ); it( 'should not be defined if selected block has no common parent with given block', () => { @@ -2487,7 +2638,9 @@ describe( 'selectors', () => { selectionEnd: { clientId: 'd' }, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'f' ) ).not.toBeDefined(); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'f' ) + ).not.toBeDefined(); } ); it( 'should return block id if selected block is ancestor of given block', () => { @@ -2497,7 +2650,9 @@ describe( 'selectors', () => { selectionEnd: { clientId: 'c' }, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'a' ) ).toBe( 'a' ); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'a' ) + ).toBe( 'a' ); } ); it( 'should return block id if selected block is nested child of given block', () => { @@ -2507,7 +2662,9 @@ describe( 'selectors', () => { selectionEnd: { clientId: 'e' }, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'a' ) ).toBe( 'a' ); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'a' ) + ).toBe( 'a' ); } ); it( 'should return block id if selected block has common parent with given block', () => { @@ -2517,7 +2674,9 @@ describe( 'selectors', () => { selectionEnd: { clientId: 'e' }, }; - expect( getLowestCommonAncestorWithSelectedBlock( state, 'c' ) ).toBe( 'a' ); + expect( + getLowestCommonAncestorWithSelectedBlock( state, 'c' ) + ).toBe( 'a' ); } ); } ); } ); diff --git a/packages/block-editor/src/utils/dom.js b/packages/block-editor/src/utils/dom.js index 12a15c93df29f8..3fb25425678ab8 100644 --- a/packages/block-editor/src/utils/dom.js +++ b/packages/block-editor/src/utils/dom.js @@ -58,7 +58,9 @@ export function isInSameBlock( a, b ) { * @return {boolean} Whether element is in the block Element but not its children. */ export function isInsideRootBlock( blockElement, element ) { - const innerBlocksContainer = blockElement.querySelector( '.block-editor-block-list__layout' ); + const innerBlocksContainer = blockElement.querySelector( + '.block-editor-block-list__layout' + ); return ( blockElement.contains( element ) && ( ! innerBlocksContainer || ! innerBlocksContainer.contains( element ) ) diff --git a/packages/block-editor/src/utils/get-paste-event-data.js b/packages/block-editor/src/utils/get-paste-event-data.js index 65a493aee13b5d..7b798887c76b0e 100644 --- a/packages/block-editor/src/utils/get-paste-event-data.js +++ b/packages/block-editor/src/utils/get-paste-event-data.js @@ -56,12 +56,16 @@ export function getPasteEventData( { clipboardData } ) { } } ); - files = files.filter( ( { type } ) => /^image\/(?:jpe?g|png|gif)$/.test( type ) ); + files = files.filter( ( { type } ) => + /^image\/(?:jpe?g|png|gif)$/.test( type ) + ); // Only process files if no HTML is present. // A pasted file may have the URL as plain text. if ( files.length && ! html ) { - html = files.map( ( file ) => `` ).join( '' ); + html = files + .map( ( file ) => `` ) + .join( '' ); plainText = ''; } diff --git a/packages/block-editor/src/utils/transform-styles/ast/parse.js b/packages/block-editor/src/utils/transform-styles/ast/parse.js index 7febb35619250f..d3746488fc1fe2 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/parse.js +++ b/packages/block-editor/src/utils/transform-styles/ast/parse.js @@ -67,7 +67,9 @@ export default function( css, options ) { const errorsList = []; function error( msg ) { - const err = new Error( options.source + ':' + lineno + ':' + column + ': ' + msg ); + const err = new Error( + options.source + ':' + lineno + ':' + column + ': ' + msg + ); err.reason = msg; err.filename = options.source; err.line = lineno; @@ -123,7 +125,11 @@ export default function( css, options ) { const accumulator = []; whitespace(); comments( accumulator ); - while ( css.length && css.charAt( 0 ) !== '}' && ( node = atrule() || rule() ) ) { + while ( + css.length && + css.charAt( 0 ) !== '}' && + ( node = atrule() || rule() ) + ) { if ( node !== false ) { accumulator.push( node ); comments( accumulator ); @@ -182,7 +188,10 @@ export default function( css, options ) { } let i = 2; - while ( '' !== css.charAt( i ) && ( '*' !== css.charAt( i ) || '/' !== css.charAt( i + 1 ) ) ) { + while ( + '' !== css.charAt( i ) && + ( '*' !== css.charAt( i ) || '/' !== css.charAt( i + 1 ) ) + ) { ++i; } i += 2; @@ -244,7 +253,9 @@ export default function( css, options ) { } // val - const val = match( /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/ ); + const val = match( + /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/ + ); const ret = pos( { type: 'declaration', diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js index e238cc97777f21..7c9cf56ce38631 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/compress.js @@ -118,7 +118,10 @@ Compiler.prototype.supports = function( node ) { Compiler.prototype.keyframes = function( node ) { return ( - this.emit( '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, node.position ) + + this.emit( + '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, + node.position + ) + this.emit( '{' ) + this.mapVisit( node.keyframes ) + this.emit( '}' ) @@ -186,7 +189,10 @@ Compiler.prototype.host = function( node ) { */ Compiler.prototype[ 'custom-media' ] = function( node ) { - return this.emit( '@custom-media ' + node.name + ' ' + node.media + ';', node.position ); + return this.emit( + '@custom-media ' + node.name + ' ' + node.media + ';', + node.position + ); }; /** @@ -212,5 +218,8 @@ Compiler.prototype.rule = function( node ) { */ Compiler.prototype.declaration = function( node ) { - return this.emit( node.property + ':' + node.value, node.position ) + this.emit( ';' ); + return ( + this.emit( node.property + ':' + node.value, node.position ) + + this.emit( ';' ) + ); }; diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js index ec9194af5bb2f6..ceb711a8dbc71a 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/identity.js @@ -56,7 +56,10 @@ Compiler.prototype.stylesheet = function( node ) { */ Compiler.prototype.comment = function( node ) { - return this.emit( this.indent() + '/*' + node.comment + '*/', node.position ); + return this.emit( + this.indent() + '/*' + node.comment + '*/', + node.position + ); }; /** @@ -130,7 +133,10 @@ Compiler.prototype.supports = function( node ) { Compiler.prototype.keyframes = function( node ) { return ( - this.emit( '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, node.position ) + + this.emit( + '@' + ( node.vendor || '' ) + 'keyframes ' + node.name, + node.position + ) + this.emit( ' {\n' + this.indent( 1 ) ) + this.mapVisit( node.keyframes, '\n' ) + this.emit( this.indent( -1 ) + '}' ) @@ -203,7 +209,10 @@ Compiler.prototype.host = function( node ) { */ Compiler.prototype[ 'custom-media' ] = function( node ) { - return this.emit( '@custom-media ' + node.name + ' ' + node.media + ';', node.position ); + return this.emit( + '@custom-media ' + node.name + ' ' + node.media + ';', + node.position + ); }; /** diff --git a/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js b/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js index cd702d1b1304f4..a326ce1e54b139 100644 --- a/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js +++ b/packages/block-editor/src/utils/transform-styles/ast/stringify/index.js @@ -23,7 +23,9 @@ import Identity from './identity'; export default function( node, options ) { options = options || {}; - const compiler = options.compress ? new Compressed( options ) : new Identity( options ); + const compiler = options.compress + ? new Compressed( options ) + : new Identity( options ); const code = compiler.compile( node ); return code; diff --git a/packages/block-editor/src/utils/transform-styles/test/traverse.js b/packages/block-editor/src/utils/transform-styles/test/traverse.js index 50d6d8da95bc3f..bb1be2635fe535 100644 --- a/packages/block-editor/src/utils/transform-styles/test/traverse.js +++ b/packages/block-editor/src/utils/transform-styles/test/traverse.js @@ -10,7 +10,9 @@ describe( 'CSS traverse', () => { if ( node.type === 'rule' ) { return { ...node, - selectors: node.selectors.map( ( selector ) => 'namespace ' + selector ), + selectors: node.selectors.map( + ( selector ) => 'namespace ' + selector + ), }; } diff --git a/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js b/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js index ab9c5a6aa3d67a..4e0d07e4083d74 100644 --- a/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js +++ b/packages/block-editor/src/utils/transform-styles/transforms/url-rewrite.js @@ -34,7 +34,10 @@ function isAbsolutePath( filePath ) { */ function isValidURL( meta ) { // ignore hashes or data uris - if ( meta.value.indexOf( 'data:' ) === 0 || meta.value.indexOf( '#' ) === 0 ) { + if ( + meta.value.indexOf( 'data:' ) === 0 || + meta.value.indexOf( '#' ) === 0 + ) { return false; } @@ -76,7 +79,14 @@ function processURL( baseURL ) { const URL = getResourcePath( meta.value, baseURL ); return { ...meta, - newUrl: 'url(' + meta.before + meta.quote + URL + meta.quote + meta.after + ')', + newUrl: + 'url(' + + meta.before + + meta.quote + + URL + + meta.quote + + meta.after + + ')', }; }; } diff --git a/packages/block-library/src/archives/edit.js b/packages/block-library/src/archives/edit.js index 56f86b30adb615..8223111736c633 100644 --- a/packages/block-library/src/archives/edit.js +++ b/packages/block-library/src/archives/edit.js @@ -16,17 +16,28 @@ export default function ArchivesEdit( { attributes, setAttributes } ) { setAttributes( { displayAsDropdown: ! displayAsDropdown } ) } + onChange={ () => + setAttributes( { + displayAsDropdown: ! displayAsDropdown, + } ) + } /> setAttributes( { showPostCounts: ! showPostCounts } ) } + onChange={ () => + setAttributes( { + showPostCounts: ! showPostCounts, + } ) + } /> - + ); diff --git a/packages/block-library/src/audio/deprecated.js b/packages/block-library/src/audio/deprecated.js index 04dae715be5621..075a173db44521 100644 --- a/packages/block-library/src/audio/deprecated.js +++ b/packages/block-library/src/audio/deprecated.js @@ -55,7 +55,10 @@ export default [ preload={ preload } /> { ! RichText.isEmpty( caption ) && ( - + ) }
    ); diff --git a/packages/block-library/src/audio/edit.js b/packages/block-library/src/audio/edit.js index c9a6b3ec6f4e1a..d9970ecd93dbf4 100644 --- a/packages/block-library/src/audio/edit.js +++ b/packages/block-library/src/audio/edit.js @@ -39,7 +39,12 @@ class AudioEdit extends Component { } componentDidMount() { - const { attributes, mediaUpload, noticeOperations, setAttributes } = this.props; + const { + attributes, + mediaUpload, + noticeOperations, + setAttributes, + } = this.props; const { id, src = '' } = attributes; if ( ! id && isBlobURL( src ) ) { @@ -75,7 +80,9 @@ class AudioEdit extends Component { // the editing UI. if ( newSrc !== src ) { // Check if there's an embed block that handles this URL. - const embedBlock = createUpgradedEmbedBlock( { attributes: { url: newSrc } } ); + const embedBlock = createUpgradedEmbedBlock( { + attributes: { url: newSrc }, + } ); if ( undefined !== embedBlock ) { this.props.onReplace( embedBlock ); return; @@ -92,7 +99,9 @@ class AudioEdit extends Component { getAutoplayHelp( checked ) { return checked - ? __( 'Note: Autoplaying audio may cause usability issues for some visitors.' ) + ? __( + 'Note: Autoplaying audio may cause usability issues for some visitors.' + ) : null; } @@ -156,7 +165,10 @@ class AudioEdit extends Component { value={ undefined !== preload ? preload : 'none' } // `undefined` is required for the preload attribute to be unset. onChange={ ( value ) => - setAttributes( { preload: 'none' !== value ? value : undefined } ) + setAttributes( { + preload: + 'none' !== value ? value : undefined, + } ) } options={ [ { value: 'auto', label: __( 'Auto' ) }, @@ -179,7 +191,9 @@ class AudioEdit extends Component { tagName="figcaption" placeholder={ __( 'Write captionโ€ฆ' ) } value={ caption } - onChange={ ( value ) => setAttributes( { caption: value } ) } + onChange={ ( value ) => + setAttributes( { caption: value } ) + } inlineToolbar /> ) } diff --git a/packages/block-library/src/audio/index.js b/packages/block-library/src/audio/index.js index 9e7e414f93c176..2946d5eca61bcd 100644 --- a/packages/block-library/src/audio/index.js +++ b/packages/block-library/src/audio/index.js @@ -20,7 +20,12 @@ export { metadata, name }; export const settings = { title: __( 'Audio' ), description: __( 'Embed a simple audio player.' ), - keywords: [ __( 'music' ), __( 'sound' ), __( 'podcast' ), __( 'recording' ) ], + keywords: [ + __( 'music' ), + __( 'sound' ), + __( 'podcast' ), + __( 'recording' ), + ], icon, transforms, deprecated, diff --git a/packages/block-library/src/audio/transforms.js b/packages/block-library/src/audio/transforms.js index 01396eda20dff0..3a61af6807cc51 100644 --- a/packages/block-library/src/audio/transforms.js +++ b/packages/block-library/src/audio/transforms.js @@ -9,7 +9,10 @@ const transforms = { { type: 'files', isMatch( files ) { - return files.length === 1 && files[ 0 ].type.indexOf( 'audio/' ) === 0; + return ( + files.length === 1 && + files[ 0 ].type.indexOf( 'audio/' ) === 0 + ); }, transform( files ) { const file = files[ 0 ]; diff --git a/packages/block-library/src/block/edit-panel/index.js b/packages/block-library/src/block/edit-panel/index.js index dbad57886bb5fe..4205167208cccf 100644 --- a/packages/block-library/src/block/edit-panel/index.js +++ b/packages/block-library/src/block/edit-panel/index.js @@ -57,13 +57,22 @@ class ReusableBlockEditPanel extends Component { } render() { - const { isEditing, title, isSaving, isEditDisabled, onEdit, instanceId } = this.props; + const { + isEditing, + title, + isSaving, + isEditDisabled, + onEdit, + instanceId, + } = this.props; return ( <> { ! isEditing && ! isSaving && (
    - { title } + + { title } +
    - + { __( 'Learn more about embeds' ) }
    diff --git a/packages/block-library/src/embed/embed-preview.js b/packages/block-library/src/embed/embed-preview.js index 4c1147a76925b3..db139e5292b7bd 100644 --- a/packages/block-library/src/embed/embed-preview.js +++ b/packages/block-library/src/embed/embed-preview.js @@ -75,8 +75,15 @@ class EmbedPreview extends Component { .join( '.' ); const cannotPreview = includes( HOSTS_NO_PREVIEWS, parsedHostBaseUrl ); // translators: %s: host providing embed content e.g: www.youtube.com - const iframeTitle = sprintf( __( 'Embedded content from %s' ), parsedHostBaseUrl ); - const sandboxClassnames = classnames( type, className, 'wp-block-embed__wrapper' ); + const iframeTitle = sprintf( + __( 'Embedded content from %s' ), + parsedHostBaseUrl + ); + const sandboxClassnames = classnames( + type, + className, + 'wp-block-embed__wrapper' + ); // Disabled because the overlay div doesn't actually have a role or functionality // as far as the user is concerned. We're just catching the first click so that @@ -111,14 +118,19 @@ class EmbedPreview extends Component { } ) } > { cannotPreview ? ( - } label={ label }> + } + label={ label } + >

    { url }

    { /* translators: %s: host providing embed content e.g: www.youtube.com */ sprintf( - __( "Embedded content from %s can't be previewed in the editor." ), + __( + "Embedded content from %s can't be previewed in the editor." + ), parsedHostBaseUrl ) }

    diff --git a/packages/block-library/src/embed/index.js b/packages/block-library/src/embed/index.js index 79c57d047ac110..05facf83fd1b9c 100644 --- a/packages/block-library/src/embed/index.js +++ b/packages/block-library/src/embed/index.js @@ -26,7 +26,8 @@ export const settings = getEmbedBlockSettings( { { type: 'raw', isMatch: ( node ) => - node.nodeName === 'P' && /^\s*(https?:\/\/\S+)\s*$/i.test( node.textContent ), + node.nodeName === 'P' && + /^\s*(https?:\/\/\S+)\s*$/i.test( node.textContent ), transform: ( node ) => { return createBlock( 'core/embed', { url: node.textContent.trim(), diff --git a/packages/block-library/src/embed/settings.js b/packages/block-library/src/embed/settings.js index e87977fb491003..20034c6d617a58 100644 --- a/packages/block-library/src/embed/settings.js +++ b/packages/block-library/src/embed/settings.js @@ -79,21 +79,31 @@ export function getEmbedBlockSettings( { getThemeSupports, } = core; const preview = undefined !== url && getEmbedPreview( url ); - const previewIsFallback = undefined !== url && isPreviewEmbedFallback( url ); - const fetching = undefined !== url && isRequestingEmbedPreview( url ); + const previewIsFallback = + undefined !== url && isPreviewEmbedFallback( url ); + const fetching = + undefined !== url && isRequestingEmbedPreview( url ); const themeSupports = getThemeSupports(); // The external oEmbed provider does not exist. We got no type info and no html. - const badEmbedProvider = !! preview && undefined === preview.type && false === preview.html; + const badEmbedProvider = + !! preview && + undefined === preview.type && + false === preview.html; // Some WordPress URLs that can't be embedded will cause the API to return // a valid JSON response with no HTML and `data.status` set to 404, rather // than generating a fallback response as other embeds do. - const wordpressCantEmbed = !! preview && preview.data && preview.data.status === 404; - const validPreview = !! preview && ! badEmbedProvider && ! wordpressCantEmbed; - const cannotEmbed = undefined !== url && ( ! validPreview || previewIsFallback ); + const wordpressCantEmbed = + !! preview && preview.data && preview.data.status === 404; + const validPreview = + !! preview && ! badEmbedProvider && ! wordpressCantEmbed; + const cannotEmbed = + undefined !== url && + ( ! validPreview || previewIsFallback ); return { preview: validPreview ? preview : undefined, fetching, - themeSupportsResponsive: themeSupports[ 'responsive-embeds' ], + themeSupportsResponsive: + themeSupports[ 'responsive-embeds' ], cannotEmbed, }; } ), @@ -101,7 +111,9 @@ export function getEmbedBlockSettings( { const { url } = ownProps.attributes; const coreData = dispatch( 'core/data' ); const tryAgain = () => { - coreData.invalidateResolution( 'core', 'getEmbedPreview', [ url ] ); + coreData.invalidateResolution( 'core', 'getEmbedPreview', [ + url, + ] ); }; return { tryAgain, @@ -127,7 +139,10 @@ export function getEmbedBlockSettings( { { `\n${ url }\n` /* URL needs to be on its own line. */ }
    { ! RichText.isEmpty( caption ) && ( - + ) } ); @@ -152,7 +167,10 @@ export function getEmbedBlockSettings( {
    { `\n${ url }\n` /* URL needs to be on its own line. */ } { ! RichText.isEmpty( caption ) && ( - + ) }
    ); diff --git a/packages/block-library/src/embed/test/index.js b/packages/block-library/src/embed/test/index.js index 26737576cd86c7..2f1e8546b770f7 100644 --- a/packages/block-library/src/embed/test/index.js +++ b/packages/block-library/src/embed/test/index.js @@ -48,14 +48,20 @@ describe( 'core/embed', () => { const html = ''; const expected = 'lovely'; expect( - getClassNames( html, 'lovely wp-embed-aspect-16-9 wp-has-aspect-ratio', false ) + getClassNames( + html, + 'lovely wp-embed-aspect-16-9 wp-has-aspect-ratio', + false + ) ).toEqual( expected ); } ); test( 'createUpgradedEmbedBlock bails early when block type does not exist', () => { const youtubeURL = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'; - expect( createUpgradedEmbedBlock( { attributes: { url: youtubeURL } }, {} ) ).toBeUndefined(); + expect( + createUpgradedEmbedBlock( { attributes: { url: youtubeURL } }, {} ) + ).toBeUndefined(); } ); test( 'createUpgradedEmbedBlock returns a YouTube embed block when given a YouTube URL', () => { @@ -66,7 +72,10 @@ describe( 'core/embed', () => { category: 'embed', } ); - const result = createUpgradedEmbedBlock( { attributes: { url: youtubeURL } }, {} ); + const result = createUpgradedEmbedBlock( + { attributes: { url: youtubeURL } }, + {} + ); unregisterBlockType( 'core-embed/youtube' ); diff --git a/packages/block-library/src/embed/util.js b/packages/block-library/src/embed/util.js index 86c631880333ae..071eee0980b6fe 100644 --- a/packages/block-library/src/embed/util.js +++ b/packages/block-library/src/embed/util.js @@ -2,7 +2,11 @@ * Internal dependencies */ import { common, others } from './core-embeds'; -import { DEFAULT_EMBED_BLOCK, WORDPRESS_EMBED_BLOCK, ASPECT_RATIOS } from './constants'; +import { + DEFAULT_EMBED_BLOCK, + WORDPRESS_EMBED_BLOCK, + ASPECT_RATIOS, +} from './constants'; /** * External dependencies @@ -92,7 +96,10 @@ export const createUpgradedEmbedBlock = ( props, attributesFromPreview ) => { // WordPress blocks can work on multiple sites, and so don't have patterns, // so if we're in a WordPress block, assume the user has chosen it for a WordPress URL. - if ( WORDPRESS_EMBED_BLOCK !== name && DEFAULT_EMBED_BLOCK !== matchingBlock ) { + if ( + WORDPRESS_EMBED_BLOCK !== name && + DEFAULT_EMBED_BLOCK !== matchingBlock + ) { // At this point, we have discovered a more suitable block for this url, so transform it. if ( name !== matchingBlock ) { return createBlock( matchingBlock, { url } ); @@ -130,13 +137,21 @@ export const createUpgradedEmbedBlock = ( props, attributesFromPreview ) => { * @param {boolean} allowResponsive If the responsive class names should be added, or removed. * @return {string} Deduped class names. */ -export function getClassNames( html, existingClassNames = '', allowResponsive = true ) { +export function getClassNames( + html, + existingClassNames = '', + allowResponsive = true +) { if ( ! allowResponsive ) { // Remove all of the aspect ratio related class names. const aspectRatioClassNames = { 'wp-has-aspect-ratio': false, }; - for ( let ratioIndex = 0; ratioIndex < ASPECT_RATIOS.length; ratioIndex++ ) { + for ( + let ratioIndex = 0; + ratioIndex < ASPECT_RATIOS.length; + ratioIndex++ + ) { const aspectRatioToRemove = ASPECT_RATIOS[ ratioIndex ]; aspectRatioClassNames[ aspectRatioToRemove.className ] = false; } @@ -151,7 +166,11 @@ export function getClassNames( html, existingClassNames = '', allowResponsive = if ( iframe && iframe.height && iframe.width ) { const aspectRatio = ( iframe.width / iframe.height ).toFixed( 2 ); // Given the actual aspect ratio, find the widest ratio to support it. - for ( let ratioIndex = 0; ratioIndex < ASPECT_RATIOS.length; ratioIndex++ ) { + for ( + let ratioIndex = 0; + ratioIndex < ASPECT_RATIOS.length; + ratioIndex++ + ) { const potentialRatio = ASPECT_RATIOS[ ratioIndex ]; if ( aspectRatio >= potentialRatio.ratio ) { return classnames( existingClassNames, { @@ -174,7 +193,9 @@ export function getClassNames( html, existingClassNames = '', allowResponsive = */ export function fallback( url, onReplace ) { const link = { url }; - onReplace( createBlock( 'core/paragraph', { content: renderToString( link ) } ) ); + onReplace( + createBlock( 'core/paragraph', { content: renderToString( link ) } ) + ); } /*** @@ -188,7 +209,13 @@ export function fallback( url, onReplace ) { * @return {Object} Attributes and values. */ export const getAttributesFromPreview = memoize( - ( preview, title, currentClassNames, isResponsive, allowResponsive = true ) => { + ( + preview, + title, + currentClassNames, + isResponsive, + allowResponsive = true + ) => { if ( ! preview ) { return {}; } @@ -199,7 +226,9 @@ export const getAttributesFromPreview = memoize( // If we got a provider name from the API, use it for the slug, otherwise we use the title, // because not all embed code gives us a provider name. const { html, provider_name: providerName } = preview; - const providerNameSlug = kebabCase( toLower( '' !== providerName ? providerName : title ) ); + const providerNameSlug = kebabCase( + toLower( '' !== providerName ? providerName : title ) + ); if ( isFromWordPress( html ) ) { type = 'wp-embed'; diff --git a/packages/block-library/src/embed/wp-embed-preview.js b/packages/block-library/src/embed/wp-embed-preview.js index 2e52a84438fe29..ccfb0449819b85 100644 --- a/packages/block-library/src/embed/wp-embed-preview.js +++ b/packages/block-library/src/embed/wp-embed-preview.js @@ -25,7 +25,10 @@ class WpEmbedPreview extends Component { checkFocus() { const { activeElement } = document; - if ( activeElement.tagName !== 'IFRAME' || activeElement.parentNode !== this.node.current ) { + if ( + activeElement.tagName !== 'IFRAME' || + activeElement.parentNode !== this.node.current + ) { return; } diff --git a/packages/block-library/src/file/edit.js b/packages/block-library/src/file/edit.js index 1837a002e60636..49b0b562c17a07 100644 --- a/packages/block-library/src/file/edit.js +++ b/packages/block-library/src/file/edit.js @@ -33,9 +33,13 @@ class FileEdit extends Component { this.onSelectFile = this.onSelectFile.bind( this ); this.confirmCopyURL = this.confirmCopyURL.bind( this ); this.resetCopyConfirmation = this.resetCopyConfirmation.bind( this ); - this.changeLinkDestinationOption = this.changeLinkDestinationOption.bind( this ); + this.changeLinkDestinationOption = this.changeLinkDestinationOption.bind( + this + ); this.changeOpenInNewWindow = this.changeOpenInNewWindow.bind( this ); - this.changeShowDownloadButton = this.changeShowDownloadButton.bind( this ); + this.changeShowDownloadButton = this.changeShowDownloadButton.bind( + this + ); this.onUploadError = this.onUploadError.bind( this ); this.state = { @@ -45,7 +49,12 @@ class FileEdit extends Component { } componentDidMount() { - const { attributes, mediaUpload, noticeOperations, setAttributes } = this.props; + const { + attributes, + mediaUpload, + noticeOperations, + setAttributes, + } = this.props; const { downloadButtonText, href } = attributes; // Upload a file drag-and-dropped into the editor @@ -120,7 +129,14 @@ class FileEdit extends Component { } render() { - const { className, isSelected, attributes, setAttributes, noticeUI, media } = this.props; + const { + className, + isSelected, + attributes, + setAttributes, + noticeUI, + media, + } = this.props; const { fileName, href, @@ -138,7 +154,9 @@ class FileEdit extends Component { icon={ } labels={ { title: __( 'File' ), - instructions: __( 'Upload a file or pick one from your media library.' ), + instructions: __( + 'Upload a file or pick one from your media library.' + ), } } onSelect={ this.onSelectFile } notices={ noticeUI } @@ -159,7 +177,8 @@ class FileEdit extends Component { { ...{ openInNewWindow: !! textLinkTarget, showDownloadButton, - changeLinkDestinationOption: this.changeLinkDestinationOption, + changeLinkDestinationOption: this + .changeLinkDestinationOption, changeOpenInNewWindow: this.changeOpenInNewWindow, changeShowDownloadButton: this.changeShowDownloadButton, } } @@ -174,7 +193,12 @@ class FileEdit extends Component { { ( { className: animateClassName } ) => ( -
    +
    setAttributes( { fileName: text } ) } + onChange={ ( text ) => + setAttributes( { fileName: text } ) + } />
    { showDownloadButton && ( -
    +
    { /* Using RichText here instead of PlainText so that it can be styled like a button */ } setAttributes( { downloadButtonText: text } ) } + onChange={ ( text ) => + setAttributes( { + downloadButtonText: text, + } ) + } />
    ) } @@ -203,12 +239,16 @@ class FileEdit extends Component { - { showCopyConfirmation ? __( 'Copied!' ) : __( 'Copy URL' ) } + { showCopyConfirmation + ? __( 'Copied!' ) + : __( 'Copy URL' ) } ) }
    diff --git a/packages/block-library/src/file/save.js b/packages/block-library/src/file/save.js index 4755b99ae4bee2..25102dfd0f92d0 100644 --- a/packages/block-library/src/file/save.js +++ b/packages/block-library/src/file/save.js @@ -26,7 +26,11 @@ export default function save( { attributes } ) { ) } { showDownloadButton && ( - + ) } diff --git a/packages/block-library/src/gallery/deprecated.js b/packages/block-library/src/gallery/deprecated.js index 6a6ba846540423..36196e6d6427dc 100644 --- a/packages/block-library/src/gallery/deprecated.js +++ b/packages/block-library/src/gallery/deprecated.js @@ -102,7 +102,11 @@ const deprecated = [ } = attributes; return ( -
    +
      { images.map( ( image ) => { let href; @@ -123,15 +127,28 @@ const deprecated = [ data-id={ image.id } data-full-url={ image.fullUrl } data-link={ image.link } - className={ image.id ? `wp-image-${ image.id }` : null } + className={ + image.id + ? `wp-image-${ image.id }` + : null + } /> ); return ( -
    • +
    • - { href ? { img } : img } - { ! RichText.isEmpty( image.caption ) && ( + { href ? ( + { img } + ) : ( + img + ) } + { ! RichText.isEmpty( + image.caption + ) && ( +
        { images.map( ( image ) => { let href; @@ -242,17 +263,30 @@ const deprecated = [ data-id={ image.id } data-full-url={ image.fullUrl } data-link={ image.link } - className={ image.id ? `wp-image-${ image.id }` : null } + className={ + image.id ? `wp-image-${ image.id }` : null + } /> ); return ( -
      • +
      • - { href ? { img } : img } - { image.caption && image.caption.length > 0 && ( - + { href ? ( + { img } + ) : ( + img ) } + { image.caption && + image.caption.length > 0 && ( + + ) }
      • ); @@ -345,7 +379,11 @@ const deprecated = [ linkTo, } = attributes; return ( -
          +
            { images.map( ( image ) => { let href; @@ -364,17 +402,30 @@ const deprecated = [ alt={ image.alt } data-id={ image.id } data-link={ image.link } - className={ image.id ? `wp-image-${ image.id }` : null } + className={ + image.id ? `wp-image-${ image.id }` : null + } /> ); return ( -
          • +
          • - { href ? { img } : img } - { image.caption && image.caption.length > 0 && ( - + { href ? ( + { img } + ) : ( + img ) } + { image.caption && + image.caption.length > 0 && ( + + ) }
          • ); @@ -389,7 +440,8 @@ const deprecated = [ type: 'array', default: [], source: 'query', - selector: 'div.wp-block-gallery figure.blocks-gallery-image img', + selector: + 'div.wp-block-gallery figure.blocks-gallery-image img', query: { url: { source: 'attribute', @@ -451,10 +503,19 @@ const deprecated = [ break; } - const img = {; + const img = ( + { + ); return ( -
            +
            { href ? { img } : img }
            ); diff --git a/packages/block-library/src/gallery/edit.js b/packages/block-library/src/gallery/edit.js index 6ff5f20e92eb78..0eda4370e76edd 100644 --- a/packages/block-library/src/gallery/edit.js +++ b/packages/block-library/src/gallery/edit.js @@ -1,7 +1,17 @@ /** * 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 @@ -37,7 +47,9 @@ const linkOptions = [ const ALLOWED_MEDIA_TYPES = [ 'image' ]; const PLACEHOLDER_TEXT = Platform.select( { - web: __( 'Drag images, upload new ones or select files from your library.' ), + web: __( + 'Drag images, upload new ones or select files from your library.' + ), native: __( 'ADD MEDIA' ), } ); @@ -133,7 +145,10 @@ class GalleryEdit extends Component { onRemoveImage( index ) { return () => { - const images = filter( this.props.attributes.images, ( img, i ) => index !== i ); + const images = filter( + this.props.attributes.images, + ( img, i ) => index !== i + ); const { columns } = this.props.attributes; this.setState( { selectedImage: null } ); this.setAttributes( { @@ -146,7 +161,9 @@ class GalleryEdit extends Component { selectCaption( newImage, images, attachmentCaptions ) { const currentImage = find( images, { id: newImage.id } ); - const currentImageCaption = currentImage ? currentImage.caption : newImage.caption; + const currentImageCaption = currentImage + ? currentImage.caption + : newImage.caption; if ( ! attachmentCaptions ) { return currentImageCaption; @@ -174,7 +191,11 @@ class GalleryEdit extends Component { this.setAttributes( { images: newImages.map( ( newImage ) => ( { ...pickRelevantMediaFiles( newImage, sizeSlug ), - caption: this.selectCaption( newImage, images, attachmentCaptions ), + caption: this.selectCaption( + newImage, + images, + attachmentCaptions + ), } ) ), columns: columns ? Math.min( newImages.length, columns ) : columns, } ); @@ -199,7 +220,9 @@ class GalleryEdit extends Component { } getImageCropHelp( checked ) { - return checked ? __( 'Thumbnails are cropped to align.' ) : __( 'Thumbnails are not cropped.' ); + return checked + ? __( 'Thumbnails are cropped to align.' ) + : __( 'Thumbnails are not cropped.' ); } onFocusGalleryCaption() { @@ -231,7 +254,9 @@ 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 } ) ); } @@ -246,7 +271,10 @@ class GalleryEdit extends Component { if ( ! image.id ) { return image; } - const url = get( resizedImages, [ parseInt( image.id, 10 ), sizeSlug ] ); + const url = get( resizedImages, [ + parseInt( image.id, 10 ), + sizeSlug, + ] ); return { ...image, ...( url && { url } ), @@ -325,7 +353,8 @@ class GalleryEdit extends Component { } const imageSizeOptions = this.getImagesSizeOptions(); - const shouldShowSizeOptions = hasImages && ! isEmpty( imageSizeOptions ); + const shouldShowSizeOptions = + hasImages && ! isEmpty( imageSizeOptions ); // This is needed to fix a separator fence-post issue on mobile. const mobileLinkToProps = shouldShowSizeOptions ? MOBILE_CONTROL_PROPS @@ -406,7 +435,11 @@ export default compose( [ const sizes = reduce( imageSizes, ( currentSizes, size ) => { - const defaultUrl = get( image, [ 'sizes', size.slug, 'url' ] ); + const defaultUrl = get( image, [ + 'sizes', + size.slug, + 'url', + ] ); const mediaDetailsUrl = get( image, [ 'media_details', 'sizes', diff --git a/packages/block-library/src/gallery/gallery-image.js b/packages/block-library/src/gallery/gallery-image.js index 6aa51e5233b43f..089141fb5e2c66 100644 --- a/packages/block-library/src/gallery/gallery-image.js +++ b/packages/block-library/src/gallery/gallery-image.js @@ -84,7 +84,11 @@ class GalleryImage extends Component { // unselect the caption so when the user selects other image and comeback // the caption is not immediately selected - if ( this.state.captionSelected && ! isSelected && prevProps.isSelected ) { + if ( + this.state.captionSelected && + ! isSelected && + prevProps.isSelected + ) { this.setState( { captionSelected: false, } ); @@ -179,10 +183,14 @@ class GalleryImage extends Component { { ( isSelected || caption ) && ( setAttributes( { caption: newCaption } ) } + onChange={ ( newCaption ) => + setAttributes( { caption: newCaption } ) + } unstableOnFocus={ this.onSelectCaption } inlineToolbar /> diff --git a/packages/block-library/src/gallery/gallery-image.native.js b/packages/block-library/src/gallery/gallery-image.native.js index 38031aabe1db30..337f2bdc4bb73a 100644 --- a/packages/block-library/src/gallery/gallery-image.native.js +++ b/packages/block-library/src/gallery/gallery-image.native.js @@ -1,7 +1,14 @@ /** * External dependencies */ -import { Image, StyleSheet, View, ScrollView, Text, TouchableWithoutFeedback } from 'react-native'; +import { + Image, + StyleSheet, + View, + ScrollView, + Text, + TouchableWithoutFeedback, +} from 'react-native'; import { requestImageFailedRetryDialog, requestImageUploadCancelDialog, @@ -26,7 +33,9 @@ import style from './gallery-image-style.scss'; const { compose } = StyleSheet; -const separatorStyle = compose( style.separator, { borderRightWidth: StyleSheet.hairlineWidth } ); +const separatorStyle = compose( style.separator, { + borderRightWidth: StyleSheet.hairlineWidth, +} ); const buttonStyle = compose( style.button, { aspectRatio: 1 } ); const removeButtonStyle = compose( style.removeButton, { aspectRatio: 1 } ); const ICON_SIZE_ARROW = 15; @@ -43,8 +52,12 @@ class GalleryImage extends Component { this.bindContainer = this.bindContainer.bind( this ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( this ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( this ); + this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( + this + ); + this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( + this + ); this.renderContent = this.renderContent.bind( this ); this.state = { @@ -114,7 +127,11 @@ class GalleryImage extends Component { // unselect the caption so when the user selects other image and comeback // the caption is not immediately selected - if ( this.state.captionSelected && ! isSelected && prevProps.isSelected ) { + if ( + this.state.captionSelected && + ! isSelected && + prevProps.isSelected + ) { this.setState( { captionSelected: false, } ); @@ -171,7 +188,10 @@ class GalleryImage extends Component { 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, @@ -179,7 +199,8 @@ class GalleryImage extends Component { ); const shouldShowCaptionEditable = ! isUploadFailed && isSelected; - const shouldShowCaptionExpanded = ! isUploadFailed && ! isSelected && !! caption; + const shouldShowCaptionExpanded = + ! isUploadFailed && ! isSelected && !! caption; const captionContainerStyle = shouldShowCaptionExpanded ? style.captionExpandedContainer @@ -201,9 +222,14 @@ class GalleryImage extends Component { { isUploadFailed && ( - + - { retryMessage } + + { retryMessage } + ) } @@ -216,8 +242,14 @@ class GalleryImage extends Component { style={ buttonStyle } icon="arrow-left-alt" iconSize={ ICON_SIZE_ARROW } - onClick={ isFirstItem ? undefined : onMoveBackward } - accessibilityLabel={ __( 'Move Image Backward' ) } + onClick={ + isFirstItem + ? undefined + : onMoveBackward + } + accessibilityLabel={ __( + 'Move Image Backward' + ) } aria-disabled={ isFirstItem } disabled={ ! isSelected } /> @@ -226,8 +258,14 @@ class GalleryImage extends Component { style={ buttonStyle } icon="arrow-right-alt" iconSize={ ICON_SIZE_ARROW } - onClick={ isLastItem ? undefined : onMoveForward } - accessibilityLabel={ __( 'Move Image Forward' ) } + onClick={ + isLastItem + ? undefined + : onMoveForward + } + accessibilityLabel={ __( + 'Move Image Forward' + ) } aria-disabled={ isLastItem } disabled={ ! isSelected } /> @@ -237,21 +275,33 @@ class GalleryImage extends Component { icon="no-alt" iconSize={ ICON_SIZE_REMOVE } onClick={ onRemove } - accessibilityLabel={ __( 'Remove Image' ) } + accessibilityLabel={ __( + 'Remove Image' + ) } disabled={ ! isSelected } /> ) } - { ( shouldShowCaptionEditable || shouldShowCaptionExpanded ) && ( + { ( shouldShowCaptionEditable || + shouldShowCaptionExpanded ) && ( - + @@ -266,7 +316,12 @@ class GalleryImage extends Component { } render() { - const { id, onRemove, getStylesFromColorScheme, isSelected } = this.props; + const { + id, + onRemove, + getStylesFromColorScheme, + isSelected, + } = this.props; const containerStyle = getStylesFromColorScheme( style.galleryImageContainer, @@ -284,8 +339,12 @@ class GalleryImage extends Component { diff --git a/packages/block-library/src/gallery/gallery.js b/packages/block-library/src/gallery/gallery.js index a077262246ef04..5f910ca8f07d49 100644 --- a/packages/block-library/src/gallery/gallery.js +++ b/packages/block-library/src/gallery/gallery.js @@ -61,19 +61,26 @@ export const Gallery = ( props ) => { ); return ( -
          • +
          • onSetImageAttributes( index, attrs ) } + setAttributes={ ( attrs ) => + onSetImageAttributes( index, attrs ) + } caption={ img.caption } aria-label={ ariaLabel } /> diff --git a/packages/block-library/src/gallery/gallery.native.js b/packages/block-library/src/gallery/gallery.native.js index 2922c9f155a22f..2ff4f0d4707987 100644 --- a/packages/block-library/src/gallery/gallery.native.js +++ b/packages/block-library/src/gallery/gallery.native.js @@ -45,7 +45,11 @@ export const Gallery = ( props ) => { onFocus, } = props; - const { columns = defaultColumnsNumber( attributes ), imageCrop, images } = attributes; + const { + columns = defaultColumnsNumber( attributes ), + imageCrop, + images, + } = attributes; // limit displayed columns when isNarrow is true (i.e. when viewport width is // less than "small", where small = 600) @@ -75,7 +79,11 @@ export const Gallery = ( props ) => { { images.map( ( img, index ) => { /* translators: %1$d is the order number of the image, %2$d is the total number of images. */ @@ -101,7 +109,9 @@ export const Gallery = ( props ) => { onRemove={ onRemoveImage( index ) } onSelect={ selectImage( index ) } onSelectBlock={ onFocus } - setAttributes={ ( attrs ) => onSetImageAttributes( index, attrs ) } + setAttributes={ ( attrs ) => + onSetImageAttributes( index, attrs ) + } caption={ img.caption } aria-label={ ariaLabel } /> diff --git a/packages/block-library/src/gallery/icons.js b/packages/block-library/src/gallery/icons.js index 72efc9dbf14326..09d906f5939325 100644 --- a/packages/block-library/src/gallery/icons.js +++ b/packages/block-library/src/gallery/icons.js @@ -4,13 +4,23 @@ import { Path, SVG } from '@wordpress/components'; export const leftArrow = ( - + ); export const rightArrow = ( - + ); diff --git a/packages/block-library/src/gallery/index.js b/packages/block-library/src/gallery/index.js index c40d96c628f6b9..66c2644a0e40b1 100644 --- a/packages/block-library/src/gallery/index.js +++ b/packages/block-library/src/gallery/index.js @@ -26,8 +26,14 @@ export const settings = { attributes: { columns: 2, images: [ - { url: 'https://s.w.org/images/core/5.3/Glacial_lakes%2C_Bhutan.jpg' }, - { url: 'https://s.w.org/images/core/5.3/Sediment_off_the_Yucatan_Peninsula.jpg' }, + { + url: + 'https://s.w.org/images/core/5.3/Glacial_lakes%2C_Bhutan.jpg', + }, + { + url: + 'https://s.w.org/images/core/5.3/Sediment_off_the_Yucatan_Peninsula.jpg', + }, ], }, }, diff --git a/packages/block-library/src/gallery/save.js b/packages/block-library/src/gallery/save.js index f699eddf90b066..aef56dc6adb1d5 100644 --- a/packages/block-library/src/gallery/save.js +++ b/packages/block-library/src/gallery/save.js @@ -18,7 +18,11 @@ export default function save( { attributes } ) { } = attributes; return ( -
            +
              { images.map( ( image ) => { let href; @@ -39,12 +43,17 @@ export default function save( { attributes } ) { data-id={ image.id } data-full-url={ image.fullUrl } data-link={ image.link } - className={ image.id ? `wp-image-${ image.id }` : null } + className={ + image.id ? `wp-image-${ image.id }` : null + } /> ); return ( -
            • +
            • { href ? { img } : img } { ! RichText.isEmpty( image.caption ) && ( diff --git a/packages/block-library/src/gallery/shared-icon.native.js b/packages/block-library/src/gallery/shared-icon.native.js index c9faf935be6d49..16e89f5a95ac43 100644 --- a/packages/block-library/src/gallery/shared-icon.native.js +++ b/packages/block-library/src/gallery/shared-icon.native.js @@ -10,9 +10,14 @@ import { gallery as icon } from '@wordpress/icons'; */ import styles from './styles.scss'; -const IconWithColorScheme = withPreferredColorScheme( ( { getStylesFromColorScheme } ) => { - const colorSchemeStyles = getStylesFromColorScheme( styles.icon, styles.iconDark ); - return ; -} ); +const IconWithColorScheme = withPreferredColorScheme( + ( { getStylesFromColorScheme } ) => { + const colorSchemeStyles = getStylesFromColorScheme( + styles.icon, + styles.iconDark + ); + return ; + } +); export const sharedIcon = ; diff --git a/packages/block-library/src/gallery/tiles.native.js b/packages/block-library/src/gallery/tiles.native.js index b08f54052745ac..c5ce52b4ba24ba 100644 --- a/packages/block-library/src/gallery/tiles.native.js +++ b/packages/block-library/src/gallery/tiles.native.js @@ -47,7 +47,8 @@ function Tiles( props ) { */ const row = Math.floor( index / columns ); - const rowLength = row === lastRow ? ( lastTile % columns ) + 1 : columns; + const rowLength = + row === lastRow ? ( lastTile % columns ) + 1 : columns; const indexInRow = index % columns; return ( @@ -57,7 +58,8 @@ function Tiles( props ) { { width: `${ 100 / rowLength }%`, paddingLeft: spacing * ( indexInRow / rowLength ), - paddingRight: spacing * ( 1 - ( indexInRow + 1 ) / rowLength ), + paddingRight: + spacing * ( 1 - ( indexInRow + 1 ) / rowLength ), paddingTop: row === 0 ? 0 : spacing / 2, paddingBottom: row === lastRow ? 0 : spacing / 2, }, diff --git a/packages/block-library/src/gallery/transforms.js b/packages/block-library/src/gallery/transforms.js index 0abdced52fd59b..05220f5c0df887 100644 --- a/packages/block-library/src/gallery/transforms.js +++ b/packages/block-library/src/gallery/transforms.js @@ -32,18 +32,24 @@ const transforms = { // Init the align and size from the first item which may be either the placeholder or an image. let { align, sizeSlug } = attributes[ 0 ]; // Loop through all the images and check if they have the same align and size. - align = every( attributes, [ 'align', align ] ) ? align : undefined; - sizeSlug = every( attributes, [ 'sizeSlug', sizeSlug ] ) ? sizeSlug : undefined; + align = every( attributes, [ 'align', align ] ) + ? align + : undefined; + sizeSlug = every( attributes, [ 'sizeSlug', sizeSlug ] ) + ? sizeSlug + : undefined; const validImages = filter( attributes, ( { url } ) => url ); return createBlock( 'core/gallery', { - images: validImages.map( ( { id, url, alt, caption } ) => ( { - id, - url, - alt, - caption, - } ) ), + images: validImages.map( + ( { id, url, alt, caption } ) => ( { + id, + url, + alt, + caption, + } ) + ), ids: validImages.map( ( { id } ) => id ), align, sizeSlug, @@ -87,7 +93,11 @@ const transforms = { type: 'files', isMatch( files ) { return ( - files.length !== 1 && every( files, ( file ) => file.type.indexOf( 'image/' ) === 0 ) + files.length !== 1 && + every( + files, + ( file ) => file.type.indexOf( 'image/' ) === 0 + ) ); }, transform( files ) { diff --git a/packages/block-library/src/group/deprecated.js b/packages/block-library/src/group/deprecated.js index ced2cfca58b993..39c69f21633652 100644 --- a/packages/block-library/src/group/deprecated.js +++ b/packages/block-library/src/group/deprecated.js @@ -27,13 +27,18 @@ const deprecated = [ save( { attributes } ) { const { backgroundColor, customBackgroundColor } = attributes; - const backgroundClass = getColorClassName( 'background-color', backgroundColor ); + const backgroundClass = getColorClassName( + 'background-color', + backgroundColor + ); const className = classnames( backgroundClass, { 'has-background': backgroundColor || customBackgroundColor, } ); const styles = { - backgroundColor: backgroundClass ? undefined : customBackgroundColor, + backgroundColor: backgroundClass + ? undefined + : customBackgroundColor, }; return ( diff --git a/packages/block-library/src/group/edit.js b/packages/block-library/src/group/edit.js index acd2f7a4a50923..6d3ec0111bb12b 100644 --- a/packages/block-library/src/group/edit.js +++ b/packages/block-library/src/group/edit.js @@ -8,7 +8,11 @@ import { useRef } from '@wordpress/element'; function GroupEdit( { hasInnerBlocks } ) { const ref = useRef(); - const { TextColor, BackgroundColor, InspectorControlsColorPanel } = __experimentalUseColors( + const { + TextColor, + BackgroundColor, + InspectorControlsColorPanel, + } = __experimentalUseColors( [ { name: 'textColor', property: 'color' }, { name: 'backgroundColor', className: 'has-background' }, @@ -26,7 +30,12 @@ function GroupEdit( { hasInnerBlocks } ) {
              - +
              diff --git a/packages/block-library/src/group/edit.native.js b/packages/block-library/src/group/edit.native.js index 9c356378a7bbff..a1b261f3340c6c 100644 --- a/packages/block-library/src/group/edit.native.js +++ b/packages/block-library/src/group/edit.native.js @@ -19,14 +19,24 @@ function GroupEdit( { hasInnerBlocks, isSelected, getStylesFromColorScheme } ) { return ( ); } - return ; + return ( + + ); } export default compose( [ diff --git a/packages/block-library/src/group/icon.js b/packages/block-library/src/group/icon.js index 94d19632e74f08..8ec4a84f778a20 100644 --- a/packages/block-library/src/group/icon.js +++ b/packages/block-library/src/group/icon.js @@ -4,7 +4,12 @@ import { Path, SVG } from '@wordpress/components'; export default ( - + { - const { align } = block.attributes; - return alignments.indexOf( align ) > alignments.indexOf( accumulator ) - ? align - : accumulator; - }, undefined ); + const widestAlignment = blocks.reduce( + ( accumulator, block ) => { + const { align } = block.attributes; + return alignments.indexOf( align ) > + alignments.indexOf( accumulator ) + ? align + : accumulator; + }, + undefined + ); // Clone the Blocks to be Grouped // Failing to create new block references causes the original blocks @@ -111,7 +123,11 @@ export const settings = { // are removed both from their original location and within the // new group block. const groupInnerBlocks = blocks.map( ( block ) => { - return createBlock( block.name, block.attributes, block.innerBlocks ); + return createBlock( + block.name, + block.attributes, + block.innerBlocks + ); } ); return createBlock( diff --git a/packages/block-library/src/group/save.js b/packages/block-library/src/group/save.js index f37cb085659f31..9125c0563168f8 100644 --- a/packages/block-library/src/group/save.js +++ b/packages/block-library/src/group/save.js @@ -9,9 +9,17 @@ import classnames from 'classnames'; import { InnerBlocks, getColorClassName } from '@wordpress/block-editor'; export default function save( { attributes } ) { - const { backgroundColor, customBackgroundColor, textColor, customTextColor } = attributes; + const { + backgroundColor, + customBackgroundColor, + textColor, + customTextColor, + } = attributes; - const backgroundClass = getColorClassName( 'background-color', backgroundColor ); + const backgroundClass = getColorClassName( + 'background-color', + backgroundColor + ); const textClass = getColorClassName( 'color', textColor ); const className = classnames( backgroundClass, { 'has-text-color': textColor || customTextColor, diff --git a/packages/block-library/src/heading/deprecated.js b/packages/block-library/src/heading/deprecated.js index d7d2a9fe30de4a..fffa0f9b4e7976 100644 --- a/packages/block-library/src/heading/deprecated.js +++ b/packages/block-library/src/heading/deprecated.js @@ -42,7 +42,13 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { align, content, customTextColor, level, textColor } = attributes; + const { + align, + content, + customTextColor, + level, + textColor, + } = attributes; const tagName = 'h' + level; const textClass = getColorClassName( 'color', textColor ); @@ -69,7 +75,13 @@ const deprecated = [ supports: blockSupports, attributes: blockAttributes, save( { attributes } ) { - const { align, level, content, textColor, customTextColor } = attributes; + const { + align, + level, + content, + textColor, + customTextColor, + } = attributes; const tagName = 'h' + level; const textClass = getColorClassName( 'color', textColor ); diff --git a/packages/block-library/src/heading/edit.js b/packages/block-library/src/heading/edit.js index f836f2c0e53509..c1811738ea2e72 100644 --- a/packages/block-library/src/heading/edit.js +++ b/packages/block-library/src/heading/edit.js @@ -23,7 +23,13 @@ import { } from '@wordpress/block-editor'; import { useRef } from '@wordpress/element'; -function HeadingEdit( { attributes, setAttributes, mergeBlocks, onReplace, className } ) { +function HeadingEdit( { + attributes, + setAttributes, + mergeBlocks, + onReplace, + className, +} ) { const ref = useRef(); const { TextColor, InspectorControlsColorPanel } = __experimentalUseColors( [ { name: 'textColor', property: 'color' } ], @@ -44,7 +50,9 @@ function HeadingEdit( { attributes, setAttributes, mergeBlocks, onReplace, class minLevel={ 2 } maxLevel={ 5 } selectedLevel={ level } - onChange={ ( newLevel ) => setAttributes( { level: newLevel } ) } + onChange={ ( newLevel ) => + setAttributes( { level: newLevel } ) + } /> setAttributes( { level: newLevel } ) } + onChange={ ( newLevel ) => + setAttributes( { level: newLevel } ) + } /> @@ -72,7 +82,9 @@ function HeadingEdit( { attributes, setAttributes, mergeBlocks, onReplace, class identifier="content" tagName={ tagName } value={ content } - onChange={ ( value ) => setAttributes( { content: value } ) } + onChange={ ( value ) => + setAttributes( { content: value } ) + } onMerge={ mergeBlocks } onSplit={ ( value ) => { if ( ! value ) { diff --git a/packages/block-library/src/heading/edit.native.js b/packages/block-library/src/heading/edit.native.js index ba098337c9325f..fdf8480713bbf2 100644 --- a/packages/block-library/src/heading/edit.native.js +++ b/packages/block-library/src/heading/edit.native.js @@ -15,14 +15,23 @@ import { __ } from '@wordpress/i18n'; import { RichText, BlockControls } from '@wordpress/block-editor'; import { createBlock } from '@wordpress/blocks'; -const HeadingEdit = ( { attributes, mergeBlocks, onFocus, onReplace, setAttributes, style } ) => ( +const HeadingEdit = ( { + attributes, + mergeBlocks, + onFocus, + onReplace, + setAttributes, + style, +} ) => ( setAttributes( { level: newLevel } ) } + onChange={ ( newLevel ) => + setAttributes( { level: newLevel } ) + } isCollapsed={ false } /> diff --git a/packages/block-library/src/heading/heading-toolbar.js b/packages/block-library/src/heading/heading-toolbar.js index c392a8533c1f72..49093ec6622dc0 100644 --- a/packages/block-library/src/heading/heading-toolbar.js +++ b/packages/block-library/src/heading/heading-toolbar.js @@ -19,7 +19,12 @@ class HeadingToolbar extends Component { createLevelControl( targetLevel, selectedLevel, onChange ) { const isActive = targetLevel === selectedLevel; return { - icon: , + icon: ( + + ), // translators: %s: heading level e.g: "1", "2", "3" title: sprintf( __( 'Heading %d' ), targetLevel ), isActive, @@ -28,7 +33,13 @@ class HeadingToolbar extends Component { } render() { - const { isCollapsed = true, minLevel, maxLevel, selectedLevel, onChange } = this.props; + const { + isCollapsed = true, + minLevel, + maxLevel, + selectedLevel, + onChange, + } = this.props; return ( { ( isDisabled ) => isPreview || isDisabled ? ( - + ) : ( setAttributes( { content } ) } + onChange={ ( content ) => + setAttributes( { content } ) + } placeholder={ __( 'Write HTMLโ€ฆ' ) } aria-label={ __( 'HTML' ) } /> diff --git a/packages/block-library/src/html/index.js b/packages/block-library/src/html/index.js index 64675afd92b141..f3e592da15318e 100644 --- a/packages/block-library/src/html/index.js +++ b/packages/block-library/src/html/index.js @@ -23,7 +23,10 @@ export const settings = { keywords: [ __( 'embed' ) ], example: { attributes: { - content: '' + __( 'Welcome to the wonderful world of blocksโ€ฆ' ) + '', + content: + '' + + __( 'Welcome to the wonderful world of blocksโ€ฆ' ) + + '', }, }, supports: { diff --git a/packages/block-library/src/html/transforms.js b/packages/block-library/src/html/transforms.js index 9ab4169ad1dd1a..7b6c054f1c2080 100644 --- a/packages/block-library/src/html/transforms.js +++ b/packages/block-library/src/html/transforms.js @@ -2,13 +2,19 @@ const transforms = { from: [ { type: 'raw', - isMatch: ( node ) => node.nodeName === 'FIGURE' && !! node.querySelector( 'iframe' ), + isMatch: ( node ) => + node.nodeName === 'FIGURE' && !! node.querySelector( 'iframe' ), schema: ( { phrasingContentSchema } ) => ( { figure: { require: [ 'iframe' ], children: { iframe: { - attributes: [ 'src', 'allowfullscreen', 'height', 'width' ], + attributes: [ + 'src', + 'allowfullscreen', + 'height', + 'width', + ], }, figcaption: { children: phrasingContentSchema, diff --git a/packages/block-library/src/image/deprecated.js b/packages/block-library/src/image/deprecated.js index fac421b2973f42..08f43101618e2a 100644 --- a/packages/block-library/src/image/deprecated.js +++ b/packages/block-library/src/image/deprecated.js @@ -73,7 +73,16 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { url, alt, caption, align, href, width, height, id } = attributes; + const { + url, + alt, + caption, + align, + href, + width, + height, + id, + } = attributes; const classes = classnames( { [ `align${ align }` ]: align, @@ -94,7 +103,10 @@ const deprecated = [
              { href ? { image } : image } { ! RichText.isEmpty( caption ) && ( - + ) }
              ); @@ -103,7 +115,16 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { url, alt, caption, align, href, width, height, id } = attributes; + const { + url, + alt, + caption, + align, + href, + width, + height, + id, + } = attributes; const image = (
              { href ? { image } : image } { ! RichText.isEmpty( caption ) && ( - + ) }
              ); @@ -128,9 +152,19 @@ const deprecated = [ { attributes: blockAttributes, save( { attributes } ) { - const { url, alt, caption, align, href, width, height } = attributes; + const { + url, + alt, + caption, + align, + href, + width, + height, + } = attributes; const extraImageProps = width || height ? { width, height } : {}; - const image = {; + const image = ( + { + ); let figureStyle = {}; @@ -141,10 +175,16 @@ const deprecated = [ } return ( -
              +
              { href ? { image } : image } { ! RichText.isEmpty( caption ) && ( - + ) }
              ); diff --git a/packages/block-library/src/image/edit.js b/packages/block-library/src/image/edit.js index 7bc050504a3a9a..56ab5c979e52f8 100644 --- a/packages/block-library/src/image/edit.js +++ b/packages/block-library/src/image/edit.js @@ -132,11 +132,18 @@ export class ImageEdit extends Component { const { id: prevID, url: prevURL = '' } = prevProps.attributes; const { id, url = '' } = this.props.attributes; - if ( isTemporaryImage( prevID, prevURL ) && ! isTemporaryImage( id, url ) ) { + if ( + isTemporaryImage( prevID, prevURL ) && + ! isTemporaryImage( id, url ) + ) { revokeBlobURL( url ); } - if ( ! this.props.isSelected && prevProps.isSelected && this.state.captionFocused ) { + if ( + ! this.props.isSelected && + prevProps.isSelected && + this.state.captionFocused + ) { this.setState( { captionFocused: false, } ); @@ -161,7 +168,13 @@ export class ImageEdit extends Component { return; } - const { id, url, alt, caption, linkDestination } = this.props.attributes; + const { + id, + url, + alt, + caption, + linkDestination, + } = this.props.attributes; let mediaAttributes = pickRelevantMediaFiles( media ); @@ -258,14 +271,24 @@ export class ImageEdit extends Component { updateAlignment( nextAlign ) { const extraUpdatedAttributes = - [ 'wide', 'full' ].indexOf( nextAlign ) !== -1 ? { width: undefined, height: undefined } : {}; - this.props.setAttributes( { ...extraUpdatedAttributes, align: nextAlign } ); + [ 'wide', 'full' ].indexOf( nextAlign ) !== -1 + ? { width: undefined, height: undefined } + : {}; + this.props.setAttributes( { + ...extraUpdatedAttributes, + align: nextAlign, + } ); } updateImage( sizeSlug ) { const { image } = this.props; - const url = get( image, [ 'media_details', 'sizes', sizeSlug, 'source_url' ] ); + const url = get( image, [ + 'media_details', + 'sizes', + sizeSlug, + 'source_url', + ] ); if ( ! url ) { return null; } @@ -328,7 +351,10 @@ export class ImageEdit extends Component { const isExternal = isExternalImage( id, url ); const controls = ( - + { url && ( - { __( 'Describe the purpose of the image' ) } + { __( + 'Describe the purpose of the image' + ) } - { __( 'Leave empty if the image is purely decorative.' ) } + { __( + 'Leave empty if the image is purely decorative.' + ) } } /> @@ -443,9 +478,13 @@ export class ImageEdit extends Component { onChange={ this.onSetTitle } help={ <> - { __( 'Describe the role of this image on the page.' ) } + { __( + 'Describe the role of this image on the page.' + ) } - { __( '(Note: many devices and browsers do not display this text.)' ) } + { __( + '(Note: many devices and browsers do not display this text.)' + ) } } @@ -475,11 +514,15 @@ export class ImageEdit extends Component { defaultedAlt = alt; } else if ( filename ) { defaultedAlt = sprintf( - __( 'This image has an empty alt attribute; its file name is %s' ), + __( + 'This image has an empty alt attribute; its file name is %s' + ), filename ); } else { - defaultedAlt = __( 'This image has an empty alt attribute' ); + defaultedAlt = __( + 'This image has an empty alt attribute' + ); } const img = ( @@ -491,28 +534,46 @@ export class ImageEdit extends Component { src={ url } alt={ defaultedAlt } onClick={ this.onImageClick } - onError={ () => this.onImageError( url ) } + onError={ () => + this.onImageError( url ) + } /> { isBlobURL( url ) && } /* eslint-enable jsx-a11y/no-noninteractive-element-interactions */ ); - if ( ! isResizable || ! imageWidthWithinContainer ) { + if ( + ! isResizable || + ! imageWidthWithinContainer + ) { return ( <> - { getInspectorControls( imageWidth, imageHeight ) } -
              { img }
              + { getInspectorControls( + imageWidth, + imageHeight + ) } +
              + { img } +
              ); } - const currentWidth = width || imageWidthWithinContainer; - const currentHeight = height || imageHeightWithinContainer; + const currentWidth = + width || imageWidthWithinContainer; + const currentHeight = + height || imageHeightWithinContainer; const ratio = imageWidth / imageHeight; - const minWidth = imageWidth < imageHeight ? MIN_SIZE : MIN_SIZE * ratio; - const minHeight = imageHeight < imageWidth ? MIN_SIZE : MIN_SIZE / ratio; + const minWidth = + imageWidth < imageHeight + ? MIN_SIZE + : MIN_SIZE * ratio; + const minHeight = + imageHeight < imageWidth + ? MIN_SIZE + : MIN_SIZE / ratio; // With the current implementation of ResizableBox, an image needs an explicit pixel value for the max-width. // In absence of being able to set the content-width, this max-width is currently dictated by the vanilla editor style. @@ -552,7 +613,10 @@ export class ImageEdit extends Component { return ( <> - { getInspectorControls( imageWidth, imageHeight ) } + { getInspectorControls( + imageWidth, + imageHeight + ) } { + onResizeStop={ ( + event, + direction, + elt, + delta + ) => { onResizeStop(); setAttributes( { - width: parseInt( currentWidth + delta.width, 10 ), - height: parseInt( currentHeight + delta.height, 10 ), + width: parseInt( + currentWidth + delta.width, + 10 + ), + height: parseInt( + currentHeight + + delta.height, + 10 + ), } ); } } > @@ -590,7 +666,9 @@ export class ImageEdit extends Component { placeholder={ __( 'Write captionโ€ฆ' ) } value={ caption } unstableOnFocus={ this.onFocusCaption } - onChange={ ( value ) => setAttributes( { caption: value } ) } + onChange={ ( value ) => + setAttributes( { caption: value } ) + } isSelected={ this.state.captionFocused } inlineToolbar /> diff --git a/packages/block-library/src/image/edit.native.js b/packages/block-library/src/image/edit.native.js index ba0d35a2f2a4c0..d562742dfb6ae0 100644 --- a/packages/block-library/src/image/edit.native.js +++ b/packages/block-library/src/image/edit.native.js @@ -2,7 +2,13 @@ * External dependencies */ import React from 'react'; -import { View, ImageBackground, Text, TouchableWithoutFeedback, Dimensions } from 'react-native'; +import { + View, + ImageBackground, + Text, + TouchableWithoutFeedback, + Dimensions, +} from 'react-native'; import { requestMediaImport, mediaUploadSync, @@ -71,7 +77,10 @@ const sizeOptionLabels = { [ IMAGE_SIZE_LARGE ]: __( 'Large' ), [ IMAGE_SIZE_FULL_SIZE ]: __( 'Full Size' ), }; -const sizeOptions = map( sizeOptionLabels, ( label, option ) => ( { value: option, label } ) ); +const sizeOptions = map( sizeOptionLabels, ( label, option ) => ( { + value: option, + label, +} ) ); // Default Image ratio 4:3 const IMAGE_ASPECT_RATIO = 4 / 3; @@ -88,10 +97,16 @@ export class ImageEdit extends React.Component { isCaptionSelected: false, }; - this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( this ); - this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( this ); + this.finishMediaUploadWithSuccess = this.finishMediaUploadWithSuccess.bind( + this + ); + this.finishMediaUploadWithFailure = this.finishMediaUploadWithFailure.bind( + this + ); this.mediaUploadStateReset = this.mediaUploadStateReset.bind( this ); - this.onSelectMediaUploadOption = this.onSelectMediaUploadOption.bind( this ); + this.onSelectMediaUploadOption = this.onSelectMediaUploadOption.bind( + this + ); this.updateMediaProgress = this.updateMediaProgress.bind( this ); this.updateAlt = this.updateAlt.bind( this ); this.updateImageURL = this.updateImageURL.bind( this ); @@ -116,7 +131,11 @@ export class ImageEdit extends React.Component { } // Detect any pasted image and start an upload - if ( ! attributes.id && attributes.url && attributes.url.indexOf( 'file:' ) === 0 ) { + if ( + ! attributes.id && + attributes.url && + attributes.url.indexOf( 'file:' ) === 0 + ) { requestMediaImport( attributes.url, ( id, url ) => { if ( url ) { setAttributes( { id, url } ); @@ -133,8 +152,14 @@ export class ImageEdit extends React.Component { componentWillUnmount() { // this action will only exist if the user pressed the trash button on the block holder - if ( hasAction( 'blocks.onRemoveBlockCheckUpload' ) && this.state.isUploadInProgress ) { - doAction( 'blocks.onRemoveBlockCheckUpload', this.props.attributes.id ); + if ( + hasAction( 'blocks.onRemoveBlockCheckUpload' ) && + this.state.isUploadInProgress + ) { + doAction( + 'blocks.onRemoveBlockCheckUpload', + this.props.attributes.id + ); } } @@ -162,7 +187,10 @@ export class ImageEdit extends React.Component { } else if ( attributes.id && ! isURL( attributes.url ) ) { requestImageFailedRetryDialog( attributes.id ); } else if ( ! this.state.isCaptionSelected ) { - requestImageFullscreenPreview( attributes.url, image && image.source_url ); + requestImageFullscreenPreview( + attributes.url, + image && image.source_url + ); } this.setState( { @@ -207,7 +235,11 @@ export class ImageEdit extends React.Component { } updateImageURL( url ) { - this.props.setAttributes( { url, width: undefined, height: undefined } ); + this.props.setAttributes( { + url, + width: undefined, + height: undefined, + } ); } updateAlignment( nextAlign ) { @@ -222,7 +254,10 @@ export class ImageEdit extends React.Component { } onSetNewTab( value ) { - const updatedLinkTarget = getUpdatedLinkTargetSettings( value, this.props.attributes ); + const updatedLinkTarget = getUpdatedLinkTargetSettings( + value, + this.props.attributes + ); this.props.setAttributes( updatedLinkTarget ); } @@ -303,7 +338,10 @@ export class ImageEdit extends React.Component { ); break; case ICON_TYPE.UPLOAD: - iconStyle = this.props.getStylesFromColorScheme( styles.iconUpload, styles.iconUploadDark ); + iconStyle = this.props.getStylesFromColorScheme( + styles.iconUpload, + styles.iconUploadDark + ); break; } return ; @@ -311,14 +349,33 @@ export class ImageEdit extends React.Component { render() { const { attributes, isSelected, image } = this.props; - const { align, url, height, width, alt, href, id, linkTarget, sizeSlug } = attributes; + const { + align, + url, + height, + width, + alt, + href, + id, + linkTarget, + sizeSlug, + } = attributes; - const actions = [ { label: __( 'Clear All Settings' ), onPress: this.onClearSettings } ]; + const actions = [ + { + label: __( 'Clear All Settings' ), + onPress: this.onClearSettings, + }, + ]; const getToolbarEditButton = ( open ) => ( - + this.onSetSizeSlug( newValue ) } + value={ + sizeOptionLabels[ + sizeSlug || DEFAULT_SIZE_SLUG + ] + } + onChangeValue={ ( newValue ) => + this.onSetSizeSlug( newValue ) + } options={ sizeOptions } /> ) } @@ -392,14 +455,19 @@ export class ImageEdit extends React.Component { wide: 'center', }; - const imageContainerHeight = Dimensions.get( 'window' ).width / IMAGE_ASPECT_RATIO; + const imageContainerHeight = + Dimensions.get( 'window' ).width / IMAGE_ASPECT_RATIO; const editImageComponent = ( { open, mediaOptions } ) => ( { mediaOptions() } - + @@ -415,15 +483,20 @@ export class ImageEdit extends React.Component { { getInspectorControls() } { getMediaOptions() } - { ! this.state.isCaptionSelected && getToolbarEditButton( openMediaOptions ) } + { ! this.state.isCaptionSelected && + getToolbarEditButton( openMediaOptions ) } { this.getIcon( ICON_TYPE.RETRY ) } + + { this.getIcon( ICON_TYPE.RETRY ) } + ); return ( @@ -451,7 +530,9 @@ export class ImageEdit extends React.Component { // only set alignSelf if an image exists because alignSelf causes the placeholder // to disappear when an aligned image can't be downloaded // https://github.com/wordpress-mobile/gutenberg-mobile/issues/1592 - alignSelf: imageWidthWithinContainer && alignToFlex[ align ], + alignSelf: + imageWidthWithinContainer && + alignToFlex[ align ], } } > { ! imageWidthWithinContainer && ( @@ -461,11 +542,19 @@ export class ImageEdit extends React.Component { styles.imageContainerUpload, styles.imageContainerUploadDark ), - { height: imageContainerHeight }, + { + height: imageContainerHeight, + }, ] } > - - { this.getIcon( ICON_TYPE.UPLOAD ) } + + { this.getIcon( + ICON_TYPE.UPLOAD + ) } ) } @@ -473,11 +562,17 @@ export class ImageEdit extends React.Component { accessible={ true } disabled={ ! isSelected } accessibilityLabel={ alt } - accessibilityHint={ __( 'Double tap and hold to edit' ) } + accessibilityHint={ __( + 'Double tap and hold to edit' + ) } accessibilityRole={ 'imagebutton' } style={ [ imageBorderOnSelectedStyle, - { width: finalWidth, height: finalHeight, opacity }, + { + width: finalWidth, + height: finalHeight, + opacity, + }, ] } resizeMethod="scale" source={ { uri: url } } @@ -487,11 +582,21 @@ export class ImageEdit extends React.Component { { iconRetryContainer } - { retryMessage } + + { retryMessage } + ) } { isSelected && @@ -501,11 +606,20 @@ export class ImageEdit extends React.Component { finalHeight && showMediaEditorButton && ( ) } diff --git a/packages/block-library/src/image/image-size.js b/packages/block-library/src/image/image-size.js index 24b6fdbe70095a..3958aafcbb714e 100644 --- a/packages/block-library/src/image/image-size.js +++ b/packages/block-library/src/image/image-size.js @@ -60,7 +60,10 @@ class ImageSize extends Component { } calculateSize() { - const { width, height } = calculatePreferedImageSize( this.image, this.container ); + const { width, height } = calculatePreferedImageSize( + this.image, + this.container + ); this.setState( { width, height } ); } @@ -73,7 +76,11 @@ class ImageSize extends Component { imageWidthWithinContainer: this.state.width, imageHeightWithinContainer: this.state.height, }; - return
              { this.props.children( sizes ) }
              ; + return ( +
              + { this.props.children( sizes ) } +
              + ); } } diff --git a/packages/block-library/src/image/index.js b/packages/block-library/src/image/index.js index 360e5b94f5fb76..332ab1afb062ca 100644 --- a/packages/block-library/src/image/index.js +++ b/packages/block-library/src/image/index.js @@ -34,7 +34,11 @@ export const settings = { }, }, styles: [ - { name: 'default', label: _x( 'Default', 'block style' ), isDefault: true }, + { + name: 'default', + label: _x( 'Default', 'block style' ), + isDefault: true, + }, { name: 'rounded', label: _x( 'Rounded', 'block style' ) }, ], __experimentalLabel( attributes, { context } ) { diff --git a/packages/block-library/src/image/save.js b/packages/block-library/src/image/save.js index 12e0245a885194..4124e9c951e382 100644 --- a/packages/block-library/src/image/save.js +++ b/packages/block-library/src/image/save.js @@ -48,7 +48,12 @@ export default function save( { attributes } ) { const figure = ( <> { href ? ( - + { image } ) : ( diff --git a/packages/block-library/src/image/test/edit.js b/packages/block-library/src/image/test/edit.js index 506a3358a54e42..a7919f15730f35 100644 --- a/packages/block-library/src/image/test/edit.js +++ b/packages/block-library/src/image/test/edit.js @@ -18,7 +18,10 @@ describe( 'core/image/edit', () => { }; const setAttributes = jest.fn( () => {} ); const testRenderer = TestRenderer.create( - + ); const instance = testRenderer.getInstance(); diff --git a/packages/block-library/src/image/test/edit.native.js b/packages/block-library/src/image/test/edit.native.js index 219572d1eb2783..86b4751177da22 100644 --- a/packages/block-library/src/image/test/edit.native.js +++ b/packages/block-library/src/image/test/edit.native.js @@ -40,17 +40,26 @@ describe( 'Image Block', () => { instance.onSetNewTab( true ); - expect( setAttributes ).toHaveBeenCalledWith( { linkTarget: '_blank', rel: undefined } ); + expect( setAttributes ).toHaveBeenCalledWith( { + linkTarget: '_blank', + rel: undefined, + } ); } ); it( 'unset link target', () => { const component = renderer.create( - getImageComponent( { linkTarget: '_blank', rel: NEW_TAB_REL.join( ' ' ) } ) + getImageComponent( { + linkTarget: '_blank', + rel: NEW_TAB_REL.join( ' ' ), + } ) ); const instance = component.getInstance(); instance.onSetNewTab( false ); - expect( setAttributes ).toHaveBeenCalledWith( { linkTarget: undefined, rel: undefined } ); + expect( setAttributes ).toHaveBeenCalledWith( { + linkTarget: undefined, + rel: undefined, + } ); } ); } ); diff --git a/packages/block-library/src/image/test/transforms.js b/packages/block-library/src/image/test/transforms.js index a72a04744bd0dd..fa9f99f0c94d1a 100644 --- a/packages/block-library/src/image/test/transforms.js +++ b/packages/block-library/src/image/test/transforms.js @@ -5,38 +5,62 @@ import { stripFirstImage } from '../transforms'; describe( 'stripFirstImage', () => { test( 'should do nothing if no image is present', () => { - expect( stripFirstImage( {}, { shortcode: { content: '' } } ) ).toEqual( '' ); - expect( stripFirstImage( {}, { shortcode: { content: 'Tucson' } } ) ).toEqual( 'Tucson' ); - expect( stripFirstImage( {}, { shortcode: { content: 'Tucson' } } ) ).toEqual( - 'Tucson' + expect( stripFirstImage( {}, { shortcode: { content: '' } } ) ).toEqual( + '' ); + expect( + stripFirstImage( {}, { shortcode: { content: 'Tucson' } } ) + ).toEqual( 'Tucson' ); + expect( + stripFirstImage( {}, { shortcode: { content: 'Tucson' } } ) + ).toEqual( 'Tucson' ); } ); test( 'should strip out image when leading as expected', () => { - expect( stripFirstImage( {}, { shortcode: { content: '' } } ) ).toEqual( '' ); - expect( stripFirstImage( {}, { shortcode: { content: 'Image!' } } ) ).toEqual( 'Image!' ); expect( - stripFirstImage( {}, { shortcode: { content: 'Image!' } } ) + stripFirstImage( {}, { shortcode: { content: '' } } ) + ).toEqual( '' ); + expect( + stripFirstImage( {}, { shortcode: { content: 'Image!' } } ) + ).toEqual( 'Image!' ); + expect( + stripFirstImage( + {}, + { shortcode: { content: 'Image!' } } + ) ).toEqual( 'Image!' ); } ); test( 'should strip out image when not in leading position as expected', () => { - expect( stripFirstImage( {}, { shortcode: { content: 'Before' } } ) ).toEqual( 'Before' ); - expect( stripFirstImage( {}, { shortcode: { content: 'BeforeImage!' } } ) ).toEqual( - 'BeforeImage!' - ); expect( - stripFirstImage( {}, { shortcode: { content: 'BeforeImage!' } } ) + stripFirstImage( {}, { shortcode: { content: 'Before' } } ) + ).toEqual( 'Before' ); + expect( + stripFirstImage( + {}, + { shortcode: { content: 'BeforeImage!' } } + ) + ).toEqual( 'BeforeImage!' ); + expect( + stripFirstImage( + {}, + { shortcode: { content: 'BeforeImage!' } } + ) ).toEqual( 'BeforeImage!' ); } ); test( 'should strip out only the first of many images', () => { - expect( stripFirstImage( {}, { shortcode: { content: '' } } ) ).toEqual( '' ); + expect( + stripFirstImage( {}, { shortcode: { content: '' } } ) + ).toEqual( '' ); } ); test( 'should strip out the first image and its wrapping parents', () => { expect( - stripFirstImage( {}, { shortcode: { content: '

              ' } } ) + stripFirstImage( + {}, + { shortcode: { content: '

              ' } } + ) ).toEqual( '

              ' ); } ); } ); diff --git a/packages/block-library/src/image/transforms.js b/packages/block-library/src/image/transforms.js index f0fe36ddf63fb9..f2cf8e61ba6634 100644 --- a/packages/block-library/src/image/transforms.js +++ b/packages/block-library/src/image/transforms.js @@ -12,7 +12,11 @@ export function stripFirstImage( attributes, { shortcode } ) { let nodeToRemove = body.querySelector( 'img' ); // if an image has parents, find the topmost node to remove - while ( nodeToRemove && nodeToRemove.parentNode && nodeToRemove.parentNode !== body ) { + while ( + nodeToRemove && + nodeToRemove.parentNode && + nodeToRemove.parentNode !== body + ) { nodeToRemove = nodeToRemove.parentNode; } @@ -38,7 +42,13 @@ function getFirstAnchorAttributeFormHTML( html, attributeName ) { const imageSchema = { img: { attributes: [ 'src', 'alt', 'title' ], - classes: [ 'alignleft', 'aligncenter', 'alignright', 'alignnone', /^wp-image-\d+$/ ], + classes: [ + 'alignleft', + 'aligncenter', + 'alignright', + 'alignnone', + /^wp-image-\d+$/, + ], }, }; @@ -62,37 +72,61 @@ const transforms = { from: [ { type: 'raw', - isMatch: ( node ) => node.nodeName === 'FIGURE' && !! node.querySelector( 'img' ), + isMatch: ( node ) => + node.nodeName === 'FIGURE' && !! node.querySelector( 'img' ), schema, transform: ( node ) => { // Search both figure and image classes. Alignment could be // set on either. ID is set on the image. - const className = node.className + ' ' + node.querySelector( 'img' ).className; - const alignMatches = /(?:^|\s)align(left|center|right)(?:$|\s)/.exec( className ); + const className = + node.className + + ' ' + + node.querySelector( 'img' ).className; + const alignMatches = /(?:^|\s)align(left|center|right)(?:$|\s)/.exec( + className + ); const align = alignMatches ? alignMatches[ 1 ] : undefined; - const idMatches = /(?:^|\s)wp-image-(\d+)(?:$|\s)/.exec( className ); + const idMatches = /(?:^|\s)wp-image-(\d+)(?:$|\s)/.exec( + className + ); const id = idMatches ? Number( idMatches[ 1 ] ) : undefined; const anchorElement = node.querySelector( 'a' ); - const linkDestination = anchorElement && anchorElement.href ? 'custom' : undefined; - const href = anchorElement && anchorElement.href ? anchorElement.href : undefined; - const rel = anchorElement && anchorElement.rel ? anchorElement.rel : undefined; + const linkDestination = + anchorElement && anchorElement.href ? 'custom' : undefined; + const href = + anchorElement && anchorElement.href + ? anchorElement.href + : undefined; + const rel = + anchorElement && anchorElement.rel + ? anchorElement.rel + : undefined; const linkClass = - anchorElement && anchorElement.className ? anchorElement.className : undefined; - const attributes = getBlockAttributes( 'core/image', node.outerHTML, { - align, - id, - linkDestination, - href, - rel, - linkClass, - } ); + anchorElement && anchorElement.className + ? anchorElement.className + : undefined; + const attributes = getBlockAttributes( + 'core/image', + node.outerHTML, + { + align, + id, + linkDestination, + href, + rel, + linkClass, + } + ); return createBlock( 'core/image', attributes ); }, }, { type: 'files', isMatch( files ) { - return files.length === 1 && files[ 0 ].type.indexOf( 'image/' ) === 0; + return ( + files.length === 1 && + files[ 0 ].type.indexOf( 'image/' ) === 0 + ); }, transform( files ) { const file = files[ 0 ]; @@ -125,17 +159,26 @@ const transforms = { }, href: { shortcode: ( attributes, { shortcode } ) => { - return getFirstAnchorAttributeFormHTML( shortcode.content, 'href' ); + return getFirstAnchorAttributeFormHTML( + shortcode.content, + 'href' + ); }, }, rel: { shortcode: ( attributes, { shortcode } ) => { - return getFirstAnchorAttributeFormHTML( shortcode.content, 'rel' ); + return getFirstAnchorAttributeFormHTML( + shortcode.content, + 'rel' + ); }, }, linkClass: { shortcode: ( attributes, { shortcode } ) => { - return getFirstAnchorAttributeFormHTML( shortcode.content, 'class' ); + return getFirstAnchorAttributeFormHTML( + shortcode.content, + 'class' + ); }, }, id: { diff --git a/packages/block-library/src/index.js b/packages/block-library/src/index.js index dfe70da275a08c..13ef75a96409d0 100644 --- a/packages/block-library/src/index.js +++ b/packages/block-library/src/index.js @@ -189,7 +189,15 @@ export const __experimentalRegisterExperimentalCoreBlocks = // Register Full Site Editing Blocks. ...( __experimentalEnableFullSiteEditing - ? [ siteTitle, templatePart, postTitle, postContent, postAuthor, postDate, postExcerpt ] + ? [ + siteTitle, + templatePart, + postTitle, + postContent, + postAuthor, + postDate, + postExcerpt, + ] : [] ), ].forEach( registerBlock ); } diff --git a/packages/block-library/src/latest-comments/edit.js b/packages/block-library/src/latest-comments/edit.js index 09096dbf064368..2d4ab81557e612 100644 --- a/packages/block-library/src/latest-comments/edit.js +++ b/packages/block-library/src/latest-comments/edit.js @@ -2,7 +2,12 @@ * WordPress dependencies */ import { InspectorControls } from '@wordpress/block-editor'; -import { Disabled, PanelBody, RangeControl, ToggleControl } from '@wordpress/components'; +import { + Disabled, + PanelBody, + RangeControl, + ToggleControl, +} from '@wordpress/components'; import ServerSideRender from '@wordpress/server-side-render'; import { Component } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; @@ -29,9 +34,13 @@ class LatestComments extends Component { // Create toggles for each attribute; we create them here rather than // passing `this.createToggleAttribute( 'displayAvatar' )` directly to // `onChange` to avoid re-renders. - this.toggleDisplayAvatar = this.createToggleAttribute( 'displayAvatar' ); + this.toggleDisplayAvatar = this.createToggleAttribute( + 'displayAvatar' + ); this.toggleDisplayDate = this.createToggleAttribute( 'displayDate' ); - this.toggleDisplayExcerpt = this.createToggleAttribute( 'displayExcerpt' ); + this.toggleDisplayExcerpt = this.createToggleAttribute( + 'displayExcerpt' + ); } createToggleAttribute( propName ) { @@ -48,7 +57,12 @@ class LatestComments extends Component { } render() { - const { commentsToShow, displayAvatar, displayDate, displayExcerpt } = this.props.attributes; + const { + commentsToShow, + displayAvatar, + displayDate, + displayExcerpt, + } = this.props.attributes; return ( <> @@ -80,7 +94,10 @@ class LatestComments extends Component { - + ); diff --git a/packages/block-library/src/latest-posts/edit.js b/packages/block-library/src/latest-posts/edit.js index 14c7c058589c76..1127716fd0833a 100644 --- a/packages/block-library/src/latest-posts/edit.js +++ b/packages/block-library/src/latest-posts/edit.js @@ -84,7 +84,9 @@ class LatestPostsEdit extends Component { setAttributes( { displayPostContent: value } ) } + onChange={ ( value ) => + setAttributes( { displayPostContent: value } ) + } /> { displayPostContent && ( setAttributes( { displayPostContentRadio: value } ) } - /> - ) } - { displayPostContent && displayPostContentRadio === 'excerpt' && ( - setAttributes( { excerptLength: value } ) } - min={ 10 } - max={ 100 } + onChange={ ( value ) => + setAttributes( { + displayPostContentRadio: value, + } ) + } /> ) } + { displayPostContent && + displayPostContentRadio === 'excerpt' && ( + + setAttributes( { excerptLength: value } ) + } + min={ 10 } + max={ 100 } + /> + ) } setAttributes( { displayPostDate: value } ) } + onChange={ ( value ) => + setAttributes( { displayPostDate: value } ) + } /> @@ -122,21 +136,36 @@ class LatestPostsEdit extends Component { numberOfItems={ postsToShow } categoriesList={ categoriesList } selectedCategoryId={ categories } - onOrderChange={ ( value ) => setAttributes( { order: value } ) } - onOrderByChange={ ( value ) => setAttributes( { orderBy: value } ) } + onOrderChange={ ( value ) => + setAttributes( { order: value } ) + } + onOrderByChange={ ( value ) => + setAttributes( { orderBy: value } ) + } onCategoryChange={ ( value ) => - setAttributes( { categories: '' !== value ? value : undefined } ) + setAttributes( { + categories: '' !== value ? value : undefined, + } ) + } + onNumberOfItemsChange={ ( value ) => + setAttributes( { postsToShow: value } ) } - onNumberOfItemsChange={ ( value ) => setAttributes( { postsToShow: value } ) } /> { postLayout === 'grid' && ( setAttributes( { columns: value } ) } + onChange={ ( value ) => + setAttributes( { columns: value } ) + } min={ 2 } max={ - ! hasPosts ? MAX_POSTS_COLUMNS : Math.min( MAX_POSTS_COLUMNS, latestPosts.length ) + ! hasPosts + ? MAX_POSTS_COLUMNS + : Math.min( + MAX_POSTS_COLUMNS, + latestPosts.length + ) } required /> @@ -150,8 +179,15 @@ class LatestPostsEdit extends Component { return ( <> { inspectorControls } - - { ! Array.isArray( latestPosts ) ? : __( 'No posts found.' ) } + + { ! Array.isArray( latestPosts ) ? ( + + ) : ( + __( 'No posts found.' ) + ) } ); @@ -159,7 +195,9 @@ class LatestPostsEdit extends Component { // Removing posts from display should be instant. const displayPosts = - latestPosts.length > postsToShow ? latestPosts.slice( 0, postsToShow ) : latestPosts; + latestPosts.length > postsToShow + ? latestPosts.slice( 0, postsToShow ) + : latestPosts; const layoutControls = [ { @@ -200,45 +238,74 @@ class LatestPostsEdit extends Component { } const excerptElement = document.createElement( 'div' ); excerptElement.innerHTML = excerpt; - excerpt = excerptElement.textContent || excerptElement.innerText || ''; + excerpt = + excerptElement.textContent || + excerptElement.innerText || + ''; return (
            • - - { titleTrimmed ? { titleTrimmed } : __( '(no title)' ) } + + { titleTrimmed ? ( + { titleTrimmed } + ) : ( + __( '(no title)' ) + ) } { displayPostDate && post.date_gmt && ( ) } - { displayPostContent && displayPostContentRadio === 'excerpt' && ( -
              - - { excerptLength < excerpt.trim().split( ' ' ).length - ? excerpt - .trim() - .split( ' ', excerptLength ) - .join( ' ' ) + - ' ... ' + - __( 'Read more' ) + - '' - : excerpt - .trim() - .split( ' ', excerptLength ) - .join( ' ' ) } - -
              - ) } - { displayPostContent && displayPostContentRadio === 'full_post' && ( -
              - { post.content.raw.trim() } -
              - ) } + { displayPostContent && + displayPostContentRadio === 'excerpt' && ( +
              + + { excerptLength < + excerpt.trim().split( ' ' ) + .length + ? excerpt + .trim() + .split( + ' ', + excerptLength + ) + .join( ' ' ) + + ' ... ' + + __( 'Read more' ) + + '' + : excerpt + .trim() + .split( + ' ', + excerptLength + ) + .join( ' ' ) } + +
              + ) } + { displayPostContent && + displayPostContentRadio === 'full_post' && ( +
              + + { post.content.raw.trim() } + +
              + ) }
            • ); } ) } diff --git a/packages/block-library/src/legacy-widget/edit/dom-manager.js b/packages/block-library/src/legacy-widget/edit/dom-manager.js index 99fb43aee1ecd1..310ac16b871ea6 100644 --- a/packages/block-library/src/legacy-widget/edit/dom-manager.js +++ b/packages/block-library/src/legacy-widget/edit/dom-manager.js @@ -30,14 +30,23 @@ class LegacyWidgetEditDomManager extends Component { let shouldTriggerWidgetUpdateEvent = false; // We can not leverage react render otherwise we would destroy dom changes applied by the plugins. // We manually update the required dom node replicating what the widget screen and the customizer do. - if ( nextProps.idBase !== this.props.idBase && this.idBaseInputRef.current ) { + if ( + nextProps.idBase !== this.props.idBase && + this.idBaseInputRef.current + ) { this.idBaseInputRef.current.value = nextProps.idBase; shouldTriggerWidgetUpdateEvent = true; } - if ( nextProps.number !== this.props.number && this.widgetNumberInputRef.current ) { + if ( + nextProps.number !== this.props.number && + this.widgetNumberInputRef.current + ) { this.widgetNumberInputRef.current.value = nextProps.number; } - if ( nextProps.form !== this.props.form && this.widgetContentRef.current ) { + if ( + nextProps.form !== this.props.form && + this.widgetContentRef.current + ) { const widgetContent = this.widgetContentRef.current; widgetContent.innerHTML = nextProps.form; shouldTriggerWidgetUpdateEvent = true; @@ -61,10 +70,16 @@ class LegacyWidgetEditDomManager extends Component { if ( this.shouldTriggerInstanceUpdate() ) { if ( isReferenceWidget ) { if ( this.containerRef.current ) { - window.wpWidgets.save( window.jQuery( this.containerRef.current ) ); + window.wpWidgets.save( + window.jQuery( + this.containerRef.current + ) + ); } } - this.props.onInstanceChange( this.retrieveUpdatedInstance() ); + this.props.onInstanceChange( + this.retrieveUpdatedInstance() + ); } } } > @@ -75,7 +90,12 @@ class LegacyWidgetEditDomManager extends Component { /> { isReferenceWidget && ( <> - + - - + + ) } @@ -115,7 +145,10 @@ class LegacyWidgetEditDomManager extends Component { } for ( const rawKey of currentFormDataKeys ) { if ( - ! isShallowEqual( currentFormData.getAll( rawKey ), this.previousFormData.getAll( rawKey ) ) + ! isShallowEqual( + currentFormData.getAll( rawKey ), + this.previousFormData.getAll( rawKey ) + ) ) { this.previousFormData = currentFormData; return true; @@ -139,12 +172,22 @@ class LegacyWidgetEditDomManager extends Component { // This fields are added to the form because the widget JavaScript code may use this values. // They are not relevant for the update mechanism. if ( - includes( [ 'widget-id', 'id_base', 'widget_number', 'multi_number', 'add_new' ], rawKey ) + includes( + [ + 'widget-id', + 'id_base', + 'widget_number', + 'multi_number', + 'add_new', + ], + rawKey + ) ) { continue; } const matches = rawKey.match( /[^\[]*\[[-\d]*\]\[([^\]]*)\]/ ); - const keyParsed = matches && matches[ 1 ] ? matches[ 1 ] : rawKey; + const keyParsed = + matches && matches[ 1 ] ? matches[ 1 ] : rawKey; const value = formData.getAll( rawKey ); if ( value.length > 1 ) { updatedInstance[ keyParsed ] = value; diff --git a/packages/block-library/src/legacy-widget/edit/handler.js b/packages/block-library/src/legacy-widget/edit/handler.js index 9af999e7b547f5..a299d94024223a 100644 --- a/packages/block-library/src/legacy-widget/edit/handler.js +++ b/packages/block-library/src/legacy-widget/edit/handler.js @@ -59,7 +59,15 @@ class LegacyWidgetEditHandler extends Component { } render() { - const { instanceId, id, number, idBase, instance, isSelected, widgetName } = this.props; + const { + instanceId, + id, + number, + idBase, + instance, + isSelected, + widgetName, + } = this.props; const { form } = this.state; if ( ! form ) { @@ -79,7 +87,11 @@ class LegacyWidgetEditHandler extends Component { } return ( <> - { title &&
              { title }
              } + { title && ( +
              + { title } +
              + ) }
              { - const { isReferenceWidget } = availableLegacyWidgets[ newWidget ]; + const { isReferenceWidget } = availableLegacyWidgets[ + newWidget + ]; setAttributes( { instance: {}, id: isReferenceWidget ? newWidget : undefined, - widgetClass: isReferenceWidget ? undefined : newWidget, + widgetClass: isReferenceWidget + ? undefined + : newWidget, } ); } } /> @@ -63,7 +69,9 @@ class LegacyWidgetEdit extends Component { const inspectorControls = widgetObject ? ( - { widgetObject.description } + + { widgetObject.description } + ) : null; if ( ! hasPermissionsToManageWidgets ) { @@ -80,7 +88,11 @@ class LegacyWidgetEdit extends Component { { widgetObject && ! widgetObject.isHidden && ( -